diff --git a/packages/cli/src/acp-integration/session/Session.test.ts b/packages/cli/src/acp-integration/session/Session.test.ts index 8b7de8b0609..25fe4f77695 100644 --- a/packages/cli/src/acp-integration/session/Session.test.ts +++ b/packages/cli/src/acp-integration/session/Session.test.ts @@ -1421,6 +1421,75 @@ describe('Session', () => { ); }); + it('wraps tool execution with the sleep inhibitor (acquire before execute, release after)', async () => { + const releaseSpy = vi.fn(); + const acquireSpy = vi + .spyOn(core, 'acquireSleepInhibitor') + .mockReturnValue({ release: releaseSpy }); + try { + const executeSpy = vi.fn().mockResolvedValue({ + llmContent: 'file contents', + returnDisplay: 'file contents', + }); + const tool = { + name: 'read_file', + kind: core.Kind.Read, + build: vi.fn().mockReturnValue({ + params: { path: '/tmp/test.txt' }, + getDefaultPermission: vi.fn().mockResolvedValue('allow'), + getDescription: vi.fn().mockReturnValue('Read file'), + toolLocations: vi.fn().mockReturnValue([]), + execute: executeSpy, + }), + }; + + mockToolRegistry.getTool.mockReturnValue(tool); + mockConfig.getApprovalMode = vi + .fn() + .mockReturnValue(ApprovalMode.YOLO); + mockChat.sendMessageStream = vi + .fn() + .mockResolvedValueOnce( + createStreamWithChunks([ + { + type: core.StreamEventType.CHUNK, + value: { + functionCalls: [ + { + id: 'call-1', + name: 'read_file', + args: { path: '/tmp/test.txt' }, + }, + ], + }, + }, + ]), + ) + .mockResolvedValueOnce(createEmptyStream()); + + await session.prompt({ + sessionId: 'test-session-id', + prompt: [{ type: 'text', text: 'read file' }], + }); + + expect(executeSpy).toHaveBeenCalledTimes(1); + expect(acquireSpy).toHaveBeenCalledWith( + expect.anything(), + expect.stringContaining('read_file'), + ); + expect(releaseSpy).toHaveBeenCalledTimes(1); + // Ordering: acquire → execute → release. + expect(acquireSpy.mock.invocationCallOrder[0]).toBeLessThan( + executeSpy.mock.invocationCallOrder[0], + ); + expect(executeSpy.mock.invocationCallOrder[0]).toBeLessThan( + releaseSpy.mock.invocationCallOrder[0], + ); + } finally { + acquireSpy.mockRestore(); + } + }); + it('stops tool response follow-up before sending when the session token limit is exceeded', async () => { const executeSpy = vi.fn().mockResolvedValue({ llmContent: 'file contents', diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 022ccbf24c2..c12ae3974e6 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -73,6 +73,7 @@ import { shouldFallback, shouldFirePermissionDeniedForAutoMode, shouldRunAutoModeForCall, + acquireSleepInhibitor, } from '@qwen-code/qwen-code-core'; import { getCommandSubcommandNames } from '../../services/commandMetadata.js'; import { getEffectiveSupportedModes } from '../../services/commandUtils.js'; @@ -2296,7 +2297,16 @@ export class Session implements SessionContext { } } - const toolResult: ToolResult = await invocation.execute(abortSignal); + const sleepInhibitorHandle = acquireSleepInhibitor( + this.config, + `Qwen Code is executing tool ${fc.name}`, + ); + let toolResult: ToolResult; + try { + toolResult = await invocation.execute(abortSignal); + } finally { + sleepInhibitorHandle.release(); + } // Clean up event listeners subAgentCleanupFunctions.forEach((cleanup) => cleanup()); diff --git a/packages/cli/src/commands/mcp/add.test.ts b/packages/cli/src/commands/mcp/add.test.ts index 3bc4f87e16b..d24db1a260a 100644 --- a/packages/cli/src/commands/mcp/add.test.ts +++ b/packages/cli/src/commands/mcp/add.test.ts @@ -29,10 +29,13 @@ vi.mock('fs/promises', async (importOriginal) => { }; }); -vi.mock('os', () => { +vi.mock('os', async (importOriginal) => { + const actual = await importOriginal(); const homedir = vi.fn(() => '/home/user'); return { + ...actual, default: { + ...actual, homedir, }, homedir, @@ -247,7 +250,7 @@ describe('mcp add command', () => { .spyOn(process, 'exit') .mockImplementation((() => { throw new Error('process.exit called'); - }) as (code?: number) => never); + }) as typeof process.exit); await expect( parser.parseAsync(`add --scope project ${serverName} ${command}`), diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 695941d4406..64a8d7c384a 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -927,6 +927,29 @@ describe('loadCliConfig', () => { expect(config.getIncludePartialMessages()).toBe(true); }); + it('should enable runtime sleep prevention by default', async () => { + process.argv = ['node', 'script.js']; + const argv = await parseArguments(); + const config = await loadCliConfig({}, argv); + + expect(config.getPreventSystemSleepEnabled()).toBe(true); + }); + + it('should propagate runtime sleep prevention setting', async () => { + process.argv = ['node', 'script.js']; + const argv = await parseArguments(); + const config = await loadCliConfig( + { + general: { + preventSystemSleep: false, + }, + }, + argv, + ); + + expect(config.getPreventSystemSleepEnabled()).toBe(false); + }); + it('should fork and load a new session when --resume is combined with --fork-session', async () => { const sourceSessionId = '123e4567-e89b-42d3-a456-426614174000'; const sourceData = { @@ -2070,7 +2093,7 @@ describe('loadCliConfig with --mcp-config', () => { const argv = await parseArguments(); const config = await loadCliConfig(baseSettings, argv); - const mcpServers = config.getMcpServers(); + const mcpServers = config.getMcpServers()!; expect(mcpServers['cli-server']).toEqual({ command: 'node', args: ['server.js'], @@ -2089,7 +2112,7 @@ describe('loadCliConfig with --mcp-config', () => { const argv = await parseArguments(); const config = await loadCliConfig(baseSettings, argv); - expect(config.getMcpServers()['direct-server']).toEqual({ + expect(config.getMcpServers()!['direct-server']).toEqual({ url: 'http://localhost:8080', }); }); @@ -2103,7 +2126,7 @@ describe('loadCliConfig with --mcp-config', () => { const config = await loadCliConfig(baseSettings, argv); // CLI config should override settings - expect(config.getMcpServers()['settings-server']).toEqual({ + expect(config.getMcpServers()!['settings-server']).toEqual({ url: 'http://localhost:8888', }); }); diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index c099324ddad..fd18b80338c 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -1857,6 +1857,7 @@ export async function loadCliConfig( useRipgrep: settings.tools?.useRipgrep, useBuiltinRipgrep: settings.tools?.useBuiltinRipgrep, shouldUseNodePtyShell: settings.tools?.shell?.enableInteractiveShell, + preventSystemSleep: settings.general?.preventSystemSleep ?? true, skipNextSpeakerCheck: settings.model?.skipNextSpeakerCheck, skipLoopDetection: settings.model?.skipLoopDetection ?? true, skipStartupContext: settings.model?.skipStartupContext ?? false, diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 048d8135f26..81bbaac575a 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -527,6 +527,19 @@ const SETTINGS_SCHEMA = { 'Play terminal bell sound when response completes or needs approval.', showInDialog: true, }, + preventSystemSleep: { + type: 'boolean', + label: 'Prevent System Sleep While Running', + category: 'General', + // Read once at startup via Config.preventSystemSleep (a readonly field + // captured in loadCliConfig), so a runtime toggle only takes effect + // after restart. + requiresRestart: true, + default: true, + description: + 'Prevent the system from sleeping while Qwen Code is streaming a model response or executing tools. Idle prompt time and permission prompts do not inhibit sleep.', + showInDialog: true, + }, chatRecording: { type: 'boolean', label: 'Chat Recording', diff --git a/packages/cli/src/utils/systemInfo.test.ts b/packages/cli/src/utils/systemInfo.test.ts index 7831a74dd0b..526ad93e762 100644 --- a/packages/cli/src/utils/systemInfo.test.ts +++ b/packages/cli/src/utils/systemInfo.test.ts @@ -62,11 +62,16 @@ const setExecFileError = (err: Error) => { }) as unknown as typeof child_process.execFile); }; -vi.mock('node:os', () => ({ - default: { - release: vi.fn(), - }, -})); +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + default: { + ...actual, + release: vi.fn(), + }, + }; +}); vi.mock('./version.js', () => ({ getCliVersion: vi.fn(), diff --git a/packages/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index 3121856ef60..779e1843794 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -1383,6 +1383,21 @@ describe('Server Config (config.ts)', () => { expect(config.getUserMemory()).toBe(''); }); + it('Config constructor should enable runtime sleep prevention by default', () => { + const config = new Config(baseParams); + + expect(config.getPreventSystemSleepEnabled()).toBe(true); + }); + + it('Config constructor should store runtime sleep prevention override', () => { + const config = new Config({ + ...baseParams, + preventSystemSleep: false, + }); + + expect(config.getPreventSystemSleepEnabled()).toBe(false); + }); + it('refreshHierarchicalMemory should append managed auto-memory index when present', async () => { const config = new Config(baseParams); diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index b7df663d5ac..67a1742e90b 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -734,6 +734,8 @@ export interface ConfigParameters { useRipgrep?: boolean; useBuiltinRipgrep?: boolean; shouldUseNodePtyShell?: boolean; + /** Prevent the system from sleeping while model or tool work is in flight. */ + preventSystemSleep?: boolean; skipNextSpeakerCheck?: boolean; shellExecutionConfig?: ShellExecutionConfig; skipLoopDetection?: boolean; @@ -1092,6 +1094,7 @@ export class Config { private readonly useRipgrep: boolean; private readonly useBuiltinRipgrep: boolean; private readonly shouldUseNodePtyShell: boolean; + private readonly preventSystemSleep: boolean; private readonly skipNextSpeakerCheck: boolean; private shellExecutionConfig: ShellExecutionConfig; private arenaManager: ArenaManager | null = null; @@ -1296,6 +1299,7 @@ export class Config { this.useBuiltinRipgrep = params.useBuiltinRipgrep ?? true; this.shouldUseNodePtyShell = params.shouldUseNodePtyShell ?? shouldDefaultToNodePty(); + this.preventSystemSleep = params.preventSystemSleep ?? true; this.skipNextSpeakerCheck = params.skipNextSpeakerCheck ?? true; this.shellExecutionConfig = { terminalWidth: params.shellExecutionConfig?.terminalWidth ?? 80, @@ -3387,6 +3391,10 @@ export class Config { return this.enableAutoSkill && !this.getBareMode(); } + getPreventSystemSleepEnabled(): boolean { + return this.preventSystemSleep; + } + /** * Return the MemoryManager instance created for this Config. * Use this to share background-task state (registry, drainer) with memory diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 32909a5d4d5..41eb53f4b37 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -85,6 +85,15 @@ type ToolSpanRecord = { const toolSpanRecords = vi.hoisted((): ToolSpanRecord[] => []); const shouldThrowToolSpanSetAttribute = vi.hoisted(() => ({ value: false })); const shouldThrowToolSpanSetStatus = vi.hoisted(() => ({ value: false })); +const { mockAcquireSleepInhibitor, mockSleepInhibitorRelease } = vi.hoisted( + () => ({ + mockAcquireSleepInhibitor: vi.fn(() => ({ + release: mockSleepInhibitorRelease, + })), + mockSleepInhibitorRelease: vi.fn(), + }), +); + const debugLoggerWarnSpy = vi.hoisted(() => vi.fn()); const debugLoggerInfoSpy = vi.hoisted(() => vi.fn()); const runSideQueryMock = vi.hoisted(() => vi.fn()); @@ -116,6 +125,10 @@ vi.mock('../telemetry/tracer.js', () => ({ }, })); +vi.mock('../services/sleepInhibitor.js', () => ({ + acquireSleepInhibitor: mockAcquireSleepInhibitor, +})); + vi.mock('../utils/sideQuery.js', () => ({ runSideQuery: (...args: unknown[]) => runSideQueryMock(...args), })); @@ -4663,6 +4676,63 @@ describe('CoreToolScheduler telemetry spans', () => { expect(spanRecord.ended).toBe(true); } + it('acquires the sleep inhibitor around actual tool execution', async () => { + mockAcquireSleepInhibitor.mockClear(); + mockSleepInhibitorRelease.mockClear(); + + const { scheduler, onAllToolCallsComplete } = buildScheduler({ + execute: vi.fn().mockResolvedValue({ + llmContent: 'ok', + returnDisplay: 'ok', + }), + }); + + await scheduler.schedule( + { + callId: 'sleep-call', + name: 'mockTool', + args: {}, + isClientInitiated: false, + prompt_id: 'prompt-id', + }, + new AbortController().signal, + ); + + await vi.waitFor(() => { + expect(onAllToolCallsComplete).toHaveBeenCalled(); + }); + expect(mockAcquireSleepInhibitor).toHaveBeenCalledWith( + expect.any(Object), + 'Qwen Code is executing tool mockTool', + ); + expect(mockSleepInhibitorRelease).toHaveBeenCalledTimes(1); + }); + + it('releases the sleep inhibitor when tool execution throws', async () => { + mockAcquireSleepInhibitor.mockClear(); + mockSleepInhibitorRelease.mockClear(); + + const { scheduler, onAllToolCallsComplete } = buildScheduler({ + execute: vi.fn().mockRejectedValue(new Error('tool crash')), + }); + + await scheduler.schedule( + { + callId: 'sleep-call-fails', + name: 'mockTool', + args: {}, + isClientInitiated: false, + prompt_id: 'prompt-id', + }, + new AbortController().signal, + ); + + await vi.waitFor(() => { + expect(onAllToolCallsComplete).toHaveBeenCalled(); + }); + expect(mockSleepInhibitorRelease).toHaveBeenCalledTimes(1); + }); + it('marks pre-hook denial with a sanitized failure kind', async () => { const execute = vi.fn().mockResolvedValue({ llmContent: 'ok', diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index 16d8898647e..0e2d4ac65d7 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -115,6 +115,7 @@ import { type HookSpanMetadata, } from '../telemetry/index.js'; import { safeJsonStringify } from '../utils/safeJsonStringify.js'; +import { acquireSleepInhibitor } from '../services/sleepInhibitor.js'; const TOOL_FAILURE_KIND_ATTRIBUTE = 'tool.failure_kind'; const TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED = 'pre_hook_blocked'; @@ -2960,6 +2961,10 @@ export class CoreToolScheduler { // throws (e.g. shell setup failure) flow into the same catch as async // rejections — otherwise execSpan leaks unended and failure hooks // are skipped. + const sleepInhibitorHandle = acquireSleepInhibitor( + this.config, + `Qwen Code is executing tool ${canonicalName}`, + ); try { let promise: Promise; if (invocation instanceof ShellToolInvocation) { @@ -3409,6 +3414,8 @@ export class CoreToolScheduler { TOOL_SPAN_STATUS_TOOL_EXCEPTION, ); } + } finally { + sleepInhibitorHandle.release(); } } diff --git a/packages/core/src/core/geminiChat.test.ts b/packages/core/src/core/geminiChat.test.ts index ed757a526d0..b19f4028208 100644 --- a/packages/core/src/core/geminiChat.test.ts +++ b/packages/core/src/core/geminiChat.test.ts @@ -91,6 +91,17 @@ vi.mock('../telemetry/uiTelemetry.js', () => ({ }, })); +const { mockAcquireSleepInhibitor, mockSleepInhibitorRelease } = vi.hoisted( + () => ({ + mockAcquireSleepInhibitor: vi.fn(), + mockSleepInhibitorRelease: vi.fn(), + }), +); + +vi.mock('../services/sleepInhibitor.js', () => ({ + acquireSleepInhibitor: mockAcquireSleepInhibitor, +})); + const { mockDebugLoggerWarn } = vi.hoisted(() => ({ mockDebugLoggerWarn: vi.fn(), })); @@ -117,6 +128,9 @@ describe('GeminiChat', async () => { beforeEach(() => { vi.clearAllMocks(); + mockAcquireSleepInhibitor.mockReturnValue({ + release: mockSleepInhibitorRelease, + }); vi.mocked(uiTelemetryService.setLastPromptTokenCount).mockClear(); mockContentGenerator = { generateContent: vi.fn(), @@ -320,6 +334,67 @@ describe('GeminiChat', async () => { }); describe('sendMessageStream', () => { + it('releases the sleep inhibitor after the stream is consumed', async () => { + vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue( + (async function* () { + yield { + candidates: [ + { + content: { role: 'model', parts: [{ text: 'done' }] }, + finishReason: 'STOP', + }, + ], + } as unknown as GenerateContentResponse; + })(), + ); + + const stream = await chat.sendMessageStream( + 'test-model', + { message: 'test message' }, + 'prompt-id-sleep-inhibitor', + ); + for await (const _ of stream) { + /* consume stream */ + } + + expect(mockAcquireSleepInhibitor).toHaveBeenCalledWith( + mockConfig, + 'Qwen Code is streaming a model response', + ); + expect(mockSleepInhibitorRelease).toHaveBeenCalledTimes(1); + }); + + it('releases the sleep inhibitor when the stream errors', async () => { + vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue( + (async function* () { + yield { + candidates: [ + { + content: { role: 'model', parts: [{ text: 'partial' }] }, + }, + ], + } as unknown as GenerateContentResponse; + throw new Error('stream aborted'); + })(), + ); + + const stream = await chat.sendMessageStream( + 'test-model', + { message: 'fail' }, + 'prompt-id-stream-error', + ); + + await expect( + (async () => { + for await (const _ of stream) { + /* consume stream */ + } + })(), + ).rejects.toThrow('stream aborted'); + + expect(mockSleepInhibitorRelease).toHaveBeenCalledTimes(1); + }); + it('should succeed if a tool call is followed by an empty part', async () => { // 1. Mock a stream that contains a tool call, then an invalid (empty) part. const streamWithToolCall = (async function* () { diff --git a/packages/core/src/core/geminiChat.ts b/packages/core/src/core/geminiChat.ts index 6c17eec1272..a494f18f613 100644 --- a/packages/core/src/core/geminiChat.ts +++ b/packages/core/src/core/geminiChat.ts @@ -51,6 +51,7 @@ import { MAX_CONSECUTIVE_FAILURES, type CompactTrigger, } from '../services/chatCompressionService.js'; +import { acquireSleepInhibitor } from '../services/sleepInhibitor.js'; import { resolveSlimmingConfig } from '../services/compactionInputSlimming.js'; import { estimatePromptTokens } from '../services/tokenEstimation.js'; import { @@ -1747,6 +1748,10 @@ export class GeminiChat { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; return (async function* () { + const sleepInhibitorHandle = acquireSleepInhibitor( + self.config, + 'Qwen Code is streaming a model response', + ); try { // Surface a successful auto-compression to the caller as the first // event in the stream. Failed/skipped compaction attempts are silent. @@ -2285,6 +2290,7 @@ export class GeminiChat { throw lastError; } } finally { + sleepInhibitorHandle.release(); streamDoneResolver!(); // Flush any deferred partial-tool_use record. Covers both the // post-retry-loop unretryable break AND the max-tokens diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6a9103df5ca..d6e24a605f5 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -153,6 +153,7 @@ export * from './services/gitWorktreeService.js'; export * from './services/sessionRecap.js'; export * from './services/sessionService.js'; export * from './services/sessionTitle.js'; +export * from './services/sleepInhibitor.js'; export * from './services/worktreeSessionService.js'; export { stripTerminalControlSequences, diff --git a/packages/core/src/services/sleepInhibitor.test.ts b/packages/core/src/services/sleepInhibitor.test.ts new file mode 100644 index 00000000000..dbb8f12665e --- /dev/null +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -0,0 +1,302 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { EventEmitter } from 'node:events'; +import type { ChildProcess, SpawnOptions } from 'node:child_process'; +import { describe, expect, it, vi } from 'vitest'; +import { acquireSleepInhibitor, SleepInhibitor } from './sleepInhibitor.js'; + +function createChild(): ChildProcess { + const child = new EventEmitter() as ChildProcess; + let killed = false; + Object.defineProperty(child, 'killed', { + get: () => killed, + }); + child.kill = vi.fn(() => { + killed = true; + return true; + }); + return child; +} + +function createHarness(platform: NodeJS.Platform = 'linux') { + const children: ChildProcess[] = []; + const spawn = vi.fn( + (_command: string, _args: string[], _options?: SpawnOptions) => { + const child = createChild(); + children.push(child); + return child; + }, + ); + const logger = { + debug: vi.fn(), + warn: vi.fn(), + }; + const inhibitor = new SleepInhibitor({ platform, spawn, logger }); + return { children, inhibitor, logger, spawn }; +} + +describe('SleepInhibitor', () => { + it('starts systemd-inhibit on linux and stops it after the final release', () => { + const { children, inhibitor, spawn } = createHarness('linux'); + + const first = inhibitor.acquire('working'); + const second = inhibitor.acquire('working again'); + + expect(spawn).toHaveBeenCalledTimes(1); + expect(spawn).toHaveBeenCalledWith( + 'systemd-inhibit', + [ + '--what=sleep', + '--who=Qwen Code', + '--why=working', + '--mode=block', + 'sleep', + 'infinity', + ], + expect.objectContaining({ + env: expect.any(Object), + stdio: 'ignore', + windowsHide: true, + }), + ); + expect(inhibitor.getActiveCount()).toBe(2); + + first.release(); + expect(children[0]!.kill).not.toHaveBeenCalled(); + expect(inhibitor.isRunning()).toBe(true); + + second.release(); + expect(children[0]!.kill).toHaveBeenCalledTimes(1); + expect(inhibitor.getActiveCount()).toBe(0); + expect(inhibitor.isRunning()).toBe(false); + }); + + it('forwards a curated environment instead of an empty env', () => { + const { inhibitor, spawn } = createHarness('linux'); + const previous = process.env['DBUS_SESSION_BUS_ADDRESS']; + process.env['DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=/run/user/1000/bus'; + try { + const handle = inhibitor.acquire(); + const env = spawn.mock.calls[0]![2]!.env as NodeJS.ProcessEnv; + // D-Bus address required by systemd-inhibit must be forwarded. + expect(env['DBUS_SESSION_BUS_ADDRESS']).toBe( + 'unix:path=/run/user/1000/bus', + ); + // Arbitrary parent env vars must NOT be forwarded. + expect(env).not.toHaveProperty('SOME_UNRELATED_SECRET'); + handle.release(); + } finally { + if (previous === undefined) { + delete process.env['DBUS_SESSION_BUS_ADDRESS']; + } else { + process.env['DBUS_SESSION_BUS_ADDRESS'] = previous; + } + } + }); + + it('uses caffeinate on macOS', () => { + const { inhibitor, spawn } = createHarness('darwin'); + + const handle = inhibitor.acquire(); + + expect(spawn).toHaveBeenCalledWith( + 'caffeinate', + ['-is'], + expect.any(Object), + ); + handle.release(); + }); + + it('uses a PowerShell SetThreadExecutionState helper on Windows', () => { + const { inhibitor, spawn } = createHarness('win32'); + + const handle = inhibitor.acquire(); + + expect(spawn).toHaveBeenCalledWith( + 'powershell.exe', + expect.arrayContaining([ + expect.stringContaining('SetThreadExecutionState'), + ]), + expect.any(Object), + ); + handle.release(); + }); + + it('ignores duplicate releases', () => { + const { children, inhibitor } = createHarness('linux'); + + const handle = inhibitor.acquire(); + handle.release(); + handle.release(); + + expect(inhibitor.getActiveCount()).toBe(0); + expect(children[0]!.kill).toHaveBeenCalledTimes(1); + }); + + it('fails open when spawning throws', () => { + const spawn = vi.fn(() => { + throw new Error('missing command'); + }); + const logger = { debug: vi.fn(), warn: vi.fn() }; + const inhibitor = new SleepInhibitor({ + platform: 'linux', + spawn, + logger, + }); + + const handle = inhibitor.acquire(); + + expect(() => handle.release()).not.toThrow(); + expect(logger.debug).toHaveBeenCalledWith( + 'Failed to spawn sleep inhibitor: missing command', + ); + expect(inhibitor.getActiveCount()).toBe(0); + }); + + it('handles async error events from the spawned child', () => { + const { children, inhibitor, logger } = createHarness('linux'); + + const handle = inhibitor.acquire(); + children[0]!.emit('error', new Error('EPERM')); + + expect(inhibitor.isRunning()).toBe(false); + expect(logger.debug).toHaveBeenCalledWith( + 'Failed to start sleep inhibitor: EPERM', + ); + handle.release(); + }); + + it('restarts after an unexpected exit when acquired again', () => { + const { children, inhibitor, logger, spawn } = createHarness('linux'); + + const first = inhibitor.acquire('initial work'); + children[0]!.emit('exit', 1, null); + + expect(inhibitor.isRunning()).toBe(false); + expect(logger.debug).toHaveBeenCalledWith( + 'Sleep inhibitor exited while active: code=1 signal=null', + ); + + const second = inhibitor.acquire('more work'); + expect(spawn).toHaveBeenCalledTimes(2); + expect(inhibitor.isRunning()).toBe(true); + + first.release(); + second.release(); + }); + + it('returns a no-op handle when config does not explicitly enable it', () => { + const disabled = acquireSleepInhibitor({ + getPreventSystemSleepEnabled: () => false, + }); + const missingGetter = acquireSleepInhibitor( + {} as { + getPreventSystemSleepEnabled: () => boolean; + }, + ); + + expect(() => disabled.release()).not.toThrow(); + expect(() => missingGetter.release()).not.toThrow(); + }); + + it('dispose kills the active child, resets state, and is idempotent', () => { + const { children, inhibitor } = createHarness('linux'); + + inhibitor.acquire('work'); + inhibitor.acquire('more work'); + expect(inhibitor.getActiveCount()).toBe(2); + expect(inhibitor.isRunning()).toBe(true); + + inhibitor.dispose(); + expect(children[0]!.kill).toHaveBeenCalledTimes(1); + expect(inhibitor.getActiveCount()).toBe(0); + expect(inhibitor.isRunning()).toBe(false); + + // Second dispose is a no-op and must not throw or re-kill. + expect(() => inhibitor.dispose()).not.toThrow(); + expect(children[0]!.kill).toHaveBeenCalledTimes(1); + }); + + it('does not propagate when child.kill() throws during release', () => { + const children: ChildProcess[] = []; + const spawn = vi.fn(() => { + const child = new EventEmitter() as ChildProcess; + Object.defineProperty(child, 'killed', { get: () => false }); + child.kill = vi.fn(() => { + throw new Error('ESRCH'); + }); + children.push(child); + return child; + }); + const logger = { debug: vi.fn(), warn: vi.fn() }; + const inhibitor = new SleepInhibitor({ platform: 'linux', spawn, logger }); + + const handle = inhibitor.acquire(); + expect(() => handle.release()).not.toThrow(); + expect(logger.warn).toHaveBeenCalledWith( + 'Failed to stop sleep inhibitor: ESRCH', + ); + expect(inhibitor.getActiveCount()).toBe(0); + }); + + it('ignores a late error event from an already-replaced child', () => { + const { children, inhibitor, logger, spawn } = createHarness('linux'); + + const first = inhibitor.acquire(); + // First child exits, so this.child is cleared and a re-acquire respawns. + children[0]!.emit('exit', 0, null); + const second = inhibitor.acquire(); + expect(spawn).toHaveBeenCalledTimes(2); + expect(inhibitor.isRunning()).toBe(true); + + logger.debug.mockClear(); + // A late error from the stale first child must be ignored: it must not + // flip spawnFailedForCurrentRun nor clear the current (second) child. + children[0]!.emit('error', new Error('ESRCH')); + expect(logger.debug).not.toHaveBeenCalledWith( + 'Failed to start sleep inhibitor: ESRCH', + ); + expect(inhibitor.isRunning()).toBe(true); + + first.release(); + second.release(); + }); + + it('latches on an unsupported platform so it only checks once', () => { + const { inhibitor, logger, spawn } = createHarness( + 'freebsd' as NodeJS.Platform, + ); + + const first = inhibitor.acquire(); + const second = inhibitor.acquire(); + + expect(spawn).not.toHaveBeenCalled(); + expect(inhibitor.isRunning()).toBe(false); + expect( + logger.debug.mock.calls.filter((call) => + String(call[0]).includes('unsupported on platform'), + ), + ).toHaveLength(1); + + first.release(); + second.release(); + }); + + it('sanitizes the systemd-inhibit reason (strips control chars, caps length)', () => { + const { inhibitor, spawn } = createHarness('linux'); + + const handle = inhibitor.acquire(`run\x00 tool\n${'x'.repeat(200)}`); + const args = spawn.mock.calls[0]![1] as string[]; + const why = args.find((arg) => arg.startsWith('--why='))!; + + // eslint-disable-next-line no-control-regex + expect(why).not.toMatch(/[\x00-\x1f\x7f]/); + expect(why.length).toBeLessThanOrEqual('--why='.length + 120); + + handle.release(); + }); +}); diff --git a/packages/core/src/services/sleepInhibitor.ts b/packages/core/src/services/sleepInhibitor.ts new file mode 100644 index 00000000000..7c7da3714f0 --- /dev/null +++ b/packages/core/src/services/sleepInhibitor.ts @@ -0,0 +1,294 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + spawn as defaultSpawn, + type ChildProcess, + type SpawnOptions, +} from 'node:child_process'; +import { platform as defaultPlatform } from 'node:os'; +import type { Config } from '../config/config.js'; +import { createDebugLogger } from '../utils/debugLogger.js'; + +const debugLogger = createDebugLogger('SLEEP_INHIBITOR'); + +export interface SleepInhibitorHandle { + release(): void; +} + +export interface SleepInhibitorConfig { + platform?: NodeJS.Platform; + spawn?: ( + command: string, + args: string[], + options?: SpawnOptions, + ) => ChildProcess; + logger?: Pick, 'debug' | 'warn'>; +} + +const NOOP_HANDLE: SleepInhibitorHandle = { + release() {}, +}; + +const MAX_INHIBITOR_REASON_LENGTH = 120; + +/** + * Sanitize the inhibitor reason before it is passed to `systemd-inhibit + * --why=`. The string is visible in process listings (`ps`, + * `systemd-inhibit --list`) on shared systems, so strip control characters + * and cap the length to avoid leaking large/multiline context. + */ +function sanitizeInhibitorReason(reason: string): string { + // Strip C0 control characters and DEL. + // eslint-disable-next-line no-control-regex + const controlChars = /[\x00-\x1f\x7f]/g; + return reason + .replace(controlChars, ' ') + .slice(0, MAX_INHIBITOR_REASON_LENGTH) + .trim(); +} + +export class SleepInhibitor { + private activeCount = 0; + private child: ChildProcess | undefined; + private spawnFailedForCurrentRun = false; + private readonly platform: NodeJS.Platform; + private readonly spawn: NonNullable; + private readonly logger: NonNullable; + + constructor(config: SleepInhibitorConfig = {}) { + this.platform = config.platform ?? defaultPlatform(); + this.spawn = + config.spawn ?? + ((command, args, options) => defaultSpawn(command, args, options ?? {})); + this.logger = config.logger ?? debugLogger; + } + + acquire(reason = 'Qwen Code is processing a request'): SleepInhibitorHandle { + this.activeCount += 1; + + if (this.activeCount === 1) { + this.spawnFailedForCurrentRun = false; + this.start(reason); + } else if (!this.child && !this.spawnFailedForCurrentRun) { + this.start(reason); + } + + let released = false; + return { + release: () => { + if (released) { + return; + } + released = true; + this.release(); + }, + }; + } + + getActiveCount(): number { + return this.activeCount; + } + + isRunning(): boolean { + return this.child !== undefined; + } + + private release(): void { + if (this.activeCount === 0) { + return; + } + + this.activeCount -= 1; + if (this.activeCount === 0) { + this.stop(); + this.spawnFailedForCurrentRun = false; + } + } + + private start(reason: string): void { + if (this.child || this.spawnFailedForCurrentRun) { + return; + } + + const command = this.getCommand(reason); + if (!command) { + this.logger.debug( + `Sleep inhibition is unsupported on platform ${this.platform}.`, + ); + // Latch so we don't re-check and re-log the unsupported platform on + // every subsequent acquire() within the same run. + this.spawnFailedForCurrentRun = true; + return; + } + + try { + const child = this.spawn(command.command, command.args, { + stdio: 'ignore', + detached: false, + windowsHide: true, + env: this.getSpawnEnv(), + }); + this.child = child; + + child.once('error', (error) => { + // Guard the whole handler: a stale child (already replaced by a + // newer spawn) must not flip spawnFailedForCurrentRun and poison the + // current run's respawn logic. + if (this.child !== child) { + return; + } + this.logger.debug(`Failed to start sleep inhibitor: ${error.message}`); + this.spawnFailedForCurrentRun = true; + this.child = undefined; + }); + + child.once('exit', (code, signal) => { + if (this.child === child) { + this.child = undefined; + } + if (this.activeCount > 0 && !this.spawnFailedForCurrentRun) { + this.logger.debug( + `Sleep inhibitor exited while active: code=${String(code)} signal=${String(signal)}`, + ); + } + }); + } catch (error) { + this.spawnFailedForCurrentRun = true; + this.logger.debug( + `Failed to spawn sleep inhibitor: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } + + /** + * Kill any active inhibitor subprocess and reset state. Safe to call + * multiple times; used by the process-exit handler to avoid orphaning the + * subprocess. + */ + dispose(): void { + this.activeCount = 0; + this.spawnFailedForCurrentRun = false; + this.stop(); + } + + /** + * Build a minimal environment for the inhibitor subprocess instead of + * passing an empty env. An empty env strips PATH (so the command cannot be + * resolved) and DBUS_SESSION_BUS_ADDRESS/XDG_RUNTIME_DIR (which + * systemd-inhibit needs to reach the user's systemd over D-Bus on Linux). + * On Windows, PowerShell needs SYSTEMROOT/WINDIR. + */ + private getSpawnEnv(): NodeJS.ProcessEnv { + const allowList = [ + 'PATH', + 'DBUS_SESSION_BUS_ADDRESS', + 'XDG_RUNTIME_DIR', + 'SYSTEMROOT', + 'WINDIR', + 'TEMP', + 'TMP', + ]; + const env: NodeJS.ProcessEnv = {}; + for (const key of allowList) { + const value = process.env[key]; + if (value !== undefined) { + env[key] = value; + } + } + return env; + } + + private stop(): void { + const child = this.child; + this.child = undefined; + if (!child || child.killed) { + return; + } + + try { + child.kill(); + } catch (error) { + this.logger.warn( + `Failed to stop sleep inhibitor: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } + + private getCommand( + reason: string, + ): { command: string; args: string[] } | undefined { + switch (this.platform) { + case 'darwin': + // -i prevents idle sleep; -s prevents system sleep but, per the + // caffeinate(8) man page, only while on AC power. On battery -s is + // ignored and lid-close sleep still occurs — macOS does not expose a + // way to block that, so this does not fully match the Linux + // systemd-inhibit semantics on battery. + return { command: 'caffeinate', args: ['-is'] }; + case 'linux': + return { + command: 'systemd-inhibit', + args: [ + '--what=sleep', + '--who=Qwen Code', + `--why=${sanitizeInhibitorReason(reason)}`, + '--mode=block', + 'sleep', + 'infinity', + ], + }; + case 'win32': + return { + command: 'powershell.exe', + args: [ + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-Command', + WINDOWS_INHIBIT_SCRIPT, + ], + }; + default: + return undefined; + } + } +} + +const WINDOWS_INHIBIT_SCRIPT = ` +Add-Type -Namespace QwenCode -Name SleepUtil -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags);'; +[QwenCode.SleepUtil]::SetThreadExecutionState(0x80000001) | Out-Null; +try { + while ($true) { Start-Sleep -Seconds 3600 } +} finally { + [QwenCode.SleepUtil]::SetThreadExecutionState(0x80000000) | Out-Null; +} +`.trim(); + +export const sleepInhibitor = new SleepInhibitor(); + +// Kill the inhibitor subprocess if the parent process exits; otherwise an +// orphaned `caffeinate`/`systemd-inhibit`/PowerShell process would keep +// blocking system sleep indefinitely. Mirrors the exit handling in +// shellExecutionService. +process.on('exit', () => { + sleepInhibitor.dispose(); +}); + +export function acquireSleepInhibitor( + config: Pick, + reason?: string, +): SleepInhibitorHandle { + if (config.getPreventSystemSleepEnabled?.() !== true) { + return NOOP_HANDLE; + } + return sleepInhibitor.acquire(reason); +} diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 54cce9f9f33..38434ecc629 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -138,6 +138,11 @@ "type": "boolean", "default": true }, + "preventSystemSleep": { + "description": "Prevent the system from sleeping while Qwen Code is streaming a model response or executing tools. Idle prompt time and permission prompts do not inhibit sleep.", + "type": "boolean", + "default": true + }, "chatRecording": { "description": "Enable saving chat history to disk. Disabling this will also prevent --continue and --resume from working.", "type": "boolean",