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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions client/packages/lowcoder-design/src/components/ExternalLink.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { ActiveTextColor, GreyTextColor } from "constants/style";
import { DocIcon } from "icons";
import styled from "styled-components";
import { ToolTipLabel } from "./toolTip";

export const ExternalLink = styled.a`
font-size: 13px;
font-weight: 400;
line-height: 13px;
color: ${GreyTextColor};
display: inline-flex;
Expand All @@ -20,14 +22,27 @@ const StyledDocIcon = styled(DocIcon)`
margin-right: 4px;
`;

export function DocLink(props: React.AnchorHTMLAttributes<HTMLAnchorElement>) {
type DocLinkProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {
tooltipZIndex?: number;
};

export function DocLink(props: DocLinkProps) {
if (!props.href) {
return <></>;
}
return (
<ExternalLink target="_blank" {...props}>
const { title, children, rel, tooltipZIndex, ...rest } = props;
const link = (
<ExternalLink target="_blank" rel={rel ?? "noopener noreferrer"} {...rest}>
<StyledDocIcon />
{props.children}
{children}
</ExternalLink>
);
if (!title) {
return link;
}
return (
<ToolTipLabel title={title} zIndex={tooltipZIndex}>
<span style={{ display: "inline-flex" }}>{link}</span>
</ToolTipLabel>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { SparklesIcon, XIcon } from "lucide-react";
import { useSelector } from "react-redux";
import styled from "styled-components";

import { DocLink } from "lowcoder-design";
import { EditorContext } from "comps/editorState";
import { trans } from "i18n";
import { getDataSourceStructures } from "redux/selectors/datasourceSelectors";
import { getSelectedAIQueryName } from "util/localStorageUtil";

Expand Down Expand Up @@ -175,6 +177,13 @@ export function AIHelperModal() {
<TitleLine>
<SparklesIcon size={16} color="#4965f2" />
<span>AI Helper</span>
<DocLink
href={trans("docUrls.githubAiHelp")}
title={trans("comp.menuViewDocsTooltip")}
tooltipZIndex={2147483001}
>
{trans("comp.menuViewDocs")}
</DocLink>
</TitleLine>
{target?.label && (
<TargetLabel title={target.label}>{target.label}</TargetLabel>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState } from "react";
import { Section, sectionNames, controlItem } from "lowcoder-design";
import { PropertyViewDocLink } from "comps/utils/propertyViewDocLink";
import { default as Segmented } from "antd/es/segmented";
import { UICompBuilder, withDefault, stateComp } from "../../generators";
import { changeValueAction, multiChangeAction } from "lowcoder-core";
Expand Down Expand Up @@ -193,6 +194,7 @@ const ChatBoxPropertyView = React.memo((props: { children: any }) => {

return (
<>
<PropertyViewDocLink href={trans("docUrls.githubChatBox")} />
<Section name={sectionNames.basic}>
{children.chatTitle.propertyView({
label: trans("chatBox.chatTitleLabel"),
Expand Down
82 changes: 16 additions & 66 deletions client/packages/lowcoder/src/comps/comps/chatComp/chatComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import { ChatContainer } from "./components/ChatContainer";
import { ChatProvider } from "./components/context/ChatContext";
import { ChatPropertyView } from "./chatPropertyView";
import { createChatStorage } from "./utils/storageFactory";
import { QueryHandler } from "./handlers/messageHandlers";
import { useMemo, useRef } from "react";
import { changeChildAction } from "lowcoder-core";
import { QueryHandler } from "./handlers/messageHandlers";
import { useMemo, useRef } from "react";
import { changeChildAction } from "lowcoder-core";
import { ChatMessage } from "./types/chatTypes";
import { getTextFromThreadContent } from "./utils/assistantMessages";
import { addSystemPromptToHistory } from "./utils/assistantMessages";
import { trans } from "i18n";
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { styleControl } from "comps/controls/styleControl";
Expand Down Expand Up @@ -86,59 +86,7 @@ const ChatEventOptions = [

export const ChatEventHandlerControl = eventHandlerControl(ChatEventOptions);

// ============================================================================
// SIMPLIFIED CHILDREN MAP - WITH EVENT HANDLERS
// ============================================================================


export function addSystemPromptToHistory(
conversationHistory: ChatMessage[],
systemPrompt: string
): Array<{ role: string; content: string; timestamp: number; attachments?: any[] }> {
// Format conversation history for use in queries
const formattedHistory = conversationHistory.map(msg => {
const baseMessage = {
role: msg.role,
content: getTextFromThreadContent(msg.content),
timestamp: msg.createdAt.getTime()
};

// Include attachment metadata if present (for API calls and external integrations)
if (msg.attachments && msg.attachments.length > 0) {
return {
...baseMessage,
attachments: msg.attachments.map(att => ({
id: att.id,
type: att.type,
name: att.name,
contentType: att.contentType,
// Include content for images (base64 data URLs are useful for APIs)
...(att.type === "image" && att.content && {
content: att.content.map(c => ({
type: c.type,
...(c.type === "image" && { image: c.image })
}))
})
}))
};
}

return baseMessage;
});

// Create system message (always exists since we have default)
const systemMessage = [{
role: "system" as const,
content: systemPrompt,
timestamp: Date.now() - 1000000 // Ensure it's always first chronologically
}];

// Return complete history with system prompt prepended
return [...systemMessage, ...formattedHistory];
}


function generateUniqueTableName(): string {
function generateUniqueTableName(): string {
return `chat${Math.floor(1000 + Math.random() * 9000)}`;
}

Expand Down Expand Up @@ -213,14 +161,16 @@ const ChatTmpComp = new UICompBuilder(

// Create message handler (Query only)
const messageHandler = useMemo(() => {
return new QueryHandler({
chatQuery: props.chatQuery.value,
dispatch,
});
}, [
props.chatQuery,
dispatch,
]);
return new QueryHandler({
chatQuery: props.chatQuery.value,
dispatch,
systemPrompt: props.systemPrompt,
});
}, [
props.chatQuery,
props.systemPrompt,
dispatch,
]);

// Handle message updates for exposed variable
// Using Lowcoder pattern: props.currentMessage.onChange()
Expand Down Expand Up @@ -297,6 +247,6 @@ const ChatCompWithAutoHeight = class extends ChatTmpComp {
export const ChatComp = withExposingConfigs(ChatCompWithAutoHeight, [
new NameConfig("currentMessage", "Current user message"),
// conversationHistory is now a proper array (not JSON string) - supports setConversationHistory(), clearConversationHistory(), resetConversationHistory()
new NameConfig("conversationHistory", "Full conversation history array with system prompt (use directly in API calls, no JSON.parse needed)"),
new NameConfig("conversationHistory", "Reactive conversation history array with system prompt (no JSON.parse needed)"),
new NameConfig("databaseName", "Database name for SQL queries (ChatDB_<componentName>)"),
]);
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
// client/packages/lowcoder/src/comps/comps/chatComp/chatPropertyView.tsx

import React, { useMemo } from "react";
import { Section, sectionNames, DocLink } from "lowcoder-design";
import { Section, sectionNames, controlItem } from "lowcoder-design";
import { trans } from "i18n";
import { hiddenPropertyView } from "comps/utils/propertyUtils";
import { controlItem } from "lowcoder-design";
import { PropertyViewDocLink } from "comps/utils/propertyViewDocLink";

// ============================================================================
// PROPERTY VIEW
Expand All @@ -15,16 +14,7 @@ export const ChatPropertyView = React.memo((props: any) => {

return useMemo(() => (
<>
{/* Help & Documentation - Outside of Section */}
<div style={{ padding: "8px 16px", marginBottom: "16px", borderBottom: "1px solid #f0f0f0" }}>
<DocLink
style={{ marginTop: 8 }}
href="https://docs.lowcoder.cloud/lowcoder-documentation"
title="Open Lowcoder Documentation"
>
📖 View Documentation
</DocLink>
</div>
<PropertyViewDocLink href={trans("docUrls.githubAiChat")} />

{/* Message Handler Configuration */}
<Section name={trans("chat.messageHandler")}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,8 @@ function ChatContainerView(props: ChatCoreProps) {
const currentMessages = actions.getCurrentMessages();

useEffect(() => {
if (currentMessages.length > 0) {
onConversationUpdateRef.current?.(currentMessages);
}
}, [currentMessages]);
onConversationUpdateRef.current?.(currentMessages);
}, [state.currentThreadId, currentMessages]);

useEffect(() => {
onEventRef.current?.("componentLoad");
Expand Down Expand Up @@ -82,13 +80,17 @@ function ChatContainerView(props: ChatCoreProps) {
}

const userMessage = createUserMessage(text, completeAttachments);
const conversationHistory = [...currentMessages, userMessage];

await actions.addMessage(state.currentThreadId, userMessage);
await updateInitialThreadTitle(userMessage);
setIsRunning(true);

try {
const assistantMessage = await props.messageHandler.sendMessage(userMessage);
const assistantMessage = await props.messageHandler.sendMessage(
userMessage,
conversationHistory
);
props.onMessageUpdate?.(getTextFromThreadContent(userMessage.content));

await actions.addMessage(state.currentThreadId, assistantMessage);
Expand Down Expand Up @@ -122,7 +124,10 @@ function ChatContainerView(props: ChatCoreProps) {
setIsRunning(true);

try {
const assistantMessage = await props.messageHandler.sendMessage(editedMessage);
const assistantMessage = await props.messageHandler.sendMessage(
editedMessage,
newMessages
);
props.onMessageUpdate?.(getTextFromThreadContent(editedMessage.content));

newMessages.push(assistantMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import React, { createContext, useContext, useReducer, useEffect, ReactNode } from "react";
import { ChatStorage, ChatMessage, ChatThread } from "../../types/chatTypes";
import { trans } from "i18n";
import { trans } from "i18n";

const EMPTY_MESSAGES: ChatMessage[] = [];

// ============================================================================
// UPDATED CONTEXT WITH CLEAN TYPES
Expand Down Expand Up @@ -353,10 +355,10 @@ export function ChatProvider({ children, storage }: {
}
};

// Utility functions
const getCurrentMessages = (): ChatMessage[] => {
return state.threads.get(state.currentThreadId) || [];
};
// Utility functions
const getCurrentMessages = (): ChatMessage[] => {
return state.threads.get(state.currentThreadId) || EMPTY_MESSAGES;
};

// Auto-initialize on mount
useEffect(() => {
Expand Down Expand Up @@ -395,4 +397,4 @@ export function useChatContext() {
}

// Re-export types for convenience
export type { ChatMessage, ChatThread };
export type { ChatMessage, ChatThread };
Loading
Loading