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(mobile): 标注审查跟进——崩溃不再为预热重挂、HEIC 转 JPEG、直接转发保持原尺寸

Dashfe8e2706dc1e
diff --git a/apps/mobile/src/__tests__/annotationBurnInQueue.test.ts b/apps/mobile/src/__tests__/annotationBurnInQueue.test.ts
index 62310b3344..cd8c95e88a 100644
--- a/apps/mobile/src/__tests__/annotationBurnInQueue.test.ts
+++ b/apps/mobile/src/__tests__/annotationBurnInQueue.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
BURN_IN_TIMEOUT_MS,
+ MAX_CONSECUTIVE_CRASH_REMOUNTS,
WEBVIEW_READY_TIMEOUT_MS,
createAnnotationBurnInQueue,
type AnnotationBurnInQueue,
@@ -228,4 +229,40 @@ describe('annotation burn-in queue', () => {
expect((await settled(a)).value).toBeDefined();
expect(host.mounted).toBeNull();
});
+
+ it('does not remount for a prewarm after a crash, so a crashing webview cannot loop', async () => {
+ const { queue, host } = setup();
+ const release = queue.acquireWarm();
+ expect(host.mounts).toEqual([1]);
+ queue.handleProcessGone(1, 'render process gone');
+ expect(host.mounted).toBeNull(); // 仅预热持有:崩溃后卸载,不重挂
+ queue.handleProcessGone(1, 'duplicate event');
+ const again = queue.acquireWarm(); // 同一标注会话里再次预热也不重挂
+ expect(host.mounts).toEqual([1]);
+ // 用户真正提交时才重新挂载。
+ const job = queue.burnIn(input);
+ expect(host.mounts).toEqual([1, 2]);
+ ready(queue, 2);
+ reply(queue, 2, 'burn-1');
+ expect((await settled(job)).value).toBeDefined();
+ again();
+ release();
+ expect(host.mounted).toBeNull();
+ // 预热全部释放后,下一次标注会话可以重新预热。
+ queue.acquireWarm();
+ expect(host.mounts).toEqual([1, 2, 3]);
+ });
+
+ it('caps consecutive crash remounts and fails the remaining jobs', async () => {
+ const { queue, host } = setup();
+ queue.acquireWarm();
+ const jobs = Array.from({ length: 6 }, () => queue.burnIn(input));
+ for (let crash = 0; crash <= MAX_CONSECUTIVE_CRASH_REMOUNTS; crash++) {
+ queue.handleProcessGone(host.mounted!, 'render process gone');
+ }
+ const outcomes = await Promise.all(jobs.map(settled));
+ expect(outcomes.every((o) => o.error?.message.includes('terminated'))).toBe(true);
+ expect(host.mounts).toHaveLength(MAX_CONSECUTIVE_CRASH_REMOUNTS + 1);
+ expect(host.mounted).toBeNull();
+ });
});
diff --git a/apps/mobile/src/__tests__/imageAnnotationModel.test.ts b/apps/mobile/src/__tests__/imageAnnotationModel.test.ts
index 2f109fd42a..b5056b0150 100644
--- a/apps/mobile/src/__tests__/imageAnnotationModel.test.ts
+++ b/apps/mobile/src/__tests__/imageAnnotationModel.test.ts
@@ -189,11 +189,17 @@ describe('planAnnotationBurnSource(烧录前预处理)', () => {
.toMatchObject({ resize: { width: 2048 }, format: 'png' });
});
- it('Android 上 HEIC / AVIF 即使是小图也先转码为 PNG;iOS 小图维持原路径', () => {
+ it('Android 上 HEIC / AVIF 即使是小图 / 尺寸未知也先转码为高质量 JPEG;iOS 小图维持原路径', () => {
expect(planAnnotationBurnSource({ mimeType: 'image/heic', platformOS: 'android', naturalWidth: 800, naturalHeight: 600 }))
- .toEqual({ resize: null, format: 'png', compress: 1, strokeSpace: null });
+ .toEqual({ resize: null, format: 'jpeg', compress: 0.92, strokeSpace: null });
expect(planAnnotationBurnSource({ mimeType: 'image/avif', platformOS: 'android' }))
- .toMatchObject({ resize: null, format: 'png' });
+ .toMatchObject({ resize: null, format: 'jpeg', compress: 0.92 });
+ // 转码 + 预缩同时发生时仍是 JPEG。
+ expect(planAnnotationBurnSource({ mimeType: 'image/heif', platformOS: 'android', naturalWidth: 4032, naturalHeight: 3024 }))
+ .toMatchObject({ resize: { width: 2048 }, format: 'jpeg', compress: 0.92, strokeSpace: { width: 4032, height: 3024 } });
+ // iOS 大 HEIC 只预缩,保持无损 PNG(与既有非 JPEG 源的输出格式一致)。
+ expect(planAnnotationBurnSource({ mimeType: 'image/heic', platformOS: 'ios', naturalWidth: 4032, naturalHeight: 3024 }))
+ .toMatchObject({ format: 'png', compress: 1 });
expect(planAnnotationBurnSource({ mimeType: 'image/heic', platformOS: 'ios', naturalWidth: 800, naturalHeight: 600 })).toBeNull();
});
diff --git a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
index c6b65347f6..2d8eaac635 100644
--- a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
+++ b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
@@ -599,10 +599,24 @@ describe("annotation drawing", () => {
expect(annotating()).toBe(true);
});
- it("lets the host keep the pen disabled (pending replacement)", () => {
- mount({ annotation: { submitLabel: "Save", onSubmit: vi.fn(), canAnnotate: () => false } });
+ it("explains why the pen is unavailable when the host blocks annotation (pending replacement)", () => {
+ let reason: string | undefined = "Still uploading";
+ mount({ annotation: { submitLabel: "Save", onSubmit: vi.fn(), annotationBlockedReason: () => reason } });
load();
- expect(runtime.nodes.get("message.imageLightboxAnnotateButton").disabled).toBe(true);
+ const pen = () => runtime.nodes.get("message.imageLightboxAnnotateButton");
+ // 置灰但可点:点按说明原因,不进入标注。
+ expect(pen().disabled).toBe(false);
+ expect(pen().accessibilityLabel).toBe("message.lightbox.annotateImageUnavailable");
+ expect(pen().accessibilityHint).toBe("Still uploading");
+ press("message.imageLightboxAnnotateButton");
+ expect(runtime.alerts).toEqual([["message.lightbox.annotateUnavailableTitle", "Still uploading"]]);
+ expect(annotating()).toBe(false);
+ // 阻塞解除后(下次渲染)恢复正常。
+ reason = undefined;
+ act(() => runtime.nodes.get("Image").onLoad({ source: { width: 401, height: 800 } }));
+ expect(pen().accessibilityLabel).toBe("message.lightbox.annotateImage");
+ press("message.imageLightboxAnnotateButton");
+ expect(annotating()).toBe(true);
});
it("drops the stray dot left when a second finger starts a pinch, but keeps taps and real strokes", async () => {
diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
index d46d24e946..c82984a321 100644
--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
@@ -991,23 +991,33 @@ describe('onAbandoned(自生成输入文件的生命周期回收)', () => {
expect(abandoned).toHaveBeenCalledTimes(1);
});
- it('removeAll / dispose / 退屏后入队 都视为放弃', async () => {
+ it('removeAll / dispose / 退屏后入队 都视为放弃,每个任务恰好回调一次', async () => {
const a = vi.fn();
const b = vi.fn();
+ const c = vi.fn();
+ const e = vi.fn();
const { deps } = makeDeps({ upload: () => new Promise(() => undefined) });
const controller = createMobileLocalAttachmentUploadController(deps);
controller.enqueue([
{ ...candidate('a.jpg'), onAbandoned: a },
{ ...candidate('b.jpg'), onAbandoned: b },
- { ...candidate('c.jpg'), onAbandoned: b },
+ { ...candidate('c.jpg'), onAbandoned: c },
], { token: 't' });
+ await flush(); // a / b 开跑(并发 2),c 排队
controller.removeAll();
+ expect(c).toHaveBeenCalledTimes(1); // 排队中:立即回调
+ await flush(); // in-flight 的 a / b 在任务落定后回调
+ expect(a).toHaveBeenCalledTimes(1);
+ expect(b).toHaveBeenCalledTimes(1);
+ controller.enqueue([{ ...candidate('e.jpg'), onAbandoned: e }], { token: 't' });
await flush();
- expect(b).toHaveBeenCalled(); // 排队中的 c 立即回调
- const d = vi.fn();
controller.dispose();
+ await flush();
+ controller.removeAll(); // 重复放弃不会二次回调
+ await flush();
+ const d = vi.fn();
controller.enqueue([{ ...candidate('d.jpg'), onAbandoned: d }], { token: 't' });
- expect(d).toHaveBeenCalledTimes(1);
+ for (const fn of [a, b, c, e, d]) expect(fn).toHaveBeenCalledTimes(1);
});
it('交接给持久发件箱:提交后才回调(文件已复制),回滚不回调', async () => {
diff --git a/apps/mobile/src/__tests__/useComposerImageAnnotations.test.tsx b/apps/mobile/src/__tests__/useComposerImageAnnotations.test.tsx
index e041ec2c57..267d4e103e 100644
--- a/apps/mobile/src/__tests__/useComposerImageAnnotations.test.tsx
+++ b/apps/mobile/src/__tests__/useComposerImageAnnotations.test.tsx
@@ -19,6 +19,8 @@ const runtime = vi.hoisted(() => ({
manipulatorResult: null as null | { width: number; height: number },
manipulatorError: null as Error | null,
manipulatorSeq: 0,
+ /** uri 前缀 → getInfoAsync 字节数(未命中默认 1234)。 */
+ sizes: {} as Record<string, number>,
burnIn: null as unknown as ReturnType<typeof vi.fn>,
acquireWarm: null as unknown as ReturnType<typeof vi.fn>,
}));
@@ -35,7 +37,10 @@ vi.mock('expo-file-system/legacy', () => ({
cacheDirectory: 'file:///cache/',
EncodingType: { Base64: 'base64' },
makeDirectoryAsync: async () => undefined,
- getInfoAsync: async () => ({ exists: true, size: 1234 }),
+ getInfoAsync: async (uri: string) => ({
+ exists: true,
+ size: Object.entries(runtime.sizes).find(([prefix]) => uri.startsWith(prefix))?.[1] ?? 1234,
+ }),
// 头部嗅探读不出魔数 → 以调用方给的 mime 为准。
readAsStringAsync: async (_uri: string, options?: { length?: number }) => (options?.length ? '' : 'QUJD'),
writeAsStringAsync: async (uri: string) => { runtime.written.push(uri); },
@@ -84,6 +89,7 @@ beforeEach(() => {
runtime.manipulatorResult = null;
runtime.manipulatorError = null;
runtime.manipulatorSeq = 0;
+ runtime.sizes = {};
runtime.burnIn = vi.fn(async (input: { mimeType: string }) => ({
base64: 'b3V0',
mimeType: input.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/png',
@@ -207,12 +213,13 @@ describe('re-edit replacement', () => {
const hook = mountHook({ getAttachment: (id) => attachments.get(id) });
const original = await seedAnnotated(hook, 'A');
attachments.set('A', attachment('A', { annotated: true }));
- expect(hook.api().trayAnnotation.canAnnotate?.(image('A'))).toBe(true);
+ expect(hook.api().trayAnnotation.annotationBlockedReason?.(image('A'))).toBeUndefined();
await traySubmit(hook.api(), 'A', hook.api().trayImageSourceUri('A', 'preview'));
const replacement = hook.enqueued().at(-1)!;
expect(replacement.replacesAttachmentId).toBe('A');
- // 替换未落定:画笔禁用,且直接提交也被拒绝(不会产生第二份替换)。
- expect(hook.api().trayAnnotation.canAnnotate?.(image('A'))).toBe(false);
+ // 替换未落定:画笔置灰并给出原因,且直接提交也被拒绝(不会产生第二份替换)。
+ expect(hook.api().trayAnnotation.annotationBlockedReason?.(image('A')))
+ .toBe('composer.attachments.replacementPending');
await expect(Promise.resolve(
hook.api().trayAnnotation.onSubmit(image('A'), 'x', STROKES, {}),
)).rejects.toThrow('composer.attachments.replacementPending');
@@ -234,7 +241,7 @@ describe('re-edit replacement', () => {
await traySubmit(hook.api(), 'A', hook.api().trayImageSourceUri('A', 'preview'));
const replacement = hook.enqueued().at(-1)!;
replacement.onAbandoned?.();
- expect(hook.api().trayAnnotation.canAnnotate?.(image('A'))).toBe(true);
+ expect(hook.api().trayAnnotation.annotationBlockedReason?.(image('A'))).toBeUndefined();
// 只删替换自己的烧录图;与 A 共享的源副本仍被 A 引用。
expect(runtime.deleted).toEqual([replacement.uri]);
expect(runtime.deleted).not.toContain(original.annotation?.sourceUri);
@@ -272,25 +279,35 @@ describe('re-edit replacement', () => {
});
describe('burn source preparation', () => {
- it('transcodes HEIC with the native manipulator on Android before burning, and falls back when it fails', async () => {
+ it('transcodes HEIC to high-quality JPEG with the native manipulator on Android, and falls back when it fails', async () => {
runtime.platform = 'android';
const hook = mountHook();
await chatSubmit(hook.api(), 'file:///photos/x.heic', [], { mimeType: 'image/heic' });
expect(runtime.manipulations).toHaveLength(1);
expect(runtime.manipulations[0].resize).toBeUndefined();
- expect(runtime.manipulations[0].save).toEqual({ format: 'png', compress: 1 });
- expect(runtime.burnIn).toHaveBeenLastCalledWith(expect.objectContaining({ mimeType: 'image/png', strokes: [] }));
+ expect(runtime.manipulations[0].save).toEqual({ format: 'jpeg', compress: 0.92 });
+ expect(runtime.burnIn).toHaveBeenLastCalledWith(expect.objectContaining({ mimeType: 'image/jpeg', strokes: [] }));
expect(runtime.burnIn.mock.calls[0][0]).not.toHaveProperty('strokeSpace');
expect(runtime.deleted).toContain('file:///cache/ImageManipulator/out-1'); // 中间产物烧完即删
- expect(hook.enqueued()[0].mimeType).toBe('image/png');
+ expect(hook.enqueued()[0].mimeType).toBe('image/jpeg');
expect(hook.enqueued()[0].annotation).toBeUndefined();
- expect(hook.enqueued()[0].name).toMatch(/^image-\d+\.png$/);
+ expect(hook.enqueued()[0].name).toMatch(/^image-\d+\.jpg$/);
runtime.manipulatorError = new Error('unsupported');
await chatSubmit(hook.api(), 'file:///photos/y.heic', [], { mimeType: 'image/heic' });
expect(runtime.burnIn).toHaveBeenLastCalledWith(expect.objectContaining({ mimeType: 'image/heic' }));
});
+ it('falls back to the original path when the transcoded file exceeds the source size limit', async () => {
+ runtime.platform = 'android';
+ runtime.sizes['file:///cache/ImageManipulator/'] = 31 * 1024 * 1024;
+ const hook = mountHook();
+ await chatSubmit(hook.api(), 'file:///photos/x.heic', STROKES, { mimeType: 'image/heic' });
+ expect(runtime.manipulations).toHaveLength(1);
+ expect(runtime.deleted).toContain('file:///cache/ImageManipulator/out-1');
+ expect(runtime.burnIn).toHaveBeenLastCalledWith(expect.objectContaining({ mimeType: 'image/heic' }));
+ });
+
it('keeps the existing WebView path for HEIC on iOS', async () => {
const hook = mountHook();
await chatSubmit(hook.api(), 'file:///photos/x.heic', [], { mimeType: 'image/heic', naturalWidth: 800, naturalHeight: 600 });
@@ -329,14 +346,16 @@ describe('burn source preparation', () => {
expect(hook.enqueued()[0]).toMatchObject({ width: 4032, height: 3024 });
});
- it('forwards the viewer size on direct (stroke-free) forwarding so preprocess can downscale', async () => {
+ it('does not pass the viewer size on direct (stroke-free) forwarding, keeping the original resolution policy', async () => {
const hook = mountHook();
await chatSubmit(hook.api(), 'file:///photos/shot.png', [], { mimeType: 'image/png', naturalWidth: 3000, naturalHeight: 2000 });
expect(runtime.burnIn).not.toHaveBeenCalled();
- expect(hook.enqueued()[0]).toMatchObject({ mimeType: 'image/png', width: 3000, height: 2000 });
- expect(hook.enqueued()[0].skipPreprocess).toBeUndefined();
- await chatSubmit(hook.api(), 'file:///photos/shot2.png', [], { mimeType: 'image/png' });
- expect(hook.enqueued()[1].width).toBeUndefined();
+ expect(runtime.manipulations).toHaveLength(0);
+ const candidate = hook.enqueued()[0];
+ expect(candidate).toMatchObject({ mimeType: 'image/png', size: 1234 });
+ expect(candidate.width).toBeUndefined();
+ expect(candidate.height).toBeUndefined();
+ expect(candidate.skipPreprocess).toBeUndefined();
});
it('exposes burn-in prewarm on both lightbox configs', () => {
diff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
new file mode 100644
index 0000000000..fd158c1215
--- /dev/null
+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
@@ -0,0 +1,122 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { MobileLocalAttachmentUploadCandidate } from '@/session/mobileLocalAttachmentUpload';
+import {
+ useMobileLocalAttachments,
+ type UseMobileLocalAttachmentsOptions,
+ type UseMobileLocalAttachmentsResult,
+} from '@/session/useMobileLocalAttachments';
+
+const runtime = vi.hoisted(() => ({
+ uploads: [] as Array<{ name: string; resolve: () => void }>,
+ discarded: [] as unknown[],
+}));
+
+vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }));
+vi.mock('react-i18next', async (importOriginal) => {
+ const t = (key: string) => key;
+ return { ...await importOriginal<typeof import('react-i18next')>(), useTranslation: () => ({ t }) };
+});
+vi.mock('expo-document-picker', () => ({}));
+vi.mock('expo-image-picker', () => ({}));
+vi.mock('expo-file-system/legacy', () => ({
+ documentDirectory: 'file:///docs/',
+ deleteAsync: async () => undefined,
+}));
+vi.mock('@/session/durableOutboxFiles', () => ({
+ retainComposerAttachmentFile: async (_owner: string, id: string) => `file:///stage/${id}`,
+}));
+vi.mock('@/session/sentAttachmentThumbStore', () => ({
+ getSentAttachmentThumbUri: () => null,
+ registerSentAttachmentThumb: async () => undefined,
+}));
+vi.mock('@/session/mobileAttachmentUpload', () => ({
+ statMobileAttachmentFileSize: async () => 1000,
+ discardMobileUploadedAttachment: (attachment: unknown) => { runtime.discarded.push(attachment); },
+ uploadMobileAttachmentFromFile: (candidate: { name: string }) => new Promise((resolve) => {
+ runtime.uploads.push({
+ name: candidate.name,
+ resolve: () => resolve({
+ id: `att-${candidate.name}`,
+ name: candidate.name,
+ path: `cindy-oss-attach://key/${candidate.name}`,
+ ext: '.png',
+ size: 1000,
+ category: 'image',
+ mimeType: 'image/png',
+ }),
+ });
+ }),
+}));
+
+let root: Root;
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ runtime.uploads = [];
+ runtime.discarded = [];
+ root = createRoot(document.createElement('div'));
+});
+afterEach(() => act(() => root.unmount()));
+
+function mount(scopeKey: string) {
+ const options: UseMobileLocalAttachmentsOptions = {
+ attachmentScopeKey: scopeKey,
+ getAccessToken: async () => 'token',
+ getAttachmentCount: () => 0,
+ onUploaded: vi.fn(),
+ onError: vi.fn(),
+ };
+ const results: UseMobileLocalAttachmentsResult[] = [];
+ function Harness({ scope }: { scope: string }) {
+ results.push(useMobileLocalAttachments({ ...options, attachmentScopeKey: scope }));
+ return null;
+ }
+ act(() => root.render(<Harness scope={scopeKey} />));
+ return {
+ options,
+ first: results[0],
+ rerender: (scope: string) => act(() => root.render(<Harness scope={scope} />)),
+ };
+}
+
+const imageCandidate = (name: string, onAbandoned: () => void): MobileLocalAttachmentUploadCandidate => ({
+ kind: 'image',
+ uri: `file:///cache/annotation-burned/${name}`,
+ name,
+ size: 1000,
+ mimeType: 'image/png',
+ onAbandoned,
+});
+const flush = () => new Promise((resolve) => { setTimeout(resolve, 0); });
+
+describe('useMobileLocalAttachments abandonment on scope change', () => {
+ it('abandons a candidate enqueued from a stale scope without starting an upload', async () => {
+ const harness = mount('session-a');
+ act(() => harness.first.discardAllPendingUploadsForScopeChange());
+ const abandoned = vi.fn();
+ act(() => harness.first.enqueueUploads([imageCandidate('late.png', abandoned)], { token: 'token' }));
+ await flush();
+ expect(abandoned).toHaveBeenCalledTimes(1);
+ expect(runtime.uploads).toHaveLength(0);
+ });
+
+ it('abandons exactly once when an upload finishes after the composer scope moved on', async () => {
+ const harness = mount('session-a');
+ const abandoned = vi.fn();
+ act(() => harness.first.enqueueUploads([imageCandidate('a.png', abandoned)], { token: 'token' }));
+ await act(async () => { await flush(); });
+ expect(runtime.uploads.map((u) => u.name)).toEqual(['a.png']);
+ // 作用域换到另一个任务,但旧任务没有被显式丢弃(防御性代际闸路径)。
+ harness.rerender('session-b');
+ await act(async () => {
+ runtime.uploads[0].resolve();
+ await flush();
+ await flush();
+ });
+ expect(harness.options.onUploaded).not.toHaveBeenCalled();
+ expect(runtime.discarded).toHaveLength(1);
+ expect(abandoned).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.json
index aa442130c7..d1d0ba2bbc 100644
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@ -19,7 +19,7 @@
"imageNotAnnotatable": "This image can't be annotated or forwarded.",
"downloadOriginalFailed": "Could not download the original image (HTTP {{status}}).",
"annotationSaveFailed": "Could not save annotation",
- "replacementPending": "The previous save of this image is still uploading. Edit it again after it finishes.",
+ "replacementPending": "Your last change to this image hasn’t finished uploading. Wait for it to finish, or retry or remove it above the input, then edit again.",
"tryAgain": "Try again.",
"sendToChat": "Send to Chat",
"save": "Save",
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 3184aadab6..1a1dd03e2a 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -160,10 +160,12 @@
"retryLoadImage": "Retry loading image",
"retry": "Retry",
"closeImage": "Close image",
- "discardAnnotationTitle": "Discard Annotation?",
+ "discardAnnotationTitle": "Discard annotation?",
"discardAnnotationBody": "Your unsaved strokes will be lost.",
- "continueAnnotating": "Keep Annotating",
- "discardAnnotation": "Discard"
+ "continueAnnotating": "Keep annotating",
+ "discardAnnotation": "Discard",
+ "annotateUnavailableTitle": "Can't annotate right now",
+ "annotateImageUnavailable": "Annotate image (unavailable)"
},
"queue": {
"continueSystemInstruction": "Continue the unfinished task (system instruction)",
diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.json
index 09b376c49d..c8b4c30c76 100644
--- a/apps/mobile/src/i18n/locales/ja/composer.json
+++ b/apps/mobile/src/i18n/locales/ja/composer.json
@@ -19,7 +19,7 @@
"imageNotAnnotatable": "この画像は注釈や転送に対応していません。",
"downloadOriginalFailed": "元の画像をダウンロードできませんでした(HTTP {{status}})。",
"annotationSaveFailed": "注釈を保存できませんでした",
- "replacementPending": "この画像の前回の保存はまだアップロード中です。完了してから編集してください。",
+ "replacementPending": "この画像への前回の変更はまだアップロードが完了していません。完了するまで待つか、入力欄の上で再試行または削除してから編集してください。",
"tryAgain": "もう一度お試しください。",
"sendToChat": "チャットに送信",
"save": "保存",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 068d7826c2..2a89fc4418 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -163,7 +163,9 @@
"discardAnnotationTitle": "注釈を破棄しますか?",
"discardAnnotationBody": "保存されていない描画は失われます。",
"continueAnnotating": "注釈を続ける",
- "discardAnnotation": "破棄"
+ "discardAnnotation": "破棄",
+ "annotateUnavailableTitle": "現在は注釈できません",
+ "annotateImageUnavailable": "画像に注釈(現在利用不可)"
},
"queue": {
"continueSystemInstruction": "未完了のタスクを続行(システム指令)",
diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.json
index 0ef65d2c96..e7da525126 100644
--- a/apps/mobile/src/i18n/locales/ko/composer.json
+++ b/apps/mobile/src/i18n/locales/ko/composer.json
@@ -19,7 +19,7 @@
"imageNotAnnotatable": "이 이미지는 주석이나 전달을 지원하지 않습니다.",
"downloadOriginalFailed": "원본 이미지를 다운로드하지 못했습니다(HTTP {{status}}).",
"annotationSaveFailed": "주석을 저장하지 못했습니다",
- "replacementPending": "이 이미지의 이전 저장이 아직 업로드 중입니다. 완료된 후 다시 편집하세요.",
+ "replacementPending": "이 이미지의 이전 변경 사항이 아직 업로드되지 않았습니다. 완료될 때까지 기다리거나 입력창 위에서 다시 시도하거나 삭제한 후 편집하세요.",
"tryAgain": "다시 시도하세요.",
"sendToChat": "대화로 보내기",
"save": "저장",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index afc6deb749..7aa102f6d6 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -163,7 +163,9 @@
"discardAnnotationTitle": "주석을 버릴까요?",
"discardAnnotationBody": "저장하지 않은 획은 사라집니다.",
"continueAnnotating": "계속 주석 달기",
- "discardAnnotation": "버리기"
+ "discardAnnotation": "버리기",
+ "annotateUnavailableTitle": "지금은 주석을 달 수 없음",
+ "annotateImageUnavailable": "이미지에 주석 (현재 사용 불가)"
},
"queue": {
"continueSystemInstruction": "완료되지 않은 작업 계속(시스템 지시)",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.json
index 60c3285dbd..0f1c80f05a 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@ -19,7 +19,7 @@
"imageNotAnnotatable": "这张图片暂不支持标注或转发。",
"downloadOriginalFailed": "下载原图失败(HTTP {{status}})。",
"annotationSaveFailed": "标注保存失败",
- "replacementPending": "这张图片上一次的保存仍在上传,完成后再编辑。",
+ "replacementPending": "这张图片的上一次修改还未上传完成,请等待完成,或在输入框上方重试或移除后再编辑。",
"tryAgain": "请重试。",
"sendToChat": "发送到对话",
"save": "保存",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index a5e68b37ca..df2bb86093 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -163,7 +163,9 @@
"discardAnnotationTitle": "放弃标注?",
"discardAnnotationBody": "未保存的笔迹将会丢失。",
"continueAnnotating": "继续标注",
- "discardAnnotation": "放弃标注"
+ "discardAnnotation": "放弃标注",
+ "annotateUnavailableTitle": "暂时无法标注",
+ "annotateImageUnavailable": "标注图片(暂不可用)"
},
"queue": {
"continueSystemInstruction": "继续未完成的任务(系统指令)",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/composer.json b/apps/mobile/src/i18n/locales/zh-TW/composer.json
index 6c892c0c2a..d7a220c906 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json
@@ -19,7 +19,7 @@
"imageNotAnnotatable": "這張圖片暫不支援標註或轉發。",
"downloadOriginalFailed": "下載原圖失敗(HTTP {{status}})。",
"annotationSaveFailed": "標註儲存失敗",
- "replacementPending": "這張圖片上一次的儲存仍在上傳,完成後再編輯。",
+ "replacementPending": "這張圖片的上一次修改尚未上傳完成,請等待完成,或在輸入框上方重試或移除後再編輯。",
"tryAgain": "請重試。",
"sendToChat": "傳送到對話",
"save": "儲存",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index f35fe632b5..4c7e0dd6eb 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -163,7 +163,9 @@
"discardAnnotationTitle": "放棄標註?",
"discardAnnotationBody": "未儲存的筆跡將會遺失。",
"continueAnnotating": "繼續標註",
- "discardAnnotation": "放棄標註"
+ "discardAnnotation": "放棄標註",
+ "annotateUnavailableTitle": "暫時無法標註",
+ "annotateImageUnavailable": "標註圖片(暫不可用)"
},
"queue": {
"continueSystemInstruction": "繼續未完成的任務(系統指令)",
diff --git a/apps/mobile/src/session/ImageLightbox.tsx b/apps/mobile/src/session/ImageLightbox.tsx
index 5266176ac8..aac6e6bd8e 100644
--- a/apps/mobile/src/session/ImageLightbox.tsx
+++ b/apps/mobile/src/session/ImageLightbox.tsx
@@ -144,10 +144,10 @@ export interface ImageLightboxAnnotationConfig {
*/
initialStrokesFor?: (image: MobileMessageGalleryImage) => readonly AnnotationStroke[] | undefined;
/**
- * 某页此刻能否进入标注(可选;缺省可以)。返回 false 时画笔按钮置灰禁用
- * (如托盘附件的替换上传尚未落定)。
+ * 某页此刻暂不能进入标注的原因(可选;返回 undefined = 可以)。有原因时画笔
+ * 按钮置灰但仍可点,点按弹出该说明(如托盘附件的上一次修改尚未上传完成)。
*/
- canAnnotate?: (image: MobileMessageGalleryImage) => boolean;
+ annotationBlockedReason?: (image: MobileMessageGalleryImage) => string | undefined;
/**
* 进入标注模式时调用(可选):宿主据此提前准备提交所需资源(烧录 WebView
* 预热)。返回的释放函数在退出标注 / 关闭查看器时调用。
@@ -560,15 +560,22 @@ export const ImageLightbox = memo(function ImageLightbox({
&& canAnnotateImageMime(activeMimeType)
&& !activeLooksGif
&& !activeLooksSvg;
- // 画笔要等图片自然尺寸就位(坐标换算基准),否则进入标注后作画静默无效;
- // 宿主也可暂时禁止(canAnnotate)。不满足时按钮置灰禁用,与撤销的禁用态同观感。
- const annotateEnabled = annotateVisible
- && !!activeNaturalSize
- && (!activeImage || !annotation?.canAnnotate || annotation.canAnnotate(activeImage));
+ // 画笔要等图片自然尺寸就位(坐标换算基准),否则进入标注后作画静默无效:
+ // 此前按钮置灰禁用,与撤销的禁用态同观感。宿主给出暂不可标注的原因时,按钮
+ // 同样置灰但可点,点按说明原因(否则用户不知道为什么不能画)。
+ const annotateReady = annotateVisible && !!activeNaturalSize;
+ const annotateBlockedReason = annotateReady && activeImage
+ ? annotation?.annotationBlockedReason?.(activeImage)
+ : undefined;
+ const annotateEnabled = annotateReady && !annotateBlockedReason;
const enterAnnotationMode = useCallback(() => {
- if (!annotateEnabled || submittingRef.current || sharingRef.current) return;
+ if (!annotateReady || submittingRef.current || sharingRef.current) return;
+ if (annotateBlockedReason) {
+ Alert.alert(t('message.lightbox.annotateUnavailableTitle'), annotateBlockedReason);
+ return;
+ }
setIsAnnotating(true);
- }, [annotateEnabled]);
+ }, [annotateReady, annotateBlockedReason, t]);
// 独立直发(发送到对话):不要求可标注——gif 等不可画的图同样能转发。
const directSubmitVisible = !!annotation?.allowDirectSubmit && !!activeImage && !!activeUri;
@@ -801,9 +808,12 @@ export const ImageLightbox = memo(function ImageLightbox({
<View style={styles.actionBarPill}>
{annotateVisible ? (
<Pressable
- accessibilityLabel={t('message.lightbox.annotateImage')}
- accessibilityState={{ disabled: !annotateEnabled }}
- disabled={annotationSubmitting || sharing || !annotateEnabled}
+ accessibilityHint={annotateBlockedReason}
+ accessibilityLabel={annotateBlockedReason
+ ? t('message.lightbox.annotateImageUnavailable')
+ : t('message.lightbox.annotateImage')}
+ accessibilityState={{ disabled: !annotateReady }}
+ disabled={annotationSubmitting || sharing || !annotateReady}
hitSlop={8}
onPress={enterAnnotationMode}
style={styles.actionItem}
@@ -862,9 +872,12 @@ export const ImageLightbox = memo(function ImageLightbox({
<View style={styles.actionBarPill}>
{annotateVisible ? (
<Pressable
- accessibilityLabel={t('message.lightbox.annotateImage')}
- accessibilityState={{ disabled: !annotateEnabled }}
- disabled={annotationSubmitting || sharing || !annotateEnabled}
+ accessibilityHint={annotateBlockedReason}
+ accessibilityLabel={annotateBlockedReason
+ ? t('message.lightbox.annotateImageUnavailable')
+ : t('message.lightbox.annotateImage')}
+ accessibilityState={{ disabled: !annotateReady }}
+ disabled={annotationSubmitting || sharing || !annotateReady}
hitSlop={8}
onPress={enterAnnotationMode}
style={styles.actionItem}
diff --git a/apps/mobile/src/session/annotationBurnInQueue.ts b/apps/mobile/src/session/annotationBurnInQueue.ts
index e940b7e2d1..bbbd8a02f9 100644
--- a/apps/mobile/src/session/annotationBurnInQueue.ts
+++ b/apps/mobile/src/session/annotationBurnInQueue.ts
@@ -12,8 +12,11 @@
* - 任务超时只覆盖真正注入 WebView 的队首任务(排队不计时);ready 超时只在
* 有任务等待时计时(预热期间不计)。
* - WebView 进程被系统杀掉 / 加载失败时,队首任务立即失败(不再干等 30s),
- * 剩余任务在一个新挂载的 WebView 上继续;每次崩溃至少消耗一个任务,不会
- * 无限重挂载。
+ * 剩余任务在一个新挂载的 WebView 上继续;每次崩溃至少消耗一个任务,连续
+ * 崩溃达到上限时剩余任务一并失败。崩溃 / 超时 / 起不来之后只为「等待中的
+ * 任务」重挂载:仅被预热持有时直接卸载,且预热不再触发重挂载(直到下一个
+ * 任务到来或预热全部释放),避免有缺陷的 System WebView / 内存压力下反复
+ * 崩溃重建。
* - 没有任务、也没有预热持有者时卸载 WebView(空闲零开销)。
*/
import {
@@ -46,6 +49,8 @@ export const BURN_IN_TIMEOUT_MS = 30_000;
* 时永远等不到 ready,任务级超时(注入时刻才起表)覆盖不到这段。
*/
export const WEBVIEW_READY_TIMEOUT_MS = 10_000;
+/** 连续崩溃(期间没有任何任务正常回包)的重挂载上限:超过后剩余任务全部失败。 */
+export const MAX_CONSECUTIVE_CRASH_REMOUNTS = 2;
export interface AnnotationBurnInQueueHost {
/** 以新的 sessionKey 挂载(或重挂载)WebView。 */
@@ -101,6 +106,10 @@ export function createAnnotationBurnInQueue(
let ready = false;
let readyTimer: unknown = null;
let warmCount = 0;
+ /** WebView 出过故障后预热不再挂载(下一个任务或预热全部释放后恢复)。 */
+ let warmSuspended = false;
+ /** 连续崩溃次数:任务正常回包(成功或脚本内失败)即清零。 */
+ let consecutiveCrashes = 0;
function clearReadyTimer(): void {
if (readyTimer !== null) clearTimer(readyTimer);
@@ -133,10 +142,9 @@ export function createAnnotationBurnInQueue(
readyTimer = null;
if (ready || queue.length === 0) return;
failAllQueued(new Error('annotation burn-in webview failed to initialize'));
- // 起不来的 WebView 不再复用:预热中则换一个新实例(无任务不计时,不会循环),
- // 否则卸载,下次任务重新挂载重试。
- if (warmCount > 0) mountFresh();
- else unmount();
+ // 起不来的 WebView 不再复用:卸载,下次任务重新挂载重试(预热不重挂)。
+ warmSuspended = true;
+ unmount();
}, readyTimeoutMs);
}
@@ -158,9 +166,13 @@ export function createAnnotationBurnInQueue(
if (warmCount === 0) unmount();
}
- /** WebView 不再可信(崩溃 / 超时):有后续需求则换新实例,否则卸载。 */
+ /**
+ * WebView 不再可信(崩溃 / 超时):还有等待中的任务才换新实例,否则卸载;
+ * 仅预热持有时不重挂(见文件头不变量)。
+ */
function replaceWebView(): void {
- if (queue.length > 0 || warmCount > 0) {
+ warmSuspended = true;
+ if (queue.length > 0) {
mountFresh();
armReadyTimer();
} else {
@@ -210,6 +222,11 @@ export function createAnnotationBurnInQueue(
if (head && takeHead(head)) {
head.reject(new Error(`annotation burn-in webview terminated: ${reason}`));
}
+ consecutiveCrashes += 1;
+ if (consecutiveCrashes > MAX_CONSECUTIVE_CRASH_REMOUNTS) {
+ // 反复崩溃:不再重建,剩余任务一并失败(走调用方既有失败提示),卸载。
+ failAllQueued(new Error(`annotation burn-in webview terminated: ${reason}`));
+ }
replaceWebView();
}
@@ -218,6 +235,8 @@ export function createAnnotationBurnInQueue(
return new Promise<AnnotationBurnInResult>((resolve, reject) => {
jobSeq += 1;
queue.push({ id: `burn-${jobSeq}`, input, resolve, reject, timer: null, dispatched: false });
+ // 用户真正提交了:给 WebView 一次新机会(连续崩溃仍受上限约束)。
+ warmSuspended = false;
ensureMounted();
if (ready) dispatchHead();
else armReadyTimer();
@@ -226,13 +245,16 @@ export function createAnnotationBurnInQueue(
acquireWarm() {
warmCount += 1;
- ensureMounted();
+ if (!warmSuspended) ensureMounted();
let released = false;
return () => {
if (released) return;
released = true;
warmCount = Math.max(0, warmCount - 1);
- if (warmCount === 0 && queue.length === 0) unmount();
+ if (warmCount === 0) {
+ warmSuspended = false;
+ if (queue.length === 0) unmount();
+ }
};
},
@@ -250,6 +272,7 @@ export function createAnnotationBurnInQueue(
// 过期回包(超时后到达 / 非队首)丢弃。
if (!active || !active.dispatched || message.id !== active.id) return;
takeHead(active);
+ consecutiveCrashes = 0;
if (message.ok) {
active.resolve({
base64: message.base64,
@@ -269,6 +292,8 @@ export function createAnnotationBurnInQueue(
clearReadyTimer();
failAllQueued(new Error('annotation burn-in host unmounted'));
warmCount = 0;
+ warmSuspended = false;
+ consecutiveCrashes = 0;
ready = false;
sessionKey = null;
},
diff --git a/apps/mobile/src/session/composerAttachmentInbox.ts b/apps/mobile/src/session/composerAttachmentInbox.ts
index cab9536707..03d25a6966 100644
--- a/apps/mobile/src/session/composerAttachmentInbox.ts
+++ b/apps/mobile/src/session/composerAttachmentInbox.ts
@@ -19,7 +19,7 @@ export interface ComposerAnnotationSubmission {
displayUri: string;
strokes: AnnotationStroke[];
mimeType?: string;
- /** lightbox 已解码的图片尺寸(可选):供烧录预缩 / 上传降采样决策。 */
+ /** lightbox 已解码的图片尺寸(可选):仅供带笔迹 / 需光栅化时的烧录前预缩决策。 */
naturalWidth?: number;
naturalHeight?: number;
/**
diff --git a/apps/mobile/src/session/imageAnnotationModel.ts b/apps/mobile/src/session/imageAnnotationModel.ts
index bc65d634b0..6cb623366c 100644
--- a/apps/mobile/src/session/imageAnnotationModel.ts
+++ b/apps/mobile/src/session/imageAnnotationModel.ts
@@ -433,6 +433,8 @@ const ANDROID_WEBVIEW_UNDECODABLE_MIMES = new Set([
'image/heif-sequence',
'image/avif',
]);
+/** Android 转码 HEIC / HEIF / AVIF 的 JPEG 质量(高质量,体积可控)。 */
+export const ANDROID_TRANSCODE_JPEG_QUALITY = 0.92;
/** 烧录前允许交给原生 manipulator 预缩的格式(未知 / 矢量 / 动图一律走原路径)。 */
const MANIPULATOR_PRESCALE_MIMES = new Set([
'image/jpeg',
@@ -445,7 +447,11 @@ const MANIPULATOR_PRESCALE_MIMES = new Set([
export interface AnnotationBurnSourcePlan {
/** 等比缩放目标(只给长边一维);null = 只转码不缩尺寸。 */
resize: { width: number } | { height: number } | null;
- /** 中间产物格式:JPEG 源保持 JPEG(最高质量),其余一律无损 PNG(保透明)。 */
+ /**
+ * 中间产物格式:JPEG 源保持 JPEG(最高质量);Android 转码的 HEIC / HEIF / AVIF
+ * 一律高质量 JPEG(照片格式,无损 PNG 在无尺寸提示时可达数十 MB);其余预缩
+ * 为无损 PNG(保透明,长边已钳到上限)。
+ */
format: 'jpeg' | 'png';
compress: number;
/**
@@ -459,8 +465,8 @@ export interface AnnotationBurnSourcePlan {
* 决定烧录前要不要先把源图交给原生 manipulator 处理。返回 null = 原样交给
* WebView(与既有路径完全一致)。
*
- * - Android 系统 WebView 解不了 HEIC / HEIF / AVIF:先转成 WebView 能解的格式,
- * 否则用户画完才得到解码失败。
+ * - Android 系统 WebView 解不了 HEIC / HEIF / AVIF:先转成高质量 JPEG,否则用户
+ * 画完才得到解码失败。
* - 已知尺寸长边超过上传上限(2048)的大图:先按上传同口径缩到上限,WebView
* 只需解码 / 注入 / 烧录一张小图(内存与注入体积按像素数下降)。
* 尺寸未知时不预缩(不为探测尺寸额外解码),维持原路径。
@@ -482,8 +488,8 @@ export function planAnnotationBurnSource(input: {
resize: prescale
? (width >= height ? { width: MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE } : { height: MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE })
: null,
- format: mime === 'image/jpeg' ? 'jpeg' : 'png',
- compress: 1,
+ format: mime === 'image/jpeg' || transcode ? 'jpeg' : 'png',
+ compress: transcode ? ANDROID_TRANSCODE_JPEG_QUALITY : 1,
strokeSpace: prescale ? annotationBurnCanvasSize(width, height) : null,
};
}
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 8daa46bbb9..5cc38ad57b 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -488,8 +488,9 @@ export function createMobileLocalAttachmentUploadController(
task.state = 'failed';
} else {
// uploaded 的成功路径由 onUploaded 在把预览换成持久缩略图后清理;
- // discarded 在这里回收全部自有临时文件。
- if (outcome === 'discarded') cleanupTaskLocalUris(task, false);
+ // discarded(以及退屏后才失败、不再保留失败卡的任务)在这里回收全部
+ // 自有临时文件并回调 onAbandoned。
+ if (outcome !== 'uploaded') cleanupTaskLocalUris(task, false);
tasks.delete(task.localId);
}
runningCount -= 1;
diff --git a/apps/mobile/src/session/useComposerImageAnnotations.ts b/apps/mobile/src/session/useComposerImageAnnotations.ts
index e16cbf5474..f04c5a6786 100644
--- a/apps/mobile/src/session/useComposerImageAnnotations.ts
+++ b/apps/mobile/src/session/useComposerImageAnnotations.ts
@@ -76,7 +76,7 @@ export interface UseComposerImageAnnotationsOptions {
getAttachment?: (attachmentId: string) => RemoteSerializedAttachment | undefined;
}
-/** lightbox 已解码的源图尺寸(可选提示,用于预缩 / 上传降采样决策)。 */
+/** lightbox 已解码的源图尺寸(可选提示,仅用于烧录前预缩决策)。 */
export interface AnnotationSourceSizeHint {
naturalWidth?: number;
naturalHeight?: number;
@@ -248,8 +248,9 @@ export function useComposerImageAnnotations(
/**
* 烧录源准备:Android WebView 解不了的格式先转码、已知超大图先按上传口径预缩
- * (见 planAnnotationBurnSource)。manipulator 失败或产物与提示尺寸对不上时
- * 回退原图(即既有路径)。tempUri = 仅供本次烧录的中间产物,烧完即删。
+ * (见 planAnnotationBurnSource)。manipulator 失败、产物与提示尺寸对不上或
+ * 体积超过源图上限(烧录要全量 base64 进 JS 内存)时回退原图(即既有路径)。
+ * tempUri = 仅供本次烧录的中间产物,烧完即删。
*/
const prepareBurnSource = useCallback(async (
source: { fileUri: string; mimeType: string },
@@ -274,7 +275,15 @@ export function useComposerImageAnnotations(
if (!plan) return original;
try {
const result = await runAnnotationBurnSourcePlan(source.fileUri, plan);
- if (!isAnnotationBurnSourceResultUsable(plan, result, hint)) {
+ const info = await FileSystem.getInfoAsync(result.uri).catch(() => null);
+ const resultSize = info?.exists && typeof info.size === 'number' && Number.isFinite(info.size)
+ ? info.size
+ : 0;
+ if (
+ !isAnnotationBurnSourceResultUsable(plan, result, hint)
+ || !(resultSize > 0)
+ || resultSize > MOBILE_MAX_ATTACHMENT_BYTES
+ ) {
void FileSystem.deleteAsync(result.uri, { idempotent: true }).catch(() => undefined);
return original;
}
@@ -402,8 +411,6 @@ export function useComposerImageAnnotations(
replacedMeta?.sourceMimeType ?? mimeTypeHint,
);
if (source.fileUri !== sourceInputUri) createdFiles.push(source.fileUri);
- const hintWidth = positiveHintDimension(sizeHint?.naturalWidth);
- const hintHeight = positiveHintDimension(sizeHint?.naturalHeight);
const annotation = strokes.length > 0 || baseIsAnnotatedBurn
? {
strokes: strokes.map((s) => ({ points: [...s.points] })),
@@ -464,10 +471,9 @@ export function useComposerImageAnnotations(
kind: 'image',
uri: source.fileUri,
name: `image-${nextFileTag()}.${ext}`,
- // 直传源至少带上真实字节数让 preprocess 的重编码判断生效;lightbox 已解码
- // 的尺寸一并带上,超大图与相册选图一样按长边上限降采样。
+ // 直传源无解码尺寸,至少带上真实字节数让 preprocess 的重编码判断生效。
+ // (lightbox 尺寸提示只用于烧录预缩,不改变直传转发的分辨率。)
size: source.size,
- ...(hintWidth && hintHeight ? { width: hintWidth, height: hintHeight } : {}),
mimeType: source.mimeType,
...(annotation ? { annotation } : {}),
};
@@ -562,8 +568,11 @@ export function useComposerImageAnnotations(
const trayAnnotation = useMemo<ImageLightboxAnnotationConfig>(() => ({
submitLabel: t('composer.attachments.save'),
initialStrokesFor: (image) => metaRef.current.get(image.key)?.strokes,
- // 替换上传未落定(上传中 / 失败待重试)的附件不可再编辑,防双重替换。
- canAnnotate: (image) => !hasPendingReplacement(image.key),
+ // 替换上传未落定(上传中 / 失败待重试)的附件不可再编辑,防双重替换;
+ // 画笔置灰,点按说明原因。
+ annotationBlockedReason: (image) => (
+ hasPendingReplacement(image.key) ? t('composer.attachments.replacementPending') : undefined
+ ),
prewarm: acquireWarm,
onSubmit: (image, displayUri, strokes, context) =>
submitAnnotation(displayUri, strokes, context.mimeType, image.key, context),