refactor session history logic

This commit is contained in:
Nate 2025-08-26 14:42:49 -07:00
parent b5933cedeb
commit e95d366e22
9 changed files with 112 additions and 168 deletions

View file

@ -22,7 +22,7 @@ import { sentryService } from "../sentry.js";
import { initializeServices } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
import { loadSession, saveSession } from "../session.js";
import { loadSession, updateSessionHistory } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
@ -138,7 +138,7 @@ async function handleManualCompaction(
chatHistory.push(...result.compactedHistory);
// Save the compacted session
saveSession(chatHistory);
updateSessionHistory(chatHistory);
if (isHeadless) {
safeStdout(
@ -351,7 +351,7 @@ async function processMessage(
}
// Save session after each successful response
saveSession(chatHistory);
updateSessionHistory(chatHistory);
} catch (e: any) {
const error = e instanceof Error ? e : new Error(String(e));

View file

@ -19,7 +19,7 @@ import {
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import { saveSession, createSession } from "../session.js";
import { createSession, updateSessionHistory } from "../session.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { formatError } from "../util/formatError.js";
@ -355,7 +355,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
);
// Save session after successful response
saveSession(state.session);
updateSessionHistory(state.session.history);
state.lastActivity = Date.now();
} catch (e: any) {

View file

@ -14,14 +14,14 @@ describe("convertFromUnifiedHistory", () => {
{
id: {
providerTitle: "file",
itemId: "attached-file-0",
itemId: "550e8400-e29b-41d4-a716-446655440000",
},
content: "console.log('Hello, world!');",
name: "test-file.txt",
description: "File: test-file.txt",
uri: {
type: "file",
value: "test-file.txt",
value: "file:///Users/user/test-file.txt",
},
},
],
@ -69,27 +69,27 @@ describe("convertFromUnifiedHistory", () => {
{
id: {
providerTitle: "file",
itemId: "attached-file-0",
itemId: "550e8400-e29b-41d4-a716-446655440000",
},
content: "const a = 1;",
name: "file1.js",
description: "File: file1.js",
uri: {
type: "file",
value: "file1.js",
value: "file:///Users/user/file1.js",
},
},
{
id: {
providerTitle: "file",
itemId: "attached-file-1",
itemId: "550e8400-e29b-41d4-a716-446655440001",
},
content: "const b = 2;",
name: "file2.js",
description: "File: file2.js",
uri: {
type: "file",
value: "file2.js",
value: "file:///Users/user/file2.js",
},
},
],
@ -117,14 +117,14 @@ describe("convertFromUnifiedHistory", () => {
{
id: {
providerTitle: "file",
itemId: "attached-file-0",
itemId: "550e8400-e29b-41d4-a716-446655440000",
},
content: "some content",
name: "file.txt",
description: "File: file.txt",
uri: {
type: "file",
value: "file.txt",
value: "file:///Users/user/file.txt",
},
},
],

View file

@ -14,12 +14,28 @@ import {
updateSessionTitle,
} from "./session.js";
// Mock dependencies
// Mock dependencies first, before any imports
vi.mock("os", () => ({
default: {
homedir: vi.fn(() => "/home/test"),
},
}));
vi.mock("fs");
vi.mock("os");
vi.mock("uuid", () => ({
v4: vi.fn(() => "test-uuid-123"),
}));
vi.mock("../../../core/util/history.js", () => ({
default: {
save: vi.fn(),
load: vi.fn(() => ({
sessionId: "test-session-id",
title: "Test Session",
workspaceDirectory: "/test/workspace",
history: [],
})),
list: vi.fn(() => []),
},
}));
const mockFs = vi.mocked(fs);
const mockOs = vi.mocked(os);
@ -84,6 +100,7 @@ describe("SessionManager", () => {
role: "user",
content: "Hello",
},
contextItems: [],
},
];
@ -109,6 +126,7 @@ describe("SessionManager", () => {
role: "user",
content: "New message",
},
contextItems: [],
},
];
@ -138,6 +156,7 @@ describe("SessionManager", () => {
role: "user",
content: "Hello",
},
contextItems: [],
},
];
@ -157,18 +176,21 @@ describe("SessionManager", () => {
role: "system",
content: "System message 1",
},
contextItems: [],
},
{
message: {
role: "user",
content: "User message",
},
contextItems: [],
},
{
message: {
role: "system",
content: "System message 2",
},
contextItems: [],
},
];
@ -209,9 +231,9 @@ describe("SessionManager", () => {
};
mockFs.readdirSync.mockReturnValue([
"old-session.json",
"sessions.json", // Should be filtered out
"recent-session.json",
"old-session.json" as any,
"sessions.json" as any, // Should be filtered out
"recent-session.json" as any,
]);
mockFs.statSync
@ -309,6 +331,7 @@ describe("SessionManager", () => {
role: "user",
content: "Test message",
},
contextItems: [],
},
]);

View file

@ -9,6 +9,7 @@ import type {
Session,
SessionMetadata,
} from "../../../core/index.js";
import historyManager from "../../../core/util/history.js";
// Re-export SessionMetadata for external consumers
export type { SessionMetadata };
@ -46,21 +47,6 @@ function getSessionDir(): string {
return sessionDir;
}
/**
* Get the sessions list file path
*/
function getSessionsListPath(): string {
const sessionDir = getSessionDir();
const listPath = path.join(sessionDir, "sessions.json");
// Initialize with empty array if doesn't exist
if (!fs.existsSync(listPath)) {
fs.writeFileSync(listPath, JSON.stringify([]));
}
return listPath;
}
/**
* Get the session file path for the current session
*/
@ -103,11 +89,13 @@ class SessionManager {
updateHistory(history: ChatHistoryItem[]): void {
const session = this.getCurrentSession();
session.history = history;
saveSession();
}
updateTitle(title: string): void {
const session = this.getCurrentSession();
session.title = title;
saveSession();
}
clear(): void {
@ -127,107 +115,41 @@ function getCurrentSessionId(): string {
return SessionManager.getInstance().getSessionId();
}
function modifySessionBeforeSave(session: Session): Session {
const filteredHistory = session.history.filter((item) => {
return item.message.role !== "system";
});
const modifiedHistory = filteredHistory.map((item) => {
if (item.message.role === "user") {
return {
...item,
editorState: item.message.content,
};
}
return item;
});
return {
...session,
history: modifiedHistory,
};
}
/**
* Save the current session to file
*/
export function saveSession(): void {
try {
const session = SessionManager.getInstance().getCurrentSession();
// Filter out system messages except for the first one
// TODO: Properly handle system messages vs informational messages in the future
const filteredHistory = session.history.filter((item, index) => {
return index === 0 || item.message.role !== "system";
});
const sessionToSave: Session = {
...session,
history: filteredHistory,
};
const sessionFilePath = path.join(
getSessionDir(),
`${session.sessionId}.json`,
);
// Write the session file
fs.writeFileSync(sessionFilePath, JSON.stringify(sessionToSave, null, 2));
// Update the sessions list
updateSessionsList(sessionToSave);
const sessionToSave = modifySessionBeforeSave(session);
historyManager.save(sessionToSave);
} catch (error) {
logger.error("Error saving session:", error);
}
}
/**
* Update the sessions list file
*/
function updateSessionsList(session: Session): void {
try {
const sessionsListFilePath = getSessionsListPath();
// Read and update the sessions list (following core/util/history.ts pattern)
try {
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
let sessionsList: SessionMetadata[];
try {
sessionsList = JSON.parse(rawSessionsList);
} catch (e) {
if (rawSessionsList.trim() === "") {
fs.writeFileSync(sessionsListFilePath, JSON.stringify([]));
sessionsList = [];
} else {
throw e;
}
}
// Filter out old format sessions (safety measure)
sessionsList = sessionsList.filter((sessionItem: any) => {
return typeof sessionItem.session_id !== "string";
});
let found = false;
for (const sessionMetadata of sessionsList) {
if (sessionMetadata.sessionId === session.sessionId) {
sessionMetadata.title = session.title || "Untitled Session";
sessionMetadata.workspaceDirectory =
session.workspaceDirectory || process.cwd();
found = true;
break;
}
}
if (!found) {
const sessionMetadata: SessionMetadata = {
sessionId: session.sessionId,
title: session.title || "Untitled Session",
dateCreated: new Date().toISOString(),
workspaceDirectory: session.workspaceDirectory || process.cwd(),
};
sessionsList.push(sessionMetadata);
}
fs.writeFileSync(
sessionsListFilePath,
JSON.stringify(sessionsList, undefined, 2),
);
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session.`,
);
}
throw new Error(
`It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`,
);
}
} catch (error) {
logger.error("Error updating sessions list:", error);
}
}
/**
* Load session from current terminal's session file
*/
@ -366,33 +288,31 @@ export function listSessions(
limit: number = 10,
): (SessionMetadata & { firstUserMessage?: string })[] {
try {
const sessionDir = getSessionDir();
const sessions = historyManager.list({ limit });
if (!fs.existsSync(sessionDir)) {
return [];
}
// Add first user message preview to each session
const sessionsWithPreview: (SessionMetadata & {
firstUserMessage?: string;
})[] = [];
const files = fs
.readdirSync(sessionDir)
.filter((file) => file.endsWith(".json") && file !== "sessions.json")
.map((file) => path.join(sessionDir, file));
for (const sessionMeta of sessions) {
const sessionFilePath = path.join(
getSessionDir(),
`${sessionMeta.sessionId}.json`,
);
const sessions: (SessionMetadata & { firstUserMessage?: string })[] = [];
for (const filePath of files) {
const metadata = getSessionMetadataWithPreview(filePath);
if (metadata) {
sessions.push(metadata);
if (fs.existsSync(sessionFilePath)) {
const metadata = getSessionMetadataWithPreview(sessionFilePath);
if (metadata) {
sessionsWithPreview.push(metadata);
}
} else {
// Fall back to basic metadata if file doesn't exist
sessionsWithPreview.push(sessionMeta);
}
}
// Sort by date created (most recent first) and limit results
return sessions
.sort(
(a, b) =>
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
)
.slice(0, limit);
return sessionsWithPreview;
} catch (error) {
logger.error("Error listing sessions:", error);
return [];
@ -404,16 +324,7 @@ export function listSessions(
*/
export function loadSessionById(sessionId: string): Session | null {
try {
const sessionDir = getSessionDir();
const sessionFilePath = path.join(sessionDir, `${sessionId}.json`);
if (!fs.existsSync(sessionFilePath)) {
return null;
}
const session: Session = JSON.parse(
fs.readFileSync(sessionFilePath, "utf8"),
);
const session = historyManager.load(sessionId);
return session;
} catch (error) {
logger.error("Error loading session by ID:", error);

View file

@ -10,7 +10,7 @@ import {
convertFromUnifiedHistory,
convertToUnifiedHistory,
} from "./messageConversion.js";
import { createSession, saveSession } from "./session.js";
import { updateSessionHistory } from "./session.js";
import { formatError } from "./util/formatError.js";
import { logger } from "./util/logger.js";
import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
@ -166,8 +166,7 @@ export async function handleAutoCompaction(
);
// Save the compacted session
const session = createSession(result.compactedHistory);
saveSession(session);
updateSessionHistory(result.compactedHistory);
// Handle success notification
handleCompactionSuccess(result, isHeadless, callbacks);

View file

@ -294,8 +294,10 @@ const UserInput: React.FC<UserInputProps> = ({
if (onFileAttached) {
try {
const fs = await import("fs/promises");
const content = await fs.readFile(filePath, "utf-8");
onFileAttached(filePath, content);
const path = await import("path");
const absolutePath = path.resolve(filePath);
const content = await fs.readFile(absolutePath, "utf-8");
onFileAttached(absolutePath, content);
} catch (error) {
console.error(`Error reading file ${filePath}:`, error);
}

View file

@ -1,8 +1,13 @@
import * as path from "node:path";
import { v4 as uuidv4 } from "uuid";
import type { ChatHistoryItem, Session } from "../../../../../core/index.js";
import { getLastNPathParts } from "../../../../../core/util/uri.js";
import { initializeChatHistory } from "../../commands/chat.js";
import { compactChatHistory } from "../../compaction.js";
import { convertFromUnifiedHistory } from "../../messageConversion.js";
import { loadSession, saveSession } from "../../session.js";
import { loadSession, updateSessionHistory } from "../../session.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
@ -89,7 +94,7 @@ export async function handleCompactCommand({
...currentSession,
history: result.compactedHistory,
};
saveSession(updatedSession);
updateSessionHistory(result.compactedHistory);
setCurrentSession(updatedSession);
setChatHistory((prev) => [
@ -225,17 +230,17 @@ export function formatMessageWithFiles(
}
// Convert attached files to context items
const contextItems = attachedFiles.map((file, index) => ({
const contextItems = attachedFiles.map((file) => ({
id: {
providerTitle: "file",
itemId: `attached-file-${index}`,
itemId: uuidv4(),
},
content: file.content,
name: file.path,
description: `File: ${file.path}`,
name: path.basename(file.path),
description: getLastNPathParts(file.path, 2),
uri: {
type: "file" as const,
value: file.path,
value: `file://${file.path}`,
},
}));

View file

@ -5,7 +5,11 @@ import type { ChatHistoryItem, Session } from "../../../../../core/index.js";
import { findCompactionIndex } from "../../compaction.js";
import { toolPermissionManager } from "../../permissions/permissionManager.js";
import { services } from "../../services/index.js";
import { createSession, loadSession, saveSession } from "../../session.js";
import {
createSession,
loadSession,
updateSessionHistory,
} from "../../session.js";
import { handleSlashCommands } from "../../slashCommands.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
@ -221,7 +225,7 @@ export function useChat({
...currentSession,
history: currentHistory,
};
saveSession(updatedSession);
updateSessionHistory(currentHistory);
setCurrentSession(updatedSession);
logger.debug("Session saved");
return currentHistory;