fix(server): image process error handle (#15820)

#### PR Dependency Tree


* **PR #15820** 👈

This tree was auto-generated by
[Charcoal](https://github.com/danerwilliams/charcoal)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved image handling in AI conversations: supported images are
resized and sent as WebP, with transparency preserved.
* Image attachments that can’t be loaded or encoded now report an error
instead of being silently omitted.
* Invalid image uploads now receive clearer error messages, while
unrelated processing errors retain their original details.
* Copilot message errors now surface more directly, while missing or
inaccessible sessions continue to be reported as unavailable.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
DarkSky authored and GitHub committed 2026-11-10 18:49:03 +08:00
1 parent 63297bca34
commit 5aa30aa7fa
10 files changed
+408 -165

No files matched your search

+126 -69
View File
@@ -35,7 +35,6 @@ impl Task for AsyncProcessImageTask {
fn compute(&mut self) -> Result<Self::Output> {
process_image_inner(&self.input, self.max_edge, self.keep_exif)
.map_err(|error| Error::new(Status::InvalidArg, error.to_string()))
}
fn resolve(&mut self, _: Env, output: Self::Output) -> Result<Self::JsValue> {
@@ -52,26 +51,30 @@ pub fn process_image(input: Buffer, max_edge: u32, keep_exif: bool) -> AsyncTask
})
}
fn process_image_inner(input: &[u8], max_edge: u32, keep_exif: bool) -> AnyResult<Vec<u8>> {
fn process_image_inner(input: &[u8], max_edge: u32, keep_exif: bool) -> Result<Vec<u8>> {
if max_edge == 0 {
bail!("max_edge must be greater than 0");
return Err(Error::new(Status::InvalidArg, "max_edge must be greater than 0"));
}
let format = image::guess_format(input).context("unsupported image format")?;
let (width, height) = read_dimensions(input, format)?;
validate_dimensions(width, height)?;
let mut image = decode_image(input, format)?;
let orientation = read_orientation(input, format)?;
let invalid_input = |error: anyhow::Error| Error::new(Status::InvalidArg, error.to_string());
let format = image::guess_format(input)
.context("unsupported image format")
.map_err(invalid_input)?;
let (width, height) = read_dimensions(input, format).map_err(invalid_input)?;
validate_dimensions(width, height).map_err(invalid_input)?;
let mut image = decode_image(input, format).map_err(invalid_input)?;
let orientation = read_orientation(input, format).map_err(invalid_input)?;
image.apply_orientation(orientation);
if image.width().max(image.height()) > max_edge {
image = image.resize(max_edge, max_edge, FilterType::Lanczos3);
}
let mut output = encode_webp_lossy(&image.into_rgba8())?;
let mut output =
encode_webp_lossy(&image.into_rgba8()).map_err(|error| Error::new(Status::GenericFailure, error.to_string()))?;
if keep_exif {
preserve_exif(input, format, &mut output)?;
preserve_exif(input, format, &mut output).map_err(|error| Error::new(Status::GenericFailure, error.to_string()))?;
}
Ok(output)
@@ -129,13 +132,17 @@ fn decode_image(input: &[u8], format: ImageFormat) -> AnyResult<DynamicImage> {
}
ImageFormat::WebP => {
let decoder = WebPDecoder::new(Cursor::new(input)).context("failed to decode image")?;
let frame = decoder
.into_frames()
.next()
.transpose()
.context("failed to decode image")?
.context("image does not contain any frames")?;
DynamicImage::ImageRgba8(frame.into_buffer())
if decoder.has_animation() {
let frame = decoder
.into_frames()
.next()
.transpose()
.context("failed to decode image")?
.context("image does not contain any frames")?;
DynamicImage::ImageRgba8(frame.into_buffer())
} else {
DynamicImage::from_decoder(decoder).context("failed to decode image")?
}
}
_ => {
let reader = ImageReader::with_format(Cursor::new(input), format);
@@ -254,12 +261,15 @@ fn map_exif_file_type(format: ImageFormat) -> Option<FileExtension> {
#[cfg(test)]
mod tests {
use image::{ExtendedColorType, GenericImageView, ImageEncoder, codecs::png::PngEncoder};
use image::{
ExtendedColorType, GenericImageView, ImageEncoder,
codecs::{png::PngEncoder, webp::WebPEncoder},
};
use super::*;
fn encode_png(width: u32, height: u32) -> Vec<u8> {
let image = image::RgbaImage::from_pixel(width, height, image::Rgba([255, 0, 0, 255]));
fn encode_png(width: u32, height: u32, alpha: u8) -> Vec<u8> {
let image = image::RgbaImage::from_pixel(width, height, image::Rgba([255, 0, 0, alpha]));
let mut encoded = Vec::new();
PngEncoder::new(&mut encoded)
.write_image(image.as_raw(), width, height, ExtendedColorType::Rgba8)
@@ -289,65 +299,112 @@ mod tests {
}
#[test]
fn process_image_keeps_small_dimensions() {
let png = encode_png(8, 6);
let output = process_image_inner(&png, 512, false).unwrap();
fn process_image_decodes_and_resizes_images() {
// Two lossless 2x2 frames (red, blue), generated locally with img2webp.
let animated_webp = vec![
0x52, 0x49, 0x46, 0x46, 0x84, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38, 0x58, 0x0a, 0x00, 0x00,
0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x41, 0x4e, 0x49, 0x4d, 0x06, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x41, 0x4e, 0x4d, 0x46, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x64, 0x00, 0x00, 0x02, 0x56, 0x50, 0x38, 0x4c, 0x0f, 0x00, 0x00, 0x00,
0x2f, 0x01, 0x40, 0x00, 0x00, 0x07, 0x10, 0xfd, 0x8f, 0xfe, 0x07, 0x22, 0xa2, 0xff, 0x01, 0x00, 0x41, 0x4e, 0x4d,
0x46, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x64, 0x00,
0x00, 0x00, 0x56, 0x50, 0x38, 0x4c, 0x0f, 0x00, 0x00, 0x00, 0x2f, 0x01, 0x40, 0x00, 0x00, 0x07, 0x10, 0xd1, 0xff,
0xfe, 0x07, 0x22, 0xa2, 0xff, 0x01, 0x00,
];
assert!(WebPDecoder::new(Cursor::new(&animated_webp)).unwrap().has_animation());
let mut inputs = vec![("animated WebP", animated_webp, (2, 2), 255)];
for (width, height) in [(8, 6), (32, 8)] {
for alpha in [255, 96] {
let png = encode_png(width, height, alpha);
let rgba = image::load_from_memory(&png).unwrap().into_rgba8();
let mut lossless = Vec::new();
WebPEncoder::new_lossless(&mut lossless)
.write_image(rgba.as_raw(), width, height, ExtendedColorType::Rgba8)
.unwrap();
let lossy = process_image_inner(&png, 1536, true).unwrap();
for (name, input) in [("PNG", png), ("lossless WebP", lossless), ("lossy WebP", lossy)] {
inputs.push((name, input, (width, height), alpha));
}
}
}
let format = image::guess_format(&output).unwrap();
assert_eq!(format, ImageFormat::WebP);
let decoded = image::load_from_memory(&output).unwrap();
assert_eq!(decoded.dimensions(), (8, 6));
}
#[test]
fn process_image_scales_down_large_dimensions() {
let png = encode_png(1024, 256);
let output = process_image_inner(&png, 512, false).unwrap();
let decoded = image::load_from_memory(&output).unwrap();
assert_eq!(decoded.dimensions(), (512, 128));
for (name, input, (width, height), alpha) in inputs {
let resized = if width > 4 {
(4, 4 * height / width)
} else {
(width, height)
};
for (max_edge, dimensions) in [(512, (width, height)), (4, resized)] {
for keep_exif in [false, true] {
let mut output = input.clone();
for _ in 0..2 {
output = process_image_inner(&output, max_edge, keep_exif)
.unwrap_or_else(|error| panic!("{name}, max_edge={max_edge}, keep_exif={keep_exif}: {error}"));
assert_eq!(image::guess_format(&output).unwrap(), ImageFormat::WebP);
let decoded = image::load_from_memory(&output).unwrap();
assert_eq!(decoded.dimensions(), dimensions);
let pixel = decoded.to_rgba8()[(0, 0)];
assert_eq!(pixel[3], alpha);
assert!(pixel[0] > pixel[2], "expected the red first frame");
}
}
}
}
}
#[test]
fn process_image_preserves_exif_without_orientation() {
let png = encode_png(8, 8);
let mut png_with_exif = png.clone();
let mut metadata = Metadata::new();
metadata.set_tag(ExifTag::ImageDescription("copilot".to_string()));
metadata.set_tag(ExifTag::Orientation(vec![6]));
metadata
.write_to_vec(&mut png_with_exif, FileExtension::PNG { as_zTXt_chunk: true })
.unwrap();
let png = encode_png(8, 8, 255);
let webp = process_image_inner(&encode_png(8, 6, 96), 512, false).unwrap();
for (mut output, format, dimensions) in [
(png, FileExtension::PNG { as_zTXt_chunk: true }, (8, 8)),
(webp, FileExtension::WEBP, (6, 8)),
] {
let mut metadata = Metadata::new();
metadata.set_tag(ExifTag::ImageDescription("copilot".to_string()));
metadata.set_tag(ExifTag::Orientation(vec![6]));
metadata.write_to_vec(&mut output, format).unwrap();
let output = process_image_inner(&png_with_exif, 512, true).unwrap();
let decoded_metadata = Metadata::new_from_vec(&output, FileExtension::WEBP).unwrap();
for _ in 0..2 {
output = process_image_inner(&output, 512, true).unwrap();
assert_eq!(image::load_from_memory(&output).unwrap().dimensions(), dimensions);
let decoded_metadata = Metadata::new_from_vec(&output, FileExtension::WEBP).unwrap();
assert!(
decoded_metadata
.get_tag(&ExifTag::ImageDescription(String::new()))
.next()
.is_some()
);
assert!(
decoded_metadata
.get_tag(&ExifTag::Orientation(vec![1]))
.next()
.is_none()
);
assert!(
decoded_metadata
.get_tag(&ExifTag::ImageDescription(String::new()))
.next()
.is_some()
);
assert!(
decoded_metadata
.get_tag(&ExifTag::Orientation(vec![1]))
.next()
.is_none()
);
}
}
}
#[test]
fn process_image_rejects_invalid_input() {
let error = process_image_inner(b"not-an-image", 512, false).unwrap_err();
assert_eq!(error.to_string(), "unsupported image format");
}
#[test]
fn process_image_rejects_images_over_dimension_limit_before_decode() {
let bmp = encode_bmp_header(MAX_IMAGE_DIMENSION + 1, 1);
let error = process_image_inner(&bmp, 512, false).unwrap_err();
assert_eq!(error.to_string(), "image dimensions exceed limit");
let png = encode_png(8, 6, 255);
for (input, max_edge, message) in [
(b"not-an-image".to_vec(), 512, "unsupported image format"),
(png.clone(), 0, "max_edge must be greater than 0"),
(png[..40].to_vec(), 512, "failed to decode image"),
(
encode_bmp_header(MAX_IMAGE_DIMENSION + 1, 1),
512,
"image dimensions exceed limit",
),
(encode_bmp_header(10_000, 4_001), 512, "image pixel count exceeds limit"),
] {
let error = process_image_inner(&input, max_edge, false).unwrap_err();
assert_eq!(error.status, Status::InvalidArg);
assert_eq!(error.reason, message);
}
assert!(validate_dimensions(MAX_IMAGE_DIMENSION, 1).is_ok());
assert!(validate_dimensions(8_000, 5_000).is_ok());
}
}
@@ -219,7 +219,7 @@ mod tests {
});
assert_eq!(matches!(decision, RouteDecision::Ready(_)), ready);
}
let profiles = vec![profile("vendor/opaque", ModelOutput::Text)];
let profiles = [profile("vendor/opaque", ModelOutput::Text)];
for (profiles, expected_byok) in [(&profiles[..], true), (&[][..], false)] {
let decision = decide(RoutePolicyInput {
slot: &slot,
@@ -1,6 +1,8 @@
import '../../plugins/copilot';
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import {
createCopilotMessageMutation,
@@ -16,8 +18,10 @@ import ava from 'ava';
import { ServerFeature, ServerService } from '../../core';
import { Models } from '../../models';
import { processImage } from '../../native';
import { McpCredentialService } from '../../plugins/copilot/mcp/credential';
import { WorkspaceMcpProvider } from '../../plugins/copilot/mcp/provider';
import { CopilotStorage } from '../../plugins/copilot/storage';
import { installMockCopilotRuntime } from '../mocks';
import { createTestingApp, createWorkspace, type TestingApp } from '../utils';
import {
@@ -196,6 +200,60 @@ test('session, message, local context restriction and durable history share one
},
});
const webp = await processImage(
readFileSync(resolve(process.cwd(), '../../../tests/fixtures/blue.png')),
1536,
true
);
const normalized = await processImage(webp, 1536, true);
const { createCopilotMessage: imageMessage } = await app.gql({
query: createCopilotMessageMutation,
variables: {
options: {
sessionId,
content: 'Translate the document containing this image.',
blobs: [
new File([new Uint8Array(webp)], 'image.webp', {
type: 'image/webp',
}),
],
},
},
});
t.truthy(imageMessage);
const imageKey = createHash('sha256').update(normalized).digest('base64url');
const imageRead = await app
.GET(
app
.get(CopilotStorage)
.sessionAttachmentUrl(sessionId, workspace.id, imageKey, 'image.webp')
)
.expect(200);
t.is(imageRead.headers['content-type'], 'image/webp');
t.deepEqual(imageRead.body, normalized);
const invalidImage = await app
.POST('/graphql')
.set('x-operation-name', createCopilotMessageMutation.op)
.field(
'operations',
JSON.stringify({
query: createCopilotMessageMutation.query,
variables: {
options: { sessionId, content: 'Invalid image', blobs: [null] },
},
})
)
.field('map', JSON.stringify({ '0': ['variables.options.blobs.0'] }))
.attach('0', Buffer.from('RIFF\u0000\u0000\u0000\u0000WEBPbroken'), {
filename: 'invalid.webp',
contentType: 'image/webp',
})
.expect(200);
t.is(invalidImage.body.errors?.[0]?.extensions.status, 400);
t.is(invalidImage.body.errors?.[0]?.extensions.name, 'BAD_REQUEST');
t.regex(invalidImage.body.errors?.[0]?.message, /^Invalid image:/);
const localWorkspaceId = randomUUID();
const localSessionId = await createCopilotSession(
app,
@@ -1,12 +1,8 @@
import { createHash } from 'node:crypto';
import { BadRequestException, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import {
type FileUpload,
ImageFormatNotSupported,
sniffMime,
} from '../../../base';
import { BadRequest, type FileUpload, sniffMime } from '../../../base';
import { processImage } from '../../../native';
import { CopilotAccessService, type CopilotScopeMode } from '../access';
import { CompatSubmissionStore } from '../compat/submission-store';
@@ -58,7 +54,7 @@ export class ConversationInboxService {
? session.config.focus.selectors.length > 0
: Array.isArray(focusSelectors) && focusSelectors.length > 0);
if (hasWorkspaceContext && mode !== 'canonical') {
throw new BadRequestException(
throw new BadRequest(
"Local workspaces don't support attachments or references."
);
}
@@ -81,8 +77,15 @@ export class ConversationInboxService {
true
);
attachmentMimeType = 'image/webp';
} catch {
throw new ImageFormatNotSupported({ format: detectedMime });
} catch (error) {
if (
error instanceof Error &&
'code' in error &&
error.code === 'InvalidArg'
) {
throw new BadRequest(`Invalid image: ${error.message}`);
}
throw error;
}
}
@@ -99,7 +102,7 @@ export class ConversationInboxService {
[options.sessionId]
);
if (terminalMode !== 'canonical') {
throw new BadRequestException(
throw new BadRequest(
"Local workspaces don't support attachments or references."
);
}
@@ -17,7 +17,6 @@ import GraphQLUpload from 'graphql-upload/GraphQLUpload.mjs';
import {
CallMetric,
CopilotDocNotFound,
CopilotFailedToCreateMessage,
CopilotSessionNotFound,
type FileUpload,
paginate,
@@ -882,32 +881,28 @@ export class CopilotResolver {
if (!lock) {
throw new TooManyRequest('Server is busy');
}
try {
const scope = await this.chatSession.getOwnedScope(
options.sessionId,
user.id
);
if (!scope) throw new CopilotSessionNotFound();
const mode = await this.access.sessionResource(
{
userId: user.id,
workspaceId: scope.workspaceId,
docId: scope.docId,
action: scope.docId ? 'Doc.Update' : 'Workspace.Copilot',
},
[options.sessionId]
);
const resolved = await this.chatSession.getInScope({
sessionId: options.sessionId,
const scope = await this.chatSession.getOwnedScope(
options.sessionId,
user.id
);
if (!scope) throw new CopilotSessionNotFound();
const mode = await this.access.sessionResource(
{
userId: user.id,
workspaceId: scope.workspaceId,
personal: mode === 'personal',
});
if (!resolved) throw new CopilotSessionNotFound();
return await this.inbox.createMessage(user.id, options, resolved, mode);
} catch (e: any) {
throw new CopilotFailedToCreateMessage(e.message);
}
docId: scope.docId,
action: scope.docId ? 'Doc.Update' : 'Workspace.Copilot',
},
[options.sessionId]
);
const resolved = await this.chatSession.getInScope({
sessionId: options.sessionId,
userId: user.id,
workspaceId: scope.workspaceId,
personal: mode === 'personal',
});
if (!resolved) throw new CopilotSessionNotFound();
return await this.inbox.createMessage(user.id, options, resolved, mode);
}
private transformToSessionType(session: Omit<ChatHistory, 'messages'>) {
@@ -34,14 +34,15 @@ export type ToImageOptions = TextToTextOptions & {
seed?: string;
};
async function resizeImage(blob: Blob | File): Promise<Blob | null> {
async function resizeImage(blob: Blob | File): Promise<Blob> {
let src = '';
try {
src = URL.createObjectURL(blob);
const img = new Image();
img.src = src;
await new Promise(resolve => {
img.onload = resolve;
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error('Unable to load image attachment.'));
img.src = src;
});
const canvas = document.createElement('canvas');
@@ -50,24 +51,30 @@ async function resizeImage(blob: Blob | File): Promise<Blob | null> {
canvas.height = Math.floor(img.height * scale);
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return await new Promise(resolve =>
canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.8)
);
if (!ctx) {
throw new Error('Unable to prepare image attachment.');
}
} catch (e) {
console.error(e);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return await new Promise<Blob>((resolve, reject) =>
canvas.toBlob(
blob =>
blob
? resolve(blob)
: reject(new Error('Unable to encode image attachment.')),
'image/webp',
0.8
)
);
} finally {
if (src) URL.revokeObjectURL(src);
}
return null;
}
function jpegFileName(name: string) {
function imageFileName(name: string, mimeType: string) {
const stem = name.replace(/\.[^./\\]+$/, '');
return `${stem || 'image'}.jpg`;
const extension = mimeType.slice('image/'.length);
return `${stem || 'image'}.${extension}`;
}
interface CreateMessageOptions {
@@ -102,26 +109,26 @@ async function createMessage({
attachment => typeof attachment === 'string'
) as [string[], (Blob | File)[]];
options.attachments = stringAttachments;
options.blobs = (
await Promise.all(
blobs.map(async blob => {
const file = blob.type.startsWith('image/')
? await resizeImage(blob)
: blob;
if (!file) return null;
const resized = file !== blob;
return new File(
[file],
resized
? jpegFileName(blob instanceof File ? blob.name : sessionId)
: blob instanceof File
? blob.name
: sessionId,
{ type: file.type }
);
})
)
).filter(Boolean) as File[];
options.blobs = await Promise.all(
blobs.map(async blob => {
const file = blob.type.startsWith('image/')
? await resizeImage(blob)
: blob;
const resized = file !== blob;
return new File(
[file],
resized
? imageFileName(
blob instanceof File ? blob.name : sessionId,
file.type
)
: blob instanceof File
? blob.name
: sessionId,
{ type: file.type }
);
})
);
}
return await client.createMessage(options, { timeout, signal });
@@ -120,7 +120,7 @@ async function drainActionResult(
await drain(stream as AsyncIterable<unknown>);
}
describe('runtime request transport BYOK local lease handling', () => {
describe('runtime request transport preparation and cancellation', () => {
beforeEach(() => {
vi.stubGlobal('BUILD_CONFIG', { isElectron: true });
electronApis.byokStorage = {
@@ -139,21 +139,55 @@ describe('runtime request transport BYOK local lease handling', () => {
};
});
test('fails closed when local BYOK providers exist but lease creation fails', async () => {
test.each([
{ failure: 'local BYOK lease', image: false },
{ failure: 'image decoding', image: true },
])('does not generate when $failure fails', async ({ image }) => {
const client = createClient({
gql: vi.fn().mockRejectedValue(new Error('mutation failed')),
});
const result = textToText({
client,
sessionId: 'session-1',
workspaceId: 'workspace-1',
content: 'hello',
}) as Promise<string>;
await expect(result).rejects.toThrow('mutation failed');
await expect(result).rejects.toBeInstanceOf(UserFriendlyError);
expect(client.chatTextStream).not.toHaveBeenCalled();
const originalImage = globalThis.Image;
const objectUrl = image
? vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:invalid-image')
: undefined;
const revokeUrl = image ? vi.spyOn(URL, 'revokeObjectURL') : undefined;
if (image) {
vi.stubGlobal(
'Image',
class {
onerror?: () => void;
set src(_value: string) {
this.onerror?.();
}
}
);
}
try {
const result = textToText({
client,
sessionId: 'session-1',
workspaceId: 'workspace-1',
content: 'hello',
attachments: image
? [new File(['broken'], 'invalid.webp', { type: 'image/webp' })]
: undefined,
}) as Promise<string>;
await expect(result).rejects.toThrow(
image ? 'Unable to load image attachment.' : 'mutation failed'
);
if (image) {
expect(client.createMessage).not.toHaveBeenCalled();
expect(client.gql).not.toHaveBeenCalled();
expect(revokeUrl).toHaveBeenCalledWith('blob:invalid-image');
} else {
await expect(result).rejects.toBeInstanceOf(UserFriendlyError);
}
expect(client.chatTextStream).not.toHaveBeenCalled();
} finally {
if (image) vi.stubGlobal('Image', originalImage);
objectUrl?.mockRestore();
revokeUrl?.mockRestore();
}
});
test('does not create stream local BYOK lease after cancellation', async () => {
@@ -113,7 +113,7 @@ async function extractEdgelessSelected(
if (sourceId) {
const blob = await host.store.blobSync.get(sourceId);
if (blob) {
images.push(new File([blob], sourceId));
images.push(new File([blob], sourceId, { type: blob.type }));
}
}
} else if (element instanceof GfxPrimitiveElementModel) {
@@ -149,7 +149,7 @@ async function extractEdgelessSelected(
if (!blob) return null;
return {
images: [new File([blob], 'selected.png'), ...images],
images: [new File([blob], 'selected.png', { type: blob.type }), ...images],
snapshot: snapshot ? JSON.stringify(snapshot) : null,
combinedElementsMarkdown: markdown.length ? markdown : null,
attachments,
@@ -227,7 +227,7 @@ export const getSelectedImagesAsBlobs = async (host: EditorHost) => {
if (!sourceId) return null;
const blob = await host.store.blobSync.get(sourceId);
if (!blob) return null;
return new File([blob], sourceId);
return new File([blob], sourceId, { type: blob.type });
}) ?? []
);
return blobs.filter((blob): blob is File => !!blob);
@@ -1,3 +1,6 @@
import assert from 'node:assert/strict';
import { runPrisma } from '@affine-test/kit/utils/cloud';
import { expect } from '@playwright/test';
import { test } from '../base/base-test';
@@ -8,15 +11,101 @@ test.describe('AIAction/Translate', () => {
await utils.chatPanel.openChatPanel(page);
});
test('should support translating the selected content', async ({
loggedInPage: page,
utils,
}) => {
const { translate } = await utils.editor.askAIWithText(page, 'Apple');
const { answer, responses } = await translate('Simplified Chinese');
await expect(answer).toHaveText(/苹果/, { timeout: 10000 });
expect(responses).toEqual(new Set(['insert-below', 'replace-selection']));
});
for (const withImage of [false, true]) {
test(`should support translating the selected content${withImage ? ' with a WebP image' : ''}`, async ({
loggedInPage: page,
utils,
}) => {
await utils.editor.focusToEditor(page);
await page.keyboard.insertText('Apple');
if (withImage) {
await page.evaluate(() => {
delete window.showOpenFilePicker;
});
await page.keyboard.press('Enter');
const fileChooserPromise = page.waitForEvent('filechooser');
await page.keyboard.press('/');
await page.keyboard.insertText('image');
await page.locator('affine-slash-menu').getByTestId('Image').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles({
name: 'blue.webp',
mimeType: 'image/webp',
buffer: Buffer.from(
'UklGRl4AAABXRUJQVlA4WAoAAAAQAAAACwAACwAAQUxQSAoAAAABB1DAiAhERP8DVlA4IC4AAACQAQCdASoMAAwAAUAmJaACdLoAA5gA/vtV4/+lwf/S4P/pcH/pcH8bss4bpAAA',
'base64'
),
});
const image = page.locator('page-editor affine-page-image img');
await expect(image).toHaveJSProperty('naturalWidth', 12);
expect(
await image.evaluate(
async (img: HTMLImageElement) =>
(await (await fetch(img.src)).blob()).type
)
).toBe('image/webp');
await image.click();
}
await page.keyboard.press('ControlOrMeta+A');
await page.keyboard.press('ControlOrMeta+A');
await page.keyboard.press('ControlOrMeta+A');
const { translate } = await utils.editor.showAIMenu(page);
const streamRequest = page.waitForRequest(
request =>
new URL(request.url()).pathname.startsWith('/api/copilot/chat/') &&
new URL(request.url()).pathname.endsWith('/stream-object')
);
const { answer, responses } = await translate('Simplified Chinese');
const request = await streamRequest;
if (withImage) {
const sessionId = new URL(request.url()).pathname.split('/')[4];
const message = await runPrisma(prisma =>
prisma.aiSessionMessage.findFirst({
where: { sessionId, role: 'user' },
})
);
const attachments = message?.attachments;
expect(attachments).toEqual([
expect.objectContaining({
kind: 'url',
mimeType: 'image/webp',
fileName: expect.stringMatching(/\.webp$/),
}),
]);
assert(Array.isArray(attachments));
const attachment = attachments[0];
assert(
attachment &&
typeof attachment === 'object' &&
!Array.isArray(attachment)
);
assert(typeof attachment.url === 'string');
const url = new URL(attachment.url, page.url()).toString();
const downloaded = await page.request.get(url);
expect(downloaded.status()).toBe(200);
expect(downloaded.headers()['content-type']).toContain('image/webp');
const bytes = await downloaded.body();
expect(bytes.subarray(0, 4).toString()).toBe('RIFF');
expect(bytes.subarray(8, 12).toString()).toBe('WEBP');
expect(
await page.evaluate(async imageUrl => {
const blob = await (await fetch(imageUrl)).blob();
const image = await createImageBitmap(blob);
const canvas = new OffscreenCanvas(image.width, image.height);
const context = canvas.getContext('2d')!;
context.drawImage(image, 0, 0);
const alpha = context.getImageData(0, 0, 1, 1).data[3];
image.close();
return alpha;
}, url)
).toBe(128);
}
await expect(answer).toHaveText(/苹果/, { timeout: 10000 });
expect(responses).toEqual(new Set(['insert-below', 'replace-selection']));
});
}
test('should support translating the selected text block in edgeless', async ({
loggedInPage: page,