diff --git a/CLAUDE.md b/CLAUDE.md
index 4b3af3b..fe175c0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -81,6 +81,7 @@ src/
│ └── note/
│ └── [id].tsx # Note editor for event (dynamic route)
├── components/
+│ ├── AuthGuard.tsx # Auth wrapper: loads user, shows loading, redirects if unauthenticated
│ ├── BaseBackground.tsx # Common screen wrapper (themed)
│ ├── BaseButton.tsx # Reusable button component (themed, supports children)
│ ├── Header.tsx # Header component (themed)
@@ -97,7 +98,7 @@ src/
│ └── logger.ts # react-native-logs config (apiLogger, storeLogger)
├── services/
│ ├── index.ts # Re-exports all services
-│ ├── ApiClient.ts # HTTP client with X-User-Id header injection, request logging
+│ ├── ApiClient.ts # HTTP client with X-User-Id header injection, request logging, handles empty responses (204)
│ ├── AuthService.ts # login(), register(), logout() - calls API and updates AuthStore
│ ├── EventService.ts # getAll(), getById(), getByDateRange(), create(), update(), delete()
│ └── ChatService.ts # sendMessage(), confirmEvent(), rejectEvent(), getConversations(), getConversation()
@@ -112,6 +113,13 @@ src/
**Routing:** Tab-based navigation with Chat, Calendar, and Settings as main screens. Auth screens (login, register) outside tabs. Dynamic routes for event detail and note editing.
+**Authentication Flow:**
+- `AuthGuard` component wraps the tab layout in `(tabs)/_layout.tsx`
+- On app start, `AuthGuard` calls `loadStoredUser()` and shows loading indicator
+- If not authenticated, redirects to `/login`
+- `index.tsx` simply redirects to `/(tabs)/chat` - AuthGuard handles the rest
+- This pattern handles Expo Router's navigation state caching (avoids race conditions)
+
### Theme System
The app supports multiple themes (light/dark) via a reactive Zustand store.
@@ -412,12 +420,14 @@ NODE_ENV=development # development = pretty logs, production = JSON
- **Authentication fully implemented:**
- `AuthStore`: Manages user state with expo-secure-store (native) / localStorage (web)
- `AuthService`: login(), register(), logout() - calls backend API
- - `ApiClient`: Automatically injects X-User-Id header for authenticated requests
+ - `ApiClient`: Automatically injects X-User-Id header for authenticated requests, handles empty responses (204)
+ - `AuthGuard`: Reusable component that wraps protected routes - loads user, shows loading, redirects if unauthenticated
- Login screen: Supports email OR userName login
- Register screen: Email validation, checks for existing email/userName
- `AuthButton`: Reusable button component with themed shadow
- `Header`: Themed header component (logout moved to Settings)
- - `index.tsx`: Auth redirect - checks stored user on app start
+ - `(tabs)/_layout.tsx`: Wraps tabs with AuthGuard for protected access
+ - `index.tsx`: Simple redirect to chat (AuthGuard handles auth)
- **Theme system fully implemented:**
- `ThemeStore`: Zustand store with theme state and setTheme()
- `Themes.tsx`: THEMES object with defaultLight/defaultDark variants
@@ -438,7 +448,7 @@ NODE_ENV=development # development = pretty logs, production = JSON
- Arrow navigation between proposals with "Event X von Y" counter
- Each proposal individually confirmable/rejectable
- **Typing indicator**: Animated dots (. .. ...) shown after 500ms delay while waiting for AI response
- - Messages persisted to database via ChatService and loaded on mount
+ - Messages persisted to database via ChatService, loaded via `useFocusEffect` when screen gains focus
- Tracks conversationId for message continuity across sessions
- ChatStore with addMessages() for bulk loading, chatMessageToMessageData() helper
- KeyboardAvoidingView for proper keyboard handling (iOS padding, Android height)
diff --git a/apps/client/src/app/(tabs)/_layout.tsx b/apps/client/src/app/(tabs)/_layout.tsx
index a85f6a3..7e3aecb 100644
--- a/apps/client/src/app/(tabs)/_layout.tsx
+++ b/apps/client/src/app/(tabs)/_layout.tsx
@@ -1,11 +1,13 @@
import { Ionicons } from "@expo/vector-icons";
import { Tabs } from "expo-router";
import { useThemeStore } from "../../stores/ThemeStore";
+import { AuthGuard } from "../../components/AuthGuard";
export default function TabLayout() {
const { theme } = useThemeStore();
return (
-
+
-
+
+
);
}
diff --git a/apps/client/src/app/(tabs)/calendar.tsx b/apps/client/src/app/(tabs)/calendar.tsx
index 9538ad4..0a63270 100644
--- a/apps/client/src/app/(tabs)/calendar.tsx
+++ b/apps/client/src/app/(tabs)/calendar.tsx
@@ -33,6 +33,14 @@ type MonthItem = {
label: string; // e.g. "January 2024"
};
+/**
+ * Formats a Date object to a string key in YYYY-MM-DD format.
+ * Used for grouping and looking up events by date.
+ */
+const getDateKey = (date: Date): string => {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+};
+
const generateMonths = (
centerYear: number,
centerMonth: number,
@@ -108,7 +116,7 @@ const Calendar = () => {
const map = new Map();
events.forEach((e) => {
const date = new Date(e.occurrenceStart);
- const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+ const key = getDateKey(date);
if (!map.has(key)) map.set(key, []);
map.get(key)!.push(e);
});
@@ -157,7 +165,7 @@ const Calendar = () => {
deleteEvent(event.id);
// Close overlay if no more events for this date
if (selectedDate) {
- const dateKey = `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDate.getDate()).padStart(2, "0")}`;
+ const dateKey = getDateKey(selectedDate);
const remainingEvents = eventsByDate.get(dateKey) || [];
if (remainingEvents.length <= 1) {
setSelectedDate(null);
@@ -175,7 +183,7 @@ const Calendar = () => {
// Get events for selected date
const selectedDateEvents = useMemo(() => {
if (!selectedDate) return [];
- const key = `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDate.getDate()).padStart(2, "0")}`;
+ const key = getDateKey(selectedDate);
return eventsByDate.get(key) || [];
}, [selectedDate, eventsByDate]);
@@ -597,10 +605,6 @@ const CalendarGrid = (props: CalendarGridProps) => {
return date;
};
- const getDateKey = (date: Date): string => {
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
- };
-
return (
{
+ const { isAuthenticated, isLoading: isAuthLoading } = useAuthStore();
const {
messages,
addMessage,
@@ -68,27 +71,31 @@ const Chat = () => {
return () => keyboardDidShow.remove();
}, []);
- // Load existing messages from database on mount
- useEffect(() => {
- const fetchMessages = async () => {
- try {
- const conversationSummaries = await ChatService.getConversations();
- if (conversationSummaries.length > 0) {
- const conversationId = conversationSummaries[0].id;
- setCurrentConversationId(conversationId);
+ // Load existing messages from database once authenticated and screen is focused
+ useFocusEffect(
+ useCallback(() => {
+ if (isAuthLoading || !isAuthenticated) return;
- const serverMessages =
- await ChatService.getConversation(conversationId);
- const clientMessages = serverMessages.map(chatMessageToMessageData);
- addMessages(clientMessages);
- scrollToEnd();
+ const fetchMessages = async () => {
+ try {
+ const conversationSummaries = await ChatService.getConversations();
+ if (conversationSummaries.length > 0) {
+ const conversationId = conversationSummaries[0].id;
+ setCurrentConversationId(conversationId);
+
+ const serverMessages =
+ await ChatService.getConversation(conversationId);
+ const clientMessages = serverMessages.map(chatMessageToMessageData);
+ addMessages(clientMessages);
+ scrollToEnd();
+ }
+ } catch (error) {
+ console.error("Failed to load messages:", error);
}
- } catch (error) {
- console.error("Failed to load messages:", error);
- }
- };
- fetchMessages();
- }, []);
+ };
+ fetchMessages();
+ }, [isAuthLoading, isAuthenticated]),
+ );
const scrollToEnd = () => {
setTimeout(() => {
@@ -283,6 +290,7 @@ const ChatInput = ({ onSend }: ChatInputProps) => {
className="flex-1 border border-solid rounded-2xl px-3 py-2 mr-2"
style={{
backgroundColor: theme.messageBorderBg,
+ color: theme.textPrimary,
minHeight: MIN_INPUT_HEIGHT,
maxHeight: MAX_INPUT_HEIGHT,
textAlignVertical: "top",
diff --git a/apps/client/src/app/index.tsx b/apps/client/src/app/index.tsx
index 3b720e3..b183de7 100644
--- a/apps/client/src/app/index.tsx
+++ b/apps/client/src/app/index.tsx
@@ -1,35 +1,6 @@
-import { useEffect } from "react";
-import { View, ActivityIndicator } from "react-native";
import { Redirect } from "expo-router";
-import { useAuthStore } from "../stores";
-import { useThemeStore } from "../stores/ThemeStore";
export default function Index() {
- const { isAuthenticated, isLoading, loadStoredUser } = useAuthStore();
- const { theme } = useThemeStore();
-
- useEffect(() => {
- loadStoredUser();
- }, [loadStoredUser]);
-
- if (isLoading) {
- return (
-
-
-
- );
- }
-
- if (isAuthenticated) {
- return ;
- }
-
- return ;
+ // AuthGuard in (tabs)/_layout.tsx handles authentication
+ return ;
}
diff --git a/apps/client/src/components/AuthGuard.tsx b/apps/client/src/components/AuthGuard.tsx
new file mode 100644
index 0000000..7f4de61
--- /dev/null
+++ b/apps/client/src/components/AuthGuard.tsx
@@ -0,0 +1,46 @@
+import { useEffect, ReactNode } from "react";
+import { View, ActivityIndicator } from "react-native";
+import { Redirect } from "expo-router";
+import { useAuthStore } from "../stores";
+import { useThemeStore } from "../stores/ThemeStore";
+
+type AuthGuardProps = {
+ children: ReactNode;
+};
+
+/**
+ * Wraps content that requires authentication.
+ * - Loads stored user on mount
+ * - Shows loading indicator while checking auth state
+ * - Redirects to login if not authenticated
+ * - Renders children if authenticated
+ */
+export const AuthGuard = ({ children }: AuthGuardProps) => {
+ const { theme } = useThemeStore();
+ const { isAuthenticated, isLoading, loadStoredUser } = useAuthStore();
+
+ useEffect(() => {
+ loadStoredUser();
+ }, [loadStoredUser]);
+
+ if (isLoading) {
+ return (
+
+
+
+ );
+ }
+
+ if (!isAuthenticated) {
+ return ;
+ }
+
+ return <>{children}>;
+};
diff --git a/apps/client/src/services/ApiClient.ts b/apps/client/src/services/ApiClient.ts
index 64ff4dd..6727554 100644
--- a/apps/client/src/services/ApiClient.ts
+++ b/apps/client/src/services/ApiClient.ts
@@ -55,7 +55,12 @@ async function request(
}
apiLogger.debug(`${method} ${endpoint} - ${response.status} (${duration}ms)`);
- return response.json();
+
+ const text = await response.text();
+ if (!text) {
+ return undefined as T;
+ }
+ return JSON.parse(text);
} catch (error) {
const duration = Math.round(performance.now() - start);
apiLogger.error(`${method} ${endpoint} failed (${duration}ms): ${error}`);