diff --git a/Architecture.md b/Architecture.md
index e25a67c2..0e764950 100644
--- a/Architecture.md
+++ b/Architecture.md
@@ -103,6 +103,7 @@ frontend/
│ ├── types/ # Auto-generated TypeScript types (gitignored) — do not edit manually, re-run `mise run //frontend:generate-frontend-assets` to regenerate (this splices the backend's `uv` onto the frontend's `PATH`)
│ │ └── models.ts # All exported types: ResponseChunk, Location, OregonCity, UsaState, chunk interfaces
│ ├── layouts/ # Layouts
+│ │ ├── ChatPageLayout.tsx # Shared layout for the Chat and Letter pages
│ │ └── PageLayout.tsx # Layout for pages
│ ├── pages/
│ │ ├── Chat/ # Chat page components
@@ -166,13 +167,14 @@ frontend/
│ │ ├── hooks/ # Hook testing
│ │ │ ├── useLetterContent.test.tsx # useLetterContent testing
│ │ │ └── useMessages.test.ts # useMessages testing
-│ │ └── utils/ # Utility function testing
-│ │ ├── exportHelper.test.ts # exportHelper testing
-│ │ ├── feedbackHelper.test.ts # feedbackHelper testing
-│ │ ├── letterHelper.test.ts # letterHelper testing
-│ │ ├── sanitizeText.test.ts # sanitizeText testing
-│ │ ├── streamHelper.test.ts # streamHelper testing
-│ │ └── formatLocation.test.ts # formatLocation testing
+│ │ ├── utils/ # Utility function testing
+│ │ │ ├── exportHelper.test.ts # exportHelper testing
+│ │ │ ├── feedbackHelper.test.ts # feedbackHelper testing
+│ │ │ ├── letterHelper.test.ts # letterHelper testing
+│ │ │ ├── sanitizeText.test.ts # sanitizeText testing
+│ │ │ ├── streamHelper.test.ts # streamHelper testing
+│ │ │ └── formatLocation.test.ts # formatLocation testing
+│ │ └── testUtils.tsx # Shared test helpers (provider render, fake stream readers)
├── public/
│ └── favicon.svg # Site favicon
├── package.json # Dependencies and scripts
diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js
index cb02440a..0fcf6c74 100644
--- a/frontend/eslint.config.js
+++ b/frontend/eslint.config.js
@@ -30,4 +30,9 @@ export default tseslint.config(
],
},
},
+ {
+ // Fast refresh never loads test files, so shared test helpers may mix exports.
+ files: ["src/tests/**"],
+ rules: { "react-refresh/only-export-components": "off" },
+ },
);
diff --git a/frontend/src/Chat.tsx b/frontend/src/Chat.tsx
index 7855a7c7..91ea67f9 100644
--- a/frontend/src/Chat.tsx
+++ b/frontend/src/Chat.tsx
@@ -3,14 +3,10 @@ import useMessages from "./hooks/useMessages";
import useSyncJurisdiction from "./hooks/useSyncJurisdiction";
import { useLetterContent } from "./hooks/useLetterContent";
import ChatDisclaimer from "./pages/Chat/components/ChatDisclaimer";
-import FrequentInquiries from "./shared/components/FrequentInquiries";
-import MessageContainer from "./shared/components/MessageContainer";
-import FeaturesPanel from "./shared/components/FeaturesPanel";
-import MobilePanel from "./shared/components/MobilePanel";
+import ChatPageLayout from "./layouts/ChatPageLayout";
import { Navigate, useParams } from "react-router-dom";
import { classifyStateSegment, pathFor } from "./shared/utils/jurisdiction";
import { DEFAULT_JURISDICTION } from "./shared/constants/jurisdictions";
-import clsx from "clsx";
/**
* Routes /chat requests by classifying the :state segment: an out-of-state
@@ -46,40 +42,17 @@ function ChatView() {
const { letterContent } = useLetterContent(messages);
return (
-
+ }
+ >
+
+
);
}
diff --git a/frontend/src/Letter.tsx b/frontend/src/Letter.tsx
index 4a89a473..cb53b1f4 100644
--- a/frontend/src/Letter.tsx
+++ b/frontend/src/Letter.tsx
@@ -23,14 +23,10 @@ import {
type JurisdictionOption,
} from "./shared/constants/jurisdictions";
import LetterDisclaimer from "./pages/Letter/components/LetterDisclaimer";
-import MessageContainer from "./shared/components/MessageContainer";
import useHousingContext from "./hooks/useHousingContext";
-import type { Location } from "./types/models";
-import FeaturesPanel from "./shared/components/FeaturesPanel";
-import FrequentInquiries from "./shared/components/FrequentInquiries";
-import MobilePanel from "./shared/components/MobilePanel";
-import clsx from "clsx";
+import ChatPageLayout from "./layouts/ChatPageLayout";
import { buildLocationPrefix } from "./shared/utils/buildLocationPrefix";
+import { createId } from "./shared/utils/createId";
/**
* Routes /letter requests by classifying the leading segment: an out-of-state
@@ -87,8 +83,6 @@ function LetterView({ jurisdiction, org }: LetterViewProps) {
const { addMessage, messages, setMessages } = useMessages();
const isOngoing = messages.length > 0;
const { letterContent } = useLetterContent(messages);
- const [startStreaming, setStartStreaming] = useState(false);
- const streamLocationRef = useRef(null);
const [isGenerating, setIsGenerating] = useState(true);
const dialogRef = useRef(null);
const timerRef = useRef | null>(null);
@@ -104,13 +98,12 @@ function LetterView({ jurisdiction, org }: LetterViewProps) {
handleCityChange(jurisdiction.key);
}, [jurisdiction, handleHousingLocation, handleCityChange]);
- // Adds the initial user message once and triggers streaming.
+ // Adds the initial user message once and streams the letter.
useEffect(() => {
if (hasInitialized.current) return;
+ hasInitialized.current = true;
const loc = toLocation(jurisdiction);
const output = buildLetterUserMessage(org, loc);
- hasInitialized.current = true;
- const userMessageId = Date.now().toString();
const content = [
buildLocationPrefix(loc.city, loc.state),
issueDescription,
@@ -118,55 +111,47 @@ function LetterView({ jurisdiction, org }: LetterViewProps) {
]
.join(" ")
.trim();
- setMessages((prev) => [
- ...prev,
- new HumanMessage({ content, id: userMessageId }),
- ]);
- streamLocationRef.current = output.selectedLocation;
- setStartStreaming(true);
- }, [jurisdiction, org, setMessages, issueDescription]);
-
- useEffect(() => {
- if (startStreaming === false || streamLocationRef.current === null) return;
- // Reset state to prevent re-running
- setStartStreaming(false);
+ const userMessage = new HumanMessage({
+ content,
+ id: createId(),
+ });
+ setMessages((prev) => [...prev, userMessage]);
const runGenerateLetter = async () => {
- if (streamLocationRef.current !== null) {
- let cleanCompletion = false;
- await streamText({
- addMessage,
- setMessages,
- housingLocation: streamLocationRef.current,
- onDone: () => {
- cleanCompletion = true;
- const uiMessage: UiMessage = {
- type: "ui",
- text: "What was generated is just an initial template. Please include details of your specific housing situation to update the letter.",
- id: Date.now().toString(),
- };
- setMessages((prev) => [...prev, uiMessage]);
- },
- });
- // No done chunk received — surface an error instead of a silent empty panel.
- if (!cleanCompletion) {
+ let cleanCompletion = false;
+ await streamText({
+ addMessage,
+ history: [userMessage],
+ setMessages,
+ housingLocation: output.selectedLocation,
+ onDone: () => {
+ cleanCompletion = true;
const uiMessage: UiMessage = {
type: "ui",
- text: "Unable to generate letter. Please try again or refresh the page.",
- id: Date.now().toString(),
+ text: "What was generated is just an initial template. Please include details of your specific housing situation to update the letter.",
+ id: createId(),
};
setMessages((prev) => [...prev, uiMessage]);
- }
- // Clear spinner after a short delay for a smoother transition.
- timerRef.current = setTimeout(
- () => setIsGenerating(false),
- LOADING_DISPLAY_DELAY_MS,
- );
+ },
+ });
+ // No done chunk received — surface an error instead of a silent empty panel.
+ if (!cleanCompletion) {
+ const uiMessage: UiMessage = {
+ type: "ui",
+ text: "Unable to generate letter. Please try again or refresh the page.",
+ id: createId(),
+ };
+ setMessages((prev) => [...prev, uiMessage]);
}
+ // Clear spinner after a short delay for a smoother transition.
+ timerRef.current = setTimeout(
+ () => setIsGenerating(false),
+ LOADING_DISPLAY_DELAY_MS,
+ );
};
runGenerateLetter();
- }, [startStreaming, addMessage, setMessages]);
+ }, [jurisdiction, org, addMessage, setMessages, issueDescription]);
// Clear any pending timer if the component unmounts before it fires.
useEffect(() => {
@@ -187,50 +172,26 @@ function LetterView({ jurisdiction, org }: LetterViewProps) {
ref={dialogRef}
isRedirected={sanitizeOrg(org) !== ""}
/>
-
-
-
-
- {isGenerating ? (
-
-
- Generating Letter...
-
-
- ) : (
-
- )}
-
-
-
-
-
}
- />
-
+ }
+ >
+ {isGenerating ? (
+
+ ) : (
+
+ )}
+
>
);
}
diff --git a/frontend/src/hooks/useMessages.tsx b/frontend/src/hooks/useMessages.tsx
index e818d8a6..39d162d4 100644
--- a/frontend/src/hooks/useMessages.tsx
+++ b/frontend/src/hooks/useMessages.tsx
@@ -23,21 +23,36 @@ export function deserializeAiMessage(text: string): string {
.join("\n");
}
-async function addNewMessage(
- messages: ChatMessage[],
- { city, state }: Location,
-) {
- const serializedMsg = messages.map((msg) => ({
- role: msg.type,
- content: msg.type === "ai" ? deserializeAiMessage(msg.text) : msg.text,
- id: msg.id,
- }));
+/** Arguments for sending the conversation history to the backend. */
+export interface AddMessageArgs extends Location {
+ messages: ChatMessage[];
+}
+
+export type AddMessage = (
+ args: AddMessageArgs,
+) => Promise | undefined>;
+
+async function addNewMessage({ messages, city, state }: AddMessageArgs) {
+ // Exclude UI-only messages and empty placeholders from backend history.
+ const serializedMsg = messages
+ .filter(
+ (msg): msg is Exclude =>
+ msg.type !== "ui" && msg.text.trim() !== "",
+ )
+ .map((msg) => ({
+ role: msg.type,
+ content: msg.type === "ai" ? deserializeAiMessage(msg.text) : msg.text,
+ id: msg.id,
+ }));
const response = await fetch("/api/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ messages: serializedMsg, city, state }),
});
+ if (!response.ok) {
+ throw new Error(`Query failed with status ${response.status}`);
+ }
return response.body?.getReader();
}
@@ -48,16 +63,7 @@ async function addNewMessage(
export default function useMessages() {
const [messages, setMessages] = useState([]);
- const addMessage = useMutation({
- mutationFn: async ({ city, state }: Location) => {
- // Exclude UI-only messages and empty placeholders from backend history.
- const filteredMessages = messages.filter(
- (msg): msg is Exclude =>
- msg.type !== "ui" && msg.text.trim() !== "",
- );
- return await addNewMessage(filteredMessages, { city, state });
- },
- });
+ const addMessage = useMutation({ mutationFn: addNewMessage });
return {
messages,
diff --git a/frontend/src/layouts/ChatPageLayout.tsx b/frontend/src/layouts/ChatPageLayout.tsx
new file mode 100644
index 00000000..60132394
--- /dev/null
+++ b/frontend/src/layouts/ChatPageLayout.tsx
@@ -0,0 +1,48 @@
+import clsx from "clsx";
+import FrequentInquiries from "../shared/components/FrequentInquiries";
+import MessageContainer from "../shared/components/MessageContainer";
+import FeaturesPanel from "../shared/components/FeaturesPanel";
+import MobilePanel from "../shared/components/MobilePanel";
+
+interface Props {
+ isOngoing: boolean;
+ letterContent: string;
+ disclaimer: React.ReactNode;
+ children: React.ReactNode;
+}
+
+/**
+ * Shared layout for the chat and letter pages: the message pane, the
+ * Frequent Inquiries side panel, and the features panel.
+ */
+export default function ChatPageLayout({
+ isOngoing,
+ letterContent,
+ disclaimer,
+ children,
+}: Props) {
+ return (
+
+
+
+ {children}
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/pages/Chat/components/InitializationForm.tsx b/frontend/src/pages/Chat/components/InitializationForm.tsx
index 123231c5..870f3b4c 100644
--- a/frontend/src/pages/Chat/components/InitializationForm.tsx
+++ b/frontend/src/pages/Chat/components/InitializationForm.tsx
@@ -1,24 +1,28 @@
import type { ChatMessage } from "../../../shared/types/messages";
import BeaverIcon from "../../../shared/components/BeaverIcon";
-import type { Location } from "../../../types/models";
+import type { AddMessage } from "../../../hooks/useMessages";
import { streamText } from "../utils/streamHelper";
+import { createId } from "../../../shared/utils/createId";
import useHousingContext from "../../../hooks/useHousingContext";
import { buildLocationPrefix } from "../../../shared/utils/buildLocationPrefix";
import { scrollToTop } from "../../../shared/utils/scrolling";
import { HumanMessage } from "@langchain/core/messages";
interface Props {
- addMessage: (
- args: Location,
- ) => Promise | undefined>;
+ addMessage: AddMessage;
setMessages: React.Dispatch>;
+ setIsLoading: React.Dispatch>;
}
/**
* Initial chat form for describing a housing issue.
* The jurisdiction is set via the navbar location picker.
*/
-export default function InitializationForm({ addMessage, setMessages }: Props) {
+export default function InitializationForm({
+ addMessage,
+ setMessages,
+ setIsLoading,
+}: Props) {
const {
housingLocation,
issueDescription,
@@ -27,22 +31,24 @@ export default function InitializationForm({ addMessage, setMessages }: Props) {
} = useHousingContext();
const handleInitialInput = async () => {
- const userMessageId = Date.now().toString();
const content = [
buildLocationPrefix(housingLocation.city, housingLocation.state),
issueDescription,
]
.join(" ")
.trim();
- setMessages((prev) => [
- ...prev,
- new HumanMessage({ content, id: userMessageId }),
- ]);
+ const userMessage = new HumanMessage({
+ content,
+ id: createId(),
+ });
+ setMessages((prev) => [...prev, userMessage]);
await streamText({
addMessage,
+ history: [userMessage],
setMessages,
housingLocation,
+ setIsLoading,
});
};
diff --git a/frontend/src/pages/Chat/components/InputField.tsx b/frontend/src/pages/Chat/components/InputField.tsx
index 46210637..00344f25 100644
--- a/frontend/src/pages/Chat/components/InputField.tsx
+++ b/frontend/src/pages/Chat/components/InputField.tsx
@@ -1,53 +1,52 @@
import { useCallback, useEffect } from "react";
import { HumanMessage } from "@langchain/core/messages";
import type { ChatMessage } from "../../../shared/types/messages";
-import type { Location } from "../../../types/models";
+import type { AddMessage } from "../../../hooks/useMessages";
import { streamText } from "../utils/streamHelper";
+import { createId } from "../../../shared/utils/createId";
import useHousingContext from "../../../hooks/useHousingContext";
import clsx from "clsx";
interface Props {
- addMessage: (
- args: Location,
- ) => Promise | undefined>;
+ messages: ChatMessage[];
+ addMessage: AddMessage;
setMessages: React.Dispatch>;
isLoading: boolean;
setIsLoading: React.Dispatch>;
value: string;
inputRef: React.RefObject;
- onChange: (e: React.ChangeEvent) => void;
+ setValue: (value: string) => void;
}
/**
* Auto-resizing text input for composing and sending chat messages.
*/
export default function InputField({
+ messages,
addMessage,
setMessages,
isLoading,
setIsLoading,
inputRef,
value,
- onChange,
+ setValue,
}: Props) {
const { housingLocation } = useHousingContext();
const handleSend = async () => {
if (!value.trim()) return;
- onChange({
- target: { value: "" },
- } as React.ChangeEvent);
+ setValue("");
- const userMessageId = Date.now().toString();
- // Add user message
- setMessages((prev) => [
- ...prev,
- new HumanMessage({ content: value, id: userMessageId }),
- ]);
+ const userMessage = new HumanMessage({
+ content: value,
+ id: createId(),
+ });
+ setMessages((prev) => [...prev, userMessage]);
await streamText({
addMessage,
+ history: [...messages, userMessage],
setMessages,
housingLocation,
setIsLoading,
@@ -70,7 +69,7 @@ export default function InputField({