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): 重连时统一状态并隐藏生成速度 (#4758)

DavidShenXDade6f398ccb4
diff --git a/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts
new file mode 100644
index 0000000000..edcf9ebe82
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import { findActiveReconnect } from '@/lib/autoResumePresentation';
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+const row = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
+ clientId: 'retry',
+ role: 'user',
+ content: '',
+ isStreaming: false,
+ systemCardType: 'auto-resume',
+ systemCardData: { attempt: 1, maxAttempts: 5 },
+ ...overrides,
+});
+const base = {
+ sessionRunning: true,
+ continuationTurnClientId: 'retry',
+ projectionCapability: 'supported' as const,
+};
+
+describe('composer reconnect presentation', () => {
+ it('shows pending backoff even without a running turn and uses the latest progress', () => {
+ const messages = [
+ row(),
+ row({
+ clientId: 'pending',
+ role: 'assistant',
+ systemCardType: 'auto-resume-pending',
+ systemCardData: { attempt: 2, maxAttempts: 5 },
+ }),
+ ];
+ expect(
+ findActiveReconnect({
+ ...base,
+ messages,
+ sessionRunning: false,
+ continuationTurnClientId: null,
+ }),
+ ).toMatchObject({ attempt: 2, maxAttempts: 5 });
+ });
+
+ it('keeps the reconnect status when backoff hands over to the running continuation', () => {
+ expect(findActiveReconnect({ ...base, messages: [row()] })).toMatchObject({
+ attempt: 1,
+ maxAttempts: 5,
+ });
+ });
+
+ it.each(['succeeded', 'failed'])('settled outcome %s stops overriding generation', (outcome) => {
+ expect(
+ findActiveReconnect({
+ ...base,
+ messages: [
+ row({
+ systemCardData: { attempt: 1, maxAttempts: 5, outcome },
+ }),
+ ],
+ }),
+ ).toBeNull();
+ });
+
+ it('does not revive historical retries or silent-stop continuations', () => {
+ expect(
+ findActiveReconnect({ ...base, continuationTurnClientId: null, messages: [row()] }),
+ ).toBeNull();
+ expect(findActiveReconnect({ ...base, messages: [row({ systemCardData: {} })] })).toBeNull();
+ });
+
+ it('legacy owners ignore steering but stop after a new user turn or Stop', () => {
+ const legacy = {
+ ...base,
+ continuationTurnClientId: null,
+ projectionCapability: 'legacy' as const,
+ };
+ const messages = [
+ row(),
+ row({ clientId: 'steer', delivery: 'steer', systemCardType: undefined }),
+ ];
+ expect(findActiveReconnect({ ...legacy, messages })).not.toBeNull();
+ expect(findActiveReconnect({ ...legacy, messages, sessionRunning: false })).toBeNull();
+ messages.push(row({ clientId: 'user', systemCardType: undefined }));
+ expect(findActiveReconnect({ ...legacy, messages })).toBeNull();
+ expect(
+ findActiveReconnect({ ...legacy, projectionCapability: 'unknown', messages: [row()] }),
+ ).toBeNull();
+ });
+
+ it('invalid progress falls back to an unnumbered pending state', () => {
+ const active = findActiveReconnect({
+ ...base,
+ messages: [
+ row({
+ role: 'assistant',
+ systemCardType: 'auto-resume-pending',
+ systemCardData: { attempt: NaN, maxAttempts: 'five' },
+ }),
+ ],
+ });
+ expect(active).not.toBeNull();
+ expect(active?.attempt).toBeUndefined();
+ expect(active?.maxAttempts).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
index c292c40fb2..4927cc6da5 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
@@ -57,6 +57,7 @@ vi.mock('@/lib/composerDraftStore', () => ({
}));
import { EMPTY_SESSION_STATE, handleStreamEvent, makerChatStore } from '@/lib/makerChatStore';
+import { findActiveReconnect } from '@/lib/autoResumePresentation';
import * as messageService from '@/lib/messageService';
import type { Message } from '@/lib/ccAgent.types';
import type { ChatMessage } from '@/lib/makerChatStore';
@@ -506,6 +507,42 @@ describe('applyInputProjection 自愈进行中提示', () => {
});
describe('Codex 原生重连进行态与终态接管交棒', () => {
+ const composerReconnect = (state: typeof EMPTY_SESSION_STATE) => findActiveReconnect({
+ messages: state.messages,
+ sessionRunning: state.agentStatus.isRunning || state.isStreaming,
+ continuationTurnClientId: state.continuationTurnClientId,
+ projectionCapability: state.continuationInFlightProjectionCapability,
+ });
+
+ it.each(['codex', 'pi'] as const)('%s reconnect overrides stale generation until substantive output or termination', (source) => {
+ const generating = {
+ ...EMPTY_SESSION_STATE,
+ agentStatus: { ...EMPTY_SESSION_STATE.agentStatus, isRunning: true, status: 'Generating...',
+ startedAt: 1, outputTokens: 465, generationDurationMs: 10000 },
+ };
+ const pending = handleStreamEvent(generating, {
+ sessionId: SID, source, type: 'error',
+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },
+ });
+ expect(composerReconnect(pending)).toMatchObject({ attempt: 1, maxAttempts: 5 });
+ const whitespace = handleStreamEvent(pending, {
+ sessionId: SID, source, type: 'text', data: { text: ' ', isFinal: false },
+ });
+ expect(composerReconnect(whitespace)).not.toBeNull();
+ const statusOnly = handleStreamEvent(whitespace, {
+ sessionId: SID, source, type: 'status', data: { status: 'Generating...' },
+ });
+ expect(composerReconnect(statusOnly)).not.toBeNull();
+ for (const event of [
+ { type: 'text' as const, data: { text: 'Recovered', isFinal: false } },
+ { type: 'tool_use' as const, data: { toolName: 'shell', toolUseId: 't1', input: { command: 'pwd' } } },
+ { type: 'done' as const, data: {} },
+ { type: 'error' as const, data: { message: 'Retries exhausted', isTerminal: true } },
+ ]) {
+ expect(composerReconnect(handleStreamEvent(statusOnly, { ...event, source, sessionId: SID }))).toBeNull();
+ }
+ });
+
const reconnectEvent = (message: string, isTerminal: boolean) => ({
sessionId: SID,
type: 'error' as const,
diff --git a/apps/desktop/src/renderer/__tests__/reducedMotionEscape.test.ts b/apps/desktop/src/renderer/__tests__/reducedMotionEscape.test.ts
index 6a28744c02..1243d91d28 100644
--- a/apps/desktop/src/renderer/__tests__/reducedMotionEscape.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reducedMotionEscape.test.ts
@@ -87,16 +87,18 @@ describe('prefers-reduced-motion 覆盖面(globals.css)', () => {
});
describe('RunningStatusBar cadenced shimmer 的运行期 reduced-motion 切换', () => {
- it('动画被摘时清空 playing/pending,并把 reducedMotion 纳入 effect 依赖', () => {
+ it('动画被摘时清空 playing/pending,并把 reducedMotion 和 reconnecting 纳入 effect 依赖', () => {
expect(sessionViewSource).toContain(
"import { useReducedMotion } from '@/hooks/useReducedMotion'",
);
expect(sessionViewSource).toContain('const reducedMotion = useReducedMotion();');
- expect(sessionViewSource).toContain('if (!visible || suppressContent || reducedMotion) {');
+ expect(sessionViewSource).toContain(
+ 'if (!visible || suppressContent || reducedMotion || reconnecting) {',
+ );
expect(sessionViewSource).toContain('shimmerPlayingRef.current = false;');
expect(sessionViewSource).toContain('shimmerPendingRef.current = false;');
expect(sessionViewSource).toMatch(
- /\},\s*\[\s*visible,\s*suppressContent,\s*reducedMotion,\s*status,\s*tokenUsage,\s*outputTokens,\s*generationDurationMs,?\s*\]\);/,
+ /\},\s*\[\s*visible,\s*suppressContent,\s*reducedMotion,\s*reconnecting,\s*status,\s*tokenUsage,\s*outputTokens,\s*generationDurationMs,?\s*\]\);/,
);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
index a89ea2c3a3..11c082bc55 100644
--- a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
@@ -52,6 +52,7 @@ const deps = {
Activity: Icon,
Layers: Icon,
Sparkles: Icon,
+ Spinner: Icon,
Square: Icon,
ArrowDown: Icon,
STATUS_BAR_FADE_MS: 400,
@@ -69,6 +70,7 @@ const RunningStatusBar = new Function(
suppressContent?: boolean;
rightLeadingSlot?: React.ReactNode;
status: string;
+ reconnectStatus?: string | null;
startedAt: number;
tokenUsage: number;
outputTokens: number;
@@ -78,6 +80,52 @@ const RunningStatusBar = new Function(
afterEach(cleanup);
+it.each([false, true])('reconnect hides stale speed and pinned history, then waits for fresh samples (pinned=%s)', (pinned) => {
+ const props = {
+ visible: true, status: 'Generating...', startedAt: 1, tokenUsage: 1000,
+ outputTokens: 0, generationDurationMs: 0, generationReliable: true,
+ };
+ const { container, rerender } = render(<RunningStatusBar {...props} />);
+ const measured = { ...props, outputTokens: 465, generationDurationMs: 10000 };
+ rerender(<RunningStatusBar {...measured} />);
+ const trigger = () => container.querySelector('[data-running-status-meta] button');
+ expect(trigger()?.textContent).toContain('chat.runningStatus.tokenRate');
+ if (pinned) {
+ fireEvent.click(trigger()!);
+ expect(screen.getByRole('dialog').textContent).toContain('46.5');
+ }
+
+ rerender(<RunningStatusBar {...measured} reconnectStatus="Reconnecting 1/5" />);
+ expect(screen.getByText('Reconnecting 1/5')).toBeTruthy();
+ expect(screen.queryByText('Generating...')).toBeNull();
+ expect(trigger()).toBeNull();
+ expect(container.querySelector('[data-running-status-meta]')?.textContent).not.toContain('token');
+ expect(screen.queryByRole('dialog')).toBeNull();
+
+ rerender(<RunningStatusBar {...measured} reconnectStatus="Reconnecting 2/5" />);
+ expect(screen.getByText('Reconnecting 2/5')).toBeTruthy();
+ expect(trigger()).toBeNull();
+
+ // Recovery must not redisplay the pre-interruption 46.5 tok/s.
+ rerender(<RunningStatusBar {...measured} />);
+ expect(screen.getByText('Generating...')).toBeTruthy();
+ expect(trigger()?.textContent).toContain('chat.runningStatus.waitingSample');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ rerender(<RunningStatusBar {...measured} outputTokens={515} generationDurationMs={11000} />);
+ expect(trigger()?.textContent).toContain('chat.runningStatus.tokenRate');
+ fireEvent.click(trigger()!);
+ expect(screen.getByRole('dialog').textContent).toContain('50');
+});
+
+it('reconnect hides token fallback for harnesses without reliable generation timing', () => {
+ const { container } = render(<RunningStatusBar
+ visible status="Generating..." reconnectStatus="Reconnecting" startedAt={1}
+ tokenUsage={1000} outputTokens={465} generationDurationMs={0} generationReliable={false}
+ />);
+ expect(screen.getByText('Reconnecting')).toBeTruthy();
+ expect(container.querySelector('[data-running-status-meta]')?.textContent).not.toContain('token');
+});
+
it('opens measured zero history and restores fallback across reliability and turn changes', () => {
const props = {
visible: true,
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index b53ddbd0bb..35614f0dd6 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -83,6 +83,8 @@ import type {
ChatMessage,
ContinuationInFlightProjectionCapability,
} from '@/hooks/useCCAgentChat';
+import { findLastUserInputClientId, isAutoResumeRowInFlight } from '@/lib/autoResumePresentation';
+export { findLastUserInputClientId, isAutoResumeRowInFlight } from '@/lib/autoResumePresentation';
import { Spinner } from '@/components/ui/spinner';
import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreference';
import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';
@@ -825,51 +827,6 @@ export function findLastUserMessageClientId(messages: readonly ChatMessage[]): s
return null;
}
-/**
- * 最后一条「用户侧输入」的 clientId —— **含**合成行(自动续跑指令本身)。
- *
- * 与上面的 `findLastUserMessageClientId` 的区别就在这里:那份服务于「编辑最后一条消息」
- * 这个**可见** affordance,刻意跳过渲染成 null 的合成行;本份要回答的是「此刻正在跑的
- * 这个 turn 是不是自动续跑发起的」——合成行恰恰是那个 turn 的发起者,跳过就答不了。
- *
- * 用途:自愈重连行判断自己是不是"仍在飞"。用户在续跑之后又自己发了消息时,最后一条用户
- * 侧输入就换成他那条,旧的重连行随之停转(正在跑的已经是另一个 turn 了)。
- */
-export function findLastUserInputClientId(messages: readonly ChatMessage[]): string | null {
- for (let i = messages.length - 1; i >= 0; i--) {
- // **插话(`delivery === 'steer'`)不算新 turn 的发起者** —— 它是同一个正在跑的 turn 内
- // 的追加输入。算进来的话,用户在自愈 turn 里插一句,正在跑的重连行会立刻被"夺走归属"、
- // 提前停转退回静态(codex P2 / greptile P1)。本文件里其它 turn 边界判断(见上方
- // `hasFollowingUserTurn` 等)也都显式排除 steer,此处保持一致。
- //
- // 首选判据直接使用 main 投影的 vendor-turn owner;旧被控端缺省 owner 字段时,
- // 才由下面的兼容分支按最后一条非 steer 用户输入兜底。
- if (messages[i].role === 'user' && messages[i].delivery !== 'steer') {
- return messages[i].clientId;
- }
- }
- return null;
-}
-
-/**
- * 自愈落库行是否仍属于当前运行中的续跑 turn。
- *
- * 新端以 main 持有的 vendor-turn owner 做精确关联;只有 wire 上确实缺省 owner 字段的旧
- * 被控端才恢复历史启发式。旧端无法区分自动续跑与不落 user 行的 Goal turn,这是协议信息
- * 不足时的兼容降级,不能扩散到 supported / unknown 两种状态。
- */
-export function isAutoResumeRowInFlight(args: {
- isContinuationTurnOwner: boolean;
- sessionRunning: boolean;
- isLastUserInput: boolean;
- projectionCapability: ContinuationInFlightProjectionCapability;
-}): boolean {
- return (
- args.isContinuationTurnOwner ||
- (args.projectionCapability === 'legacy' && args.sessionRunning && args.isLastUserInput)
- );
-}
-
export function shouldBlockAssistantFork(
isSessionStreaming: boolean,
message: ChatMessage,
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index da5dd8ca8c..3ae8fe1733 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -21,6 +21,11 @@ import {
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
+import {
+ hasInterruptionContext,
+ readAutoResumeInfo,
+ type AutoResumeCardInfo,
+} from '@/lib/autoResumePresentation';
import { cn } from '@/lib/utils';
import { Collapse } from '@/components/ui/collapse';
import { Spinner } from '@/components/ui/spinner';
@@ -851,53 +856,6 @@ function GoalResumedCard({ data }: { data?: { kind?: string } }) {
);
}
-/**
- * silent-stop 自动续跑分隔条:上游空响应静默收尾后,main 守卫自动补发了隐藏的
- * 「继续」。用户不看到用户气泡,只看到这条轻分隔线标记"上一段与下一段之间发生过
- * 一次自动接续"(否则模型"一句话断成两段凭空接着说"会让人怀疑消息丢了)。
- * 复用 CompactBoundaryCard / GoalResumedCard 的分隔条视觉语言。
- */
-/** 活动行需要的展示信息(从 systemCardData 松散读取,缺字段一律降级而不是崩)。 */
-interface AutoResumeCardInfo {
- error?: string;
- attempt?: number;
- maxAttempts?: number;
- sessionTotal?: number;
- /** 结果:由 main 在产出 / 再次被打断时回填;缺省 = 还在等结果。 */
- outcome?: 'succeeded' | 'failed';
-}
-
-/**
- * 这条自动续跑记录属于「中断重连」还是 silent-stop 的「空回复后续跑」。
- *
- * 判据是有没有任何中断上下文(原因 / 次数 / 累计 / 结果)。**必须区分**:silent-stop 那条
- * 路径也走 `auto-resume` 卡,但它不是重连——把三态重连行套上去,历史里那条「已自动继续」
- * 会变成语义错误的「重新连接」(copilot review)。
- */
-function hasInterruptionContext(info: AutoResumeCardInfo): boolean {
- return (
- info.error !== undefined ||
- info.attempt !== undefined ||
- info.maxAttempts !== undefined ||
- info.sessionTotal !== undefined ||
- info.outcome !== undefined
- );
-}
-
-function readAutoResumeInfo(data?: Record<string, unknown>): AutoResumeCardInfo {
- const num = (v: unknown) =>
- typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined;
- return {
- ...(typeof data?.error === 'string' && data.error.length > 0 ? { error: data.error } : {}),
- ...(num(data?.attempt) !== undefined ? { attempt: num(data?.attempt) } : {}),
- ...(num(data?.maxAttempts) !== undefined ? { maxAttempts: num(data?.maxAttempts) } : {}),
- ...(num(data?.sessionTotal) !== undefined ? { sessionTotal: num(data?.sessionTotal) } : {}),
- ...(data?.outcome === 'succeeded' || data?.outcome === 'failed'
- ? { outcome: data.outcome }
- : {}),
- };
-}
-
/**
* 把中断原文压成一行摘要,放进活动行的 param 位(对齐 AgentActionRow 的
* 「动词 + 命令 / 文件名」结构)。
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 8b3c8836d4..a7e95c11af 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -298,6 +298,7 @@ import {
} from './deferredUiAssignment';
import { shouldFallbackVendorModel } from './lib/vendorModelFallback';
import { localizeAgentStatus } from './lib/localizeAgentStatus';
+import { findActiveReconnect } from '@/lib/autoResumePresentation';
import { createSessionRefreshSequence } from './lib/sessionRefreshSequence';
import { hasInlineOverloadRetry } from './lib/inlineRetryError';
import { createSessionSnapshotPatchBuffer } from './lib/sessionSnapshotPatchBuffer';
@@ -2012,6 +2013,23 @@ export function CCAgentSessionView({
() => (isRemoteSession || remoteDeviceId ? null : summarizeRunningWorkflow(taskUpdates)),
[isRemoteSession, remoteDeviceId, taskUpdates],
);
+ const activeReconnect = useMemo(
+ () => findActiveReconnect({
+ messages,
+ sessionRunning: agentStatus.isRunning || isStreaming,
+ continuationTurnClientId,
+ projectionCapability: continuationInFlightProjectionCapability,
+ }),
+ [messages, agentStatus.isRunning, isStreaming, continuationTurnClientId, continuationInFlightProjectionCapability],
+ );
+ const reconnectStatus = activeReconnect
+ ? activeReconnect.attempt !== undefined && activeReconnect.maxAttempts !== undefined
+ ? t('chat.systemCard.autoResumePending.labelWithProgress', {
+ attempt: activeReconnect.attempt,
+ total: activeReconnect.maxAttempts,
+ })
+ : t('chat.systemCard.autoResumePending.label')
+ : null;
const composerStatus = runningWorkflow
? runningWorkflow.total > 0
? t('ccAgent.agentStatus.waitingWorkflowProgress', runningWorkflow)
@@ -4841,12 +4859,13 @@ export function CCAgentSessionView({
key={sessionId}
sessionKey={sessionId ?? null}
status={composerStatus}
+ reconnectStatus={reconnectStatus}
tokenUsage={agentStatus.tokenUsage}
outputTokens={agentStatus.outputTokens ?? 0}
generationDurationMs={agentStatus.generationDurationMs ?? 0}
generationReliable={agentStatus.generationReliable ?? true}
startedAt={agentStatus.startedAt}
- visible={composerRuntimeVisible}
+ visible={composerRuntimeVisible || (!pendingPlanReview && activeReconnect !== null)}
inputWidth={inputWidth}
sideTaskRunning={agentStatus.sideTaskRunning ?? false}
backgroundTasksRunning={backgroundTasksActive}
@@ -5702,6 +5721,7 @@ const CONTROLLED_BANNER_MAX_WIDTH = 420;
function RunningStatusBar({
status,
+ reconnectStatus = null,
tokenUsage,
outputTokens = 0,
generationDurationMs = 0,
@@ -5721,6 +5741,8 @@ function RunningStatusBar({
className,
}: {
status: string;
+ /** Same pending row / continuation owner as the message stream; overrides stale agent status. */
+ reconnectStatus?: string | null;
tokenUsage: number;
outputTokens?: number;
generationDurationMs?: number;
@@ -5770,6 +5792,10 @@ function RunningStatusBar({
const [showContent, setShowContent] = useState(visible);
const [fading, setFading] = useState(false);
const [ratePanelPinned, setRatePanelPinned] = useState(false);
+ const reconnecting = reconnectStatus !== null;
+ useEffect(() => {
+ if (reconnecting) setRatePanelPinned(false);
+ }, [reconnecting]);
useEffect(() => {
if (visible) {
@@ -5809,11 +5835,12 @@ function RunningStatusBar({
// side-task / 后台子任务运行中永远当成进行态 (即便上一轮 LLM 留下的 status 文案
// 是 "Done", 此时任务还在跑, 显示 ✓ 完成图标会让用户以为已经做完)。
- const isDone = status === 'Done' && !sideTaskRunning && !backgroundTasksRunning;
+ const isDone = status === 'Done' && !reconnecting && !sideTaskRunning && !backgroundTasksRunning;
// 后台子任务模式的左段文案:上一轮残留的 status(多半是 "Done")在此语义下是
// 误导信息,整体替换为后台运行提示。仅后台 Bash 时用带数量的专属文案 ——
// 「模型用量仍在消耗」对不调模型的 bash 任务是错误陈述。
const displayStatus =
+ reconnectStatus ??
workflowStatus ??
(backgroundTasksRunning
? backgroundBashOnlyCount > 0
@@ -5851,7 +5878,7 @@ function RunningStatusBar({
// suppressContent 或 reduced-motion 期间 shimmer 类/动画被摘,
// onAnimationEnd 不会到来。立即清零播放态,确保运行期关闭减弱动效后
// 下一次真实动静能重新触发呼吸,不必等 visible 先变 false。
- if (!visible || suppressContent || reducedMotion) {
+ if (!visible || suppressContent || reducedMotion || reconnecting) {
// 运行结束把播放态清零,下一轮 turn 的首次动静立即触发而不是误判在播。
shimmerPlayingRef.current = false;
shimmerPendingRef.current = false;
@@ -5867,6 +5894,7 @@ function RunningStatusBar({
visible,
suppressContent,
reducedMotion,
+ reconnecting,
status,
tokenUsage,
outputTokens,
@@ -5887,6 +5915,7 @@ function RunningStatusBar({
generationDurationMs,
generationReliable:
generationReliable &&
+ !reconnecting &&
!sideTaskRunning &&
!backgroundTasksRunning &&
!workflowWaiting,
@@ -5901,7 +5930,7 @@ function RunningStatusBar({
});
const latestRateText = latestRate !== null ? formatRecentOutputTokenRate(latestRate) : null;
const rateText =
- !isHidden && usageMeta.kind === 'rate'
+ !isHidden && !reconnecting && usageMeta.kind === 'rate'
? latestRateText !== null
? t('chat.runningStatus.tokenRate', { rate: latestRateText })
: t('chat.runningStatus.waitingSample')
@@ -5917,12 +5946,13 @@ function RunningStatusBar({
pointerEvents: isHidden ? 'none' : 'auto',
};
const showRatePanel =
- ratePanelPinned ||
- (!workflowWaiting &&
- !sideTaskRunning &&
- !backgroundTasksRunning &&
- Boolean(rateText) &&
- usageMeta.kind === 'rate');
+ !reconnecting &&
+ (ratePanelPinned ||
+ (!workflowWaiting &&
+ !sideTaskRunning &&
+ !backgroundTasksRunning &&
+ Boolean(rateText) &&
+ usageMeta.kind === 'rate'));
// A pinned panel keeps its anchor mounted through idle and subsequent turns.
// 空闲后真正收起,不再给输入框上方留下固定空行。overlay 的 ResizeObserver 会在
// DOM 尺寸变化后补齐 MessageStream 的 bottomPadding,因此不靠硬编码高度制造跳变。
@@ -5949,6 +5979,7 @@ function RunningStatusBar({
// min-w-0(非 shrink-0):让内部 status span 的 truncate 真正生效 —— status 可变长
// (turn-start 带用户名 / tool 进度长串),窄宽时左段截断而非把右段顶出界。
'flex min-w-0 items-center gap-[6px]',
+ reconnecting && 'text-[var(--status-bar-accent)]',
// 隐藏时一律摘所有动画类:动画即便 visibility:hidden 不画也照算样式/合成层,
// 长期累积会复刻 0f8fa84 那次 breathing 在 :root 的内存泄漏。
// 非隐藏时 done 与 shimmer 区别对待:
@@ -5957,12 +5988,14 @@ function RunningStatusBar({
// - done 是 0.4s 一次性 pop(keyframe 已去掉 opacity、只动 transform),turn
// 结束那一刻(isDone 必伴随 !visible)要弹一下,故保持 !isHidden gate;
// 不动 opacity 所以不会盖 fade。
- isHidden ? '' : isDone ? 'status-bar-done' : visible ? 'status-bar-shimmer' : '',
+ isHidden ? '' : isDone ? 'status-bar-done' : visible && !reconnecting ? 'status-bar-shimmer' : '',
)}
style={fadeStyle}
aria-hidden={isHidden}
>
- {isDone ? (
+ {reconnecting ? (
+ <Spinner size={14} />
+ ) : isDone ? (
<Check size={14} className="shrink-0" strokeWidth={2.5} />
) : // 后台子任务模式换 Activity 图标(与 Compacting 换 Layers 同一设计逻辑:
// 图标回答"现在在干嘛")。优先于 isCompacting —— 后者按残留 status 文本
@@ -6038,7 +6071,7 @@ function RunningStatusBar({
<span className="text-13 font-medium text-[var(--status-bar-meta)]">
{elapsedText}
</span>
- {!sideTaskRunning && usageMeta.kind !== 'none' && (
+ {!reconnecting && !sideTaskRunning && usageMeta.kind !== 'none' && (
<>
<span className="text-13 font-medium text-[var(--status-bar-meta)]">
&middot;
diff --git a/apps/desktop/src/renderer/lib/autoResumePresentation.ts b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
new file mode 100644
index 0000000000..dd44de2dcb
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
@@ -0,0 +1,93 @@
+import type { ChatMessage, ContinuationInFlightProjectionCapability } from './makerChatStore';
+
+export interface AutoResumeCardInfo {
+ error?: string;
+ attempt?: number;
+ maxAttempts?: number;
+ sessionTotal?: number;
+ outcome?: 'succeeded' | 'failed';
+}
+
+/** Silent-stop continuations have no interruption context and are not reconnects. */
+export function hasInterruptionContext(info: AutoResumeCardInfo): boolean {
+ return (
+ info.error !== undefined ||
+ info.attempt !== undefined ||
+ info.maxAttempts !== undefined ||
+ info.sessionTotal !== undefined ||
+ info.outcome !== undefined
+ );
+}
+
+export function readAutoResumeInfo(data?: Record<string, unknown>): AutoResumeCardInfo {
+ const num = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
+ return {
+ ...(typeof data?.error === 'string' && data.error.length > 0 ? { error: data.error } : {}),
+ ...(num(data?.attempt) !== undefined ? { attempt: num(data?.attempt) } : {}),
+ ...(num(data?.maxAttempts) !== undefined ? { maxAttempts: num(data?.maxAttempts) } : {}),
+ ...(num(data?.sessionTotal) !== undefined ? { sessionTotal: num(data?.sessionTotal) } : {}),
+ ...(data?.outcome === 'succeeded' || data?.outcome === 'failed'
+ ? { outcome: data.outcome }
+ : {}),
+ };
+}
+
+/** Synthetic continuation inputs own turns; steering messages do not replace that owner. */
+export function findLastUserInputClientId(messages: readonly ChatMessage[]): string | null {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i].role === 'user' && messages[i].delivery !== 'steer') {
+ return messages[i].clientId;
+ }
+ }
+ return null;
+}
+
+/**
+ * Only legacy hosts may fall back to the last user input; newer hosts publish the turn owner.
+ * That legacy heuristic cannot distinguish a Goal turn without a user row from a continuation,
+ * so never apply it to supported/unknown hosts.
+ */
+export function isAutoResumeRowInFlight(args: {
+ isContinuationTurnOwner: boolean;
+ sessionRunning: boolean;
+ isLastUserInput: boolean;
+ projectionCapability: ContinuationInFlightProjectionCapability;
+}): boolean {
+ return (
+ args.isContinuationTurnOwner ||
+ (args.projectionCapability === 'legacy' && args.sessionRunning && args.isLastUserInput)
+ );
+}
+
+/** The composer follows the same live rows and outcomes as the message stream. */
+export function findActiveReconnect(args: {
+ messages: readonly ChatMessage[];
+ sessionRunning: boolean;
+ continuationTurnClientId: string | null;
+ projectionCapability: ContinuationInFlightProjectionCapability;
+}): AutoResumeCardInfo | null {
+ const lastInput =
+ args.projectionCapability === 'legacy' ? findLastUserInputClientId(args.messages) : null;
+ for (let i = args.messages.length - 1; i >= 0; i--) {
+ const message = args.messages[i];
+ if (message.systemCardType === 'auto-resume-pending') {
+ // Also covers backoff: there may not be a running vendor turn yet.
+ return readAutoResumeInfo(message.systemCardData);
+ }
+ if (message.role !== 'user' || message.systemCardType !== 'auto-resume') continue;
+ const info = readAutoResumeInfo(message.systemCardData);
+ if (
+ hasInterruptionContext(info) &&
+ info.outcome === undefined &&
+ isAutoResumeRowInFlight({
+ isContinuationTurnOwner: message.clientId === args.continuationTurnClientId,
+ sessionRunning: args.sessionRunning,
+ isLastUserInput: message.clientId === lastInput,
+ projectionCapability: args.projectionCapability,
+ })
+ )
+ return info;
+ }
+ return null;
+}