mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +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": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4502,7 +4501,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4516,7 +4514,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4530,7 +4527,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4544,7 +4540,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4558,7 +4553,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4572,7 +4566,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4586,7 +4579,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4600,7 +4592,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4614,7 +4605,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4628,7 +4618,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4642,7 +4631,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4656,7 +4644,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4670,7 +4657,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4684,7 +4670,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4698,7 +4683,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4712,7 +4696,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4726,7 +4709,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4740,7 +4722,6 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4754,7 +4735,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -115,7 +115,7 @@ export function ProjectTitleMenu({
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
New Chat
|
||||
{t('newChat')}
|
||||
</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 { Skeleton } from '@/components/ui/skeleton';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { ChevronDown, Play } from 'lucide-react';
|
||||
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
@@ -47,11 +47,12 @@ import OpenAI from 'openai';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { SessionDivider } from '@/components/SessionDivider';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage } from '@/lib/SessionManager';
|
||||
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -294,9 +295,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
const {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
isLoadingHistory,
|
||||
hasMoreHistory,
|
||||
isLoadingMoreHistory,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
lastFinishReason,
|
||||
@@ -305,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
startNewSession: internalStartNewSession,
|
||||
loadMoreHistory,
|
||||
} = useAIChat({
|
||||
projectId,
|
||||
tools,
|
||||
@@ -318,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const checkTemplateInfo = async () => {
|
||||
try {
|
||||
// Only check if we have at least 1 message
|
||||
if (messages.length === 0) {
|
||||
if (displayMessages.length === 0) {
|
||||
setShowTemplateInfo(false);
|
||||
return;
|
||||
}
|
||||
@@ -357,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
};
|
||||
|
||||
checkTemplateInfo();
|
||||
}, [fs, projectsPath, projectId, messages.length]);
|
||||
}, [fs, projectsPath, projectId, displayMessages.length]);
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(async () => {
|
||||
@@ -436,7 +442,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = useCallback(() => {
|
||||
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(() => {
|
||||
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 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;
|
||||
|
||||
// Only auto-scroll if user was already near the bottom
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
// Scroll to bottom if user sent a message or was already near the bottom
|
||||
if (isUserMessage || isNearBottom) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}
|
||||
}, [messages, streamingMessage, isLoading]);
|
||||
}, [messages, streamingMessage, isLoading, scrollToBottom]);
|
||||
|
||||
// Scroll to bottom when first visiting a project (including page refresh)
|
||||
useEffect(() => {
|
||||
@@ -577,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// Scroll to bottom when user sends a message
|
||||
scrollToBottom();
|
||||
|
||||
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
|
||||
const handleTextareaFocus = useCallback(() => {
|
||||
@@ -757,7 +773,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
)}
|
||||
|
||||
{/* 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="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="mb-6">
|
||||
@@ -781,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</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
|
||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||
if (message.role === 'tool') {
|
||||
// Look backwards to find the assistant message with matching tool call
|
||||
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) {
|
||||
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
||||
if (toolCall) break;
|
||||
@@ -796,14 +848,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return (
|
||||
<AIMessageItem
|
||||
<div
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
/>
|
||||
className={isOlderSession ? 'opacity-65' : ''}
|
||||
>
|
||||
{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()}
|
||||
|
||||
{/* 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 { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
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 { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
@@ -39,12 +39,16 @@ export function useAIChat({
|
||||
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
|
||||
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
|
||||
|
||||
const initSession = useCallback(async () => {
|
||||
setIsLoadingHistory(true);
|
||||
@@ -53,11 +57,15 @@ export function useAIChat({
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setDisplayMessages([...session.displayMessages]);
|
||||
setSessionName(session.sessionName);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
setLastFinishReason(session.lastFinishReason ?? null);
|
||||
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
|
||||
} finally {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
@@ -123,6 +131,25 @@ export function useAIChat({
|
||||
}
|
||||
}, [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
|
||||
const sendMessage = useCallback(async (
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
@@ -164,7 +191,13 @@ export function useAIChat({
|
||||
const startNewSession = useCallback(async () => {
|
||||
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([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
@@ -177,11 +210,19 @@ export function useAIChat({
|
||||
await startNewSession();
|
||||
}, [startNewSession]);
|
||||
|
||||
const loadMoreHistory = useCallback(async () => {
|
||||
await sessionManager.loadOlderSession(projectId);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
return {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
isLoadingHistory,
|
||||
hasMoreHistory,
|
||||
isLoadingMoreHistory,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
lastFinishReason,
|
||||
@@ -191,6 +232,7 @@ export function useAIChat({
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
loadMoreHistory,
|
||||
isConfigured,
|
||||
projectId
|
||||
};
|
||||
|
||||
@@ -27,73 +27,6 @@ describe('DotAI', () => {
|
||||
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', () => {
|
||||
it('should create history directory if it does not exist', async () => {
|
||||
// Mock historyDirExists to return false initially
|
||||
|
||||
+34
-50
@@ -216,66 +216,50 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the most recent session history
|
||||
* @returns Object containing messages array and session name, or null if no history found
|
||||
* List all session names sorted chronologically (oldest first)
|
||||
* Fast operation - does not load message content
|
||||
* @returns Array of session names (filenames without .jsonl extension)
|
||||
*/
|
||||
async readLastSessionHistory(): Promise<{
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
sessionName: string;
|
||||
} | null> {
|
||||
async listSessionNames(): Promise<string[]> {
|
||||
try {
|
||||
// Check if history directory exists
|
||||
if (!(await this.historyDirExists())) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
// Find the most recent session file
|
||||
try {
|
||||
const files = await this.fs.readdir(this.historyDir);
|
||||
const sessionFiles = files
|
||||
.filter(file => file.endsWith('.jsonl'))
|
||||
.sort()
|
||||
.reverse(); // Most recent first
|
||||
const files = await this.fs.readdir(this.historyDir);
|
||||
return files
|
||||
.filter(file => file.endsWith('.jsonl'))
|
||||
.map(file => file.replace('.jsonl', ''))
|
||||
.sort(); // Chronological order (oldest first) - filenames contain timestamps
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (sessionFiles.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const latestSessionFile = sessionFiles[0];
|
||||
const sessionPath = join(this.historyDir, latestSessionFile);
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
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 {
|
||||
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 {
|
||||
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;
|
||||
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
messages.push(message);
|
||||
} catch {
|
||||
// Skip malformed lines
|
||||
}
|
||||
} catch (readdirError) {
|
||||
console.warn('Failed to read history directory:', readdirError);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read last session history:', error);
|
||||
return null;
|
||||
|
||||
return messages;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+118
-11
@@ -24,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
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 {
|
||||
projectId: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
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?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
@@ -37,6 +45,7 @@ export interface SessionState {
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
isLoading: boolean;
|
||||
isLoadingMoreHistory: boolean; // Loading older sessions
|
||||
sessionName: string;
|
||||
lastActivity: Date;
|
||||
abortController?: AbortController;
|
||||
@@ -50,8 +59,11 @@ export interface SessionManagerEvents {
|
||||
sessionCreated: (projectId: string) => void;
|
||||
sessionDeleted: (projectId: string) => 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;
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
contextUsageUpdated: (projectId: string, inputTokens: number) => 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(
|
||||
projectId: string,
|
||||
@@ -105,18 +117,39 @@ export class SessionManager {
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
const messages: AIMessage[] = [];
|
||||
const displayMessages: DisplayMessage[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
let availableSessionNames: string[] = [];
|
||||
let loadedSessionCount = 0;
|
||||
let lastFinishReason: string | null | undefined;
|
||||
|
||||
// Try to load existing history
|
||||
// Try to load existing history (lazy - only load last session)
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
sessionName = lastSession.sessionName;
|
||||
|
||||
// Get all available session names (fast - no content loading)
|
||||
availableSessionNames = await dotAI.listSessionNames();
|
||||
|
||||
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
|
||||
@@ -131,21 +164,33 @@ export class SessionManager {
|
||||
customTools,
|
||||
maxSteps,
|
||||
isLoading: false,
|
||||
isLoadingMoreHistory: false,
|
||||
lastActivity: new Date(),
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
lastFinishReason,
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
displayMessages,
|
||||
availableSessionNames,
|
||||
loadedSessionCount,
|
||||
sessionName,
|
||||
};
|
||||
|
||||
// Update session configuration
|
||||
session.projectId = projectId;
|
||||
session.tools = tools;
|
||||
|
||||
session.customTools = customTools;
|
||||
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);
|
||||
|
||||
@@ -187,11 +232,69 @@ export class SessionManager {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// Add to current session messages (for AI prompts)
|
||||
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();
|
||||
|
||||
await this.saveSessionHistory(projectId);
|
||||
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> {
|
||||
const session = this.sessions.get(projectId);
|
||||
@@ -707,9 +810,13 @@ export class SessionManager {
|
||||
|
||||
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.streamingMessage = undefined;
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.sessionName = newSessionName;
|
||||
session.lastActivity = new Date();
|
||||
session.totalCost = 0;
|
||||
session.lastInputTokens = 0;
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Anonymous",
|
||||
"logIn": "Log in",
|
||||
"signUp": "Sign up",
|
||||
"newChat": "New Chat",
|
||||
"loadOlderMessages": "Load older messages",
|
||||
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
||||
"theme": "Theme",
|
||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Maras Suna",
|
||||
"logIn": "Shiga",
|
||||
"signUp": "Yi Rajista",
|
||||
"newChat": "Sabon Tattaunawa",
|
||||
"loadOlderMessages": "Loda saƙonni masu tsufa",
|
||||
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
||||
"theme": "Jigogi",
|
||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Onye na-amaghị aha",
|
||||
"logIn": "Banye",
|
||||
"signUp": "Debanye aha",
|
||||
"newChat": "Nkata Ọhụrụ",
|
||||
"loadOlderMessages": "Bulite ozi ochie",
|
||||
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
||||
"theme": "Isiokwu",
|
||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Anônimo",
|
||||
"logIn": "Entrar",
|
||||
"signUp": "Cadastrar",
|
||||
"newChat": "Nova Conversa",
|
||||
"loadOlderMessages": "Carregar mensagens anteriores",
|
||||
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
||||
"theme": "Tema",
|
||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Alainidamọ",
|
||||
"logIn": "Wọle",
|
||||
"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.",
|
||||
"theme": "Akori",
|
||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "匿名",
|
||||
"logIn": "登录",
|
||||
"signUp": "注册",
|
||||
"newChat": "新对话",
|
||||
"loadOlderMessages": "加载更早的消息",
|
||||
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
||||
"theme": "主题",
|
||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||
|
||||
Reference in new issue
Block a user