src/vs/workbench/contrib/chat/common/chatImageExtraction.ts
254 LOC · 244 covered · 10 uncovered · 54 ranges · 37 concepts · 26 introducers · 30 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
/*---------------------------------------------------------------------------------------------
chatImageExtraction.ts ×8
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { decodeBase64, VSBuffer } from '../../../../base/common/buffer.js';
import { IMarkdownString } from '../../../../base/common/htmlContent.js';
import { getExtensionForMimeType, getMediaMime } from '../../../../base/common/mime.js';
import { URI } from '../../../../base/common/uri.js';
import { localize } from '../../../../nls.js';
import { isLocation } from '../../../../editor/common/languages.js';
import { IChatResponseViewModel, IChatRequestViewModel, isRequestVM } from './model/chatViewModel.js';
import { ChatResponseResource } from './model/chatModel.js';
import { IChatContentInlineReference, IChatToolInvocation, IChatToolInvocationSerialized, IToolResultOutputDetailsSerialized } from './chatService/chatService.js';
import { isToolResultInputOutputDetails, isToolResultOutputDetails, IToolResultOutputDetails } from './tools/languageModelToolsService.js';
import { getExplicitFileOrImageAttachmentSummary, type IChatRequestVariableEntry, isImageVariableEntry } from './attachments/chatVariableEntries.js';
export interface IChatExtractedImage {
readonly id: string;
readonly uri: URI;
readonly name: string;
readonly mimeType: string;
readonly data: VSBuffer;
readonly source: string;
readonly caption: string | IMarkdownString | undefined;
}
export interface IChatExtractedImageCollection {
readonly id: string;
readonly title: string;
readonly images: IChatExtractedImage[];
}
/**
* Extract all images from a chat response's tool invocations and inline references.
* Tool invocation images are extracted from output details and message URIs.
* Inline reference images (file URIs) are read via the provided {@link readFile} callback.
*/
response: IChatResponseViewModel,
readFile: (uri: URI) => Promise<VSBuffer>,
): Promise<IChatExtractedImageCollection> {
const allImages: IChatExtractedImage[] = [];
for (const item of response.response.value) {
if (item.kind === 'toolInvocation' || item.kind === 'toolInvocationSerialized') {
chatImageExtraction.ts ×3
const images = extractImagesFromToolInvocationOutputDetails(item, response.sessionResource);
chatImageExtraction.ts ×4
allImages.push(...images);
const messageImages = await extractImagesFromToolInvocationMessages(item, readFile);
allImages.push(...messageImages);
if (image) {
}
// Use the corresponding user request as the carousel title
const request = response.session.getItems().find((item): item is IChatRequestViewModel => isRequestVM(item) && item.id === response.requestId);
const title = request ? request.messageText.trim() || getExplicitFileOrImageAttachmentSummary(request.variables) || localize('chatImageExtraction.defaultTitle', "Images") : localize('chatImageExtraction.defaultTitle', "Images");
return {
id: response.sessionResource.toString() + '_' + response.id,
title,
images: allImages,
};
}
export function extractImagesFromToolInvocationOutputDetails(toolInvocation: IChatToolInvocation | IChatToolInvocationSerialized, sessionResource: URI): IChatExtractedImage[] {
const resultDetails = IChatToolInvocation.resultDetails(toolInvocation);
const caption = toolInvocation.pastTenseMessage ?? toolInvocation.invocationMessage;
const pushImage = (mimeType: string, data: VSBuffer, outputIndex: number) => {
const permalinkBasename = ext ? `file${ext}` : 'file.bin';
const uri = ChatResponseResource.createUri(sessionResource, toolInvocation.toolCallId, outputIndex, permalinkBasename);
images.push({
id: `${toolInvocation.toolCallId}_${outputIndex}`,
uri,
name: localize('chatImageExtraction.imageName', "Image {0}", images.length + 1),
mimeType,
data,
source: localize('chatImageExtraction.toolSource', "Tool: {0}", toolInvocation.toolId),
caption,
});
};
if (isToolResultInputOutputDetails(resultDetails)) {
const outputItem = resultDetails.output[i];
if (outputItem.type === 'embed' && outputItem.mimeType?.startsWith('image/') && !outputItem.isText) {
pushImage(outputItem.mimeType, decodeBase64(outputItem.value), i);
}
}
}
if (output.mimeType?.startsWith('image/')) {
const data = getImageDataFromOutputDetails(resultDetails, toolInvocation);
chatImageExtraction.ts ×3
if (data) {
pushImage(output.mimeType, data, 0);
}
}
return images;
}
toolInvocation: IChatToolInvocation | IChatToolInvocationSerialized,
readFile: (uri: URI) => Promise<VSBuffer>
): Promise<IChatExtractedImage[]> {
// Use pastTenseMessage if available, otherwise fall back to invocationMessage.
// When pastTenseMessage exists it visually replaces invocationMessage in the UI,
// so we only look at its URIs — we don't fall back to invocationMessage URIs.
const message = toolInvocation.pastTenseMessage ?? toolInvocation.invocationMessage;
if (!message || typeof message === 'string' || !message.uris || Object.keys(message.uris).length === 0) {
}
const images: IChatExtractedImage[] = [];
for (const uriComponents of Object.values(message.uris)) {
const uri = URI.revive(uriComponents);
const mimeType = getMediaMime(uri.path);
if (mimeType?.startsWith('image/')) {
try {
data = await readFile(uri);
} catch {
}
images.push({
id: uri.toString(),
uri,
name,
mimeType,
data,
source: localize('chatImageExtraction.toolSource', "Tool: {0}", toolInvocation.toolId),
caption: message,
});
}
return images;
}
function getImageDataFromOutputDetails(resultDetails: IToolResultOutputDetails, toolInvocation: IChatToolInvocation | IChatToolInvocationSerialized): VSBuffer | undefined {
chatImageExtraction.ts ×3
if (toolInvocation.kind === 'toolInvocationSerialized') {
const serializedDetails = resultDetails as unknown as IToolResultOutputDetailsSerialized;
if (serializedDetails.output.base64Data) {
return decodeBase64(serializedDetails.output.base64Data);
}
return undefined;
} else {
return resultDetails.output.value;
}
part: IChatContentInlineReference,
readFile: (uri: URI) => Promise<VSBuffer>,
): Promise<IChatExtractedImage | undefined> {
const ref = part.inlineReference;
const refUri = URI.isUri(ref) ? ref : isLocation(ref) ? ref.uri : ref.location.uri;
const mime = getMediaMime(refUri.path);
if (!mime?.startsWith('image/')) {
}
let data: VSBuffer;
try {
data = await readFile(refUri);
} catch {
}
return {
id: refUri.toString(),
uri: refUri,
name,
mimeType: mime,
data,
source: localize('chatImageExtraction.inlineReference', "File"),
caption: undefined,
};
}
export function coerceImageBuffer(value: unknown): Uint8Array | undefined {
}
}
return undefined;
}
const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort((a, b) => Number(a) - Number(b));
if (keys.length === 0) {
return undefined;
}
const result = new Uint8Array(keys.length);
for (let index = 0; index < keys.length; index++) {
const byte = record[keys[index]];
if (keys[index] !== String(index) || typeof byte !== 'number' || !Number.isInteger(byte) || byte < 0 || byte > 255) {
}
}
return result;
}
/**
* Extract images from a chat request's variable attachments (user-attached images).
*/
export function extractImagesFromChatRequest(
): IChatExtractedImage[] {
return extractImagesFromChatVariables(request.variables);
}
export function extractImagesFromChatVariables(
): IChatExtractedImage[] {
const images: IChatExtractedImage[] = [];
for (const variable of variables) {
if (!isImageVariableEntry(variable)) {
continue;
}
if (!buffer) {
}
const mimeType = variable.mimeType ?? getMediaMime(variable.name) ?? 'image/png';
chatImageExtraction.ts ×6
const uri = variable.references?.[0]?.reference;
const imageUri = URI.isUri(uri) ? uri : URI.from({ scheme: 'data', path: `${variable.id}/${encodeURIComponent(variable.name)}` });
images.push({
id: imageUri.toString(),
uri: imageUri,
name: variable.name,
mimeType,
data: VSBuffer.wrap(buffer),
source: localize('chatImageExtraction.userAttachment', "Attachment"),
caption: undefined,
});
}
return images;
}