Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/mobile/app/(authenticated)/chat/[sessionId].tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ChatScreen } from "@/screens/(authenticated)/chat/[sessionId]";

export default ChatScreen;
3 changes: 3 additions & 0 deletions apps/mobile/app/(authenticated)/chat/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ChatListScreen } from "@/screens/(authenticated)/chat";

export default ChatListScreen;
2 changes: 2 additions & 0 deletions apps/mobile/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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
Expand Down
119 changes: 119 additions & 0 deletions apps/mobile/lib/streams/client.ts
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();
Comment on lines +38 to +118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, locate the file
find . -name "client.ts" -o -name "client.tsx" | grep -E "mobile|streams"

Repository: superset-sh/superset

Length of output: 201


🏁 Script executed:

# Check if the file exists and get its full structure
test -f "apps/mobile/lib/streams/client.ts" && echo "File exists" || echo "File not found"

Repository: superset-sh/superset

Length of output: 75


🏁 Script executed:

# Get the line count and content of the file
wc -l apps/mobile/lib/streams/client.ts 2>/dev/null || echo "File not accessible"

Repository: superset-sh/superset

Length of output: 101


🏁 Script executed:

# Read the file to verify the exact lines and current state
head -120 apps/mobile/lib/streams/client.ts | tail -90 2>/dev/null || cat apps/mobile/lib/streams/client.ts 2>/dev/null | head -130

Repository: superset-sh/superset

Length of output: 1930


🏁 Script executed:

# Check if zod is in dependencies
find . -name "package.json" | xargs grep -l "zod" | head -5

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.ts

Repository: superset-sh/superset

Length of output: 1142


🏁 Script executed:

# Check mobile app's package.json for zod
cat apps/mobile/package.json | jq '.dependencies, .devDependencies' | grep -A 5 -B 5 "zod" || echo "Checking if zod exists in mobile..."

Repository: superset-sh/superset

Length of output: 317


🏁 Script executed:

# Check mobile app's package.json structure
head -50 apps/mobile/package.json

Repository: superset-sh/superset

Length of output: 1626


🏁 Script executed:

# Get the complete file
cat apps/mobile/lib/streams/client.ts

Repository: superset-sh/superset

Length of output: 2698


🏁 Script executed:

# Verify if there are any other files that might import/use SessionInfo or handle responses
rg "SessionInfo" apps/mobile --type ts --type tsx

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Check if there are any existing validation patterns in the mobile app
rg "safeParse|zod" apps/mobile --type ts --type tsx | head -20

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Check SessionInfo usage without file type restriction
rg "SessionInfo" apps/mobile

Repository: superset-sh/superset

Length of output: 874


🏁 Script executed:

# Check for zod usage without file type restriction
rg "safeParse|\.parse\(" apps/mobile | head -20

Repository: superset-sh/superset

Length of output: 123


🏁 Script executed:

