Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
46 changes: 39 additions & 7 deletions packages/cli/src/acp-integration/acp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
/* ACP defines a schema for a simple (experimental) JSON-RPC protocol that allows GUI applications to interact with agents. */

import { z } from 'zod';
import { createDebugLogger } from '@qwen-code/qwen-code-core';
import * as schema from './schema.js';
import { ACP_ERROR_CODES } from './errorCodes.js';
export * from './schema.js';

import type { WritableStream, ReadableStream } from 'node:stream/web';

const debugLogger = createDebugLogger('ACP_PROTOCOL');
export class AgentSideConnection implements Client {
#connection: Connection;

Expand Down Expand Up @@ -220,8 +222,16 @@ class Connection {
const trimmedLine = line.trim();

if (trimmedLine) {
const message = JSON.parse(trimmedLine);
this.#processMessage(message);
try {
const message = JSON.parse(trimmedLine);
this.#processMessage(message);
} catch (error) {
debugLogger.error('ACP parse error for inbound message.', {
code: ACP_ERROR_CODES.PARSE_ERROR,
line: trimmedLine,
error,
});
}
}
}
}
Expand Down Expand Up @@ -258,13 +268,23 @@ class Connection {
return { result: result ?? null };
} catch (error: unknown) {
if (error instanceof RequestError) {
debugLogger.debug('ACP handler returned request error.', {
method,
code: error.code,
message: error.message,
details: error.data?.details,
});
return error.toResult();
}

if (error instanceof z.ZodError) {
return RequestError.invalidParams(
JSON.stringify(error.format(), undefined, 2),
).toResult();
const formattedDetails = JSON.stringify(error.format(), undefined, 2);
debugLogger.debug('ACP handler validation error.', {
method,
code: ACP_ERROR_CODES.INVALID_PARAMS,
details: formattedDetails,
});
return RequestError.invalidParams(formattedDetails).toResult();
}

let errorName;
Expand All @@ -286,6 +306,11 @@ class Connection {
return RequestError.authRequired(details).toResult();
}

debugLogger.error(
'ACP handler failed with internal error.',
{ method, errorName, details },
error,
);
return RequestError.internalError(details).toResult();
}
}
Expand All @@ -296,7 +321,14 @@ class Connection {
if ('result' in response) {
pendingResponse.resolve(response.result);
} else if ('error' in response) {
pendingResponse.reject(response.error);
const { error } = response;
debugLogger.warn('ACP response error received.', {
id: response.id,
code: error.code,
message: error.message,
data: error.data,
});
pendingResponse.reject(error);
}
this.#pendingResponses.delete(response.id);
}
Expand Down Expand Up @@ -328,7 +360,7 @@ class Connection {
})
.catch((error) => {
// Continue processing writes on error
console.error('ACP write error:', error);
debugLogger.error('ACP write error:', error);
});
return this.#writeQueue;
}
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/acp-integration/acpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
APPROVAL_MODES,
AuthType,
clearCachedCredentialFile,
createDebugLogger,
QwenOAuth2Event,
qwenOAuth2Events,
MCPServerConfig,
Expand All @@ -33,6 +34,8 @@ import { loadCliConfig } from '../config/config.js';
// Import the modular Session class
import { Session } from './session/Session.js';

const debugLogger = createDebugLogger('ACP_AGENT');

export async function runAcpAgent(
config: Config,
settings: LoadedSettings,
Expand Down Expand Up @@ -301,7 +304,7 @@ class GeminiAgent {
// Use true for the second argument to ensure only cached credentials are used
await config.refreshAuth(selectedType, true);
} catch (e) {
console.error(`Authentication failed: ${e}`);
debugLogger.error(`Authentication failed: ${e}`);
throw acp.RequestError.authRequired(
'Authentication failed: ' + (e as Error).message,
);
Expand Down
5 changes: 0 additions & 5 deletions packages/cli/src/acp-integration/session/Session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,6 @@ describe('Session', () => {
});

it('swallows errors and does not throw', async () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => undefined);
getAvailableCommandsSpy.mockRejectedValueOnce(
new Error('Command discovery failed'),
);
Expand All @@ -187,8 +184,6 @@ describe('Session', () => {
session.sendAvailableCommandsUpdate(),
).resolves.toBeUndefined();
expect(mockClient.sessionUpdate).not.toHaveBeenCalled();
expect(consoleErrorSpy).toHaveBeenCalled();
consoleErrorSpy.mockRestore();
});
});

