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。

23.7 KB
Raw Blame
import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';
import { beforeAll, describe, expect, it } from 'vitest';
import { DeviceLinkError } from '@cindy/device-link';
import { i18n } from '@/i18n';
import {
  buildOutboxItem,
  createOutboxClientId,
  hasActiveOutboxHandoff,
  isSafelyUnsentOutboxEnqueueError,
  outboxDisplayItem,
  outboxItemAttachments,
  outboxItemReady,
  outboxItemRetrying,
  outboxItemWaitingForConnection,
  outboxItemWithEnqueueFailure,
  outboxItemWithUpload,
  outboxItemWithUploadFailure,
  outboxOwnsUpload,
  outboxWithUploadResult,
  recoverOutboxItemsToComposerDraft,
  replaceOutboxItem,
  shouldHoldOutboxDispatchForConnection,
} from '@/session/sessionOutbox';
import type { RemoteSerializedAttachment } from '@/session/types';
import { serializeComposerDocument } from '@/session/composerDocument';

// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。
beforeAll(async () => {
  await i18n.changeLanguage('zh-CN');
});

function attachmentFor(name: string): RemoteSerializedAttachment {
  return {
    id: `mobile-upload:key/${name}`,
    name,
    path: `cindy-oss-attach://key/${name}`,
    ext: '.jpg',
    size: 500_000,
    category: 'image',
    mimeType: 'image/jpeg',
  };
}

function itemWith(overrides: Partial<Parameters<typeof buildOutboxItem>[0]> = {}) {
  return buildOutboxItem({
    clientId: 'c-1',
    sessionId: 's-1',
    text: 'hello',
    permissionModeAtSend: 'ask',
    readyAttachments: [],
    claimedUploads: [],
    ...overrides,
  });
}

describe('createOutboxClientId', () => {
  it('生成非空且互不相同的 id', () => {
    const a = createOutboxClientId();
    const b = createOutboxClientId();
    expect(a).toBeTruthy();
    expect(a).not.toBe(b);
  });
});

describe('hasActiveOutboxHandoff', () => {
  const online = {
    relayOnline: true,
    targetAvailable: true,
    deviceUnresponsive: false,
    autoRecoveringError: false,
    syncInProgress: false,
  };
  const target = { deviceId: 'device-1', sessionId: 'session-1' };
  const none = new Set<string>();
  const record = (overrides: Partial<Parameters<typeof hasActiveOutboxHandoff>[0][number]> = {}) => ({
    deviceId: 'device-1',
    item: { sessionId: 'session-1', clientId: 'client-1' } as Parameters<typeof hasActiveOutboxHandoff>[0][number]['item'],
    state: 'queued' as const,
    ...overrides,
  });

  it('待发、enqueue 在途、被控端已收下未确认都算消息正在交接', () => {
    expect(hasActiveOutboxHandoff([record()], target, online, none)).toBe(true);
    expect(hasActiveOutboxHandoff([record({ state: 'sending' })], target, online, none)).toBe(true);
    expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true })], target, online, none)).toBe(true);
    expect(hasActiveOutboxHandoff([], target, online, none)).toBe(false);
  });

  it('只看当前设备的当前会话', () => {
    expect(hasActiveOutboxHandoff([record({ deviceId: 'device-2' })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([
      record({ item: { sessionId: 'session-2', clientId: 'client-1' } as ReturnType<typeof record>['item'] }),
    ], target, online, none)).toBe(false);
  });

  it('断线或被控端无响应时消息只是在等重连,不算交接', () => {
    expect(hasActiveOutboxHandoff([record()], target, { ...online, relayOnline: false }, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record()], target, { ...online, targetAvailable: false }, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record()], target, { ...online, deviceUnresponsive: true }, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record()], target, { ...online, autoRecoveringError: true }, none)).toBe(false);
  });

  it('发送后的同步不打断交接', () => {
    expect(hasActiveOutboxHandoff([record()], target, { ...online, syncInProgress: true }, none)).toBe(true);
    expect(hasActiveOutboxHandoff([record()], target, { ...online, targetAvailable: null }, none)).toBe(true);
  });

  it('出错、失败、撤销中、挂起和待确认的条目不算交接', () => {
    expect(hasActiveOutboxHandoff([record({ error: '网络错误' })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ state: 'failed' })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ state: 'confirming' })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ cancelRequested: true })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ suspended: true })], target, online, none)).toBe(false);
  });

  it('未移交的记录只看会话 FIFO 队首:队首卡住时后面的消息不算交接', () => {
    const later = record({ item: { sessionId: 'session-1', clientId: 'client-2' } as ReturnType<typeof record>['item'] });
    expect(hasActiveOutboxHandoff([record({ state: 'failed' }), later], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ suspended: true }), later], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ cancelRequested: true }), later], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ state: 'confirming', error: '待确认' }), later], target, online, none)).toBe(false);
    // 已移交被控端的记录不挡队首,下一条正常推进照样算。
    expect(hasActiveOutboxHandoff([
      record({ state: 'host-owned', retrySafe: true, cancelRequested: true }),
      later,
    ], target, online, none)).toBe(true);
  });

  it('已落定、撤销中的已移交记录不算交接', () => {
    expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true, cleanupOutcome: 'accepted' })], target, online, none)).toBe(false);
    expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true, cancelRequested: true })], target, online, none)).toBe(false);
  });

  it('已进被控端队列或已回流进历史的条目不算交接', () => {
    expect(hasActiveOutboxHandoff([record({ state: 'host-owned', retrySafe: true })], target, online, new Set(['client-1']))).toBe(false);
    // 历史已确认的 clientId 同样走这个集合:快速 turn 结束后不必等 outbox 对账。
    expect(hasActiveOutboxHandoff([
      record({ state: 'host-owned', retrySafe: true }),
      record({ state: 'host-owned', retrySafe: true, item: { sessionId: 'session-1', clientId: 'client-2' } as ReturnType<typeof record>['item'] }),
    ], target, online, new Set(['client-1', 'client-2']))).toBe(false);
  });
});

