Skip to content
Draft
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
6 changes: 5 additions & 1 deletion apps/client/src/services/note_autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export interface Options {
hideAllButtons?: boolean;
/** If set, enables command palette mode */
isCommandPalette?: boolean;
/** If true, close the dropdown when the input loses focus (even when using a container). Defaults to false. */
closeOnBlur?: boolean;
}

async function autocompleteSourceForCKEditor(queryText: string) {
Expand Down Expand Up @@ -258,7 +260,9 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
let autocompleteOptions: AutoCompleteConfig = {};
if (options.container) {
autocompleteOptions.dropdownMenuContainer = options.container;
autocompleteOptions.debug = true; // don't close on blur
if (!options.closeOnBlur) {
autocompleteOptions.debug = true; // don't close on blur
}
}

if (options.allowJumpToSearchNotes) {
Expand Down
4 changes: 4 additions & 0 deletions apps/client/src/translations/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1641,6 +1641,10 @@
"sources": "Sources",
"sources_summary": "{{count}} sources from {{sites}} sites",
"extended_thinking": "Extended thinking",
"knowledge_base": "Knowledge base",
"knowledge_base_sources": "Knowledge base sources",
"knowledge_base_add": "Add a note as source...",
"knowledge_base_remove": "Remove source",
"legacy_models": "Legacy models",
"thinking": "Thinking...",
"thought_process": "Thought process",
Expand Down
92 changes: 92 additions & 0 deletions apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,95 @@
margin: 0;
font-size: 0.9rem;
}

/* Knowledge base sources */
.llm-chat-kb-sources {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.5rem;
border: 1px solid var(--main-border-color);
border-radius: 6px;
background: var(--accented-background-color);
}

.llm-chat-kb-header {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.8rem;
color: var(--muted-text-color);
font-weight: 600;
}

.llm-chat-kb-chips {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}

.llm-chat-kb-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.125rem 0.375rem;
border-radius: 4px;
background: var(--main-background-color);
border: 1px solid var(--main-border-color);
font-size: 0.8rem;
max-width: 200px;
}

.llm-chat-kb-chip-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

.llm-chat-kb-chip-remove {
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
cursor: pointer;
padding: 0;
color: var(--muted-text-color);
font-size: 0.9rem;
line-height: 1;
}

.llm-chat-kb-chip-remove:hover:not(:disabled) {
color: var(--danger-color, #d9534f);
}

.llm-chat-kb-chip-remove:disabled {
opacity: 0.5;
cursor: not-allowed;
}

.llm-chat-kb-sources .note-autocomplete-container input {
font-size: 0.8rem;
padding: 0.25rem 0.5rem;
}

/* Position the autocomplete dropdown above the input */
.llm-chat-kb-autocomplete-wrapper {
position: relative;
margin-top: 0.25rem;
}

.llm-chat-kb-autocomplete-wrapper .aa-dropdown-menu {
position: absolute !important;
bottom: 100% !important;
top: auto !important;
left: 0;
right: 0;
max-height: 300px;
overflow: auto;
margin-bottom: 2px;
background-color: var(--main-background-color);
border: 1px solid var(--main-border-color);
border-radius: 6px;
z-index: 2000;
}
88 changes: 87 additions & 1 deletion apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too many changes to an already big file, extract to a separate component with its own stylesheet.

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import "./ChatInputBar.css";

import type { RefObject } from "preact";
import { useState, useCallback } from "preact/hooks";
import { useState, useCallback, useEffect, useRef } from "preact/hooks";

import { t } from "../../../services/i18n.js";
import ActionButton from "../../react/ActionButton.js";
Expand All @@ -10,6 +10,8 @@ import Dropdown from "../../react/Dropdown.js";
import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListToggleableItem } from "../../react/FormList.js";
import type { UseLlmChatReturn } from "./useLlmChat.js";
import AddProviderModal, { type LlmProviderConfig } from "../options/llm/AddProviderModal.js";
import NoteAutocomplete from "../../react/NoteAutocomplete.js";
import froca from "../../../services/froca.js";
import options from "../../../services/options.js";

