Skip to content

Add automatic session saving with list and resume support. (feature/2174)#2419

Closed
saheersk wants to merge 15 commits intogoogle-gemini:mainfrom
saheersk:feature/2174
Closed

Add automatic session saving with list and resume support. (feature/2174)#2419
saheersk wants to merge 15 commits intogoogle-gemini:mainfrom
saheersk:feature/2174

Conversation

@saheersk
Copy link
Copy Markdown

  • Automatically checkpoints conversation history after each user+model turn
  • Saves checkpoints in .gemini/tmp/ with unique identifiers (timestamp/UUID)
  • Limits total checkpoints to avoid excessive disk usage (configurable)
  • Adds chat list-auto to display available saved sessions
  • Adds chat resume-auto <session_id> to resume a specific session
  • Ensures last session is saved on graceful CLI exit

TLDR

This PR adds automatic session saving and resumption to the Gemini CLI. After every complete chat turn (user input + model response), the conversation history is checkpointed to disk. It also introduces new sub-commands to list and resume saved sessions.

This makes the user experience significantly smoother by removing the need to manually save with /chat save and ensures continuity between sessions even after restarting the CLI.

Dive Deeper

What's New:

  • Automatic Checkpointing
    • After each message exchange, the session is saved to .gemini/tmp with a UUID or timestamp-based filename.
    • A retention mechanism ensures only the last N checkpoints are kept, preventing disk clutter.
  • Session Listing
    • New command: /chat list-auto
    • Displays all available saved sessions with human-readable timestamps and IDs.
  • Session Resumption
    • New command: /chat resume-auto <session_id>
    • Loads a specific checkpoint and restores the chat history to that state.
  • Graceful Exit Handling
    • Ensures the most recent session is saved on clean CLI exit

Reviewer Test Plan

To verify that everything works correctly, please follow these steps:

  • Start a chat session and interact with the CLI.

  • Verify that a new checkpoint is created in .gemini/tmp/ after each complete user + model turn.

  • Run /chat list-auto

    • ✅ You should see session IDs with readable timestamps.
  • Run /chat resume-auto <session_id> with one of the listed IDs

    • ✅ The session should reload and match the saved history.
  • Test graceful exit using CTRL+C or typing exit

    • ✅ Then restart CLI and check .gemini/tmp/ to confirm the last checkpoint was saved.

Optionally, test deletion or limit behavior by generating more than N checkpoints and verifying older ones are cleaned up.

Testing Matrix

Other platforms have not been tested directly, but the feature is expected to work cross-platform.
Contributions or confirmations from users on Linux and Windows are welcome

🍏 🪟 🐧
npm run
npx
Docker
Podman - -
Seatbelt - -

Linked issues / bugs

#2174

saheersk added 2 commits June 28, 2025 17:39
- Automatically checkpoints conversation history after each user+model turn
- Saves checkpoints in `.gemini/tmp/` with unique identifiers (timestamp/UUID)
- Limits total checkpoints to avoid excessive disk usage (configurable)
- Adds `chat list-auto` to display available saved sessions
- Adds `chat resume-auto <session_id>` to resume a specific session
- Ensures last session is saved on graceful CLI exit
@saheersk saheersk requested a review from a team as a code owner June 28, 2025 12:32
@umairidris
Copy link
Copy Markdown
Contributor

/gemini summary

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

This pull request significantly enhances the user experience by introducing automatic conversation session saving and resumption capabilities to the Gemini CLI. It ensures that chat history is persistently stored, can be easily listed and reloaded, and is preserved even upon unexpected exits, making the CLI more robust and user-friendly.

Highlights

  • Automatic Session Checkpointing: I've implemented automatic checkpointing of conversation history after each user and model turn. These checkpoints are saved in a new .gemini/tmp/sessions directory with unique identifiers (timestamp-based filenames).
  • Session Retention Policy: To prevent excessive disk usage, a retention mechanism has been added that limits the total number of automatically saved checkpoints, keeping only the 5 most recent ones. This replaces the previous behavior of deleting all checkpoints on startup.
  • New CLI Commands for Session Management: Two new sub-commands have been introduced under /chat: /chat list-auto to display available automatically saved sessions with human-readable IDs and timestamps, and /chat resume-auto <session_id> to load and restore a specific saved session.
  • Graceful Exit Session Saving: The CLI now ensures that the most recent conversation session is automatically saved upon a graceful exit (e.g., CTRL+C or /quit). This improves continuity by preserving the last chat state.
  • Non-Interactive Mode Support: The new list-auto and resume-auto commands are also supported in non-interactive mode, allowing users to manage sessions via command-line arguments.
