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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ frontend/
│ │ └── utils/
│ │ ├── buildLocationPrefix.ts # Helper function for location prefix
│ │ ├── scrolling.ts # Helper function for window scrolling
│ │ ├── dompurify.ts # Helper function for sanitizing text
│ │ └── formatLocation.ts # Formats OregonCity/UsaState into a display string (e.g. "Portland, OR")
│ └── tests/ # Testing suite
│ │ ├── components/ # Component testing
Expand All @@ -168,7 +167,6 @@ frontend/
│ │ │ ├── useLetterContent.test.tsx # useLetterContent testing
│ │ │ └── useMessages.test.ts # useMessages testing
│ │ └── utils/ # Utility function testing
│ │ ├── dompurify.test.ts # dompurify testing
│ │ ├── exportHelper.test.ts # exportHelper testing
│ │ ├── feedbackHelper.test.ts # feedbackHelper testing
│ │ ├── letterHelper.test.ts # letterHelper testing
Expand Down
16 changes: 0 additions & 16 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"@tailwindcss/vite": "^4.1.6",
"@tanstack/react-query": "^5.77.2",
"clsx": "^2.1.1",
"dompurify": "^3.3.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-markdown": "^10.1.0",
Expand Down
10 changes: 8 additions & 2 deletions frontend/src/Letter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import { Navigate, useParams, useSearchParams } from "react-router-dom";
import { useLetterContent } from "./hooks/useLetterContent";
import { streamText } from "./pages/Chat/utils/streamHelper";
import LetterGenerationDialog from "./pages/Letter/components/LetterGenerationDialog";
import { buildLetterUserMessage } from "./pages/Letter/utils/letterHelper";
import {
buildLetterUserMessage,
sanitizeOrg,
} from "./pages/Letter/utils/letterHelper";
import {
classifyStateSegment,
pathFor,
Expand Down Expand Up @@ -180,7 +183,10 @@ function LetterView({ jurisdiction, org }: LetterViewProps) {

return (
<>
<LetterGenerationDialog ref={dialogRef} />
<LetterGenerationDialog
ref={dialogRef}
isRedirected={sanitizeOrg(org) !== ""}
/>
<div className="min-h-full lg:h-full w-full flex flex-col lg:flex-row transition-all duration-300 lg:relative lg:bg-paper-background">
<div className="flex-1 lg:my-0 w-full lg:flex-1 flex lg:order-2">
<MessageContainer isOngoing={isOngoing} letterContent={letterContent}>
Expand Down
5 changes: 1 addition & 4 deletions frontend/src/contexts/HousingContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createContext, useCallback, useMemo, useState } from "react";
import DOMPurify, { SANITIZE_USER_SETTINGS } from "../shared/utils/dompurify";
import type { Location } from "../types/models";
import type { JurisdictionKey } from "../shared/constants/jurisdictions";

Expand Down Expand Up @@ -39,9 +38,7 @@ export default function HousingContextProvider({ children }: Props) {

const handleIssueDescription = useCallback(
(event: React.ChangeEvent<HTMLTextAreaElement>) => {
setIssueDescription(
DOMPurify.sanitize(event.target.value, SANITIZE_USER_SETTINGS),
);
setIssueDescription(event.target.value);
},
[],
);
Expand Down
56 changes: 42 additions & 14 deletions frontend/src/pages/Chat/components/FeedbackModal.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import sendFeedback from "../utils/feedbackHelper";
import type { ChatMessage } from "../../../shared/types/messages";

const AUTO_CLOSE_DELAY_MS = 1500;

interface Props {
messages: ChatMessage[];
setOpenFeedback: React.Dispatch<React.SetStateAction<boolean>>;
Expand All @@ -14,7 +16,10 @@ export default function FeedbackModal({ messages, setOpenFeedback }: Props) {
const [feedback, setFeedback] = useState("");
const [wordsToRedact, setWordsToRedact] = useState("");
const [emailsToCC, setEmailsToCC] = useState("");
const [status, setStatus] = useState("idle");
const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">(
"idle",
);
const canEdit = status === "idle" || status === "error";

const handleModalClose = () => {
setOpenFeedback(false);
Expand All @@ -24,6 +29,14 @@ export default function FeedbackModal({ messages, setOpenFeedback }: Props) {
setWordsToRedact("");
};

// Unmounting the modal resets its state, so closing is enough; the cleanup
// cancels the timer if the user clicks Close first.
useEffect(() => {
if (status !== "sent") return;
const timer = setTimeout(() => setOpenFeedback(false), AUTO_CLOSE_DELAY_MS);
return () => clearTimeout(timer);
}, [status, setOpenFeedback]);

return (
<dialog
open
Expand All @@ -33,29 +46,37 @@ export default function FeedbackModal({ messages, setOpenFeedback }: Props) {
w-[300px] sm:w-[500px] h-[300px] p-4
rounded-lg z-10`}
>
{status === "idle" ? (
{canEdit ? (
<>
{status === "error" && (
<p role="alert" className="text-red-dark">
Couldn't send feedback. Please try again.
</p>
)}
<textarea
className="h-[80%] w-full"
className="flex-[4] min-h-0 w-full"
placeholder="Please enter your feedback with regards to the chatbot here. A copy of your chat transcript will automatically be included with your response."
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
/>
<input
className="h-[20%] w-full"
className="flex-1 min-h-0 w-full"
placeholder="Enter email(s) to CC transcript separated by commas"
type="text"
value={emailsToCC}
onChange={(event) => setEmailsToCC(event.target.value)}
/>
<input
className="h-[20%] w-full"
className="flex-1 min-h-0 w-full"
placeholder="Please enter word(s) to redact separated by commas"
type="text"
value={wordsToRedact}
onChange={(event) => setWordsToRedact(event.target.value)}
/>
</>
) : (
<div className="flex items-center justify-center h-[80%] w-full">
<p>Feedback Sent!</p>
<div className="flex items-center justify-center flex-1 w-full">
<p>{status === "sending" ? "Sending…" : "Feedback Sent!"}</p>
</div>
)}
<div className="flex gap-4">
Expand All @@ -64,13 +85,20 @@ export default function FeedbackModal({ messages, setOpenFeedback }: Props) {
text-green-dark
border border-green-medium hover:border-green-dark
hover:bg-green-light`}
onClick={() => {
if (feedback.trim() === "") handleModalClose();
setStatus("sending");
setTimeout(() => {
sendFeedback(messages, feedback, emailsToCC, wordsToRedact);
disabled={!canEdit}
onClick={async () => {
if (feedback.trim() === "") {
handleModalClose();
}, 1000);
return;
}
setStatus("sending");
try {
await sendFeedback(messages, feedback, emailsToCC, wordsToRedact);
setStatus("sent");
} catch (error) {
console.error("Failed to send feedback:", error);
setStatus("error");
}
}}
>
Send
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/Chat/components/InitializationForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export default function InitializationForm({ addMessage, setMessages }: Props) {
<textarea
className="h-25 md:h-16 w-full"
placeholder="Briefly describe your specific housing situation or question about housing."
value={issueDescription}
onChange={handleIssueDescription}
/>
</div>
Expand Down
8 changes: 7 additions & 1 deletion frontend/src/pages/Chat/components/InputField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,13 @@ export default function InputField({
onChange={onChange}
onInput={resizeTextArea}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
// keyCode 229 covers Safari, which ends composition before keydown.
if (
e.key === "Enter" &&
!e.shiftKey &&
!e.nativeEvent.isComposing &&
e.keyCode !== 229
) {
e.preventDefault();
handleSend();
}
Expand Down
76 changes: 57 additions & 19 deletions frontend/src/pages/Chat/utils/feedbackHelper.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,81 @@
import { deserializeAiMessage } from "../../../hooks/useMessages";
import type { ChatMessage, UiMessage } from "../../../shared/types/messages";
import sanitizeText from "../../../shared/utils/sanitizeText";
import {
escapeHtml,
stripAnchorTags,
} from "../../../shared/utils/sanitizeText";

function redactText(message: string, wordsToRedact: string) {
let redactedMessage = message;
const redactList = wordsToRedact
.split(/\s*,\s*/)
.map((s) => s.trim())
.filter((s) => s.length > 0);
redactList.forEach((word) => {
const regex = new RegExp(`\\b${word.replace(/\s+/g, "\\s+")}\\b`, "gi");
redactedMessage = redactedMessage.replace(regex, () => {
return `<span style="
const REDACTED_SPAN = `<span style="
background-color: black;
color:transparent;
white-space: nowrap;
user-select: none;
">${"_".repeat(10)}</span>`;
});
});
return redactedMessage;

// Unicode-aware word boundary; a capture group instead of lookbehind keeps
// older Safari (< 16.4) working. The consumed delimiter means back-to-back
// matches like "C++C++" only redact the first.
const NON_WORD = "[^\\p{L}\\p{N}_]";

function buildRedactRegex(wordsToRedact: string): RegExp | null {
const terms = wordsToRedact
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0)
// Longest first so a term that contains another redacts in full.
.sort((a, b) => b.length - a.length)
.map((s) =>
s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s+"),
);
if (terms.length === 0) return null;
return new RegExp(
`(^|${NON_WORD})(${terms.join("|")})(?=$|${NON_WORD})`,
"giu",
);
}

/**
* Strips anchors, redacts matches in the raw text, then HTML-escapes everything between them.
* Redacting before escaping keeps terms from matching entities or inserted markup.
*/
function redactAndEscape(text: string, regex: RegExp | null) {
text = stripAnchorTags(text);
if (regex === null) return escapeHtml(text);
let result = "";
let lastIndex = 0;
for (const match of text.matchAll(regex)) {
const start = match.index + match[1].length;
result += escapeHtml(text.slice(lastIndex, start)) + REDACTED_SPAN;
lastIndex = start + match[2].length;
}
return result + escapeHtml(text.slice(lastIndex));
}

/**
* Submits user feedback along with a redacted chat transcript to the backend.
* Builds an HTML transcript, applies word redaction, and sends via FormData.
* Throws if there is no exchange to send, the request fails, or the server responds with an error.
*/
export default async function sendFeedback(
messages: ChatMessage[],
userFeedback: string,
emailsToCC: string,
wordsToRedact: string,
) {
if (messages.length < 2) return;
const transcriptMessages = messages.filter(
(msg): msg is Exclude<ChatMessage, UiMessage> => msg.type !== "ui",
);
if (transcriptMessages.length < 2) {
throw new Error("Not enough messages to send feedback");
}

const messageChain = messages
.filter((msg): msg is Exclude<ChatMessage, UiMessage> => msg.type !== "ui")
const redactRegex = buildRedactRegex(wordsToRedact);
const messageChain = transcriptMessages
.map(
(msg) =>
`<p><strong>${
msg.type === "human" ? "User" : "AI"
}</strong>: ${redactText(sanitizeText(msg.type === "ai" ? deserializeAiMessage(msg.text) : msg.text), wordsToRedact)}</p>`,
}</strong>: ${redactAndEscape(msg.type === "ai" ? deserializeAiMessage(msg.text) : msg.text, redactRegex)}</p>`,
)
.join("");

Expand Down Expand Up @@ -75,8 +110,11 @@ export default async function sendFeedback(
formData.append("emailsToCC", emailsToCC);
formData.append("transcript", blob, "transcript.html");

await fetch("/api/feedback", {
const response = await fetch("/api/feedback", {
method: "POST",
body: formData,
});
if (!response.ok) {
throw new Error(`Feedback request failed with status ${response.status}`);
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { useLocation } from "react-router-dom";

interface Props {
ref: React.RefObject<HTMLDialogElement | null>;
isRedirected: boolean;
}

export default function LetterGenerationDialog({ ref }: Props) {
const location = useLocation();
const isRedirected = location.pathname !== "/letter";
export default function LetterGenerationDialog({ ref, isRedirected }: Props) {
const redirectMessage = isRedirected
? "You've been redirected here so we can help you create a letter to your landlord. "
: "";
Expand Down
Loading
Loading