Repository navigation
feat(mobile): add AI chat screens #1206
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { ChatScreen } from "@/screens/(authenticated)/chat/[sessionId]"; | ||
|
|
||
| export default ChatScreen; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { ChatListScreen } from "@/screens/(authenticated)/chat"; | ||
|
|
||
| export default ChatListScreen; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<SessionInfo[]> { | ||
| 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<SessionInfo | null> { | ||
| 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<SessionInfo> { | ||
| 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<SessionInfo> { | ||
| 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(); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| export { | ||
| createSession, | ||
| getOrCreateSession, | ||
| getSession, | ||
| listSessions, | ||
| type SessionInfo, | ||
| } from "./client"; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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:*", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🏁 Script executed: # Check root workspace config
cat -n package.json | head -40Repository: superset-sh/superset Length of output: 1745 🏁 Script executed: # Find all package.json files and check for `@superset/ai-chat`
fd 'package.json$' -x grep -l '@superset/ai-chat'Repository: superset-sh/superset Length of output: 90 🏁 Script executed: # Find Metro config files in the monorepo
fd -e 'js' -e 'cjs' -e 'mjs' -e 'ts' | grep -i metroRepository: superset-sh/superset Length of output: 91 🏁 Script executed: # Check if ai-chat package exists in apps directory
fd -type d '@superset.*ai-chat|ai-chat' apps/Repository: superset-sh/superset Length of output: 234 🏁 Script executed: # Get full root package.json to check for workspaces field
cat package.json | grep -A 20 '"workspaces"'Repository: superset-sh/superset Length of output: 222 🏁 Script executed: # Read the metro config to see resolver setup
cat -n apps/mobile/metro.config.jsRepository: superset-sh/superset Length of output: 989 🏁 Script executed: # Search for ai-chat package definition
find . -path '*/ai-chat/package.json' -o -path '*/ai-chat/index.*' 2>/dev/null | head -5Repository: superset-sh/superset Length of output: 46 🏁 Script executed: # Check what packages exist in apps and packages directories
ls -la apps/ && echo "---" && ls -la packages/Repository: superset-sh/superset Length of output: 1220 🏁 Script executed: # Search for any reference to ai-chat in the codebase
rg 'ai-chat' --type js --type json -i | head -20Repository: superset-sh/superset Length of output: 126 🏁 Script executed: # Check if there's an ai-chat directory anywhere in the monorepo
find . -type d -name '*ai*chat*' 2>/dev/nullRepository: superset-sh/superset Length of output: 46 🏁 Script executed: # Look at the full apps/mobile/package.json to understand context
cat -n apps/mobile/package.json | head -50Repository: superset-sh/superset Length of output: 1976 Create the The The existing workspace configuration ( 🤖 Prompt for AI Agents |
||
| "@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", | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, | ||
| }); | ||
|
Comment on lines
+29
to
+38
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🏁 Script executed: find . -type f -name "ChatListScreen.tsx" | head -5Repository: superset-sh/superset Length of output: 125 🏁 Script executed: cat -n apps/mobile/screens/authenticated/chat/ChatListScreen.tsx | head -100Repository: superset-sh/superset Length of output: 153 🏁 Script executed: cat -n "apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx" | head -100Repository: superset-sh/superset Length of output: 3722 🏁 Script executed: cat -n "apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx" | sed -n '100,220p'Repository: superset-sh/superset Length of output: 3861 Handle useQuery errors explicitly instead of silencing them as empty state. The Extract the Proposed fixconst {
data: sessions = [],
isLoading,
+ error,
refetch,
isRefetching,
} = useQuery({
queryKey: ["sessions"],
queryFn: listSessions,
enabled: !!streamsUrl,
+ onError: (err) => {
+ console.error("[chat-list] Failed to load sessions:", err);
+ },
});
...
ListEmptyComponent={
<View className="flex-1 items-center justify-center py-20">
- {isLoading ? (
+ {isLoading ? (
<Text className="text-muted-foreground">Loading chats...</Text>
+ ) : error ? (
+ <View className="items-center">
+ <Text className="text-destructive">
+ Failed to load chats
+ </Text>
+ <Button className="mt-4" onPress={() => refetch()}>
+ <Text>Retry</Text>
+ </Button>
+ </View>
) : (
<View className="items-center">
<MessageSquare size={48} color="#9ca3af" />
<Text className="text-muted-foreground mt-4">
No chats yet
</Text>
<Button className="mt-4" onPress={() => setShowNewChat(true)}>
<Text>Start a Chat</Text>
</Button>
</View>
)}
</View>
}🤖 Prompt for AI Agents |
||
|
|
||
| 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 }) => ( | ||
| <Pressable onPress={() => handleSelectSession(item)}> | ||
| <Card className="mx-4 mb-3"> | ||
| <CardContent className="flex-row items-center py-4"> | ||
| <View className="w-10 h-10 rounded-full bg-muted items-center justify-center mr-3"> | ||
| <MessageSquare size={20} color="#6b7280" /> | ||
| </View> | ||
| <View className="flex-1"> | ||
| <Text className="font-medium">{item.title}</Text> | ||
| <Text className="text-sm text-muted-foreground"> | ||
| {formatDate(item.createdAt)} | ||
| </Text> | ||
| </View> | ||
| </CardContent> | ||
| </Card> | ||
| </Pressable> | ||
| ), | ||
| [handleSelectSession], | ||
| ); | ||
|
|
||
| const keyExtractor = useCallback((item: SessionInfo) => item.sessionId, []); | ||
|
|
||
| if (!streamsUrl) { | ||
| return ( | ||
| <> | ||
| <Stack.Screen | ||
| options={{ | ||
| title: "Chat", | ||
| headerShown: true, | ||
| }} | ||
| /> | ||
| <View className="flex-1 bg-background items-center justify-center p-4"> | ||
| <Text className="text-destructive text-center"> | ||
| EXPO_PUBLIC_STREAMS_URL is not configured | ||
| </Text> | ||
| </View> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| return ( | ||
| <> | ||
| <Stack.Screen | ||
| options={{ | ||
| title: "Chat", | ||
| headerShown: true, | ||
| headerRight: () => ( | ||
| <Pressable | ||
| onPress={() => setShowNewChat(true)} | ||
| className="mr-4 p-2" | ||
| > | ||
| <Plus size={24} color="#6b7280" /> | ||
| </Pressable> | ||
| ), | ||
| }} | ||
| /> | ||
| <View className="flex-1 bg-background"> | ||
| {showNewChat && ( | ||
| <View className="p-4 border-b border-border bg-card"> | ||
| <Text className="font-medium mb-2">New Chat</Text> | ||
| <Input | ||
| placeholder="Enter chat title..." | ||
| value={newChatTitle} | ||
| onChangeText={setNewChatTitle} | ||
| autoFocus | ||
| /> | ||
| <View className="flex-row gap-2 mt-3"> | ||
| <Button | ||
| variant="outline" | ||
| className="flex-1" | ||
| onPress={() => { | ||
| setShowNewChat(false); | ||
| setNewChatTitle(""); | ||
| }} | ||
| disabled={isCreating} | ||
| > | ||
| <Text>Cancel</Text> | ||
| </Button> | ||
| <Button | ||
| className="flex-1" | ||
| onPress={handleCreateSession} | ||
| disabled={isCreating || !newChatTitle.trim()} | ||
| > | ||
| <Text>{isCreating ? "Creating..." : "Create"}</Text> | ||
| </Button> | ||
| </View> | ||
| </View> | ||
| )} | ||
|
|
||
| <FlatList | ||
| className="flex-1" | ||
| data={sessions} | ||
| renderItem={renderSession} | ||
| keyExtractor={keyExtractor} | ||
| contentContainerStyle={{ paddingTop: 16 }} | ||
| refreshControl={ | ||
| <RefreshControl refreshing={isRefetching} onRefresh={refetch} /> | ||
| } | ||
| ListEmptyComponent={ | ||
| <View className="flex-1 items-center justify-center py-20"> | ||
| {isLoading ? ( | ||
| <Text className="text-muted-foreground">Loading chats...</Text> | ||
| ) : ( | ||
| <View className="items-center"> | ||
| <MessageSquare size={48} color="#9ca3af" /> | ||
| <Text className="text-muted-foreground mt-4"> | ||
| No chats yet | ||
| </Text> | ||
| <Button className="mt-4" onPress={() => setShowNewChat(true)}> | ||
| <Text>Start a Chat</Text> | ||
| </Button> | ||
| </View> | ||
| )} | ||
| </View> | ||
| } | ||
| /> | ||
| </View> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| 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" }); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 201
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 75
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 101
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 1930
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 196
🏁 Script executed:
# Read the complete file including imports and beginning head -40 apps/mobile/lib/streams/client.tsRepository: superset-sh/superset
Length of output: 1142
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 317
🏁 Script executed:
# Check mobile app's package.json structure head -50 apps/mobile/package.jsonRepository: superset-sh/superset
Length of output: 1626
🏁 Script executed:
# Get the complete file cat apps/mobile/lib/streams/client.tsRepository: superset-sh/superset
Length of output: 2698
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 91
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 91
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 874
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 123
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 389
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 609
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 1171
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 840
Validate Streams API responses before returning them.
The client currently trusts
res.json()implicitly; malformed payloads from the API can break the UI. Add Zod schema validation to parse and validate each response, failing fast on invalid data.Proposed fix (schema validation)
Per coding guidelines: Validate external API data as untrusted by handling missing fields, unknown enums, and unexpected shapes with tolerant parsing and explicit fallbacks.
🤖 Prompt for AI Agents