Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions packages/cli/src/acp-integration/session/Session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
12 changes: 11 additions & 1 deletion packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -2296,7 +2297,16 @@ export class Session implements SessionContext {
}
}

const toolResult: ToolResult = await invocation.execute(abortSignal);
const sleepInhibitorHandle = acquireSleepInhibitor(
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
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());
Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/commands/mcp/add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,13 @@ vi.mock('fs/promises', async (importOriginal) => {
};
});

vi.mock('os', () => {
vi.mock('os', async (importOriginal) => {
const actual = await importOriginal<typeof import('os')>();
const homedir = vi.fn(() => '/home/user');
return {
...actual,
default: {
...actual,
homedir,
},
homedir,
Expand Down Expand Up @@ -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}`),
Expand Down
29 changes: 26 additions & 3 deletions packages/cli/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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'],
Expand All @@ -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',
});
});
Expand All @@ -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',
});
});
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions packages/cli/src/config/settingsSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
15 changes: 10 additions & 5 deletions packages/cli/src/utils/systemInfo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import('node:os')>();
return {
...actual,
default: {
...actual,
release: vi.fn(),
},
};
});

vi.mock('./version.js', () => ({
getCliVersion: vi.fn(),
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions packages/core/src/core/coreToolScheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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),
}));
Expand Down Expand Up @@ -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);
Comment thread
DragonnZhang marked this conversation as resolved.
Resolved
});

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',
Expand Down
Loading
Loading