diff --git a/package-lock.json b/package-lock.json index b3eb7183..eb308bfe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -195,6 +195,7 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -1830,6 +1831,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1853,6 +1855,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -1874,6 +1877,7 @@ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "license": "MIT", + "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -5442,8 +5446,7 @@ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/chrome": { "version": "0.0.74", @@ -5655,6 +5658,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz", "integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==", "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" @@ -5666,6 +5670,7 @@ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "devOptional": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^18.0.0" } @@ -5749,6 +5754,7 @@ "integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.31.1", "@typescript-eslint/types": "8.31.1", @@ -6108,6 +6114,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -6622,6 +6629,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -6851,6 +6859,7 @@ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "license": "MIT", + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -7610,8 +7619,7 @@ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/dom-helpers": { "version": "5.2.1", @@ -7676,7 +7684,8 @@ "version": "8.6.0", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/embla-carousel-react": { "version": "8.6.0", @@ -7962,6 +7971,7 @@ "integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", @@ -8227,6 +8237,7 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", "license": "MIT", + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.0", @@ -9324,6 +9335,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.27.6" }, @@ -10117,6 +10129,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -10501,7 +10514,6 @@ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -12255,6 +12267,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -12422,7 +12435,6 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -12438,7 +12450,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -12449,7 +12460,6 @@ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -12462,8 +12472,7 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/prismjs": { "version": "1.30.0", @@ -12637,6 +12646,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -12663,6 +12673,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -12688,6 +12699,7 @@ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", "integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=18.0.0" }, @@ -12736,6 +12748,7 @@ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", "license": "MIT", + "peer": true, "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", @@ -13278,6 +13291,7 @@ "integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@types/estree": "1.0.7" }, @@ -14332,6 +14346,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -14535,6 +14550,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -14830,6 +14846,7 @@ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -15357,6 +15374,7 @@ "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -15501,6 +15519,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -15972,6 +15991,7 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -16048,6 +16068,7 @@ "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -16496,6 +16517,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/src/components/SessionDivider.tsx b/src/components/SessionDivider.tsx new file mode 100644 index 00000000..e7f5e612 --- /dev/null +++ b/src/components/SessionDivider.tsx @@ -0,0 +1,16 @@ +import { useTranslation } from 'react-i18next'; + +/** Visual divider between chat sessions */ +export function SessionDivider() { + const { t } = useTranslation(); + + return ( +
+
+ + {t('newChat', 'New chat')} + +
+
+ ); +} diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f65afe90..f7238ada 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -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(({ const { messages, + displayMessages, + sessionBoundaries, streamingMessage, isLoading: internalIsLoading, isLoadingHistory, @@ -318,7 +321,7 @@ export const ChatPane = forwardRef(({ 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(({ }; 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(({ )} {/* Empty state when no messages and not loading */} - {!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && ( + {!isLoadingHistory && displayMessages.length === 0 && !streamingMessage && !isLoading && (
@@ -781,13 +784,22 @@ export const ChatPane = forwardRef(({
)} - {!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(({ } return ( - + className={isOlderSession ? 'opacity-65' : ''} + > + {boundary && } + +
); })} + {/* Trailing session divider - shown immediately when "New Chat" is clicked */} + {!isLoadingHistory && (() => { + const trailingBoundary = sessionBoundaries.find( + (b: SessionBoundary) => b.index === displayMessages.length + ); + return trailingBoundary ? : null; + })()} + {!isLoadingHistory && renderStreamingMessage()} {/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */} diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index 8e5031b8..688305d7 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -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([]); + const [displayMessages, setDisplayMessages] = useState([]); + const [sessionBoundaries, setSessionBoundaries] = useState([]); const [streamingMessage, setStreamingMessage] = useState(undefined); const [isLoading, setIsLoading] = useState(false); const [totalCost, setTotalCost] = useState(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, @@ -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, diff --git a/src/lib/DotAI.ts b/src/lib/DotAI.ts index cecd7ce9..b2d37c5b 100644 --- a/src/lib/DotAI.ts +++ b/src/lib/DotAI.ts @@ -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> { + 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 diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 0a177286..0dbc80a7 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -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; customTools: Record>; 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>, maxSteps?: number ): Promise { - 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 { 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;