diff --git a/AGENTS.md b/AGENTS.md index 59275697..3dda0bd2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,8 +85,8 @@ Run checks before delivery; `package.json` defines no validation scripts, so ## Architecture - `apps/web/src` is the React 19 SPA: react-router 7, Tailwind CSS 4, - assistant-ui for chat, Mapbox GL for the dorm map, and supabase-js for auth - and user data. + shadcn/ui and AI Elements for chat, Mapbox GL for the dorm map, and + supabase-js for auth and user data. - `apps/web/worker` is the Cloudflare Worker named `uiuc`. It routes `/api/*` and serves the SPA's static assets for every other path, so the app and the whole API share one origin. It also hosts the streaming tool-use agent diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index f1726180..ed947da3 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -121,6 +121,8 @@ Feature SQL, after the core schema: `add_floor_plan_bed_size.sql`; `add_soul_and_memory.sql` (all in `scripts/migrations/`). - `scripts/create_dorm_user_features.sql`: dorm favorites and viewing history. +- `scripts/migrations/add_message_sources.sql`: `messages.sources`, the web + pages each chat reply cited. Until it runs, replies are saved without them. The tracked SQL does not create every table the app uses. Create `conversations` (referenced by `add_soul_and_memory.sql`), `messages`, `reading_history`, @@ -155,26 +157,32 @@ service-role key that bypasses RLS. The seed upserts the bundled `UIUC_DORMS` in tags with stored ones, and never deletes rows. It does not read the archived `dorm_overrides`. -## assistant-ui +## shadcn/ui and AI Elements -This project uses assistant-ui for chat interfaces. +UI primitives come from [shadcn/ui](https://ui.shadcn.com) and chat building +blocks from [AI Elements](https://ai-sdk.dev/elements), both copied into the +repo by the shadcn CLI (`components.json`): -Documentation: https://www.assistant-ui.com/llms-full.txt - -Key patterns: - -- Use AssistantRuntimeProvider at the app root -- Thread component for full chat interface -- AssistantModal for floating chat widget -- useChatRuntime hook with AI SDK transport +- `src/components/ui/` holds shadcn primitives next to the app's own generic + UI. `src/components/ai-elements/` holds AI Elements components. +- Add components with `npx shadcn@latest add ` or + `npx shadcn@latest add @ai-elements/` from `apps/web`. The CLI may + write `import { cn } from "cn"`; the helper lives at `@/utils/cn`. +- Copied files are ours to edit; mark local changes with a comment so a later + `add --overwrite` does not silently drop them. +- Theme tokens (`--background`, `--primary`, ...) are defined in + `src/index.css` and mapped onto the slate + Illini palette. The app is + light-only; `dark:` utilities only apply under a `.dark` ancestor. ## Chat Components ### General Chat (`src/components/chat/**` + `src/pages/chat/ChatPage.tsx`) -- Full-page general-purpose chat interface -- Uses assistant-ui runtime (ChatRuntimeProvider, ChatThread) -- Supports tool-use (SearchToolUI, WebSearchToolUI, GrepDocsToolUI) +- Full-page general-purpose chat interface (`ChatThread`), state in + `useChatSession`, scrolling in `useTopAnchoredScroll` +- Replies show the agent's thinking steps until the answer starts, then the + web pages it read (`source-url` SSE events) as a sources pill and numbered + citations - Conversation management with persistent IDs - Route: `/chat` diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 00000000..77142c57 --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "ui": "@/components/ui", + "utils": "@/utils/cn", + "lib": "@/utils", + "hooks": "@/hooks" + }, + "registries": { + "@ai-elements": "https://ai-sdk.dev/elements/api/registry/{name}.json" + } +} diff --git a/apps/web/doctor.config.jsonc b/apps/web/doctor.config.jsonc new file mode 100644 index 00000000..d9369d2b --- /dev/null +++ b/apps/web/doctor.config.jsonc @@ -0,0 +1,26 @@ +{ + "$schema": "https://react.doctor/schema/config.json", + "ignore": { + // Files the shadcn CLI copied in (see AGENTS.md). They keep upstream's + // patterns so a later `shadcn add --overwrite` stays a drop-in update; + // real bugs in them are fixed in place and marked "Local change". + "overrides": [ + { + // badgeVariants / buttonVariants are shadcn's shared API: other shadcn + // components import them from these files. + "files": ["src/components/ui/badge.tsx", "src/components/ui/button.tsx"], + "rules": ["react-doctor/only-export-components"], + }, + { + // `setApi` is Embla's documented way to hand the carousel API to a + // parent; AI Elements' InlineCitationCarousel relies on it. + "files": ["src/components/ui/carousel.tsx"], + "rules": [ + "react-doctor/no-pass-data-to-parent", + "react-doctor/no-pass-live-state-to-parent", + "react-doctor/no-prop-callback-in-effect", + ], + }, + ], + }, +} diff --git a/apps/web/package.json b/apps/web/package.json index 19c36158..04ae543d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,20 +7,24 @@ "dev": "vp dev" }, "dependencies": { - "@assistant-ui/react": "^0.15.22", - "@assistant-ui/react-markdown": "0.14.17", "@headlessui/react": "^2.2.10", "@supabase/supabase-js": "^2.117.2", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "embla-carousel-react": "^8.6.0", "framer-motion": "^13.4.4", "lucide-react": "^1.48.0", "mapbox-gl": "^3.31.0", + "radix-ui": "^1.6.7", "rc-slider": "^11.1.9", "react": "^19.3.0", "react-dom": "^19.3.0", "react-map-gl": "^8.1.3", "react-markdown": "^10.1.0", "react-router-dom": "^7.18.4", - "remark-gfm": "^4.0.1" + "remark-gfm": "^4.0.1", + "tailwind-merge": "^3.7.0", + "tw-animate-css": "^1.4.0" }, "devDependencies": { "@cloudflare/vite-plugin": "^2.0.0-beta.sha-238e489d5", diff --git a/apps/web/scripts/migrations/add_message_sources.sql b/apps/web/scripts/migrations/add_message_sources.sql new file mode 100644 index 00000000..1b7f1551 --- /dev/null +++ b/apps/web/scripts/migrations/add_message_sources.sql @@ -0,0 +1,11 @@ +-- Migration: Add sources to chat messages +-- Purpose: Keep the web pages an assistant reply was based on, so the +-- "N sources" button and numbered citations survive reloading a conversation. +-- Shape: [{ "id": text, "url": text, "title": text, "snippet"?: text }] +-- Until this runs, the app saves messages without their sources. + +ALTER TABLE public.messages + ADD COLUMN IF NOT EXISTS sources JSONB; + +-- Reload PostgREST's schema cache so the new column is accepted right away. +NOTIFY pgrst, 'reload schema'; diff --git a/apps/web/src/components/ai-elements/inline-citation.tsx b/apps/web/src/components/ai-elements/inline-citation.tsx new file mode 100644 index 00000000..9025d7d2 --- /dev/null +++ b/apps/web/src/components/ai-elements/inline-citation.tsx @@ -0,0 +1,254 @@ +"use client" + +import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react" +import type { ComponentProps } from "react" +import { createContext, useCallback, useContext, useEffect, useState } from "react" + +import { Badge } from "@/components/ui/badge" +import type { CarouselApi } from "@/components/ui/carousel" +import { Carousel, CarouselContent, CarouselItem } from "@/components/ui/carousel" +import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card" +import { cn } from "@/utils/cn" + +export type InlineCitationProps = ComponentProps<"span"> + +export const InlineCitation = ({ className, ...props }: InlineCitationProps) => ( + +) + +export type InlineCitationTextProps = ComponentProps<"span"> + +export const InlineCitationText = ({ className, ...props }: InlineCitationTextProps) => ( + +) + +export type InlineCitationCardProps = ComponentProps + +export const InlineCitationCard = (props: InlineCitationCardProps) => ( + +) + +export type InlineCitationCardTriggerProps = ComponentProps & { + sources: string[] +} + +export const InlineCitationCardTrigger = ({ + sources, + className, + children, + ...props +}: InlineCitationCardTriggerProps) => ( + + + {/* Local change: callers may pass their own label (IlliniGuide shows the source number). */} + {children ?? + (sources[0] ? ( + <> + {new URL(sources[0]).hostname} {sources.length > 1 && `+${sources.length - 1}`} + + ) : ( + "unknown" + ))} + + +) + +export type InlineCitationCardBodyProps = ComponentProps<"div"> + +export const InlineCitationCardBody = ({ className, ...props }: InlineCitationCardBodyProps) => ( + +) + +const CarouselApiContext = createContext(undefined) + +const useCarouselApi = () => { + const context = useContext(CarouselApiContext) + return context +} + +export type InlineCitationCarouselProps = ComponentProps + +export const InlineCitationCarousel = ({ + className, + children, + ...props +}: InlineCitationCarouselProps) => { + const [api, setApi] = useState() + + return ( + + + {children} + + + ) +} + +export type InlineCitationCarouselContentProps = ComponentProps<"div"> + +export const InlineCitationCarouselContent = (props: InlineCitationCarouselContentProps) => ( + +) + +export type InlineCitationCarouselItemProps = ComponentProps<"div"> + +export const InlineCitationCarouselItem = ({ + className, + ...props +}: InlineCitationCarouselItemProps) => ( + +) + +export type InlineCitationCarouselHeaderProps = ComponentProps<"div"> + +export const InlineCitationCarouselHeader = ({ + className, + ...props +}: InlineCitationCarouselHeaderProps) => ( +
+) + +export type InlineCitationCarouselIndexProps = ComponentProps<"div"> + +export const InlineCitationCarouselIndex = ({ + children, + className, + ...props +}: InlineCitationCarouselIndexProps) => { + const api = useCarouselApi() + const [current, setCurrent] = useState(0) + const [count, setCount] = useState(0) + + const syncState = useCallback(() => { + if (!api) { + return + } + setCount(api.scrollSnapList().length) + setCurrent(api.selectedScrollSnap() + 1) + }, [api]) + + useEffect(() => { + if (!api) { + return + } + + syncState() + + api.on("select", syncState) + + return () => { + api.off("select", syncState) + } + }, [api, syncState]) + + return ( +
+ {children ?? `${current}/${count}`} +
+ ) +} + +export type InlineCitationCarouselPrevProps = ComponentProps<"button"> + +export const InlineCitationCarouselPrev = ({ + className, + ...props +}: InlineCitationCarouselPrevProps) => { + const api = useCarouselApi() + + const handleClick = useCallback(() => { + if (api) { + api.scrollPrev() + } + }, [api]) + + return ( + + ) +} + +export type InlineCitationCarouselNextProps = ComponentProps<"button"> + +export const InlineCitationCarouselNext = ({ + className, + ...props +}: InlineCitationCarouselNextProps) => { + const api = useCarouselApi() + + const handleClick = useCallback(() => { + if (api) { + api.scrollNext() + } + }, [api]) + + return ( + + ) +} + +export type InlineCitationSourceProps = ComponentProps<"div"> & { + title?: string + url?: string + description?: string +} + +export const InlineCitationSource = ({ + title, + url, + description, + className, + children, + ...props +}: InlineCitationSourceProps) => ( +
+ {title &&

{title}

} + {url &&

{url}

} + {description && ( +

{description}

+ )} + {children} +
+) + +export type InlineCitationQuoteProps = ComponentProps<"blockquote"> + +export const InlineCitationQuote = ({ + children, + className, + ...props +}: InlineCitationQuoteProps) => ( +
+ {children} +
+) diff --git a/apps/web/src/components/ai-elements/sources.tsx b/apps/web/src/components/ai-elements/sources.tsx new file mode 100644 index 00000000..4501ab5e --- /dev/null +++ b/apps/web/src/components/ai-elements/sources.tsx @@ -0,0 +1,54 @@ +"use client" + +import { BookIcon, ChevronDownIcon } from "lucide-react" +import type { ComponentProps } from "react" + +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" +import { cn } from "@/utils/cn" + +export type SourcesProps = ComponentProps<"div"> + +export const Sources = ({ className, ...props }: SourcesProps) => ( + +) + +export type SourcesTriggerProps = ComponentProps & { + count: number +} + +export const SourcesTrigger = ({ className, count, children, ...props }: SourcesTriggerProps) => ( + + {children ?? ( + <> +

