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。

20.4 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import { buildMessageRenderItems } from '@cindy/maker-shared/message-render';
import { CONTINUE_AFTER_ERROR_PROMPT } from '@cindy/maker-shared/synthetic-trigger';
import { normalizeRemoteMessages } from '@/session/messageNormalize';
import {
  buildMobileMessageRenderItems,
  markTurnFinalAssistants,
  scopeUnsettledToolsToActiveTail,
  type MobileMessageRenderItem,
  type MobileSubagentGroupItem,
} from '@/session/messageRenderModel';
import type { RemoteMessage } from '@/session/types';

let seq = 0;
function msg(patch: Partial<RemoteMessage> & Pick<RemoteMessage, 'role' | 'content'>): RemoteMessage {
  seq += 1;
  const id = patch.id ?? `m${seq}`;
  return {
    id,
    clientId: id,
    sessionId: 's1',
    toolUseId: null,
    agentMeta: null,
    createdAt: patch.createdAt ?? `2026-01-01T00:00:${String(seq).padStart(2, '0')}.000Z`,
    ...patch,
  };
}

function agentToolUse(toolUseId: string, opts: { description?: string; subagentType?: string; parentUuid?: string; createdAt?: string } = {}): RemoteMessage {
  return msg({
    role: 'tool_use',
    content: { toolUseId, toolName: 'Agent', input: { description: opts.description, subagent_type: opts.subagentType } },
    toolUseId,
    agentMeta: opts.parentUuid ? { parentUuid: opts.parentUuid } : null,
    createdAt: opts.createdAt,
  });
}

function childTool(toolName: string, parentUuid: string, createdAt?: string): RemoteMessage {
  const toolUseId = `t-${seq + 1}`;
  return msg({
    role: 'tool_use',
    content: { toolUseId, toolName, input: {} },
    toolUseId,
    agentMeta: { parentUuid },
    createdAt,
  });
}

function agentResult(toolUseId: string, content: string, createdAt?: string): RemoteMessage {
  return msg({ role: 'tool_result', content, toolUseId, createdAt });
}

/** 显式 id / toolUseId 的 tool_result:模拟邻接的、非子任务自己的工具结果。 */
function toolResult(id: string, toolUseId: string, content: string, createdAt?: string): RemoteMessage {
  return msg({ id, role: 'tool_result', content, toolUseId, createdAt });
}

function subagentGroups(items: readonly MobileMessageRenderItem[]): MobileSubagentGroupItem[] {
  return items.filter((item): item is MobileSubagentGroupItem => item.type === 'subagent_group');
}

// 递归收集输出里所有 render item 携带的 source 消息 id(用于"恰好出现一次"不变量检查)。
function collectSourceIds(items: readonly MobileMessageRenderItem[]): string[] {
  const ids: string[] = [];
  const walk = (list: readonly MobileMessageRenderItem[]) => {
    for (const item of list) {
      if (item.type === 'message' || item.type === 'thinking') ids.push(item.message.source.id);
      else if (item.type === 'tool_group') item.tools.forEach((tool) => ids.push(tool.source.id));
      else if (item.type === 'work_group') walk(item.children as MobileMessageRenderItem[]);
      else if (item.type === 'subagent_group') walk(item.childItems);
    }
  };
  walk(items);
  return ids;
}

