feat(#37-41): Add domains, ideas, relationships, agents, widgets schema

Schema additions for issues #37-41:

New models:
- Domain (#37): Life domains (work, marriage, homelab, etc.)
- Idea (#38): Brain dumps with pgvector embeddings
- Relationship (#39): Generic entity linking (blocks, depends_on)
- Agent (#40): ClawdBot agent tracking with metrics
- AgentSession (#40): Conversation session tracking
- WidgetDefinition (#41): HUD widget registry
- UserLayout (#41): Per-user dashboard configuration

Updated models:
- Task, Event, Project: Added domainId foreign key
- User, Workspace: Added new relations

New enums:
- IdeaStatus: CAPTURED, PROCESSING, ACTIONABLE, ARCHIVED, DISCARDED
- RelationshipType: BLOCKS, BLOCKED_BY, DEPENDS_ON, etc.
- AgentStatus: IDLE, WORKING, WAITING, ERROR, TERMINATED
- EntityType: Added IDEA, DOMAIN

Migration: 20260129182803_add_domains_ideas_agents_widgets
This commit is contained in:
Jason Woltje
2026-01-29 12:29:21 -06:00
parent a220c2dc0a
commit 973502f26e
308 changed files with 18374 additions and 113 deletions

View File

@@ -0,0 +1,95 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import CallbackPage from "./page";
// Mock next/navigation
const mockPush = vi.fn();
const mockSearchParams = new Map<string, string>();
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mockPush,
}),
useSearchParams: () => ({
get: (key: string) => mockSearchParams.get(key),
}),
}));
// Mock auth context
vi.mock("@/lib/auth/auth-context", () => ({
useAuth: vi.fn(() => ({
refreshSession: vi.fn(),
})),
}));
const { useAuth } = await import("@/lib/auth/auth-context");
describe("CallbackPage", () => {
beforeEach(() => {
mockPush.mockClear();
mockSearchParams.clear();
vi.mocked(useAuth).mockReturnValue({
refreshSession: vi.fn(),
user: null,
isLoading: false,
isAuthenticated: false,
signOut: vi.fn(),
});
});
it("should render processing message", () => {
render(<CallbackPage />);
expect(
screen.getByText(/completing authentication/i)
).toBeInTheDocument();
});
it("should redirect to tasks page on success", async () => {
const mockRefreshSession = vi.fn().mockResolvedValue(undefined);
vi.mocked(useAuth).mockReturnValue({
refreshSession: mockRefreshSession,
user: null,
isLoading: false,
isAuthenticated: false,
signOut: vi.fn(),
});
render(<CallbackPage />);
await waitFor(() => {
expect(mockRefreshSession).toHaveBeenCalled();
expect(mockPush).toHaveBeenCalledWith("/tasks");
});
});
it("should redirect to login on error parameter", async () => {
mockSearchParams.set("error", "access_denied");
mockSearchParams.set("error_description", "User cancelled");
render(<CallbackPage />);
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith("/login?error=access_denied");
});
});
it("should handle refresh session errors gracefully", async () => {
const mockRefreshSession = vi
.fn()
.mockRejectedValue(new Error("Session error"));
vi.mocked(useAuth).mockReturnValue({
refreshSession: mockRefreshSession,
user: null,
isLoading: false,
isAuthenticated: false,
signOut: vi.fn(),
});
render(<CallbackPage />);
await waitFor(() => {
expect(mockRefreshSession).toHaveBeenCalled();
expect(mockPush).toHaveBeenCalledWith("/login?error=session_failed");
});
});
});

View File

@@ -0,0 +1,59 @@
"use client";
import { Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/lib/auth/auth-context";
function CallbackContent() {
const router = useRouter();
const searchParams = useSearchParams();
const { refreshSession } = useAuth();
useEffect(() => {
async function handleCallback() {
// Check for OAuth errors
const error = searchParams.get("error");
if (error) {
console.error("OAuth error:", error, searchParams.get("error_description"));
router.push(`/login?error=${error}`);
return;
}
// Refresh the session to load the authenticated user
try {
await refreshSession();
router.push("/tasks");
} catch (error) {
console.error("Session refresh failed:", error);
router.push("/login?error=session_failed");
}
}
handleCallback();
}, [router, searchParams, refreshSession]);
return (
<div className="flex min-h-screen flex-col items-center justify-center p-8">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mx-auto mb-4"></div>
<h1 className="text-2xl font-semibold mb-2">Completing authentication...</h1>
<p className="text-gray-600">You will be redirected shortly.</p>
</div>
</div>
);
}
export default function CallbackPage() {
return (
<Suspense fallback={
<div className="flex min-h-screen flex-col items-center justify-center p-8">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mx-auto mb-4"></div>
<h1 className="text-2xl font-semibold mb-2">Loading...</h1>
</div>
</div>
}>
<CallbackContent />
</Suspense>
);
}

View File

@@ -0,0 +1,39 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import LoginPage from "./page";
// Mock next/navigation
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: vi.fn(),
}),
}));
describe("LoginPage", () => {
it("should render the login page with title", () => {
render(<LoginPage />);
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent(
"Welcome to Mosaic Stack"
);
});
it("should display the description", () => {
render(<LoginPage />);
const descriptions = screen.getAllByText(/Your personal assistant platform/i);
expect(descriptions.length).toBeGreaterThan(0);
expect(descriptions[0]).toBeInTheDocument();
});
it("should render the sign in button", () => {
render(<LoginPage />);
const buttons = screen.getAllByRole("button", { name: /sign in/i });
expect(buttons.length).toBeGreaterThan(0);
expect(buttons[0]).toBeInTheDocument();
});
it("should have proper layout styling", () => {
const { container } = render(<LoginPage />);
const main = container.querySelector("main");
expect(main).toHaveClass("flex", "min-h-screen");
});
});

View File

@@ -0,0 +1,20 @@
import { LoginButton } from "@/components/auth/LoginButton";
export default function LoginPage() {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-8 bg-gray-50">
<div className="w-full max-w-md space-y-8">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">Welcome to Mosaic Stack</h1>
<p className="text-lg text-gray-600">
Your personal assistant platform. Organize tasks, events, and
projects with a PDA-friendly approach.
</p>
</div>
<div className="bg-white p-8 rounded-lg shadow-md">
<LoginButton />
</div>
</div>
</main>
);
}

View File

@@ -0,0 +1,27 @@
"use client";
import { Calendar } from "@/components/calendar/Calendar";
import { mockEvents } from "@/lib/api/events";
export default function CalendarPage() {
// TODO: Replace with real API call when backend is ready
// const { data: events, isLoading } = useQuery({
// queryKey: ["events"],
// queryFn: fetchEvents,
// });
const events = mockEvents;
const isLoading = false;
return (
<main className="container mx-auto px-4 py-8">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900">Calendar</h1>
<p className="text-gray-600 mt-2">
View your schedule at a glance
</p>
</div>
<Calendar events={events} isLoading={isLoading} />
</main>
);
}

View File

@@ -0,0 +1,37 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth/auth-context";
import { Navigation } from "@/components/layout/Navigation";
import type { ReactNode } from "react";
export default function AuthenticatedLayout({ children }: { children: ReactNode }) {
const router = useRouter();
const { isAuthenticated, isLoading } = useAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push("/login");
}
}, [isAuthenticated, isLoading, router]);
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen bg-gray-50">
<Navigation />
<div className="pt-16">{children}</div>
</div>
);
}

View File

