mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
remove redundant tracking, add session ids
This commit is contained in:
1 parent
66bfb56694
commit
a07368b190
3 files changed
+50
-68
No files matched your search
@@ -52,7 +52,7 @@ import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage, SessionBoundary } from '@/lib/SessionManager';
|
||||
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -296,7 +296,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
isLoadingHistory,
|
||||
@@ -785,14 +785,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
)}
|
||||
|
||||
{!isLoadingHistory && displayMessages.map((message, index) => {
|
||||
// Check if there's a session boundary at this index
|
||||
const boundary = sessionBoundaries.find((b: SessionBoundary) => b.index === index);
|
||||
// Get the current and last session IDs to derive boundaries
|
||||
const currentSessionId = (message as DisplayMessage)._sessionId;
|
||||
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage)._sessionId : undefined;
|
||||
const lastSessionId = displayMessages.length > 0
|
||||
? (displayMessages[displayMessages.length - 1] as DisplayMessage)._sessionId
|
||||
: undefined;
|
||||
|
||||
// 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;
|
||||
// Show divider when session changes (not on first message)
|
||||
const showDivider = index > 0 && currentSessionId !== prevSessionId;
|
||||
|
||||
// Determine if this message is from an older session
|
||||
const isOlderSession = currentSessionId !== lastSessionId;
|
||||
|
||||
// Find the corresponding tool call for tool messages
|
||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||
@@ -812,7 +816,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
className={isOlderSession ? 'opacity-65' : ''}
|
||||
>
|
||||
{boundary && <SessionDivider />}
|
||||
{showDivider && <SessionDivider />}
|
||||
<AIMessageItem
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
@@ -821,12 +825,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 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;
|
||||
{/* 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()}
|
||||
|
||||
+12
-12
@@ -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, SessionBoundary } from '@/lib/SessionManager';
|
||||
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
@@ -39,8 +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 [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);
|
||||
@@ -56,7 +56,7 @@ export function useAIChat({
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setDisplayMessages([...session.displayMessages]);
|
||||
setSessionBoundaries([...session.sessionBoundaries]);
|
||||
setSessionName(session.sessionName);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
@@ -127,18 +127,12 @@ export function useAIChat({
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: AIMessage) => {
|
||||
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
|
||||
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>,
|
||||
@@ -180,6 +174,12 @@ export function useAIChat({
|
||||
const startNewSession = useCallback(async () => {
|
||||
await sessionManager.startNewSession(projectId);
|
||||
|
||||
// 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);
|
||||
@@ -196,7 +196,7 @@ export function useAIChat({
|
||||
return {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
isLoadingHistory,
|
||||
|
||||
+18
-40
@@ -24,12 +24,10 @@ 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
|
||||
}
|
||||
/** 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;
|
||||
@@ -37,8 +35,7 @@ export interface SessionState {
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
maxSteps?: number;
|
||||
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
|
||||
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with _sessionId)
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
@@ -59,8 +56,7 @@ 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;
|
||||
displayMessageAdded: (projectId: string, message: DisplayMessage) => 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;
|
||||
@@ -117,8 +113,7 @@ export class SessionManager {
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
const messages: AIMessage[] = [];
|
||||
const displayMessages: AIMessage[] = [];
|
||||
const sessionBoundaries: SessionBoundary[] = [];
|
||||
const displayMessages: DisplayMessage[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
let lastFinishReason: string | null | undefined;
|
||||
|
||||
@@ -131,19 +126,15 @@ export class SessionManager {
|
||||
const allSessions = await dotAI.readAllSessionHistories();
|
||||
|
||||
if (allSessions.length > 0) {
|
||||
// Build displayMessages and sessionBoundaries from all sessions
|
||||
// Build displayMessages with _sessionId annotations
|
||||
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 with _sessionId annotation
|
||||
for (const msg of session.messages) {
|
||||
displayMessages.push({
|
||||
...msg as AIMessage,
|
||||
_sessionId: session.sessionName,
|
||||
});
|
||||
}
|
||||
|
||||
// Add all messages from this session to displayMessages
|
||||
displayMessages.push(...session.messages as AIMessage[]);
|
||||
}
|
||||
|
||||
// Current session messages come from the last session
|
||||
@@ -171,7 +162,6 @@ export class SessionManager {
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionBoundaries,
|
||||
sessionName,
|
||||
};
|
||||
|
||||
@@ -185,7 +175,6 @@ export class SessionManager {
|
||||
if (!this.sessions.has(projectId)) {
|
||||
session.messages = messages;
|
||||
session.displayMessages = displayMessages;
|
||||
session.sessionBoundaries = sessionBoundaries;
|
||||
session.sessionName = sessionName;
|
||||
}
|
||||
|
||||
@@ -232,14 +221,15 @@ export class SessionManager {
|
||||
// Add to current session messages (for AI prompts)
|
||||
session.messages.push(message);
|
||||
|
||||
// Also add to display messages (for UI)
|
||||
session.displayMessages.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, message);
|
||||
this.emit('displayMessageAdded', projectId, displayMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -755,20 +745,8 @@ export class SessionManager {
|
||||
|
||||
this.stopGeneration(projectId);
|
||||
|
||||
// Generate new session name and timestamp
|
||||
// Generate new session name - new messages will automatically get this _sessionId
|
||||
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 = [];
|
||||
|
||||
Reference in new issue
Block a user