xonecas.io
53129
Pa

PAT / commit 316acbe

refactor: extract formatting and message creation utilities

- Extract formatTimestamp to src/lib/format-timestamp.ts
- Extract message metadata formatting to src/lib/format-message-metadata.ts
- Extract message creation helpers to src/lib/message-helpers.ts
- Update message components to use shared utilities
- Remove duplicate code from message components

xonecas2025-12-19 316acbe4a9bb47ca2f79a1042c59ea2b5d006581 parent 26f0075

9 files changed

AGENTS.md+6−0
@@ -10,6 +10,12 @@
1010 - **Always do exactly what was asked** - Don't add anything that wasn't explicitly mentioned.
1111 - **Always lint and typecheck** changes using `npm run lint` and `npm run typecheck`.
1212 - **Always write modular, testable code** - Prefer small, focused functions and components, focused on reusability.
13+- **Always review your changes before committing**:
14+ - identify code repetition and consolidate
15+ - identify overly complex code and simplify
16+ - ensure code modularity and separation of concerns
17+ - ensure code respects project guidelines
18+ - ensure the code uses best practices for React and Next.js
1319
1420 ## Coding Guidelines
1521
src/components/MessageList/AssistantMessage.tsx+6−33
@@ -4,6 +4,12 @@ import ReactMarkdown from "react-markdown";
44 import remarkGfm from "remark-gfm";
55 import rehypeHighlight from "rehype-highlight";
66 import type { Message } from "@/src/lib/db/schema";
7+import { formatTimestamp } from "@/src/lib/format-timestamp";
8+import {
9+ formatGenerationTime,
10+ formatToolCalls,
11+ formatPromptSize,
12+} from "@/src/lib/format-message-metadata";
713 import "../../../app/highlight-theme.css";
814
915 type AssistantMessageProps = {
@@ -11,39 +17,6 @@ type AssistantMessageProps = {
1117 };
1218
1319 export default function AssistantMessage({ message }: AssistantMessageProps) {
14- const formatTimestamp = (date: Date | string): string => {
15- const d = typeof date === "string" ? new Date(date) : date;
16- return d.toLocaleString();
17- };
18-
19- const formatGenerationTime = (ms: number | null): string => {
20- if (!ms) return "";
21- if (ms < 1000) return `${ms}ms`;
22- return `${(ms / 1000).toFixed(1)}s`;
23- };
24-
25- const formatToolCalls = (toolCallsJson: string | null): string | null => {
26- if (!toolCallsJson) return null;
27- try {
28- const toolCounts: Record<string, number> = JSON.parse(toolCallsJson);
29- if (typeof toolCounts !== "object" || toolCounts === null) return null;
30-
31- // Format as "toolName x count"
32- const formatted = Object.entries(toolCounts)
33- .map(([name, count]) => `${name} x ${count}`)
34- .join(", ");
35-
36- return formatted || null;
37- } catch {
38- return null;
39- }
40- };
41-
42- const formatPromptSize = (maxPromptLength: number | null): string => {
43- if (maxPromptLength === null) return "none";
44- return `${maxPromptLength}`;
45- };
46-
4720 const hasContent = message.content && message.content.trim() !== "";
4821
4922 return (
src/components/MessageList/SystemMessage.tsx+1−6
@@ -1,17 +1,13 @@
11 "use client";
22
33 import type { Message } from "@/src/lib/db/schema";
4+import { formatTimestamp } from "@/src/lib/format-timestamp";
45
56 type SystemMessageProps = {
67 message: Message;
78 };
89
910 export default function SystemMessage({ message }: SystemMessageProps) {
10- const formatTimestamp = (date: Date | string): string => {
11- const d = typeof date === "string" ? new Date(date) : date;
12- return d.toLocaleString();
13- };
14-
1511 return (
1612 <div className="mx-auto w-1/2 min-w-64 rounded-lg bg-neutral-100 p-2 text-sm text-neutral-500 dark:bg-neutral-900 dark:text-neutral-500">
1713 <div>{message.content}</div>
@@ -21,4 +17,3 @@ export default function SystemMessage({ message }: SystemMessageProps) {
2117 </div>
2218 );
2319 }
24-
src/components/MessageList/ToolMessage.tsx+1−6
@@ -1,17 +1,13 @@
11 "use client";
22
33 import type { Message } from "@/src/lib/db/schema";
4+import { formatTimestamp } from "@/src/lib/format-timestamp";
45
56 type ToolMessageProps = {
67 message: Message;
78 };
89
910 export default function ToolMessage({ message }: ToolMessageProps) {
10- const formatTimestamp = (date: Date | string): string => {
11- const d = typeof date === "string" ? new Date(date) : date;
12- return d.toLocaleString();
13- };
14-
1511 return (
1612 <div className="mx-auto w-1/2 min-w-64 rounded-lg bg-neutral-100 p-2 text-sm text-neutral-500 dark:bg-neutral-900 dark:text-neutral-500">
1713 <div>{message.content}</div>
@@ -21,4 +17,3 @@ export default function ToolMessage({ message }: ToolMessageProps) {
2117 </div>
2218 );
2319 }
24-
src/components/MessageList/UserMessage.tsx+1−5
@@ -2,6 +2,7 @@
22
33 import { useRef, useEffect, useState } from "react";
44 import type { Message } from "@/src/lib/db/schema";
5+import { formatTimestamp } from "@/src/lib/format-timestamp";
56
67 type UserMessageProps = {
78 message: Message;
@@ -11,11 +12,6 @@ export default function UserMessage({ message }: UserMessageProps) {
1112 const contentRef = useRef<HTMLDivElement>(null);
1213 const [showGradient, setShowGradient] = useState(false);
1314
14- const formatTimestamp = (date: Date | string): string => {
15- const d = typeof date === "string" ? new Date(date) : date;
16- return d.toLocaleString();
17- };
18-
1915 useEffect(() => {
2016 const checkOverflow = () => {
2117 if (contentRef.current) {
src/hooks/useMessages.ts+43−65
@@ -2,6 +2,12 @@ import { useState, useEffect, useCallback, useRef } from "react";
22 import type { Message } from "@/src/lib/db/schema";
33 import { getParseErrorMessage, handleError } from "@/src/lib/errors";
44 import { useMessageDisplaySettings } from "./useMessageDisplaySettings";
5+import {
6+ createUserMessage,
7+ createAssistantMessage,
8+ createToolMessage,
9+ createSystemMessage,
10+} from "@/src/lib/message-helpers";
511
612 /**
713 * Custom hook for managing messages within a thread.
@@ -66,63 +72,6 @@ export function useMessages(
6672 [messageDisplaySettings.showSystemMessages, messageDisplaySettings.showToolMessages]
6773 );
6874
69- const createUserMessage = (message: string, threadId: number): Message => ({
70- id: Date.now(),
71- threadId,
72- role: "user",
73- content: message,
74- createdAt: new Date(),
75- model: null,
76- maxPromptLength: null,
77- generationTimeMs: null,
78- toolCallCounts: null,
79- });
80-
81- const createAssistantMessage = (
82- id: number,
83- threadId: number,
84- content: string,
85- metadata?: {
86- model?: string | null;
87- maxPromptLength?: number | null;
88- toolCallCounts?: string | null;
89- }
90- ): Message => ({
91- id,
92- threadId,
93- role: "assistant",
94- content,
95- createdAt: new Date(),
96- model: metadata?.model ?? null,
97- maxPromptLength: metadata?.maxPromptLength ?? null,
98- generationTimeMs: null,
99- toolCallCounts: metadata?.toolCallCounts ?? null,
100- });
101-
102- const createToolMessage = (id: number, threadId: number, content: string, createdAt?: string | Date): Message => ({
103- id,
104- threadId,
105- role: "tool",
106- content,
107- createdAt: createdAt ? (typeof createdAt === "string" ? new Date(createdAt) : createdAt) : new Date(),
108- model: null,
109- maxPromptLength: null,
110- generationTimeMs: null,
111- toolCallCounts: null,
112- });
113-
114- const createSystemMessage = (id: number, threadId: number, content: string, createdAt?: string | Date): Message => ({
115- id,
116- threadId,
117- role: "system",
118- content,
119- createdAt: createdAt ? (typeof createdAt === "string" ? new Date(createdAt) : createdAt) : new Date(),
120- model: null,
121- maxPromptLength: null,
122- generationTimeMs: null,
123- toolCallCounts: null,
124- });
125-
12675 const updateAssistantMessage = (
12776 messageId: number,
12877 content: string,
@@ -198,7 +147,13 @@ export function useMessages(
198147 const sendMessage = async (
199148 message: string,
200149 currentThreadId: number | null,
201- onCreateThread: (title?: string, firstMessage?: string) => Promise<{ threadId: number; systemMessage?: { id: number; content: string; createdAt: string } } | null>,
150+ onCreateThread: (
151+ title?: string,
152+ firstMessage?: string
153+ ) => Promise<{
154+ threadId: number;
155+ systemMessage?: { id: number; content: string; createdAt: string };
156+ } | null>,
202157 onThreadSelect: (id: number) => void,
203158 onThreadsReload: () => void,
204159 onError?: (error: string) => void
@@ -220,7 +175,7 @@ export function useMessages(
220175 return;
221176 }
222177 targetThreadId = threadResult.threadId;
223-
178+
224179 // Add system message to state if it was returned and setting is enabled
225180 if (threadResult.systemMessage && messageDisplaySettings.showSystemMessages) {
226181 addSystemMessage(
@@ -230,7 +185,7 @@ export function useMessages(
230185 threadResult.systemMessage.createdAt
231186 );
232187 }
233-
188+
234189 // Mark that we're sending to this thread before selecting it
235190 sendingToThreadIdRef.current = targetThreadId;
236191 onThreadSelect(targetThreadId);
@@ -291,7 +246,11 @@ export function useMessages(
291246 accumulatedContent += data.content || "";
292247 // Only add the message when we have content
293248 if (!messageAdded && accumulatedContent.trim()) {
294- const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, accumulatedContent);
249+ const botMsg = createAssistantMessage(
250+ assistantMsgId,
251+ targetThreadId,
252+ accumulatedContent
253+ );
295254 setMessages((prev) => [...prev, botMsg]);
296255 messageAdded = true;
297256 } else if (messageAdded) {
@@ -299,7 +258,12 @@ export function useMessages(
299258 }
300259 } else if (data.type === "toolMessage") {
301260 // Add tool message to state in real-time
302- const toolMsg = createToolMessage(data.id, data.threadId, data.content, data.createdAt);
261+ const toolMsg = createToolMessage(
262+ data.id,
263+ data.threadId,
264+ data.content,
265+ data.createdAt
266+ );
303267 setMessages((prev) => [...prev, toolMsg]);
304268 } else if (data.type === "done") {
305269 // Final update with complete answer and metadata
@@ -311,7 +275,12 @@ export function useMessages(
311275 };
312276
313277 if (!messageAdded) {
314- const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, finalContent, metadata);
278+ const botMsg = createAssistantMessage(
279+ assistantMsgId,
280+ targetThreadId,
281+ finalContent,
282+ metadata
283+ );
315284 setMessages((prev) => [...prev, botMsg]);
316285 } else {
317286 updateAssistantMessage(assistantMsgId, finalContent, metadata);
@@ -346,7 +315,11 @@ export function useMessages(
346315 if (data.error === "Generation stopped") {
347316 // If we have content but message wasn't added, add it now
348317 if (!messageAdded && accumulatedContent.trim()) {
349- const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, accumulatedContent);
318+ const botMsg = createAssistantMessage(
319+ assistantMsgId,
320+ targetThreadId,
321+ accumulatedContent
322+ );
350323 setMessages((prev) => [...prev, botMsg]);
351324 }
352325 setStreamingMessageId(null);
@@ -416,7 +389,12 @@ export function useMessages(
416389 }
417390 };
418391
419- const addSystemMessage = (id: number, threadId: number, content: string, createdAt?: string | Date) => {
392+ const addSystemMessage = (
393+ id: number,
394+ threadId: number,
395+ content: string,
396+ createdAt?: string | Date
397+ ) => {
420398 const systemMsg = createSystemMessage(id, threadId, content, createdAt);
421399 setMessages((prev) => {
422400 // Check if message already exists to avoid duplicates
src/lib/format-message-metadata.ts+41−0
@@ -0,0 +1,41 @@
1+/**
2+ * Formats generation time in milliseconds to a human-readable string.
3+ * @param ms - Generation time in milliseconds, or null
4+ * @returns Formatted string (e.g., "123ms" or "1.5s") or empty string if null
5+ */
6+export function formatGenerationTime(ms: number | null): string {
7+ if (!ms) return "";
8+ if (ms < 1000) return `${ms}ms`;
9+ return `${(ms / 1000).toFixed(1)}s`;
10+}
11+
12+/**
13+ * Formats tool call counts from JSON string to a human-readable string.
14+ * @param toolCallsJson - JSON string containing tool call counts, or null
15+ * @returns Formatted string (e.g., "toolName x 2, otherTool x 1") or null
16+ */
17+export function formatToolCalls(toolCallsJson: string | null): string | null {
18+ if (!toolCallsJson) return null;
19+ try {
20+ const toolCounts: Record<string, number> = JSON.parse(toolCallsJson);
21+ if (typeof toolCounts !== "object" || toolCounts === null) return null;
22+
23+ const formatted = Object.entries(toolCounts)
24+ .map(([name, count]) => `${name} x ${count}`)
25+ .join(", ");
26+
27+ return formatted || null;
28+ } catch {
29+ return null;
30+ }
31+}
32+
33+/**
34+ * Formats max prompt length to a string representation.
35+ * @param maxPromptLength - Maximum prompt length, or null
36+ * @returns Formatted string (e.g., "1024" or "none")
37+ */
38+export function formatPromptSize(maxPromptLength: number | null): string {
39+ if (maxPromptLength === null) return "none";
40+ return `${maxPromptLength}`;
41+}
src/lib/format-timestamp.ts+9−0
@@ -0,0 +1,9 @@
1+/**
2+ * Formats a date or date string into a localized string representation.
3+ * @param date - The date to format (Date object or ISO string)
4+ * @returns Formatted date string
5+ */
6+export function formatTimestamp(date: Date | string): string {
7+ const d = typeof date === "string" ? new Date(date) : date;
8+ return d.toLocaleString();
9+}
src/lib/message-helpers.ts+116−0
@@ -0,0 +1,116 @@
1+import type { Message } from "@/src/lib/db/schema";
2+
3+type MessageMetadata = {
4+ model?: string | null;
5+ maxPromptLength?: number | null;
6+ toolCallCounts?: string | null;
7+};
8+
9+/**
10+ * Creates a user message object.
11+ * @param message - The message content
12+ * @param threadId - The thread ID this message belongs to
13+ * @returns A Message object with role "user"
14+ */
15+export function createUserMessage(message: string, threadId: number): Message {
16+ return {
17+ id: Date.now(),
18+ threadId,
19+ role: "user",
20+ content: message,
21+ createdAt: new Date(),
22+ model: null,
23+ maxPromptLength: null,
24+ generationTimeMs: null,
25+ toolCallCounts: null,
26+ };
27+}
28+
29+/**
30+ * Creates an assistant message object.
31+ * @param id - The message ID
32+ * @param threadId - The thread ID this message belongs to
33+ * @param content - The message content
34+ * @param metadata - Optional metadata (model, maxPromptLength, toolCallCounts)
35+ * @returns A Message object with role "assistant"
36+ */
37+export function createAssistantMessage(
38+ id: number,
39+ threadId: number,
40+ content: string,
41+ metadata?: MessageMetadata
42+): Message {
43+ return {
44+ id,
45+ threadId,
46+ role: "assistant",
47+ content,
48+ createdAt: new Date(),
49+ model: metadata?.model ?? null,
50+ maxPromptLength: metadata?.maxPromptLength ?? null,
51+ generationTimeMs: null,
52+ toolCallCounts: metadata?.toolCallCounts ?? null,
53+ };
54+}
55+
56+/**
57+ * Creates a tool message object.
58+ * @param id - The message ID
59+ * @param threadId - The thread ID this message belongs to
60+ * @param content - The message content
61+ * @param createdAt - Optional creation date (string or Date), defaults to now
62+ * @returns A Message object with role "tool"
63+ */
64+export function createToolMessage(
65+ id: number,
66+ threadId: number,
67+ content: string,
68+ createdAt?: string | Date
69+): Message {
70+ return {
71+ id,
72+ threadId,
73+ role: "tool",
74+ content,
75+ createdAt: createdAt
76+ ? typeof createdAt === "string"
77+ ? new Date(createdAt)
78+ : createdAt
79+ : new Date(),
80+ model: null,
81+ maxPromptLength: null,
82+ generationTimeMs: null,
83+ toolCallCounts: null,
84+ };
85+}
86+
87+/**
88+ * Creates a system message object.
89+ * @param id - The message ID
90+ * @param threadId - The thread ID this message belongs to
91+ * @param content - The message content
92+ * @param createdAt - Optional creation date (string or Date), defaults to now
93+ * @returns A Message object with role "system"
94+ */
95+export function createSystemMessage(
96+ id: number,
97+ threadId: number,
98+ content: string,
99+ createdAt?: string | Date
100+): Message {
101+ return {
102+ id,
103+ threadId,
104+ role: "system",
105+ content,
106+ createdAt: createdAt
107+ ? typeof createdAt === "string"
108+ ? new Date(createdAt)
109+ : createdAt
110+ : new Date(),
111+ model: null,
112+ maxPromptLength: null,
113+ generationTimeMs: null,
114+ toolCallCounts: null,
115+ };
116+}