refactor: update component styles and improve layout

- Adjusted button height in KnowledgeDropdown for better consistency.
- Modified margin and padding in KnowledgeFilterList for improved spacing.
- Refined message handling in ChatPage for cleaner code and better readability.
- Enhanced layout structure in KnowledgeSourcesPage and LayoutWrapper for better responsiveness and alignment.
- Updated various components to use consistent arrow function syntax for state updates.
This commit is contained in:
Deon Sanchez 2025-10-03 10:41:36 -06:00
parent c55b891968
commit 5b78cac7cb
7 changed files with 1313 additions and 1321 deletions

View file

@ -442,7 +442,7 @@ export function KnowledgeDropdown({
disabled={isLoading} disabled={isLoading}
className={cn( className={cn(
variant === "button" variant === "button"
? "rounded-lg h-12 px-4 flex items-center gap-2 bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" ? "rounded-lg h-10 px-4 flex items-center gap-2 bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
: "text-sm group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed", : "text-sm group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",
variant === "navigation" && active variant === "navigation" && active
? "bg-accent text-accent-foreground shadow-sm" ? "bg-accent text-accent-foreground shadow-sm"

View file

@ -67,7 +67,7 @@ export function KnowledgeFilterList({
<div className="flex-1 min-h-0 flex flex-col"> <div className="flex-1 min-h-0 flex flex-col">
<div className="px-3 flex-1 min-h-0 flex flex-col"> <div className="px-3 flex-1 min-h-0 flex flex-col">
<div className="flex-shrink-0"> <div className="flex-shrink-0">
<div className="flex items-center justify-between mb-3 ml-3 mr-2"> <div className="flex items-center justify-between mb-3 mr-2 ml-4">
<h3 className="text-xs font-medium text-muted-foreground"> <h3 className="text-xs font-medium text-muted-foreground">
Knowledge Filters Knowledge Filters
</h3> </h3>
@ -82,11 +82,11 @@ export function KnowledgeFilterList({
</div> </div>
<div className="overflow-y-auto scrollbar-hide space-y-1"> <div className="overflow-y-auto scrollbar-hide space-y-1">
{loading ? ( {loading ? (
<div className="text-[13px] text-muted-foreground p-2 ml-1"> <div className="text-[13px] text-muted-foreground p-2 ml-2">
Loading... Loading...
</div> </div>
) : filters.length === 0 ? ( ) : filters.length === 0 ? (
<div className="text-[13px] text-muted-foreground p-2 ml-1"> <div className="text-[13px] text-muted-foreground pb-2 pt-3 ml-4">
{searchQuery ? "No filters found" : "No saved filters"} {searchQuery ? "No filters found" : "No saved filters"}
</div> </div>
) : ( ) : (

View file

@ -232,7 +232,7 @@ function ChatPage() {
content: `🔄 Starting upload of **${file.name}**...`, content: `🔄 Starting upload of **${file.name}**...`,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, uploadStartMessage]); setMessages(prev => [...prev, uploadStartMessage]);
try { try {
const formData = new FormData(); const formData = new FormData();
@ -258,7 +258,7 @@ function ChatPage() {
"Upload failed with status:", "Upload failed with status:",
response.status, response.status,
"Response:", "Response:",
errorText, errorText
); );
throw new Error("Failed to process document"); throw new Error("Failed to process document");
} }
@ -284,7 +284,7 @@ function ChatPage() {
content: `⏳ Upload initiated for **${file.name}**. Processing in background... (Task ID: ${taskId})`, content: `⏳ Upload initiated for **${file.name}**. Processing in background... (Task ID: ${taskId})`,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev.slice(0, -1), pollingMessage]); setMessages(prev => [...prev.slice(0, -1), pollingMessage]);
} else if (response.ok) { } else if (response.ok) {
// Original flow: Direct response // Original flow: Direct response
@ -298,7 +298,7 @@ function ChatPage() {
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev.slice(0, -1), uploadMessage]); setMessages(prev => [...prev.slice(0, -1), uploadMessage]);
// Add file to conversation docs // Add file to conversation docs
if (result.filename) { if (result.filename) {
@ -307,7 +307,7 @@ function ChatPage() {
// Update the response ID for this endpoint // Update the response ID for this endpoint
if (result.response_id) { if (result.response_id) {
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[endpoint]: result.response_id, [endpoint]: result.response_id,
})); }));
@ -331,7 +331,7 @@ function ChatPage() {
content: `❌ Failed to process document. Please try again.`, content: `❌ Failed to process document. Please try again.`,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev.slice(0, -1), errorMessage]); setMessages(prev => [...prev.slice(0, -1), errorMessage]);
} finally { } finally {
setIsUploading(false); setIsUploading(false);
setLoading(false); setLoading(false);
@ -468,7 +468,7 @@ function ChatPage() {
console.log( console.log(
"Loading conversation with", "Loading conversation with",
conversationData.messages.length, conversationData.messages.length,
"messages", "messages"
); );
// Convert backend message format to frontend Message interface // Convert backend message format to frontend Message interface
const convertedMessages: Message[] = conversationData.messages.map( const convertedMessages: Message[] = conversationData.messages.map(
@ -596,7 +596,7 @@ function ChatPage() {
) === "string" ) === "string"
? toolCall.function?.arguments || toolCall.arguments ? toolCall.function?.arguments || toolCall.arguments
: JSON.stringify( : JSON.stringify(
toolCall.function?.arguments || toolCall.arguments, toolCall.function?.arguments || toolCall.arguments
), ),
result: toolCall.result, result: toolCall.result,
status: "completed", status: "completed",
@ -615,14 +615,14 @@ function ChatPage() {
} }
return message; return message;
}, }
); );
setMessages(convertedMessages); setMessages(convertedMessages);
lastLoadedConversationRef.current = conversationData.response_id; lastLoadedConversationRef.current = conversationData.response_id;
// Set the previous response ID for this conversation // Set the previous response ID for this conversation
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[conversationData.endpoint]: conversationData.response_id, [conversationData.endpoint]: conversationData.response_id,
})); }));
@ -664,7 +664,7 @@ function ChatPage() {
content: `🔄 Starting upload of **${filename}**...`, content: `🔄 Starting upload of **${filename}**...`,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, uploadStartMessage]); setMessages(prev => [...prev, uploadStartMessage]);
}; };
const handleFileUploaded = (event: CustomEvent) => { const handleFileUploaded = (event: CustomEvent) => {
@ -682,11 +682,11 @@ function ChatPage() {
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev.slice(0, -1), uploadMessage]); setMessages(prev => [...prev.slice(0, -1), uploadMessage]);
// Update the response ID for this endpoint // Update the response ID for this endpoint
if (result.response_id) { if (result.response_id) {
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[endpoint]: result.response_id, [endpoint]: result.response_id,
})); }));
@ -704,7 +704,7 @@ function ChatPage() {
console.log( console.log(
"Chat page received file upload error event:", "Chat page received file upload error event:",
filename, filename,
error, error
); );
// Replace the last message with error message // Replace the last message with error message
@ -713,48 +713,48 @@ function ChatPage() {
content: `❌ Upload failed for **${filename}**: ${error}`, content: `❌ Upload failed for **${filename}**: ${error}`,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev.slice(0, -1), errorMessage]); setMessages(prev => [...prev.slice(0, -1), errorMessage]);
}; };
window.addEventListener( window.addEventListener(
"fileUploadStart", "fileUploadStart",
handleFileUploadStart as EventListener, handleFileUploadStart as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploaded", "fileUploaded",
handleFileUploaded as EventListener, handleFileUploaded as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploadComplete", "fileUploadComplete",
handleFileUploadComplete as EventListener, handleFileUploadComplete as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploadError", "fileUploadError",
handleFileUploadError as EventListener, handleFileUploadError as EventListener
); );
return () => { return () => {
window.removeEventListener( window.removeEventListener(
"fileUploadStart", "fileUploadStart",
handleFileUploadStart as EventListener, handleFileUploadStart as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploaded", "fileUploaded",
handleFileUploaded as EventListener, handleFileUploaded as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploadComplete", "fileUploadComplete",
handleFileUploadComplete as EventListener, handleFileUploadComplete as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploadError", "fileUploadError",
handleFileUploadError as EventListener, handleFileUploadError as EventListener
); );
}; };
}, [endpoint, setPreviousResponseIds]); }, [endpoint, setPreviousResponseIds]);
const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery( const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery(
previousResponseIds[endpoint], previousResponseIds[endpoint]
); );
const handleSSEStream = async (userMessage: Message) => { const handleSSEStream = async (userMessage: Message) => {
@ -859,7 +859,7 @@ function ChatPage() {
console.log( console.log(
"Received chunk:", "Received chunk:",
chunk.type || chunk.object, chunk.type || chunk.object,
chunk, chunk
); );
// Extract response ID if present // Extract response ID if present
@ -875,14 +875,14 @@ function ChatPage() {
if (chunk.delta.function_call) { if (chunk.delta.function_call) {
console.log( console.log(
"Function call in delta:", "Function call in delta:",
chunk.delta.function_call, chunk.delta.function_call
); );
// Check if this is a new function call // Check if this is a new function call
if (chunk.delta.function_call.name) { if (chunk.delta.function_call.name) {
console.log( console.log(
"New function call:", "New function call:",
chunk.delta.function_call.name, chunk.delta.function_call.name
); );
const functionCall: FunctionCall = { const functionCall: FunctionCall = {
name: chunk.delta.function_call.name, name: chunk.delta.function_call.name,
@ -898,7 +898,7 @@ function ChatPage() {
else if (chunk.delta.function_call.arguments) { else if (chunk.delta.function_call.arguments) {
console.log( console.log(
"Function call arguments delta:", "Function call arguments delta:",
chunk.delta.function_call.arguments, chunk.delta.function_call.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
@ -910,14 +910,14 @@ function ChatPage() {
chunk.delta.function_call.arguments; chunk.delta.function_call.arguments;
console.log( console.log(
"Accumulated arguments:", "Accumulated arguments:",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
// Try to parse arguments if they look complete // Try to parse arguments if they look complete
if (lastFunctionCall.argumentsString.includes("}")) { if (lastFunctionCall.argumentsString.includes("}")) {
try { try {
const parsed = JSON.parse( const parsed = JSON.parse(
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
lastFunctionCall.arguments = parsed; lastFunctionCall.arguments = parsed;
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
@ -925,7 +925,7 @@ function ChatPage() {
} catch (e) { } catch (e) {
console.log( console.log(
"Arguments not yet complete or invalid JSON:", "Arguments not yet complete or invalid JSON:",
e, e
); );
} }
} }
@ -958,7 +958,7 @@ function ChatPage() {
else if (toolCall.function.arguments) { else if (toolCall.function.arguments) {
console.log( console.log(
"Tool call arguments delta:", "Tool call arguments delta:",
toolCall.function.arguments, toolCall.function.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[ currentFunctionCalls[
@ -972,7 +972,7 @@ function ChatPage() {
toolCall.function.arguments; toolCall.function.arguments;
console.log( console.log(
"Accumulated tool arguments:", "Accumulated tool arguments:",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
// Try to parse arguments if they look complete // Try to parse arguments if they look complete
@ -981,7 +981,7 @@ function ChatPage() {
) { ) {
try { try {
const parsed = JSON.parse( const parsed = JSON.parse(
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
lastFunctionCall.arguments = parsed; lastFunctionCall.arguments = parsed;
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
@ -989,7 +989,7 @@ function ChatPage() {
} catch (e) { } catch (e) {
console.log( console.log(
"Tool arguments not yet complete or invalid JSON:", "Tool arguments not yet complete or invalid JSON:",
e, e
); );
} }
} }
@ -1009,7 +1009,7 @@ function ChatPage() {
if (chunk.delta.finish_reason) { if (chunk.delta.finish_reason) {
console.log("Finish reason:", chunk.delta.finish_reason); console.log("Finish reason:", chunk.delta.finish_reason);
// Mark any pending function calls as completed // Mark any pending function calls as completed
currentFunctionCalls.forEach((fc) => { currentFunctionCalls.forEach(fc => {
if (fc.status === "pending" && fc.argumentsString) { if (fc.status === "pending" && fc.argumentsString) {
try { try {
fc.arguments = JSON.parse(fc.argumentsString); fc.arguments = JSON.parse(fc.argumentsString);
@ -1021,7 +1021,7 @@ function ChatPage() {
console.log( console.log(
"Error parsing function call on finish:", "Error parsing function call on finish:",
fc, fc,
e, e
); );
} }
} }
@ -1037,21 +1037,21 @@ function ChatPage() {
console.log( console.log(
"🟢 CREATING function call (added):", "🟢 CREATING function call (added):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name
); );
// Try to find an existing pending call to update (created by earlier deltas) // Try to find an existing pending call to update (created by earlier deltas)
let existing = currentFunctionCalls.find( let existing = currentFunctionCalls.find(
(fc) => fc.id === chunk.item.id, fc => fc.id === chunk.item.id
); );
if (!existing) { if (!existing) {
existing = [...currentFunctionCalls] existing = [...currentFunctionCalls]
.reverse() .reverse()
.find( .find(
(fc) => fc =>
fc.status === "pending" && fc.status === "pending" &&
!fc.id && !fc.id &&
fc.name === (chunk.item.tool_name || chunk.item.name), fc.name === (chunk.item.tool_name || chunk.item.name)
); );
} }
@ -1064,7 +1064,7 @@ function ChatPage() {
chunk.item.inputs || existing.arguments; chunk.item.inputs || existing.arguments;
console.log( console.log(
"🟢 UPDATED existing pending function call with id:", "🟢 UPDATED existing pending function call with id:",
existing.id, existing.id
); );
} else { } else {
const functionCall: FunctionCall = { const functionCall: FunctionCall = {
@ -1079,10 +1079,10 @@ function ChatPage() {
currentFunctionCalls.push(functionCall); currentFunctionCalls.push(functionCall);
console.log( console.log(
"🟢 Function calls now:", "🟢 Function calls now:",
currentFunctionCalls.map((fc) => ({ currentFunctionCalls.map(fc => ({
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
})), }))
); );
} }
} }
@ -1093,7 +1093,7 @@ function ChatPage() {
) { ) {
console.log( console.log(
"Function args delta (Realtime API):", "Function args delta (Realtime API):",
chunk.delta, chunk.delta
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
@ -1104,7 +1104,7 @@ function ChatPage() {
lastFunctionCall.argumentsString += chunk.delta || ""; lastFunctionCall.argumentsString += chunk.delta || "";
console.log( console.log(
"Accumulated arguments (Realtime API):", "Accumulated arguments (Realtime API):",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
} }
} }
@ -1115,26 +1115,26 @@ function ChatPage() {
) { ) {
console.log( console.log(
"Function args done (Realtime API):", "Function args done (Realtime API):",
chunk.arguments, chunk.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
if (lastFunctionCall) { if (lastFunctionCall) {
try { try {
lastFunctionCall.arguments = JSON.parse( lastFunctionCall.arguments = JSON.parse(
chunk.arguments || "{}", chunk.arguments || "{}"
); );
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
console.log( console.log(
"Parsed function arguments (Realtime API):", "Parsed function arguments (Realtime API):",
lastFunctionCall.arguments, lastFunctionCall.arguments
); );
} catch (e) { } catch (e) {
lastFunctionCall.arguments = { raw: chunk.arguments }; lastFunctionCall.arguments = { raw: chunk.arguments };
lastFunctionCall.status = "error"; lastFunctionCall.status = "error";
console.log( console.log(
"Error parsing function arguments (Realtime API):", "Error parsing function arguments (Realtime API):",
e, e
); );
} }
} }
@ -1148,29 +1148,29 @@ function ChatPage() {
console.log( console.log(
"🔵 UPDATING function call (done):", "🔵 UPDATING function call (done):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name
); );
console.log( console.log(
"🔵 Looking for existing function calls:", "🔵 Looking for existing function calls:",
currentFunctionCalls.map((fc) => ({ currentFunctionCalls.map(fc => ({
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
})), }))
); );
// Find existing function call by ID or name // Find existing function call by ID or name
const functionCall = currentFunctionCalls.find( const functionCall = currentFunctionCalls.find(
(fc) => fc =>
fc.id === chunk.item.id || fc.id === chunk.item.id ||
fc.name === chunk.item.tool_name || fc.name === chunk.item.tool_name ||
fc.name === chunk.item.name, fc.name === chunk.item.name
); );
if (functionCall) { if (functionCall) {
console.log( console.log(
"🔵 FOUND existing function call, updating:", "🔵 FOUND existing function call, updating:",
functionCall.id, functionCall.id,
functionCall.name, functionCall.name
); );
// Update existing function call with completion data // Update existing function call with completion data
functionCall.status = functionCall.status =
@ -1193,7 +1193,7 @@ function ChatPage() {
"🔴 WARNING: Could not find existing function call to update:", "🔴 WARNING: Could not find existing function call to update:",
chunk.item.id, chunk.item.id,
chunk.item.tool_name, chunk.item.tool_name,
chunk.item.name, chunk.item.name
); );
} }
} }
@ -1208,13 +1208,13 @@ function ChatPage() {
// Find existing function call by ID, or by name/type if ID not available // Find existing function call by ID, or by name/type if ID not available
const functionCall = currentFunctionCalls.find( const functionCall = currentFunctionCalls.find(
(fc) => fc =>
fc.id === chunk.item.id || fc.id === chunk.item.id ||
fc.name === chunk.item.tool_name || fc.name === chunk.item.tool_name ||
fc.name === chunk.item.name || fc.name === chunk.item.name ||
fc.name === chunk.item.type || fc.name === chunk.item.type ||
fc.name.includes(chunk.item.type.replace("_call", "")) || fc.name.includes(chunk.item.type.replace("_call", "")) ||
chunk.item.type.includes(fc.name), chunk.item.type.includes(fc.name)
); );
if (functionCall) { if (functionCall) {
@ -1258,24 +1258,24 @@ function ChatPage() {
"🟡 CREATING tool call (added):", "🟡 CREATING tool call (added):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name,
chunk.item.type, chunk.item.type
); );
// Dedupe by id or pending with same name // Dedupe by id or pending with same name
let existing = currentFunctionCalls.find( let existing = currentFunctionCalls.find(
(fc) => fc.id === chunk.item.id, fc => fc.id === chunk.item.id
); );
if (!existing) { if (!existing) {
existing = [...currentFunctionCalls] existing = [...currentFunctionCalls]
.reverse() .reverse()
.find( .find(
(fc) => fc =>
fc.status === "pending" && fc.status === "pending" &&
!fc.id && !fc.id &&
fc.name === fc.name ===
(chunk.item.tool_name || (chunk.item.tool_name ||
chunk.item.name || chunk.item.name ||
chunk.item.type), chunk.item.type)
); );
} }
@ -1291,7 +1291,7 @@ function ChatPage() {
chunk.item.inputs || existing.arguments; chunk.item.inputs || existing.arguments;
console.log( console.log(
"🟡 UPDATED existing pending tool call with id:", "🟡 UPDATED existing pending tool call with id:",
existing.id, existing.id
); );
} else { } else {
const functionCall = { const functionCall = {
@ -1308,11 +1308,11 @@ function ChatPage() {
currentFunctionCalls.push(functionCall); currentFunctionCalls.push(functionCall);
console.log( console.log(
"🟡 Function calls now:", "🟡 Function calls now:",
currentFunctionCalls.map((fc) => ({ currentFunctionCalls.map(fc => ({
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
type: fc.type, type: fc.type,
})), }))
); );
} }
} }
@ -1406,7 +1406,7 @@ function ChatPage() {
}; };
if (!controller.signal.aborted && thisStreamId === streamIdRef.current) { if (!controller.signal.aborted && thisStreamId === streamIdRef.current) {
setMessages((prev) => [...prev, finalMessage]); setMessages(prev => [...prev, finalMessage]);
setStreamingMessage(null); setStreamingMessage(null);
if (previousResponseIds[endpoint]) { if (previousResponseIds[endpoint]) {
cancelNudges(); cancelNudges();
@ -1419,7 +1419,7 @@ function ChatPage() {
!controller.signal.aborted && !controller.signal.aborted &&
thisStreamId === streamIdRef.current thisStreamId === streamIdRef.current
) { ) {
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[endpoint]: newResponseId, [endpoint]: newResponseId,
})); }));
@ -1447,7 +1447,7 @@ function ChatPage() {
"Sorry, I couldn't connect to the chat service. Please try again.", "Sorry, I couldn't connect to the chat service. Please try again.",
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, errorMessage]); setMessages(prev => [...prev, errorMessage]);
} }
}; };
@ -1460,7 +1460,7 @@ function ChatPage() {
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, userMessage]); setMessages(prev => [...prev, userMessage]);
setInput(""); setInput("");
setLoading(true); setLoading(true);
setIsFilterHighlighted(false); setIsFilterHighlighted(false);
@ -1526,14 +1526,14 @@ function ChatPage() {
content: result.response, content: result.response,
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, assistantMessage]); setMessages(prev => [...prev, assistantMessage]);
if (result.response_id) { if (result.response_id) {
cancelNudges(); cancelNudges();
} }
// Store the response ID if present for this endpoint // Store the response ID if present for this endpoint
if (result.response_id) { if (result.response_id) {
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[endpoint]: result.response_id, [endpoint]: result.response_id,
})); }));
@ -1554,7 +1554,7 @@ function ChatPage() {
content: "Sorry, I encountered an error. Please try again.", content: "Sorry, I encountered an error. Please try again.",
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, errorMessage]); setMessages(prev => [...prev, errorMessage]);
} }
} catch (error) { } catch (error) {
console.error("Chat error:", error); console.error("Chat error:", error);
@ -1564,7 +1564,7 @@ function ChatPage() {
"Sorry, I couldn't connect to the chat service. Please try again.", "Sorry, I couldn't connect to the chat service. Please try again.",
timestamp: new Date(), timestamp: new Date(),
}; };
setMessages((prev) => [...prev, errorMessage]); setMessages(prev => [...prev, errorMessage]);
} }
} }
@ -1577,7 +1577,7 @@ function ChatPage() {
}; };
const toggleFunctionCall = (functionCallId: string) => { const toggleFunctionCall = (functionCallId: string) => {
setExpandedFunctionCalls((prev) => { setExpandedFunctionCalls(prev => {
const newSet = new Set(prev); const newSet = new Set(prev);
if (newSet.has(functionCallId)) { if (newSet.has(functionCallId)) {
newSet.delete(functionCallId); newSet.delete(functionCallId);
@ -1590,7 +1590,7 @@ function ChatPage() {
const handleForkConversation = ( const handleForkConversation = (
messageIndex: number, messageIndex: number,
event?: React.MouseEvent, event?: React.MouseEvent
) => { ) => {
// Prevent any default behavior and stop event propagation // Prevent any default behavior and stop event propagation
if (event) { if (event) {
@ -1634,7 +1634,7 @@ function ChatPage() {
// Set the response_id we want to continue from as the previous response ID // Set the response_id we want to continue from as the previous response ID
// This tells the backend to continue the conversation from this point // This tells the backend to continue the conversation from this point
setPreviousResponseIds((prev) => ({ setPreviousResponseIds(prev => ({
...prev, ...prev,
[endpoint]: responseIdToForkFrom, [endpoint]: responseIdToForkFrom,
})); }));
@ -1655,7 +1655,7 @@ function ChatPage() {
const renderFunctionCalls = ( const renderFunctionCalls = (
functionCalls: FunctionCall[], functionCalls: FunctionCall[],
messageIndex?: number, messageIndex?: number
) => { ) => {
if (!functionCalls || functionCalls.length === 0) return null; if (!functionCalls || functionCalls.length === 0) return null;
@ -1905,8 +1905,8 @@ function ChatPage() {
} }
if (isFilterDropdownOpen) { if (isFilterDropdownOpen) {
const filteredFilters = availableFilters.filter((filter) => const filteredFilters = availableFilters.filter(filter =>
filter.name.toLowerCase().includes(filterSearchTerm.toLowerCase()), filter.name.toLowerCase().includes(filterSearchTerm.toLowerCase())
); );
if (e.key === "Escape") { if (e.key === "Escape") {
@ -1923,16 +1923,16 @@ function ChatPage() {
if (e.key === "ArrowDown") { if (e.key === "ArrowDown") {
e.preventDefault(); e.preventDefault();
setSelectedFilterIndex((prev) => setSelectedFilterIndex(prev =>
prev < filteredFilters.length - 1 ? prev + 1 : 0, prev < filteredFilters.length - 1 ? prev + 1 : 0
); );
return; return;
} }
if (e.key === "ArrowUp") { if (e.key === "ArrowUp") {
e.preventDefault(); e.preventDefault();
setSelectedFilterIndex((prev) => setSelectedFilterIndex(prev =>
prev > 0 ? prev - 1 : filteredFilters.length - 1, prev > 0 ? prev - 1 : filteredFilters.length - 1
); );
return; return;
} }
@ -2029,7 +2029,7 @@ function ChatPage() {
// Get button position for popover anchoring // Get button position for popover anchoring
const button = document.querySelector( const button = document.querySelector(
"[data-filter-button]", "[data-filter-button]"
) as HTMLElement; ) as HTMLElement;
if (button) { if (button) {
const rect = button.getBoundingClientRect(); const rect = button.getBoundingClientRect();
@ -2046,7 +2046,7 @@ function ChatPage() {
return ( return (
<div <div
className={`fixed inset-0 md:left-72 top-[53px] flex flex-col transition-all duration-300 ${ className={`fixed inset-0 md:left-72 top-[40px] flex flex-col transition-all duration-300 container mx-auto ${
isMenuOpen && isPanelOpen isMenuOpen && isPanelOpen
? "md:right-[704px]" // Both open: 384px (menu) + 320px (KF panel) ? "md:right-[704px]" // Both open: 384px (menu) + 320px (KF panel)
: isMenuOpen : isMenuOpen
@ -2164,14 +2164,14 @@ function ChatPage() {
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
{renderFunctionCalls( {renderFunctionCalls(
message.functionCalls || [], message.functionCalls || [],
index, index
)} )}
<MarkdownRenderer chatMessage={message.content} /> <MarkdownRenderer chatMessage={message.content} />
</div> </div>
{endpoint === "chat" && ( {endpoint === "chat" && (
<div className="flex-shrink-0 ml-2"> <div className="flex-shrink-0 ml-2">
<button <button
onClick={(e) => handleForkConversation(index, e)} onClick={e => handleForkConversation(index, e)}
className="opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground" className="opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground"
title="Fork conversation from here" title="Fork conversation from here"
> >
@ -2193,7 +2193,7 @@ function ChatPage() {
<div className="flex-1"> <div className="flex-1">
{renderFunctionCalls( {renderFunctionCalls(
streamingMessage.functionCalls, streamingMessage.functionCalls,
messages.length, messages.length
)} )}
<MarkdownRenderer <MarkdownRenderer
chatMessage={streamingMessage.content} chatMessage={streamingMessage.content}
@ -2235,8 +2235,8 @@ function ChatPage() {
)} )}
{/* Input Area - Fixed at bottom */} {/* Input Area - Fixed at bottom */}
<div className="flex-shrink-0 p-6 pb-8 pt-4 flex justify-center"> <div className="pb-8 pt-4 flex px-6">
<div className="w-full max-w-[75%]"> <div className="w-full">
<form onSubmit={handleSubmit} className="relative"> <form onSubmit={handleSubmit} className="relative">
<div className="relative w-full bg-muted/20 rounded-lg border border-border/50 focus-within:ring-1 focus-within:ring-ring"> <div className="relative w-full bg-muted/20 rounded-lg border border-border/50 focus-within:ring-1 focus-within:ring-ring">
{selectedFilter && ( {selectedFilter && (
@ -2260,13 +2260,16 @@ function ChatPage() {
</span> </span>
</div> </div>
)} )}
<div className="relative" style={{height: `${textareaHeight + 60}px`}}> <div
className="relative"
style={{ height: `${textareaHeight + 60}px` }}
>
<TextareaAutosize <TextareaAutosize
ref={inputRef} ref={inputRef}
value={input} value={input}
onChange={onChange} onChange={onChange}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
onHeightChange={(height) => setTextareaHeight(height)} onHeightChange={height => setTextareaHeight(height)}
maxRows={7} maxRows={7}
minRows={2} minRows={2}
placeholder="Type to ask a question..." placeholder="Type to ask a question..."
@ -2279,10 +2282,9 @@ function ChatPage() {
{/* Safe area at bottom for buttons */} {/* Safe area at bottom for buttons */}
<div <div
className="absolute bottom-0 left-0 right-0 bg-transparent pointer-events-none" className="absolute bottom-0 left-0 right-0 bg-transparent pointer-events-none"
style={{ height: '60px' }} style={{ height: "60px" }}
/> />
</div> </div>
</div> </div>
<input <input
ref={fileInputRef} ref={fileInputRef}
@ -2296,7 +2298,7 @@ function ChatPage() {
variant="outline" variant="outline"
size="iconSm" size="iconSm"
className="absolute bottom-3 left-3 h-8 w-8 p-0 rounded-full hover:bg-muted/50" className="absolute bottom-3 left-3 h-8 w-8 p-0 rounded-full hover:bg-muted/50"
onMouseDown={(e) => { onMouseDown={e => {
e.preventDefault(); e.preventDefault();
}} }}
onClick={onAtClick} onClick={onAtClick}
@ -2306,7 +2308,7 @@ function ChatPage() {
</Button> </Button>
<Popover <Popover
open={isFilterDropdownOpen} open={isFilterDropdownOpen}
onOpenChange={(open) => { onOpenChange={open => {
setIsFilterDropdownOpen(open); setIsFilterDropdownOpen(open);
}} }}
> >
@ -2331,7 +2333,7 @@ function ChatPage() {
align="start" align="start"
sideOffset={6} sideOffset={6}
alignOffset={-18} alignOffset={-18}
onOpenAutoFocus={(e) => { onOpenAutoFocus={e => {
// Prevent auto focus on the popover content // Prevent auto focus on the popover content
e.preventDefault(); e.preventDefault();
// Keep focus on the input // Keep focus on the input
@ -2364,10 +2366,10 @@ function ChatPage() {
</button> </button>
)} )}
{availableFilters {availableFilters
.filter((filter) => .filter(filter =>
filter.name filter.name
.toLowerCase() .toLowerCase()
.includes(filterSearchTerm.toLowerCase()), .includes(filterSearchTerm.toLowerCase())
) )
.map((filter, index) => ( .map((filter, index) => (
<button <button
@ -2393,10 +2395,10 @@ function ChatPage() {
)} )}
</button> </button>
))} ))}
{availableFilters.filter((filter) => {availableFilters.filter(filter =>
filter.name filter.name
.toLowerCase() .toLowerCase()
.includes(filterSearchTerm.toLowerCase()), .includes(filterSearchTerm.toLowerCase())
).length === 0 && ).length === 0 &&
filterSearchTerm && ( filterSearchTerm && (
<div className="px-2 py-3 text-sm text-muted-foreground"> <div className="px-2 py-3 text-sm text-muted-foreground">

View file

@ -60,7 +60,7 @@ function ChunksPageContent() {
setChunksFilteredByQuery(chunks); setChunksFilteredByQuery(chunks);
} else { } else {
setChunksFilteredByQuery( setChunksFilteredByQuery(
chunks.filter((chunk) => chunks.filter(chunk =>
chunk.text.toLowerCase().includes(queryInputText.toLowerCase()) chunk.text.toLowerCase().includes(queryInputText.toLowerCase())
) )
); );
@ -103,7 +103,7 @@ function ChunksPageContent() {
const handleChunkCardCheckboxChange = useCallback( const handleChunkCardCheckboxChange = useCallback(
(index: number) => { (index: number) => {
setSelectedChunks((prevSelected) => { setSelectedChunks(prevSelected => {
const newSelected = new Set(prevSelected); const newSelected = new Set(prevSelected);
if (newSelected.has(index)) { if (newSelected.has(index)) {
newSelected.delete(index); newSelected.delete(index);
@ -132,7 +132,7 @@ function ChunksPageContent() {
return ( return (
<div <div
className={`fixed inset-0 md:left-72 top-[53px] flex flex-row transition-all duration-300 ${ className={`fixed inset-0 md:left-72 top-[40px] flex flex-row transition-all duration-300 container mx-auto ${
isMenuOpen && isPanelOpen isMenuOpen && isPanelOpen
? "md:right-[704px]" ? "md:right-[704px]"
: // Both open: 384px (menu) + 320px (KF panel) : // Both open: 384px (menu) + 320px (KF panel)
@ -166,7 +166,7 @@ function ChunksPageContent() {
type="text" type="text"
defaultValue={parsedFilterData?.query} defaultValue={parsedFilterData?.query}
value={queryInputText} value={queryInputText}
onChange={(e) => setQueryInputText(e.target.value)} onChange={e => setQueryInputText(e.target.value)}
placeholder="Search chunks..." placeholder="Search chunks..."
/> />
</div> </div>
@ -174,7 +174,7 @@ function ChunksPageContent() {
<Checkbox <Checkbox
id="selectAllChunks" id="selectAllChunks"
checked={selectAll} checked={selectAll}
onCheckedChange={(handleSelectAll) => onCheckedChange={handleSelectAll =>
setSelectAll(!!handleSelectAll) setSelectAll(!!handleSelectAll)
} }
/> />

View file

@ -64,7 +64,7 @@ function SearchPage() {
}; };
// Convert TaskFiles to File format and merge with backend results // Convert TaskFiles to File format and merge with backend results
const taskFilesAsFiles: File[] = taskFiles.map((taskFile) => { const taskFilesAsFiles: File[] = taskFiles.map(taskFile => {
return { return {
filename: taskFile.filename, filename: taskFile.filename,
mimetype: taskFile.mimetype, mimetype: taskFile.mimetype,
@ -77,11 +77,11 @@ function SearchPage() {
const backendFiles = data as File[]; const backendFiles = data as File[];
const filteredTaskFiles = taskFilesAsFiles.filter((taskFile) => { const filteredTaskFiles = taskFilesAsFiles.filter(taskFile => {
return ( return (
taskFile.status !== "active" && taskFile.status !== "active" &&
!backendFiles.some( !backendFiles.some(
(backendFile) => backendFile.filename === taskFile.filename backendFile => backendFile.filename === taskFile.filename
) )
); );
}); });
@ -123,7 +123,7 @@ function SearchPage() {
{ {
field: "size", field: "size",
headerName: "Size", headerName: "Size",
valueFormatter: (params) => valueFormatter: params =>
params.value ? `${Math.round(params.value / 1024)} KB` : "-", params.value ? `${Math.round(params.value / 1024)} KB` : "-",
}, },
{ {
@ -133,18 +133,17 @@ function SearchPage() {
{ {
field: "owner", field: "owner",
headerName: "Owner", headerName: "Owner",
valueFormatter: (params) => valueFormatter: params =>
params.data?.owner_name || params.data?.owner_email || "—", params.data?.owner_name || params.data?.owner_email || "—",
}, },
{ {
field: "chunkCount", field: "chunkCount",
headerName: "Chunks", headerName: "Chunks",
valueFormatter: (params) => params.data?.chunkCount?.toString() || "-", valueFormatter: params => params.data?.chunkCount?.toString() || "-",
}, },
{ {
field: "avgScore", field: "avgScore",
headerName: "Avg score", headerName: "Avg score",
initialFlex: 0.5,
cellRenderer: ({ value }: CustomCellRendererProps<File>) => { cellRenderer: ({ value }: CustomCellRendererProps<File>) => {
return ( return (
<span className="text-xs text-accent-emerald-foreground bg-accent-emerald px-2 py-1 rounded"> <span className="text-xs text-accent-emerald-foreground bg-accent-emerald px-2 py-1 rounded">
@ -201,7 +200,7 @@ function SearchPage() {
try { try {
// Delete each file individually since the API expects one filename at a time // Delete each file individually since the API expects one filename at a time
const deletePromises = selectedRows.map((row) => const deletePromises = selectedRows.map(row =>
deleteDocumentMutation.mutateAsync({ filename: row.filename }) deleteDocumentMutation.mutateAsync({ filename: row.filename })
); );
@ -230,7 +229,7 @@ function SearchPage() {
return ( return (
<div <div
className={`fixed inset-0 md:left-72 top-[53px] flex flex-col transition-all duration-300 ${ className={`fixed inset-0 md:left-72 top-[40px] flex flex-col transition-all duration-300 container mx-auto ${
isMenuOpen && isPanelOpen isMenuOpen && isPanelOpen
? "md:right-[704px]" ? "md:right-[704px]"
: // Both open: 384px (menu) + 320px (KF panel) : // Both open: 384px (menu) + 320px (KF panel)
@ -244,7 +243,7 @@ function SearchPage() {
}`} }`}
> >
<div className="flex-1 flex flex-col min-h-0 px-6 py-6"> <div className="flex-1 flex flex-col min-h-0 px-6 py-6">
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6 h-10">
<h2 className="text-lg font-semibold">Project Knowledge</h2> <h2 className="text-lg font-semibold">Project Knowledge</h2>
<KnowledgeDropdown variant="button" /> <KnowledgeDropdown variant="button" />
</div> </div>
@ -312,8 +311,9 @@ function SearchPage() {
)} )}
</form> </form>
</div> </div>
<div className="flex-1 min-h-0 max-h-[700px] overflow-hidden h-full">
<AgGridReact <AgGridReact
className="w-full overflow-auto" className="h-full w-full"
columnDefs={columnDefs} columnDefs={columnDefs}
defaultColDef={defaultColDef} defaultColDef={defaultColDef}
loading={isFetching} loading={isFetching}
@ -322,7 +322,7 @@ function SearchPage() {
rowSelection="multiple" rowSelection="multiple"
rowMultiSelectWithClick={false} rowMultiSelectWithClick={false}
suppressRowClickSelection={true} suppressRowClickSelection={true}
getRowId={(params) => params.data.filename} getRowId={params => params.data.filename}
domLayout="normal" domLayout="normal"
onSelectionChanged={onSelectionChanged} onSelectionChanged={onSelectionChanged}
noRowsOverlayComponent={() => ( noRowsOverlayComponent={() => (
@ -337,6 +337,7 @@ function SearchPage() {
)} )}
/> />
</div> </div>
</div>
{/* Bulk Delete Confirmation Dialog */} {/* Bulk Delete Confirmation Dialog */}
<DeleteConfirmationDialog <DeleteConfirmationDialog
@ -350,7 +351,7 @@ function SearchPage() {
}? This will remove all chunks and data associated with these documents. This action cannot be undone. }? This will remove all chunks and data associated with these documents. This action cannot be undone.
Documents to be deleted: Documents to be deleted:
${selectedRows.map((row) => `${row.filename}`).join("\n")}`} ${selectedRows.map(row => `${row.filename}`).join("\n")}`}
confirmText="Delete All" confirmText="Delete All"
onConfirm={handleBulkDelete} onConfirm={handleBulkDelete}
isLoading={deleteDocumentMutation.isPending} isLoading={deleteDocumentMutation.isPending}

View file

@ -164,7 +164,7 @@ function KnowledgeSourcesPage() {
{ {
enabled: enabled:
(isAuthenticated || isNoAuthMode) && currentProvider === "openai", (isAuthenticated || isNoAuthMode) && currentProvider === "openai",
}, }
); );
const { data: ollamaModelsData } = useGetOllamaModelsQuery( const { data: ollamaModelsData } = useGetOllamaModelsQuery(
@ -172,7 +172,7 @@ function KnowledgeSourcesPage() {
{ {
enabled: enabled:
(isAuthenticated || isNoAuthMode) && currentProvider === "ollama", (isAuthenticated || isNoAuthMode) && currentProvider === "ollama",
}, }
); );
const { data: ibmModelsData } = useGetIBMModelsQuery( const { data: ibmModelsData } = useGetIBMModelsQuery(
@ -180,7 +180,7 @@ function KnowledgeSourcesPage() {
{ {
enabled: enabled:
(isAuthenticated || isNoAuthMode) && currentProvider === "watsonx", (isAuthenticated || isNoAuthMode) && currentProvider === "watsonx",
}, }
); );
// Select the appropriate models data based on provider // Select the appropriate models data based on provider
@ -198,7 +198,7 @@ function KnowledgeSourcesPage() {
onSuccess: () => { onSuccess: () => {
console.log("Setting updated successfully"); console.log("Setting updated successfully");
}, },
onError: (error) => { onError: error => {
console.error("Failed to update setting:", error.message); console.error("Failed to update setting:", error.message);
}, },
}); });
@ -208,7 +208,7 @@ function KnowledgeSourcesPage() {
(variables: Parameters<typeof updateFlowSettingMutation.mutate>[0]) => { (variables: Parameters<typeof updateFlowSettingMutation.mutate>[0]) => {
updateFlowSettingMutation.mutate(variables); updateFlowSettingMutation.mutate(variables);
}, },
500, 500
); );
// Sync system prompt state with settings data // Sync system prompt state with settings data
@ -333,8 +333,8 @@ function KnowledgeSourcesPage() {
// Initialize connectors list with metadata from backend // Initialize connectors list with metadata from backend
const initialConnectors = connectorTypes const initialConnectors = connectorTypes
.filter((type) => connectorsResult.connectors[type].available) // Only show available connectors .filter(type => connectorsResult.connectors[type].available) // Only show available connectors
.map((type) => ({ .map(type => ({
id: type, id: type,
name: connectorsResult.connectors[type].name, name: connectorsResult.connectors[type].name,
description: connectorsResult.connectors[type].description, description: connectorsResult.connectors[type].description,
@ -353,20 +353,20 @@ function KnowledgeSourcesPage() {
const data = await response.json(); const data = await response.json();
const connections = data.connections || []; const connections = data.connections || [];
const activeConnection = connections.find( const activeConnection = connections.find(
(conn: Connection) => conn.is_active, (conn: Connection) => conn.is_active
); );
const isConnected = activeConnection !== undefined; const isConnected = activeConnection !== undefined;
setConnectors((prev) => setConnectors(prev =>
prev.map((c) => prev.map(c =>
c.type === connectorType c.type === connectorType
? { ? {
...c, ...c,
status: isConnected ? "connected" : "not_connected", status: isConnected ? "connected" : "not_connected",
connectionId: activeConnection?.connection_id, connectionId: activeConnection?.connection_id,
} }
: c, : c
), )
); );
} }
} }
@ -377,7 +377,7 @@ function KnowledgeSourcesPage() {
const handleConnect = async (connector: Connector) => { const handleConnect = async (connector: Connector) => {
setIsConnecting(connector.id); setIsConnecting(connector.id);
setSyncResults((prev) => ({ ...prev, [connector.id]: null })); setSyncResults(prev => ({ ...prev, [connector.id]: null }));
try { try {
// Use the shared auth callback URL, same as connectors page // Use the shared auth callback URL, same as connectors page
@ -409,7 +409,7 @@ function KnowledgeSourcesPage() {
`response_type=code&` + `response_type=code&` +
`scope=${result.oauth_config.scopes.join(" ")}&` + `scope=${result.oauth_config.scopes.join(" ")}&` +
`redirect_uri=${encodeURIComponent( `redirect_uri=${encodeURIComponent(
result.oauth_config.redirect_uri, result.oauth_config.redirect_uri
)}&` + )}&` +
`access_type=offline&` + `access_type=offline&` +
`prompt=consent&` + `prompt=consent&` +
@ -517,9 +517,9 @@ function KnowledgeSourcesPage() {
// Watch for task completions and refresh stats // Watch for task completions and refresh stats
useEffect(() => { useEffect(() => {
// Find newly completed tasks by comparing with previous state // Find newly completed tasks by comparing with previous state
const newlyCompletedTasks = tasks.filter((task) => { const newlyCompletedTasks = tasks.filter(task => {
const wasCompleted = const wasCompleted =
prevTasks.find((prev) => prev.task_id === task.task_id)?.status === prevTasks.find(prev => prev.task_id === task.task_id)?.status ===
"completed"; "completed";
return task.status === "completed" && !wasCompleted; return task.status === "completed" && !wasCompleted;
}); });
@ -542,7 +542,7 @@ function KnowledgeSourcesPage() {
const handleEditInLangflow = ( const handleEditInLangflow = (
flowType: "chat" | "ingest", flowType: "chat" | "ingest",
closeDialog: () => void, closeDialog: () => void
) => { ) => {
// Select the appropriate flow ID and edit URL based on flow type // Select the appropriate flow ID and edit URL based on flow type
const targetFlowId = const targetFlowId =
@ -573,7 +573,7 @@ function KnowledgeSourcesPage() {
fetch(`/api/reset-flow/retrieval`, { fetch(`/api/reset-flow/retrieval`, {
method: "POST", method: "POST",
}) })
.then((response) => { .then(response => {
if (response.ok) { if (response.ok) {
return response.json(); return response.json();
} }
@ -586,7 +586,7 @@ function KnowledgeSourcesPage() {
handleModelChange(DEFAULT_AGENT_SETTINGS.llm_model); handleModelChange(DEFAULT_AGENT_SETTINGS.llm_model);
closeDialog(); // Close after successful completion closeDialog(); // Close after successful completion
}) })
.catch((error) => { .catch(error => {
console.error("Error restoring retrieval flow:", error); console.error("Error restoring retrieval flow:", error);
closeDialog(); // Close even on error (could show error toast instead) closeDialog(); // Close even on error (could show error toast instead)
}); });
@ -596,7 +596,7 @@ function KnowledgeSourcesPage() {
fetch(`/api/reset-flow/ingest`, { fetch(`/api/reset-flow/ingest`, {
method: "POST", method: "POST",
}) })
.then((response) => { .then(response => {
if (response.ok) { if (response.ok) {
return response.json(); return response.json();
} }
@ -611,20 +611,18 @@ function KnowledgeSourcesPage() {
setPictureDescriptions(false); setPictureDescriptions(false);
closeDialog(); // Close after successful completion closeDialog(); // Close after successful completion
}) })
.catch((error) => { .catch(error => {
console.error("Error restoring ingest flow:", error); console.error("Error restoring ingest flow:", error);
closeDialog(); // Close even on error (could show error toast instead) closeDialog(); // Close even on error (could show error toast instead)
}); });
}; };
return ( return (
<div className="space-y-8"> <div className="space-y-8 container mx-auto">
{/* Connectors Section */} {/* Connectors Section */}
<div className="space-y-6"> <div className="space-y-6">
<div> <div className="flex items-center justify-between mb-6 h-10">
<h2 className="text-lg font-semibold tracking-tight mb-2"> <h2 className="text-lg font-semibold">Cloud Connectors</h2>
Cloud Connectors
</h2>
</div> </div>
{/* Conditional Sync Settings or No-Auth Message */} {/* Conditional Sync Settings or No-Auth Message */}
@ -709,10 +707,8 @@ function KnowledgeSourcesPage() {
{/* Connectors Grid */} {/* Connectors Grid */}
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3"> <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{DEFAULT_CONNECTORS.map((connector) => { {DEFAULT_CONNECTORS.map(connector => {
const actualConnector = connectors.find( const actualConnector = connectors.find(c => c.id === connector.id);
(c) => c.id === connector.id,
);
return ( return (
<Card key={connector.id} className="relative flex flex-col"> <Card key={connector.id} className="relative flex flex-col">
<CardHeader> <CardHeader>
@ -855,7 +851,7 @@ function KnowledgeSourcesPage() {
} }
confirmText="Proceed" confirmText="Proceed"
confirmIcon={<ArrowUpRight />} confirmIcon={<ArrowUpRight />}
onConfirm={(closeDialog) => onConfirm={closeDialog =>
handleEditInLangflow("chat", closeDialog) handleEditInLangflow("chat", closeDialog)
} }
variant="warning" variant="warning"
@ -874,7 +870,11 @@ function KnowledgeSourcesPage() {
> >
<ModelSelector <ModelSelector
options={modelsData?.language_models || []} options={modelsData?.language_models || []}
noOptionsPlaceholder={modelsData ? "No language models detected." : "Loading models..."} noOptionsPlaceholder={
modelsData
? "No language models detected."
: "Loading models..."
}
icon={<OpenAILogo className="w-4 h-4" />} icon={<OpenAILogo className="w-4 h-4" />}
value={modelsData ? settings.agent?.llm_model || "" : ""} value={modelsData ? settings.agent?.llm_model || "" : ""}
onValueChange={handleModelChange} onValueChange={handleModelChange}
@ -887,7 +887,7 @@ function KnowledgeSourcesPage() {
id="system-prompt" id="system-prompt"
placeholder="Enter your agent instructions here..." placeholder="Enter your agent instructions here..."
value={systemPrompt} value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)} onChange={e => setSystemPrompt(e.target.value)}
rows={6} rows={6}
className={`resize-none ${ className={`resize-none ${
systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
@ -1001,7 +1001,7 @@ function KnowledgeSourcesPage() {
confirmText="Proceed" confirmText="Proceed"
confirmIcon={<ArrowUpRight />} confirmIcon={<ArrowUpRight />}
variant="warning" variant="warning"
onConfirm={(closeDialog) => onConfirm={closeDialog =>
handleEditInLangflow("ingest", closeDialog) handleEditInLangflow("ingest", closeDialog)
} }
/> />
@ -1021,8 +1021,7 @@ function KnowledgeSourcesPage() {
disabled={true} disabled={true}
value={ value={
settings.knowledge?.embedding_model || settings.knowledge?.embedding_model ||
modelsData?.embedding_models?.find((m) => m.default) modelsData?.embedding_models?.find(m => m.default)?.value ||
?.value ||
"text-embedding-ada-002" "text-embedding-ada-002"
} }
onValueChange={handleEmbeddingModelChange} onValueChange={handleEmbeddingModelChange}
@ -1058,7 +1057,7 @@ function KnowledgeSourcesPage() {
type="number" type="number"
min="1" min="1"
value={chunkSize} value={chunkSize}
onChange={(e) => handleChunkSizeChange(e.target.value)} onChange={e => handleChunkSizeChange(e.target.value)}
className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
/> />
<div className="absolute inset-y-0 right-0 flex items-center"> <div className="absolute inset-y-0 right-0 flex items-center">
@ -1101,7 +1100,7 @@ function KnowledgeSourcesPage() {
type="number" type="number"
min="0" min="0"
value={chunkOverlap} value={chunkOverlap}
onChange={(e) => handleChunkOverlapChange(e.target.value)} onChange={e => handleChunkOverlapChange(e.target.value)}
className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
/> />
<div className="absolute inset-y-0 right-0 flex items-center"> <div className="absolute inset-y-0 right-0 flex items-center">
@ -1116,7 +1115,7 @@ function KnowledgeSourcesPage() {
size="iconSm" size="iconSm"
onClick={() => onClick={() =>
handleChunkOverlapChange( handleChunkOverlapChange(
(chunkOverlap + 1).toString(), (chunkOverlap + 1).toString()
) )
} }
> >
@ -1129,7 +1128,7 @@ function KnowledgeSourcesPage() {
size="iconSm" size="iconSm"
onClick={() => onClick={() =>
handleChunkOverlapChange( handleChunkOverlapChange(
(chunkOverlap - 1).toString(), (chunkOverlap - 1).toString()
) )
} }
> >

View file

@ -11,7 +11,6 @@ import { KnowledgeFilterPanel } from "@/components/knowledge-filter-panel";
import Logo from "@/components/logo/logo"; import Logo from "@/components/logo/logo";
import { Navigation } from "@/components/navigation"; import { Navigation } from "@/components/navigation";
import { TaskNotificationMenu } from "@/components/task-notification-menu"; import { TaskNotificationMenu } from "@/components/task-notification-menu";
import { Button } from "@/components/ui/button";
import { UserNav } from "@/components/user-nav"; import { UserNav } from "@/components/user-nav";
import { useAuth } from "@/contexts/auth-context"; import { useAuth } from "@/contexts/auth-context";
import { useChat } from "@/contexts/chat-context"; import { useChat } from "@/contexts/chat-context";
@ -52,10 +51,6 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
const authPaths = ["/login", "/auth/callback", "/onboarding"]; const authPaths = ["/login", "/auth/callback", "/onboarding"];
const isAuthPage = authPaths.includes(pathname); const isAuthPage = authPaths.includes(pathname);
// List of paths with smaller max-width
const smallWidthPaths = ["/settings", "/settings/connector/new"];
const isSmallWidthPath = smallWidthPaths.includes(pathname);
// Calculate active tasks for the bell icon // Calculate active tasks for the bell icon
const activeTasks = tasks.filter( const activeTasks = tasks.filter(
task => task =>
@ -145,12 +140,7 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
"md:pr-0" // Neither open: 24px "md:pr-0" // Neither open: 24px
}`} }`}
> >
<div <div className={cn("pb-6 pt-6 lg:pb-8 px-4 lg:px-6 container mx-auto")}>
className={cn(
"py-6 lg:py-8 px-4 lg:px-6",
isSmallWidthPath ? "max-w-[850px]" : "container"
)}
>
{children} {children}
</div> </div>
</main> </main>