@@ -0,0 +1,30 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import TasksPage from "./page";
// Mock the TaskList component
vi.mock("@/components/tasks/TaskList", () => ({
TaskList: ({ tasks, isLoading }: { tasks: unknown[]; isLoading: boolean }) => (
<div data-testid="task-list">
{isLoading ? "Loading" : `${tasks.length} tasks`}
</div>
),
}));
describe("TasksPage", () => {
it("should render the page title", () => {
render(<TasksPage />);
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Tasks");
});
it("should render the TaskList component", () => {
render(<TasksPage />);
expect(screen.getByTestId("task-list")).toBeInTheDocument();
});
it("should have proper layout structure", () => {
const { container } = render(<TasksPage />);
const main = container.querySelector("main");
expect(main).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,27 @@
"use client";
import { TaskList } from "@/components/tasks/TaskList";
import { mockTasks } from "@/lib/api/tasks";
export default function TasksPage() {
// TODO: Replace with real API call when backend is ready
// const { data: tasks, isLoading } = useQuery({
// queryKey: ["tasks"],
// queryFn: fetchTasks,
// });
const tasks = mockTasks;
const isLoading = false;
return (
<main className="container mx-auto px-4 py-8">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900">Tasks</h1>
<p className="text-gray-600 mt-2">
Organize your work at your own pace
</p>
</div>
<TaskList tasks={tasks} isLoading={isLoading} />
</main>
);
}

View File

@@ -1,5 +1,7 @@
import type { Metadata } from "next";
import type { ReactNode } from "react";
import { AuthProvider } from "@/lib/auth/auth-context";
import { ErrorBoundary } from "@/components/error-boundary";
import "./globals.css";
export const metadata: Metadata = {
@@ -10,7 +12,11 @@ export const metadata: Metadata = {
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
<body>
<ErrorBoundary>
<AuthProvider>{children}</AuthProvider>
</ErrorBoundary>
</body>
</html>
);
}

View File

@@ -1,22 +1,42 @@
import { describe, expect, it, afterEach } from "vitest";
import { render, screen, cleanup } from "@testing-library/react";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { render } from "@testing-library/react";
import Home from "./page";
afterEach(() => {
cleanup();
});
// Mock Next.js navigation
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mockPush,
replace: vi.fn(),
prefetch: vi.fn(),
}),
}));
// Mock auth context
vi.mock("@/lib/auth/auth-context", () => ({
useAuth: () => ({
user: null,
isLoading: false,
isAuthenticated: false,
signOut: vi.fn(),
refreshSession: vi.fn(),
}),
}));
describe("Home", () => {
it("should render the title", () => {
render(<Home />);
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Mosaic Stack");
beforeEach(() => {
mockPush.mockClear();
});
it("should render the buttons", () => {
it("should render loading spinner", () => {
const { container } = render(<Home />);
// The home page shows a loading spinner while redirecting
const spinner = container.querySelector(".animate-spin");
expect(spinner).toBeInTheDocument();
});
it("should redirect unauthenticated users to login", () => {
render(<Home />);
const buttons = screen.getAllByRole("button");
expect(buttons.length).toBe(2);
expect(buttons[0]).toHaveTextContent("Get Started");
expect(buttons[1]).toHaveTextContent("Learn More");
expect(mockPush).toHaveBeenCalledWith("/login");
});
});

View File

@@ -1,14 +1,26 @@
import { Button } from "@mosaic/ui";
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth/auth-context";
export default function Home() {
const router = useRouter();
const { isAuthenticated, isLoading } = useAuth();
useEffect(() => {
if (!isLoading) {
if (isAuthenticated) {
router.push("/tasks");
} else {
router.push("/login");
}
}
}, [isAuthenticated, isLoading, router]);
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24">
<h1 className="text-4xl font-bold mb-8">Mosaic Stack</h1>
<p className="text-lg text-gray-600 mb-8">Welcome to the Mosaic Stack monorepo</p>
<div className="flex gap-4">
<Button variant="primary">Get Started</Button>
<Button variant="secondary">Learn More</Button>
</div>
</main>
<div className="flex min-h-screen items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
);
}

View File

@@ -0,0 +1,45 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { LoginButton } from "./LoginButton";
// Mock window.location
const mockLocation = {
href: "",
assign: vi.fn(),
};
Object.defineProperty(window, "location", {
value: mockLocation,
writable: true,
});
describe("LoginButton", () => {
beforeEach(() => {
mockLocation.href = "";
mockLocation.assign.mockClear();
});
it("should render sign in button", () => {
render(<LoginButton />);
const button = screen.getByRole("button", { name: /sign in/i });
expect(button).toBeInTheDocument();
});
it("should redirect to OIDC endpoint on click", async () => {
const user = userEvent.setup();
render(<LoginButton />);
const button = screen.getByRole("button", { name: /sign in/i });
await user.click(button);
expect(mockLocation.assign).toHaveBeenCalledWith(
"http://localhost:3001/auth/callback/authentik"
);
});
it("should have proper styling", () => {
render(<LoginButton />);
const button = screen.getByRole("button", { name: /sign in/i });
expect(button).toHaveClass("w-full");
});
});

View File

@@ -0,0 +1,19 @@
"use client";
import { Button } from "@mosaic/ui";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
export function LoginButton() {
const handleLogin = () => {
// Redirect to the backend OIDC authentication endpoint
// BetterAuth will handle the OIDC flow and redirect back to the callback
window.location.assign(`${API_URL}/auth/callback/authentik`);
};
return (
<Button variant="primary" onClick={handleLogin} className="w-full">
Sign In with Authentik
</Button>
);
}

View File

@@ -0,0 +1,83 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { LogoutButton } from "./LogoutButton";
// Mock next/navigation
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mockPush,
}),
}));
// Mock auth context
const mockSignOut = vi.fn();
vi.mock("@/lib/auth/auth-context", () => ({
useAuth: () => ({
signOut: mockSignOut,
}),
}));
describe("LogoutButton", () => {
beforeEach(() => {
mockPush.mockClear();
mockSignOut.mockClear();
});
it("should render sign out button", () => {
render(<LogoutButton />);
const button = screen.getByRole("button", { name: /sign out/i });
expect(button).toBeInTheDocument();
});
it("should call signOut and redirect on click", async () => {
const user = userEvent.setup();
mockSignOut.mockResolvedValue(undefined);
render(<LogoutButton />);
const button = screen.getByRole("button", { name: /sign out/i });
await user.click(button);
await waitFor(() => {
expect(mockSignOut).toHaveBeenCalled();
expect(mockPush).toHaveBeenCalledWith("/login");
});
});
it("should redirect to login even if signOut fails", async () => {
const user = userEvent.setup();
mockSignOut.mockRejectedValue(new Error("Sign out failed"));
// Suppress console.error for this test
const consoleErrorSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
render(<LogoutButton />);
const button = screen.getByRole("button", { name: /sign out/i });
await user.click(button);
await waitFor(() => {
expect(mockSignOut).toHaveBeenCalled();
expect(mockPush).toHaveBeenCalledWith("/login");
});
consoleErrorSpy.mockRestore();
});
it("should have secondary variant by default", () => {
render(<LogoutButton />);
const button = screen.getByRole("button", { name: /sign out/i });
// The Button component from @mosaic/ui should apply the variant
expect(button).toBeInTheDocument();
});
it("should accept custom variant prop", () => {
render(<LogoutButton variant="primary" />);
const button = screen.getByRole("button", { name: /sign out/i });
expect(button).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,31 @@
"use client";
import { useRouter } from "next/navigation";
import { Button, type ButtonProps } from "@mosaic/ui";
import { useAuth } from "@/lib/auth/auth-context";
interface LogoutButtonProps {
variant?: ButtonProps["variant"];
className?: string;
}
export function LogoutButton({ variant = "secondary", className }: LogoutButtonProps) {
const router = useRouter();
const { signOut } = useAuth();
const handleSignOut = async () => {
try {
await signOut();
} catch (error) {
console.error("Sign out error:", error);
} finally {
router.push("/login");
}
};
return (
<Button variant={variant} onClick={handleSignOut} className={className}>
Sign Out
</Button>
);
}

View File

@@ -0,0 +1,64 @@
import type { Event } from "@mosaic/shared";
import { EventCard } from "./EventCard";
import { getDateGroupLabel } from "@/lib/utils/date-format";
interface CalendarProps {
events: Event[];
isLoading: boolean;
}
export function Calendar({ events, isLoading }: CalendarProps) {
if (isLoading) {
return (
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
<span className="ml-3 text-gray-600">Loading calendar...</span>
</div>
);
}
if (events.length === 0) {
return (
<div className="text-center p-8 text-gray-500">
<p className="text-lg">No events scheduled</p>
<p className="text-sm mt-2">Your calendar is clear</p>
</div>
);
}
// Group events by date
const groupedEvents = events.reduce((groups, event) => {
const label = getDateGroupLabel(event.startTime);
if (!groups[label]) {
groups[label] = [];
}
groups[label].push(event);
return groups;
}, {} as Record<string, Event[]>);
const groupOrder = ["Today", "Tomorrow", "This Week", "Next Week", "Later"];
return (
<main className="space-y-6">
{groupOrder.map((groupLabel) => {
const groupEvents = groupedEvents[groupLabel];
if (!groupEvents || groupEvents.length === 0) {
return null;
}
return (
<section key={groupLabel}>
<h2 className="text-lg font-semibold text-gray-700 mb-3">
{groupLabel}
</h2>
<div className="space-y-2">
{groupEvents.map((event) => (
<EventCard key={event.id} event={event} />
))}
</div>
</section>
);
})}
</main>
);
}

View File

@@ -0,0 +1,32 @@
import type { Event } from "@mosaic/shared";
import { formatTime } from "@/lib/utils/date-format";
interface EventCardProps {
event: Event;
}
export function EventCard({ event }: EventCardProps) {
return (
<div className="bg-white p-3 rounded-lg border-l-4 border-blue-500 shadow-sm hover:shadow-md transition-shadow">
<div className="flex justify-between items-start mb-1">
<h3 className="font-semibold text-gray-900">{event.title}</h3>
{event.allDay ? (
<span className="text-xs text-gray-500 px-2 py-1 bg-gray-100 rounded">
All day
</span>
) : (
<span className="text-xs text-gray-500">
{formatTime(event.startTime)}
{event.endTime && ` - ${formatTime(event.endTime)}`}
</span>
)}
</div>
{event.description && (
<p className="text-sm text-gray-600 mb-2">{event.description}</p>
)}
{event.location && (
<p className="text-xs text-gray-500">📍 {event.location}</p>
)}
</div>
);
}

View File

@@ -0,0 +1,114 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ErrorBoundary } from "./error-boundary";
// Component that throws an error for testing
function ThrowError({ shouldThrow }: { shouldThrow: boolean }) {
if (shouldThrow) {
throw new Error("Test error");
}
return <div>No error</div>;
}
describe("ErrorBoundary", () => {
// Suppress console.error for these tests
const originalError = console.error;
beforeEach(() => {
console.error = vi.fn();
});
afterEach(() => {
console.error = originalError;
});
it("should render children when there is no error", () => {
render(
<ErrorBoundary>
<div>Test content</div>
</ErrorBoundary>
);
expect(screen.getByText("Test content")).toBeInTheDocument();
});
it("should render error UI when child throws error", () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
// Should show PDA-friendly message, not harsh "error" language
expect(screen.getByText(/something unexpected happened/i)).toBeInTheDocument();
});
it("should use PDA-friendly language without demanding words", () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
const errorText = screen.getByText(/something unexpected happened/i).textContent || "";
// Should NOT contain demanding/harsh words
expect(errorText.toLowerCase()).not.toMatch(/error|critical|urgent|must|required/);
});
it("should provide a reload option", () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
const reloadButton = screen.getByRole("button", { name: /refresh/i });
expect(reloadButton).toBeInTheDocument();
});
it("should reload page when reload button is clicked", async () => {
const user = userEvent.setup();
const mockReload = vi.fn();
Object.defineProperty(window, "location", {
value: { reload: mockReload },
writable: true,
});
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
const reloadButton = screen.getByRole("button", { name: /refresh/i });
await user.click(reloadButton);
expect(mockReload).toHaveBeenCalled();
});
it("should provide a way to go back home", () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
const homeLink = screen.getByRole("link", { name: /home/i });
expect(homeLink).toBeInTheDocument();
expect(homeLink).toHaveAttribute("href", "/");
});
it("should have calm, non-alarming visual design", () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
const container = screen.getByText(/something unexpected happened/i).closest("div");
// Should not have aggressive red colors (check for calm colors)
const className = container?.className || "";
expect(className).not.toMatch(/bg-red-|text-red-/);
});
});