Expand Down
15 changes: 8 additions & 7 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
DiscoveredMCPTool,
StreamEventType,
ToolConfirmationOutcome,
createDebugLogger,
logToolCall,
logUserPrompt,
getErrorStatus,
Expand Down Expand Up @@ -67,6 +68,8 @@ import { PlanEmitter } from './emitters/PlanEmitter.js';
import { MessageEmitter } from './emitters/MessageEmitter.js';
import { SubAgentTracker } from './SubAgentTracker.js';

const debugLogger = createDebugLogger('ACP_SESSION');

/**
* Session represents an active conversation session with the AI model.
* It uses modular components for consistent event emission:
Expand Down Expand Up @@ -318,7 +321,7 @@ export class Session implements SessionContext {
await this.sendUpdate(update);
} catch (error) {
// Log error but don't fail session creation
console.error('Error sending available commands update:', error);
debugLogger.error('Error sending available commands update:', error);
}
}

Expand Down Expand Up @@ -857,7 +860,7 @@ export class Session implements SessionContext {
const reason = respectGitIgnore
? 'git-ignored and will be skipped'
: 'ignored by custom patterns';
console.warn(`Path ${pathName} is ${reason}.`);
debugLogger.warn(`Path ${pathName} is ${reason}.`);
continue;
}
let currentPathSpec = pathName;
Expand Down Expand Up @@ -924,7 +927,7 @@ export class Session implements SessionContext {
);
}
} catch (globError) {
console.error(
debugLogger.error(
`Error during glob search for ${pathName}: ${getErrorMessage(globError)}`,
);
}
Expand All @@ -934,7 +937,7 @@ export class Session implements SessionContext {
);
}
} else {
console.error(
debugLogger.error(
`Error stating path ${pathName}. Path ${pathName} will be skipped.`,
);
}
Expand Down Expand Up @@ -1041,9 +1044,7 @@ export class Session implements SessionContext {
}

debug(msg: string): void {
if (this.config.getDebugMode()) {
console.warn(msg);
}
debugLogger.debug(msg);
}
}

Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/acp-integration/session/SubAgentTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ import type {
import {
SubAgentEventType,
ToolConfirmationOutcome,
createDebugLogger,
} from '@qwen-code/qwen-code-core';
import { z } from 'zod';
import type { SessionContext } from './types.js';
import { ToolCallEmitter } from './emitters/ToolCallEmitter.js';
import { MessageEmitter } from './emitters/MessageEmitter.js';
import type * as acp from '../acp.js';

const debugLogger = createDebugLogger('ACP_SUBAGENT_TRACKER');

/**
* Permission option kind type matching ACP schema.
*/
Expand Down Expand Up @@ -151,7 +154,7 @@ export class SubAgentTracker {
invocation = tool.build(event.args);
} catch (e) {
// If building fails, continue with defaults
console.warn(`Failed to build subagent tool ${event.name}:`, e);
debugLogger.warn(`Failed to build subagent tool ${event.name}:`, e);
}
}

