Skip to content
Merged
5 changes: 4 additions & 1 deletion packages/cli/src/nonInteractiveCli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ import type { LoadedSettings } from './config/settings.js';
import { CommandKind, type ExecutionMode } from './ui/commands/types.js';
import { filterCommandsForMode } from './services/commandUtils.js';
import { _resetCleanupFunctionsForTest } from './utils/cleanup.js';
import { AlreadyReportedError, _resetExitLatchForTest } from './utils/errors.js';
import {
AlreadyReportedError,
_resetExitLatchForTest,
} from './utils/errors.js';

// Mock core modules
vi.mock('./ui/hooks/atCommandProcessor.js');
Expand Down
55 changes: 55 additions & 0 deletions packages/cli/src/ui/commands/clearCommand.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,5 +470,60 @@ describe('clearCommand', () => {
expect(mockStartNewSession).not.toHaveBeenCalled();
expect(mockResetChat).not.toHaveBeenCalled();
});

it('blocks session clearing while a background shell is still running', async () => {
if (!clearCommand.action)
throw new Error('clearCommand must have an action.');

const blockedContext = createMockCommandContext({
executionMode: 'non_interactive',
services: {
config: {
getBackgroundTaskRegistry: vi.fn().mockReturnValue({
hasUnfinalizedTasks: vi.fn().mockReturnValue(false),
reset: vi.fn(),
}),
getBackgroundShellRegistry: vi.fn().mockReturnValue({
getAll: vi.fn().mockReturnValue([
{
shellId: 'shell_123',
status: 'running',
},
]),
reset: vi.fn(),
}),
getMonitorRegistry: vi.fn().mockReturnValue({
getRunning: vi.fn().mockReturnValue([]),
reset: vi.fn(),
}),
getHookSystem: mockGetHookSystem,
startNewSession: mockStartNewSession,
getGeminiClient: vi.fn().mockReturnValue({
resetChat: mockResetChat,
} as unknown as GeminiClient),
getModel: vi.fn().mockReturnValue('test-model'),
getApprovalMode: vi.fn().mockReturnValue('default'),
getToolRegistry: vi.fn().mockReturnValue({
getAllTools: vi.fn().mockReturnValue([]),
}),
getDebugLogger: vi.fn().mockReturnValue({ warn: vi.fn() }),
},
},
session: {
startNewSession: vi.fn(),
},
});

const result = await clearCommand.action(blockedContext, '');

expect(result).toEqual({
type: 'message',
messageType: 'error',
content:
"Stop the current session's running background tasks before starting a new session.",
});
expect(mockStartNewSession).not.toHaveBeenCalled();
expect(mockResetChat).not.toHaveBeenCalled();
});
});
});
22 changes: 4 additions & 18 deletions packages/cli/src/ui/commands/clearCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,12 @@ import {
SessionEndReason,
SessionStartSource,
ToolNames,
type Config,
type PermissionMode,
} from '@qwen-code/qwen-code-core';

function hasBlockingBackgroundWork(config: Config): boolean {
return (
config.getBackgroundTaskRegistry().hasUnfinalizedTasks() ||
config.getMonitorRegistry().getRunning().length > 0 ||
config
.getBackgroundShellRegistry()
.getAll()
.some((entry) => entry.status === 'running')
);
}

function resetBackgroundStateForSessionSwitch(config: Config): void {
config.getBackgroundTaskRegistry().reset();
config.getMonitorRegistry().reset();
config.getBackgroundShellRegistry().reset();
}
import {
hasBlockingBackgroundWork,
resetBackgroundStateForSessionSwitch,
} from '../utils/backgroundWorkUtils.js';

