Skip to content

feat(cli): add /new command to start fresh sessions without overwriting existing history#20431

Closed
SuvanshTembe wants to merge 8 commits intogoogle-gemini:mainfrom
SuvanshTembe:feat/new-command-to-create-new-session
Closed

feat(cli): add /new command to start fresh sessions without overwriting existing history#20431
SuvanshTembe wants to merge 8 commits intogoogle-gemini:mainfrom
SuvanshTembe:feat/new-command-to-create-new-session

Conversation

@SuvanshTembe
Copy link
Copy Markdown

Summary

This PR introduces a new /new slash command that allows users to start a completely fresh session directly within the Gemini CLI. Currently, users must manually run /save followed by /clear, or restart the CLI, to avoid overwriting their existing session. The new command simplifies session management by generating a new session UUID while preserving the previous session for later use via /resume.

Details

  • Added a new built-in CLI command: /new
  • The command initializes a fresh session by:
  • Generating a new session ID
  • Resetting the active chat context
  • Preserving existing sessions so they remain accessible through /resume

Related Issues

Closes #20428

How to Validate

  1. Start the CLI:
  2. npm run start
  3. Create some chat history in the current session.
  4. Run:
    /new
    Expected:
    A new session starts.
    Previous session remains available via /resume.
  5. Verify /resume:
  6. Run /resume
  7. Confirm the previous session appears in the list and can be restored.

Edge cases tested:

Running /new multiple times consecutively

Switching between /new and /resume

Starting a new session after /clear

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

Screenshots

Before(session one):
before_new
After creating a new session with /new (session two):
after_new
Result (Both sessions are saved):
result

@SuvanshTembe SuvanshTembe requested a review from a team as a code owner February 26, 2026 13:02
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @SuvanshTembe, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances session management within the CLI by introducing a dedicated /new command. This command streamlines the process of starting a fresh conversation, ensuring that previous session data is safely preserved and accessible. The change clarifies the distinct roles of /new and /clear, providing users with more intuitive control over their chat history and session context.

Highlights

  • New /new command: Introduced a new /new slash command that allows users to start a completely fresh session without overwriting existing history. This command generates a new session UUID, resets the active chat context, and preserves the previous session for later use via /resume.
  • /clear command behavior change: The /clear command has been updated to re-initialize the current session with the same session ID, rather than generating a new one. This ensures /clear empties the current session while /new creates a truly fresh session.
  • Policy Engine Updates: Added new integration tests and policy configurations to ensure write_file is allowed in AUTO_EDIT mode and that read-only tools (like read_file, google_web_search, list_directory) are consistently allowed by the policy engine across different modes.
Changelog
  • packages/cli/src/config/policy-engine.integration.test.ts
    • Updated policy engine integration tests to include checks for write_file and read-only tools (read_file, google_web_search, list_directory) in AUTO_EDIT mode, ensuring correct policy decisions.
  • packages/cli/src/services/BuiltinCommandLoader.ts
    • Imported and registered the new newCommand to make it available as a built-in CLI command.
  • packages/cli/src/ui/commands/clearCommand.ts
    • Removed the randomUUID import and the logic for generating a new session ID, modifying /clear to re-initialize the current session with its existing ID.
    • Updated comments to reflect that /clear now re-initializes the recording service with the same session ID.
  • packages/cli/src/ui/commands/newCommand.ts
    • Added a new file defining the /new slash command, which orchestrates the process of starting a new session, including displaying messages, resetting the chat, clearing the UI, and generating a new session ID.
  • packages/cli/src/ui/hooks/slashCommandProcessor.ts
    • Imported createSessionId for generating new session identifiers.
    • Added a new case to handle the clear_session action, which generates a new session ID, resets the Gemini client's chat, clears the UI, and resets session-specific states.
  • packages/core/src/commands/new.test.ts
    • Added unit tests for the performNewSession function, verifying that it yields the correct sequence of actions (an info message and a clear_session action).
  • packages/core/src/commands/new.ts
    • Added a new file defining the performNewSession asynchronous generator function, which yields a message indicating a new session is starting and then a clear_session action.
  • packages/core/src/commands/types.ts
    • Defined a new interface ClearSessionActionReturn to represent the action of clearing a session.
    • Extended the CommandActionReturn union type to include ClearSessionActionReturn.
  • packages/core/src/index.ts
    • Exported the new new.js module to make the performNewSession function accessible.
  • packages/core/src/policy/config.test.ts
    • Added tests to confirm that write_file is allowed in AUTO_EDIT mode by the policy engine.
    • Added tests to ensure read-only tools like read_file and list_directory are still allowed in AUTO_EDIT mode.
    • Adjusted an assertion for the number of shell rules to be more flexible, checking for at least one matching rule instead of exactly two.
  • packages/core/src/services/chatRecordingService.ts
    • Modified the initialize method to refresh the session ID from the configuration, ensuring it uses the latest session ID (e.g., after a /new command).
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

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 a /new command to start a fresh session, which is a great usability improvement. The implementation correctly separates core logic from the UI by introducing a performNewSession generator in the core package. However, there's a significant architectural issue in the CLI package where the session creation logic is duplicated and split between newCommand.ts and useSlashCommandProcessor.ts. My review focuses on consolidating this logic into the useSlashCommandProcessor hook to improve maintainability and ensure correctness, aligning with the rule to avoid duplicating subcommand routing logic. This involves refactoring newCommand to delegate handling to the processor and completing the implementation in the processor's clear_session handler to ensure all related logic is centralized.

