mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
316ddf284d | ||
|
|
5fc96c9007 | ||
|
|
9352b70df8 | ||
|
|
b4cfc1a5ee | ||
|
|
a07368b190 | ||
|
|
66bfb56694 | ||
|
|
3cb7a8f673 |
No files matched your search
Generated
-20
@@ -4488,7 +4488,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4502,7 +4501,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4516,7 +4514,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4530,7 +4527,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4544,7 +4540,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4558,7 +4553,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4572,7 +4566,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4586,7 +4579,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4600,7 +4592,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4614,7 +4605,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4628,7 +4618,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4642,7 +4631,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4656,7 +4644,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4670,7 +4657,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4684,7 +4670,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4698,7 +4683,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4712,7 +4696,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4726,7 +4709,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4740,7 +4722,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ia32"
|
"ia32"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4754,7 +4735,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ export function ProjectTitleMenu({
|
|||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
<MessageSquarePlus className="h-4 w-4" />
|
<MessageSquarePlus className="h-4 w-4" />
|
||||||
New Chat
|
{t('newChat')}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
/** Visual divider between chat sessions */
|
||||||
|
export function SessionDivider() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3 text-xs text-muted-foreground py-4">
|
||||||
|
<div className="flex-1 h-px bg-border" />
|
||||||
|
<span className="uppercase tracking-wide">
|
||||||
|
{t('newChat', 'New chat')}
|
||||||
|
</span>
|
||||||
|
<div className="flex-1 h-px bg-border" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||||
import { ChevronDown, Play } from 'lucide-react';
|
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
@@ -47,11 +47,12 @@ import OpenAI from 'openai';
|
|||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { Quilly } from '@/components/Quilly';
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||||
|
import { SessionDivider } from '@/components/SessionDivider';
|
||||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||||
import { DotAI } from '@/lib/DotAI';
|
import { DotAI } from '@/lib/DotAI';
|
||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||||
import { AIMessage } from '@/lib/SessionManager';
|
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||||
|
|
||||||
// Clean interfaces now handled by proper hooks
|
// Clean interfaces now handled by proper hooks
|
||||||
|
|
||||||
@@ -294,9 +295,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading: internalIsLoading,
|
isLoading: internalIsLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -305,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
startGeneration,
|
startGeneration,
|
||||||
stopGeneration,
|
stopGeneration,
|
||||||
startNewSession: internalStartNewSession,
|
startNewSession: internalStartNewSession,
|
||||||
|
loadMoreHistory,
|
||||||
} = useAIChat({
|
} = useAIChat({
|
||||||
projectId,
|
projectId,
|
||||||
tools,
|
tools,
|
||||||
@@ -318,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
const checkTemplateInfo = async () => {
|
const checkTemplateInfo = async () => {
|
||||||
try {
|
try {
|
||||||
// Only check if we have at least 1 message
|
// Only check if we have at least 1 message
|
||||||
if (messages.length === 0) {
|
if (displayMessages.length === 0) {
|
||||||
setShowTemplateInfo(false);
|
setShowTemplateInfo(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -357,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
};
|
};
|
||||||
|
|
||||||
checkTemplateInfo();
|
checkTemplateInfo();
|
||||||
}, [fs, projectsPath, projectId, messages.length]);
|
}, [fs, projectsPath, projectId, displayMessages.length]);
|
||||||
|
|
||||||
// Handle console error help requests
|
// Handle console error help requests
|
||||||
const handleConsoleErrorHelp = useCallback(async () => {
|
const handleConsoleErrorHelp = useCallback(async () => {
|
||||||
@@ -436,7 +442,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Function to scroll to bottom
|
// Function to scroll to bottom
|
||||||
const scrollToBottom = useCallback(() => {
|
const scrollToBottom = useCallback(() => {
|
||||||
if (scrollAreaRef.current) {
|
if (scrollAreaRef.current) {
|
||||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
requestAnimationFrame(() => {
|
||||||
|
if (scrollAreaRef.current) {
|
||||||
|
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -489,17 +499,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||||
// Check if user was already at or near the bottom (within 100px threshold)
|
|
||||||
const threshold = 100;
|
|
||||||
const container = scrollAreaRef.current;
|
const container = scrollAreaRef.current;
|
||||||
|
const lastMessage = messages[messages.length - 1];
|
||||||
|
const isUserMessage = lastMessage?.role === 'user';
|
||||||
|
|
||||||
|
// Check if user was already near the bottom (within 100px threshold)
|
||||||
|
const threshold = 100;
|
||||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||||
|
|
||||||
// Only auto-scroll if user was already near the bottom
|
// Scroll to bottom if user sent a message or was already near the bottom
|
||||||
if (isNearBottom) {
|
if (isUserMessage || isNearBottom) {
|
||||||
container.scrollTop = container.scrollHeight;
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [messages, streamingMessage, isLoading]);
|
}, [messages, streamingMessage, isLoading, scrollToBottom]);
|
||||||
|
|
||||||
// Scroll to bottom when first visiting a project (including page refresh)
|
// Scroll to bottom when first visiting a project (including page refresh)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -577,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Add model to recently used when sending a message
|
// Add model to recently used when sending a message
|
||||||
addRecentlyUsedModel(modelToUse);
|
addRecentlyUsedModel(modelToUse);
|
||||||
|
|
||||||
|
// Scroll to bottom when user sends a message
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
await sendMessage(messageContent, modelToUse);
|
await sendMessage(messageContent, modelToUse);
|
||||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, scrollToBottom]);
|
||||||
|
|
||||||
// Handle textarea focus - show onboarding if not configured
|
// Handle textarea focus - show onboarding if not configured
|
||||||
const handleTextareaFocus = useCallback(() => {
|
const handleTextareaFocus = useCallback(() => {
|
||||||
@@ -757,7 +773,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Empty state when no messages and not loading */}
|
{/* Empty state when no messages and not loading */}
|
||||||
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
|
{!isLoadingHistory && displayMessages.length === 0 && !streamingMessage && !isLoading && (
|
||||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
@@ -781,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoadingHistory && messages.map((message, index) => {
|
{/* Load older messages button */}
|
||||||
|
{!isLoadingHistory && hasMoreHistory && (
|
||||||
|
<div className="flex justify-center py-3">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={async () => {
|
||||||
|
const container = scrollAreaRef.current;
|
||||||
|
const oldScrollHeight = container?.scrollHeight || 0;
|
||||||
|
await loadMoreHistory();
|
||||||
|
// Preserve scroll position after prepending content
|
||||||
|
if (container) {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
container.scrollTop += container.scrollHeight - oldScrollHeight;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={isLoadingMoreHistory}
|
||||||
|
className="gap-2 text-muted-foreground"
|
||||||
|
>
|
||||||
|
<ChevronUp className="h-4 w-4" />
|
||||||
|
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoadingHistory && displayMessages.map((message, index) => {
|
||||||
|
// Get the current message's session ID and compare to previous
|
||||||
|
const currentSessionId = (message as DisplayMessage).sessionId;
|
||||||
|
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage).sessionId : undefined;
|
||||||
|
|
||||||
|
// Show divider when session changes (not on first message)
|
||||||
|
const showDivider = index > 0 && currentSessionId !== prevSessionId;
|
||||||
|
|
||||||
|
// Dim messages from older sessions (compare against current active session)
|
||||||
|
const isOlderSession = currentSessionId !== sessionName;
|
||||||
|
|
||||||
// Find the corresponding tool call for tool messages
|
// Find the corresponding tool call for tool messages
|
||||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||||
if (message.role === 'tool') {
|
if (message.role === 'tool') {
|
||||||
// Look backwards to find the assistant message with matching tool call
|
// Look backwards to find the assistant message with matching tool call
|
||||||
for (let i = index - 1; i >= 0; i--) {
|
for (let i = index - 1; i >= 0; i--) {
|
||||||
const prevMessage = messages[i];
|
const prevMessage = displayMessages[i];
|
||||||
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
||||||
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
||||||
if (toolCall) break;
|
if (toolCall) break;
|
||||||
@@ -796,14 +848,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AIMessageItem
|
<div
|
||||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||||
message={message}
|
className={isOlderSession ? 'opacity-65' : ''}
|
||||||
toolCall={toolCall}
|
>
|
||||||
/>
|
{showDivider && <SessionDivider />}
|
||||||
|
<AIMessageItem
|
||||||
|
message={message}
|
||||||
|
toolCall={toolCall}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{/* Trailing session divider - shown when New Chat is clicked before sending a message */}
|
||||||
|
{!isLoadingHistory && displayMessages.length > 0 && (() => {
|
||||||
|
const lastSessionId = (displayMessages[displayMessages.length - 1] as DisplayMessage).sessionId;
|
||||||
|
return sessionName && lastSessionId && sessionName !== lastSessionId ? (
|
||||||
|
<SessionDivider key="trailing-divider" />
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
|
|
||||||
{!isLoadingHistory && renderStreamingMessage()}
|
{!isLoadingHistory && renderStreamingMessage()}
|
||||||
|
|
||||||
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
||||||
|
|||||||
+44
-2
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
|
|||||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import type { AIMessage } from '@/lib/SessionManager';
|
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||||
import type OpenAI from 'openai';
|
import type OpenAI from 'openai';
|
||||||
import type { Tool } from '@/lib/tools/Tool';
|
import type { Tool } from '@/lib/tools/Tool';
|
||||||
|
|
||||||
@@ -39,12 +39,16 @@ export function useAIChat({
|
|||||||
|
|
||||||
// Split session state into individual variables for efficient updates
|
// Split session state into individual variables for efficient updates
|
||||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||||
|
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
|
||||||
|
const [sessionName, setSessionName] = useState<string>('');
|
||||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
const [totalCost, setTotalCost] = useState<number>(0);
|
const [totalCost, setTotalCost] = useState<number>(0);
|
||||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||||
|
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
|
||||||
|
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
|
||||||
|
|
||||||
const initSession = useCallback(async () => {
|
const initSession = useCallback(async () => {
|
||||||
setIsLoadingHistory(true);
|
setIsLoadingHistory(true);
|
||||||
@@ -53,11 +57,15 @@ export function useAIChat({
|
|||||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||||
// Initialize individual state variables from existing session
|
// Initialize individual state variables from existing session
|
||||||
setMessages([...session.messages]);
|
setMessages([...session.messages]);
|
||||||
|
setDisplayMessages([...session.displayMessages]);
|
||||||
|
setSessionName(session.sessionName);
|
||||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||||
setIsLoading(session.isLoading);
|
setIsLoading(session.isLoading);
|
||||||
setTotalCost(session.totalCost || 0);
|
setTotalCost(session.totalCost || 0);
|
||||||
setLastInputTokens(session.lastInputTokens || 0);
|
setLastInputTokens(session.lastInputTokens || 0);
|
||||||
setLastFinishReason(session.lastFinishReason ?? null);
|
setLastFinishReason(session.lastFinishReason ?? null);
|
||||||
|
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||||
|
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingHistory(false);
|
setIsLoadingHistory(false);
|
||||||
}
|
}
|
||||||
@@ -123,6 +131,25 @@ export function useAIChat({
|
|||||||
}
|
}
|
||||||
}, [projectId]);
|
}, [projectId]);
|
||||||
|
|
||||||
|
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setDisplayMessages(prev => [...prev, message]);
|
||||||
|
}
|
||||||
|
}, [projectId]);
|
||||||
|
|
||||||
|
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setDisplayMessages(prev => [...newMessages, ...prev]);
|
||||||
|
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||||
|
}
|
||||||
|
}, [projectId, sessionManager]);
|
||||||
|
|
||||||
|
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setIsLoadingMoreHistory(loading);
|
||||||
|
}
|
||||||
|
}, [projectId]);
|
||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
const sendMessage = useCallback(async (
|
const sendMessage = useCallback(async (
|
||||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||||
@@ -164,7 +191,13 @@ export function useAIChat({
|
|||||||
const startNewSession = useCallback(async () => {
|
const startNewSession = useCallback(async () => {
|
||||||
await sessionManager.startNewSession(projectId);
|
await sessionManager.startNewSession(projectId);
|
||||||
|
|
||||||
// Reset individual state variables
|
// Get the updated session to retrieve the new session name
|
||||||
|
const session = sessionManager.getSession(projectId);
|
||||||
|
if (session) {
|
||||||
|
setSessionName(session.sessionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset only AI prompt state (not display state which is handled via events)
|
||||||
setMessages([]);
|
setMessages([]);
|
||||||
setStreamingMessage(undefined);
|
setStreamingMessage(undefined);
|
||||||
setTotalCost(0);
|
setTotalCost(0);
|
||||||
@@ -177,11 +210,19 @@ export function useAIChat({
|
|||||||
await startNewSession();
|
await startNewSession();
|
||||||
}, [startNewSession]);
|
}, [startNewSession]);
|
||||||
|
|
||||||
|
const loadMoreHistory = useCallback(async () => {
|
||||||
|
await sessionManager.loadOlderSession(projectId);
|
||||||
|
}, [projectId, sessionManager]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading,
|
isLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -191,6 +232,7 @@ export function useAIChat({
|
|||||||
clearMessages,
|
clearMessages,
|
||||||
startNewSession,
|
startNewSession,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
loadMoreHistory,
|
||||||
isConfigured,
|
isConfigured,
|
||||||
projectId
|
projectId
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -27,73 +27,6 @@ describe('DotAI', () => {
|
|||||||
dotAI = new DotAI(mockFS, '/test-project');
|
dotAI = new DotAI(mockFS, '/test-project');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('readLastSessionHistory', () => {
|
|
||||||
it('should return null when history directory does not exist', async () => {
|
|
||||||
// Mock historyDirExists to return false
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return null when no session files exist', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return empty array
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([]);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return messages and session name from most recent file', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return session files
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([
|
|
||||||
'2024-08-24T16-30-45Z-abc.jsonl',
|
|
||||||
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
|
|
||||||
'2024-08-24T15-00-00Z-xyz.jsonl'
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Mock readFile to return JSONL content
|
|
||||||
const mockContent = `{"role":"user","content":"Hello"}
|
|
||||||
{"role":"assistant","content":"Hi there!"}`;
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
|
||||||
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
|
|
||||||
expect(result?.messages).toHaveLength(2);
|
|
||||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
|
||||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle malformed JSON lines gracefully', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return session files
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
|
|
||||||
|
|
||||||
// Mock readFile to return content with malformed JSON
|
|
||||||
const mockContent = `{"role":"user","content":"Hello"}
|
|
||||||
invalid json line
|
|
||||||
{"role":"assistant","content":"Hi there!"}`;
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
|
||||||
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
|
|
||||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
|
||||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('setHistory', () => {
|
describe('setHistory', () => {
|
||||||
it('should create history directory if it does not exist', async () => {
|
it('should create history directory if it does not exist', async () => {
|
||||||
// Mock historyDirExists to return false initially
|
// Mock historyDirExists to return false initially
|
||||||
|
|||||||
+34
-50
@@ -216,66 +216,50 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the most recent session history
|
* List all session names sorted chronologically (oldest first)
|
||||||
* @returns Object containing messages array and session name, or null if no history found
|
* Fast operation - does not load message content
|
||||||
|
* @returns Array of session names (filenames without .jsonl extension)
|
||||||
*/
|
*/
|
||||||
async readLastSessionHistory(): Promise<{
|
async listSessionNames(): Promise<string[]> {
|
||||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
|
||||||
sessionName: string;
|
|
||||||
} | null> {
|
|
||||||
try {
|
try {
|
||||||
// Check if history directory exists
|
|
||||||
if (!(await this.historyDirExists())) {
|
if (!(await this.historyDirExists())) {
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the most recent session file
|
const files = await this.fs.readdir(this.historyDir);
|
||||||
try {
|
return files
|
||||||
const files = await this.fs.readdir(this.historyDir);
|
.filter(file => file.endsWith('.jsonl'))
|
||||||
const sessionFiles = files
|
.map(file => file.replace('.jsonl', ''))
|
||||||
.filter(file => file.endsWith('.jsonl'))
|
.sort(); // Chronological order (oldest first) - filenames contain timestamps
|
||||||
.sort()
|
} catch {
|
||||||
.reverse(); // Most recent first
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (sessionFiles.length === 0) {
|
/**
|
||||||
return null;
|
* Read messages for a single session
|
||||||
}
|
* @param sessionName The session name (filename without .jsonl)
|
||||||
|
* @returns Array of messages, or empty array if session not found
|
||||||
const latestSessionFile = sessionFiles[0];
|
*/
|
||||||
const sessionPath = join(this.historyDir, latestSessionFile);
|
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
|
||||||
|
try {
|
||||||
|
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
|
||||||
|
const content = await this.fs.readFile(sessionPath, 'utf8');
|
||||||
|
const lines = content.trim().split('\n').filter(line => line.trim());
|
||||||
|
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
try {
|
try {
|
||||||
const content = await this.fs.readFile(sessionPath, 'utf8');
|
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
messages.push(message);
|
||||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
} catch {
|
||||||
|
// Skip malformed lines
|
||||||
for (const line of lines) {
|
|
||||||
try {
|
|
||||||
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
|
||||||
messages.push(message);
|
|
||||||
} catch (parseError) {
|
|
||||||
console.warn('Failed to parse message from history:', parseError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return session name without .jsonl extension
|
|
||||||
const sessionName = latestSessionFile.replace('.jsonl', '');
|
|
||||||
|
|
||||||
return {
|
|
||||||
messages,
|
|
||||||
sessionName
|
|
||||||
};
|
|
||||||
} catch (readError) {
|
|
||||||
console.warn('Failed to read session file:', readError);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
} catch (readdirError) {
|
|
||||||
console.warn('Failed to read history directory:', readdirError);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to read last session history:', error);
|
return messages;
|
||||||
return null;
|
} catch {
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+118
-11
@@ -24,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** AIMessage with session tracking for UI display */
|
||||||
|
export type DisplayMessage = AIMessage & {
|
||||||
|
sessionId?: string; // Session identifier for grouping messages in UI
|
||||||
|
};
|
||||||
|
|
||||||
export interface SessionState {
|
export interface SessionState {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||||
customTools: Record<string, Tool<unknown>>;
|
customTools: Record<string, Tool<unknown>>;
|
||||||
maxSteps?: number;
|
maxSteps?: number;
|
||||||
messages: AIMessage[];
|
messages: AIMessage[]; // Current session messages (sent to AI)
|
||||||
|
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
|
||||||
|
availableSessionNames: string[]; // All session names (for lazy loading)
|
||||||
|
loadedSessionCount: number; // How many sessions loaded from the end
|
||||||
streamingMessage?: {
|
streamingMessage?: {
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
content: string;
|
content: string;
|
||||||
@@ -37,6 +45,7 @@ export interface SessionState {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||||
};
|
};
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
isLoadingMoreHistory: boolean; // Loading older sessions
|
||||||
sessionName: string;
|
sessionName: string;
|
||||||
lastActivity: Date;
|
lastActivity: Date;
|
||||||
abortController?: AbortController;
|
abortController?: AbortController;
|
||||||
@@ -50,8 +59,11 @@ export interface SessionManagerEvents {
|
|||||||
sessionCreated: (projectId: string) => void;
|
sessionCreated: (projectId: string) => void;
|
||||||
sessionDeleted: (projectId: string) => void;
|
sessionDeleted: (projectId: string) => void;
|
||||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||||
|
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
|
||||||
|
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
|
||||||
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
|
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
costUpdated: (projectId: string, totalCost: number) => void;
|
costUpdated: (projectId: string, totalCost: number) => void;
|
||||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||||
fileChanged: (projectId: string, filePath: string) => void;
|
fileChanged: (projectId: string, filePath: string) => void;
|
||||||
@@ -97,7 +109,7 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new session for a project
|
* Create a new session for a project (lazy loading - only loads most recent session)
|
||||||
*/
|
*/
|
||||||
async loadSession(
|
async loadSession(
|
||||||
projectId: string,
|
projectId: string,
|
||||||
@@ -105,18 +117,39 @@ export class SessionManager {
|
|||||||
customTools: Record<string, Tool<unknown>>,
|
customTools: Record<string, Tool<unknown>>,
|
||||||
maxSteps?: number
|
maxSteps?: number
|
||||||
): Promise<SessionState> {
|
): Promise<SessionState> {
|
||||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
const messages: AIMessage[] = [];
|
||||||
|
const displayMessages: DisplayMessage[] = [];
|
||||||
let sessionName = DotAI.generateSessionName();
|
let sessionName = DotAI.generateSessionName();
|
||||||
|
let availableSessionNames: string[] = [];
|
||||||
|
let loadedSessionCount = 0;
|
||||||
let lastFinishReason: string | null | undefined;
|
let lastFinishReason: string | null | undefined;
|
||||||
|
|
||||||
// Try to load existing history
|
// Try to load existing history (lazy - only load last session)
|
||||||
try {
|
try {
|
||||||
const config = this.getConfig();
|
const config = this.getConfig();
|
||||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||||
const lastSession = await dotAI.readLastSessionHistory();
|
|
||||||
if (lastSession) {
|
// Get all available session names (fast - no content loading)
|
||||||
messages = lastSession.messages;
|
availableSessionNames = await dotAI.listSessionNames();
|
||||||
sessionName = lastSession.sessionName;
|
|
||||||
|
if (availableSessionNames.length > 0) {
|
||||||
|
// Only load the most recent session
|
||||||
|
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
|
||||||
|
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
|
||||||
|
|
||||||
|
if (lastSessionMessages.length > 0) {
|
||||||
|
// Add messages with sessionId annotation
|
||||||
|
for (const msg of lastSessionMessages) {
|
||||||
|
displayMessages.push({
|
||||||
|
...msg as AIMessage,
|
||||||
|
sessionId: lastSessionName,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
messages.push(...lastSessionMessages as AIMessage[]);
|
||||||
|
sessionName = lastSessionName;
|
||||||
|
loadedSessionCount = 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load last finish reason
|
// Load last finish reason
|
||||||
@@ -131,22 +164,34 @@ export class SessionManager {
|
|||||||
customTools,
|
customTools,
|
||||||
maxSteps,
|
maxSteps,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
isLoadingMoreHistory: false,
|
||||||
lastActivity: new Date(),
|
lastActivity: new Date(),
|
||||||
totalCost: 0,
|
totalCost: 0,
|
||||||
lastInputTokens: 0,
|
lastInputTokens: 0,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
...this.sessions.get(projectId),
|
...this.sessions.get(projectId),
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
availableSessionNames,
|
||||||
|
loadedSessionCount,
|
||||||
sessionName,
|
sessionName,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Update session configuration
|
// Update session configuration
|
||||||
session.projectId = projectId;
|
session.projectId = projectId;
|
||||||
session.tools = tools;
|
session.tools = tools;
|
||||||
|
|
||||||
session.customTools = customTools;
|
session.customTools = customTools;
|
||||||
session.maxSteps = maxSteps;
|
session.maxSteps = maxSteps;
|
||||||
|
|
||||||
|
// Update messages from loaded history if not already set by an existing session
|
||||||
|
if (!this.sessions.has(projectId)) {
|
||||||
|
session.messages = messages;
|
||||||
|
session.displayMessages = displayMessages;
|
||||||
|
session.availableSessionNames = availableSessionNames;
|
||||||
|
session.loadedSessionCount = loadedSessionCount;
|
||||||
|
session.sessionName = sessionName;
|
||||||
|
}
|
||||||
|
|
||||||
this.sessions.set(projectId, session);
|
this.sessions.set(projectId, session);
|
||||||
|
|
||||||
this.emit('sessionCreated', projectId);
|
this.emit('sessionCreated', projectId);
|
||||||
@@ -187,11 +232,69 @@ export class SessionManager {
|
|||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
if (!session) return;
|
if (!session) return;
|
||||||
|
|
||||||
|
// Add to current session messages (for AI prompts)
|
||||||
session.messages.push(message);
|
session.messages.push(message);
|
||||||
|
|
||||||
|
// Also add to display messages with session ID annotation (for UI)
|
||||||
|
const displayMessage: DisplayMessage = { ...message, sessionId: session.sessionName };
|
||||||
|
session.displayMessages.push(displayMessage);
|
||||||
|
|
||||||
session.lastActivity = new Date();
|
session.lastActivity = new Date();
|
||||||
|
|
||||||
await this.saveSessionHistory(projectId);
|
await this.saveSessionHistory(projectId);
|
||||||
this.emit('messageAdded', projectId, message);
|
this.emit('messageAdded', projectId, message);
|
||||||
|
this.emit('displayMessageAdded', projectId, displayMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if there are more historical sessions to load
|
||||||
|
*/
|
||||||
|
hasMoreHistory(projectId: string): boolean {
|
||||||
|
const session = this.sessions.get(projectId);
|
||||||
|
if (!session) return false;
|
||||||
|
return session.loadedSessionCount < session.availableSessionNames.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the next older session and prepend to displayMessages
|
||||||
|
*/
|
||||||
|
async loadOlderSession(projectId: string): Promise<void> {
|
||||||
|
const session = this.sessions.get(projectId);
|
||||||
|
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
|
||||||
|
|
||||||
|
session.isLoadingMoreHistory = true;
|
||||||
|
this.emit('loadingMoreHistoryChanged', projectId, true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const config = this.getConfig();
|
||||||
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||||
|
|
||||||
|
// Get the next older session (counting from the end)
|
||||||
|
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
|
||||||
|
if (nextIndex < 0) return;
|
||||||
|
|
||||||
|
const olderSessionName = session.availableSessionNames[nextIndex];
|
||||||
|
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
|
||||||
|
|
||||||
|
if (olderMessages.length > 0) {
|
||||||
|
// Create display messages with sessionId
|
||||||
|
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
|
||||||
|
...msg as AIMessage,
|
||||||
|
sessionId: olderSessionName,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Prepend to displayMessages
|
||||||
|
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
|
||||||
|
session.loadedSessionCount++;
|
||||||
|
|
||||||
|
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to load older session:', error);
|
||||||
|
} finally {
|
||||||
|
session.isLoadingMoreHistory = false;
|
||||||
|
this.emit('loadingMoreHistoryChanged', projectId, false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -699,7 +802,7 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start a new session (clear messages but keep configuration)
|
* Start a new session (clear AI messages but keep display history)
|
||||||
*/
|
*/
|
||||||
async startNewSession(projectId: string): Promise<void> {
|
async startNewSession(projectId: string): Promise<void> {
|
||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
@@ -707,9 +810,13 @@ export class SessionManager {
|
|||||||
|
|
||||||
this.stopGeneration(projectId);
|
this.stopGeneration(projectId);
|
||||||
|
|
||||||
|
// Generate new session name - new messages will automatically get this sessionId
|
||||||
|
const newSessionName = DotAI.generateSessionName();
|
||||||
|
|
||||||
|
// Clear only the AI prompt messages (not display messages)
|
||||||
session.messages = [];
|
session.messages = [];
|
||||||
session.streamingMessage = undefined;
|
session.streamingMessage = undefined;
|
||||||
session.sessionName = DotAI.generateSessionName();
|
session.sessionName = newSessionName;
|
||||||
session.lastActivity = new Date();
|
session.lastActivity = new Date();
|
||||||
session.totalCost = 0;
|
session.totalCost = 0;
|
||||||
session.lastInputTokens = 0;
|
session.lastInputTokens = 0;
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anonymous",
|
"anonymous": "Anonymous",
|
||||||
"logIn": "Log in",
|
"logIn": "Log in",
|
||||||
"signUp": "Sign up",
|
"signUp": "Sign up",
|
||||||
|
"newChat": "New Chat",
|
||||||
|
"loadOlderMessages": "Load older messages",
|
||||||
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
||||||
"theme": "Theme",
|
"theme": "Theme",
|
||||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Maras Suna",
|
"anonymous": "Maras Suna",
|
||||||
"logIn": "Shiga",
|
"logIn": "Shiga",
|
||||||
"signUp": "Yi Rajista",
|
"signUp": "Yi Rajista",
|
||||||
|
"newChat": "Sabon Tattaunawa",
|
||||||
|
"loadOlderMessages": "Loda saƙonni masu tsufa",
|
||||||
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
||||||
"theme": "Jigogi",
|
"theme": "Jigogi",
|
||||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Onye na-amaghị aha",
|
"anonymous": "Onye na-amaghị aha",
|
||||||
"logIn": "Banye",
|
"logIn": "Banye",
|
||||||
"signUp": "Debanye aha",
|
"signUp": "Debanye aha",
|
||||||
|
"newChat": "Nkata Ọhụrụ",
|
||||||
|
"loadOlderMessages": "Bulite ozi ochie",
|
||||||
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
||||||
"theme": "Isiokwu",
|
"theme": "Isiokwu",
|
||||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anônimo",
|
"anonymous": "Anônimo",
|
||||||
"logIn": "Entrar",
|
"logIn": "Entrar",
|
||||||
"signUp": "Cadastrar",
|
"signUp": "Cadastrar",
|
||||||
|
"newChat": "Nova Conversa",
|
||||||
|
"loadOlderMessages": "Carregar mensagens anteriores",
|
||||||
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
||||||
"theme": "Tema",
|
"theme": "Tema",
|
||||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Alainidamọ",
|
"anonymous": "Alainidamọ",
|
||||||
"logIn": "Wọle",
|
"logIn": "Wọle",
|
||||||
"signUp": "Forukọsilẹ",
|
"signUp": "Forukọsilẹ",
|
||||||
|
"newChat": "Ọrọ Tuntun",
|
||||||
|
"loadOlderMessages": "Gbe awọn ifiranṣẹ atijọ",
|
||||||
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
||||||
"theme": "Akori",
|
"theme": "Akori",
|
||||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "匿名",
|
"anonymous": "匿名",
|
||||||
"logIn": "登录",
|
"logIn": "登录",
|
||||||
"signUp": "注册",
|
"signUp": "注册",
|
||||||
|
"newChat": "新对话",
|
||||||
|
"loadOlderMessages": "加载更早的消息",
|
||||||
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
||||||
"theme": "主题",
|
"theme": "主题",
|
||||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||||
|
|||||||
Reference in new issue
Block a user