Use the host image loader for chat attachments

This commit is contained in:
QQ 2026-11-28 16:39:16 +08:00
parent 348f774669
commit eec1b3f1a6
7 changed files with 30 additions and 68 deletions

View File

@ -46611,12 +46611,6 @@ ${trimmed}
}); });
}); });
// src/client/Blocks.tsx // src/client/Blocks.tsx
const IMAGE_TYPES = /* @__PURE__ */ new Set([
"image/png",
"image/jpeg",
"image/webp",
"image/gif"
]);
var BlockBoundary = class extends react.Component { var BlockBoundary = class extends react.Component {
state = { state = {
failed: false, failed: false,
@ -46643,7 +46637,7 @@ ${trimmed}
}) : this.props.children; }) : this.props.children;
} }
}; };
const ImageBlock = (0, react.memo)(function ImageBlock({ attachment, label = attachment.name, loadImage, loadUrl }) { const ImageBlock = (0, react.memo)(function ImageBlock({ attachment, label = attachment.name, loadImage }) {
const [attempt, setAttempt] = (0, react.useState)(0); const [attempt, setAttempt] = (0, react.useState)(0);
const [url, setUrl] = (0, react.useState)(null); const [url, setUrl] = (0, react.useState)(null);
const [error, setError] = (0, react.useState)(false); const [error, setError] = (0, react.useState)(false);
@ -46652,7 +46646,6 @@ ${trimmed}
const opener = (0, react.useRef)(null); const opener = (0, react.useRef)(null);
(0, react.useEffect)(() => { (0, react.useEffect)(() => {
let active = true; let active = true;
let owned = null;
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
if (active) { if (active) {
setError(true); setError(true);
@ -46662,16 +46655,7 @@ ${trimmed}
setError(false); setError(false);
setDecoded(false); setDecoded(false);
setUrl(null); setUrl(null);
const resolve = async () => { Promise.resolve().then(() => loadImage(attachment)).then((result) => {
if (loadUrl) return loadUrl(attachment);
const result = await loadImage(attachment);
if (!active) return null;
if (!IMAGE_TYPES.has(result.mediaType)) throw new Error("Unsupported image media type");
const bytes = Uint8Array.from(result.data);
owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType }));
return owned;
};
resolve().then((result) => {
if (!active) return; if (!active) return;
clearTimeout(timeout); clearTimeout(timeout);
setUrl(result); setUrl(result);
@ -46682,13 +46666,11 @@ ${trimmed}
return () => { return () => {
active = false; active = false;
clearTimeout(timeout); clearTimeout(timeout);
if (owned) URL.revokeObjectURL(owned);
}; };
}, [ }, [
attachment.attachmentId, attachment,
attempt, attempt,
loadImage, loadImage
loadUrl
]); ]);
const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4; const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4;
const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3; const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3;
@ -46756,7 +46738,7 @@ ${trimmed}
children: images.map((image, index) => "attachment" in image ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ImageBlock, { children: images.map((image, index) => "attachment" in image ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ImageBlock, {
attachment: image.attachment, attachment: image.attachment,
label: image.label, label: image.label,
loadUrl: loadImage loadImage
}, index) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { }, index) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
className: Reader_module_css_default.pendingImage, className: Reader_module_css_default.pendingImage,
src: image.preview.url, src: image.preview.url,
@ -52499,7 +52481,7 @@ ${trimmed}
const shared = { const shared = {
useChat: useFlowChat, useChat: useFlowChat,
renderSlotChain: props.renderSlotChain, renderSlotChain: props.renderSlotChain,
loadImage: props.loadImage, loadImage: props.officialImageLoader,
fillComposer: props.fillComposer, fillComposer: props.fillComposer,
openFile: props.openFile, openFile: props.openFile,
revealFile: props.revealFile, revealFile: props.revealFile,
@ -53551,6 +53533,7 @@ ${trimmed}
}, },
store, store,
inject: (sessionId) => { inject: (sessionId) => {
const uiConversation = ctx.uiConversation;
const session = () => { const session = () => {
const current = ctx.sessions.binding(sessionId)?.session; const current = ctx.sessions.binding(sessionId)?.session;
if (!current) throw new Error("阅读页对应的会话已关闭。"); if (!current) throw new Error("阅读页对应的会话已关闭。");
@ -53558,7 +53541,7 @@ ${trimmed}
}; };
return { return {
openPrefs: prefs, openPrefs: prefs,
officialImageLoader: Object.assign((attachment) => ctx.uiConversation.imageUrl(sessionId, attachment), { peek: (attachment) => ctx.uiConversation.peekImageUrl(sessionId, attachment) }), officialImageLoader: Object.assign((attachment) => uiConversation.imageUrl(sessionId, attachment), { peek: (attachment) => uiConversation.peekImageUrl(sessionId, attachment) }),
officialFileMentions: (owner) => ctx.get("chatFileMentions")?.forClosing(owner, sessionId), officialFileMentions: (owner) => ctx.get("chatFileMentions")?.forClosing(owner, sessionId),
officialPreviewFile: (path) => { officialPreviewFile: (path) => {
const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd; const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;
@ -53570,14 +53553,6 @@ ${trimmed}
loadOlder: async () => { loadOlder: async () => {
await session().loadOlder(); await session().loadOlder();
}, },
loadImage: async (attachment) => {
const receipt = await session().readAttachment(attachment.attachmentId);
if (!receipt.ok) throw new Error(receipt.error.message);
return {
data: Uint8Array.from(receipt.value.data),
mediaType: receipt.value.attachment.mediaType
};
},
openFile: async (path, options) => { openFile: async (path, options) => {
try { try {
const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd; const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd;

File diff suppressed because one or more lines are too long

View File

@ -13,8 +13,6 @@ import { activeTextTransform, displayStreaming, originalAnswerText, readerBlockO
import type { TextTransformRegistry } from './text-transform.js'; import type { TextTransformRegistry } from './text-transform.js';
import css from './Reader.module.css'; import css from './Reader.module.css';
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
export class BlockBoundary extends Component<{ children: ReactNode }, { failed: boolean; detail: string }> { export class BlockBoundary extends Component<{ children: ReactNode }, { failed: boolean; detail: string }> {
state = { failed: false, detail: '' }; state = { failed: false, detail: '' };
// Temporary diagnostic: surface the reason inline so a recurrence is reportable // Temporary diagnostic: surface the reason inline so a recurrence is reportable
@ -30,12 +28,9 @@ export class BlockBoundary extends Component<{ children: ReactNode }, { failed:
} }
} }
type ImageBlockProps = { attachment: ImageAttachmentRef; label?: string } & ( type ImageBlockProps = { attachment: ImageAttachmentRef; label?: string; loadImage: MessageImageLoader };
| { loadImage: BlockRenderProps['loadImage']; loadUrl?: never }
| { loadImage?: never; loadUrl: MessageImageLoader }
);
export const ImageBlock = memo(function ImageBlock({ attachment, label = attachment.name, loadImage, loadUrl }: ImageBlockProps) { export const ImageBlock = memo(function ImageBlock({ attachment, label = attachment.name, loadImage }: ImageBlockProps) {
const [attempt, setAttempt] = useState(0); const [attempt, setAttempt] = useState(0);
const [url, setUrl] = useState<string | null>(null); const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState(false); const [error, setError] = useState(false);
@ -44,26 +39,16 @@ export const ImageBlock = memo(function ImageBlock({ attachment, label = attachm
const opener = useRef<HTMLButtonElement>(null); const opener = useRef<HTMLButtonElement>(null);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
let owned: string | null = null;
const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 20000); const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 20000);
setError(false); setDecoded(false); setUrl(null); setError(false); setDecoded(false); setUrl(null);
const resolve = async () => { // Await the canonical URL. The host may revoke a cached submission preview.
// The cached preview can be revoked when the canonical attachment arrives. void Promise.resolve().then(() => loadImage(attachment)).then(result => {
if (loadUrl) return loadUrl(attachment);
const result = await loadImage(attachment);
if (!active) return null;
if (!IMAGE_TYPES.has(result.mediaType)) throw new Error('Unsupported image media type');
const bytes = Uint8Array.from(result.data);
owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType }));
return owned;
};
void resolve().then(result => {
if (!active) return; if (!active) return;
clearTimeout(timeout); clearTimeout(timeout);
setUrl(result); setUrl(result);
}).catch(() => { clearTimeout(timeout); if (active) setError(true); }); }).catch(() => { clearTimeout(timeout); if (active) setError(true); });
return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); }; return () => { active = false; clearTimeout(timeout); };
}, [attachment.attachmentId, attempt, loadImage, loadUrl]); }, [attachment, attempt, loadImage]);
const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4; const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4;
const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3; const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3;
return <figure className={css.imageFigure} data-reader-image data-image-state={error ? 'error' : decoded ? 'ready' : 'loading'}> return <figure className={css.imageFigure} data-reader-image data-image-state={error ? 'error' : decoded ? 'ready' : 'loading'}>
@ -88,7 +73,7 @@ export const ImageBlock = memo(function ImageBlock({ attachment, label = attachm
export function UserImageFallback({ images, loadImage }: MessageImagesOwnerProps) { export function UserImageFallback({ images, loadImage }: MessageImagesOwnerProps) {
return <div className={css.userImages}> return <div className={css.userImages}>
{images.map((image, index) => 'attachment' in image {images.map((image, index) => 'attachment' in image
? <ImageBlock key={index} attachment={image.attachment} label={image.label} loadUrl={loadImage} /> ? <ImageBlock key={index} attachment={image.attachment} label={image.label} loadImage={loadImage} />
: <img key={index} className={css.pendingImage} src={image.preview.url} alt={image.preview.name ?? '发送的图片'} />)} : <img key={index} className={css.pendingImage} src={image.preview.url} alt={image.preview.name ?? '发送的图片'} />)}
</div>; </div>;
} }

View File

@ -564,7 +564,7 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
const shared = { const shared = {
useChat: useFlowChat, useChat: useFlowChat,
renderSlotChain: props.renderSlotChain, renderSlotChain: props.renderSlotChain,
loadImage: props.loadImage, loadImage: props.officialImageLoader,
fillComposer: props.fillComposer, fillComposer: props.fillComposer,
openFile: props.openFile, openFile: props.openFile,
revealFile: props.revealFile, revealFile: props.revealFile,

View File

@ -109,6 +109,7 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
}, },
store, store,
inject: (sessionId: SessionId): ReaderInjected => { inject: (sessionId: SessionId): ReaderInjected => {
const uiConversation = ctx.uiConversation;
const session = () => { const session = () => {
const current = ctx.sessions.binding(sessionId)?.session; const current = ctx.sessions.binding(sessionId)?.session;
if (!current) throw new Error('阅读页对应的会话已关闭。'); if (!current) throw new Error('阅读页对应的会话已关闭。');
@ -117,8 +118,8 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
return { return {
openPrefs: prefs, openPrefs: prefs,
officialImageLoader: Object.assign( officialImageLoader: Object.assign(
(attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment), (attachment: ImageAttachmentRef) => uiConversation.imageUrl(sessionId, attachment),
{ peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) }, { peek: (attachment: ImageAttachmentRef) => uiConversation.peekImageUrl(sessionId, attachment) },
), ),
officialFileMentions: owner => ctx.get('chatFileMentions')?.forClosing(owner, sessionId), officialFileMentions: owner => ctx.get('chatFileMentions')?.forClosing(owner, sessionId),
officialPreviewFile: path => { officialPreviewFile: path => {
@ -129,11 +130,6 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
}, },
officialHostHome, officialHostHome,
loadOlder: async () => { await session().loadOlder(); }, loadOlder: async () => { await session().loadOlder(); },
loadImage: async attachment => {
const receipt = await session().readAttachment(attachment.attachmentId);
if (!receipt.ok) throw new Error(receipt.error.message);
return { data: Uint8Array.from(receipt.value.data), mediaType: receipt.value.attachment.mediaType };
},
openFile: async (path, options) => { openFile: async (path, options) => {
try { try {
const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd; const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd;

View File

@ -1,4 +1,3 @@
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import type { AssistantBlock, MessageImageLoader } from '@deepseek-ai/dsh-client-ui-conversation/client'; import type { AssistantBlock, MessageImageLoader } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives'; import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives';
import type { PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'; import type { PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots';
@ -44,7 +43,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
export interface ReaderInjected { export interface ReaderInjected {
loadOlder: () => Promise<void>; loadOlder: () => Promise<void>;
loadImage: (attachment: ImageAttachmentRef) => Promise<{ data: Uint8Array; mediaType: string }>;
/** /**
* Writes text into this session's composer draft via the sanctioned * Writes text into this session's composer draft via the sanctioned
* conversation input face, with a DOM fallback. Returns true when the * conversation input face, with a DOM fallback. Returns true when the
@ -86,7 +84,8 @@ export type ReaderProps = PropsRuntime<'conversation.view'>
& PropsRenderSlots<'dsh-better-display.block' | OfficialSeat> & PropsRenderSlots<'dsh-better-display.block' | OfficialSeat>
& PropsStore<ReturnType<typeof createReaderStore>> & PropsStore<ReturnType<typeof createReaderStore>>
& ReaderInjected; & ReaderInjected;
export type BlockRenderProps = Pick<ReaderProps, 'renderSlotChain' | 'loadImage' | 'fillComposer'> & { export type BlockRenderProps = Pick<ReaderProps, 'renderSlotChain' | 'fillComposer'> & {
loadImage: MessageImageLoader;
official?: Pick<ReaderProps, 'renderSlot' | 'renderSlotChain' | 'officialImageLoader' | 'officialFileMentions' | 'officialPreviewFile' | 'officialHostHome' | 'openView'>; official?: Pick<ReaderProps, 'renderSlot' | 'renderSlotChain' | 'officialImageLoader' | 'officialFileMentions' | 'officialPreviewFile' | 'officialHostHome' | 'openView'>;
cwd?: string; cwd?: string;
openFile?: (path: string, options?: OpenFileOptions) => Promise<void> | void; openFile?: (path: string, options?: OpenFileOptions) => Promise<void> | void;

View File

@ -51,7 +51,7 @@ test('reasoning bodies render through compact Markdown', () => {
test('the optional user-image slot has a low-priority renderer', () => { test('the optional user-image slot has a low-priority renderer', () => {
assert.match(source, /name: 'conversation\.chat\.user\.images',\s*priority: 1000,[\s\S]*?UserImageFallback/u); assert.match(source, /name: 'conversation\.chat\.user\.images',\s*priority: 1000,[\s\S]*?UserImageFallback/u);
assert.match(blocks, /loadUrl=\{loadImage\}/u); assert.match(blocks, /loadImage=\{loadImage\}/u);
assert.match(blocks, /src=\{image\.preview\.url\}/u); assert.match(blocks, /src=\{image\.preview\.url\}/u);
}); });
@ -87,3 +87,10 @@ test('live summaries and visible work share a frame that is removed when folded'
assert.match(readerCss, /\[data-flow-process\] > \.flowCellInner:not\(:empty\)/u); assert.match(readerCss, /\[data-flow-process\] > \.flowCellInner:not\(:empty\)/u);
assert.match(reader, /const expanded = !autoFold \|\| holdingSelection \|\| processExpanded\(expansionChoice, boundary\)/u); assert.match(reader, /const expanded = !autoFold \|\| holdingSelection \|\| processExpanded\(expansionChoice, boundary\)/u);
}); });
test('all Reader attachment previews delegate the full reference to the host loader', () => {
assert.match(reader, /loadImage: props\.officialImageLoader/u);
assert.match(source, /uiConversation\.imageUrl\(sessionId, attachment\)/u);
assert.match(blocks, /loadImage\(attachment\)/u);
assert.doesNotMatch(source, /readAttachment\(attachment\.attachmentId\)/u);
});