Skip to content

Commit bf76922

Browse files
feat(console-ai): an image or PDF attached in the AI chat is uploaded as the user and sent to the agent as a file part (#34459)
Part of #32749 — the console half of ruling A. The agent half (turning these file parts into model input, and putting the file into a record's file field) is cloud code and keeps the card open. Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:控制台「问 AI」聊天里附上的图片(PNG/JPEG/GIF/WebP)和 PDF,现在以当前用户身份上传到存储(不绑定任何记录),并作为文件部件随这一轮消息发给 agent,带上 `sys_file` id;输入框显示附件按钮和附件卡片。表格附件照旧在页面里解析。 - 为什么改:裁决 A(#32749):员工把发票照片发给自带 AI,不该再收到「只支持表格类附件,内容没有读取」;同一份上传以后由 agent 直接挂到记录的文件字段上,不用再选第二次。 - 风险与回滚:只动控制台聊天的发送路径和 `useObjectChat().sendMessage` 的一个可选参数;agent 端(cloud)还没读这些文件部件之前,模型只看到文件名和「已作为文件发送」的说明。回滚即 revert 本 PR。 - 先看:`ui/packages/app-shell/src/console/ai/chatAttachments.ts`(类型、10 MiB 上限、上传失败的处理);`AiChatPage.tsx` 的 `doSend`;`ui/packages/plugin-chatbot/src/useObjectChat.ts` 的 `sendMessage`。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx`,预期 5 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes - **Composer** (`AiChatPage`): the chat's `ChatbotEnhanced` now gets `enableFileUpload`, so the attach button and the attachment chips show. Before, a file pasted or dropped into the composer was attached with no chip, and there was no button to pick one. - **Send path** (`doSend` in `AiChatPage`, helpers in the new `chatAttachments.ts`): - spreadsheets (`.xlsx .xlsm .csv .tsv .txt`) keep the in-page parse and brief, unchanged; - an image (`image/png`, `image/jpeg`, `image/gif`, `image/webp`) or a PDF (`application/pdf`) of at most 10 MiB is uploaded through the console's ambient upload adapter (`useUpload()` from `@object-ui/fields`, which the console mounts with `createObjectStackUploadAdapter`), as the signed-in user, and completed without `attachTo`, so no record holds it. Each uploaded file becomes one file part on the user turn (shape below), and the turn's text names the files it sent; - any other file, a file over the cap, and a file whose upload failed is not sent; the turn's text names it and says why ("over the 10 MB cap", "type not supported", "upload failed", each "content not read"). The turn still sends. The old blanket "only spreadsheets are read; I did not read these files" line is gone; - a spreadsheet beside an image: the sheet is briefed and the image uploaded, in one turn. - **`@object-ui/plugin-chatbot`**: `useObjectChat().sendMessage(content, files?, fileParts?)` takes an optional third argument, `fileParts` (new exported type `ChatFilePart`, declared structurally so the package does not republish the pinned AI SDK type). The API mode passes them to the AI SDK's `sendMessage({ text, files })`, which puts them in the user message before the text part. Two-argument calls send exactly what they sent before (`{ text }`). The second argument, `files: File[]`, was never sent and still is not; its doc now says so. ## Seam for the agent half What the cloud agent receives, in the chat route's request body (`messages[]`, last `role: 'user'` message), per uploaded file: ```json { "type": "file", "mediaType": "image/png", "filename": "receipt.png", "url": "https://HOST/api/v1/storage/files/FILE_ID", "providerMetadata": { "objectstack": { "fileId": "FILE_ID" } } } ``` - **Where:** `parts` of the user message, before its `text` part (the AI SDK's order), one part per uploaded file, in attach order. `AiMessageSchema.parts` is `z.array(z.unknown())`, so no spec change. - **`fileId`:** `providerMetadata.objectstack.fileId`, the `sys_file` id. The AI SDK keeps `providerMetadata` on the part as sent, and the transport sends `messages` verbatim, so it reaches the route; the test reads it off the captured request body. - **`url`:** the storage service's stable download endpoint, `/api/v1/storage/files/FILE_ID` as the upload adapter answers it, made absolute against the page's location. Never a data URL. The endpoint is the governed download door (302 to a short-lived signed URL for a caller who may read the file), so a model provider cannot fetch it: the agent reads the bytes as the user, by `fileId`, and converts the part for its model. - **`mediaType`:** one of `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `application/pdf`. The browser's type, or, when the browser gives none, the one the extension names. - **The stored file:** `sys_file` row with `owner_id` = the user, `scope: 'user'` (the server default), `status: 'committed'` (the upload was completed, so the download door serves it and a later record write may name it), no owning record. It is "pending" only in the ruling's sense: no record has claimed it yet. A record write by the same user naming it in a file field claims it (the existing file-reference lifecycle); what binds it to "this user, this conversation" for the attach step is the agent half's, after #32686. - **Caps:** 10 MiB per image and per PDF. PDFs take the same 10 MiB as images: the ruling gives no PDF cap, the composer already refuses any file over 10 MiB before the send sees it (`maxFileSize` default), and one cap keeps the rule one sentence; a larger PDF still goes onto a record through its file field. No cap on the count per turn. - **Text:** the user text carries a line naming the files sent (`(用户附上了 N 个文件:NAMES — 已作为文件随本条消息发送。)`) and one line per not-sent group (over cap / unsupported type / upload failed, each naming the files and saying the content was not read). A model that cannot read images sees the names only — the ruling's attached condition (say so plainly, never invent a value from a file name) is the agent half's. ## Tests `ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx` mounts the real `AiChatPage` send path with the real `useChatConversation` and the real `useObjectChat` transport, a `fetch` stub capturing the chat POST, and a test upload adapter through the real `UploadProvider`: 1. an image and a PDF are uploaded, and the user message carries exactly two file parts with the URL and `providerMetadata.objectstack.fileId` above; 2. CONTROL: a spreadsheet is parsed (parser called once), nothing is uploaded, no file part; 3. a 10 MiB + 1 byte JPEG and a `.docx` are not uploaded and are named in the text as over the cap / unsupported; 4. one upload failing: it is named as failed, and the turn still sends the other file's part; 5. a spreadsheet beside an image: parsed once, uploaded once, one file part. <details><summary>Runs (head 2b95bb8 for the file list; test runs on the branch's code before the main merge, which touched only objectql)</summary> ``` vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx Tests 5 passed (5) · VERDICT command-exit 0 vitest run packages/plugin-chatbot/ packages/app-shell/src/console/ai/ Test Files 156 passed (156) · Tests 1362 passed (1362) · VERDICT command-exit 0 (before the 5th pin was added) pnpm --filter @object-ui/plugin-chatbot run type-check VERDICT command-exit 0 pnpm --filter @object-ui/app-shell run type-check VERDICT command-exit 0 (tsconfig.test.json includes src/**/*.test.tsx) eslint on the five changed ui files 0 errors (warnings all pre-existing) ``` </details> <details><summary>Ablation (each mutation landed on disk, tests read the source through the vitest alias, restored to HEAD)</summary> ``` A1 AiChatPage: sendMessage(text + chatAttachmentNotes(outcome), undefined, outcome.parts) -> sendMessage(text + chatAttachmentNotes(outcome)) ablation-replace: ok mutation landed: anchor 1 -> 0, blob 78062f0 -> 3ce0c5693378 × uploads an image and a PDF and sends one file part per file, carrying its sys_file id AssertionError: expected [] to deeply equal [ { type: 'file', …(4) }, …(1) ] × names a failed upload as not read, and still sends the turn with the file that did upload AssertionError: expected [] to deeply equal [ 'file-ok.png' ] Tests 2 failed | 2 passed (4) ablation-replace: ok restored: blob == HEAD (78062f0) and `git diff HEAD` is empty A2 useObjectChat: ? { text: trimmed, files: fileParts.map((part) => ({ ...part })) } -> ? { text: trimmed } ablation-replace: ok mutation landed: anchor 1 -> 0, blob 928647e -> 301ea3a70cce the same two tests fail with the same two assertions; Tests 2 failed | 2 passed (4) ablation-replace: ok restored: blob == HEAD (928647e) and `git diff HEAD` is empty ``` The control (spreadsheet) and the disclosure-only test stay green under both mutations, as they should: neither sends a file part. </details> ## Acceptance notes - The claim's file surface names `AiChatPage.tsx`, its tests and a storage-helper call site. This PR also edits `ui/packages/plugin-chatbot/src/useObjectChat.ts` (plus one barrel export): `useObjectChat().sendMessage` dropped every file it was handed, so no console-only change could put a part on the turn. The change is one optional argument; existing calls are byte-identical on the wire. - The changeset is in the root `.changeset/`, not `ui/.changeset/`: `ui/AGENTS.md` says the root config does not read `ui/.changeset/` and no new entries go there. - The attachment notes are Chinese whatever the conversation's language, like the spreadsheet brief and the line they replace; moving the whole attachment brief onto the conversation-language resolver (`outboundAgentText.ts`) is not done here. Follow-up: #34461. - No busy state while uploads run: the composer clears, and the user bubble appears when the uploads settle (seconds for a large photo). A second message sent meanwhile can reach the agent first. Follow-up: #34462 (introduced here). - The composer refuses a file over its `maxFileSize` (10 MiB) with only a `console.warn`; the send's own cap is the guard for any other entry. On main before this PR; follow-up: #34463. ## Verification - `node scripts/pm/dispatch-gates.mjs --ran`: 39 derived, 39 run, 0 NOT-MEASURED, every one exit 0 (a derived zero). - CI runs the rest (Lint UI, Type Check UI, Test UI, Build & E2E UI and the repo gates); its result is read at the final head. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (spec untouched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint on the changed files reports 0 errors (repo-wide `pnpm lint` is CI's). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the maintainer quick-read is Chinese by the repo's rule). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5obaLbqgzRUR9xXfft --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ea28882 commit bf76922

6 files changed

Lines changed: 519 additions & 18 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/console': patch
4+
'@object-ui/plugin-chatbot': patch
5+
---
6+
7+
feat(console-ai): an image or PDF attached in the AI chat is uploaded as the user and sent to the agent as a file part
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
The console's AI chat used to send only spreadsheet attachments (parsed in the page) and told the model that every other file "was not read". Now:
13+
14+
- The composer shows its attach button and the attachment chips, so a file can be picked, pasted or dropped and seen before it is sent.
15+
- An image (PNG, JPEG, GIF, WebP) or a PDF of at most 10 MiB is uploaded to storage as the signed-in user through the console's upload adapter (`POST /api/v1/storage/upload/presigned`, the bytes, then `POST /api/v1/storage/upload/complete` without `attachTo`), so it belongs to no record yet. The user turn carries one AI SDK file part per uploaded file: `{ type: 'file', mediaType, filename, url, providerMetadata: { objectstack: { fileId } } }`, where `url` is the stored file's address (`/api/v1/storage/files/{fileId}`, made absolute) and never an inline data URL, so the request and the stored conversation stay small. The turn's text names the files it sent.
16+
- A file over the cap, of another type, or whose upload failed is not sent, and the turn's text names it and says why, so the user and the agent both know its content was not read. The turn still sends.
17+
- A spreadsheet keeps the in-page parse, unchanged.
18+
19+
`@object-ui/plugin-chatbot`: `useObjectChat().sendMessage` takes a third, optional argument, `fileParts` (the new exported `ChatFilePart` type), which the API mode sends as the turn's file parts. Its second argument, `files`, is still not sent: upload the files first and pass the result as `fileParts`. Existing two-argument calls are unchanged.
20+
21+
Reading the files is the agent's side: an agent service that does not yet convert these parts for its model sees the file names in the text and the parts it does not read.

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ import { resolveOutboundAgentText, type OutboundAgentTextKey } from './outboundA
155155
import { resolveApiBase } from './resolveApiBase.js';
156156
import { AiUnavailable } from './AiUnavailable.js';
157157
import { recordWriteFormTarget } from '../../utils/recordFormAiDraft.js';
158+
import { useUpload } from '@object-ui/fields';
159+
import { isSpreadsheetAttachment, uploadChatAttachments, chatAttachmentNotes } from './chatAttachments.js';
158160

159161
/**
160162
* The app segment a record of `objectName` lives under: the object's owning
@@ -2428,21 +2430,28 @@ export function ChatPane({
24282430
// leave the page) and the agent is briefed with a compact structured block —
24292431
// headers + first sample rows + row count — appended to the user's text. The
24302432
// agent's solution-design skill takes it from there (match an object, offer
2431-
// missing fields, point at the object list's Import action). Non-spreadsheet
2432-
// attachments stay out of scope and are disclosed rather than dropped.
2433+
// missing fields, point at the object list's Import action).
2434+
//
2435+
// Images and PDFs (objectstack#32749, ruling A) are uploaded to storage as
2436+
// the signed-in user, bound to no record, and ride the turn as AI SDK file
2437+
// parts carrying their `sys_file` id (`chatAttachments.ts`). Any other
2438+
// attachment, and one over the cap or whose upload failed, is named in the
2439+
// turn's text as not read, never dropped silently.
2440+
const { upload } = useUpload();
2441+
const sendNonSheetAttachments = useCallback(
2442+
async (text: string, nonSheets: File[]): Promise<void> => {
2443+
const outcome = await uploadChatAttachments(nonSheets, upload, window.location.href);
2444+
sendMessage(text + chatAttachmentNotes(outcome), undefined, outcome.parts);
2445+
},
2446+
[upload, sendMessage],
2447+
);
24332448
const doSend = useCallback(
24342449
(content: string, files?: File[]) => {
24352450
resetSuppression();
2436-
const sheets = (files ?? []).filter((f) => /\.(xlsx|xlsm|csv|tsv|txt)$/i.test(f.name));
2451+
const sheets = (files ?? []).filter(isSpreadsheetAttachment);
24372452
if (!sheets.length) {
24382453
if (files?.length) {
2439-
// Honest disclosure beats a silent drop — the agent cannot read these.
2440-
sendMessage(
2441-
`${content}\n\n(用户上传了 ${files.length} 个附件:${files
2442-
.map((f) => f.name)
2443-
.join('、')} — 当前仅支持读取表格类附件(Excel/CSV),这些文件的内容我没有读取。)`,
2444-
);
2445-
onSent(content);
2454+
void sendNonSheetAttachments(content, files).then(() => onSent(content));
24462455
return;
24472456
}
24482457
sendMessage(content);
@@ -2474,13 +2483,13 @@ export function ChatPane({
24742483
}
24752484
}
24762485
if (sheets.length > 2) merged += `\n\n(另有 ${sheets.length - 2} 个表格附件未读取 — 一次最多读取 2 个。)`;
2477-
const nonSheets = (files ?? []).length - sheets.length;
2478-
if (nonSheets > 0) merged += `\n\n(另有 ${nonSheets} 个非表格附件,内容未读取。)`;
2479-
sendMessage(merged);
2486+
const nonSheets = (files ?? []).filter((f) => !isSpreadsheetAttachment(f));
2487+
if (nonSheets.length > 0) await sendNonSheetAttachments(merged, nonSheets);
2488+
else sendMessage(merged);
24802489
onSent(merged);
24812490
})();
24822491
},
2483-
[resetSuppression, sendMessage, onSent],
2492+
[resetSuppression, sendMessage, onSent, sendNonSheetAttachments, setPendingSheet],
24842493
);
24852494

24862495
// Guards the empty-state first send against the conversation-id remount race:
@@ -3169,6 +3178,10 @@ export function ChatPane({
31693178
allowanceUsedFraction={allowanceUsedFraction}
31703179
suggestions={suggestions}
31713180
onSendMessage={handleSend}
3181+
// objectstack#32749 — the attach button and the attachment chips: the
3182+
// send reads spreadsheets, images and PDFs (see `doSend`), and a file
3183+
// pasted or dropped without them was attached unseen.
3184+
enableFileUpload
31723185
onClear={clear}
31733186
hideClearBar
31743187
onStop={isLoading ? stop : undefined}
Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#32749 (ruling A, console half) — an image or PDF attached in the
5+
* AI chat is uploaded as the signed-in user and rides the user turn as an AI
6+
* SDK file part carrying its `sys_file` id; a spreadsheet keeps the in-page
7+
* parse; any file not sent is named in the turn as not read.
8+
*
9+
* ## Real subjects
10+
*
11+
* The full-page chat (`AiChatPage` at `/ai/build`) with the REAL `ChatPane`
12+
* send path, the REAL `useChatConversation` and the REAL `useObjectChat`
13+
* transport. What is pinned is the user message inside the JSON body of the
14+
* POST to the agent's chat route (captured off a `fetch` stub) and the calls
15+
* the ambient upload adapter received. The stand-ins: the agent catalog,
16+
* `ChatbotEnhanced` (a recorder exposing the composer's send), the upload
17+
* adapter (mounted through the real `UploadProvider`) and the spreadsheet
18+
* parser.
19+
*
20+
* Pins:
21+
* - an image and a PDF are uploaded, and the turn carries one file part per
22+
* file, with the stored file's URL and its id under
23+
* `providerMetadata.objectstack.fileId`;
24+
* - CONTROL: a spreadsheet is parsed in the page, uploaded never, and the
25+
* turn carries no file part;
26+
* - an over-cap image and an unsupported type are not uploaded and are named
27+
* in the turn's text;
28+
* - a failed upload is named in the turn's text, and the turn still sends
29+
* the file that did upload;
30+
* - a spreadsheet beside an image: the sheet is parsed, the image uploaded,
31+
* and one turn carries both.
32+
*/
33+
34+
import '@testing-library/jest-dom/vitest';
35+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
36+
import { act, cleanup, render, waitFor } from '@testing-library/react';
37+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
38+
import React from 'react';
39+
import type { UploadAdapter } from '@object-ui/types';
40+
41+
interface SentPart {
42+
type: string;
43+
text?: string;
44+
mediaType?: string;
45+
filename?: string;
46+
url?: string;
47+
providerMetadata?: { objectstack?: { fileId?: string } };
48+
}
49+
interface SentBody {
50+
messages?: Array<{ role: string; parts: SentPart[] }>;
51+
}
52+
53+
const state = {
54+
pane: undefined as { onSendMessage?: (text: string, files?: File[]) => void } | undefined,
55+
sent: [] as SentBody[],
56+
uploads: [] as string[],
57+
minted: 0,
58+
};
59+
60+
const parseSpreadsheetFile = vi.fn(async (_file: File) => [
61+
['merchant', 'amount'],
62+
['Taxi', '42'],
63+
]);
64+
65+
vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({
66+
...(await importOriginal<Record<string, unknown>>()),
67+
parseSpreadsheetFile: (file: File) => parseSpreadsheetFile(file),
68+
}));
69+
vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
70+
const actual = await importOriginal<Record<string, unknown>>();
71+
return {
72+
...actual,
73+
useAiModels: () => ({ models: [], defaultModelId: undefined }),
74+
useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }),
75+
ChatbotEnhanced: (props: typeof state.pane) => {
76+
state.pane = props;
77+
return <div data-testid="pane" />;
78+
},
79+
};
80+
});
81+
vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
82+
...(await importOriginal<typeof import('@object-ui/plugin-chatbot/core')>()),
83+
useAgents: () => ({
84+
agents: [{ name: 'build', label: 'Build', capabilities: ['build'] }],
85+
isLoading: false,
86+
loading: false,
87+
error: undefined,
88+
refetch: vi.fn(),
89+
}),
90+
}));
91+
vi.mock('@object-ui/auth', async (importOriginal) => ({
92+
...(await importOriginal<Record<string, unknown>>()),
93+
useAuth: () => ({ user: { id: 'u1' } }),
94+
}));
95+
vi.mock('../../../providers/MetadataProvider', async (importOriginal) => ({
96+
...(await importOriginal<Record<string, unknown>>()),
97+
useMetadata: () => ({ apps: [] }),
98+
}));
99+
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({
100+
...(await importOriginal<Record<string, unknown>>()),
101+
useAdapter: () => null,
102+
}));
103+
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true }));
104+
vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null }));
105+
vi.mock('../LiveCanvas', () => ({ LiveCanvas: () => null }));
106+
vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null }));
107+
108+
import { I18nProvider } from '@object-ui/i18n';
109+
import { UploadProvider } from '@object-ui/fields';
110+
import { AiChatPage } from '../AiChatPage';
111+
112+
window.matchMedia = ((query: string) => ({
113+
matches: false,
114+
media: query,
115+
onchange: null,
116+
addEventListener: () => {},
117+
removeEventListener: () => {},
118+
addListener: () => {},
119+
removeListener: () => {},
120+
dispatchEvent: () => false,
121+
})) as unknown as typeof window.matchMedia;
122+
123+
/** The storage adapter: answers a stored file per upload, and fails `broken.png`. */
124+
const uploadAdapter: UploadAdapter = {
125+
name: 'test-storage',
126+
async upload(file) {
127+
const name = (file as File).name;
128+
state.uploads.push(name);
129+
if (name === 'broken.png') throw new Error('Upload completion failed (500)');
130+
const fileId = `file-${name}`;
131+
return {
132+
url: `/api/v1/storage/files/${fileId}`,
133+
name,
134+
size: file.size,
135+
mimeType: file.type,
136+
meta: { fileId },
137+
};
138+
},
139+
};
140+
141+
function dataStreamResponse(): Response {
142+
return new Response('data: {"type":"start"}\n\ndata: {"type":"finish"}\n\ndata: [DONE]\n\n', {
143+
status: 200,
144+
headers: { 'Content-Type': 'text/event-stream', 'x-vercel-ai-ui-message-stream': 'v1' },
145+
});
146+
}
147+
148+
function installFetch(): void {
149+
vi.stubGlobal(
150+
'fetch',
151+
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
152+
const url = String(input);
153+
const method = init?.method ?? 'GET';
154+
const json = (body: unknown) =>
155+
new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });
156+
if (/\/agents\/[^/]+\/chat$/.test(url) && method === 'POST') {
157+
state.sent.push(JSON.parse(String(init?.body ?? '{}')));
158+
return dataStreamResponse();
159+
}
160+
if (/\/conversations$/.test(url) && method === 'POST') {
161+
state.minted += 1;
162+
return json({ id: `conv-${state.minted}`, messages: [] });
163+
}
164+
const one = /\/conversations\/([^/?]+)$/.exec(url);
165+
if (one && method === 'GET') return json({ id: decodeURIComponent(one[1]), messages: [] });
166+
return json({ success: true, data: [] });
167+
}),
168+
);
169+
}
170+
171+
function mountPage(): void {
172+
render(
173+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
174+
<UploadProvider adapter={uploadAdapter}>
175+
<MemoryRouter initialEntries={['/ai/build']}>
176+
<Routes>
177+
<Route path="/ai/:agent/:conversationId" element={<AiChatPage />} />
178+
<Route path="/ai/:agent" element={<AiChatPage />} />
179+
</Routes>
180+
</MemoryRouter>
181+
</UploadProvider>
182+
</I18nProvider>,
183+
);
184+
}
185+
186+
/** Sends one turn through the composer, and returns the user message that left. */
187+
async function send(text: string, files: File[]): Promise<{ parts: SentPart[]; text: string; files: SentPart[] }> {
188+
mountPage();
189+
await waitFor(() => expect(state.pane?.onSendMessage).toBeTypeOf('function'), { timeout: 4000 });
190+
await act(async () => {
191+
state.pane!.onSendMessage!(text, files);
192+
});
193+
await waitFor(() => expect(state.sent.length).toBe(1), { timeout: 4000 });
194+
const user = [...(state.sent[0].messages ?? [])].reverse().find((m) => m.role === 'user');
195+
const parts = user?.parts ?? [];
196+
return {
197+
parts,
198+
text: parts.filter((p) => p.type === 'text').map((p) => p.text ?? '').join(''),
199+
files: parts.filter((p) => p.type === 'file'),
200+
};
201+
}
202+
203+
function file(name: string, type: string, size?: number): File {
204+
const f = new File(['bytes'], name, { type });
205+
if (size !== undefined) Object.defineProperty(f, 'size', { value: size });
206+
return f;
207+
}
208+
209+
const storedUrl = (fileId: string) => new URL(`/api/v1/storage/files/${fileId}`, window.location.href).href;
210+
211+
beforeEach(() => {
212+
state.pane = undefined;
213+
state.sent = [];
214+
state.uploads = [];
215+
state.minted = 0;
216+
parseSpreadsheetFile.mockClear();
217+
window.localStorage.clear();
218+
window.sessionStorage.clear();
219+
installFetch();
220+
});
221+
222+
afterEach(() => {
223+
cleanup();
224+
vi.unstubAllGlobals();
225+
});
226+
227+
describe('AiChatPage — image and PDF attachments ride the turn as stored file parts (objectstack#32749)', () => {
228+
it('uploads an image and a PDF and sends one file part per file, carrying its sys_file id', async () => {
229+
const turn = await send('Fill a claim from these', [
230+
file('receipt.png', 'image/png'),
231+
file('invoice.pdf', 'application/pdf'),
232+
]);
233+
234+
expect(state.uploads).toEqual(['receipt.png', 'invoice.pdf']);
235+
expect(turn.files).toEqual([
236+
{
237+
type: 'file',
238+
mediaType: 'image/png',
239+
filename: 'receipt.png',
240+
url: storedUrl('file-receipt.png'),
241+
providerMetadata: { objectstack: { fileId: 'file-receipt.png' } },
242+
},
243+
{
244+
type: 'file',
245+
mediaType: 'application/pdf',
246+
filename: 'invoice.pdf',
247+
url: storedUrl('file-invoice.pdf'),
248+
providerMetadata: { objectstack: { fileId: 'file-invoice.pdf' } },
249+
},
250+
]);
251+
expect(turn.text).toContain('Fill a claim from these');
252+
expect(turn.text).toContain('receipt.png、invoice.pdf');
253+
expect(turn.text).not.toContain('未读取');
254+
expect(parseSpreadsheetFile).not.toHaveBeenCalled();
255+
});
256+
257+
it('CONTROL: a spreadsheet is parsed in the page, never uploaded, and sends no file part', async () => {
258+
const turn = await send('Build an app from this', [file('claims.csv', 'text/csv')]);
259+
260+
expect(parseSpreadsheetFile).toHaveBeenCalledTimes(1);
261+
expect(state.uploads).toEqual([]);
262+
expect(turn.files).toEqual([]);
263+
expect(turn.text).toContain('[附件表格 claims.csv');
264+
});
265+
266+
it('names an over-cap image and an unsupported type as not read, and uploads neither', async () => {
267+
const turn = await send('Here', [
268+
file('huge.jpg', 'image/jpeg', 10 * 1024 * 1024 + 1),
269+
file('notes.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
270+
]);
271+
272+
expect(state.uploads).toEqual([]);
273+
expect(turn.files).toEqual([]);
274+
expect(turn.text).toMatch(/超过 10 MB 上限,未上传,内容未读取:huge\.jpg/);
275+
expect(turn.text).toMatch(/类型暂不支持读取,未上传,内容未读取:notes\.docx/);
276+
});
277+
278+
it('names a failed upload as not read, and still sends the turn with the file that did upload', async () => {
279+
const turn = await send('Two photos', [file('broken.png', 'image/png'), file('ok.png', 'image/png')]);
280+
281+
expect(state.uploads).toEqual(['broken.png', 'ok.png']);
282+
expect(turn.files.map((p) => p.providerMetadata?.objectstack?.fileId)).toEqual(['file-ok.png']);
283+
expect(turn.text).toMatch(/上传失败,内容未读取:broken\.png/);
284+
});
285+
286+
it('parses a spreadsheet and uploads an image attached beside it, in one turn', async () => {
287+
const turn = await send('Claims and a receipt', [file('claims.csv', 'text/csv'), file('receipt.jpg', 'image/jpeg')]);
288+
289+
expect(parseSpreadsheetFile).toHaveBeenCalledTimes(1);
290+
expect(state.uploads).toEqual(['receipt.jpg']);
291+
expect(turn.files.map((p) => p.providerMetadata?.objectstack?.fileId)).toEqual(['file-receipt.jpg']);
292+
expect(turn.text).toContain('[附件表格 claims.csv');
293+
});
294+
});

0 commit comments

Comments
 (0)