Merge pull request #9055 from continuedev/nate/feat-session-id-persistence

feat(cli): add session ID support for serve command to persist chat history
This commit is contained in:
Nate Sesti 2025-12-07 10:20:31 -08:00 • committed by GitHub
commit b9332d72db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 98 additions and 15 deletions

View file

@ -23,7 +23,11 @@ import {
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import { createSession, getCompleteStateSnapshot } from "../session.js";
import {
createSession,
getCompleteStateSnapshot,
loadOrCreateSessionById,
} from "../session.js";
import { messageQueue } from "../stream/messageQueue.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
@ -142,7 +146,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
}
const session = createSession(initialHistory);
const trimmedId = options.id?.trim();
const session =
trimmedId && trimmedId.length > 0
? loadOrCreateSessionById(trimmedId, initialHistory)
: createSession(initialHistory);
// Align ChatHistoryService with server session and enable remote mode
try {

View file

@ -10,6 +10,7 @@ import {
createSession,
getCurrentSession,
hasSession,
loadOrCreateSessionById,
loadSession,
saveSession,
startNewSession,
@ -36,17 +37,24 @@ vi.mock("./util/logger.js", () => ({
error: vi.fn(),
},
}));
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 mockHistoryManager: any = vi.hoisted(() => ({
save: vi.fn((session: any) => {
// Mimic writing the session payload to disk so expectations on fs still work
fs.writeFileSync(
`/home/test/.continue/sessions/${session.sessionId}.json`,
JSON.stringify(session),
);
}),
load: vi.fn(() => ({
sessionId: "test-session-id",
title: "Test Session",
workspaceDirectory: "/test/workspace",
history: [],
})),
list: vi.fn(() => []),
}));
vi.mock("core/util/history.js", () => ({
default: mockHistoryManager,
}));
const mockFs = vi.mocked(fs);
@ -71,6 +79,9 @@ describe("SessionManager", () => {
mockFs.readFileSync.mockReturnValue("[]");
mockFs.readdirSync.mockReturnValue([]);
mockFs.statSync.mockReturnValue({ mtime: new Date() } as any);
// Ensure each test starts with a fresh session
clearSession();
});
describe("getCurrentSession", () => {
@ -145,6 +156,13 @@ describe("SessionManager", () => {
expect(currentSession).toBe(session);
});
it("should use provided sessionId when supplied", () => {
const session = createSession([], "custom-session-id");
expect(session.sessionId).toBe("custom-session-id");
expect(uuidv4).not.toHaveBeenCalled();
});
});
describe("updateSessionHistory", () => {
@ -235,6 +253,42 @@ describe("SessionManager", () => {
});
});
describe("loadOrCreateSessionById", () => {
it("should load an existing session and set it as current", () => {
const existingSession: Session = {
sessionId: "existing-id",
title: "Existing",
workspaceDirectory: "/test/workspace",
history: [
{
message: { role: "user", content: "hi" },
contextItems: [],
},
],
};
mockHistoryManager.load.mockReturnValue(existingSession);
const session = loadOrCreateSessionById("existing-id");
expect(session).toBe(existingSession);
expect(mockHistoryManager.load).toHaveBeenCalledWith("existing-id");
expect(getCurrentSession()).toBe(existingSession);
});
it("should create a new session when none exists for the id", () => {
mockHistoryManager.load.mockImplementation(() => {
throw new Error("not found");
});
const session = loadOrCreateSessionById("new-id");
expect(session.sessionId).toBe("new-id");
expect(session.history).toEqual([]);
expect(getCurrentSession()).toBe(session);
});
});
describe("loadSession", () => {
it("should return null if session directory doesn't exist", () => {
mockFs.existsSync.mockReturnValue(false);

View file

@ -316,9 +316,12 @@ export function loadSession(): Session | null {
/**
* Create a new session
*/
export function createSession(history: ChatHistoryItem[] = []): Session {
export function createSession(
history: ChatHistoryItem[] = [],
sessionId?: string,
): Session {
const session: Session = {
sessionId: uuidv4(),
sessionId: sessionId ?? uuidv4(),
title: DEFAULT_SESSION_TITLE,
workspaceDirectory: process.cwd(),
history,
@ -526,6 +529,24 @@ export function loadSessionById(sessionId: string): Session | null {
}
}
/**
* Load an existing session by ID or create a new one with that ID.
* Useful for long-lived processes (e.g., cn serve) that need to
* preserve chat history across restarts for the same storage/agent id.
*/
export function loadOrCreateSessionById(
sessionId: string,
history: ChatHistoryItem[] = [],
): Session {
const existing = loadSessionById(sessionId);
if (existing) {
SessionManager.getInstance().setSession(existing);
return existing;
}
return createSession(history, sessionId);
}
/**
* Update the current session's history
*/