@marktiderman/genesis-cli 1.8.0 → 1.10.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.
@@ -51,7 +51,7 @@ describe("check-in photos", () => {
51
51
  });
52
52
 
53
53
  it("is wired into the check-in screen, with a photo-library sentence", () => {
54
- expect(read("src/app/(app)/(home)/check-in.tsx")).toMatch(/photos=\{checkInPhotos\}/);
54
+ expect(read("src/lib/check-in-screen.tsx")).toMatch(/photos=\{checkInPhotos\}/);
55
55
  // The check-in picks from the library only. The camera and microphone sentences are chat's video
56
56
  // and voice messages, the same as expo-camera's and expo-audio's, or the picker would delete them.
57
57
  expect(read("app.config.ts")).toMatch(/\["expo-image-picker", \{ photosPermission: "[^"]{20,}", cameraPermission: CAMERA, microphonePermission: MICROPHONE \}\]/);
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from "@jest/globals";
2
+ import { screen } from "@testing-library/react-native";
3
+ import type { ChatAttachment } from "@marktiderman/genesis-chat";
4
+ import { copy } from "@/copy";
5
+ import { attachmentKinds, kindAllowsTopics } from "@/lib/chat";
6
+ import { expectPathname, renderApp } from "./render-app";
7
+
8
+ const checkIn = { id: "a1", kind: "check_in", ref: { title: "Hilltop Gym" } } as unknown as ChatAttachment;
9
+
10
+ describe("Messages", () => {
11
+ it("opens a check-in from a conversation inside the Messages stack, so Back returns to it", async () => {
12
+ const app = await renderApp("/messages/check-in", "person@example.com");
13
+ expect(await screen.findByTestId("check-in")).toBeOnTheScreen();
14
+ await expectPathname(app, "/messages/check-in");
15
+ });
16
+
17
+ it("shows the sender Sent on their own check-in card, and the others Answer", () => {
18
+ const kind = attachmentKinds.check_in!;
19
+ const call = <R,>(fn: unknown, mine: boolean) => (fn as (a: ChatAttachment, ctx: { mine: boolean }) => R)(checkIn, { mine });
20
+ expect(call<{ label: string } | null>(kind.action, false)?.label).toBe(copy.messages.checkInAnswer);
21
+ expect(call(kind.action, true)).toBeNull();
22
+ expect(call(kind.subtitle, true)).toBe(`${copy.messages.checkInSent} · Hilltop Gym`);
23
+ expect(call(kind.subtitle, false)).toBe("Hilltop Gym");
24
+ expect(kind.title(checkIn)).toBe(copy.messages.checkInCard);
25
+ });
26
+
27
+ it("offers topics in a group, not in a direct conversation", () => {
28
+ expect(kindAllowsTopics({ maxMembers: null })).toBe(true);
29
+ expect(kindAllowsTopics({ maxMembers: 12 })).toBe(true);
30
+ expect(kindAllowsTopics({ maxMembers: 2 })).toBe(false);
31
+ expect(kindAllowsTopics(null)).toBe(false);
32
+ });
33
+ });
@@ -1,41 +1,7 @@
1
- import { Redirect, Stack, router, useLocalSearchParams } from "expo-router";
2
- import type { Session } from "@supabase/supabase-js";
3
- import { useSession } from "@marktiderman/genesis-native";
4
- import { FormFocus, Button } from "@marktiderman/genesis-forms-native";
5
- import { useFormDraft } from "@marktiderman/genesis-forms-react";
6
- import { ScreenContainer } from "@marktiderman/genesis-ui-native";
7
- import starter from "../../../../starter.config";
8
1
  import { copy } from "@/copy";
9
- import { checkInDrafts, checkInForm, checkInHaptics, checkInHostOptions, checkInKey, checkInOutbox, checkInPhotos } from "@/lib/check-in";
2
+ import { CheckInScreen } from "@/lib/check-in-screen";
10
3
 
11
- /**
12
- * The check-in example (`features.checkIn`): one question per screen, the title in the native
13
- * header, a draft per signed-in user and the offline outbox. Open it with a link to fill in the
14
- * gym: `genesis-starter://check-in?gym=hilltop`.
15
- */
16
- export default function CheckInScreen() {
17
- const params = useLocalSearchParams<{ gym?: string }>();
18
- const { session } = useSession<Session>();
19
- const draft = useFormDraft(checkInForm, {
20
- store: checkInDrafts,
21
- respondent: session?.user.id ?? "signed-out",
22
- hostOptions: checkInHostOptions,
23
- linkParams: params.gym ? { gym: params.gym } : undefined,
24
- });
25
- if (!starter.features.checkIn) return <Redirect href="/" />;
26
- return (
27
- <ScreenContainer testID="check-in">
28
- <FormFocus
29
- draft={draft}
30
- outbox={checkInOutbox}
31
- createKey={checkInKey}
32
- haptics={checkInHaptics}
33
- photos={checkInPhotos}
34
- screen={Stack.Screen}
35
- headerOptions={{ headerBackTitle: copy.home.title }}
36
- testID="check-in-form"
37
- slotProps={{ ending: { actions: <Button onPress={() => router.back()} testID="check-in-done">{copy.checkIn.done}</Button> } }}
38
- />
39
- </ScreenContainer>
40
- );
4
+ /** The check-in from Home (and its link, `genesis-starter://check-in?gym=hilltop`). */
5
+ export default function HomeCheckIn() {
6
+ return <CheckInScreen backTitle={copy.home.title} />;
41
7
  }
@@ -1,12 +1,12 @@
1
1
  import { useMemo } from "react";
2
- import { Redirect, Stack, router, useLocalSearchParams, type Href } from "expo-router";
2
+ import { Redirect, Stack, router, useIsFocused, useLocalSearchParams, type Href } from "expo-router";
3
3
  import { useQuery } from "@tanstack/react-query";
4
4
  import { ChatIconButton, ChatThreadScreen, chatThreadMatch, useChatThreadStackOptions } from "@marktiderman/genesis-chat/native";
5
5
  import { chatKeys, useChat, usePeople } from "@marktiderman/genesis-chat/react";
6
6
  import { useSuppressNotifications } from "@marktiderman/genesis-native/push";
7
7
  import starter from "../../../../starter.config";
8
8
  import { copy } from "@/copy";
9
- import { chatClient } from "@/lib/chat";
9
+ import { chatClient, kindAllowsTopics } from "@/lib/chat";
10
10
 
11
11
  /**
12
12
  * One conversation (`features.chat`; ChatThreadScreen). Its own pushes stay quiet while it is open.
@@ -40,15 +40,24 @@ function Thread({ id, message, seq }: { id: string; message?: string; seq?: stri
40
40
  />
41
41
  ),
42
42
  });
43
- // A check-in card opens the check-in.
44
- const openAttachment = (a: { kind: string }) => (a.kind === "check_in" && starter.features.checkIn ? router.push("/check-in") : undefined);
43
+ // The kind's rules (the query the thread reads): a group can start its first topic, a direct one has none.
44
+ const { data: rules } = useQuery({
45
+ queryKey: ["genesis-chat", "kind", conversation?.kind ?? ""],
46
+ queryFn: () => chatClient.kind(conversation!.kind),
47
+ enabled: Boolean(conversation?.kind),
48
+ staleTime: 10 * 60_000,
49
+ });
50
+ // Another tab or a screen pushed over it pauses what the thread is playing.
51
+ const focused = useIsFocused();
52
+ // A check-in card opens the check-in in this stack, so Back comes back here.
53
+ const openAttachment = (a: { kind: string }) => (a.kind === "check_in" && starter.features.checkIn ? router.push("/messages/check-in" as Href) : undefined);
45
54
  const jumpTo = useMemo(() => (message ? { messageId: message, seq: seq ? Number(seq) : undefined } : null), [message, seq]);
46
55
  return (
47
56
  <>
48
57
  <Stack.Screen options={options} />
49
58
  {/* Keyed by the conversation: a push or link that opens another one in this screen starts it fresh
50
59
  (its list position, sheets, viewer and composer), instead of carrying the last one's over. */}
51
- <ChatThreadScreen key={id} conversationId={id} jumpTo={jumpTo} onOpenAttachment={openAttachment} />
60
+ <ChatThreadScreen key={id} conversationId={id} jumpTo={jumpTo} onOpenAttachment={openAttachment} showTopics={kindAllowsTopics(rules)} focused={focused} />
52
61
  </>
53
62
  );
54
63
  }
@@ -0,0 +1,9 @@
1
+ import { CheckInScreen } from "@/lib/check-in-screen";
2
+
3
+ /**
4
+ * The check-in opened from a card in a conversation: in the Messages stack, so Back returns to
5
+ * the conversation (its back button reads the conversation's title).
6
+ */
7
+ export default function MessagesCheckIn() {
8
+ return <CheckInScreen />;
9
+ }
@@ -1,19 +1,31 @@
1
1
  import { Redirect, Stack, router, useLocalSearchParams, type Href } from "expo-router";
2
2
  import { ChatSearchScreen } from "@marktiderman/genesis-chat/native";
3
3
  import { getSettingsPageStackOptions } from "@marktiderman/genesis-ui-native";
4
+ import { useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
4
5
  import starter from "../../../../starter.config";
5
6
  import { copy } from "@/copy";
6
7
 
7
8
  /**
8
9
  * Search (`features.chat`): every conversation from the inbox, or one (`?conversationId=`) from
9
10
  * its thread. A result opens its thread at the message: from a thread, back to that thread.
11
+ *
12
+ * The bar is opaque, in the screen's background, like the thread's (`useChatThreadStackOptions`):
13
+ * the search field sits in a plain view, not a scroll view iOS insets, so under the see-through
14
+ * bar iOS 26 draws it would sit behind the bar and the status bar.
10
15
  */
11
16
  export default function MessagesSearchScreen() {
12
17
  const { conversationId } = useLocalSearchParams<{ conversationId?: string }>();
18
+ const colors = useThemeRoles();
13
19
  if (!starter.features.chat) return <Redirect href="/" />;
14
20
  return (
15
21
  <>
16
- <Stack.Screen options={getSettingsPageStackOptions({ headerTitle: copy.messages.searchTitle, large: false })} />
22
+ <Stack.Screen
23
+ options={getSettingsPageStackOptions({
24
+ headerTitle: copy.messages.searchTitle,
25
+ large: false,
26
+ headerOptions: { headerTransparent: false, headerStyle: { backgroundColor: colors.groupedBackground } },
27
+ })}
28
+ />
17
29
  <ChatSearchScreen
18
30
  conversationId={conversationId ?? null}
19
31
  onOpen={(hit) => {
@@ -121,6 +121,8 @@ const en = {
121
121
  // A check-in sent in a conversation (an attachment of kind `check_in`), drawn as a card.
122
122
  checkInCard: "Check-in",
123
123
  checkInAnswer: "Answer",
124
+ // On the sender's own check-in card, in place of Answer.
125
+ checkInSent: "Sent",
124
126
  },
125
127
  } as const;
126
128
 
@@ -42,6 +42,7 @@ import {
42
42
  handleChatPushResponse,
43
43
  videoUploads,
44
44
  registerChatNotificationActions,
45
+ type ChatCardContext,
45
46
  type ChatNativeModules,
46
47
  } from "@marktiderman/genesis-chat/native";
47
48
  import { useSession } from "@marktiderman/genesis-native";
@@ -91,16 +92,26 @@ const modules: ChatNativeModules = {
91
92
  // Mux when the app has an upload handler, else storage (src/lib/chat-video.ts).
92
93
  const videoUpload = chatVideoUpload();
93
94
 
94
- // The app's own attachment kinds, drawn as cards in the thread. A check-in sent in a conversation
95
- // opens the check-in screen (`onOpenAttachment` in messages/[id].tsx).
96
- const attachmentKinds: NonNullable<ChatProviderProps["attachmentKinds"]> = {
95
+ // The app's own attachment kinds, drawn as cards in the thread (and named by their title in the
96
+ // inbox's preview). A check-in sent in a conversation opens the check-in screen
97
+ // (`onOpenAttachment` in messages/[id].tsx); its sender sees "Sent" instead of Answer
98
+ // (genesis-chat's native cards pass `{ mine }`).
99
+ export const attachmentKinds: NonNullable<ChatProviderProps["attachmentKinds"]> = {
97
100
  check_in: {
98
101
  title: () => copy.messages.checkInCard,
99
- subtitle: (a) => (typeof a.ref.title === "string" ? a.ref.title : null),
100
- action: () => (starter.features.checkIn ? { label: copy.messages.checkInAnswer } : null),
102
+ subtitle: (a, ctx?: ChatCardContext) => {
103
+ const title = typeof a.ref.title === "string" ? a.ref.title : null;
104
+ return ctx?.mine ? [copy.messages.checkInSent, title].filter(Boolean).join(" · ") : title;
105
+ },
106
+ action: (_a, ctx?: ChatCardContext) => (starter.features.checkIn && !ctx?.mine ? { label: copy.messages.checkInAnswer } : null),
101
107
  },
102
108
  };
103
109
 
110
+ /** Whether a conversation's kind can have topics: any kind for more than two people (not a direct one). */
111
+ export function kindAllowsTopics(rules: { maxMembers: number | null } | null | undefined): boolean {
112
+ return Boolean(rules) && rules!.maxMembers !== 2;
113
+ }
114
+
104
115
  /** Unsent messages wait here between launches (per signed-in person). */
105
116
  function outboxStore(userId: string): OutboxStore {
106
117
  const key = outboxKey(userId);
@@ -227,6 +238,18 @@ function ShareOutbox({ userId }: { userId: string }) {
227
238
  // Who was signed in last, kept outside React: the layout that sees the sign-out may be a new instance.
228
239
  let lastChatUser: string | null = null;
229
240
 
241
+ /**
242
+ * Who was signed in last, forgotten as it is read. A function on purpose: the React Compiler
243
+ * folded `const who = lastChatUser; lastChatUser = null;` in the hook below into reads of
244
+ * `lastChatUser` after the reset, so sign-out cleared the drafts, unsent messages and recent
245
+ * emoji of `null` instead of the person's.
246
+ */
247
+ function takeLastChatUser(): string | null {
248
+ const who = lastChatUser;
249
+ lastChatUser = null;
250
+ return who;
251
+ }
252
+
230
253
  /** Chat's copies of pictures in the cache: shared photos and pasted ones kept for unsent messages. */
231
254
  function clearChatFiles() {
232
255
  for (const entry of new Directory(Paths.cache).list()) {
@@ -253,9 +276,9 @@ export function useClearChatOnSignOut() {
253
276
  lastChatUser = userId;
254
277
  return;
255
278
  }
256
- if (status !== "signedOut" || !lastChatUser) return;
257
- const who = lastChatUser;
258
- lastChatUser = null;
279
+ if (status !== "signedOut") return;
280
+ const who = takeLastChatUser();
281
+ if (!who) return;
259
282
  void clearDrafts(modules.drafts!, who, onError);
260
283
  // Videos still uploading were theirs: they stop, and nothing is sent after sign-out.
261
284
  videoUploads.cancelAll();
@@ -0,0 +1,43 @@
1
+ import { Redirect, Stack, router, useLocalSearchParams } from "expo-router";
2
+ import type { Session } from "@supabase/supabase-js";
3
+ import { useSession } from "@marktiderman/genesis-native";
4
+ import { FormFocus, Button } from "@marktiderman/genesis-forms-native";
5
+ import { useFormDraft } from "@marktiderman/genesis-forms-react";
6
+ import { ScreenContainer } from "@marktiderman/genesis-ui-native";
7
+ import starter from "../../starter.config";
8
+ import { copy } from "@/copy";
9
+ import { checkInDrafts, checkInForm, checkInHaptics, checkInHostOptions, checkInKey, checkInOutbox, checkInPhotos } from "@/lib/check-in";
10
+
11
+ /**
12
+ * The check-in example (`features.checkIn`): one question per screen, the title in the native
13
+ * header, a draft per signed-in user and the offline outbox. Open it with a link to fill in the
14
+ * gym: `genesis-starter://check-in?gym=hilltop`. The Home tab shows it at `/check-in`; a check-in
15
+ * card in a conversation opens it in the Messages stack (`/messages/check-in`), so Back returns
16
+ * to the conversation. `backTitle` names the screen under it (left out, iOS uses that screen's title).
17
+ */
18
+ export function CheckInScreen({ backTitle }: { backTitle?: string }) {
19
+ const params = useLocalSearchParams<{ gym?: string }>();
20
+ const { session } = useSession<Session>();
21
+ const draft = useFormDraft(checkInForm, {
22
+ store: checkInDrafts,
23
+ respondent: session?.user.id ?? "signed-out",
24
+ hostOptions: checkInHostOptions,
25
+ linkParams: params.gym ? { gym: params.gym } : undefined,
26
+ });
27
+ if (!starter.features.checkIn) return <Redirect href="/" />;
28
+ return (
29
+ <ScreenContainer testID="check-in">
30
+ <FormFocus
31
+ draft={draft}
32
+ outbox={checkInOutbox}
33
+ createKey={checkInKey}
34
+ haptics={checkInHaptics}
35
+ photos={checkInPhotos}
36
+ screen={Stack.Screen}
37
+ headerOptions={{ headerBackTitle: backTitle }}
38
+ testID="check-in-form"
39
+ slotProps={{ ending: { actions: <Button onPress={() => router.back()} testID="check-in-done">{copy.checkIn.done}</Button> } }}
40
+ />
41
+ </ScreenContainer>
42
+ );
43
+ }
@@ -0,0 +1,85 @@
1
+ -- Genesis Chat 0003: a search hit inside a reply thread says which thread
2
+ --
3
+ -- Builds on 0001 and 0002 (never edited once released). genesis_chat.search_messages now also
4
+ -- returns thread_root_id, so the app opens the thread a reply lives in instead of reporting the
5
+ -- message missing. A return type can't change in place, so the function is dropped and made
6
+ -- again, with its grants given again by name.
7
+ --
8
+ -- Also: any change to a message's moderation (a moderator job, an admin edit, not only
9
+ -- moderate_message) sends readers a live hint, so a hidden message updates without a relaunch.
10
+ --
11
+ -- Use: `genesis add chat` copies this after 0002. Verify: tests/0003_genesis_chat_search_threads.test.sql.
12
+
13
+ -- Messages (and voice or video transcripts) you can read that match `p_query`, newest first.
14
+ -- Within one conversation, or across all of yours. The snippet marks matches with « and »; the
15
+ -- text's own « and » become ‹ and › first, so a message can't fake a highlight. A reply in a
16
+ -- thread carries its thread_root_id.
17
+ drop function genesis_chat.search_messages(text, uuid, integer);
18
+ create function genesis_chat.search_messages(p_query text, p_conversation_id uuid default null, p_limit integer default 30)
19
+ returns table (message_id uuid, conversation_id uuid, seq bigint, sender_id uuid, created_at timestamptz, snippet text, in_transcript boolean, thread_root_id uuid)
20
+ language plpgsql
21
+ stable
22
+ security definer
23
+ set search_path = ''
24
+ as $$
25
+ declare
26
+ q tsquery;
27
+ begin
28
+ if auth.uid() is null or length(btrim(coalesce(p_query, ''))) < 2 then
29
+ return;
30
+ end if;
31
+ q := websearch_to_tsquery('simple', p_query);
32
+ return query
33
+ with mine as (
34
+ select me.conversation_id from genesis_chat.members me
35
+ where me.user_id = auth.uid() and me.left_at is null and me.role <> 'observer'
36
+ and (p_conversation_id is null or me.conversation_id = p_conversation_id)
37
+ union
38
+ select p_conversation_id where p_conversation_id is not null and genesis_chat.i_observe(p_conversation_id)
39
+ ), hits as (
40
+ select m.id, m.conversation_id, m.seq, m.sender_id, m.created_at,
41
+ ts_headline('simple', translate(m.body, '«»', '‹›'), q, 'MaxWords=18, MinWords=6, StartSel=«, StopSel=»') as snippet, false as in_transcript,
42
+ m.thread_root_id
43
+ from genesis_chat.messages m join mine using (conversation_id)
44
+ where m.search @@ q and m.deleted_at is null
45
+ and (m.visibility = 'everyone' or genesis_chat.i_observe(m.conversation_id))
46
+ and (m.moderation is distinct from 'hidden' or m.sender_id = auth.uid() or genesis_chat.i_observe(m.conversation_id))
47
+ union all
48
+ select m.id, m.conversation_id, m.seq, m.sender_id, m.created_at,
49
+ ts_headline('simple', translate(a.transcript, '«»', '‹›'), q, 'MaxWords=18, MinWords=6, StartSel=«, StopSel=»'), true,
50
+ m.thread_root_id
51
+ from genesis_chat.attachments a
52
+ join genesis_chat.messages m on m.id = a.message_id
53
+ join mine on mine.conversation_id = m.conversation_id
54
+ where a.transcript is not null and a.transcript_search @@ q and m.deleted_at is null
55
+ and (m.visibility = 'everyone' or genesis_chat.i_observe(m.conversation_id))
56
+ and (m.moderation is distinct from 'hidden' or m.sender_id = auth.uid() or genesis_chat.i_observe(m.conversation_id))
57
+ )
58
+ select distinct on (h.created_at, h.id) h.id, h.conversation_id, h.seq, h.sender_id, h.created_at, h.snippet, h.in_transcript, h.thread_root_id
59
+ from hits h
60
+ order by h.created_at desc, h.id
61
+ limit least(greatest(coalesce(p_limit, 30), 1), 100);
62
+ end;
63
+ $$;
64
+
65
+ revoke execute on function genesis_chat.search_messages(text, uuid, integer) from public, anon;
66
+ grant execute on function genesis_chat.search_messages(text, uuid, integer) to authenticated, service_role;
67
+
68
+ -- ── Moderation changes reach readers live ─────────────────────────────────────
69
+
70
+ create or replace function genesis_chat.message_moderation_changed()
71
+ returns trigger
72
+ language plpgsql
73
+ security definer
74
+ set search_path = ''
75
+ as $$
76
+ begin
77
+ perform genesis_chat.broadcast('genesis-chat:conv:' || new.conversation_id, 'message',
78
+ jsonb_build_object('id', new.id, 'seq', new.seq, 'conversation_id', new.conversation_id, 'op', 'update'));
79
+ return null;
80
+ end;
81
+ $$;
82
+ revoke execute on function genesis_chat.message_moderation_changed() from public, anon, authenticated;
83
+ create trigger messages_moderation_changed after update of moderation on genesis_chat.messages
84
+ for each row when (new.moderation is distinct from old.moderation)
85
+ execute function genesis_chat.message_moderation_changed();
@@ -6,7 +6,7 @@
6
6
  -- People: a1 owns a group with b2 and e5 in it; c3 is outside; d4 is staff (an observer).
7
7
  begin;
8
8
  create extension if not exists pgtap with schema extensions;
9
- select plan(65);
9
+ select plan(66);
10
10
 
11
11
  insert into auth.users (id, aud, role, email, instance_id)
12
12
  select ('00000000-0000-4000-8000-00000000c2' || n)::uuid, 'authenticated', 'authenticated', 'genesis-chat2-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
@@ -257,9 +257,13 @@ select ok(not exists (select 1 from genesis_chat.inbox(p_exclude_kinds => array[
257
257
  'and leaves out the kinds asked to');
258
258
  select ok(genesis_chat.unread_total(p_exclude_kinds => array['cohort', 'direct']) = 0, 'so does the badge');
259
259
 
260
+ select pg_temp.sign_in('a1');
261
+ insert into t select 'late', (genesis_chat.send_message(pg_temp.v('dm1'), gen_random_uuid(), 'One more thing')).id;
260
262
  select pg_temp.as_server();
261
- select ok((select coalesce(bool_and(unread_total = 0), true) from genesis_chat.push_targets(pg_temp.v('bad'), array['cohort', 'direct'])),
262
- 'the push badge leaves out the kinds the app leaves out of its own');
263
+ select ok((select unread_total > 0 from genesis_chat.push_targets(pg_temp.v('late')) where user_id = pg_temp.person('b2')),
264
+ 'the push badge counts a new message');
265
+ select is((select unread_total from genesis_chat.push_targets(pg_temp.v('late'), array['cohort', 'direct']) where user_id = pg_temp.person('b2')), 0,
266
+ 'and leaves out the kinds the app leaves out of its own');
263
267
 
264
268
  select * from finish();
265
269
  rollback;
@@ -0,0 +1,50 @@
1
+ -- @feat:chat
2
+ -- pgTAP test for 0003_genesis_chat_search_threads.sql (with 0001 and 0002 applied).
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
+ -- Writes only its own users, kinds and conversations, and rolls everything back.
5
+ begin;
6
+ create extension if not exists pgtap with schema extensions;
7
+ select plan(6);
8
+
9
+ insert into auth.users (id, aud, role, email, instance_id)
10
+ select ('00000000-0000-4000-8000-00000000c3' || n)::uuid, 'authenticated', 'authenticated', 'genesis-chat3-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
11
+ from unnest(array['a1', 'b2', 'c3']) n;
12
+
13
+ create function pg_temp.person(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-00000000c3' || n)::uuid $$;
14
+ create function pg_temp.sign_in(n text) returns void language plpgsql as $$
15
+ begin
16
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.person(n), 'role', 'authenticated')::text, true);
17
+ perform set_config('request.jwt.claim.sub', pg_temp.person(n)::text, true);
18
+ perform set_config('role', 'authenticated', true);
19
+ end $$;
20
+ grant execute on function pg_temp.person(text), pg_temp.sign_in(text) to authenticated, service_role;
21
+
22
+ create temp table t (k text primary key, v uuid);
23
+ grant select, insert on t to authenticated, service_role;
24
+ create function pg_temp.v(k_ text) returns uuid language sql stable as $$ select v from t where k = k_ $$;
25
+ grant execute on function pg_temp.v(text) to authenticated, service_role;
26
+
27
+ create function public.genesis_chat3_test_may_start(member_ids uuid[], subject_type text, subject_id text, user_id uuid)
28
+ returns boolean language sql stable set search_path = '' as $$ select true $$;
29
+ select genesis_chat.register_kind('group', 'Group', p_membership => 'admins',
30
+ p_start_check => 'public.genesis_chat3_test_may_start(uuid[], text, text, uuid)');
31
+
32
+ select pg_temp.sign_in('a1');
33
+ insert into t select 'grp', genesis_chat.start_conversation('group', array[pg_temp.person('b2')], 'Search lab');
34
+ insert into t select 'root', (genesis_chat.send_message(pg_temp.v('grp'), gen_random_uuid(), 'a thread starter about kayaks')).id;
35
+ select genesis_chat.send_message(pg_temp.v('grp'), gen_random_uuid(), 'a reply about zebras', p_thread_root_id => pg_temp.v('root'));
36
+
37
+ select pg_temp.sign_in('b2');
38
+ select is((select thread_root_id from genesis_chat.search_messages('zebras')), pg_temp.v('root'), 'a reply in a thread comes with its thread');
39
+ select is((select thread_root_id from genesis_chat.search_messages('kayaks')), null, 'a message on the main timeline with none');
40
+ select pg_temp.sign_in('c3');
41
+ select ok(not exists (select 1 from genesis_chat.search_messages('zebras')), 'someone outside still finds nothing');
42
+ reset role;
43
+ select ok(not has_function_privilege('anon', 'genesis_chat.search_messages(text, uuid, integer)', 'execute'), 'anon can''t search');
44
+ select ok(has_function_privilege('authenticated', 'genesis_chat.search_messages(text, uuid, integer)', 'execute'), 'signed-in people can');
45
+
46
+ select ok(exists (select 1 from pg_trigger where tgname = 'messages_moderation_changed' and tgrelid = 'genesis_chat.messages'::regclass),
47
+ 'a change to a message''s moderation sends readers a live hint');
48
+
49
+ select * from finish();
50
+ rollback;