Path: blob/main/src/vs/workbench/contrib/chat/common/widget/annotations.ts
5220 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/4import { MarkdownString } from '../../../../../base/common/htmlContent.js';5import { basename } from '../../../../../base/common/resources.js';6import { URI } from '../../../../../base/common/uri.js';7import { IRange } from '../../../../../editor/common/core/range.js';8import { isLocation } from '../../../../../editor/common/languages.js';9import { IChatProgressRenderableResponseContent, IChatProgressResponseContent, appendMarkdownString, canMergeMarkdownStrings } from '../model/chatModel.js';10import { IChatAgentVulnerabilityDetails } from '../chatService/chatService.js';1112export const contentRefUrl = 'http://_vscodecontentref_'; // must be lowercase for URI1314export function annotateSpecialMarkdownContent(response: Iterable<IChatProgressResponseContent>): IChatProgressRenderableResponseContent[] {15let refIdPool = 0;1617const result: IChatProgressRenderableResponseContent[] = [];18for (const item of response) {19const previousItemIndex = result.findLastIndex(p => p.kind !== 'textEditGroup' && p.kind !== 'undoStop');20const previousItem = result[previousItemIndex];21if (item.kind === 'inlineReference') {22let label: string | undefined = item.name;23if (!label) {24if (URI.isUri(item.inlineReference)) {25label = basename(item.inlineReference);26} else if (isLocation(item.inlineReference)) {27label = basename(item.inlineReference.uri);28} else {29label = item.inlineReference.name;30}31}3233const refId = refIdPool++;34const printUri = URI.parse(contentRefUrl).with({ path: String(refId) });35const markdownText = `[${label}](${printUri.toString()})`;3637const annotationMetadata = { [refId]: item };3839if (previousItem?.kind === 'markdownContent') {40const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));41result[previousItemIndex] = { ...previousItem, content: merged, inlineReferences: { ...annotationMetadata, ...(previousItem.inlineReferences || {}) } };42} else {43result.push({ content: new MarkdownString(markdownText), inlineReferences: annotationMetadata, kind: 'markdownContent' });44}45} else if (item.kind === 'markdownContent' && previousItem?.kind === 'markdownContent' && canMergeMarkdownStrings(previousItem.content, item.content)) {46const merged = appendMarkdownString(previousItem.content, item.content);47result[previousItemIndex] = { ...previousItem, content: merged };48} else if (item.kind === 'markdownVuln') {49const vulnText = encodeURIComponent(JSON.stringify(item.vulnerabilities));50const markdownText = `<vscode_annotation details='${vulnText}'>${item.content.value}</vscode_annotation>`;51if (previousItem?.kind === 'markdownContent') {52// Since this is inside a codeblock, it needs to be merged into the previous markdown content.53const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));54result[previousItemIndex] = { ...previousItem, content: merged };55} else {56result.push({ content: new MarkdownString(markdownText), kind: 'markdownContent' });57}58} else if (item.kind === 'codeblockUri') {59if (previousItem?.kind === 'markdownContent') {60const isEditText = item.isEdit ? ` isEdit` : '';61const subAgentText = item.subAgentInvocationId ? ` subAgentInvocationId="${encodeURIComponent(item.subAgentInvocationId)}"` : '';62const markdownText = `<vscode_codeblock_uri${isEditText}${subAgentText}>${item.uri.toString()}</vscode_codeblock_uri>`;63const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));64// delete the previous and append to ensure that we don't reorder the edit before the undo stop containing it65result.splice(previousItemIndex, 1);66result.push({ ...previousItem, content: merged });67}68} else {69result.push(item);70}71}7273return result;74}7576export interface IMarkdownVulnerability {77readonly title: string;78readonly description: string;79readonly range: IRange;80}81export function extractCodeblockUrisFromText(text: string): { uri: URI; isEdit?: boolean; subAgentInvocationId?: string; textWithoutResult: string } | undefined {82const match = /<vscode_codeblock_uri( isEdit)?( subAgentInvocationId="([^"]*)")?>([\s\S]*?)<\/vscode_codeblock_uri>/ms.exec(text);83if (match) {84const [all, isEdit, , encodedSubAgentId, uriString] = match;85if (uriString) {86const result = URI.parse(uriString);87const textWithoutResult = text.substring(0, match.index) + text.substring(match.index + all.length);88let subAgentInvocationId: string | undefined;89if (encodedSubAgentId) {90try {91subAgentInvocationId = decodeURIComponent(encodedSubAgentId);92} catch {93subAgentInvocationId = encodedSubAgentId;94}95}96return { uri: result, textWithoutResult, isEdit: !!isEdit, subAgentInvocationId };97}98}99return undefined;100}101102export function extractSubAgentInvocationIdFromText(text: string): string | undefined {103const match = /<vscode_codeblock_uri[^>]* subAgentInvocationId="([^"]*)"/ms.exec(text);104if (match) {105try {106return decodeURIComponent(match[1]);107} catch {108return match[1];109}110}111return undefined;112}113114export function hasCodeblockUriTag(text: string): boolean {115return text.includes('<vscode_codeblock_uri');116}117118export function extractVulnerabilitiesFromText(text: string): { newText: string; vulnerabilities: IMarkdownVulnerability[] } {119const vulnerabilities: IMarkdownVulnerability[] = [];120let newText = text;121let match: RegExpExecArray | null;122while ((match = /<vscode_annotation details='(.*?)'>(.*?)<\/vscode_annotation>/ms.exec(newText)) !== null) {123const [full, details, content] = match;124const start = match.index;125const textBefore = newText.substring(0, start);126const linesBefore = textBefore.split('\n').length - 1;127const linesInside = content.split('\n').length - 1;128129const previousNewlineIdx = textBefore.lastIndexOf('\n');130const startColumn = start - (previousNewlineIdx + 1) + 1;131const endPreviousNewlineIdx = (textBefore + content).lastIndexOf('\n');132const endColumn = start + content.length - (endPreviousNewlineIdx + 1) + 1;133134try {135const vulnDetails: IChatAgentVulnerabilityDetails[] = JSON.parse(decodeURIComponent(details));136vulnDetails.forEach(({ title, description }) => vulnerabilities.push({137title, description, range: { startLineNumber: linesBefore + 1, startColumn, endLineNumber: linesBefore + linesInside + 1, endColumn }138}));139} catch (err) {140// Something went wrong with encoding this text, just ignore it141}142newText = newText.substring(0, start) + content + newText.substring(start + full.length);143}144145return { newText, vulnerabilities };146}147148149