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..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 @@ -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,89 @@ describe('AgenticChatController', () => { sinon.assert.calledOnceWithExactly(fsWriteFileStub, expectedPath, '', { mode: 0o600 }) }) + + 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 showMessageStub = sinon.stub().resolves() + testFeatures.lsp.window.showMessage = showMessageStub + + await chatController.onCreatePrompt({ promptName: 'testRule', isRule: true }) + + 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 () => { + 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') + ) + }) + + 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 a23f31460b..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,20 +766,27 @@ 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') - if (workspaceFolders.length > 0) { - 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) @@ -4534,7 +4541,14 @@ 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 => { + 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) 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..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 @@ -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,103 @@ 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('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 }) + await new Promise(resolve => setImmediate(resolve)) + + sinon.assert.neverCalledWithMatch( + testFeatures.logging.error as sinon.SinonStub, + sinon.match(createPromptNotificationType.method) + ) + sinon.assert.neverCalledWithMatch( + testFeatures.workspace.fs.writeFile as sinon.SinonStub, + sinon.match(/no-folder-rule\.md$/) + ) + sinon.assert.calledOnce(showMessageStub) + }) + }) }) 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..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 @@ -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,83 @@ 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 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 + + 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)) + }) + + 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('document read failed')) + ) + }) + }) }) 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 +}