-
Notifications
You must be signed in to change notification settings - Fork 13k
feat(daemon): add stateful headless daemon mode #20700
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
h30s
wants to merge
6
commits into
google-gemini:main
Choose a base branch
from
h30s:feat/daemon-mode-15338
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4cb18c4
feat(daemon): add stateful headless daemon mode
h30s 81ce1b3
fix(daemon): address security and robustness review comments
h30s 9680163
fix(daemon): ensure client output ends with trailing newline
h30s ff03c29
fix(daemon): harden IPC auth and headless safety
h30s 320021d
Resolve merge conflicts with origin/main
h30s cab1b1d
fix(ci): lint, Scheduler context, Config MCP await, and Windows daemo…
h30s File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; | ||
| import net from 'node:net'; | ||
| import fs from 'node:fs'; | ||
| import os from 'node:os'; | ||
| import { getDaemonSocketPath, checkDaemonStatus } from './daemonClient.js'; | ||
|
|
||
| vi.mock('../config/config.js'); | ||
| vi.mock('@google/gemini-cli-core', async (importOriginal) => { | ||
| const actual = await importOriginal<Record<string, unknown>>(); | ||
| return { | ||
| ...actual, | ||
| debugLogger: { | ||
| error: vi.fn(), | ||
| log: vi.fn(), | ||
| warn: vi.fn(), | ||
| debug: vi.fn(), | ||
| }, | ||
| writeToStdout: vi.fn(), | ||
| writeToStderr: vi.fn(), | ||
| }; | ||
| }); | ||
|
|
||
| describe('Daemon Mode', () => { | ||
| const testHome = '/tmp/gemini-test-home'; | ||
| const socketPath = `${testHome}/.gemini/daemon.sock`; | ||
| let mockServer: net.Server; | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.spyOn(process, 'exit').mockImplementation((() => {}) as unknown as ( | ||
| code?: number, | ||
| ) => never); | ||
|
|
||
| // Mock os.homedir to avoid polluting real user dirs | ||
| vi.spyOn(os, 'homedir').mockReturnValue(testHome); | ||
| if (!fs.existsSync(`${testHome}/.gemini`)) { | ||
| fs.mkdirSync(`${testHome}/.gemini`, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| if (mockServer) { | ||
| mockServer.close(); | ||
| } | ||
| if (fs.existsSync(socketPath)) { | ||
| fs.unlinkSync(socketPath); | ||
| } | ||
| }); | ||
|
|
||
| describe('daemonClient', () => { | ||
| it('should throw an error on Windows', () => { | ||
| const originalPlatform = process.platform; | ||
| Object.defineProperty(process, 'platform', { value: 'win32' }); | ||
| expect(() => getDaemonSocketPath()).toThrow( | ||
| 'Daemon mode is currently not supported on Windows.', | ||
| ); | ||
| Object.defineProperty(process, 'platform', { value: originalPlatform }); | ||
| }); | ||
|
|
||
| it('should return false if daemon is not running', async () => { | ||
| const isRunning = await checkDaemonStatus(); | ||
| expect(isRunning).toBe(false); | ||
| }); | ||
|
|
||
| it('should return true if daemon is running', async () => { | ||
| mockServer = net.createServer().listen(socketPath); | ||
| await new Promise((resolve) => setTimeout(resolve, 100)); // wait for listen | ||
|
|
||
| const isRunning = await checkDaemonStatus(); | ||
| expect(isRunning).toBe(true); | ||
| }); | ||
|
|
||
| // We can add more comprehensive e2e test if necessary. | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2026 Google LLC | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| import net from 'node:net'; | ||
| import os from 'node:os'; | ||
| import path from 'node:path'; | ||
| import { | ||
| ExitCodes, | ||
| writeToStderr, | ||
| writeToStdout, | ||
| } from '@google/gemini-cli-core'; | ||
| import type { CliArgs } from '../config/config.js'; | ||
|
|
||
| export function getDaemonSocketPath(): string { | ||
| if (process.platform === 'win32') { | ||
| throw new Error('Daemon mode is currently not supported on Windows.'); | ||
| } | ||
| return path.join(os.homedir(), '.gemini', 'daemon.sock'); | ||
| } | ||
|
|
||
| export async function checkDaemonStatus(): Promise<boolean> { | ||
| const socketPath = getDaemonSocketPath(); | ||
| return new Promise((resolve) => { | ||
| const client = net.createConnection(socketPath, () => { | ||
| client.end(); | ||
| resolve(true); | ||
| }); | ||
| client.on('error', () => { | ||
| resolve(false); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| function connectToDaemon(socketPath: string): Promise<net.Socket> { | ||
| return new Promise((resolve, reject) => { | ||
| const client = net.createConnection(socketPath, () => { | ||
| resolve(client); | ||
| }); | ||
| client.on('error', (err) => { | ||
| reject(err); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| export async function runDaemonClientCommands( | ||
| argv: CliArgs, | ||
| input: string | undefined, | ||
| ): Promise<void> { | ||
| const socketPath = getDaemonSocketPath(); | ||
|
|
||
| if (argv.daemonStatus) { | ||
| const isRunning = await checkDaemonStatus(); | ||
| if (isRunning) { | ||
| writeToStdout('Daemon is running.\n'); | ||
| process.exit(ExitCodes.SUCCESS); | ||
| } else { | ||
| writeToStderr('Daemon is not running.\n'); | ||
| process.exit(1); | ||
| } | ||
| } | ||
|
|
||
| if (argv.daemonStop) { | ||
| try { | ||
| const client = await connectToDaemon(socketPath); | ||
| client.write(JSON.stringify({ action: 'stop' }) + '\n'); | ||
| client.end(); | ||
| writeToStdout('Daemon stop signal sent.\n'); | ||
| process.exit(ExitCodes.SUCCESS); | ||
| } catch (_err) { | ||
| writeToStderr('Error: Daemon not running.\n'); | ||
| process.exit(1); | ||
| } | ||
| } | ||
|
|
||
| if (argv.close) { | ||
| if (!argv.session) { | ||
| writeToStderr( | ||
| 'Error: Please provide a session name with --session when using --close.\n', | ||
| ); | ||
| process.exit(1); | ||
| } | ||
| try { | ||
| const client = await connectToDaemon(socketPath); | ||
| client.write( | ||
| JSON.stringify({ action: 'close_session', session: argv.session }) + | ||
| '\n', | ||
| ); | ||
| await new Promise<void>((resolve) => { | ||
| let buffer = ''; | ||
| client.on('data', (d) => { | ||
| buffer += d.toString(); | ||
| if (buffer.includes('\n')) { | ||
| client.end(); | ||
| resolve(); | ||
| } | ||
| }); | ||
| client.on('end', resolve); | ||
| }).then(() => { | ||
| writeToStdout(`Session '${argv.session}' closed.\n`); | ||
| process.exit(ExitCodes.SUCCESS); | ||
| }); | ||
| return; | ||
| } catch (_err) { | ||
| writeToStderr('Error: Daemon not running.\n'); | ||
| process.exit(1); | ||
| } | ||
| } | ||
|
|
||
| if (argv.client) { | ||
| if (!input) { | ||
| writeToStderr('Error: No prompt provided.\n'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| try { | ||
| const client = await connectToDaemon(socketPath); | ||
|
|
||
| const payload = { | ||
| action: 'prompt', | ||
| session: argv.session || 'default', | ||
| cwd: process.cwd(), | ||
| input, | ||
| verbose: argv.verbose || false, | ||
| }; | ||
|
|
||
| client.write(JSON.stringify(payload) + '\n'); | ||
|
|
||
| client.on('data', (data) => { | ||
| // Output might contain chunks of text or specific formatted messages. | ||
| // For Phase 1 we can just assume the daemon streams back raw text or json lines. | ||
| const lines = data.toString().split('\n'); | ||
| for (let i = 0; i < lines.length - 1; i++) { | ||
| const line = lines[i]; | ||
| if (!line) continue; | ||
| try { | ||
| const msg = JSON.parse(line); | ||
| if (msg.type === 'output') { | ||
| writeToStdout(msg.content); | ||
| } else if (msg.type === 'error') { | ||
| writeToStderr(msg.content + '\n'); | ||
| process.exit(1); | ||
| } else if (msg.type === 'verbose' && argv.verbose) { | ||
| writeToStderr(msg.content + '\n'); | ||
| } else if (msg.type === 'end') { | ||
| client.end(); | ||
| process.exit(ExitCodes.SUCCESS); | ||
| } | ||
| } catch (_e) { | ||
| // Unparseable, just print generic | ||
| writeToStdout(line + '\n'); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| client.on('end', () => { | ||
| process.exit(ExitCodes.SUCCESS); | ||
| }); | ||
|
|
||
| client.on('error', (err) => { | ||
| writeToStderr(`Stream error: ${err.message}\n`); | ||
| process.exit(1); | ||
| }); | ||
| } catch (_err) { | ||
| writeToStderr( | ||
| 'Error: Daemon not running. Start with `gemini --daemon`\n', | ||
| ); | ||
| process.exit(1); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.