Comment on lines +21 to +61
action: async (
context: CommandContext,
_args: string,
): Promise<void | SlashCommandActionReturn> => {
const actionStream = performNewSession();

for await (const action of actionStream) {
if (action.type === 'message') {
context.ui.addItem(
{
type: action.messageType,
text: action.content,
},
Date.now(),
);
} else if (action.type === 'clear_session') {
const geminiClient = context.services.config?.getGeminiClient();
const config = context.services.config;
const chatRecordingService = context.services.config
?.getGeminiClient()
?.getChat()
.getChatRecordingService();

if (geminiClient) {
await geminiClient.resetChat();
}

// Reset user steering hints
config?.userHintService.clear();

// Start a new conversation recording with a new session ID
if (config && chatRecordingService) {
const newSessionId = randomUUID();
config.setSessionId(newSessionId);
chatRecordingService.initialize();
}

context.ui.clear();
}
}
},
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The logic for creating a new session is implemented directly within this command's action. However, a handler for the clear_session action has also been added to useSlashCommandProcessor.ts, leading to duplicated and split logic. This is a maintainability concern, as both places would need to be kept in sync.

To centralize UI and state update logic, this command should delegate handling to the useSlashCommandProcessor hook. Please refactor this action to return the clear_session action object yielded by performNewSession(). The processor will then execute the complete session creation logic.

  action: async (
    context: CommandContext,
    _args: string,
  ): Promise<void | SlashCommandActionReturn> => {
    const actionStream = performNewSession();

    let lastAction: SlashCommandActionReturn | undefined;
    for await (const action of actionStream) {
      if (action.type === 'message') {
        context.ui.addItem(
          {
            type: action.messageType,
            text: action.content,
          },
          Date.now(),
        );
      } else {
        lastAction = action;
      }
    }

    return lastAction;
  },
References
  1. Avoid duplicating subcommand routing logic within a parent command's action if a higher-level CLI router is already responsible for it. The parent command's action should only contain the default behavior.

Comment on lines +660 to +668
case 'clear_session': {
const newSessionId = createSessionId();
config?.setSessionId(newSessionId);
await config?.getGeminiClient()?.resetChat();
fullCommandContext.ui.clear();
setSessionShellAllowlist(new Set());
setPendingItem(null);
return { type: 'handled' };
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

This handler for clear_session is incomplete. It's missing calls to userHintService.clear() and chatRecordingService.initialize(), which are necessary to fully reset the session state and create a new session file on disk.

As this is the centralized place for handling session creation, all related logic should be consolidated here. This ensures that starting a new session is handled consistently and correctly.

                case 'clear_session': {
                  const newSessionId = createSessionId();
                  config?.setSessionId(newSessionId);
                  await config?.getGeminiClient()?.resetChat();

                  // Reset user steering hints for the new session.
                  config?.userHintService.clear();

                  // Re-initialize the recording service to create a new session file.
                  config
                    ?.getGeminiClient()
                    ?.getChat()
                    .getChatRecordingService()
                    ?.initialize();

                  fullCommandContext.ui.clear();
                  setSessionShellAllowlist(new Set());
                  setPendingItem(null);
                  return { type: 'handled' };
                }
References
  1. Avoid duplicating subcommand routing logic within a parent command's action if a higher-level CLI router is already responsible for it. This rule supports centralizing all related logic within the designated router to ensure completeness and consistency.

@jackwotherspoon
Copy link
Copy Markdown
Collaborator

This seems like a duplicate of #16848

Going to see if the original author of that PR is open to continuing to work on this.

@jackwotherspoon
Copy link
Copy Markdown
Collaborator

Really appreciate the contribution @SuvanshTembe 👏

Friendly reminder to do a quick search for open issues and PRs ahead of starting work so that it saves you from working on something that someone has already worked or started on 😄

@SuvanshTembe
Copy link
Copy Markdown
Author

@jackwotherspoon Understood. I'll check first from next time.
Can you please review my other PR #20295 ?
Thanks

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.

Feature Request: Add /new command for starting fresh new sessions

2 participants