| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 |
- import { FileCard, Message } from './api/models';
- import { GroupTurn } from './group-turns';
- import { mergeConsecutiveBodies, MergedMessage } from './message-merge';
- import { isToolActivityMessage, ProcessStep, splitMessage } from './message-segments';
- import { Turn } from './turn-aggregator';
- /**
- * AI 输出的回合视图模型(2026-11-06 用户需求)
- *
- * ## 为什么要有这一层
- *
- * 用户要求「所有输出在一个固定区域内持续追加,顶部过程区可折叠,
- * 下半部分是正文与文档宫格」,并且**双端、单聊与群聊效果一致**。
- *
- * 但四个页面原本各写一套:桌面单聊是扁平流、桌面群聊是 turn → 容器块、
- * 移动两页又是一套。规则一旦分叉就会漂移(右栏预览就是前车之鉴)。
- *
- * 所以把「回合长什么样」收敛到这里:**纯函数,不依赖 Angular**,
- * 两端共用同一份数据,只在渲染层保留与端相关的样式差异。
- *
- * ## 单聊与群聊的统一
- *
- * - 群聊:一个回合有 N 个块(每个被 @ 的容器一块)
- * - 单聊:同样用块表达,但**固定只有 1 块**(`agentId: null`)
- *
- * 这样上层模板只认 `blocks[]`,不必区分单聊群聊。
- *
- * ## 顶部过程区从哪来
- *
- * 容器的回复把「过程行」和「正文」混在**同一条消息文本**里:
- *
- * ```
- * 我先看一下环境。
- * · bash
- * 找到了,正在改。
- * ```
- *
- * 两步取过程:
- * ① 纯终端消息(整条都是 `· bash` 这类)→ 整条进过程区
- * ② 混在正文里的过程行 → 由 `splitMessage` 拆出来
- *
- * 判定全部复用 `message-segments.ts` 的既有口径,**不在本文件新造正则**。
- */
- /** 下半区的内容块(顶部过程区已单独抽出,不在此列) */
- export type TurnBodyBlock =
- | { kind: 'text'; key: string; message: MergedMessage }
- | { kind: 'file'; key: string; file: FileCard; message: Message }
- | { kind: 'task'; key: string; taskId: string; message: Message };
- /** 一个「说话方」在回合内的呈现数据 */
- export interface TurnBlockView {
- key: string;
- /** 单聊为 null;群聊为容器 id */
- agentId: string | null;
- /** 群聊成员显示名(由宿主传入 `nameOf` 时才有) */
- agentName?: string;
- /**
- * 容器真实处理耗时(秒):首条 → 末条 agent 消息。
- *
- * 🔴 UI **不再直接读取**它(读数走 `elapsedSeconds()`),仅保留作数据/诊断用,
- * 以及 `updatedAt <= startAt` 这种退化情形下的兜底。
- */
- seconds: number;
- /**
- * 本块开始时刻(epoch ms;0 = 无锚点)。
- *
- * 2026-11-10 新增:秒数改为**逐秒现算**,锚点必须是时刻而不是秒数,
- * 否则只能靠容器发新事件来「跳一下」。见 `elapsedSeconds()`。
- */
- startAt: number;
- /** 本块最后活动时刻(epoch ms,0 = 无消息)—— 结束态定格用 */
- updatedAt: number;
- /** 顶部过程区 */
- steps: ProcessStep[];
- /** 下半区正文 / 文件 / 任务 */
- body: TurnBodyBlock[];
- /** 文件宫格的数据(从 body 的 file 项抽出,便于模板直接栅格渲染) */
- files: { key: string; file: FileCard }[];
- /** 本块是否仍在输出 */
- live: boolean;
- /** 本块是否无内容且未在输出(群聊未响应) */
- empty: boolean;
- /**
- * 本块自身合并后的正文(2026-11-07)。
- *
- * 群聊多容器时,**每个容器单独渲染自己的正文**,不能跨容器拼接 ——
- * 用户要求「@ 了三个人就要看出谁说了什么」,拼在一起等于丢失归属。
- * 单聊只有一块,用回合级的 `merged` 即可。
- */
- merged: TurnMergedBody | null;
- /** 用户发出这条消息的时刻(毫秒)。0 = 无锚点(容器主动发言) */
- waitingSince: number;
- /**
- * 构建这一帧时,距用户发消息已经等了多久(毫秒)。
- *
- * 🔴 组件渲染用 `waitingSince` + 实时时钟现算,`waitMs` 只是构建快照,
- * 供纯函数与测试使用(2026-11-09)。
- */
- waitMs: number;
- }
- export type TurnPhase = 'thinking' | 'replying' | 'done' | 'failed' | 'idle' | 'progressOnly';
- /**
- * 整轮合并后的正文(2026-11-07 用户需求)。
- *
- * 用户要求「这一轮对话的所有输出融合到**一张卡片**里,不再是每段单独复制,
- * 顶部折叠思考和操作」。所以正文本不该按容器/消息分段,而应拼成一份。
- */
- export interface TurnMergedBody {
- /** 稳定 key(首条正文消息 id),用于模板 track */
- key: string;
- /** 合并后的正文(Markdown) */
- text: string;
- /** 参与合并的消息(末尾那条用于取时间戳、任务引用等元信息) */
- message: Message;
- }
- /** 一个完整回合:一条用户消息 + 它的全部回复 */
- export interface AssistantTurn {
- id: string;
- userMessage?: Message;
- /** 用户在同回合内额外发的文件(群聊「文字 + 多个文件」时) */
- userFiles: Message[];
- blocks: TurnBlockView[];
- phase: TurnPhase;
- /** 容器真实处理耗时(秒,诊断用;UI 读数走 `elapsedSeconds(blocks[i], now)`) */
- seconds: number;
- live: boolean;
- closed: boolean;
- /** 过程步骤总数,用于折叠头「运行了 N 步」 */
- stepCount: number;
- /** 文件总数,用于宫格标题 */
- fileCount: number;
- /**
- * 整轮合并后的正文与文件(2026-11-07)。
- *
- * 「一整轮 = 一张卡」:不管中间隔了多少次工具调用,正文全部拼成一份
- * 给卡片渲染,过程进顶部折叠区,文件进底部宫格。
- *
- * 🔴 **单聊用这个**。群聊多容器时各自独立,见 `blocks[].merged`。
- */
- merged: TurnMergedBody | null;
- /** 整轮的全部文件(跨容器聚合,宫格统一渲染) */
- files: { key: string; file: FileCard }[];
- }
- /** 构建一块所需的原料(由单聊/群聊两种输入各转一份) */
- interface BlockSource {
- agentId: string | null;
- messages: Message[];
- startedAt: number;
- updatedAt: number;
- typing: boolean;
- closed: boolean;
- }
- /* ------------------------------------------------------------------ */
- /* 从原始消息派生「过程」与「正文」 */
- /* ------------------------------------------------------------------ */
- /**
- * 把一组消息拆成「顶部过程步骤」与「下半区内容块」。
- *
- * 处理顺序很关键:
- * 1. 先按纯终端消息把整条消息**提走**进过程区(它不该出现在正文里)
- * 2. 剩下的正文消息交给 `mergeConsecutiveBodies` 合并连续片段
- * 3. 合并后再用 `splitMessage` 把夹在正文里的过程行拆出来
- *
- * 🔴 这里不能只认 `block.kind === 'process'`。
- * `toBlocks()` 有个既有设计:**孤立单步(前后无空行)会被内联成 text**
- * (`message-segments.ts:281-285`),为的是「只有一个步骤时不必多点一次」。
- * 但在本视图模型里,顶部过程区与下半区必须**严格互斥**,否则
- * 「过程区折叠了、正文里却还留着那一行」。
- * 所以这里按**行**再判一次:`· 工具名` 形态的行一律归过程区。
- */
- function splitIntoParts(messages: Message[]): {
- steps: ProcessStep[];
- body: TurnBodyBlock[];
- } {
- const steps: ProcessStep[] = [];
- const bodies: Message[] = [];
- for (const m of messages) {
- const text = m.text ?? '';
- // ① 整条都是终端活动 → 过程区,不进正文
- if (text && isToolActivityMessage(text) && !proseOf(text)) {
- steps.push(...stepsOf(text));
- continue;
- }
- if (text.trim()) bodies.push(m);
- }
- /*
- * ② 合并连续正文。
- * 带附件的消息由 `mergeConsecutiveBodies` 内部规则挡住(见 message-merge.ts 注释),
- * 它们不进 `bodies`,单独成块。
- */
- const merged = mergeConsecutiveBodies(bodies);
- const body: TurnBodyBlock[] = [];
- for (const mm of merged) {
- const { steps: s, text } = divideText(mm.text ?? '');
- steps.push(...s);
- if (text.trim()) {
- body.push({ kind: 'text', key: mm.mergedIds[0], message: { ...mm, text: text.trim() } });
- }
- if (mm.file) {
- body.push({ kind: 'file', key: `${mm.mergedIds[0]}-f`, file: mm.file, message: mm });
- }
- if (mm.taskId) {
- body.push({ kind: 'task', key: `${mm.mergedIds[0]}-t`, taskId: mm.taskId, message: mm });
- }
- }
- /*
- * ③ 只有附件、没有正文的消息不会被 `mergeConsecutiveBodies` 输出(它只处理 text),
- * 这里补回来,否则「容器只回了一个文件」会整个消失。
- */
- for (const m of messages) {
- if (!m.file && !m.taskId) continue;
- const covered = body.some((b) => b.message.id === m.id);
- if (covered) continue;
- if (m.file) body.push({ kind: 'file', key: `${m.id}-f`, file: m.file, message: m });
- if (m.taskId) body.push({ kind: 'task', key: `${m.id}-t`, taskId: m.taskId, message: m });
- }
- return { steps, body };
- }
- /**
- * 从一段文本里取过程行(返回 steps)。
- * 纯终端文本直接用 `splitMessage` 的 process 块。
- */
- function stepsOf(text: string): ProcessStep[] {
- const out: ProcessStep[] = [];
- for (const b of splitMessage(text)) {
- if (b.kind === 'process') out.push(...b.steps);
- }
- return out;
- }
- /**
- * 把一段**混合**文本拆成「过程步骤」与「纯正文」。
- *
- * 两步:
- * ① `splitMessage` 能识别的 process 块 → 步骤
- * ② 剩下的 text 块里,仍可能有被 `toBlocks` 内联的单步行(`· bash`),按行再剥一次
- *
- * 返回的 text 已不含过程行,顶部折叠后正文不会再出现一遍。
- */function divideText(text: string): { steps: ProcessStep[]; text: string } {
- const steps: ProcessStep[] = [];
- const keep: string[] = [];
- for (const b of splitMessage(text)) {
- if (b.kind === 'process') {
- /*
- * 🔴 `splitMessage` 也会把「行首 emoji + 成句中文」解析成 process 块
- * (`💾 自我升级小结:…了。` 实测如此)。这类是**结论**不是过程,
- * 交还正文,否则折叠区里会出现半句话。
- */
- const prose = b.steps.filter((s) => proseOf(s.label));
- const tools = b.steps.filter((s) => !proseOf(s.label));
- steps.push(...tools);
- for (const p of prose) keep.push(p.label);
- continue;
- }
- if (b.kind !== 'text') continue;
- for (const line of b.text.split('\n')) {
- const inline = inlineStepOf(line);
- if (inline && !proseOf(line)) steps.push(inline);
- else keep.push(line);
- }
- }
- return { steps, text: keep.join('\n').replace(/\n{3,}/g, '\n\n') };
- }
- /** 行首 `· 工具名` 形态 → 一步;否则 null */
- const INLINE_STEP = /^\s*[·•]\s*([a-zA-Z][\w.\-]{0,40})(?:\s*[::]?\s*(.+))?$/;
- function inlineStepOf(line: string): ProcessStep | null {
- const m = INLINE_STEP.exec(line);
- if (!m) return null;
- return { kind: 'tool', label: m[1], detail: m[2]?.trim() || undefined };
- }
- /**
- * 这条「看起来像终端活动」的文本,其实是一句**结论性叙述**吗?
- *
- * ## 为什么需要(2026-11-07 实测)
- *
- * 容器会这样汇报一次自我升级:
- *
- * ```
- * 💾 自我升级小结:🔧 「multi-artifact-delivery」磨得更锋利了。
- * ```
- *
- * 行首 `💾` 命中了 `TOOL_EMOJI_LEAD`,于是整条被当成工具活动,
- * 折叠头上显示成「运行了 1 步 · 自我升级小结:…」——
- * 用户要读的**结论**被折进了过程区。
- *
- * ## 判定口径(宁可放过、不可误折)
- *
- * 同时满足才算叙述:
- * ① 以中文句末标点收尾(。!?)
- * ② 去掉行首 emoji 后,剩下的是一段**中文句子**(至少 6 个汉字)
- *
- * 真正的工具行(`💻 bash`、`✍️ Writing /path`)主体是英文工具名与路径,
- * 不含成句中文,不会被误判。
- */
- function proseOf(text: string): boolean {
- const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
- if (lines.length === 0) return false;
- // 只要有一条是「成句中文」,整条就当正文 —— 终端活动不会夹杂叙述
- return lines.some((line) => {
- if (!/[。!?]$/.test(line)) return false;
- // 剥掉行首的项目符号与 emoji(含变体选择符 / 零宽连接符)
- const body = line
- .replace(/^[\s*·•-]+/, '')
- .replace(/^[\p{Extended_Pictographic}️\u{1F3FB}-\u{1F3FF}]+\s*/u, '');
- return (body.match(/[一-龥]/g)?.length ?? 0) >= 6;
- });
- }
- /* ------------------------------------------------------------------ */
- /* 块 → 视图 */
- /* ------------------------------------------------------------------ */
- /**
- * 默认「还在输出」的静默窗口 —— 与 `turn-aggregator.QUIET_MS` 同源。
- *
- * 🔴 为什么不能用一个短窗口(2026-11-08 用户反馈「只闪一下『正在回复』就消失」):
- * 容器跑工具时,两段正文之间常有 5–20 秒空档。窗口短于一拍,
- * 回合就被判成「已结束」,界面的「正在思考…」随之消失 ——
- * 而容器其实还在干活,用户无从得知。
- *
- * 调用方应优先传 `QUIET_MS`;这里的字面量只是兜底,两处必须同步修改。
- */
- /**
- * 判定「超时」的时长门槛。
- *
- * 用户裁决(2026-11-10 第二次调整):**发出消息后 3 分钟内没有任何回复**才算异常。
- *
- * 演进:5 分钟太长(干等)→ 1 分钟太短(容器跑长任务时误报,用户实测被误判)
- * → 定为 3 分钟。容器正常回一轮 10~60 秒,但要跑任务时可能几分钟。
- *
- * ⚠️ 注意:这个值同时参与 `waitingTooLong`(超时后 `live` 转 false、占位消失)。
- * 改大意味着占位会多挂一段时间,这是有意的 —— 用户宁可看「正在思考」
- * 也不愿意 1 分钟就被告知「异常」。
- */
- export const TURN_TIMEOUT_MS = 180_000;
- const DEFAULT_QUIET_MS = 25_000;
- function toBlockView(
- src: BlockSource,
- now: number,
- quietMs: number,
- waitingSince = 0,
- /**
- * 用户已发出消息、但容器还一条都没回(2026-11-09)。
- *
- * 🔴 为什么需要独立标志:
- * 这类回合 `blocks` 为空 → `updatedAt = 0` → `idleFor` 极大 → `live` 恒 false,
- * 于是回合卡根本不会生成,界面在发送后**什么状态都不显示**,
- * 只能干等容器约 10 秒后第一次回话(用户实测「10 秒后才显示正在思考」)。
- *
- * 但「已发出」本身就是一个确定的状态,应该立刻可见。
- */
- awaitingFirstReply = false,
- ): TurnBlockView {
- const { steps, body } = splitIntoParts(src.messages);
- const files = body
- .filter((b): b is Extract<TurnBodyBlock, { kind: 'file' }> => b.kind === 'file')
- .map((b) => ({ key: b.key, file: b.file }));
- /*
- * live 判定与 `isTurnOpen` 同口径:容器正在 typing,或末条消息至今未超过静默窗口。
- * 群聊里某个成员可能先回完,所以按**块**判断而不是按回合。
- *
- * 🔴 typing 不能无限期作数(2026-11-09)。
- *
- * 实测:容器一轮结束后**不会**发 `m.typing:false`,`peerTyping` 一直停在 true。
- * 这时 `live` 恒为真 → 回合永远「输出中」、永远不会自动折叠
- * (用户实测:内容早已输出完,界面挂着「运行了 2 步 · 163s 输出中」)。
- *
- * 所以 typing 也受静默窗口约束:已经很久没有新内容,就不再信它。
- */
- const idleFor = now - src.updatedAt;
- const typingAlive = src.typing && idleFor < quietMs * 2;
- /*
- * 等待超时收尾(2026-11-10,用户裁决保留):
- *
- * `awaitingFirstReply` 若恒为真 → `live` 永远 true → 界面永远挂着
- * 「已送达,等待回复…(253s)」,`isTurnTimedOut` 要求 `!live` 永远不成立,
- * 全局提示也就永远不弹。所以等待超过 `TURN_TIMEOUT_MS` 后不再算「还在等」,
- * 交给超时逻辑收尾 → 占位消失、全局提示出现。
- */
- const waitingTooLong =
- awaitingFirstReply && waitingSince > 0 && now - waitingSince >= TURN_TIMEOUT_MS;
- const live =
- !src.closed && !waitingTooLong && (awaitingFirstReply || typingAlive || idleFor < quietMs);
- /*
- * 用时读数(2026-11-10 合并口径):
- *
- * | 字段 | 锚点 | 用途 |
- * |---|---|---|
- * | `startAt` | **用户发出问话的时刻** | 头部与段头的实时读数(1→2→3… 每秒加) |
- * | `seconds` | 首条 → 末条 agent 消息 | 容器**真实处理耗时**,结束时定格,不跳变 |
- *
- * 进行中的读数由渲染层用每秒时钟现算(`elapsedSeconds()`),
- * 不再用「消息事件时间戳相减」——那样只会 5s → 18s → 30s 地跳。
- */
- const startAt = waitingSince > 0 ? waitingSince : src.startedAt;
- return {
- key: src.agentId ?? 'agent',
- agentId: src.agentId,
- /** 容器真实处理耗时(首条 → 末条 agent 消息),结束才有意义 */
- seconds:
- src.startedAt > 0 && src.updatedAt >= src.startedAt
- ? Math.max(0, Math.round((src.updatedAt - src.startedAt) / 1000))
- : 0,
- /** 本块开始时刻(epoch ms,0 = 无锚点)—— 逐秒读数的锚点 */
- startAt,
- updatedAt: src.updatedAt,
- steps,
- body,
- files,
- live,
- empty: !live && body.length === 0 && steps.length === 0,
- merged: mergeBodies([{ body }]),
- waitingSince,
- waitMs: waitingSince > 0 ? Math.max(0, now - waitingSince) : 0,
- };
- }
- /**
- * 由各块合成回合阶段。
- *
- * 🔴 2026-11-10:「已完成」必须真的代表**有东西交付给用户**。
- *
- * 原判据是「只要不是全空就算 done」,于是容器只回了一串内部进度
- * (`🐍 Running code…` + 一句日志)时,卡片照样标「已完成」,
- * 用户打开一看什么也没有(实测截图)。
- *
- * 现在区分三档:
- * · 有正文 或 有文件 → `done`(真的交付了)
- * · 只有过程步骤、没有正文也没有文件 → `progressOnly`(干了活,但没交付)
- * · 什么都没有 → `idle`
- */
- function phaseOf(blocks: TurnBlockView[], closed: boolean): TurnPhase {
- if (blocks.some((b) => b.live && (b.body.length > 0 || b.steps.length > 0))) return 'replying';
- if (blocks.some((b) => b.live)) return 'thinking';
- if (blocks.length === 0) return closed ? 'idle' : 'thinking';
- const delivered = blocks.some((b) => b.body.length > 0 || b.files.length > 0);
- if (delivered) return 'done';
- // 只剩过程步骤:做过事,但没有可交付的内容
- return blocks.some((b) => b.steps.length > 0) ? 'progressOnly' : 'idle';
- }
- /**
- * 一块的**当前**用时秒数(2026-11-10 用户要求:一秒一秒叠加)。
- *
- * | 状态 | 返回值 |
- * |---|---|
- * | 无锚点(`startAt <= 0`) | 0,不显示 |
- * | 已结束(`!live`) | 从用户发问到结束的总用时(定格) |
- * | 进行中 | `floor((now - startAt) / 1000)`,**逐秒递增** |
- *
- * 🔴 进行中必须用实时时钟现算。原来直接用结束时刻相减,
- * 只在容器发新事件那一跳才变,用户看到的是 5s → 18s → 30s 的跳变。
- *
- * 取整一律 `floor`:进行中与结束态用同一种口径,结束瞬间才不会倒退 1 秒。
- *
- * @param block 块视图
- * @param now 当前时间(组件每秒刷新一次的那个时钟)
- */
- export function elapsedSeconds(block: TurnBlockView, now: number): number {
- if (block.startAt <= 0) return 0;
- /*
- * 结束态 = 用户发问 → 末条 agent 消息(体感用时)。
- * `block.seconds` 是「首条 → 末条 agent」,起点不同,不可与之相加。
- */
- if (!block.live) {
- return block.updatedAt > block.startAt
- ? Math.max(0, Math.floor((block.updatedAt - block.startAt) / 1000))
- : block.seconds;
- }
- return Math.max(0, Math.floor((now - block.startAt) / 1000));
- }
- /**
- * 等待中的占位文案(2026-11-09 用户裁决)。
- *
- * | 阶段 | 判据 | 文案 |
- * |---|---|---|
- * | 已发出,还没有任何输出 | `live` 且无内容 | 8 秒内「正在思考…」;之后「已送达,等待回复…(Ns)」 |
- * | 开始输出 | `live` 且有内容 | 「正在输出…(Ns)」 |
- * | 结束且全空 | 非 live 且 empty | **空**(不再显示「未响应」气泡) |
- *
- * 🔴 文案要**一直兜底到回复真的回来**,中途不能消失:
- * 容器回一轮要十几秒,界面空白会被理解成「发了没反应」。
- *
- * 🔴 2026-11-10 用户裁决:**超时不再在会话里留「未响应」气泡**。
- *
- * 原实现回合结束后恒显示一个「⊙ 未响应」的小气泡,永远留在消息流里,
- * 看起来像「每条都失败了」。改为:
- * · 会话内**完全移除**该占位(返回空串,段级判据同步不再渲染)
- * · 由页面层弹**全局提示**(可手动关闭、不自动消失),见 `useTurnTimeout()`
- *
- * @param waitMs 距用户发出消息已经过了多久
- * @param hasOutput 是否已经开始输出内容
- * @param live 是否仍在进行中
- * @param empty 是否已结束且什么也没有
- */
- export function waitText(waitMs: number, hasOutput: boolean, live: boolean, empty: boolean): string {
- // 已结束:无论有没有内容,都不再留等待占位(超时提示交给全局 toast)
- if (!live) return '';
- const sec = Math.max(0, Math.round(waitMs / 1000));
- if (hasOutput) return sec > 0 ? `正在输出…(${sec}s)` : '正在输出…';
- if (waitMs < WAIT_HINT_MS) return '正在思考…';
- return sec > 0 ? `已送达,等待回复…(${sec}s)` : '已送达,等待回复…';
- }
- /** 超过这个时长就明确告诉用户「发出了、在等」,不再只是「正在思考」 */
- export const WAIT_HINT_MS = 8_000;
- /**
- * 判定「这一轮是否已经超时未响应」(2026-11-10)。
- *
- * 超时 = 用户已发出消息、但经过 `timeoutMs` 仍**没有任何 agent 输出**,且回合已结束。
- * 页面据此弹全局提示(手动关闭)。
- *
- * @param waitMs 距用户发出消息的毫秒数
- * @param hasOutput agent 是否已经有正文或步骤
- * @param live 回合是否仍在进行
- */
- export function isTurnTimedOut(
- waitMs: number,
- hasOutput: boolean,
- live: boolean,
- timeoutMs = TURN_TIMEOUT_MS,
- ): boolean {
- return !live && !hasOutput && waitMs >= timeoutMs;
- }
- /* ------------------------------------------------------------------ */
- /* 两种输入 → 统一的回合视图 */
- /* ------------------------------------------------------------------ */
- /**
- * 群聊:`buildGroupTurns` 的结果 → 回合视图。
- *
- * 每个 `GroupBlock` 对应一个块;块顺序保持 `targets` 的声明顺序。
- */
- export function turnsFromGroup(
- turns: GroupTurn[],
- now: number,
- quietMs = DEFAULT_QUIET_MS,
- nameOf?: (agentId: string) => string,
- ): AssistantTurn[] {
- return turns.map((t) => {
- const blocks = t.blocks.map((b) => {
- const view = toBlockView(
- {
- agentId: b.agentId,
- messages: b.messages,
- startedAt: b.startedAt,
- updatedAt: b.updatedAt,
- typing: b.typing,
- closed: b.closed,
- },
- now,
- quietMs,
- t.userMessage ? Date.parse(t.userMessage.ts) || 0 : 0,
- /*
- * 群聊里「这一块还没收到任何回复」= 等待中(2026-11-09,与单聊同口径)。
- *
- * 原来空块的 `updatedAt = 0` 会让 `idleFor` 极大,`live` 恒 false,
- * 于是卡片是个空壳、没有文字 —— 用户看不到「谁在思考」(实测)。
- */
- b.messages.length === 0 && !b.closed,
- );
- const name = nameOf?.(b.agentId);
- return name ? { ...view, agentName: name } : view;
- });
- const live = blocks.some((b) => b.live);
- return {
- id: t.id,
- userMessage: t.userMessage,
- userFiles: t.userFiles ?? [],
- blocks,
- phase: phaseOf(blocks, t.closed),
- // 与块级同口径:从用户发消息起算,live 时走当前时钟(时间戳取自原始块)
- seconds: roundSeconds(t.blocks, now, live, t.userMessage ? Date.parse(t.userMessage.ts) || 0 : 0),
- live,
- closed: t.closed,
- stepCount: blocks.reduce((n, b) => n + b.steps.length, 0),
- fileCount: blocks.reduce((n, b) => n + b.files.length, 0),
- merged: mergeBodies(blocks),
- files: collectFiles(blocks),
- };
- });
- }
- /**
- * 单聊:`buildTurns` 的结果 → 回合视图(固定 1 块)。
- *
- * @param typing 容器是否在 typing(容器大多不发,通常为 false)
- * @param quietMs 「还在输出」的静默窗口,调用方传 `QUIET_MS`
- * @param agentIdle 容器**明确上报**的空闲态。为 true 时忽略静默窗口直接收尾 ——
- * 只有容器能宣布「我干完了」,比任何时间窗都准。
- */
- export function turnsFromDm(
- turns: Turn[],
- now: number,
- typing: boolean,
- quietMs = DEFAULT_QUIET_MS,
- agentIdle = false,
- ): AssistantTurn[] {
- return turns.map((t) => {
- /*
- * 「已发出、容器还没回一个字」——这是发送后立刻可见的状态(2026-11-09)。
- *
- * 判据:有用户消息、没有 agent 消息、回合还没结束。
- * 注意要用 `t.userMessage` 的时间做锚点,不能用 `t.updatedAt`
- * (后者在无 agent 消息时等于用户消息时间,但语义上不是「最后活动」)。
- */
- const awaitingFirstReply = !!t.userMessage && t.blocks.length === 0 && !t.closed;
- const userAsk = t.userMessage ? Date.parse(t.userMessage.ts) || 0 : 0;
- /*
- * 🔴 按「轮次」拆块(2026-11-10)。
- *
- * 容器对「图 + 文字」会各跑一轮,两轮在消息流里没有分界标记。
- * 每轮单独成块 → 各自独立判断 live、独立计时、占位提示只出现在
- * 「正在跑的那一轮」下面,不再挂到上一轮已答完的正文后面。
- */
- const rounds = t.rounds && t.rounds.length > 0 ? t.rounds : t.blocks.length > 0 ? [t.blocks] : [];
- /*
- * 没有 agent 消息时也要有**一个**占位块,否则「已发出、等回复」的标志
- * (`awaitingFirstReply`)无处挂载,卡片会整张消失。
- */
- const blocks = rounds.length
- ? rounds.map((msgs) => {
- const times = msgs.map((m) => Date.parse(m.ts) || 0).filter((n) => n > 0);
- const first = times.length ? Math.min(...times) : 0;
- const last = times.length ? Math.max(...times) : 0;
- /*
- * 本轮读秒锚点 = **不晚于本轮首条消息的最后一个用户提问时刻**。
- * 图文被拆成两条时:图片那轮用图片的发出时刻,文字那轮用文字的发出时刻,
- * 两轮读数各算各的,不会互相拉高,也不会在结束瞬间倒退。
- */
- const asks = (t.userAskTimes ?? []).filter((a) => a > 0 && (first === 0 || a <= first));
- const startAt = asks.length ? Math.max(...asks) : first || userAsk;
- return toBlockView(
- {
- agentId: null,
- messages: msgs,
- startedAt: first,
- updatedAt: last,
- typing,
- closed: t.closed,
- },
- now,
- agentIdle ? 0 : quietMs,
- startAt,
- false,
- );
- })
- : [
- toBlockView(
- { agentId: null, messages: [], startedAt: 0, updatedAt: 0, typing, closed: t.closed },
- now,
- agentIdle ? 0 : quietMs,
- userAsk,
- awaitingFirstReply,
- ),
- ];
- const live = blocks.some((b) => b.live);
- return {
- id: t.id,
- userMessage: t.userMessage,
- userFiles: t.userFiles ?? [],
- blocks,
- phase: phaseOf(blocks, t.closed),
- /* 回合用时取最长的块(各轮并行跑,按最长那轮算体感) */
- seconds: blocks.reduce((max, b) => Math.max(max, b.seconds), 0),
- live,
- closed: t.closed,
- stepCount: blocks.reduce((n, b) => n + b.steps.length, 0),
- fileCount: blocks.reduce((n, b) => n + b.files.length, 0),
- /*
- * 单聊的正文仍**合并成一份**(2026-11-07 用户要求「一整轮一张卡」)。
- * 拆轮只为了分别计时与分别判定状态,不改变阅读形态。
- */
- merged: mergeBodies(blocks),
- files: collectFiles(blocks),
- };
- });
- }
- /** 整轮的全部文件(跨容器聚合,宫格统一渲染) */
- function collectFiles(blocks: TurnBlockView[]): { key: string; file: FileCard }[] {
- const seen = new Set<string>();
- const out: { key: string; file: FileCard }[] = [];
- for (const b of blocks) {
- for (const f of b.files) {
- // 同名同大小的重复文件只出一张卡(多容器转发同一份时)
- const sig = `${f.file.name}|${f.file.size ?? 0}|${f.file.url}`;
- if (seen.has(sig)) continue;
- seen.add(sig);
- out.push(f);
- }
- }
- return out;
- }
- /**
- * 把整轮所有块的正文拼成一份。
- *
- * 块之间用空行分隔(Markdown 段落边界),保持可读;
- * key 取首条正文消息 id,**不随内容增长而变** —— 否则流式时模板会重建 DOM。
- */
- function mergeBodies(blocks: { body: TurnBodyBlock[] }[]): TurnMergedBody | null {
- const parts: string[] = [];
- let first: Message | null = null;
- let last: Message | null = null;
- for (const b of blocks) {
- for (const part of b.body) {
- if (part.kind !== 'text') continue;
- const t = (part.message.text ?? '').trim();
- if (!t) continue;
- parts.push(t);
- if (!first) first = part.message;
- last = part.message;
- }
- }
- if (!first || !last) return null;
- return { key: first.id, text: parts.join('\n\n'), message: last };
- }
- /** 回合耗时:首条 agent 消息到末条(各块取并集,避免多块重复计算) */
- /**
- * 回合级耗时(群聊汇总用)。
- *
- * 🔴 必须与块级 `toBlockView` 同一口径(2026-11-10),否则同一张卡片上
- * 段头写一个数、汇总写另一个数,用户会以为界面在乱跳。
- *
- * 口径:从**用户发出消息**起算。live 时取当前时钟(稳定递增),
- * 结束后冻结在最晚的一条消息时间。多块之间取「最大结束 - 用户消息」,
- * 也就是「这一轮最忙的那个成员干完为止」。
- */
- function roundSeconds(
- blocks: { startedAt: number; updatedAt: number }[],
- now: number,
- live: boolean,
- waitingSince: number,
- ): number {
- const starts = blocks.map((b) => b.startedAt).filter((n) => n > 0);
- const ends = blocks.map((b) => b.updatedAt).filter((n) => n > 0);
- // 锚点优先取用户消息,没有才回落到最早的一条 agent 消息
- const anchor = waitingSince > 0 ? waitingSince : starts.length ? Math.min(...starts) : 0;
- if (anchor <= 0) return 0;
- const endAt = live ? now : ends.length ? Math.max(...ends) : 0;
- if (endAt < anchor) return 0;
- return Math.max(0, Math.round((endAt - anchor) / 1000));
- }
- /** 便捷入口:判断回合里是否有该文件(避免模板里重复过滤) */
- export function hasFiles(t: AssistantTurn): boolean {
- return t.fileCount > 0;
- }
|