describe('shouldHoldOutboxDispatchForConnection', () => {
  const online = {
    relayOnline: true,
    targetAvailable: true,
    deviceUnresponsive: false,
    autoRecoveringError: false,
    syncInProgress: false,
  };

  it('只在 relay、目标 presence、熔断和请求状态都健康时派发', () => {
    expect(shouldHoldOutboxDispatchForConnection(online)).toBe(false);
    expect(shouldHoldOutboxDispatchForConnection({ ...online, relayOnline: false })).toBe(true);
    expect(shouldHoldOutboxDispatchForConnection({ ...online, targetAvailable: false })).toBe(true);
    expect(shouldHoldOutboxDispatchForConnection({ ...online, deviceUnresponsive: true })).toBe(true);
    expect(shouldHoldOutboxDispatchForConnection({ ...online, autoRecoveringError: true })).toBe(true);
    expect(shouldHoldOutboxDispatchForConnection({ ...online, syncInProgress: true })).toBe(true);
  });

  it('presence 尚未知时不把健康连接永久卡住', () => {
    expect(shouldHoldOutboxDispatchForConnection({
      ...online,
      targetAvailable: null,
    })).toBe(false);
  });

  it('新连接代把旧 offline 降为 unknown,且本代新 offline 仍会重新阻塞', () => {
    expect(shouldHoldOutboxDispatchForConnection({
      ...online,
      targetAvailable: false,
    })).toBe(true);
    expect(shouldHoldOutboxDispatchForConnection({
      ...online,
      targetAvailable: null,
    })).toBe(false);
    expect(shouldHoldOutboxDispatchForConnection({
      ...online,
      targetAvailable: false,
    })).toBe(true);
  });
});

describe('isSafelyUnsentOutboxEnqueueError', () => {
  it('只允许明确发生在派发前的连接失败自动回队', () => {
    expect(isSafelyUnsentOutboxEnqueueError(
      new DeviceLinkError('NOT_CONNECTED', 'not connected'),
    )).toBe(true);
    expect(isSafelyUnsentOutboxEnqueueError(
      new DeviceLinkError('LINK_NOT_OPEN', 'link is closed'),
    )).toBe(true);
    expect(isSafelyUnsentOutboxEnqueueError('[DEVICE_UNRESPONSIVE] circuit open')).toBe(true);
  });

  it('拒绝可能已经到达被控端的 in-flight 断线与 invoke 超时', () => {
    const ambiguous = new DeviceLinkError('NOT_CONNECTED', 'ack may be lost');
    ambiguous.inFlight = true;
    expect(isSafelyUnsentOutboxEnqueueError(ambiguous)).toBe(false);
    expect(isSafelyUnsentOutboxEnqueueError(
      new DeviceLinkError('INVOKE_TIMEOUT', 'no result'),
    )).toBe(false);
  });
});

describe('buildOutboxItem', () => {
  it('就绪附件占前段槽位,在途任务按序占后段;有失败卡时直接失败态', () => {
    const ready = [attachmentFor('a.jpg')];
    const item = buildOutboxItem({
      clientId: 'c-1',
      sessionId: 's-1',
      text: 'hi',
      permissionModeAtSend: 'plan',
      readyAttachments: ready,
      claimedUploads: [
        { localId: 'u-1', failed: false },
        { localId: 'u-2', failed: true },
      ],
    });
    expect(item.attachmentSlots).toEqual([ready[0], null, null]);
    expect(item.slotByLocalId).toEqual({ 'u-1': 1, 'u-2': 2 });
    expect(item.waitingIds).toEqual(['u-1']);
    expect(item.failedIds).toEqual(['u-2']);
    expect(item.phase).toBe('failed');
    expect(outboxItemReady(item)).toBe(false);
  });

  it('纯文本(无附件)即刻就绪', () => {
    const item = itemWith();
    expect(outboxItemReady(item)).toBe(true);
    expect(outboxItemAttachments(item)).toEqual([]);
  });

  it('keeps quote metadata until the outbox item is dispatched', () => {
    expect(itemWith({ quotesEncoded: true }).quotesEncoded).toBe(true);
    expect(itemWith().quotesEncoded).toBe(false);
  });

  it('keeps session reference source hints until the outbox item is dispatched', () => {
    const sessionRefs = [{ sessionId: 'source', deviceId: 'source-device' }];
    const item = itemWith({ sessionRefs });

    expect(item.sessionRefs).toEqual(sessionRefs);
    expect(item.sessionRefs).not.toBe(sessionRefs);
  });

  it('keeps structured reference metadata until dispatch', () => {
    const href = 'cindy://session/session-a?message=message-a';
    const text = `inspect ${href}`;
    const reference = {
      kind: 'message' as const,
      start: text.indexOf(href),
      end: text.length,
      href,
      sessionId: 'session-a',
      messageClientId: 'message-a',
      text: 'Complete target message body',
    };

    expect(itemWith({ text, agentReferences: [reference] }).agentReferences)
      .toEqual([reference]);
  });
});

describe('recoverOutboxItemsToComposerDraft', () => {
  it('restores marked quotes separately while keeping the composer text marker-free', () => {
    const encoded = [
      '> <!-- cindy-composer-quote -->',
      '> selected',
      '',
      'reply',
      '',
      '> <!-- cindy-composer-quote -->',
      '> second',
      '',
      'more',
    ].join('\n');
    const item = itemWith({ text: encoded, quotesEncoded: true });

    const recovery = recoverOutboxItemsToComposerDraft([item], {
      visibleText: 'new draft',
      encodedBody: 'new draft',
      quotes: [],
    });
    expect(recovery).toMatchObject({
      visibleText: 'reply\n\nmore\n\nnew draft',
      encodedBody: `${encoded}\n\nnew draft`,
      quotes: [{ text: 'selected' }, { text: 'second' }],
    });
    expect(serializeComposerDocument(recovery.document).text).toBe(`${encoded}\n\nnew draft`);
  });

  it('keeps existing quoted draft metadata aligned after outbox recovery', () => {
    const recoveredEncoded = [
      '> <!-- cindy-composer-quote -->',
      '> recovered quote',
      '',
      'recovered reply',
    ].join('\n');
    const existingEncoded = [
      '> <!-- cindy-composer-quote -->',
      '> existing quote',
      '',
      'existing reply',
    ].join('\n');

    const recovery = recoverOutboxItemsToComposerDraft(
      [itemWith({ text: recoveredEncoded, quotesEncoded: true })],
      {
        visibleText: 'existing reply',
        encodedBody: existingEncoded,
        quotes: [{ text: 'existing quote' }],
      },
    );
    expect(recovery).toMatchObject({
      visibleText: 'recovered reply\n\nexisting reply',
      encodedBody: `${recoveredEncoded}\n\n${existingEncoded}`,
      quotes: [{ text: 'recovered quote' }, { text: 'existing quote' }],
    });
    expect(serializeComposerDocument(recovery.document).text).toBe(
      `${recoveredEncoded}\n\n${existingEncoded}`,
    );
  });

  it('keeps markerless legacy parsing leading-only during salvage', () => {
    const encoded = '> old quote\n\nHere:\n> user markdown';
    const item = itemWith({ text: encoded, quotesEncoded: true });

    expect(recoverOutboxItemsToComposerDraft([item])).toMatchObject({
      visibleText: 'Here:\n> user markdown',
      encodedBody: encoded,
      quotes: [{ text: 'old quote' }],
    });
  });

  it('restores pasted-text and slash atoms instead of flattening failed attachment sends', () => {
    const item = itemWith({
      text: '/help before long\ntext after',
      pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (2 lines)' }],
      slashCommandRanges: [{ start: 0, end: 5 }],
    });
    const recovery = recoverOutboxItemsToComposerDraft([item]);

    expect(recovery.document.nodes.map((node) => node.type)).toEqual([
      'text', 'text', 'pasted-text', 'text',
    ]);
    expect(serializeComposerDocument(recovery.document)).toMatchObject({
      pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (2 lines)' }],
      slashCommandRanges: [{ start: 0, end: 5 }],
    });
  });

  it('restores message references instead of flattening them to private URIs', () => {
    const href = 'cindy://session/session-a?message=message-a';
    const text = `inspect ${href}`;
    const reference = {
      kind: 'message' as const,
      start: text.indexOf(href),
      end: text.length,
      href,
      sessionId: 'session-a',
      messageClientId: 'message-a',
      text: 'Complete target message body',
    };
    const recovery = recoverOutboxItemsToComposerDraft([
      itemWith({ text, agentReferences: [reference] }),
    ]);

    expect(serializeComposerDocument(recovery.document).agentReferences)
      .toEqual([reference]);
  });
});

describe('outboxItemWithUpload / outboxItemWithUploadFailure', () => {
  it('上传成功按 localId 填槽,全部落定后就绪且附件保持槽序', () => {
    const ready = [attachmentFor('first.jpg')];
    let item = buildOutboxItem({
      clientId: 'c-1',
      sessionId: 's-1',
      text: 'hi',
      permissionModeAtSend: 'ask',
      readyAttachments: ready,
      claimedUploads: [
        { localId: 'u-1', failed: false },
        { localId: 'u-2', failed: false },
      ],
    });
    expect(outboxItemReady(item)).toBe(false);
    // 后入队的先完成:槽序不受完成顺序影响。
    const late = attachmentFor('late.jpg');
    const early = attachmentFor('early.jpg');
    item = outboxItemWithUpload(item, 'u-2', late);
    expect(outboxItemReady(item)).toBe(false);
    item = outboxItemWithUpload(item, 'u-1', early);
    expect(outboxItemReady(item)).toBe(true);
    expect(outboxItemAttachments(item)).toEqual([ready[0], early, late]);
  });

  it('不属于本条目的 localId 返回原引用', () => {
    const item = itemWith({ claimedUploads: [{ localId: 'u-1', failed: false }] });
    expect(outboxItemWithUpload(item, 'other', attachmentFor('x.jpg'))).toBe(item);
    expect(outboxItemWithUploadFailure(item, 'other')).toBe(item);
  });

  it('上传失败转失败态并阻塞就绪;重复失败回调幂等', () => {
    let item = itemWith({ claimedUploads: [{ localId: 'u-1', failed: false }] });
    item = outboxItemWithUploadFailure(item, 'u-1');
    expect(item.phase).toBe('failed');
    expect(item.failedIds).toEqual(['u-1']);
    expect(item.waitingIds).toEqual([]);
    expect(outboxItemWithUploadFailure(item, 'u-1')).toBe(item);
  });

  it('失败任务重试成功(直接收到 onUploaded)时从 failedIds 摘除并解除失败态', () => {
    let item = itemWith({ claimedUploads: [{ localId: 'u-1', failed: true }] });
    expect(item.phase).toBe('failed');
    item = outboxItemWithUpload(item, 'u-1', attachmentFor('a.jpg'));
    expect(item.failedIds).toEqual([]);
    expect(item.phase).toBe('uploading');
    expect(outboxItemReady(item)).toBe(true);
  });
});

describe('outboxItemRetrying / outboxItemWithEnqueueFailure', () => {
  it('重试把失败任务移回等待集并清除 enqueue 错误', () => {
    let item = itemWith({ claimedUploads: [{ localId: 'u-1', failed: true }] });
    item = outboxItemWithEnqueueFailure(item, 'boom');
    expect(item.phase).toBe('failed');
    expect(item.enqueueError).toBe('boom');
    item = outboxItemRetrying(item);
    expect(item.phase).toBe('uploading');
    expect(item.enqueueError).toBeNull();
    expect(item.waitingIds).toEqual(['u-1']);
    expect(item.failedIds).toEqual([]);
  });

  it('enqueue 失败型(附件已齐)重试后即刻就绪,可直接重新派发', () => {
    let item = itemWith();
    item = outboxItemWithEnqueueFailure(item, 'network');
    expect(outboxItemReady(item)).toBe(false);
    item = outboxItemRetrying(item);
    expect(outboxItemReady(item)).toBe(true);
  });

  it('派发途中断线回到等待连接态,不变成需要用户重试的失败项', () => {
    const dispatching = { ...itemWith(), phase: 'dispatching' as const };
    const waiting = outboxItemWaitingForConnection(dispatching);
    expect(waiting.phase).toBe('uploading');
    expect(waiting.enqueueError).toBeNull();
    expect(outboxItemReady(waiting)).toBe(true);
  });
});

describe('outboxDisplayItem', () => {
  it('上传进度与失败文案', () => {
    let item = buildOutboxItem({
      clientId: 'c-1',
      sessionId: 's-1',
      text: 'hi',
      permissionModeAtSend: 'ask',
      readyAttachments: [attachmentFor('a.jpg')],
      claimedUploads: [{ localId: 'u-1', failed: false }],
    });
    expect(outboxDisplayItem(item)).toMatchObject({
      attachmentCount: 2,
      uploadedCount: 1,
      failed: false,
      errorText: null,
    });
    item = outboxItemWithUploadFailure(item, 'u-1');
    const display = outboxDisplayItem(item);
    expect(display.failed).toBe(true);
    expect(display.errorText).toContain('附件上传失败');
    const enqueueFailed = outboxDisplayItem(outboxItemWithEnqueueFailure(itemWith(), 'RPC boom'));
    expect(enqueueFailed.errorText).toBe('RPC boom');
  });

  it('发件箱整条失败时只在投递记下的那张图上标失败,其余图不再转圈;入队失败不标图片', () => {
    // 与 durableOutboxDisplayItem 的真实输出同形:失败只记在 phase / failedUploadSlot 上,failedIds 为空。
    const base = buildOutboxItem({
      clientId: 'c-1', sessionId: 's-1', text: 'hi', permissionModeAtSend: 'ask', readyAttachments: [],
      claimedUploads: [
        { localId: 'u-a', failed: false, kind: 'image', previewUri: 'file:///tmp/a.jpg' },
        { localId: 'u-b', failed: false, kind: 'image', previewUri: 'file:///tmp/b.jpg' },
      ],
    });
    const failed = { ...base, phase: 'failed' as const, enqueueError: 'upload failed', failedUploadSlot: 1 };
    expect(outboxDisplayItem(failed).thumbnails.map(({ key, uploading, failed: bad }) => ({ key, uploading, failed: bad }))).toEqual([
      { key: 'c-1-slot-0', uploading: false, failed: undefined },
      { key: 'c-1-slot-1', uploading: false, failed: true },
    ]);
    const enqueueFailed = { ...base, phase: 'failed' as const, enqueueError: 'RPC boom' };
    expect(outboxDisplayItem(enqueueFailed).thumbnails.some((thumb) => thumb.failed)).toBe(false);
  });

  it('图片槽出缩略格(本地预览 / 落定 ossRef / 上传中态),文件槽走计数行', () => {
    let item = buildOutboxItem({
      clientId: 'c-1',
      sessionId: 's-1',
      text: 'hi',
      permissionModeAtSend: 'ask',
      readyAttachments: [attachmentFor('ready.jpg')],
      readyPreviews: ['file:///tmp/ready-preview.jpg'],
      claimedUploads: [
        { localId: 'u-img', failed: false, kind: 'image', previewUri: 'file:///tmp/pending.jpg' },
        { localId: 'u-pdf', failed: false, kind: 'file', previewUri: 'file:///tmp/scan.pdf', name: 'scan.pdf' },
      ],
    });
    let display = outboxDisplayItem(item);
    // 就绪图:本地预览 + ossRef 双源;上传中图:仅本地预览,uploading 真;pdf 不进缩略条。
    expect(display.thumbnails).toEqual([
      {
        key: 'c-1-slot-0',
        uri: 'file:///tmp/ready-preview.jpg',
        ossRef: 'cindy-oss-attach://key/ready.jpg',
        uploading: false,
      },
      { key: 'c-1-slot-1', uri: 'file:///tmp/pending.jpg', ossRef: null, uploading: true },
    ]);
    expect(display.fileCount).toBe(1);
    expect(display.fileNames).toEqual(['scan.pdf']);
    // 上传落定后:uploading 归零,ossRef 补上,本地预览保留(第一帧到落定零跳变)。
    item = outboxItemWithUpload(item, 'u-img', attachmentFor('landed.jpg'));
    display = outboxDisplayItem(item);
    expect(display.thumbnails[1]).toEqual({
      key: 'c-1-slot-1',
      uri: 'file:///tmp/pending.jpg',
      ossRef: 'cindy-oss-attach://key/landed.jpg',
      uploading: false,
    });
  });
});

describe('outboxWithUploadResult / outboxOwnsUpload / replaceOutboxItem', () => {
  it('按 localId 路由到正确条目;不属于任何条目时返回原引用', () => {
    const first = buildOutboxItem({
      clientId: 'c-1',
      sessionId: 's-1',
      text: 'one',
      permissionModeAtSend: 'ask',
      readyAttachments: [],
      claimedUploads: [{ localId: 'u-1', failed: false }],
    });
    const second = buildOutboxItem({
      clientId: 'c-2',
      sessionId: 's-1',
      text: 'two',
      permissionModeAtSend: 'ask',
      readyAttachments: [],
      claimedUploads: [{ localId: 'u-2', failed: false }],
    });
    const items = [first, second];
    expect(outboxOwnsUpload(items, 'u-2')).toBe(true);
    expect(outboxOwnsUpload(items, 'nope')).toBe(false);
    const next = outboxWithUploadResult(items, 'u-2', { attachment: attachmentFor('b.jpg') });
    expect(next).not.toBe(items);
    expect(next[0]).toBe(first);
    expect(outboxItemReady(next[1]!)).toBe(true);
    expect(outboxWithUploadResult(items, 'nope', { failed: true })).toBe(items);
  });

  it('replaceOutboxItem 原位替换,找不到返回原引用', () => {
    const item = itemWith();
    const other = { ...item, clientId: 'other' };
    const items = [item];
    expect(replaceOutboxItem(items, other)).toBe(items);
    const replaced = replaceOutboxItem(items, { ...item, text: 'changed' });
    expect(replaced[0]?.text).toBe('changed');
  });
});

it('preserves external share order across completed and pending durable slots', () => {
  const later = attachmentFor('second.pdf');
  const item = itemWith({
    readyAttachments: [later], readyPreviews: ['file:///stage/second'],
    claimedUploads: [{ localId: 'first', failed: false, kind: 'file', name: 'first.pdf', previewUri: 'file:///share/first' }],
    attachmentOrder: incomingShareSlotOrder([{ batchId: 'batch', index: 1 }, { batchId: 'batch', index: 0 }]),
  });
  expect(item.attachmentSlots).toEqual([null, later]);
  expect(item.slotByLocalId.first).toBe(0);
  expect(item.slotMeta.map(meta => meta.name)).toEqual(['first.pdf', 'second.pdf']);
  expect(item.slotMeta.map(meta => meta.previewUri)).toEqual(['file:///share/first', 'file:///stage/second']);
  const complete = outboxItemWithUpload(item, 'first', attachmentFor('first.pdf'));
  expect(outboxItemAttachments(complete).map(attachment => attachment.name)).toEqual(['first.pdf', 'second.pdf']);
});