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): 对齐计划与被控提醒并修复完成态残留 (#1842)

Kafeifei3a53b1c0fa1b
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 0aacec37db..76cf082302 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -146,6 +146,26 @@ describe('maker:event hot path ordering', () => {
);
});
+ it('persists a terminal Codex plan before clearing its turn-owned lookup maps', () => {
+ const wireSessionSource = extractWireSessionSource();
+ const persistIndex = wireSessionSource.indexOf('persistCodexPlanOnDone(');
+ const barrierIndex = wireSessionSource.indexOf(
+ 'markTurnEndedAfterPersistDrain(session.id);',
+ persistIndex,
+ );
+ const resetIndex = wireSessionSource.indexOf('resetTurnPersistState(session.id);', barrierIndex);
+
+ expect(persistIndex).toBeGreaterThanOrEqual(0);
+ expect(barrierIndex).toBeGreaterThan(persistIndex);
+ expect(resetIndex).toBeGreaterThan(barrierIndex);
+ expect(wireSessionSource.slice(persistIndex - 800, persistIndex)).toContain(
+ 'isContinuationBoundary',
+ );
+ expect(wireSessionSource.slice(persistIndex - 500, persistIndex)).toContain(
+ '!isContinuationBoundary',
+ );
+ });
+
it('defers remote auth island errors until the renderer reports retry failure', () => {
const wireSessionSource = extractWireSessionSource();
const deferredHandler = source.match(
@@ -316,6 +336,8 @@ describe('maker:event hot path ordering', () => {
expectOrder(boundaryBlock, 'consumeLastAssistantPersistId(session.id);', 'consumeLastTopLevelAssistantPersistId(session.id);');
expectOrder(boundaryBlock, 'consumeLastTopLevelAssistantPersistId(session.id);', 'flushOrphanToolResults(session.id, eventAgentMeta);');
expect(boundaryBlock).toContain("event.type === 'done'");
+ expect(boundaryBlock).toContain("event.source !== 'codex'");
+ expect(boundaryBlock).toContain('isSuccessfulCodexDoneEventData(event.data)');
expect(boundaryBlock).toContain('markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId)');
expect(boundaryBlock).toContain('markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId)');
expect(boundaryBlock).toContain('pendingFailedTurnAssistantPersistId.get(session.id)');
@@ -325,6 +347,11 @@ describe('maker:event hot path ordering', () => {
'isPairedFailedTurnDone = true',
"else if (!isPairedFailedTurnDone)",
);
+ expectOrder(
+ boundaryBlock,
+ 'isSuccessfulCodexDoneEventData(event.data)',
+ 'markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId)',
+ );
});
it('rejects stale Agent Island interactions before renderer delivery', () => {
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 976150061d..eac8f150d0 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../localDb/ipc/messages.js', () => ({
broadcastMessageAgentMetaUpdate: vi.fn(async () => true),
+ broadcastMessageRow: vi.fn(),
createMessage: vi.fn(async () => ({}) as unknown),
patchMessageAgentMetaWithResult: vi.fn(async (_sessionId, _clientId, patch) => ({
previous: {},
@@ -45,6 +46,7 @@ vi.mock('../device-link/broadcast-tap.js', () => ({
import {
broadcastMessageAgentMetaUpdate,
+ broadcastMessageRow,
createMessage,
patchMessageAgentMetaWithResult,
updateMessageContent,
@@ -55,6 +57,7 @@ import {
} from '../mcp-integrations/mediaToolResultFallback.js';
import {
onToolUseEvent,
+ persistCodexPlanOnDone,
onToolResultEvent,
onToolResultFullEvent,
prepareSyntheticToolEventForBroadcast,
@@ -63,6 +66,7 @@ import {
onThinkingEvent,
flushAssistantBlock,
flushOrphanToolResults,
+ isSuccessfulCodexDoneEventData,
onTurnErrorEvent,
resetTurnPersistState,
clearSessionPersistState,
@@ -86,6 +90,16 @@ const SUMMARY = 'tool finished';
const flushWrites = () => new Promise((resolve) => setTimeout(resolve, 0));
const broadcastGuard = () => expect.objectContaining({ shouldBroadcast: expect.any(Function) });
+describe('Codex done completion boundary', () => {
+ it('only treats successful terminal data as a completed turn', () => {
+ expect(isSuccessfulCodexDoneEventData({ raw: { status: 'completed' } })).toBe(true);
+ expect(isSuccessfulCodexDoneEventData({ raw: { status: 'interrupted' } })).toBe(false);
+ expect(isSuccessfulCodexDoneEventData({ raw: { status: 'failed' } })).toBe(false);
+ expect(isSuccessfulCodexDoneEventData({ cancelled: true })).toBe(false);
+ expect(isSuccessfulCodexDoneEventData({ raw: { id: 'legacy-turn' } })).toBe(false);
+ });
+});
+
beforeEach(() => {
vi.clearAllMocks();
ownerScopeState.current = true;
@@ -172,6 +186,124 @@ describe('update_plan tool_use persistence', () => {
);
});
+ it('persists a successful turn plan as completed so reload cannot resurrect progress', async () => {
+ const persistId = onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: {
+ explanation: 'keep this field',
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'in_progress' },
+ ],
+ },
+ },
+ null,
+ );
+
+ expect(persistCodexPlanOnDone(SESSION, {
+ raw: { id: 'turn-1', status: 'completed' },
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'in_progress' },
+ ],
+ })).toBe(true);
+
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledWith(
+ SESSION,
+ persistId,
+ {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: {
+ explanation: 'keep this field',
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'completed' },
+ ],
+ },
+ terminalPlanSnapshot: true,
+ },
+ );
+ expect(broadcastMessageRow).toHaveBeenCalledWith(
+ SESSION,
+ expect.any(Object),
+ ownerScopeState.scope,
+ );
+ });
+
+ it('stamps an already-completed plan as terminal at the successful done boundary', async () => {
+ const persistId = onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'plan:turn-complete',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Ship', status: 'completed' }] },
+ },
+ null,
+ );
+
+ expect(persistCodexPlanOnDone(SESSION, {
+ raw: { id: 'turn-complete', status: 'completed' },
+ plan: [{ step: 'Ship', status: 'completed' }],
+ })).toBe(true);
+
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledWith(
+ SESSION,
+ persistId,
+ {
+ toolUseId: 'plan:turn-complete',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Ship', status: 'completed' }] },
+ terminalPlanSnapshot: true,
+ },
+ );
+ expect(broadcastMessageRow).toHaveBeenCalledWith(
+ SESSION,
+ expect.any(Object),
+ ownerScopeState.scope,
+ );
+ });
+
+ it('persists non-success boundaries without inferring completion or touching unrelated turns', async () => {
+ const persistId = onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Wait for user', status: 'in_progress' }] },
+ },
+ null,
+ );
+
+ expect(persistCodexPlanOnDone(SESSION, {
+ raw: { id: 'turn-1', status: 'interrupted' },
+ })).toBe(true);
+ expect(persistCodexPlanOnDone(SESSION, {
+ cancelled: true,
+ raw: { id: 'turn-1', status: 'completed' },
+ })).toBe(true);
+ expect(persistCodexPlanOnDone(SESSION, {
+ raw: { id: 'turn-2', status: 'completed' },
+ })).toBe(false);
+
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledWith(
+ SESSION,
+ persistId,
+ {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Wait for user', status: 'in_progress' }] },
+ turnCompleted: false,
+ },
+ );
+ });
+
it('does not dedupe ordinary repeated tool_use ids', async () => {
const firstPersistId = onToolUseEvent(
SESSION,
diff --git a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
index c52a6a8b99..91c15edc14 100644
--- a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
@@ -106,4 +106,21 @@ describe('runtime-configs', () => {
expect(prompt).not.toMatch(/\$[\w:-]+|\/(?:Users|home)\/|[A-Z]:\\/u);
}
});
+
+ it('asks Claude and Codex to write user-facing plans in plain language', async () => {
+ vi.doMock('../memory-settings-store.js', () => ({
+ readMemorySettings: () => memorySettings,
+ }));
+
+ const { buildDesktopClaudeRuntimeConfig, desktopCodexRuntimeConfig } = await import(
+ '../runtime-configs.js'
+ );
+ const claudeConfig = buildDesktopClaudeRuntimeConfig(() => 'http://127.0.0.1:1234');
+
+ for (const prompt of [claudeConfig.systemPrompt, desktopCodexRuntimeConfig.systemPrompt]) {
+ expect(prompt).toContain('## User-facing plans');
+ expect(prompt).toContain('Write for a general user, not as internal engineering notes.');
+ expect(prompt).toContain('Name the real action and visible result instead.');
+ }
+ });
});
diff --git a/apps/desktop/src/main/maker-host/claude-system-prompt.md b/apps/desktop/src/main/maker-host/claude-system-prompt.md
index e69de29bb2..33bde1f9b3 100644
--- a/apps/desktop/src/main/maker-host/claude-system-prompt.md
+++ b/apps/desktop/src/main/maker-host/claude-system-prompt.md
@@ -0,0 +1,9 @@
+## User-facing plans
+
+When you create or update a plan that the user can see:
+
+- Write for a general user, not as internal engineering notes.
+- Use natural language that says what you will do, what it applies to, and what the user will get from it.
+- Prefer the user's own words. Keep technical names only when they help identify the exact thing being changed.
+- Do not pad plans with generic filler such as "confirm requirements", "inspect the implementation", "make necessary changes", "run validation", or "perform final checks". Name the real action and visible result instead.
+- For example, prefer "Find where the plan appears above the chat box" or "Reopen the task and make sure the finished plan does not return."
diff --git a/apps/desktop/src/main/maker-host/codex-system-prompt.md b/apps/desktop/src/main/maker-host/codex-system-prompt.md
index e69de29bb2..33bde1f9b3 100644
--- a/apps/desktop/src/main/maker-host/codex-system-prompt.md
+++ b/apps/desktop/src/main/maker-host/codex-system-prompt.md
@@ -0,0 +1,9 @@
+## User-facing plans
+
+When you create or update a plan that the user can see:
+
+- Write for a general user, not as internal engineering notes.
+- Use natural language that says what you will do, what it applies to, and what the user will get from it.
+- Prefer the user's own words. Keep technical names only when they help identify the exact thing being changed.
+- Do not pad plans with generic filler such as "confirm requirements", "inspect the implementation", "make necessary changes", "run validation", or "perform final checks". Name the real action and visible result instead.
+- For example, prefer "Find where the plan appears above the chat box" or "Reopen the task and make sure the finished plan does not return."
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 57ed2a95bb..613551c4bb 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -309,6 +309,7 @@ import {
flushOrphanToolResults,
getLastAssistantTranscriptUuid,
getSessionDbAgentKind,
+ isSuccessfulCodexDoneEventData,
markAssistantTurnCompleted,
markAssistantTurnFailed,
noteAgentMeta,
@@ -318,6 +319,7 @@ import {
onAssistantTextEvent,
onInteractionMessage,
onInteractionResolved,
+ persistCodexPlanOnDone,
onThinkingEvent,
onToolResultEvent,
onToolResultFullEvent,
@@ -3675,7 +3677,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 在同一 durable FIFO 内先盖 turn seal、再复用 local-db:messages:created 广播
// 更新后的完整行。失败轮的 paired done 只复用 id 做 usage 记账,不能把
// terminal error 已写的 false seal 覆盖成 true、让施工播报重新进入标题素材。
- if (event.type !== 'done') {
+ // Codex 的 interrupted / failed 同样以 done 收尾;即使没有配套 error,也必须
+ // 写 false,避免历史计划兼容逻辑把用户主动停止的半截计划推成全部完成。
+ const isSuccessfulDone =
+ event.type === 'done' &&
+ (event.source !== 'codex' || isSuccessfulCodexDoneEventData(event.data));
+ if (!isSuccessfulDone) {
void markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId);
} else if (!isPairedFailedTurnDone) {
void markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId);
@@ -3742,6 +3749,22 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// A claim-bearing done seals this SDK segment, but the product turn is
// still running and may emit another continuation segment. Reset the
// per-SDK-turn persistence maps while deferring the logical turn marker.
+ if (!isContinuationBoundary && event.source === 'codex' && event.type === 'done') {
+ // Renderer applies this terminal snapshot immediately. Persist the
+ // same state before sealing the persist queue and clearing the
+ // turn-owned lookup maps. The drain barrier below must include this
+ // write, otherwise app exit can still leave an in-progress plan.
+ persistCodexPlanOnDone(
+ session.id,
+ event.data as
+ | {
+ plan?: unknown;
+ raw?: { id?: unknown; status?: unknown };
+ }
+ | null
+ | undefined,
+ );
+ }
if (!isContinuationBoundary) {
markTurnEndedAfterPersistDrain(session.id);
}
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 7370c18baa..878448e30a 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -31,8 +31,10 @@ import { createId } from '@paralleldrive/cuid2';
import { BrowserWindow } from 'electron';
import { desc, eq } from 'drizzle-orm';
+import { resolveCodexPlanSnapshotOnDone } from '@cindy/maker-shared/message-render';
import {
+ broadcastMessageRow,
broadcastMessageAgentMetaUpdate,
createMessage as createDbMessage,
patchMessageAgentMetaWithResult,
@@ -282,6 +284,20 @@ export function markAssistantTurnFailed(
return markAssistantTurnBoundary(sessionId, clientId, false);
}
+/**
+ * Codex emits `done` for every terminal turn, including user interruption and
+ * failure. Only the successful variant may create a persisted completion seal;
+ * otherwise historical plan recovery would later treat partial work as done.
+ */
+export function isSuccessfulCodexDoneEventData(data: unknown): boolean {
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return false;
+ const done = data as { cancelled?: unknown; raw?: unknown };
+ if (done.cancelled === true) return false;
+ if (!done.raw || typeof done.raw !== 'object' || Array.isArray(done.raw)) return false;
+ const status = (done.raw as { status?: unknown }).status;
+ return status === 'completed';
+}
+
/**
* 给一条自动续跑(中断自愈)的 user 消息补上**结果**。
*
@@ -569,6 +585,65 @@ export function onToolUseEvent(
return persistId;
}
+/**
+ * Persist the same terminal Codex plan convergence that the renderer applies
+ * immediately on `done`. Without this DB update, switching tasks or reloading
+ * the renderer resurrects the last in-progress snapshot and leaves the pinned
+ * plan visible forever even though the turn completed successfully.
+ *
+ * The turn id is the ownership boundary: only `plan:<raw.id>` may be updated.
+ * Failed, interrupted, or unrelated turns never infer completion. A matching
+ * failed turn still stamps `turnCompleted: false` on its plan row because the
+ * turn may have ended before any assistant row existed to carry that seal.
+ */
+export function persistCodexPlanOnDone(
+ sessionId: string,
+ data:
+ | { cancelled?: unknown; plan?: unknown; raw?: { id?: unknown; status?: unknown } }
+ | null
+ | undefined,
+): boolean {
+ const turnId = typeof data?.raw?.id === 'string' ? data.raw.id : null;
+ if (!turnId) return false;
+
+ const toolUseId = `plan:${turnId}`;
+ const infoMap = toolUseInfoBySession.get(sessionId);
+ const info = infoMap?.get(toolUseId);
+ const persistId = updatableToolUsePersistIdBySession.get(sessionId)?.get(toolUseId);
+ if (!info || info.toolName !== 'update_plan' || !persistId) return false;
+
+ const input = info.input && typeof info.input === 'object' && !Array.isArray(info.input)
+ ? info.input as Record<string, unknown>
+ : null;
+ if (!input || !Array.isArray(input.plan)) return false;
+
+ const isSuccessfulTerminal = isSuccessfulCodexDoneEventData(data);
+ const nextPlan =
+ resolveCodexPlanSnapshotOnDone(input.plan, data?.plan, isSuccessfulTerminal) ??
+ (isSuccessfulTerminal ? null : input.plan);
+ if (!nextPlan) return false;
+ // Even when Codex already emitted the exact completed/empty plan, stamp the
+ // durable row at done. Renderer must distinguish this authoritative write
+ // from an older ordinary DB echo that merely happens to look completed.
+ const nextInput = { ...input, plan: nextPlan };
+ infoMap?.set(toolUseId, { ...info, input: nextInput });
+ enqueueWrite(`codex_plan_done:${sessionId}:${persistId}`, async (ownerScope) => {
+ const updated = await updateDbMessageContent(sessionId, persistId, {
+ toolUseId,
+ toolName: 'update_plan',
+ input: nextInput,
+ ...(isSuccessfulTerminal
+ ? { terminalPlanSnapshot: true }
+ : { turnCompleted: false }),
+ });
+ // Reuse the existing upsert-style row broadcast so a renderer that mounts
+ // between `done` and this queued write, plus remote mirrors, receives the
+ // durable terminal snapshot instead of keeping its stale local copy.
+ if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
+ });
+ return true;
+}
+
/**
* Main 侧合成 tool 事件也必须遵守 renderer 的展示契约:
* tool_result / tool_result_full 只有带 persistId + resolvedContent 才会渲染。
diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
index c1ec1381f4..5c2544f7f3 100644
--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
@@ -12,69 +12,122 @@ const routeSource = read('features/cc-agent/OrcaWorkflowRoute.tsx');
const workerPanelSource = read('features/cc-agent/OrcaWorkerPanel.tsx');
const mainLayoutSource = read('components/layout/MainLayout.tsx');
const controlledBannerSource = read('features/remote-device/ControlledBanner.tsx');
+const pinnedPlanSource = read('components/new-chat/PinnedPlanPanel.tsx');
+const todoListSource = read('components/chat/TodoListCard.tsx');
describe('controlled banner placement', () => {
- it('renders the controlled banner in the input status bar for routed chat or explicit opt-in', () => {
+ it('switches the controlled banner between the centered group and token metadata', () => {
expect(sessionViewSource).toContain('showControlledBanner?: boolean;');
expect(sessionViewSource).toContain('showControlledBanner = false');
expect(sessionViewSource).toContain(
- 'const showInlineControlledBanner = ownsRoute || showControlledBanner;',
+ 'const showComposerControlledBanner = ownsRoute || showControlledBanner;',
);
- expect(sessionViewSource).toMatch(
- /centerSlot=\{\s*showInlineControlledBanner\s*\?\s*<ControlledBanner placement="statusbar" \/>\s*:\s*null\s*\}/,
+ expect(sessionViewSource).toContain(
+ 'const hasControlledBanner = showComposerControlledBanner && controlledBy.length > 0;',
);
expect(sessionViewSource).toContain(
- '<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />',
+ 'const controlledBannerCollapsed = useComposerCollapsed(sessionId ?? null);',
);
- });
-
- it('keeps the statusbar center slot geometrically centered above lower-priority side text', () => {
- expect(sessionViewSource).toContain('const STATUS_BAR_CENTER_SLOT_MAX_WIDTH = 420;');
- expect(sessionViewSource).toContain('const STATUS_BAR_CENTER_SLOT_WIDTH_RATIO = 0.5;');
expect(sessionViewSource).toContain(
- 'function getControlledBannerMaxWidth(inputWidth?: number): number',
+ 'const showExpandedControlledBanner = hasControlledBanner && !controlledBannerCollapsed;',
);
- expect(sessionViewSource).toContain('(inputWidth - 16) * STATUS_BAR_CENTER_SLOT_WIDTH_RATIO');
+ expect(sessionViewSource).toContain('placement="composer"');
+ expect(sessionViewSource).toContain('sessionId={sessionId ?? null}');
+ expect(sessionViewSource).toContain('rightLeadingSlot={');
+ expect(sessionViewSource).toContain('hasControlledBanner && controlledBannerCollapsed ? (');
expect(sessionViewSource).toContain(
- 'const centerSlotMaxWidth = getControlledBannerMaxWidth(inputWidth);',
+ '{(!pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed)) && (',
);
+ expect(sessionViewSource).toContain('suppressContent={Boolean(pendingPlanReview)}');
expect(sessionViewSource).toContain(
- 'const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);',
+ 'const isHidden = suppressContent || (!showContent && !visible);',
);
- expect(sessionViewSource).toContain('grid-cols-[minmax(0,1fr)_minmax(0,auto)_minmax(0,1fr)]');
+ expect(sessionViewSource).toContain('{showExpandedControlledBanner && (');
+ expect(sessionViewSource).toContain('rightLeadingSlot?: ReactNode;');
+ expect(sessionViewSource).toContain('{rightLeadingSlot}');
+ expect(sessionViewSource).toContain('data-running-status-meta="true"');
+ expect(sessionViewSource).not.toContain('className="mx-auto flex h-9 shrink-0 items-center"');
+ });
+
+ it('keeps only the collapsed breathing light anchored before token metadata', () => {
+ expect(sessionViewSource).toContain('const CONTROLLED_BANNER_MAX_WIDTH = 420;');
+ expect(sessionViewSource).toContain('const CONTROLLED_BANNER_WIDTH_RATIO = 0.5;');
expect(sessionViewSource).toContain(
- 'className="z-10 flex min-w-0 max-w-full items-center justify-center px-2"',
+ 'function getControlledBannerMaxWidth(inputWidth?: number): number',
);
- expect(sessionViewSource).toContain('style={{ maxWidth: centerSlotMaxWidth }}');
+ expect(sessionViewSource).toContain('(inputWidth - 16) * CONTROLLED_BANNER_WIDTH_RATIO');
expect(sessionViewSource).toContain(
- 'className="flex min-w-0 items-center justify-self-end gap-[6px]"',
+ 'const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);',
+ );
+ expect(sessionViewSource).toContain('if (isHidden && !rightLeadingSlot) return null;');
+ expect(controlledBannerSource).toContain("placement?: 'floating' | 'inline' | 'composer';");
+ expect(controlledBannerSource).toContain(
+ 'className="pointer-events-auto flex min-w-0 max-w-full shrink justify-end"',
+ );
+ expect(controlledBannerSource).not.toContain(
+ 'className="pointer-events-auto flex max-w-full shrink-0 -translate-y-0.5 justify-end"',
+ );
+ expect(controlledBannerSource).toContain(
+ 'className="session-status-breathing h-1.5 w-1.5 rounded-full"',
);
expect(controlledBannerSource).toContain(
- 'flex min-w-0 max-w-full select-none items-center gap-2 overflow-hidden',
+ 'const collapsedComposerSessionIds = new Set<string>();',
);
expect(controlledBannerSource).toContain(
- 'className="min-w-0 truncate text-[12px] text-[var(--text-primary)]"',
+ 'export function useComposerCollapsed(sessionId: string | null): boolean',
);
+ expect(controlledBannerSource).toContain('data-controlled-banner-collapse="true"');
+ expect(controlledBannerSource).toContain('data-controlled-banner="collapsed"');
+ expect(controlledBannerSource).toContain('data-controlled-banner-chip="true"');
expect(controlledBannerSource).toContain(
- 'className="flex min-w-0 max-w-[45%] shrink items-center gap-1',
+ "'pointer-events-auto flex h-7 min-w-0 max-w-full select-none items-center gap-2 overflow-hidden rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-0',",
);
- expect(controlledBannerSource).toContain('<span className="min-w-0 truncate">');
- expect(controlledBannerSource).not.toContain("placement === 'statusbar' && 'my-");
- expect(sessionViewSource).not.toContain('grid-cols-[1fr_auto_1fr]');
- expect(sessionViewSource).not.toContain('absolute left-1/2');
+ expect(sessionViewSource).toContain(
+ 'className="flex min-w-0 items-center justify-self-end gap-2"',
+ );
+ expect(sessionViewSource).not.toContain('<div className="-translate-y-0.5">');
+ expect(controlledBannerSource).toContain(
+ 'onClick={() => setComposerCollapsed(composerSessionId, false)}',
+ );
+ expect(controlledBannerSource).toContain("t('remoteDevice.revokeAccess')");
+ expect(sessionViewSource).not.toContain('rightSlot=');
+ expect(controlledBannerSource).not.toContain("placement === 'statusbar'");
+ expect(sessionViewSource).not.toContain('centerSlot=');
});
- it('uses the same width cap for the plan-review inline fallback', () => {
- expect(controlledBannerSource).toContain('maxWidth?: number;');
- expect(controlledBannerSource).toContain('style={maxWidth == null ? undefined : { maxWidth }}');
+ it('centers the plan and expanded controlled chip as one non-overlapping flex group', () => {
+ expect(sessionViewSource.match(/<PinnedPlanPanel/g)).toHaveLength(1);
+ expect(sessionViewSource).toContain(
+ 'className="mx-auto grid grid-cols-1 grid-rows-1 items-center"',
+ );
+ expect(sessionViewSource).toContain('className="col-start-1 row-start-1"');
+ expect(sessionViewSource).toContain('data-composer-center-group="true"');
expect(sessionViewSource).toContain(
- '<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />',
+ 'className="pointer-events-none relative z-10 col-start-1 row-start-1 flex max-w-full -translate-y-1 items-center justify-center gap-2"',
+ );
+ expect(sessionViewSource).toContain('className="mb-0"');
+ expect(pinnedPlanSource).toContain(
+ "cn('mb-1.5 flex h-8 w-auto max-w-full shrink-0 items-center', className)",
);
+ expect(todoListSource).toContain(
+ 'className="pointer-events-none flex w-auto shrink-0 justify-center"',
+ );
+ expect(todoListSource).toContain('data-plan-pill-anchor="true"');
+ expect(todoListSource).toContain('data-plan-flyout-positioner="composer"');
+ expect(sessionViewSource).not.toContain('fitContent=');
+ expect(pinnedPlanSource).not.toContain('fitContent');
+ expect(todoListSource).not.toContain('fitContent');
+ });
+
+ it('caps the right-aligned composer chip without changing the input width', () => {
+ expect(controlledBannerSource).toContain('maxWidth?: number;');
+ expect(controlledBannerSource).toContain('style={maxWidth == null ? undefined : { maxWidth }}');
+ expect(sessionViewSource).toContain('maxWidth={controlledBannerMaxWidth}');
});
it('opts in only route-owned chat views, not Worker panes or embedded doc rails', () => {
expect(sessionViewSource).toContain(
- 'const showInlineControlledBanner = ownsRoute || showControlledBanner;',
+ 'const showComposerControlledBanner = ownsRoute || showControlledBanner;',
);
expect(routeSource).not.toContain('<CCAgentSessionView');
expect(routeSource).not.toContain('showControlledBanner');
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 5d20180496..3f333a8ba0 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -664,6 +664,281 @@ describe('makerChatStore text delta batching', () => {
});
});
+ it('accepts the terminal persisted plan when the renderer mounted with stale progress', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'in_progress' },
+ ],
+ },
+ },
+ },
+ persistId: 'plan-message-1',
+ });
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: serverMessage({
+ id: 'plan-row-1',
+ clientId: 'plan-message-1',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ terminalPlanSnapshot: true,
+ input: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'completed' },
+ ],
+ },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({
+ clientId: 'plan-message-1',
+ toolInput: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'completed' },
+ ],
+ },
+ });
+ });
+
+ it('accepts a terminal persisted empty plan instead of restoring stale progress', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-clear',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Wait for user', status: 'in_progress' }] },
+ },
+ },
+ persistId: 'plan-message-clear',
+ });
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: serverMessage({
+ id: 'plan-row-clear',
+ clientId: 'plan-message-clear',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-clear',
+ toolName: 'update_plan',
+ terminalPlanSnapshot: true,
+ input: { plan: [] },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({
+ clientId: 'plan-message-clear',
+ toolInput: { plan: [] },
+ });
+ });
+
+ it('restores a failed turn boundary from its persisted plan row', () => {
+ const [mapped] = makerChatStore.__mapServerMessagesForTest([
+ serverMessage({
+ id: 'plan-row-interrupted',
+ clientId: 'plan-message-interrupted',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-interrupted',
+ toolName: 'update_plan',
+ turnCompleted: false,
+ input: { plan: [{ step: 'Wait for user', status: 'in_progress' }] },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ ]);
+
+ expect(mapped).toMatchObject({
+ clientId: 'plan-message-interrupted',
+ role: 'tool_use',
+ toolName: 'update_plan',
+ turnCompleted: false,
+ });
+ });
+
+ it('does not let an unmarked completed-plan echo replace newer live work', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-race',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Initial work', status: 'completed' }] },
+ },
+ },
+ persistId: 'plan-message-race',
+ });
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-race',
+ toolName: 'update_plan',
+ input: {
+ plan: [
+ { step: 'Initial work', status: 'completed' },
+ { step: 'Follow-up work', status: 'in_progress' },
+ ],
+ },
+ },
+ },
+ persistId: 'plan-message-race',
+ });
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: serverMessage({
+ id: 'plan-row-race',
+ clientId: 'plan-message-race',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-race',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'Initial work', status: 'completed' }] },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({
+ toolInput: {
+ plan: [
+ { step: 'Initial work', status: 'completed' },
+ { step: 'Follow-up work', status: 'in_progress' },
+ ],
+ },
+ });
+ });
+
+ it('does not let an unmarked empty-plan echo replace newer live work', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-empty-race',
+ toolName: 'update_plan',
+ input: { plan: [] },
+ },
+ },
+ persistId: 'plan-message-empty-race',
+ });
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-empty-race',
+ toolName: 'update_plan',
+ input: { plan: [{ step: 'New work', status: 'in_progress' }] },
+ },
+ },
+ persistId: 'plan-message-empty-race',
+ });
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: serverMessage({
+ id: 'plan-row-empty-race',
+ clientId: 'plan-message-empty-race',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-empty-race',
+ toolName: 'update_plan',
+ input: { plan: [] },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({
+ toolInput: { plan: [{ step: 'New work', status: 'in_progress' }] },
+ });
+ });
+
+ it('still ignores a stale open-plan DB echo after live progress moved forward', () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'completed' },
+ ],
+ },
+ },
+ },
+ persistId: 'plan-message-1',
+ });
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: serverMessage({
+ id: 'plan-row-1',
+ clientId: 'plan-message-1',
+ sessionId: SESSION_ID,
+ role: 'tool_use',
+ content: {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ input: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'in_progress' },
+ ],
+ },
+ },
+ createdAt: '2026-08-05T00:00:00.000Z',
+ }),
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]).toMatchObject({
+ toolInput: {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'completed' },
+ ],
+ },
+ });
+ });
+
it('flushes pending text before a permission interaction request on the separate IPC channel', () => {
const snapshots: Array<{ roles: string[]; pendingPermission: string | null }> = [];
const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {
diff --git a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
index 010e264d64..a7bfbead04 100644
--- a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
@@ -257,6 +257,27 @@ describe('makerChatStore per-turn 费用', () => {
expect(usageOnly?.turnCompleted).toBe(true);
});
+ it('历史加载:明确失败 seal 优先于旧 usage 收尾兜底', async () => {
+ vi.mocked(messageService.list).mockResolvedValueOnce([
+ serverMessage({
+ clientId: 'failed-with-usage',
+ agentMeta: {
+ turnCompleted: false,
+ turnUsageDetails: GPT_DETAILS,
+ },
+ }),
+ ]);
+ makerChatStore.ensureInitialMessages(SID);
+ await flush();
+ await flush();
+
+ const failed = makerChatStore
+ .getSnapshot(SID)
+ .messages.find((m) => m.clientId === 'failed-with-usage');
+ expect(failed?.turnUsageDetails).toEqual(GPT_DETAILS);
+ expect(failed?.turnCompleted).toBe(false);
+ });
+
it('device-link 旧历史:缺少持久化累计值时按完整用户轮投影', async () => {
vi.mocked(messageService.list).mockResolvedValueOnce([
serverMessage({
diff --git a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
index ff3952a35d..a880220cf8 100644
--- a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
@@ -8,8 +8,10 @@
* - 鼠标悬停时临时展开,移开即收起;点击/Enter 后固定展开,再次触发立即收起。
* 浮层绝对定位(bottom-full),不改变 composer overlay 的实测高度,
* 消息流不会因 hover 抖动。
- * - 浮层行:completed 灰(check 圆圈),in_progress 高亮(虚线圆圈 + 旋转),
+ * - 浮层行:completed 灰(check 圆圈),in_progress 高亮(静态虚线圆圈),
* pending 正常前景色(空心圆圈)。
+ * - 胶囊图标使用静态灰度进度圆环表达当前步骤位置,不使用持续旋转或 pulse;
+ * 进度变化只通过圆环长度的短过渡反馈。
*
* 颜色沿用 ToolCallCard 同套 token(设计系统零阴影,浮层用 1px 边框):
* --msg-tool-card-text: primary(icon、in_progress/pending 文本)
@@ -22,7 +24,6 @@ import { useTranslation } from 'react-i18next';
import type { MessageRenderTodoItem } from '@cindy/maker-shared/message-render';
import { cn } from '@/lib/utils';
-import { Spinner } from '@/components/ui/spinner';
// ---------------------------------------------------------------------------
// Types — normalized agent plan/todo item
@@ -32,18 +33,78 @@ export type TodoItem = MessageRenderTodoItem;
type FlyoutOpenMode = 'closed' | 'hover' | 'pinned';
+/**
+ * 静态灰度进度圆环。
+ *
+ * 这里没有 loading 语义:圆环表达计划当前位于第几步,而不是告诉用户“还在转”。
+ * SVG 本身不挂常驻动画;步骤变化时只过渡 stroke-dashoffset,避免在聊天底部制造
+ * 持续运动和额外注意力竞争。
+ */
+function ProgressRing({
+ progress,
+ size,
+ strokeWidth = 1.75,
+ className,
+}: {
+ progress: number;
+ size: number;
+ strokeWidth?: number;
+ className?: string;
+}) {
+ const clampedProgress = Math.min(1, Math.max(0, progress));
+ const radius = (size - strokeWidth) / 2;
+ const circumference = 2 * Math.PI * radius;
+ const dashOffset = circumference * (1 - clampedProgress);
+
+ return (
+ <svg
+ data-plan-progress-ring="true"
+ width={size}
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ className={cn('shrink-0', className)}
+ aria-hidden="true"
+ focusable="false"
+ >
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ r={radius}
+ fill="none"
+ stroke="var(--msg-tool-card-chevron)"
+ strokeWidth={strokeWidth}
+ opacity={0.45}
+ />
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ r={radius}
+ fill="none"
+ stroke="var(--msg-tool-card-text)"
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeDasharray={circumference}
+ strokeDashoffset={dashOffset}
+ transform={`rotate(-90 ${size / 2} ${size / 2})`}
+ className="transition-[stroke-dashoffset] duration-[var(--motion-base,200ms)] ease-[var(--motion-ease-move,cubic-bezier(0.4,0,0.2,1))] motion-reduce:transition-none"
+ />
+ </svg>
+ );
+}
+
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export function TodoListCard({
todos,
- animated = true,
maxWidth,
}: {
todos: TodoItem[];
- /** When false, in_progress items render the dashed circle but no pulse / spin —
- * used after the session stops so frozen todos don't keep "spinning". */
+ /**
+ * Kept for source compatibility with older callers. Plan progress is intentionally
+ * static now, so this flag no longer enables an infinite animation.
+ */
animated?: boolean;
/** Composer/chat column width. Keeps the flyout inside clipped compact panes. */
maxWidth?: number;
@@ -93,17 +154,17 @@ export function TodoListCard({
? pendingIndex
: Math.min(completed, total - 1);
const currentStep = allDone ? total : currentIndex + 1;
- const hasActive = todos.some((todo) => todo.status === 'in_progress');
+ const stepProgress = total > 0 ? currentStep / total : 0;
const flyoutMaxWidth =
typeof maxWidth === 'number' && Number.isFinite(maxWidth) && maxWidth > 0
? `${Math.floor(maxWidth)}px`
: null;
return (
- <div className="flex w-full justify-center">
+ <div className="pointer-events-none flex w-auto shrink-0 justify-center">
<div
ref={cardRef}
- className="relative inline-flex items-center justify-center"
+ className="pointer-events-auto inline-flex items-center justify-center"
onMouseEnter={() => {
setOpenMode((current) => (current === 'closed' ? 'hover' : current));
}}
@@ -111,93 +172,85 @@ export function TodoListCard({
setOpenMode((current) => (current === 'hover' ? 'closed' : current));
}}
>
- {/* Collapsed pill — `[icon] Step N / M`,点击/Enter 也可切换浮层(键盘可达)。 */}
- <button
- type="button"
- onClick={() => {
- setOpenMode((current) => (current === 'pinned' ? 'closed' : 'pinned'));
- }}
- aria-controls={flyoutId}
- aria-expanded={revealed}
- className={cn(
- 'flex items-center gap-2 rounded-full',
- 'border border-[var(--msg-tool-card-border)]',
- 'bg-[var(--msg-tool-card-bg)]',
- 'px-[14px] py-[8px]',
- 'cursor-pointer select-none',
- 'hover:opacity-80 transition-opacity',
- )}
+ <div
+ data-plan-pill-anchor="true"
+ className="pointer-events-auto relative inline-flex items-center justify-center"
>
- {allDone ? (
- <CircleCheck
- size={14}
- strokeWidth={2}
- className="shrink-0 text-[var(--msg-tool-card-text)]"
- />
- ) : hasActive ? (
- <Spinner
- icon={CircleDashed}
- size={14}
- strokeWidth={2}
- spinning={animated}
- className="shrink-0 text-[var(--msg-tool-card-text)]"
- />
- ) : (
- <Circle
- size={14}
- strokeWidth={2}
- className="shrink-0 text-[var(--msg-tool-card-text)]"
- />
- )}
- <span className="text-13 leading-none tabular-nums text-[var(--msg-tool-card-text)]">
- {t('chat.planPill.step', { current: currentStep, total })}
- </span>
- </button>
+ {/* Collapsed pill — `[icon] Step N / M`,点击/Enter 也可切换浮层(键盘可达)。 */}
+ <button
+ type="button"
+ onClick={() => {
+ setOpenMode((current) => (current === 'pinned' ? 'closed' : 'pinned'));
+ }}
+ aria-controls={flyoutId}
+ aria-expanded={revealed}
+ className={cn(
+ 'flex items-center gap-2 rounded-full',
+ 'border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)]',
+ // 28px 紧凑高度:计划槽位仍保持 32px,上下各留约 2px,避免胶囊贴住输入框。
+ 'px-[14px] py-[6px]',
+ 'cursor-pointer select-none',
+ 'hover:opacity-80 transition-opacity',
+ )}
+ >
+ {allDone ? (
+ <CircleCheck
+ size={14}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
+ ) : (
+ <ProgressRing progress={stepProgress} size={16} strokeWidth={2} />
+ )}
+ <span className="text-13 leading-none tabular-nums text-[var(--msg-tool-card-text)]">
+ {t('chat.planPill.step', { current: currentStep, total })}
+ </span>
+ </button>
- {/* Hover flyout — 完整清单向上浮出;绝对定位不占布局高度,消息流不抖动。 */}
- {renderFlyout && (
- <>
+ {/* 只让 hover 热区跟随胶囊;完整浮层则相对 composer 中央区域定位。 */}
+ {renderFlyout && (
<div
- className="absolute bottom-full left-1/2 h-2 min-w-full -translate-x-1/2"
+ className="absolute bottom-full left-1/2 h-3 min-w-full -translate-x-1/2"
aria-hidden="true"
/>
+ )}
+ </div>
+
+ {/* Hover flyout — 相对 composer 中央区域居中,被控提示把胶囊左推时也不会越界。 */}
+ {renderFlyout && (
+ <div
+ id={flyoutId}
+ data-plan-flyout-positioner="composer"
+ className={cn(
+ 'absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2',
+ 'w-max',
+ flyoutMaxWidth === null && 'min-w-[220px] max-w-[min(420px,calc(100vw-32px))]',
+ )}
+ style={
+ flyoutMaxWidth === null
+ ? undefined
+ : {
+ minWidth: `min(220px, ${flyoutMaxWidth})`,
+ maxWidth: `min(420px, ${flyoutMaxWidth}, calc(100vw - 32px))`,
+ }
+ }
+ >
<div
- id={flyoutId}
+ aria-hidden={!revealed}
className={cn(
- 'absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2',
- 'w-max',
- flyoutMaxWidth === null && 'min-w-[220px] max-w-[min(420px,calc(100vw-32px))]',
+ 'w-full origin-bottom overflow-hidden rounded-[12px]',
+ 'border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)]',
+ revealed ? 'animate-float-in' : 'animate-float-out',
)}
- style={
- flyoutMaxWidth === null
- ? undefined
- : {
- minWidth: `min(220px, ${flyoutMaxWidth})`,
- maxWidth: `min(420px, ${flyoutMaxWidth}, calc(100vw - 32px))`,
- }
- }
+ onAnimationEnd={() => {
+ if (!revealed) setRenderFlyout(false);
+ }}
>
- <div
- aria-hidden={!revealed}
- className={cn(
- 'w-full origin-bottom overflow-hidden rounded-[12px]',
- 'border border-[var(--msg-tool-card-border)]',
- 'bg-[var(--msg-tool-card-bg)]',
- revealed ? 'animate-float-in' : 'animate-float-out',
- )}
- onAnimationEnd={() => {
- if (!revealed) setRenderFlyout(false);
- }}
- >
- <div className="flex max-h-[280px] flex-col gap-[2px] overflow-y-auto px-[14px] py-[10px]">
- {todos.map((todo, i) => (
- <div
- key={i}
- className={cn(
- 'flex h-[30px] items-center gap-[10px]',
- todo.status === 'in_progress' && animated && 'animate-pulse',
- )}
- >
+ <div className="flex max-h-[280px] flex-col gap-[2px] overflow-y-auto px-[14px] py-[10px]">
+ {todos.map((todo, i) => (
+ <div key={i} className="flex h-[30px] items-center gap-[10px]">
{/* Icon */}
{todo.status === 'completed' && (
<CircleCheck
@@ -207,12 +260,10 @@ export function TodoListCard({
/>
)}
{todo.status === 'in_progress' && (
- <Spinner
- icon={CircleDashed}
+ <CircleDashed
size={18}
strokeWidth={1.5}
- spinning={animated}
- className="text-[var(--msg-tool-card-text)]"
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
/>
)}
{todo.status === 'pending' && (
@@ -237,12 +288,11 @@ export function TodoListCard({
>
{todo.content}
</span>
- </div>
- ))}
- </div>
+ </div>
+ ))}
</div>
</div>
- </>
+ </div>
)}
</div>
</div>
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
index ea20ca186d..21c575d438 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TodoListCard.test.tsx
@@ -20,16 +20,45 @@ const TODOS = [
afterEach(cleanup);
describe('TodoListCard flyout interaction', () => {
- it('uses the pending icon when no step is currently in progress', () => {
+ it('uses a compact 28px pill inside the 32px plan slot', () => {
+ render(<TodoListCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 2' });
+ expect(trigger.classList.contains('py-[6px]')).toBe(true);
+ expect(trigger.classList.contains('py-[8px]')).toBe(false);
+ });
+
+ it('shrinks to the plan pill width when it shares the centered row', () => {
+ const { container } = render(<TodoListCard todos={TODOS} />);
+
+ expect(container.firstElementChild?.classList.contains('w-auto')).toBe(true);
+ expect(container.firstElementChild?.classList.contains('shrink-0')).toBe(true);
+ expect(container.firstElementChild?.classList.contains('w-full')).toBe(false);
+ });
+
+ it('uses a static grayscale progress ring without spin or pulse', () => {
const { container } = render(
<TodoListCard todos={[{ content: 'Queued step', status: 'pending' }]} animated />,
);
const trigger = screen.getByRole('button', { name: 'Step 1 / 1' });
- expect(trigger.querySelector('svg.lucide-circle')).not.toBeNull();
- expect(trigger.querySelector('svg.lucide-circle-dashed')).toBeNull();
- expect(container.querySelector('svg.lucide-circle-dashed')).toBeNull();
+ expect(container.firstElementChild?.classList.contains('pointer-events-none')).toBe(true);
+ expect(trigger.parentElement?.classList.contains('pointer-events-auto')).toBe(true);
+ expect(trigger.querySelector('svg[data-plan-progress-ring="true"]')).not.toBeNull();
+ expect(container.querySelector('.animate-spin')).toBeNull();
+ expect(container.querySelector('.animate-pulse')).toBeNull();
+ });
+
+ it('keeps the active row static when the flyout is open', () => {
+ const { container } = render(<TodoListCard todos={TODOS} animated />);
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 2' });
+ fireEvent.mouseEnter(trigger.parentElement as HTMLElement);
+
+ expect(container.querySelector('svg.lucide-circle-dashed')).not.toBeNull();
+ expect(container.querySelector('.animate-spin')).toBeNull();
+ expect(container.querySelector('.animate-pulse')).toBeNull();
});
it('opens transiently on hover and closes when the pointer leaves', () => {
@@ -121,6 +150,22 @@ describe('TodoListCard flyout interaction', () => {
expect(animatedContent.classList.contains('-translate-x-1/2')).toBe(false);
});
+ it('positions the flyout outside the shifted plan pill anchor', () => {
+ render(<TodoListCard todos={TODOS} animated={false} />);
+
+ const trigger = screen.getByRole('button', { name: 'Step 1 / 2' });
+ const pillAnchor = trigger.closest('[data-plan-pill-anchor="true"]') as HTMLElement;
+ fireEvent.mouseEnter(pillAnchor);
+
+ const flyoutId = trigger.getAttribute('aria-controls') as string;
+ const positioner = document.getElementById(flyoutId) as HTMLElement;
+
+ expect(positioner.dataset.planFlyoutPositioner).toBe('composer');
+ expect(positioner.parentElement).toBe(pillAnchor.parentElement);
+ expect(positioner.parentElement).not.toBe(pillAnchor);
+ expect(pillAnchor.querySelector('.h-3')).not.toBeNull();
+ });
+
it('hides the flyout from assistive technology while its exit animation remains mounted', () => {
render(<TodoListCard todos={TODOS} animated={false} />);
diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
index 42ba4d0781..79f4e43b36 100644
--- a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
@@ -14,6 +14,7 @@ import { findLatestMessageTodoInsertion } from '@cindy/maker-shared/message-rend
import { TodoListCard } from '@/components/chat/TodoListCard';
import type { ChatMessage } from '@/lib/makerChatStore';
+import { cn } from '@/lib/utils';
const COMPLETED_PLAN_VISIBLE_MS = 2_000;
@@ -24,16 +25,18 @@ export function PinnedPlanPanel({
width,
taskHistoryMayBeIncomplete = false,
visible = true,
+ className,
}: {
sessionId: string | null;
messages: readonly ChatMessage[];
- /** 会话仍在流式时进行中项呼吸/旋转;停止后冻结。 */
+ /** 保留旧调用方的兼容参数;计划胶囊现在始终使用静态灰度进度环。 */
animated: boolean;
/** 与 composer 同宽(inputWidth),胶囊在该宽度内居中,浮层不超出。 */
width: number;
taskHistoryMayBeIncomplete?: boolean;
/** 交互卡接管底部区域时只隐藏视图,保留完成后的计时与已收起状态。 */
visible?: boolean;
+ className?: string;
}): React.ReactElement | null {
const insertion = useMemo(
() => findLatestMessageTodoInsertion(messages, { taskHistoryMayBeIncomplete }),
@@ -46,9 +49,7 @@ export function PinnedPlanPanel({
);
const completedAtMs = insertion?.updatedAtMs ?? Date.parse(insertion?.createdAt ?? '');
const persistedCompletionDeadlineMs =
- allDone && Number.isFinite(completedAtMs)
- ? completedAtMs + COMPLETED_PLAN_VISIBLE_MS
- : null;
+ allDone && Number.isFinite(completedAtMs) ? completedAtMs + COMPLETED_PLAN_VISIBLE_MS : null;
const [fallbackCompletionVisibility, setFallbackCompletionVisibility] = useState<{
identity: string;
deadlineMs: number;
@@ -103,7 +104,10 @@ export function PinnedPlanPanel({
return null;
return (
- <div className="mb-1.5 max-w-full" style={{ width }}>
+ <div
+ data-pinned-plan="true"
+ className={cn('mb-1.5 flex h-8 w-auto max-w-full shrink-0 items-center', className)}
+ >
{/* key 按 plan session 锚定:新计划重挂载,浮层/进度从头开始。 */}
<TodoListCard
key={insertion.key}
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
index 593adde031..66505c4a4d 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PinnedPlanPanel.test.tsx
@@ -260,6 +260,28 @@ describe('PinnedPlanPanel completed plan lifetime', () => {
expect(screen.queryByTestId('plan-pill')).toBeNull();
});
+ it('keeps a legacy open Codex plan when its old completed seal is ambiguous', () => {
+ vi.setSystemTime(T0 + 10_000);
+ const completedAssistant: ChatMessage = {
+ clientId: 'answer-1',
+ role: 'assistant',
+ content: 'Dev server is running.',
+ createdAt: new Date(T0 + 1_000).toISOString(),
+ turnCompleted: true,
+ };
+
+ render(
+ <PinnedPlanPanel
+ sessionId="legacy-open-plan"
+ messages={[planMessage('in_progress'), completedAssistant]}
+ animated={false}
+ width={400}
+ />,
+ );
+
+ expect(screen.queryByTestId('plan-pill')).not.toBeNull();
+ });
+
it('falls back to a component-local lifetime when the completion timestamp is missing', () => {
render(
<PinnedPlanPanel
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index ce8d1b376f..6b78458d13 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -30,10 +30,7 @@ import {
isCodexResumeNotReadyProjectionError,
type AgentInputReference,
} from '@cindy/maker-shared/agent-input-projection';
-import {
- connectedProvidersForAgent,
- providerOffersModel,
-} from '@cindy/model-providers';
+import { connectedProvidersForAgent, providerOffersModel } from '@cindy/model-providers';
import { useProportionalWidth } from '@/hooks/useProportionalWidth';
import {
Activity,
@@ -59,10 +56,7 @@ import { GoalIndicator } from '@/components/new-chat/GoalIndicator';
import { PinnedPlanPanel } from '@/components/new-chat/PinnedPlanPanel';
import { sessionsStore } from '@/lib/sessionsStore';
import { useStopOrcaCollab } from './hooks/useStopOrcaCollab';
-import {
- useWorkerProjection,
- useWorkerProjectionOwner,
-} from './hooks/workerProjectionStore';
+import { useWorkerProjection, useWorkerProjectionOwner } from './hooks/workerProjectionStore';
import { CreateWorkerPopover, type CreateWorkerForm } from './CreateWorkerPopover';
import { createWorkerLabel } from './workerLabel';
import { TakeoverMask } from '@/components/new-chat/TakeoverMask';
@@ -128,7 +122,11 @@ import { useRemoteSessionLoading } from '@/features/cc-agent/hooks/useRemoteSess
import { RemoteSessionBanner } from './RemoteSessionBanner';
import { decideRemoteSessionExit } from './remoteSessionExit';
import { RemoteSessionLoading } from './RemoteSessionLoading';
-import { ControlledBanner } from '@/features/remote-device/ControlledBanner';
+import {
+ ControlledBanner,
+ useComposerCollapsed,
+ useControlledBy,
+} from '@/features/remote-device/ControlledBanner';
import { useAnimatedNumber } from '@/hooks/useAnimatedNumber';
import { loadAllCommands, dispatchCommand, type UnifiedCommand } from '@/lib/slashCommands';
import * as sessionService from '@/lib/sessionService';
@@ -325,7 +323,7 @@ interface CCAgentSessionViewProps {
sessionIdProp?: string;
compact?: boolean;
orcaMode?: boolean;
- /** 在输入区状态栏中央显示被控端 Banner。普通路由自动显示;协同 Lead pane 显式传入。 */
+ /** 在输入区显示被控端提示。普通路由自动显示;完整态居中,折叠态位于 token 左侧。 */
showControlledBanner?: boolean;
/**
* 工具行采用紧凑布局 (flex-wrap 兜底)。
@@ -586,7 +584,11 @@ export function CCAgentSessionView({
// 「全屏聊天视图」这个实例拥有右栏开关 / 声明右栏在场;内嵌复用实例(doc 模式
// chat rail / 协同 worker 面板,带 sessionIdProp 或处于 compact/orca 语境)不参与。
const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;
- const showInlineControlledBanner = ownsRoute || showControlledBanner;
+ const showComposerControlledBanner = ownsRoute || showControlledBanner;
+ const controlledBy = useControlledBy();
+ const hasControlledBanner = showComposerControlledBanner && controlledBy.length > 0;
+ const controlledBannerCollapsed = useComposerCollapsed(sessionId ?? null);
+ const showExpandedControlledBanner = hasControlledBanner && !controlledBannerCollapsed;
// 平台分流:mac 右栏开关放在 ContentHeader 右端(见 ContentHeader.tsx),Windows
// 放在下方 chip 栈第一行。两端都靠 ownsRoute 限定只在全屏聊天视图出现。
const isMac = window.electronAPI?.platform === 'darwin';
@@ -2786,8 +2788,8 @@ export function CCAgentSessionView({
isCodexResumeNotReadyProjectionError(detail)
? t('chat.errorBanner.codexResumeNotReady')
: ipcError?.code === 'FORK_UNSUPPORTED_HISTORY'
- ? t('chat.userMessage.forkErrors.unsupportedHistory')
- : detail,
+ ? t('chat.userMessage.forkErrors.unsupportedHistory')
+ : detail,
);
} finally {
setForkStripEncryptedRunning(false);
@@ -3372,38 +3374,81 @@ export function CCAgentSessionView({
{/* Solid background zone */}
<div className="pointer-events-auto flex w-full flex-col items-center bg-[hsl(var(--content-area))] pb-5">
- {/* Running Status Bar (F-SDK-3) — hidden while a plan review is pending (FP-7)。
- turn 结束但后台子任务仍在调模型时,状态栏保持点亮(shimmer 呼吸)显示
- 后台运行文案 + 右侧「全部停止」入口 —— 替代原独立横幅(Lizi 拍板:
- 不新增信息栏,复用状态栏)。 */}
- {!pendingPlanReview && (
- <RunningStatusBar
- key={sessionId}
- status={agentStatus.status}
- tokenUsage={agentStatus.tokenUsage}
- startedAt={agentStatus.startedAt}
- visible={agentStatus.isRunning || backgroundTasksActive}
- inputWidth={inputWidth}
- sideTaskRunning={agentStatus.sideTaskRunning ?? false}
- backgroundTasksRunning={backgroundTasksActive}
- // 仅后台 Bash 在跑(无模型调用)时换专属文案 + 温和停止语义:
- // 逐任务 stopTask,不关常驻子进程。proxy 信号在时维持原语义
- // (关子进程止损,bash 任务随之终止,无需再逐个停)。
- backgroundBashOnlyCount={
- backgroundActivity.active ? 0 : backgroundBash.tasks.length
- }
- backgroundStopping={backgroundActivity.stopping || backgroundBash.stopping}
- onStopBackgroundTasks={() => {
- if (backgroundActivity.active) void backgroundActivity.stopAll();
- else void backgroundBash.stopAll();
- }}
- // 被控端可见性 chip 嵌进状态栏中央槽位,与 thinking / 时间 token 同行
- // (不再单独占一行)。中央槽位独立于状态栏淡入淡出 → 空闲时仍显示。
- centerSlot={
- showInlineControlledBanner ? <ControlledBanner placement="statusbar" /> : null
- }
- />
- )}
+ {/* 单行 composer 状态层:RunningStatusBar 与中央胶囊组合叠在同一个 grid row。
+ 展开态由「计划 + 完整被控提示」组成真实 flex 组合共同居中,被控提示会把计划
+ 向左挤且不会互相覆盖;折叠态计划恢复单独居中,呼吸灯移到 token 统计左侧。 */}
+ <div
+ className="mx-auto grid grid-cols-1 grid-rows-1 items-center"
+ style={{ width: inputWidth }}
+ >
+ {(!pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed)) && (
+ <RunningStatusBar
+ key={sessionId}
+ status={agentStatus.status}
+ tokenUsage={agentStatus.tokenUsage}
+ startedAt={agentStatus.startedAt}
+ visible={!pendingPlanReview && (agentStatus.isRunning || backgroundTasksActive)}
+ inputWidth={inputWidth}
+ sideTaskRunning={agentStatus.sideTaskRunning ?? false}
+ backgroundTasksRunning={backgroundTasksActive}
+ // 仅后台 Bash 在跑(无模型调用)时换专属文案 + 温和停止语义:
+ // 逐任务 stopTask,不关常驻子进程。proxy 信号在时维持原语义
+ // (关子进程止损,bash 任务随之终止,无需再逐个停)。
+ backgroundBashOnlyCount={
+ backgroundActivity.active ? 0 : backgroundBash.tasks.length
+ }
+ backgroundStopping={backgroundActivity.stopping || backgroundBash.stopping}
+ suppressContent={Boolean(pendingPlanReview)}
+ onStopBackgroundTasks={() => {
+ if (backgroundActivity.active) void backgroundActivity.stopAll();
+ else void backgroundBash.stopAll();
+ }}
+ rightLeadingSlot={
+ hasControlledBanner && controlledBannerCollapsed ? (
+ <ControlledBanner
+ placement="composer"
+ maxWidth={controlledBannerMaxWidth}
+ sessionId={sessionId ?? null}
+ />
+ ) : null
+ }
+ className="col-start-1 row-start-1"
+ />
+ )}
+ <div
+ data-composer-center-group="true"
+ className="pointer-events-none relative z-10 col-start-1 row-start-1 flex max-w-full -translate-y-1 items-center justify-center gap-2"
+ >
+ <PinnedPlanPanel
+ sessionId={sessionId ?? null}
+ messages={messages}
+ animated={isStreaming}
+ width={inputWidth}
+ taskHistoryMayBeIncomplete={
+ !historyLoaded || hasMoreMessages || historyWindowHasIsland
+ }
+ visible={
+ !(
+ pendingPlanReview ||
+ pendingPermission ||
+ pendingAskUser ||
+ pendingPluginSetup ||
+ pendingIssueConfirm ||
+ pendingRenameSessionsConfirm ||
+ pendingGhostGrantConfirm
+ )
+ }
+ className="mb-0"
+ />
+ {showExpandedControlledBanner && (
+ <ControlledBanner
+ placement="composer"
+ maxWidth={controlledBannerMaxWidth}
+ sessionId={sessionId ?? null}
+ />
+ )}
+ </div>
+ </div>
{/* Error display.
- agentKind 传到 ErrorBanner 让 codex 401 / Missing bearer 不仅在远端
@@ -3559,13 +3604,6 @@ export function CCAgentSessionView({
className="mx-auto flex flex-col items-center gap-[10px]"
style={{ width: inputWidth }}
>
- {/* 被控端可见性:常规情况下 chip 已并入 RunningStatusBar 中央槽位(见上)。
- plan-review 时 RunningStatusBar 不渲染,这里回退到独占一行的 inline,
- 让被控提示在 plan 卡片上方仍可见。 */}
- {showInlineControlledBanner && pendingPlanReview && (
- <ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />
- )}
-
{/* FP-7 / F-PERM-2 / F7.4: mutually exclusive prompts.
Plan review takes precedence — the SDK won't interleave it with
other tool calls, but explicit priority guards against layout
@@ -3654,31 +3692,6 @@ export function CCAgentSessionView({
</InteractionPromptHost>
{/* 会话内 /goal 进行中状态条(composer 上方);无 goal 时返回 null 不占位。 */}
<GoalIndicator sessionId={sessionId} />
- {/* Codex IDE 扩展式常驻计划面板 —— 计划在流内不再渲染,这里是唯一
- 呈现处:钉在输入框上方原地更新。任意 pending interaction(计划
- 审核 / 权限 / 提问 / 插件配置 / 各类确认卡)接管底部区时隐藏:
- 胶囊的悬停浮层向上展开,会盖住交互卡内容(条件集与下方 ternary
- 的静默判定保持一致)。 */}
- <PinnedPlanPanel
- sessionId={sessionId ?? null}
- messages={messages}
- animated={isStreaming}
- width={inputWidth}
- taskHistoryMayBeIncomplete={
- !historyLoaded || hasMoreMessages || historyWindowHasIsland
- }
- visible={
- !(
- pendingPlanReview ||
- pendingPermission ||
- pendingAskUser ||
- pendingPluginSetup ||
- pendingIssueConfirm ||
- pendingRenameSessionsConfirm ||
- pendingGhostGrantConfirm
- )
- }
- />
{/* 互斥:有任意 pending interaction 时,下方 takeover/overlay/ChatInput
全部静默 — 跟改造前 ternary 链 (Plan ? : Perm ? : Ask ? :
Takeover ? : ChatInput) 的语义一致。
@@ -4110,17 +4123,14 @@ function HandoffSourcePill({
// ---------------------------------------------------------------------------
const STATUS_BAR_FADE_MS = 400;
-const STATUS_BAR_CENTER_SLOT_MAX_WIDTH = 420;
-const STATUS_BAR_CENTER_SLOT_WIDTH_RATIO = 0.5;
+const CONTROLLED_BANNER_MAX_WIDTH = 420;
+const CONTROLLED_BANNER_WIDTH_RATIO = 0.5;
function getControlledBannerMaxWidth(inputWidth?: number): number {
- if (inputWidth == null) return STATUS_BAR_CENTER_SLOT_MAX_WIDTH;
+ if (inputWidth == null) return CONTROLLED_BANNER_MAX_WIDTH;
return Math.max(
0,
- Math.min(
- (inputWidth - 16) * STATUS_BAR_CENTER_SLOT_WIDTH_RATIO,
- STATUS_BAR_CENTER_SLOT_MAX_WIDTH,
- ),
+ Math.min((inputWidth - 16) * CONTROLLED_BANNER_WIDTH_RATIO, CONTROLLED_BANNER_MAX_WIDTH),
);
}
@@ -4135,7 +4145,9 @@ function RunningStatusBar({
backgroundBashOnlyCount = 0,
backgroundStopping = false,
onStopBackgroundTasks,
- centerSlot = null,
+ rightLeadingSlot = null,
+ suppressContent = false,
+ className,
}: {
status: string;
tokenUsage: number;
@@ -4166,20 +4178,16 @@ function RunningStatusBar({
backgroundStopping?: boolean;
/** 「全部停止」入口(关闭常驻 CC 子进程,会话可续)。 */
onStopBackgroundTasks?: () => void;
- /**
- * 中央槽位 —— 渲染在左侧状态与右侧 elapsed/tokens 之间、水平居中。
- * 关键:它**独立于**左右两段的淡入淡出/隐藏(下方 fadeStyle 只作用于左右),
- * 所以即便 agent 空闲、状态栏整体淡出占位时,这里的内容(被控提示 chip)仍
- * 持续可见。左右两段只是低优先级信息,窄宽时允许收缩 / 被中央 chip 覆盖。
- */
- centerSlot?: ReactNode;
+ /** 独立于运行态淡出的右侧前置槽位;折叠后的被控呼吸灯固定在 token 统计左侧。 */
+ rightLeadingSlot?: ReactNode;
+ /** 交互卡接管 composer 时立即隐藏旧运行文案/token,只保留折叠呼吸灯。 */
+ suppressContent?: boolean;
+ className?: string;
}) {
const { t } = useTranslation();
- // `showContent` controls whether real content is rendered.
- // We intentionally NEVER return null — instead we fall back to a fixed-height
- // placeholder so the overlay's ResizeObserver sees a stable height and
- // MessageStream's bottomPadding doesn't change, eliminating the layout jump
- // that was visible when the status bar disappeared.
+ // `showContent` controls whether real content is rendered. During the short
+ // linger/fade window we keep the row's height stable; once it is fully idle the
+ // component returns null below so the composer does not retain an empty line.
const [showContent, setShowContent] = useState(visible);
const [fading, setFading] = useState(false);
@@ -4216,7 +4224,7 @@ function RunningStatusBar({
return () => clearInterval(interval);
}, [startedAt]);
- const isHidden = !showContent && !visible;
+ const isHidden = suppressContent || (!showContent && !visible);
// side-task / 后台子任务运行中永远当成进行态 (即便上一轮 LLM 留下的 status 文案
// 是 "Done", 此时任务还在跑, 显示 ✓ 完成图标会让用户以为已经做完)。
@@ -4249,35 +4257,29 @@ function RunningStatusBar({
? `${(animatedTokens / 1000).toFixed(1)}k tokens`
: `${animatedTokens} tokens`;
- // 淡入淡出/隐藏占位样式 —— 只作用于左(状态)、右(elapsed/tokens)两段;
- // 中央槽位(centerSlot)不套此样式,故空闲淡出时其内容(被控提示 chip)仍可见。
- // visibility:hidden 只隐藏不收高 → 左右两段始终占位,外层高度恒定,overlay 的
- // ResizeObserver 看到的高度不变,MessageStream 的 bottomPadding 不抖。
+ // 淡入淡出/隐藏占位样式 —— 同时作用于左(状态)、右(elapsed/tokens)两段。
+ // visibility:hidden 只隐藏不收高,让 linger / fade 阶段稳定;淡出结束后整个
+ // RunningStatusBar 才收起为 null。
const fadeStyle: CSSProperties = {
visibility: isHidden ? 'hidden' : 'visible',
opacity: isHidden ? 0 : fading ? 0 : 1,
transition: isHidden ? 'none' : `opacity ${STATUS_BAR_FADE_MS}ms ease-out`,
pointerEvents: isHidden ? 'none' : 'auto',
};
- const centerSlotMaxWidth = getControlledBannerMaxWidth(inputWidth);
+ // 空闲后真正收起,不再给输入框上方留下固定空行。overlay 的 ResizeObserver 会在
+ // DOM 尺寸变化后补齐 MessageStream 的 bottomPadding,因此不靠硬编码高度制造跳变。
+ if (isHidden && !rightLeadingSlot) return null;
- // Always render the full DOM structure — never return null or a differently-
- // shaped placeholder. Height is determined by real content + padding, so it
- // never changes regardless of visibility state. The overlay ResizeObserver
- // therefore sees a stable height and MessageStream's bottomPadding stays put.
- //
- // 三段式布局:左(状态)/ 中(centerSlot)/ 右(elapsed·tokens)。
- // 中央槽位用三列 grid 居中:左右列都是 minmax(0,1fr),中列 minmax(0,auto)。
- // 中列再用输入框宽度比例 + 明确 maxWidth 封顶,避免长设备名把 banner 撑成超长条;
- // 同时它仍参与正常文档流,会按 chip 高度撑出原有上下留白。
+ // 两段式布局:左(运行状态) / 右(elapsed·tokens)。
// - 左段 min-w-0(可收缩):status 并非短枚举 —— turn-start 文案带用户名(可含中文长句)、
// claude tool 进度会拼成 `mcp__x__y running...` 长串,窄宽时左段靠 span truncate;
- // - 右段 justify-self-end + min-w-0:elapsed / token 是低优先级信息,必要时可溢出
- // 但不会改变中列几何中心;中列 z-10 让 chip 视觉优先。
- // 外层只管布局 / 宽度 / 高度,恒可见。
+ // - 右段 justify-self-end + min-w-0:elapsed / token 是低优先级信息,必要时可溢出。
return (
<div
- className="mx-auto grid select-none grid-cols-[minmax(0,1fr)_minmax(0,auto)_minmax(0,1fr)] items-center px-2 py-[6px]"
+ className={cn(
+ 'mx-auto grid select-none grid-cols-[minmax(0,1fr)_auto] items-center px-2 py-[6px]',
+ className,
+ )}
style={{ width: inputWidth }}
>
<div
@@ -4317,63 +4319,60 @@ function RunningStatusBar({
)}
<span className="truncate text-[13px] font-medium">{displayStatus}</span>
</div>
- {/* 中央槽位(几何真居中):被控提示 chip 等。maxWidth 封顶 + max-w-full 让长设备名
- 在窄宽时收缩,chip 靠自带 max-w-full + 内部 truncate 截断;不套 fadeStyle
- 故空闲淡出时仍持续可见。 */}
- <div
- className="z-10 flex min-w-0 max-w-full items-center justify-center px-2"
- style={{ maxWidth: centerSlotMaxWidth }}
- >
- {centerSlot}
- </div>
- {/* pen 里右侧是分离的 4 个节点:elapsed / · / arrow-down / tokens,gap 6px。
+ {/* 右侧先放不随运行态淡出的被控呼吸灯,再放 elapsed / · / arrow-down / tokens。
side-task (mivo 等) 运行时只显示 elapsed, 不带 token 行 —— 这类任务不
走 LLM, 显示残留 token 计数会误导用户以为也耗了 token。 */}
- <div
- className="flex min-w-0 items-center justify-self-end gap-[6px]"
- style={fadeStyle}
- aria-hidden={isHidden}
- >
- {backgroundTasksRunning ? (
- // 后台子任务模式:elapsed 是上一轮 turn 的残留计时、tokens 是残留计数,
- // 都不成立 —— 整段换成「全部停止」入口(原横幅唯一操作,横幅已删)。
- <button
- type="button"
- onClick={onStopBackgroundTasks}
- disabled={backgroundStopping || !onStopBackgroundTasks}
- className={cn(
- 'flex shrink-0 items-center gap-1 text-[13px] font-medium',
- 'text-[var(--text-primary)] hover:opacity-70 transition-opacity',
- 'disabled:opacity-50 disabled:cursor-not-allowed',
- )}
- title={t(
- backgroundBashOnlyCount > 0
- ? 'chat.backgroundActivity.stopBashTitle'
- : 'chat.backgroundActivity.stopAllTitle',
- )}
+ <div className="flex min-w-0 items-center justify-self-end gap-2">
+ {rightLeadingSlot}
+ {!isHidden && (
+ <div
+ data-running-status-meta="true"
+ className="flex min-w-0 items-center gap-[6px]"
+ style={fadeStyle}
+ aria-hidden={isHidden}
>
- <Square size={12} />
- {backgroundStopping
- ? t('chat.backgroundActivity.stopping')
- : t('chat.backgroundActivity.stopAll')}
- </button>
- ) : (
- <>
- <span className="text-[13px] font-medium text-[var(--status-bar-meta)]">
- {elapsedText}
- </span>
- {!sideTaskRunning && (
+ {backgroundTasksRunning ? (
+ // 后台子任务模式:elapsed 是上一轮 turn 的残留计时、tokens 是残留计数,
+ // 都不成立 —— 整段换成「全部停止」入口(原横幅唯一操作,横幅已删)。
+ <button
+ type="button"
+ onClick={onStopBackgroundTasks}
+ disabled={backgroundStopping || !onStopBackgroundTasks}
+ className={cn(
+ 'flex shrink-0 items-center gap-1 text-[13px] font-medium',
+ 'text-[var(--text-primary)] hover:opacity-70 transition-opacity',
+ 'disabled:opacity-50 disabled:cursor-not-allowed',
+ )}
+ title={t(
+ backgroundBashOnlyCount > 0
+ ? 'chat.backgroundActivity.stopBashTitle'
+ : 'chat.backgroundActivity.stopAllTitle',
+ )}
+ >
+ <Square size={12} />
+ {backgroundStopping
+ ? t('chat.backgroundActivity.stopping')
+ : t('chat.backgroundActivity.stopAll')}
+ </button>
+ ) : (
<>
<span className="text-[13px] font-medium text-[var(--status-bar-meta)]">
- &middot;
- </span>
- <ArrowDown size={13} className="shrink-0 text-[var(--status-bar-meta)]" />
- <span className="text-[13px] font-medium text-[var(--status-bar-meta)]">
- {tokenText}
+ {elapsedText}
</span>
+ {!sideTaskRunning && (
+ <>
+ <span className="text-[13px] font-medium text-[var(--status-bar-meta)]">
+ &middot;
+ </span>
+ <ArrowDown size={13} className="shrink-0 text-[var(--status-bar-meta)]" />
+ <span className="text-[13px] font-medium text-[var(--status-bar-meta)]">
+ {tokenText}
+ </span>
+ </>
+ )}
</>
)}
- </>
+ </div>
)}
</div>
</div>
diff --git a/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx b/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
index 9ab225dadb..89f02412a7 100644
--- a/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
+++ b/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
@@ -2,22 +2,22 @@
* ControlledBanner —— 被控端可见性指示。
*
* 当本机正在被同账号的其它设备远程控制时,在聊天输入框上方或全局兜底位置显示一条 chip:
- * 「正在被 <设备名> 控制」+「撤销访问权限」按钮。订阅 device-link:controlled-state push,
- * 初值经 getState().controlledBy。主聊天页嵌进 RunningStatusBar 中央槽位(statusbar)
- * 与 thinking 状态 / 时间 token 同行;其它页面全局挂载(MainLayout),与
- * FeishuConflictDialogHost 同级。
+ * 「动态状态点 + 正在被 <设备名> 控制 + 撤销访问权限」。主聊天页展开时与计划胶囊
+ * 组成一组共同居中;点胶囊内的叉后,只把呼吸灯放到 RunningStatusBar 右侧 token 统计
+ * 之前。其它页面全局挂载(MainLayout),与 FeishuConflictDialogHost 同级。状态订阅来自
+ * device-link:controlled-state push,初值经 getState().controlledBy。
*
* 单设备时按钮调 revoke(deviceId)(逐设备黑名单,持久化);多设备时跳转到设置页,
* 让用户逐台查看 / 撤销。撤销后控制端连不回来,需被控端到设置「控制本机的设备」里手动恢复。
*
* chip 文字不可选中(select-none) —— 它是状态指示而非可复制内容;hover 弹 Tip,展示
- * 完整设备名 + 远程控制逻辑说明(statusbar 窄宽时设备名会 truncate,完整名只在 Tip 里看)。
+ * 完整设备名 + 远程控制逻辑说明。
*/
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
-import { Eye, MonitorOff } from 'lucide-react';
+import { Eye, MonitorOff, X } from 'lucide-react';
import { toast } from '@/lib/toast';
import { createLogger } from '@/lib/logger';
@@ -35,16 +35,48 @@ interface Controller {
/**
* 共享的「谁在控制本机」状态 —— 提到组件之上、模块级单例缓存 + 单一订阅。
*
- * 为什么:ControlledBanner 会在 statusbar / inline / floating 三种 placement 间切换挂载
- * (典型:plan-review 切换时 statusbar 实例 unmount、inline 实例全新 mount)。若每个实例各自
+ * 为什么:ControlledBanner 会在 composer / floating placement 间切换挂载。若每个实例各自
* 持 useState([]) + 异步 getState() 回填,新挂载的实例首帧 controllers 必为空 → 返回 null →
- * 被控 chip 闪空 1 帧、其所在行高度随之抖动。把状态缓存到模块级,任何实例挂载时同步读到上次
- * 最新值,首帧即有内容,消除 remount 闪空。
+ * 被控 chip 闪空 1 帧。把状态缓存到模块级,任何实例挂载时同步读到上次最新值,首帧即有内容。
*/
let cachedControllers: Controller[] = [];
let pushSubscribed = false;
const controllerListeners = new Set<(c: Controller[]) => void>();
+// composer 被控提示的折叠状态只在当前 renderer 生命周期内保存,并严格按 sessionId
+// 分桶。它不是全局偏好,不写 localStorage / DB / 服务端;切换任务时直接读取对应桶,
+// 因此不会把 A 任务的折叠态闪到 B 任务首帧。
+const collapsedComposerSessionIds = new Set<string>();
+const collapsedComposerListeners = new Set<() => void>();
+
+function subscribeCollapsedComposer(listener: () => void) {
+ collapsedComposerListeners.add(listener);
+ return () => collapsedComposerListeners.delete(listener);
+}
+
+function setComposerCollapsed(sessionId: string, collapsed: boolean) {
+ if (collapsedComposerSessionIds.has(sessionId) === collapsed) return;
+ if (collapsed) collapsedComposerSessionIds.add(sessionId);
+ else collapsedComposerSessionIds.delete(sessionId);
+ for (const listener of collapsedComposerListeners) listener();
+}
+
+export function useComposerCollapsed(sessionId: string | null): boolean {
+ const getSnapshot = useCallback(
+ () => sessionId !== null && collapsedComposerSessionIds.has(sessionId),
+ [sessionId],
+ );
+ return useSyncExternalStore(subscribeCollapsedComposer, getSnapshot, getSnapshot);
+}
+
+export function __resetControlledBannerForTests(): void {
+ cachedControllers = [];
+ pushSubscribed = false;
+ controllerListeners.clear();
+ collapsedComposerSessionIds.clear();
+ collapsedComposerListeners.clear();
+}
+
function emitControllers(next: Controller[]) {
cachedControllers = next;
for (const listener of controllerListeners) listener(next);
@@ -54,6 +86,7 @@ function emitControllers(next: Controller[]) {
// 生命周期:这是单条轻量 IPC 监听,换来跨 remount 的状态连续性,故不在每个实例卸载时反复拆装。
function ensureControllerSubscription() {
if (pushSubscribed) return;
+ if (typeof window === 'undefined' || !window.electronAPI?.deviceLink) return;
pushSubscribed = true;
void window.electronAPI.deviceLink
.getState()
@@ -63,7 +96,11 @@ function ensureControllerSubscription() {
}
// 读共享的被控状态:首帧同步返回模块级缓存(remount 不再闪空),后续随 push 更新。
-function useControlledBy(): Controller[] {
+/**
+ * 读取当前被控端控制者列表,供聊天布局在挂载 composer 被控行前判断是否需要占位。
+ * 状态仍由本模块的单例订阅维护,调用方不会建立额外 IPC 监听。
+ */
+export function useControlledBy(): Controller[] {
const [controllers, setControllers] = useState<Controller[]>(cachedControllers);
useEffect(() => {
ensureControllerSubscription();
@@ -81,21 +118,26 @@ function useControlledBy(): Controller[] {
* 控制被控提示的呈现方式:
* - 'floating' : 全局悬浮兜底(右下角,带 shadow),非主聊天路由用。
* - 'inline' : 独占一行、水平居中(带 w-full 包裹),plan-review 等场景用。
- * - 'statusbar' : 裸 chip,嵌进 RunningStatusBar 中央槽位,由状态栏三段式布局负责居中。
+ * - 'composer' : 主聊天输入区的完整 chip / 折叠呼吸灯,具体挂载位置由会话布局决定。
*/
interface ControlledBannerProps {
- placement?: 'floating' | 'inline' | 'statusbar';
+ placement?: 'floating' | 'inline' | 'composer';
maxWidth?: number;
+ /** composer placement 的任务 ID,用于隔离完整 / 呼吸灯折叠态。 */
+ sessionId?: string | null;
}
export function ControlledBanner({
placement = 'floating',
maxWidth,
+ sessionId = null,
}: ControlledBannerProps = {}) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
const navigate = useNavigate();
const controllers = useControlledBy();
+ const composerSessionId = placement === 'composer' ? sessionId : null;
+ const composerCollapsed = useComposerCollapsed(composerSessionId);
if (controllers.length === 0) return null;
@@ -142,17 +184,45 @@ export function ControlledBanner({
</div>
);
+ const collapsedIndicator = composerSessionId ? (
+ <Tip text={tooltipContent}>
+ <button
+ type="button"
+ data-controlled-banner="collapsed"
+ aria-label={t('remoteDevice.expandControlledNotice', { label })}
+ onClick={() => setComposerCollapsed(composerSessionId, false)}
+ className={cn(
+ // 20px 布局盒与右侧元信息行同高,避免把整行从 32px 撑到 40px;
+ // ::before 把鼠标热区无布局地扩回 28px。
+ "pointer-events-auto relative flex h-5 w-5 shrink-0 items-center justify-center rounded-full before:absolute before:-inset-1 before:content-['']",
+ 'text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <span
+ // 圆点的几何中心与文字盒中心相同,但字形/箭头的可见像素重心更低;
+ // 单独下移 1px 做光学对齐,不改变按钮盒、状态行或计划位置。
+ className="session-status-breathing h-2 w-2 translate-y-[2px] rounded-full"
+ style={{ backgroundColor: 'var(--status-bar-accent)' }}
+ aria-hidden
+ />
+ </button>
+ </Tip>
+ ) : null;
+
const chip = (
<Tip text={tooltipContent}>
<div
+ data-controlled-banner-chip="true"
className={cn(
// select-none:被控提示是状态指示,不应像正文一样可被鼠标框选复制。
- 'pointer-events-auto flex min-w-0 max-w-full select-none items-center gap-2 overflow-hidden rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-1.5',
+ // h-7 与计划胶囊同为 28px;显式去掉纵向 padding,避免撤销按钮把主体撑到 32px。
+ 'pointer-events-auto flex h-7 min-w-0 max-w-full select-none items-center gap-2 overflow-hidden rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-0',
placement === 'floating' && 'shadow-[var(--shadow-menu)]',
)}
>
<span
- className="h-1.5 w-1.5 animate-pulse rounded-full"
+ className="session-status-breathing h-1.5 w-1.5 rounded-full"
style={{ backgroundColor: 'var(--status-bar-accent)' }}
aria-hidden
/>
@@ -162,11 +232,32 @@ export function ControlledBanner({
onClick={hasMultipleControllers ? onViewControllers : () => void onRevoke()}
className="flex min-w-0 max-w-[45%] shrink items-center gap-1 rounded-full px-2 py-0.5 text-[12px] text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]"
>
- {hasMultipleControllers ? <Eye size={13} className="shrink-0" /> : <MonitorOff size={13} className="shrink-0" />}
+ {hasMultipleControllers ? (
+ <Eye size={13} className="shrink-0" />
+ ) : (
+ <MonitorOff size={13} className="shrink-0" />
+ )}
<span className="min-w-0 truncate">
- {hasMultipleControllers ? t('remoteDevice.viewControllers') : t('remoteDevice.revokeAccess')}
+ {hasMultipleControllers
+ ? t('remoteDevice.viewControllers')
+ : t('remoteDevice.revokeAccess')}
</span>
</button>
+ {composerSessionId && (
+ <button
+ type="button"
+ data-controlled-banner-collapse="true"
+ aria-label={t('remoteDevice.collapseControlledNotice')}
+ onClick={() => setComposerCollapsed(composerSessionId, true)}
+ className={cn(
+ 'flex h-5 w-5 shrink-0 items-center justify-center rounded-full',
+ 'text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <X size={13} aria-hidden />
+ </button>
+ )}
</div>
</Tip>
);
@@ -184,10 +275,17 @@ export function ControlledBanner({
);
}
- // 嵌进 RunningStatusBar 中央槽位:不要 w-full / 居中外壳(居中由状态栏的三段式
- // flex 负责),chip 自带 max-w-full + 内部 truncate 兜底窄宽,避免与左右文字重叠。
- if (placement === 'statusbar') {
- return chip;
+ if (placement === 'composer') {
+ return (
+ <div className="pointer-events-auto flex min-w-0 max-w-full shrink justify-end">
+ <div
+ className="flex min-w-0 max-w-full justify-end"
+ style={maxWidth == null ? undefined : { maxWidth }}
+ >
+ {composerCollapsed && collapsedIndicator ? collapsedIndicator : chip}
+ </div>
+ </div>
+ );
}
return (
diff --git a/apps/desktop/src/renderer/features/remote-device/__tests__/ControlledBanner.test.tsx b/apps/desktop/src/renderer/features/remote-device/__tests__/ControlledBanner.test.tsx
new file mode 100644
index 0000000000..df19bba4a4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-device/__tests__/ControlledBanner.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+
+import type { ReactElement } from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ControlledBanner, __resetControlledBannerForTests } from '../ControlledBanner';
+
+const navigate = vi.hoisted(() => vi.fn());
+const confirm = vi.hoisted(() => vi.fn(async () => false));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ if (key === 'remoteDevice.controlledBy') return `Controlled by ${String(values?.name)}`;
+ if (key === 'remoteDevice.expandControlledNotice') {
+ return `Expand: ${String(values?.label)}`;
+ }
+ return key;
+ },
+ }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => navigate,
+}));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm }),
+}));
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children }: { children: ReactElement }) => children,
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+
+beforeEach(() => {
+ __resetControlledBannerForTests();
+ const api = {
+ getState: vi.fn(async () => ({
+ remoteControlEnabled: true,
+ keepAwake: false,
+ linkStatus: 'online' as const,
+ connectionIssue: null,
+ standby: false,
+ controlledBy: [{ deviceId: 'iphone', name: 'iPhone' }],
+ revokedControllers: [],
+ disabledControlDeviceIds: [],
+ unresponsiveDeviceIds: [],
+ })),
+ onControlledState: vi.fn(() => vi.fn()),
+ revoke: vi.fn(async () => undefined),
+ };
+ (window as unknown as { electronAPI: { deviceLink: typeof api } }).electronAPI = {
+ deviceLink: api,
+ };
+});
+
+afterEach(() => {
+ cleanup();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ vi.clearAllMocks();
+});
+
+describe('ControlledBanner composer collapse state', () => {
+ it('keeps collapse state isolated by session and restores the full chip from the breathing light', async () => {
+ const view = render(
+ <ControlledBanner placement="composer" sessionId="session-a" maxWidth={420} />,
+ );
+
+ expect(await screen.findByText('Controlled by iPhone')).toBeTruthy();
+ const chip = document.querySelector('[data-controlled-banner-chip="true"]');
+ const collapseButton = screen.getByRole('button', {
+ name: 'remoteDevice.collapseControlledNotice',
+ });
+ expect(chip).toBeTruthy();
+ expect(chip?.contains(collapseButton)).toBe(true);
+ fireEvent.click(collapseButton);
+
+ expect(screen.queryByText('Controlled by iPhone')).toBeNull();
+ expect(document.querySelector('[data-controlled-banner-chip="true"]')).toBeNull();
+ const collapsedButton = screen.getByRole('button', { name: 'Expand: Controlled by iPhone' });
+ expect(collapsedButton).toBeTruthy();
+ expect(collapsedButton.querySelector('span')?.classList.contains('translate-y-[2px]')).toBe(
+ true,
+ );
+
+ view.rerender(<ControlledBanner placement="composer" sessionId="session-b" maxWidth={420} />);
+ expect(screen.getByText('Controlled by iPhone')).toBeTruthy();
+
+ view.rerender(<ControlledBanner placement="composer" sessionId="session-a" maxWidth={420} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Expand: Controlled by iPhone' }));
+
+ expect(screen.getByText('Controlled by iPhone')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'remoteDevice.collapseControlledNotice' }),
+ ).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 1bd727e1df..eb988a8f38 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3893,6 +3893,8 @@
"controlledTooltip": "Another device signed in to the same account is remotely controlling this machine. You can revoke its access.",
"revokeAccess": "Revoke",
"viewControllers": "View",
+ "collapseControlledNotice": "Collapse remote control notice",
+ "expandControlledNotice": "Expand remote control notice: {{label}}",
"versionMismatch": "Version mismatch with the other device; some features may be limited"
},
"accountDeletion": {
@@ -5589,7 +5591,7 @@
"outputFile": "Output: {{path}}"
},
"planPill": {
- "step": "Step {{current}} / {{total}}"
+ "step": "Step {{current}} of {{total}}"
},
"forkOrigin": {
"label": "Created from another session"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 616297de98..06f23b5cd2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3891,6 +3891,8 @@
"controlledTooltip": "同じアカウントでログイン中の別のデバイスがこの端末をリモート操作しています。アクセス権限を撤回できます。",
"revokeAccess": "権限を撤回",
"viewControllers": "表示",
+ "collapseControlledNotice": "リモート操作の通知を折りたたむ",
+ "expandControlledNotice": "リモート操作の通知を展開: {{label}}",
"versionMismatch": "相手のバージョンが異なります。一部機能が制限される場合があります"
},
"accountDeletion": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 258a4c5c1d..0817136fe0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3891,6 +3891,8 @@
"controlledTooltip": "같은 계정으로 로그인한 다른 기기가 이 기기를 원격 제어하고 있습니다. 접근 권한을 철회할 수 있습니다.",
"revokeAccess": "권한 철회",
"viewControllers": "보기",
+ "collapseControlledNotice": "원격 제어 알림 접기",
+ "expandControlledNotice": "원격 제어 알림 펼치기: {{label}}",
"versionMismatch": "상대 기기 버전이 달라 일부 기능이 제한될 수 있습니다"
},
"accountDeletion": {
@@ -5587,7 +5589,7 @@
"outputFile": "출력: {{path}}"
},
"planPill": {
- "step": "단계 {{current}} / {{total}}"
+ "step": "{{current}} / {{total}}단계"
},
"forkOrigin": {
"label": "원래 세션에서 생성됨"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index aba91880e4..80030538ab 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3891,6 +3891,8 @@
"controlledTooltip": "另一台登录同账号的设备正在远程控制本机。你可以撤销其访问权限。",
"revokeAccess": "撤销权限",
"viewControllers": "查看",
+ "collapseControlledNotice": "收起被控提示",
+ "expandControlledNotice": "展开被控提示:{{label}}",
"versionMismatch": "对方版本不一致,部分功能可能受限"
},
"accountDeletion": {
@@ -5587,7 +5589,7 @@
"outputFile": "输出:{{path}}"
},
"planPill": {
- "step": "步骤 {{current}} / {{total}}"
+ "step": "第 {{current}} / {{total}} 步"
},
"forkOrigin": {
"label": "基于原任务创建"
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 365e2abca9..40b2b507ed 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -369,6 +369,8 @@ export interface ChatMessage {
* rewritten because it also participates in message ordering.
*/
planUpdatedAtMs?: number;
+ /** Main stamped this persisted Codex plan at the successful done boundary. */
+ terminalPlanSnapshot?: boolean;
/**
* 产生这条消息的模型 raw id(读自 agentMeta.model)。对 subagent 子消息而言
* 即子代理实际跑的模型(如 'claude-haiku-4-5-20251001')。仅 SDK 带 model 的
@@ -376,8 +378,9 @@ export interface ChatMessage {
*/
model?: string;
/**
- * Host 在 SDK `done` 边界写入的持久化 turn seal。一个真实用户请求可能因后台任务
- * 完成而自动续跑多个 SDK turn;每个 seal 都代表一条应保留在「已工作」外的正式回复。
+ * Host 在 SDK `done` 边界写入的持久化 turn seal。通常位于最后一条 assistant;
+ * 无 assistant 文本的 Codex 失败轮会把 false 写在所属 update_plan 行,防止后续轮次
+ * 的成功边界误收口旧计划。
*/
turnCompleted?: boolean;
/**
@@ -3879,7 +3882,11 @@ function hydratePersistedMessage(
typeof persisted.toolInput === 'object' &&
persisted.toolInput !== null &&
Array.isArray((existing.toolInput as { plan?: unknown }).plan) &&
- Array.isArray((persisted.toolInput as { plan?: unknown }).plan)
+ Array.isArray((persisted.toolInput as { plan?: unknown }).plan) &&
+ // Ordinary DB echoes can lag behind the live Codex event, including rows
+ // whose old payload happens to be fully completed or empty. Only Main's
+ // explicit done-boundary stamp may close a newer in-memory plan.
+ persisted.terminalPlanSnapshot !== true
) {
hydrated.toolInput = existing.toolInput;
hydrated.content = existing.content;
@@ -4645,7 +4652,9 @@ export function handleStreamEvent(
...messages[existingUpdatableToolIdx],
content: formatToolUseSummary(toolName, input),
toolInput: input,
- ...(toolName === 'update_plan' ? { planUpdatedAtMs: Date.now() } : {}),
+ ...(toolName === 'update_plan'
+ ? { planUpdatedAtMs: Date.now(), terminalPlanSnapshot: false }
+ : {}),
};
return {
...finalized,
@@ -14154,6 +14163,12 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
toolUseId,
toolName,
toolInput,
+ ...(toolName === 'update_plan' && c.terminalPlanSnapshot === true
+ ? { terminalPlanSnapshot: true }
+ : {}),
+ ...(toolName === 'update_plan' && c.turnCompleted === false
+ ? { turnCompleted: false }
+ : {}),
isStreaming: false,
// subagent-model-chip: 从持久化 agentMeta 复原 model / parentUuid,
// 让历史重载后 Agent/Task 行也能显示子代理模型 chip(透传点 B)。
@@ -14482,6 +14497,16 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
userTurnCostIsEstimate: agentMeta.userTurnCostIsEstimate === true,
}
: {};
+ // 新数据的显式 turn seal 权威高于旧历史兜底:失败/中断轮也可能带 usage 或费用,
+ // `false` 不能因此被重新推成成功。只有 seal 缺失的存量行才用收尾费用/明细补 true。
+ const persistedTurnCompleted =
+ m.role !== 'assistant'
+ ? undefined
+ : typeof agentMeta?.turnCompleted === 'boolean'
+ ? agentMeta.turnCompleted
+ : (persistedTurnMoney?.amount ?? 0) > 0 || turnUsageDetails !== undefined
+ ? true
+ : undefined;
return {
clientId: m.clientId,
role: m.role,
@@ -14490,16 +14515,8 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
...(m.role === 'tool_result' && typeof m.toolUseId === 'string' && m.toolUseId.length > 0
? { toolUseId: m.toolUseId }
: {}),
- // SDK done turn seal:新数据用 turnCompleted;存量会话已有 turnCostUsd 的收尾
- // assistant 等价可推导,直接补投影让本修复对历史复现会话立即生效。
- // turnUsageDetails 同样是 turn 结束才 patch 的字段(无报价轮只落它),因此
- // 也是等价的收尾信号 —— 少了它,无金额轮重开会话就挂不出 action bar。
- ...(m.role === 'assistant' &&
- (agentMeta?.turnCompleted === true ||
- (persistedTurnMoney?.amount ?? 0) > 0 ||
- turnUsageDetails !== undefined)
- ? { turnCompleted: true }
- : {}),
+ // SDK done turn seal;存量会话 seal 缺失时才用 turn 费用/明细补成功边界。
+ ...(persistedTurnCompleted !== undefined ? { turnCompleted: persistedTurnCompleted } : {}),
// 本轮 token 明细独立于金额挂载:Pi/新模型算不出报价的轮次只有它,
// UI 据此退回显示 token,历史加载不能把它绑在 money 分支。
...(m.role === 'assistant' && turnUsageDetails ? { turnUsageDetails } : {}),
diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.ts
index 4f32f64657..42912048e5 100644
--- a/packages/maker-shared/src/__tests__/messageRender.test.ts
+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts
@@ -870,6 +870,56 @@ describe('message render todo grouping', () => {
expect(findLatestMessageTodoInsertion([tool('t1', 'Bash', {})])).toBeNull();
});
+ it('does not infer completion from an ambiguous legacy Codex turn seal', () => {
+ const plan = {
+ ...tool('plan1', 'update_plan', {
+ plan: [
+ { step: 'Inspect', status: 'completed' },
+ { step: 'Start dev', status: 'in_progress' },
+ ],
+ }),
+ createdAt: at(1),
+ };
+ const completedBoundary: MessageRenderSourceMessageLike = {
+ role: 'assistant',
+ clientId: 'answer-1',
+ content: 'Dev server is running.',
+ createdAt: at(8),
+ turnCompleted: true,
+ };
+
+ expect(findLatestMessageTodoInsertion([plan, completedBoundary])).toMatchObject({
+ source: 'codex',
+ createdAt: at(1),
+ todos: [
+ { content: 'Inspect', status: 'completed' },
+ { content: 'Start dev', status: 'in_progress' },
+ ],
+ });
+ });
+
+ it('does not infer completion when an ambiguous legacy seal precedes the final plan update', () => {
+ const completedBoundary: MessageRenderSourceMessageLike = {
+ role: 'assistant',
+ clientId: 'answer-1',
+ content: 'The work is complete.',
+ createdAt: at(7),
+ turnCompleted: true,
+ };
+ const plan = {
+ ...tool('plan1', 'update_plan', {
+ plan: [{ step: 'Record the final state', status: 'in_progress' }],
+ }),
+ createdAt: at(8),
+ };
+
+ expect(findLatestMessageTodoInsertion([completedBoundary, plan])).toMatchObject({
+ source: 'codex',
+ createdAt: at(8),
+ todos: [{ content: 'Record the final state', status: 'in_progress' }],
+ });
+ });
+
it('findLatestMessageTodoInsertion treats empty plan updates as clearing the pinned plan', () => {
const first = tool('todo1', 'TodoWrite', {
todos: [{ content: 'Read code', status: 'in_progress' }],
diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.ts
index 215dd9869a..ea6786edf4 100644
--- a/packages/maker-shared/src/messageRender.ts
+++ b/packages/maker-shared/src/messageRender.ts
@@ -17,6 +17,8 @@ export interface MessageRenderSourceMessageLike {
toolInput?: unknown;
/** SDK tool-use id — used to link a Task/collab tool-call to its live `agent_task_update`. */
toolUseId?: string | null;
+ /** Host-persisted SDK turn boundary on the final assistant or owning Codex plan row. */
+ turnCompleted?: boolean;
}
export type MessageRenderNormalizedMessageKind =
@@ -548,6 +550,29 @@ export interface CodexPlanSnapshotApplyResult<
toolUseId: string | null;
}
+/**
+ * Resolve the plan payload that should survive a Codex turn terminal event.
+ * A successful turn is authoritative even when Codex only returns its last
+ * cached in-progress snapshot: every remaining item belongs to that finished
+ * turn and must converge to completed. Other terminal states may only apply an
+ * explicit snapshot; they must never infer completion from stale progress.
+ */
+export function resolveCodexPlanSnapshotOnDone(
+ currentPlan: readonly unknown[],
+ snapshot: unknown,
+ inferCompletion: boolean,
+): unknown[] | null {
+ const authoritativeSnapshot = Array.isArray(snapshot) ? snapshot : null;
+ if (!authoritativeSnapshot && !inferCompletion) return null;
+
+ const snapshotSource = authoritativeSnapshot ?? currentPlan;
+ if (!inferCompletion) return authoritativeSnapshot;
+ return snapshotSource.map((item) => {
+ const record = readRecord(item);
+ return record ? { ...record, status: 'completed' } : item;
+ });
+}
+
export function applyCodexPlanSnapshotOnDone<
TMessage extends MessageRenderSourceMessageLike,
>(
@@ -564,10 +589,6 @@ export function applyCodexPlanSnapshotOnDone<
return { messages, changed: false, toolUseId: null };
}
const expectedToolUseId = turnId ? `plan:${turnId}` : null;
- const shouldInferCompletion = canInferCompletion && (
- !hasAuthoritativeSnapshot
- || authoritativeSnapshot.some((item) => readRecord(item)?.status !== 'completed')
- );
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
@@ -586,13 +607,11 @@ export function applyCodexPlanSnapshotOnDone<
// matching, explicitly successful turn. Without a turn id, an array can
// still be applied as supplied but completion must never be inferred for an
// unrelated last plan row.
- const snapshotSource = authoritativeSnapshot ?? input.plan;
- const nextSnapshot = shouldInferCompletion
- ? snapshotSource.map((item) => {
- const record = readRecord(item);
- return record ? { ...record, status: 'completed' } : item;
- })
- : authoritativeSnapshot;
+ const nextSnapshot = resolveCodexPlanSnapshotOnDone(
+ input.plan,
+ authoritativeSnapshot,
+ canInferCompletion,
+ );
if (!nextSnapshot) {
return { messages, changed: false, toolUseId: null };
}