Expand Down Expand Up @@ -268,7 +271,7 @@ export class SubAgentTracker {
await event.respond(outcome);
} catch (error) {
// If permission request fails, cancel the tool call
console.error(
debugLogger.error(
`Permission request failed for subagent tool ${event.name}:`,
error,
);
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/commands/extensions/consent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { ConfirmationRequest } from '../../ui/types.js';
import chalk from 'chalk';
import prompts from 'prompts';
import { t } from '../../i18n/index.js';
import { writeStdoutLine } from '../../utils/stdioHelpers.js';

/**
* Requests consent from the user to perform an action, by reading a Y/n
Expand All @@ -22,7 +23,7 @@ import { t } from '../../i18n/index.js';
export async function requestConsentNonInteractive(
consentDescription: string,
): Promise<boolean> {
console.info(consentDescription);
writeStdoutLine(consentDescription);
const result = await promptForConsentNonInteractive(
t('Do you want to continue? [Y/n]: '),
);
Expand Down
56 changes: 36 additions & 20 deletions packages/cli/src/commands/extensions/disable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,14 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {
describe,
it,
expect,
vi,
beforeEach,
type MockInstance,
} from 'vitest';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { disableCommand, handleDisable } from './disable.js';
import yargs from 'yargs';
import { SettingScope } from '../../config/settings.js';

const mockDisableExtension = vi.hoisted(() => vi.fn());
const mockWriteStdoutLine = vi.hoisted(() => vi.fn());
const mockWriteStderrLine = vi.hoisted(() => vi.fn());

vi.mock('./utils.js', () => ({
getExtensionManager: vi.fn().mockResolvedValue({
Expand All @@ -28,6 +23,12 @@ vi.mock('../../utils/errors.js', () => ({
getErrorMessage: vi.fn((error: Error) => error.message),
}));

vi.mock('../../utils/stdioHelpers.js', () => ({
writeStdoutLine: mockWriteStdoutLine,
writeStderrLine: mockWriteStderrLine,
clearScreen: vi.fn(),
}));

describe('extensions disable command', () => {
it('should fail if no name is provided', () => {
const validationParser = yargs([])
Expand Down Expand Up @@ -59,20 +60,15 @@ describe('extensions disable command', () => {
});

describe('handleDisable', () => {
let consoleLogSpy: MockInstance;
let consoleErrorSpy: MockInstance;
let processExitSpy: MockInstance;

beforeEach(() => {
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation(() => undefined as never);
vi.clearAllMocks();
});

it('should disable an extension with user scope', async () => {
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation(() => undefined as never);

await handleDisable({
name: 'test-extension',
scope: 'user',
Expand All @@ -82,12 +78,18 @@ describe('handleDisable', () => {
'test-extension',
SettingScope.User,
);
expect(consoleLogSpy).toHaveBeenCalledWith(
expect(mockWriteStdoutLine).toHaveBeenCalledWith(
'Extension "test-extension" successfully disabled for scope "user".',
);

processExitSpy.mockRestore();
});

it('should disable an extension with workspace scope', async () => {
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation(() => undefined as never);

await handleDisable({
name: 'test-extension',
scope: 'workspace',
Expand All @@ -97,12 +99,18 @@ describe('handleDisable', () => {
'test-extension',
SettingScope.Workspace,
);
expect(consoleLogSpy).toHaveBeenCalledWith(
expect(mockWriteStdoutLine).toHaveBeenCalledWith(
'Extension "test-extension" successfully disabled for scope "workspace".',
);

processExitSpy.mockRestore();
});

it('should default to user scope when no scope is provided', async () => {
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation(() => undefined as never);

await handleDisable({
name: 'test-extension',
});
Expand All @@ -111,9 +119,15 @@ describe('handleDisable', () => {
'test-extension',
SettingScope.User,
);

processExitSpy.mockRestore();
});

it('should handle errors and exit with code 1', async () => {
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation(() => undefined as never);

mockDisableExtension.mockImplementationOnce(() => {
throw new Error('Disable failed');
});
Expand All @@ -123,7 +137,9 @@ describe('handleDisable', () => {
scope: 'user',
});

expect(consoleErrorSpy).toHaveBeenCalledWith('Disable failed');
expect(mockWriteStderrLine).toHaveBeenCalledWith('Disable failed');
expect(processExitSpy).toHaveBeenCalledWith(1);

processExitSpy.mockRestore();
});
});
Loading
Loading