Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 隔离留图账号并拒绝已取消上传的迟到缓存
Dash99f8cc1b9e78
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.tsindex ce227c3241..0d7d4715ca 100644--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts@@ -1,4 +1,5 @@-import { beforeAll, describe, expect, it, vi } from 'vitest';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { apiFetchRaw } from '@/api/client';import { installPeerUpload } from '@/device-link/peerFileRegistry';import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';@@ -22,8 +23,28 @@ beforeAll(async () => {const readFileChunk = vi.fn(async (_uri: string, _position: number, length: number) =>Buffer.alloc(length, 0x78).toString('base64'),);+beforeEach(() => setMobileAuthOwner('alice'));describe('mobileAttachmentUpload', () => {+ // Unit: late peer completion must not retain removed uploads or an invalidated owner's pixels.+ it.each(['cancelled', 'outbox-removed', 'account-switched'] as const)('does not retain a late upload after %s', async (reason) => {+ const abort = new AbortController();+ let active = true;+ const retainImage = vi.fn();+ const off = installPeerUpload(async (_device, _uri, metadata) => {+ if (reason === 'cancelled') abort.abort();+ if (reason === 'outbox-removed') active = false;+ if (reason === 'account-switched') { setMobileAuthOwner('bob'); setMobileAuthOwner('alice'); }+ return buildPeerAttachmentRef({ ...metadata, ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' });+ });+ try {+ await uploadMobileAttachmentFromFile({ name: 'photo.png', size: 4, mimeType: 'image/png' }, 'file:///source', {+ token: 'token', deviceId: 'computer', signal: abort.signal, isActive: () => active,+ deps: { readFileChunk, retainImage },+ });+ expect(retainImage).not.toHaveBeenCalled();+ } finally { off(); }+ });// Unit regression: background outbox calls this entry without the composer's onUploaded.// The immutable snapshot must be retained before it is removed on either transport.it.each(['oss', 'peer'] as const)('retains the sent %s image snapshot before cleanup', async (transport) => {diff --git a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.tsindex af812ea751..15b2938bd7 100644--- a/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts+++ b/apps/mobile/src/__tests__/sentAttachmentThumbStore.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest';import { vi } from 'vitest';import { buildAttachmentOssRef, buildPeerAttachmentRef } from '@cindy/device-link';import { resolveMobileRemoteMedia } from '@/session/remoteMedia';+import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';const storage = vi.hoisted(() => new Map<string, string>());vi.mock('expo-file-system/legacy', () => ({@@ -68,9 +69,55 @@ beforeEach(async () => {await __testing.flushPersist();__testing.reset();storage.clear();+ setMobileAuthOwner('alice');});describe('sentAttachmentThumbStore', () => {+ // Unit: cache ownership must survive restart without exposing another account's pixels.+ // Previously the global exact-ref and content-hash indices both ignored the owner.+ it('isolates exact and content-address reads by account, realm and logout', async () => {+ const finalRef = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ const ref = buildAttachmentOssRef({ ossKey: 'uploads/alice', sha256: 'a'.repeat(64), size: 1000, mimeType: 'image/png' });+ const { deps } = makeFsDeps();+ await registerSentAttachmentThumb(ref, 'file:///alice.png', deps);+ await __testing.flushPersist();+ __testing.reset();+ for (const [id, realm] of [['bob', 'global'], ['alice', 'cn'], ['', 'global']] as const) {+ setMobileAuthOwner(id, realm);+ expect(await resolveSentAttachmentThumb(ref, deps)).toBeNull();+ expect(getSentAttachmentThumbUri(ref)).toBeNull();+ expect(await resolveSentAttachmentThumb(finalRef, deps)).toBeNull();+ }+ setMobileAuthOwner('alice');+ expect(await resolveSentAttachmentThumb(ref, deps)).not.toBeNull();+ expect(await resolveSentAttachmentThumb(finalRef, deps)).not.toBeNull();+ expect(await resolveSentAttachmentThumb(finalRef, { ...deps, statSize: async () => {+ setMobileAuthOwner('bob');+ return 1000;+ } })).toBeNull();+ });++ it.each(['owner', 'cancelled'] as const)('removes a copy invalidated during file IO (%s)', async (reason) => {+ let active = true;+ const { deps, removed, copies } = makeFsDeps();+ const copy = deps.copy;+ deps.copy = async (from, to) => {+ await copy(from, to);+ if (reason === 'owner') { setMobileAuthOwner('bob'); setMobileAuthOwner('alice'); }+ else active = false;+ };+ await registerSentAttachmentThumb(OSS_REF, 'file:///alice.png', deps, () => active);+ await __testing.flushPersist();+ expect(getSentAttachmentThumbUri(OSS_REF)).toBeNull();+ expect(removed).toContain(copies[0].to);+ expect(storage.has(__testing.storageKey)).toBe(false);+ });++ it('does not assign unowned legacy records to the next logged-in account', async () => {+ storage.set(__testing.storageKey, JSON.stringify([{ ossRef: OSS_REF, file: 'old.png', at: 1 }]));+ await ensureSentAttachmentThumbsHydrated(makeFsDeps().deps);+ expect(getSentAttachmentThumbUri(OSS_REF)).toBeNull();+ });// Regression: sent photos became unavailable offline after history replaced the upload URL.// Existing tests only queried the original ref. Unit tier exercises persistence + real lookup.it.each(['oss', 'peer'] as const)('keeps a %s upload readable by its final content address after restart', async (transport) => {@@ -188,8 +235,8 @@ describe('sentAttachmentThumbStore', () => {it('hydrate 保留旧映射,只清目录孤儿文件', async () => {const now = Date.now();storage.set(__testing.storageKey, JSON.stringify([- { ossRef: OSS_REF, file: 'thumb-fresh.jpg', at: now - 1000 },- { ossRef: OSS_REF_2, file: 'thumb-stale.jpg', at: now - 30 * 24 * 60 * 60 * 1000 },+ { ossRef: OSS_REF, file: 'thumb-fresh.jpg', at: now - 1000, accountKey: getMobileAuthOwner().accountKey },+ { ossRef: OSS_REF_2, file: 'thumb-stale.jpg', at: now - 30 * 24 * 60 * 60 * 1000, accountKey: getMobileAuthOwner().accountKey },]));const { deps, removed, setDirFiles } = makeFsDeps();setDirFiles(['thumb-fresh.jpg', 'thumb-stale.jpg', 'thumb-orphan.jpg']);diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsxindex f339f7d558..74431331cf 100644--- a/apps/mobile/src/session/MobileOutboxBridge.tsx+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx@@ -286,6 +286,7 @@ export function MobileOutboxBridge() {token,deviceId: r.deviceId,sharedTaskId: parseSharedTaskPeer(r.deviceId)?.sharedTaskId,+ isActive: () => isCurrent() && mobileDurableOutbox.getSnapshot().includes(r),},);if (!isCurrent() || !mobileDurableOutbox.getSnapshot().includes(r)) {diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.tsindex 85e58d2a4a..6e4eaabc16 100644--- a/apps/mobile/src/session/mobileAttachmentUpload.ts+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts@@ -1,4 +1,5 @@import { apiFetchRaw } from '@/api/client';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';import { canMobilePeerUpload, tryMobilePeerUpload } from '@/device-link/peerFileRegistry';import { DEVICE_LINK_API_BASE_URL } from '@/config/env';import { i18n } from '@/i18n';@@ -333,8 +334,13 @@ export async function uploadMobileAttachmentFromFile(id?: string;deps?: UploadDeps;signal?: AbortSignal;+ /** The outbox can remove a record without aborting its already-running upload. */+ isActive?: () => boolean;},): Promise<RemoteSerializedAttachment> {+ const owner = getMobileAuthOwner();+ const isActive = () => !!owner.accountKey && isMobileAuthOwnerCurrent(owner)+ && !options.signal?.aborted && (options.isActive?.() ?? true);assertMobileDocumentSize(candidate.size);// 直连不设体积上限;超过 OSS 上限的附件只能直连——先确认直连可用(只查对端能力),// 不可用就在快照和摘要之前失败,不白复制、白读一遍数 GB 的文件。@@ -353,11 +359,14 @@ export async function uploadMobileAttachmentFromFile(// Both the composer and the background outbox upload here. Keep the exact hashed// snapshot before cleanup; retaining only in the composer loses background sends.const retain = async (attachment: RemoteSerializedAttachment) => {- if (attachment.category === 'image') {+ if (attachment.category === 'image' && isActive()) {try {- const save = options.deps?.retainImage- ?? (await import('@/session/sentAttachmentThumbStore')).registerSentAttachmentThumb;- await save(attachment.url ?? attachment.path, snapshot.uri);+ if (options.deps?.retainImage) {+ await options.deps.retainImage(attachment.url ?? attachment.path, snapshot.uri);+ } else {+ const { registerSentAttachmentThumb } = await import('@/session/sentAttachmentThumbStore');+ await registerSentAttachmentThumb(attachment.url ?? attachment.path, snapshot.uri, undefined, isActive);+ }} catch { /* Optional local copy must not turn a completed upload into a failed send. */ }}return attachment;diff --git a/apps/mobile/src/session/sentAttachmentThumbStore.ts b/apps/mobile/src/session/sentAttachmentThumbStore.tsindex d649e8c529..18874b8180 100644--- a/apps/mobile/src/session/sentAttachmentThumbStore.ts+++ b/apps/mobile/src/session/sentAttachmentThumbStore.ts@@ -15,6 +15,7 @@*/import AsyncStorage from '@react-native-async-storage/async-storage';import { useSyncExternalStore } from 'react';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';import { isAttachmentOssRef, parseAttachmentOssRef, isPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';import { isPayloadDesktopLocalMediaUrl } from '@cindy/maker-shared/payload-summary';import { extOfMime, imageMimeFromUrl, type RemoteMediaDiskCacheHit } from '@/session/remoteMediaDiskCache';@@ -26,6 +27,7 @@ const THUMB_DIR_NAME = 'sent-attachment-thumbs';const KNOWN_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp']);interface ThumbEntry {+ accountKey: string;/** THUMB_DIR_NAME 下的相对文件名。 */file: string;/** 注册时间戳。 */@@ -85,6 +87,11 @@ function bump(): void {version += 1;for (const listener of [...listeners]) listener();}+subscribeMobileAuthOwner(bump);++function scopedKey(accountKey: string, ref: string): string {+ return JSON.stringify([accountKey, ref]);+}function thumbDir(): string | null {return cachedDocDir ? `${cachedDocDir}${THUMB_DIR_NAME}` : null;@@ -101,9 +108,9 @@ function imageMimeForRef(ref: string): string | undefined {}function rememberEntry(ref: string, entry: ThumbEntry): void {- entries.set(ref, entry);+ entries.set(scopedKey(entry.accountKey, ref), entry);const hash = contentHash(ref);- if (hash) entriesByHash.set(hash, entry);+ if (hash) entriesByHash.set(scopedKey(entry.accountKey, hash), entry);}/**@@ -126,7 +133,7 @@ async function hydrateInternal(deps: SentAttachmentThumbFsDeps): Promise<void> {// 内存以磁盘为底、保留 hydrate 期间已注册的新条目(register 先 await hydrate,// 实际不会先写;防御性合并保证后写胜)。for (const [ossRef, entry] of keep) {- if (!entries.has(ossRef)) rememberEntry(ossRef, entry);+ if (!entries.has(scopedKey(entry.accountKey, ossRef))) rememberEntry(ossRef, entry);}// 目录孤儿清理:磁盘上存在但映射不再引用的文件。const dir = thumbDir();@@ -161,11 +168,15 @@ export async function registerSentAttachmentThumb(ossRef: string | undefined,sourceUri: string,deps: SentAttachmentThumbFsDeps = defaultFsDeps,+ isActive: () => boolean = () => true,): Promise<void> {if (!isThumbBackedRef(ossRef) || !sourceUri) return;+ const owner = getMobileAuthOwner();+ const current = () => !!owner.accountKey && isMobileAuthOwnerCurrent(owner) && isActive();+ if (!current()) return;try {await ensureSentAttachmentThumbsHydrated(deps);- if (entries.has(ossRef)) return;+ if (!current() || entries.has(scopedKey(owner.accountKey, ossRef))) return;const dir = thumbDir();if (!dir) return;const at = Date.now();@@ -175,8 +186,13 @@ export async function registerSentAttachmentThumb(const mime = imageMimeForRef(ossRef);const file = `thumb-${at}-${fileSeq}.${mime?.startsWith('image/') ? extOfMime(mime) : extForUri(sourceUri)}`;await deps.makeDirectory(dir);+ if (!current()) return;await deps.copy(sourceUri, `${dir}/${file}`);- rememberEntry(ossRef, { file, at });+ if (!current()) {+ await deps.remove(`${dir}/${file}`);+ return;+ }+ rememberEntry(ossRef, { file, at, accountKey: owner.accountKey });schedulePersist();bump();} catch {@@ -189,11 +205,14 @@ export async function registerSentAttachmentThumb(* 未 hydrate 时顺带惰性触发,完成后经版本订阅驱动重渲染。*/export function getSentAttachmentThumbUri(ossRef: string): string | null {+ const { accountKey } = getMobileAuthOwner();+ if (!accountKey) return null;if (!hydratePromise) void ensureSentAttachmentThumbsHydrated();const dir = thumbDir();if (!dir) return null;const hash = contentHash(ossRef);- const entry = entries.get(ossRef) ?? (hash ? entriesByHash.get(hash) : undefined);+ const entry = entries.get(scopedKey(accountKey, ossRef))+ ?? (hash ? entriesByHash.get(scopedKey(accountKey, hash)) : undefined);return entry ? `${dir}/${entry.file}` : null;}@@ -202,11 +221,14 @@ export async function resolveSentAttachmentThumb(ref: string,deps: SentAttachmentThumbFsDeps = defaultFsDeps,): Promise<RemoteMediaDiskCacheHit | null> {+ const owner = getMobileAuthOwner();+ if (!owner.accountKey) return null;await ensureSentAttachmentThumbsHydrated(deps);+ if (!isMobileAuthOwnerCurrent(owner)) return null;const uri = getSentAttachmentThumbUri(ref);if (!uri) return null;const size = await deps.statSize(uri).catch(() => 0);- if (size <= 0) return null;+ if (size <= 0 || !isMobileAuthOwnerCurrent(owner)) return null;const mimeType = imageMimeForRef(ref) ?? imageMimeFromUrl(uri);return mimeType?.startsWith('image/') ? { uri, size, mimeType } : null;}@@ -273,8 +295,10 @@ function parseStoredEntries(raw: string | null): Array<[string, ThumbEntry]> {&& record.file.length > 0&& typeof record.at === 'number'&& Number.isFinite(record.at)+ && typeof record.accountKey === 'string'+ && record.accountKey.length > 0) {- out.push([record.ossRef, { file: record.file, at: record.at }]);+ out.push([record.ossRef, { file: record.file, at: record.at, accountKey: record.accountKey }]);}}return out;@@ -284,8 +308,9 @@ function parseStoredEntries(raw: string | null): Array<[string, ThumbEntry]> {}function schedulePersist(): void {- const snapshot = [...entries.entries()].map(([ossRef, entry]) => ({- ossRef,+ const snapshot = [...entries.entries()].map(([key, entry]) => ({+ ossRef: (JSON.parse(key) as [string, string])[1],+ accountKey: entry.accountKey,file: entry.file,at: entry.at,}));diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.tsindex 5b241e794f..a53800f0db 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -51,7 +51,6 @@ import {} from '@/session/pastedImageAttachment';import {getSentAttachmentThumbUri,- registerSentAttachmentThumb,} from '@/session/sentAttachmentThumbStore';import type { RemoteSerializedAttachment } from '@/session/types';@@ -305,21 +304,13 @@ export function useMobileLocalAttachments(try { candidate.onAbandoned?.(); } catch { /* 回收失败不影响管线 */ }return;}- // 发送后气泡的本地缩略图兜底:消息里持久化的是 cindy-oss-attach:// 中转引用,- // 被控端物化改写前(乐观渲染 / 电脑离线窗口)渲染端没有任何预览路径——把- // 实际上传的文件拷进自有目录记映射,气泡用本地图顶上。+ // The upload entry already retained the exact snapshot with its owner/cancellation+ // fence. Do not register again here under a potentially newer account.let deliveredCandidate = candidate;- if (candidate.kind === 'image') {+ if (candidate.kind === 'image' && candidate.cleanupLocalUris) {const ossRef = attachment.url ?? attachment.path;- if (candidate.cleanupLocalUris) {- // 粘贴源文件需要回收:先等持久缩略图完成接管,才能安全删源文件。- await registerSentAttachmentThumb(ossRef, uploadedUri || candidate.uri);- const durablePreviewUri = ossRef ? getSentAttachmentThumbUri(ossRef) : null;- if (durablePreviewUri) deliveredCandidate = { ...candidate, uri: durablePreviewUri };- } else {- // 相册 / 相机原有路径不拥有源文件,保持 fire-and-forget,不拉长上传落定时间。- void registerSentAttachmentThumb(ossRef, uploadedUri || candidate.uri);- }+ const durablePreviewUri = ossRef ? getSentAttachmentThumbUri(ossRef) : null;+ if (durablePreviewUri) deliveredCandidate = { ...candidate, uri: durablePreviewUri };}if (candidate.cleanupLocalUris) {for (const uri of localUris) {diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex af1672e06b..7b909ad5aa 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -101,7 +101,10 @@ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。相册、粘贴及后台发件箱共用 `uploadMobileAttachmentFromFile`:上传成功后、删除上传快照前,把实际发送的图片保留到已有 `sentAttachmentThumbStore`。OSS 与直传引用都留底;从既有引用的完整性指纹重建查询索引,正式消息换成 `cindy-media://blobs/…` 后仍使用同一副本。-重启恢复无需重新下载,旧版已保存且带指纹的 OSS 记录也能直接关联。没有指纹的旧引用仅按原地址匹配。+留存记录、原地址和指纹查询均带账号及区域归属;同账号重启恢复无需重新下载。+旧版无账号归属的记录不能猜测分配给当前登录者,需联网重新读取。没有指纹的有归属引用仅按原地址匹配。+上传开始时捕获现有账号代次,留存前后复核账号、取消信号及发件箱记录有效性;失效副本立即回收,+不得在编辑器完成回调里以新账号重新登记。登出期间不提供缓存读取或写入。缓存文件扩展名按图片格式保存,不能因上传快照没有后缀而把 PNG/GIF 当成 JPEG 分享。缩略图、原图查看和分享均先读取本地副本;原图读取须等索引恢复并检查文件存在,副本缺失或强制修复时沿用远端取件。缓存失败不阻断已经成功的上传。