# Check if there are other API clients to see if they validate responses
ls -la apps/mobile/lib/*/client.ts

Repository: superset-sh/superset

Length of output: 389


🏁 Script executed:

# Check one of the other client files to see if validation patterns exist
cat apps/mobile/lib/auth/client.ts | head -60

Repository: superset-sh/superset

Length of output: 609


🏁 Script executed:

# Check env.ts to see the Zod pattern used in the codebase
cat apps/mobile/lib/env.ts | head -40

Repository: superset-sh/superset

Length of output: 1171


🏁 Script executed:

# Verify ChatListScreen uses SessionInfo and see how it's consumed
grep -A 5 -B 5 "SessionInfo" apps/mobile/screens/\(authenticated\)/chat/ChatListScreen.tsx | head -30

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)
+import { z } from "zod";
 import { env } from "../env";

 export interface SessionInfo {
 	sessionId: string;
 	title: string;
 	createdAt: string;
 	createdBy?: string;
 }
+
+const sessionInfoSchema = z.object({
+	sessionId: z.string(),
+	title: z.string(),
+	createdAt: z.string(),
+	createdBy: z.string().optional(),
+});
+const sessionListSchema = z.array(sessionInfoSchema);
+
+function parseSessionInfo(data: unknown): SessionInfo {
+	const parsed = sessionInfoSchema.safeParse(data);
+	if (!parsed.success) {
+		throw new Error("Invalid session response");
+	}
+	return parsed.data;
+}

 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();
+	return sessionListSchema.parse(await 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();
+	return parseSessionInfo(await 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();
+	return parseSessionInfo(await 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();
+	return parseSessionInfo(await res.json());
 }

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
In `@apps/mobile/lib/streams/client.ts` around lines 38 - 118, Responses from the
Streams API in listSessions, getSession, createSession and getOrCreateSession
are used without validation; add Zod schemas (e.g., SessionInfoSchema and
SessionsArraySchema) and use them to parse/validate the parsed JSON from each
fetch before returning, throwing a clear error on validation failure; import z
from "zod", call await res.json() into a variable, run SessionInfoSchema.parse
or .safeParse (for listSessions use the array schema), and provide tolerant
parsing/fallbacks for optional fields like createdBy so malformed payloads fail
fast and don’t break the UI.

}
7 changes: 7 additions & 0 deletions apps/mobile/lib/streams/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export {
createSession,
getOrCreateSession,
getSession,
listSessions,
type SessionInfo,
} from "./client";
7 changes: 4 additions & 3 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Check root workspace config
cat -n package.json | head -40

Repository: 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 metro

Repository: 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.js

Repository: 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 -5

Repository: 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 -20

Repository: 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/null

Repository: 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 -50

Repository: superset-sh/superset

Length of output: 1976


Create the @superset/ai-chat package before declaring it as a workspace dependency.

The @superset/ai-chat package referenced in Line 22 does not exist in the monorepo. Adding "workspace:*" dependency to a non-existent package will cause installation and resolution failures.

The existing workspace configuration ("workspaces": ["packages/*", "apps/*"] in root package.json) and Metro setup (watchFolders and nodeModulesPaths in metro.config.js) are already properly configured for monorepo resolution, but they cannot help if the package itself is missing. Either create the @superset/ai-chat package in the appropriate directory (packages/ or apps/) or remove this dependency.

🤖 Prompt for AI Agents
In `@apps/mobile/package.json` at line 22, The package dependency
"@superset/ai-chat" declared with "workspace:*" is missing from the monorepo;
either add a new package named "@superset/ai-chat" under your workspaces
(packages/* or apps/*) with a valid package.json and export entry points, or
remove the "@superset/ai-chat" entry from the apps/mobile package.json to avoid
workspace resolution failures; update any import usage to match the created
package name or adjust imports to existing packages if you remove the
dependency.

"@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",
Expand Down
218 changes: 218 additions & 0 deletions apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "ChatListScreen.tsx" | head -5

Repository: superset-sh/superset

Length of output: 125


🏁 Script executed:

cat -n apps/mobile/screens/authenticated/chat/ChatListScreen.tsx | head -100

Repository: superset-sh/superset

Length of output: 153


🏁 Script executed:

cat -n "apps/mobile/screens/(authenticated)/chat/ChatListScreen.tsx" | head -100

Repository: 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 listSessions query at lines 29–38 doesn't destructure the error state or log failures, so when the query fails, sessions falls back to [] and the UI shows "No chats yet" instead of indicating the actual problem. This violates the coding guideline to never swallow errors silently.

Extract the error property, add an onError callback with context logging, and display an error UI with a retry button in the ListEmptyComponent (lines 179–193) when error exists.

Proposed fix
const {
    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
In `@apps/mobile/screens/`(authenticated)/chat/ChatListScreen.tsx around lines 29
- 38, Destructure the error from the useQuery call that uses queryFn:
listSessions (i.e., add error to the returned fields) and add an onError
callback to that useQuery to log the failure (e.g., console.error or your app
logger) with context; then update the ListEmptyComponent to render an error
state when that error exists (show a user-facing message and a Retry button that
calls refetch) instead of silently showing "No chats yet", ensuring you
reference the same useQuery variables (error, isLoading, refetch, isRefetching)
and the list's ListEmptyComponent to implement the retry UI.


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" });
}
Loading
Loading