Repository navigation
Chat page add SystemPrompt and Authorization Textbox - #180
Conversation
Chat Add SystemPrompt and Authorization Textbox. SystemPrompt is saved to database Authorization textbox value is passthrough to the Rest API
Reviewer's GuideThis PR enhances the Chat page by adding a per-user system prompt editor and an authorization token input, wiring them through the message pipeline and MCP service, introducing frontend services and backend persistence for system prompts, and sanitizing tool names for consistent tool calls. Sequence diagram for saving and loading System PromptsequenceDiagram
actor User
participant ChatPage as Chat Page (Frontend)
participant SystemPromptAPI as SystemPrompt API (Backend)
participant DB as Database
User->>ChatPage: Open Chat page
ChatPage->>SystemPromptAPI: GET /chat/systemprompt
SystemPromptAPI->>DB: GetSystemPrompt(userID)
DB-->>SystemPromptAPI: SystemPrompt
SystemPromptAPI-->>ChatPage: { prompt }
User->>ChatPage: Edit and Save System Prompt
ChatPage->>SystemPromptAPI: PUT /chat/systemprompt { prompt }
SystemPromptAPI->>DB: SaveSystemPrompt(userID, prompt)
DB-->>SystemPromptAPI: OK
SystemPromptAPI-->>ChatPage: { success: true }
Sequence diagram for sending chat message with System Prompt and Authorization TokensequenceDiagram
actor User
participant ChatPage as Chat Page (Frontend)
participant LLMService as LLM Chat Service
participant MCPService as MCP Service
participant MCPServer as MCP Server
User->>ChatPage: Enter message, System Prompt, Auth Token
ChatPage->>LLMService: sendMessage(..., systemPrompt, authToken)
LLMService->>MCPService: connect(..., authToken)
MCPService->>MCPServer: Connect with Authorization header
LLMService->>MCPService: getTools(...)
MCPService->>MCPServer: Request tools (with Auth header)
LLMService->>MCPService: send message (with systemPrompt)
MCPService->>MCPServer: Forward message (with systemPrompt, Auth header)
MCPServer-->>MCPService: LLM response
MCPService-->>LLMService: LLM response
LLMService-->>ChatPage: Display response
ER diagram for new SystemPrompt tableerDiagram
USER ||--o| SYSTEM_PROMPT : has
SYSTEM_PROMPT {
uint UserID PK "Primary key, foreign key to User.ID"
string Prompt "System prompt text"
time UpdatedAt "Last update time"
}
Class diagram for SystemPrompt backend model and database interfaceclassDiagram
class SystemPrompt {
+uint UserID
+string Prompt
+time.Time UpdatedAt
}
class Database {
+GetSystemPrompt(ctx, userID) string
+SaveSystemPrompt(ctx, userID, prompt) error
}
Database <|.. MySQL
Database <|.. Postgres
Database <|.. SQLite
MySQL : +GetSystemPrompt(ctx, userID) string
MySQL : +SaveSystemPrompt(ctx, userID, prompt) error
Postgres : +GetSystemPrompt(ctx, userID) string
Postgres : +SaveSystemPrompt(ctx, userID, prompt) error
SQLite : +GetSystemPrompt(ctx, userID) string
SQLite : +SaveSystemPrompt(ctx, userID, prompt) error
User "1" -- "0..1" SystemPrompt : owns
Class diagram for frontend SystemPrompt serviceclassDiagram
class SystemPromptService {
+getSystemPrompt() string
+saveSystemPrompt(prompt string) void
}
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey @boston008 - I've reviewed your changes - here's some feedback:
- The LLMChatInterface component has grown very large—consider refactoring parts (like the SystemPrompt modal, auth token input, and message builders) into smaller subcomponents or custom hooks for clarity and maintainability.
- You’ve duplicated logic for building availableTools lists and sanitizing tool names in multiple handlers—extract that into shared utility functions to DRY up the code.
- The sanitizeToolName and getSanitizedToolNameMap helpers live inside the component; moving them to a standalone utils file will improve testability and separate concerns.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The LLMChatInterface component has grown very large—consider refactoring parts (like the SystemPrompt modal, auth token input, and message builders) into smaller subcomponents or custom hooks for clarity and maintainability.
- You’ve duplicated logic for building availableTools lists and sanitizing tool names in multiple handlers—extract that into shared utility functions to DRY up the code.
- The sanitizeToolName and getSanitizedToolNameMap helpers live inside the component; moving them to a standalone utils file will improve testability and separate concerns.
## Individual Comments
### Comment 1
<location> `web/src/pages/chat/llm-chat-interface.tsx:320` </location>
<code_context>
async (newToolCalls) => {
- setMessages(prev => {
+ // Patch tool calls to always have originalName
+ const patchedToolCalls = newToolCalls.map((tc: any) => ({
+ ...tc,
+ function: {
</code_context>
<issue_to_address>
Avoid using 'any' for tool call typing.
Use the specific ToolCall type to improve type safety and maintainability.
</issue_to_address>
### Comment 2
<location> `web/src/pages/chat/llm-chat-interface.tsx:288` </location>
<code_context>
};
- setMessages(prev => [...prev, assistantMessage]);
+ setMessages((prev: Message[]) => [...prev, assistantMessage]);
setIsGenerating(true);
</code_context>
<issue_to_address>
Consider deduplicating code for message streaming and tool call patching.
Extract the repeated logic into a helper function to improve maintainability and consistency.
Suggested implementation:
```typescript
addStreamingAssistantMessage(setMessages);
// Helper function to add a streaming assistant message
function addStreamingAssistantMessage(setMessages: React.Dispatch<React.SetStateAction<Message[]>>) {
const assistantMessage: Message = {
id: uuidv4(),
isStreaming: true
};
setMessages((prev: Message[]) => [...prev, assistantMessage]);
}
export function LLMChatInterface() {
```
- Replace any other repeated instances of adding a streaming assistant message (with the same structure) in this file with a call to `addStreamingAssistantMessage(setMessages)`.
- If tool call patching logic is also repeated, extract it similarly into a helper function and replace repeated code with calls to that function.
- Ensure the helper function is placed at an appropriate location in the file (e.g., above the component definition).
</issue_to_address>
### Comment 3
<location> `web/src/pages/chat/llm-chat-interface.tsx:605` </location>
<code_context>
+ }, []);
+
+ // Utility to sanitize tool names for VertexAI/Gemini
+ function sanitizeToolName(name: string): string {
+ // Only allow [a-zA-Z0-9_], must start with a letter or underscore
+ let sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_');
+ if (!/^[a-zA-Z_]/.test(sanitized)) {
+ sanitized = '_' + sanitized;
+ }
+ return sanitized;
+ }
+
</code_context>
<issue_to_address>
Sanitization may cause name collisions for tools with similar names.
Names differing only by non-alphanumeric characters will be sanitized to the same value. Please implement a collision check or use a more robust mapping to prevent this.
</issue_to_address>
### Comment 4
<location> `web/src/pages/chat/llm-chat-interface.tsx:766` </location>
<code_context>
selectionMode="multiple"
selectedKeys={activeServices}
- onSelectionChange={(keys) => setActiveServices(Array.from(keys) as string[])}
+ onSelectionChange={(keys: any) => setActiveServices(Array.from(keys) as string[])}
className="w-48"
size="sm"
</code_context>
<issue_to_address>
Avoid using 'any' for keys in onSelectionChange.
Specify the correct type for 'keys' to improve type safety.
</issue_to_address>
### Comment 5
<location> `web/src/pages/chat/llm-chat-interface.tsx:793` </location>
<code_context>
+ {isSystemPromptModalOpen && (
</code_context>
<issue_to_address>
System prompt modal does not handle save errors.
Currently, if saveSystemPrompt fails, the modal closes without notifying the user. Please add user feedback for save errors to enhance the user experience.
</issue_to_address>
### Comment 6
<location> `web/src/pages/chat/components/chat-message.tsx:37` </location>
<code_context>
try {
- if (!tool?.function?.name) {
+ // Use originalName if present, else fallback
+ const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;
+ if (!toolNameForParsing) {
toast.error(t('errors.invalid_tool_name'), {
</code_context>
<issue_to_address>
Using 'any' for tool.function reduces type safety.
Consider defining a type for tool.function that includes an optional originalName property to maintain type safety.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
// Use originalName if present, else fallback
const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;
=======
// Define a type for tool.function that includes optional originalName
type ToolFunctionWithOriginalName = typeof tool.function & { originalName?: string };
// Use originalName if present, else fallback
const toolFunction = tool?.function as ToolFunctionWithOriginalName;
const toolNameForParsing = toolFunction?.originalName || toolFunction?.name;
>>>>>>> REPLACE
</suggested_fix>
### Comment 7
<location> `web/src/pages/chat/components/chat-message.tsx:176` </location>
<code_context>
)}
{message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
const toolResult = findToolResult(tool.id);
+ const toolDisplayName = (tool.function as any).originalName || tool.function.name;
return (
<div key={index} className="mt-3 border border-blue-200 dark:border-blue-800 rounded-lg bg-blue-50/50 dark:bg-blue-950/20 overflow-hidden">
</code_context>
<issue_to_address>
Consider typing tool.function to avoid 'any' usage.
If tool.function may have an originalName property, update its type definition to include it for improved type safety.
Suggested implementation:
```typescript
{message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
const toolResult = findToolResult(tool.id);
const toolDisplayName = tool.function.originalName || tool.function.name;
return (
```
You will also need to update the type definition for `tool.function` wherever it is defined (likely in a types or interfaces file). For example, if you have an interface like:
```ts
interface ToolFunction {
name: string;
// ...other properties
}
```
Update it to:
```ts
interface ToolFunction {
name: string;
originalName?: string;
// ...other properties
}
```
And ensure that the type of `tool.function` is `ToolFunction`. If the type is defined inline or imported, update it accordingly.
</issue_to_address>
### Comment 8
<location> `web/src/services/mcp.ts:91` </location>
<code_context>
- client.onerror = (error) => {
- onError?.(error);
- toast.error(t('errors.mcp_server_error', { server: serverName, error: error.message }), {
+ client.onerror = (error: unknown) => {
+ onError?.(error as Error);
+ toast.error(t('errors.mcp_server_error', { server: serverName, error: (error as Error).message }), {
duration: 3000,
});
</code_context>
<issue_to_address>
Casting error to Error may not always be safe.
Check if error is an instance of Error before accessing .message to avoid runtime issues.
</issue_to_address>
### Comment 9
<location> `web/src/services/mcp.ts:171` </location>
<code_context>
};
+ // Prepare options for request
+ const options: any = this.lastEventIds.get(serverName)
+ ? { resumptionToken: this.lastEventIds.get(serverName) }
+ : {};
</code_context>
<issue_to_address>
Avoid using 'any' for options; define a proper type.
Consider creating a specific type for the options object to improve type safety when using client.request.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
// Prepare options for request
const options: any = this.lastEventIds.get(serverName)
? { resumptionToken: this.lastEventIds.get(serverName) }
: {};
=======
// Define a type for the options object
type McpRequestOptions = {
resumptionToken?: string;
};
// Prepare options for request
const options: McpRequestOptions = this.lastEventIds.get(serverName)
? { resumptionToken: this.lastEventIds.get(serverName) }
: {};
>>>>>>> REPLACE
</suggested_fix>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| async (newToolCalls) => { | ||
| setMessages(prev => { | ||
| // Patch tool calls to always have originalName | ||
| const patchedToolCalls = newToolCalls.map((tc: any) => ({ |
There was a problem hiding this comment.
suggestion: Avoid using 'any' for tool call typing.
Use the specific ToolCall type to improve type safety and maintainability.
| }; | ||
|
|
||
| setMessages(prev => [...prev, assistantMessage]); | ||
| setMessages((prev: Message[]) => [...prev, assistantMessage]); |
There was a problem hiding this comment.
suggestion: Consider deduplicating code for message streaming and tool call patching.
Extract the repeated logic into a helper function to improve maintainability and consistency.
Suggested implementation:
addStreamingAssistantMessage(setMessages);
// Helper function to add a streaming assistant message
function addStreamingAssistantMessage(setMessages: React.Dispatch<React.SetStateAction<Message[]>>) {
const assistantMessage: Message = {
id: uuidv4(),
isStreaming: true
};
setMessages((prev: Message[]) => [...prev, assistantMessage]);
}
export function LLMChatInterface() {- Replace any other repeated instances of adding a streaming assistant message (with the same structure) in this file with a call to
addStreamingAssistantMessage(setMessages). - If tool call patching logic is also repeated, extract it similarly into a helper function and replace repeated code with calls to that function.
- Ensure the helper function is placed at an appropriate location in the file (e.g., above the component definition).
| function sanitizeToolName(name: string): string { | ||
| // Only allow [a-zA-Z0-9_], must start with a letter or underscore | ||
| let sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_'); | ||
| if (!/^[a-zA-Z_]/.test(sanitized)) { | ||
| sanitized = '_' + sanitized; | ||
| } | ||
| return sanitized; |
There was a problem hiding this comment.
issue (bug_risk): Sanitization may cause name collisions for tools with similar names.
Names differing only by non-alphanumeric characters will be sanitized to the same value. Please implement a collision check or use a more robust mapping to prevent this.
| selectionMode="multiple" | ||
| selectedKeys={activeServices} | ||
| onSelectionChange={(keys) => setActiveServices(Array.from(keys) as string[])} | ||
| onSelectionChange={(keys: any) => setActiveServices(Array.from(keys) as string[])} |
There was a problem hiding this comment.
suggestion: Avoid using 'any' for keys in onSelectionChange.
Specify the correct type for 'keys' to improve type safety.
| @@ -647,19 +709,65 @@ export function LLMChatInterface() { | |||
| ))} | |||
| </Select> | |||
| )} | |||
There was a problem hiding this comment.
suggestion: System prompt modal does not handle save errors.
Currently, if saveSystemPrompt fails, the modal closes without notifying the user. Please add user feedback for save errors to enhance the user experience.
| // Use originalName if present, else fallback | ||
| const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name; |
There was a problem hiding this comment.
suggestion: Using 'any' for tool.function reduces type safety.
Consider defining a type for tool.function that includes an optional originalName property to maintain type safety.
| // Use originalName if present, else fallback | |
| const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name; | |
| // Define a type for tool.function that includes optional originalName | |
| type ToolFunctionWithOriginalName = typeof tool.function & { originalName?: string }; | |
| // Use originalName if present, else fallback | |
| const toolFunction = tool?.function as ToolFunctionWithOriginalName; | |
| const toolNameForParsing = toolFunction?.originalName || toolFunction?.name; |
| )} | ||
| {message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => { | ||
| const toolResult = findToolResult(tool.id); | ||
| const toolDisplayName = (tool.function as any).originalName || tool.function.name; |
There was a problem hiding this comment.
suggestion: Consider typing tool.function to avoid 'any' usage.
If tool.function may have an originalName property, update its type definition to include it for improved type safety.
Suggested implementation:
{message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
const toolResult = findToolResult(tool.id);
const toolDisplayName = tool.function.originalName || tool.function.name;
return (You will also need to update the type definition for tool.function wherever it is defined (likely in a types or interfaces file). For example, if you have an interface like:
interface ToolFunction {
name: string;
// ...other properties
}Update it to:
interface ToolFunction {
name: string;
originalName?: string;
// ...other properties
}And ensure that the type of tool.function is ToolFunction. If the type is defined inline or imported, update it accordingly.
| client.onerror = (error: unknown) => { | ||
| onError?.(error as Error); | ||
| toast.error(t('errors.mcp_server_error', { server: serverName, error: (error as Error).message }), { |
There was a problem hiding this comment.
suggestion (bug_risk): Casting error to Error may not always be safe.
Check if error is an instance of Error before accessing .message to avoid runtime issues.
| // Prepare options for request | ||
| const options: any = this.lastEventIds.get(serverName) | ||
| ? { resumptionToken: this.lastEventIds.get(serverName) } | ||
| : {}; |
There was a problem hiding this comment.
suggestion: Avoid using 'any' for options; define a proper type.
Consider creating a specific type for the options object to improve type safety when using client.request.
| // Prepare options for request | |
| const options: any = this.lastEventIds.get(serverName) | |
| ? { resumptionToken: this.lastEventIds.get(serverName) } | |
| : {}; | |
| // Define a type for the options object | |
| type McpRequestOptions = { | |
| resumptionToken?: string; | |
| }; | |
| // Prepare options for request | |
| const options: McpRequestOptions = this.lastEventIds.get(serverName) | |
| ? { resumptionToken: this.lastEventIds.get(serverName) } | |
| : {}; |
fix the import sequence of gateway and toast
|
Order of import has been updated to fix the web tests and lint tsdk |
KamToHung
left a comment
There was a problem hiding this comment.
Please verify your codes as copilot suggestions.
In Chat page add SystemPrompt and Authorization Textbox.
User has ability to add SystemPrompt & Authorization Code in Chat
SystemPrompt is send to llm with user input message.
Authorization textbox value is passthrough to the Rest API
SystemPrompt is saved to database,
Summary by Sourcery
Add a customizable system prompt feature and authorization token support to the chat interface, including persistence, API endpoints, and UI enhancements.
New Features:
Enhancements: