diff --git a/apps/mobile/app/(authenticated)/chat/[sessionId].tsx b/apps/mobile/app/(authenticated)/chat/[sessionId].tsx new file mode 100644 index 00000000000..f8c75a8d269 --- /dev/null +++ b/apps/mobile/app/(authenticated)/chat/[sessionId].tsx @@ -0,0 +1,3 @@ +import { ChatScreen } from "@/screens/(authenticated)/chat/[sessionId]"; + +export default ChatScreen; diff --git a/apps/mobile/app/(authenticated)/chat/index.tsx b/apps/mobile/app/(authenticated)/chat/index.tsx new file mode 100644 index 00000000000..d4284f8bd4b --- /dev/null +++ b/apps/mobile/app/(authenticated)/chat/index.tsx @@ -0,0 +1,3 @@ +import { ChatListScreen } from "@/screens/(authenticated)/chat"; + +export default ChatListScreen; diff --git a/apps/mobile/lib/env.ts b/apps/mobile/lib/env.ts index 5173ffcf431..d2d9693f117 100644 --- a/apps/mobile/lib/env.ts +++ b/apps/mobile/lib/env.ts @@ -6,6 +6,7 @@ const envSchema = z.object({ .default("development"), EXPO_PUBLIC_API_URL: z.url(), EXPO_PUBLIC_WEB_URL: z.url().optional(), + EXPO_PUBLIC_STREAMS_URL: z.url().optional(), EXPO_PUBLIC_DEEP_LINK_SCHEME: z.string().default("superset"), EXPO_PUBLIC_DEEP_LINK_DOMAIN: z.string().optional(), EXPO_PUBLIC_POSTHOG_KEY: z.string(), @@ -16,6 +17,7 @@ export const env = envSchema.parse({ NODE_ENV: process.env.NODE_ENV as unknown, EXPO_PUBLIC_API_URL: process.env.EXPO_PUBLIC_API_URL as unknown, EXPO_PUBLIC_WEB_URL: process.env.EXPO_PUBLIC_WEB_URL as unknown, + EXPO_PUBLIC_STREAMS_URL: process.env.EXPO_PUBLIC_STREAMS_URL as unknown, EXPO_PUBLIC_DEEP_LINK_SCHEME: process.env .EXPO_PUBLIC_DEEP_LINK_SCHEME as unknown, EXPO_PUBLIC_DEEP_LINK_DOMAIN: process.env diff --git a/apps/mobile/lib/streams/client.ts b/apps/mobile/lib/streams/client.ts new file mode 100644 index 00000000000..2ea0dde0fcb --- /dev/null +++ b/apps/mobile/lib/streams/client.ts @@ -0,0 +1,119 @@ +/** + * Streams API Client + * + * Client for interacting with the session registry API on the streams server. + */ + +import { env } from "../env"; + +/** + * Generate a UUID using crypto.getRandomValues (polyfilled by react-native-get-random-values) + */ +export function generateUUID(): string { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + bytes[6] = (bytes[6] & 0x0f) | 0x40; // Version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // Variant 10 + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join( + "", + ); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +export interface SessionInfo { + sessionId: string; + title: string; + createdAt: string; + createdBy?: string; +} + +function getStreamsUrl(): string { + const url = env.EXPO_PUBLIC_STREAMS_URL; + if (!url) { + throw new Error("EXPO_PUBLIC_STREAMS_URL is not configured"); + } + return url; +} + +export async function listSessions(): Promise { + const url = getStreamsUrl(); + const res = await fetch(`${url}/sessions`); + + if (!res.ok) { + throw new Error(`Failed to list sessions: ${res.status} ${res.statusText}`); + } + + return res.json(); +} + +export async function getSession( + sessionId: string, +): Promise { + const url = getStreamsUrl(); + const res = await fetch(`${url}/sessions/${sessionId}`); + + if (res.status === 404) { + return null; + } + + if (!res.ok) { + throw new Error(`Failed to get session: ${res.status} ${res.statusText}`); + } + + return res.json(); +} + +export async function createSession({ + title, + createdBy, +}: { + title: string; + createdBy?: string; +}): Promise { + const url = getStreamsUrl(); + const sessionId = generateUUID(); + + const res = await fetch(`${url}/sessions`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionId, title, createdBy }), + }); + + if (!res.ok) { + throw new Error( + `Failed to create session: ${res.status} ${res.statusText}`, + ); + } + + return res.json(); +} + +export async function getOrCreateSession({ + sessionId, + title, + createdBy, +}: { + sessionId: string; + title: string; + createdBy?: string; +}): Promise { + const existing = await getSession(sessionId); + if (existing) { + return existing; + } + + const url = getStreamsUrl(); + const res = await fetch(`${url}/sessions`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionId, title, createdBy }), + }); + + if (!res.ok) { + throw new Error( + `Failed to create session: ${res.status} ${res.statusText}`, + ); + } + + return res.json(); +} diff --git a/apps/mobile/lib/streams/index.ts b/apps/mobile/lib/streams/index.ts new file mode 100644 index 00000000000..a3cb5c33259 --- /dev/null +++ b/apps/mobile/lib/streams/index.ts @@ -0,0 +1,7 @@ +export { + createSession, + getOrCreateSession, + getSession, + listSessions, + type SessionInfo, +} from "./client"; diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 03cb5f14f20..1fd58d5ef81 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -19,11 +19,12 @@ "@rn-primitives/portal": "^1.3.0", "@rn-primitives/slot": "^1.2.0", "@rn-primitives/switch": "^1.2.0", + "@superset/ai-chat": "workspace:*", "@superset/db": "workspace:*", "@superset/trpc": "workspace:*", - "@tanstack/db": "0.5.22", - "@tanstack/electric-db-collection": "0.2.27", - "@tanstack/react-db": "0.1.66", + "@tanstack/db": "^0.5.24", + "@tanstack/electric-db-collection": "0.2.30", + "@tanstack/react-db": "^0.1.68", "@tanstack/react-query": "^5.90.19", "@trpc/client": "^11.7.1", "@trpc/react-query": "^11.7.1", diff --git a/apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx b/apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx new file mode 100644 index 00000000000..4e4068d5498 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx @@ -0,0 +1,218 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { Stack, useRouter } from "expo-router"; +import { MessageSquare, Plus } from "lucide-react-native"; +import { useCallback, useState } from "react"; +import { Alert, FlatList, Pressable, RefreshControl, View } from "react-native"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Text } from "@/components/ui/text"; +import { useSession } from "@/lib/auth/client"; +import { env } from "@/lib/env"; +import { + createSession, + listSessions, + type SessionInfo, +} from "@/lib/streams/client"; + +export function ChatListScreen() { + const router = useRouter(); + const queryClient = useQueryClient(); + const { data: authSession } = useSession(); + + const [showNewChat, setShowNewChat] = useState(false); + const [newChatTitle, setNewChatTitle] = useState(""); + const [isCreating, setIsCreating] = useState(false); + + const streamsUrl = env.EXPO_PUBLIC_STREAMS_URL; + + const { + data: sessions = [], + isLoading, + refetch, + isRefetching, + } = useQuery({ + queryKey: ["sessions"], + queryFn: listSessions, + enabled: !!streamsUrl, + }); + + const handleCreateSession = useCallback(async () => { + if (!newChatTitle.trim()) { + Alert.alert("Error", "Please enter a chat title"); + return; + } + + setIsCreating(true); + try { + const session = await createSession({ + title: newChatTitle.trim(), + createdBy: authSession?.user?.id, + }); + + setNewChatTitle(""); + setShowNewChat(false); + queryClient.invalidateQueries({ queryKey: ["sessions"] }); + + // Navigate to the new chat + router.push({ + pathname: "/(authenticated)/chat/[sessionId]", + params: { sessionId: session.sessionId, title: session.title }, + }); + } catch (err) { + console.error("[chat-list] Failed to create session:", err); + Alert.alert("Error", "Failed to create chat session"); + } finally { + setIsCreating(false); + } + }, [newChatTitle, authSession?.user?.id, queryClient, router]); + + const handleSelectSession = useCallback( + (session: SessionInfo) => { + router.push({ + pathname: "/(authenticated)/chat/[sessionId]", + params: { sessionId: session.sessionId, title: session.title }, + }); + }, + [router], + ); + + const renderSession = useCallback( + ({ item }: { item: SessionInfo }) => ( + handleSelectSession(item)}> + + + + + + + {item.title} + + {formatDate(item.createdAt)} + + + + + + ), + [handleSelectSession], + ); + + const keyExtractor = useCallback((item: SessionInfo) => item.sessionId, []); + + if (!streamsUrl) { + return ( + <> + + + + EXPO_PUBLIC_STREAMS_URL is not configured + + + + ); + } + + return ( + <> + ( + setShowNewChat(true)} + className="mr-4 p-2" + > + + + ), + }} + /> + + {showNewChat && ( + + New Chat + + + + + + + )} + + + } + ListEmptyComponent={ + + {isLoading ? ( + Loading chats... + ) : ( + + + + No chats yet + + + + )} + + } + /> + + + ); +} + +function formatDate(dateString: string): string { + const date = new Date(dateString); + const now = new Date(); + const diff = now.getTime() - date.getTime(); + + // Less than 24 hours + if (diff < 24 * 60 * 60 * 1000) { + return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + } + + // Less than 7 days + if (diff < 7 * 24 * 60 * 60 * 1000) { + return date.toLocaleDateString([], { weekday: "short" }); + } + + return date.toLocaleDateString([], { month: "short", day: "numeric" }); +} diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/ChatScreen.tsx b/apps/mobile/screens/(authenticated)/chat/[sessionId]/ChatScreen.tsx new file mode 100644 index 00000000000..7267b119a2c --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/ChatScreen.tsx @@ -0,0 +1,211 @@ +import { type MessageRow, useChatSession } from "@superset/ai-chat/stream"; +import { Stack, useLocalSearchParams } from "expo-router"; +import { useCallback, useEffect, useRef } from "react"; +import { + ActivityIndicator, + FlatList, + KeyboardAvoidingView, + Platform, + View, +} from "react-native"; +import { Text } from "@/components/ui/text"; +import { useSession } from "@/lib/auth/client"; +import { env } from "@/lib/env"; +import { generateUUID } from "@/lib/streams/client"; +import { ChatInput } from "./components/ChatInput"; +import { ChatMessage } from "./components/ChatMessage"; +import { PresenceBar } from "./components/PresenceBar"; + +/** + * Send a message to the durable stream. + * Local implementation that uses generateUUID instead of crypto.randomUUID + * which isn't available in React Native. + */ +async function sendMessageToStream({ + proxyUrl, + sessionId, + userId, + content, +}: { + proxyUrl: string; + sessionId: string; + userId: string; + content: string; +}): Promise { + const uuid = generateUUID(); + + const events = [ + { + type: "chunk", + key: uuid, + value: { + type: "user_input", + content, + actorId: userId, + createdAt: new Date().toISOString(), + }, + headers: { operation: "insert" }, + }, + ]; + + const response = await fetch(`${proxyUrl}/streams/${sessionId}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(events), + }); + + if (!response.ok) { + throw new Error(`Failed to send message: ${response.status}`); + } +} + +export function ChatScreen() { + const params = useLocalSearchParams<{ sessionId: string; title?: string }>(); + const { sessionId, title } = params; + + const { data: authSession } = useSession(); + const user = authSession?.user + ? { userId: authSession.user.id, name: authSession.user.name ?? "Unknown" } + : null; + + const flatListRef = useRef>(null); + + const streamsUrl = env.EXPO_PUBLIC_STREAMS_URL; + + const { + messages, + streamingMessage, + users, + draft, + setDraft, + isLoading, + connectionStatus, + error, + } = useChatSession({ + proxyUrl: streamsUrl ?? "", + sessionId: sessionId ?? "", + user, + autoConnect: !!user && !!streamsUrl && !!sessionId, + }); + + // Scroll to bottom when new messages arrive + useEffect(() => { + if (messages.length > 0 || streamingMessage) { + setTimeout(() => { + flatListRef.current?.scrollToEnd({ animated: true }); + }, 100); + } + }, [messages.length, streamingMessage?.content, streamingMessage]); + + const handleSend = useCallback( + async (content: string) => { + if (!user?.userId || !streamsUrl || !sessionId) { + console.error( + "[chat] Cannot send message: missing user, URL, or sessionId", + ); + return; + } + try { + await sendMessageToStream({ + proxyUrl: streamsUrl, + sessionId, + userId: user.userId, + content, + }); + } catch (err) { + console.error("[chat] Failed to send message:", err); + } + }, + [user?.userId, sessionId], + ); + + const allMessages = streamingMessage + ? [...messages, streamingMessage] + : messages; + + const renderMessage = useCallback( + ({ item }: { item: MessageRow }) => ( + + ), + [user?.userId], + ); + + const keyExtractor = useCallback((item: MessageRow) => item.id, []); + + if (!sessionId) { + return ( + + No session selected + + ); + } + + if (!streamsUrl) { + return ( + + + EXPO_PUBLIC_STREAMS_URL is not configured + + + ); + } + + return ( + <> + + + + + {connectionStatus === "connecting" && ( + + + Connecting... + + )} + + {error && ( + + + Error: {error.message} + + + )} + + + + {isLoading ? "Loading messages..." : "No messages yet"} + + + } + /> + + + + + ); +} diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/ChatInput.tsx b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/ChatInput.tsx new file mode 100644 index 00000000000..d19fac07210 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/ChatInput.tsx @@ -0,0 +1,67 @@ +import { Send } from "lucide-react-native"; +import { useState } from "react"; +import { Pressable, TextInput, View } from "react-native"; + +export interface ChatInputProps { + value: string; + onChange: (value: string) => void; + onSend: (message: string) => void; + disabled?: boolean; + placeholder?: string; +} + +export function ChatInput({ + value, + onChange, + onSend, + disabled = false, + placeholder = "Type a message...", +}: ChatInputProps) { + const [isFocused, setIsFocused] = useState(false); + + const handleSend = () => { + const trimmed = value.trim(); + if (trimmed && !disabled) { + onSend(trimmed); + onChange(""); + } + }; + + const canSend = value.trim().length > 0 && !disabled; + + return ( + + + setIsFocused(true)} + onBlur={() => setIsFocused(false)} + onSubmitEditing={handleSend} + /> + + + + + + ); +} diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/index.ts b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/index.ts new file mode 100644 index 00000000000..eabdf78c145 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatInput/index.ts @@ -0,0 +1 @@ +export { ChatInput, type ChatInputProps } from "./ChatInput"; diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/ChatMessage.tsx b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/ChatMessage.tsx new file mode 100644 index 00000000000..dfd8f6657be --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/ChatMessage.tsx @@ -0,0 +1,36 @@ +import type { MessageRow } from "@superset/ai-chat/stream"; +import { View } from "react-native"; +import { Text } from "@/components/ui/text"; + +export interface ChatMessageProps { + message: MessageRow; + isCurrentUser: boolean; +} + +export function ChatMessage({ message, isCurrentUser }: ChatMessageProps) { + const alignment = isCurrentUser ? "items-end" : "items-start"; + const bgColor = isCurrentUser ? "bg-primary" : "bg-muted"; + const textColor = isCurrentUser + ? "text-primary-foreground" + : "text-foreground"; + + return ( + + + {!isCurrentUser && message.role !== "user" && ( + + {message.role} + + )} + {message.content} + + {formatTime(message.createdAt)} + + + + ); +} + +function formatTime(date: Date): string { + return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); +} diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/index.ts b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/index.ts new file mode 100644 index 00000000000..6cce2515a23 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/ChatMessage/index.ts @@ -0,0 +1 @@ +export { ChatMessage, type ChatMessageProps } from "./ChatMessage"; diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/PresenceBar.tsx b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/PresenceBar.tsx new file mode 100644 index 00000000000..63fa416accf --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/PresenceBar.tsx @@ -0,0 +1,32 @@ +import type { ChatUser } from "@superset/ai-chat/stream"; +import { View } from "react-native"; +import { Text } from "@/components/ui/text"; + +export interface PresenceBarProps { + users: ChatUser[]; + currentUserId?: string; +} + +export function PresenceBar({ users, currentUserId }: PresenceBarProps) { + const otherUsers = users.filter((u) => u.userId !== currentUserId); + + if (otherUsers.length === 0) { + return null; + } + + const displayNames = + otherUsers.length <= 3 + ? otherUsers.map((u) => u.name).join(", ") + : `${otherUsers + .slice(0, 2) + .map((u) => u.name) + .join(", ")} +${otherUsers.length - 2}`; + + return ( + + + {displayNames} {otherUsers.length === 1 ? "is" : "are"} here + + + ); +} diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/index.ts b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/index.ts new file mode 100644 index 00000000000..accc01d8d92 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/PresenceBar/index.ts @@ -0,0 +1 @@ +export { PresenceBar, type PresenceBarProps } from "./PresenceBar"; diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/index.ts b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/index.ts new file mode 100644 index 00000000000..47e55ac80f3 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/components/index.ts @@ -0,0 +1,3 @@ +export { ChatInput, type ChatInputProps } from "./ChatInput"; +export { ChatMessage, type ChatMessageProps } from "./ChatMessage"; +export { PresenceBar, type PresenceBarProps } from "./PresenceBar"; diff --git a/apps/mobile/screens/(authenticated)/chat/[sessionId]/index.ts b/apps/mobile/screens/(authenticated)/chat/[sessionId]/index.ts new file mode 100644 index 00000000000..7c2a8af1ac1 --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/[sessionId]/index.ts @@ -0,0 +1 @@ +export { ChatScreen } from "./ChatScreen"; diff --git a/apps/mobile/screens/(authenticated)/chat/index.ts b/apps/mobile/screens/(authenticated)/chat/index.ts new file mode 100644 index 00000000000..6fe1aad06fe --- /dev/null +++ b/apps/mobile/screens/(authenticated)/chat/index.ts @@ -0,0 +1,2 @@ +export { ChatScreen } from "./[sessionId]"; +export { ChatListScreen } from "./ChatListScreen"; diff --git a/apps/mobile/screens/(authenticated)/index/HomeScreen.tsx b/apps/mobile/screens/(authenticated)/index/HomeScreen.tsx index 5e6cb6682c0..c8f591b9c58 100644 --- a/apps/mobile/screens/(authenticated)/index/HomeScreen.tsx +++ b/apps/mobile/screens/(authenticated)/index/HomeScreen.tsx @@ -82,6 +82,21 @@ export function HomeScreen() { + {/* Chat */} + + + Real-time Chat + + Chat with durable streams - syncs across all devices + + + + + + + {/* Electric Collections Demo Link */}