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): edit queued messages in composer

DavidShenbf205d9d7fcc
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 78c988d4bb..1fedb9ef89 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7132,6 +7132,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
trustedContexts,
opts,
),
+ updateContent: (
+ sessionId: string,
+ clientId: string,
+ item: import('../shared/agentInputQueue').AgentInputQueuedMessage,
+ opts?: { expectedClearBoundaryMs?: number | null },
+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>
+ ipcRenderer.invoke('maker:input:update-content', sessionId, clientId, item, opts),
move: (
sessionId: string,
clientId: string,
diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
index c679658348..7ce3443f15 100644
--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
@@ -88,6 +88,8 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
{ userName: 'Carol' },
);
api.input.clearSession('rs');
+ const replacement = { clientId: 'q1' } as never;
+ api.input.updateContent('rs', 'q1', replacement);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:fork', ['rs', 'msg']);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:fork-strip-encrypted', ['rs']);
@@ -118,6 +120,11 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
{ userName: 'Carol' },
]);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:input:clear-session', ['rs']);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:input:update-content', [
+ 'rs',
+ 'q1',
+ replacement,
+ ]);
});
it('已捕获的 deviceId 在 session origin 暂时消失后仍固定走远程隧道', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
index be4a17a67e..4a46afba2f 100644
--- a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
@@ -81,6 +81,13 @@ let remoteInvoke = vi.fn();
const legacySend = vi.fn(async () => {});
const legacySteer = vi.fn(async () => {});
const generateTitle = vi.fn(async () => ({ title: 't' }));
+const cacheMediaForSession = vi.fn(async () => ({
+ url: 'xdt-image://session/copied.png',
+ name: 'copied.png',
+ ext: 'png',
+ mimeType: 'image/png',
+ size: 10,
+}));
const input = {
getProjection: vi.fn(async (sessionId: string) => projection(sessionId)),
@@ -104,6 +111,10 @@ const input = {
clearError: vi.fn(async (sessionId: string) => projection(sessionId)),
remove: vi.fn(async (sessionId: string) => projection(sessionId)),
updateText: vi.fn(async (sessionId: string) => projection(sessionId)),
+ updateContent: vi.fn(
+ async (sessionId: string, _clientId: string, item: AgentInputQueuedMessage) =>
+ projection(sessionId, { pendingQueue: [item] }),
+ ),
move: vi.fn(async (sessionId: string) => projection(sessionId)),
setExpanded: vi.fn(async (sessionId: string, expanded: boolean) =>
projection(sessionId, { queueExpanded: expanded }),
@@ -196,6 +207,7 @@ function installElectronBridge(): void {
},
},
deviceLink: { invoke: remoteInvoke },
+ cacheMediaForSession,
};
}
@@ -376,6 +388,133 @@ describe('renderer input queue facade', () => {
expect(legacySteer).not.toHaveBeenCalled();
});
+ it('replaces queued text and attachments through update-content', async () => {
+ const sid = `content-${Math.random().toString(36).slice(2, 8)}`;
+ const item = queued('q-content', 'keep metadata');
+ item.chatMessage.quotesEncoded = true;
+ item.chatMessage.slashCommandRanges = [{ start: 0, end: 4 }];
+
+ makerChatStore.initGlobalListeners();
+ projectionHandler?.(projection(sid, { pendingQueue: [item] }));
+
+ const saved = await makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content: {
+ text: item.text,
+ mentions: [],
+ hasQuotes: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ },
+ files: [
+ {
+ id: 'new-image',
+ name: 'new.png',
+ path: 'C:\\images\\new.png',
+ ext: 'png',
+ size: 123,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'xdt-image://session/new.png',
+ },
+ ],
+ });
+
+ expect(saved).toBe(true);
+ expect(input.updateContent).toHaveBeenCalledWith(
+ sid,
+ item.clientId,
+ expect.objectContaining({
+ clientId: item.clientId,
+ files: [expect.objectContaining({ id: 'new-image' })],
+ chatMessage: expect.objectContaining({
+ quotesEncoded: true,
+ slashCommandRanges: [{ start: 0, end: 4 }],
+ }),
+ }),
+ );
+ });
+
+ it('supports attachment-only queue edits and rejects a fully empty replacement', async () => {
+ const sid = `attachment-only-${Math.random().toString(36).slice(2, 8)}`;
+ const item = queued('q-attachment-only', '');
+ makerChatStore.initGlobalListeners();
+ projectionHandler?.(projection(sid, { pendingQueue: [item] }));
+
+ const content = {
+ text: '',
+ mentions: [],
+ hasQuotes: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ };
+ const saved = await makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content,
+ files: [
+ {
+ id: 'only-image',
+ name: 'only.png',
+ path: 'C:\\images\\only.png',
+ ext: 'png',
+ size: 1,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'xdt-image://session/only.png',
+ },
+ ],
+ });
+ expect(saved).toBe(true);
+
+ input.updateContent.mockClear();
+ const rejected = await makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content,
+ files: [],
+ });
+ expect(rejected).toBe(false);
+ expect(input.updateContent).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unchanged queued image in place instead of copying its shared draft view', async () => {
+ const sid = `existing-image-${Math.random().toString(36).slice(2, 8)}`;
+ const item = queued('q-existing-image', 'keep image');
+ const existingImage = {
+ id: 'existing-image',
+ name: 'existing.png',
+ path: 'C:\\images\\existing.png',
+ ext: 'png',
+ size: 10,
+ category: 'image' as const,
+ mimeType: 'image/png',
+ url: 'xdt-image://session/existing.png',
+ };
+ item.files = [{ ...existingImage, pathOrigin: 'desktop-host' }];
+ makerChatStore.initGlobalListeners();
+ projectionHandler?.(projection(sid, { pendingQueue: [item] }));
+
+ const saved = await makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content: {
+ text: item.text,
+ mentions: [],
+ hasQuotes: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ },
+ files: [{ ...existingImage, cacheUrlShared: true, stagedPathShared: true }],
+ });
+
+ expect(saved).toBe(true);
+ expect(cacheMediaForSession).not.toHaveBeenCalled();
+ expect(input.updateContent).toHaveBeenCalledWith(
+ sid,
+ item.clientId,
+ expect.objectContaining({
+ files: [expect.objectContaining({ url: existingImage.url })],
+ }),
+ );
+ });
+
it('keeps queue controls on the sticky remote device while the live mirror is rebuilding', async () => {
const sid = `sticky-row-${Math.random().toString(36).slice(2, 8)}`;
const deviceId = 'dev-sticky';
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts
index 7317ddbd8f..e57356d147 100644
--- a/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pendingQueueSteerShortcut.test.ts
@@ -22,7 +22,7 @@ describe('PendingQueuePanel steer shortcut contract', () => {
const rowKeydownBlock = extractBetween(
pendingQueueSource,
'const handleRowKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {',
- 'const handleEditKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {',
+ 'const handleDragHandleKeyDown = (e: ReactKeyboardEvent<HTMLButtonElement>) => {',
);
expect(shortcutHelper).toContain("event.key === 'Enter'");
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 99bb71fa84..4854a48af9 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -580,8 +580,18 @@ interface ChatInputProps {
onQueueExpandedChange?: (expanded: boolean) => void;
/** F-QUEUE-DEFER: remove a single un-dispatched queued message. */
onQueueRemove?: (clientId: string) => void;
- /** F-QUEUE-DEFER: edit a single un-dispatched queued message's text. */
- onQueueEdit?: (clientId: string, newText: string) => void;
+ /** Queue row currently loaded into this shared composer. */
+ queueEditingClientId?: string | null;
+ /** Load one queued row into the shared composer. */
+ onQueueEditBegin?: (entry: QueuedMessage) => void;
+ /** Save the shared composer's complete text/reference/attachment snapshot. */
+ onQueueEditSubmit?: (
+ clientId: string,
+ content: SerializedComposerContent,
+ files: AttachedFile[],
+ ) => Promise<boolean>;
+ /** Cancel queue editing and restore the normal composer draft. */
+ onQueueEditCancel?: () => void;
/**
* Same-turn 插话: a queued row can be delivered into the currently-running
* turn without waiting for FIFO drain. This is a delivery choice only; the
@@ -1105,7 +1115,10 @@ export function ChatInput({
queueExpanded = false,
onQueueExpandedChange,
onQueueRemove,
- onQueueEdit,
+ queueEditingClientId = null,
+ onQueueEditBegin,
+ onQueueEditSubmit,
+ onQueueEditCancel,
onQueueSteer,
steeringQueueClientIds = [],
queuePaused = false,
@@ -1390,6 +1403,11 @@ export function ChatInput({
queueExpandedRef.current = queueExpanded;
const onQueueExpandedChangeRef = useRef(onQueueExpandedChange);
onQueueExpandedChangeRef.current = onQueueExpandedChange;
+ const queueEditingClientIdRef = useRef(queueEditingClientId);
+ queueEditingClientIdRef.current = queueEditingClientId;
+ const onQueueEditCancelRef = useRef(onQueueEditCancel);
+ onQueueEditCancelRef.current = onQueueEditCancel;
+ const queueEditCancelAllowedRef = useRef(true);
// F-QUEUE-DEFER: outside-click collapses the queue tail. Boundary = the
// palette anchor layer that holds the merged card (panel + input editor)
// AND the palette host (slash / at-mention popovers) — clicking into the
@@ -2052,6 +2070,7 @@ export function ChatInput({
// sendDispatchInFlight 锁到 onSend 结算,避免按钮亮着点了却被 in-flight guard 静默丢掉。
const [sendDispatchInFlight, setSendDispatchInFlight] = useState(false);
const [allowTypeDuringSend, setAllowTypeDuringSend] = useState(false);
+ queueEditCancelAllowedRef.current = !sendDispatchInFlight;
const composerEditorLocked = disabled || sendDispatchInFlight;
const composerMutationLockedRef = useRef(composerEditorLocked);
composerMutationLockedRef.current = composerEditorLocked;
@@ -2471,6 +2490,15 @@ export function ChatInput({
// ESC — back out of the topmost thing the user is interacting with.
if (event.key === 'Escape') {
+ if (
+ queueEditingClientIdRef.current &&
+ queueEditCancelAllowedRef.current &&
+ onQueueEditCancelRef.current
+ ) {
+ event.preventDefault();
+ onQueueEditCancelRef.current();
+ return true;
+ }
// F-QUEUE-DEFER: if the queue tail is expanded, Esc collapses that
// visual tail before falling through to Stop.
if (queueExpandedRef.current && onQueueExpandedChangeRef.current) {
@@ -5906,6 +5934,41 @@ export function ChatInput({
[onQueueSteer],
);
+ const queueEditActive = Boolean(queueEditingClientId && onQueueEditSubmit);
+ const submitQueueEdit = useCallback(async () => {
+ if (
+ !editor ||
+ editor.isDestroyed ||
+ !queueEditingClientId ||
+ !onQueueEditSubmit ||
+ disabled ||
+ sendDispatchInFlight
+ ) {
+ return;
+ }
+ const content = serializeEditorContent(editor);
+ if (content.text.trim().length === 0 && attachments.length === 0) return;
+
+ setSendDispatchInFlight(true);
+ try {
+ const saved = await onQueueEditSubmit(queueEditingClientId, content, [...attachments]);
+ if (!saved) toast.error(t('errors.INTERNAL'));
+ } catch (error) {
+ log.warn('queue edit rejected:', error instanceof Error ? error.message : String(error));
+ toast.error(t(mapIpcErrorToI18nKey(error, { fallback: 'errors.INTERNAL' })));
+ } finally {
+ setSendDispatchInFlight(false);
+ }
+ }, [
+ attachments,
+ disabled,
+ editor,
+ onQueueEditSubmit,
+ queueEditingClientId,
+ sendDispatchInFlight,
+ t,
+ ]);
+
const acceptPromptRecommendation = useCallback((): boolean => {
if (
!editor ||
@@ -5933,6 +5996,10 @@ export function ChatInput({
const handleClickSend = useCallback(
async (deliveryMode: MessageDeliveryMode = 'queue') => {
+ if (queueEditActive) {
+ await submitQueueEdit();
+ return;
+ }
if (voiceBusyOnCurrentComposer) {
const currentCanSend = !isEditorEmpty(editor) || hasAttachments;
if (!voiceInput.isListening && !currentCanSend && voiceInput.draftText.trim().length === 0)
@@ -5969,6 +6036,8 @@ export function ChatInput({
editor,
handleVoiceInputStop,
hasAttachments,
+ queueEditActive,
+ submitQueueEdit,
voiceBusyOnCurrentComposer,
voiceInput.draftText,
voiceInput.isBusy,
@@ -8116,7 +8185,9 @@ export function ChatInput({
serializeEditorContent(editor).text, slashCommandsReady ? mergedCommands : null,
).kind === 'start';
const [voiceReleaseToSendActive, setVoiceReleaseToSendActive] = useState(false);
- const sendButtonDisabled = Boolean(
+ const sendButtonDisabled = queueEditActive
+ ? Boolean(disabled || sendDispatchInFlight || (!hasMessage && !hasAttachments))
+ : Boolean(
disabled || sessionModelLoading ||
// 空態:当前 agent 无已连接来源 → Send 禁用(设计 Q7NYAD「send 置灰」),引导用户先去连接来源。
(!makeNeedsNoModel && noConnectedSource) ||
@@ -8157,13 +8228,15 @@ export function ChatInput({
// (listening + submitting + refining), 让槽位从开录到润色结束保持不变; 润色期间主槽是
// 禁用态 Send (见 sendButtonDisabled), 停止任务的能力由次槽 Stop 承担.
const mainSlotIsStop =
+ !queueEditActive &&
showStopButton && (sendDispatchInFlight || (!canSend && !voiceBusyOnCurrentComposer));
const showSecondaryStop =
+ !queueEditActive &&
showStopButton && (canSend || voiceBusyOnCurrentComposer) && !sendDispatchInFlight;
useEffect(() => {
- voiceInputCanStopAndSendRef.current = !sendButtonDisabled;
+ voiceInputCanStopAndSendRef.current = !queueEditActive && !sendButtonDisabled;
composerCanSubmitRef.current = !sendButtonDisabled;
- }, [sendButtonDisabled]);
+ }, [queueEditActive, sendButtonDisabled]);
const canReleaseVoiceToSend = Boolean(
!disabled && (voiceInput.isListening || canSend || hasVoiceDraftText),
);
@@ -8266,7 +8339,10 @@ export function ChatInput({
expanded={queueExpanded}
onToggle={() => queuePanelState.onExpandedChange(!queueExpanded)}
onRemove={queuePanelState.onRemove}
- onEdit={onQueueEdit}
+ editingClientId={queueEditingClientId}
+ editSubmitting={sendDispatchInFlight}
+ onEditBegin={onQueueEditBegin}
+ onEditCancel={onQueueEditCancel}
onSteer={onQueueSteer ? handleQueueSteer : undefined}
steeringClientIds={steeringQueueClientIds}
paused={queuePaused}
@@ -8962,26 +9038,49 @@ export function ChatInput({
visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
/>
)}
- <VoiceInputButton
- state={voiceBusyOnCurrentComposer ? voiceInput.state : 'idle'}
- // The surrounding controls stay locked during voice input, but
- // this control must remain enabled so the recording can stop.
- disabled={
- composerEditorLocked ||
- !editor ||
- (voiceInput.isBusy && !voiceBusyOnCurrentComposer)
- }
- shortcutLabel={voiceInputShortcutLabel}
- onStart={handleVoiceInputStart}
- onStop={handleVoiceInputPlainStop}
- onStopAndSend={handleClickSend}
- sendTargetRef={sendButtonRef}
- canReleaseToSend={canReleaseVoiceToSend}
- releaseToSendActive={voiceReleaseToSendActive}
- onReleaseToSendChange={setVoiceReleaseToSendActive}
- visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
- className={isCreateAgentVariant && !useNarrowToolbar ? 'ml-[7px]' : undefined}
- />
+ {queueEditActive && (
+ <Tip text={t('newChat.pendingQueue.editCancelAria')} side="top">
+ <button
+ type="button"
+ onClick={onQueueEditCancel}
+ disabled={sendDispatchInFlight}
+ className={cn(
+ 'flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-full',
+ 'border border-[var(--border-default)] bg-[var(--composer-pill-bg)] text-[var(--composer-pill-icon)]',
+ 'transition-colors hover:bg-[var(--model-trigger-hover)] focus-visible:outline-none',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ 'disabled:cursor-wait disabled:opacity-40',
+ )}
+ aria-label={t('newChat.pendingQueue.editCancelAria')}
+ >
+ <X size={15} strokeWidth={2} aria-hidden />
+ </button>
+ </Tip>
+ )}
+ {!queueEditActive && (
+ <VoiceInputButton
+ state={voiceBusyOnCurrentComposer ? voiceInput.state : 'idle'}
+ // The surrounding controls stay locked during voice input, but
+ // this control must remain enabled so the recording can stop.
+ disabled={
+ composerEditorLocked ||
+ !editor ||
+ (voiceInput.isBusy && !voiceBusyOnCurrentComposer)
+ }
+ shortcutLabel={voiceInputShortcutLabel}
+ onStart={handleVoiceInputStart}
+ onStop={handleVoiceInputPlainStop}
+ onStopAndSend={handleClickSend}
+ sendTargetRef={sendButtonRef}
+ canReleaseToSend={canReleaseVoiceToSend}
+ releaseToSendActive={voiceReleaseToSendActive}
+ onReleaseToSendChange={setVoiceReleaseToSendActive}
+ visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
+ className={
+ isCreateAgentVariant && !useNarrowToolbar ? 'ml-[7px]' : undefined
+ }
+ />
+ )}
{/* mousedown 吃掉默认行为:否则点发送会把焦点从 contenteditable
挪到 button 上,发完光标就没了(接着打字要先点回输入框),
推荐提示词的 Tab 也会因为编辑器失焦而落到原生焦点导航上。
@@ -9006,7 +9105,9 @@ export function ChatInput({
) : (
<Tip
text={
- voiceReleaseToSendActive
+ queueEditActive
+ ? t('newChat.pendingQueue.editSaveAria')
+ : voiceReleaseToSendActive
? t('newChat.chatInput.voiceInput.releaseToSend')
: voiceInput.isListening && !sendButtonDisabled
? `${t('newChat.chatInput.voiceInput.finishAndSend')} · ${composerSendShortcutLabel}`
@@ -9034,11 +9135,14 @@ export function ChatInput({
<SendButton
disabled={sendButtonDisabled}
highlighted={voiceReleaseToSendActive}
+ action={queueEditActive ? 'save' : 'send'}
visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
ariaLabel={
- showStopButton
- ? t('newChat.sendButton.queue')
- : t('newChat.sendButton.send')
+ queueEditActive
+ ? t('newChat.pendingQueue.editSaveAria')
+ : showStopButton
+ ? t('newChat.sendButton.queue')
+ : t('newChat.sendButton.send')
}
onClick={() => {
void handleClickSend();
diff --git a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
index f8de515f21..82d026f1ff 100644
--- a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
@@ -24,7 +24,6 @@ import {
AlarmClock,
ArrowUp,
Bot,
- Check,
ChevronDown,
ChevronUp,
GripVertical,
@@ -38,7 +37,6 @@ import { useTranslation } from 'react-i18next';
import { SortableList } from '@/components/sidebar/SortableList';
import { SentInlineAtomBody } from '@/components/chat/SentInlineAtomBody';
-import { ListComposerTextarea } from './ListComposerTextarea';
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
@@ -52,10 +50,7 @@ import {
isPendingQueueRowActive,
prunePendingQueueRowActivity,
} from './pendingQueueRowActivity';
-import {
- getPendingQueueRowPresentation,
- resolvePendingQueueEditSubmission,
-} from './pendingQueueRowPresentation';
+import { getPendingQueueRowPresentation } from './pendingQueueRowPresentation';
import {
acquireQueueEditLock,
acquireQueueInteractionLock,
@@ -71,7 +66,14 @@ interface PendingQueuePanelProps {
expanded: boolean;
onToggle: () => void;
onRemove: (clientId: string) => void;
- onEdit?: (clientId: string, newText: string) => void;
+ /** Queue row currently loaded into the shared composer. */
+ editingClientId?: string | null;
+ /** Complete-content replacement is in flight; keep the row lock until it settles. */
+ editSubmitting?: boolean;
+ /** Load a queued message into the shared composer. */
+ onEditBegin?: (entry: QueuedMessage) => void;
+ /** Leave composer-backed queue editing and restore the normal draft. */
+ onEditCancel?: () => void;
onSteer?: (clientId: string) => Promise<boolean>;
steeringClientIds?: string[];
/** True after Stop pauses queued messages. */
@@ -150,7 +152,10 @@ export function PendingQueuePanel({
expanded,
onToggle,
onRemove,
- onEdit,
+ editingClientId = null,
+ editSubmitting = false,
+ onEditBegin,
+ onEditCancel,
onSteer,
steeringClientIds = [],
paused = false,
@@ -166,9 +171,6 @@ export function PendingQueuePanel({
const { t } = useTranslation();
const resolvedAriaLabel = ariaLabel ?? t('newChat.pendingQueue.regionAria');
const [rowActivity, setRowActivity] = useState(emptyPendingQueueRowActivityState);
- const [editingClientId, setEditingClientId] = useState<string | null>(null);
- const [editingDraft, setEditingDraft] = useState<string>('');
- const editingTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const editingLockOwnerRef = useRef<QueueEditLockOwner | null>(null);
const onEditLockRef = useRef(onEditLock);
const interactionLockedRef = useRef(false);
@@ -232,8 +234,6 @@ export function PendingQueuePanel({
useEffect(() => {
if (editingClientId !== null && !queue.some((q) => q.clientId === editingClientId)) {
releaseEditLock(editingClientId);
- setEditingClientId(null);
- setEditingDraft('');
}
setRowActivity((activity) =>
prunePendingQueueRowActivity(activity, queue.map(getQueuedMessageId)),
@@ -241,42 +241,24 @@ export function PendingQueuePanel({
}, [editingClientId, queue, releaseEditLock]);
useEffect(() => {
- if (editingClientId === null) return;
- const ta = editingTextareaRef.current;
- if (!ta) return;
- ta.focus();
- ta.select();
- }, [editingClientId]);
+ if (editingClientId !== null) acquireEditLock(editingClientId);
+ else releaseEditLock();
+ }, [acquireEditLock, editingClientId, releaseEditLock]);
const beginEdit = useCallback(
- (clientId: string, currentText: string) => {
- if (!onEdit) return;
- if (steeringClientIds.includes(clientId)) return;
- acquireEditLock(clientId);
- setEditingClientId(clientId);
- setEditingDraft(currentText);
+ (entry: QueuedMessage) => {
+ if (!onEditBegin) return;
+ if (steeringClientIds.includes(entry.clientId)) return;
+ acquireEditLock(entry.clientId);
+ onEditBegin(entry);
},
- [acquireEditLock, onEdit, steeringClientIds],
+ [acquireEditLock, onEditBegin, steeringClientIds],
);
const cancelEdit = useCallback(() => {
releaseEditLock(editingClientId);
- setEditingClientId(null);
- setEditingDraft('');
- }, [editingClientId, releaseEditLock]);
-
- const commitEdit = useCallback(() => {
- if (editingClientId === null) return;
- const trimmed = editingDraft.trim();
- if (trimmed.length > 0) {
- const entry = queue.find((item) => item.clientId === editingClientId);
- const submission = entry ? resolvePendingQueueEditSubmission(entry, editingDraft) : null;
- if (submission !== null) onEdit?.(editingClientId, submission);
- }
- releaseEditLock(editingClientId);
- setEditingClientId(null);
- setEditingDraft('');
- }, [editingClientId, editingDraft, onEdit, queue, releaseEditLock]);
+ onEditCancel?.();
+ }, [editingClientId, onEditCancel, releaseEditLock]);
const handleSortableReorder = useCallback(
(nextVisibleIds: string[]) => {
@@ -326,7 +308,10 @@ export function PendingQueuePanel({
const isSteering = steeringClientIds.includes(entry.clientId);
const showActions = !isPendingEnqueue && (isRowActive || isSteering || isRowEditing);
const canSteerRow = Boolean(onSteer) && rowPresentation.canSteer;
- const canEditRow = Boolean(onEdit) && rowPresentation.canEdit;
+ const canEditRow =
+ Boolean(onEditBegin) &&
+ rowPresentation.canEdit &&
+ (editingClientId === null || isRowEditing);
const chatMessageContent = entry.chatMessage.content ?? entry.text;
const agentReferences =
entry.chatMessage.agentReferences?.length
@@ -382,19 +367,6 @@ export function PendingQueuePanel({
e.stopPropagation();
void onSteer(entry.clientId);
};
- const handleEditKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
- e.preventDefault();
- e.stopPropagation();
- commitEdit();
- return;
- }
- if (e.key === 'Escape') {
- e.preventDefault();
- e.stopPropagation();
- cancelEdit();
- }
- };
const handleDragHandleKeyDown = (e: ReactKeyboardEvent<HTMLButtonElement>) => {
if (isPendingQueueSteerShortcut(e)) return;
if (dragDisabled || !onReorder) return;
@@ -470,8 +442,8 @@ export function PendingQueuePanel({
className={cn(
'group flex gap-1.5 rounded-[8px] border border-transparent px-2 py-0.5',
// 单行展示态整行垂直居中, 让 drag handle / 文字 / actions 光学对齐;
- // 编辑态 textarea 可能多行, 保持顶对齐让 handle / actions 留在首行。
- isRowEditing ? 'items-start' : 'items-center',
+ // 编辑态仅保留行高亮与取消入口,正文统一在主输入框修改。
+ 'items-center',
(isRowActive || isRowEditing) && 'bg-[var(--chat-input-chip-bg)]',
)}
>
@@ -492,22 +464,7 @@ export function PendingQueuePanel({
>
<GripVertical size={12} strokeWidth={2} aria-hidden />
</button>
- {isRowEditing ? (
- <ListComposerTextarea
- ref={editingTextareaRef}
- value={editingDraft}
- onChange={(e) => setEditingDraft(e.target.value)}
- onKeyDown={handleEditKeyDown}
- onBlur={commitEdit}
- rows={1}
- aria-label={t('newChat.pendingQueue.editAria', { index: originalIdx + 1 })}
- className={cn(
- 'min-h-[18px] min-w-0 flex-1 resize-none rounded-[6px] bg-transparent text-13 leading-[1.25]',
- 'max-h-[120px] overflow-y-auto text-[var(--msg-assistant-text)] outline-none',
- '[field-sizing:content]',
- )}
- />
- ) : rowPresentation.isOrca || rowPresentation.isScheduler ? (
+ {rowPresentation.isOrca || rowPresentation.isScheduler ? (
<div
aria-label={t(
rowPresentation.isScheduler
@@ -574,26 +531,16 @@ export function PendingQueuePanel({
<Spinner size={12} strokeWidth={2.25} />
</span>
) : isRowEditing ? (
- <div className="flex shrink-0 items-center gap-1">
+ <div className="flex shrink-0 items-center">
<button
type="button"
- onMouseDown={(e) => e.preventDefault()}
onClick={cancelEdit}
+ disabled={editSubmitting}
aria-label={t('newChat.pendingQueue.editCancelAria')}
- className={iconButtonClassName}
+ className={cn(iconButtonClassName, 'disabled:cursor-wait disabled:opacity-40')}
>
<X size={12} strokeWidth={2.25} aria-hidden />
</button>
- <button
- type="button"
- onMouseDown={(e) => e.preventDefault()}
- onClick={commitEdit}
- disabled={editingDraft.trim().length === 0}
- aria-label={t('newChat.pendingQueue.editSaveAria')}
- className={cn(iconButtonClassName, 'disabled:opacity-40')}
- >
- <Check size={12} strokeWidth={2.25} aria-hidden />
- </button>
</div>
) : showActions ? (
<div
@@ -630,7 +577,7 @@ export function PendingQueuePanel({
<Tip text={t('newChat.pendingQueue.editAction')} side="top">
<button
type="button"
- onClick={() => beginEdit(entry.clientId, rowPresentation.displayText)}
+ onClick={() => beginEdit(entry)}
aria-label={t('newChat.pendingQueue.editAria', { index: originalIdx + 1 })}
className={iconButtonClassName}
>
diff --git a/apps/desktop/src/renderer/components/new-chat/SendButton.tsx b/apps/desktop/src/renderer/components/new-chat/SendButton.tsx
index 54668c6ea0..5aded1da66 100644
--- a/apps/desktop/src/renderer/components/new-chat/SendButton.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/SendButton.tsx
@@ -1,5 +1,6 @@
import { forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -12,6 +13,8 @@ interface SendButtonProps {
highlighted?: boolean;
/** Override for the accessible action name when Send visually means Queue. */
ariaLabel?: string;
+ /** Save reuses the send button shell while queue content is edited in the composer. */
+ action?: 'send' | 'save';
/** CREATE AGENT 首页按 Figma 185:2724 使用独立私有 token。 */
visualVariant?: 'default' | 'create-agent';
}
@@ -36,7 +39,15 @@ function CreateAgentSendIcon() {
* Stop (streaming):复用 Send 壳样式,仅把内容换成 10×10 圆角 1.5 的停止方块
*/
export const SendButton = forwardRef<HTMLButtonElement, SendButtonProps>(function SendButton(
- { disabled, onClick, isStreaming = false, highlighted = false, ariaLabel, visualVariant = 'default' },
+ {
+ disabled,
+ onClick,
+ isStreaming = false,
+ highlighted = false,
+ ariaLabel,
+ action = 'send',
+ visualVariant = 'default',
+ },
ref,
) {
const { t } = useTranslation();
@@ -71,7 +82,11 @@ export const SendButton = forwardRef<HTMLButtonElement, SendButtonProps>(functio
isStreaming ? 'scale-75 opacity-0' : 'scale-100 opacity-100',
)}
>
- <CreateAgentSendIcon />
+ {action === 'save' ? (
+ <Check className="h-4 w-4" strokeWidth={2.4} />
+ ) : (
+ <CreateAgentSendIcon />
+ )}
</span>
<span
className={cn(
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 3549a09ddd..9af8782486 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -142,7 +142,7 @@ import { TopRightChipStack, TopRightChipStackProvider } from '@/components/chat/
import { ChatDisplaySnapshotProvider } from '@/components/chat/ChatDisplaySnapshotContext';
import { useCCAgentChat } from '@/hooks/useCCAgentChat';
import { ackErrorAlertHandled } from '@/lib/errorAlertAck';
-import { useAttachments } from '@/hooks/useAttachments';
+import { cleanupRemovedCachedImage, useAttachments } from '@/hooks/useAttachments';
import { useCCSessions } from '@/hooks/useCCSessions';
import { SessionContentHeaderRegistration } from './SessionContentHeader';
import { resolveSessionInterruptCandidate } from './sessionInterruptBannerModel';
@@ -207,6 +207,7 @@ import {
makerChatStore,
type AgentTaskUpdate,
type MessageDeliveryMode,
+ type QueuedMessage,
} from '@/lib/makerChatStore';
import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';
import { openSubagentsTab } from '@/features/right-sidebar/lib/openSubagentsTab';
@@ -237,6 +238,9 @@ import {
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import type { AttachedFile, ComposerBotMention, MentionedResource } from '@/lib/fileTypes';
import { serializeAttachedFiles } from '@/lib/messageAttachmentPayload';
+import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
+import { queueMessageToComposerEditDraft } from '@/lib/queueComposerEdit';
+import type { SerializedComposerContent } from '@/components/new-chat/composerContentSerialization';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import { createLogger } from '@/lib/logger';
import { subscribeWorkLouderCodexAction } from '@/lib/workLouderCodexActions';
@@ -269,6 +273,9 @@ import {
type RecoverableHandoffKind,
} from '@/state/pendingFirstMessage';
import {
+ clearDraftAndNotify as clearComposerDraftAndNotify,
+ discardDraft as discardComposerDraft,
+ getDraft as getComposerDraft,
saveDraft as saveComposerDraft,
getDraftPresence as getComposerDraftPresence,
plainTextToTiptapDoc,
@@ -1428,7 +1435,21 @@ export function CCAgentSessionView({
// Attachments are managed here so the entire content area can act as a drop zone.
// image-local-cache: pass sessionId so addFiles/addClipboardImage can cache
// images into userData/cc-agent/images/{sessionId}/ via IPC.
- const attachmentState = useAttachments(sessionId);
+ const [queueComposerEdit, setQueueComposerEdit] = useState<{
+ sessionId: string;
+ clientId: string;
+ draftKey: string;
+ originalAttachmentIds: string[];
+ } | null>(null);
+ const activeQueueComposerEdit =
+ queueComposerEdit?.sessionId === sessionId ? queueComposerEdit : null;
+ const queueComposerEditRef = useRef(queueComposerEdit);
+ queueComposerEditRef.current = queueComposerEdit;
+ const queueComposerEditSavingRef = useRef(false);
+ const composerDraftKey = activeQueueComposerEdit?.draftKey ?? sessionId;
+ const attachmentState = useAttachments(sessionId, composerDraftKey);
+ const queueComposerEditAttachmentsRef = useRef<readonly AttachedFile[]>([]);
+ queueComposerEditAttachmentsRef.current = attachmentState.attachments;
const [isDragOver, setIsDragOver] = useState(false);
const dragCounterRef = useRef(0);
const resetFullAreaDragState = useCallback(() => {
@@ -1776,9 +1797,110 @@ export function CCAgentSessionView({
setQueueInteractionLock,
setQueueEditLock,
removeFromQueue,
- updateQueueItem,
+ updateQueueItemContent,
chatDisplaySnapshot,
} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });
+
+ const clearQueueComposerEditDraft = useCallback(
+ (edit: NonNullable<typeof queueComposerEdit>, files: readonly AttachedFile[]) => {
+ const originalIds = new Set(edit.originalAttachmentIds);
+ const addedFiles = files.filter((file) => !originalIds.has(file.id));
+ for (const file of addedFiles) cleanupRemovedCachedImage(file);
+ cleanupStagedChatAttachmentFiles(addedFiles);
+ discardComposerDraft(edit.draftKey);
+ },
+ [],
+ );
+
+ const beginQueueComposerEdit = useCallback(
+ (entry: QueuedMessage) => {
+ if (!sessionId || activeQueueComposerEdit) return;
+ const prepared = queueMessageToComposerEditDraft(sessionId, entry);
+ const nextEdit = {
+ sessionId,
+ clientId: entry.clientId,
+ draftKey: prepared.draftKey,
+ originalAttachmentIds: prepared.originalAttachmentIds,
+ };
+ saveComposerDraft(prepared.draftKey, prepared.draft);
+ queueComposerEditRef.current = nextEdit;
+ setQueueComposerEdit(nextEdit);
+ },
+ [activeQueueComposerEdit, sessionId],
+ );
+
+ const cancelQueueComposerEdit = useCallback(() => {
+ if (queueComposerEditSavingRef.current) return;
+ const edit = activeQueueComposerEdit;
+ if (!edit) return;
+ clearQueueComposerEditDraft(edit, attachmentState.attachments);
+ attachmentState.clearFiles();
+ queueComposerEditRef.current = null;
+ setQueueComposerEdit(null);
+ }, [activeQueueComposerEdit, attachmentState, clearQueueComposerEditDraft]);
+
+ const submitQueueComposerEdit = useCallback(
+ async (clientId: string, content: SerializedComposerContent, files: AttachedFile[]) => {
+ const edit = activeQueueComposerEdit;
+ if (!edit || edit.clientId !== clientId || queueComposerEditSavingRef.current) return false;
+ queueComposerEditSavingRef.current = true;
+ let rowDisappeared = false;
+ try {
+ const updated = await updateQueueItemContent(clientId, { content, files });
+ if (!updated) {
+ rowDisappeared = !makerChatStore
+ .getSnapshot(edit.sessionId)
+ .pendingQueue.some((entry) => entry.clientId === clientId);
+ return false;
+ }
+ attachmentState.clearFiles();
+ clearComposerDraftAndNotify(edit.draftKey);
+ queueComposerEditRef.current = null;
+ setQueueComposerEdit(null);
+ return true;
+ } finally {
+ queueComposerEditSavingRef.current = false;
+ if (rowDisappeared) queueMicrotask(cancelQueueComposerEdit);
+ }
+ },
+ [
+ activeQueueComposerEdit,
+ attachmentState,
+ cancelQueueComposerEdit,
+ updateQueueItemContent,
+ ],
+ );
+
+ useEffect(() => {
+ return () => {
+ if (queueComposerEditSavingRef.current) return;
+ const edit = queueComposerEditRef.current;
+ if (!edit || edit.sessionId !== sessionId) return;
+ const filesById = new Map(
+ queueComposerEditAttachmentsRef.current.map((file) => [file.id, file]),
+ );
+ for (const file of getComposerDraft(edit.draftKey)?.attachments ?? []) {
+ filesById.set(file.id, file);
+ }
+ clearQueueComposerEditDraft(edit, [...filesById.values()]);
+ queueComposerEditRef.current = null;
+ };
+ }, [clearQueueComposerEditDraft, sessionId]);
+
+ useEffect(() => {
+ if (queueComposerEdit && queueComposerEdit.sessionId !== sessionId) {
+ setQueueComposerEdit(null);
+ }
+ }, [queueComposerEdit, sessionId]);
+
+ useEffect(() => {
+ if (
+ activeQueueComposerEdit &&
+ !pendingQueue.some((entry) => entry.clientId === activeQueueComposerEdit.clientId)
+ ) {
+ cancelQueueComposerEdit();
+ }
+ }, [activeQueueComposerEdit, cancelQueueComposerEdit, pendingQueue]);
const makeState = useCindyMakeState();
const cindyMakePreparation = useMemo(
() =>
@@ -5324,13 +5446,18 @@ export function CCAgentSessionView({
onStop={handleStopSession}
pendingQueue={pendingQueue}
disabled={readOnly || remoteHandoffPreparing || session?.source === 'review'}
- settingsLocked={readOnly || session?.source === 'review'}
+ settingsLocked={
+ readOnly || session?.source === 'review' || Boolean(activeQueueComposerEdit)
+ }
queuePaused={queuePaused}
queueExpanded={queueExpanded}
onQueueExpandedChange={setQueueExpanded}
onQueueResume={resumeQueue}
onQueueRemove={removeFromQueue}
- onQueueEdit={updateQueueItem}
+ queueEditingClientId={activeQueueComposerEdit?.clientId ?? null}
+ onQueueEditBegin={beginQueueComposerEdit}
+ onQueueEditSubmit={submitQueueComposerEdit}
+ onQueueEditCancel={cancelQueueComposerEdit}
onQueueSteer={steerQueuedMessage}
onQueueReorder={moveQueueItem}
onQueueInteractionLock={setQueueInteractionLock}
@@ -5352,6 +5479,7 @@ export function CCAgentSessionView({
onEffortDidChange={handleEffortDidChange}
onPermissionModeDidChange={handlePermissionModeDidChange}
attachmentState={attachmentState}
+ draftKey={composerDraftKey}
externalDragOver={isDragOver}
onComposerDropHandled={resetFullAreaDragState}
vendorKey={normalizeDbAgentKind(displayAgentKind)}
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index a218615259..55585cd260 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -48,6 +48,7 @@ import {
type PendingRemoteDesktopConfirmation,
type PendingPlanReview,
type PlanViewerState,
+ type QueueItemContentUpdate,
type QueuedMessage,
type SessionChatLightState,
type SessionChatState,
@@ -114,8 +115,8 @@ interface UseCCAgentChatReturn {
setQueueEditLock: (clientId: string, locked: boolean) => void;
/** F-QUEUE-DEFER: 从队列中移除一条未派发消息(行尾 ✕)。已在派发的不可移除。 */
removeFromQueue: (clientId: string) => void;
- /** F-QUEUE-DEFER: 修改一条未派发消息的文本(行尾 ✏️)。空文本/找不到/未变化时 no-op。 */
- updateQueueItem: (clientId: string, newText: string) => void;
+ /** F-QUEUE-DEFER: replace one queued message's complete composer content. */
+ updateQueueItemContent: (clientId: string, update: QueueItemContentUpdate) => Promise<boolean>;
sendMessage: (
text: string,
model: string,
@@ -812,10 +813,10 @@ export function useCCAgentChat(
[sessionId],
);
- const updateQueueItem = useCallback(
- (clientId: string, newText: string) => {
- if (!sessionId) return;
- makerChatStore.updateQueueItem(sessionId, clientId, newText);
+ const updateQueueItemContent = useCallback(
+ (clientId: string, update: QueueItemContentUpdate) => {
+ if (!sessionId) return Promise.resolve(false);
+ return makerChatStore.updateQueueItemContent(sessionId, clientId, update);
},
[sessionId],
);
@@ -838,7 +839,7 @@ export function useCCAgentChat(
setQueueInteractionLock,
setQueueEditLock,
removeFromQueue,
- updateQueueItem,
+ updateQueueItemContent,
sendMessage,
compactSession,
steerMessage,
diff --git a/apps/desktop/src/renderer/lib/__tests__/chatAttachmentStageCleanup.test.ts b/apps/desktop/src/renderer/lib/__tests__/chatAttachmentStageCleanup.test.ts
new file mode 100644
index 0000000000..f74a10d8a1
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/chatAttachmentStageCleanup.test.ts
@@ -0,0 +1,39 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
+
+const cleanupStagedChatAttachments = vi.fn(async () => undefined);
+let previousWindow: typeof globalThis.window | undefined;
+
+beforeAll(() => {
+ previousWindow = globalThis.window;
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: { electronAPI: { cleanupStagedChatAttachments } },
+ });
+});
+
+afterAll(() => {
+ if (previousWindow === undefined) Reflect.deleteProperty(globalThis, 'window');
+ else {
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: previousWindow,
+ });
+ }
+});
+
+beforeEach(() => {
+ cleanupStagedChatAttachments.mockClear();
+});
+
+describe('cleanupStagedChatAttachmentFiles', () => {
+ it('does not delete a staged path shared with a queued message', () => {
+ cleanupStagedChatAttachmentFiles([
+ { path: 'C:\\cache\\owned.bin', stagedPathShared: true },
+ { path: 'C:\\cache\\draft.bin' },
+ ]);
+
+ expect(cleanupStagedChatAttachments).toHaveBeenCalledWith(['C:\\cache\\draft.bin']);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts b/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts
new file mode 100644
index 0000000000..7cb0b4cd67
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+
+import type { QueuedMessage } from '@/lib/makerChatStore';
+import {
+ queueComposerEditDraftKey,
+ queueMessageToComposerEditDraft,
+} from '@/lib/queueComposerEdit';
+
+function queuedMessage(): QueuedMessage {
+ return {
+ clientId: 'queue-1',
+ text: 'queued text',
+ persistedContent: JSON.stringify({ text: 'queued text' }),
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: 'C:\\workspace',
+ files: [
+ {
+ id: 'existing-image',
+ name: 'existing.png',
+ path: 'C:\\images\\existing.png',
+ ext: 'png',
+ size: 10,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'xdt-image://session/existing.png',
+ pathOrigin: 'desktop-host',
+ },
+ ],
+ chatMessage: {
+ clientId: 'queue-1',
+ role: 'user',
+ content: 'queued text',
+ isStreaming: false,
+ },
+ createOpts: {
+ agentKind: 'claude-code',
+ workingDir: 'C:\\workspace',
+ model: 'model',
+ },
+ };
+}
+
+describe('queueMessageToComposerEditDraft', () => {
+ it('uses an isolated draft key and treats queued image caches as shared', () => {
+ const prepared = queueMessageToComposerEditDraft('session-1', queuedMessage());
+
+ expect(prepared.draftKey).toBe(queueComposerEditDraftKey('session-1', 'queue-1'));
+ expect(prepared.originalAttachmentIds).toEqual(['existing-image']);
+ expect(prepared.draft.attachments).toEqual([
+ expect.objectContaining({
+ id: 'existing-image',
+ cacheUrlShared: true,
+ stagedPathShared: true,
+ }),
+ ]);
+ expect(prepared.draft.attachments[0]).not.toHaveProperty('pathOrigin');
+ expect(prepared.draft.text).toEqual(expect.objectContaining({ type: 'doc' }));
+ expect(prepared.draft.focusAtEnd).toBe(true);
+ });
+
+ it('keeps attachment-only queue rows editable', () => {
+ const entry = queuedMessage();
+ entry.text = '';
+ entry.chatMessage.content = '';
+
+ const prepared = queueMessageToComposerEditDraft('session-1', entry);
+
+ expect(prepared.draft.text).toBeNull();
+ expect(prepared.draft.attachments).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts b/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts
index 3cc2caf9c6..7ede34dd4e 100644
--- a/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts
+++ b/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts
@@ -3,10 +3,13 @@ import { createLogger } from './logger';
const log = createLogger('ChatAttachmentStageCleanup');
-function stagedPaths(files: readonly Pick<AttachedFile, 'path'>[]): string[] {
+function stagedPaths(
+ files: readonly Pick<AttachedFile, 'path' | 'stagedPathShared'>[],
+): string[] {
return [
...new Set(
files
+ .filter((file) => file.stagedPathShared !== true)
.map((file) => file.path)
.filter((filePath): filePath is string =>
typeof filePath === 'string' && filePath.toLowerCase().endsWith('.bin'),
@@ -21,7 +24,7 @@ function stagedPaths(files: readonly Pick<AttachedFile, 'path'>[]): string[] {
* to pass through and are simply ignored there.
*/
export function cleanupStagedChatAttachmentFiles(
- files: readonly Pick<AttachedFile, 'path'>[],
+ files: readonly Pick<AttachedFile, 'path' | 'stagedPathShared'>[],
): void {
const paths = stagedPaths(files);
if (paths.length === 0) return;
diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.ts
index 9da79d36b3..cbfa1c805b 100644
--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts
+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts
@@ -122,6 +122,7 @@ const ATTACHED_FILE_SNAPSHOT_KEYS = [
'annotated',
'annotationSourceUrl',
'cacheUrlShared',
+ 'stagedPathShared',
] as const;
/**
diff --git a/apps/desktop/src/renderer/lib/fileTypes.ts b/apps/desktop/src/renderer/lib/fileTypes.ts
index 4469ada3b0..2ad0f55a60 100644
--- a/apps/desktop/src/renderer/lib/fileTypes.ts
+++ b/apps/desktop/src/renderer/lib/fileTypes.ts
@@ -113,6 +113,11 @@ export interface AttachedFile {
* 删除附件时不清理该文件。缺省(false)为附件私有,删除时照常清理。
*/
cacheUrlShared?: boolean;
+ /**
+ * `path` points at a staged copy owned by another durable surface. Removing
+ * this draft attachment must not delete that shared staged file.
+ */
+ stagedPathShared?: boolean;
/**
* @deprecated image-local-cache removed blob-URL thumbnails. Setting this
* is now a compile error so any leftover code path surfaces immediately.
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 0e1091904b..c9391a6601 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -13391,6 +13391,134 @@ function updateQueueItem(sessionId: string, clientId: string, newText: string):
).catch((err) => log.warn('updateQueueItem failed:', err));
}
+export interface QueueItemContentUpdate {
+ content: {
+ text: string;
+ mentions: MentionedResource[];
+ hasQuotes: boolean;
+ agentReferences: AgentInputReference[];
+ pastedTextRanges: PastedTextRange[];
+ slashCommandRanges: SlashCommandRange[];
+ };
+ files: AttachedFile[];
+}
+
+function queuedContentProjectionMatches(
+ accepted: QueuedMessage | undefined,
+ replacement: QueuedMessage,
+): boolean {
+ if (!accepted || accepted.text !== replacement.text) return false;
+ if (accepted.persistedContent === replacement.persistedContent) return true;
+ const stableFiles = (files: QueuedMessage['files']) =>
+ (files ?? []).map(({ path: _, url: __, pathOrigin: ___, ...file }) => file);
+ return (
+ JSON.stringify(stableFiles(accepted.files)) ===
+ JSON.stringify(stableFiles(replacement.files)) &&
+ JSON.stringify(accepted.mentions ?? []) === JSON.stringify(replacement.mentions ?? []) &&
+ accepted.chatMessage.quotesEncoded === replacement.chatMessage.quotesEncoded &&
+ JSON.stringify(accepted.chatMessage.agentReferences ?? []) ===
+ JSON.stringify(replacement.chatMessage.agentReferences ?? []) &&
+ JSON.stringify(accepted.chatMessage.pastedTextRanges ?? []) ===
+ JSON.stringify(replacement.chatMessage.pastedTextRanges ?? []) &&
+ JSON.stringify(accepted.chatMessage.slashCommandRanges ?? []) ===
+ JSON.stringify(replacement.chatMessage.slashCommandRanges ?? [])
+ );
+}
+
+function cleanupUnacceptedQueueEditMaterialization(
+ originalFiles: readonly AttachedFile[],
+ preparedFiles: readonly AttachedFile[],
+): void {
+ const originalUrls = new Set(originalFiles.map((file) => file.url).filter(Boolean));
+ const generatedUrls = preparedFiles
+ .map((file) => file.url)
+ .filter((url): url is string => Boolean(url) && !originalUrls.has(url));
+ if (generatedUrls.length === 0) return;
+ void window.electronAPI.cleanupCachedImages(generatedUrls).catch((error: unknown) => {
+ log.warn('cleanup rejected queue edit images failed:', error);
+ });
+}
+
+async function updateQueueItemContent(
+ sessionId: string,
+ clientId: string,
+ update: QueueItemContentUpdate,
+): Promise<boolean> {
+ if (!sessionId || !clientId) return false;
+ const queued = getOrCreateState(sessionId).pendingQueue.find((item) => item.clientId === clientId);
+ if (!queued) return false;
+ const { content, files } = update;
+ if (!content.text.trim() && files.length === 0) return false;
+ const queuedFilesById = new Map((queued.files ?? []).map((file) => [file.id, file]));
+ const filesForMaterialization = files.map((file) => {
+ const queuedFile = queuedFilesById.get(file.id);
+ if (!queuedFile || queuedFile.url !== file.url || queuedFile.path !== file.path) return file;
+ return { ...file, cacheUrlShared: undefined, stagedPathShared: undefined };
+ });
+ const preparedFiles =
+ (await materializeAnnotatedAttachmentsForSend(filesForMaterialization, sessionId, {
+ stripAnnotationMeta: isRemoteMediaSession(sessionId),
+ })) ?? [];
+
+ const textUnchanged = content.text === queued.text;
+ const queuedAgentReferences =
+ queued.chatMessage.agentReferences?.length
+ ? queued.chatMessage.agentReferences
+ : (queued.agentReferences ?? []);
+ const replacement = buildQueuedMessage(
+ sessionId,
+ content.text,
+ queued.model,
+ queued.effort,
+ queued.permissionMode,
+ queued.workingDir,
+ preparedFiles,
+ textUnchanged ? queued.mentions : content.mentions,
+ {
+ ...(queued.vendorOptions ? { vendorOptions: queued.vendorOptions } : {}),
+ ...((textUnchanged ? queued.chatMessage.quotesEncoded === true : content.hasQuotes)
+ ? { quotesEncoded: true }
+ : {}),
+ ...((textUnchanged ? queuedAgentReferences : content.agentReferences).length > 0
+ ? { agentReferences: textUnchanged ? queuedAgentReferences : content.agentReferences }
+ : {}),
+ ...((textUnchanged
+ ? (queued.chatMessage.pastedTextRanges ?? [])
+ : content.pastedTextRanges
+ ).length > 0
+ ? {
+ pastedTextRanges: textUnchanged
+ ? queued.chatMessage.pastedTextRanges
+ : content.pastedTextRanges,
+ }
+ : {}),
+ slashCommandRanges: textUnchanged
+ ? queued.chatMessage.slashCommandRanges
+ : content.slashCommandRanges,
+ },
+ {
+ clientId: queued.clientId,
+ createdAt: queued.chatMessage.createdAt ?? new Date().toISOString(),
+ },
+ );
+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);
+ let projection: AgentInputProjection;
+ try {
+ ({ projection } = await runInputProjectionOperation(sessionId, (input) =>
+ boundaryOpts
+ ? input.updateContent(sessionId, clientId, replacement, boundaryOpts)
+ : input.updateContent(sessionId, clientId, replacement),
+ ));
+ } catch (error) {
+ cleanupUnacceptedQueueEditMaterialization(files, preparedFiles);
+ throw error;
+ }
+ const accepted = projection.pendingQueue.find((item) => item.clientId === clientId);
+ const updated = queuedContentProjectionMatches(accepted, replacement);
+ if (!updated) cleanupUnacceptedQueueEditMaterialization(files, preparedFiles);
+ return updated;
+}
+
/**
* 已确认「不再需要自动起名」的会话(main 返回 done=true:已起过名,或用户手动
* 改过名)。纯粹是省 IPC 的缓存 —— 权威判定始终在 main。
@@ -16508,6 +16636,7 @@ export const makerChatStore = {
removeFromQueue,
/** F-QUEUE-DEFER: edit a single queued message's text (✏️ button). */
updateQueueItem,
+ updateQueueItemContent,
clearSession,
/** Dismiss the error banner without retrying. */
clearError,
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index d953d3b72a..d873131220 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -94,6 +94,7 @@ export interface RoutableMaker {
| 'move'
| 'remove'
| 'updateText'
+ | 'updateContent'
| 'clearError'
| 'retryLastError'
| 'clearSession'
@@ -206,6 +207,7 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
move: t('maker:input:move') as FullMaker['input']['move'],
remove: t('maker:input:remove') as FullMaker['input']['remove'],
updateText: t('maker:input:update-text') as FullMaker['input']['updateText'],
+ updateContent: t('maker:input:update-content') as FullMaker['input']['updateContent'],
clearError: t('maker:input:clear-error') as FullMaker['input']['clearError'],
retryLastError: t('maker:input:retry-last-error') as FullMaker['input']['retryLastError'],
clearSession: t('maker:input:clear-session') as FullMaker['input']['clearSession'],
diff --git a/apps/desktop/src/renderer/lib/queueComposerEdit.ts b/apps/desktop/src/renderer/lib/queueComposerEdit.ts
new file mode 100644
index 0000000000..fce0305dc2
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/queueComposerEdit.ts
@@ -0,0 +1,45 @@
+import type { ComposerDraft } from '@/lib/composerDraftStore';
+import { plainTextToTiptapDoc } from '@/lib/composerDraftStore';
+import { parseChatQuoteSegments } from '@/lib/chatQuotes';
+import { quoteSegmentsToComposerDocument } from '@/lib/composerQuoteDocument';
+import type { AttachedFile } from '@/lib/fileTypes';
+import type { QueuedMessage } from '@/lib/makerChatStore';
+
+export interface QueueComposerEditDraft {
+ draftKey: string;
+ draft: ComposerDraft;
+ originalAttachmentIds: string[];
+}
+
+export function queueComposerEditDraftKey(sessionId: string, clientId: string): string {
+ return `queue-edit:${sessionId}:${clientId}`;
+}
+
+export function queueMessageToComposerEditDraft(
+ sessionId: string,
+ entry: QueuedMessage,
+): QueueComposerEditDraft {
+ const text = entry.chatMessage.content ?? entry.text;
+ const attachments: AttachedFile[] = (entry.files ?? []).map(({ pathOrigin: _, ...file }) => ({
+ ...file,
+ cacheUrlShared: true,
+ stagedPathShared: true,
+ }));
+ const document = entry.chatMessage.quotesEncoded
+ ? quoteSegmentsToComposerDocument(parseChatQuoteSegments(text))
+ : text.length > 0
+ ? plainTextToTiptapDoc(text)
+ : null;
+
+ return {
+ draftKey: queueComposerEditDraftKey(sessionId, entry.clientId),
+ draft: {
+ text: document,
+ attachments,
+ quotes: [],
+ browserComments: [],
+ focusAtEnd: true,
+ },
+ originalAttachmentIds: attachments.map((file) => file.id),
+ };
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 55620b03ae..9bb77e0a68 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5960,6 +5960,12 @@ interface ElectronAPI {
trustedContexts?: import('../shared/agentInputQueue').AgentInputSessionReferenceContext[],
opts?: { expectedClearBoundaryMs?: number | null },
) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;
+ updateContent: (
+ sessionId: string,
+ clientId: string,
+ item: import('../shared/agentInputQueue').AgentInputQueuedMessage,
+ opts?: { expectedClearBoundaryMs?: number | null },
+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;
move: (
sessionId: string,
clientId: string,