From c377d9547120e20bbf952d8709c6cc2715471483 Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Tue, 17 Nov 2026 01:40:00 +0000 Subject: [PATCH 1/3] fix(amazonq): log errors from chat notification handlers The chat server and the agentic chat server now log an error from a notification handler, and from the background code symbol update, instead of leaving an unhandled rejection. A rule request with no workspace folder open now creates a saved prompt. Adds tests. --- .../agenticChat/agenticChatController.test.ts | 55 ++++++- .../agenticChat/agenticChatController.ts | 8 +- .../agenticChat/qAgenticChatServer.test.ts | 114 +++++++++++++ .../agenticChat/qAgenticChatServer.ts | 155 ++++++++++++------ .../chat/notificationErrors.test.ts | 99 +++++++++++ .../chat/notificationErrors.ts | 28 ++++ .../language-server/chat/qChatServer.test.ts | 86 ++++++++++ .../src/language-server/chat/qChatServer.ts | 69 +++++--- .../src/shared/testUtils.ts | 22 +++ 9 files changed, 556 insertions(+), 80 deletions(-) create mode 100644 server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.test.ts create mode 100644 server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.ts diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts index 192f41c013..877d194cf0 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts @@ -52,7 +52,11 @@ import { import { MessageType, Model } from '@aws/language-server-runtimes/protocol' import { TestFeatures } from '@aws/language-server-runtimes/testing' import * as assert from 'assert' -import { createIterableResponse, setCredentialsForAmazonQTokenServiceManagerFactory } from '../../shared/testUtils' +import { + createIterableResponse, + setCredentialsForAmazonQTokenServiceManagerFactory, + unhandledRejectionsDuring, +} from '../../shared/testUtils' import sinon from 'ts-sinon' import { AgenticChatController } from './agenticChatController' import { ChatSessionManagementService } from '../chat/chatSessionManagementService' @@ -2227,6 +2231,55 @@ describe('AgenticChatController', () => { sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) }) + + it('creates a saved prompt file when a rule is requested with no workspace folder open', async () => { + sinon.stub(workspaceUtils, 'getWorkspaceFolderPaths').returns([]) + const expectedPath = path.join(getUserPromptsDirectory(), `testRule${promptFileExtension}`) + + await chatController.onCreatePrompt({ promptName: 'testRule', isRule: true }) + + sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) + }) + + it('creates a rule file in the rules folder of the first workspace folder', async () => { + const workspaceFolder = path.join(os.tmpdir(), 'create-rule-workspace') + const secondWorkspaceFolder = path.join(os.tmpdir(), 'create-rule-second-workspace') + sinon.stub(workspaceUtils, 'getWorkspaceFolderPaths').returns([workspaceFolder, secondWorkspaceFolder]) + const rulesDirectory = path.join(workspaceFolder, '.amazonq', 'rules') + const expectedPath = path.join(rulesDirectory, `testRule${promptFileExtension}`) + + await chatController.onCreatePrompt({ promptName: 'testRule', isRule: true }) + + sinon.assert.calledWithExactly(testFeatures.workspace.fs.mkdir as sinon.SinonStub, rulesDirectory, { + recursive: true, + }) + sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) + sinon.assert.calledWithMatch(testFeatures.lsp.window.showDocument as sinon.SinonStub, { + uri: URI.file(expectedPath).toString(), + }) + }) + }) + + describe('onReady', () => { + it('logs a failed background code symbol update and leaves no unhandled rejection', async () => { + const maybeUpdateCodeSymbolsStub = ContextCommandsProvider.prototype + .maybeUpdateCodeSymbols as sinon.SinonStub + const failure = new Error('code symbols failed') + maybeUpdateCodeSymbolsStub.rejects(failure) + + const rejections = await unhandledRejectionsDuring(() => chatController.onReady()) + + assert.ok(!rejections.includes(failure), 'the failed update was left as an unhandled rejection') + sinon.assert.calledOnce(maybeUpdateCodeSymbolsStub) + sinon.assert.calledWithMatch( + testFeatures.logging.log as sinon.SinonStub, + sinon.match('Error updating code symbols').and(sinon.match('code symbols failed')) + ) + sinon.assert.neverCalledWithMatch( + testFeatures.logging.log as sinon.SinonStub, + sinon.match('Error initializing context commands') + ) + }) }) describe('onInlineChatPrompt', () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts index a23f31460b..0c9210ee20 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts @@ -767,8 +767,9 @@ export class AgenticChatController implements ChatHandlers { async onCreatePrompt(params: CreatePromptParams): Promise { if (params.isRule) { let workspaceFolders = workspaceUtils.getWorkspaceFolderPaths(this.#features.workspace) - let workspaceRulesDirectory = path.join(workspaceFolders[0], '.amazonq', 'rules') + // Rules live in a workspace folder. With no folder open, the request creates a saved prompt below. if (workspaceFolders.length > 0) { + const workspaceRulesDirectory = path.join(workspaceFolders[0], '.amazonq', 'rules') const newFilePath = getNewRuleFilePath(params.promptName, workspaceRulesDirectory) const newFileContent = '' try { @@ -4534,7 +4535,10 @@ export class AgenticChatController implements ChatHandlers { const contextItems = await localProjectContextController.getContextCommandItems() this.#contextCommandsProvider.setFilesAndFoldersPending(false) await this.#contextCommandsProvider.processContextCommandUpdate(contextItems) - void this.#contextCommandsProvider.maybeUpdateCodeSymbols() + // This update runs in the background, so its failure must be handled here, not by the catch below + this.#contextCommandsProvider.maybeUpdateCodeSymbols().catch(error => { + this.#log('Error updating code symbols for context commands: ' + error) + }) } catch (error) { this.#contextCommandsProvider.setFilesAndFoldersFailed(true) await this.#contextCommandsProvider.processContextCommandUpdate([]) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts index 2468c306bc..7e5bcf0c42 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts @@ -3,7 +3,24 @@ * Will be deleted or merged. */ +import * as assert from 'assert' import { CancellationToken, Server } from '@aws/language-server-runtimes/server-interface' +import { + activeEditorChangedNotificationType, + createPromptNotificationType, + feedbackNotificationType, + fileClickNotificationType, + followUpClickNotificationType, + inlineChatResultNotificationType, + insertToCursorPositionNotificationType, + onPinnedContextAddNotificationType, + onPinnedContextRemoveNotificationType, + promptInputOptionChangeNotificationType, + readyNotificationType, + tabAddNotificationType, + tabChangeNotificationType, + tabRemoveNotificationType, +} from '@aws/language-server-runtimes/protocol' import { TestFeatures } from '@aws/language-server-runtimes/testing' import sinon from 'ts-sinon' import { AgenticChatController } from './agenticChatController' @@ -12,6 +29,7 @@ import { QAgenticChatServer } from './qAgenticChatServer' import { AmazonQTokenServiceManager } from '../../shared/amazonQServiceManager/AmazonQTokenServiceManager' import { AmazonQBaseServiceManager } from '../../shared/amazonQServiceManager/BaseAmazonQServiceManager' import { LocalProjectContextController } from '../../shared/localProjectContextController' +import { unhandledRejectionsDuring } from '../../shared/testUtils' import { Features } from '../types' describe('QAgenticChatServer', () => { @@ -148,4 +166,100 @@ describe('QAgenticChatServer', () => { sinon.assert.calledOnce(tabBarActionStub) }) + + describe('request handler results', () => { + // The chat registrations that the runtime binds to JSON-RPC requests. They must return the controller's + // result, because the JSON-RPC layer sends it as the response. + const requestRegistrations = [ + 'onEndChat', + 'onChatPrompt', + 'onOpenFileDialog', + 'onInlineChatPrompt', + 'onQuickAction', + 'onListConversations', + 'onListRules', + 'onConversationClick', + 'onRuleClick', + 'onListMcpServers', + 'onMcpServerClick', + 'onTabBarAction', + 'onButtonClick', + 'onListAvailableModels', + ] as const + + for (const name of requestRegistrations) { + it(`returns the controller result from the ${name} handler`, () => { + const result = { marker: name } + sinon.stub(AgenticChatController.prototype, name).returns(result as any) + const handler = (testFeatures.chat[name] as sinon.SinonStub).firstCall.firstArg + + assert.strictEqual(handler({ tabId: mockTabId }, {}), result) + }) + } + }) + + describe('notification handler failures', () => { + // The chat registrations that the runtime binds to JSON-RPC notifications, with their method names. Each + // registration has the same name as the controller method that it calls. + const notificationRegistrations = [ + ['onTabAdd', tabAddNotificationType.method], + ['onReady', readyNotificationType.method], + ['onTabChange', tabChangeNotificationType.method], + ['onTabRemove', tabRemoveNotificationType.method], + ['onSendFeedback', feedbackNotificationType.method], + ['onCodeInsertToCursorPosition', insertToCursorPositionNotificationType.method], + ['onCreatePrompt', createPromptNotificationType.method], + ['onFileClicked', fileClickNotificationType.method], + ['onFollowUpClicked', followUpClickNotificationType.method], + ['onPromptInputOptionChange', promptInputOptionChangeNotificationType.method], + ['onInlineChatResult', inlineChatResultNotificationType.method], + ['onActiveEditorChanged', activeEditorChangedNotificationType.method], + ['onPinnedContextAdd', onPinnedContextAddNotificationType.method], + ['onPinnedContextRemove', onPinnedContextRemoveNotificationType.method], + ] as const + + for (const [name, method] of notificationRegistrations) { + it(`logs a rejected ${name} handler and leaves no unhandled rejection`, async () => { + const failure = new Error(`${name} failed`) + sinon.stub(AgenticChatController.prototype, name).rejects(failure) + const handler = (testFeatures.chat[name] as sinon.SinonStub).firstCall.firstArg + + const rejections = await unhandledRejectionsDuring(() => handler({ tabId: mockTabId })) + + assert.ok(!rejections.includes(failure), `the ${name} failure was left as an unhandled rejection`) + sinon.assert.calledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(method).and(sinon.match(`${name} failed`)) + ) + }) + } + + it('logs a notification handler that throws instead of throwing to the caller', () => { + sinon.stub(AgenticChatController.prototype, 'onTabAdd').throws(new Error('onTabAdd threw')) + + assert.doesNotThrow(() => testFeatures.chat.onTabAdd.firstCall.firstArg({ tabId: mockTabId })) + + sinon.assert.calledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(tabAddNotificationType.method).and(sinon.match('onTabAdd threw')) + ) + }) + + it('creates a saved prompt when a rule is requested with no workspace folder open', async () => { + testFeatures.workspace.getAllWorkspaceFolders.returns([]) + const handler = testFeatures.chat.onCreatePrompt.firstCall.firstArg + + handler({ promptName: 'no-folder-rule', isRule: true }) + await new Promise(resolve => setImmediate(resolve)) + + sinon.assert.neverCalledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(createPromptNotificationType.method) + ) + sinon.assert.calledWithMatch( + testFeatures.workspace.fs.writeFile as sinon.SinonStub, + sinon.match(/no-folder-rule\.md$/) + ) + }) + }) }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.ts index 445ca78d85..ff2113062c 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.ts @@ -4,8 +4,25 @@ */ import { InitializeParams, Server } from '@aws/language-server-runtimes/server-interface' +import { + activeEditorChangedNotificationType, + createPromptNotificationType, + feedbackNotificationType, + fileClickNotificationType, + followUpClickNotificationType, + inlineChatResultNotificationType, + insertToCursorPositionNotificationType, + onPinnedContextAddNotificationType, + onPinnedContextRemoveNotificationType, + promptInputOptionChangeNotificationType, + readyNotificationType, + tabAddNotificationType, + tabChangeNotificationType, + tabRemoveNotificationType, +} from '@aws/language-server-runtimes/protocol' import { AgenticChatController } from './agenticChatController' import { ChatSessionManagementService } from '../chat/chatSessionManagementService' +import { logNotificationErrors } from '../chat/notificationErrors' import { CLEAR_QUICK_ACTION, COMPACT_QUICK_ACTION, HELP_QUICK_ACTION } from '../chat/quickActions' import { TelemetryService } from '../../shared/telemetry/telemetryService' import { makeUserContextObject } from '../../shared/telemetryUtils' @@ -131,27 +148,37 @@ export const QAgenticChatServer = return chatController.onExecuteCommand(params, token) }) - chat.onTabAdd(params => { - logging.log(`Adding tab: ${params.tabId}`) - - return chatController.onTabAdd(params) - }) - chat.onReady(() => { - logging.log(`Received ready notification`) - return chatController.onReady() - }) - - chat.onTabChange(params => { - logging.log(`Changing to tab: ${params.tabId}`) - - return chatController.onTabChange(params) - }) - - chat.onTabRemove(params => { - logging.log(`Removing tab: ${params.tabId}`) - - return chatController.onTabRemove(params) - }) + // Wrap each chat notification handler in logNotificationErrors. Request handlers need no wrapper, because the + // JSON-RPC layer sends an error response when a request handler fails. + chat.onTabAdd( + logNotificationErrors(logging, tabAddNotificationType.method, params => { + logging.log(`Adding tab: ${params.tabId}`) + + return chatController.onTabAdd(params) + }) + ) + chat.onReady( + logNotificationErrors(logging, readyNotificationType.method, () => { + logging.log(`Received ready notification`) + return chatController.onReady() + }) + ) + + chat.onTabChange( + logNotificationErrors(logging, tabChangeNotificationType.method, params => { + logging.log(`Changing to tab: ${params.tabId}`) + + return chatController.onTabChange(params) + }) + ) + + chat.onTabRemove( + logNotificationErrors(logging, tabRemoveNotificationType.method, params => { + logging.log(`Removing tab: ${params.tabId}`) + + return chatController.onTabRemove(params) + }) + ) chat.onEndChat((...params) => { logging.log('Received end chat request') @@ -177,13 +204,17 @@ export const QAgenticChatServer = return chatController.onQuickAction(...params) }) - chat.onSendFeedback(params => { - return chatController.onSendFeedback(params) - }) + chat.onSendFeedback( + logNotificationErrors(logging, feedbackNotificationType.method, params => { + return chatController.onSendFeedback(params) + }) + ) - chat.onCodeInsertToCursorPosition(params => { - return chatController.onCodeInsertToCursorPosition(params) - }) + chat.onCodeInsertToCursorPosition( + logNotificationErrors(logging, insertToCursorPositionNotificationType.method, params => { + return chatController.onCodeInsertToCursorPosition(params) + }) + ) chat.onListConversations(params => { return chatController.onListConversations(params) @@ -209,25 +240,33 @@ export const QAgenticChatServer = return chatController.onMcpServerClick(params) }) - chat.onCreatePrompt((params) => { - return chatController.onCreatePrompt(params) - }) + chat.onCreatePrompt( + logNotificationErrors(logging, createPromptNotificationType.method, params => { + return chatController.onCreatePrompt(params) + }) + ) - chat.onFileClicked((params) => { - return chatController.onFileClicked(params) - }) + chat.onFileClicked( + logNotificationErrors(logging, fileClickNotificationType.method, params => { + return chatController.onFileClicked(params) + }) + ) - chat.onFollowUpClicked((params) => { - return chatController.onFollowUpClicked(params) - }) + chat.onFollowUpClicked( + logNotificationErrors(logging, followUpClickNotificationType.method, params => { + return chatController.onFollowUpClicked(params) + }) + ) chat.onTabBarAction(params => { return chatController.onTabBarAction(params) }) - chat.onPromptInputOptionChange(params => { - return chatController.onPromptInputOptionChange(params) - }) + chat.onPromptInputOptionChange( + logNotificationErrors(logging, promptInputOptionChangeNotificationType.method, params => { + return chatController.onPromptInputOptionChange(params) + }) + ) // ;(chat as any).onPromptInputButtonClick((params: any) => { // chatController.setPaidTierMode(params.tabId, 'paidtier') @@ -237,21 +276,29 @@ export const QAgenticChatServer = return chatController.onButtonClick(params) }) - chat.onInlineChatResult(params => { - return chatController.onInlineChatResult(params) - }) - - chat.onActiveEditorChanged(params => { - return chatController.onActiveEditorChanged(params) - }) - - chat.onPinnedContextAdd(params => { - return chatController.onPinnedContextAdd(params) - }) - - chat.onPinnedContextRemove(params => { - return chatController.onPinnedContextRemove(params) - }) + chat.onInlineChatResult( + logNotificationErrors(logging, inlineChatResultNotificationType.method, params => { + return chatController.onInlineChatResult(params) + }) + ) + + chat.onActiveEditorChanged( + logNotificationErrors(logging, activeEditorChangedNotificationType.method, params => { + return chatController.onActiveEditorChanged(params) + }) + ) + + chat.onPinnedContextAdd( + logNotificationErrors(logging, onPinnedContextAddNotificationType.method, params => { + return chatController.onPinnedContextAdd(params) + }) + ) + + chat.onPinnedContextRemove( + logNotificationErrors(logging, onPinnedContextRemoveNotificationType.method, params => { + return chatController.onPinnedContextRemove(params) + }) + ) chat.onListAvailableModels(params => { return chatController.onListAvailableModels(params) diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.test.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.test.ts new file mode 100644 index 0000000000..bb8b9f2bf4 --- /dev/null +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.test.ts @@ -0,0 +1,99 @@ +import * as assert from 'assert' +import { Logging } from '@aws/language-server-runtimes/server-interface' +import sinon from 'ts-sinon' +import { logNotificationErrors } from './notificationErrors' +import { unhandledRejectionsDuring } from '../../shared/testUtils' + +describe('logNotificationErrors()', () => { + let logError: sinon.SinonStub + let logging: Logging + + beforeEach(() => { + logError = sinon.stub() + logging = { error: logError } as unknown as Logging + }) + + afterEach(() => { + sinon.restore() + }) + + it('passes the params to the handler and logs nothing when the handler succeeds', async () => { + const syncHandler = sinon.stub().returns(undefined) + const asyncHandler = sinon.stub().resolves('done') + + logNotificationErrors(logging, 'test/sync', syncHandler)({ value: 1 }) + logNotificationErrors(logging, 'test/async', asyncHandler)({ value: 2 }) + await new Promise(resolve => setImmediate(resolve)) + + sinon.assert.calledOnceWithExactly(syncHandler, { value: 1 }) + sinon.assert.calledOnceWithExactly(asyncHandler, { value: 2 }) + sinon.assert.notCalled(logError) + }) + + it('calls the handler before it returns', () => { + const handler = sinon.stub() + + logNotificationErrors(logging, 'test/sync', handler)({ value: 1 }) + + sinon.assert.calledOnce(handler) + }) + + it('logs a rejection with the notification method and the reason', async () => { + const failure = new Error('rejected') + + const rejections = await unhandledRejectionsDuring(() => + logNotificationErrors(logging, 'test/reject', () => Promise.reject(failure))(undefined) + ) + + assert.ok(!rejections.includes(failure), 'the rejection was left unhandled') + sinon.assert.calledOnceWithMatch(logError, sinon.match('test/reject').and(sinon.match('rejected'))) + }) + + it('logs a handler that throws instead of throwing to the caller', () => { + const handler = logNotificationErrors(logging, 'test/throw', () => { + throw new Error('thrown') + }) + + assert.doesNotThrow(() => handler(undefined)) + + sinon.assert.calledOnceWithMatch(logError, sinon.match('test/throw').and(sinon.match('thrown'))) + }) + + it('logs a rejection reason that is not an Error', async () => { + logNotificationErrors(logging, 'test/reject', () => Promise.reject('plain reason'))(undefined) + await new Promise(resolve => setImmediate(resolve)) + + sinon.assert.calledOnceWithMatch(logError, sinon.match('test/reject').and(sinon.match('plain reason'))) + }) + + it('leaves no unhandled rejection when the rejection reason cannot be formatted', async () => { + // JSON serialization, which formatErr uses, throws a TypeError on a bigint + const rejections = await unhandledRejectionsDuring(() => + logNotificationErrors(logging, 'test/bigint', () => Promise.reject(10n))(undefined) + ) + + assert.ok( + !rejections.some( + reason => reason === 10n || (reason instanceof TypeError && /BigInt/.test(reason.message)) + ), + 'the rejection or the formatting error was left unhandled' + ) + }) + + it('leaves no unhandled rejection or exception when the logger throws', async () => { + const loggerFailure = new Error('logger failed') + const failure = new Error('rejected') + logError.throws(loggerFailure) + + const rejections = await unhandledRejectionsDuring(() => { + logNotificationErrors(logging, 'test/reject', () => Promise.reject(failure))(undefined) + logNotificationErrors(logging, 'test/throw', () => { + throw new Error('thrown') + })(undefined) + }) + + assert.ok(!rejections.includes(failure), 'the rejection was left unhandled') + assert.ok(!rejections.includes(loggerFailure), 'the logger error was left unhandled') + sinon.assert.calledTwice(logError) + }) +}) diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.ts new file mode 100644 index 0000000000..655558f078 --- /dev/null +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/notificationErrors.ts @@ -0,0 +1,28 @@ +import { Logging } from '@aws/language-server-runtimes/server-interface' +import { loggingUtils } from '@aws/lsp-core' + +/** + * Wraps a chat notification handler so that a failure is logged and does not escape. The JSON-RPC layer ignores the + * value that a notification handler returns, so a rejected promise from an async controller method would otherwise + * be an unhandled rejection. + */ +export function logNotificationErrors

( + logging: Logging, + method: string, + handler: (params: P) => unknown +): (params: P) => void { + const logError = (error: unknown) => { + try { + logging.error(`Chat notification ${method} failed: ${loggingUtils.formatErr(error)}`) + } catch { + // An error that cannot be formatted, or a logger that throws, must not become an unhandled rejection + } + } + return params => { + try { + void Promise.resolve(handler(params)).catch(logError) + } catch (error) { + logError(error) + } + } +} diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts index 36b005193b..12515da28c 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts @@ -1,10 +1,20 @@ +import * as assert from 'assert' import { CancellationToken, Server } from '@aws/language-server-runtimes/server-interface' +import { + feedbackNotificationType, + inlineChatResultNotificationType, + insertToCursorPositionNotificationType, + tabAddNotificationType, + tabChangeNotificationType, + tabRemoveNotificationType, +} from '@aws/language-server-runtimes/protocol' import { TestFeatures } from '@aws/language-server-runtimes/testing' import sinon from 'ts-sinon' import { ChatController } from './chatController' import { ChatSessionManagementService } from './chatSessionManagementService' import { QChatServerFactory } from './qChatServer' import { initBaseTestServiceManager, TestAmazonQServiceManager } from '../../shared/amazonQServiceManager/testUtils' +import { unhandledRejectionsDuring } from '../../shared/testUtils' describe('QChatServer', () => { const mockTabId = 'mockTabId' @@ -110,4 +120,80 @@ describe('QChatServer', () => { mockCancellationToken ) }) + + describe('request handler results', () => { + // The chat registrations that the runtime binds to JSON-RPC requests. They must return the controller's + // result, because the JSON-RPC layer sends it as the response. + const requestRegistrations = ['onEndChat', 'onChatPrompt', 'onInlineChatPrompt', 'onQuickAction'] as const + + for (const name of requestRegistrations) { + it(`returns the controller result from the ${name} handler`, () => { + const result = { marker: name } + sinon.stub(ChatController.prototype, name).returns(result as any) + const handler = (testFeatures.chat[name] as sinon.SinonStub).firstCall.firstArg + + assert.strictEqual(handler({ tabId: mockTabId }, {}), result) + }) + } + }) + + describe('notification handler failures', () => { + // The chat registrations that the runtime binds to JSON-RPC notifications, with their method names. Each + // registration has the same name as the controller method that it calls. + const notificationRegistrations = [ + ['onTabAdd', tabAddNotificationType.method], + ['onTabChange', tabChangeNotificationType.method], + ['onTabRemove', tabRemoveNotificationType.method], + ['onSendFeedback', feedbackNotificationType.method], + ['onCodeInsertToCursorPosition', insertToCursorPositionNotificationType.method], + ['onInlineChatResult', inlineChatResultNotificationType.method], + ] as const + + for (const [name, method] of notificationRegistrations) { + it(`logs a rejected ${name} handler and leaves no unhandled rejection`, async () => { + const failure = new Error(`${name} failed`) + sinon.stub(ChatController.prototype, name).rejects(failure) + const handler = (testFeatures.chat[name] as sinon.SinonStub).firstCall.firstArg + + const rejections = await unhandledRejectionsDuring(() => handler({ tabId: mockTabId })) + + assert.ok(!rejections.includes(failure), `the ${name} failure was left as an unhandled rejection`) + sinon.assert.calledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(method).and(sinon.match(`${name} failed`)) + ) + }) + } + + it('logs a notification handler that throws instead of throwing to the caller', () => { + sinon.stub(ChatController.prototype, 'onTabAdd').throws(new Error('onTabAdd threw')) + + assert.doesNotThrow(() => testFeatures.chat.onTabAdd.firstCall.firstArg({ tabId: mockTabId })) + + sinon.assert.calledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(tabAddNotificationType.method).and(sinon.match('onTabAdd threw')) + ) + }) + + it('logs an insert notification whose code is not a string', async () => { + const handler = testFeatures.chat.onCodeInsertToCursorPosition.firstCall.firstArg + + handler({ + tabId: mockTabId, + textDocument: { uri: 'file:///insert-check.ts' }, + cursorPosition: { line: 0, character: 0 }, + code: 123, + }) + await new Promise(resolve => setImmediate(resolve)) + + sinon.assert.calledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon + .match(insertToCursorPositionNotificationType.method) + .and(sinon.match('TypeError')) + .and(sinon.match('is not a function')) + ) + }) + }) }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.ts index d110ea4e41..a5a3263554 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.ts @@ -1,6 +1,15 @@ import { InitializeParams, Server } from '@aws/language-server-runtimes/server-interface' +import { + feedbackNotificationType, + inlineChatResultNotificationType, + insertToCursorPositionNotificationType, + tabAddNotificationType, + tabChangeNotificationType, + tabRemoveNotificationType, +} from '@aws/language-server-runtimes/protocol' import { ChatController } from './chatController' import { ChatSessionManagementService } from './chatSessionManagementService' +import { logNotificationErrors } from './notificationErrors' import { CLEAR_QUICK_ACTION, HELP_QUICK_ACTION } from './quickActions' import { TelemetryService } from '../../shared/telemetry/telemetryService' import { makeUserContextObject } from '../../shared/telemetryUtils' @@ -73,23 +82,31 @@ export const QChatServerFactory = await amazonQServiceManager.addDidChangeConfigurationListener(updateConfigurationHandler) }) - chat.onTabAdd(params => { - logging.log(`Adding tab: ${params.tabId}`) + // Wrap each chat notification handler in logNotificationErrors. Request handlers need no wrapper, because the + // JSON-RPC layer sends an error response when a request handler fails. + chat.onTabAdd( + logNotificationErrors(logging, tabAddNotificationType.method, params => { + logging.log(`Adding tab: ${params.tabId}`) - return chatController.onTabAdd(params) - }) + return chatController.onTabAdd(params) + }) + ) - chat.onTabChange(params => { - logging.log(`Changing to tab: ${params.tabId}`) + chat.onTabChange( + logNotificationErrors(logging, tabChangeNotificationType.method, params => { + logging.log(`Changing to tab: ${params.tabId}`) - return chatController.onTabChange(params) - }) + return chatController.onTabChange(params) + }) + ) - chat.onTabRemove(params => { - logging.log(`Removing tab: ${params.tabId}`) + chat.onTabRemove( + logNotificationErrors(logging, tabRemoveNotificationType.method, params => { + logging.log(`Removing tab: ${params.tabId}`) - return chatController.onTabRemove(params) - }) + return chatController.onTabRemove(params) + }) + ) chat.onEndChat((...params) => { logging.log('Received end chat request') @@ -110,17 +127,23 @@ export const QChatServerFactory = return chatController.onQuickAction(...params) }) - chat.onSendFeedback(params => { - return chatController.onSendFeedback(params) - }) - - chat.onCodeInsertToCursorPosition(params => { - return chatController.onCodeInsertToCursorPosition(params) - }) - - chat.onInlineChatResult(params => { - return chatController.onInlineChatResult(params) - }) + chat.onSendFeedback( + logNotificationErrors(logging, feedbackNotificationType.method, params => { + return chatController.onSendFeedback(params) + }) + ) + + chat.onCodeInsertToCursorPosition( + logNotificationErrors(logging, insertToCursorPositionNotificationType.method, params => { + return chatController.onCodeInsertToCursorPosition(params) + }) + ) + + chat.onInlineChatResult( + logNotificationErrors(logging, inlineChatResultNotificationType.method, params => { + return chatController.onInlineChatResult(params) + }) + ) logging.log('Q Chat server has been initialized') diff --git a/server/aws-lsp-codewhisperer/src/shared/testUtils.ts b/server/aws-lsp-codewhisperer/src/shared/testUtils.ts index efa76d2fdc..3d4006989b 100644 --- a/server/aws-lsp-codewhisperer/src/shared/testUtils.ts +++ b/server/aws-lsp-codewhisperer/src/shared/testUtils.ts @@ -314,3 +314,25 @@ export const stubCodeWhispererService = () = return service } + +/** + * Runs `action` and waits for the promise that it returns, if any. Then lets pending promise callbacks run, and + * returns the rejections that had no handler. A rejection of the promise that `action` returns is thrown, not + * returned. Mocha re-emits an unhandled rejection from test code instead of failing on it, so a listener added + * here receives it, possibly more than once. + * + * Background work from other tests can also reject in this window. Check the result for the test's own rejection + * reason, not for an empty list. + */ +export async function unhandledRejectionsDuring(action: () => unknown): Promise { + const rejections: unknown[] = [] + const listener = (reason: unknown) => rejections.push(reason) + process.on('unhandledRejection', listener) + try { + await action() + await new Promise(resolve => setImmediate(resolve)) + } finally { + process.removeListener('unhandledRejection', listener) + } + return rejections +} From 6ff701cd044a8f325135572b362617fd58c5b5b8 Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Wed, 18 Nov 2026 03:26:33 +0000 Subject: [PATCH 2/3] fix(amazonq): log a background code symbol update failure that has no string form The agentic chat controller formats the failure of its background code symbol update with formatErr, so a reason with no string form is logged too. A reason that cannot be formatted is dropped instead of becoming an unhandled rejection. The insert notification test of the older chat server now makes the document read of the controller fail. --- .../agenticChat/agenticChatController.test.ts | 27 +++++++++++++++++++ .../agenticChat/agenticChatController.ts | 6 ++++- .../language-server/chat/qChatServer.test.ts | 25 +++++++++-------- 3 files changed, 46 insertions(+), 12 deletions(-) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts index 877d194cf0..8c8e154ec3 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts @@ -2280,6 +2280,33 @@ describe('AgenticChatController', () => { sinon.match('Error initializing context commands') ) }) + + it('logs a failed background code symbol update whose reason has no string form', async () => { + const maybeUpdateCodeSymbolsStub = ContextCommandsProvider.prototype + .maybeUpdateCodeSymbols as sinon.SinonStub + maybeUpdateCodeSymbolsStub.rejects(Object.create(null)) + + await unhandledRejectionsDuring(() => chatController.onReady()) + + sinon.assert.calledWithMatch( + testFeatures.logging.log as sinon.SinonStub, + sinon.match('Error updating code symbols') + ) + }) + + it('leaves no unhandled rejection when a failed background code symbol update cannot be logged', async () => { + const maybeUpdateCodeSymbolsStub = ContextCommandsProvider.prototype + .maybeUpdateCodeSymbols as sinon.SinonStub + // JSON serialization, which formatErr uses, throws a TypeError on a bigint + maybeUpdateCodeSymbolsStub.rejects(10n) + + const rejections = await unhandledRejectionsDuring(() => chatController.onReady()) + + assert.ok( + !rejections.some(reason => reason instanceof TypeError && reason.message.includes('BigInt')), + 'the failure to log the update was left as an unhandled rejection' + ) + }) }) describe('onInlineChatPrompt', () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts index 0c9210ee20..3f3b3030ef 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts @@ -4537,7 +4537,11 @@ export class AgenticChatController implements ChatHandlers { await this.#contextCommandsProvider.processContextCommandUpdate(contextItems) // This update runs in the background, so its failure must be handled here, not by the catch below this.#contextCommandsProvider.maybeUpdateCodeSymbols().catch(error => { - this.#log('Error updating code symbols for context commands: ' + error) + try { + this.#log(`Error updating code symbols for context commands: ${loggingUtils.formatErr(error)}`) + } catch { + // A failure that cannot be formatted must not become an unhandled rejection + } }) } catch (error) { this.#contextCommandsProvider.setFilesAndFoldersFailed(true) diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts index 12515da28c..52472df697 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/qChatServer.test.ts @@ -176,23 +176,26 @@ describe('QChatServer', () => { ) }) - it('logs an insert notification whose code is not a string', async () => { + it('logs a failure of the controller insert handler with the method name', async () => { + const failure = new Error('document read failed') + testFeatures.workspace.getTextDocument = sinon.stub() + testFeatures.workspace.getTextDocument.rejects(failure) const handler = testFeatures.chat.onCodeInsertToCursorPosition.firstCall.firstArg - handler({ - tabId: mockTabId, - textDocument: { uri: 'file:///insert-check.ts' }, - cursorPosition: { line: 0, character: 0 }, - code: 123, + const rejections = await unhandledRejectionsDuring(async () => { + handler({ + tabId: mockTabId, + textDocument: { uri: 'file:///insert-check.ts' }, + cursorPosition: { line: 0, character: 0 }, + code: 'const a = 1', + }) + await new Promise(resolve => setImmediate(resolve)) }) - await new Promise(resolve => setImmediate(resolve)) + assert.ok(!rejections.includes(failure), 'the insert failure was left as an unhandled rejection') sinon.assert.calledWithMatch( testFeatures.logging.error as sinon.SinonStub, - sinon - .match(insertToCursorPositionNotificationType.method) - .and(sinon.match('TypeError')) - .and(sinon.match('is not a function')) + sinon.match(insertToCursorPositionNotificationType.method).and(sinon.match('document read failed')) ) }) }) From d08c9f12fe9f4de0d901e80eb09e853cdcc1b56e Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Thu, 19 Nov 2026 17:51:51 +0000 Subject: [PATCH 3/3] fix(amazonq): do not create a file for a rule request with no workspace folder open A rule is a file in the rules folder of the first workspace folder. With no workspace folder open, onCreatePrompt now logs a warning and shows a message that asks for a folder, and writes no file. Before, it fell through to the saved prompt write, which emptied a saved prompt with the same name. Updates the controller and server tests for the new behavior. --- .../agenticChat/agenticChatController.test.ts | 13 ++++++-- .../agenticChat/agenticChatController.ts | 32 +++++++++++-------- .../agenticChat/qAgenticChatServer.test.ts | 7 ++-- 3 files changed, 34 insertions(+), 18 deletions(-) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts index 8c8e154ec3..187400e2a3 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts @@ -2232,13 +2232,20 @@ describe('AgenticChatController', () => { sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) }) - it('creates a saved prompt file when a rule is requested with no workspace folder open', async () => { + it('creates no file and asks for a folder when a rule is requested with no workspace folder open', async () => { sinon.stub(workspaceUtils, 'getWorkspaceFolderPaths').returns([]) - const expectedPath = path.join(getUserPromptsDirectory(), `testRule${promptFileExtension}`) + const showMessageStub = sinon.stub().resolves() + testFeatures.lsp.window.showMessage = showMessageStub await chatController.onCreatePrompt({ promptName: 'testRule', isRule: true }) - sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) + sinon.assert.neverCalledWith(testFeatures.workspace.fs.mkdir as sinon.SinonStub, getUserPromptsDirectory()) + sinon.assert.notCalled(fsWriteFileStub) + sinon.assert.notCalled(testFeatures.lsp.window.showDocument as sinon.SinonStub) + sinon.assert.calledOnceWithExactly(showMessageStub, { + type: MessageType.Warning, + message: 'Open a folder to create a rule.', + }) }) it('creates a rule file in the rules folder of the first workspace folder', async () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts index 3f3b3030ef..7e1bcb4547 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts @@ -766,21 +766,27 @@ export class AgenticChatController implements ChatHandlers { async onCreatePrompt(params: CreatePromptParams): Promise { if (params.isRule) { - let workspaceFolders = workspaceUtils.getWorkspaceFolderPaths(this.#features.workspace) - // Rules live in a workspace folder. With no folder open, the request creates a saved prompt below. - if (workspaceFolders.length > 0) { - const workspaceRulesDirectory = path.join(workspaceFolders[0], '.amazonq', 'rules') - const newFilePath = getNewRuleFilePath(params.promptName, workspaceRulesDirectory) - const newFileContent = '' - try { - await this.#features.workspace.fs.mkdir(workspaceRulesDirectory, { recursive: true }) - await this.#features.workspace.fs.writeFile(newFilePath, newFileContent, { mode: 0o600 }) - await this.#features.lsp.window.showDocument({ uri: URI.file(newFilePath).toString() }) - } catch (e) { - this.#features.logging.warn(`Error creating rule file: ${e}`) - } + const workspaceFolders = workspaceUtils.getWorkspaceFolderPaths(this.#features.workspace) + // A rule is a file in the rules folder of the first workspace folder, so it needs an open folder. + if (workspaceFolders.length === 0) { + this.#features.logging.warn('Not creating a rule: no workspace folder is open') + await this.#features.lsp.window.showMessage({ + type: MessageType.Warning, + message: 'Open a folder to create a rule.', + }) return } + const workspaceRulesDirectory = path.join(workspaceFolders[0], '.amazonq', 'rules') + const newFilePath = getNewRuleFilePath(params.promptName, workspaceRulesDirectory) + const newFileContent = '' + try { + await this.#features.workspace.fs.mkdir(workspaceRulesDirectory, { recursive: true }) + await this.#features.workspace.fs.writeFile(newFilePath, newFileContent, { mode: 0o600 }) + await this.#features.lsp.window.showDocument({ uri: URI.file(newFilePath).toString() }) + } catch (e) { + this.#features.logging.warn(`Error creating rule file: ${e}`) + } + return } const newFilePath = getNewPromptFilePath(params.promptName) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts index 7e5bcf0c42..1080c4abe3 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/qAgenticChatServer.test.ts @@ -245,8 +245,10 @@ describe('QAgenticChatServer', () => { ) }) - it('creates a saved prompt when a rule is requested with no workspace folder open', async () => { + it('shows a message and creates no saved prompt when a rule is requested with no workspace folder open', async () => { testFeatures.workspace.getAllWorkspaceFolders.returns([]) + const showMessageStub = sinon.stub().resolves() + testFeatures.lsp.window.showMessage = showMessageStub const handler = testFeatures.chat.onCreatePrompt.firstCall.firstArg handler({ promptName: 'no-folder-rule', isRule: true }) @@ -256,10 +258,11 @@ describe('QAgenticChatServer', () => { testFeatures.logging.error as sinon.SinonStub, sinon.match(createPromptNotificationType.method) ) - sinon.assert.calledWithMatch( + sinon.assert.neverCalledWithMatch( testFeatures.workspace.fs.writeFile as sinon.SinonStub, sinon.match(/no-folder-rule\.md$/) ) + sinon.assert.calledOnce(showMessageStub) }) }) })