Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 上传头像时把 HDR 图片转成真正的 SDR (#5975)

Dash7fd2a5698d2f
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/hlg-bt2100.png b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/hlg-bt2100.png
new file mode 100644
index 0000000000..552306c4dd
Binary files /dev/null and b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/hlg-bt2100.png differ
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/iso-gainmap.jpg b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/iso-gainmap.jpg
new file mode 100644
index 0000000000..94ffea6a67
Binary files /dev/null and b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/iso-gainmap.jpg differ
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/make-hdr-avatar-fixtures.swift b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/make-hdr-avatar-fixtures.swift
new file mode 100644
index 0000000000..2f9b93b516
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/make-hdr-avatar-fixtures.swift
@@ -0,0 +1,47 @@
+// Provenance of the HDR avatar fixtures used by hdrAvatarToSdr.test.ts.
+// The files are encoded by macOS ImageIO (not hand-built), so they carry the
+// real-world signalling: PNG cICP + ICC v4 cicp tags, and ISO 21496-1 gain maps.
+// Regenerate on macOS 15+:
+// swiftc -O make-hdr-avatar-fixtures.swift -o /tmp/make-hdr-avatar-fixtures
+// /tmp/make-hdr-avatar-fixtures "$PWD"
+import Foundation
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+
+let W = 256, H = 128
+// Linear extended sRGB scene: horizontal ramp 0 → 8x SDR white, top half neutral, bottom half warm.
+var px = [Float](repeating: 0, count: W * H * 4)
+for y in 0..<H { for x in 0..<W {
+ let v = Float(x) / Float(W - 1) * 8.0
+ let i = (y * W + x) * 4
+ if y < H / 2 { px[i] = v; px[i+1] = v; px[i+2] = v } else { px[i] = v; px[i+1] = v * 0.6; px[i+2] = v * 0.3 }
+ px[i+3] = 1
+}}
+let extLinear = CGColorSpace(name: CGColorSpace.extendedLinearSRGB)!
+let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.floatComponents.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
+let provider = CGDataProvider(data: Data(bytes: px, count: px.count * 4) as CFData)!
+let hdr = CGImage(width: W, height: H, bitsPerComponent: 32, bitsPerPixel: 128, bytesPerRow: W * 16, space: extLinear, bitmapInfo: info, provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!
+
+func convert(_ img: CGImage, to name: CFString, bits: Int) -> CGImage {
+ let cs = CGColorSpace(name: name)!
+ let bi: UInt32 = bits == 16 ? (CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder16Little.rawValue) : CGImageAlphaInfo.premultipliedLast.rawValue
+ let ctx = CGContext(data: nil, width: W, height: H, bitsPerComponent: bits, bytesPerRow: 0, space: cs, bitmapInfo: bi)!
+ ctx.draw(img, in: CGRect(x: 0, y: 0, width: W, height: H))
+ return ctx.makeImage()!
+}
+func write(_ img: CGImage, _ path: String, _ type: UTType, _ opts: [CFString: Any] = [:]) {
+ let url = URL(fileURLWithPath: path)
+ let dest = CGImageDestinationCreateWithURL(url as CFURL, type.identifier as CFString, 1, nil)!
+ CGImageDestinationAddImage(dest, img, opts as CFDictionary)
+ print(path, CGImageDestinationFinalize(dest))
+}
+let dir = CommandLine.arguments[1]
+let pq = convert(hdr, to: CGColorSpace.itur_2100_PQ, bits: 16)
+write(pq, "\(dir)/pq-bt2100.png", .png)
+let hlg = convert(hdr, to: CGColorSpace.itur_2100_HLG, bits: 16)
+write(hlg, "\(dir)/hlg-bt2100.png", .png)
+write(pq, "\(dir)/pq-bt2100.jpg", .jpeg, [kCGImageDestinationLossyCompressionQuality: 0.95])
+write(hdr, "\(dir)/iso-gainmap.jpg", .jpeg, [kCGImageDestinationEncodeRequest: kCGImageDestinationEncodeToISOGainmap, kCGImageDestinationLossyCompressionQuality: 0.95])
+// SDR rendition by ImageIO itself: Display P3 + sRGB transfer cICP (12/13), must stay untouched.
+write(hdr, "\(dir)/sdr-display-p3.png", .png, [kCGImageDestinationEncodeRequest: kCGImageDestinationEncodeToSDR])
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.jpg b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.jpg
new file mode 100644
index 0000000000..e4cb8001cd
Binary files /dev/null and b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.jpg differ
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.png b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.png
new file mode 100644
index 0000000000..8ada08d1d6
Binary files /dev/null and b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/pq-bt2100.png differ
diff --git a/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/sdr-display-p3.png b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/sdr-display-p3.png
new file mode 100644
index 0000000000..36a187ff56
Binary files /dev/null and b/apps/desktop/src/main/__tests__/fixtures/hdr-avatar/sdr-display-p3.png differ
diff --git a/apps/desktop/src/main/__tests__/hdrAvatarToSdr.test.ts b/apps/desktop/src/main/__tests__/hdrAvatarToSdr.test.ts
new file mode 100644
index 0000000000..145e09a9ff
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/hdrAvatarToSdr.test.ts
@@ -0,0 +1,499 @@
+/**
+ * hdrAvatarToSdr 单测:用 macOS ImageIO 真实编码的 HDR 夹具(PQ / HLG PNG、PQ JPEG、
+ * ISO 21496-1 增益图 JPEG,来源见 fixtures/hdr-avatar/make-hdr-avatar-fixtures.swift)
+ * 跑真实 sharp 转换,并对输出字节逐项断言:不再携带 HDR 信号,且像素确为 SDR 色调映射
+ * 结果。夹具场景为线性光水平渐变 0 → 8×SDR 白(x / 255 × 8),上半中性、下半暖色。
+ */
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { readFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import sharp from 'sharp';
+import { describe, expect, it } from 'vitest';
+import {
+ readIccCicp,
+ readPngHdrChunks,
+ toSdrAvatarImage,
+} from '../hdrAvatarToSdr';
+
+const fixture = (name: string) =>
+ readFileSync(path.join(__dirname, 'fixtures', 'hdr-avatar', name));
+
+const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+function pngChunk(type: string, data: Buffer): Buffer {
+ const body = Buffer.concat([Buffer.from(type, 'latin1'), data]);
+ let crc = 0xffffffff;
+ for (const byte of body) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
+ const out = Buffer.alloc(body.length + 8);
+ out.writeUInt32BE(data.length, 0);
+ body.copy(out, 4);
+ out.writeUInt32BE((crc ^ 0xffffffff) >>> 0, body.length + 4);
+ return out;
+}
+/** 在 IHDR 之后插入块(IHDR 固定占 8 + 25 字节)。 */
+function insertAfterIhdr(png: Buffer, ...chunks: Buffer[]): Buffer {
+ return Buffer.concat([png.subarray(0, 33), ...chunks, png.subarray(33)]);
+}
+function pngChunkTypes(png: Buffer): string[] {
+ const types: string[] = [];
+ for (let offset = 8; offset + 8 <= png.length;) {
+ const length = png.readUInt32BE(offset);
+ types.push(png.toString('latin1', offset + 4, offset + 8));
+ offset += 12 + length;
+ }
+ return types;
+}
+
+const PQ = (nits: number) => {
+ const m1 = 2610 / 16384,
+ m2 = (2523 / 4096) * 128;
+ const c1 = 3424 / 4096,
+ c2 = (2413 / 4096) * 32,
+ c3 = (2392 / 4096) * 32;
+ const y = Math.pow(nits / 10_000, m1);
+ return Math.pow((c1 + c2 * y) / (1 + c3 * y), m2);
+};
+
+/** 16-bit RGBA PQ(BT.709 原色)PNG,仅靠 cICP 块声明 HDR,不带 ICC。 */
+async function syntheticPqPng(
+ pixels: Array<{ nits: [number, number, number]; alpha: number }>,
+ options: { cicp?: [number, number, number, number]; cllNits?: number; orientation?: number } = {},
+) {
+ const raw = new Uint16Array(pixels.length * 4);
+ pixels.forEach(({ nits, alpha }, index) => {
+ raw.set([...nits.map((value) => Math.round(PQ(value) * 65535)), alpha], index * 4);
+ });
+ let encoder = sharp(raw, { raw: { width: pixels.length, height: 1, channels: 4 } }).toColourspace(
+ 'rgb16',
+ );
+ if (options.orientation) encoder = encoder.withMetadata({ orientation: options.orientation });
+ const png = await encoder.png().toBuffer();
+ const extra = [pngChunk('cICP', Buffer.from(options.cicp ?? [1, 16, 0, 1]))];
+ if (options.cllNits) {
+ const clli = Buffer.alloc(8);
+ clli.writeUInt32BE(options.cllNits * 10_000, 0);
+ extra.push(pngChunk('cLLI', clli));
+ }
+ return insertAfterIhdr(png, ...extra);
+}
+
+/** 仿 Apple HDR gain map 的字节:SDR 主图后追加一张带 hdrgainmap XMP 的辅助图(无 libvips 可解析的增益图结构)。 */
+async function appleGainMapJpeg(width: number, height: number): Promise<Buffer> {
+ const primary = await sharp({
+ create: { width, height, channels: 3, background: { r: 90, g: 90, b: 90 } },
+ })
+ .jpeg()
+ .toBuffer();
+ const xmp = Buffer.from(
+ '<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:Description apdi:AuxiliaryImageType="urn:com:apple:photo:2020:aux:hdrgainmap"/></x:xmpmeta>',
+ 'latin1',
+ );
+ const app1 = Buffer.alloc(4);
+ app1.writeUInt16BE(0xffe1, 0);
+ app1.writeUInt16BE(xmp.length + 2, 2);
+ const auxiliary = await sharp(Buffer.alloc(8 * 8 * 3, 90), {
+ raw: { width: 8, height: 8, channels: 3 },
+ })
+ .jpeg()
+ .toBuffer();
+ const secondary = Buffer.concat([auxiliary.subarray(0, 2), app1, xmp, auxiliary.subarray(2)]);
+ return Buffer.concat([primary, secondary]);
+}
+
+async function rgbaAt(buffer: Buffer, xs: number[], y = 0) {
+ const { data, info } = await sharp(buffer)
+ .toColourspace('srgb')
+ .ensureAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ return xs.map((x) => [...data.subarray((y * info.width + x) * 4, (y * info.width + x) * 4 + 4)]);
+}
+
+/** 输出必须是 8-bit、无 HDR 信号(ICC cicp / PNG cICP / 增益图签名)的普通 SDR 图。 */
+async function expectNoHdrSignal(buffer: Buffer) {
+ const metadata = await sharp(buffer).metadata();
+ expect(metadata.depth).toBe('uchar');
+ expect(metadata.gainMap).toBeUndefined();
+ expect(readIccCicp(metadata.icc)?.transfer ?? 0).not.toBeOneOf([16, 18]);
+ if (metadata.format === 'png') expect(readPngHdrChunks(buffer).cicp).toBeNull();
+ for (const signature of ['urn:iso:std:iso:ts:21496:-1', 'hdr-gain-map', 'aux:hdrgainmap']) {
+ expect(buffer.includes(signature)).toBe(false);
+ }
+ return metadata;
+}
+
+// 夹具渐变上的采样列与其场景线性值:0, 0.25, 0.5, 1.0(SDR 白), 4.0, 8.0。
+const RAMP_XS = [0, 8, 16, 32, 128, 255];
+
+describe('toSdrAvatarImage — PQ / HLG', () => {
+ it.each([
+ ['pq-bt2100.png', 'image/png', 16],
+ ['hlg-bt2100.png', 'image/png', 18],
+ ['pq-bt2100.jpg', 'image/jpeg', 16],
+ ])('%s is tone mapped to 8-bit sRGB without HDR signalling', async (name, mimeType, transfer) => {
+ const input = fixture(name);
+ const inputMetadata = await sharp(input).metadata();
+ expect(readIccCicp(inputMetadata.icc)?.transfer).toBe(transfer);
+
+ const output = await toSdrAvatarImage({ buffer: input, mimeType });
+ expect(output.mimeType).toBe(mimeType);
+ const metadata = await expectNoHdrSignal(output.buffer);
+ expect(metadata.hasProfile).toBe(false);
+ expect([metadata.width, metadata.height]).toEqual([inputMetadata.width, inputMetadata.height]);
+
+ const neutral = (await rgbaAt(output.buffer, RAMP_XS, 10)).map(([r]) => r!);
+ // 中间调与 macOS 自身 SDR 渲染(sdr-display-p3.png:0.25 → 137, 0.5 → 188)一致;
+ // SDR 白保持接近白而不是被整体压暗;高光平滑滚降到 255 而非按 PQ 码值显示成灰色。
+ expect(neutral[0]).toBeLessThanOrEqual(2);
+ expect(Math.abs(neutral[1]! - 137)).toBeLessThanOrEqual(3);
+ expect(Math.abs(neutral[2]! - 188)).toBeLessThanOrEqual(3);
+ expect(neutral[3]).toBeGreaterThanOrEqual(238);
+ expect(neutral[3]).toBeLessThan(250);
+ expect(neutral[5]).toBeGreaterThanOrEqual(252);
+ for (let index = 1; index < neutral.length; index++) {
+ expect(neutral[index]).toBeGreaterThanOrEqual(neutral[index - 1]! - 1);
+ }
+ // 暖色行在 SDR 白处保持 R > G > B 的色相(线性 1 : 0.6 : 0.3)。
+ const [, , , [r, g, b]] = await rgbaAt(output.buffer, RAMP_XS, 100);
+ expect(r).toBeGreaterThan(g!);
+ expect(g).toBeGreaterThan(b!);
+ expect(Math.abs(g! - 194)).toBeLessThanOrEqual(8);
+ });
+
+ it('reads cICP-only PNGs, honours cLLI, and keeps transparency', async () => {
+ const pixels = [
+ { nits: [203, 203, 203] as [number, number, number], alpha: 65535 },
+ { nits: [600, 600, 600] as [number, number, number], alpha: 32768 },
+ { nits: [50, 10, 2] as [number, number, number], alpha: 0 },
+ ];
+ const input = await syntheticPqPng(pixels);
+ expect(pngChunkTypes(input)).toContain('cICP');
+ const output = await toSdrAvatarImage({ buffer: input, mimeType: 'image/png' });
+ await expectNoHdrSignal(output.buffer);
+ expect(pngChunkTypes(output.buffer)).not.toContain('cICP');
+ const [white, bright, dim] = await rgbaAt(output.buffer, [0, 1, 2]);
+ expect(white![3]).toBe(255);
+ expect(bright![3]).toBe(128);
+ expect(dim![3]).toBe(0);
+ expect(white![0]).toBeGreaterThanOrEqual(238);
+ expect(bright![0]).toBeGreaterThan(white![0]!);
+
+ // 声明的内容峰值更高时,同样 600 nit 会被压得更多(更暗)。
+ const brighterMaster = await toSdrAvatarImage({
+ buffer: await syntheticPqPng(pixels, { cllNits: 4000 }),
+ mimeType: 'image/png',
+ });
+ const [, brightUnderHigherPeak] = await rgbaAt(brighterMaster.buffer, [0, 1, 2]);
+ expect(brightUnderHigherPeak![0]).toBeLessThan(bright![0]!);
+ });
+
+ it('bakes EXIF orientation into converted pixels', async () => {
+ const input = await syntheticPqPng(
+ [
+ { nits: [203, 0, 0], alpha: 65535 },
+ { nits: [0, 0, 203], alpha: 65535 },
+ ],
+ { orientation: 6 },
+ );
+ expect((await sharp(input).metadata()).orientation).toBe(6);
+ const output = await toSdrAvatarImage({ buffer: input, mimeType: 'image/png' });
+ const metadata = await sharp(output.buffer).metadata();
+ expect([metadata.width, metadata.height, metadata.orientation]).toEqual([1, 2, undefined]);
+ const [[top], [bottom]] = [
+ await rgbaAt(output.buffer, [0], 0),
+ await rgbaAt(output.buffer, [0], 1),
+ ];
+ // Orientation 6 = 顺时针 90°:原来最左的红色像素到顶部。
+ expect(top![0]).toBeGreaterThan(200);
+ expect(bottom![2]).toBeGreaterThan(200);
+ });
+
+ it('converts WebP whose ICC profile declares PQ', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'hdr-avatar-'));
+ try {
+ const iccPath = path.join(dir, 'pq.icc');
+ await writeFile(iccPath, (await sharp(fixture('pq-bt2100.png')).metadata()).icc!);
+ const input = await sharp(Buffer.alloc(16 * 16 * 3, 200), {
+ raw: { width: 16, height: 16, channels: 3 },
+ })
+ .withIccProfile(iccPath)
+ .webp({ quality: 95 })
+ .toBuffer();
+ expect(readIccCicp((await sharp(input).metadata()).icc)?.transfer).toBe(16);
+ const output = await toSdrAvatarImage({ buffer: input, mimeType: 'image/webp' });
+ expect(output.mimeType).toBe('image/webp');
+ expect((await expectNoHdrSignal(output.buffer)).hasProfile).toBe(false);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ it('adapts DCI-P3 (primaries 11) from the DCI white point instead of treating it as P3-D65', async () => {
+ const pixels = [
+ { nits: [100, 100, 100] as [number, number, number], alpha: 65535 },
+ { nits: [100, 20, 20] as [number, number, number], alpha: 65535 },
+ ];
+ const convert = async (primaries: number) =>
+ rgbaAt(
+ (
+ await toSdrAvatarImage({
+ buffer: await syntheticPqPng(pixels, { cicp: [primaries, 16, 0, 1] }),
+ mimeType: 'image/png',
+ })
+ ).buffer,
+ [0, 1],
+ );
+ const [[dciNeutral, dciRed], [, p3d65Red]] = [await convert(11), await convert(12)];
+ // 色适应后 DCI 白仍映射为中性色;饱和色则因白点不同而与 P3-D65 结果不同。
+ expect(
+ Math.max(...dciNeutral!.slice(0, 3)) - Math.min(...dciNeutral!.slice(0, 3)),
+ ).toBeLessThanOrEqual(1);
+ expect(dciRed!.slice(0, 3)).not.toEqual(p3d65Red!.slice(0, 3));
+ });
+
+ it('converts every H.273 primaries code it supports with its own gamut and rejects the rest', async () => {
+ const pixels = [
+ { nits: [100, 100, 100] as [number, number, number], alpha: 65535 },
+ { nits: [20, 100, 20] as [number, number, number], alpha: 65535 },
+ ];
+ const convert = async (primaries: number) =>
+ rgbaAt(
+ (
+ await toSdrAvatarImage({
+ buffer: await syntheticPqPng(pixels, { cicp: [primaries, 16, 0, 1] }),
+ mimeType: 'image/png',
+ })
+ ).buffer,
+ [0, 1],
+ );
+ const results = new Map<number, number[][]>();
+ for (const code of [1, 2, 4, 5, 6, 7, 8, 9, 11, 12, 22]) {
+ const [neutral, green] = await convert(code);
+ // 各自白点(含光源 C)适应到 D65 后中性色仍为中性。
+ expect(
+ Math.max(...neutral!.slice(0, 3)) - Math.min(...neutral!.slice(0, 3)),
+ ).toBeLessThanOrEqual(1);
+ results.set(code, [neutral!.slice(0, 3), green!.slice(0, 3)]);
+ }
+ // 未指定(2)按 BT.2020;显式声明的其它原色不再被当作 BT.2020。
+ expect(results.get(2)).toEqual(results.get(9));
+ for (const code of [5, 6, 22]) expect(results.get(code)![1]).not.toEqual(results.get(9)![1]);
+ expect(results.get(6)).toEqual(results.get(7));
+
+ for (const code of [0, 3, 10, 13, 23, 255]) {
+ await expect(
+ toSdrAvatarImage({
+ buffer: await syntheticPqPng(pixels, { cicp: [code, 16, 0, 1] }),
+ mimeType: 'image/png',
+ }),
+ ).rejects.toThrow(/INVALID_PARAMS.*primaries/);
+ }
+ });
+
+ it('downscales large PQ sources to at most 2048² before tone mapping', async () => {
+ const [width, height] = [3000, 1500];
+ const raw = new Uint16Array(width * height * 3).fill(Math.round(PQ(203) * 65535));
+ const input = insertAfterIhdr(
+ await sharp(raw, { raw: { width, height, channels: 3 } }).toColourspace('rgb16').png().toBuffer(),
+ pngChunk('cICP', Buffer.from([1, 16, 0, 1])),
+ );
+ const metadata = await expectNoHdrSignal(
+ (await toSdrAvatarImage({ buffer: input, mimeType: 'image/png' })).buffer,
+ );
+ expect(metadata.width! * metadata.height!).toBeLessThanOrEqual(2048 * 2048);
+ expect(Math.abs(metadata.width! / metadata.height! - 2)).toBeLessThan(0.01);
+ });
+
+ it('rejects HDR sources whose declared dimensions exceed the limit before decoding', async () => {
+ const png = await syntheticPqPng([{ nits: [203, 203, 203], alpha: 65535 }]);
+ // 改写 IHDR 宽高(1 亿 / 4 亿像素),文件仍只有几百字节;后者超过 sharp 默认像素上限。
+ for (const side of [10_000, 20_000]) {
+ const ihdr = Buffer.from(png.subarray(16, 29));
+ ihdr.writeUInt32BE(side, 0);
+ ihdr.writeUInt32BE(side, 4);
+ const inflated = Buffer.concat([
+ png.subarray(0, 8),
+ pngChunk('IHDR', ihdr),
+ png.subarray(33),
+ ]);
+ await expect(toSdrAvatarImage({ buffer: inflated, mimeType: 'image/png' })).rejects.toThrow(
+ /INVALID_PARAMS.*dimensions exceed/,
+ );
+ }
+ });
+
+ it('rejects HDR bytes it cannot decode instead of storing them unchanged', async () => {
+ const valid = await syntheticPqPng([{ nits: [203, 203, 203], alpha: 65535 }]);
+ const truncated = valid.subarray(0, valid.length - 20);
+ await expect(toSdrAvatarImage({ buffer: truncated, mimeType: 'image/png' })).rejects.toThrow(
+ /INVALID_PARAMS/,
+ );
+ });
+
+ it('rejects animated HDR instead of flattening it to the first frame, and leaves animated SDR alone', async () => {
+ const frames = await Promise.all(
+ ['#c80000', '#0000c8'].map((background) =>
+ sharp({ create: { width: 8, height: 8, channels: 3, background } }).png().toBuffer(),
+ ),
+ );
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'hdr-avatar-'));
+ try {
+ const iccPath = path.join(dir, 'pq.icc');
+ await writeFile(iccPath, (await sharp(fixture('pq-bt2100.png')).metadata()).icc!);
+ const animatedWebp = (withPq: boolean) => {
+ const pipeline = sharp(frames, { join: { animated: true } });
+ return (withPq ? pipeline.withIccProfile(iccPath) : pipeline).webp().toBuffer();
+ };
+ const hdrWebp = await animatedWebp(true);
+ const hdrWebpMetadata = await sharp(hdrWebp).metadata();
+ expect(hdrWebpMetadata.pages).toBe(2);
+ expect(readIccCicp(hdrWebpMetadata.icc)?.transfer).toBe(16);
+ await expect(toSdrAvatarImage({ buffer: hdrWebp, mimeType: 'image/webp' })).rejects.toThrow(
+ /INVALID_PARAMS.*Animated/,
+ );
+ const sdrWebp = { buffer: await animatedWebp(false), mimeType: 'image/webp' };
+ expect(await toSdrAvatarImage(sdrWebp)).toBe(sdrWebp);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+
+ // APNG:acTL 声明 2 帧;libvips 只解码默认图像,转换会丢掉其余帧。
+ const acTL = pngChunk('acTL', Buffer.from([0, 0, 0, 2, 0, 0, 0, 0]));
+ const hdrApng = insertAfterIhdr(
+ await syntheticPqPng([{ nits: [203, 203, 203], alpha: 65535 }]),
+ acTL,
+ );
+ expect(readPngHdrChunks(hdrApng).animated).toBe(true);
+ await expect(toSdrAvatarImage({ buffer: hdrApng, mimeType: 'image/png' })).rejects.toThrow(
+ /INVALID_PARAMS.*Animated/,
+ );
+ const sdrApng = { buffer: insertAfterIhdr(frames[0]!, acTL), mimeType: 'image/png' };
+ expect(await toSdrAvatarImage(sdrApng)).toBe(sdrApng);
+ });
+});
+
+describe('toSdrAvatarImage — gain maps', () => {
+ it('drops an ISO 21496-1 gain map and keeps the SDR base rendition', async () => {
+ const input = fixture('iso-gainmap.jpg');
+ const inputMetadata = await sharp(input).metadata();
+ expect(inputMetadata.gainMap).toBeDefined();
+ expect(input.includes('urn:iso:std:iso:ts:21496:-1')).toBe(true);
+
+ const output = await toSdrAvatarImage({ buffer: input, mimeType: 'image/jpeg' });
+ expect(output.mimeType).toBe('image/jpeg');
+ const metadata = await expectNoHdrSignal(output.buffer);
+ // 主图的 Display P3 ICC 原样保留,SDR 颜色不被改写。
+ expect(metadata.icc?.equals(inputMetadata.icc!)).toBe(true);
+ expect([metadata.width, metadata.height]).toEqual([inputMetadata.width, inputMetadata.height]);
+ const before = await rgbaAt(input, RAMP_XS, 100);
+ const after = await rgbaAt(output.buffer, RAMP_XS, 100);
+ after.forEach((pixel, index) => {
+ pixel.slice(0, 3).forEach((value, channel) => {
+ expect(Math.abs(value - before[index]![channel]!)).toBeLessThanOrEqual(6);
+ });
+ });
+ });
+
+ it('treats only a parsed gain-map structure as HDR, not gain-map strings in metadata', async () => {
+ const sdr = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#5a5a5a' } })
+ .jpeg()
+ .toBuffer();
+ const segment = (marker: number, text: string) => {
+ const body = Buffer.from(text, 'latin1');
+ const header = Buffer.alloc(4);
+ header.writeUInt16BE(marker, 0);
+ header.writeUInt16BE(body.length + 2, 2);
+ return Buffer.concat([header, body]);
+ };
+ const withSegment = (marker: number, text: string) =>
+ Buffer.concat([sdr.subarray(0, 2), segment(marker, text), sdr.subarray(2)]);
+ for (const buffer of [
+ // XMP 里声明了 Ultra HDR 命名空间,但没有增益图。
+ withSegment(0xffe1, '<x:xmpmeta xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"/>'),
+ // JPEG 注释里出现 ISO 21496-1 URN。
+ withSegment(0xfffe, 'urn:iso:std:iso:ts:21496:-1'),
+ // 末尾附带 Apple 辅助图 XMP,但没有 libvips 可解析的增益图结构。
+ await appleGainMapJpeg(8, 8),
+ ]) {
+ expect((await sharp(buffer).metadata()).gainMap).toBeUndefined();
+ const image = { buffer, mimeType: 'image/jpeg' };
+ expect(await toSdrAvatarImage(image)).toBe(image);
+ }
+ });
+});
+
+describe('toSdrAvatarImage — SDR passthrough', () => {
+ it('returns SDR inputs byte-for-byte, including wide-gamut and 16-bit PNG', async () => {
+ const sdrP3 = fixture('sdr-display-p3.png');
+ // ImageIO 自身的 SDR 渲染:16-bit、Display P3、cICP 声明 sRGB 传递函数(13)。
+ expect(readPngHdrChunks(sdrP3).cicp).toMatchObject({ primaries: 12, transfer: 13 });
+ const oriented = await sharp(Buffer.alloc(4 * 2 * 3, 120), {
+ raw: { width: 4, height: 2, channels: 3 },
+ })
+ .withMetadata({ orientation: 6 })
+ .jpeg()
+ .toBuffer();
+ const transparentWebp = await sharp(Buffer.alloc(4 * 4 * 4, 80), {
+ raw: { width: 4, height: 4, channels: 4 },
+ })
+ .webp()
+ .toBuffer();
+ for (const [buffer, mimeType] of [
+ [sdrP3, 'image/png'],
+ [oriented, 'image/jpeg'],
+ [transparentWebp, 'image/webp'],
+ ] as const) {
+ const image = { buffer, mimeType };
+ expect(await toSdrAvatarImage(image)).toBe(image);
+ }
+ });
+
+ it('rejects unparseable headers only when the bytes themselves carry an HDR signal', async () => {
+ // IHDR 宽度为 0(CRC 合法):sharp 读不出头部,但 cICP 块仍可直接从字节读到。
+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: '#888' } })
+ .png()
+ .toBuffer();
+ const ihdr = Buffer.from(png.subarray(16, 29));
+ ihdr.writeUInt32BE(0, 0);
+ const brokenPng = (transfer: number) =>
+ Buffer.concat([
+ png.subarray(0, 8),
+ pngChunk('IHDR', ihdr),
+ pngChunk('cICP', Buffer.from([9, transfer, 0, 1])),
+ png.subarray(33),
+ ]);
+ for (const buffer of [brokenPng(16), brokenPng(18)]) {
+ await expect(sharp(buffer).metadata()).rejects.toThrow();
+ await expect(toSdrAvatarImage({ buffer, mimeType: 'image/png' })).rejects.toThrow(
+ /INVALID_PARAMS/,
+ );
+ }
+ // 增益图只认解析出的结构;读不出头部的 JPEG 即使带增益图字符串也按既有行为放行。
+ const xmp = Buffer.from('<x:xmpmeta hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"/>', 'latin1');
+ const app1 = Buffer.alloc(4);
+ app1.writeUInt16BE(0xffe1, 0);
+ app1.writeUInt16BE(xmp.length + 2, 2);
+ for (const image of [
+ { buffer: brokenPng(13), mimeType: 'image/png' },
+ { buffer: Buffer.concat([Buffer.from([0xff, 0xd8]), app1, xmp]), mimeType: 'image/jpeg' },
+ ]) {
+ await expect(sharp(image.buffer).metadata()).rejects.toThrow();
+ expect(await toSdrAvatarImage(image)).toBe(image);
+ }
+ });
+
+ it('passes through bytes it cannot parse, preserving the existing validation behaviour', async () => {
+ for (const buffer of [
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10]),
+ Buffer.from([0xff, 0xd8, 0xff, 0xe0]),
+ Buffer.from('not an image'),
+ ]) {
+ const image = { buffer, mimeType: 'image/png' };
+ expect(await toSdrAvatarImage(image)).toBe(image);
+ }
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/profileEdit.test.ts b/apps/desktop/src/main/__tests__/profileEdit.test.ts
index 46f62ecd0f..ed37c33531 100644
--- a/apps/desktop/src/main/__tests__/profileEdit.test.ts
+++ b/apps/desktop/src/main/__tests__/profileEdit.test.ts
@@ -2,10 +2,13 @@
* profileEdit.test.ts — 个人资料编辑业务体单测(规则 14:全依赖注入,内存直测)。
* 覆盖:未登录 / 非法参数拒绝、名字收敛(留空/一致 = 不改)、头像三态
* (keep / set / reset)的 OSS 直传与 PATCH 组装、体积与扩展名校验、
- * 上传 / PATCH 失败的错误码映射、无变化零请求。
+ * 上传 / PATCH 失败的错误码映射、无变化零请求、HDR 头像先转 SDR 再预览 / 上传。
*/
import { describe, it, expect, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { toSdrAvatarImage, readPngHdrChunks } from '../hdrAvatarToSdr';
import {
AVATAR_MAX_BYTES,
@@ -28,9 +31,11 @@ function makeDeps(overrides: Partial<ProfileEditDeps> = {}): {
const patches: ProfilePatch[] = [];
const deps: ProfileEditDeps = {
getCurrentUserId: () => 'u1',
+ getAccountScopeKey: () => 'cloud:u1:1',
getServerProfile: () => ({ name: 'Server Name', avatar: null }),
showAvatarOpenDialog: vi.fn(async () => null),
readFile: vi.fn(async () => Buffer.from([1, 2, 3])),
+ toSdrAvatar: vi.fn(async (image) => image),
uploadAvatar: vi.fn(async () => ({ ok: true as const, publicUrl: PUBLIC_URL })),
patchProfile: vi.fn(async (patch: ProfilePatch) => {
patches.push(patch);
@@ -173,6 +178,93 @@ describe('头像三态', () => {
});
});
+describe('HDR 头像转 SDR 后再预览 / 上传', () => {
+ const hdrPng = readFileSync(path.join(__dirname, 'fixtures', 'hdr-avatar', 'pq-bt2100.png'));
+
+ it('set:上传的是真实转换后的 SDR 字节,而不是原 HDR 文件', async () => {
+ const { deps } = makeDeps({ readFile: vi.fn(async () => hdrPng), toSdrAvatar: toSdrAvatarImage });
+ await updateProfile(deps, { name: null, avatar: { type: 'set', filePath: '/pics/hdr.png' } });
+ const [[uploaded]] = (deps.uploadAvatar as ReturnType<typeof vi.fn>).mock.calls as [[{ buffer: Buffer; mimeType: string }]];
+ expect(uploaded.mimeType).toBe('image/png');
+ expect(uploaded.buffer.equals(hdrPng)).toBe(false);
+ expect(readPngHdrChunks(hdrPng).cicp?.transfer).toBe(16);
+ expect(readPngHdrChunks(uploaded.buffer).cicp).toBeNull();
+ });
+
+ it('chooseAvatarFile:预览与将要上传的字节一致(同为 SDR)', async () => {
+ const { deps } = makeDeps({
+ showAvatarOpenDialog: vi.fn(async () => '/pics/hdr.png'),
+ readFile: vi.fn(async () => hdrPng),
+ toSdrAvatar: toSdrAvatarImage,
+ });
+ const result = await chooseAvatarFile(deps);
+ const preview = Buffer.from(result.previewDataUrl!.split(',')[1]!, 'base64');
+ expect(result.previewDataUrl!.startsWith('data:image/png;base64,')).toBe(true);
+ expect(readPngHdrChunks(preview).cicp).toBeNull();
+ expect(preview.equals((await toSdrAvatarImage({ buffer: hdrPng, mimeType: 'image/png' })).buffer)).toBe(true);
+ });
+
+ it('转换结果超出体积上限 → INVALID_PARAMS,不触发上传', async () => {
+ const { deps } = makeDeps({
+ toSdrAvatar: vi.fn(async () => ({ buffer: Buffer.alloc(AVATAR_MAX_BYTES + 1), mimeType: 'image/png' })),
+ });
+ await expect(
+ updateProfile(deps, { name: null, avatar: { type: 'set', filePath: '/a/b.png' } }),
+ ).rejects.toSatisfy((e) => ipcCode(e) === 'INVALID_PARAMS');
+ expect(deps.uploadAvatar).not.toHaveBeenCalled();
+ });
+
+ it('chooseAvatarFile:转换结果超出体积上限 → 选图阶段就 INVALID_PARAMS', async () => {
+ const { deps } = makeDeps({
+ showAvatarOpenDialog: vi.fn(async () => '/pics/hdr.png'),
+ toSdrAvatar: vi.fn(async () => ({ buffer: Buffer.alloc(AVATAR_MAX_BYTES + 1), mimeType: 'image/png' })),
+ });
+ await expect(chooseAvatarFile(deps)).rejects.toSatisfy((e) => ipcCode(e) === 'INVALID_PARAMS');
+ });
+});
+
+describe('保存途中切换账号', () => {
+ // 每次读取账号会话标识时推进一步:前 n 次仍是原会话,之后换成新会话,模拟在第 n 个 await 前后切号。
+ const switchAfter = (reads: number, next = 'cloud:u2:2') => {
+ let count = 0;
+ return () => (++count <= reads ? 'cloud:u1:1' : next);
+ };
+
+ it('HDR 转换(或排队)期间切号 → PRECONDITION_FAILED,不上传也不 PATCH', async () => {
+ const { deps } = makeDeps({ getAccountScopeKey: switchAfter(1) });
+ await expect(
+ updateProfile(deps, { name: 'Lizi', avatar: { type: 'set', filePath: '/a/b.png' } }),
+ ).rejects.toSatisfy((e) => ipcCode(e) === 'PRECONDITION_FAILED');
+ expect(deps.toSdrAvatar).toHaveBeenCalledTimes(1);
+ expect(deps.uploadAvatar).not.toHaveBeenCalled();
+ expect(deps.patchProfile).not.toHaveBeenCalled();
+ });
+
+ it('上传期间切号 → PRECONDITION_FAILED,不把头像与旧名字 PATCH 到新账号', async () => {
+ const { deps } = makeDeps({ getAccountScopeKey: switchAfter(2) });
+ await expect(
+ updateProfile(deps, { name: 'Lizi', avatar: { type: 'set', filePath: '/a/b.png' } }),
+ ).rejects.toSatisfy((e) => ipcCode(e) === 'PRECONDITION_FAILED');
+ expect(deps.uploadAvatar).toHaveBeenCalledTimes(1);
+ expect(deps.patchProfile).not.toHaveBeenCalled();
+ });
+
+ it('同一用户 id 切到另一区域(会话代次变化)同样拦下,不 PATCH 到新区域', async () => {
+ // getCurrentUserId 始终是 u1:只比较用户 id 的检查会放行。
+ const { deps } = makeDeps({ getAccountScopeKey: switchAfter(2, 'cloud:u1:2') });
+ await expect(
+ updateProfile(deps, { name: 'Lizi', avatar: { type: 'set', filePath: '/a/b.png' } }),
+ ).rejects.toSatisfy((e) => ipcCode(e) === 'PRECONDITION_FAILED');
+ expect(deps.patchProfile).not.toHaveBeenCalled();
+ });
+
+ it('账号不变时照常上传并 PATCH', async () => {
+ const { deps, patches } = makeDeps({ getAccountScopeKey: switchAfter(Infinity) });
+ await updateProfile(deps, { name: 'Lizi', avatar: { type: 'set', filePath: '/a/b.png' } });
+ expect(patches).toEqual([{ displayName: 'Lizi', avatarUrl: PUBLIC_URL }]);
+ });
+});
+
describe('chooseAvatarFile(选图预校验,不上传)', () => {
it('取消选择返回 canceled,不读文件', async () => {
const { deps } = makeDeps();
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 9c055ec17d..da9cf38bcb 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -302,6 +302,7 @@ import {
import { createAccountDeletionIpcHandlers } from './accountDeletionIpc';
import * as profileEdit from './profileEdit';
import { uploadPublicAsset } from './ossPublicUpload';
+import { toSdrAvatarImage } from './hdrAvatarToSdr';
import { removeRefs as removeMediaRefs } from './cindy-media/ledger';
import {
installWebviewHardener,
@@ -5980,6 +5981,7 @@ const registerIpcHandlers = () => {
const profileEditLog = createLogger('profileEdit');
const profileEditDeps: profileEdit.ProfileEditDeps = {
getCurrentUserId: () => authManager.getCurrentUserId(),
+ getAccountScopeKey: activeOwnerScopeKey,
getServerProfile: () => authManager.getServerProfile(),
showAvatarOpenDialog: async () => {
const result = await dialog.showOpenDialog({
@@ -5989,6 +5991,7 @@ const registerIpcHandlers = () => {
return result.canceled || !result.filePaths[0] ? null : result.filePaths[0];
},
readFile: (filePath) => fs.promises.readFile(filePath),
+ toSdrAvatar: toSdrAvatarImage,
uploadAvatar: async ({ buffer, mimeType }) => {
const result = await uploadPublicAsset(
{
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index 0fc07779a1..72ea8a1bd2 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -12,6 +12,7 @@ import { parseRoutineInput, type RoutineInput } from '@cindy/maker-scheduler';
import { normalizeBotName } from '../../shared/botCreation.js';
import { listBotRemoteResourceSources } from '../localDb/ipc/bots.js';
import { validateBotAvatarBuffer, decodeBotAvatarImage } from '../localDb/ipc/botAvatarSelection.js';
+import { toSdrAvatarImage } from '../hdrAvatarToSdr.js';
import { COMPANION_IMPORT_CHUNK_LENGTH, COMPANION_IMPORT_READ_MAX_LENGTH, COMPANION_IMPORT_SELECTION_CHUNK_LENGTH } from '@cindy/maker-shared/companion-import';
import type { CompanionImportPreview, CompanionImportResult, CompanionImportSelection, CompanionImportSubmission, CompanionImportSource } from '@cindy/maker-shared/companion-import';
import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
@@ -117,8 +118,10 @@ export async function previewCompanionImport(sourceId: string, controller: strin
const inspected = await inspectImportSource(source, readers()); scope.assert();
const snapshot = { ...inspected, items: inspected.items.map((item, index) => ({ ...item, sourceIndex: index })) };
if (snapshot.avatarImageBase64) {
- const buffer = Buffer.from(snapshot.avatarImageBase64, 'base64');
- validateBotAvatarBuffer(buffer);
+ const original = Buffer.from(snapshot.avatarImageBase64, 'base64');
+ // Tone map before resizing: the thumbnail below would otherwise misread PQ / HLG pixels as sRGB.
+ const { buffer } = await toSdrAvatarImage({ buffer: original, mimeType: validateBotAvatarBuffer(original) });
+ scope.assert();
snapshot.avatarImageBase64 = (await sharp(buffer, { limitInputPixels: 40_000_000 }).resize(256, 256, { fit: 'cover' }).jpeg({ quality: 65 }).toBuffer()).toString('base64');
scope.assert();
}
diff --git a/apps/desktop/src/main/hdrAvatarToSdr.ts b/apps/desktop/src/main/hdrAvatarToSdr.ts
new file mode 100644
index 0000000000..3765f3bb0d
--- /dev/null
+++ b/apps/desktop/src/main/hdrAvatarToSdr.ts
@@ -0,0 +1,467 @@
+/**
+ * hdrAvatarToSdr.ts — 头像入口的 HDR → SDR 归一化。
+ * ---------------------------------------------------------------------------
+ * 头像会在列表、通知、手机端等大量 SDR 语境里与其它界面元素并排显示;HDR 头像
+ * 在 HDR 屏上会比周围 UI 亮出一截(高光刺眼),在不同端又各自走不同的色调映射。
+ * 因此用户上传的头像在入库 / 上传前就转成真正的 SDR 字节,而不是靠 CSS 调暗。
+ *
+ * 只处理头像白名单(PNG / JPEG / WebP)里浏览器会按 HDR 渲染的两类信号:
+ * 1. 增益图(gain map)JPEG:以 libvips 从文件结构解析出的增益图为准(Ultra HDR /
+ * ISO 21496-1,即 sharp `metadata.gainMap`),不按元数据里的字符串猜测。
+ * 主图本身就是 SDR 版本,丢弃增益图与相关元数据后按主图重编码即可;
+ * 2. PQ / HLG 传递函数:PNG `cICP` 块或 ICC v4.4 `cicp` 标签声明 transfer=16/18。
+ * 这类像素本身是 HDR 编码,需解码到线性光 → 转 BT.709 色域 → 高光压缩 →
+ * sRGB 编码为 8-bit。
+ * 其它输入(含一切 SDR 图片、无法解析头部的字节)原样返回,保证既有 SDR 头像的
+ * 字节、颜色、方向、透明度与尺寸行为完全不变。
+ */
+
+import sharp, { type Metadata, type Sharp } from 'sharp';
+import { throwIpcError } from './utils/ipcValidate';
+
+export interface AvatarImageBytes {
+ buffer: Buffer;
+ mimeType: string;
+}
+
+type AvatarFormat = 'png' | 'jpeg' | 'webp';
+type HdrTransfer = 'pq' | 'hlg';
+
+interface Cicp {
+ primaries: number;
+ transfer: number;
+ fullRange: boolean;
+}
+
+/** H.273 TransferCharacteristics:16 = SMPTE ST 2084 (PQ),18 = ARIB STD-B67 (HLG)。 */
+const H273_TRANSFER_PQ = 16;
+const H273_TRANSFER_HLG = 18;
+
+/** BT.2408 的 HDR 参考白(203 cd/m²)对应 SDR 的 1.0。 */
+const HDR_REFERENCE_WHITE_NITS = 203;
+/** 无 cLLI 时 PQ 内容的假定峰值,及 HLG 的标称显示峰值(BT.2100 Lw = 1000)。 */
+const DEFAULT_HDR_PEAK_NITS = 1000;
+/** 线性 SDR 中低于该值的部分保持不变,只把以上到峰值的高光平滑压进 (knee, 1]。 */
+const TONE_MAP_KNEE = 0.8;
+/**
+ * 两条转换路径的输出像素上限;超出先等比缩小。头像展示远小于 2048²,按此上限单次
+ * PQ / HLG 转换在 main 进程持有的像素缓冲 ≤ 48 MiB(16-bit RGBA 32 MiB + 8-bit 输出 16 MiB)。
+ */
+const HDR_MAX_PIXELS = 2048 * 2048;
+/**
+ * 源图像素上限:≤5 MB 的 PNG / WebP 也能声明上亿像素,超出时在解码前按头部尺寸拒绝,
+ * 并作为每次解码的 limitInputPixels 兜底(sharp 默认上限约 2.7 亿)。覆盖 4800 万像素手机原片。
+ */
+const HDR_MAX_INPUT_PIXELS = 64_000_000;
+/** 每处理这么多像素让出一次事件循环,避免长时间阻塞 main。 */
+const PIXELS_PER_YIELD = 1 << 18;
+
+function sniffFormat(buffer: Buffer): AvatarFormat | null {
+ if (
+ buffer.length >= 8 &&
+ buffer.readUInt32BE(0) === 0x89504e47 &&
+ buffer.readUInt32BE(4) === 0x0d0a1a0a
+ ) {
+ return 'png';
+ }
+ if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff)
+ return 'jpeg';
+ if (
+ buffer.length >= 12 &&
+ buffer.toString('latin1', 0, 4) === 'RIFF' &&
+ buffer.toString('latin1', 8, 12) === 'WEBP'
+ ) {
+ return 'webp';
+ }
+ return null;
+}
+
+/**
+ * 读取 IDAT 之前的 cICP / cLLI 块,以及标记 APNG 的 acTL 块(PNG / APNG 规范要求三者
+ * 都出现在 IDAT 之前)。
+ */
+export function readPngHdrChunks(buffer: Buffer): {
+ cicp: Cicp | null;
+ maxCllNits: number | null;
+ animated: boolean;
+} {
+ let cicp: Cicp | null = null;
+ let maxCllNits: number | null = null;
+ let animated = false;
+ let offset = 8;
+ while (offset + 8 <= buffer.length) {
+ const length = buffer.readUInt32BE(offset);
+ const type = buffer.toString('latin1', offset + 4, offset + 8);
+ const data = offset + 8;
+ if (type === 'IDAT' || type === 'IEND' || data + length > buffer.length) break;
+ if (type === 'cICP' && length === 4) {
+ cicp = {
+ primaries: buffer[data]!,
+ transfer: buffer[data + 1]!,
+ fullRange: buffer[data + 3] !== 0,
+ };
+ } else if (type === 'cLLI' && length === 8) {
+ // MaxCLL 单位 0.0001 cd/m²;0 表示未知。
+ const value = buffer.readUInt32BE(data) / 10_000;
+ maxCllNits = value > 0 ? value : null;
+ } else if (type === 'acTL') {
+ animated = true;
+ }
+ offset = data + length + 4;
+ }
+ return { cicp, maxCllNits, animated };
+}
+
+/** 读取 ICC v4.4 的 `cicp` 标签;没有或结构不完整时返回 null。 */
+export function readIccCicp(icc: Buffer | undefined): Cicp | null {
+ if (!icc || icc.length < 132) return null;
+ const count = icc.readUInt32BE(128);
+ for (let index = 0; index < count; index++) {
+ const entry = 132 + index * 12;
+ if (entry + 12 > icc.length) return null;
+ if (icc.toString('latin1', entry, entry + 4) !== 'cicp') continue;
+ const offset = icc.readUInt32BE(entry + 4);
+ const size = icc.readUInt32BE(entry + 8);
+ if (
+ size < 12 ||
+ offset + 12 > icc.length ||
+ icc.toString('latin1', offset, offset + 4) !== 'cicp'
+ ) {
+ return null;
+ }
+ return {
+ primaries: icc[offset + 8]!,
+ transfer: icc[offset + 9]!,
+ fullRange: icc[offset + 11] !== 0,
+ };
+ }
+ return null;
+}
+
+function hdrTransferOf(cicp: Cicp | null): HdrTransfer | null {
+ if (cicp?.transfer === H273_TRANSFER_PQ) return 'pq';
+ if (cicp?.transfer === H273_TRANSFER_HLG) return 'hlg';
+ return null;
+}
+
+// ── 色彩数学 ────────────────────────────────────────────────────────────────
+
+type Mat3 = [number, number, number, number, number, number, number, number, number];
+type Chromaticities = {
+ r: [number, number];
+ g: [number, number];
+ b: [number, number];
+ white: [number, number];
+};
+
+const D65: [number, number] = [0.3127, 0.329];
+/** CIE 标准光源 C(BT.470 System M 与通用胶片原色的白点)。 */
+const ILLUMINANT_C: [number, number] = [0.31, 0.316];
+const BT709: Chromaticities = { r: [0.64, 0.33], g: [0.3, 0.6], b: [0.15, 0.06], white: D65 };
+/** BT.601 525 行(SMPTE 170M / 240M)。 */
+const SMPTE_170M: Chromaticities = {
+ r: [0.63, 0.34],
+ g: [0.31, 0.595],
+ b: [0.155, 0.07],
+ white: D65,
+};
+const BT2020: Chromaticities = {
+ r: [0.708, 0.292],
+ g: [0.17, 0.797],
+ b: [0.131, 0.046],
+ white: D65,
+};
+const P3_D65: Chromaticities = { r: [0.68, 0.32], g: [0.265, 0.69], b: [0.15, 0.06], white: D65 };
+/** SMPTE ST 431-2:与 P3-D65 同原色,但白点是 DCI 白。 */
+const DCI_P3: Chromaticities = { ...P3_D65, white: [0.314, 0.351] };
+const BRADFORD: Mat3 = [0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296];
+
+/**
+ * H.273 ColourPrimaries → 色度。2(未指定)按 HDR 惯例视为 BT.2020;10(ST 428-1 XYZ)
+ * 与保留值无法用 RGB 原色表达,返回 null 由调用方拒绝,不猜色域。
+ */
+const PRIMARIES_BY_CODE: Record<number, Chromaticities> = {
+ 1: BT709,
+ 2: BT2020,
+ 4: { r: [0.67, 0.33], g: [0.21, 0.71], b: [0.14, 0.08], white: ILLUMINANT_C },
+ 5: { r: [0.64, 0.33], g: [0.29, 0.6], b: [0.15, 0.06], white: D65 },
+ 6: SMPTE_170M,
+ 7: SMPTE_170M,
+ 8: { r: [0.681, 0.319], g: [0.243, 0.692], b: [0.145, 0.049], white: ILLUMINANT_C },
+ 9: BT2020,
+ 11: DCI_P3,
+ 12: P3_D65,
+ 22: { r: [0.63, 0.34], g: [0.295, 0.605], b: [0.155, 0.077], white: D65 },
+};
+
+function primariesFor(code: number): Chromaticities | null {
+ return PRIMARIES_BY_CODE[code] ?? null;
+}
+
+function multiply(a: Mat3, b: Mat3): Mat3 {
+ const out = new Array(9).fill(0) as Mat3;
+ for (let row = 0; row < 3; row++) {
+ for (let col = 0; col < 3; col++) {
+ out[row * 3 + col] =
+ a[row * 3]! * b[col]! + a[row * 3 + 1]! * b[3 + col]! + a[row * 3 + 2]! * b[6 + col]!;
+ }
+ }
+ return out;
+}
+
+function invert(m: Mat3): Mat3 {
+ const [a, b, c, d, e, f, g, h, i] = m;
+ const A = e * i - f * h;
+ const B = -(d * i - f * g);
+ const C = d * h - e * g;
+ const det = a * A + b * B + c * C;
+ return [
+ A / det,
+ -(b * i - c * h) / det,
+ (b * f - c * e) / det,
+ B / det,
+ (a * i - c * g) / det,
+ -(a * f - c * d) / det,
+ C / det,
+ -(a * h - b * g) / det,
+ (a * e - b * d) / det,
+ ];
+}
+
+function xyToXyz([x, y]: [number, number]): [number, number, number] {
+ return [x / y, 1, (1 - x - y) / y];
+}
+
+function apply(m: Mat3, [x, y, z]: [number, number, number]): [number, number, number] {
+ return [
+ m[0] * x + m[1] * y + m[2] * z,
+ m[3] * x + m[4] * y + m[5] * z,
+ m[6] * x + m[7] * y + m[8] * z,
+ ];
+}
+
+function diagonal([a, b, c]: [number, number, number]): Mat3 {
+ return [a, 0, 0, 0, b, 0, 0, 0, c];
+}
+
+/**
+ * 由 RGB 原色与其白点推导线性 RGB → XYZ 矩阵;白点不是 D65 时再经 Bradford 色适应到 D65,
+ * 与后续 BT.709 / sRGB 的 D65 目标对齐。
+ */
+function rgbToXyz({ r, g, b, white }: Chromaticities): Mat3 {
+ const [rx, ry, rz] = xyToXyz(r);
+ const [gx, gy, gz] = xyToXyz(g);
+ const [bx, by, bz] = xyToXyz(b);
+ const primaries: Mat3 = [rx, gx, bx, ry, gy, by, rz, gz, bz];
+ const toXyz = multiply(primaries, diagonal(apply(invert(primaries), xyToXyz(white))));
+ if (white === D65) return toXyz;
+ const [ls, ms, ss] = apply(BRADFORD, xyToXyz(white));
+ const [ld, md, sd] = apply(BRADFORD, xyToXyz(D65));
+ const scale = diagonal([ld / ls, md / ms, sd / ss]);
+ return multiply(multiply(invert(BRADFORD), multiply(scale, BRADFORD)), toXyz);
+}
+
+function pqToNits(encoded: number): number {
+ const m1 = 2610 / 16384;
+ const m2 = (2523 / 4096) * 128;
+ const c1 = 3424 / 4096;
+ const c2 = (2413 / 4096) * 32;
+ const c3 = (2392 / 4096) * 32;
+ const p = Math.pow(Math.max(encoded, 0), 1 / m2);
+ return 10_000 * Math.pow(Math.max(p - c1, 0) / (c2 - c3 * p), 1 / m1);
+}
+
+/** BT.2100 HLG 逆 OETF:非线性信号 → 归一化场景线性光 [0, 1]。 */
+function hlgToSceneLinear(encoded: number): number {
+ const a = 0.17883277;
+ const b = 1 - 4 * a;
+ const c = 0.5 - a * Math.log(4 * a);
+ const e = Math.max(encoded, 0);
+ return e <= 0.5 ? (e * e) / 3 : (Math.exp((e - c) / a) + b) / 12;
+}
+
+function srgbEncode(linear: number): number {
+ return linear <= 0.0031308 ? 12.92 * linear : 1.055 * Math.pow(linear, 1 / 2.4) - 0.055;
+}
+
+/** maxRGB 高光压缩:knee 以下恒等,(knee, peak] 用扩展 Reinhard 平滑压进 (knee, 1]。 */
+function toneMapMax(max: number, peak: number): number {
+ if (max <= TONE_MAP_KNEE || peak <= 1) return Math.min(max, 1);
+ if (max >= peak) return 1;
+ const t = (max - TONE_MAP_KNEE) / (1 - TONE_MAP_KNEE);
+ const white = (peak - TONE_MAP_KNEE) / (1 - TONE_MAP_KNEE);
+ return TONE_MAP_KNEE + (1 - TONE_MAP_KNEE) * ((t * (1 + t / (white * white))) / (1 + t));
+}
+
+const yieldToEventLoop = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+// ── 转换 ────────────────────────────────────────────────────────────────────
+
+async function encode(pipeline: Sharp, format: AvatarFormat): Promise<AvatarImageBytes> {
+ if (format === 'png') return { buffer: await pipeline.png().toBuffer(), mimeType: 'image/png' };
+ if (format === 'webp')
+ return { buffer: await pipeline.webp({ quality: 90 }).toBuffer(), mimeType: 'image/webp' };
+ return { buffer: await pipeline.jpeg({ quality: 90 }).toBuffer(), mimeType: 'image/jpeg' };
+}
+
+/**
+ * 两条转换路径共用的解码入口:EXIF 方向烘焙进像素,源图受 HDR_MAX_INPUT_PIXELS 约束,
+ * 按旋转后的尺寸超出 HDR_MAX_PIXELS 时等比缩小。
+ */
+function openHdrSource(buffer: Buffer, metadata: Metadata, ignoreIcc: boolean): Sharp {
+ const pipeline = sharp(buffer, {
+ ignoreIcc,
+ autoOrient: true,
+ limitInputPixels: HDR_MAX_INPUT_PIXELS,
+ });
+ const width = metadata.autoOrient?.width ?? metadata.width ?? 0;
+ const height = metadata.autoOrient?.height ?? metadata.height ?? 0;
+ if (width * height <= HDR_MAX_PIXELS) return pipeline;
+ const scale = Math.sqrt(HDR_MAX_PIXELS / (width * height));
+ return pipeline.resize(
+ Math.max(1, Math.floor(width * scale)),
+ Math.max(1, Math.floor(height * scale)),
+ { fit: 'fill' },
+ );
+}
+
+/**
+ * 增益图 JPEG:主图即 SDR 版本。sharp 默认不保留增益图、XMP 与 MPF 次图,
+ * 保留主图 ICC(常见为 Display P3)以免改变 SDR 颜色。
+ */
+async function dropGainMap(buffer: Buffer, metadata: Metadata): Promise<AvatarImageBytes> {
+ return encode(openHdrSource(buffer, metadata, false).keepIccProfile(), 'jpeg');
+}
+
+async function toneMapToSdr(
+ buffer: Buffer,
+ metadata: Metadata,
+ format: AvatarFormat,
+ cicp: Cicp,
+ primaries: Chromaticities,
+ transfer: HdrTransfer,
+ maxCllNits: number | null,
+): Promise<AvatarImageBytes> {
+ const wide = metadata.depth === 'ushort';
+ // ignoreIcc:像素必须保持 PQ / HLG 编码原值,不能先被 lcms 按 ICC 转成 sRGB(会过曝裁切)。
+ const { data, info } = await openHdrSource(buffer, metadata, true)
+ .toColourspace(wide ? 'rgb16' : 'srgb')
+ .raw({ depth: wide ? 'ushort' : 'uchar' })
+ .toBuffer({ resolveWithObject: true });
+ const channels = info.channels;
+ if (channels < 3) throw new Error('unexpected channel count');
+ const source = wide
+ ? new Uint16Array(data.buffer, data.byteOffset, data.byteLength / 2)
+ : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ const maxCode = wide ? 65535 : 255;
+
+ // 码值 → 线性:PQ 直接到「相对参考白」的显示线性;HLG 先到场景线性,OOTF 需逐像素亮度。
+ const narrowScale = wide ? 256 : 1;
+ const decode = new Float32Array(maxCode + 1);
+ for (let code = 0; code <= maxCode; code++) {
+ const signal = cicp.fullRange
+ ? code / maxCode
+ : (code - 16 * narrowScale) / (219 * narrowScale);
+ decode[code] =
+ transfer === 'pq' ? pqToNits(signal) / HDR_REFERENCE_WHITE_NITS : hlgToSceneLinear(signal);
+ }
+ const encodeLut = new Uint8Array(65536);
+ for (let index = 0; index < encodeLut.length; index++) {
+ encodeLut[index] = Math.round(srgbEncode(index / 65535) * 255);
+ }
+
+ const sourceToXyz = rgbToXyz(primaries);
+ const toBt709 = multiply(invert(rgbToXyz(BT709)), sourceToXyz);
+ const [yr, yg, yb] = [sourceToXyz[3], sourceToXyz[4], sourceToXyz[5]];
+ const peakNits =
+ transfer === 'pq'
+ ? Math.min(Math.max(maxCllNits ?? DEFAULT_HDR_PEAK_NITS, HDR_REFERENCE_WHITE_NITS), 10_000)
+ : DEFAULT_HDR_PEAK_NITS;
+ const peak = peakNits / HDR_REFERENCE_WHITE_NITS;
+
+ const pixels = info.width * info.height;
+ const out = Buffer.alloc(pixels * channels);
+ for (let start = 0; start < pixels; start += PIXELS_PER_YIELD) {
+ const end = Math.min(pixels, start + PIXELS_PER_YIELD);
+ for (let pixel = start; pixel < end; pixel++) {
+ const i = pixel * channels;
+ let r = decode[source[i]!]!;
+ let g = decode[source[i + 1]!]!;
+ let b = decode[source[i + 2]!]!;
+ if (transfer === 'hlg') {
+ // BT.2100 OOTF(γ = 1.2,Lw = 1000)后再相对参考白归一。
+ const ys = yr * r + yg * g + yb * b;
+ const gain =
+ (DEFAULT_HDR_PEAK_NITS * Math.pow(Math.max(ys, 0), 0.2)) / HDR_REFERENCE_WHITE_NITS;
+ r *= gain;
+ g *= gain;
+ b *= gain;
+ }
+ const lr = Math.max(0, toBt709[0] * r + toBt709[1] * g + toBt709[2] * b);
+ const lg = Math.max(0, toBt709[3] * r + toBt709[4] * g + toBt709[5] * b);
+ const lb = Math.max(0, toBt709[6] * r + toBt709[7] * g + toBt709[8] * b);
+ const max = Math.max(lr, lg, lb);
+ const scale = max > 0 ? toneMapMax(max, peak) / max : 0;
+ out[i] = encodeLut[Math.round(Math.min(lr * scale, 1) * 65535)]!;
+ out[i + 1] = encodeLut[Math.round(Math.min(lg * scale, 1) * 65535)]!;
+ out[i + 2] = encodeLut[Math.round(Math.min(lb * scale, 1) * 65535)]!;
+ // Alpha 为直通(非预乘)通道,只做位深缩放。
+ if (channels === 4)
+ out[i + 3] = wide ? Math.round((source[i + 3]! * 255) / 65535) : source[i + 3]!;
+ }
+ if (end < pixels) await yieldToEventLoop();
+ }
+ // 输出不带 ICC / cICP / EXIF,即隐式 sRGB 8-bit;方向已在解码时烘焙。
+ return encode(
+ sharp(out, { raw: { width: info.width, height: info.height, channels: channels as 3 | 4 } }),
+ format,
+ );
+}
+
+/**
+ * 头像入口统一调用:HDR 输入返回转换后的 SDR 字节与真实 MIME,其它输入原样返回
+ * 同一对象。头部无法解析且字节中没有 HDR 信号时按既有行为放行;带 HDR 信号却无法
+ * 解析、超限、为多帧动画或转换失败时一律拒绝,不把 HDR 字节静默落库或上传,也不把
+ * 动画静默压成首帧。
+ */
+export async function toSdrAvatarImage(image: AvatarImageBytes): Promise<AvatarImageBytes> {
+ const format = sniffFormat(image.buffer);
+ if (!format) return image;
+ const png =
+ format === 'png'
+ ? readPngHdrChunks(image.buffer)
+ : { cicp: null, maxCllNits: null, animated: false };
+ let metadata: Metadata;
+ try {
+ // 只读头部、不解码像素:关闭默认像素上限,超大 HDR 才能被识别并在下方按尺寸拒绝。
+ metadata = await sharp(image.buffer, { limitInputPixels: false }).metadata();
+ } catch {
+ if (hdrTransferOf(png.cicp)) {
+ throwIpcError('INVALID_PARAMS', 'HDR avatar could not be converted to SDR');
+ }
+ return image;
+ }
+ // PNG 规范:cICP 优先于 iCCP;其它格式只有 ICC 能声明传递函数。
+ const cicp = png.cicp ?? readIccCicp(metadata.icc);
+ const transfer = hdrTransferOf(cicp);
+ const gainMap = format === 'jpeg' && Boolean(metadata.gainMap);
+ if (!transfer && !gainMap) return image;
+ // 转换只处理单帧:动画 WebP(pages > 1)与 APNG(acTL;libvips 只读首帧)都会丢帧。
+ if ((metadata.pages ?? 1) > 1 || png.animated) {
+ throwIpcError('INVALID_PARAMS', 'Animated HDR avatars cannot be converted to SDR');
+ }
+ if ((metadata.width ?? 0) * (metadata.height ?? 0) > HDR_MAX_INPUT_PIXELS) {
+ throwIpcError('INVALID_PARAMS', 'HDR avatar dimensions exceed the conversion limit');
+ }
+ const primaries = cicp ? primariesFor(cicp.primaries) : null;
+ if (transfer && !primaries) {
+ throwIpcError('INVALID_PARAMS', 'HDR avatar declares unsupported colour primaries');
+ }
+ try {
+ return transfer && cicp && primaries
+ ? await toneMapToSdr(image.buffer, metadata, format, cicp, primaries, transfer, png.maxCllNits)
+ : await dropGainMap(image.buffer, metadata);
+ } catch {
+ throwIpcError('INVALID_PARAMS', 'HDR avatar could not be converted to SDR');
+ }
+}
diff --git a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts
index c59670df59..da9654e429 100644
--- a/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts
+++ b/apps/desktop/src/main/localDb/ipc/botAvatarSelection.ts
@@ -3,6 +3,7 @@ import { app } from 'electron';
import { writeBlob } from '../../cindy-media/blobStore.js';
import { recordBlob, type LedgerDb } from '../../cindy-media/ledger.js';
import { sniffImageMime } from '../../lightboxMediaActions.js';
+import { toSdrAvatarImage } from '../../hdrAvatarToSdr.js';
import { throwIpcError } from '../../utils/ipcValidate.js';
import { BOT_AVATAR_MAX_BYTES } from '../../../shared/botAvatarValue.js';
@@ -37,14 +38,20 @@ export function decodeBotAvatarImage(value: unknown): { buffer: Buffer; mimeType
return { buffer, mimeType: validateBotAvatarBuffer(buffer) };
}
-/** Shared upload/migration ingress; the caller atomically attaches the returned blob to the profile. */
+/**
+ * Shared upload/migration ingress; the caller atomically attaches the returned blob to the profile.
+ * HDR uploads (local picker, phone, import) are stored as real SDR bytes; SDR bytes are unchanged.
+ */
export async function storeTeammateAvatarImage(
image: { buffer: Buffer; mimeType: string },
db: LedgerDb,
assertCurrent: () => void,
) {
assertCurrent();
- const written = await writeBlob({ buffer: image.buffer, mimeType: validateBotAvatarBuffer(image.buffer) });
+ validateBotAvatarBuffer(image.buffer);
+ const sdr = await toSdrAvatarImage(image);
+ assertCurrent();
+ const written = await writeBlob({ buffer: sdr.buffer, mimeType: validateBotAvatarBuffer(sdr.buffer) });
assertCurrent();
await recordBlob({ hash: written.hash, ext: written.ext, mimeType: written.mimeType, bytes: written.bytes, isCache: false }, db);
assertCurrent();
diff --git a/apps/desktop/src/main/profileEdit.ts b/apps/desktop/src/main/profileEdit.ts
index d6109b3791..d031d9b1a7 100644
--- a/apps/desktop/src/main/profileEdit.ts
+++ b/apps/desktop/src/main/profileEdit.ts
@@ -40,12 +40,19 @@ export const AVATAR_FILE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp'];
export interface ProfileEditDeps {
/** 当前登录用户 id;未登录 null。 */
getCurrentUserId(): string | null;
+ /**
+ * 当前账号会话的不透明标识(appSessionState.activeOwnerScopeKey):模式、账号或
+ * 区域任一切换都会变化,跨 await 的账号副作用前后比对它。
+ */
+ getAccountScopeKey(): string;
/** 当前展示资料(authManager.getServerProfile,弹窗预填 + 改名去重用)。 */
getServerProfile(): { name: string; avatar: string | null } | null;
/** 弹系统文件选择器,返回所选路径;取消返回 null。 */
showAvatarOpenDialog(): Promise<string | null>;
/** 读文件字节(fs.promises.readFile)。 */
readFile(filePath: string): Promise<Buffer>;
+ /** HDR 头像转 SDR(hdrAvatarToSdr.toSdrAvatarImage);SDR 原样返回。 */
+ toSdrAvatar(image: { buffer: Buffer; mimeType: string }): Promise<{ buffer: Buffer; mimeType: string }>;
/** 头像直传 OSS(ossPublicUpload.uploadPublicAsset 的 avatar 场景特化)。 */
uploadAvatar(params: { buffer: Uint8Array; mimeType: string }): Promise<
| { ok: true; publicUrl: string }
@@ -99,6 +106,16 @@ function requireUserId(deps: ProfileEditDeps): string {
return userId;
}
+/**
+ * 保存过程中每次 await 之后、触达账号的副作用(上传 / PATCH)之前复查:上传与 PATCH
+ * 都按调用时的登录态取 token,中途切换账号(含同 id 换区域)会把资料写到新账号上。
+ */
+function requireSameAccount(deps: ProfileEditDeps, accountScope: string): void {
+ if (deps.getAccountScopeKey() !== accountScope) {
+ throwIpcError('PRECONDITION_FAILED', 'account changed while saving profile');
+ }
+}
+
function parseAvatarAction(value: unknown): AvatarAction | null {
if (value === null || typeof value !== 'object') return null;
const action = value as { type?: unknown; filePath?: unknown };
@@ -121,7 +138,8 @@ export function getProfileEditState(deps: ProfileEditDeps): ProfileEditState {
}
/**
- * 选头像文件:系统选择器 → 扩展名 / 体积校验 → 返回路径 + 预览 data URL。
+ * 选头像文件:系统选择器 → 扩展名 / 体积校验 → HDR 转 SDR → 返回路径 + 预览 data URL。
+ * 预览即转换后的 SDR 像素,与「保存」时上传的字节一致。
* 这里**不**上传——用户点「保存」才走 OSS 直传,取消弹窗零副作用。
*/
export async function chooseAvatarFile(deps: ProfileEditDeps): Promise<ChooseAvatarResult> {
@@ -141,26 +159,33 @@ export async function chooseAvatarFile(deps: ProfileEditDeps): Promise<ChooseAva
if (buffer.byteLength === 0 || buffer.byteLength > AVATAR_MAX_BYTES) {
throwIpcError('INVALID_PARAMS', `avatar file size out of range: ${buffer.byteLength}`);
}
+ const preview = await deps.toSdrAvatar({ buffer, mimeType: mime });
+ // 选图阶段就拒绝转换后超限的头像,不让用户在保存时才看到失败。
+ if (preview.buffer.byteLength > AVATAR_MAX_BYTES) {
+ throwIpcError('INVALID_PARAMS', `avatar file size out of range: ${preview.buffer.byteLength}`);
+ }
return {
canceled: false,
filePath,
- previewDataUrl: `data:${mime};base64,${buffer.toString('base64')}`,
+ previewDataUrl: `data:${preview.mimeType};base64,${preview.buffer.toString('base64')}`,
};
}
/**
* 保存资料:name 与 avatar 各自收敛成 PATCH 字段,一次提交服务端。
* - name:trim 后为空或与当前一致 → 不改;否则 displayName;
- * - avatar keep:不动;set:校验 → OSS 直传拿 publicUrl;reset:avatarUrl null;
+ * - avatar keep:不动;set:校验 → HDR 转 SDR → OSS 直传拿 publicUrl;reset:avatarUrl null;
* - 两个字段都没变化 → 直接成功返回,零网络请求。
* 上传成功但 PATCH 失败时,已传对象成为孤儿(bucket 生命周期规则兜底清理,
* 契约见 oss-server 文档),客户端无需补偿删除。
+ * 中途切换账号 → PRECONDITION_FAILED,不向新账号上传或 PATCH。
*/
export async function updateProfile(
deps: ProfileEditDeps,
rawParams: unknown,
): Promise<{ ok: true }> {
requireUserId(deps);
+ const accountScope = deps.getAccountScopeKey();
const profile = deps.getServerProfile();
if (!profile) throwIpcError('PRECONDITION_FAILED', 'not logged in');
@@ -200,7 +225,12 @@ export async function updateProfile(
if (buffer.byteLength === 0 || buffer.byteLength > AVATAR_MAX_BYTES) {
throwIpcError('INVALID_PARAMS', `avatar file size out of range: ${buffer.byteLength}`);
}
- const uploaded = await deps.uploadAvatar({ buffer, mimeType: mime });
+ const image = await deps.toSdrAvatar({ buffer, mimeType: mime });
+ if (image.buffer.byteLength > AVATAR_MAX_BYTES) {
+ throwIpcError('INVALID_PARAMS', `avatar file size out of range: ${image.buffer.byteLength}`);
+ }
+ requireSameAccount(deps, accountScope);
+ const uploaded = await deps.uploadAvatar(image);
if (!uploaded.ok) {
throwIpcError(
'PROFILE_AVATAR_UPLOAD_FAILED',
@@ -216,6 +246,7 @@ export async function updateProfile(
if (nextDisplayName === undefined && nextAvatarUrl === undefined) {
return { ok: true };
}
+ requireSameAccount(deps, accountScope);
const patched = await deps.patchProfile({
...(nextDisplayName !== undefined ? { displayName: nextDisplayName } : {}),
...(nextAvatarUrl !== undefined ? { avatarUrl: nextAvatarUrl } : {}),