Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote): 编辑排队消息后保留仍在使用的图片附件 (#5862)
Dash232169b778eb
diff --git a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.tsindex 566e179ba4..68235d8290 100644--- a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts+++ b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts@@ -81,7 +81,9 @@ import {materializeDirectSendOssAttachments,normalizeUserMessage,materializeQueuedOssAttachmentsDeferred,+ collectQueuedAttachmentRefs,} from '../maker-ipc/normalizeAttachments';+import { QueuedAttachmentOwnershipRegistry } from '../maker-ipc/queuedAttachmentOwnership';import { buildAttachmentOssRef } from '../../shared/attachmentOssRef';import { buildPeerAttachmentRef } from '@cindy/device-link';@@ -104,6 +106,79 @@ describe('peer attachment materialization', () => {expect(downloadToFile).not.toHaveBeenCalled();expect(removeRemote).not.toHaveBeenCalled();});++ it('keeps the local copy when a queue edit saves the same attachment again', async () => {+ const metadata = { ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', size: 11, sha256: ATTACHMENT_SHA256, mimeType: 'image/png' };+ const ref = buildPeerAttachmentRef(metadata);+ const enqueued = await materializeQueuedOssAttachmentsDeferred('sess-1', {+ files: [{ path: ref, url: ref, mimeType: 'image/png', category: 'image', ext: '.png' }],+ persistedContent: JSON.stringify({ text: 'before', images: [{ url: ref }] }),+ });+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('sess-1', 'client-1', enqueued.cleanupLocalMaterialization, {+ parts: enqueued.materializedParts,+ });+ registry.activateCurrentOwner('sess-1', 'client-1', ownerId!);++ // The edit only changes text; the attachment is already host-managed, so no new copy exists.+ const queued = enqueued.item as { files: unknown[]; persistedContent: string };+ const edited = await materializeQueuedOssAttachmentsDeferred('sess-1', {+ files: queued.files,+ persistedContent: JSON.stringify({ ...JSON.parse(queued.persistedContent), text: 'after' }),+ });+ expect(edited.cleanupLocalMaterialization).toBeUndefined();+ const replacementRefs = collectQueuedAttachmentRefs(edited.item);+ const survivor = registry.retainReferencedOwners('sess-1', 'client-1', null, (value) =>+ replacementRefs.has(value),+ );+ await registry.discardClient('sess-1', 'client-1', survivor ?? undefined);++ expect(survivor).toBe(ownerId);+ expect(removeRefById).not.toHaveBeenCalled();+ });++ it('releases only the attachment a queue edit removed from one enqueue', async () => {+ const hashA = 'b'.repeat(64);+ const hashB = 'c'.repeat(64);+ ingestMedia+ .mockResolvedValueOnce({ hash: hashA, ext: '.png', mimeType: 'image/png', bytes: 11, url: `cindy-media://blobs/${hashA}.png`, deduplicated: false, refIds: ['ref-a'] })+ .mockResolvedValueOnce({ hash: hashB, ext: '.png', mimeType: 'image/png', bytes: 11, url: `cindy-media://blobs/${hashB}.png`, deduplicated: false, refIds: ['ref-b'] });+ deleteZeroRefBlobRecord.mockResolvedValue(true);+ const refA = buildPeerAttachmentRef({ ticket: 'aaaaaaaa-0000-0000-0000-00000000000a', size: 11, sha256: hashA, mimeType: 'image/png' });+ const refB = buildPeerAttachmentRef({ ticket: 'aaaaaaaa-0000-0000-0000-00000000000b', size: 11, sha256: hashB, mimeType: 'image/png' });+ const enqueued = await materializeQueuedOssAttachmentsDeferred('sess-1', {+ files: [refA, refB].map((ref) => ({ path: ref, url: ref, mimeType: 'image/png', category: 'image', ext: '.png' })),+ persistedContent: JSON.stringify({ text: 'two', images: [{ url: refA }, { url: refB }] }),+ });+ expect(enqueued.materializedParts).toHaveLength(2);+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('sess-1', 'client-1', enqueued.cleanupLocalMaterialization, {+ parts: enqueued.materializedParts,+ });+ registry.activateCurrentOwner('sess-1', 'client-1', ownerId!);++ // Edit keeps the first image and removes the second.+ const queued = enqueued.item as { files: unknown[]; persistedContent: string };+ const persisted = JSON.parse(queued.persistedContent) as { images: unknown[] };+ const edited = await materializeQueuedOssAttachmentsDeferred('sess-1', {+ files: queued.files.slice(0, 1),+ persistedContent: JSON.stringify({ text: 'one', images: persisted.images.slice(0, 1) }),+ });+ const replacementRefs = collectQueuedAttachmentRefs(edited.item);+ const survivor = registry.retainReferencedOwners('sess-1', 'client-1', null, (value) =>+ replacementRefs.has(value),+ );+ await registry.discardClient('sess-1', 'client-1', survivor ?? undefined);++ expect(survivor).toBe(ownerId);+ expect(removeRefById.mock.calls).toEqual([['ref-b']]);+ expect(deleteBlobFile).toHaveBeenCalledWith(hashB, '.png');+ expect(deleteBlobFile).not.toHaveBeenCalledWith(hashA, '.png');++ // Discarding the item later releases the kept attachment exactly once.+ await registry.discardClient('sess-1', 'client-1');+ expect(removeRefById.mock.calls).toEqual([['ref-b'], ['ref-a']]);+ });});describe('queued attachment cleanup regression', () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.tsindex 97faa99db5..473e0a6f4c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.ts@@ -171,6 +171,134 @@ describe('QueuedAttachmentOwnershipRegistry', () => {expect(registry.getCurrentOwnerId('session-1', 'client-1')).toBeNull();});+ it('keeps the current owner when a queue edit still references its media without a new copy', async () => {+ const cleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/a.png', '/blobs/a.png'], cleanup }],+ });+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ const survivor = registry.retainReferencedOwners(+ 'session-1',+ 'client-1',+ null,+ (ref) => ref === 'cindy-media://blobs/a.png',+ );+ await registry.discardClient('session-1', 'client-1', survivor ?? undefined);++ expect(survivor).toBe(ownerId);+ expect(cleanup).not.toHaveBeenCalled();+ await registry.discardClient('session-1', 'client-1');+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it('splits one materialisation so an edit releases only its dropped attachments', async () => {+ const keptLocal = vi.fn(async () => {});+ const droppedLocal = vi.fn(async () => {});+ const remote = vi.fn(async () => {});+ const otherLocal = vi.fn(async () => {});+ const newLocal = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ // One enqueue materialised two attachments; the edit keeps one of them.+ const enqueuedOwnerId = registry.register('session-1', 'client-1', undefined, {+ cleanupAfterDurable: remote,+ parts: [+ { refs: ['cindy-media://blobs/kept.png'], cleanup: keptLocal },+ { refs: ['cindy-media://blobs/dropped.png'], cleanup: droppedLocal },+ ],+ });+ registry.activateCurrentOwner('session-1', 'client-1', enqueuedOwnerId!);+ registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/other.png'], cleanup: otherLocal }],+ });+ const newOwnerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/new.png'], cleanup: newLocal }],+ });++ const replacement = new Set(['cindy-media://blobs/kept.png', 'cindy-media://blobs/new.png']);+ const survivor = registry.retainReferencedOwners('session-1', 'client-1', newOwnerId, (ref) =>+ replacement.has(ref),+ );+ registry.activateCurrentOwner('session-1', 'client-1', survivor!);+ await registry.discardClient('session-1', 'client-1', survivor!);++ expect(survivor).toBe(newOwnerId);+ expect(droppedLocal).toHaveBeenCalledTimes(1);+ expect(otherLocal).toHaveBeenCalledTimes(1);+ expect(keptLocal).not.toHaveBeenCalled();+ expect(newLocal).not.toHaveBeenCalled();+ // The remote source moved with the kept attachment and waits for the durable boundary.+ expect(remote).not.toHaveBeenCalled();++ await registry.markDurable('session-1', 'client-1', survivor!);+ expect(remote).toHaveBeenCalledTimes(1);+ await registry.settleDurable('session-1', 'client-1');+ expect(keptLocal).not.toHaveBeenCalled();+ expect(newLocal).not.toHaveBeenCalled();+ expect(remote).toHaveBeenCalledTimes(1);+ });++ it('resolves a deferred superseded discard against the owner current when it runs', async () => {+ const firstLocal = vi.fn(async () => {});+ const secondLocal = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const firstOwnerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/first.png'], cleanup: firstLocal }],+ });+ registry.activateCurrentOwner('session-1', 'client-1', firstOwnerId!);++ // Edit 1 keeps the first image; its discard waits for the queue snapshot.+ registry.retainReferencedOwners('session-1', 'client-1', null, (ref) =>+ ref === 'cindy-media://blobs/first.png',+ );+ // Edit 2 is accepted meanwhile: it keeps the first image and adds a new one.+ const secondOwnerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/second.png'], cleanup: secondLocal }],+ });+ const edit2Refs = new Set(['cindy-media://blobs/first.png', 'cindy-media://blobs/second.png']);+ const survivor = registry.retainReferencedOwners('session-1', 'client-1', secondOwnerId, (ref) =>+ edit2Refs.has(ref),+ );+ registry.activateCurrentOwner('session-1', 'client-1', survivor!);++ // Both deferred discards now run; neither may release media edit 2 still uses.+ await registry.discardSuperseded('session-1', 'client-1');+ await registry.discardSuperseded('session-1', 'client-1');++ expect(survivor).toBe(secondOwnerId);+ expect(firstLocal).not.toHaveBeenCalled();+ expect(secondLocal).not.toHaveBeenCalled();+ await registry.discardClient('session-1', 'client-1');+ expect(firstLocal).toHaveBeenCalledTimes(1);+ expect(secondLocal).toHaveBeenCalledTimes(1);+ });++ it('leaves a later edit preparation that is not accepted yet to its own handler', async () => {+ const acceptedLocal = vi.fn(async () => {});+ const pendingLocal = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const acceptedOwnerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/old.png'], cleanup: acceptedLocal }],+ });+ registry.activateCurrentOwner('session-1', 'client-1', acceptedOwnerId!);+ // Edit 1 drops the old image and is accepted without a copy of its own.+ expect(registry.retainReferencedOwners('session-1', 'client-1', null, () => false)).toBeNull();+ registry.restoreCurrentOwner('session-1', 'client-1', null);+ // Edit 2 has materialised a new image but is still preparing when edit 1's discard runs.+ const pendingOwnerId = registry.register('session-1', 'client-1', undefined, {+ parts: [{ refs: ['cindy-media://blobs/new.png'], cleanup: pendingLocal }],+ });++ await registry.discardSuperseded('session-1', 'client-1');++ expect(acceptedLocal).toHaveBeenCalledTimes(1);+ expect(pendingLocal).not.toHaveBeenCalled();+ registry.activateCurrentOwner('session-1', 'client-1', pendingOwnerId!);+ await registry.discardSuperseded('session-1', 'client-1');+ expect(pendingLocal).not.toHaveBeenCalled();+ });+it('does not clean a duplicate materialisation that was never accepted', async () => {const acceptedCleanup = vi.fn(async () => {});const duplicateCleanup = vi.fn(async () => {});diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.tsindex bc23200ab1..49ab85301a 100644--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts@@ -524,6 +524,8 @@ function persistedContentNeedsMaterialize(json: string): boolean {/** 物化结果:被控端 image cache 里的 `xdt-image://` url(渲染用)+ 其绝对路径(file chip / agent 用)。 */type MaterializedRef = { url: string; absPath: string };type MaterializedCleanup = () => void | Promise<void>;+/** One materialised attachment: its host-managed URL/path and the cleanup that releases only it. */+export type MaterializedAttachmentPart = { refs: string[]; cleanup: MaterializedCleanup };/*** 用 materialize(OSS 引用串 → image cache 物化结果)改写 persistedContent JSON 串。@@ -595,6 +597,8 @@ async function materializeQueuedOssAttachmentsInternal(cleanupAfterAcceptance?: () => void;cleanupBeforeAcceptance?: () => Promise<void>;cleanupLocalMaterialization?: () => Promise<void>;+ /** Per-attachment local copies, so a queue edit can release only the attachments it dropped. */+ materializedParts?: MaterializedAttachmentPart[];}> {if (!item || typeof item !== 'object') return { item };const it = item as { files?: unknown; persistedContent?: unknown };@@ -618,12 +622,20 @@ async function materializeQueuedOssAttachmentsInternal(cleanedUp = true;for (const key of ossKeys) void removeRemote(key);};- const localCleanupCallbacks: MaterializedCleanup[] = [];+ const localParts: MaterializedAttachmentPart[] = [];+ const addLocalPart = (entry: MaterializedRef, cleanup: MaterializedCleanup): void => {+ // Each part runs at most once whether released alone (queue edit) or with the whole item.+ let run: Promise<void> | null = null;+ localParts.push({+ refs: [entry.url, entry.absPath],+ cleanup: () => (run ??= Promise.resolve().then(cleanup)),+ });+ };let localCleanedUp = false;const cleanupLocalMaterializations = async (): Promise<void> => {if (localCleanedUp) return;localCleanedUp = true;- for (const cleanup of localCleanupCallbacks) {+ for (const { cleanup } of localParts) {try {await cleanup();} catch (e) {@@ -657,9 +669,10 @@ async function materializeQueuedOssAttachmentsInternal(},],});+ const entry = { url: written.url, absPath: cindyMediaBlobStore.resolveSafe(written.url).absPath };const refId = written.refIds[0];if (refId) {- localCleanupCallbacks.push(async () => {+ addLocalPart(entry, async () => {await cindyMediaLedger.removeRefById(refId);const removed = await cindyMediaLedger.deleteZeroRefBlobRecord(written.hash,@@ -668,7 +681,7 @@ async function materializeQueuedOssAttachmentsInternal(if (removed) await cindyMediaBlobStore.deleteBlobFile(written.hash, written.ext);});}- return { url: written.url, absPath: cindyMediaBlobStore.resolveSafe(written.url).absPath };+ return entry;};// 物化:被控端本机绝对路径图片(手机文件浏览器发送)读字节入总仓;OSS 引用走// 流式下载 → 临时文件 → 媒体 mime 入总仓 / 非媒体(pdf/doc/.bin 等)拷进老@@ -722,8 +735,8 @@ async function materializeQueuedOssAttachmentsInternal(originalName,lifecycle: 'committed',});- localCleanupCallbacks.push(() => imageCacheStore.removeFile(url));entry = { url, absPath: imageCacheStore.resolveSafe(url).absPath };+ addLocalPart(entry, () => imageCacheStore.removeFile(url));}byRef.set(refStr, entry);if (ref.ossKey) ossKeys.add(ref.ossKey);@@ -788,12 +801,15 @@ async function materializeQueuedOssAttachmentsInternal(};return {item: materializedItem,- ...(ossKeys.size > 0 || localCleanupCallbacks.length > 0+ ...(ossKeys.size > 0 || localParts.length > 0? {cleanupAfterAcceptance: cleanupOss,cleanupBeforeAcceptance,- ...(localCleanupCallbacks.length > 0- ? { cleanupLocalMaterialization: cleanupLocalMaterializations }+ ...(localParts.length > 0+ ? {+ cleanupLocalMaterialization: cleanupLocalMaterializations,+ materializedParts: localParts,+ }: {}),}: {}),@@ -821,10 +837,47 @@ export async function materializeQueuedOssAttachmentsDeferred(cleanupAfterAcceptance?: () => void;cleanupBeforeAcceptance?: () => Promise<void>;cleanupLocalMaterialization?: () => Promise<void>;+ materializedParts?: MaterializedAttachmentPart[];}> {return materializeQueuedOssAttachmentsInternal(sessionId, item);}+/**+ * Every attachment reference a queued item still carries: `files[]` url/path+ * plus the persisted envelope's images[].url / files[].path. A queue edit+ * compares these with each owned attachment's refs so unchanged attachments+ * keep their local copy.+ */+export function collectQueuedAttachmentRefs(item: unknown): Set<string> {+ const refs = new Set<string>();+ const add = (value: unknown) => {+ if (typeof value === 'string' && value) refs.add(value);+ };+ const it = (item && typeof item === 'object' ? item : {}) as {+ files?: unknown;+ persistedContent?: unknown;+ };+ for (const file of Array.isArray(it.files) ? it.files : []) {+ if (!file || typeof file !== 'object') continue;+ add((file as SerializedFileLike).url);+ add((file as SerializedFileLike).path);+ }+ if (typeof it.persistedContent === 'string') {+ try {+ const parsed = JSON.parse(it.persistedContent) as { images?: unknown; files?: unknown };+ for (const image of Array.isArray(parsed?.images) ? parsed.images : []) {+ if (image && typeof image === 'object') add((image as { url?: unknown }).url);+ }+ for (const file of Array.isArray(parsed?.files) ? parsed.files : []) {+ if (file && typeof file === 'object') add((file as { path?: unknown }).path);+ }+ } catch {+ // Plain-text persisted content carries no attachment references.+ }+ }+ return refs;+}+/*** Direct maker:send carries attachment references in two parallel shapes:* the user-message blocks consumed by the agent anddiff --git a/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts b/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.tsindex 2948c76f39..f7c5c04e42 100644--- a/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts+++ b/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts@@ -8,11 +8,26 @@ export type QueuedAttachmentOwnershipOptions = {* failure may run it.*/cleanupAfterDurable?: QueuedAttachmentCleanup;+ /**+ * The local materialisation split per attachment: its host-managed refs+ * (managed URL and absolute path) and the cleanup releasing only it. When+ * given, these replace `cleanup`, so a queue edit can keep the attachments+ * the replacement still carries and release only the ones it dropped.+ */+ parts?: ReadonlyArray<{ refs: readonly string[]; cleanup: QueuedAttachmentCleanup }>;};+type OwnedAttachment = { refs: ReadonlySet<string>; cleanup: QueuedAttachmentCleanup };+type QueuedAttachmentOwnership = {- cleanup: QueuedAttachmentCleanup;+ parts: OwnedAttachment[];cleanupAfterDurable?: QueuedAttachmentCleanup;+ /**+ * Set once the coordinator accepted this materialisation. A preparation that+ * is still awaiting acceptance belongs to its own handler, which activates or+ * discards it; a superseded-owner discard must leave it alone.+ */+ accepted: boolean;durableBoundaryReached: boolean;persistenceInFlight: boolean;discardRequested: boolean;@@ -53,7 +68,12 @@ export class QueuedAttachmentOwnershipRegistry {cleanup: QueuedAttachmentCleanup | undefined,options?: QueuedAttachmentOwnershipOptions,): string | null {- if (!cleanup && !options?.cleanupAfterDurable) return null;+ const parts: OwnedAttachment[] = options?.parts?.length+ ? options.parts.map((part) => ({ refs: new Set(part.refs), cleanup: part.cleanup }))+ : cleanup+ ? [{ refs: new Set(), cleanup }]+ : [];+ if (parts.length === 0 && !options?.cleanupAfterDurable) return null;let byClient = this.ownership.get(sessionId);if (!byClient) {byClient = new Map();@@ -66,8 +86,9 @@ export class QueuedAttachmentOwnershipRegistry {}const ownerId = `${clientId}:${++this.nextOwnerId}`;clientOwnership.owners.set(ownerId, {- cleanup: cleanup ?? (() => {}),+ parts,...(options?.cleanupAfterDurable ? { cleanupAfterDurable: options.cleanupAfterDurable } : {}),+ accepted: false,durableBoundaryReached: false,persistenceInFlight: false,discardRequested: false,@@ -83,7 +104,9 @@ export class QueuedAttachmentOwnershipRegistry {*/activateCurrentOwner(sessionId: string, clientId: string, ownerId: string): string | null {const clientOwnership = this.ownership.get(sessionId)?.get(clientId);- if (!clientOwnership?.owners.has(ownerId)) return null;+ const owner = clientOwnership?.owners.get(ownerId);+ if (!clientOwnership || !owner) return null;+ owner.accepted = true;const previousOwnerId = clientOwnership.currentOwnerId;clientOwnership.currentOwnerId = ownerId;return previousOwnerId;@@ -96,6 +119,68 @@ export class QueuedAttachmentOwnershipRegistry {ownerId && clientOwnership.owners.has(ownerId) ? ownerId : null;}+ /**+ * Queue edit: move every attachment the replacement still references into+ * one surviving owner, so the caller's later superseded-owner discard+ * releases only the attachments the edit dropped. The survivor is+ * `keepOwnerId` (the edit's own materialisation) or, when the edit created+ * none, the first owner with a referenced attachment. Dropped attachments of+ * a partly kept owner stay behind in a superseded owner. Returns the survivor+ * id, which the caller activates and excludes from its discard.+ */+ retainReferencedOwners(+ sessionId: string,+ clientId: string,+ keepOwnerId: string | null,+ isReferenced: (ref: string) => boolean,+ ): string | null {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return null;+ let survivorId = keepOwnerId && clientOwnership.owners.has(keepOwnerId) ? keepOwnerId : null;+ for (const [ownerId, owner] of [...clientOwnership.owners]) {+ // Another edit's preparation that is not accepted yet is not ours to move.+ if (ownerId === survivorId || !owner.accepted) continue;+ const kept = owner.parts.filter((part) => [...part.refs].some(isReferenced));+ if (kept.length === 0) continue;+ const dropped = owner.parts.filter((part) => !kept.includes(part));+ if (!survivorId) {+ survivorId = ownerId;+ owner.parts = kept;+ } else {+ const survivor = clientOwnership.owners.get(survivorId)!;+ survivor.parts.push(...kept);+ const pendingRemote = owner.durableBoundaryReached ? undefined : owner.cleanupAfterDurable;+ if (pendingRemote) {+ const survivorRemote = survivor.cleanupAfterDurable;+ survivor.cleanupAfterDurable = survivorRemote+ ? async () => {+ await survivorRemote();+ await pendingRemote();+ }+ : pendingRemote;+ // The moved remote source has not been released yet; the caller's+ // next durable mark must run it.+ survivor.durableBoundaryReached = false;+ }+ survivor.persistenceInFlight ||= owner.persistenceInFlight;+ survivor.discardRequested ||= owner.discardRequested;+ clientOwnership.owners.delete(ownerId);+ if (clientOwnership.currentOwnerId === ownerId) clientOwnership.currentOwnerId = survivorId;+ }+ if (dropped.length > 0) {+ // The remote source travels with the kept attachments; only local copies remain here.+ clientOwnership.owners.set(`${clientId}:${++this.nextOwnerId}`, {+ parts: dropped,+ accepted: true,+ durableBoundaryReached: true,+ persistenceInFlight: owner.persistenceInFlight,+ discardRequested: owner.discardRequested,+ });+ }+ }+ return survivorId;+ }+getCurrentOwnerId(sessionId: string, clientId: string): string | null {return this.ownership.get(sessionId)?.get(clientId)?.currentOwnerId ?? null;}@@ -145,7 +230,7 @@ export class QueuedAttachmentOwnershipRegistry {continue;}clientOwnership.owners.delete(ownerId);- cleanups.push(owner.cleanup);+ cleanups.push(...localCleanups(owner));if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {cleanups.push(owner.cleanupAfterDurable);}@@ -218,7 +303,7 @@ export class QueuedAttachmentOwnershipRegistry {cleanups.push(owner.cleanupAfterDurable);}} else {- cleanups.push(owner.cleanup);+ cleanups.push(...localCleanups(owner));if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {cleanups.push(owner.cleanupAfterDurable);}@@ -234,6 +319,22 @@ export class QueuedAttachmentOwnershipRegistry {return this.discardWhere(sessionId, clientId, (ownerId) => ownerId !== keepOwnerId);}+ /**+ * Discard every accepted owner except the coordinator's current one,+ * resolved when this runs rather than when the discard was scheduled.+ * Preparations not yet accepted stay with the handler that registered them.+ */+ discardSuperseded(sessionId: string, clientId: string): Promise<void> {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ const currentOwnerId = clientOwnership?.currentOwnerId ?? null;+ return this.discardWhere(+ sessionId,+ clientId,+ (ownerId) =>+ ownerId !== currentOwnerId && clientOwnership?.owners.get(ownerId)?.accepted === true,+ );+ }+discardSpecific(sessionId: string, clientId: string, ownerId: string): Promise<void> {return this.discardWhere(sessionId, clientId, (candidate) => candidate === ownerId);}@@ -283,7 +384,7 @@ export class QueuedAttachmentOwnershipRegistry {}clientOwnership.owners.delete(ownerId);if (clientOwnership.currentOwnerId === ownerId) clientOwnership.currentOwnerId = null;- cleanups.push(owner.cleanup);+ cleanups.push(...localCleanups(owner));if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {cleanups.push(owner.cleanupAfterDurable);}@@ -315,3 +416,7 @@ export class QueuedAttachmentOwnershipRegistry {);}}++function localCleanups(owner: QueuedAttachmentOwnership): QueuedAttachmentCleanup[] {+ return owner.parts.map((part) => part.cleanup);+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 391b6254c8..c6f4fa87a2 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -870,6 +870,7 @@ import {normalizeUserMessage,materializeDirectSendOssAttachments,materializeQueuedOssAttachmentsDeferred,+ collectQueuedAttachmentRefs,} from './normalizeAttachments.js';import { QueuedAttachmentOwnershipRegistry } from './queuedAttachmentOwnership.js';import { prepareRemoteReviewAttachments } from './reviewRemoteInput.js';@@ -16919,7 +16920,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const discardQueuedAttachmentOwnership = (sessionId: string,clientId: string,- keepOwnerId?: string,+ opts?: { keepCurrentOwner?: boolean },): void => {// Coordinator discard callbacks can run before the state mutation that// removes the item emits its replacement snapshot (remove/stop/clear do@@ -16931,7 +16932,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)void (async () => {try {await awaitAgentInputQueueSnapshotPersistence(sessionId);- await queuedAttachmentOwnership.discardClient(sessionId, clientId, keepOwnerId);+ // A superseding edit keeps whichever owner is current when the+ // discard finally runs: a later edit accepted while this one waited+ // may have replaced or merged the owner that was current earlier.+ await (opts?.keepCurrentOwner+ ? queuedAttachmentOwnership.discardSuperseded(sessionId, clientId)+ : queuedAttachmentOwnership.discardClient(sessionId, clientId));} catch (error) {// A failed snapshot must keep the ownership callbacks alive. The// recycler/next lifecycle boundary can retry without losing data.@@ -18543,7 +18549,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sid,parsed.clientId,materialized.cleanupLocalMaterialization,- { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ {+ cleanupAfterDurable: materialized.cleanupAfterAcceptance,+ parts: materialized.materializedParts,+ },);let acceptedByCoordinator = false;try {@@ -18761,6 +18770,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)cleanupAfterAcceptance: undefined,cleanupBeforeAcceptance: undefined,cleanupLocalMaterialization: undefined,+ materializedParts: undefined,}: await materializeQueuedOssAttachmentsDeferred(sid, parsed);const attachmentOwnerId = steeringStoredQueueItem@@ -18769,7 +18779,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sid,parsed.clientId,materialized.cleanupLocalMaterialization,- { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ {+ cleanupAfterDurable: materialized.cleanupAfterAcceptance,+ parts: materialized.materializedParts,+ },);let acceptedByCoordinator = false;let previousAttachmentOwnerId: string | null = null;@@ -19135,7 +19148,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sid,cid,materialized.cleanupLocalMaterialization,- { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ {+ cleanupAfterDurable: materialized.cleanupAfterAcceptance,+ parts: materialized.materializedParts,+ },);let acceptedByCoordinator = false;try {@@ -19173,14 +19189,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));acceptedByCoordinator = result.updated;if (result.updated) {- // The replacement supersedes any older local materialisation owned by- // this clientId. Keep the new owner alive for the queue item's later- // persistence/discard boundary, but release old refs now.- if (attachmentOwnerId) {- queuedAttachmentOwnership.activateCurrentOwner(sid, cid, attachmentOwnerId);+ // The replacement supersedes older local materialisations owned by+ // this clientId, except media it still carries: an edit that keeps an+ // attachment creates no new copy, so the existing owner must survive+ // or the queued item would point at a deleted blob. Release only the+ // owners whose media the edit dropped.+ const replacementRefs = collectQueuedAttachmentRefs(update);+ const survivingOwnerId = queuedAttachmentOwnership.retainReferencedOwners(+ sid,+ cid,+ attachmentOwnerId,+ (ref) => replacementRefs.has(ref),+ );+ if (survivingOwnerId) {+ queuedAttachmentOwnership.activateCurrentOwner(sid, cid, survivingOwnerId);+ } else {+ // The replacement carries none of the owned media; nothing stays current.+ queuedAttachmentOwnership.restoreCurrentOwner(sid, cid, null);}- discardQueuedAttachmentOwnership(sid, cid, attachmentOwnerId ?? undefined);- markQueuedAttachmentDurableAfterSnapshot(sid, cid, attachmentOwnerId);+ discardQueuedAttachmentOwnership(sid, cid, { keepCurrentOwner: true });+ markQueuedAttachmentDurableAfterSnapshot(sid, cid, survivingOwnerId);} else {await materialized.cleanupBeforeAcceptance?.();if (attachmentOwnerId) {