From 732fd089f39bf51aa9d4bc4784f85a179bfb9e8d Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Fri, 22 May 2026 15:41:07 +0800 Subject: [PATCH 1/6] feat(cli): prevent system sleep while running --- .../src/acp-integration/session/Session.ts | 12 +- packages/cli/src/config/config.test.ts | 23 ++ packages/cli/src/config/config.ts | 1 + packages/cli/src/config/settingsSchema.ts | 10 + packages/core/src/config/config.test.ts | 15 ++ packages/core/src/config/config.ts | 8 + .../core/src/core/coreToolScheduler.test.ts | 44 ++++ packages/core/src/core/coreToolScheduler.ts | 7 + packages/core/src/core/geminiChat.test.ts | 44 ++++ packages/core/src/core/geminiChat.ts | 6 + packages/core/src/index.ts | 1 + .../core/src/services/sleepInhibitor.test.ts | 159 +++++++++++++ packages/core/src/services/sleepInhibitor.ts | 215 ++++++++++++++++++ .../schemas/settings.schema.json | 5 + 14 files changed, 549 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/services/sleepInhibitor.test.ts create mode 100644 packages/core/src/services/sleepInhibitor.ts diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 624a3554cbf..4d2a6314e4f 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -68,6 +68,7 @@ import { recordFallbackApprove, shouldFallback, shouldRunAutoModeForCall, + acquireSleepInhibitor, } from '@qwen-code/qwen-code-core'; import { getCommandSubcommandNames } from '../../services/commandMetadata.js'; import { getEffectiveSupportedModes } from '../../services/commandUtils.js'; @@ -2237,7 +2238,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/config/config.test.ts b/packages/cli/src/config/config.test.ts index 972bec8c8ce..1af1e0d4f95 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 = { diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index baea941922e..aa8eda207ce 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -1758,6 +1758,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 46726450ae8..a322ea89063 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -513,6 +513,16 @@ 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', + requiresRestart: false, + 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/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index a9badd5878d..a5d7a6e13ba 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -1186,6 +1186,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 733f8bab3e8..2ccfda86227 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -624,6 +624,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; @@ -903,6 +905,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; @@ -1088,6 +1091,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, @@ -3040,6 +3044,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 bd301398f79..c8eba1a2909 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -83,6 +83,14 @@ 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(), + }), +); vi.mock('../telemetry/tracer.js', () => ({ safeSetStatus: ( @@ -97,6 +105,10 @@ vi.mock('../telemetry/tracer.js', () => ({ }, })); +vi.mock('../services/sleepInhibitor.js', () => ({ + acquireSleepInhibitor: mockAcquireSleepInhibitor, +})); + function createMockToolSpan( name: string, attributes: Record, @@ -3474,6 +3486,38 @@ 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('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 9b594554132..afb3a52614e 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -108,6 +108,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'; @@ -2695,6 +2696,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) { @@ -3144,6 +3149,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 55582e77efe..0f866b4918f 100644 --- a/packages/core/src/core/geminiChat.test.ts +++ b/packages/core/src/core/geminiChat.test.ts @@ -83,6 +83,17 @@ vi.mock('../telemetry/uiTelemetry.js', () => ({ }, })); +const { mockAcquireSleepInhibitor, mockSleepInhibitorRelease } = vi.hoisted( + () => ({ + mockAcquireSleepInhibitor: vi.fn(), + mockSleepInhibitorRelease: vi.fn(), + }), +); + +vi.mock('../services/sleepInhibitor.js', () => ({ + acquireSleepInhibitor: mockAcquireSleepInhibitor, +})); + describe('GeminiChat', async () => { let mockContentGenerator: ContentGenerator; let chat: GeminiChat; @@ -91,6 +102,9 @@ describe('GeminiChat', async () => { beforeEach(() => { vi.clearAllMocks(); + mockAcquireSleepInhibitor.mockReturnValue({ + release: mockSleepInhibitorRelease, + }); vi.mocked(uiTelemetryService.setLastPromptTokenCount).mockClear(); mockContentGenerator = { generateContent: vi.fn(), @@ -292,6 +306,36 @@ 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('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 c657b02f5cf..cec4554d46b 100644 --- a/packages/core/src/core/geminiChat.ts +++ b/packages/core/src/core/geminiChat.ts @@ -46,6 +46,7 @@ import { ChatCompressionService, type CompactTrigger, } from '../services/chatCompressionService.js'; +import { acquireSleepInhibitor } from '../services/sleepInhibitor.js'; import { ContentRetryEvent, ContentRetryFailureEvent, @@ -1090,6 +1091,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. @@ -1525,6 +1530,7 @@ export class GeminiChat { throw lastError; } } finally { + sleepInhibitorHandle.release(); streamDoneResolver!(); } })(); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fa6b98522df..79b71848dba 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -149,6 +149,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..e66679703df --- /dev/null +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -0,0 +1,159 @@ +/** + * @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({ 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('uses caffeinate on macOS', () => { + const { inhibitor, spawn } = createHarness('darwin'); + + const handle = inhibitor.acquire(); + + expect(spawn).toHaveBeenCalledWith( + 'caffeinate', + ['-i'], + 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('clears the child when it exits unexpectedly', () => { + const { children, inhibitor, logger } = createHarness('linux'); + + const handle = inhibitor.acquire(); + children[0]!.emit('exit', 1, null); + + expect(inhibitor.isRunning()).toBe(false); + expect(logger.debug).toHaveBeenCalledWith( + 'Sleep inhibitor exited while active: code=1 signal=null', + ); + handle.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(); + }); +}); diff --git a/packages/core/src/services/sleepInhibitor.ts b/packages/core/src/services/sleepInhibitor.ts new file mode 100644 index 00000000000..cef4468a328 --- /dev/null +++ b/packages/core/src/services/sleepInhibitor.ts @@ -0,0 +1,215 @@ +/** + * @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() {}, +}; + +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); + } + + 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}.`, + ); + return; + } + + try { + const child = this.spawn(command.command, command.args, { + stdio: 'ignore', + detached: false, + windowsHide: true, + }); + this.child = child; + + child.once('error', (error) => { + this.logger.debug(`Failed to start sleep inhibitor: ${error.message}`); + this.spawnFailedForCurrentRun = true; + if (this.child === child) { + 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) + }`, + ); + } + } + + 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': + return { command: 'caffeinate', args: ['-i'] }; + case 'linux': + return { + command: 'systemd-inhibit', + args: [ + '--what=sleep', + '--who=Qwen Code', + `--why=${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(); + +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 9ea83878b01..84fce958646 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -133,6 +133,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", From 8e46c8259e9e84bfeb9b95550cfe1b2734c61dbd Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Fri, 22 May 2026 17:37:37 +0800 Subject: [PATCH 2/6] fix(cli): spread actual node:os exports in test mocks for sleepInhibitor barrel compat The sleepInhibitor module (added to core barrel export) imports 'platform' as a named export from node:os and instantiates a module-level singleton. Test mocks in systemInfo.test.ts and add.test.ts replaced the entire node:os module with incomplete overrides, causing 'defaultPlatform is not a function' during module evaluation. Fix: use importOriginal to spread actual node:os exports before applying test-specific overrides, matching the pattern already used by other os mocks in the codebase. --- packages/cli/src/commands/mcp/add.test.ts | 5 ++++- packages/cli/src/utils/systemInfo.test.ts | 15 ++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/commands/mcp/add.test.ts b/packages/cli/src/commands/mcp/add.test.ts index 3bc4f87e16b..f5489b8751c 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, 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(), From 0074dfd6f92853684f4ed802e2a4797f5f7b774c Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Mon, 25 May 2026 11:19:54 +0800 Subject: [PATCH 3/6] fix(core): use caffeinate -is on macOS to also prevent lid-close sleep caffeinate -i only prevents idle sleep. Adding -s also prevents system sleep (including lid-close on AC power), matching the Linux systemd-inhibit semantics which blocks all sleep transitions. This was the most common real-world failure scenario: a user closing the laptop lid during a long tool execution would still trigger sleep on macOS despite the inhibitor being active. Addresses PR #4434 review feedback. --- packages/core/src/services/sleepInhibitor.test.ts | 2 +- packages/core/src/services/sleepInhibitor.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/src/services/sleepInhibitor.test.ts b/packages/core/src/services/sleepInhibitor.test.ts index e66679703df..77c48db27d4 100644 --- a/packages/core/src/services/sleepInhibitor.test.ts +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -78,7 +78,7 @@ describe('SleepInhibitor', () => { expect(spawn).toHaveBeenCalledWith( 'caffeinate', - ['-i'], + ['-is'], expect.any(Object), ); handle.release(); diff --git a/packages/core/src/services/sleepInhibitor.ts b/packages/core/src/services/sleepInhibitor.ts index cef4468a328..5dd9f22684f 100644 --- a/packages/core/src/services/sleepInhibitor.ts +++ b/packages/core/src/services/sleepInhibitor.ts @@ -161,7 +161,10 @@ export class SleepInhibitor { ): { command: string; args: string[] } | undefined { switch (this.platform) { case 'darwin': - return { command: 'caffeinate', args: ['-i'] }; + // -i prevents idle sleep, -s prevents system sleep (including + // lid-close on AC power). Both are needed to match the Linux + // systemd-inhibit semantics which blocks all sleep transitions. + return { command: 'caffeinate', args: ['-is'] }; case 'linux': return { command: 'systemd-inhibit', From 3b53c32f0c018c894f42ca79cec5d503a5fe1f4a Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Mon, 25 May 2026 11:37:45 +0800 Subject: [PATCH 4/6] fix(core): address sleep inhibitor review feedback --- packages/cli/src/commands/mcp/add.test.ts | 2 +- packages/cli/src/config/config.test.ts | 6 ++-- .../core/src/core/coreToolScheduler.test.ts | 25 +++++++++++++++ packages/core/src/core/geminiChat.test.ts | 31 +++++++++++++++++++ .../core/src/services/sleepInhibitor.test.ts | 29 +++++++++++++++-- packages/core/src/services/sleepInhibitor.ts | 3 ++ 6 files changed, 89 insertions(+), 7 deletions(-) diff --git a/packages/cli/src/commands/mcp/add.test.ts b/packages/cli/src/commands/mcp/add.test.ts index f5489b8751c..d24db1a260a 100644 --- a/packages/cli/src/commands/mcp/add.test.ts +++ b/packages/cli/src/commands/mcp/add.test.ts @@ -250,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 1af1e0d4f95..8a853a16044 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -2093,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'], @@ -2112,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', }); }); @@ -2126,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/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index c8eba1a2909..284ff34fca1 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -3518,6 +3518,31 @@ describe('CoreToolScheduler telemetry spans', () => { 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/geminiChat.test.ts b/packages/core/src/core/geminiChat.test.ts index 0f866b4918f..35fc3c99e3a 100644 --- a/packages/core/src/core/geminiChat.test.ts +++ b/packages/core/src/core/geminiChat.test.ts @@ -336,6 +336,37 @@ describe('GeminiChat', async () => { 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/services/sleepInhibitor.test.ts b/packages/core/src/services/sleepInhibitor.test.ts index 77c48db27d4..d3e627f324e 100644 --- a/packages/core/src/services/sleepInhibitor.test.ts +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -57,7 +57,11 @@ describe('SleepInhibitor', () => { 'sleep', 'infinity', ], - expect.objectContaining({ stdio: 'ignore', windowsHide: true }), + expect.objectContaining({ + env: {}, + stdio: 'ignore', + windowsHide: true, + }), ); expect(inhibitor.getActiveCount()).toBe(2); @@ -130,17 +134,36 @@ describe('SleepInhibitor', () => { expect(inhibitor.getActiveCount()).toBe(0); }); - it('clears the child when it exits unexpectedly', () => { + 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', ); - handle.release(); + + 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', () => { diff --git a/packages/core/src/services/sleepInhibitor.ts b/packages/core/src/services/sleepInhibitor.ts index 5dd9f22684f..8df981d55bd 100644 --- a/packages/core/src/services/sleepInhibitor.ts +++ b/packages/core/src/services/sleepInhibitor.ts @@ -55,6 +55,8 @@ export class SleepInhibitor { if (this.activeCount === 1) { this.spawnFailedForCurrentRun = false; this.start(reason); + } else if (!this.child && !this.spawnFailedForCurrentRun) { + this.start(reason); } let released = false; @@ -107,6 +109,7 @@ export class SleepInhibitor { stdio: 'ignore', detached: false, windowsHide: true, + env: {}, }); this.child = child; From 2e647661a2abd7feba3293fccce1ec4352170380 Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Fri, 5 Jun 2026 14:52:35 +0800 Subject: [PATCH 5/6] fix(core): harden sleep inhibitor per review feedback - Register a process 'exit' handler so the caffeinate/systemd-inhibit/ PowerShell subprocess is killed when the parent exits, preventing an orphaned process from blocking system sleep indefinitely. - Pass a curated environment instead of an empty one: an empty env stripped PATH (command resolution) and DBUS_SESSION_BUS_ADDRESS/XDG_RUNTIME_DIR (required by systemd-inhibit over D-Bus on Linux) and SYSTEMROOT/WINDIR (required by PowerShell on Windows). - Guard the whole 'error' handler with `this.child === child` so a stale child's error cannot poison spawnFailedForCurrentRun and block respawn. --- .../core/src/services/sleepInhibitor.test.ts | 25 +++++++- packages/core/src/services/sleepInhibitor.ts | 58 +++++++++++++++++-- 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/packages/core/src/services/sleepInhibitor.test.ts b/packages/core/src/services/sleepInhibitor.test.ts index d3e627f324e..7674b77c523 100644 --- a/packages/core/src/services/sleepInhibitor.test.ts +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -58,7 +58,7 @@ describe('SleepInhibitor', () => { 'infinity', ], expect.objectContaining({ - env: {}, + env: expect.any(Object), stdio: 'ignore', windowsHide: true, }), @@ -75,6 +75,29 @@ describe('SleepInhibitor', () => { 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'); diff --git a/packages/core/src/services/sleepInhibitor.ts b/packages/core/src/services/sleepInhibitor.ts index 8df981d55bd..87cbf3738ba 100644 --- a/packages/core/src/services/sleepInhibitor.ts +++ b/packages/core/src/services/sleepInhibitor.ts @@ -109,16 +109,20 @@ export class SleepInhibitor { stdio: 'ignore', detached: false, windowsHide: true, - env: {}, + 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; - if (this.child === child) { - this.child = undefined; - } + this.child = undefined; }); child.once('exit', (code, signal) => { @@ -141,6 +145,44 @@ export class SleepInhibitor { } } + /** + * 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; @@ -210,6 +252,14 @@ try { 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, From 1b29c18d75c66de75d052ecfabd06591de0443a8 Mon Sep 17 00:00:00 2001 From: DragonnZhang <731557579@qq.com> Date: Fri, 5 Jun 2026 16:23:11 +0800 Subject: [PATCH 6/6] fix(core): refine sleep inhibitor per follow-up review - settingsSchema: mark preventSystemSleep requiresRestart (it's read once at startup via Config.preventSystemSleep, so a runtime toggle needs a restart). - Latch spawnFailedForCurrentRun on unsupported platforms so acquire() doesn't re-check and re-log on every call. - Sanitize the systemd-inhibit --why reason (strip control chars, cap length) since it is visible in process listings on shared systems. - Correct the caffeinate comment: -s only blocks system sleep on AC power; on battery lid-close sleep is not prevented (macOS limitation). - Tests: cover dispose() (kills child, resets state, idempotent), stop()'s kill-throws catch, the stale-child error guard, the unsupported-platform latch, reason sanitization, and the ACP Session acquire/execute/release wrap. --- .../acp-integration/session/Session.test.ts | 69 +++++++++++++ packages/cli/src/config/settingsSchema.ts | 5 +- .../core/src/services/sleepInhibitor.test.ts | 97 +++++++++++++++++++ packages/core/src/services/sleepInhibitor.ts | 31 +++++- 4 files changed, 197 insertions(+), 5 deletions(-) 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/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 24ac3eaa455..81bbaac575a 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -531,7 +531,10 @@ const SETTINGS_SCHEMA = { type: 'boolean', label: 'Prevent System Sleep While Running', category: 'General', - requiresRestart: false, + // 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.', diff --git a/packages/core/src/services/sleepInhibitor.test.ts b/packages/core/src/services/sleepInhibitor.test.ts index 7674b77c523..dbb8f12665e 100644 --- a/packages/core/src/services/sleepInhibitor.test.ts +++ b/packages/core/src/services/sleepInhibitor.test.ts @@ -202,4 +202,101 @@ describe('SleepInhibitor', () => { 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 index 87cbf3738ba..7c7da3714f0 100644 --- a/packages/core/src/services/sleepInhibitor.ts +++ b/packages/core/src/services/sleepInhibitor.ts @@ -33,6 +33,24 @@ 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; @@ -101,6 +119,9 @@ export class SleepInhibitor { 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; } @@ -206,9 +227,11 @@ export class SleepInhibitor { ): { command: string; args: string[] } | undefined { switch (this.platform) { case 'darwin': - // -i prevents idle sleep, -s prevents system sleep (including - // lid-close on AC power). Both are needed to match the Linux - // systemd-inhibit semantics which blocks all sleep transitions. + // -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 { @@ -216,7 +239,7 @@ export class SleepInhibitor { args: [ '--what=sleep', '--who=Qwen Code', - `--why=${reason}`, + `--why=${sanitizeInhibitorReason(reason)}`, '--mode=block', 'sleep', 'infinity',