mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
feat: maintain continuous chat history after new chat start
This commit is contained in:
1 parent
6edc623c13
commit
3cb7a8f673
6 files changed
+253
-31
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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, SessionBoundary } from '@/lib/SessionManager';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -294,6 +295,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
const {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
isLoadingHistory,
|
||||
@@ -318,7 +321,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 +360,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 () => {
|
||||
@@ -757,7 +760,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 +784,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoadingHistory && messages.map((message, index) => {
|
||||
{!isLoadingHistory && displayMessages.map((message, index) => {
|
||||
// Check if there's a session boundary at this index
|
||||
const boundary = sessionBoundaries.find((b: SessionBoundary) => b.index === index);
|
||||
|
||||
// Determine if this message is from an older session (before the last boundary)
|
||||
const lastBoundaryIndex = sessionBoundaries.length > 0
|
||||
? sessionBoundaries[sessionBoundaries.length - 1].index
|
||||
: -1;
|
||||
const isOlderSession = lastBoundaryIndex > 0 && index < lastBoundaryIndex;
|
||||
|
||||
// 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 +808,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' : ''}
|
||||
>
|
||||
{boundary && <SessionDivider />}
|
||||
<AIMessageItem
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Trailing session divider - shown immediately when "New Chat" is clicked */}
|
||||
{!isLoadingHistory && (() => {
|
||||
const trailingBoundary = sessionBoundaries.find(
|
||||
(b: SessionBoundary) => b.index === displayMessages.length
|
||||
);
|
||||
return trailingBoundary ? <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) */}
|
||||
|
||||
+20
-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, SessionBoundary } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
@@ -39,6 +39,8 @@ export function useAIChat({
|
||||
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [displayMessages, setDisplayMessages] = useState<AIMessage[]>([]);
|
||||
const [sessionBoundaries, setSessionBoundaries] = useState<SessionBoundary[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
@@ -53,6 +55,8 @@ 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]);
|
||||
setSessionBoundaries([...session.sessionBoundaries]);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
@@ -123,6 +127,18 @@ export function useAIChat({
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: AIMessage) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setDisplayMessages(prev => [...prev, message]);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('sessionBoundaryAdded', (updatedProjectId: string, boundary: SessionBoundary) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setSessionBoundaries(prev => [...prev, boundary]);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
@@ -164,7 +180,7 @@ export function useAIChat({
|
||||
const startNewSession = useCallback(async () => {
|
||||
await sessionManager.startNewSession(projectId);
|
||||
|
||||
// Reset individual state variables
|
||||
// Reset only AI prompt state (not display state which is handled via events)
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
@@ -179,6 +195,8 @@ export function useAIChat({
|
||||
|
||||
return {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
isLoadingHistory,
|
||||
|
||||
@@ -215,6 +215,83 @@ export class DotAI {
|
||||
await this.writeAiParameters(currentParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse timestamp from session name (format: YYYY-MM-DDTHH-MM-SSZ-suffix)
|
||||
*/
|
||||
static parseSessionTimestamp(sessionName: string): Date {
|
||||
// Session name format: 2024-01-10T12-30-45Z-abc
|
||||
// Need to convert back to ISO format: 2024-01-10T12:30:45Z
|
||||
const match = sessionName.match(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})Z/);
|
||||
if (match) {
|
||||
const [, date, hour, min, sec] = match;
|
||||
return new Date(`${date}T${hour}:${min}:${sec}Z`);
|
||||
}
|
||||
// Fallback to current time if parsing fails
|
||||
return new Date();
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all session histories sorted chronologically
|
||||
* @returns Array of session histories with messages and timestamps
|
||||
*/
|
||||
async readAllSessionHistories(): Promise<Array<{
|
||||
sessionName: string;
|
||||
timestamp: Date;
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
}>> {
|
||||
const sessions: Array<{
|
||||
sessionName: string;
|
||||
timestamp: Date;
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
if (!(await this.historyDirExists())) {
|
||||
return sessions;
|
||||
}
|
||||
|
||||
const files = await this.fs.readdir(this.historyDir);
|
||||
const sessionFiles = files
|
||||
.filter(file => file.endsWith('.jsonl'))
|
||||
.sort(); // Chronological order (oldest first)
|
||||
|
||||
for (const file of sessionFiles) {
|
||||
const sessionPath = join(this.historyDir, file);
|
||||
const sessionName = file.replace('.jsonl', '');
|
||||
|
||||
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 {
|
||||
// Skip malformed lines
|
||||
}
|
||||
}
|
||||
|
||||
// Only include sessions with messages
|
||||
if (messages.length > 0) {
|
||||
sessions.push({
|
||||
sessionName,
|
||||
timestamp: DotAI.parseSessionTimestamp(sessionName),
|
||||
messages,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Skip unreadable files
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read all session histories:', error);
|
||||
}
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the most recent session history
|
||||
* @returns Object containing messages array and session name, or null if no history found
|
||||
|
||||
@@ -24,12 +24,21 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
|
||||
/** Marks where a new chat session begins in the display messages */
|
||||
export interface SessionBoundary {
|
||||
index: number; // Index in displayMessages where this session starts
|
||||
timestamp: Date; // When the session was created
|
||||
sessionName: string; // The session name
|
||||
}
|
||||
|
||||
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: AIMessage[]; // All messages from all sessions (for UI)
|
||||
sessionBoundaries: SessionBoundary[]; // Where new sessions start in displayMessages
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
@@ -50,6 +59,8 @@ export interface SessionManagerEvents {
|
||||
sessionCreated: (projectId: string) => void;
|
||||
sessionDeleted: (projectId: string) => void;
|
||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||
displayMessageAdded: (projectId: string, message: AIMessage) => void;
|
||||
sessionBoundaryAdded: (projectId: string, boundary: SessionBoundary) => void;
|
||||
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
@@ -105,7 +116,9 @@ export class SessionManager {
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
const messages: AIMessage[] = [];
|
||||
const displayMessages: AIMessage[] = [];
|
||||
const sessionBoundaries: SessionBoundary[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
let lastFinishReason: string | null | undefined;
|
||||
|
||||
@@ -113,9 +126,29 @@ export class SessionManager {
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
|
||||
// Load all session histories for display
|
||||
const allSessions = await dotAI.readAllSessionHistories();
|
||||
|
||||
if (allSessions.length > 0) {
|
||||
// Build displayMessages and sessionBoundaries from all sessions
|
||||
for (const session of allSessions) {
|
||||
// Add boundary marker at the start of each session (except the first)
|
||||
if (displayMessages.length > 0) {
|
||||
sessionBoundaries.push({
|
||||
index: displayMessages.length,
|
||||
timestamp: session.timestamp,
|
||||
sessionName: session.sessionName,
|
||||
});
|
||||
}
|
||||
|
||||
// Add all messages from this session to displayMessages
|
||||
displayMessages.push(...session.messages as AIMessage[]);
|
||||
}
|
||||
|
||||
// Current session messages come from the last session
|
||||
const lastSession = allSessions[allSessions.length - 1];
|
||||
messages.push(...lastSession.messages as AIMessage[]);
|
||||
sessionName = lastSession.sessionName;
|
||||
}
|
||||
|
||||
@@ -137,15 +170,24 @@ export class SessionManager {
|
||||
lastFinishReason,
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
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.sessionBoundaries = sessionBoundaries;
|
||||
session.sessionName = sessionName;
|
||||
}
|
||||
|
||||
this.sessions.set(projectId, session);
|
||||
|
||||
@@ -187,11 +229,17 @@ 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 (for UI)
|
||||
session.displayMessages.push(message);
|
||||
|
||||
session.lastActivity = new Date();
|
||||
|
||||
await this.saveSessionHistory(projectId);
|
||||
this.emit('messageAdded', projectId, message);
|
||||
this.emit('displayMessageAdded', projectId, message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -699,7 +747,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 +755,25 @@ export class SessionManager {
|
||||
|
||||
this.stopGeneration(projectId);
|
||||
|
||||
// Generate new session name and timestamp
|
||||
const newSessionName = DotAI.generateSessionName();
|
||||
const newTimestamp = DotAI.parseSessionTimestamp(newSessionName);
|
||||
|
||||
// Add boundary marker if there are existing display messages
|
||||
if (session.displayMessages.length > 0) {
|
||||
const boundary: SessionBoundary = {
|
||||
index: session.displayMessages.length,
|
||||
timestamp: newTimestamp,
|
||||
sessionName: newSessionName,
|
||||
};
|
||||
session.sessionBoundaries.push(boundary);
|
||||
this.emit('sessionBoundaryAdded', projectId, boundary);
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
Reference in new issue
Block a user