Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(composer): attach images as inline draft chips with hover preview
vastsab6648d1e6ad2
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 07fbcd1c4..ed2886e66 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -49,7 +49,6 @@ import { useComposerDraft } from "../features/chat/composer/hooks/useComposerDraimport { useComposerInputHistory } from "../features/chat/composer/hooks/useComposerInputHistory";import { usePluginComposerBridge } from "../features/chat/composer/hooks/usePluginComposerBridge";import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSubmit";-import { ComposerImageAttachments } from "../features/chat/composer/ComposerImageAttachments";import { ComposerInput } from "../features/chat/composer/ComposerInput";import { useComposerModelMenu } from "../features/chat/composer/hooks/useComposerModelMenu";import { useVoiceInput } from "../features/voice/useVoiceInput";@@ -538,7 +537,6 @@ export function Composer({insertDroppedDirectoryPaths={insertDroppedDirectoryPaths}dismissDroppedDirectories={dismissDroppedDirectories}/>- <ComposerImageAttachments controller={draft.imagePreview} onRemove={draft.removeImage} disabled={inputBlocked} /><divref={composerShellRef}className={`composer-shell${inputBlocked ? " is-gated" : ""}${diff --git a/apps/desktop/src/features/chat/composer/ComposerImageAttachments.tsx b/apps/desktop/src/features/chat/composer/ComposerImageAttachments.tsxdeleted file mode 100644index 4d24ec83b..000000000--- a/apps/desktop/src/features/chat/composer/ComposerImageAttachments.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { useTranslation } from "react-i18next";-import { IconClose, IconImage } from "../../../components/icons";-import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";--/** Attachment controls stay outside both the editable draft and its shell. */-export function ComposerImageAttachments({ controller, onRemove, disabled }: {- controller: ComposerImagePreviewController;- onRemove: (id: string) => void;- disabled: boolean;-}) {- const { t } = useTranslation();- if (!controller.images.length) return null;- return (- <div className="composer-image-attachments">- {controller.images.map((reference) => {- const source = controller.sources?.get(reference.id);- return (- <div key={reference.id} className="composer-image-attachment">- <button- type="button"- className="composer-image-attachment-open"- title={reference.path}- aria-label={`${reference.name} — ${reference.path}`}- onMouseDown={(event) => { if (event.button === 0) event.preventDefault(); }}- onClick={() => controller.open(reference)}- onKeyDown={(event) => {- if (event.key !== "Enter" && event.key !== " ") return;- event.preventDefault();- controller.open(reference);- }}- >- <IconImage size={24} />- {source?.status === "ready" ? <img src={source.src} alt="" draggable={false} onError={(event) => { event.currentTarget.hidden = true; }} /> : null}- </button>- <button- type="button"- className="composer-image-attachment-remove"- disabled={disabled}- aria-label={t("chat.removeFileReference", { name: reference.name })}- title={t("chat.removeFileReference", { name: reference.name })}- onClick={() => onRemove(reference.id)}- ><IconClose size={12} /></button>- </div>- );- })}- </div>- );-}diff --git a/apps/desktop/src/features/chat/composer/ComposerImageHoverPreview.tsx b/apps/desktop/src/features/chat/composer/ComposerImageHoverPreview.tsxnew file mode 100644index 000000000..d82fc69a1--- /dev/null+++ b/apps/desktop/src/features/chat/composer/ComposerImageHoverPreview.tsx@@ -0,0 +1,63 @@+import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";+import { portalToBody } from "../../../lib/portal-visibility";+import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";+import { useComposerImageHover, type ComposerImageHoverTarget } from "./hooks/useComposerImageHover";++/** Distance between the hovered chip and its preview card. */+const PREVIEW_GAP = 8;++/**+ * Hover preview for inline image chips. It stays a read-only card: clicking the+ * chip is what opens the modal preview.+ */+export function ComposerImageHover({ controller, editorRef }: {+ controller: ComposerImagePreviewController;+ editorRef: RefObject<HTMLDivElement | null>;+}) {+ const images = controller.images;+ // The controller hands back a fresh `images` array on every render, so keep+ // the lookup stable: the hover listeners must not detach while the pointer+ // still rests on a chip.+ const imagesRef = useRef(images);+ imagesRef.current = images;+ const idForToken = useCallback(+ (token: string) => imagesRef.current.find((image) => image.token === token)?.id ?? null,+ [],+ );+ const hover = useComposerImageHover(editorRef, idForToken);+ // The modal already shows the image; a card behind it would be noise.+ return <ComposerImageHoverCard controller={controller} target={controller.preview ? null : hover} />;+}++function ComposerImageHoverCard({ controller, target }: {+ controller: ComposerImagePreviewController;+ target: ComposerImageHoverTarget | null;+}) {+ const cardRef = useRef<HTMLDivElement>(null);+ const [placement, setPlacement] = useState<"above" | "below">("above");+ const source = target ? controller.sources?.get(target.id) : undefined;+ const src = source?.status === "ready" ? source.src : null;+ useLayoutEffect(() => {+ const card = cardRef.current;+ if (!target || !card) return;+ // A chip on the first line has no room above it.+ setPlacement(target.anchor.top - card.offsetHeight - PREVIEW_GAP < 0 ? "below" : "above");+ }, [target, src]);+ if (!target || !src) return null;+ return portalToBody(+ <div+ ref={cardRef}+ className="composer-image-hover"+ data-placement={placement}+ role="presentation"+ style={{+ left: target.anchor.left + target.anchor.width / 2,+ top: placement === "above"+ ? target.anchor.top - PREVIEW_GAP+ : target.anchor.bottom + PREVIEW_GAP,+ }}+ >+ <img src={src} alt="" draggable={false} />+ </div>,+ );+}diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex bb1b53491..66ca68c02 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -10,6 +10,7 @@ import type {} from "react";import { editorSelectionRange, readEditorValue } from "./editor";import { ComposerImagePreview } from "./ComposerImagePreview";+import { ComposerImageHover } from "./ComposerImageHoverPreview";import type { CompletionController } from "./hooks/useComposerCompletions";import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";@@ -75,6 +76,7 @@ export function ComposerInput({return (<div className="composer-input-wrap">{imagePreview ? <ComposerImagePreview controller={imagePreview} /> : null}+ {imagePreview ? <ComposerImageHover controller={imagePreview} editorRef={inputRef} /> : null}<div className="composer-input-stage">{/* React does not render children into this node; the editor modulepaints atomic attachment chips imperatively. */}diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex 4db3115a7..04ce64244 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -287,6 +287,7 @@ function buildChipElement(removeLabel: string,onRemove: (token: string) => void,onExpandText: (token: string) => void,+ onOpenImage: (token: string) => void,): HTMLElement {const chip = document.createElement("span");chip.className = "composer-chip";@@ -296,13 +297,19 @@ function buildChipElement(const origin = isPluginMark(reference) ? (reference.plugin?.pluginId ?? "") : reference.path;if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;chip.title = origin;- const editableText = isEditableTextReference(reference);- const activate = editableText ? () => onExpandText(token) : undefined;+ // An image keeps the compact chip and opens its preview; only plain text+ // references expand into editable draft text.+ const image = chipIconKey(reference) === "image";+ if (image) chip.dataset.image = "";+ const editableText = !image && isEditableTextReference(reference);+ const activate = editableText ? () => onExpandText(token) : image ? () => onOpenImage(token) : undefined;chip.setAttribute("role", activate ? "button" : "listitem");chip.setAttribute("aria-label", `${reference.name} — ${origin}`);if (activate) {chip.tabIndex = 0;- chip.dataset.action = "expand-text-reference";+ // Only a text reference expands into editable text; an image chip opens+ // its preview instead.+ chip.dataset.action = editableText ? "expand-text-reference" : "open-image-preview";chip.addEventListener("click", activate);chip.addEventListener("keydown", (event) => {if (event.target !== chip) return;@@ -350,6 +357,7 @@ export function paintEditorValue(removeLabelFor: (reference: ComposerFileReference) => string,onRemove: (token: string) => void,onExpandText: (token: string) => void,+ onOpenImage: (token: string) => void,): void {el.replaceChildren();let textBuffer = "";@@ -371,6 +379,7 @@ export function paintEditorValue(removeLabelFor(reference),onRemove,onExpandText,+ onOpenImage,),);continue;diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 96d79cc05..026578491 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -37,6 +37,7 @@ import {isEditableTextReference,isPersistedScratchReference,isPluginMark,+ nextChipToken,paintEditorValue,readEditorValue,setEditorCaret,@@ -45,7 +46,7 @@ import {import type { ComposerPrefill } from "../model";import { useComposerImagePreview, type ComposerImagePreviewController } from "./useComposerImagePreview";-import { detachImageTokens, isImageReference } from "../image-attachments";+import { attachImageTokens } from "../image-attachments";type ComposerSession = { id: string };@@ -134,13 +135,19 @@ export function useComposerDraft({const draftKey = draftKeyForSession(activeSessionId);const referenceSessionId = activeSessionId ?? "";const initialDraft = readComposerDraft(draftKey);- const [value, setValue] = useState(() => initialDraft?.text ?? "");- const [fileReferences, setFileReferences] = useState<ComposerFileReference[]>(() =>- (initialDraft?.fileReferences ?? []).map((fileReference) =>+ // Images are inline chips, so a draft cached by an older build regains one+ // token per attachment instead of dropping its chip.+ const [initialDraftState] = useState(() => {+ const references = (initialDraft?.fileReferences ?? []).map((fileReference) =>createFileReferenceFromSnapshot(fileReference, referenceSessionId),- ),+ );+ return attachImageTokens(initialDraft?.text ?? "", references, nextChipToken);+ });+ const [value, setValue] = useState(initialDraftState.text);+ const [fileReferences, setFileReferences] = useState<ComposerFileReference[]>(+ initialDraftState.references,);- const [cursor, setCursor] = useState(() => initialDraft?.text.length ?? 0);+ const [cursor, setCursor] = useState(initialDraftState.text.length);// `onSelect` fires on every caret move; avoid re-rendering for an unchanged// cursor so autocomplete trigger detection stays quiet.const updateCursor = (next: number) =>@@ -236,6 +243,11 @@ export function useComposerDraft({const imagePreview = useComposerImagePreview({ references: fileReferences, value, sessionId: referenceSessionId, editorRef: ref });const removeChipByTokenRef = useRef<(token: string) => void>(() => {});const expandTextReferenceRef = useRef<(token: string) => void>(() => {});+ const openImageReferenceRef = useRef<(token: string) => void>(() => {});+ openImageReferenceRef.current = (token) => {+ const reference = referenceByTokenRef.current.get(token);+ if (reference) imagePreview.open(reference);+ };const pendingEditorCaretRef = useRef<number | null>(initialDraft?.text ? initialDraft.text.length : null,);@@ -265,6 +277,7 @@ export function useComposerDraft({}),(token) => removeChipByTokenRef.current(token),(token) => expandTextReferenceRef.current(token),+ (token) => openImageReferenceRef.current(token),);editorValueRef.current = nextValue;};@@ -272,17 +285,6 @@ export function useComposerDraft({useLayoutEffect(() => {const element = ref.current;if (!element) return;- if (fileReferences.some((reference) => isImageReference(reference) && reference.token)) {- const detached = detachImageTokens(value, fileReferences, pendingEditorCaretRef.current ?? cursor);- valueRef.current = detached.text;- fileReferencesRef.current = detached.references;- pendingEditorCaretRef.current = detached.caret;- editorValueRef.current = null;- setValue(detached.text);- setCursor(detached.caret);- setFileReferences(detached.references);- return;- }if (editorValueRef.current === value) return;paintCurrentDraft(element, value);const pendingCaret = pendingEditorCaretRef.current;@@ -392,13 +394,13 @@ export function useComposerDraft({if (previousKey === HOME_DRAFT_KEY) flushScheduledHomeDraftAdopt(draftKey);draftKeyRef.current = draftKey;const nextDraft = readComposerDraft(draftKey);- setValue(nextDraft?.text ?? "");- setFileReferences(- nextDraft?.fileReferences.map((fileReference) =>- createFileReferenceFromSnapshot(fileReference, referenceSessionId),- ) ?? [],+ const nextReferences = (nextDraft?.fileReferences ?? []).map((fileReference) =>+ createFileReferenceFromSnapshot(fileReference, referenceSessionId),);- setCursor(nextDraft?.text.length ?? 0);+ const nextDraftState = attachImageTokens(nextDraft?.text ?? "", nextReferences, nextChipToken);+ setValue(nextDraftState.text);+ setFileReferences(nextDraftState.references);+ setCursor(nextDraftState.text.length);return;}// Current drafts are serialized lazily on switch, unmount, blur, or a@@ -503,14 +505,16 @@ export function useComposerDraft({useEffect(() => {if (!composerPrefill || composerPrefill.sessionId !== activeSessionId) return;markComposerDraftEdited(draftKeyForSession(composerPrefill.sessionId));- setValue(composerPrefill.text);+ const prefilledReferences = composerPrefill.fileReferences.map((fileReference) =>+ createFileReferenceFromSnapshot(fileReference, composerPrefill.sessionId),+ );+ const prefilled = attachImageTokens(composerPrefill.text, prefilledReferences, nextChipToken);+ setValue(prefilled.text);setFileReferences((current) => [...current.filter((fileReference) => fileReference.sessionId !== composerPrefill.sessionId,),- ...composerPrefill.fileReferences.map((fileReference) =>- createFileReferenceFromSnapshot(fileReference, composerPrefill.sessionId),- ),+ ...prefilled.references,]);clearComposerPrefill();requestAnimationFrame(() => {@@ -540,10 +544,9 @@ export function useComposerDraft({caret: number,focus = true,) => {- const detached = detachImageTokens(nextText, nextReferences, caret);- nextText = detached.text;- nextReferences = detached.references;- caret = detached.caret;+ const entered = attachImageTokens(nextText, nextReferences, nextChipToken);+ nextText = entered.text;+ nextReferences = entered.references;markComposerDraftEdited(draftKeyRef.current);// A token may now refer to a different attachment even when text is equal.editorValueRef.current = null;@@ -664,14 +667,16 @@ export function useComposerDraft({if (fileReferencesRef.current.some((reference) => reference.sessionId === (currentActiveSessionId ?? ""))) return;markComposerDraftEdited(key);const sessionId = currentActiveSessionId ?? "";- setValue(snapshot.text);+ const restoredReferences = snapshot.fileReferences.map((fileReference) =>+ createFileReferenceFromSnapshot(fileReference, sessionId),+ );+ const restored = attachImageTokens(snapshot.text, restoredReferences, nextChipToken);+ setValue(restored.text);setFileReferences((current) => [...current.filter((fileReference) => fileReference.sessionId !== sessionId),- ...snapshot.fileReferences.map((fileReference) =>- createFileReferenceFromSnapshot(fileReference, sessionId),- ),+ ...restored.references,]);- setCursor(snapshot.text.length);+ setCursor(restored.text.length);};const draftSnapshot = (text: string): ComposerDraftSnapshot => ({diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerImageHover.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerImageHover.tsnew file mode 100644index 000000000..cabe76f15--- /dev/null+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerImageHover.ts@@ -0,0 +1,88 @@+import { useEffect, useState, type RefObject } from "react";++export type ComposerImageHoverTarget = {+ id: string;+ /** Viewport rect of the hovered chip, used to place the preview card. */+ anchor: { left: number; top: number; bottom: number; width: number };+};++/** Pointer dwell before a chip reveals its preview. */+const HOVER_DELAY_MS = 180;++const IMAGE_CHIP_SELECTOR = ".composer-chip[data-image]";++/**+ * Track the image chip under the pointer inside the composer editor. Chips are+ * painted imperatively, so the editor delegates pointer movement here instead+ * of every chip owning preview state.+ */+export function useComposerImageHover(+ editorRef: RefObject<HTMLDivElement | null>,+ idForToken: (token: string) => string | null,+): ComposerImageHoverTarget | null {+ const [target, setTarget] = useState<ComposerImageHoverTarget | null>(null);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor) return;+ let timer: number | null = null;+ let pending: string | null = null;+ const cancel = () => {+ if (timer !== null) window.clearTimeout(timer);+ timer = null;+ pending = null;+ };+ const hide = () => {+ cancel();+ setTarget(null);+ };+ const chipOf = (node: EventTarget | null): HTMLElement | null =>+ node instanceof Element ? node.closest<HTMLElement>(IMAGE_CHIP_SELECTOR) : null;+ const reveal = (chip: HTMLElement, id: string) => {+ const rect = chip.getBoundingClientRect();+ setTarget({+ id,+ anchor: { left: rect.left, top: rect.top, bottom: rect.bottom, width: rect.width },+ });+ };+ const onPointerOver = (event: PointerEvent) => {+ const chip = chipOf(event.target);+ const id = chip ? idForToken(chip.dataset.token ?? "") : null;+ if (!chip || !id) {+ hide();+ return;+ }+ if (pending === id) return;+ cancel();+ pending = id;+ timer = window.setTimeout(() => {+ timer = null;+ if (pending === id) reveal(chip, id);+ }, HOVER_DELAY_MS);+ };+ const onPointerOut = (event: PointerEvent) => {+ const chip = chipOf(event.target);+ if (!chip || chipOf(event.relatedTarget) === chip) return;+ hide();+ };+ editor.addEventListener("pointerover", onPointerOver);+ editor.addEventListener("pointerout", onPointerOut);+ // A chip that moves under the pointer (typing, wrapping, scrolling) must+ // never leave a stale card behind.+ editor.addEventListener("input", hide);+ editor.addEventListener("scroll", hide, true);+ window.addEventListener("resize", hide);+ window.addEventListener("scroll", hide, true);+ return () => {+ cancel();+ editor.removeEventListener("pointerover", onPointerOver);+ editor.removeEventListener("pointerout", onPointerOut);+ editor.removeEventListener("input", hide);+ editor.removeEventListener("scroll", hide, true);+ window.removeEventListener("resize", hide);+ window.removeEventListener("scroll", hide, true);+ };+ }, [editorRef, idForToken]);++ return target;+}diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.tsindex 9e6f9c6c4..49ad9abbb 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts@@ -90,7 +90,7 @@ export function useComposerImagePreview({const current = useAppStore.getState();if (!editor.isConnected || (current.activeSessionId ?? "") !== reference.sessionId ||(current.workspace?.path ?? null) !== openingWorkspace) return;- if (focused instanceof HTMLElement && focused.isConnected && (editor.contains(focused) || focused.closest(".composer-image-attachments"))) focused.focus();+ if (focused instanceof HTMLElement && focused.isConnected && (editor.contains(focused) || focused.closest(".composer-chip[data-image]"))) focused.focus();else editor.focus();if (range && editor.contains(range.commonAncestorContainer)) {const selection = window.getSelection();diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.tsindex fbb1649c2..641c1429a 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts@@ -18,6 +18,7 @@ import {resolveSlashDispatch,} from "../slash-dispatch";import { readEditorValue, setEditorCaret, type ComposerFileReference } from "../editor";+import { detachImageTokens } from "../image-attachments";import type { ComposerDraftSnapshot } from "../../../../lib/composer-smart-stop";import type { ComposerDraftController } from "./useComposerDraft";@@ -198,12 +199,15 @@ export function useComposerSubmit({};const submit = async (steering = false) => {- const text = draft.ref.current ? readEditorValue(draft.ref.current) : value;+ const rawText = draft.ref.current ? readEditorValue(draft.ref.current) : value;+ // Images stay inline chips while editing; the model still receives them as+ // the structured attachment, so their tokens leave the prompt text here.+ const outgoing = detachImageTokens(rawText, activeFileReferences, 0);const inlineContent = serializeInlineComposerFileReferences(- text,- activeFileReferences,+ outgoing.text,+ outgoing.references,);- const serializedContent = serializeComposerFileReferences(text, activeFileReferences);+ const serializedContent = serializeComposerFileReferences(outgoing.text, outgoing.references);if (!serializedContent) return;if (sendBlocked) {if (pasting) showToast(t("chat.pasteInProgress"), { variant: "info" });@@ -212,7 +216,7 @@ export function useComposerSubmit({invalidatePromptEnhancement();const submittedDraftKey = draftKey;const submittedDraftRevision = draft.draftRevision(submittedDraftKey);- const submittedDraft = draft.draftSnapshot(text);+ const submittedDraft = draft.draftSnapshot(rawText);// Recall keeps what the user typed, in the conversation that submitted it.// For a mode command that is the whole `/agent …` text rather than its body,// so re-submitting re-runs it; every other recorded path stores exactly the@@ -252,16 +256,17 @@ export function useComposerSubmit({if (isModeCommand && commandBody) {try {await runPaletteCommand(command.id);- const visibleDraft = text.trim();+ const visibleDraft = rawText.trim();const visibleCommandEnd = visibleDraft.search(/\s/);const visibleCommandBody =visibleCommandEnd === -1? "": visibleDraft.slice(visibleCommandEnd).trim();+ const outgoingBody = detachImageTokens(visibleCommandBody, activeFileReferences, 0);const accepted = await sendPrompt(serializeInlineComposerFileReferences(- visibleCommandBody,- activeFileReferences,+ outgoingBody.text,+ outgoingBody.references,),draft.draftSnapshot(visibleCommandBody),activeSessionId ?? undefined,diff --git a/apps/desktop/src/features/chat/composer/image-attachments.ts b/apps/desktop/src/features/chat/composer/image-attachments.tsindex 814229183..b643a41dd 100644--- a/apps/desktop/src/features/chat/composer/image-attachments.ts+++ b/apps/desktop/src/features/chat/composer/image-attachments.ts@@ -4,7 +4,11 @@ export function isImageReference(reference: ComposerFileReference): boolean {return reference.kind === "image" || Boolean(reference.mimeType?.toLowerCase().startsWith("image/"));}-/** Keep images outside editable text, including restored inline-image drafts. */+/**+ * Keep images outside the submitted prompt text. Images stay inline chips while+ * the draft is being edited, so the text handed to the model is detached only+ * at submission time, where the structured reference already carries the image.+ */export function detachImageTokens(text: string, references: ComposerFileReference[], caret: number) {let nextText = text;let nextCaret = caret;@@ -21,3 +25,24 @@ export function detachImageTokens(text: string, references: ComposerFileReferenc});return { text: nextText, references: nextReferences, caret: nextCaret };}++/**+ * Keep images visible as inline chips when a draft enters the editor. A draft+ * cached before images became chips, a restored queue entry, or a prefill can+ * name an image without a token, so every image gets one and the text carries+ * it; appending in reference order keeps the attachment next to the draft.+ */+export function attachImageTokens(+ text: string,+ references: ComposerFileReference[],+ nextToken: () => string,+): { text: string; references: ComposerFileReference[] } {+ let nextText = text;+ const nextReferences = references.map((reference) => {+ if (!isImageReference(reference)) return reference;+ const token = reference.token ?? nextToken();+ if (!nextText.includes(token)) nextText += token;+ return reference.token ? reference : { ...reference, token };+ });+ return { text: nextText, references: nextReferences };+}diff --git a/apps/desktop/src/styles/composer-image-preview.css b/apps/desktop/src/styles/composer-image-preview.cssindex d65572ff7..67295ec3f 100644--- a/apps/desktop/src/styles/composer-image-preview.css+++ b/apps/desktop/src/styles/composer-image-preview.css@@ -1,61 +1,25 @@-.composer-image-attachments {- display: flex;- flex-wrap: wrap;- justify-content: flex-start;- gap: 12px;- padding: 6px;- box-sizing: border-box;- max-height: min(212px, 30dvh);- overflow-y: auto;- overscroll-behavior: contain;-}--.composer-image-attachment { position: relative; width: 88px; height: 88px; }-.composer-image-attachment-open {+/* Read-only hover card for an inline image chip in the draft. */+.composer-image-hover {+ position: fixed;+ z-index: 55;box-sizing: border-box;- position: relative;- display: flex;- align-items: center;- justify-content: center;- width: 100%;- height: 100%;- padding: 0;- overflow: hidden;- color: var(--ds-text-secondary);+ padding: 3px;background: var(--ds-bg-elevated);border: 1px solid var(--ds-border-default);- border-radius: var(--radius-lg);- cursor: pointer;-}-.composer-image-attachment-open img {- position: absolute;- inset: 0;- width: 100%;- height: 100%;- object-fit: cover;-}-.composer-image-attachment-remove {- position: absolute;- right: -5px;- top: -5px;- display: flex;- align-items: center;- justify-content: center;- width: 20px;- height: 20px;- padding: 0;- opacity: 0;- color: var(--ds-text-secondary);- background: var(--ds-bg-elevated);- border: 1px solid var(--ds-border-default);- border-radius: var(--radius-full);- cursor: pointer;+ border-radius: var(--radius-md);+ box-shadow: var(--ds-shadow-dialog);+ pointer-events: none;}-.composer-image-attachment:hover .composer-image-attachment-remove,-.composer-image-attachment:focus-within .composer-image-attachment-remove { opacity: 1; }-.composer-image-attachment button:focus-visible { outline: 2px solid var(--ds-text-secondary); outline-offset: 2px; }-@media (hover: none) {- .composer-image-attachment-remove { opacity: 1; }++.composer-image-hover[data-placement="above"] { transform: translate(-50%, -100%); }+.composer-image-hover[data-placement="below"] { transform: translate(-50%, 0); }++.composer-image-hover img {+ display: block;+ max-width: min(240px, 40vw);+ max-height: min(240px, 40dvh);+ border-radius: var(--radius-2xs);+ object-fit: contain;}.composer-image-preview {diff --git a/apps/desktop/test/composer-draft-cache.test.mjs b/apps/desktop/test/composer-draft-cache.test.mjsindex 9bba60786..183021922 100644--- a/apps/desktop/test/composer-draft-cache.test.mjs+++ b/apps/desktop/test/composer-draft-cache.test.mjs@@ -149,7 +149,12 @@ test("flushing a scheduled adopt uses the Composer persist that rewrote home", (test("composer hydrates from the shared cache and persists across unmount and hidden windows", () => {assert.match(draftHook, /composer-draft-cache/);assert.match(composer, /readComposerDraft\(draftKey\)/);- assert.match(composer, /useState\(\(\) => initialDraft\?\.text \?\? ""\)/);+ // A cached draft hydrates through the image attach helper so inline image+ // chips come back together with their draft.+ assert.match(+ composer,+ /return attachImageTokens\(initialDraft\?\.text \?\? "", references, nextChipToken\)/,+ );assert.match(composer, /persistDraft\(draftKeyRef\.current\)/);assert.match(composer, /document\.visibilityState === "hidden"/);assert.match(composer, /window\.addEventListener\("blur", onWindowBlur\)/);@@ -159,8 +164,8 @@ test("composer hydrates from the shared cache and persists across unmount and hiassert.match(composer, /persistDraft\(previousKey\)/);assert.match(composer, /flushScheduledHomeDraftAdopt\(draftKey\)/);assert.match(composer, /const nextDraft = readComposerDraft\(draftKey\)/);- assert.match(composer, /setValue\(nextDraft\?\.text \?\? ""\)/);- assert.match(composer, /setFileReferences\(\s*nextDraft\?\.fileReferences\.map/);+ assert.match(composer, /setValue\(nextDraftState\.text\)/);+ assert.match(composer, /setFileReferences\(nextDraftState\.references\)/);assert.doesNotMatch(composer, /new Map<string, ComposerDraftSnapshot>\(\)/);assert.doesNotMatch(composer, /draftCacheRef/);});diff --git a/apps/desktop/test/composer-file-reference-display.test.mjs b/apps/desktop/test/composer-file-reference-display.test.mjsindex 81cdd99f1..442c63f7c 100644--- a/apps/desktop/test/composer-file-reference-display.test.mjs+++ b/apps/desktop/test/composer-file-reference-display.test.mjs@@ -79,7 +79,7 @@ test("composer renders atomic inline chips and serializes paths on send", () =>assert.match(composer, /chip\.title = origin/);assert.match(composer,- /serializeComposerFileReferences\(text, activeFileReferences\)/,+ /serializeComposerFileReferences\(outgoing\.text, outgoing\.references\)/,);assert.match(composer,@@ -118,7 +118,7 @@ test("text file chips expand into editable draft text", () => {});test("unanswered stop restores compact references instead of serialized paths", () => {- assert.match(composer, /setValue\(composerPrefill\.text\)/);+ assert.match(composer, /setValue\(prefilled\.text\)/);assert.match(composer, /composerPrefill\.fileReferences\.map/);assert.match(composer, /composerPrefill\.sessionId !== activeSessionId/);assert.match(diff --git a/apps/desktop/test/composer-image-attachments.test.mjs b/apps/desktop/test/composer-image-attachments.test.mjsindex 6a7b4fca2..9eac91454 100644--- a/apps/desktop/test/composer-image-attachments.test.mjs+++ b/apps/desktop/test/composer-image-attachments.test.mjs@@ -1,11 +1,15 @@import assert from "node:assert/strict";import test from "node:test";-import { detachImageTokens } from "../src/features/chat/composer/image-attachments.ts";+import {+ attachImageTokens,+ detachImageTokens,+} from "../src/features/chat/composer/image-attachments.ts";const image = { id: "image", sessionId: "a", path: "/scratch/a.png", name: "a.png", kind: "image", token: "\ue001" };+const tokenlessImage = { id: "inline", sessionId: "a", path: "/scratch/b.png", name: "b.png", kind: "image" };const file = { id: "file", sessionId: "a", path: "/scratch/a.txt", name: "a.txt", kind: "file", token: "\ue002" };-test("restored inline images retain identity and paths while text and file chips retain order", () => {+test("submission detaches image tokens and image references while text keeps file order", () => {const result = detachImageTokens(`before ${image.token}${file.token} after`, [image, file], 9);assert.equal(result.text, `before ${file.token} after`);assert.equal(result.caret, 8);@@ -28,3 +32,25 @@ test("MIME image references detach without changing earlier text or repeated norassert.equal(result.caret, 2);assert.deepEqual(detachImageTokens(result.text, result.references, result.caret), result);});++test("a restored image without a token becomes an inline chip", () => {+ const { text, references } = attachImageTokens(`look${file.token} here`, [tokenlessImage, file], () => "\ue101");+ assert.equal(text, `look${file.token} here\ue101`);+ assert.equal(references[0].token, "\ue101");+ assert.equal(references[0].path, tokenlessImage.path);+ assert.equal(tokenlessImage.token, undefined);+ assert.equal(references[1], file);+});++test("an image that already carries its token is neither duplicated nor replaced", () => {+ const { text, references } = attachImageTokens(`x${image.token}`, [image], () => "\ue103");+ assert.equal(text, `x${image.token}`);+ assert.equal(references[0], image);+});++test("attaching restored drafts is idempotent", () => {+ const first = attachImageTokens("", [tokenlessImage], () => "\ue104");+ const second = attachImageTokens(first.text, first.references, () => "\ue105");+ assert.equal(second.text, first.text);+ assert.equal(second.references[0].token, "\ue104");+});diff --git a/apps/desktop/test/composer-inline-image-chips.test.mjs b/apps/desktop/test/composer-inline-image-chips.test.mjsnew file mode 100644index 000000000..fbbd5064b--- /dev/null+++ b/apps/desktop/test/composer-inline-image-chips.test.mjs@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { readComposerModule, readComposerSource } from "./helpers/composer-source.mjs";++const read = (path) => readFile(new URL(path, import.meta.url), "utf8");++const [composer, editor, hoverCard, hoverHook, styles, submitHook] = await Promise.all([+ readComposerSource(),+ readComposerModule("editor.ts"),+ readComposerModule("ComposerImageHoverPreview.tsx"),+ readComposerModule("hooks/useComposerImageHover.ts"),+ read("../src/styles/composer-image-preview.css"),+ readComposerModule("hooks/useComposerSubmit.ts"),+]);++test("pasted images stay inline chips like every other attachment", () => {+ assert.match(editor, /const image = chipIconKey\(reference\) === "image";/);+ assert.match(editor, /if \(image\) chip\.dataset\.image = "";/);+ assert.match(editor, /const editableText = !image && isEditableTextReference\(reference\);/);+ // Activating an image chip opens the preview; it never expands draft text.+ assert.match(editor, /image \? \(\) => onOpenImage\(token\)/);+ assert.match(editor, /chip\.dataset\.action = editableText \? "expand-text-reference" : "open-image-preview";/);+ assert.match(composer, /openImageReferenceRef\.current = \(token\) => \{[\s\S]*?imagePreview\.open\(reference\)/);+ // The detached attachment row above the input shell is gone.+ assert.doesNotMatch(composer, /ComposerImageAttachments/);+ assert.doesNotMatch(styles, /\.composer-image-attachments/);+ assert.doesNotMatch(styles, /\.composer-image-attachment\b/);+});++test("hovering an image chip reveals a read-only preview card", () => {+ assert.match(composer, /<ComposerImageHover controller=\{imagePreview\} editorRef=\{inputRef\} \/>/);+ assert.match(hoverHook, /const IMAGE_CHIP_SELECTOR = "\.composer-chip\[data-image\]";/);+ assert.match(hoverHook, /getBoundingClientRect\(\)/);+ // A chip that moves under the pointer must not leave a stale card behind.+ assert.match(hoverHook, /editor\.addEventListener\("input", hide\)/);+ assert.match(hoverCard, /className="composer-image-hover"/);+ assert.match(hoverCard, /data-placement=\{placement\}/);+ assert.match(styles, /\.composer-image-hover img \{[\s\S]*?max-width: min\(240px, 40vw\)/);+ assert.match(styles, /\.composer-image-hover \{[\s\S]*?pointer-events: none/);+ // The modal owns the open image; the card would only be noise behind it.+ assert.match(hoverCard, /target=\{controller\.preview \? null : hover\}/);+});++test("image tokens leave the prompt text only at submission", () => {+ assert.match(submitHook, /const outgoing = detachImageTokens\(rawText, activeFileReferences, 0\);/);+ assert.match(submitHook, /serializeComposerFileReferences\(outgoing\.text, outgoing\.references\)/);+ assert.match(submitHook, /const submittedDraft = draft\.draftSnapshot\(rawText\);/);+ assert.match(composer, /attachImageTokens\(/);+});diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjsindex c34e87d4c..cbaa01e0c 100644--- a/apps/desktop/test/composer-paste-files.test.mjs+++ b/apps/desktop/test/composer-paste-files.test.mjs@@ -40,10 +40,10 @@ test("composer converts oversized text paste and materializes clipboard files",composer,/createFileReference\(file\.path, file\.name, sessionId, \{[\s\S]*kind: file\.kind/,);- assert.match(composer, /serializeComposerFileReferences\(text, activeFileReferences\)/);+ assert.match(composer, /serializeComposerFileReferences\(outgoing\.text, outgoing\.references\)/);assert.match(composer,- /const serializedContent = serializeComposerFileReferences\(text, activeFileReferences\)/,+ /const serializedContent = serializeComposerFileReferences\(outgoing\.text, outgoing\.references\)/,);// The draft is a contenteditable rich field: sentinels render as atomic// chips and every caret write goes through the DOM-range helper.diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjsindex 584e375d5..3846f71e3 100644--- a/apps/desktop/test/composer-send-state.test.mjs+++ b/apps/desktop/test/composer-send-state.test.mjs@@ -240,9 +240,9 @@ test("send clears the composer before the round trip and restores a rejected dra// still pending under load must not drop the last characters typed.assert.match(submit,- /const text = draft\.ref\.current \? readEditorValue\(draft\.ref\.current\) : value;/,+ /const rawText = draft\.ref\.current \? readEditorValue\(draft\.ref\.current\) : value;/,);- assert.match(submit, /serializeInlineComposerFileReferences\(\s*text,\s*activeFileReferences,\s*\)/);+ assert.match(submit, /serializeInlineComposerFileReferences\(\s*outgoing\.text,\s*outgoing\.references,\s*\)/);// Blocked and not-ready states are said, not swallowed.assert.match(submit, /if \(pasting\) showToast\(t\("chat\.pasteInProgress"\)/);assert.match(@@ -262,8 +262,8 @@ test("send clears the composer before the round trip and restores a rejected dra// draft in its cache slot for the next switch back.assert.match(restore, /if \(valueRef\.current\.trim\(\)\) return;/);assert.match(restore, /if \(currentKey !== key\) \{[\s\S]*?writeComposerDraft\(key, snapshot\);/);- assert.match(restore, /setValue\(snapshot\.text\);/);- assert.match(restore, /setCursor\(snapshot\.text\.length\);/);+ assert.match(restore, /setValue\(restored\.text\);/);+ assert.match(restore, /setCursor\(restored\.text\.length\);/);});test("mode slash prefixes send the trailing prompt and retain failed drafts", () => {@@ -279,11 +279,11 @@ test("mode slash prefixes send the trailing prompt and retain failed drafts", ());assert.match(submit,- /serializeInlineComposerFileReferences\(\s*visibleCommandBody,\s*activeFileReferences,\s*\)/,+ /serializeInlineComposerFileReferences\(\s*outgoingBody\.text,\s*outgoingBody\.references,\s*\)/,);assert.match(submit,- /const submittedDraftRevision = draft\.draftRevision\(submittedDraftKey\);\s*const submittedDraft = draft\.draftSnapshot\(text\);[\s\S]*?draft\.clearDraftForKey\(submittedDraftKey, submittedDraftRevision, submittedDraft\);\s*const accepted = steering\s*\?\s*await steerPrompt\(inlineContent, submittedDraft\)\s*:\s*await sendPrompt\(\s*inlineContent,\s*submittedDraft,\s*activeSessionId \?\? undefined,\s*captureAcceptedSession,\s*\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,+ /const submittedDraftRevision = draft\.draftRevision\(submittedDraftKey\);\s*const submittedDraft = draft\.draftSnapshot\(rawText\);[\s\S]*?draft\.clearDraftForKey\(submittedDraftKey, submittedDraftRevision, submittedDraft\);\s*const accepted = steering\s*\?\s*await steerPrompt\(inlineContent, submittedDraft\)\s*:\s*await sendPrompt\(\s*inlineContent,\s*submittedDraft,\s*activeSessionId \?\? undefined,\s*captureAcceptedSession,\s*\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,);assert.match(store, /draft\?: ComposerDraftSnapshot/);const sendPrompt = queueSlice.slice(diff --git a/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs b/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjsindex bdadc1c6b..785337b32 100644--- a/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs+++ b/apps/desktop/test/e2e/plugin-ui-slots/composer-draft.mjs@@ -14,8 +14,8 @@ function composerView() {mark: chip.dataset.pluginMark ?? null,name: chip.querySelector(".composer-chip-name")?.textContent ?? "",}));- const images = [...document.querySelectorAll(".composer-image-attachment-open")].map(- (open) => open.getAttribute("aria-label")?.split(" — ")[0] ?? "",+ const images = [...(input?.querySelectorAll(".composer-chip[data-image]") ?? [])].map(+ (chip) => chip.getAttribute("aria-label")?.split(" — ")[0] ?? "",);return {text: input ? (input.value ?? input.textContent) : null,@@ -190,9 +190,10 @@ export async function driveComposerDraft({ renderer, check }) {const image = await step("attach-image", "the image", (out) => out.text === "image attached" || out.status === "error");const withImage = await view();check(- "an image attachment joins the draft's images, not its text",- image.status === "ok" && withImage.images.includes("lab-dot.png") && withImage.chips.length === withNote.chips.length,- JSON.stringify({ image, images: withImage.images }),+ "an image attachment joins the draft as its own inline image chip",+ image.status === "ok" && withImage.images.includes("lab-dot.png") &&+ withImage.chips.some((chip) => chip.name === "lab-dot.png"),+ JSON.stringify({ image, images: withImage.images, chips: withImage.chips }),);const path = await step("attach-path", "the path", (out) => out.status === "error");check("a path is refused, not read", path.text === "PLUGIN_ATTACHMENT_REFERENCE_REFUSED", JSON.stringify(path));diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1624622dc..e96d7cfd8 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3385,17 +3385,21 @@ Anatomy:Text/plain and `.txt` chips are also keyboard-focusable buttons: clicking orpressing Enter/Space expands their bounded contents into editable draft text;binary, image, oversized, or failed reads keep the chip. Ordinary files stay- compact chips. Unsent images render in a left-aligned attachment row above and- outside the input shell, never within editable text. Their existing detached- reference metadata survives text selection, editing, undo, and session- switching; restored inline-image tokens are removed from text while keeping- the attachment. Image-only drafts enable Send; a rejected send restores both- text and attachments even when rejection precedes the next render. The- attachment row is height-limited and scrolls vertically so every image remains- reachable in a narrow chat pane. Thumbnails have an independent- remove button shown on hover/focus (always visible for touch input). No- separate explanatory vision-status row is rendered.- Clicking an image or pressing Enter/Space opens a modal image preview, without+ compact chips. Unsent images render as the same compact inline chip inside the+ editable draft, at the insertion point, with the image glyph and leaf name.+ Hovering one reveals a read-only preview card of its bounded data URL above+ the chip, or below it when the chip sits on the first line; moving the pointer+ away, typing, scrolling, resizing, or opening the modal dismisses the card,+ and the card never takes pointer events from the draft. A restored image+ reference without an inline token gains one, so a cache written before inline+ image chips, a restored queue entry, or a prefill still shows every image.+ Reference metadata survives text selection, editing, undo, and session+ switching; the chip's own remove button drops the attachment. Image-only+ drafts enable Send; a rejected send restores both text and attachments even+ when rejection precedes the next render. No separate explanatory+ vision-status row is rendered.+ Clicking an image chip or pressing Enter/Space on it opens a modal image+ preview, withoutsending the draft or changing the work-panel tabs. Inside the dark viewport,the image is horizontally and vertically centered, keeps its aspect ratio,and initially fits available space without upscaling small images. The@@ -3408,7 +3412,7 @@ Anatomy:the close button, or a blank-area click dismisses it and restores the priorinput focus/caret. Focus remains inside the modal, and native plugin surfacesare hidden while it is open. The remove button never opens or submits.- Thumbnails and previews use the bounded, contained `fs/readImageDataUrl`+ Preview cards and the modal use the bounded, contained `fs/readImageDataUrl`bridge, including allowed scratch files when no project is open. Missing,unsupported, oversized, or undecodable images show a retry state and retainthe draft. Session/project changes or removal of the selected attachmentdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c56f2e9fa..63e15d4fb 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7833,14 +7833,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.removable leaf-name chip and no scratch absolute path occupies thetextarea. Hover/focus chips to inspect their full paths, remove one, thensend the prompt and inspect the session message's attachment metadata.- Before sending, verify image thumbnails sit left-aligned above and outside- the input shell. Replacing/undoing all text must retain the images; image-only- drafts must survive session switching and retain submission metadata.- Mount the complete Composer: click Send for image-only input, verify- attachment delivery and successful clearing, and immediately reject a- text-plus-image send to verify full draft restoration. In a narrow pane,- add 20 images, scroll to the last one and remove it without losing others.- Inspect the thumbnail and open it with click, Enter, and+ Before sending, verify each image is a compact inline chip in the draft and+ that hovering it reveals its preview card. Replacing all text removes the+ inline image chips while undo restores them; image-only drafts must survive+ session switching and retain submission metadata.+ Mount the complete Composer: click Send for image-only input, verify+ attachment delivery and successful clearing, and immediately reject a+ text-plus-image send to verify full draft restoration. In a narrow pane,+ prefill 20 images, confirm 20 inline chips inside the composer, and remove+ one without losing the others.+ Inspect the chip and open it with click, Enter, andSpace. Confirm a centered modal preview opens, the work panel staysunchanged, and the draft is neither edited nor sent. Check small imagesstay at natural size, wide images fit without distortion, zoom/reset anddiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex cf98ccc75..9173a1012 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2322,19 +2322,20 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展分开是因为身份和调度使用规范路径,而不是名称。`text/plain` 和 `.txt`芯片还可通过键盘聚焦;点击或按 Enter/Space 会将有界内容展开为可编辑草稿文本。二进制、图像、过大或读取失败时保留芯片。- 未发送图片在输入框外上方单独一行靠左显示缩略图,不占据可编辑正文。- 全选、编辑或撤销正文不会删除图片;切换会话保留图片,旧草稿里的图片标记恢复为- 独立附件。只有图片的草稿也能点击发送;发送立即失败时仍恢复文字与附件。- 附件区限制高度并可纵向滚动,窄聊天面板内也能查看和删除每张图片。- 悬停或聚焦时显示独立删除按钮,触屏始终显示。- 点击或按 Enter/Space 打开图片浮层,不发送草稿,不改变工作面板选项卡。+ 未发送图片与文件一样渲染为草稿内的内联芯片(图片图标 + 叶子名),插在光标处。+ 悬停芯片会浮出只读预览小卡(图片位于首行时改在下方显示);移开指针、继续输入、+ 滚动、调整窗口或打开浮层都会收起,小卡不接管指针事件。恢复的图片引用若没有内联+ 标记会补上一个,因此内联图片芯片之前缓存的草稿、恢复的排队条目与预填内容都能看到+ 每张图片。全选、编辑或撤销正文不会单独删除图片:图片作为芯片随正文一起被替换或+ 删除,切换会话保留图片。只有图片的草稿也能点击发送;发送立即失败时仍恢复文字与附件。+ 点击图片芯片或在其上按 Enter/Space 打开图片浮层,不发送草稿,不改变工作面板选项卡。图片在深色遮罩内水平、垂直居中,保持比例并适应可用区域,小图默认不放大。支持缩放、适应窗口、下载原图及同一草稿内的多图切换;切图重置缩放与位置。按住图片拖动或滚动可在任意缩放下平移,指针移出图片后仍能连续拖动;松开或取消即结束拖动,不关闭浮层。图片保留一部分在可见区域内,适应窗口会恢复居中。按 Esc、点击关闭或空白处退出并恢复输入焦点与光标。焦点限制在浮层内,- 打开期间隐藏原生插件视图。删除按钮不触发预览或发送。- 缩略图与预览沿用有界、受限的 `fs/readImageDataUrl` 接口,无项目时也可读取允许+ 打开期间隐藏原生插件视图。芯片的删除按钮不触发预览或发送。+ 预览小卡与浮层沿用有界、受限的 `fs/readImageDataUrl` 接口,无项目时也可读取允许访问的暂存图片。图片丢失、格式不支持、过大或解码失败时显示重试并保留草稿。切换会话或项目、删除正在查看的附件时关闭预览;晚到的读取结果不得覆盖新图片。- 发送的模板调用在记录中呈现为等宽命令diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex d5e8af915..a5d6b4c58 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5011,11 +5011,12 @@ eleven-tool-round desktop paths are verified by可移动的叶名芯片和无划痕的绝对路径占用文本区域。 Hover/focus 芯片检查其完整路径,删除一个,然后发送提示并检查会话消息。- 发送前确认缩略图位于输入框外上方并靠左排列。全选替换与撤销正文应保留图片;- 仅图片草稿切换会话后仍保留图片与发送元数据。挂载完整 Composer,验证- 仅图片时点击发送会交付附件并清空草稿,文字加图片的发送立即失败时全部恢复。- 窄面板添加 20 张图片后应能滚动到最后一张并删除,其他图片保留。- 用点击、Enter 和空格打开居中图片浮层,工作面板与草稿保持+ 发送前确认每张图片都是草稿内的内联芯片,悬停芯片会浮出预览小卡。全选替换会删除+ 内联图片芯片,撤销会恢复;仅图片草稿切换会话后仍保留图片与发送元数据。挂载完整+ Composer,验证仅图片时点击发送会交付附件并清空草稿,文字加图片的发送立即失败时+ 全部恢复。窄面板预填 20 张图片,确认输入框内有 20 个内联芯片,删除其中一个后其余保留。+ 点击芯片或用 Enter/空格激活它打开居中图片浮层,工作面板与草稿保持+ 不变。小图不放大,宽图等比适应窗口;验证缩放、重置、下载原图、多图按钮与方向键不变。小图不放大,宽图等比适应窗口;验证缩放、重置、下载原图、多图按钮与方向键切换。切图重置缩放与位置。在适应窗口和放大后拖动图片,验证移出图片后松手、取消拖动与滚动平移;适应窗口恢复居中,拖动不关闭浮层,关闭或切换会话diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex e5cbe0f7d..6d8cf391f 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -5,7 +5,6 @@ import { createQueueSlice } from "../../apps/desktop/src/stores/slices/queue-sliimport type { SessionRuntime } from "../../apps/desktop/src/stores/runtime/session-runtime";import { useComposerSubmit } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerSubmit";import { verifyComposerSubmission } from "./composer-submission";-import { ComposerImageAttachments } from "../../apps/desktop/src/features/chat/composer/ComposerImageAttachments";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import { createInstance } from "i18next";@@ -98,7 +97,6 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunct});return (<div className="composer-stack">- <ComposerImageAttachments controller={draft.imagePreview} onRemove={draft.removeImage} disabled={attachments.pasting} /><div className="composer-shell"><ComposerInputimagePreview={draft.imagePreview}@@ -533,21 +531,27 @@ globalThis.composerPasteProbe = async () => {controller.fileReferences[0].kind === "image","native image file was mistaken for text",);- assert(!controller.ref.current!.querySelector("img"), "image thumbnails must be outside the text editor");- assert(document.querySelector(".composer-image-attachments"), "image thumbnails must have a separate row above the input");- const tray = document.querySelector<HTMLElement>(".composer-image-attachments")!;- const shell = document.querySelector<HTMLElement>(".composer-shell")!;- assert(!shell.contains(tray) && tray.getBoundingClientRect().bottom <= shell.getBoundingClientRect().top,- "attachment row must sit above and outside the input shell");- assert(readEditorValue(controller.ref.current!) === "prefix suffix", "image token leaked into visible text");- // #117: enter through the real attachment, read through sandboxed image IPC,+ // Pasted images are inline chips in the draft, exactly like a pasted file.+ const draftText = () => {+ let text = readEditorValue(controller.ref.current!);+ for (const reference of controller.fileReferences) {+ if (reference.token) text = text.split(reference.token).join("");+ }+ return text;+ };+ const imageChipByToken = (token: string) => controller.ref.current!+ .querySelector<HTMLElement>(`.composer-chip[data-image][data-token="${token}"]`);+ const chip = imageChipByToken(controller.fileReferences[0].token!)!;+ assert(chip, "pasted images must render as inline chips");+ assert(!document.querySelector(".composer-image-attachments"), "the detached attachment row must be gone");+ assert(chip.getAttribute("role") === "button" && chip.tabIndex === 0,+ "image chip must be keyboard accessible");+ assert(draftText() === "prefix suffix", "image chip changed the surrounding draft text");+ // #117: enter through the real chip, read through sandboxed image IPC,// and keep the draft, caret, and work-panel state independent of inspection.editor = controller.ref.current!;const beforePreview = readEditorValue(editor);const imageReference = controller.fileReferences[0];- const chip = document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!;- assert(chip.tagName === "BUTTON" && chip.tabIndex === 0,- "image attachment must be keyboard accessible");const dialog = () => document.querySelector<HTMLDialogElement>("dialog.composer-image-preview[open]");const until = async (condition: () => unknown, message: string) => {const deadline = performance.now() + 5000;@@ -567,7 +571,12 @@ globalThis.composerPasteProbe = async () => {const button = (label: string) => Array.from(dialog()!.querySelectorAll<HTMLButtonElement>("button")).find((element) => element.getAttribute("aria-label") === label || element.textContent === label)!;const close = () => flushSync(() => button(i18n.t("common.close")).click());- await until(() => chip.querySelector<HTMLImageElement>("img")?.naturalWidth === 1, "attachment thumbnail missing");+ // Hovering the chip reveals its preview card without opening the modal.+ chip.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));+ await until(() => document.querySelector<HTMLImageElement>(".composer-image-hover img")?.naturalWidth === 1,+ "hover preview card missing");+ chip.dispatchEvent(new PointerEvent("pointerout", { bubbles: true }));+ await until(() => !document.querySelector(".composer-image-hover"), "hover preview card outlived the pointer");editor.focus();setEditorCaret(editor, 7);flushSync(() => chip.click());@@ -617,7 +626,7 @@ globalThis.composerPasteProbe = async () => {kind: "image", mimeType: "image/png", token: "\ueffe",});flushSync(() => controller.applyEditorDraft(`${beforePreview}${wide.token}`, [imageReference, wide], 7));- flushSync(() => document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!.click());+ flushSync(() => imageChipByToken(imageReference.token!)!.click());await previewReady();assert(button(i18n.t("chat.imagePreview.previous")).disabled, "first image should disable previous");flushSync(() => button(i18n.t("chat.imagePreview.next")).click());@@ -683,17 +692,18 @@ globalThis.composerPasteProbe = async () => {assert(!dialog(), "blank-area click did not close preview");if (globalThis.composerPreviewCapture) await globalThis.composerPreviewCapture();editor.focus();- select(editor, 0, readEditorValue(editor).length);+ const galleryDraft = readEditorValue(editor);+ select(editor, 0, galleryDraft.length);assert(document.execCommand("insertText", false, "new prompt"), "text replacement failed");await new Promise(requestAnimationFrame);- assert(controller.fileReferences.length === 2 && document.querySelectorAll(".composer-image-attachment").length === 2,- "editing all text removed independent image attachments");- assert(controller.draftSnapshot("new prompt").fileReferences.length === 2,- "submission snapshot lost detached images");+ assert(controller.fileReferences.length === 0,+ "replacing the whole draft removed its inline image chips");+ assert(controller.draftSnapshot("new prompt").fileReferences.length === 0,+ "submission snapshot kept a replaced image");assert(document.execCommand("undo"), "image draft text undo unavailable");await new Promise(requestAnimationFrame);- assert(readEditorValue(editor) === beforePreview && controller.fileReferences.length === 2,- "text undo changed image attachments");+ assert(readEditorValue(editor) === galleryDraft && controller.fileReferences.length === 2,+ "text undo did not restore the inline image chips");// Cancelled image reads must never overwrite a later draft's image.const realRead = api.fsReadImageDataUrl;@@ -704,12 +714,12 @@ globalThis.composerPasteProbe = async () => {api.fsReadImageDataUrl = () => new Promise((_resolve, reject) => { rejectRead = reject; });try {flushSync(() => controller.applyEditorDraft(beforePreview, [delayed], 7));- flushSync(() => document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!.click());+ flushSync(() => imageChipByToken(imageReference.token!)!.click());assert(rejectRead && dialog(), "deferred image read was not started");api.fsReadImageDataUrl = realRead;flushSync(() => controller.applyEditorDraft(beforePreview, [imageReference], 7));assert(!dialog(), "removed preview attachment left the dialog open");- flushSync(() => document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!.click());+ flushSync(() => imageChipByToken(imageReference.token!)!.click());await previewReady();rejectRead!(new Error("late fixture read failure"));await new Promise(requestAnimationFrame);@@ -721,19 +731,19 @@ globalThis.composerPasteProbe = async () => {render("paste-a");await new Promise(requestAnimationFrame);editor = controller.ref.current!;- const currentChip = document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!;+ const currentChip = imageChipByToken(imageReference.token!)!;assert(currentChip, "returning to the session did not restore its image chip");useAppStore.setState({ activeSessionId: "paste-b" });flushSync(() => currentChip.click());assert(!dialog(), "old chip opened in another session");useAppStore.setState({ activeSessionId: "paste-a" });- const remove = currentChip.parentElement!.querySelector<HTMLButtonElement>(".composer-image-attachment-remove")!;+ const remove = currentChip.querySelector<HTMLButtonElement>(".composer-chip-remove")!;flushSync(() => {remove.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));remove.click();});assert(!dialog() && submitted === 0, "remove opened the preview or submitted the prompt");- assert(controller.fileReferences.length === 0 && readEditorValue(editor) === "prefix suffix",+ assert(controller.fileReferences.length === 0 && draftText() === "prefix suffix","remove did not preserve the surrounding draft");// Failed images remain attached, show a retry action, and never blank the draft.@@ -741,7 +751,7 @@ globalThis.composerPasteProbe = async () => {kind: "image", mimeType: "image/png", token: imageReference.token,});flushSync(() => controller.applyEditorDraft(beforePreview, [missing], 7));- flushSync(() => document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!.click());+ flushSync(() => imageChipByToken(imageReference.token!)!.click());await until(() => dialog()?.textContent?.includes(i18n.t("chat.imagePreview.error")), "missing image did not show an error");assert(readEditorValue(editor) === beforePreview && controller.fileReferences.length === 1,"failed preview lost the draft");@@ -755,24 +765,36 @@ globalThis.composerPasteProbe = async () => {kind: "image", mimeType: "image/png", token: imageReference.token,});flushSync(() => controller.applyEditorDraft(beforePreview, [corrupt], 7));- flushSync(() => document.querySelector<HTMLButtonElement>(".composer-image-attachment-open")!.click());+ flushSync(() => imageChipByToken(imageReference.token!)!.click());await until(() => dialog()?.textContent?.includes(i18n.t("chat.imagePreview.error")), "undecodable image did not show retry");assert(readEditorValue(editor) === beforePreview, "decode failure changed the draft");close();// An image-only draft remains sendable and survives session switching.editor = await paste("", [image], true);- assert(readEditorValue(editor) === "" && controller.draftSnapshot("").fileReferences.length === 1,+ assert(controller.ref.current!.querySelectorAll(".composer-chip[data-image]").length === 1 &&+ controller.draftSnapshot(readEditorValue(controller.ref.current!)).fileReferences.length === 1,"image-only draft lost its sendable attachment");const attachedId = controller.fileReferences[0].path;flushSync(() => controller.restoreDraftForKey("paste-a", { text: "older draft", fileReferences: [] }));- assert(readEditorValue(editor) === "" && controller.fileReferences[0]?.path === attachedId,+ assert(controller.ref.current!.querySelector(".composer-chip[data-image]") &&+ controller.fileReferences[0]?.path === attachedId,"restoring an old draft overwrote a newer image-only draft");render("paste-b");flushSync(() => controller.restoreDraftForKey("paste-a", { text: "older draft", fileReferences: [] }));render("paste-a");- await new Promise(requestAnimationFrame);- assert(controller.fileReferences[0]?.path === attachedId && document.querySelector(".composer-image-attachment"),+ // The restored draft hydrates from the cache in the switch effect, so give+ // the layout paint a bounded window before asserting the chip is back.+ const restoredDeadline = performance.now() + 2000;+ while (+ (controller.fileReferences[0]?.path !== attachedId ||+ !controller.ref.current!.querySelector(".composer-chip[data-image]")) &&+ performance.now() < restoredDeadline+ ) {+ await new Promise(requestAnimationFrame);+ }+ assert(controller.fileReferences[0]?.path === attachedId &&+ controller.ref.current!.querySelector(".composer-chip[data-image]"),"image-only draft did not survive session switching");await paste("file names", nativeFiles);@@ -835,8 +857,13 @@ globalThis.composerPasteProbe = async () => {await new Promise(requestAnimationFrame);await rejectSubmission();await new Promise(requestAnimationFrame);- assert(readEditorValue(controller.ref.current!) === "retry draft" && controller.fileReferences[0]?.path === imageReference.path,- "fast rejection before React commits must restore the text and attachments");+ const retryToken = controller.fileReferences[0]?.token ?? "";+ assert(+ retryToken !== "" &&+ readEditorValue(controller.ref.current!) === `retry draft${retryToken}` &&+ controller.fileReferences[0]?.path === imageReference.path,+ "fast rejection before React commits must restore the text and attachments",+ );// Native undo must restore reference metadata as well as the visible chip.await reset("inspect \uE050 please", 8, 9);const undoReference = createFileReference("src/main.ts", "main.ts", "paste-a", { token: "\uE050" });@@ -913,7 +940,7 @@ globalThis.composerPasteProbe = async () => {imagePreviewAndKeyboard: true,centeredImageGallery: true,imageDragAndReset: true,- separateImageAttachmentRow: true,+ inlineImageChips: true,imageZoomFocusAndRecovery: true,nativeMultipleFiles: true,selectionAndSessionDrafts: true,diff --git a/scripts/e2e/composer-submission.tsx b/scripts/e2e/composer-submission.tsxindex 3b4afe115..f1de6dc78 100644--- a/scripts/e2e/composer-submission.tsx+++ b/scripts/e2e/composer-submission.tsx@@ -7,6 +7,7 @@ import { useAppStore } from "../../apps/desktop/src/stores/app-store";import { api } from "../../apps/desktop/src/lib/api";import { writeComposerDraft, deleteComposerDraft } from "../../apps/desktop/src/lib/composer-draft-cache";import type { ComposerDraftSnapshot } from "../../apps/desktop/src/lib/composer-smart-stop";+import { readEditorValue } from "../../apps/desktop/src/features/chat/composer/editor";const assert = (value: unknown, message: string) => { if (!value) throw new Error(message); };const painted = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));@@ -28,6 +29,21 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {};const sendButton = () => host.querySelector<HTMLButtonElement>(".send-btn")!;const editor = () => host.querySelector<HTMLElement>(".composer-input")!;+ const imageChips = () => host.querySelectorAll<HTMLElement>(".composer-chip[data-image]");+ /** Draft text without the inline attachment chips it carries. */+ const draftText = () => {+ let text = readEditorValue(editor());+ for (const chip of imageChips()) {+ const token = chip.dataset.token ?? "";+ if (token) text = text.split(token).join("");+ }+ return text;+ };+ /** Wait until exactly `count` inline image chips are rendered. */+ const untilImageChips = async (count: number) => {+ const deadline = performance.now() + 2000;+ while (imageChips().length !== count && performance.now() < deadline) await painted();+ };try {writeComposerDraft(sessionId, { text: "retry draft", fileReferences: [attachment] });useAppStore.setState({@@ -98,7 +114,8 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {// Do not flush the click: an immediate rejection must beat React's next render.sendButton().click();await painted();- assert(sent.length === 1 && editor().textContent === "retry draft" && host.querySelectorAll(".composer-image-attachment").length === 1,+ await untilImageChips(1);+ assert(sent.length === 1 && draftText() === "retry draft" && imageChips().length === 1,"immediately rejected submission must restore text and image attachments");prefill("");@@ -109,22 +126,17 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {await painted();assert(sent.length === 2 && sent[1].content === "" && sent[1].draft?.fileReferences[0]?.path === imagePath,"image-only send must preserve the attachment at the submission boundary");- assert(!host.querySelector(".composer-image-attachment") && sendButton().disabled,+ assert(imageChips().length === 0 && sendButton().disabled,"accepted image-only submission must clear the composer");prefill("", Array.from({ length: 20 }, (_, index) => ({ ...attachment, name: `image-${index}.png` })));- await painted();- const tray = host.querySelector<HTMLElement>(".composer-image-attachments")!;- assert(tray.scrollHeight > tray.clientHeight && ["auto", "scroll"].includes(getComputedStyle(tray).overflowY),- "many image attachments must use a bounded scroll region");- assert(tray.getBoundingClientRect().top >= host.getBoundingClientRect().top,- "attachment list must stay inside the chat pane");- tray.scrollTop = tray.scrollHeight;- const last = tray.lastElementChild as HTMLElement;- assert(last.getBoundingClientRect().bottom <= tray.getBoundingClientRect().bottom + 1,- "last image must be reachable by scrolling");- flushSync(() => last.querySelector<HTMLButtonElement>(".composer-image-attachment-remove")!.click());- assert(tray.children.length === 19 && !sendButton().disabled, "scrolled attachment removal must preserve other images");+ await untilImageChips(20);+ assert(imageChips().length === 20, "every prefilled image must render an inline chip");+ assert(editor().getBoundingClientRect().bottom <= host.getBoundingClientRect().bottom + 1,+ "inline image chips must stay inside the composer pane");+ flushSync(() => imageChips()[19].querySelector<HTMLButtonElement>(".composer-chip-remove")!.click());+ assert(imageChips().length === 19 && !sendButton().disabled,+ "removing one chip must preserve the other images");// A restarted renderer has only the Host queue entry, not the cached draft.const originalRemoveQueuedPrompt = api.removeQueuedPrompt;@@ -143,16 +155,17 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {}));host.querySelector<HTMLButtonElement>(".composer-queued-prompt-edit")!.click();await painted();- assert(editor().textContent === "Review @/scratch/notes.txt" && host.querySelectorAll(".composer-image-attachment").length === 1,+ await untilImageChips(1);+ assert(draftText() === "Review @/scratch/notes.txt" && imageChips().length === 1,"editing a restored queue entry must recover text and image attachments");- editor().textContent = "Review";- flushSync(() => editor().dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" })));- await painted();+ // Sending the restored entry must carry its image attachment with it.sendButton().click();await painted();const restoredSubmission = sent.at(-1);- assert(restoredSubmission?.content === "Review" && restoredSubmission.draft?.fileReferences.length === 1 && restoredSubmission.draft.fileReferences[0].path === imagePath,- "deleting a restored inline file must remove that attachment while preserving the image");+ assert(+ restoredSubmission?.draft?.fileReferences.some((reference) => reference.path === imagePath),+ "a restored queue entry must keep its image attachment at submission",+ );} finally {api.removeQueuedPrompt = originalRemoveQueuedPrompt;}@@ -248,9 +261,10 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {: change === "attachment" || change === "reentered"? "/compact": "Next message written during compaction";- assert(editor().textContent === expectedDraft,- `completed command must preserve the expected ${change} draft: ${JSON.stringify(editor().textContent)}`);- if (change === "attachment") assert(host.querySelectorAll(".composer-image-attachment").length === 1,+ if (change === "attachment") await untilImageChips(1);+ assert(draftText() === expectedDraft,+ `completed command must preserve the expected ${change} draft: ${JSON.stringify(draftText())}`);+ if (change === "attachment") assert(imageChips().length === 1,"completed command must preserve an image added while it was running");}} finally {