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。

feat: 首页任务建议悬停预览 prompt,点击填入输入框而非直接发送 (#5120)

Dash2c18a537eea5
diff --git a/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts b/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts
new file mode 100644
index 0000000000..d19de3181f
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/chatInputPromptPreview.test.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const chatInputSource = readFileSync(
+ resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
+ 'utf8',
+);
+
+describe('ChatInput home-suggestion prompt preview', () => {
+ it('never lets a keystroke edit or send the draft hidden behind the preview', () => {
+ const keyDown = chatInputSource.slice(chatInputSource.indexOf('handleKeyDown(view, event) {'));
+ // The preview guard runs before every other key handler (palette, Tab, Enter/send).
+ expect(keyDown.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
+ keyDown.indexOf('panelBridgeRef.current'),
+ );
+ expect(chatInputSource).toContain('promptPreviewInputGuardRef.current = () => {');
+ expect(chatInputSource).toContain('setDismissedPreviewPrompt(previewPrompt ?? null);');
+ expect(chatInputSource).toContain(
+ '!!previewPrompt && previewPrompt !== dismissedPreviewPrompt && !composerMutationLocked;',
+ );
+ });
+
+ it('guards hardware composer actions with the same preview gate', () => {
+ const hardware = chatInputSource.slice(
+ chatInputSource.indexOf('return subscribeWorkLouderCodexAction((action) => {'),
+ );
+ expect(hardware.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
+ hardware.indexOf("action.type === 'skill'"),
+ );
+ expect(hardware.indexOf('promptPreviewInputGuardRef.current()')).toBeLessThan(
+ hardware.indexOf("case 'composer.submit':"),
+ );
+ });
+
+ it('never resizes the composer; long previews are clamped to the space it already has', () => {
+ expect(chatInputSource).not.toContain('--prompt-preview-min-h');
+ expect(chatInputSource).toContain('style={{ WebkitLineClamp: promptPreviewLines }}');
+ expect(chatInputSource).toContain(
+ "'pointer-events-none absolute inset-x-0 top-0 line-clamp-1 py-[3px] pr-[11px]',",
+ );
+ });
+
+ it('reports the composer mutation lock so external fills can stand down', () => {
+ expect(chatInputSource).toContain('onMutationLockChange?.(composerMutationLocked);');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts b/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts
index 1e8d885549..6719e0372c 100644
--- a/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerPlaceholderCss.test.ts
@@ -6,9 +6,7 @@ const globalsSource = readFileSync(resolve(__dirname, '..', 'styles', 'globals.c
describe('composer placeholder CSS', () => {
it('renders the placeholder when Tiptap leaves only the empty-node class', () => {
- expect(globalsSource).toContain(
- '.ProseMirror > p.is-empty:first-child:only-child::before {',
- );
+ expect(globalsSource).toContain('.ProseMirror > p.is-empty:first-child:only-child::before {');
});
it('keeps the empty-node fallback hidden while a voice draft is active', () => {
@@ -22,4 +20,11 @@ describe('composer placeholder CSS', () => {
"[data-recommendation-active='true'] .ProseMirror > p.is-empty:first-child:only-child::before {",
);
});
+
+ it('only hides the editor content while a suggestion preview is active, never resizing it', () => {
+ const start = globalsSource.indexOf("[data-prompt-preview-active='true'] .ProseMirror {");
+ const block = globalsSource.slice(start, globalsSource.indexOf('}', start));
+ expect(block).toContain('opacity: 0;');
+ expect(block).not.toContain('height');
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
index 7ce0d5037a..62338742ba 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
@@ -121,7 +121,9 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
expect(source).toContain('absolute right-0 top-[22px]');
// 快捷入口与输入框同宽(w-full 跟随父列 inputWidth),左右两缘对齐 ChatInput;
// 旧 800px 封顶在宽窗口下右缘短一截,2026-07-24 用户反馈后摘除。
- expect(source).toMatch(/<HomeSuggestionList[\s\S]*?narrow=\{isDraftNarrow\}[\s\S]*?onSelect=\{handleHomeSuggestion\}[\s\S]*?onPluginSelect=\{handlePluginSuggestion\}/);
+ expect(source).toMatch(
+ /<HomeSuggestionList[\s\S]*?narrow=\{isDraftNarrow\}[\s\S]*?onSelect=\{handleHomeSuggestion\}[\s\S]*?onPluginSelect=\{handlePluginSuggestion\}/,
+ );
expect(source).toContain('<HomeZeroModelAction');
expect(source).not.toContain('ConnectProviderCard');
expect(source).not.toMatch(/data-testid="create-agent-quick-starts"/);
@@ -190,17 +192,29 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
expect(source).not.toContain('boxShadow');
});
- it('sends suggestions without first writing into the visible home composer', () => {
+ it('fills suggestions into the home composer instead of sending them', () => {
const suggestionBlock = source.slice(
- source.indexOf('const handleHomeSuggestion'),
+ source.indexOf('const [suggestionPreview, setSuggestionPreview]'),
source.indexOf('// 注意:不要给 ChatInput 加 key 强制 remount'),
);
- expect(suggestionBlock).toContain('if (sendInFlightRef.current) return;');
- expect(suggestionBlock).toMatch(/void handleSend\(\s*prompt,/);
- expect(suggestionBlock).toContain('recoveryDraftDoc: plainTextToTiptapDoc(prompt)');
- expect(suggestionBlock).not.toContain('saveComposerDraft(');
- expect(suggestionBlock).not.toContain('quickStartTextToTiptapDoc(');
+ expect(suggestionBlock).toContain('saveComposerDraft(NEW_MAKER_DRAFT_KEY, {');
+ expect(suggestionBlock).toContain('text: plainTextToTiptapDoc(prompt)');
+ expect(suggestionBlock).not.toContain('handleSend(');
+ // 悬停预览只走 ChatInput 的只读 overlay,不写草稿。
+ expect(source).toContain('previewPrompt={suggestionPreview}');
+ expect(source).toContain('onPreviewChange={handleSuggestionPreview}');
+ // 视觉预览与读屏描述共用同一个「点击后会填入的文字」计算。
+ expect(source).toContain('composerTextFor={suggestionComposerText}');
+ expect(suggestionBlock).toContain(
+ 'setSuggestionPreview(suggestion ? suggestionComposerText(suggestion) : null)',
+ );
+ // 语音占用 / 发送中时不填入,且预览与填入共用同一份插件文字计算。
+ expect(suggestionBlock).toContain(
+ 'if (sendInFlightRef.current || composerMutationLockedRef.current) return false;',
+ );
+ expect(source).toContain('onMutationLockChange={handleComposerMutationLockChange}');
+ expect(suggestionBlock.match(/pluginSuggestionComposerText\(/g)).toHaveLength(2);
// 普通发送直接使用输入内容,不再经过可能残留推荐内容的中转 ref。
expect(source).toContain('onSend={handleSend}');
expect(source).not.toContain('pendingHomePromptRef');
@@ -306,8 +320,12 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
expect(colorsSource).toContain("'create-agent-send-disabled-icon'");
expect(colorRegistry.resolveDefault('create-agent-send-disabled-icon', 'dark')).toBe('#585555');
expect(colorsSource).toContain("'create-agent-segment-inactive-text'");
- expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'light')).toBe('#9A9DA3');
- expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'dark')).toBe('#6F6F6F');
+ expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'light')).toBe(
+ '#9A9DA3',
+ );
+ expect(colorRegistry.resolveDefault('create-agent-segment-inactive-text', 'dark')).toBe(
+ '#6F6F6F',
+ );
expect(colorsSource).toContain("'create-agent-control-border'");
expect(colorRegistry.resolveDefault('create-agent-control-border', 'light')).toBe('#DCDFE3');
expect(colorRegistry.resolveDefault('create-agent-control-border', 'dark')).toBe('#434343');
diff --git a/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx b/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
index ea076370f6..37d68b989a 100644
--- a/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
@@ -5,8 +5,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { act, renderHook } from '@testing-library/react';
import ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { expandGhostCommand } from '../cindy-brain/ghostCommand';
-import type { InstalledGhost } from '../../shared/ghost';
+import { pluginSuggestionComposerText } from '../features/cc-agent/pluginHomeSuggestions';
// Execute the production callbacks without mounting the unrelated full desktop shell.
function compile(source: string, bindings: Record<string, unknown>) {
@@ -19,7 +18,7 @@ afterEach(() => vi.unstubAllGlobals());
describe('plugin recommendation recovery', () => {
it.each(['mail', undefined])(
- 'keeps the actual plugin-bound message in the retry draft (command=%s)',
+ 'fills the composer with the plugin-bound prompt instead of sending (command=%s)',
async (command) => {
const source = readFileSync(
resolve(__dirname, '../features/cc-agent/NewMakerDraftRoute.tsx'),
@@ -29,11 +28,15 @@ describe('plugin recommendation recovery', () => {
source.indexOf(' const runPluginSuggestion ='),
source.indexOf(' const handlePluginSuggestion ='),
);
+ expect(block).not.toContain('handleSend');
const suggestion = { id: 'one', pluginId: 'mail', prompt: 'Review my mail' };
const ghost = { manifest: { id: 'mail', name: 'Mail', command }, enabled: true };
- const handleSend = vi.fn(async () => false);
+ const fillComposerWithSuggestion = vi.fn((_text: string) => true);
+ const markUsed = vi.fn(async () => ({ ids: ['mail'] }));
vi.stubGlobal('electronAPI', {});
- Object.assign(window, { electronAPI: { ghosts: { listSync: () => ({ ghosts: [ghost] }) } } });
+ Object.assign(window, {
+ electronAPI: { ghosts: { listSync: () => ({ ghosts: [ghost] }), markUsed } },
+ });
const run = compile(`${block}\nreturn runPluginSuggestion;`, {
useCallback: (callback: unknown) => callback,
sendInFlightRef: { current: false },
@@ -45,9 +48,8 @@ describe('plugin recommendation recovery', () => {
readPluginRecommendationSnapshot: () => ({ ownerId: 'owner' }),
buildHomeTaskCatalog: () => [suggestion],
filterGhostsForWorkdir: (ghosts: unknown[]) => ghosts,
- expandGhostCommand,
- plainTextToTiptapDoc: (text: string) => ({ text }),
- handleSend,
+ fillComposerWithSuggestion,
+ pluginSuggestionComposerText,
i18n: { language: 'en' },
t: () => 'Use plugin mail via ghost_info and ghost_call',
isRemoteProjectDraft: false,
@@ -56,20 +58,21 @@ describe('plugin recommendation recovery', () => {
toast: { error: vi.fn() },
});
await run({ suggestion, ownerId: 'owner', targetKey: 'local', workingDir: '/project' });
- expect(handleSend).toHaveBeenCalledOnce();
- const [sent, , , , , , options] = handleSend.mock.calls[0] as unknown as [
- string,
- unknown,
- unknown,
- unknown,
- unknown,
- unknown,
- { recoveryDraftDoc: { text: string } },
- ];
- expect(sent).toContain(command ? '$mail' : 'ghost_info');
- expect(expandGhostCommand(options.recoveryDraftDoc.text, [ghost as InstalledGhost])).toBe(
- sent,
+ expect(fillComposerWithSuggestion).toHaveBeenCalledOnce();
+ const [filled] = fillComposerWithSuggestion.mock.calls[0] as [string];
+ expect(filled).toContain('Review my mail');
+ // $command stays as typed text; ChatInput expands it when the user sends.
+ expect(filled).toContain(command ? '$mail ' : 'ghost_info');
+ // Hover preview uses the same helper, so it shows exactly this text.
+ expect(filled).toBe(
+ pluginSuggestionComposerText(
+ suggestion.prompt,
+ ghost,
+ () => 'Use plugin mail via ghost_info and ghost_call',
+ ),
);
+ // Filling counts as using the plugin (plain-text sends cannot identify it later).
+ expect(markUsed).toHaveBeenCalledWith('mail');
},
);
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 6b679938e5..524b62f50a 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -616,6 +616,16 @@ interface ChatInputProps {
messages?: Array<{ role: string; content: string; quotesEncoded?: boolean }>;
/** Custom placeholder text. Defaults to "今天我们做点什么呢~" */
placeholder?: string;
+ /**
+ * 只读预览文案(首页任务建议悬停时的完整 prompt)。非空时盖在编辑器上显示,
+ * 暂时遮住当前正文,不写入草稿;置回 null 即恢复原样。
+ */
+ previewPrompt?: string | null;
+ /**
+ * 输入框「正文不可改」锁定状态变化时回调(禁用 / 发送中 / 语音占用)。供外部写草稿的入口
+ * (如首页建议点击填入)在锁定期间放弃写入,避免覆盖进行中的语音稿或待发正文。
+ */
+ onMutationLockChange?: (locked: boolean) => void;
/** Controlled open state for FolderPickerPopover. When omitted, internal state is used. */
folderPickerOpen?: boolean;
/** Callback when FolderPickerPopover open state changes (controlled mode). */
@@ -1130,6 +1140,8 @@ export function ChatInput({
onQueueEditLock,
messages,
placeholder,
+ previewPrompt,
+ onMutationLockChange,
folderPickerOpen,
onFolderPickerOpenChange,
showFolderPicker = true,
@@ -1191,6 +1203,9 @@ export function ChatInput({
const recommendationRef = useRef(recommendation);
recommendationRef.current = recommendation;
const showRecommendationRef = useRef(false);
+ // 首页建议预览遮住正文期间的输入闸门(键盘与硬件动作共用,见 showPromptPreview);
+ // handleKeyDown 与硬件动作订阅都是稳定闭包,经 ref 读当前值。
+ const promptPreviewInputGuardRef = useRef<() => boolean>(() => false);
const acceptPromptRecommendationRef = useRef<() => boolean>(() => false);
// session 切换时 ChatInput/Editor 会复用;推荐资格必须等目标草稿完成水合后再判断。
const [composerHydrationGeneration, setComposerHydrationGeneration] = useState(0);
@@ -2457,6 +2472,16 @@ export function ChatInput({
return true;
},
handleKeyDown(view, event) {
+ // 首页建议预览正遮住正文时,编辑器可能仍持有焦点:先撤掉预览并吞掉这一键,
+ // 保证编辑与发送永远作用在用户看得见的正文上。纯修饰键不算。
+ if (
+ !['Shift', 'Meta', 'Control', 'Alt', 'CapsLock'].includes(event.key) &&
+ promptPreviewInputGuardRef.current()
+ ) {
+ event.preventDefault();
+ return true;
+ }
+
// Delegate panel navigation keys (↑ ↓ Enter Esc Tab) when a
// palette is open. We can't read React state from here directly,
// but we expose a ref-based escape hatch via `panelBridgeRef`.
@@ -7578,6 +7603,9 @@ export function ChatInput({
return false;
}
if (!ownsHardwareComposerActions) return false;
+ // 预览遮住正文时,硬件动作与键盘一样先撤掉预览、不作用于看不见的正文。语音会锁定
+ // 输入框并随之收起预览,照常放行。
+ if (action.type !== 'voice' && promptPreviewInputGuardRef.current()) return true;
if (action.type === 'skill') {
if (!editor || editor.isDestroyed || composerMutationLocked) return false;
editor.chain().focus().insertContent(`$${action.name} `).run();
@@ -8202,6 +8230,59 @@ export function ChatInput({
});
// handleKeyDown 的稳定闭包只按真实可见性接受 Tab,避免隐藏推荐被误填入。
showRecommendationRef.current = showRecommendationOverlay;
+ // 首页建议悬停预览:输入框锁定(发送中 / 语音占用 / 禁用)时不预览,免得遮住进行中的状态。
+ // 预览期间有按键或硬件动作时撤掉本次预览、露出真实正文(闸门见 handleKeyDown 与硬件动作订阅);
+ // 建议移开后复位。
+ const [dismissedPreviewPrompt, setDismissedPreviewPrompt] = useState<string | null>(null);
+ if (!previewPrompt && dismissedPreviewPrompt !== null) setDismissedPreviewPrompt(null);
+ const showPromptPreview =
+ !!previewPrompt && previewPrompt !== dismissedPreviewPrompt && !composerMutationLocked;
+ promptPreviewInputGuardRef.current = () => {
+ if (!showPromptPreview) return false;
+ setDismissedPreviewPrompt(previewPrompt ?? null);
+ return true;
+ };
+ useEffect(() => {
+ onMutationLockChange?.(composerMutationLocked);
+ }, [composerMutationLocked, onMutationLockChange]);
+ // 预览是 absolute overlay,绝不改变输入框高度:一旦撑高,下方建议行会被挤离鼠标,触发
+ // 移出→预览收起→行移回的闪烁。只用编辑区及其与下一块(工具栏)之间现有的空白,按能容纳的
+ // 行数截断并以省略号提示;点击填入后全文进入输入框,可滚动查看。
+ const promptPreviewRef = useRef<HTMLDivElement>(null);
+ const [promptPreviewLines, setPromptPreviewLines] = useState(1);
+ useLayoutEffect(() => {
+ const preview = promptPreviewRef.current;
+ const editorBlock = preview?.parentElement;
+ const card = editorBlock?.closest<HTMLElement>('[data-split-group-composer-drop-target]');
+ if (!showPromptPreview || !preview || !editorBlock || !card) return;
+ let cardChild: HTMLElement = editorBlock;
+ while (cardChild.parentElement && cardChild.parentElement !== card) {
+ cardChild = cardChild.parentElement;
+ }
+ const measure = () => {
+ let next = cardChild.nextElementSibling;
+ while (next && ['absolute', 'fixed'].includes(getComputedStyle(next).position)) {
+ next = next.nextElementSibling;
+ }
+ const cardStyle = getComputedStyle(card);
+ const limit = next
+ ? next.getBoundingClientRect().top
+ : card.getBoundingClientRect().bottom -
+ parseFloat(cardStyle.paddingBottom) -
+ parseFloat(cardStyle.borderBottomWidth);
+ const previewStyle = getComputedStyle(preview);
+ const lineHeight = parseFloat(previewStyle.lineHeight) || 22;
+ const padding = parseFloat(previewStyle.paddingTop) + parseFloat(previewStyle.paddingBottom);
+ const available = limit - editorBlock.getBoundingClientRect().top - padding;
+ setPromptPreviewLines(Math.max(1, Math.floor(available / lineHeight)));
+ };
+ measure();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(card);
+ observer.observe(editorBlock);
+ return () => observer.disconnect();
+ }, [showPromptPreview]);
// 可见推荐本身就是一次可发送输入:按钮点击时会先把它同步写入正文,再走现有发送链。
const canSend = hasComposerPayload || showRecommendationOverlay;
const makeNeedsNoModel = (noConnectedSource || selectedSourceDisconnected) && !!editor &&
@@ -8668,6 +8749,8 @@ export function ChatInput({
className="relative w-full"
// 推荐词生效时由 CSS 关掉原生 placeholder,避免两行字叠在一起。
data-recommendation-active={showRecommendationOverlay ? 'true' : undefined}
+ // 建议预览生效时由 CSS 隐去编辑器正文。
+ data-prompt-preview-active={showPromptPreview ? 'true' : undefined}
>
<EditorContent
editor={editor}
@@ -8681,11 +8764,27 @@ export function ChatInput({
voiceBusyOnCurrentComposer && voiceInput.draftText ? 'true' : undefined
}
/>
+ {/* 建议预览:排版与原生 placeholder 对齐,py-[3px] 同下方推荐词 overlay 的说明。 */}
+ {showPromptPreview && (
+ <div
+ ref={promptPreviewRef}
+ data-testid="chat-input-prompt-preview"
+ aria-hidden="true"
+ style={{ WebkitLineClamp: promptPreviewLines }}
+ className={cn(
+ 'pointer-events-none absolute inset-x-0 top-0 line-clamp-1 py-[3px] pr-[11px]',
+ 'whitespace-pre-wrap break-words text-15 leading-[1.467] font-normal',
+ 'text-[var(--chat-input-placeholder-subtle)]',
+ )}
+ >
+ {previewPrompt}
+ </div>
+ )}
{/* 字号 / 行高 / 颜色与原生 placeholder 对齐,单行截断防止长句撑高输入框。
py-[3px] 是镜像 .ProseMirror 的 py-[3px]:它的 -my-[3px] 会穿过这里
向外折叠(relative 不建立 BFC),于是 .ProseMirror 的 border box 贴在本
容器顶边、正文被自身 padding 推低 3px。overlay 不跟着补这 3px 就会高一行边距。 */}
- {showRecommendationOverlay && (
+ {showRecommendationOverlay && !showPromptPreview && (
<div
className={cn(
'pointer-events-none absolute left-0 top-0 inline-flex max-w-full min-w-0 items-center py-[3px]',
diff --git a/apps/desktop/src/renderer/features/cc-agent/HomeSuggestionList.tsx b/apps/desktop/src/renderer/features/cc-agent/HomeSuggestionList.tsx
index 359c596cfc..1a1ac852e0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/HomeSuggestionList.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/HomeSuggestionList.tsx
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button';
-import { useState } from 'react';
+import { Fragment, useEffect, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
AppWindow,
@@ -76,11 +76,17 @@ export function HomeSuggestionList({
narrow,
onSelect,
onPluginSelect,
+ onPreviewChange,
+ composerTextFor,
includePlugins = true,
}: {
narrow: boolean;
onSelect: (id: HomeSuggestionId) => void;
onPluginSelect?: (suggestion: HomeTaskSuggestion) => void;
+ /** 鼠标悬停某条建议时报告该条目,离开时报告 null;由调用方算出与点击填入一致的预览文字。 */
+ onPreviewChange?: (suggestion: HomeTaskSuggestion | null) => void;
+ /** 点击该条建议后实际填入输入框的文字(与视觉预览同源),用作读屏描述;缺省为建议 prompt。 */
+ composerTextFor?: (suggestion: HomeTaskSuggestion) => string;
includePlugins?: boolean;
}) {
const { t, i18n } = useTranslation();
@@ -101,11 +107,31 @@ export function HomeSuggestionList({
};
const [batch, setBatch] = useState(() => draw(null));
const [hidden, setHidden] = useState(isHomeSuggestionsHidden);
+ // 行在悬停中被卸载(隐藏、换批、整块被替换)时收不到 mouseleave,由这里兜底清掉预览。
+ const onPreviewChangeRef = useRef(onPreviewChange);
+ onPreviewChangeRef.current = onPreviewChange;
+ useEffect(() => () => onPreviewChangeRef.current?.(null), []);
+ // 预览只跟随鼠标悬停:移入报告该条,移出清空;点击(填入)视为本次悬停结束,直到再次移入。
+ // 键盘 / 读屏用户通过按钮描述得到同样的文字,且点击只填入不发送,可在输入框里再看再改。
+ const hoveredRef = useRef<HomeTaskSuggestion | null>(null);
+ const setHovered = (item: HomeTaskSuggestion | null) => {
+ hoveredRef.current = item;
+ onPreviewChange?.(item);
+ };
+ const descriptionIdPrefix = useId();
if (batchSize > batch.displayedCount) {
setBatch({ ...batch, displayedCount: batchSize });
}
const visible = batch.items.slice(0, batchSize);
+ // 预览只能指向当前仍显示的条目:窄屏裁掉行、换一批等让行离开 DOM 时收不到可靠的
+ // mouseleave,这里按可见集合统一清掉失效的悬停项。
+ const visibleKey = visible.map((item) => item.id).join('\n');
+ useEffect(() => {
+ const hovered = hoveredRef.current;
+ if (hovered && !visibleKey.split('\n').includes(hovered.id)) setHovered(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- setHovered 每次渲染重建,只在可见集合变化时核对
+ }, [visibleKey]);
if (hidden) return null;
@@ -116,20 +142,33 @@ export function HomeSuggestionList({
const { id } = item;
const Icon = item.builtinId ? ICONS[item.builtinId] : Puzzle;
return (
- <button
- key={id}
- type="button"
- data-testid={`home-suggestion-${id}`}
- onClick={() => (item.builtinId ? onSelect(item.builtinId) : onPluginSelect?.(item))}
- className={cn(
- 'inline-flex h-[38px] max-w-full items-center gap-2.5 rounded-full px-3',
- 'text-14 text-[var(--text-secondary)] transition-colors',
- 'hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
- )}
- >
- <Icon size={16} strokeWidth={2} className="shrink-0 text-current" />
- <span className="min-w-0 truncate">{item.label}</span>
- </button>
+ <Fragment key={id}>
+ <button
+ type="button"
+ data-testid={`home-suggestion-${id}`}
+ // 输入框里的视觉预览对读屏隐藏;点击后实际填入的文字通过描述关联到按钮本身。
+ aria-describedby={`${descriptionIdPrefix}-${id}`}
+ onClick={() => {
+ setHovered(null);
+ if (item.builtinId) onSelect(item.builtinId);
+ else onPluginSelect?.(item);
+ }}
+ onMouseEnter={() => setHovered(item)}
+ onMouseLeave={() => setHovered(null)}
+ className={cn(
+ 'inline-flex h-[38px] max-w-full items-center gap-2.5 rounded-full px-3',
+ 'text-14 text-[var(--text-secondary)] transition-colors',
+ 'hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ <Icon size={16} strokeWidth={2} className="shrink-0 text-current" />
+ <span className="min-w-0 truncate">{item.label}</span>
+ </button>
+ {/* 放在按钮外,只作描述,不并入按钮名称。 */}
+ <span id={`${descriptionIdPrefix}-${id}`} className="sr-only">
+ {composerTextFor ? composerTextFor(item) : item.prompt}
+ </span>
+ </Fragment>
);
})}
</div>
@@ -141,7 +180,10 @@ export function HomeSuggestionList({
tone="quiet"
type="button"
data-testid="home-suggestions-shuffle"
- onClick={() => setBatch((previous) => draw(previous))}
+ onClick={() => {
+ setHovered(null);
+ setBatch((previous) => draw(previous));
+ }}
className="opacity-0 group-hover/sug:opacity-100 focus-visible:opacity-100"
>
<Shuffle size={11} strokeWidth={2} />
@@ -155,6 +197,7 @@ export function HomeSuggestionList({
type="button"
data-testid="home-suggestions-dismiss"
onClick={() => {
+ setHovered(null);
setHomeSuggestionsHidden(true);
setHidden(true);
}}
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 9e2743e946..8e5c2dd165 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -177,15 +177,16 @@ import { HomeSuggestionList } from './HomeSuggestionList';
import { type HomeSuggestionId, homeSuggestionPromptKey } from './homeSuggestions';
import {
buildHomeTaskCatalog,
+ pluginSuggestionComposerText,
readPluginRecommendationSnapshot,
type HomeTaskSuggestion,
} from './pluginHomeSuggestions';
+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import {
startPendingPluginSuggestion,
takePendingPluginSuggestion,
type PluginSuggestionRequest,
} from './pendingPluginSuggestion';
-import { expandGhostCommand } from '@/cindy-brain/ghostCommand';
import { filterGhostsForWorkdir } from '@/cindy-brain/ghostWorkdirFilter';
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import {
@@ -4995,32 +4996,58 @@ export function NewMakerDraftRoute() {
return proceed;
}, [vendorAuthGate]);
- const handleHomeSuggestion = useCallback(
- (id: HomeSuggestionId) => {
- if (sendInFlightRef.current) return;
- const prompt = t(homeSuggestionPromptKey(id));
- void handleSend(
- prompt,
- draftInitialModel,
- (draftInitialEffort ?? 'medium') as Effort,
- chatInitialPermissionMode,
- attachmentState.attachments,
- undefined,
- {
- providerId: chatInitialProviderId,
- recoveryDraftDoc: plainTextToTiptapDoc(prompt),
- },
- );
+ // 首页任务建议:悬停只在输入框里预览 prompt,点击把完整 prompt 填进输入框交给用户
+ // 改写后自己发送,不再直接替用户发出。填入走草稿存储的外部写入通道,ChatInput 订阅后
+ // 替换正文并把光标放到末尾;附件等其余草稿内容原样保留。输入框锁定(发送中 / 语音占用)
+ // 时不写入,免得覆盖进行中的语音稿或待发正文。预览与填入共用同一份文字计算。
+ const [suggestionPreview, setSuggestionPreview] = useState<string | null>(null);
+ const composerMutationLockedRef = useRef(false);
+ const handleComposerMutationLockChange = useCallback((locked: boolean) => {
+ composerMutationLockedRef.current = locked;
+ }, []);
+ const fillComposerWithSuggestion = useCallback((prompt: string): boolean => {
+ if (sendInFlightRef.current || composerMutationLockedRef.current) return false;
+ const existing = getComposerDraft(NEW_MAKER_DRAFT_KEY);
+ saveComposerDraft(NEW_MAKER_DRAFT_KEY, {
+ ...existing,
+ text: plainTextToTiptapDoc(prompt),
+ attachments: existing?.attachments ?? [],
+ });
+ return true;
+ }, []);
+ // 一条建议「点击后会填入的文字」的唯一计算:视觉预览与读屏描述都用它,点击填入走同一个
+ // pluginSuggestionComposerText。插件可用时带 $指令(或插件调用说明);需要先安装的插件
+ // 点击后走安装引导、不会立即填入,只显示建议本身。插件清单变化时随之重算。
+ // 可用插件表按插件清单与工作目录缓存:filterGhostsForWorkdir 会同步查询目录禁用表,
+ // 不能在每次渲染 / 每条建议上重复调用。
+ const installedGhosts = useInstalledGhosts();
+ const usableSuggestionGhosts = useMemo(
+ () =>
+ new Map(
+ filterGhostsForWorkdir(installedGhosts, effectiveWorkingDir)
+ .filter((g) => g.enabled)
+ .map((g) => [g.manifest.id, g]),
+ ),
+ [effectiveWorkingDir, installedGhosts],
+ );
+ const suggestionComposerText = useCallback(
+ (suggestion: HomeTaskSuggestion) => {
+ const ghost = suggestion.pluginId
+ ? usableSuggestionGhosts.get(suggestion.pluginId)
+ : undefined;
+ return ghost ? pluginSuggestionComposerText(suggestion.prompt, ghost, t) : suggestion.prompt;
},
- [
- attachmentState.attachments,
- chatInitialPermissionMode,
- chatInitialProviderId,
- draftInitialEffort,
- draftInitialModel,
- handleSend,
- t,
- ],
+ [t, usableSuggestionGhosts],
+ );
+ const handleSuggestionPreview = useCallback(
+ (suggestion: HomeTaskSuggestion | null) =>
+ setSuggestionPreview(suggestion ? suggestionComposerText(suggestion) : null),
+ [suggestionComposerText],
+ );
+
+ const handleHomeSuggestion = useCallback(
+ (id: HomeSuggestionId) => fillComposerWithSuggestion(t(homeSuggestionPromptKey(id))),
+ [fillComposerWithSuggestion, t],
);
const pluginSuggestionFlight = useRef(false);
@@ -5109,28 +5136,12 @@ export function NewMakerDraftRoute() {
navigate(`${route}&recommendation=${encodeURIComponent(nonce)}`);
return;
}
- const recoveryPrompt = ghost.manifest.command
- ? `$${ghost.manifest.command} ${suggestion.prompt}`
- : `${suggestion.prompt}\n\n${t('newChat.pluginSuggestions.usePlugin', { name: ghost.manifest.name, id: ghost.manifest.id })}`;
- // Retry goes through ChatInput, which expands $commands itself.
- const prompt = ghost.manifest.command
- ? expandGhostCommand(recoveryPrompt, [ghost])
- : recoveryPrompt;
- await handleSend(
- prompt,
- request.model,
- request.effort,
- request.permissionMode,
- request.files,
- undefined,
- {
- providerId: request.providerId,
- recoveryDraftDoc: plainTextToTiptapDoc(recoveryPrompt),
- onAccepted: () => {
- void window.electronAPI.ghosts.markUsed(ghost.manifest.id).catch(() => undefined);
- },
- },
- );
+ // 填进输入框而不是直接发送;ChatInput 发送时会自己展开 $command。无指令插件发送时
+ // 识别不出所用插件,所以选中插件建议并成功填入即记一次最近使用(有指令的插件发送时
+ // 还会再记一次,只刷新时间,不影响排序语义)。
+ if (fillComposerWithSuggestion(pluginSuggestionComposerText(suggestion.prompt, ghost, t))) {
+ void window.electronAPI.ghosts.markUsed(ghost.manifest.id).catch(() => undefined);
+ }
} catch {
if (pluginSuggestionMounted.current)
toast.error(t('newChat.pluginSuggestions.unavailable'));
@@ -5139,7 +5150,7 @@ export function NewMakerDraftRoute() {
}
},
[
- handleSend,
+ fillComposerWithSuggestion,
i18n.language,
i18n.resolvedLanguage,
isDeviceLinkDraft,
@@ -5157,20 +5168,10 @@ export function NewMakerDraftRoute() {
ownerId: dataOwnerId,
targetKey: pluginSuggestionTargetKey,
workingDir: effectiveWorkingDir,
- model: draftInitialModel,
- effort: (draftInitialEffort ?? 'medium') as Effort,
- permissionMode: chatInitialPermissionMode,
- providerId: chatInitialProviderId,
- files: attachmentState.attachments,
});
},
[
- attachmentState.attachments,
- chatInitialPermissionMode,
- chatInitialProviderId,
dataOwnerId,
- draftInitialEffort,
- draftInitialModel,
effectiveWorkingDir,
pluginSuggestionTargetKey,
runPluginSuggestion,
@@ -5407,6 +5408,8 @@ export function NewMakerDraftRoute() {
visualVariant="create-agent"
compactToolbar
placeholder={t('newChat.chatInput.createAgentPlaceholder')}
+ previewPrompt={suggestionPreview}
+ onMutationLockChange={handleComposerMutationLockChange}
sessionId={undefined}
initialWorkingDir={effectiveWorkingDir}
remoteHostId={draft.remoteHostId ?? null}
@@ -5580,6 +5583,8 @@ export function NewMakerDraftRoute() {
onSelect={handleHomeSuggestion}
includePlugins={!isRemoteProjectDraft && !isDeviceLinkDraft}
onPluginSelect={handlePluginSuggestion}
+ onPreviewChange={handleSuggestionPreview}
+ composerTextFor={suggestionComposerText}
/>
)}
{/* 首页「新建目标」弹窗:无 sessionId → onCreate 建会话并 setGoal(见 handleCreateGoal)。
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/HomeSuggestionList.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/HomeSuggestionList.test.tsx
index 03783d0d6b..a0c8bc4c38 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/HomeSuggestionList.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/HomeSuggestionList.test.tsx
@@ -72,4 +72,70 @@ describe('HomeSuggestionList', () => {
rerender(<HomeSuggestionList narrow={false} onSelect={onSelect} />);
expect(ids().some((id) => seen.includes(id))).toBe(false);
});
+
+ it('previews only the hovered suggestion and clears it on leave, click and unmount', () => {
+ const onSelect = vi.fn();
+ const onPreviewChange = vi.fn();
+ const { unmount } = render(
+ <HomeSuggestionList narrow={false} onSelect={onSelect} onPreviewChange={onPreviewChange} />,
+ );
+ const row = screen.getAllByTestId(/^home-suggestion-/)[0];
+ const id = row.getAttribute('data-testid')!.replace('home-suggestion-', '');
+
+ fireEvent.mouseEnter(row);
+ expect(onPreviewChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id, prompt: `newChat.homeSuggestions.${id}.prompt` }),
+ );
+ fireEvent.mouseLeave(row);
+ expect(onPreviewChange).toHaveBeenLastCalledWith(null);
+
+ // Keyboard focus alone does not drive the visual preview (the row description covers it).
+ fireEvent.focus(row);
+ expect(onPreviewChange).toHaveBeenLastCalledWith(null);
+ fireEvent.mouseEnter(row);
+ fireEvent.click(row);
+ expect(onPreviewChange).toHaveBeenLastCalledWith(null);
+ expect(onSelect).toHaveBeenCalledWith(id);
+
+ fireEvent.mouseEnter(row);
+ onPreviewChange.mockClear();
+ unmount();
+ expect(onPreviewChange).toHaveBeenCalledWith(null);
+ });
+
+ it('exposes each full prompt to assistive technology as the row description', () => {
+ render(<HomeSuggestionList narrow={false} onSelect={vi.fn()} />);
+ const row = screen.getAllByTestId(/^home-suggestion-/)[0];
+ const id = row.getAttribute('data-testid')!.replace('home-suggestion-', '');
+ const description = document.getElementById(row.getAttribute('aria-describedby')!);
+ expect(description?.textContent).toBe(`newChat.homeSuggestions.${id}.prompt`);
+ // The description lives outside the button so it never joins the accessible name.
+ expect(row.contains(description)).toBe(false);
+ });
+
+ it('clears the preview when the window narrows past the hovered row', () => {
+ const onPreviewChange = vi.fn();
+ const { rerender } = render(
+ <HomeSuggestionList narrow={false} onSelect={vi.fn()} onPreviewChange={onPreviewChange} />,
+ );
+ const rows = screen.getAllByTestId(/^home-suggestion-/);
+ fireEvent.mouseEnter(rows[3]);
+ onPreviewChange.mockClear();
+ rerender(<HomeSuggestionList narrow onSelect={vi.fn()} onPreviewChange={onPreviewChange} />);
+ expect(onPreviewChange).toHaveBeenLastCalledWith(null);
+ });
+
+ it('describes each row with the exact text a click will fill, not the raw prompt', () => {
+ render(
+ <HomeSuggestionList
+ narrow={false}
+ onSelect={vi.fn()}
+ composerTextFor={(item) => `$mail ${item.prompt}`}
+ />,
+ );
+ const row = screen.getAllByTestId(/^home-suggestion-/)[0];
+ const id = row.getAttribute('data-testid')!.replace('home-suggestion-', '');
+ const description = document.getElementById(row.getAttribute('aria-describedby')!);
+ expect(description?.textContent).toBe(`$mail newChat.homeSuggestions.${id}.prompt`);
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
index 4c1d9b54ee..b2faefc671 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
@@ -11,10 +11,6 @@ const request: PluginSuggestionRequest = {
ownerId: 'a',
targetKey: 'local',
workingDir: null,
- model: 'test',
- effort: 'medium',
- permissionMode: 'default',
- files: [],
suggestion: {
id: 'plugin:test:one',
category: 'email',
diff --git a/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts b/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
index b31d507389..3df837342b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
@@ -1,5 +1,3 @@
-import type { AttachedFile } from '@/lib/fileTypes';
-import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import type { HomeTaskSuggestion } from './pluginHomeSuggestions';
export interface PluginSuggestionRequest {
@@ -7,11 +5,6 @@ export interface PluginSuggestionRequest {
ownerId: string;
targetKey: string;
workingDir: string | null;
- model: string;
- effort: Effort;
- permissionMode: PermissionMode;
- providerId?: string | null;
- files: AttachedFile[];
}
export interface PendingPluginSuggestion extends PluginSuggestionRequest {
nonce: string;
diff --git a/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts b/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
index f2585ae2ab..fe9f54b605 100644
--- a/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
@@ -166,3 +166,18 @@ export function nextHomeTaskBatch(
}
return { items, seenIds: [...seen], displayedCount: visibleCount };
}
+
+/**
+ * Composer text for a plugin suggestion whose plugin is usable here. Hover preview and click
+ * fill share this so the preview always shows exactly what lands in the composer; `$command`
+ * stays as typed text and ChatInput expands it on send.
+ */
+export function pluginSuggestionComposerText(
+ prompt: string,
+ ghost: { manifest: { id: string; name: string; command?: string } },
+ t: (key: string, options?: Record<string, unknown>) => string,
+): string {
+ return ghost.manifest.command
+ ? `$${ghost.manifest.command} ${prompt}`
+ : `${prompt}\n\n${t('newChat.pluginSuggestions.usePlugin', { name: ghost.manifest.name, id: ghost.manifest.id })}`;
+}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index a9c078a2fb..e0b9f0baad 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -63,10 +63,6 @@ const suggestion: PluginSuggestionRequest = {
ownerId: 'navigation-owner',
targetKey: 'local',
workingDir: null,
- model: 'test',
- effort: 'medium',
- permissionMode: 'default',
- files: [],
suggestion: {
id: 'plugin:navigation',
category: 'email',
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 4a3052e020..e46035dc00 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -335,6 +335,11 @@ html:lang(ko) {
[data-recommendation-active='true'] .ProseMirror > p.is-empty:first-child:only-child::before {
content: none;
}
+/* 首页建议悬停预览:预览由 ChatInput 的 overlay 承载,暂时隐去正文/placeholder;
+ 预览不改变编辑器高度,见 ChatInput 的 promptPreviewLines。 */
+[data-prompt-preview-active='true'] .ProseMirror {
+ opacity: 0;
+}
.ProseMirror {
caret-color: var(--caret-accent);
}