chore(vscode-ide-companion): revert some log util, will continue next time

This commit is contained in:
yiliang114
2025-12-11 23:57:21 +08:00
parent b34894c8ea
commit c20df192a8
10 changed files with 123 additions and 282 deletions

View File

@@ -8,11 +8,7 @@ import * as vscode from 'vscode';
import { IDEServer } from './ide-server.js'; import { IDEServer } from './ide-server.js';
import semver from 'semver'; import semver from 'semver';
import { DiffContentProvider, DiffManager } from './diff-manager.js'; import { DiffContentProvider, DiffManager } from './diff-manager.js';
import { import { createLogger } from './utils/logger.js';
createLogger,
getConsoleLogger,
initSharedConsoleLogger,
} from './utils/logger.js';
import { import {
detectIdeFromEnv, detectIdeFromEnv,
IDE_DEFINITIONS, IDE_DEFINITIONS,
@@ -109,8 +105,6 @@ async function checkForUpdates(
export async function activate(context: vscode.ExtensionContext) { export async function activate(context: vscode.ExtensionContext) {
logger = vscode.window.createOutputChannel('Qwen Code Companion'); logger = vscode.window.createOutputChannel('Qwen Code Companion');
initSharedConsoleLogger(context);
const consoleLog = getConsoleLogger();
log = createLogger(context, logger); log = createLogger(context, logger);
log('Extension activated'); log('Extension activated');
@@ -148,18 +142,18 @@ export async function activate(context: vscode.ExtensionContext) {
webviewPanel: vscode.WebviewPanel, webviewPanel: vscode.WebviewPanel,
state: unknown, state: unknown,
) { ) {
consoleLog( console.log(
'[Extension] Deserializing WebView panel with state:', '[Extension] Deserializing WebView panel with state:',
state, state,
); );
// Create a new provider for the restored panel // Create a new provider for the restored panel
const provider = createWebViewProvider(); const provider = createWebViewProvider();
consoleLog('[Extension] Provider created for deserialization'); console.log('[Extension] Provider created for deserialization');
// Restore state if available BEFORE restoring the panel // Restore state if available BEFORE restoring the panel
if (state && typeof state === 'object') { if (state && typeof state === 'object') {
consoleLog('[Extension] Restoring state:', state); console.log('[Extension] Restoring state:', state);
provider.restoreState( provider.restoreState(
state as { state as {
conversationId: string | null; conversationId: string | null;
@@ -167,11 +161,11 @@ export async function activate(context: vscode.ExtensionContext) {
}, },
); );
} else { } else {
consoleLog('[Extension] No state to restore or invalid state'); console.log('[Extension] No state to restore or invalid state');
} }
await provider.restorePanel(webviewPanel); await provider.restorePanel(webviewPanel);
consoleLog('[Extension] Panel restore completed'); console.log('[Extension] Panel restore completed');
log('WebView panel restored from serialization'); log('WebView panel restored from serialization');
}, },
@@ -212,6 +206,7 @@ export async function activate(context: vscode.ExtensionContext) {
} catch (err) { } catch (err) {
console.warn('[Extension] Auto-allow on diff.accept failed:', err); console.warn('[Extension] Auto-allow on diff.accept failed:', err);
} }
console.log('[Extension] Diff accepted');
}), }),
vscode.commands.registerCommand('qwen.diff.cancel', (uri?: vscode.Uri) => { vscode.commands.registerCommand('qwen.diff.cancel', (uri?: vscode.Uri) => {
const docUri = uri ?? vscode.window.activeTextEditor?.document.uri; const docUri = uri ?? vscode.window.activeTextEditor?.document.uri;
@@ -228,6 +223,7 @@ export async function activate(context: vscode.ExtensionContext) {
} catch (err) { } catch (err) {
console.warn('[Extension] Auto-reject on diff.cancel failed:', err); console.warn('[Extension] Auto-reject on diff.cancel failed:', err);
} }
console.log('[Extension] Diff cancelled');
})), })),
vscode.commands.registerCommand('qwen.diff.closeAll', async () => { vscode.commands.registerCommand('qwen.diff.closeAll', async () => {
try { try {

View File

@@ -31,6 +31,7 @@ export class AcpConnection {
private child: ChildProcess | null = null; private child: ChildProcess | null = null;
private pendingRequests = new Map<number, PendingRequest<unknown>>(); private pendingRequests = new Map<number, PendingRequest<unknown>>();
private nextRequestId = { value: 0 }; private nextRequestId = { value: 0 };
// Deduplicate concurrent authenticate calls (across retry paths) // Deduplicate concurrent authenticate calls (across retry paths)
private static authInFlight: Promise<AcpResponse> | null = null; private static authInFlight: Promise<AcpResponse> | null = null;
// Remember the working dir provided at connect() so later ACP calls // Remember the working dir provided at connect() so later ACP calls

View File

@@ -5,7 +5,6 @@
*/ */
import type * as vscode from 'vscode'; import type * as vscode from 'vscode';
import { createConsoleLogger, getConsoleLogger } from '../utils/logger.js';
interface AuthState { interface AuthState {
isAuthenticated: boolean; isAuthenticated: boolean;
@@ -22,7 +21,6 @@ export class AuthStateManager {
private static context: vscode.ExtensionContext | null = null; private static context: vscode.ExtensionContext | null = null;
private static readonly AUTH_STATE_KEY = 'qwen.authState'; private static readonly AUTH_STATE_KEY = 'qwen.authState';
private static readonly AUTH_CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours private static readonly AUTH_CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours
private static consoleLog: (...args: unknown[]) => void = getConsoleLogger();
// Deduplicate concurrent auth flows (e.g., multiple tabs prompting login) // Deduplicate concurrent auth flows (e.g., multiple tabs prompting login)
private static authFlowInFlight: Promise<unknown> | null = null; private static authFlowInFlight: Promise<unknown> | null = null;
private constructor() {} private constructor() {}
@@ -38,10 +36,6 @@ export class AuthStateManager {
// If a context is provided, update the static context // If a context is provided, update the static context
if (context) { if (context) {
AuthStateManager.context = context; AuthStateManager.context = context;
AuthStateManager.consoleLog = createConsoleLogger(
context,
'AuthStateManager',
);
} }
return AuthStateManager.instance; return AuthStateManager.instance;
@@ -76,19 +70,17 @@ export class AuthStateManager {
const state = await this.getAuthState(); const state = await this.getAuthState();
if (!state) { if (!state) {
AuthStateManager.consoleLog( console.log('[AuthStateManager] No cached auth state found');
'[AuthStateManager] No cached auth state found',
);
return false; return false;
} }
AuthStateManager.consoleLog('[AuthStateManager] Found cached auth state:', { console.log('[AuthStateManager] Found cached auth state:', {
workingDir: state.workingDir, workingDir: state.workingDir,
authMethod: state.authMethod, authMethod: state.authMethod,
timestamp: new Date(state.timestamp).toISOString(), timestamp: new Date(state.timestamp).toISOString(),
isAuthenticated: state.isAuthenticated, isAuthenticated: state.isAuthenticated,
}); });
AuthStateManager.consoleLog('[AuthStateManager] Checking against:', { console.log('[AuthStateManager] Checking against:', {
workingDir, workingDir,
authMethod, authMethod,
}); });
@@ -99,8 +91,8 @@ export class AuthStateManager {
now - state.timestamp > AuthStateManager.AUTH_CACHE_DURATION; now - state.timestamp > AuthStateManager.AUTH_CACHE_DURATION;
if (isExpired) { if (isExpired) {
AuthStateManager.consoleLog('[AuthStateManager] Cached auth expired'); console.log('[AuthStateManager] Cached auth expired');
AuthStateManager.consoleLog( console.log(
'[AuthStateManager] Cache age:', '[AuthStateManager] Cache age:',
Math.floor((now - state.timestamp) / 1000 / 60), Math.floor((now - state.timestamp) / 1000 / 60),
'minutes', 'minutes',
@@ -114,29 +106,15 @@ export class AuthStateManager {
state.workingDir === workingDir && state.authMethod === authMethod; state.workingDir === workingDir && state.authMethod === authMethod;
if (!isSameContext) { if (!isSameContext) {
AuthStateManager.consoleLog( console.log('[AuthStateManager] Working dir or auth method changed');
'[AuthStateManager] Working dir or auth method changed', console.log('[AuthStateManager] Cached workingDir:', state.workingDir);
); console.log('[AuthStateManager] Current workingDir:', workingDir);
AuthStateManager.consoleLog( console.log('[AuthStateManager] Cached authMethod:', state.authMethod);
'[AuthStateManager] Cached workingDir:', console.log('[AuthStateManager] Current authMethod:', authMethod);
state.workingDir,
);
AuthStateManager.consoleLog(
'[AuthStateManager] Current workingDir:',
workingDir,
);
AuthStateManager.consoleLog(
'[AuthStateManager] Cached authMethod:',
state.authMethod,
);
AuthStateManager.consoleLog(
'[AuthStateManager] Current authMethod:',
authMethod,
);
return false; return false;
} }
AuthStateManager.consoleLog('[AuthStateManager] Valid cached auth found'); console.log('[AuthStateManager] Valid cached auth found');
return state.isAuthenticated; return state.isAuthenticated;
} }
@@ -146,10 +124,7 @@ export class AuthStateManager {
*/ */
async debugAuthState(): Promise<void> { async debugAuthState(): Promise<void> {
const state = await this.getAuthState(); const state = await this.getAuthState();
AuthStateManager.consoleLog( console.log('[AuthStateManager] DEBUG - Current auth state:', state);
'[AuthStateManager] DEBUG - Current auth state:',
state,
);
if (state) { if (state) {
const now = Date.now(); const now = Date.now();
@@ -157,16 +132,9 @@ export class AuthStateManager {
const isExpired = const isExpired =
now - state.timestamp > AuthStateManager.AUTH_CACHE_DURATION; now - state.timestamp > AuthStateManager.AUTH_CACHE_DURATION;
AuthStateManager.consoleLog( console.log('[AuthStateManager] DEBUG - Auth state age:', age, 'minutes');
'[AuthStateManager] DEBUG - Auth state age:', console.log('[AuthStateManager] DEBUG - Auth state expired:', isExpired);
age, console.log(
'minutes',
);
AuthStateManager.consoleLog(
'[AuthStateManager] DEBUG - Auth state expired:',
isExpired,
);
AuthStateManager.consoleLog(
'[AuthStateManager] DEBUG - Auth state valid:', '[AuthStateManager] DEBUG - Auth state valid:',
state.isAuthenticated, state.isAuthenticated,
); );
@@ -191,7 +159,7 @@ export class AuthStateManager {
timestamp: Date.now(), timestamp: Date.now(),
}; };
AuthStateManager.consoleLog('[AuthStateManager] Saving auth state:', { console.log('[AuthStateManager] Saving auth state:', {
workingDir, workingDir,
authMethod, authMethod,
timestamp: new Date(state.timestamp).toISOString(), timestamp: new Date(state.timestamp).toISOString(),
@@ -201,14 +169,11 @@ export class AuthStateManager {
AuthStateManager.AUTH_STATE_KEY, AuthStateManager.AUTH_STATE_KEY,
state, state,
); );
AuthStateManager.consoleLog('[AuthStateManager] Auth state saved'); console.log('[AuthStateManager] Auth state saved');
// Verify the state was saved correctly // Verify the state was saved correctly
const savedState = await this.getAuthState(); const savedState = await this.getAuthState();
AuthStateManager.consoleLog( console.log('[AuthStateManager] Verified saved state:', savedState);
'[AuthStateManager] Verified saved state:',
savedState,
);
} }
/** /**
@@ -222,9 +187,9 @@ export class AuthStateManager {
); );
} }
AuthStateManager.consoleLog('[AuthStateManager] Clearing auth state'); console.log('[AuthStateManager] Clearing auth state');
const currentState = await this.getAuthState(); const currentState = await this.getAuthState();
AuthStateManager.consoleLog( console.log(
'[AuthStateManager] Current state before clearing:', '[AuthStateManager] Current state before clearing:',
currentState, currentState,
); );
@@ -233,14 +198,11 @@ export class AuthStateManager {
AuthStateManager.AUTH_STATE_KEY, AuthStateManager.AUTH_STATE_KEY,
undefined, undefined,
); );
AuthStateManager.consoleLog('[AuthStateManager] Auth state cleared'); console.log('[AuthStateManager] Auth state cleared');
// Verify the state was cleared // Verify the state was cleared
const newState = await this.getAuthState(); const newState = await this.getAuthState();
AuthStateManager.consoleLog( console.log('[AuthStateManager] State after clearing:', newState);
'[AuthStateManager] State after clearing:',
newState,
);
} }
/** /**
@@ -249,15 +211,17 @@ export class AuthStateManager {
private async getAuthState(): Promise<AuthState | undefined> { private async getAuthState(): Promise<AuthState | undefined> {
// Ensure we have a valid context // Ensure we have a valid context
if (!AuthStateManager.context) { if (!AuthStateManager.context) {
AuthStateManager.consoleLog( console.log(
'[AuthStateManager] No context available for getting auth state', '[AuthStateManager] No context available for getting auth state',
); );
return undefined; return undefined;
} }
return AuthStateManager.context.globalState.get<AuthState>( const a = AuthStateManager.context.globalState.get<AuthState>(
AuthStateManager.AUTH_STATE_KEY, AuthStateManager.AUTH_STATE_KEY,
); );
console.log('[AuthStateManager] Auth state:', a);
return a;
} }
/** /**

View File

@@ -23,7 +23,6 @@ import { QwenSessionUpdateHandler } from './qwenSessionUpdateHandler.js';
import { CliContextManager } from '../cli/cliContextManager.js'; import { CliContextManager } from '../cli/cliContextManager.js';
import { authMethod } from '../types/acpTypes.js'; import { authMethod } from '../types/acpTypes.js';
import { MIN_CLI_VERSION_FOR_SESSION_METHODS } from '../cli/cliVersionManager.js'; import { MIN_CLI_VERSION_FOR_SESSION_METHODS } from '../cli/cliVersionManager.js';
import { getConsoleLogger } from '../utils/logger.js';
export type { ChatMessage, PlanEntry, ToolCallUpdateData }; export type { ChatMessage, PlanEntry, ToolCallUpdateData };
@@ -51,10 +50,8 @@ export class QwenAgentManager {
// Callback storage // Callback storage
private callbacks: QwenAgentCallbacks = {}; private callbacks: QwenAgentCallbacks = {};
private consoleLog: (...args: unknown[]) => void;
constructor(consoleLogger = getConsoleLogger()) { constructor() {
this.consoleLog = consoleLogger;
this.connection = new AcpConnection(); this.connection = new AcpConnection();
this.sessionReader = new QwenSessionReader(); this.sessionReader = new QwenSessionReader();
this.sessionManager = new QwenSessionManager(); this.sessionManager = new QwenSessionManager();
@@ -81,7 +78,7 @@ export class QwenAgentManager {
).update; ).update;
const text = update?.content?.text || ''; const text = update?.content?.text || '';
if (update?.sessionUpdate === 'user_message_chunk' && text) { if (update?.sessionUpdate === 'user_message_chunk' && text) {
this.consoleLog( console.log(
'[QwenAgentManager] Rehydration: routing user message chunk', '[QwenAgentManager] Rehydration: routing user message chunk',
); );
this.callbacks.onMessage?.({ this.callbacks.onMessage?.({
@@ -92,7 +89,7 @@ export class QwenAgentManager {
return; return;
} }
if (update?.sessionUpdate === 'agent_message_chunk' && text) { if (update?.sessionUpdate === 'agent_message_chunk' && text) {
this.consoleLog( console.log(
'[QwenAgentManager] Rehydration: routing agent message chunk', '[QwenAgentManager] Rehydration: routing agent message chunk',
); );
this.callbacks.onMessage?.({ this.callbacks.onMessage?.({
@@ -103,7 +100,7 @@ export class QwenAgentManager {
return; return;
} }
// For other types during rehydration, fall through to normal handler // For other types during rehydration, fall through to normal handler
this.consoleLog( console.log(
'[QwenAgentManager] Rehydration: non-text update, forwarding to handler', '[QwenAgentManager] Rehydration: non-text update, forwarding to handler',
); );
} }
@@ -262,7 +259,7 @@ export class QwenAgentManager {
* @returns Session list * @returns Session list
*/ */
async getSessionList(): Promise<Array<Record<string, unknown>>> { async getSessionList(): Promise<Array<Record<string, unknown>>> {
this.consoleLog( console.log(
'[QwenAgentManager] Getting session list with version-aware strategy', '[QwenAgentManager] Getting session list with version-aware strategy',
); );
@@ -270,7 +267,7 @@ export class QwenAgentManager {
const cliContextManager = CliContextManager.getInstance(); const cliContextManager = CliContextManager.getInstance();
const supportsSessionList = cliContextManager.supportsSessionList(); const supportsSessionList = cliContextManager.supportsSessionList();
this.consoleLog( console.log(
'[QwenAgentManager] CLI supports session/list:', '[QwenAgentManager] CLI supports session/list:',
supportsSessionList, supportsSessionList,
); );
@@ -278,14 +275,11 @@ export class QwenAgentManager {
// Try ACP method first if supported // Try ACP method first if supported
if (supportsSessionList) { if (supportsSessionList) {
try { try {
this.consoleLog( console.log(
'[QwenAgentManager] Attempting to get session list via ACP method', '[QwenAgentManager] Attempting to get session list via ACP method',
); );
const response = await this.connection.listSessions(); const response = await this.connection.listSessions();
this.consoleLog( console.log('[QwenAgentManager] ACP session list response:', response);
'[QwenAgentManager] ACP session list response:',
response,
);
// sendRequest resolves with the JSON-RPC "result" directly // sendRequest resolves with the JSON-RPC "result" directly
// Newer CLI returns an object: { items: [...], nextCursor?, hasMore } // Newer CLI returns an object: { items: [...], nextCursor?, hasMore }
@@ -303,7 +297,7 @@ export class QwenAgentManager {
: []; : [];
} }
this.consoleLog( console.log(
'[QwenAgentManager] Sessions retrieved via ACP:', '[QwenAgentManager] Sessions retrieved via ACP:',
res, res,
items.length, items.length,
@@ -322,7 +316,7 @@ export class QwenAgentManager {
cwd: item.cwd, cwd: item.cwd,
})); }));
this.consoleLog( console.log(
'[QwenAgentManager] Sessions retrieved via ACP:', '[QwenAgentManager] Sessions retrieved via ACP:',
sessions.length, sessions.length,
); );
@@ -338,11 +332,9 @@ export class QwenAgentManager {
// Always fall back to file system method // Always fall back to file system method
try { try {
this.consoleLog( console.log('[QwenAgentManager] Getting session list from file system');
'[QwenAgentManager] Getting session list from file system',
);
const sessions = await this.sessionReader.getAllSessions(undefined, true); const sessions = await this.sessionReader.getAllSessions(undefined, true);
this.consoleLog( console.log(
'[QwenAgentManager] Session list from file system (all projects):', '[QwenAgentManager] Session list from file system (all projects):',
sessions.length, sessions.length,
); );
@@ -360,7 +352,7 @@ export class QwenAgentManager {
}), }),
); );
this.consoleLog( console.log(
'[QwenAgentManager] Sessions retrieved from file system:', '[QwenAgentManager] Sessions retrieved from file system:',
result.length, result.length,
); );
@@ -500,7 +492,7 @@ export class QwenAgentManager {
const item = list.find( const item = list.find(
(s) => s.sessionId === sessionId || s.id === sessionId, (s) => s.sessionId === sessionId || s.id === sessionId,
); );
this.consoleLog( console.log(
'[QwenAgentManager] Session list item for filePath lookup:', '[QwenAgentManager] Session list item for filePath lookup:',
item, item,
); );
@@ -571,7 +563,7 @@ export class QwenAgentManager {
} }
} }
// Simple linear reconstruction: filter user/assistant and sort by timestamp // Simple linear reconstruction: filter user/assistant and sort by timestamp
this.consoleLog( console.log(
'[QwenAgentManager] JSONL records read:', '[QwenAgentManager] JSONL records read:',
records.length, records.length,
filePath, filePath,
@@ -728,7 +720,7 @@ export class QwenAgentManager {
// Handle other types if needed // Handle other types if needed
} }
this.consoleLog( console.log(
'[QwenAgentManager] JSONL messages reconstructed:', '[QwenAgentManager] JSONL messages reconstructed:',
msgs.length, msgs.length,
); );
@@ -866,7 +858,7 @@ export class QwenAgentManager {
tag: string, tag: string,
): Promise<{ success: boolean; message?: string }> { ): Promise<{ success: boolean; message?: string }> {
try { try {
this.consoleLog( console.log(
'[QwenAgentManager] Saving session via /chat save command:', '[QwenAgentManager] Saving session via /chat save command:',
sessionId, sessionId,
'with tag:', 'with tag:',
@@ -877,9 +869,7 @@ export class QwenAgentManager {
// The CLI will handle this as a special command // The CLI will handle this as a special command
await this.connection.sendPrompt(`/chat save "${tag}"`); await this.connection.sendPrompt(`/chat save "${tag}"`);
this.consoleLog( console.log('[QwenAgentManager] /chat save command sent successfully');
'[QwenAgentManager] /chat save command sent successfully',
);
return { return {
success: true, success: true,
message: `Session saved with tag: ${tag}`, message: `Session saved with tag: ${tag}`,
@@ -926,14 +916,14 @@ export class QwenAgentManager {
conversationId: string, conversationId: string,
): Promise<{ success: boolean; tag?: string; message?: string }> { ): Promise<{ success: boolean; tag?: string; message?: string }> {
try { try {
this.consoleLog('[QwenAgentManager] ===== CHECKPOINT SAVE START ====='); console.log('[QwenAgentManager] ===== CHECKPOINT SAVE START =====');
this.consoleLog('[QwenAgentManager] Conversation ID:', conversationId); console.log('[QwenAgentManager] Conversation ID:', conversationId);
this.consoleLog('[QwenAgentManager] Message count:', messages.length); console.log('[QwenAgentManager] Message count:', messages.length);
this.consoleLog( console.log(
'[QwenAgentManager] Current working dir:', '[QwenAgentManager] Current working dir:',
this.currentWorkingDir, this.currentWorkingDir,
); );
this.consoleLog( console.log(
'[QwenAgentManager] Current session ID (from CLI):', '[QwenAgentManager] Current session ID (from CLI):',
this.currentSessionId, this.currentSessionId,
); );
@@ -1010,11 +1000,11 @@ export class QwenAgentManager {
try { try {
// Route upcoming session/update messages as discrete messages for replay // Route upcoming session/update messages as discrete messages for replay
this.rehydratingSessionId = sessionId; this.rehydratingSessionId = sessionId;
this.consoleLog( console.log(
'[QwenAgentManager] Rehydration start for session:', '[QwenAgentManager] Rehydration start for session:',
sessionId, sessionId,
); );
this.consoleLog( console.log(
'[QwenAgentManager] Attempting session/load via ACP for session:', '[QwenAgentManager] Attempting session/load via ACP for session:',
sessionId, sessionId,
); );
@@ -1022,7 +1012,7 @@ export class QwenAgentManager {
sessionId, sessionId,
cwdOverride, cwdOverride,
); );
this.consoleLog( console.log(
'[QwenAgentManager] Session load succeeded. Response:', '[QwenAgentManager] Session load succeeded. Response:',
JSON.stringify(response).substring(0, 200), JSON.stringify(response).substring(0, 200),
); );
@@ -1062,10 +1052,7 @@ export class QwenAgentManager {
throw error; throw error;
} finally { } finally {
// End rehydration routing regardless of outcome // End rehydration routing regardless of outcome
this.consoleLog( console.log('[QwenAgentManager] Rehydration end for session:', sessionId);
'[QwenAgentManager] Rehydration end for session:',
sessionId,
);
this.rehydratingSessionId = null; this.rehydratingSessionId = null;
} }
} }
@@ -1078,7 +1065,7 @@ export class QwenAgentManager {
* @returns Loaded session messages or null * @returns Loaded session messages or null
*/ */
async loadSession(sessionId: string): Promise<ChatMessage[] | null> { async loadSession(sessionId: string): Promise<ChatMessage[] | null> {
this.consoleLog( console.log(
'[QwenAgentManager] Loading session with version-aware strategy:', '[QwenAgentManager] Loading session with version-aware strategy:',
sessionId, sessionId,
); );
@@ -1087,7 +1074,7 @@ export class QwenAgentManager {
const cliContextManager = CliContextManager.getInstance(); const cliContextManager = CliContextManager.getInstance();
const supportsSessionLoad = cliContextManager.supportsSessionLoad(); const supportsSessionLoad = cliContextManager.supportsSessionLoad();
this.consoleLog( console.log(
'[QwenAgentManager] CLI supports session/load:', '[QwenAgentManager] CLI supports session/load:',
supportsSessionLoad, supportsSessionLoad,
); );
@@ -1095,13 +1082,11 @@ export class QwenAgentManager {
// Try ACP method first if supported // Try ACP method first if supported
if (supportsSessionLoad) { if (supportsSessionLoad) {
try { try {
this.consoleLog( console.log(
'[QwenAgentManager] Attempting to load session via ACP method', '[QwenAgentManager] Attempting to load session via ACP method',
); );
await this.loadSessionViaAcp(sessionId); await this.loadSessionViaAcp(sessionId);
this.consoleLog( console.log('[QwenAgentManager] Session loaded successfully via ACP');
'[QwenAgentManager] Session loaded successfully via ACP',
);
// After loading via ACP, we still need to get messages from file system // After loading via ACP, we still need to get messages from file system
// In future, we might get them directly from the ACP response // In future, we might get them directly from the ACP response
@@ -1115,11 +1100,11 @@ export class QwenAgentManager {
// Always fall back to file system method // Always fall back to file system method
try { try {
this.consoleLog( console.log(
'[QwenAgentManager] Loading session messages from file system', '[QwenAgentManager] Loading session messages from file system',
); );
const messages = await this.loadSessionMessagesFromFile(sessionId); const messages = await this.loadSessionMessagesFromFile(sessionId);
this.consoleLog( console.log(
'[QwenAgentManager] Session messages loaded successfully from file system', '[QwenAgentManager] Session messages loaded successfully from file system',
); );
return messages; return messages;
@@ -1142,7 +1127,7 @@ export class QwenAgentManager {
sessionId: string, sessionId: string,
): Promise<ChatMessage[] | null> { ): Promise<ChatMessage[] | null> {
try { try {
this.consoleLog( console.log(
'[QwenAgentManager] Loading session from file system:', '[QwenAgentManager] Loading session from file system:',
sessionId, sessionId,
); );
@@ -1154,7 +1139,7 @@ export class QwenAgentManager {
); );
if (!session) { if (!session) {
this.consoleLog( console.log(
'[QwenAgentManager] Session not found in file system:', '[QwenAgentManager] Session not found in file system:',
sessionId, sessionId,
); );
@@ -1209,7 +1194,7 @@ export class QwenAgentManager {
return this.sessionCreateInFlight; return this.sessionCreateInFlight;
} }
this.consoleLog('[QwenAgentManager] Creating new session...'); console.log('[QwenAgentManager] Creating new session...');
// Prefer the provided authStateManager, otherwise fall back to the one // Prefer the provided authStateManager, otherwise fall back to the one
// remembered during connect(). This prevents accidental re-auth in // remembered during connect(). This prevents accidental re-auth in
// fallback paths (e.g. session switching) when the handler didn't pass it. // fallback paths (e.g. session switching) when the handler didn't pass it.
@@ -1250,7 +1235,7 @@ export class QwenAgentManager {
} }
} }
const newSessionId = this.connection.currentSessionId; const newSessionId = this.connection.currentSessionId;
this.consoleLog( console.log(
'[QwenAgentManager] New session created with ID:', '[QwenAgentManager] New session created with ID:',
newSessionId, newSessionId,
); );
@@ -1276,7 +1261,7 @@ export class QwenAgentManager {
* Cancel current prompt * Cancel current prompt
*/ */
async cancelCurrentPrompt(): Promise<void> { async cancelCurrentPrompt(): Promise<void> {
this.consoleLog('[QwenAgentManager] Cancelling current prompt'); console.log('[QwenAgentManager] Cancelling current prompt');
await this.connection.cancelSession(); await this.connection.cancelSession();
} }

View File

@@ -6,11 +6,6 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
type ConsoleLogger = (...args: unknown[]) => void;
// Shared console logger instance, initialized during extension activation.
let sharedConsoleLogger: ConsoleLogger = () => {};
export function createLogger( export function createLogger(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
logger: vscode.OutputChannel, logger: vscode.OutputChannel,
@@ -21,40 +16,3 @@ export function createLogger(
} }
}; };
} }
/**
* Creates a dev-only logger that writes to the VS Code console (Developer Tools).
*/
export function createConsoleLogger(
context: vscode.ExtensionContext,
scope?: string,
): ConsoleLogger {
return (...args: unknown[]) => {
if (context.extensionMode !== vscode.ExtensionMode.Development) {
return;
}
if (scope) {
console.log(`[${scope}]`, ...args);
return;
}
console.log(...args);
};
}
/**
* Initialize the shared console logger so other modules can import it without
* threading the extension context everywhere.
*/
export function initSharedConsoleLogger(
context: vscode.ExtensionContext,
scope?: string,
) {
sharedConsoleLogger = createConsoleLogger(context, scope);
}
/**
* Get the shared console logger (no-op until initialized).
*/
export function getConsoleLogger(): ConsoleLogger {
return sharedConsoleLogger;
}

View File

@@ -45,11 +45,9 @@ import { FileIcon, UserIcon } from './components/icons/index.js';
import { ApprovalMode, NEXT_APPROVAL_MODE } from '../types/acpTypes.js'; import { ApprovalMode, NEXT_APPROVAL_MODE } from '../types/acpTypes.js';
import type { ApprovalModeValue } from '../types/acpTypes.js'; import type { ApprovalModeValue } from '../types/acpTypes.js';
import type { PlanEntry } from '../types/chatTypes.js'; import type { PlanEntry } from '../types/chatTypes.js';
import { createWebviewConsoleLogger } from './utils/logger.js';
export const App: React.FC = () => { export const App: React.FC = () => {
const vscode = useVSCode(); const vscode = useVSCode();
const consoleLog = useMemo(() => createWebviewConsoleLogger('App'), []);
// Core hooks // Core hooks
const sessionManagement = useSessionManagement(vscode); const sessionManagement = useSessionManagement(vscode);
@@ -542,7 +540,7 @@ export const App: React.FC = () => {
); );
}, [messageHandling.messages, inProgressToolCalls, completedToolCalls]); }, [messageHandling.messages, inProgressToolCalls, completedToolCalls]);
consoleLog('[App] Rendering messages:', allMessages); console.log('[App] Rendering messages:', allMessages);
// Render all messages and tool calls // Render all messages and tool calls
const renderMessages = useCallback<() => React.ReactNode>( const renderMessages = useCallback<() => React.ReactNode>(

View File

@@ -16,7 +16,6 @@ import { WebViewContent } from '../webview/WebViewContent.js';
import { CliInstaller } from '../cli/cliInstaller.js'; import { CliInstaller } from '../cli/cliInstaller.js';
import { getFileName } from './utils/webviewUtils.js'; import { getFileName } from './utils/webviewUtils.js';
import { authMethod, type ApprovalModeValue } from '../types/acpTypes.js'; import { authMethod, type ApprovalModeValue } from '../types/acpTypes.js';
import { createConsoleLogger } from '../utils/logger.js';
export class WebViewProvider { export class WebViewProvider {
private panelManager: PanelManager; private panelManager: PanelManager;
@@ -33,15 +32,12 @@ export class WebViewProvider {
private pendingPermissionResolve: ((optionId: string) => void) | null = null; private pendingPermissionResolve: ((optionId: string) => void) | null = null;
// Track current ACP mode id to influence permission/diff behavior // Track current ACP mode id to influence permission/diff behavior
private currentModeId: ApprovalModeValue | null = null; private currentModeId: ApprovalModeValue | null = null;
private consoleLog: (...args: unknown[]) => void;
constructor( constructor(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
private extensionUri: vscode.Uri, private extensionUri: vscode.Uri,
) { ) {
const agentConsoleLogger = createConsoleLogger(context, 'QwenAgentManager'); this.agentManager = new QwenAgentManager();
this.consoleLog = createConsoleLogger(context, 'WebViewProvider');
this.agentManager = new QwenAgentManager(agentConsoleLogger);
this.conversationStore = new ConversationStore(context); this.conversationStore = new ConversationStore(context);
this.authStateManager = AuthStateManager.getInstance(context); this.authStateManager = AuthStateManager.getInstance(context);
this.panelManager = new PanelManager(extensionUri, () => { this.panelManager = new PanelManager(extensionUri, () => {
@@ -384,7 +380,7 @@ export class WebViewProvider {
// Set up state serialization // Set up state serialization
newPanel.onDidChangeViewState(() => { newPanel.onDidChangeViewState(() => {
this.consoleLog( console.log(
'[WebViewProvider] Panel view state changed, triggering serialization check', '[WebViewProvider] Panel view state changed, triggering serialization check',
); );
}); });
@@ -514,7 +510,7 @@ export class WebViewProvider {
} }
// Attempt to restore authentication state and initialize connection // Attempt to restore authentication state and initialize connection
this.consoleLog( console.log(
'[WebViewProvider] Attempting to restore auth state and connection...', '[WebViewProvider] Attempting to restore auth state and connection...',
); );
await this.attemptAuthStateRestoration(); await this.attemptAuthStateRestoration();
@@ -536,26 +532,23 @@ export class WebViewProvider {
workingDir, workingDir,
authMethod, authMethod,
); );
this.consoleLog( console.log('[WebViewProvider] Has valid cached auth:', hasValidAuth);
'[WebViewProvider] Has valid cached auth:',
hasValidAuth,
);
if (hasValidAuth) { if (hasValidAuth) {
this.consoleLog( console.log(
'[WebViewProvider] Valid auth found, attempting connection...', '[WebViewProvider] Valid auth found, attempting connection...',
); );
// Try to connect with cached auth // Try to connect with cached auth
await this.initializeAgentConnection(); await this.initializeAgentConnection();
} else { } else {
this.consoleLog( console.log(
'[WebViewProvider] No valid auth found, rendering empty conversation', '[WebViewProvider] No valid auth found, rendering empty conversation',
); );
// Render the chat UI immediately without connecting // Render the chat UI immediately without connecting
await this.initializeEmptyConversation(); await this.initializeEmptyConversation();
} }
} else { } else {
this.consoleLog( console.log(
'[WebViewProvider] No auth state manager, rendering empty conversation', '[WebViewProvider] No auth state manager, rendering empty conversation',
); );
await this.initializeEmptyConversation(); await this.initializeEmptyConversation();
@@ -585,11 +578,11 @@ export class WebViewProvider {
const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
const workingDir = workspaceFolder?.uri.fsPath || process.cwd(); const workingDir = workspaceFolder?.uri.fsPath || process.cwd();
this.consoleLog( console.log(
'[WebViewProvider] Starting initialization, workingDir:', '[WebViewProvider] Starting initialization, workingDir:',
workingDir, workingDir,
); );
this.consoleLog( console.log(
'[WebViewProvider] AuthStateManager available:', '[WebViewProvider] AuthStateManager available:',
!!this.authStateManager, !!this.authStateManager,
); );
@@ -598,10 +591,10 @@ export class WebViewProvider {
const cliDetection = await CliDetector.detectQwenCli(); const cliDetection = await CliDetector.detectQwenCli();
if (!cliDetection.isInstalled) { if (!cliDetection.isInstalled) {
this.consoleLog( console.log(
'[WebViewProvider] Qwen CLI not detected, skipping agent connection', '[WebViewProvider] Qwen CLI not detected, skipping agent connection',
); );
this.consoleLog( console.log(
'[WebViewProvider] CLI detection error:', '[WebViewProvider] CLI detection error:',
cliDetection.error, cliDetection.error,
); );
@@ -612,20 +605,20 @@ export class WebViewProvider {
// Initialize empty conversation (can still browse history) // Initialize empty conversation (can still browse history)
await this.initializeEmptyConversation(); await this.initializeEmptyConversation();
} else { } else {
this.consoleLog( console.log(
'[WebViewProvider] Qwen CLI detected, attempting connection...', '[WebViewProvider] Qwen CLI detected, attempting connection...',
); );
this.consoleLog('[WebViewProvider] CLI path:', cliDetection.cliPath); console.log('[WebViewProvider] CLI path:', cliDetection.cliPath);
this.consoleLog('[WebViewProvider] CLI version:', cliDetection.version); console.log('[WebViewProvider] CLI version:', cliDetection.version);
try { try {
this.consoleLog('[WebViewProvider] Connecting to agent...'); console.log('[WebViewProvider] Connecting to agent...');
this.consoleLog( console.log(
'[WebViewProvider] Using authStateManager:', '[WebViewProvider] Using authStateManager:',
!!this.authStateManager, !!this.authStateManager,
); );
const authInfo = await this.authStateManager.getAuthInfo(); const authInfo = await this.authStateManager.getAuthInfo();
this.consoleLog('[WebViewProvider] Auth cache status:', authInfo); console.log('[WebViewProvider] Auth cache status:', authInfo);
// Pass the detected CLI path to ensure we use the correct installation // Pass the detected CLI path to ensure we use the correct installation
await this.agentManager.connect( await this.agentManager.connect(
@@ -633,7 +626,7 @@ export class WebViewProvider {
this.authStateManager, this.authStateManager,
cliDetection.cliPath, cliDetection.cliPath,
); );
this.consoleLog('[WebViewProvider] Agent connected successfully'); console.log('[WebViewProvider] Agent connected successfully');
this.agentInitialized = true; this.agentInitialized = true;
// Load messages from the current Qwen session // Load messages from the current Qwen session
@@ -674,8 +667,8 @@ export class WebViewProvider {
* Called when user explicitly uses /login command * Called when user explicitly uses /login command
*/ */
async forceReLogin(): Promise<void> { async forceReLogin(): Promise<void> {
this.consoleLog('[WebViewProvider] Force re-login requested'); console.log('[WebViewProvider] Force re-login requested');
this.consoleLog( console.log(
'[WebViewProvider] Current authStateManager:', '[WebViewProvider] Current authStateManager:',
!!this.authStateManager, !!this.authStateManager,
); );
@@ -694,23 +687,20 @@ export class WebViewProvider {
// Clear existing auth cache // Clear existing auth cache
if (this.authStateManager) { if (this.authStateManager) {
await this.authStateManager.clearAuthState(); await this.authStateManager.clearAuthState();
this.consoleLog('[WebViewProvider] Auth cache cleared'); console.log('[WebViewProvider] Auth cache cleared');
} else { } else {
this.consoleLog('[WebViewProvider] No authStateManager to clear'); console.log('[WebViewProvider] No authStateManager to clear');
} }
// Disconnect existing connection if any // Disconnect existing connection if any
if (this.agentInitialized) { if (this.agentInitialized) {
try { try {
this.agentManager.disconnect(); this.agentManager.disconnect();
this.consoleLog( console.log(
'[WebViewProvider] Existing connection disconnected', '[WebViewProvider] Existing connection disconnected',
); );
} catch (_error) { } catch (_error) {
this.consoleLog( console.log('[WebViewProvider] Error disconnecting:', _error);
'[WebViewProvider] Error disconnecting:',
_error,
);
} }
this.agentInitialized = false; this.agentInitialized = false;
} }
@@ -724,7 +714,7 @@ export class WebViewProvider {
// Reinitialize connection (will trigger fresh authentication) // Reinitialize connection (will trigger fresh authentication)
await this.doInitializeAgentConnection(); await this.doInitializeAgentConnection();
this.consoleLog( console.log(
'[WebViewProvider] Force re-login completed successfully', '[WebViewProvider] Force re-login completed successfully',
); );
@@ -733,9 +723,7 @@ export class WebViewProvider {
const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
const workingDir = workspaceFolder?.uri.fsPath || process.cwd(); const workingDir = workspaceFolder?.uri.fsPath || process.cwd();
await this.authStateManager.saveAuthState(workingDir, authMethod); await this.authStateManager.saveAuthState(workingDir, authMethod);
this.consoleLog( console.log('[WebViewProvider] Auth state saved after re-login');
'[WebViewProvider] Auth state saved after re-login',
);
} }
// Send success notification to WebView // Send success notification to WebView
@@ -772,15 +760,15 @@ export class WebViewProvider {
* Called when restoring WebView after VSCode restart * Called when restoring WebView after VSCode restart
*/ */
async refreshConnection(): Promise<void> { async refreshConnection(): Promise<void> {
this.consoleLog('[WebViewProvider] Refresh connection requested'); console.log('[WebViewProvider] Refresh connection requested');
// Disconnect existing connection if any // Disconnect existing connection if any
if (this.agentInitialized) { if (this.agentInitialized) {
try { try {
this.agentManager.disconnect(); this.agentManager.disconnect();
this.consoleLog('[WebViewProvider] Existing connection disconnected'); console.log('[WebViewProvider] Existing connection disconnected');
} catch (_error) { } catch (_error) {
this.consoleLog('[WebViewProvider] Error disconnecting:', _error); console.log('[WebViewProvider] Error disconnecting:', _error);
} }
this.agentInitialized = false; this.agentInitialized = false;
} }
@@ -791,7 +779,7 @@ export class WebViewProvider {
// Reinitialize connection (will use cached auth if available) // Reinitialize connection (will use cached auth if available)
try { try {
await this.initializeAgentConnection(); await this.initializeAgentConnection();
this.consoleLog( console.log(
'[WebViewProvider] Connection refresh completed successfully', '[WebViewProvider] Connection refresh completed successfully',
); );
@@ -821,7 +809,7 @@ export class WebViewProvider {
*/ */
private async loadCurrentSessionMessages(): Promise<void> { private async loadCurrentSessionMessages(): Promise<void> {
try { try {
this.consoleLog( console.log(
'[WebViewProvider] Initializing with new session (skipping restoration)', '[WebViewProvider] Initializing with new session (skipping restoration)',
); );
@@ -835,12 +823,12 @@ export class WebViewProvider {
workingDir, workingDir,
this.authStateManager, this.authStateManager,
); );
this.consoleLog('[WebViewProvider] ACP session created successfully'); console.log('[WebViewProvider] ACP session created successfully');
// Ensure auth state is saved after successful session creation // Ensure auth state is saved after successful session creation
if (this.authStateManager) { if (this.authStateManager) {
await this.authStateManager.saveAuthState(workingDir, authMethod); await this.authStateManager.saveAuthState(workingDir, authMethod);
this.consoleLog( console.log(
'[WebViewProvider] Auth state saved after session creation', '[WebViewProvider] Auth state saved after session creation',
); );
} }
@@ -854,7 +842,7 @@ export class WebViewProvider {
); );
} }
} else { } else {
this.consoleLog( console.log(
'[WebViewProvider] Existing ACP session detected, skipping new session creation', '[WebViewProvider] Existing ACP session detected, skipping new session creation',
); );
} }
@@ -878,14 +866,14 @@ export class WebViewProvider {
*/ */
private async initializeEmptyConversation(): Promise<void> { private async initializeEmptyConversation(): Promise<void> {
try { try {
this.consoleLog('[WebViewProvider] Initializing empty conversation'); console.log('[WebViewProvider] Initializing empty conversation');
const newConv = await this.conversationStore.createConversation(); const newConv = await this.conversationStore.createConversation();
this.messageHandler.setCurrentConversationId(newConv.id); this.messageHandler.setCurrentConversationId(newConv.id);
this.sendMessageToWebView({ this.sendMessageToWebView({
type: 'conversationLoaded', type: 'conversationLoaded',
data: newConv, data: newConv,
}); });
this.consoleLog( console.log(
'[WebViewProvider] Empty conversation initialized:', '[WebViewProvider] Empty conversation initialized:',
this.messageHandler.getCurrentConversationId(), this.messageHandler.getCurrentConversationId(),
); );
@@ -1009,7 +997,7 @@ export class WebViewProvider {
* Call this when auth cache is cleared to force re-authentication * Call this when auth cache is cleared to force re-authentication
*/ */
resetAgentState(): void { resetAgentState(): void {
this.consoleLog('[WebViewProvider] Resetting agent state'); console.log('[WebViewProvider] Resetting agent state');
this.agentInitialized = false; this.agentInitialized = false;
// Disconnect existing connection // Disconnect existing connection
this.agentManager.disconnect(); this.agentManager.disconnect();
@@ -1019,7 +1007,7 @@ export class WebViewProvider {
* Clear authentication cache for this WebViewProvider instance * Clear authentication cache for this WebViewProvider instance
*/ */
async clearAuthCache(): Promise<void> { async clearAuthCache(): Promise<void> {
this.consoleLog('[WebViewProvider] Clearing auth cache for this instance'); console.log('[WebViewProvider] Clearing auth cache for this instance');
if (this.authStateManager) { if (this.authStateManager) {
await this.authStateManager.clearAuthState(); await this.authStateManager.clearAuthState();
this.resetAgentState(); this.resetAgentState();
@@ -1031,8 +1019,8 @@ export class WebViewProvider {
* This sets up the panel with all event listeners * This sets up the panel with all event listeners
*/ */
async restorePanel(panel: vscode.WebviewPanel): Promise<void> { async restorePanel(panel: vscode.WebviewPanel): Promise<void> {
this.consoleLog('[WebViewProvider] Restoring WebView panel'); console.log('[WebViewProvider] Restoring WebView panel');
this.consoleLog( console.log(
'[WebViewProvider] Current authStateManager in restore:', '[WebViewProvider] Current authStateManager in restore:',
!!this.authStateManager, !!this.authStateManager,
); );
@@ -1163,10 +1151,10 @@ export class WebViewProvider {
// Capture the tab reference on restore // Capture the tab reference on restore
this.panelManager.captureTab(); this.panelManager.captureTab();
this.consoleLog('[WebViewProvider] Panel restored successfully'); console.log('[WebViewProvider] Panel restored successfully');
// Attempt to restore authentication state and initialize connection // Attempt to restore authentication state and initialize connection
this.consoleLog( console.log(
'[WebViewProvider] Attempting to restore auth state and connection after restore...', '[WebViewProvider] Attempting to restore auth state and connection after restore...',
); );
await this.attemptAuthStateRestoration(); await this.attemptAuthStateRestoration();
@@ -1180,12 +1168,12 @@ export class WebViewProvider {
conversationId: string | null; conversationId: string | null;
agentInitialized: boolean; agentInitialized: boolean;
} { } {
this.consoleLog('[WebViewProvider] Getting state for serialization'); console.log('[WebViewProvider] Getting state for serialization');
this.consoleLog( console.log(
'[WebViewProvider] Current conversationId:', '[WebViewProvider] Current conversationId:',
this.messageHandler.getCurrentConversationId(), this.messageHandler.getCurrentConversationId(),
); );
this.consoleLog( console.log(
'[WebViewProvider] Current agentInitialized:', '[WebViewProvider] Current agentInitialized:',
this.agentInitialized, this.agentInitialized,
); );
@@ -1193,7 +1181,7 @@ export class WebViewProvider {
conversationId: this.messageHandler.getCurrentConversationId(), conversationId: this.messageHandler.getCurrentConversationId(),
agentInitialized: this.agentInitialized, agentInitialized: this.agentInitialized,
}; };
this.consoleLog('[WebViewProvider] Returning state:', state); console.log('[WebViewProvider] Returning state:', state);
return state; return state;
} }
@@ -1211,10 +1199,10 @@ export class WebViewProvider {
conversationId: string | null; conversationId: string | null;
agentInitialized: boolean; agentInitialized: boolean;
}): void { }): void {
this.consoleLog('[WebViewProvider] Restoring state:', state); console.log('[WebViewProvider] Restoring state:', state);
this.messageHandler.setCurrentConversationId(state.conversationId); this.messageHandler.setCurrentConversationId(state.conversationId);
this.agentInitialized = state.agentInitialized; this.agentInitialized = state.agentInitialized;
this.consoleLog( console.log(
'[WebViewProvider] State restored. agentInitialized:', '[WebViewProvider] State restored. agentInitialized:',
this.agentInitialized, this.agentInitialized,
); );

View File

@@ -61,25 +61,6 @@ export const safeTitle = (title: unknown): string => {
return ''; return '';
}; };
/**
* Get icon emoji for a given tool kind
*/
export const getKindIcon = (kind: string): string => {
const kindMap: Record<string, string> = {
edit: '✏️',
write: '✏️',
read: '📖',
execute: '⚡',
fetch: '🌐',
delete: '🗑️',
move: '📦',
search: '🔍',
think: '💭',
diff: '📝',
};
return kindMap[kind.toLowerCase()] || '🔧';
};
/** /**
* Check if a tool call should be displayed * Check if a tool call should be displayed
* Hides internal tool calls * Hides internal tool calls

View File

@@ -14,7 +14,6 @@ import type {
import type { ToolCallUpdate } from '../../types/chatTypes.js'; import type { ToolCallUpdate } from '../../types/chatTypes.js';
import type { ApprovalModeValue } from '../../types/acpTypes.js'; import type { ApprovalModeValue } from '../../types/acpTypes.js';
import type { PlanEntry } from '../../types/chatTypes.js'; import type { PlanEntry } from '../../types/chatTypes.js';
import { createWebviewConsoleLogger } from '../utils/logger.js';
interface UseWebViewMessagesProps { interface UseWebViewMessagesProps {
// Session management // Session management
@@ -130,7 +129,6 @@ export const useWebViewMessages = ({
}: UseWebViewMessagesProps) => { }: UseWebViewMessagesProps) => {
// VS Code API for posting messages back to the extension host // VS Code API for posting messages back to the extension host
const vscode = useVSCode(); const vscode = useVSCode();
const consoleLog = useRef(createWebviewConsoleLogger('WebViewMessages'));
// Track active long-running tool calls (execute/bash/command) so we can // Track active long-running tool calls (execute/bash/command) so we can
// keep the bottom "waiting" message visible until all of them complete. // keep the bottom "waiting" message visible until all of them complete.
const activeExecToolCallsRef = useRef<Set<string>>(new Set()); const activeExecToolCallsRef = useRef<Set<string>>(new Set());
@@ -753,10 +751,7 @@ export const useWebViewMessages = ({
path: string; path: string;
}>; }>;
if (files) { if (files) {
consoleLog.current( console.log('[WebView] Received workspaceFiles:', files.length);
'[WebView] Received workspaceFiles:',
files.length,
);
handlers.fileContext.setWorkspaceFiles(files); handlers.fileContext.setWorkspaceFiles(files);
} }
break; break;

View File

@@ -1,25 +0,0 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Creates a dev-only console logger for the WebView bundle.
* In production builds it becomes a no-op to avoid noisy logs.
*/
export function createWebviewConsoleLogger(scope?: string) {
return (...args: unknown[]) => {
const env = (globalThis as { process?: { env?: Record<string, string> } })
.process?.env;
const isProduction = env?.NODE_ENV === 'production';
if (isProduction) {
return;
}
if (scope) {
console.log(`[${scope}]`, ...args);
return;
}
console.log(...args);
};
}