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。

fix(desktop): 「已工作」时长丢失首段思考时间,段起点改锚上一边界 (#598)

Mario258dd149483a
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index 828468d34c..51a76fd693 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -1162,7 +1162,7 @@ describe('groupWorkRuns — work-group collapsing', () => {
expect(items[2].key).toBe('plan-tw1');
});
- it('computes durationMs from run start createdAt to the terminating text createdAt', () => {
+ it('computes durationMs from the previous boundary (user message) to the terminating text createdAt', () => {
const seq = [
withTs(mkUser('u1'), '2026-06-10T10:00:00.000Z'),
withTs(mkTool('t1', 'Bash'), '2026-06-10T10:00:05.000Z'),
@@ -1171,7 +1171,9 @@ describe('groupWorkRuns — work-group collapsing', () => {
];
const items = build(seq, false);
const group = items.find((it): it is Extract<RenderItem, { type: 'work_group' }> => it.type === 'work_group');
- expect(group?.durationMs).toBe(140_000); // 10:00:05 → 10:02:25 = 2m20s
+ // 10:00:00 → 10:02:25 = 2m25s:段起点锚上一边界(用户消息),把首个动作到达前
+ // 的模型思考/延迟计入,与「正在工作…」活表口径一致(见 workGroupDurationAnchor.test)。
+ expect(group?.durationMs).toBe(145_000);
});
it('computes each nested action duration between assistant work updates', () => {
@@ -1190,10 +1192,12 @@ describe('groupWorkRuns — work-group collapsing', () => {
const nested = outer.children.filter(
(child): child is Extract<RenderItem, { type: 'work_group' }> => child.type === 'work_group',
);
- expect(outer.durationMs).toBe(18_000);
+ // 外层从上一边界(用户消息 10:00:00)到最终正文 10:00:20 = 20s;
+ // 内层各段从上一句正文起表:t1 = 10:00:01→10:00:10 = 9s,t2 = 10:00:10→10:00:20 = 10s。
+ expect(outer.durationMs).toBe(20_000);
expect(nested.map((group) => [group.key, group.durationMs])).toEqual([
- ['work-t1', 8_000],
- ['work-t2', 8_000],
+ ['work-t1', 9_000],
+ ['work-t2', 10_000],
]);
});
diff --git a/apps/desktop/src/renderer/__tests__/workGroupDurationAnchor.test.ts b/apps/desktop/src/renderer/__tests__/workGroupDurationAnchor.test.ts
new file mode 100644
index 0000000000..40efce2594
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/workGroupDurationAnchor.test.ts
@@ -0,0 +1,162 @@
+/**
+ * workGroupDurationAnchor.test.ts
+ * ---------------------------------------------------------------------------
+ * 回归:「已工作 Xs」低报 —— 段时长起点锚在段内第一个动作自带的时间戳上。
+ * 一次性到达(非流式)的 thinking 块 createdAt≈结束时刻(DB 恢复路径也只能回推出
+ * durationMs 的到达窗口),模型真正思考的几秒被整段丢弃。
+ *
+ * 复现(镜像真实会话数据):用户消息 → 6s 后 thinking 落库(自记时长仅 109ms)
+ * → 2ms 后正文。首段实际耗时 ~6s,界面显示「已工作 1s」;外层总表 29s,
+ * 内层两段 1s + 26s = 27s,账对不上。
+ *
+ * 修复:段起点优先锚在上一个边界(用户消息 / 上一句正文)——与「正在工作…」
+ * 活表使用的墙钟口径一致;边界缺失(窗口截断)或时序异常(rewind 改序)时
+ * 退回原有段内锚点,行为不劣于修复前。
+ *
+ * Node 环境(buildRenderItems / groupWorkRuns 都是纯函数)。
+ */
+
+import { describe, it, expect } from 'vitest';
+import { buildRenderItems, groupWorkRuns } from '../components/chat/MessageStream';
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+// ── 时间线基准(镜像真实 DB 证据的间隔) ─────────────────────────────────────
+const T0 = Date.parse('2026-07-01T00:00:00.000Z');
+const iso = (offsetMs: number) => new Date(T0 + offsetMs).toISOString();
+
+// ── 工厂 ───────────────────────────────────────────────────────────────────
+
+const mkUser = (id: string, createdAt?: string): ChatMessage => ({
+ clientId: id,
+ role: 'user',
+ content: '你觉得这个项目如何。',
+ ...(createdAt ? { createdAt } : {}),
+});
+
+const mkAssistant = (id: string, content: string, createdAt?: string): ChatMessage => ({
+ clientId: id,
+ role: 'assistant',
+ content,
+ ...(createdAt ? { createdAt } : {}),
+});
+
+/** 一次性到达的 thinking:createdAt≈结束时刻,自记时长只有到达窗口的毫秒级。 */
+const mkThinking = (id: string, createdAt: string, thinkingDurationMs: number): ChatMessage => ({
+ clientId: id,
+ role: 'thinking',
+ content: 'Reviewing the repository structure…',
+ createdAt,
+ thinkingDurationMs,
+});
+
+const mkTool = (id: string, createdAt: string): ChatMessage => ({
+ clientId: id,
+ role: 'tool_use',
+ content: '',
+ toolUseId: `tu-${id}`,
+ toolName: 'Bash',
+ toolInput: { command: 'ls' },
+ createdAt,
+});
+
+const mkResult = (id: string, toolUseId: string, createdAt: string): ChatMessage => ({
+ clientId: id,
+ role: 'tool_result',
+ content: 'ok',
+ toolUseId,
+ createdAt,
+});
+
+// ── 断言小工具 ───────────────────────────────────────────────────────────────
+
+type RenderItems = ReturnType<typeof groupWorkRuns>;
+type WorkGroupItem = Extract<RenderItems[number], { type: 'work_group' }>;
+
+function topLevelWorkGroups(items: RenderItems): WorkGroupItem[] {
+ return items.filter((it): it is WorkGroupItem => it.type === 'work_group');
+}
+
+/** 外层完成态组(work-summary-*)里的内层工作组,按出现顺序。 */
+function innerWorkGroups(outer: WorkGroupItem): WorkGroupItem[] {
+ return outer.children.filter((it): it is WorkGroupItem => it.type === 'work_group');
+}
+
+/** 复现截图的已回答 turn:
+ * user(T0) → thinking(T0+5951,自记 109ms) → 正文(T0+6062)
+ * → tool(T0+6500)/result → 最终正文(T0+29000)。 */
+function answeredTurnMessages(): ChatMessage[] {
+ return [
+ mkUser('u1', iso(0)),
+ mkThinking('th1', iso(5951), 109),
+ mkAssistant('a1', '我先快速摸一下代码规模和质量证据,再给评价。', iso(6062)),
+ mkTool('b1', iso(6500)),
+ mkResult('r1', 'tu-b1', iso(7000)),
+ mkAssistant('a2', '说下我的看法,老板。总体判断:这是个工程素养相当高的认真项目。', iso(29000)),
+ ];
+}
+
+// ── 完成态:内层段与外层总表都锚上一边界 ────────────────────────────────────
+
+describe('「已工作」时长 — 已回答 turn 锚定上一边界', () => {
+ it('纯 thinking 首段计入模型思考时间(6s,而非 111ms 的到达窗口)', () => {
+ const items = groupWorkRuns(buildRenderItems(answeredTurnMessages()).items, false);
+
+ const outers = topLevelWorkGroups(items);
+ expect(outers).toHaveLength(1);
+ const inners = innerWorkGroups(outers[0]);
+ expect(inners.length).toBeGreaterThanOrEqual(2);
+
+ // 首段 = [thinking th1],边界为 user(T0) → 正文 a1(T0+6062)
+ expect(inners[0].durationMs).toBe(6062);
+ });
+
+ it('后续段从上一句正文起表,外层总表覆盖整轮,内层相加=外层', () => {
+ const items = groupWorkRuns(buildRenderItems(answeredTurnMessages()).items, false);
+
+ const outer = topLevelWorkGroups(items)[0];
+ const inners = innerWorkGroups(outer);
+
+ // 第二段 = [tool b1],边界为正文 a1(T0+6062) → 最终正文 a2(T0+29000)
+ expect(inners[1].durationMs).toBe(29000 - 6062);
+ // 外层总表:user(T0) → 最终正文(T0+29000)
+ expect(outer.durationMs).toBe(29000);
+ // 账目对齐:内层相加 = 外层
+ const sum = inners.reduce((acc, g) => acc + (g.durationMs ?? 0), 0);
+ expect(sum).toBe(outer.durationMs);
+ });
+});
+
+// ── 流式尾 turn:活表 startedAtMs 同口径 ────────────────────────────────────
+
+describe('「正在工作…」活表 — 流式尾 turn 锚定上一边界', () => {
+ it('startedAtMs 从用户消息起跳,而非段内 thinking 到达时刻', () => {
+ const messages: ChatMessage[] = [mkUser('u1', iso(0)), mkThinking('th1', iso(5951), 109)];
+ const items = groupWorkRuns(buildRenderItems(messages).items, true);
+
+ const groups = topLevelWorkGroups(items);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].isStreaming).toBe(true);
+ expect(groups[0].startedAtMs).toBe(T0);
+ });
+});
+
+// ── 防御:边界缺失时退回原有段内锚点 ────────────────────────────────────────
+
+describe('「已工作」时长 — 无上一边界时退回段内锚点', () => {
+ it('窗口截断(无用户消息)时保持修复前行为', () => {
+ const messages: ChatMessage[] = [
+ mkThinking('th1', iso(5951), 109),
+ mkAssistant('a1', '我先快速摸一下代码规模和质量证据,再给评价。', iso(6062)),
+ mkTool('b1', iso(6500)),
+ mkResult('r1', 'tu-b1', iso(7000)),
+ mkAssistant('a2', '说下我的看法,老板。', iso(29000)),
+ ];
+ const items = groupWorkRuns(buildRenderItems(messages).items, false);
+
+ const outer = topLevelWorkGroups(items)[0];
+ const inners = innerWorkGroups(outer);
+ // 首段无上一边界:起点仍是 thinking createdAt+durationMs 口径的段内锚
+ // (workRunStartTs = createdAt),6062 - 5951 = 111ms
+ expect(inners[0].durationMs).toBe(111);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 96296539e1..4ddbe3d37b 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -300,7 +300,9 @@ interface WorkGroupRenderItem {
durationMs?: number;
/** 当前是否是仍在执行的尾部动作段。完成态时间线始终 false。 */
isStreaming: boolean;
- /** 工作段首个真实活动的 epoch ms,供 live elapsed ticker 使用。 */
+ /** 工作段起点 epoch ms,供 live elapsed ticker 使用。优先是上一个边界
+ * (用户消息/上一句正文,可能早于段内首个活动),边界缺失时退回首个活动
+ * 时间戳 —— 与 durationMs 的段起点同源(见 createWorkGroup)。 */
startedAtMs?: number;
}
@@ -1370,6 +1372,12 @@ function messageTs(msg: ChatMessage): number | null {
return Number.isFinite(t) ? t : null;
}
+/** 边界项(用户消息 / assistant 正文)的时间戳;非 message 项(卡片等)返回 null,
+ * 让下一段退回段内锚点,避免把已折叠段的时长重复计入。 */
+function boundaryTs(item: RenderItem | undefined): number | null {
+ return item && item.type === 'message' ? messageTs(item.message) : null;
+}
+
/** run 首子项的起始时间戳。 */
function workRunStartTs(it: WorkChildItem): number | null {
if (it.type === 'tool_segment') return messageTs(it.toolCalls[0]);
@@ -1408,9 +1416,18 @@ function createWorkGroup(
run: WorkChildItem[],
nextItem: RenderItem | undefined,
isStreaming = false,
+ prevBoundaryTs: number | null = null,
): Extract<RenderItem, { type: 'work_group' }> {
const firstActivity = run.find((it) => it.type !== 'message' || it.message.role === 'thinking');
- const startTs = workRunStartTs(firstActivity ?? run[0]);
+ const anchorTs = workRunStartTs(firstActivity ?? run[0]);
+ // 段起点优先锚上一个边界(用户消息 / 上一句正文),与「正在工作…」活表的墙钟
+ // 口径一致:一次性到达的 thinking 块 createdAt≈结束时刻,只用段内锚点会把
+ // 模型思考整段丢掉(实际 6s 显示 1s,内层相加也对不上外层总表)。边界缺失
+ // (窗口截断)或时序异常(rewind 改序)时退回段内锚点。
+ const startTs =
+ prevBoundaryTs !== null && (anchorTs === null || prevBoundaryTs <= anchorTs)
+ ? prevBoundaryTs
+ : anchorTs;
const endTs =
nextItem && nextItem.type === 'message'
? messageTs(nextItem.message)
@@ -1433,17 +1450,19 @@ function createWorkGroup(
function createCompletedWorkGroup(
run: WorkChildItem[],
nextItem: RenderItem | undefined,
+ prevBoundaryTs: number | null = null,
): WorkGroupRenderItem {
const hasAssistantText = run.some(
(item) => item.type === 'message' && item.message.role === 'assistant',
);
- if (!hasAssistantText) return createWorkGroup(run, nextItem);
+ if (!hasAssistantText) return createWorkGroup(run, nextItem, false, prevBoundaryTs);
const children: WorkGroupChildItem[] = [];
let activityRun: WorkChildItem[] = [];
+ let innerPrevBoundaryTs = prevBoundaryTs;
const flushActivityRun = (activityNextItem: RenderItem | undefined) => {
if (activityRun.length === 0) return;
- children.push(createWorkGroup(activityRun, activityNextItem));
+ children.push(createWorkGroup(activityRun, activityNextItem, false, innerPrevBoundaryTs));
activityRun = [];
};
@@ -1454,10 +1473,11 @@ function createCompletedWorkGroup(
}
flushActivityRun(item);
children.push(item);
+ innerPrevBoundaryTs = boundaryTs(item);
}
flushActivityRun(nextItem);
- const outer = createWorkGroup(run, nextItem);
+ const outer = createWorkGroup(run, nextItem, false, prevBoundaryTs);
return {
...outer,
key: `work-summary-${workGroupClientId(run)}`,
@@ -1466,13 +1486,14 @@ function createCompletedWorkGroup(
};
}
-function groupLegacyWorkRuns(items: RenderItem[]): RenderItem[] {
+function groupLegacyWorkRuns(items: RenderItem[], turnStartTs: number | null = null): RenderItem[] {
const out: RenderItem[] = [];
let run: WorkChildItem[] = [];
+ let prevBoundaryTs = turnStartTs;
const flushRun = (nextItem: RenderItem | undefined) => {
if (run.length === 0) return;
- out.push(createWorkGroup(run, nextItem));
+ out.push(createWorkGroup(run, nextItem, false, prevBoundaryTs));
run = [];
};
@@ -1485,6 +1506,7 @@ function groupLegacyWorkRuns(items: RenderItem[]): RenderItem[] {
} else {
flushRun(it);
out.push(it);
+ prevBoundaryTs = boundaryTs(it);
}
}
flushRun(undefined);
@@ -1498,7 +1520,7 @@ function groupLegacyWorkRuns(items: RenderItem[]): RenderItem[] {
* - 最后一段之后还没有新的边界时,该段才标成 streaming,
* 默认显示 latest-five preview。
*/
-function groupActiveWorkRuns(items: RenderItem[]): RenderItem[] {
+function groupActiveWorkRuns(items: RenderItem[], turnStartTs: number | null = null): RenderItem[] {
let lastCompletedRunBoundaryIdx = -1;
for (let i = 0; i < items.length; i++) {
if (isAssistantAnswerCandidate(items[i]) || isCompactBoundaryItem(items[i])) {
@@ -1509,9 +1531,12 @@ function groupActiveWorkRuns(items: RenderItem[]): RenderItem[] {
const out: RenderItem[] = [];
let run: WorkChildItem[] = [];
let runLastIdx = -1;
+ let prevBoundaryTs = turnStartTs;
const flushRun = (nextItem: RenderItem | undefined) => {
if (run.length === 0) return;
- out.push(createWorkGroup(run, nextItem, runLastIdx > lastCompletedRunBoundaryIdx));
+ out.push(
+ createWorkGroup(run, nextItem, runLastIdx > lastCompletedRunBoundaryIdx, prevBoundaryTs),
+ );
run = [];
};
@@ -1523,6 +1548,7 @@ function groupActiveWorkRuns(items: RenderItem[]): RenderItem[] {
} else {
flushRun(it);
out.push(it);
+ prevBoundaryTs = boundaryTs(it);
}
}
flushRun(undefined);
@@ -1540,7 +1566,10 @@ function groupActiveWorkRuns(items: RenderItem[]): RenderItem[] {
* handled:false,交回 groupLegacyWorkRuns 按连续动作折叠。tool_media /
* agent_plan /运行中子 Agent 等非可归档项保持可见,并作为顺序锚点切开工作组。
*/
-function groupAnsweredTurnItems(turnItems: RenderItem[]): {
+function groupAnsweredTurnItems(
+ turnItems: RenderItem[],
+ turnStartTs: number | null = null,
+): {
items: RenderItem[];
handled: boolean;
} {
@@ -1616,9 +1645,10 @@ function groupAnsweredTurnItems(turnItems: RenderItem[]): {
const out: RenderItem[] = [];
let run: WorkChildItem[] = [];
+ let prevBoundaryTs = turnStartTs;
const flushRun = (nextItem: RenderItem | undefined) => {
if (run.length === 0) return;
- out.push(createCompletedWorkGroup(run, nextItem));
+ out.push(createCompletedWorkGroup(run, nextItem, prevBoundaryTs));
run = [];
};
@@ -1629,6 +1659,7 @@ function groupAnsweredTurnItems(turnItems: RenderItem[]): {
} else {
flushRun(it);
out.push(it);
+ prevBoundaryTs = boundaryTs(it);
}
}
flushRun(undefined);
@@ -1776,17 +1807,20 @@ function renderWorkGroupChild(
export function groupWorkRuns(items: RenderItem[], isSessionStreaming: boolean): RenderItem[] {
const out: RenderItem[] = [];
let currentTurn: RenderItem[] = [];
+ // turn 开场边界(用户消息)的时间戳;窗口截断没见到用户消息时为 null,
+ // 各分组路径退回段内锚点。
+ let turnStartTs: number | null = null;
const flushTurn = (isActiveTail: boolean) => {
if (currentTurn.length === 0) return;
const activeStreaming = isActiveTail && isSessionStreaming;
if (activeStreaming) {
- out.push(...groupActiveWorkRuns(currentTurn));
+ out.push(...groupActiveWorkRuns(currentTurn, turnStartTs));
currentTurn = [];
return;
}
- const grouped = groupAnsweredTurnItems(currentTurn);
- out.push(...(grouped.handled ? grouped.items : groupLegacyWorkRuns(currentTurn)));
+ const grouped = groupAnsweredTurnItems(currentTurn, turnStartTs);
+ out.push(...(grouped.handled ? grouped.items : groupLegacyWorkRuns(currentTurn, turnStartTs)));
currentTurn = [];
};
@@ -1794,6 +1828,7 @@ export function groupWorkRuns(items: RenderItem[], isSessionStreaming: boolean):
if (it.type === 'message' && it.message.role === 'user') {
flushTurn(false);
out.push(it);
+ turnStartTs = messageTs(it.message);
continue;
}
currentTurn.push(it);
diff --git a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx
index 81394b4f39..901da2533b 100644
--- a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx
+++ b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx
@@ -102,7 +102,9 @@ export interface WorkGroupBlockProps {
durationMs?: number;
/** True while this is the active trailing work run. */
isStreaming?: boolean;
- /** Epoch ms of the first real activity, used for the live elapsed ticker. */
+ /** Work-run start epoch ms for the live elapsed ticker: the previous
+ * boundary (user message / preceding text) when available — may predate
+ * the first activity — falling back to the first activity timestamp. */
startedAtMs?: number;
childItems: WorkGroupChild[];
}