/** Format token count with thousands separators */
Expand Down Expand Up @@ -96,6 +98,37 @@ export default function ChatInputBar({

const isNoteContextEnabled = !!chat.contextNoteId && !!activeNoteId;

const [sourceTitles, setSourceTitles] = useState<Record<string, string>>({});
const [kbPanelOpen, setKbPanelOpen] = useState(chat.sourceNoteIds.length > 0);
const kbContainerRef = useRef<HTMLDivElement>(null);

// Open KB panel when sources are loaded from saved content
useEffect(() => {
if (chat.sourceNoteIds.length > 0) {
setKbPanelOpen(true);
}
}, [chat.sourceNoteIds.length]);

// Resolve note titles for source note chips
useEffect(() => {
const ids = chat.sourceNoteIds.filter(id => !sourceTitles[id]);
if (ids.length === 0) return;

Promise.all(ids.map(id => froca.getNote(id, true))).then(notes => {
const newTitles: Record<string, string> = {};
for (let i = 0; i < ids.length; i++) {
newTitles[ids[i]] = notes[i]?.title ?? ids[i];
}
setSourceTitles(prev => ({ ...prev, ...newTitles }));
});
}, [chat.sourceNoteIds]);

const handleAddSourceNote = useCallback((noteId: string) => {
if (noteId && !chat.sourceNoteIds.includes(noteId)) {
chat.addSourceNote(noteId);
}
}, [chat.sourceNoteIds, chat.addSourceNote]);

const currentModel = chat.availableModels.find(m => m.id === chat.selectedModel);
const currentModels = chat.availableModels.filter(m => !m.isLegacy);
const legacyModels = chat.availableModels.filter(m => m.isLegacy);
Expand Down Expand Up @@ -139,6 +172,45 @@ export default function ChatInputBar({
onKeyDown={handleKeyDown}
rows={rows}
/>
{kbPanelOpen && (
<div className="llm-chat-kb-sources">
<div className="llm-chat-kb-header">
<span className="bx bx-book-open" />
<span>{t("llm_chat.knowledge_base_sources")}</span>
</div>
<div className="llm-chat-kb-chips">
{chat.sourceNoteIds.map(noteId => (
<span key={noteId} className="llm-chat-kb-chip">
<span className="llm-chat-kb-chip-title">{sourceTitles[noteId] ?? noteId}</span>
<button
type="button"
className="llm-chat-kb-chip-remove"
onClick={() => {
chat.removeSourceNote(noteId);
setSourceTitles(prev => {
const next = { ...prev };
delete next[noteId];
return next;
});
}}
disabled={chat.isStreaming}
title={t("llm_chat.knowledge_base_remove")}
>
<span className="bx bx-x" />
</button>
</span>
))}
</div>
<div className="llm-chat-kb-autocomplete-wrapper" ref={kbContainerRef}>
<NoteAutocomplete
placeholder={t("llm_chat.knowledge_base_add")}
noteIdChanged={handleAddSourceNote}
container={kbContainerRef}
opts={{ closeOnBlur: true }}
/>
</div>
</div>
)}
<div className="llm-chat-options">
<div className="llm-chat-model-selector">
<span className="bx bx-chip" />
Expand Down Expand Up @@ -197,6 +269,20 @@ export default function ChatInputBar({
onChange={handleExtendedThinkingToggle}
disabled={chat.isStreaming}
/>
<FormDropdownDivider />
<FormListToggleableItem
icon="bx bx-book-open"
title={t("llm_chat.knowledge_base")}
currentValue={kbPanelOpen}
onChange={(newValue) => {
setKbPanelOpen(newValue);
if (!newValue) {
chat.setSourceNoteIds([]);
setSourceTitles({});
}
}}
disabled={chat.isStreaming}
/>
</Dropdown>
{activeNoteId && activeNoteTitle && (
<Button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,5 @@ export interface LlmChatContent {
enableWebSearch?: boolean;
enableNoteTools?: boolean;
enableExtendedThinking?: boolean;
sourceNoteIds?: string[];
}
32 changes: 29 additions & 3 deletions apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface UseLlmChatReturn {
enableNoteTools: boolean;
enableExtendedThinking: boolean;
contextNoteId: string | undefined;
sourceNoteIds: string[];
lastPromptTokens: number;
messagesEndRef: RefObject<HTMLDivElement>;
textareaRef: RefObject<HTMLTextAreaElement>;
Expand All @@ -53,6 +54,9 @@ export interface UseLlmChatReturn {
setEnableExtendedThinking: (value: boolean) => void;
setContextNoteId: (noteId: string | undefined) => void;
setChatNoteId: (noteId: string | undefined) => void;
setSourceNoteIds: (noteIds: string[]) => void;
addSourceNote: (noteId: string) => void;
removeSourceNote: (noteId: string) => void;

// Actions
handleSubmit: (e: Event) => Promise<void>;
Expand Down Expand Up @@ -84,6 +88,7 @@ export function useLlmChat(
const [enableExtendedThinking, setEnableExtendedThinking] = useState(false);
const [contextNoteId, setContextNoteId] = useState<string | undefined>(initialContextNoteId);
const [chatNoteId, setChatNoteIdState] = useState<string | undefined>(initialChatNoteId);
const [sourceNoteIds, setSourceNoteIds] = useState<string[]>([]);
const [lastPromptTokens, setLastPromptTokens] = useState<number>(0);
const [hasProvider, setHasProvider] = useState<boolean>(true); // Assume true initially
const [isCheckingProvider, setIsCheckingProvider] = useState<boolean>(true);
Expand All @@ -109,6 +114,16 @@ export function useLlmChat(
}, []);
const contextNoteIdRef = useRef(contextNoteId);
contextNoteIdRef.current = contextNoteId;
const sourceNoteIdsRef = useRef(sourceNoteIds);
sourceNoteIdsRef.current = sourceNoteIds;

const addSourceNote = useCallback((noteId: string) => {
setSourceNoteIds(prev => prev.includes(noteId) ? prev : [...prev, noteId]);
}, []);

const removeSourceNote = useCallback((noteId: string) => {
setSourceNoteIds(prev => prev.filter(id => id !== noteId));
}, []);

// Wrapper to call onMessagesChange when messages update
const setMessages = useCallback((newMessages: StoredMessage[]) => {
Expand Down Expand Up @@ -168,6 +183,9 @@ export function useLlmChat(
if (supportsExtendedThinking && typeof content.enableExtendedThinking === "boolean") {
setEnableExtendedThinking(content.enableExtendedThinking);
}
if (Array.isArray(content.sourceNoteIds)) {
setSourceNoteIds(content.sourceNoteIds);
}
// Restore last prompt tokens from the most recent message with usage
const lastUsage = [...(content.messages || [])].reverse().find(m => m.usage)?.usage;
setLastPromptTokens(lastUsage?.promptTokens ?? 0);
Expand All @@ -185,6 +203,9 @@ export function useLlmChat(
if (supportsExtendedThinking) {
content.enableExtendedThinking = enableExtendedThinkingRef.current;
}
if (sourceNoteIdsRef.current.length > 0) {
content.sourceNoteIds = sourceNoteIdsRef.current;
}
return content;
}, [supportsExtendedThinking]);

Expand Down Expand Up @@ -243,9 +264,10 @@ export function useLlmChat(
model: selectedModel || undefined,
provider: selectedModelProvider,
enableWebSearch,
enableNoteTools,
enableNoteTools: enableNoteTools || sourceNoteIds.length > 0,
contextNoteId,
chatNoteId: chatNoteIdRef.current
chatNoteId: chatNoteIdRef.current,
sourceNoteIds: sourceNoteIds.length > 0 ? sourceNoteIds : undefined
};
if (supportsExtendedThinking) {
streamOptions.enableExtendedThinking = enableExtendedThinking;
Expand Down Expand Up @@ -356,7 +378,7 @@ export function useLlmChat(
}
}
);
}, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages]);
}, [input, isStreaming, messages, selectedModel, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, sourceNoteIds, supportsExtendedThinking, setMessages]);

const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
Expand All @@ -380,6 +402,7 @@ export function useLlmChat(
enableNoteTools,
enableExtendedThinking,
contextNoteId,
sourceNoteIds,
lastPromptTokens,
messagesEndRef,
textareaRef,
Expand All @@ -395,6 +418,9 @@ export function useLlmChat(
setEnableExtendedThinking,
setContextNoteId,
setChatNoteId,
setSourceNoteIds,
addSourceNote,
removeSourceNote,

// Actions
handleSubmit,
Expand Down
Loading
Loading