View File

@@ -0,0 +1,116 @@
"use client";
import { Component, type ReactNode } from "react";
import Link from "next/link";
interface ErrorBoundaryProps {
children: ReactNode;
}
interface ErrorBoundaryState {
hasError: boolean;
error?: Error;
}
/**
* Error boundary component for graceful error handling
* Uses PDA-friendly language and calm visual design
*/
export class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// Log to console for debugging (could also send to error tracking service)
console.error("Component error:", error, errorInfo);
}
handleReload = () => {
window.location.reload();
};
render() {
if (this.state.hasError) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="max-w-md w-full text-center space-y-6">
{/* Icon - calm blue instead of alarming red */}
<div className="flex justify-center">
<div className="rounded-full bg-blue-100 p-3">
<svg
className="w-8 h-8 text-blue-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</div>
</div>
{/* Message - PDA-friendly, no harsh language */}
<div className="space-y-2">
<h1 className="text-2xl font-semibold text-gray-900">
Something unexpected happened
</h1>
<p className="text-gray-600">
The page ran into an issue while loading. You can try refreshing
or head back home to continue.
</p>
</div>
{/* Actions */}
<div className="flex flex-col gap-3 pt-4">
<button
onClick={this.handleReload}
className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Refresh page
</button>
<Link
href="/"
className="inline-flex items-center justify-center px-4 py-2 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Go home
</Link>
</div>
{/* Technical details in dev mode */}
{process.env.NODE_ENV === "development" && this.state.error && (
<details className="mt-8 text-left">
<summary className="cursor-pointer text-sm text-gray-500 hover:text-gray-700">
Technical details
</summary>
<pre className="mt-2 text-xs text-gray-600 bg-gray-100 p-3 rounded overflow-auto max-h-40">
{this.state.error.message}
{"\n\n"}
{this.state.error.stack}
</pre>
</details>
)}
</div>
</div>
);
}
return this.props.children;
}
}

View File