Used {count} sources

+ + + )} +
+) + +export type SourcesContentProps = ComponentProps + +export const SourcesContent = ({ className, ...props }: SourcesContentProps) => ( + +) + +export type SourceProps = ComponentProps<"a"> + +export const Source = ({ href, title, children, ...props }: SourceProps) => ( + + {children ?? ( + <> + + {title} + + )} + +) diff --git a/apps/web/src/components/ai-elements/suggestion.tsx b/apps/web/src/components/ai-elements/suggestion.tsx new file mode 100644 index 00000000..cdc529ee --- /dev/null +++ b/apps/web/src/components/ai-elements/suggestion.tsx @@ -0,0 +1,49 @@ +"use client" + +import type { ComponentProps } from "react" +import { useCallback } from "react" + +import { Button } from "@/components/ui/button" +import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area" +import { cn } from "@/utils/cn" + +export type SuggestionsProps = ComponentProps + +export const Suggestions = ({ className, children, ...props }: SuggestionsProps) => ( + +
{children}
+ +
+) + +export type SuggestionProps = Omit, "onClick"> & { + suggestion: string + onClick?: (suggestion: string) => void +} + +export const Suggestion = ({ + suggestion, + onClick, + className, + variant = "outline", + size = "sm", + children, + ...props +}: SuggestionProps) => { + const handleClick = useCallback(() => { + onClick?.(suggestion) + }, [onClick, suggestion]) + + return ( + + ) +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b2fed600..c8e9fe6e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,103 +1,82 @@ -import { AuiIf, ComposerPrimitive } from "@assistant-ui/react" import { ArrowUp, Loader2 } from "lucide-react" import * as React from "react" +import { Button } from "@/components/ui/button" + interface ChatComposerProps { placeholder: string hint: string + /** A reply is streaming; sending is blocked until it finishes. */ + isRunning: boolean + onSend: (text: string) => void } -const toTextareaValue = (value: React.TextareaHTMLAttributes["value"]) => { - if (Array.isArray(value)) { - return value.join(",") - } - - return value?.toString() ?? "" -} - -const isNativeInputComposing = (event: React.ChangeEvent) => - event.nativeEvent instanceof InputEvent && event.nativeEvent.isComposing - -const ImeSafeComposerTextarea = React.forwardRef< - HTMLTextAreaElement, - React.TextareaHTMLAttributes ->(({ onChange, onCompositionEnd, onCompositionStart, value, ...props }, ref) => { - const isComposingRef = React.useRef(false) - const [compositionValue, setCompositionValue] = React.useState("") - const controlledValue = toTextareaValue(value) - - const handleCompositionStart = (event: React.CompositionEvent) => { - isComposingRef.current = true - setCompositionValue(event.currentTarget.value) - onCompositionStart?.(event) - } - - const handleChange = (event: React.ChangeEvent) => { - if (isComposingRef.current || isNativeInputComposing(event)) { - setCompositionValue(event.currentTarget.value) - } +/** + * Auto-growing input with a send button that turns into a spinner while a + * reply is running. Enter sends and Shift + Enter adds a line; an Enter that + * confirms an IME candidate (e.g. pinyin) is left to the IME. The textarea + * grows with its content via `field-sizing: content`, capped at ~8 lines. + */ +export const ChatComposer = ({ placeholder, hint, isRunning, onSend }: ChatComposerProps) => { + const [value, setValue] = React.useState("") + const canSend = !isRunning && value.trim().length > 0 - onChange?.(event) + const submit = () => { + if (!canSend) return + onSend(value) + setValue("") } - const handleCompositionEnd = (event: React.CompositionEvent) => { - isComposingRef.current = false - setCompositionValue(event.currentTarget.value) - onCompositionEnd?.(event) + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return + event.preventDefault() + submit() } return ( -