Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): include generated images in the conversation gallery (#641)

Kmny84d4edee49c7
diff --git a/apps/desktop/src/renderer/__tests__/chatSessionFileContext.test.ts b/apps/desktop/src/renderer/__tests__/chatSessionFileContext.test.ts
index 4ef3fc605e..ce8408e830 100644
--- a/apps/desktop/src/renderer/__tests__/chatSessionFileContext.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatSessionFileContext.test.ts
@@ -51,6 +51,12 @@ import {
} from '../components/chat/ChatSessionFileContext';
import { collectSessionImageSrcs, type RenderItem } from '../components/chat/MessageStream';
import { rewriteToRemoteMediaOrigin, type RemoteMediaOrigin } from '../../shared/remoteMediaUrl';
+import type { GhostCardSnapshot } from '@/cindy-brain/ghostCardStore';
+import {
+ createGhostCardSpawnIndex,
+ ghostCardGalleryId,
+} from '@/cindy-brain/ghostCardGallery';
+import { GHOST_CARD_SPAWN_SEP } from '../../shared/ghost';
describe('sessionFileOrigin(纯函数)', () => {
it('deviceId 优先于 remoteHostId,两者皆空回落 local 单例', () => {
@@ -236,4 +242,70 @@ describe('collectSessionImageSrcs 与渲染改写同源契约', () => {
expect(remote[0].annotationSourceUrl).toBeUndefined();
expect(remote[0].annotationStrokes).toBeUndefined();
});
+
+ it('按消息流顺序合并用户图、插件生成图、衍生图和卡后回锚图', () => {
+ const userImage = `cindy-media://blobs/${'1'.repeat(64)}.png`;
+ const rootImage = `cindy-media://blobs/${'2'.repeat(64)}.png`;
+ const spawnImage = `cindy-media://blobs/${'3'.repeat(64)}.png`;
+ const anchoredImage = `cindy-media://blobs/${'4'.repeat(64)}.png`;
+ const spawnCallId = `card-1${GHOST_CARD_SPAWN_SEP}001`;
+ const ghostCards: GhostCardSnapshot = {
+ version: 1,
+ liveCards: [],
+ byCallId: new Map([
+ [
+ 'card-1',
+ {
+ status: 'ready',
+ ghostId: 'cindy-art',
+ html: `<img src="${rootImage}">`,
+ height: 200,
+ },
+ ],
+ [
+ spawnCallId,
+ {
+ status: 'ready',
+ ghostId: 'cindy-art',
+ html: `<img src="${spawnImage}">`,
+ height: 200,
+ },
+ ],
+ ]),
+ };
+ const mixedItems: RenderItem[] = [
+ {
+ type: 'message',
+ key: 'u-gallery',
+ message: {
+ clientId: 'u-gallery',
+ role: 'user',
+ content: 'compare',
+ images: [{ url: userImage }],
+ } as never,
+ },
+ {
+ type: 'ghost_card',
+ key: 'ghostcard-tool-1',
+ callId: 'card-1',
+ ghostId: 'cindy-art',
+ tool: 'generate',
+ toolCall: {
+ clientId: 'tool-1',
+ role: 'assistant',
+ content: '',
+ } as never,
+ settled: true,
+ media: [{ kind: 'image', url: anchoredImage }],
+ },
+ ];
+
+ expect(createGhostCardSpawnIndex(ghostCards).get('card-1')).toHaveLength(1);
+ expect(collectSessionImageSrcs(mixedItems, undefined, ghostCards)).toEqual([
+ { src: userImage },
+ { src: rootImage, galleryId: ghostCardGalleryId('card-1', 0) },
+ { src: spawnImage, galleryId: ghostCardGalleryId(spawnCallId, 0) },
+ { src: anchoredImage },
+ ]);
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/ghostCardFrameCanvas.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardFrameCanvas.test.ts
index 31db9039e3..5eb1f3f275 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCardFrameCanvas.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCardFrameCanvas.test.ts
@@ -19,4 +19,12 @@ describe('ghost card iframe canvas styling', () => {
"backgroundColor: 'var(--msg-tool-card-bg, var(--surface-elevated))'",
);
});
+
+ it('bridges iframe images into the host conversation gallery without widening the sandbox', () => {
+ expect(source).toContain('extractGhostCardGallerySrcs(renderedCardHtml)');
+ expect(source).toContain('data-gallery-src={src}');
+ expect(source).toMatch(/<ImageLightbox[\s\S]*galleryId=\{lightbox\.galleryId\}[\s\S]*enableGallery/);
+ expect(source).toContain("img.closest('[data-ghost-action], [data-ghost-link]')");
+ expect(source).toContain('sandbox="allow-same-origin"');
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/ghostCardGallery.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardGallery.test.ts
new file mode 100644
index 0000000000..b6bf56e316
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/ghostCardGallery.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ collectGhostCardGalleryImages,
+ createGhostCardSpawnIndex,
+ extractGhostCardGallerySrcs,
+ ghostCardGalleryId,
+} from '@/cindy-brain/ghostCardGallery';
+import type { GhostCardSnapshot } from '@/cindy-brain/ghostCardStore';
+import { GHOST_CARD_SPAWN_SEP } from '../../shared/ghost';
+
+function media(char: string, ext = 'png'): string {
+ return `cindy-media://blobs/${char.repeat(64)}.${ext}`;
+}
+
+describe('ghost card conversation gallery projection', () => {
+ it('keeps only images whose card click route opens ImageLightbox', () => {
+ const normal = media('a');
+ const action = media('b');
+ const link = media('c');
+ const modelPoster = media('d');
+ const nestedAction = media('e');
+ const nestedLink = media('6');
+ const cssPhantom = media('7');
+
+ expect(
+ extractGhostCardGallerySrcs(`
+ <style>.preview::before { content: '<img src="${cssPhantom}">'; }</style>
+ <img src="${normal}" alt="result">
+ <img src="${action}" data-ghost-action="retry">
+ <img src="${link}" data-ghost-link="https://example.com">
+ <div data-ghost-action="retry"><img src="${nestedAction}"></div>
+ <a data-ghost-link="https://example.com"><img src="${nestedLink}"></a>
+ <img src="${modelPoster}" data-ghost-model="${media('8', 'glb')}">
+ <img src="https://example.com/not-managed.png">
+ `),
+ ).toEqual([normal]);
+ });
+
+ it('matches root and spawned card render order with stable duplicate identities', () => {
+ const repeated = media('f');
+ const animated = media('1');
+ const spawnEarly = `root${GHOST_CARD_SPAWN_SEP}001`;
+ const spawnLate = `root${GHOST_CARD_SPAWN_SEP}002`;
+ const snapshot: GhostCardSnapshot = {
+ version: 1,
+ liveCards: [],
+ byCallId: new Map([
+ [
+ spawnLate,
+ {
+ status: 'ready',
+ ghostId: 'cindy-art',
+ html: `<img src="${repeated}">`,
+ height: 200,
+ },
+ ],
+ [
+ 'root',
+ {
+ status: 'ready',
+ ghostId: 'cindy-art',
+ html: `<img src="${repeated}">`,
+ animatedHtml: `<img src="${animated}">`,
+ height: 200,
+ },
+ ],
+ [
+ spawnEarly,
+ {
+ status: 'ready',
+ ghostId: 'cindy-art',
+ html: `<img src="${repeated}">`,
+ height: 200,
+ },
+ ],
+ ]),
+ };
+
+ const spawnIndex = createGhostCardSpawnIndex(snapshot);
+ expect([...spawnIndex.keys()]).toEqual(['root']);
+ expect(collectGhostCardGalleryImages('root', snapshot, true, spawnIndex)).toEqual([
+ { src: animated, galleryId: ghostCardGalleryId('root', 0) },
+ { src: repeated, galleryId: ghostCardGalleryId(spawnEarly, 0) },
+ { src: repeated, galleryId: ghostCardGalleryId(spawnLate, 0) },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/ghostImageLightboxGallery.test.tsx b/apps/desktop/src/renderer/__tests__/ghostImageLightboxGallery.test.tsx
new file mode 100644
index 0000000000..4086ffc869
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/ghostImageLightboxGallery.test.tsx
@@ -0,0 +1,35 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import '@/i18n';
+import { ImageGalleryContext } from '@/components/chat/ImageGalleryContext';
+import { ImageLightbox } from '@/components/chat/ImageLightbox';
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('Ghost card ImageLightbox gallery positioning', () => {
+ it('opens the exact duplicate image selected inside a plugin card iframe', () => {
+ const repeated = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ render(
+ <ImageGalleryContext.Provider
+ value={[
+ { src: repeated, galleryId: 'ghost-card:first:0' },
+ { src: repeated, galleryId: 'ghost-card:second:0' },
+ ]}
+ >
+ <ImageLightbox
+ src={repeated}
+ galleryId="ghost-card:second:0"
+ enableGallery
+ onClose={vi.fn()}
+ />
+ </ImageGalleryContext.Provider>,
+ );
+
+ expect(screen.getByText('2 / 2')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostCardGallery.ts b/apps/desktop/src/renderer/cindy-brain/ghostCardGallery.ts
new file mode 100644
index 0000000000..a899695f77
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/ghostCardGallery.ts
@@ -0,0 +1,93 @@
+/**
+ * Ghost card image gallery projection.
+ *
+ * Card HTML has already been sanitized by Main before it reaches Renderer.
+ * This module only projects image references into the host-owned conversation
+ * gallery; it does not parse bytes, widen the iframe bridge, or grant plugins
+ * any new capability.
+ */
+
+import { ghostCardRootCallId } from '../../shared/ghost';
+import type { GhostCardEntry, GhostCardSnapshot } from './ghostCardStore';
+import type { GalleryImage } from '@/components/chat/ImageGalleryContext';
+
+const CINDY_MEDIA_IMAGE_RE = /^cindy-media:\/\/blobs\/[0-9a-f]{64}\.(?:png|jpe?g|gif|webp)$/;
+
+type ReadyGhostCardEntry = Extract<GhostCardEntry, { status: 'ready' }>;
+type SpawnCard = { callId: string; entry: ReadyGhostCardEntry };
+export type GhostCardSpawnIndex = ReadonlyMap<string, readonly SpawnCard[]>;
+
+/**
+ * Returns only images whose click route opens ImageLightbox. Action/link images
+ * remain card controls, while model posters continue to open ModelLightbox.
+ */
+export function extractGhostCardGallerySrcs(html: string): string[] {
+ const cardDocument = new DOMParser().parseFromString(html, 'text/html');
+ return [...cardDocument.querySelectorAll<HTMLImageElement>('img[src]')]
+ .filter((img) => {
+ const src = img.getAttribute('src')?.trim() ?? '';
+ return (
+ CINDY_MEDIA_IMAGE_RE.test(src) &&
+ !img.closest('[data-ghost-action], [data-ghost-link]') &&
+ !img.dataset.ghostModel
+ );
+ })
+ .map((img) => img.getAttribute('src')!.trim());
+}
+
+/** Stable identity used to locate duplicate URLs at the exact clicked card image. */
+export function ghostCardGalleryId(callId: string, imageIndex: number): string {
+ return `ghost-card:${callId}:${imageIndex}`;
+}
+
+function visibleCardHtml(entry: ReadyGhostCardEntry, running: boolean): string {
+ return running && entry.animatedHtml ? entry.animatedHtml : entry.html;
+}
+
+function projectCard(callId: string, entry: ReadyGhostCardEntry, running: boolean): GalleryImage[] {
+ return extractGhostCardGallerySrcs(visibleCardHtml(entry, running)).map((src, imageIndex) => ({
+ src,
+ galleryId: ghostCardGalleryId(callId, imageIndex),
+ }));
+}
+
+/** Builds the root → spawned-card lookup once for one session gallery projection. */
+export function createGhostCardSpawnIndex(snapshot: GhostCardSnapshot): GhostCardSpawnIndex {
+ const mutable = new Map<string, SpawnCard[]>();
+ for (const [callId, entry] of snapshot.byCallId) {
+ if (entry.status !== 'ready') continue;
+ const rootCallId = ghostCardRootCallId(callId);
+ if (rootCallId === callId) continue;
+ const cards = mutable.get(rootCallId) ?? [];
+ cards.push({ callId, entry });
+ mutable.set(rootCallId, cards);
+ }
+ for (const cards of mutable.values()) {
+ cards.sort((left, right) =>
+ left.callId < right.callId ? -1 : left.callId > right.callId ? 1 : 0,
+ );
+ }
+ return mutable;
+}
+
+/**
+ * Projects a rendered root card followed by its spawned cards, matching
+ * GhostToolCard's DOM order. Only entries belonging to this root call are read.
+ */
+export function collectGhostCardGalleryImages(
+ rootCallId: string,
+ snapshot: GhostCardSnapshot,
+ rootRunning: boolean,
+ spawnIndex: GhostCardSpawnIndex,
+): GalleryImage[] {
+ const root = snapshot.byCallId.get(rootCallId);
+ const images: GalleryImage[] = [];
+ if (root?.status === 'ready') {
+ images.push(...projectCard(rootCallId, root, rootRunning || root.state === 'working'));
+ }
+
+ for (const { callId, entry } of spawnIndex.get(rootCallId) ?? []) {
+ images.push(...projectCard(callId, entry, entry.state === 'working'));
+ }
+ return images;
+}
diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
index 0e73bd118f..3d61f940d3 100644
--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
@@ -52,6 +52,10 @@ import {
subscribeGhostCards,
} from '@/cindy-brain/ghostCardStore';
import { useGhostCardThemeVars } from '@/cindy-brain/useGhostCardThemeVars';
+import {
+ extractGhostCardGallerySrcs,
+ ghostCardGalleryId,
+} from '@/cindy-brain/ghostCardGallery';
import {
GHOST_CARD_ACTION_INFLIGHT_MS,
GHOST_CARD_ACTION_PROMPT_MAX_LEN,
@@ -166,7 +170,7 @@ function GhostCardCanvas({
const { t } = useTranslation();
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const anchorRef = useRef<HTMLDivElement | null>(null);
- const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
+ const [lightbox, setLightbox] = useState<{ src: string; galleryId: string } | null>(null);
// data-ghost-model 声明的 3D 预览:点击开应用内 3D 查看器(GLB 已在媒体
// 总仓,blob 来源直读,预览图作 poster)。
const [modelView, setModelView] = useState<{ url: string; poster: string } | null>(null);
@@ -211,6 +215,11 @@ function GhostCardCanvas({
// 只立 pending 标记,等 commit 落地后的 effect 再放开缓动开关。
const settledOnceRef = useRef(false);
const pendingSettleRef = useRef(false);
+ const renderedCardHtml = running && animatedHtml ? animatedHtml : html;
+ const gallerySrcs = useMemo(
+ () => extractGhostCardGallerySrcs(renderedCardHtml),
+ [renderedCardHtml],
+ );
const measureHeight = useCallback(() => {
const doc = iframeRef.current?.contentDocument;
@@ -374,6 +383,7 @@ function GhostCardCanvas({
const doc = iframeRef.current?.contentDocument;
if (!doc) return;
const imgs = doc.querySelectorAll<HTMLImageElement>('img[src^="cindy-media://"]');
+ let galleryImageIndex = 0;
imgs.forEach((img) => {
// 量高写回会让 height prop 变化 → effect 重跑,对同一份未重载的文档
// 再走到这里;dataset 标记去重,避免重复挂监听(srcDoc 换新文档时
@@ -397,9 +407,12 @@ function GhostCardCanvas({
// 图片点击的四级路由:data-ghost-action(动作按钮)> data-ghost-link
// (外链,均由下面的循环挂)> data-ghost-model(3D 预览 → 应用内 3D
// 查看器)> 普通看大图 lightbox。
- if (!img.dataset.ghostAction && !img.dataset.ghostLink) {
+ if (!img.closest('[data-ghost-action], [data-ghost-link]')) {
img.style.cursor = 'pointer';
const modelUrl = img.dataset.ghostModel;
+ const galleryId = modelUrl
+ ? null
+ : ghostCardGalleryId(callId, galleryImageIndex++);
img.addEventListener('click', (e) => {
e.stopPropagation();
// 点击发生在 iframe 里,焦点会留在 guest 文档——keydown 不跨文档冒泡,
@@ -407,7 +420,7 @@ function GhostCardCanvas({
// GhostMediaLightboxHost 同坑同解:blur 掉 iframe,键盘立即归位)。
iframeRef.current?.blur();
if (modelUrl) setModelView({ url: modelUrl, poster: img.src });
- else setLightboxSrc(img.src);
+ else if (galleryId) setLightbox({ src: img.src, galleryId });
});
}
// 右键 → 宿主图片菜单(复制图片 / 打开所在目录,与基座 ChatImageView 同
@@ -596,7 +609,7 @@ function GhostCardCanvas({
<iframe
ref={iframeRef}
sandbox="allow-same-origin"
- srcDoc={buildCardSrcDoc(running && animatedHtml ? animatedHtml : html, themeVars)}
+ srcDoc={buildCardSrcDoc(renderedCardHtml, themeVars)}
onLoad={attachClickBridge}
title={ariaTitle}
className="block w-full border-0"
@@ -626,6 +639,17 @@ function GhostCardCanvas({
</div>
) : null}
</div>
+ {/* iframe 子文档不在宿主 querySelector 范围内。镜像零尺寸标记让既有
+ DOM 位置映射仍看到完整顺序,避免相同 URL 的普通附件被错定位到
+ 插件图片;真正的图片和点击处理仍留在沙箱 iframe 内。 */}
+ {gallerySrcs.map((src, imageIndex) => (
+ <span
+ key={ghostCardGalleryId(callId, imageIndex)}
+ hidden
+ aria-hidden
+ data-gallery-src={src}
+ />
+ ))}
{/* ── data-ghost-prompt 输入面板(宿主交互面,与 lightbox 同层;体验与
老基座 ChatImageActions 的 imgPrompt popover 一致:textarea + 回车
@@ -825,8 +849,14 @@ function GhostCardCanvas({
</DropdownMenu>
) : null}
- {lightboxSrc ? (
- <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} sessionId={sessionId} />
+ {lightbox ? (
+ <ImageLightbox
+ src={lightbox.src}
+ galleryId={lightbox.galleryId}
+ enableGallery
+ onClose={() => setLightbox(null)}
+ sessionId={sessionId}
+ />
) : null}
{modelView ? (
<ModelLightbox
diff --git a/apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx b/apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx
index c8e36050fb..4a2ca3a16c 100644
--- a/apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx
+++ b/apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx
@@ -24,6 +24,12 @@ import type { AnnotationStroke } from './lightboxAnnotations';
/** 会话画廊里的一张图:src 为渲染所用 URL(标注图 = 烧录图)。 */
export interface GalleryImage {
src: string;
+ /**
+ * Optional stable identity for images rendered outside the host DOM, such as
+ * plugin card iframe images. It disambiguates repeated URLs when opening the
+ * conversation gallery from one of those images.
+ */
+ galleryId?: string;
/** 烧录标注图的未烧录原图 URL(与 ImageRef.annotationSourceUrl 同源)。 */
annotationSourceUrl?: string;
/** 持久化的矢量笔迹;与 annotationSourceUrl 成对出现才有意义。 */
diff --git a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
index 676a47daae..0d77b71090 100644
--- a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
+++ b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx
@@ -107,6 +107,11 @@ const FIT_VIEWPORT: LightboxViewport = { scale: 1, tx: 0, ty: 0 };
interface ImageLightboxProps {
src: string;
onClose: () => void;
+ /**
+ * Stable identity of the clicked gallery item. Needed when the source lives
+ * inside an iframe, where the host DOM active-marker fallback cannot reach.
+ */
+ galleryId?: string;
/**
* 会话内翻图。开启后,lightbox 提供左右箭头 + ←/→ 键盘翻页 + "n / 总数" 计数,
* 在当前会话的所有图片间切换。
@@ -327,6 +332,7 @@ export function ImageLightbox({
src,
onClose,
enableGallery = false,
+ galleryId,
sessionId: sessionIdProp,
annotationEdit,
initialStrokes,
@@ -351,6 +357,13 @@ export function ImageLightbox({
// 不然会套用会话画廊、起始落到不相干的第 0 张图。
const [gallery] = useState<{ items: readonly GalleryImage[]; start: number }>(() => {
if (!enableGallery) return { items: [{ src }], start: 0 };
+ const keyedIndex =
+ galleryId && sessionImages
+ ? sessionImages.findIndex((item) => item.galleryId === galleryId)
+ : -1;
+ if (sessionImages && keyedIndex >= 0) {
+ return { items: sessionImages, start: keyedIndex };
+ }
if (sessionImages?.some((g) => g.src === src)) {
return { items: sessionImages, start: resolveStartIndexInFull(sessionImages, src) };
}
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index d64ccab26a..96296539e1 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -158,6 +158,10 @@ import {
subscribeGhostCards,
type GhostCardSnapshot,
} from '@/cindy-brain/ghostCardStore';
+import {
+ collectGhostCardGalleryImages,
+ createGhostCardSpawnIndex,
+} from '@/cindy-brain/ghostCardGallery';
import { ChatImageView } from './ChatImageView';
import { ImageGalleryContext, type GalleryImage } from './ImageGalleryContext';
import { GhostFulfillmentContext } from './GhostSummonCard';
@@ -664,9 +668,10 @@ export function findRestorableViewportItemIdx(items: RenderItem[], viewportTopKe
/**
* 从全量 render items 里按渲染顺序抽出会话内所有图片的 src,作为 lightbox 翻图
- * 的数据源(全量,不受渲染窗口裁剪影响)。只收**结构化、确定会渲染成图**的两类:
+ * 的数据源(全量,不受渲染窗口裁剪影响)。只收**结构化、确定会渲染成图**的三类:
* - tool-output 图(art 出图 / 飞书拉图等)→ tool_media item 的 image 项
* - 用户上传图 → user message 的 images(url 或 data:base64,与 UserMessage 同款拼法)
+ * - 插件生成图 → ghost card 及其衍生卡中会打开 ImageLightbox 的图片
*
* 不收正文 Markdown 内嵌图:用正则扫文本会误抓代码块里当作文本展示的 ![]() 语法,
* 虚增计数 / 让翻页跳到无效图(codex review);要准确得复刻 MarkdownRenderer 的
@@ -676,12 +681,15 @@ export function findRestorableViewportItemIdx(items: RenderItem[], viewportTopKe
export function collectSessionImageSrcs(
items: RenderItem[],
mediaOrigin?: RemoteMediaOrigin,
+ ghostCards?: GhostCardSnapshot,
+ isSessionStreaming = false,
): GalleryImage[] {
// 远程会话:画廊 src 必须与渲染出的 <img data-gallery-src> 同样改写到 cindy-remote-media://,
// 否则 ImageLightbox 的画廊 src 匹配对不上、退化成仅当前窗口翻图 + 计数错。
const push = (url: string, meta?: Omit<GalleryImage, 'src'>): void =>
void out.push({ src: rewriteToRemoteMediaOrigin(url, mediaOrigin), ...meta });
const out: GalleryImage[] = [];
+ const ghostCardSpawnIndex = ghostCards ? createGhostCardSpawnIndex(ghostCards) : undefined;
for (const item of items) {
if (item.type === 'fork_origin') {
continue;
@@ -689,6 +697,21 @@ export function collectSessionImageSrcs(
for (const m of item.items) {
if (m.kind === 'image' && m.url) push(m.url);
}
+ } else if (item.type === 'ghost_card') {
+ if (ghostCards) {
+ for (const image of collectGhostCardGalleryImages(
+ item.callId,
+ ghostCards,
+ !item.settled && isSessionStreaming,
+ ghostCardSpawnIndex!,
+ )) {
+ push(image.src, { galleryId: image.galleryId });
+ }
+ }
+ // 回锚媒体渲染在卡片及其衍生卡之后,画廊顺序必须与 DOM 一致。
+ for (const media of item.media ?? []) {
+ if (media.kind === 'image' && media.url) push(media.url);
+ }
} else if (item.type === 'message') {
const msg = item.message;
if (msg.role === 'user' && msg.images) {
@@ -709,6 +732,16 @@ export function collectSessionImageSrcs(
push(`data:${img.mimeType};base64,${img.base64}`);
}
}
+ } else if (msg.role === 'assistant' && ghostCards) {
+ // will-assistant-message 出口钩子的自绘卡以消息 clientId 为根 callId。
+ for (const image of collectGhostCardGalleryImages(
+ msg.clientId,
+ ghostCards,
+ false,
+ ghostCardSpawnIndex!,
+ )) {
+ push(image.src, { galleryId: image.galleryId });
+ }
}
}
}
@@ -2082,8 +2115,14 @@ export function MessageStream({
[sessionFileValue],
);
const sessionImageSrcs = useMemo(
- () => collectSessionImageSrcs(allRenderItems, galleryMediaOrigin),
- [allRenderItems, galleryMediaOrigin],
+ () =>
+ collectSessionImageSrcs(
+ allRenderItems,
+ galleryMediaOrigin,
+ ghostCardSnapshot,
+ isSessionStreaming,
+ ),
+ [allRenderItems, galleryMediaOrigin, ghostCardSnapshot, isSessionStreaming],
);
// 把可见窗口往前(更早)推 RENDER_WINDOW_GROWTH_ITEMS 个 item,用于滚到顶时的客户端扩窗。