fix(cli): prevent empty sessions from being saved (#11076)

* add /sessions slash command

* do not save empty sessions

* update tests

* Update extensions/cli/src/services/ChatHistoryService.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* remove duplicate telemetry capture

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
Aditya Mitra 2026-03-14 00:41:48 +05:30 • committed by GitHub
parent b9174c0ee8
commit f77daf2269
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 79 additions and 18 deletions

View file

@ -111,6 +111,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "List background jobs",
category: "system",
},
{
name: "sessions",
description: "Show all chat sessions",
category: "system",
},
];
// Remote mode specific commands

View file

@ -38,7 +38,7 @@ describe("ChatHistoryService", () => {
expect(state.history).toEqual([]);
expect(state.compactionIndex).toBeNull();
expect(state.sessionId).toBe("test-session-id");
expect(state.sessionId).toBe("");
expect(state.isRemoteMode).toBe(false);
});

View file

@ -1,11 +1,7 @@
import type { ChatHistoryItem, ToolStatus } from "core/index.js";
import { createHistoryItem } from "core/util/messageConversion.js";
import {
updateSessionHistory,
loadSessionById,
createSession,
} from "../session.js";
import { loadSessionById, updateSessionHistory } from "../session.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
@ -76,23 +72,31 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
/**
* Initialize the service with optional session
* If no session is provided, we delay session creation until content is added
*/
async doInitialize(
session?: any,
isRemoteMode = false,
): Promise<ChatHistoryState> {
const activeSession = session || createSession([]);
logger.debug("Initializing ChatHistoryService", {
sessionId: activeSession.sessionId,
historyLength: activeSession.history.length,
sessionId: session?.sessionId,
historyLength: session?.history?.length,
isRemoteMode,
});
if (session) {
return {
history: session.history || [],
compactionIndex: this.findCompactionIndex(session.history || []),
sessionId: session.sessionId,
isRemoteMode,
};
}
return {
history: activeSession.history || [],
compactionIndex: this.findCompactionIndex(activeSession.history || []),
sessionId: activeSession.sessionId,
history: [],
compactionIndex: null,
sessionId: "",
isRemoteMode,
};
}

View file

@ -195,7 +195,7 @@ describe("SessionManager", () => {
});
describe("saveSession", () => {
it("should save the current session to file", () => {
it("should save the current session to file when it has content", () => {
const session = getCurrentSession();
session.title = "Test Session";
session.history = [
@ -216,6 +216,32 @@ describe("SessionManager", () => {
);
});
it("should not save empty sessions", () => {
const session = getCurrentSession();
session.history = [];
saveSession();
expect(mockFs.writeFileSync).not.toHaveBeenCalled();
});
it("should not save sessions with only system messages", () => {
const session = getCurrentSession();
session.history = [
{
message: {
role: "system",
content: "System message",
},
contextItems: [],
},
];
saveSession();
expect(mockFs.writeFileSync).not.toHaveBeenCalled();
});
it("should filter out system messages except the first one", () => {
const session = getCurrentSession();
session.history = [

View file

@ -264,12 +264,36 @@ export function getCompleteStateSnapshot(
};
}
/**
* Check if a session has meaningful content for saving
*/
function hasSessionContent(session: Session): boolean {
if (!session.history || session.history.length === 0) {
return false;
}
const nonSystemMessages = session.history.filter(
(item) => item.message.role !== "system",
);
return nonSystemMessages.length > 0;
}
/**
* Save the current session to file
*/
export function saveSession(): void {
try {
const session = SessionManager.getInstance().getCurrentSession();
const manager = SessionManager.getInstance();
if (!manager.hasSession()) {
return;
}
const session = manager.getCurrentSession();
if (!hasSessionContent(session)) {
return;
}
const sessionToSave = getSessionPersistenceSnapshot(session);
historyManager.save(sessionToSave);
} catch (error) {

View file

@ -143,8 +143,6 @@ async function handleFork() {
}
function handleTitle(args: string[]) {
posthogService.capture("useSlashCommand", { name: "title" });
const title = args.join(" ").trim();
if (!title) {
return {
@ -173,6 +171,10 @@ function handleJobs() {
return { openJobsSelector: true };
}
function handleSessions() {
return { openSessionSelector: true };
}
const commandHandlers: Record<string, CommandHandler> = {
help: handleHelp,
clear: () => {
@ -202,13 +204,13 @@ const commandHandlers: Record<string, CommandHandler> = {
title: handleTitle,
rename: handleTitle,
init: (args, assistant) => {
posthogService.capture("useSlashCommand", { name: "init" });
return handleInit(args, assistant);
},
update: () => {
return { openUpdateSelector: true };
},
jobs: handleJobs,
sessions: handleSessions,
};
export async function handleSlashCommands(