Changelog
  • docs/cli/commands.md
    • Updated the description for the /chat command to reflect the new automatic session management features.
    • Added documentation for the new /chat list-auto and /chat resume-auto sub-commands, including their descriptions and usage.
  • packages/cli/src/gemini.tsx
    • Imported new session management utilities (saveSession, loadSession, listSessions).
    • Renamed cleanupCheckpoints to cleanupOldCheckpoints and updated its call.
    • Added a process.on('exit') hook to automatically save the current session history when the CLI exits gracefully.
    • Modified the main function to handle /chat list-auto and /chat resume-auto commands when provided as initial command-line input, allowing non-interactive use.
    • Passed initialHistory to the AppWrapper component to load a resumed session into the interactive UI.
    • Adjusted input handling for non-TTY scenarios and telemetry logging to correctly account for initial history and potentially empty prompts after a session resume.
  • packages/cli/src/nonInteractiveCli.test.ts
    • Updated tests for runNonInteractive to expect errors to be thrown (instead of process.exit(1)) when tool execution or API calls fail, aligning with the new error handling strategy.
  • packages/cli/src/nonInteractiveCli.ts
    • Imported listSessions and loadSession for non-interactive session management.
    • Modified the runNonInteractive function signature to accept an initialHistory and return the final Content[] history.
    • Implemented logic within runNonInteractive to process /chat list-auto and /chat resume-auto commands, displaying session lists or loading history accordingly.
    • Changed return statements from return; to return currentMessages; to ensure the session history is always returned.
    • Replaced process.exit(1) with throw error; for tool execution and API errors, allowing the caller to handle exceptions.
  • packages/cli/src/ui/App.tsx
    • Added initialHistory as a prop to AppProps and the App component.
    • Implemented a useMemo hook to convert the initialHistory (Content[]) into the HistoryItem[] format required by the useHistory hook, ensuring proper display of loaded sessions.
  • packages/cli/src/ui/hooks/slashCommandProcessor.test.ts
    • Updated mock GeminiClient to include getChat and getHistory for more comprehensive testing of session-related commands.
    • Refactored quit/exit command tests to directly call the command's action and verify behavior, including the new session saving logic.
  • packages/cli/src/ui/hooks/slashCommandProcessor.ts
    • Imported listSessions, loadSession, and saveSession for interactive UI session management.
    • Updated the SlashCommand interface to allow completion functions to receive mainCommand and subCommand for more context-aware suggestions.
    • Added new cases for list-auto and resume-auto to the /chat command's action, enabling interactive listing and resumption of sessions, including clearing and reloading the chat history.
    • Modified the completion function for /chat to suggest resume-auto session IDs.
    • Added an explicit call to saveSession within the /quit and /exit command actions to ensure the current session is saved before the application terminates.
  • packages/cli/src/ui/hooks/useCompletion.ts
    • Modified the command.completion call to pass commandName and subCommand, enabling more dynamic command completions.
  • packages/cli/src/ui/hooks/useHistoryManager.ts
    • Updated the useHistory hook to accept an optional initialHistory array, allowing it to be initialized with a loaded session's content.
  • packages/cli/src/ui/hooks/useLoadingIndicator.test.ts
    • Improved the test for useLoadingIndicator by mocking Math.random to ensure predictable cycling of loading phrases, making the test more robust.
  • packages/cli/src/utils/cleanup.ts
    • Renamed cleanupCheckpoints to cleanupOldCheckpoints to better reflect its new purpose.
    • Changed the cleanup logic from deleting the entire checkpoints directory to a more sophisticated mechanism that retains only the MAX_CHECKPOINTS (currently 5) most recent session files, preventing excessive disk usage while preserving recent history.
    • Added console.warn for errors during the cleanup process instead of silently ignoring them.
  • packages/cli/src/utils/session.ts
    • New file: Introduced saveSession, loadSession, and listSessions functions.
    • saveSession writes the current conversation history to a JSON file in a timestamp-based format within .gemini/tmp/sessions.
    • loadSession reads and parses a specified session file, returning the conversation history.
    • listSessions reads the sessions directory, filters for session files, and returns a sorted list of session IDs with human-readable timestamps.
