Skip to content

Commit c37a3bf

Browse files
authored
feat(chat): accept bounded UTF-8 document attachments (#7740)
1 parent 0ad08b1 commit c37a3bf

28 files changed

Lines changed: 405 additions & 50 deletions

‎.github/workflows/python-tests.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,15 @@ jobs:
484484
if-no-files-found: error
485485
retention-days: 3
486486

487+
- name: Upload text document visual evidence
488+
if: always() && hashFiles('output/playwright/personal-workspace/document-*.png') != ''
489+
uses: actions/upload-artifact@v7
490+
with:
491+
name: text-document-evidence-${{ matrix.shard }}
492+
path: output/playwright/personal-workspace/document-*.png
493+
if-no-files-found: error
494+
retention-days: 14
495+
487496
dashboard-acceptance:
488497
needs: [changes, dashboard-browser]
489498
if: needs.changes.outputs.core_tests == 'true' && !cancelled() && needs.dashboard-browser.result == 'success'

‎apps/presentation/dashboard/src/data/chat.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -931,6 +931,7 @@ export type ChatReplyContext = {
931931
};
932932
};
933933

934+
// Existing attachment wire shape; MIME distinguishes images and UTF-8 documents.
934935
export type ChatImageAttachment = {
935936
data_url: string;
936937
id: string;

‎apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {DocumentAttachment, isTextDocument} from "./document-attachment";
12
import { MessageActivity } from "./message-activity";
23
import { GoalDraftCard } from "./goal-draft-card";
34
import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js";
@@ -196,7 +197,7 @@ export function ChannelTimeline({
196197
{item.message.role !== "user" ? <span className="personal-message-avatar"><Bot size={17} /></span> : null}
197198
<div>
198199
<header><strong>{item.message.role === "user" ? item.message.agentLabel ?? t("common.you") : item.message.agentLabel ?? t("header.manager")}</strong>{item.message.time ? <time>{item.message.time}</time> : null}</header>
199-
{item.message.attachments?.length ? <div className="personal-message-images">{item.message.attachments.map((attachment) => <img alt={attachment.name} key={attachment.id} src={attachment.dataUrl} />)}</div> : null}
200+
{item.message.attachments?.length ? <div className="personal-message-images">{item.message.attachments.map((attachment) => isTextDocument(attachment.mimeType) ? <DocumentAttachment key={attachment.id} {...attachment} zh={locale === "zh-CN"}/> : <img alt={attachment.name} key={attachment.id} src={attachment.dataUrl} />)}</div> : null}
200201
{item.message.role === "user" ? <p>{item.message.text}</p> : item.message.text ? <HistoricalMessageText text={item.message.text}
201202
initiallyCollapsed={Boolean(historical?.has(messageKey(item.message)))}
202203
focused={Boolean(messageFocus && messageKey(item.message) === focusKey)} zh={locale === "zh-CN"} onRead={onReadMessage}/> : null}

‎apps/presentation/dashboard/src/features/personal-workspace/conversation-requests.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {DocumentAttachment, isTextDocument} from "./document-attachment";
12
import {useEffect, useRef, useState} from "react";
23
import {ChevronRight, CircleAlert, ListChecks, RefreshCw, X} from "lucide-react";
34
import {fetchChatSession, fetchChatSessions, requestJson, type ChatImageAttachment, type ChatVisibleMessage, type ChatReplyContext} from "../../data/chat";
@@ -132,6 +133,7 @@ function requestStage(row: ConversationRequest, zh: boolean) {
132133

133134
function OriginalImage({attachment, zh}: {attachment: ChatImageAttachment; zh: boolean}) {
134135
const [failed, setFailed] = useState(false);
136+
if (isTextDocument(attachment.mime_type)) return <DocumentAttachment dataUrl={attachment.data_url} name={attachment.name} size={attachment.size} zh={zh}/>;
135137
return failed ? <p role="status">{zh ? "图片无法显示:" : "Image unavailable: "}{attachment.name}</p>
136138
: <img src={attachment.data_url} alt={attachment.name} onError={() => setFailed(true)}/>;
137139
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import {useState} from "react";
2+
3+
export const isTextDocument = (mime: string) => mime === "text/plain" || mime === "text/markdown";
4+
5+
/** Render source as inert text; downloading preserves the original UTF-8 bytes. */
6+
export function DocumentAttachment({dataUrl, name, size, zh}: {dataUrl: string; name: string; size: number; zh: boolean}) {
7+
const [open, setOpen] = useState(false);
8+
let text: string;
9+
try {
10+
if (!/^data:text\/(plain|markdown);base64,[A-Za-z0-9+/=]*$/.test(dataUrl)) throw new Error("Invalid source");
11+
text = new TextDecoder("utf-8", {fatal: true, ignoreBOM: true}).decode(Uint8Array.from(atob(dataUrl.split(",")[1]), c => c.charCodeAt(0)));
12+
} catch {
13+
return <p role="alert">{zh ? "文件无法读取:" : "Document unavailable: "}{name}</p>;
14+
}
15+
return <div className="personal-document-attachment">
16+
<button type="button" aria-expanded={open} onClick={() => setOpen(value => !value)}>{name} · {size.toLocaleString()} B</button>
17+
<a href={dataUrl} download={name}>{zh ? "下载原文" : "Download source"}</a>
18+
{open ? <pre tabIndex={0} aria-label={name}>{text}</pre> : null}
19+
</div>;
20+
}

‎apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -197,11 +197,11 @@ const en = {
197197
"common.task": "Task",
198198
"common.you": "You",
199199
"common.waiting": "Waiting",
200-
"composer.addImage": "Add image",
200+
"composer.addImage": "Add attachment",
201201
"composer.agentProgress": "Ask Agent for a progress report",
202202
"composer.blockers": "Ask what blocks",
203203
"composer.agentProgressPrompt": "Give me a progress report for this Goal: completed, running, blocked, and next steps.",
204-
"composer.attachImageHint": "Choose, paste, or drag an image",
204+
"composer.attachImageHint": "Choose images or UTF-8 .md / .txt (local managed Codex; 64KB message limit)",
205205
"composer.createGoal": "Create Goal",
206206
"composer.createGoalHint": "Configure and review a new Goal",
207207
"composer.evidence": "Check what is proven",
@@ -214,15 +214,15 @@ const en = {
214214
"masthead.completeTitle": "Read the complete Goal",
215215
"composer.goalPrompt": "Ask about progress, or suggest a change…",
216216
"composer.goalPlaceholder": "Ask or guide {goal}…",
217-
"composer.imageAnalysisPrompt": "Analyze these images in the context of the current Goal and tell me the next step.",
218-
"composer.imageCountError": "You can add up to {count} images.",
219-
"composer.imagePicker": "Image file picker",
217+
"composer.imageAnalysisPrompt": "Read these attachments in the context of the current Goal and tell me the next step.",
218+
"composer.imageCountError": "You can add up to {count} attachments.",
219+
"composer.imagePicker": "Attachment file picker",
220220
"composer.imageReadError": "Could not read image {name}.",
221221
"composer.imageReadGenericError": "Could not read the image.",
222222
"composer.imageSizeError": "Each image must be {size} MB or smaller.",
223223
"composer.imageTotalSizeError": "Images must total {size} MB or less.",
224-
"composer.imageTypeError": "PNG, JPEG, WebP, and GIF images are supported.",
225-
"composer.imagesPending": "Images to send",
224+
"composer.imageTypeError": "Choose PNG, JPEG, WebP, GIF, or UTF-8 .md / .txt documents.",
225+
"composer.imagesPending": "Attachments to send",
226226
"composer.managerMessageHint": "Your message goes to the LoopX Manager across Goals for global questions or Goal creation.",
227227
"composer.managerPlaceholder": "Ask the LoopX Manager, or describe a new Goal…",
228228
"composer.monitor": "Configure scheduled check",
@@ -242,7 +242,7 @@ const en = {
242242
"composer.sendMessage": "Send a message to LoopX",
243243
"composer.sendMessageHint": "Send message",
244244
"composer.turnRunning": "A turn is in progress. Adjust or interrupt it from the reply, then send.",
245-
"composer.sentImageAlt": "Remove image {name}",
245+
"composer.sentImageAlt": "Remove attachment {name}",
246246
"conversation.agentPending": "Working…",
247247
"conversation.close": "Close conversation receipt",
248248
"conversation.convertHint": "Turn the Agent’s latest reply into a Task draft",
@@ -1858,11 +1858,11 @@ const zhCN: Record<WorkspaceMessageKey, string> = {
18581858
"common.task": "Task",
18591859
"common.you": "你",
18601860
"common.waiting": "等待中",
1861-
"composer.addImage": "添加图片",
1861+
"composer.addImage": "添加附件",
18621862
"composer.agentProgress": "向 Agent 获取进度报告",
18631863
"composer.agentProgressPrompt": "请给我一份当前 Goal 的进度报告:已完成、执行中、阻塞和下一步。",
18641864
"composer.blockers": "看阻塞",
1865-
"composer.attachImageHint": "选择、粘贴或拖入图片",
1865+
"composer.attachImageHint": "选择图片或 UTF-8 .md / .txt(文本限本地托管 Codex,消息共用 64KB)",
18661866
"composer.evidence": "查证据",
18671867
"composer.createGoal": "创建新 Goal",
18681868
"composer.createGoalHint": "填写 Goal 配置,检查后再创建",
@@ -1875,15 +1875,15 @@ const zhCN: Record<WorkspaceMessageKey, string> = {
18751875
"masthead.completeTitle": "查看完整 Goal",
18761876
"composer.goalPrompt": "询问进展,或提出调整…",
18771877
"composer.goalPlaceholder": "询问或纠偏 {goal}…",
1878-
"composer.imageAnalysisPrompt": "请结合这些图片分析当前 Goal,并告诉我下一步。",
1879-
"composer.imageCountError": "最多添加 {count} 张图片。",
1880-
"composer.imagePicker": "图片文件选择器",
1878+
"composer.imageAnalysisPrompt": "请结合这些附件分析当前 Goal,并告诉我下一步。",
1879+
"composer.imageCountError": "最多添加 {count} 个附件。",
1880+
"composer.imagePicker": "附件文件选择器",
18811881
"composer.imageReadError": "无法读取图片 {name}",
18821882
"composer.imageReadGenericError": "图片读取失败。",
18831883
"composer.imageSizeError": "单张图片不能超过 {size}MB。",
18841884
"composer.imageTotalSizeError": "图片总大小不能超过 {size}MB。",
1885-
"composer.imageTypeError": "支持 PNG、JPEG、WebP 和 GIF 图片。",
1886-
"composer.imagesPending": "待发送图片",
1885+
"composer.imageTypeError": "支持 PNG、JPEG、WebP、GIF 图片和 UTF-8 .md / .txt 文本文件。",
1886+
"composer.imagesPending": "待发送附件",
18871887
"composer.managerMessageHint": "你的消息由 LoopX 管家跨 Goal 接收,支持全局询问与创建 Goal",
18881888
"composer.managerPlaceholder": "问问 LoopX 管家,或描述一个新 Goal…",
18891889
"composer.monitor": "配置定时检查",
@@ -1903,7 +1903,7 @@ const zhCN: Record<WorkspaceMessageKey, string> = {
19031903
"composer.sendMessage": "向 LoopX 发送消息",
19041904
"composer.sendMessageHint": "发送消息",
19051905
"composer.turnRunning": "本轮回答进行中。可在回答里调整或中断本轮,结束后再发送。",
1906-
"composer.sentImageAlt": "移除图片 {name}",
1906+
"composer.sentImageAlt": "移除附件 {name}",
19071907
"conversation.agentPending": "正在整理…",
19081908
"conversation.close": "关闭对话回执",
19091909
"conversation.convertHint": "将 Agent 最新回复转为 Task 草稿",

‎apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ assert.match(timeline, /t\("timeline\.waitingConfirmation"\)/, "Historical gated
177177
assert.match(timeline, /gatedItems\.length/, "The compact Gate summary exposes the pending count");
178178
assert.match(timeline, /Boolean\(item\.run\.sessionId\)/, "Running count requires a discovered execution Session");
179179
assert.match(timeline, /Boolean\(item\.run\.canInterrupt\)/, "Running count requires an active interruptible turn");
180-
assert.match(page, /accept="image\/png,image\/jpeg,image\/webp,image\/gif"/, "Composer accepts bounded image types");
180+
assert.match(page, /accept="image\/png,image\/jpeg,image\/webp,image\/gif,\.md,\.txt"/, "Composer accepts bounded image types");
181181
assert.match(page, /imageInputRef\.current\?\.click\(\)/, "Attachment button explicitly opens the native file chooser");
182182
assert.match(page, /onDrop=\{\(event\)/, "Composer accepts dragged image files");
183183
assert.match(page, /onPaste=\{[^}]*handleComposerPaste/s, "Composer accepts pasted clipboard images");

‎apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ export type WorkspaceReturnDelivery = {
424424
request_revision?: number | null;
425425
};
426426

427+
// Existing attachment wire shape; MIME distinguishes images and UTF-8 documents.
427428
export type WorkspaceImageAttachment = {
428429
dataUrl: string;
429430
id: string;

‎apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {DocumentAttachment, isTextDocument} from "./document-attachment";
12
import {AlertCircle, Bot, CalendarClock, CircleHelp, FileText, ListPlus, MessageCircleQuestion, Paperclip, Plus, RefreshCw, Send, X} from "lucide-react";
23
import {ContextHelp} from "./context-help";
34
import {readSettingsRoute, writeSettingsRoute} from "./workspace-settings-route";
@@ -903,13 +904,22 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate)
903904
}
904905

905906
const acceptedImageTypes = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
907+
const documentMime = (file: File) => /\.md$/i.test(file.name) ? "text/markdown" : /\.txt$/i.test(file.name) ? "text/plain" : null;
906908
const maxImageAttachmentBytes = 5 * 1024 * 1024;
907909
const maxImageAttachmentCount = 4;
908910
// Project refs are alphanumeric, so this value can never name a workspace.
909911
const stewardScopeValue = "@steward";
910912
const maxImageAttachmentTotalBytes = 12 * 1024 * 1024;
911913

912-
function readImageAttachment(file: File, t: WorkspaceTranslate): Promise<WorkspaceImageAttachment> {
914+
async function readImageAttachment(file: File, t: WorkspaceTranslate): Promise<WorkspaceImageAttachment> {
915+
const mime = documentMime(file);
916+
if (mime) {
917+
const bytes = new Uint8Array(await file.arrayBuffer());
918+
const text = new TextDecoder("utf-8", {fatal: true, ignoreBOM: true}).decode(bytes);
919+
if (text.includes("\0")) throw new Error("UTF-8 text required; binary files are not supported.");
920+
const dataUrl = `data:${mime};base64,${btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join(""))}`;
921+
return {dataUrl, id: crypto.randomUUID(), mimeType: mime, name: file.name, size: bytes.length};
922+
}
913923
return new Promise((resolve, reject) => {
914924
const reader = new FileReader();
915925
reader.onerror = () => reject(new Error(t("composer.imageReadError", { name: file.name })));
@@ -2455,7 +2465,7 @@ export function PersonalWorkspacePage({
24552465
const queue = retry?.delivery === "queue" || (!retry && intent === "send" && Boolean(queueTurnId));
24562466
if (queue && conversationSessionId && callbacks.onQueueConversationTurn) {
24572467
if (retry && JSON.stringify(pendingImages) !== JSON.stringify(retry.attachments ?? [])) {
2458-
setImageAttachmentError(locale === "zh-CN" ? "待确认消息的图片不能替换;原请求与当前图片已保留。" : "Unconfirmed images cannot be replaced. Original request and current images retained.");
2468+
setImageAttachmentError(locale === "zh-CN" ? "待确认消息的附件不能替换;原请求与当前附件已保留。" : "Unconfirmed attachments cannot be replaced. Original request and current attachments retained.");
24592469
return;
24602470
}
24612471
const request = retry ?? { sessionId: conversationSessionId, turnId: queueTurnId!, text: message,
@@ -2483,7 +2493,7 @@ export function PersonalWorkspacePage({
24832493
}
24842494
if ((retry || (intent === "steer" && steeringTurnId)) && conversationSessionId && callbacks.onSteerConversationTurn) {
24852495
if (pendingImages.length) {
2486-
setImageAttachmentError(locale === "zh-CN" ? "本轮追加指令暂不支持图片,图片和草稿已保留。" : "This turn accepts text instructions only. Images and draft retained.");
2496+
setImageAttachmentError(locale === "zh-CN" ? "本轮追加指令暂不支持附件,附件和草稿已保留。" : "This turn accepts text instructions only. Attachments and draft retained.");
24872497
return;
24882498
}
24892499
const request = retry ?? { sessionId: conversationSessionId, turnId: steeringTurnId!, text: message, id: crypto.randomUUID() };
@@ -2567,8 +2577,12 @@ export function PersonalWorkspacePage({
25672577
if (!files?.length) return;
25682578
const available = maxImageAttachmentCount - imageAttachments.length;
25692579
const selected = Array.from(files).slice(0, Math.max(0, available));
2570-
const invalid = selected.find((file) => !acceptedImageTypes.has(file.type));
2580+
const invalid = selected.find((file) => !acceptedImageTypes.has(file.type) && !documentMime(file));
25712581
const oversized = selected.find((file) => file.size > maxImageAttachmentBytes);
2582+
if (selected.some(file => documentMime(file) && file.size > 48_000)) {
2583+
setImageAttachmentError(locale === "zh-CN" ? "文本文件和消息共用 64KB 限额,请缩小文件。" : "Documents and message share a 64KB limit. Choose a smaller file.");
2584+
return;
2585+
}
25722586
if (available <= 0) {
25732587
setImageAttachmentError(t("composer.imageCountError", { count: maxImageAttachmentCount }));
25742588
return;
@@ -2587,6 +2601,13 @@ export function PersonalWorkspacePage({
25872601
}
25882602
try {
25892603
const loaded = await Promise.all(selected.map((file) => readImageAttachment(file, t)));
2604+
const envelope = {message: composer, attachments: [...imageAttachments, ...loaded].map(file => ({
2605+
name: file.name, size: file.size, id: file.id, mime_type: file.mimeType,
2606+
...(isTextDocument(file.mimeType) ? {data_url: file.dataUrl} : {}),
2607+
}))};
2608+
if (new TextEncoder().encode(JSON.stringify(envelope)).length > 63_000) {
2609+
throw new Error(locale === "zh-CN" ? "文本文件和消息共用 64KB 限额,请缩小文件。" : "Documents and message share a 64KB limit. Choose a smaller file.");
2610+
}
25902611
setImageAttachments((current) => [...current, ...loaded].slice(0, maxImageAttachmentCount));
25912612
setImageAttachmentError(files.length > selected.length ? t("composer.imageCountError", { count: maxImageAttachmentCount }) : null);
25922613
} catch (error) {
@@ -3144,7 +3165,7 @@ export function PersonalWorkspacePage({
31443165
}} /> : null}
31453166
{imageAttachments.length ? <div className="personal-composer-images" aria-label={t("composer.imagesPending")}>{imageAttachments.map((attachment) => (
31463167
<figure key={attachment.id}>
3147-
<img alt={attachment.name} src={attachment.dataUrl} />
3168+
<>{isTextDocument(attachment.mimeType) ? <DocumentAttachment {...attachment} zh={locale === "zh-CN"}/> : <img alt={attachment.name} src={attachment.dataUrl} />}</>
31483169
<button aria-label={t("composer.sentImageAlt", { name: attachment.name })} onClick={() => setImageAttachments((current) => current.filter((item) => item.id !== attachment.id))} type="button"><X size={13} /></button>
31493170
</figure>
31503171
))}</div> : null}
@@ -3185,18 +3206,18 @@ export function PersonalWorkspacePage({
31853206
<div
31863207
className="personal-channel-composer"
31873208
onDragOver={(event) => {
3188-
if ([...event.dataTransfer.items].some((item) => item.kind === "file" && item.type.startsWith("image/"))) {
3209+
if ([...event.dataTransfer.items].some((item) => item.kind === "file")) {
31893210
event.preventDefault();
31903211
}
31913212
}}
31923213
onDrop={(event) => {
3193-
const images = [...event.dataTransfer.files].filter((file) => file.type.startsWith("image/"));
3214+
const images = [...event.dataTransfer.files];
31943215
if (!images.length) return;
31953216
event.preventDefault();
31963217
void selectImages(images);
31973218
}}
31983219
>
3199-
<input accept="image/png,image/jpeg,image/webp,image/gif" aria-label={t("composer.imagePicker")} className="personal-composer-file-input" disabled={Boolean(workspaceConversations?.entryGate) || steering || (sending && !queueTurnId) || imageAttachments.length >= maxImageAttachmentCount} multiple onChange={(event) => void selectImages(event.target.files)} ref={imageInputRef} type="file" />
3220+
<input accept="image/png,image/jpeg,image/webp,image/gif,.md,.txt" aria-label={t("composer.imagePicker")} className="personal-composer-file-input" disabled={Boolean(workspaceConversations?.entryGate) || steering || (sending && !queueTurnId) || imageAttachments.length >= maxImageAttachmentCount} multiple onChange={(event) => void selectImages(event.target.files)} ref={imageInputRef} type="file" />
32003221
<textarea
32013222
disabled={Boolean(workspaceConversations?.entryGate)}
32023223
id="personal-conversation-composer"

0 commit comments

Comments
 (0)