describe('subagent grouping (buildMobileMessageRenderItems)', () => {
  it.each([
    { streaming: false, autoResume: false },
    { streaming: true, autoResume: false },
    { streaming: false, autoResume: true },
    { streaming: true, autoResume: true },
  ])('folds progress across Agent segments on recovery (%j)', ({ streaming, autoResume }) => {
    seq = 0;
    const messages = [
      msg({ id: 'u', role: 'user', content: 'go' }),
      msg({ id: 'progress', role: 'assistant', content: 'Starting research' }),
      agentToolUse('A1'),
      msg({ id: 'between', role: 'assistant', content: 'Checking another source', agentMeta: { turnCompleted: true } }),
      agentToolUse('A2'),
      msg({ id: 'error', role: 'error', content: 'Interrupted' }),
      msg({ id: 'resume', role: 'user', content: CONTINUE_AFTER_ERROR_PROMPT, agentMeta: autoResume ? { autoResume: true } : null }),
      msg({ id: 'active', role: 'assistant', content: 'Continuing' }),
    ].map((message, index) => ({ ...message, createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString() }));
    const items = buildMobileMessageRenderItems(messages, { isSessionStreaming: streaming });
    expect(items.map(item => item.type)).toEqual([
      'message', 'work_group', 'subagent_group', 'work_group', 'subagent_group', 'message', 'message',
      ...(autoResume ? ['message'] : []),
    ]);
    for (const [index, id] of [[1, 'progress'], [3, 'between']] as const) {
      const item = items[index];
      expect(item.type).toBe('work_group');
      if (item.type !== 'work_group') throw new Error('Expected folded progress');
      expect(item.isStreaming).toBe(false);
      expect(collectSourceIds(item.children)).toEqual([id]);
    }
    expect(collectSourceIds(items)).toEqual(['u', 'progress', 'between', 'error', ...(autoResume ? ['resume'] : []), 'active']);

    const steer = msg({ id: 'steer', role: 'user', content: 'Check this too', agentMeta: { delivery: 'steer' }, createdAt: '2026-01-01T00:00:02.500Z' });
    const withSteer = [...messages.slice(0, 3), steer, ...messages.slice(3)];
    const steered = buildMobileMessageRenderItems(withSteer, { isSessionStreaming: streaming });
    expect(steered.map(item => item.type)).toEqual([
      'message', 'work_group', 'subagent_group', 'message', 'work_group', 'subagent_group', 'message',
      ...(autoResume ? ['message'] : []), 'message',
    ]);
    expect(collectSourceIds(steered)).toEqual(['u', 'progress', 'steer', 'between', 'error', ...(autoResume ? ['resume'] : []), 'active']);

    // A borrowed recovery must not reach an earlier disconnected history window.
    const gapped = messages.map((message, index) => index < 2 ? message : {
      ...message, createdAt: new Date(Date.parse(message.createdAt!) + 48 * 60 * 60_000).toISOString(),
    });
    const afterGap = buildMobileMessageRenderItems(gapped, { isSessionStreaming: streaming });
    expect(afterGap[1].type).toBe('message');
    expect(afterGap[3].type).toBe('work_group');
    expect(collectSourceIds(afterGap)).toEqual(collectSourceIds(items));

    // A real user turn blocks recovery from affecting earlier Agent segments.
    const ordinaryBoundary = msg({ id: 'other', role: 'user', content: 'Another request', createdAt: '2026-01-01T00:00:02.500Z' });
    messages.splice(3, 0, ordinaryBoundary);
    const separated = buildMobileMessageRenderItems(messages, { isSessionStreaming: streaming });
    expect(separated[1].type).toBe('message');
    expect(collectSourceIds(separated).filter(id => id === 'progress')).toEqual(['progress']);
  });

  it.each([1, 2, 7])('preserves history paragraph order through %s nesting levels and fallback', (depth) => {
    const parents = Array.from({ length: depth }, (_, index) => agentToolUse(`order-A${index}`, {
      parentUuid: index === 0 ? undefined : `order-A${index - 1}`,
      createdAt: `2026-01-01T00:00:0${index}.000Z`,
    }));
    const paragraphs = ['first', 'second', 'third'].map((id, index) => msg({
      id, role: 'assistant', content: id,
      agentMeta: { parentUuid: `order-A${depth === 7 && index === 1 ? 5 : depth - 1}`, isStreaming: index > 0 },
      createdAt: `2026-01-01T00:00:${30 - index}.000Z`,
    }));
    const messages = [...parents, ...paragraphs];
    const original = structuredClone(messages);
    const paragraphIds = (preserveSourceOrder: boolean) => collectSourceIds(buildMobileMessageRenderItems(
      messages, { preserveSourceOrder, isSessionStreaming: true },
    )).filter(id => paragraphs.some(message => message.id === id));
    expect(paragraphIds(true)).toEqual(['first', 'second', 'third']);
    expect(paragraphIds(false)).toEqual(['third', 'second', 'first']);
    expect(messages).toEqual(original);
  });

  it('replaces a top-level Agent tool_use with a subagent_group nesting its children', () => {
    const items = buildMobileMessageRenderItems([
      msg({ id: 'u', role: 'user', content: { text: 'go' }, createdAt: '2026-01-01T00:00:01.000Z' }),
      agentToolUse('A1', { description: '调研', subagentType: 'Explore', createdAt: '2026-01-01T00:00:02.000Z' }),
      childTool('Bash', 'A1', '2026-01-01T00:00:03.000Z'),
      childTool('Read', 'A1', '2026-01-01T00:00:04.000Z'),
      agentResult('A1', '调研完成,结论 X', '2026-01-01T00:00:05.000Z'),
    ]);

    const groups = subagentGroups(items);
    expect(groups).toHaveLength(1);
    const g = groups[0];
    expect(g.header).toEqual({ description: '调研', subagentType: 'Explore' });
    expect(g.summary).toBe('调研完成,结论 X');
    expect(g.status).toBe('completed');
    expect(g.durationMs).toBe(3000); // 00:05 - 00:02
    // children(2 个 tool)被归一化/折叠进 childItems(tool_group),不在顶层平铺。
    expect(g.childItems.length).toBeGreaterThan(0);
    // 顶层没有裸的 Agent tool_group 行。
    const topToolGroups = items.filter((i) => i.type === 'tool_group');
    expect(topToolGroups).toHaveLength(0);
  });

  it('recurses for nested sub-agents (2 levels)', () => {
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'general-purpose', createdAt: '2026-01-01T00:00:01.000Z' }),
      agentToolUse('A2', { subagentType: 'Explore', parentUuid: 'A1', createdAt: '2026-01-01T00:00:02.000Z' }),
      childTool('Bash', 'A2', '2026-01-01T00:00:03.000Z'),
      agentResult('A2', 'inner done', '2026-01-01T00:00:04.000Z'),
      agentResult('A1', 'outer done', '2026-01-01T00:00:05.000Z'),
    ]);
    const groups = subagentGroups(items);
    expect(groups).toHaveLength(1);
    const inner = subagentGroups(groups[0].childItems);
    expect(inner).toHaveLength(1);
    expect(inner[0].header.subagentType).toBe('Explore');
    expect(inner[0].summary).toBe('inner done');
  });

  it('keeps parallel/interleaved agents separated by parentUuid, not by time order', () => {
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'one', createdAt: '2026-01-01T00:00:01.000Z' }),
      agentToolUse('A2', { subagentType: 'two', createdAt: '2026-01-01T00:00:02.000Z' }),
      childTool('Bash', 'A2', '2026-01-01T00:00:03.000Z'), // A2 的 child 时间上夹在 A1/A2 之间
      childTool('Read', 'A1', '2026-01-01T00:00:04.000Z'),
      agentResult('A1', 'a1 done', '2026-01-01T00:00:05.000Z'),
      agentResult('A2', 'a2 done', '2026-01-01T00:00:06.000Z'),
    ]);
    const groups = subagentGroups(items);
    expect(groups.map((g) => g.header.subagentType)).toEqual(['one', 'two']);
    expect(groups[0].childItems.length).toBeGreaterThan(0); // A1 got its Read child
    expect(groups[1].childItems.length).toBeGreaterThan(0); // A2 got its Bash child
  });

  it('handles an empty sub-agent (no children) without crashing', () => {
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
      agentResult('A1', 'nothing to do', '2026-01-01T00:00:02.000Z'),
    ]);
    const groups = subagentGroups(items);
    expect(groups).toHaveLength(1);
    expect(groups[0].childItems).toEqual([]);
    expect(groups[0].status).toBe('completed');
  });

  it('历史 Agent 缺 toolUseId 时,从已配对的 secondaryBody 恢复 failed 终态', () => {
    // buildSubagentResultMeta 对无 toolUseId 的结果没有条目;归一化层经 adjacency
    // 把 tool_result 配对进 secondaryBody。若这里不读 secondaryBody,重连后同一失败
    // 会被显示成 completed(streaming 时为 running)而不是承诺的 failed。
    const items = buildMobileMessageRenderItems([
      msg({
        id: 'legacy-agent',
        role: 'tool_use',
        content: { toolUseId: null, toolName: 'Agent', input: { description: 'legacy' } },
        toolUseId: null,
        createdAt: '2026-01-01T00:00:01.000Z',
      }),
      msg({
        id: 'legacy-result',
        role: 'tool_result',
        content: '<tool_use_error>legacy boom</tool_use_error>',
        toolUseId: null,
        createdAt: '2026-01-01T00:00:02.000Z',
      }),
    ]);
    const groups = subagentGroups(items);
    expect(groups).toHaveLength(1);
    expect(groups[0].status).toBe('failed');
  });

  it('带 toolUseId 的在跑 Agent 即使有邻接 secondaryBody 也不提前收口', () => {
    // 带 ID 的 Agent 尚无自身 result,归一化层可能把下一行其他工具的 result 经
    // adjacency 临时借进 secondaryBody —— 该借用非权威,不得让任务提前 completed/
    // failed(尤其邻接文本以 <tool_use_error> 开头时不能误判 failed)。
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
      childTool('Bash', 'A1', '2026-01-01T00:00:02.000Z'),
      toolResult('other-1', 'tu-other', '<tool_use_error>not the agent result</tool_use_error>'),
    ], { isSessionStreaming: true });
    const groups = subagentGroups(items);
    expect(groups).toHaveLength(1);
    expect(groups[0].status).toBe('running');
  });

  it('marks status running when no closing tool_result and session is streaming', () => {
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
      childTool('Bash', 'A1', '2026-01-01T00:00:02.000Z'),
    ], { isSessionStreaming: true });
    expect(subagentGroups(items)[0].status).toBe('running');
  });

  it('stays completed even when the summary text mentions error/失败 (no keyword false-positive)', () => {
    // 回归:code-review/research 类子 agent 的总结天然讨论 "error/失败/exception",此前关键词扫正文
    // 会把成功完成误判成失败。缺少结构化终态的旧历史仍只按 closing tool_result 判 completed。
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'general-purpose', createdAt: '2026-01-01T00:00:01.000Z' }),
      agentResult(
        'A1',
        '审查完成:发现 3 处 error handling 缺陷与一个会抛 exception 的失败分支,均已修复。',
        '2026-01-01T00:00:02.000Z',
      ),
    ]);
    const group = subagentGroups(items)[0];
    expect(group.status).toBe('completed');
    expect(group.status).not.toBe('failed');
  });

  it.each(['failed', 'stopped'] as const)(
    'uses the persisted %s terminal state for a nested Agent group',
    (status) => {
      const items = buildMobileMessageRenderItems([
        msg({
          id: 'agent',
          role: 'tool_use',
          toolUseId: 'toolu-agent',
          content: { toolUseId: 'toolu-agent', toolName: 'Agent', input: { description: 'Review' } },
          agentMeta: { agentTaskStatus: status },
        }),
        msg({
          id: 'result',
          role: 'tool_result',
          toolUseId: 'toolu-agent',
          content: 'finished with a terminal outcome',
        }),
      ]);

      expect(subagentGroups(items)[0].status).toBe(status);
    },
  );

  it('restores failed for a replayed protocol error result (<tool_use_error>)', () => {
    // 回归(#3024):Mobile 重连/历史回放只有配对的 `<tool_use_error>` 结果、无 agentTaskStatus 时,
    // subagent_group 曾只凭"存在 result"判 completed,同一启动失败在 Desktop 显示 failed、Mobile 显示
    // completed(跨端终态不一致)。现与 Desktop deriveAgentTaskStatus 同口径恢复 failed。
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
      agentResult('A1', '<tool_use_error>Agent launch failed: model unavailable</tool_use_error>', '2026-01-01T00:00:02.000Z'),
    ]);
    const group = subagentGroups(items)[0];
    expect(group.status).toBe('failed');
  });

  it('keeps completed when only a nested block array result mentions tool_use_error mid-text (prefix match only)', () => {
    // 防误报:只有以 `<tool_use_error>` 开头才是协议错误;正文中段出现不算(block 数组形态)。
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:01.000Z' }),
      msg({
        role: 'tool_result',
        toolUseId: 'A1',
        createdAt: '2026-01-01T00:00:02.000Z',
        content: [{ type: 'text', text: '总结:<tool_use_error> 是 SDK 的错误标记格式,本次任务已完整解析并修复它。' }],
      }),
    ]);
    expect(subagentGroups(items)[0].status).toBe('completed');
  });

  it('still prefers the persisted terminal status over the protocol error fallback', () => {
    // persisted agentTaskStatus 优先级不变:即使结果以 <tool_use_error> 开头,
    // 已持久化的终态(如 failed→重试后 succeeded 场景的 stopped)不被覆盖。
    const items = buildMobileMessageRenderItems([
      msg({
        id: 'agent',
        role: 'tool_use',
        toolUseId: 'toolu-agent',
        content: { toolUseId: 'toolu-agent', toolName: 'Agent', input: { description: 'Retry' } },
        agentMeta: { agentTaskStatus: 'stopped' },
      }),
      msg({
        id: 'result',
        role: 'tool_result',
        toolUseId: 'toolu-agent',
        content: '<tool_use_error>stale error from earlier attempt</tool_use_error>',
      }),
    ]);
    expect(subagentGroups(items)[0].status).toBe('stopped');
  });

  it('leaves an ordinary session (no Agent / no parentUuid) byte-identical to the shared builder', () => {
    const messages = [
      msg({ id: 'u', role: 'user', content: { text: 'hi' }, createdAt: '2026-01-01T00:00:01.000Z' }),
      msg({ id: 't', role: 'tool_use', content: { toolUseId: 'x', toolName: 'Read', input: {} }, toolUseId: 'x', createdAt: '2026-01-01T00:00:02.000Z' }),
      msg({ id: 'a', role: 'assistant', content: 'done', createdAt: '2026-01-01T00:00:03.000Z' }),
    ];
    // 对照侧同样做 mobile 后处理(buildMobileMessageRenderItems 内置这些步骤),其余逐字节一致。
    const reference = normalizeRemoteMessages(messages);
    scopeUnsettledToolsToActiveTail(reference);
    markTurnFinalAssistants(reference, false);
    expect(buildMobileMessageRenderItems(messages)).toEqual(
      buildMessageRenderItems(reference),
    );
    expect(subagentGroups(buildMobileMessageRenderItems(messages))).toHaveLength(0);
  });

  it('terminates and bounds nesting when the parent chain exceeds the depth cap', () => {
    // 构造 7 层链 A0←A1←…←A6,远超 MAX_SUBAGENT_NEST_DEPTH(5),确保不爆栈、不无限建组。
    const rows: RemoteMessage[] = [];
    for (let i = 0; i <= 6; i += 1) {
      rows.push(agentToolUse(`A${i}`, {
        subagentType: `lv${i}`,
        parentUuid: i === 0 ? undefined : `A${i - 1}`,
        createdAt: `2026-01-01T00:01:0${i}.000Z`,
      }));
    }
    let items: MobileMessageRenderItem[] = [];
    expect(() => { items = buildMobileMessageRenderItems(rows); }).not.toThrow();
    // 顶层只有 1 个 group(A0),逐层下钻深度有限。
    expect(subagentGroups(items)).toHaveLength(1);
    let depth = 0;
    let cursor = subagentGroups(items);
    while (cursor.length > 0) {
      depth += 1;
      cursor = subagentGroups(cursor[0].childItems);
      if (depth > 10) break; // 安全阀:若无限会在此断开并让断言失败
    }
    expect(depth).toBeLessThanOrEqual(5);
  });

  it('flat-renders orphan children whose parent Agent is outside the window (F1: no silent drop)', () => {
    // 复现分页窗口劈开子 agent 块:父 Agent 落窗外、children 在窗内,parentUuid 指向窗外父;窗内另有真 Agent
    // (A1)使流程走 subagent-aware 路径。修复前这些 children 进不可达孤儿桶、整段消失;修复后回退 flat。
    const orphan1 = childTool('Read', 'AGENT_OUTSIDE_WINDOW', '2026-01-01T00:00:05.000Z');
    const orphan2 = childTool('Grep', 'AGENT_OUTSIDE_WINDOW', '2026-01-01T00:00:06.000Z');
    const inWindowChild = childTool('Bash', 'A1', '2026-01-01T00:00:03.000Z');
    const items = buildMobileMessageRenderItems([
      agentToolUse('A1', { subagentType: 'Explore', createdAt: '2026-01-01T00:00:02.000Z' }),
      inWindowChild,
      agentResult('A1', 'done', '2026-01-01T00:00:04.000Z'),
      orphan1,
      orphan2,
    ]);

    const collected = collectSourceIds(items);
    // 孤儿(父在窗外)仍出现在输出 —— 直接锁死 F1。
    expect(collected).toContain(orphan1.id);
    expect(collected).toContain(orphan2.id);
    // 窗内子 agent 的 child 仍正常嵌套。
    expect(collected).toContain(inWindowChild.id);
    // 恰好出现一次:无重复(A1 自身被并入 group header,不计为 source 行)。
    expect(new Set(collected).size).toBe(collected.length);
    expect(collected).toHaveLength(3);
    expect(subagentGroups(items)).toHaveLength(1);
  });
});