pi-mono/packages/coding-agent/src/utils/image-resize-worker.ts
David Brailovsky b30a6dd779 fix(coding-agent): ignore Node's own worker messages in image resize
Under `node --watch`, Node 24.19+ and 26.x post `{ "watch:require": [...] }`
on the worker message channel (nodejs/node#65044). The image resize code
treated the first message as the worker's reply, resolved it to `null`, and
dropped the image as "could not be resized below the inline image size limit".

Worker replies now carry a `type` marker, and the main thread ignores any
message without it. The reply type is now either a result or an error.

fixes #10527
2026-10-07 12:26:43 +02:00

43 lines
1.3 KiB
TypeScript

import { parentPort } from "node:worker_threads";
import {
IMAGE_RESIZE_WORKER_RESPONSE_TYPE,
type ImageResizeOptions,
type ResizeImageWorkerResponse,
resizeImageInProcess,
} from "./image-resize-core.ts";
interface ResizeImageWorkerRequest {
inputBytes: Uint8Array;
mimeType: string;
options?: ImageResizeOptions;
}
function isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {
if (!value || typeof value !== "object") return false;
const record = value as Record<string, unknown>;
return record.inputBytes instanceof Uint8Array && typeof record.mimeType === "string";
}
const port = parentPort;
if (!port) {
throw new Error("image resize worker requires parentPort");
}
port.once("message", (message: unknown) => {
void (async () => {
try {
if (!isResizeImageWorkerRequest(message)) {
throw new Error("Invalid image resize worker request");
}
const result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);
const response: ResizeImageWorkerResponse = { type: IMAGE_RESIZE_WORKER_RESPONSE_TYPE, result };
port.postMessage(response);
} catch (error) {
const response: ResizeImageWorkerResponse = {
type: IMAGE_RESIZE_WORKER_RESPONSE_TYPE,
error: error instanceof Error ? error.message : String(error),
};
port.postMessage(response);
}
})();
});