Skip to content

Commit 07590d0

Browse files
roberttwangclaude
andcommitted
fix(web): detect binary deliverables by content before previewing
A deliverable declared without a media type is stored as text/markdown, so a small zip or other binary file was still rendered as garbage. Check the body instead of the declared type: NUL bytes or a mostly undecodable start show the download hint, while text types such as NDJSON keep previewing. Co-Authored-By: Claude Code <noreply@anthropic.com>
1 parent f5085f6 commit 07590d0

4 files changed

Lines changed: 52 additions & 10 deletions

File tree

‎chatbot/src/RichContent.jsx‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,13 @@ export function Attachment({ attachment, sessionId, onOpen }) {
540540
}
541541
// Larger files are offered for download instead of being read into the page.
542542
const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
543+
// Deliverables without a declared type are stored as Markdown, so the body
544+
// decides: NUL bytes or a mostly undecodable start mean binary content.
545+
function looksBinary(content) {
546+
if (content.includes("\u0000")) return true;
547+
const head = content.slice(0, 65536);
548+
return (head.match(/\uFFFD/g) || []).length > head.length * 0.1;
549+
}
543550
export function ArtifactPreview({ artifact }) {
544551
const [text, setText] = useState("");
545552
const [error, setError] = useState("");
@@ -599,7 +606,9 @@ export function ArtifactPreview({ artifact }) {
599606
}, [artifact?.id, artifact?.url, artifact?.localDataUrl, readable, oversized]);
600607
if (!artifact) return null;
601608
const source = artifact.url ? text : (artifact.content ?? text);
602-
const hasSource = typeof source === "string" && source.length > 0 && !error;
609+
const binary = Boolean(artifact.url) && looksBinary(text);
610+
const hasSource =
611+
typeof source === "string" && source.length > 0 && !error && !binary;
603612
const isMarkdown =
604613
artifact.mimeType?.startsWith("text/markdown") ||
605614
["markdown", "md"].includes(artifact.language?.toLowerCase());
@@ -701,6 +710,8 @@ export function ArtifactPreview({ artifact }) {
701710
/>
702711
) : oversized ? (
703712
<p className="muted">文件较大,不在页面内预览,可通过右上角下载查看。</p>
713+
) : binary ? (
714+
<p className="muted">此类型文件可通过右上角下载查看。</p>
704715
) : mode === "source" && canPreview ? (
705716
<pre className="artifact-source">
706717
<code>{source}</code>

‎chatbot/tests/components.test.jsx‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,23 @@ describe("content and panels", () => {
244244
globalThis.fetch = originalFetch;
245245
});
246246

247+
test("offers binary content declared as Markdown for download", async () => {
248+
const originalFetch = globalThis.fetch;
249+
globalThis.fetch = vi.fn(async () => ({ ok: true, text: async () => "PK\u0003\u0004\u0000\u0000garbage" }));
250+
render(
251+
<ArtifactPreview artifact={{
252+
id: "zip",
253+
name: "pkg.zip",
254+
mimeType: "text/markdown",
255+
url: "/pkg.zip",
256+
size: 2048,
257+
}} />,
258+
);
259+
expect(await screen.findByText("此类型文件可通过右上角下载查看。")).toBeInTheDocument();
260+
expect(screen.queryByText(/garbage/)).not.toBeInTheDocument();
261+
globalThis.fetch = originalFetch;
262+
});
263+
247264
test("previews an attached HTML file in the script-only sandbox", async () => {
248265
const user = userEvent.setup();
249266
const originalFetch = globalThis.fetch;

‎web/app/runs.js‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1598,12 +1598,13 @@ function openArtifactPreview({title,icon,details,url,action,download=false,loadi
15981598
}else modal.querySelector('.artifact-close').focus();
15991599
return artifactPreviewRequest.signal;
16001600
}
1601-
/** 页面内预览会整份读入并渲染正文,因此只预览不超过 5 MiB 的文本产物;二进制内容当作文本渲染会卡住页面。 */
1601+
/** 页面内预览会整份读入并渲染正文,超过 5 MiB 的产物只提供下载。 */
16021602
const ARTIFACT_PREVIEW_MAX_BYTES=5*1024*1024;
1603-
function artifactPreviewable(artifact){
1604-
if((artifact?.size||0)>ARTIFACT_PREVIEW_MAX_BYTES)return false;
1605-
const type=String(artifact?.mediaType||'').split(';')[0].trim().toLowerCase();
1606-
return !type||type.startsWith('text/')||/^application\/(json|xml|yaml|x-yaml|javascript|toml|x-sh)$/.test(type)||/\+(json|xml|yaml)$/.test(type);
1603+
/** 未声明类型的产物会登记为 Markdown,因此按正文判断二进制:含 NUL,或开头有大量无法解码的字符。 */
1604+
function artifactLooksBinary(content){
1605+
if(content.includes('\u0000'))return true;
1606+
const head=content.slice(0,65536);
1607+
return (head.match(/\uFFFD/g)||[]).length>head.length*0.1;
16071608
}
16081609
function artifactDownloadName(artifact){
16091610
return String(artifact?.path||'').split('/').pop()||artifact?.name||'artifact.txt';
@@ -1627,7 +1628,7 @@ async function previewArtifact(run,artifactId,opener){
16271628
url,action:'在新窗口打开 ↗',loading:'正在加载交付物…',opener,
16281629
});
16291630
try{
1630-
if(!artifactPreviewable(artifact)){
1631+
const renderDownloadOnly=()=>{
16311632
const sizeKB=Math.max(1,Math.ceil((artifact.size||0)/1024));
16321633
const size=sizeKB>=1024?`${(sizeKB/1024).toFixed(1)} MB`:`${sizeKB} KB`;
16331634
host.innerHTML=`
@@ -1644,12 +1645,13 @@ async function previewArtifact(run,artifactId,opener){
16441645
</div>
16451646
<div class="empty-properties"><b>此文件不在页面内预览</b><p>文件较大或为二进制内容,请下载后查看。</p></div>`;
16461647
host.querySelector('[data-download-artifact]').onclick=()=>downloadArtifactFile(url,artifact);
1647-
return;
1648-
}
1648+
};
1649+
if((artifact.size||0)>ARTIFACT_PREVIEW_MAX_BYTES){renderDownloadOnly();return}
16491650
const res=await fetch(url,{signal});
16501651
if(!res.ok)throw new Error(`HTTP ${res.status}`);
16511652
const content=await res.text();
16521653
if(signal.aborted)return;
1654+
if(artifactLooksBinary(content)){renderDownloadOnly();return}
16531655
const isMd=isMarkdownArtifact(artifact, content);
16541656
$('#artifactPreviewHeading .artifact-preview-icon').textContent=isMd?'MD':'{}';
16551657
let viewMode=isMd?'preview':'source';

‎webtest/tests/runs-actions.test.mjs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ test('run helpers merge streams and format timing, output, logs, telemetry, prev
2626
app.router.get('/api/workflows', app.evaluate('structuredClone(state.data.workflows)'));
2727
app.router.get('/api/agents', app.evaluate('structuredClone(state.data.agents)'));
2828
app.router.get('/api/runs/run-x/artifacts/art-1', '# Report\\n\\n```js\\nconsole.log("ok")\\n```');
29+
app.router.get('/api/runs/run-x/artifacts/art-zip', 'PK\u0003\u0004\u0000\u0000# not markdown');
30+
app.router.get('/api/runs/run-x/artifacts/art-ndjson', '{"id":1}\n');
2931
app.router.get('/api/runs/child-1', {
3032
id: 'child-1', status: 'waiting', workflowId: 'child-flow',
3133
workflowSnapshot: { id: 'child-flow', name: 'Child Flow', nodes: [{ id: 'approve', name: 'Approve' }] },
@@ -144,7 +146,9 @@ test('run helpers merge streams and format timing, output, logs, telemetry, prev
144146
app.evaluate(`
145147
state.activeRun={...state.activeRun,status:'failed',artifacts:[
146148
{id:'art-1',nodeId:'b',name:'report.md',path:'out/report.md',attempt:2,size:1200,sha256:'abcdef',mediaType:'text/markdown'},
147-
{id:'art-bin',nodeId:'b',name:'model',path:'out/model.bin',attempt:2,size:20971520,sha256:'fedcba',mediaType:'application/octet-stream'}]};
149+
{id:'art-bin',nodeId:'b',name:'model',path:'out/model.bin',attempt:2,size:20971520,sha256:'fedcba',mediaType:'application/octet-stream'},
150+
{id:'art-zip',nodeId:'b',name:'pkg',path:'out/pkg.zip',attempt:2,size:2048,sha256:'aa',mediaType:'text/markdown'},
151+
{id:'art-ndjson',nodeId:'b',name:'rows',path:'out/rows.ndjson',attempt:2,size:9,sha256:'bb',mediaType:'application/x-ndjson'}]};
148152
state.selectedRun='run-x';state.currentUser.codeBuddyApiKeyConfigured=true;
149153
const host=document.querySelector('#runDetail');host.dataset.runId='run-x';
150154
host.innerHTML='<div data-run-pane="eval"></div>';
@@ -200,6 +204,14 @@ test('run helpers merge streams and format timing, output, logs, telemetry, prev
200204
assert.match(app.document.querySelector('#artifactPreview').textContent, /不在页面内预览/);
201205
artifactModal.querySelector('[data-download-artifact]').click();
202206
assert.deepEqual(downloads.at(-1), ['/api/runs/run-x/artifacts/art-bin', 'model.bin']);
207+
artifactModal.close();
208+
await app.evaluate(`previewArtifact(state.activeRun,'art-zip')`);
209+
assert.match(app.document.querySelector('#artifactPreview').textContent, /不在页面内预览/);
210+
artifactModal.querySelector('[data-download-artifact]').click();
211+
assert.deepEqual(downloads.at(-1), ['/api/runs/run-x/artifacts/art-zip', 'pkg.zip']);
212+
artifactModal.close();
213+
await app.evaluate(`previewArtifact(state.activeRun,'art-ndjson')`);
214+
assert.match(app.document.querySelector('#artifactPreview .artifact-content').textContent, /"id":1/);
203215
app.window.HTMLAnchorElement.prototype.click = clickAnchor;
204216
artifactModal.close();
205217
app.evaluate(`toast('Outside artifact preview')`);

0 commit comments

Comments
 (0)