export const clearCommand: SlashCommand = {
name: 'clear',
Expand Down
21 changes: 4 additions & 17 deletions packages/cli/src/ui/hooks/useResumeCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import {
import { buildResumedHistoryItems } from '../utils/resumeHistoryUtils.js';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import { MessageType, type HistoryItem } from '../types.js';
import {
hasBlockingBackgroundWork,
resetBackgroundStateForSessionSwitch,
} from '../utils/backgroundWorkUtils.js';

export interface UseResumeCommandOptions {
config: Config | null;
Expand Down Expand Up @@ -45,23 +49,6 @@ export interface UseResumeCommandResult {
const BACKGROUND_WORK_SWITCH_BLOCKED_MESSAGE =
"Stop the current session's running background tasks before resuming another session.";

function hasBlockingBackgroundWork(config: Config): boolean {
return (
config.getBackgroundTaskRegistry().hasUnfinalizedTasks() ||
config.getMonitorRegistry().getRunning().length > 0 ||
config
.getBackgroundShellRegistry()
.getAll()
.some((entry) => entry.status === 'running')
);
}

function resetBackgroundStateForSessionSwitch(config: Config): void {
config.getBackgroundTaskRegistry().reset();
config.getMonitorRegistry().reset();
config.getBackgroundShellRegistry().reset();
}

export function useResumeCommand(
options?: UseResumeCommandOptions,
): UseResumeCommandResult {
Expand Down
24 changes: 24 additions & 0 deletions packages/cli/src/ui/utils/backgroundWorkUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @license
* Copyright 2025 Qwen Code
* SPDX-License-Identifier: Apache-2.0
*/

import type { Config } from '@qwen-code/qwen-code-core';

export function hasBlockingBackgroundWork(config: Config): boolean {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Suggestion] 提取到共享模块的 hasBlockingBackgroundWork 缺少 JSDoc。建议添加说明其检查顺序和阻塞语义:

Suggested change
export function hasBlockingBackgroundWork(config: Config): boolean {
/**
* Returns true when any background work is still in progress that would
* conflict with starting or resuming a session.
*
* Checks in short-circuit order: unfinalized tasks, running monitors,
* then running background shells.
*/
export function hasBlockingBackgroundWork(config: Config): boolean {

— deepseek-v4-pro via Qwen Code /review

return (
config.getBackgroundTaskRegistry().hasUnfinalizedTasks() ||
config.getMonitorRegistry().getRunning().length > 0 ||
config
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
.getBackgroundShellRegistry()
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
.getAll()
.some((entry) => entry.status === 'running')
);
}
Comment thread
doudouOUC marked this conversation as resolved.
Resolved

export function resetBackgroundStateForSessionSwitch(config: Config): void {
config.getBackgroundTaskRegistry().reset();
config.getMonitorRegistry().reset();
config.getBackgroundShellRegistry().reset();
}
3 changes: 2 additions & 1 deletion packages/cli/src/utils/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,8 @@ describe('errors', () => {
{
error: {
type: 'AlreadyReportedError',
message: '[API Error: 402 Model X is not available for billing.]',
message:
'[API Error: 402 Model X is not available for billing.]',
code: 42,
},
},
Expand Down
20 changes: 7 additions & 13 deletions packages/core/src/permissions/permission-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
matchesRule,
resolveToolName,
splitCompoundCommand,
SHELL_TOOL_NAMES,
} from './rule-parser.js';
import type { PathMatchContext } from './rule-parser.js';
import { extractShellOperations } from './shell-semantics.js';
Expand All @@ -32,13 +33,6 @@ import type {

const debugLogger = createDebugLogger('PERMISSIONS');

/**
* Tools that spawn shell commands and share the same permission evaluation
* semantics: compound-command splitting, AST read-only analysis, and
* virtual file/network operation matching.
*/
const SHELL_LIKE_TOOLS = new Set(['run_shell_command', 'monitor']);

/**
* Numeric priority for each PermissionDecision.
* Higher number = more restrictive. Used to combine decisions by taking
Expand Down Expand Up @@ -189,7 +183,7 @@ export class PermissionManager {
// a concrete permission (deny/ask/allow) based on the command's readonly status.
if (
decision === 'default' &&
SHELL_LIKE_TOOLS.has(toolName) &&
SHELL_TOOL_NAMES.has(toolName) &&
command !== undefined
) {
return this.resolveDefaultPermission(command);
Expand Down Expand Up @@ -267,7 +261,7 @@ export class PermissionManager {
// must never downgrade an explicit 'allow' decision from a Bash rule.
// Example: `git status` has no file ops; an allow rule for `Bash(git *)`
// should return 'allow', not be downgraded to 'default'.
if (SHELL_LIKE_TOOLS.has(toolName) && command !== undefined) {
if (SHELL_TOOL_NAMES.has(toolName) && command !== undefined) {
const cwd = pathCtx?.cwd ?? process.cwd();
const virtualDecision = this.evaluateShellVirtualOps(
extractShellOperations(command, cwd),
Expand Down Expand Up @@ -584,7 +578,7 @@ export class PermissionManager {
ctx = this.normalizePermissionContext(ctx);
const { toolName, command, cwd, filePath, domain, specifier } = ctx;

if (SHELL_LIKE_TOOLS.has(ctx.toolName) && command !== undefined) {
if (SHELL_TOOL_NAMES.has(ctx.toolName) && command !== undefined) {
const subCommands = splitCompoundCommand(command);
if (subCommands.length > 1) {
return subCommands.some((subCmd) =>
Expand Down Expand Up @@ -625,7 +619,7 @@ export class PermissionManager {
// extracted from the command has a relevant rule. This ensures the PM is
// consulted (and the confirmation dialog shown) when Read/Edit/etc. rules
// would match equivalent shell commands.
if (SHELL_LIKE_TOOLS.has(ctx.toolName) && ctx.command !== undefined) {
if (SHELL_TOOL_NAMES.has(ctx.toolName) && ctx.command !== undefined) {
const cwd = pathCtx?.cwd ?? process.cwd();
const ops = extractShellOperations(ctx.command, cwd);
if (
Expand Down Expand Up @@ -661,7 +655,7 @@ export class PermissionManager {
ctx = this.normalizePermissionContext(ctx);
const { toolName, command, cwd, filePath, domain, specifier } = ctx;

if (SHELL_LIKE_TOOLS.has(ctx.toolName) && command !== undefined) {
if (SHELL_TOOL_NAMES.has(ctx.toolName) && command !== undefined) {
const subCommands = splitCompoundCommand(command);
if (subCommands.length > 1) {
return subCommands.some((subCmd) =>
Expand Down Expand Up @@ -693,7 +687,7 @@ export class PermissionManager {
return true;
}

if (SHELL_LIKE_TOOLS.has(ctx.toolName) && ctx.command !== undefined) {
if (SHELL_TOOL_NAMES.has(ctx.toolName) && ctx.command !== undefined) {
const cwd = pathCtx?.cwd ?? process.cwd();
const ops = extractShellOperations(ctx.command, cwd);
return ops.some((op) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/permissions/rule-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export const TOOL_NAME_ALIASES: Readonly<Record<string, string>> = {
/**
* Shell tool canonical names. These use command-style rule specifiers.
*/
const SHELL_TOOL_NAMES = new Set(['run_shell_command', 'monitor']);
export const SHELL_TOOL_NAMES = new Set(['run_shell_command', 'monitor']);
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
Comment thread
doudouOUC marked this conversation as resolved.
Resolved

Comment thread
doudouOUC marked this conversation as resolved.
Resolved
/**
* File-reading tools — "Read" rules apply to all of these (best-effort).
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/services/monitorRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,21 @@ describe('MonitorRegistry', () => {
).not.toThrow();
});

it('includes droppedLines count in terminal notification text', () => {
const callback = vi.fn();
registry.setNotificationCallback(callback);
const entry = createEntry();
registry.register(entry);

// Simulate throttle drops (droppedLines is incremented by Monitor tool)
entry.droppedLines = 5;
registry.complete('mon-1', 0);

const [displayText, modelText] = callback.mock.calls[0] as [string, string];
expect(displayText).toContain('5 lines dropped due to throttling');
expect(modelText).toContain('5 lines dropped due to throttling');
});

describe('setStatusChangeCallback', () => {
it('fires once on register (nothing → running)', () => {
const cb = vi.fn();
Expand Down
94 changes: 94 additions & 0 deletions packages/core/src/tools/monitor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,26 @@ describe('MonitorTool', () => {
'Monitor(tail -f /tmp/app.log)',
]);
});

it('keeps sub-command in confirmation scope when AST read-only check fails', async () => {
mockIsShellCommandReadOnlyAST.mockRejectedValueOnce(
new Error('AST parse failure'),
);

const invocation = createInvocation({
command: 'tail -f /tmp/app.log',
});

const details = (await invocation.getConfirmationDetails(
new AbortController().signal,
)) as ToolCallConfirmationDetails & {
permissionRules?: string[];
};

// Sub-command should still be in confirmation scope (not dropped)
expect(details.permissionRules).toBeDefined();
expect(details.permissionRules!.length).toBeGreaterThan(0);
});
});

describe('getDefaultPermission', () => {
Expand Down Expand Up @@ -983,6 +1003,30 @@ describe('MonitorTool', () => {
expect(all[0].status).toBe('failed');
});

it('settles as completed when exit and close both report null code and null signal', async () => {
const callback = vi.fn();
monitorRegistry.setNotificationCallback(callback);

const invocation = createInvocation({
command: 'some-cmd',
});

await invocation.execute(new AbortController().signal);
mockChild._emitExit(null, null);
mockChild._emitClose(null, null);

const all = monitorRegistry.getAll();
expect(all[0].status).toBe('completed');
// Terminal notification should not include a result tag (exitCode is null)
const terminalCall = callback.mock.calls.find(
(args) =>
typeof args[1] === 'string' &&
(args[1] as string).includes('<status>completed</status>'),
);
expect(terminalCall).toBeDefined();
expect(terminalCall![1]).not.toContain('<result>');
});

it('does not kill monitor on turn signal abort', async () => {
const turnAc = new AbortController();
const invocation = createInvocation({
Expand Down Expand Up @@ -1227,6 +1271,56 @@ describe('MonitorTool', () => {
vi.useRealTimers();
}
});

it('recovers token bucket when clock moves backwards (suspend/resume)', async () => {
const realDateNow = Date.now;
let mockTime = 0;
Date.now = () => mockTime;
try {
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
mockTime = 0;
const callback = vi.fn();
monitorRegistry.setNotificationCallback(callback);

const invocation = createInvocation({ command: 'noisy-cmd' });
await invocation.execute(new AbortController().signal);

// Burn the entire burst at t=0.
mockChild.stdout.emit('data', Buffer.from('l1\nl2\nl3\nl4\nl5\n'));
expect(callback).toHaveBeenCalledTimes(5);

// Advance to t=5000, drain 5 refilled tokens, then confirm bucket
// is empty by emitting a line that gets dropped.
mockTime = 5000;
mockChild.stdout.emit('data', Buffer.from('l6\nl7\nl8\nl9\nl10\n'));
expect(callback).toHaveBeenCalledTimes(10);
mockChild.stdout.emit('data', Buffer.from('l11\n'));
expect(callback).toHaveBeenCalledTimes(10); // l11 dropped

// Simulate clock going backwards (suspend/resume, NTP rollback).
// At this point lastRefill=5000. Setting time to 2000 makes
// elapsed = 2000-5000 = -3000. Without the guard, the bucket
// stays starved. With the guard, lastRefill resets to 2000.
mockTime = 2000;

// Emit while clock is in the past — guard has just reset
// lastRefill to 2000, so elapsed = 0, no refill, bucket still 0.
// l12a is dropped (confirming bucket is empty after the reset).
mockChild.stdout.emit('data', Buffer.from('l12a\n'));
expect(callback).toHaveBeenCalledTimes(10);

// Advance 1s past the reset point — one token refills.
mockTime = 3000;
mockChild.stdout.emit('data', Buffer.from('l12b\n'));
expect(callback).toHaveBeenCalledTimes(11);

Comment thread
doudouOUC marked this conversation as resolved.
Resolved
// This final assertion is the regression check: without the guard,
// lastRefill would still be 5000, elapsed = 3000-5000 = -2000,
// and l12b would be dropped (callback still 10).
} finally {
Date.now = realDateNow;
monitorRegistry.abortAll({ notify: false });
}
});
});
});

Expand Down
Loading
Loading