xonecas.io
53129
Pa

PAT / commit a43e8db

refactor: add extracted hooks and streaming utilities

- add useAutoResizeTextarea hook for textarea auto-resize functionality
- add useMessageHistory hook for message history navigation
- add parse-message-stream utility for streaming message parsing
- these were created in previous refactoring but not committed

xonecas2025-12-19 a43e8db0dccdf27acd199e402b5d576f9e80fb04 parent ee48e66

3 files changed

src/hooks/useAutoResizeTextarea.ts+39−0
@@ -0,0 +1,39 @@
1+import { useEffect, useRef } from "react";
2+
3+/**
4+ * Custom hook for auto-resizing a textarea element.
5+ * Keeps an empty line at the bottom and enforces min/max height constraints.
6+ *
7+ * @param value - The current value of the textarea
8+ * @param minLines - Minimum number of lines (default: 3)
9+ * @param maxLines - Maximum number of lines (default: 10)
10+ * @returns Ref to attach to the textarea element
11+ */
12+export function useAutoResizeTextarea(
13+ value: string,
14+ minLines = 3,
15+ maxLines = 10
16+): React.RefObject<HTMLTextAreaElement> {
17+ const textareaRef = useRef<HTMLTextAreaElement>(null);
18+
19+ useEffect(() => {
20+ const textarea = textareaRef.current;
21+ if (!textarea) return;
22+
23+ textarea.style.height = "auto";
24+
25+ const computedStyle = getComputedStyle(textarea);
26+ const lineHeight = parseFloat(computedStyle.lineHeight) || 24;
27+ const paddingTop = parseFloat(computedStyle.paddingTop) || 8;
28+ const paddingBottom = parseFloat(computedStyle.paddingBottom) || 8;
29+
30+ const minHeight = lineHeight * minLines + paddingTop + paddingBottom;
31+ const maxHeight = lineHeight * maxLines + paddingTop + paddingBottom;
32+
33+ const calculatedHeight = textarea.scrollHeight + lineHeight;
34+ const newHeight = Math.min(maxHeight, Math.max(minHeight, calculatedHeight));
35+ textarea.style.height = `${newHeight}px`;
36+ }, [value, minLines, maxLines]);
37+
38+ return textareaRef;
39+}
src/hooks/useMessageHistory.ts+61−0
@@ -0,0 +1,61 @@
1+import { useState, useRef } from "react";
2+import type { Message } from "@/src/lib/db/schema";
3+
4+/**
5+ * Custom hook for managing message history navigation in a text input.
6+ * Allows cycling through previous user messages using Ctrl/Cmd + Arrow keys.
7+ *
8+ * @param messages - Array of all messages to extract user messages from
9+ * @returns Object containing:
10+ * - `input` - Current input value
11+ * - `setInput` - Function to set input value
12+ * - `historyIndex` - Current history index (null if not navigating)
13+ * - `handleKeyDown` - Handler function for keyboard events
14+ * - `resetHistory` - Function to reset history navigation
15+ */
16+export function useMessageHistory(messages: Message[]) {
17+ const [input, setInput] = useState("");
18+ const [historyIndex, setHistoryIndex] = useState<number | null>(null);
19+ const draftInputRef = useRef<string>("");
20+
21+ const userMessages = messages.filter((m) => m.role === "user");
22+
23+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
24+ if (e.key === "ArrowUp" && (e.ctrlKey || e.metaKey)) {
25+ e.preventDefault();
26+ if (historyIndex === null) {
27+ draftInputRef.current = input;
28+ }
29+ const idx = historyIndex ?? userMessages.length;
30+ if (idx > 0) {
31+ const newIdx = idx - 1;
32+ setHistoryIndex(newIdx);
33+ setInput(userMessages[newIdx].content);
34+ }
35+ } else if (e.key === "ArrowDown" && (e.ctrlKey || e.metaKey)) {
36+ e.preventDefault();
37+ if (historyIndex !== null) {
38+ const newIdx = historyIndex + 1;
39+ if (newIdx < userMessages.length) {
40+ setHistoryIndex(newIdx);
41+ setInput(userMessages[newIdx].content);
42+ } else {
43+ setHistoryIndex(null);
44+ setInput(draftInputRef.current);
45+ }
46+ }
47+ }
48+ };
49+
50+ const resetHistory = () => {
51+ setHistoryIndex(null);
52+ };
53+
54+ return {
55+ input,
56+ setInput,
57+ historyIndex,
58+ handleKeyDown,
59+ resetHistory,
60+ };
61+}
src/lib/parse-message-stream.ts+114−0
@@ -0,0 +1,114 @@
1+import { getParseErrorMessage, handleError } from "@/src/lib/errors";
2+
3+type StreamEventCallbacks = {
4+ onContent?: (content: string) => void;
5+ onToolMessage?: (id: number, threadId: number, content: string, createdAt?: string) => void;
6+ onDone?: (data: {
7+ answer?: string;
8+ model?: string;
9+ maxPromptLength?: number | null;
10+ toolCallCounts?: string | null;
11+ }) => void;
12+ onError?: (error: string) => void;
13+ onStop?: () => void;
14+};
15+
16+/**
17+ * Parses a streaming message response from the chat API.
18+ * Handles Server-Sent Events (SSE) format with different message types.
19+ *
20+ * @param reader - ReadableStreamDefaultReader from the fetch response
21+ * @param callbacks - Callback functions for different event types
22+ * @param onError - Optional error handler callback
23+ */
24+export async function parseMessageStream(
25+ reader: ReadableStreamDefaultReader<Uint8Array>,
26+ callbacks: StreamEventCallbacks,
27+ onError?: (error: string) => void
28+): Promise<void> {
29+ const decoder = new TextDecoder();
30+ let buffer = "";
31+ let accumulatedContent = "";
32+
33+ while (true) {
34+ const { done, value } = await reader.read();
35+ if (done) break;
36+
37+ buffer += decoder.decode(value, { stream: true });
38+ const lines = buffer.split("\n");
39+ buffer = lines.pop() || "";
40+
41+ for (const line of lines) {
42+ if (line.trim() === "") continue;
43+ if (line.startsWith("data: ")) {
44+ try {
45+ const data = JSON.parse(line.slice(6));
46+ if (data.type === "content") {
47+ accumulatedContent += data.content || "";
48+ callbacks.onContent?.(accumulatedContent);
49+ } else if (data.type === "toolMessage") {
50+ callbacks.onToolMessage?.(data.id, data.threadId, data.content, data.createdAt);
51+ } else if (data.type === "done") {
52+ callbacks.onDone?.({
53+ answer: data.answer,
54+ model: data.model,
55+ maxPromptLength: data.maxPromptLength,
56+ toolCallCounts: data.toolCallCounts,
57+ });
58+ return;
59+ } else if (data.type === "error") {
60+ if (data.error === "Generation stopped") {
61+ callbacks.onStop?.();
62+ return;
63+ }
64+ const errorMsg = data.error || "Unknown error";
65+ callbacks.onError?.(errorMsg);
66+ if (onError) onError(errorMsg);
67+ throw new Error(errorMsg);
68+ }
69+ } catch (parseError) {
70+ handleError(parseError, onError);
71+ }
72+ }
73+ }
74+ }
75+}
76+
77+/**
78+ * Fetches and parses a streaming chat response.
79+ *
80+ * @param message - The message to send
81+ * @param threadId - The thread ID
82+ * @param callbacks - Callback functions for different event types
83+ * @param signal - Optional AbortSignal to cancel the request
84+ * @param onError - Optional error handler callback
85+ * @throws If the request fails or response is invalid
86+ */
87+export async function fetchAndParseMessageStream(
88+ message: string,
89+ threadId: number,
90+ callbacks: StreamEventCallbacks,
91+ signal?: AbortSignal,
92+ onError?: (error: string) => void
93+): Promise<void> {
94+ const res = await fetch("/api/chat", {
95+ method: "POST",
96+ headers: { "Content-Type": "application/json" },
97+ body: JSON.stringify({ message: message.trim(), threadId }),
98+ signal,
99+ });
100+
101+ if (!res.ok) {
102+ const errorData = await res.json().catch((parseError) => {
103+ throw new Error(getParseErrorMessage(parseError));
104+ });
105+ throw new Error(errorData.error || `HTTP error! status: ${res.status}`);
106+ }
107+
108+ if (!res.body) {
109+ throw new Error("Response body is null");
110+ }
111+
112+ const reader = res.body.getReader();
113+ await parseMessageStream(reader, callbacks, onError);
114+}