@@ -0,0 +1,56 @@
"use client";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { useAuth } from "@/lib/auth/auth-context";
import { LogoutButton } from "@/components/auth/LogoutButton";
export function Navigation() {
const pathname = usePathname();
const { user } = useAuth();
const navItems = [
{ href: "/tasks", label: "Tasks" },
{ href: "/calendar", label: "Calendar" },
];
return (
<nav className="fixed top-0 left-0 right-0 bg-white border-b border-gray-200 z-50">
<div className="container mx-auto px-4">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-8">
<Link href="/tasks" className="text-xl font-bold text-gray-900">
Mosaic Stack
</Link>
<div className="flex gap-4">
{navItems.map((item) => {
const isActive = pathname === item.href;
return (
<Link
key={item.href}
href={item.href}
className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${
isActive
? "bg-blue-100 text-blue-700"
: "text-gray-600 hover:bg-gray-100"
}`}
>
{item.label}
</Link>
);
})}
</div>
</div>
<div className="flex items-center gap-4">
{user && (
<div className="text-sm text-gray-600">
{user.name || user.email}
</div>
)}
<LogoutButton variant="secondary" />
</div>
</div>
</div>
</nav>
);
}

View File

@@ -0,0 +1,227 @@
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { TaskItem } from "./TaskItem";
import { TaskStatus, TaskPriority, type Task } from "@mosaic/shared";
describe("TaskItem", () => {
const baseTask: Task = {
id: "task-1",
title: "Test task",
description: "Task description",
status: TaskStatus.IN_PROGRESS,
priority: TaskPriority.MEDIUM,
dueDate: new Date("2026-01-29"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 0,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
};
it("should render task title", () => {
render(<TaskItem task={baseTask} />);
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should render task description when present", () => {
render(<TaskItem task={baseTask} />);
expect(screen.getByText("Task description")).toBeInTheDocument();
});
it("should show status indicator for active task", () => {
render(<TaskItem task={{ ...baseTask, status: TaskStatus.IN_PROGRESS }} />);
expect(screen.getByText("🟢")).toBeInTheDocument();
});
it("should show status indicator for not started task", () => {
render(<TaskItem task={{ ...baseTask, status: TaskStatus.NOT_STARTED }} />);
expect(screen.getByText("⚪")).toBeInTheDocument();
});
it("should show status indicator for paused task", () => {
render(<TaskItem task={{ ...baseTask, status: TaskStatus.PAUSED }} />);
expect(screen.getByText("⏸️")).toBeInTheDocument();
});
it("should display priority badge", () => {
render(<TaskItem task={{ ...baseTask, priority: TaskPriority.HIGH }} />);
expect(screen.getByText("High priority")).toBeInTheDocument();
});
it("should not use demanding language", () => {
const { container } = render(<TaskItem task={baseTask} />);
const text = container.textContent;
expect(text).not.toMatch(/overdue/i);
expect(text).not.toMatch(/urgent/i);
expect(text).not.toMatch(/must/i);
expect(text).not.toMatch(/critical/i);
});
it("should show 'Target passed' for past due dates", () => {
const pastTask = {
...baseTask,
dueDate: new Date("2026-01-27"), // Past date
};
render(<TaskItem task={pastTask} />);
expect(screen.getByText(/target passed/i)).toBeInTheDocument();
});
it("should show 'Approaching target' for near due dates", () => {
const soonTask = {
...baseTask,
dueDate: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours from now
};
render(<TaskItem task={soonTask} />);
expect(screen.getByText(/approaching target/i)).toBeInTheDocument();
});
describe("error states", () => {
it("should handle task with missing title", () => {
const taskWithoutTitle = {
...baseTask,
title: "",
};
const { container } = render(<TaskItem task={taskWithoutTitle} />);
// Should render without crashing, even with empty title
expect(container.querySelector(".bg-white")).toBeInTheDocument();
});
it("should handle task with missing description", () => {
const taskWithoutDescription = {
...baseTask,
description: null,
};
render(<TaskItem task={taskWithoutDescription} />);
expect(screen.getByText("Test task")).toBeInTheDocument();
// Description paragraph should not be rendered when null
expect(screen.queryByText("Task description")).not.toBeInTheDocument();
});
it("should handle task with invalid status", () => {
const taskWithInvalidStatus = {
...baseTask,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
status: "invalid-status" as any,
};
const { container } = render(<TaskItem task={taskWithInvalidStatus} />);
// Should render without crashing even with invalid status
expect(container.querySelector(".bg-white")).toBeInTheDocument();
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should handle task with invalid priority", () => {
const taskWithInvalidPriority = {
...baseTask,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
priority: "invalid-priority" as any,
};
const { container } = render(<TaskItem task={taskWithInvalidPriority} />);
// Should render without crashing even with invalid priority
expect(container.querySelector(".bg-white")).toBeInTheDocument();
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should handle task with missing dueDate", () => {
const taskWithoutDueDate = {
...baseTask,
dueDate: null,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
render(<TaskItem task={taskWithoutDueDate as any} />);
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should handle task with invalid dueDate", () => {
const taskWithInvalidDate = {
...baseTask,
dueDate: new Date("invalid-date"),
};
const { container } = render(<TaskItem task={taskWithInvalidDate} />);
expect(container.querySelector(".bg-white")).toBeInTheDocument();
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should handle task with very long title", () => {
const longTitle = "A".repeat(500);
const taskWithLongTitle = {
...baseTask,
title: longTitle,
};
render(<TaskItem task={taskWithLongTitle} />);
expect(screen.getByText(longTitle)).toBeInTheDocument();
});
it("should handle task with special characters in title", () => {
const taskWithSpecialChars = {
...baseTask,
title: '<img src="x" onerror="alert(1)">',
};
const { container } = render(<TaskItem task={taskWithSpecialChars} />);
// Should render escaped HTML entities, not execute
// React escapes to &lt;img... &gt; which is safe
expect(container.innerHTML).toContain("&lt;img");
expect(container.innerHTML).not.toContain("<img src=");
// Text should be displayed as-is
expect(screen.getByText(/<img src="x" onerror="alert\(1\)">/)).toBeInTheDocument();
});
it("should handle task with HTML in description", () => {
const taskWithHtmlDesc = {
...baseTask,
description: '<b>Bold text</b><script>alert("xss")</script>',
};
const { container } = render(<TaskItem task={taskWithHtmlDesc} />);
// Should render as text, not HTML - React escapes by default
expect(container.innerHTML).not.toContain("<script>");
// Text should be displayed as-is
expect(screen.getByText(/Bold text/)).toBeInTheDocument();
});
it("should handle task with missing required IDs", () => {
const taskWithMissingIds = {
...baseTask,
id: "",
workspaceId: "",
};
const { container } = render(<TaskItem task={taskWithMissingIds} />);
expect(container.querySelector(".bg-white")).toBeInTheDocument();
expect(screen.getByText("Test task")).toBeInTheDocument();
});
it("should handle task with extremely old due date", () => {
const veryOldTask = {
...baseTask,
dueDate: new Date("1970-01-01"),
};
render(<TaskItem task={veryOldTask} />);
expect(screen.getByText(/target passed/i)).toBeInTheDocument();
});
it("should handle task with far future due date", () => {
const farFutureTask = {
...baseTask,
dueDate: new Date("2099-12-31"),
};
const { container } = render(<TaskItem task={farFutureTask} />);
expect(container.querySelector(".bg-white")).toBeInTheDocument();
expect(screen.getByText("Test task")).toBeInTheDocument();
});
});
});

View File

@@ -0,0 +1,69 @@
import type { Task } from "@mosaic/shared";
import { TaskStatus, TaskPriority } from "@mosaic/shared";
import { formatDate, isPastTarget, isApproachingTarget } from "@/lib/utils/date-format";
interface TaskItemProps {
task: Task;
}
const statusIcons: Record<TaskStatus, string> = {
[TaskStatus.NOT_STARTED]: "⚪",
[TaskStatus.IN_PROGRESS]: "🟢",
[TaskStatus.PAUSED]: "⏸️",
[TaskStatus.COMPLETED]: "✅",
[TaskStatus.ARCHIVED]: "💤",
};
const priorityLabels: Record<TaskPriority, string> = {
[TaskPriority.HIGH]: "High priority",
[TaskPriority.MEDIUM]: "Medium priority",
[TaskPriority.LOW]: "Low priority",
};
export function TaskItem({ task }: TaskItemProps) {
const statusIcon = statusIcons[task.status];
const priorityLabel = priorityLabels[task.priority];
// PDA-friendly date status
let dateStatus = "";
if (task.dueDate) {
if (isPastTarget(task.dueDate)) {
dateStatus = "Target passed";
} else if (isApproachingTarget(task.dueDate)) {
dateStatus = "Approaching target";
}
}
return (
<div className="bg-white p-4 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-shadow">
<div className="flex items-start gap-3">
<span className="text-xl flex-shrink-0" aria-label={`Status: ${task.status}`}>
{statusIcon}
</span>
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-gray-900 mb-1">{task.title}</h3>
{task.description && (
<p className="text-sm text-gray-600 mb-2">{task.description}</p>
)}
<div className="flex flex-wrap items-center gap-2 text-xs">
{task.priority && (
<span className="px-2 py-1 bg-blue-100 text-blue-700 rounded-full">
{priorityLabel}
</span>
)}
{task.dueDate && (
<span className="text-gray-500">
{formatDate(task.dueDate)}
</span>
)}
{dateStatus && (
<span className="px-2 py-1 bg-amber-100 text-amber-700 rounded-full">
{dateStatus}
</span>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,156 @@
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { TaskList } from "./TaskList";
import { TaskStatus, TaskPriority, type Task } from "@mosaic/shared";
describe("TaskList", () => {
const mockTasks: Task[] = [
{
id: "task-1",
title: "Review pull request",
description: "Review and provide feedback on frontend PR",
status: TaskStatus.IN_PROGRESS,
priority: TaskPriority.HIGH,
dueDate: new Date("2026-01-29"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 0,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "task-2",
title: "Update documentation",
description: "Add setup instructions",
status: TaskStatus.NOT_STARTED,
priority: TaskPriority.MEDIUM,
dueDate: new Date("2026-02-05"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 1,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
];
it("should render empty state when no tasks", () => {
render(<TaskList tasks={[]} isLoading={false} />);
expect(screen.getByText(/no tasks scheduled/i)).toBeInTheDocument();
});
it("should render loading state", () => {
render(<TaskList tasks={[]} isLoading={true} />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
});
it("should render tasks list", () => {
render(<TaskList tasks={mockTasks} isLoading={false} />);
expect(screen.getByText("Review pull request")).toBeInTheDocument();
expect(screen.getByText("Update documentation")).toBeInTheDocument();
});
it("should group tasks by date", () => {
render(<TaskList tasks={mockTasks} isLoading={false} />);
// Should have date group sections (Today, This Week, etc.)
// The exact sections depend on the current date, so just verify grouping works
const sections = screen.getAllByRole("heading", { level: 2 });
expect(sections.length).toBeGreaterThan(0);
});
it("should use PDA-friendly language", () => {
render(<TaskList tasks={mockTasks} isLoading={false} />);
// Should NOT contain demanding language
const text = screen.getByRole("main").textContent;
expect(text).not.toMatch(/overdue/i);
expect(text).not.toMatch(/urgent/i);
expect(text).not.toMatch(/must do/i);
});
it("should display status indicators", () => {
render(<TaskList tasks={mockTasks} isLoading={false} />);
// Check for emoji status indicators (rendered as text)
const listItems = screen.getAllByRole("listitem");
expect(listItems.length).toBe(mockTasks.length);
});
describe("error states", () => {
it("should handle undefined tasks gracefully", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
render(<TaskList tasks={undefined as any} isLoading={false} />);
expect(screen.getByText(/no tasks scheduled/i)).toBeInTheDocument();
});
it("should handle null tasks gracefully", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
render(<TaskList tasks={null as any} isLoading={false} />);
expect(screen.getByText(/no tasks scheduled/i)).toBeInTheDocument();
});
it("should handle tasks with missing required fields", () => {
const malformedTasks = [
{
...mockTasks[0],
title: "", // Empty title
},
];
render(<TaskList tasks={malformedTasks} isLoading={false} />);
// Component should render without crashing
expect(screen.getByRole("main")).toBeInTheDocument();
});
it("should handle tasks with invalid dates", () => {
const tasksWithBadDates = [
{
...mockTasks[0],
dueDate: new Date("invalid-date"),
},
];
render(<TaskList tasks={tasksWithBadDates} isLoading={false} />);
expect(screen.getByRole("main")).toBeInTheDocument();
});
it("should handle extremely large task lists", () => {
const largeTasks = Array.from({ length: 1000 }, (_, i) => ({
...mockTasks[0],
id: `task-${i}`,
title: `Task ${i}`,
}));
render(<TaskList tasks={largeTasks} isLoading={false} />);
expect(screen.getByRole("main")).toBeInTheDocument();
});
it("should handle tasks with very long titles", () => {
const longTitleTask = {
...mockTasks[0],
title: "A".repeat(500),
};
render(<TaskList tasks={[longTitleTask]} isLoading={false} />);
expect(screen.getByText(/A{500}/)).toBeInTheDocument();
});
it("should handle tasks with special characters in title", () => {
const specialCharTask = {
...mockTasks[0],
title: '<script>alert("xss")</script>',
};
render(<TaskList tasks={[specialCharTask]} isLoading={false} />);
// Should render escaped, not execute
expect(screen.getByRole("main").innerHTML).not.toContain("<script>");
});
});
});

View File

@@ -0,0 +1,70 @@
import type { Task } from "@mosaic/shared";
import { TaskItem } from "./TaskItem";
import { getDateGroupLabel } from "@/lib/utils/date-format";
interface TaskListProps {
tasks: Task[];
isLoading: boolean;
}
export function TaskList({ tasks, isLoading }: TaskListProps) {
if (isLoading) {
return (
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
<span className="ml-3 text-gray-600">Loading tasks...</span>
</div>
);
}
// Handle null/undefined tasks gracefully
if (!tasks || tasks.length === 0) {
return (
<div className="text-center p-8 text-gray-500">
<p className="text-lg">No tasks scheduled</p>
<p className="text-sm mt-2">Your task list is clear</p>
</div>
);
}
// Group tasks by date
const groupedTasks = tasks.reduce((groups, task) => {
if (!task.dueDate) {
return groups;
}
const label = getDateGroupLabel(task.dueDate);
if (!groups[label]) {
groups[label] = [];
}
groups[label].push(task);
return groups;
}, {} as Record<string, Task[]>);
const groupOrder = ["Today", "Tomorrow", "This Week", "Next Week", "Later"];
return (
<main className="space-y-6">
{groupOrder.map((groupLabel) => {
const groupTasks = groupedTasks[groupLabel];
if (!groupTasks || groupTasks.length === 0) {
return null;
}
return (
<section key={groupLabel}>
<h2 className="text-lg font-semibold text-gray-700 mb-3">
{groupLabel}
</h2>
<ul className="space-y-2">
{groupTasks.map((task) => (
<li key={task.id}>
<TaskItem task={task} />
</li>
))}
</ul>
</section>
);
})}
</main>
);
}

View File

@@ -0,0 +1,340 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { apiRequest, apiGet, apiPost, apiPatch, apiDelete } from "./client";
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("API Client", () => {
beforeEach(() => {
mockFetch.mockClear();
});
afterEach(() => {
vi.resetAllMocks();
});
describe("apiRequest", () => {
it("should make a successful GET request", async () => {
const mockData = { id: "1", name: "Test" };
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockData,
});
const result = await apiRequest<typeof mockData>("/test");
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test",
expect.objectContaining({
headers: expect.objectContaining({
"Content-Type": "application/json",
}),
credentials: "include",
})
);
expect(result).toEqual(mockData);
});
it("should include custom headers", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
await apiRequest("/test", {
headers: { Authorization: "Bearer token123" },
});
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test",
expect.objectContaining({
headers: expect.objectContaining({
"Content-Type": "application/json",
Authorization: "Bearer token123",
}),
})
);
});
it("should throw error on failed request", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Not Found",
json: async () => ({
code: "NOT_FOUND",
message: "Resource not found",
}),
});
await expect(apiRequest("/test")).rejects.toThrow("Resource not found");
});
it("should handle errors when JSON parsing fails", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Internal Server Error",
json: async () => {
throw new Error("Invalid JSON");
},
});
await expect(apiRequest("/test")).rejects.toThrow(
"Internal Server Error"
);
});
});
describe("apiGet", () => {
it("should make a GET request", async () => {
const mockData = { id: "1" };
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockData,
});
const result = await apiGet<typeof mockData>("/test");
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test",
expect.objectContaining({ method: "GET" })
);
expect(result).toEqual(mockData);
});
});
describe("apiPost", () => {
it("should make a POST request with data", async () => {
const postData = { name: "New Item" };
const mockResponse = { id: "1", ...postData };
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse,
});
const result = await apiPost<typeof mockResponse>("/test", postData);
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test",
expect.objectContaining({
method: "POST",
body: JSON.stringify(postData),
})
);
expect(result).toEqual(mockResponse);
});
it("should make a POST request without data", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
await apiPost("/test");
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test",
expect.objectContaining({
method: "POST",
// When no data is provided, body property is not set (not undefined)
})
);
// Verify body is not in the call
const callArgs = mockFetch.mock.calls[0][1] as RequestInit;
expect(callArgs.body).toBeUndefined();
});
});
describe("apiPatch", () => {
it("should make a PATCH request with data", async () => {
const patchData = { name: "Updated" };
const mockResponse = { id: "1", ...patchData };
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse,
});
const result = await apiPatch<typeof mockResponse>("/test/1", patchData);
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test/1",
expect.objectContaining({
method: "PATCH",
body: JSON.stringify(patchData),
})
);
expect(result).toEqual(mockResponse);
});
});
describe("apiDelete", () => {
it("should make a DELETE request", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ success: true }),
});
const result = await apiDelete<{ success: boolean }>("/test/1");
expect(mockFetch).toHaveBeenCalledWith(
"http://localhost:3001/test/1",
expect.objectContaining({ method: "DELETE" })
);
expect(result).toEqual({ success: true });
});
});
describe("error handling", () => {
it("should handle network errors", async () => {
mockFetch.mockRejectedValueOnce(new Error("Network request failed"));
await expect(apiGet("/test")).rejects.toThrow("Network request failed");
});
it("should handle 401 unauthorized errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Unauthorized",
status: 401,
json: async () => ({
code: "UNAUTHORIZED",
message: "Authentication required",
}),
});
await expect(apiGet("/test")).rejects.toThrow("Authentication required");
});
it("should handle 403 forbidden errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Forbidden",
status: 403,
json: async () => ({
code: "FORBIDDEN",
message: "Access denied",
}),
});
await expect(apiGet("/test")).rejects.toThrow("Access denied");
});
it("should handle 404 not found errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Not Found",
status: 404,
json: async () => ({
code: "NOT_FOUND",
message: "Resource not found",
}),
});
await expect(apiGet("/test")).rejects.toThrow("Resource not found");
});
it("should handle 500 server errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Internal Server Error",
status: 500,
json: async () => ({
code: "INTERNAL_ERROR",
message: "Internal server error",
}),
});
await expect(apiGet("/test")).rejects.toThrow("Internal server error");
});
it("should handle malformed JSON responses", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => {
throw new Error("Unexpected token in JSON");
},
});
await expect(apiGet("/test")).rejects.toThrow("Unexpected token in JSON");
});
it("should handle empty error responses", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Bad Request",
status: 400,
json: async () => {
throw new Error("No JSON body");
},
});
await expect(apiGet("/test")).rejects.toThrow("Bad Request");
});
it("should handle timeout errors", async () => {
mockFetch.mockImplementationOnce(() => {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error("Request timeout")), 1);
});
});
await expect(apiGet("/test")).rejects.toThrow("Request timeout");
});
it("should handle malformed error responses with details", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Validation Error",
status: 422,
json: async () => ({
code: "VALIDATION_ERROR",
message: "Invalid input",
details: {
fields: {
email: "Invalid email format",
password: "Password too short",
},
},
}),
});
await expect(apiGet("/test")).rejects.toThrow("Invalid input");
});
it("should handle CORS errors", async () => {
mockFetch.mockRejectedValueOnce(
new TypeError("Failed to fetch")
);
await expect(apiGet("/test")).rejects.toThrow("Failed to fetch");
});
it("should handle rate limit errors", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
statusText: "Too Many Requests",
status: 429,
json: async () => ({
code: "RATE_LIMIT_EXCEEDED",
message: "Too many requests. Please try again later.",
}),
});
await expect(apiGet("/test")).rejects.toThrow(
"Too many requests. Please try again later."
);
});
it("should handle connection refused errors", async () => {
mockFetch.mockRejectedValueOnce({
name: "FetchError",
message: "request to http://localhost:3001/test failed, reason: connect ECONNREFUSED",
});
await expect(apiGet("/test")).rejects.toMatchObject({
message: expect.stringContaining("ECONNREFUSED"),
});
});
});
});

View File

@@ -0,0 +1,90 @@
/**
* API Client for Mosaic Stack
* Handles authenticated requests to the backend API
*/
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
export interface ApiError {
code: string;
message: string;
details?: unknown;
}
export interface ApiResponse<T> {
data: T;
meta?: {
total?: number;
page?: number;
limit?: number;
};
}
/**
* Make an authenticated API request
*/
export async function apiRequest<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = `${API_BASE_URL}${endpoint}`;
const response = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
credentials: "include", // Include cookies for session
});
if (!response.ok) {
const error: ApiError = await response.json().catch(() => ({
code: "UNKNOWN_ERROR",
message: response.statusText || "An unknown error occurred",
}));
throw new Error(error.message);
}
return response.json();
}
/**
* GET request helper
*/
export async function apiGet<T>(endpoint: string): Promise<T> {
return apiRequest<T>(endpoint, { method: "GET" });
}
/**
* POST request helper
*/
export async function apiPost<T>(endpoint: string, data?: unknown): Promise<T> {
const options: RequestInit = {
method: "POST",
};
if (data !== undefined) {
options.body = JSON.stringify(data);
}
return apiRequest<T>(endpoint, options);
}
/**
* PATCH request helper
*/
export async function apiPatch<T>(endpoint: string, data: unknown): Promise<T> {
return apiRequest<T>(endpoint, {
method: "PATCH",
body: JSON.stringify(data),
});
}
/**
* DELETE request helper
*/
export async function apiDelete<T>(endpoint: string): Promise<T> {
return apiRequest<T>(endpoint, { method: "DELETE" });
}

View File

@@ -0,0 +1,90 @@
/**
* Event API Client
* Handles event-related API requests
*/
import type { Event } from "@mosaic/shared";
import { apiGet, type ApiResponse } from "./client";
export interface EventFilters {
startDate?: Date;
endDate?: Date;
workspaceId?: string;
}
/**
* Fetch events with optional filters
*/
export async function fetchEvents(filters?: EventFilters): Promise<Event[]> {
const params = new URLSearchParams();
if (filters?.startDate) {
params.append("startDate", filters.startDate.toISOString());
}
if (filters?.endDate) {
params.append("endDate", filters.endDate.toISOString());
}
if (filters?.workspaceId) {
params.append("workspaceId", filters.workspaceId);
}
const queryString = params.toString();
const endpoint = queryString ? `/api/events?${queryString}` : "/api/events";
const response = await apiGet<ApiResponse<Event[]>>(endpoint);
return response.data;
}
/**
* Mock events for development (until backend endpoints are ready)
*/
export const mockEvents: Event[] = [
{
id: "event-1",
title: "Team standup",
description: "Daily sync meeting",
startTime: new Date("2026-01-29T10:00:00"),
endTime: new Date("2026-01-29T10:30:00"),
allDay: false,
location: "Zoom",
recurrence: null,
creatorId: "user-1",
workspaceId: "workspace-1",
projectId: null,
metadata: {},
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "event-2",
title: "Project review",
description: "Quarterly project review session",
startTime: new Date("2026-01-30T14:00:00"),
endTime: new Date("2026-01-30T15:30:00"),
allDay: false,
location: "Conference Room A",
recurrence: null,
creatorId: "user-1",
workspaceId: "workspace-1",
projectId: null,
metadata: {},
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "event-3",
title: "Focus time",
description: "Dedicated time for deep work",
startTime: new Date("2026-01-31T09:00:00"),
endTime: new Date("2026-01-31T12:00:00"),
allDay: false,
location: null,
recurrence: null,
creatorId: "user-1",
workspaceId: "workspace-1",
projectId: null,
metadata: {},
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
];

View File

@@ -0,0 +1,167 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fetchTasks } from "./tasks";
import type { Task } from "@mosaic/shared";
// Mock the API client
vi.mock("./client", () => ({
apiGet: vi.fn(),
}));
const { apiGet } = await import("./client");
describe("Task API Client", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should fetch tasks successfully", async () => {
const mockTasks: Task[] = [
{
id: "task-1",
title: "Complete project setup",
description: "Set up the development environment",
status: "active",
priority: "high",
dueDate: new Date("2026-02-01"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 0,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "task-2",
title: "Review documentation",
description: "Review and update project docs",
status: "upcoming",
priority: "medium",
dueDate: new Date("2026-02-05"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 1,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
];
vi.mocked(apiGet).mockResolvedValueOnce({ data: mockTasks });
const result = await fetchTasks();
expect(apiGet).toHaveBeenCalledWith("/api/tasks");
expect(result).toEqual(mockTasks);
});
it("should handle errors when fetching tasks", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(new Error("Network error"));
await expect(fetchTasks()).rejects.toThrow("Network error");
});
it("should fetch tasks with filters", async () => {
const mockTasks: Task[] = [];
vi.mocked(apiGet).mockResolvedValueOnce({ data: mockTasks });
await fetchTasks({ status: "active" });
expect(apiGet).toHaveBeenCalledWith("/api/tasks?status=active");
});
it("should fetch tasks with multiple filters", async () => {
const mockTasks: Task[] = [];
vi.mocked(apiGet).mockResolvedValueOnce({ data: mockTasks });
await fetchTasks({ status: "active", priority: "high" });
expect(apiGet).toHaveBeenCalledWith(
"/api/tasks?status=active&priority=high"
);
});
describe("error handling", () => {
it("should handle network errors when fetching tasks", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(
new Error("Network request failed")
);
await expect(fetchTasks()).rejects.toThrow("Network request failed");
});
it("should handle API returning malformed data", async () => {
vi.mocked(apiGet).mockResolvedValueOnce({
data: null,
});
const result = await fetchTasks();
expect(result).toBeNull();
});
it("should handle auth token expiration (401 error)", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(
new Error("Authentication required")
);
await expect(fetchTasks()).rejects.toThrow("Authentication required");
});
it("should handle server 500 errors", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(
new Error("Internal server error")
);
await expect(fetchTasks()).rejects.toThrow("Internal server error");
});
it("should handle forbidden access (403 error)", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(new Error("Access denied"));
await expect(fetchTasks()).rejects.toThrow("Access denied");
});
it("should handle rate limiting errors", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(
new Error("Too many requests. Please try again later.")
);
await expect(fetchTasks()).rejects.toThrow(
"Too many requests. Please try again later."
);
});
it("should ignore malformed filter parameters", async () => {
const mockTasks: Task[] = [];
vi.mocked(apiGet).mockResolvedValueOnce({ data: mockTasks });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await fetchTasks({ invalidFilter: "value" } as any);
// Function should ignore invalid filters and call without query params
expect(apiGet).toHaveBeenCalledWith("/api/tasks");
});
it("should handle empty response data", async () => {
vi.mocked(apiGet).mockResolvedValueOnce({});
const result = await fetchTasks();
expect(result).toBeUndefined();
});
it("should handle timeout errors", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(new Error("Request timeout"));
await expect(fetchTasks()).rejects.toThrow("Request timeout");
});
});
});

View File

@@ -0,0 +1,115 @@
/**
* Task API Client
* Handles task-related API requests
*/
import type { Task } from "@mosaic/shared";
import { TaskStatus, TaskPriority } from "@mosaic/shared";
import { apiGet, type ApiResponse } from "./client";
export interface TaskFilters {
status?: TaskStatus;
priority?: TaskPriority;
workspaceId?: string;
}
/**
* Fetch tasks with optional filters
*/
export async function fetchTasks(filters?: TaskFilters): Promise<Task[]> {
const params = new URLSearchParams();
if (filters?.status) {
params.append("status", filters.status);
}
if (filters?.priority) {
params.append("priority", filters.priority);
}
if (filters?.workspaceId) {
params.append("workspaceId", filters.workspaceId);
}
const queryString = params.toString();
const endpoint = queryString ? `/api/tasks?${queryString}` : "/api/tasks";
const response = await apiGet<ApiResponse<Task[]>>(endpoint);
return response.data;
}
/**
* Mock tasks for development (until backend endpoints are ready)
*/
export const mockTasks: Task[] = [
{
id: "task-1",
title: "Review pull request",
description: "Review and provide feedback on frontend PR",
status: TaskStatus.IN_PROGRESS,
priority: TaskPriority.HIGH,
dueDate: new Date("2026-01-29"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 0,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "task-2",
title: "Update documentation",
description: "Add setup instructions for new developers",
status: TaskStatus.IN_PROGRESS,
priority: TaskPriority.MEDIUM,
dueDate: new Date("2026-01-30"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 1,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "task-3",
title: "Plan Q1 roadmap",
description: "Define priorities for Q1 2026",
status: TaskStatus.NOT_STARTED,
priority: TaskPriority.HIGH,
dueDate: new Date("2026-02-03"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 2,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
{
id: "task-4",
title: "Research new libraries",
description: "Evaluate options for state management",
status: TaskStatus.PAUSED,
priority: TaskPriority.LOW,
dueDate: new Date("2026-02-10"),
creatorId: "user-1",
assigneeId: "user-1",
workspaceId: "workspace-1",
projectId: null,
parentId: null,
sortOrder: 3,
metadata: {},
completedAt: null,
createdAt: new Date("2026-01-28"),
updatedAt: new Date("2026-01-28"),
},
];

View File

@@ -0,0 +1,157 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { AuthProvider, useAuth } from "./auth-context";
import type { AuthUser } from "@mosaic/shared";
// Mock the API client
vi.mock("../api/client", () => ({
apiGet: vi.fn(),
apiPost: vi.fn(),
}));
const { apiGet, apiPost } = await import("../api/client");
// Test component that uses the auth context
function TestComponent() {
const { user, isLoading, isAuthenticated, signOut } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
<div data-testid="auth-status">
{isAuthenticated ? "Authenticated" : "Not Authenticated"}
</div>
{user && (
<div>
<div data-testid="user-email">{user.email}</div>
<div data-testid="user-name">{user.name}</div>
</div>
)}
<button onClick={signOut}>Sign Out</button>
</div>
);
}
describe("AuthContext", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should provide loading state initially", () => {
vi.mocked(apiGet).mockImplementation(
() => new Promise(() => {}) // Never resolves
);
render(
<AuthProvider>
<TestComponent />
</AuthProvider>
);
expect(screen.getByText("Loading...")).toBeInTheDocument();
});
it("should provide authenticated user when session exists", async () => {
const mockUser: AuthUser = {
id: "user-1",
email: "test@example.com",
name: "Test User",
};
vi.mocked(apiGet).mockResolvedValueOnce({
user: mockUser,
session: { id: "session-1", token: "token123", expiresAt: new Date() },
});
render(
<AuthProvider>
<TestComponent />
</AuthProvider>
);
await waitFor(() => {
expect(screen.getByTestId("auth-status")).toHaveTextContent(
"Authenticated"
);
});
expect(screen.getByTestId("user-email")).toHaveTextContent(
"test@example.com"
);
expect(screen.getByTestId("user-name")).toHaveTextContent("Test User");
});
it("should handle unauthenticated state when session check fails", async () => {
vi.mocked(apiGet).mockRejectedValueOnce(new Error("Unauthorized"));
render(
<AuthProvider>
<TestComponent />
</AuthProvider>
);
await waitFor(() => {
expect(screen.getByTestId("auth-status")).toHaveTextContent(
"Not Authenticated"
);
});
expect(screen.queryByTestId("user-email")).not.toBeInTheDocument();
});
it("should clear user on sign out", async () => {
const mockUser: AuthUser = {
id: "user-1",
email: "test@example.com",
name: "Test User",
};
vi.mocked(apiGet).mockResolvedValueOnce({
user: mockUser,
session: { id: "session-1", token: "token123", expiresAt: new Date() },
});
vi.mocked(apiPost).mockResolvedValueOnce({ success: true });
render(
<AuthProvider>
<TestComponent />
</AuthProvider>
);
// Wait for authenticated state
await waitFor(() => {
expect(screen.getByTestId("auth-status")).toHaveTextContent(
"Authenticated"
);
});
// Click sign out
const signOutButton = screen.getByRole("button", { name: "Sign Out" });
signOutButton.click();
await waitFor(() => {
expect(screen.getByTestId("auth-status")).toHaveTextContent(
"Not Authenticated"
);
});
expect(apiPost).toHaveBeenCalledWith("/auth/sign-out");
});
it("should throw error when useAuth is used outside AuthProvider", () => {
// Suppress console.error for this test
const consoleErrorSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useAuth must be used within AuthProvider");
consoleErrorSpy.mockRestore();
});
});

View File

@@ -0,0 +1,74 @@
"use client";
import {
createContext,
useContext,
useState,
useEffect,
useCallback,
type ReactNode,
} from "react";
import type { AuthUser, AuthSession } from "@mosaic/shared";
import { apiGet, apiPost } from "../api/client";
interface AuthContextValue {
user: AuthUser | null;
isLoading: boolean;
isAuthenticated: boolean;
signOut: () => Promise<void>;
refreshSession: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null);
const [isLoading, setIsLoading] = useState(true);
const checkSession = useCallback(async () => {
try {
const session = await apiGet<AuthSession>("/auth/session");
setUser(session.user);
} catch (error) {
setUser(null);
} finally {
setIsLoading(false);
}
}, []);
const signOut = useCallback(async () => {
try {
await apiPost("/auth/sign-out");
} catch (error) {
console.error("Sign out error:", error);
} finally {
setUser(null);
}
}, []);
const refreshSession = useCallback(async () => {
await checkSession();
}, [checkSession]);
useEffect(() => {
checkSession();
}, [checkSession]);
const value: AuthContextValue = {
user,
isLoading,
isAuthenticated: user !== null,
signOut,
refreshSession,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within AuthProvider");
}
return context;
}

View File

@@ -0,0 +1,111 @@
import { describe, it, expect } from "vitest";
import {
formatDate,
formatTime,
getDateGroupLabel,
isPastTarget,
isApproachingTarget,
} from "./date-format";
describe("date-format utils", () => {
describe("formatDate", () => {
it("should format date in readable format", () => {
// Use explicit time to avoid timezone issues
const date = new Date("2026-01-29T12:00:00");
const result = formatDate(date);
expect(result).toMatch(/Jan/);
expect(result).toMatch(/2026/);
// Note: Day might be 28 or 29 depending on timezone
expect(result).toMatch(/\d{1,2}/);
});
it("should handle invalid dates", () => {
const result = formatDate(new Date("invalid"));
expect(result).toBe("Invalid Date");
});
});
describe("formatTime", () => {
it("should format time in 12-hour format", () => {
const date = new Date("2026-01-29T14:30:00");
const result = formatTime(date);
expect(result).toMatch(/\d{1,2}:\d{2} [AP]M/i);
});
it("should handle invalid time", () => {
const result = formatTime(new Date("invalid"));
expect(result).toBe("Invalid Time");
});
});
describe("getDateGroupLabel", () => {
const today = new Date("2026-01-28T12:00:00");
it("should return 'Today' for today's date", () => {
const date = new Date("2026-01-28T14:00:00");
const result = getDateGroupLabel(date, today);
expect(result).toBe("Today");
});
it("should return 'Tomorrow' for tomorrow's date", () => {
const date = new Date("2026-01-29T10:00:00");
const result = getDateGroupLabel(date, today);
expect(result).toBe("Tomorrow");
});
it("should return 'This Week' for dates within 7 days", () => {
const date = new Date("2026-02-02T10:00:00");
const result = getDateGroupLabel(date, today);
expect(result).toBe("This Week");
});
it("should return 'Next Week' for dates 7-14 days out", () => {
const date = new Date("2026-02-08T10:00:00");
const result = getDateGroupLabel(date, today);
expect(result).toBe("Next Week");
});
it("should return 'Later' for dates beyond 2 weeks", () => {
const date = new Date("2026-03-15T10:00:00");
const result = getDateGroupLabel(date, today);
expect(result).toBe("Later");
});
});
describe("isPastTarget", () => {
const now = new Date("2026-01-28T12:00:00");
it("should return true for past dates", () => {
const pastDate = new Date("2026-01-27T10:00:00");
expect(isPastTarget(pastDate, now)).toBe(true);
});
it("should return false for future dates", () => {
const futureDate = new Date("2026-01-29T10:00:00");
expect(isPastTarget(futureDate, now)).toBe(false);
});
it("should return false for current time", () => {
expect(isPastTarget(now, now)).toBe(false);
});
});
describe("isApproachingTarget", () => {
const now = new Date("2026-01-28T12:00:00");
it("should return true for dates within 24 hours", () => {
const soonDate = new Date("2026-01-29T10:00:00");
expect(isApproachingTarget(soonDate, now)).toBe(true);
});
it("should return false for dates beyond 24 hours", () => {
const laterDate = new Date("2026-01-30T14:00:00");
expect(isApproachingTarget(laterDate, now)).toBe(false);
});
it("should return false for past dates", () => {
const pastDate = new Date("2026-01-27T10:00:00");
expect(isApproachingTarget(pastDate, now)).toBe(false);
});
});
});

View File

@@ -0,0 +1,69 @@
/**
* Date formatting utilities
* Provides PDA-friendly date formatting and grouping
*/
import { format, isToday, isTomorrow, differenceInDays, isBefore } from "date-fns";
/**
* Format a date in a readable format
*/
export function formatDate(date: Date): string {
try {
return format(date, "MMM d, yyyy");
} catch (error) {
return "Invalid Date";
}
}
/**
* Format time in 12-hour format
*/
export function formatTime(date: Date): string {
try {
return format(date, "h:mm a");
} catch (error) {
return "Invalid Time";
}
}
/**
* Get a PDA-friendly label for date grouping
* Returns: "Today", "Tomorrow", "This Week", "Next Week", "Later"
*/
export function getDateGroupLabel(date: Date, referenceDate: Date = new Date()): string {
if (isToday(date)) {
return "Today";
}
if (isTomorrow(date)) {
return "Tomorrow";
}
const daysUntil = differenceInDays(date, referenceDate);
if (daysUntil >= 0 && daysUntil <= 7) {
return "This Week";
}
if (daysUntil > 7 && daysUntil <= 14) {
return "Next Week";
}
return "Later";
}
/**
* Check if a date has passed (PDA-friendly: "target passed" instead of "overdue")
*/
export function isPastTarget(targetDate: Date, now: Date = new Date()): boolean {
return isBefore(targetDate, now);
}
/**
* Check if a date is approaching (within 24 hours)
*/
export function isApproachingTarget(targetDate: Date, now: Date = new Date()): boolean {
const hoursUntil = differenceInDays(targetDate, now);
return hoursUntil >= 0 && hoursUntil <= 1;
}