Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
* Will be deleted or merged.
*/

import * as crypto from 'crypto'

Check warning on line 6 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test (Windows)

Do not import Node.js builtin module "crypto"

Check warning on line 6 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test

Do not import Node.js builtin module "crypto"
import * as path from 'path'

Check warning on line 7 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test (Windows)

Do not import Node.js builtin module "path"

Check warning on line 7 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test

Do not import Node.js builtin module "path"
import * as os from 'os'

Check warning on line 8 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test (Windows)

Do not import Node.js builtin module "os"

Check warning on line 8 in server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts

View workflow job for this annotation

GitHub Actions / Test

Do not import Node.js builtin module "os"
import {
ChatTriggerType,
Origin,
Expand Down Expand Up @@ -766,20 +766,27 @@

async onCreatePrompt(params: CreatePromptParams): Promise<void> {
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)
Expand Down Expand Up @@ -4534,7 +4541,14 @@
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([])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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)
})
})
})
Loading
Loading