| 47 | let channel: RealtimeChannel | undefined; |
| 48 | |
| 49 | const init = async () => { |
| 50 | // Ensure an anonymous session exists. |
| 51 | // Anonymous users get a stable UUID that persists across page refreshes |
| 52 | // and is used to scope threads via Row Level Security. |
| 53 | const { |
| 54 | data: { session }, |
| 55 | } = await supabase.auth.getSession(); |
| 56 | if (!session) { |
| 57 | await supabase.auth.signInAnonymously(); |
| 58 | } |
| 59 | |
| 60 | // Subscribe to Realtime changes on the threads table. |
| 61 | // This fires whenever any thread is created, updated, or deleted — |
| 62 | // including from another tab or device logged in with the same account. |
| 63 | channel = supabase |
| 64 | .channel("threads-realtime") |
| 65 | .on("postgres_changes", { event: "*", schema: "public", table: "threads" }, () => { |
| 66 | // Remount ChatProvider so the thread sidebar refreshes. |
| 67 | // Note: remounting clears the current in-progress conversation. |
| 68 | // For production, consider a more granular update strategy. |
| 69 | setThreadListKey((k) => k + 1); |
| 70 | }) |
| 71 | .subscribe(); |
| 72 | }; |
| 73 | |
| 74 | init(); |
| 75 | |