Activity
  • The author, saheersk, opened this pull request to add automatic session saving and resume support.
  • A comment was made by @umairidris requesting a summary of the pull request using the /gemini summary command.

@umairidris
Copy link
Copy Markdown
Contributor

/gemini review

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces automatic session saving and resumption. There are a few critical and high-severity issues that need to be addressed:

  • A critical issue with using an asynchronous operation in a synchronous process.on('exit') handler, which could lead to data loss.
  • A high-severity bug where the session cleanup logic targets the wrong directory, preventing old sessions from being deleted.
  • A high-severity bug in session listing where sorting by a localized date string will lead to incorrect ordering.

Comment thread packages/cli/src/gemini.tsx Outdated
Comment thread packages/cli/src/utils/cleanup.ts
Comment thread packages/cli/src/utils/session.ts Outdated
saheersk added 2 commits June 29, 2025 10:08
  - Replace 'exit' event with 'beforeExit' for async session saving
  - Add signal handlers for SIGINT, SIGTERM, SIGHUP, SIGQUIT
  - Add crash protection for uncaught exceptions/rejections
  - Implement sync fallback for immediate exits
  - Prevent duplicate saves with exit state tracking
  - Sort sessions using numeric mtimeMs values for reliable chronological order
  - Fix locale-dependent string sorting that caused incorrect session ordering
@saheersk saheersk force-pushed the feature/2174 branch 2 times, most recently from c923894 to 3c2607d Compare June 29, 2025 04:53
@saheersk
Copy link
Copy Markdown
Author

Hi @umairidris ,

I've fixed the issue by replacing the unreliable localized timestamp sorting with a proper sort using mtimeMs for accurate chronological order. Also addressed the async saveSession call by using beforeExit and signal handlers for graceful shutdown.

Could you please run the review again when you get a chance? Let me know if anything needs clarification. Thanks

@allenhutchison
Copy link
Copy Markdown
Contributor

@sethtroisi could you please review this one?

@doublej doublej mentioned this pull request Jun 30, 2025
Comment thread packages/cli/src/gemini.tsx Outdated
Comment thread packages/cli/src/gemini.tsx Outdated
Comment thread packages/cli/src/gemini.tsx
Comment thread packages/cli/src/nonInteractiveCli.ts Outdated
@blueneogeo
Copy link
Copy Markdown

This is so close to auto saving and resuming chats, only the auto resume is missing. Would you consider adding a startup parameter to gemini so it will resume the last chat you had? (I assume the auto-id with the highest number, if available)

@allenhutchison
Copy link
Copy Markdown
Contributor

@saheersk are you still interested in pursuing this PR? It looks like @sethtroisi comments still need to be addressed and there are several merge conflicts that will also need to be resolved.

@saheersk
Copy link
Copy Markdown
Author

saheersk commented Aug 9, 2025

Hi @allenhutchison,
Yes, I’m still interested in pursuing this PR. I was a bit occupied with other things, but I’ll work on addressing @sethtroisi’s comments and resolving the merge conflicts, and will update tomorrow. Thanks for following up.

  - Replace undefined input with empty string for cleaner type safety
  - Remove process.exit calls in chat resume/list commands, use empty input fallback
  - Add TODO comments for future chat processor refactoring
  - Simplify stdin concatenation logic
@saheersk
Copy link
Copy Markdown
Author

Hey @allenhutchison @sethtroisi,

I’ve added all the new changes and resolved the merge conflicts. Could you please re-review when you get a chance?.

Thanks.

Comment thread packages/cli/src/gemini.tsx
Comment thread packages/cli/src/gemini.tsx Outdated
Comment thread packages/cli/src/ui/commands/chatCommand.ts Outdated
@saheersk
Copy link
Copy Markdown
Author

Hey @sethtroisi,

I’ve resolved all the issues and pushed the changes. Please validate when you get a chance.

@allenhutchison
Copy link
Copy Markdown
Contributor

@saheersk it looks like #5221 is working on the same thing and making progress. Do you want to see if you can combine forces with that author to get this feature out?

@saheersk
Copy link
Copy Markdown
Author

hey @allenhutchison, #5221 is already merged. Is there anything i can do further.

@allenhutchison
Copy link
Copy Markdown
Contributor

Probably not on this PR. Sorry about that. We're trying to get better at staying ahead of the incoming PRs. I'll close this one since the other one is merged in now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants