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。

29.2 KB
Raw Blame
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
/**
 * 待发送气泡 → 消息流渲染项的构造。
 *
 * 这些气泡原来挂在列表 footer,消息回流时跨 footer↔data 搬家,位置会跳(空会话时被撑满高度
 * 的居中同步占位顶到屏幕中间,实测差约 18% 屏高),用户看到「气泡在中间 → 消失 → 在底部
 * 重新出现」。改成消息流项后靠两点保证连续:key 与正式消息一致(`message-${clientId}`)、
 * 已回流的 clientId 立刻不再产出气泡(避免同一句话双显)。
 */
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { CONTINUE_AFTER_ERROR_PROMPT, UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';
import { i18n } from '@/i18n';
import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';
import {
  appendPendingSendItems,
  buildMobileMessageListExtraData,
  buildPendingSendItems,
  isPendingSendItemSelected,
  mergePendingSendItems,
  pendingSendItemKey,
  pendingSendBubbleText,
  pendingSendSpins,
  type MobilePendingSendActions,
} from '@/session/pendingSendItems';
import type { MobileOutboxDisplayItem } from '@/session/sessionOutbox';
import type { QueuedRemoteMessage, RemoteMessage } from '@/session/types';
import { remoteSessionStore } from '@/session/remoteSessionStore';
import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';
import { buildMobileStreamingRenderWindow } from '@/session/messageRenderStreamingCache';
import { computeVanishedQueueItems } from '@/session/queueSettling';
import { appendOptimisticUserMessage, projectOptimisticUserMessages, reconcileOptimisticUserMessages, type OptimisticUserMessage } from '@/session/optimisticUserMessages';

const NO_IDS: ReadonlySet<string> = new Set();
const NO_PRESENTATION: ReadonlyMap<string, { actions: MobilePendingSendActions; hint: string | null }> = new Map();

function queued(clientId: string, text = `text-${clientId}`): QueuedRemoteMessage {
  return {
    clientId,
    text,
    persistedContent: text,
    model: 'm',
    effort: '',
    permissionMode: 'ask',
    workingDir: '/tmp',
    chatMessage: {
      clientId,
      role: 'user',
      content: text,
      isStreaming: false,
      createdAt: '2026-07-30T00:00:00.000Z',
    },
    createOpts: { agentKind: 'codex', workingDir: '/tmp' },
  } as unknown as QueuedRemoteMessage;
}

function outboxItem(clientId: string, overrides: Partial<MobileOutboxDisplayItem> = {}): MobileOutboxDisplayItem {
  return {
    clientId,
    text: `outbox-${clientId}`,
    quotesEncoded: false,
    attachmentCount: 0,
    uploadedCount: 0,
    thumbnails: [],
    fileCount: 0,
    failed: false,
    errorText: null,
    ...overrides,
  };
}

function build(overrides: Partial<Parameters<typeof buildPendingSendItems>[0]> = {}) {
  return buildPendingSendItems({
    queue: [],
    settling: [],
    outbox: [],
    hiddenClientIds: NO_IDS,
    sendingClientIds: NO_IDS,
    editingClientId: null,
    steeringClientIds: NO_IDS,
    presentationByClientId: NO_PRESENTATION,
    ...overrides,
  });
}

describe('appendPendingSendItems', () => {
  it.each(['text', 'image'])('replaces %s pending rows when history arrives before queue reconciliation', (kind) => {
    const pending = build({ outbox: [outboxItem('sent', kind === 'image' ? {
      text: '', attachmentCount: 1, uploadedCount: 1,
      thumbnails: [{ key: 'sent-slot-0', uri: 'file:///image.png', ossRef: null, uploading: false }],
    } : {}), outboxItem('next')] });
    const previous = { key: 'message-previous', type: 'message' };
    const delivered = { key: pendingSendItemKey('sent'), type: 'message' };
    expect(appendPendingSendItems([previous], pending)).toEqual([previous, ...pending]);
    // The history snapshot advanced, but raw-store token / pending snapshot did not.
    const during = appendPendingSendItems([previous, delivered], pending);
    expect(during).toEqual([previous, delivered, pending[1]]);
    expect(new Set(during.map((row) => row.key)).size).toBe(during.length);
    expect(appendPendingSendItems([previous, delivered], pending.slice(1))).toEqual(during);
  });

  it('retains the rendered list when no optimistic rows remain', () => {
    const rendered = [{ key: pendingSendItemKey('sent') }];
    expect(appendPendingSendItems(rendered, [])).toBe(rendered);
    expect(appendPendingSendItems(rendered, build({ queue: [queued('sent')] }))).toBe(rendered);
  });
});

describe('reply before user echo', () => {
  const sessionId = 'reply-order';
  function row(clientId: string, role: RemoteMessage['role'], seconds: number): RemoteMessage {
    return { id: clientId, clientId, sessionId, role,
      createdAt: new Date(Date.UTC(2026, 6, 30, 0, 0, seconds)).toISOString(),
      content: role === 'user' ? { text: 'Continue' } : 'Reply', toolUseId: null, agentMeta: null };
  }
  function push(message: RemoteMessage) {
    remoteSessionStore.applyRemotePush('dev', 'local-db:messages:created', { sessionId, message });
  }
  function reserve(current: readonly OptimisticUserMessage[] = [], clientId = 'sent') {
    return appendOptimisticUserMessage(current, remoteSessionStore.getMessages(sessionId), queued(clientId), sessionId);
  }
  function render(pending: ReturnType<typeof build>, slots: readonly OptimisticUserMessage[]) {
    const messages = remoteSessionStore.getMessages(sessionId);
    const echoed = new Set(messages.map((message) => message.clientId));
    return mergePendingSendItems(buildMobileMessageRenderItems(
      projectOptimisticUserMessages(messages, slots), { isSessionStreaming: true, preserveSourceOrder: true },
    ), pending, new Set(slots.map((entry) => entry.message.clientId).filter((id) => !echoed.has(id))));
  }
  afterEach(() => { remoteSessionStore.clear(); vi.useRealTimers(); });

  it.each([false, true])('leaves unreserved busy sends to authoritative history (separate renders: %s)', (separateRenders) => {
    push(row('current', 'user', 0));
    push(row('current-reply', 'assistant', 1));
    const previousQueue = [queued('sent')];
    // Busy sends keep the existing pending tail, without claiming a turn slot.
    expect(render(build({ queue: previousQueue }), []).at(-1)?.key).toBe('message-sent');
    push(row('next-reply', 'assistant', 3));
    if (separateRenders) {
      expect(render(build({ queue: previousQueue }), []).map((item) => item.key)).toEqual([
        'message-current', 'message-current-reply', 'message-next-reply', 'message-sent',
      ]);
    }
    const settling = computeVanishedQueueItems({
      previous: previousQueue, current: [], previousSteeringClientIds: NO_IDS,
      currentSteeringClientIds: NO_IDS, hiddenClientIds: NO_IDS, locallyRemovedClientIds: NO_IDS,
    });
    expect(render(build({ settling }), []).map((item) => item.key)).toEqual([
      'message-current', 'message-current-reply', 'message-next-reply', 'message-sent',
    ]);
    push(row('sent', 'user', 2));
    expect(render(build({ settling }), []).map((item) => item.key)).toEqual([
      'message-current', 'message-current-reply', 'message-sent', 'message-next-reply',
    ]);
  });

  it('invalidates the streaming prefix when a local user introduces a new turn boundary', () => {
    const old = [row('old-user', 'user', 0), { ...row('old-thinking', 'thinking', 1), content: { text: 'Old thought' } }];
    const previous = buildMobileStreamingRenderWindow({
      cacheKey: 'en', messages: old, messageStructureToken: {},
      options: { isSessionStreaming: true, sessionId },
    });
    const slots = appendOptimisticUserMessage([], old, queued('sent'), sessionId);
    const current = [...old, { ...row('new-thinking', 'thinking', 3), content: { text: 'New thought' } }];
    const next = buildMobileStreamingRenderWindow({
      cacheKey: 'en', messages: projectOptimisticUserMessages(current, slots),
      messageStructureToken: {}, previousPrefix: previous.prefix,
      options: { isSessionStreaming: true, preserveSourceOrder: true, sessionId },
    });
    expect(next.items.map((item) => item.key)).toEqual([
      'message-old-user', 'work-old-thinking', 'message-sent', 'work-new-thinking',
    ]);
  });

  it.each(['settling', 'sending'])('keeps the %s bubble before an early reply and replaces it in place', (phase) => {
    push(row('old-user', 'user', 0));
    push(row('old-reply', 'assistant', 1));
    const slots = reserve(); // The production send path reserves BEFORE enqueue.
    const pending = build({
      settling: phase === 'settling' ? [queued('sent')] : [],
      queue: phase === 'sending' ? [queued('sent'), queued('next')] : [queued('next')],
      sendingClientIds: new Set(phase === 'sending' ? ['sent'] : []),
      outbox: [outboxItem('upload', { attachmentCount: 1, uploadedCount: 0 })],
    });
    push(row('reply', 'assistant', 3));
    const before = render(pending, slots);
    expect(before.map((item) => item.key)).toEqual([
      'message-old-user', 'message-old-reply', 'message-sent', 'message-reply', 'message-next', 'message-upload',
    ]);
    expect(before[2]).toBe(pending[0]);
    push(row('sent', 'user', 2));
    expect(render(pending, slots).map((item) => item.key)).toEqual(before.map((item) => item.key));
    expect(render(pending, slots)[2].type).toBe('message');
  });

  it.each(['2020-01-01', '2030-01-01'])('ignores a phone clock set to %s', (clock) => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date(clock));
    const source = queued('sent');
    source.chatMessage.createdAt = new Date().toISOString();
    const slots = appendOptimisticUserMessage([], [], source, sessionId);
    const pending = build({ settling: [source] });
    remoteSessionStore.applyRemotePush('dev', 'maker:event', {
      sessionId, persistId: 'reply', event: { type: 'text', data: { text: 'Reply', isFinal: false } },
    });
    vi.advanceTimersByTime(100);
    expect(render(pending, slots).map((item) => item.key)).toEqual(['message-sent', 'message-reply']);
    push(row('sent', 'user', 2));
    expect(render(pending, slots).map((item) => item.key)).toEqual(['message-sent', 'message-reply']);
  });

  it('separates new folded work from the previous turn before grouping', () => {
    push(row('old-user', 'user', 0));
    push({ ...row('old-thinking', 'thinking', 1), content: { text: 'Old thought' } });
    const slots = reserve();
    push({ ...row('thinking', 'thinking', 3), content: { text: 'New thought' } });
    const items = render(build({ settling: [queued('sent')] }), slots);
    expect(items.map((item) => item.key)).toEqual([
      'message-old-user', 'work-old-thinking', 'message-sent', 'work-thinking',
    ]);
  });

  it.each(['image', 'synthetic'])('retains the reserved %s bubble before reply grouping', (kind) => {
    const source = queued('sent', kind === 'synthetic' ? '[UI_ACTION_TRIGGER] hidden action' : '');
    if (kind === 'image') source.chatMessage.images = [{ url: 'https://example.com/image.png', name: 'image.png' }];
    const slots = appendOptimisticUserMessage([], [], source, sessionId);
    push(row('reply', 'assistant', 3));
    const pending = build({ settling: [source] });
    const items = render(pending, slots);
    expect(items.map((item) => item.key)).toEqual(['message-sent', 'message-reply']);
    expect(items[0]).toBe(pending[0]);
    expect(JSON.stringify(items[0])).not.toContain('hidden action');
  });

  it.each(['sent', 'second'])('keeps two reserved positions when %s echoes first', (firstEcho) => {
    let slots = reserve();
    push(row('reply', 'assistant', 3));
    slots = reserve(slots, 'second');
    push(row('second-reply', 'assistant', 5));
    let pending = build({ settling: [queued('sent'), queued('second')] });
    const expected = ['message-sent', 'message-reply', 'message-second', 'message-second-reply'];
    expect(render(pending, slots).map((item) => item.key)).toEqual(expected);
    push(row(firstEcho, 'user', firstEcho === 'sent' ? 2 : 4));
    expect(render(pending, slots).map((item) => item.key)).toEqual(expected);
    pending = pending.filter((item) => item.clientId !== firstEcho);
    slots = reconcileOptimisticUserMessages(slots, remoteSessionStore.getMessages(sessionId),
      new Set(pending.map((item) => item.clientId)), new Set([firstEcho]));
    expect(render(pending, slots).map((item) => item.key)).toEqual(expected);
  });

  it('keeps a busy follow-up and unsent outbox at the tail until dispatch', () => {
    push(row('current', 'user', 0));
    const pending = build({ queue: [queued('next')], sendingClientIds: new Set(['next']), outbox: [outboxItem('upload')] });
    push(row('reply', 'assistant', 3));
    expect(render(pending, []).map((item) => item.key))
      .toEqual(['message-current', 'message-reply', 'message-next', 'message-upload']);
    const slots = reserve([], 'next');
    push(row('next-reply', 'assistant', 5));
    expect(render(build({ settling: [queued('next')] }), slots).map((item) => item.key))
      .toEqual(['message-current', 'message-reply', 'message-next', 'message-next-reply']);
  });

  it('drops failed, cancelled, and rolled-back queue reservations', () => {
    const slots = reserve();
    expect(reconcileOptimisticUserMessages(slots, [], NO_IDS, NO_IDS)).toEqual([]);
    expect(reconcileOptimisticUserMessages(slots, [], new Set(['sent']), NO_IDS)).toBe(slots);
    const echo = row('sent', 'user', 2);
    const echoedSlots = reconcileOptimisticUserMessages(slots, [echo], NO_IDS, NO_IDS);
    expect(echoedSlots).toEqual([{ ...slots[0], message: echo }]);
    expect(reconcileOptimisticUserMessages(echoedSlots, [echo], NO_IDS, NO_IDS)).toBe(echoedSlots);
    expect(reconcileOptimisticUserMessages(slots, [row('sent', 'user', 2)], NO_IDS, new Set(['sent']))).toEqual([]);
  });

  it('preserves prepended history and does not use timestamps to reanchor the send', () => {
    push(row('old-reply', 'assistant', 1));
    const slots = reserve();
    push(row('older-user', 'user', 0));
    push(row('reply', 'assistant', 3));
    expect(render(build({ settling: [queued('sent')] }), slots).map((item) => item.key))
      .toEqual(['message-older-user', 'message-old-reply', 'message-sent', 'message-reply']);
  });
});

describe('buildPendingSendItems', () => {
  it('shares the message item key so the bubble and the real message land in one place', () => {
    const [item] = build({ queue: [queued('abc')] });
    expect(item.key).toBe(pendingSendItemKey('abc'));
    expect(item.key).toBe('message-abc');
  });

  it('orders settling first, queue next, local outbox last', () => {
    const items = build({
      settling: [queued('settled')],
      queue: [queued('q1'), queued('q2')],
      outbox: [outboxItem('local')],
    });
    expect(items.map((entry) => entry.clientId)).toEqual(['settled', 'q1', 'q2', 'local']);
    expect(items.map((entry) => entry.phase)).toEqual(['settling', 'queued', 'queued', 'sending']);
  });

  it('drops anything whose real message already came back (no double bubble)', () => {
    const items = build({
      settling: [queued('done')],
      queue: [queued('live')],
      hiddenClientIds: new Set(['done']),
    });
    expect(items.map((entry) => entry.clientId)).toEqual(['live']);
  });

  it('prefers the queue entry when an item is both settling and back in the queue', () => {
    const items = build({
      settling: [queued('same')],
      queue: [queued('same')],
      presentationByClientId: new Map([['same', {
        actions: {
          moveUp: { disabled: true, disabledReason: null, targetIndex: null },
          moveDown: { disabled: true, disabledReason: null, targetIndex: null },
          remove: { disabled: false, disabledReason: null },
          edit: { disabled: false, disabledReason: null },
          steer: { disabled: false, disabledReason: null },
        },
        hint: null,
      }]]),
    });
    expect(items).toHaveLength(1);
    expect(items[0].phase).toBe('queued');
    // 回到队列的条目重新可操作(取消 / 编辑 / 插队)。
    expect(items[0].actions).not.toBeNull();
    expect(items[0].queueIndex).toBe(1);
  });

  it('marks in-flight enqueue and steering as sending, editing as editing', () => {
    const items = build({
      queue: [queued('a'), queued('b'), queued('c')],
      sendingClientIds: new Set(['a']),
      steeringClientIds: new Set(['b']),
      editingClientId: 'c',
    });
    expect(items.map((entry) => entry.phase)).toEqual(['sending', 'sending', 'editing']);
  });

  it('derives outbox phases from upload progress and failure', () => {
    const items = build({
      outbox: [
        outboxItem('uploading', { attachmentCount: 2, uploadedCount: 1 }),
        outboxItem('ready', { attachmentCount: 2, uploadedCount: 2 }),
        outboxItem('broken', { failed: true, errorText: 'boom' }),
      ],
    });
    expect(items.map((entry) => entry.phase)).toEqual(['uploading', 'sending', 'failed']);
    expect(items[2].errorText).toBe('boom');
    // 失败条目不给队列操作(它还没入队),重试 / 删除走 outbox 侧动作。
    expect(items[2].actions).toBeNull();
  });

  it('holds local sends as waiting while disconnected, including unfinished uploads, but keeps failures', () => {
    const [ready, uploading, failed, handed] = build({
      outboxWaitingFor: 'computer',
      outbox: [
        outboxItem('ready'),
        outboxItem('uploading', { attachmentCount: 1, uploadedCount: 0, thumbnails: [{ key: 'uploading-slot-0', uri: 'file:///a.jpg', ossRef: null, uploading: true }] }),
        outboxItem('failed', { failed: true }),
        outboxItem('handed', { dispatching: true, sentAt: 1_700_000_000_000 }),
      ],
    });
    expect(ready).toMatchObject({ phase: 'waiting', waitingFor: 'computer' });
    expect(isPendingSendItemSelected(ready, 'ready')).toBe(true);
    // 断开时附件上传也停着:写等待,图片不转圈。
    expect(uploading).toMatchObject({ phase: 'waiting', waitingFor: 'computer' });
    expect(uploading.thumbs.every((thumb) => !thumb.uploading)).toBe(true);
    expect(failed.phase).toBe('failed');
    // 已交给电脑的条目在等对账,不是在等着发。
    expect(handed.phase).toBe('sending');
    // 发件箱的发送时刻带进气泡,伙伴对话按它分组。
    expect(handed.sentAt).toBe(1_700_000_000_000);
    expect(build({ outbox: [outboxItem('ready')] })[0].phase).toBe('sending');
  });

  it('keeps a first-message creation row non-interactive until creation recovery is available', () => {
    const [item] = build({ outbox: [outboxItem('first', { canCancel: false })] });
    expect(item.canCancel).toBe(false);
    expect(isPendingSendItemSelected(item, 'first')).toBe(false);
  });

  it('never exposes queue actions for items that left the queue', () => {
    const [settling] = build({ settling: [queued('gone')] });
    expect(settling.actions).toBeNull();
    expect(settling.queueIndex).toBeNull();
  });

  it('keeps queue atom metadata for the optimistic chip renderer', () => {
    const quote = formatQuoteForSend({ text: 'quoted context' });
    const text = `${quote}\n\n/help\n\nfull pasted payload`;
    const slashStart = text.indexOf('/help');
    const pastedStart = text.indexOf('full pasted payload');
    const queuedItem = queued('atoms', text);
    queuedItem.chatMessage.quotesEncoded = true;
    queuedItem.chatMessage.slashCommandRanges = [{ start: slashStart, end: slashStart + 5 }];
    queuedItem.chatMessage.pastedTextRanges = [{
      start: pastedStart,
      end: text.length,
      display: 'Pasted text (1 line)',
    }];

    const [item] = build({ queue: [queuedItem] });
    expect(item.sentInlineTokens.map((token) => token.kind)).toEqual([
      'quote',
      'slash',
      'text',
      'pasted',
    ]);
  });

  it('keeps outbox atom metadata while attachments are still uploading', () => {
    const text = '/help full pasted payload';
    const outbox = outboxItem('outbox-atoms', {
      text,
      quotesEncoded: false,
      slashCommandRanges: [{ start: 0, end: 5 }],
      pastedTextRanges: [{ start: 6, end: text.length, display: 'Pasted text (1 line)' }],
      attachmentCount: 1,
      uploadedCount: 0,
    });

    const [item] = build({ outbox: [outbox] });
    expect(item.phase).toBe('uploading');
    expect(item.sentInlineTokens.map((token) => token.kind)).toEqual(['slash', 'text', 'pasted']);
  });
});

describe('pending_send 渲染接线', () => {
  it('changes the list refresh signal and exposes queue actions when a bubble is selected', () => {
    const [item] = build({
      queue: [queued('selected')],
      presentationByClientId: new Map([['selected', {
        actions: {
          moveUp: { disabled: true, disabledReason: null, targetIndex: null },
          moveDown: { disabled: true, disabledReason: null, targetIndex: null },
          remove: { disabled: false, disabledReason: null },
          edit: { disabled: false, disabledReason: null },
          steer: { disabled: false, disabledReason: null },
        },
        hint: null,
      }]]),
    });
    const collapsed = buildMobileMessageListExtraData(null, false);
    const expanded = buildMobileMessageListExtraData(item.clientId, false);

    expect(expanded).not.toEqual(collapsed);
    expect(isPendingSendItemSelected(item, collapsed.pendingSendSelectedClientId)).toBe(false);
    expect(isPendingSendItemSelected(item, expanded.pendingSendSelectedClientId)).toBe(true);
  });


});

  it('preserves pending send actions through the production renderer memo', () => {
    const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
    const tree = ts.createSourceFile('renderer.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
    let callback: ts.Expression | undefined;
    function visit(node: ts.Node) {
      if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'actions' && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];
      ts.forEachChild(node, visit);
    }
    visit(tree);
    if (!callback) throw new Error('Missing renderer actions memo');
    const identifiers = new Set<string>();
    function readNames(node: ts.Node) {
      if (ts.isShorthandPropertyAssignment(node)) identifiers.add(node.name.text);
      if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.initializer)) identifiers.add(node.initializer.text);
      ts.forEachChild(node, readNames);
    }
    readNames(callback);
    const pendingSend = { onSelect: vi.fn(), onRemove: vi.fn(), onSendNow: vi.fn() };
    const bindings: Record<string, unknown> = Object.fromEntries([...identifiers].map((name) => [name, undefined]));
    Object.assign(bindings, { pendingSend, viewportLayout: { contentWidth: 390 } });
    const compiled = ts.transpileModule('const project = ' + callback.getText(tree) + ';', { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
    const actions = new Function(...Object.keys(bindings), compiled + '\nreturn project();')(...Object.values(bindings));
    expect(actions.pendingSend).toBe(pendingSend);
    actions.pendingSend.onSelect('queued');
    expect(pendingSend.onSelect).toHaveBeenCalledWith('queued');
  });

describe('pendingSendSpins', () => {
  it('spins only while the message has not been confirmed as queued', () => {
    expect(pendingSendSpins('sending')).toBe(true);
    expect(pendingSendSpins('settling')).toBe(true);
    expect(pendingSendSpins('uploading')).toBe(true);
    expect(pendingSendSpins('queued')).toBe(false);
    expect(pendingSendSpins('editing')).toBe(false);
    expect(pendingSendSpins('failed')).toBe(false);
  });
});

describe('pending bubbles for inputs sent by another task', () => {
  it('show the persisted visible body, not the agent-facing teammate prefix', () => {
    const interjection = {
      ...queued('interject', '[来自 Cindy 的补充]\n\nplease review'),
      persistedContent: 'please review',
      origin: { kind: 'session', senderSessionId: 'bot-task', displayText: '[来自 Cindy 的补充]\n\nplease review' },
    } as QueuedRemoteMessage;
    const [queuedBubble] = build({ queue: [interjection] });
    const [settlingBubble] = build({ settling: [interjection] });
    expect(queuedBubble.text).toBe('please review');
    expect(settlingBubble.text).toBe('please review');
    expect(JSON.stringify(queuedBubble.sentInlineTokens)).not.toContain('来自 Cindy');
  });

  it('keeps ordinary composer items on their own text', () => {
    const [bubble] = build({ queue: [queued('plain', 'hello')] });
    expect(bubble.text).toBe('hello');
  });
});

describe('pending bubble source labels', () => {
  let previousLanguage = 'en';
  beforeAll(async () => {
    previousLanguage = i18n.language;
    await i18n.changeLanguage('zh-CN');
  });
  afterAll(async () => {
    await i18n.changeLanguage(previousLanguage);
  });

  const withOrigin = (clientId: string, origin: Record<string, unknown>, text = 'body', persisted = text) => ({
    ...queued(clientId, text),
    persistedContent: persisted,
    origin,
  }) as QueuedRemoteMessage;

  it('labels automation, task, teammate, Orca and plugin rows like the desktop queue panel', () => {
    const items = build({
      queue: [
        withOrigin('auto', { kind: 'scheduler', scheduleId: 'sch-1', scheduleName: 'PR 心跳' }),
        withOrigin('auto-redacted', { kind: 'scheduler' }),
        // Hook 渠道消息复用 scheduler 形态:不是自动化,与历史消息一致不出自动化标签。
        withOrigin('hook', { kind: 'scheduler', scheduleId: 'hook:conn-1', scheduleName: 'Hook · Team Slack' }),
        withOrigin('task', { kind: 'session', senderSessionId: 's1', senderSessionTitle: '发布清单', displayText: 'body' }),
        withOrigin('task-redacted', { kind: 'session', senderSessionId: '', displayText: 'body' }),
        withOrigin('mate', { kind: 'session', senderSessionId: 's2', senderBotId: 'b1', senderBotName: 'Cindy', displayText: 'body' }),
        withOrigin('lead', { kind: 'orca', senderLabel: 'Lead', displayText: '先跑测试' },
          '[From Orca Lead] 先跑测试', '{"orcaSource":"lead","content":"先跑测试"}'),
        withOrigin('worker', { kind: 'orca', senderLabel: 'frontend' },
          '[From Orca Worker frontend] 完成', '{"orcaSource":"worker","content":"完成"}'),
        { ...queued('plugin'), sourcePlugin: { pluginId: 'pl-1', name: '日报' } } as QueuedRemoteMessage,
        queued('mine', 'hello'),
      ],
    });
    expect(items.map((item) => [item.clientId, item.source?.kind ?? null, item.source?.label ?? null])).toEqual([
      ['auto', 'automation', '由自动化「PR 心跳」发送'],
      ['auto-redacted', 'automation', '由自动化发送'],
      ['hook', null, null],
      ['task', 'session', '由任务「发布清单」发送'],
      ['task-redacted', 'session', '由其他任务发送'],
      ['mate', 'teammate', '由伙伴「Cindy」发送'],
      ['lead', 'orca', '来自 Lead 的消息'],
      ['worker', 'orca', '来自 Worker「frontend」的消息'],
      ['plugin', 'plugin', '由插件「日报」发送'],
      ['mine', null, null],
    ]);
    // 来源 ID 随标签保留(长按显示);脱敏来源与 Orca 没有。
    expect(Object.fromEntries(items.map((item) => [item.clientId, item.source?.idText ?? null]))).toMatchObject({
      auto: '自动化 ID:sch-1',
      'auto-redacted': null,
      task: '任务 ID:s1',
      'task-redacted': null,
      // 伙伴来源与模型说明一致:伙伴 ID + 来源任务 ID。
      mate: '伙伴 ID:b1\n任务 ID:s2',
      plugin: '插件 ID:pl-1',
      mine: null,
    });
    // Orca 条目显示正文,不显示发给 Agent 的前缀或落库 JSON。
    expect(items.find((item) => item.clientId === 'lead')?.text).toBe('先跑测试');
    expect(items.find((item) => item.clientId === 'worker')?.text).toBe('完成');
    for (const item of items) expect(item.text).not.toMatch(/orcaSource|\[From Orca/);
  });

  it('never shows the stored text of synthetic UI-action rows, only a label', () => {
    const hidden = `${UI_ACTION_TRIGGER_PREFIX} regenerate image 42`;
    const items = build({
      queue: [
        queued('synthetic', hidden),
        // 发给 Agent 的 text 带前缀、落库正文不带:仍按 text 判定为合成指令。
        withOrigin('synthetic-auto', { kind: 'scheduler', scheduleId: 'sch-1', scheduleName: '巡检' }, hidden, 'regenerate image 42'),
        queued('continue', CONTINUE_AFTER_ERROR_PROMPT),
      ],
    });
    expect(items.map((item) => item.text)).toEqual(['系统指令', '系统指令', '继续未完成的任务(系统指令)']);
    for (const item of items) {
      expect(item.sentInlineTokens).toEqual([]);
      expect(JSON.stringify(item)).not.toContain('regenerate image 42');
    }
    expect(items[1].source?.label).toBe('由自动化「巡检」发送');
  });

  it('keeps local outbox rows unlabeled', () => {
    const [bubble] = build({ outbox: [outboxItem('o1')] });
    expect(bubble.source).toBeNull();
  });
});


// Unit regression: remote pending bubble used to expose transport escapes. The
// original queue item is retained for sending; a human draft is not decoded.
it('decodes only attributed forwarded pending bubbles', () => {
  const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n第二段"';
  const item = { ...queued('forwarded', content), origin: { kind: 'session' as const, senderSessionId: 'sender' } };
  expect(pendingSendBubbleText(item)).toContain('第一段\n第二段');
  expect(item.persistedContent).toBe(content);
  expect(pendingSendBubbleText(queued('human', content))).toBe(content);
});