From b126dbdeec511090668fecc9fd77c4d9bf8acf8d Mon Sep 17 00:00:00 2001 From: xiaomakuaiz Date: Mon, 27 Jul 2026 12:18:02 +0000 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E4=BA=91=E7=AB=AF=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E6=94=AF=E6=8C=81=E4=B8=8A=E4=BC=A0=E5=9B=BE=E7=89=87?= =?UTF-8?q?/=E6=96=87=E4=BB=B6(=E8=81=8A=E5=A4=A9=E9=99=84=E4=BB=B6=20+=20?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=8A=BD=E5=B1=89)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对齐 web 端两条上传链路,凭证不出内核: 聊天附件(presign → 对象存储): - 壳命令 mc_upload:presign 换预签名 URL + 壳内 PUT 直传,避开 WebView 跨域 - cloudUpload.ts 管线对齐 web 约束:单条 3 附件、单文件 2MB、>200KB 图片 canvas 转 webp(q0.6,压不动回退)、扩展名必填(粘贴截图按 MIME 补名) - 投递状态机整链携带附件:排队合并、失败回队、结束提醒不静默丢 - 输入区:回形针选文件/粘贴/拖拽(HTML5 + Linux 原生通道)+ 附件条 - reduce 解析 user-input.attachments,气泡直链渲染——web/mobile 发的 带附件消息桌面端不再丢弃 文件抽屉(REST multipart 直达 VM): - 壳命令 mc_file_upload:POST /users/files/upload(mc cookie,10MB 上限) - FilesDrawer 增可选 upload 能力位:header 传根目录 + 目录行悬停按钮 传该目录,完成强刷并展开;本地抽屉不接入,保持只读 - 结束态任务不给入口(VM 已回收);上传后重拉改动徽标 测试:vitest 291 全过(新增 7 用例),cargo test 166 全过 --- desktop/Cargo.lock | 17 +++ desktop/Cargo.toml | 2 +- desktop/build.rs | 2 + desktop/src/baizhi/mod.rs | 27 ++++ desktop/src/baizhi/monkeycode.rs | 86 +++++++++++++ desktop/src/main.rs | 2 + desktop/tauri.conf.json | 2 + desktop/ui/src/cloudUpload.ts | 117 ++++++++++++++++++ desktop/ui/src/cloudapi.test.ts | 30 ++++- desktop/ui/src/cloudapi.ts | 49 +++++--- desktop/ui/src/cloudfiles.tsx | 43 ++++++- desktop/ui/src/cloudtask.tsx | 185 ++++++++++++++++++++++++++-- desktop/ui/src/filesdrawer.test.tsx | 20 +++ desktop/ui/src/filesdrawer.tsx | 81 +++++++++++- desktop/ui/src/icons.tsx | 30 +++++ desktop/ui/src/logView.tsx | 87 ++++++++++++- desktop/ui/src/reduce.test.ts | 26 ++++ desktop/ui/src/reduce.ts | 9 +- desktop/ui/src/types.ts | 9 ++ desktop/ui/src/useCloudTask.test.ts | 27 ++++ desktop/ui/src/useCloudTask.ts | 130 +++++++++++++++---- 21 files changed, 924 insertions(+), 57 deletions(-) create mode 100644 desktop/ui/src/cloudUpload.ts diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index 1f2a0602..454a015f 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -2093,6 +2093,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minisign-verify" version = "0.2.5" @@ -3056,6 +3066,7 @@ dependencies = [ "hyper-util", "js-sys", "log", + "mime_guess", "percent-encoding", "pin-project-lite", "quinn", @@ -4739,6 +4750,12 @@ dependencies = [ "unic-common", ] +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 6e9bd254..03f183f0 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -25,7 +25,7 @@ tauri-plugin-updater = "2" # 引擎驱动层:壳直连 agent 内核(REST/WS/stdio),UI 只经 Tauri IPC # rustls 而非系统 openssl:Win7/老发行版无需系统 TLS 依赖 -reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream", "multipart"] } tokio = { version = "1", features = ["sync", "time", "macros", "io-util", "process"] } # rustls-tls-webpki-roots 不能少:云端桥拨的是 wss,缺 TLS feature 时 # connect_async 直接报 "TLS support not compiled in",所有云端 WS 秒败 diff --git a/desktop/build.rs b/desktop/build.rs index 2fdf9f00..f6f23716 100644 --- a/desktop/build.rs +++ b/desktop/build.rs @@ -64,6 +64,8 @@ fn main() { "mc_task_delete", "mc_task_create", "mc_task_options", + "mc_upload", + "mc_file_upload", ]), ), ) diff --git a/desktop/src/baizhi/mod.rs b/desktop/src/baizhi/mod.rs index d6bf5018..703aaf2b 100644 --- a/desktop/src/baizhi/mod.rs +++ b/desktop/src/baizhi/mod.rs @@ -594,3 +594,30 @@ pub async fn mc_task_create(bz: State<'_, BaizhiState>, req: Value) -> Result) -> Result { monkeycode::mc_task_options(&bz.0).await.map_err(BzErr::msg) } + +/// 云端聊天附件上传(data = base64 文件字节);返回 {access_url}。 +#[tauri::command] +pub async fn mc_upload(bz: State<'_, BaizhiState>, filename: String, data: String) -> Result { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data.as_bytes()) + .map_err(|e| format!("附件数据解码失败: {e}"))?; + let access_url = monkeycode::mc_upload(&bz.0, &filename, bytes).await.map_err(BzErr::msg)?; + Ok(json!({ "access_url": access_url })) +} + +/// 上传文件到云端任务 VM 工作区(path 为 VM 内绝对路径,data = base64 文件字节)。 +#[tauri::command] +pub async fn mc_file_upload( + bz: State<'_, BaizhiState>, + vm_id: String, + path: String, + data: String, +) -> Result { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data.as_bytes()) + .map_err(|e| format!("文件数据解码失败: {e}"))?; + monkeycode::mc_file_upload(&bz.0, &vm_id, &path, bytes).await.map_err(BzErr::msg)?; + Ok(json!({ "ok": true })) +} diff --git a/desktop/src/baizhi/monkeycode.rs b/desktop/src/baizhi/monkeycode.rs index 8eb1c54f..8b185f62 100644 --- a/desktop/src/baizhi/monkeycode.rs +++ b/desktop/src/baizhi/monkeycode.rs @@ -360,6 +360,92 @@ pub async fn mc_task_options(svc: &Service) -> BzResult { Ok(res) } +/// 附件上传壳侧护栏:UI 按云端约束(2MB,超限图片先压 webp)拦截,这里只防 +/// 超大载荷绕过 UI 直达 IPC;放宽到 4MB 免得两层阈值因压缩误差打架。 +const MC_UPLOAD_MAX_BYTES: usize = 4 << 20; + +/// 云端聊天附件上传(对齐 web uploadFileWithPresignedUrl):presign 换预签名 +/// URL → 壳直传对象存储(PUT 裸字节,预签名 URL 自带凭证,不带鉴权/Content-Type +/// 头)→ 返回 access_url,由 UI 放进 user-input 帧的 attachments。 +pub async fn mc_upload(svc: &Service, filename: &str, data: Vec) -> BzResult { + if filename.trim().is_empty() { + return Err(other("附件缺少文件名")); + } + if data.is_empty() { + return Err(other("附件内容为空")); + } + if data.len() > MC_UPLOAD_MAX_BYTES { + return Err(other("附件过大(上限 2MB)")); + } + let out = mc_call( + svc, + reqwest::Method::POST, + "/api/v1/uploader/presign", + Some(&json!({ "filename": filename })), + ) + .await?; + let field = |k: &str| out.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); + let (upload_url, access_url) = (field("upload_url"), field("access_url")); + if upload_url.is_empty() || access_url.is_empty() { + return Err(other("预签名应答缺少上传/访问地址")); + } + // 直传走长超时客户端:2MB 在慢速网络下可能贴近 30s 普通超时 + let resp = svc + .lp()? + .put(&upload_url) + .body(data) + .send() + .await + .map_err(|e| other(format!("上传附件失败: {e}")))?; + let status = resp.status().as_u16(); + if !(200..300).contains(&status) { + return Err(other(format!("上传附件失败(HTTP {status})"))); + } + Ok(access_url) +} + +/// 工作区文件上传壳侧护栏(UI 按 web 控制台同款 10MB 拦截,这里防超大 +/// 载荷绕过 UI 直达 IPC;放宽到 12MB 免得两层阈值打架)。 +const MC_FILE_UPLOAD_MAX_BYTES: usize = 12 << 20; + +/// 上传文件到云端任务 VM 工作区(对齐 web 控制台文件树的"上传文件": +/// POST /api/v1/users/files/upload?id=&path=<绝对路径>,multipart 字段 +/// file)。path 须为 VM 内绝对路径(如 /workspace/dir/name.txt),文件名取 +/// 其末段。 +pub async fn mc_file_upload(svc: &Service, vm_id: &str, path: &str, data: Vec) -> BzResult<()> { + if vm_id.is_empty() { + return Err(other("缺少虚拟机 ID")); + } + let filename = path.rsplit('/').next().unwrap_or("").to_string(); + if !path.starts_with('/') || filename.is_empty() { + return Err(other("目标路径必须是文件的绝对路径")); + } + if data.is_empty() { + return Err(other("文件内容为空")); + } + if data.len() > MC_FILE_UPLOAD_MAX_BYTES { + return Err(other("文件过大(上限 10MB)")); + } + let target = format!( + "{}/api/v1/users/files/upload?id={}&path={}", + svc.ep.monkeycode, + urlencode(vm_id), + urlencode(path) + ); + let url = reqwest::Url::parse(&target).map_err(|e| other(format!("地址异常: {e}")))?; + let form = reqwest::multipart::Form::new() + .part("file", reqwest::multipart::Part::bytes(data).file_name(filename)); + // 长超时客户端:10MB 在慢速网络下会贴近 30s 普通超时 + let mut req = svc.lp()?.post(url.clone()).multipart(form); + if let Some(h) = svc.mc.header(&url) { + req = req.header(reqwest::header::COOKIE, h); + } + let resp = req.send().await.map_err(|e| other(format!("上传失败: {e}")))?; + let status = resp.status().as_u16(); + let body = resp.bytes().await.map_err(|e| other(format!("读取响应失败: {e}")))?; + unwrap_envelope(&body, status, &ENV_MC).map(|_| ()) +} + /// MonkeyCode 云端包壳 {code,message,data}。401 不看响应体直接判会话失效: /// 恢复动作是"重新同步云端账号"(桥接登录),与百智云的"重新登录"不同。 pub(crate) const ENV_MC: Envelope = Envelope { diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 91628f77..335bb0d5 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -1110,6 +1110,8 @@ fn main() { baizhi::mc_task_delete, baizhi::mc_task_create, baizhi::mc_task_options, + baizhi::mc_upload, + baizhi::mc_file_upload, baizhi::monkeycode::cloud_ws_open, baizhi::monkeycode::cloud_ws_send, baizhi::monkeycode::cloud_ws_close diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.json index e97758de..0f31f884 100644 --- a/desktop/tauri.conf.json +++ b/desktop/tauri.conf.json @@ -80,6 +80,8 @@ "allow-mc-task-delete", "allow-mc-task-create", "allow-mc-task-options", + "allow-mc-upload", + "allow-mc-file-upload", "dialog:allow-open", "opener:allow-open-url", "opener:allow-default-urls", diff --git a/desktop/ui/src/cloudUpload.ts b/desktop/ui/src/cloudUpload.ts new file mode 100644 index 00000000..adcec2bc --- /dev/null +++ b/desktop/ui/src/cloudUpload.ts @@ -0,0 +1,117 @@ +// 云端任务聊天附件上传管线(约束对齐 web frontend 的 task-file-upload.tsx): +// 单条消息最多 3 个附件、单文件 2MB;超过 200KB 的可压缩图片先经 canvas 转 +// webp(质量 0.6)缩体积,压不动(变大/编码失败)回退原图再按 2MB 拦截。 +// 实际上传经壳命令 mc_upload(presign + PUT 都在壳内完成,凭证不出内核, +// 也避开 WebView 直传对象存储的跨域限制)。 +import { mcUpload } from "./cloudapi"; +import type { CloudAttachment } from "./types"; + +export const MAX_CLOUD_ATTS = 3; +export const MAX_CLOUD_FILE_BYTES = 2 * 1024 * 1024; +const COMPRESS_THRESHOLD_BYTES = 200 * 1024; +const COMPRESS_QUALITY = 0.6; + +/** 待发送的云端附件:上传已完成。preview 为图片的本地 dataURL 缩略 + * (发送时只取 url/filename,与 web/mobile 的 attachments 契约一致)。 */ +export interface CloudUploadedAtt extends CloudAttachment { + isImage: boolean; + preview?: string; +} + +/** 图片扩展名判定(对齐 web isTaskImageAttachment 的扩展名清单) */ +const IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp|bmp|svg|avif)$/i; +export const isImageFilename = (name: string) => IMAGE_EXT_RE.test(name); + +/** 有损转 webp 收益可观的位图类型(gif 动图/svg 矢量转了会坏,不碰) */ +const COMPRESSIBLE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/bmp", "image/avif"]); + +const MIME_EXT: Record = { + "image/png": "png", + "image/jpeg": "jpg", + "image/webp": "webp", + "image/gif": "gif", + "image/bmp": "bmp", + "image/svg+xml": "svg", + "image/avif": "avif", +}; + +const HAS_EXT_RE = /\.[^./\\]+$/; + +/** 剪贴板截图常无文件名/扩展名,而云端按扩展名识别类型:能从 MIME 推断的 + * 补齐扩展名(空名补时间戳名),推不出的原样返回交由调用方拦截。 */ +export function normalizeUploadName(f: File): string { + const name = (f.name || "").trim(); + if (name && HAS_EXT_RE.test(name)) return name; + const ext = MIME_EXT[f.type]; + if (!ext) return name; + const stamp = new Date() + .toISOString() + .replace(/\D/g, "") + .slice(0, 14); + return `${name || `pasted-image-${stamp}`}.${ext}`; +} + +/** canvas 转 webp。返回 null = 放弃压缩(解码失败/WebView 不支持 webp 编码), + * 调用方回退原图——压缩是省流量的优化,绝不能成为上传失败的理由。 */ +async function compressImage(f: File, name: string): Promise { + const url = URL.createObjectURL(f); + try { + const img = await new Promise((resolve, reject) => { + const el = new Image(); + el.onload = () => resolve(el); + el.onerror = () => reject(new Error("图片解码失败")); + el.src = url; + }); + const canvas = document.createElement("canvas"); + canvas.width = img.naturalWidth; + canvas.height = img.naturalHeight; + const ctx = canvas.getContext("2d"); + if (!ctx) return null; + ctx.drawImage(img, 0, 0); + const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/webp", COMPRESS_QUALITY)); + // toBlob 对不支持的编码会落回 png 等类型:类型不对视同不支持,回退原图 + if (!blob || blob.type !== "image/webp") return null; + return new File([blob], name.replace(/\.[^.]+$/, "") + ".webp", { type: "image/webp" }); + } catch { + return null; + } finally { + URL.revokeObjectURL(url); + } +} + +/** File → dataURL(聊天附件与文件抽屉上传共用;base64 取逗号后段) */ +export function readDataURL(f: File): Promise { + return new Promise((resolve, reject) => { + const r = new FileReader(); + r.onload = () => resolve(r.result as string); + r.onerror = () => reject(new Error("读取文件失败")); + r.readAsDataURL(f); + }); +} + +/** 单文件上传:校验(空文件/扩展名/大小)→ 必要时压缩 → base64 → 壳直传。 + * 失败抛 Error(中文提示,调用方外显)。 */ +export async function uploadCloudFile(f: File): Promise { + if (f.size === 0) throw new Error(`${f.name || "文件"} 是空文件`); + let name = normalizeUploadName(f); + if (!name || !HAS_EXT_RE.test(name)) { + throw new Error(`${f.name || "文件"} 缺少扩展名,云端无法识别类型`); + } + const compressible = COMPRESSIBLE_TYPES.has(f.type); + if (f.size > MAX_CLOUD_FILE_BYTES && !compressible) { + throw new Error(`${name} 过大(单文件上限 2MB)`); + } + let file: File = f; + if (compressible && f.size > COMPRESS_THRESHOLD_BYTES) { + const c = await compressImage(f, name); + if (c && c.size < f.size) { + file = c; + name = c.name; + } + } + if (file.size > MAX_CLOUD_FILE_BYTES) throw new Error(`${name} 压缩后仍超过 2MB 上限`); + const dataURL = await readDataURL(file); + const { access_url } = await mcUpload(name, dataURL.slice(dataURL.indexOf(",") + 1)); + const isImage = f.type.startsWith("image/") || isImageFilename(name); + return { url: access_url, filename: name, isImage, preview: isImage ? dataURL : undefined }; +} diff --git a/desktop/ui/src/cloudapi.test.ts b/desktop/ui/src/cloudapi.test.ts index 4bec23d1..ab28e991 100644 --- a/desktop/ui/src/cloudapi.test.ts +++ b/desktop/ui/src/cloudapi.test.ts @@ -81,7 +81,10 @@ afterEach(() => { delete (globalThis as Record).window; }); -async function makeConn(mode: "attach" | "new", firstInput?: string) { +async function makeConn( + mode: "attach" | "new", + firstInput?: string | { content: string; attachments?: { url: string; filename: string }[] }, +) { const { connectCloudTask } = await import("./cloudapi"); const events: string[] = []; const conn = connectCloudTask( @@ -92,7 +95,7 @@ async function makeConn(mode: "attach" | "new", firstInput?: string) { onStatus: (text) => events.push("status:" + text), onEnded: () => events.push("ended"), onIdle: () => events.push("idle"), - onSendFailed: (text) => events.push("sendFailed:" + text), + onSendFailed: (input) => events.push("sendFailed:" + input.content), onReconnect: () => events.push("reconnect"), }, firstInput, @@ -211,6 +214,29 @@ describe("connectCloudTask 重连状态机", () => { expect(openCalls).toBe(1); }); + it("mode=new 首条输入带附件 → user-input 帧携带 attachments(content 仍双层 base64)", async () => { + script.opens = [true]; + const att = { url: "https://oss.example.com/a.webp", filename: "a.webp" }; + await makeConn("new", { content: "看下这张图", attachments: [att] }); + await vi.advanceTimersByTimeAsync(0); + expect(sent.length).toBe(1); + const frame = JSON.parse(sent[0]) as { type: string; data: string }; + expect(frame.type).toBe("user-input"); + const payload = JSON.parse(b64decode(frame.data)) as { content: string; attachments: unknown }; + expect(b64decode(payload.content)).toBe("看下这张图"); + expect(payload.attachments).toEqual([att]); + }); + + it("mode=new 裸字符串首条输入(兼容旧调用)→ attachments 为空数组", async () => { + script.opens = [true]; + await makeConn("new", "纯文本"); + await vi.advanceTimersByTimeAsync(0); + const payload = JSON.parse(b64decode((JSON.parse(sent[0]) as { data: string }).data)) as { + attachments: unknown; + }; + expect(payload.attachments).toEqual([]); + }); + it("mode=new 有回显后中断 → 正常按断线重连(不误判拒收)", async () => { script.opens = [true, true]; const { events } = await makeConn("new", "正常输入"); diff --git a/desktop/ui/src/cloudapi.ts b/desktop/ui/src/cloudapi.ts index 2cdd5cc6..66e9e8e5 100644 --- a/desktop/ui/src/cloudapi.ts +++ b/desktop/ui/src/cloudapi.ts @@ -4,7 +4,7 @@ import { b64encode, frameData } from "./codec"; import type { McTaskOptions } from "./cloud"; import { invoke, listenAsync } from "./ipc"; -import type { CloudProjectsResp, CloudTaskDetail, CloudTasksResp, Frame, McStatus, McUser, WsCloseInfo } from "./types"; +import type { CloudAttachment, CloudProjectsResp, CloudTaskDetail, CloudTasksResp, Frame, McStatus, McUser, WsCloseInfo } from "./types"; // ==================== 云端 REST(壳命令代理) ==================== @@ -60,6 +60,16 @@ export const mcTaskCreate = (req: { export const mcTaskOptions = () => invoke("mc_task_options"); +/** 云端聊天附件上传(壳内 presign + 直传对象存储,凭证不出内核;data 为 + * base64 文件字节)。返回的 access_url 放进 user-input 的 attachments。 */ +export const mcUpload = (filename: string, dataB64: string) => + invoke<{ access_url: string }>("mc_upload", { filename, data: dataB64 }); + +/** 上传文件到云端任务 VM 工作区(壳代理 multipart,对齐 web 控制台文件树 + * 的"上传文件")。path 为 VM 内绝对路径(如 /workspace/dir/name.txt)。 */ +export const mcFileUpload = (vmId: string, path: string, dataB64: string) => + invoke<{ ok: boolean }>("mc_file_upload", { vmId, path, data: dataB64 }); + // ==================== 云端 WS 桥(壳做纯文本管道,协议逻辑在本层) ==================== /** 打开一条云端 WS 管道:onText 收下行文本帧,onClose 收断开(带服务端 @@ -120,6 +130,12 @@ export interface CloudConn { close(): void; } +/** mode=new 的首条输入:正文 + 附件(与 web/mobile 的 user-input 契约一致)。 */ +export interface CloudUserInput { + content: string; + attachments?: CloudAttachment[]; +} + /** 连接云端任务流(内核代理:内核带 monkeycode 会话拨 wss 到云端)。 * mode=attach 回放当前轮+实时跟看;mode=new 开新一轮(连上即发 firstInput)。 * 帧结构与本地会话 Frame 同构,可直接喂 reduceBatch;ping 已滤除,seq 单调去重。 @@ -136,10 +152,11 @@ export function connectCloudTask( /** 空闲关闭/连接彻底失败:云端对"当前轮已结束"的 attach 会直接关连接, * 这不是断线,不该重连——视图应转入"就绪"态(发消息时再建连接)。 */ onIdle?(): void; - /** mode=new 的首条输入未能送达(拨号失败):视图应把内容放回队列 */ - onSendFailed?(text: string): void; + /** mode=new 的首条输入未能送达(拨号失败):视图应把内容(含附件)放回队列 */ + onSendFailed?(input: CloudUserInput): void; }, - firstInput?: string, + /** 裸字符串视作无附件正文(兼容旧调用/测试) */ + firstInput?: string | CloudUserInput, ): CloudConn { let pipe: { send(t: string): Promise; close(): void } | null = null; let closed = false; @@ -148,7 +165,8 @@ export function connectCloudTask( let queue: Frame[] = []; let flushScheduled = false; let reconnectTimer: ReturnType | null = null; - let pendingFirst = firstInput; + let pendingFirst: CloudUserInput | undefined = + firstInput === undefined ? undefined : typeof firstInput === "string" ? { content: firstInput } : firstInput; let curMode = mode; let attempt = 0; let openedThisAttempt = false; // 本次尝试是否成功建立过管道 @@ -157,7 +175,7 @@ export function connectCloudTask( let dialErr = ""; // 最近一次拨号失败原因(状态行外显,不能吞——否则无从诊断) let dropCount = 0; // 连续短命断流次数(收过流又快速被关;超限转就绪兜底) let openedAt = 0; // 本次管道建立时刻(存活超 1 分钟视为健康,断流计数归零) - let sentFirstText: string | null = null; // 已上行但尚无任何回显的首条输入 + let sentFirst: CloudUserInput | null = null; // 已上行但尚无任何回显的首条输入 function flush() { flushScheduled = false; @@ -208,7 +226,7 @@ export function connectCloudTask( // 成断流而无限重连 if (f.type !== "cursor" && f.type !== "error" && f.type !== "task-error") { framesThisOpen += 1; - sentFirstText = null; // 有回显 = 首条输入已被云端接收 + sentFirst = null; // 有回显 = 首条输入已被云端接收 } queue.push(f); schedule(); @@ -228,10 +246,10 @@ export function connectCloudTask( const cleanClose = info?.code === 1000 || info?.code === 1001; if (openedThisAttempt && (cleanClose || framesThisOpen === 0)) { closed = true; - if (sentFirstText !== null) { + if (sentFirst !== null) { // mode=new 发了首条输入却零回显被关:大概率被拒(休眠/运行互斥), // 内容交还队列重试,绝不静默丢 - h.onSendFailed?.(sentFirstText); + h.onSendFailed?.(sentFirst); return; } // 云端收束/一帧未发就被关:停止重连,转"就绪"——发消息时会另建 @@ -243,10 +261,10 @@ export function connectCloudTask( dialFails += 1; if (pendingFirst !== undefined) { // 带首条输入的连接没拨通:内容交还视图排队,本连接就此作废 - const text = pendingFirst; + const input = pendingFirst; pendingFirst = undefined; closed = true; - h.onSendFailed?.(text); + h.onSendFailed?.(input); return; } if (dialFails >= DIAL_GIVEUP_FAILS) { @@ -304,9 +322,12 @@ export function connectCloudTask( h.onStatus("已连接云端", true); // 新一轮:云端等第一条 user-input 才开跑;content 需再包一层 base64 if (pendingFirst !== undefined) { - sentFirstText = pendingFirst; - // 发送失败不在此处理:零回显被关时经 sentFirstText → onSendFailed 兜底 - void doSend("user-input", { content: b64encode(pendingFirst), attachments: [] }); + sentFirst = pendingFirst; + // 发送失败不在此处理:零回显被关时经 sentFirst → onSendFailed 兜底 + void doSend("user-input", { + content: b64encode(pendingFirst.content), + attachments: pendingFirst.attachments ?? [], + }); pendingFirst = undefined; } }) diff --git a/desktop/ui/src/cloudfiles.tsx b/desktop/ui/src/cloudfiles.tsx index 19a215be..dc71d429 100644 --- a/desktop/ui/src/cloudfiles.tsx +++ b/desktop/ui/src/cloudfiles.tsx @@ -4,7 +4,8 @@ // repo_file_diff(与 web 控制台 task-file-explorer 同一套 kind 与字段), // 差异是 base64 内容解码、entry_mode 判目录、读取上限与唤醒超时余量。 import { useEffect, useRef, useState } from "react"; -import { connectCloudControl, type CloudControl } from "./cloudapi"; +import { connectCloudControl, mcFileUpload, type CloudControl } from "./cloudapi"; +import { readDataURL } from "./cloudUpload"; import type { CloudFileChange, CloudRepoFile } from "./types"; import { b64decode } from "./codec"; import { FilesDrawer, fmtSize, type FsAdapter } from "./filesdrawer"; @@ -13,11 +14,25 @@ const isDir = (f: CloudRepoFile) => f.entry_mode === 4 || f.entry_mode === 5; const MAX_FILE_SIZE = 1 << 20; // 读取上限 1MB(对齐 web/mobile) +const MAX_UPLOAD_SIZE = 10 * 1024 * 1024; // 上传上限 10MB(对齐 web 控制台文件树) + +/** 树内相对路径 → VM 内绝对路径(与 web 同一约定:工作区固定挂 /workspace) */ +const vmPath = (dir: string, name: string) => "/workspace/" + (dir ? dir + "/" : "") + name; + // 控制流 call 默认 15s 超时,但拨号会触发休眠 VM 唤醒(以分钟计): // 抽屉打开即发的列表/改动调用给足唤醒余量,免得唤醒期间必然超时 const WAKE_CALL_OPTS = { timeoutMs: 90_000, timeoutMsg: "云端环境可能在唤醒中,响应超时,请稍后重试" }; -export function CloudFilesDrawer({ taskId, onClose }: { taskId: string; onClose: () => void }) { +export function CloudFilesDrawer({ + taskId, + vmId, + onClose, +}: { + taskId: string; + /** 任务 VM id(REST 文件上传按它寻址);空 = 无上传入口(VM 未就绪/已结束) */ + vmId?: string; + onClose: () => void; +}) { const [changes, setChanges] = useState(null); const [ctrlErr, setCtrlErr] = useState(""); const ctrlRef = useRef(null); @@ -31,12 +46,17 @@ export function CloudFilesDrawer({ taskId, onClose }: { taskId: string; onClose: }, })); - // 拉改动(根目录由 FilesDrawer 挂载时经适配层拉取);卸载即断开 - useEffect(() => { + // 拉改动(根目录由 FilesDrawer 挂载时经适配层拉取);上传后也重拉, + // 新文件的「??」要能出现在改动徽标里 + const refreshChanges = () => ensureCtrl() .call<{ changes?: CloudFileChange[] }>("repo_file_changes", {}, WAKE_CALL_OPTS) .then((r) => setChanges(r.changes ?? [])) .catch(() => setChanges([])); + + // 打开即拉改动;卸载即断开 + useEffect(() => { + void refreshChanges(); return () => { ctrlRef.current?.close(); ctrlRef.current = null; @@ -76,6 +96,21 @@ export function CloudFilesDrawer({ taskId, onClose }: { taskId: string; onClose: }, diffTransientKind: "plain", clearErrOnListSuccess: true, + // 上传(REST 直达 VM,壳代理 multipart;与 web 控制台同一端点与 10MB 上限)。 + // 顺序上传、失败即止:已传成功的部分随抽屉强刷可见,错误在列表区外显 + ...(vmId + ? { + upload: async (dir: string, files: File[]) => { + for (const f of files) { + if (f.size === 0) throw new Error(`${f.name} 是空文件`); + if (f.size > MAX_UPLOAD_SIZE) throw new Error(`${f.name} 过大(单文件上限 10MB)`); + const dataURL = await readDataURL(f); + await mcFileUpload(vmId, vmPath(dir, f.name), dataURL.slice(dataURL.indexOf(",") + 1)); + } + void refreshChanges(); + }, + } + : {}), }; return ( diff --git a/desktop/ui/src/cloudtask.tsx b/desktop/ui/src/cloudtask.tsx index be6747ee..60a92f80 100644 --- a/desktop/ui/src/cloudtask.tsx +++ b/desktop/ui/src/cloudtask.tsx @@ -2,17 +2,19 @@ // 任务,不开浏览器。连接编排与投递状态机全部在 useCloudTask 里收口, // 这里只消费 CloudTaskHandle + 持有纯 UI 状态(菜单/抽屉/终端开合)。 // 渲染复用本地会话的帧归约链(reduceBatch → LogList):云端帧与本地 Frame 同构。 -import { useState } from "react"; +import { useRef, useState, type ClipboardEvent, type DragEvent } from "react"; import { openExternal } from "./host"; import type { CloudTask, CloudTaskDetail } from "./types"; import { cloudModelLabel } from "./cloud"; import { CloudFilesDrawer } from "./cloudfiles"; import { CloudTerminal } from "./cloudterm"; +import { MAX_CLOUD_ATTS } from "./cloudUpload"; import { COL_MAX, ModelMenuItem, ModelPickerTrigger } from "./chat"; import { HeaderFilesButton, HeaderMenu, LogList, TaskPanel, ViewHeader, type MenuState } from "./components"; import { Composer, QueuedChip, RunningBar } from "./composer"; -import { IconCloud, IconGlobe, IconMonitor, IconStop, IconX } from "./icons"; +import { IconCloud, IconFile, IconGlobe, IconMonitor, IconPaperclip, IconStop, IconX } from "./icons"; import { useUpwardMenuHeight } from "./menuPosition"; +import { useNativeFileDrop } from "./nativeDrop"; import { useCloudTask } from "./useCloudTask"; const STATUS_LABEL: Record = { @@ -63,6 +65,53 @@ export function CloudTaskView({ const [filesOpen, setFilesOpen] = useState(false); const [termOpen, setTermOpen] = useState(false); + // ===== 附件入口(选择/粘贴/拖入;上传与额度在 hook)===== + const fileRef = useRef(null); + const [dragging, setDragging] = useState(false); + const dragDepth = useRef(0); + const onPaste = (e: ClipboardEvent) => { + if (ended) return; + const files: File[] = []; + for (const item of e.clipboardData.items) { + if (item.kind === "file") { + const f = item.getAsFile(); + if (f) files.push(f); + } + } + if (files.length) { + e.preventDefault(); + h.addFiles(files); + } + }; + // 拖拽文件进对话区(与本地 ChatView 同一套 DOM 事件;Linux 走原生通道) + const onDragEnter = (e: DragEvent) => { + if (ended || ![...e.dataTransfer.items].some((i) => i.kind === "file")) return; + e.preventDefault(); + dragDepth.current++; + setDragging(true); + }; + const onDragLeave = (e: DragEvent) => { + e.preventDefault(); + if (--dragDepth.current <= 0) { + dragDepth.current = 0; + setDragging(false); + } + }; + const onDrop = (e: DragEvent) => { + e.preventDefault(); + dragDepth.current = 0; + setDragging(false); + if (ended) return; + const files = [...e.dataTransfer.files]; + if (files.length) h.addFiles(files); + }; + useNativeFileDrop({ + enabled: !ended, + onDragging: setDragging, + onFiles: (files) => h.addFiles(files), + onError: (msg) => h.notify("⚠ 附件上传失败: " + msg), + }); + // 云端模型下拉开合(列表加载/切换在 hook) const [modelOpen, setModelOpen] = useState(false); const { anchorRef: modelAnchorRef, menuMaxHeight: modelMenuMaxHeight } = useUpwardMenuHeight(modelOpen, 320); @@ -74,7 +123,34 @@ export function CloudTaskView({ const st = STATUS_LABEL[taskStatus] ?? { text: taskStatus, color: "var(--t4)" }; return ( -
+
e.preventDefault()} + onDragLeave={onDragLeave} + onDrop={onDrop} + > + {dragging && !ended && ( +
+ 松开以添加附件 +
+ )} {/* ==== 标题栏:共享 ViewHeader(与 ChatView 同一几何)==== */} 0 ? `${queued}(+${h.queuedAtts} 附件)` : queued} hint={taskStatus === "pending" ? "环境就绪后自动发送" : vmWaking ? "环境唤醒后自动发送" : "本轮结束后自动发送"} onClear={h.clearQueued} /> @@ -293,13 +369,107 @@ export function CloudTaskView({ ? "环境唤醒中…现在发送会排队,唤醒后自动送达" : running ? "补充说明…运行中发送会排队" - : "继续对话…" + : "继续对话…粘贴或拖入图片、文件可作为附件" } sendActive={!!h.input.trim()} onChange={h.setInput} onSend={h.send} + onPaste={onPaste} + above={ + (h.atts.length > 0 || h.uploading > 0) && ( +
+ {h.atts.map((a, i) => ( + + {a.isImage && a.preview ? ( + {a.filename} + ) : ( + + + {a.filename} + + )} + + + ))} + {h.uploading > 0 && ( + + + 上传中… + + )} +
+ ) + } controls={ <> + { + const files = [...(e.target.files ?? [])]; + e.target.value = ""; // 允许重复选同一文件 + if (files.length) h.addFiles(files); + }} + /> + - {/* ==== 云端文件抽屉(共享 FilesDrawer 浮层,数据经控制流适配)==== */} - {filesOpen && setFilesOpen(false)} />} + {/* ==== 云端文件抽屉(共享 FilesDrawer 浮层,数据经控制流适配; + 上传只对未结束任务开放——结束态 VM 已回收,写不进去)==== */} + {filesOpen && setFilesOpen(false)} />}
); } diff --git a/desktop/ui/src/filesdrawer.test.tsx b/desktop/ui/src/filesdrawer.test.tsx index eb144aef..0d142483 100644 --- a/desktop/ui/src/filesdrawer.test.tsx +++ b/desktop/ui/src/filesdrawer.test.tsx @@ -24,6 +24,26 @@ const renderDrawer = (showChangesTab: boolean, initialTab: "files" | "changes" = />, ); +describe("FilesDrawer 上传入口", () => { + it("adapter 无 upload:不渲染上传按钮(本地抽屉保持只读现状)", () => { + expect(renderDrawer(true)).not.toContain("上传文件到工作区根目录"); + }); + + it("adapter 带 upload(云端 VM 就绪):header 出现根目录上传按钮", () => { + const html = renderToStaticMarkup( + {} }} + onClose={() => {}} + changes={[]} + errPad="0" + changesEmptyText="没有文件改动" + viewerCloseTitle="关闭预览" + />, + ); + expect(html).toContain("上传文件到工作区根目录"); + }); +}); + describe("FilesDrawer tabs", () => { it("hides the changes tab for a non-git workspace", () => { const html = renderDrawer(false, "changes"); diff --git a/desktop/ui/src/filesdrawer.tsx b/desktop/ui/src/filesdrawer.tsx index 2e868214..f6205140 100644 --- a/desktop/ui/src/filesdrawer.tsx +++ b/desktop/ui/src/filesdrawer.tsx @@ -7,7 +7,7 @@ import { Fragment, useEffect, useRef, useState, type CSSProperties, type MutableRefObject, type ReactNode } from "react"; import { basename } from "./chat"; import { CodeView, DiffPanel, MONO } from "./components"; -import { IconChevronRight, IconFile, IconFolder, IconX } from "./icons"; +import { IconChevronRight, IconFile, IconFolder, IconUpload, IconX } from "./icons"; /** 改动状态 → 普通用户可读的中文标签与配色(git 的 A/M/D 不外显)。 * 云端词汇是本地(A/M/D)的超集,对齐 web/移动端:M/A/D/R/RM/?? */ @@ -88,6 +88,9 @@ export interface FsAdapter { diffTransientKind: "diff" | "plain"; /** 列表拉取成功后清除错误行(云端历史行为;本地保留错误) */ clearErrOnListSuccess?: boolean; + /** 上传能力(云端 VM 工作区;缺省无上传入口):把一批文件传到目录 + * (dir "" = 工作区根),抛错 → 错误行外显。完成后抽屉自行强刷该目录。 */ + upload?(dir: string, files: File[]): Promise; } export function FilesDrawer({ @@ -227,6 +230,34 @@ export function FilesDrawer({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + // ===== 上传(adapter.upload 存在才有入口):header 传根目录,目录行悬停 + // 按钮传该目录;完成后强刷目标目录并展开让结果可见 ===== + const uploadInputRef = useRef(null); + const uploadDirRef = useRef(""); // 点击入口时锁定的目标目录(input 异步回调里读) + const [uploadingTo, setUploadingTo] = useState(null); + const canUpload = !!adapter.upload; + const pickUpload = (dir: string) => { + if (uploadingTo !== null) return; // 一次一批,避免并发写同目录交错 + uploadDirRef.current = dir; + uploadInputRef.current?.click(); + }; + const onUploadPicked = async (files: File[]) => { + const dir = uploadDirRef.current; + if (!files.length || !adapterRef.current.upload) return; + setUploadingTo(dir); + try { + await adapterRef.current.upload(dir, files); + setFsErr(""); + } catch (e) { + // 批量顺序上传中途失败:已传上去的部分随下方强刷可见,不算静默 + setFsErr(e instanceof Error ? e.message : String(e)); + } finally { + setUploadingTo(null); + } + if (dir) setExpanded((s) => new Set(s).add(dir)); + await loadChildren(dir, true); + }; + // 展开/收起文件夹(展开时懒加载子项,已缓存的即时展开) const toggleDir = (dir: string) => { setExpanded((prev) => { @@ -365,10 +396,11 @@ export function FilesDrawer({ const subCount = en.isDir && dirChangeBadges ? changedUnder(en.path) : 0; const open = en.isDir && expanded.has(en.path); const active = viewer?.path === en.path; + const rowUpload = en.isDir && canUpload; rows.push(
(en.isDir ? toggleDir(en.path) : void showFile(en))} style={{ ...fileRow, paddingLeft: pad, background: active ? "var(--hov)" : "transparent" }} @@ -389,6 +421,24 @@ export function FilesDrawer({ {en.isDir && subCount > 0 && ( {subCount} 处改动 )} + {rowUpload && ( + + )} {!en.isDir && kind && {kind.text}} {!en.isDir && !kind && ( @@ -452,12 +502,39 @@ export function FilesDrawer({ )} + {canUpload && tab === "files" && ( + + )} {headerExtra}
+ {canUpload && ( + { + const files = [...(e.target.files ?? [])]; + e.target.value = ""; // 允许重复选同一文件 + void onUploadPicked(files); + }} + /> + )} {(fsErr || externalErr) && (
{fsErr || externalErr}
diff --git a/desktop/ui/src/icons.tsx b/desktop/ui/src/icons.tsx index 15c02238..8fcac204 100644 --- a/desktop/ui/src/icons.tsx +++ b/desktop/ui/src/icons.tsx @@ -237,6 +237,36 @@ export function IconX({ size = 9, color = "var(--t5)", style }: IconProps) { ); } +/** 上传(托盘 + 上箭头) */ +export function IconUpload({ size = 12, color = "var(--t3)", style }: IconProps) { + return ( + + + + ); +} + +/** 回形针(添加附件) */ +export function IconPaperclip({ size = 13, color = "var(--t3)", style }: IconProps) { + return ( + + + + ); +} + /** 发送(上箭头) */ export function IconSend({ size = 13, color = "var(--onAcc)", style }: IconProps) { return ( diff --git a/desktop/ui/src/logView.tsx b/desktop/ui/src/logView.tsx index 4a90b67d..72647a20 100644 --- a/desktop/ui/src/logView.tsx +++ b/desktop/ui/src/logView.tsx @@ -1,11 +1,13 @@ // 对话流:思考块、轮次边界、模型切换、用户气泡与逐项分发(相邻工具卡共享外框)。 import { useState, type ReactElement } from "react"; +import { isImageFilename } from "./cloudUpload"; +import { openExternal } from "./host"; import { IconChevronRight, IconSpark } from "./icons"; import { Markdown } from "./markdown"; import { AskCard, PermCard } from "./promptCards"; import { permAnchors } from "./reduce"; import { ToolCard } from "./toolCard"; -import type { Frame, LogItem } from "./types"; +import type { CloudAttachment, Frame, LogItem } from "./types"; import { UploadImg, downloadUpload } from "./uploadMedia"; /** 思考块:单行折叠(✦ 思考 + 摘要省略),点击在下方展开完整文本的缩进块。 @@ -105,20 +107,27 @@ function MessageTime({ timestamp, align }: { timestamp?: number; align: "start" ); } -/** 用户气泡:文本 + 附图缩略图(点击看大图)+ 文件 chip(点击下载) */ +/** 用户气泡:文本 + 附图缩略图(点击看大图)+ 文件 chip(点击下载)。 + * 附件两个来源互斥:本地会话走正文附件行约定(uploadUrl 回读工作区), + * 云端任务走 attachments 字段(对象存储直链,CSP 已放行 https: 图源)。 */ function UserBubble({ text, timestamp, seq, uploadUrl, + attachments, }: { text: string; timestamp?: number; /** 产生它的 user-input 帧 seq:提问大纲按它定位这条气泡 */ seq?: number; uploadUrl?: (path: string) => Promise; + /** 云端任务附件(url 直链渲染;文件 chip 点击在浏览器打开) */ + attachments?: CloudAttachment[]; }) { const [zoom, setZoom] = useState(null); + // 云端图片大图预览(直链,与本地 zoom 的回读语义不同,分开持有) + const [zoomUrl, setZoomUrl] = useState(null); const lines = text.split("\n"); const images: string[] = []; const files: string[] = []; @@ -129,6 +138,8 @@ function UserBubble({ else rest.push(line); } const body = rest.join("\n").trim(); + const cloudImages = (attachments ?? []).filter((a) => isImageFilename(a.filename)); + const cloudFiles = (attachments ?? []).filter((a) => !isImageFilename(a.filename)); return (
{body} - {(images.length > 0 || files.length > 0) && ( + {(images.length > 0 || files.length > 0 || cloudImages.length > 0 || cloudFiles.length > 0) && (
+ {cloudImages.map((a) => ( + {a.filename} setZoomUrl(a.url)} + style={{ + maxWidth: 150, + maxHeight: 120, + borderRadius: 8, + border: "1px solid var(--accBd)", + cursor: "zoom-in", + display: "block", + }} + /> + ))} + {cloudFiles.map((a) => ( + openExternal(a.url)} + style={{ + height: 28, + display: "flex", + alignItems: "center", + gap: 6, + padding: "0 10px", + borderRadius: 8, + border: "1px solid var(--accBd)", + background: "var(--card)", + fontSize: 12, + color: "var(--t2)", + maxWidth: 240, + cursor: "pointer", + }} + > + 📄 + {a.filename} + + ))} {images.map((p) => (
)} + {zoomUrl && ( +
setZoomUrl(null)} + style={{ + position: "fixed", + inset: 0, + background: "var(--scrim3)", + zIndex: 50, + display: "flex", + alignItems: "center", + justifyContent: "center", + cursor: "zoom-out", + }} + > + +
+ )}
); } @@ -239,7 +312,13 @@ function ItemView({ switch (item.kind) { case "user": return ( - + ); case "agent": return ( diff --git a/desktop/ui/src/reduce.test.ts b/desktop/ui/src/reduce.test.ts index ccaa8972..5674e50f 100644 --- a/desktop/ui/src/reduce.test.ts +++ b/desktop/ui/src/reduce.test.ts @@ -473,6 +473,32 @@ describe("轮次与系统帧", () => { expect(s.items[0]).toEqual({ kind: "user", text: "带时间", timestamp: 1_234 }); }); + it("user-input 解析云端附件;缺 filename 用 URL 末段兜底,无 url 的条目丢弃", () => { + const s = run([ + frame("user-input", { + content: b64encode("看下这张图"), + attachments: [ + { url: "https://oss.example.com/a.webp", filename: "a.webp" }, + { url: "https://oss.example.com/x/b.pdf" }, // 旧帧缺 filename + { filename: "孤儿.png" }, // 无 url:不可渲染,丢弃 + ], + }), + ]); + expect(s.items[0]).toEqual({ + kind: "user", + text: "看下这张图", + attachments: [ + { url: "https://oss.example.com/a.webp", filename: "a.webp" }, + { url: "https://oss.example.com/x/b.pdf", filename: "b.pdf" }, + ], + }); + // 空 attachments:字段缺席(不污染全等比较) + expect(run([frame("user-input", { content: b64encode("无附件"), attachments: [] })]).items[0]).toEqual({ + kind: "user", + text: "无附件", + }); + }); + it("usage/model/permMode 回写状态并留系统行", () => { const s = run([ acp({ sessionUpdate: "usage_update", used: 1200, size: 200000 }), diff --git a/desktop/ui/src/reduce.ts b/desktop/ui/src/reduce.ts index 1e1630ad..18d1a472 100644 --- a/desktop/ui/src/reduce.ts +++ b/desktop/ui/src/reduce.ts @@ -424,19 +424,26 @@ export function reduceFrame(s: ChatState, f: Frame): ChatState { }; } case "user-input": { - const data = frameData<{ content?: string }>(f); + const data = frameData<{ content?: string; attachments?: { url?: string; filename?: string }[] }>(f); let text = ""; try { text = data?.content ? b64decode(data.content) : ""; } catch { text = data?.content ?? ""; } + // 云端附件({url, filename},与 web/mobile 契约一致):缺 filename 的 + // 旧帧用 URL 末段兜底;本地会话帧无此字段,不受影响 + const atts = (data?.attachments ?? []) + .filter((a) => !!a?.url) + .map((a) => ({ url: a.url!, filename: a.filename || a.url!.split("/").pop() || "附件" })); return push(s, { kind: "user", text, ...(f.timestamp !== undefined ? { timestamp: f.timestamp } : {}), // 大纲跳转的锚:壳的 session_outline 条目按同一 seq 对表 ...(f.seq !== undefined ? { seq: f.seq } : {}), + // 有才写:undefined/空数组键会污染测试的全等比较,语义上也该缺席 + ...(atts.length ? { attachments: atts } : {}), }); } case "permission-req": { diff --git a/desktop/ui/src/types.ts b/desktop/ui/src/types.ts index 622cea66..7183bfeb 100644 --- a/desktop/ui/src/types.ts +++ b/desktop/ui/src/types.ts @@ -160,6 +160,13 @@ export interface AskQuestion { answer?: string | string[]; } +/** 云端任务聊天附件(user-input 帧的 attachments 条目;url 为对象存储 + * access_url,与 web/mobile 同一契约,单条消息云端上限 10 个)。 */ +export interface CloudAttachment { + url: string; + filename: string; +} + /** 对话流里的一条渲染项 */ export type LogItem = | { @@ -170,6 +177,8 @@ export type LogItem = /** 产生它的 user-input 帧 seq:提问大纲 ↔ 渲染项 ↔ DOM 的稳定锚 * (下标会因"加载更早"整体平移,seq 不会;旧记录可缺省) */ seq?: number; + /** 云端任务附件(url 直链渲染;本地会话走文本附件行约定,不用此字段) */ + attachments?: CloudAttachment[]; } | { kind: "agent"; text: string; /** 首个流式分片时间(Unix ms;旧记录可缺省) */ timestamp?: number } | { kind: "thought"; text: string } diff --git a/desktop/ui/src/useCloudTask.test.ts b/desktop/ui/src/useCloudTask.test.ts index 53c1103e..c814b2b1 100644 --- a/desktop/ui/src/useCloudTask.test.ts +++ b/desktop/ui/src/useCloudTask.test.ts @@ -85,6 +85,14 @@ function sentUserInputs(): string[] { .map((m) => b64decode((JSON.parse(b64decode(m.data)) as { content: string }).content)); } +/** 上行 user-input 帧携带的 attachments(按帧序) */ +function sentAttachments(): unknown[] { + return sent + .map((t) => JSON.parse(t) as { type: string; data: string }) + .filter((m) => m.type === "user-input") + .map((m) => (JSON.parse(b64decode(m.data)) as { attachments?: unknown }).attachments); +} + /** 组装核心 + 记录型 IO(排队/状态/错误/回写全部落到 out,便于断言) */ function makeCore(taskStatus = "processing") { const events: string[] = []; @@ -169,6 +177,25 @@ describe("云端投递状态机:排队与自动投递", () => { expect(sentUserInputs()).toEqual(["第一条", "第二条"]); }); + it("附件随消息投递:直发带附件;未回执入队的附件轮结束后随队发出", async () => { + opens = [true, true]; + const { core, out } = makeCore(); + const att1 = { url: "https://oss.example.com/a.webp", filename: "a.webp" }; + const att2 = { url: "https://oss.example.com/b.pdf", filename: "b.pdf" }; + core.send("第一条", [att1]); + await vi.advanceTimersByTimeAsync(0); + expect(sentAttachments()).toEqual([[att1]]); + // 上一条未回执:第二条连同附件一起排队 + core.send("第二条", [att2]); + expect(out.queued).toBe("第二条"); + // 回显解除回执等待;轮结束后排队消息(含附件)自动投递 + pushFrame({ type: "user-input", seq: 1, data: "e30=" }); + pushFrame({ type: "task-ended", seq: 2 }); + await vi.advanceTimersByTimeAsync(250); + expect(sentUserInputs()).toEqual(["第一条", "第二条"]); + expect(sentAttachments()).toEqual([[att1], [att2]]); + }); + it("已收到运行帧后再次发送仍入队,不会直接抢开新一轮", async () => { opens = [true, true]; const { core, out } = makeCore(); diff --git a/desktop/ui/src/useCloudTask.ts b/desktop/ui/src/useCloudTask.ts index 44d23050..1f4104bc 100644 --- a/desktop/ui/src/useCloudTask.ts +++ b/desktop/ui/src/useCloudTask.ts @@ -23,11 +23,13 @@ import { mcTaskRounds, mcTaskStop, type CloudConn, + type CloudUserInput, } from "./cloudapi"; import { usableCloudModels, type McCloudModel } from "./cloud"; +import { MAX_CLOUD_ATTS, uploadCloudFile, type CloudUploadedAtt } from "./cloudUpload"; import { frameData } from "./codec"; import { answerAsk as applyAskAnswer, initialChat, reduceBatch, type ChatState } from "./reduce"; -import type { CloudTask, CloudTaskDetail, Frame } from "./types"; +import type { CloudAttachment, CloudTask, CloudTaskDetail, Frame } from "./types"; /** cursor 帧载荷:attach 下发时 data 既有裸 JSON 对象也有 base64(JSON) * 形态(云端契约不归本仓库管)——frameData 的双格式容错正是为此收口。 */ @@ -61,8 +63,8 @@ export interface CloudCoreIO { setConnected(ok: boolean): void; /** 翻页游标:仅在尚未持有游标时采纳(attach 回放的 cursor 帧) */ setCursorIfEmpty(cursor: string, hasMore: boolean): void; - /** 排队内容镜像(React state,供 UI 外显) */ - setQueued(text: string): void; + /** 排队内容镜像(React state,供 UI 外显;atts 为随队待发附件) */ + setQueued(text: string, atts: CloudAttachment[]): void; setErr(text: string): void; /** 重新武装 attach effect(唤醒完成 / 投递被拒后重建观察通道) */ bumpAttachEpoch(): void; @@ -93,6 +95,7 @@ export function createCloudTaskCore( // 先入队,就绪(轮结束、attach 同步完)后自动投递;连发多条合并进同一队列, // 不会再出现"第二条把第一条的连接关掉导致丢消息"。 let queued = ""; // 单一事实源(原 queuedRef + state 双写在此收敛,io.setQueued 只是镜像) + let queuedAtts: CloudAttachment[] = []; // 随队待发附件(与 queued 同生命周期) let running = false; // chat.running 镜像(稳定回调里读) let sending = false; // 直发后等首帧回执,期间再发只入队 let taskStatus = "pending"; // 详情状态的渲染期镜像(原 statusRef) @@ -102,9 +105,19 @@ export function createCloudTaskCore( let attachIdle = false; let sendFails = 0; // 连续投递失败计数(超限暂停自动重试) - const setQueued = (v: string) => { + const setQueued = (v: string, atts: CloudAttachment[]) => { queued = v; - io.setQueued(v); + queuedAtts = atts; + io.setQueued(v, atts); + }; + + /** 云端单条 user-input 附件上限(backend 契约为 10);排队合并超限时 + * 截断并外显——静默丢会让用户以为图已随消息送达 */ + const MAX_SEND_ATTS = 10; + const capAtts = (atts: CloudAttachment[]) => { + if (atts.length <= MAX_SEND_ATTS) return atts; + io.setErr(`合并排队后附件超过 ${MAX_SEND_ATTS} 个上限,已丢弃后 ${atts.length - MAX_SEND_ATTS} 个`); + return atts.slice(0, MAX_SEND_ATTS); }; // 帧下发处理:cursor 帧捕获翻页游标,其余喂归约;轮结束把当前轮归档进历史 @@ -169,10 +182,13 @@ export function createCloudTaskCore( // 首条输入未送达(拨号失败/零回显被关):放回队列头,绝不静默丢。 // 该连接已死,引用一并清掉;连续失败超限后暂停自动重试(内容仍在 // 队列),否则"投递→被拒→2s 再投"会自持死循环 - onSendFailed: (text: string) => { + onSendFailed: (input: CloudUserInput) => { sending = false; conn = null; - setQueued(queued ? text + "\n" + queued : text); + setQueued( + queued ? input.content + "\n" + queued : input.content, + capAtts([...(input.attachments ?? []), ...queuedAtts]), + ); sendFails += 1; // 重建 attach 拿回观察通道:被拒大多因为轮在跑/环境未就绪, // attach 回放能揭示真实轮状态(收到帧会把失败计数归零), @@ -194,7 +210,7 @@ export function createCloudTaskCore( } // 直发:并入历史 → 换 mode=new 连接(连上自动上行 user-input,云端回显)。 - const dispatch = (text: string) => { + const dispatch = (text: string, atts: CloudAttachment[]) => { history = [...history, ...live]; live = []; conn?.close(); @@ -207,7 +223,7 @@ export function createCloudTaskCore( trySendQueued(); } }, 15000); - conn = connect(id, "new", handlers(), text); + conn = connect(id, "new", handlers(), { content: text, attachments: atts }); }; // 投递排队消息(对齐 mobile handleSend:直接建 mode=new 连接上行,服务端 @@ -221,34 +237,36 @@ export function createCloudTaskCore( if (running || sending) return; // 可见在跑/未回执才等 if (sendFails >= 3) return; // 连败暂停:收到帧/唤醒/手动发送解除 const q = queued; - setQueued(""); - dispatch(q); + const qa = queuedAtts; + setQueued("", []); + dispatch(q, qa); } return { // ==================== 投递状态机(视图动作) ==================== /** 发送:随时可按。当前轮执行中或上一条未回执 → 入队 - * (多条合并,轮结束自动投递);空闲时才直发。 */ - send(text: string) { + * (多条合并,轮结束自动投递);空闲时才直发。atts 为随消息附件。 */ + send(text: string, atts: CloudAttachment[] = []) { if (!text || taskStatus === "finished" || taskStatus === "error") return; sendFails = 0; // 手动发送 = 用户明确要投递,重试机会重置 // 当前轮还在执行或上一条直发还没回执:合并入队,别抢开新一轮或 // 把在途连接顶掉。task-ended / onIdle 会解除 running 并自动投递。 if (running || sending) { - setQueued(queued ? queued + "\n" + text : text); + setQueued(queued ? queued + "\n" + text : text, capAtts([...queuedAtts, ...atts])); return; } // 空闲时,把队列里压着的一并带上 const full = [queued, text].filter(Boolean).join("\n"); - setQueued(""); - dispatch(full); + const fullAtts = capAtts([...queuedAtts, ...atts]); + setQueued("", []); + dispatch(full, fullAtts); }, trySendQueued, clearQueued() { - setQueued(""); + setQueued("", []); }, /** 中断当前执行(WS user-cancel,不终止任务);发送结果是真实布尔—— @@ -281,9 +299,10 @@ export function createCloudTaskCore( /** 任务结束时还压着排队消息:外显提醒,不静默丢 */ handleEnded() { - if (!queued) return; - io.setErr(`任务已结束,有未发送的消息:「${queued.slice(0, 60)}」`); - setQueued(""); + if (!queued && queuedAtts.length === 0) return; + const attNote = queuedAtts.length ? `(含 ${queuedAtts.length} 个附件)` : ""; + io.setErr(`任务已结束,有未发送的消息:「${queued.slice(0, 60)}」${attNote}`); + setQueued("", []); }, // ==================== 连接编排(hook effects 驱动) ==================== @@ -391,8 +410,19 @@ export interface CloudTaskHandle { input: string; setInput(v: string): void; queued: string; + /** 随排队消息待发的附件数(排队 chip 外显) */ + queuedAtts: number; clearQueued(): void; send(): void; + /** 待发送附件(已上传完成;单条消息上限 3) */ + atts: CloudUploadedAtt[]; + /** 上传进行中的附件数(>0 时发送先拦下,避免半套附件出门) */ + uploading: number; + /** 选择/粘贴/拖入的文件逐个上传为附件(超限/失败经 err 外显) */ + addFiles(files: File[]): void; + removeAtt(i: number): void; + /** 视图侧错误外显(如原生拖放读文件失败),走 err 横幅 */ + notify(text: string): void; /** 中断当前执行(user-cancel,不终止任务) */ cancel(): void; /** 终止任务(REST stop;确认交互在视图) */ @@ -434,6 +464,12 @@ export function useCloudTask( const [loadingEarlier, setLoadingEarlier] = useState(false); const [err, setErr] = useState(""); const [queued, setQueuedState] = useState(""); + const [queuedAtts, setQueuedAttsState] = useState([]); + // 待发送附件与上传中计数(附件随消息发出/入队后清空,额度重新起算) + const [atts, setAtts] = useState([]); + const [uploading, setUploading] = useState(0); + // 额度计数含上传中的(并发粘贴/拖入共享额度,state 异步更新看不住) + const attCountRef = useRef(0); // attach 生命周期与轮询解耦:vmStatus 抖动不能反复拆建连接——每次重建 // 都会把 connectCloudTask 内部的重连上限(dialFails/dropCount)清零, // 3s/10s 的轮询节奏快于内部 ~30s 的放弃阈值,表现为永久"断开重连"。 @@ -459,7 +495,10 @@ export function useCloudTask( setStatus, setConnected, setCursorIfEmpty: (c, hasMore) => setCursor((prev) => prev ?? { cursor: c, hasMore }), - setQueued: setQueuedState, + setQueued: (text, queueAtts) => { + setQueuedState(text); + setQueuedAttsState(queueAtts); + }, setErr, bumpAttachEpoch: () => setAttachEpoch((e) => e + 1), pin: () => { @@ -505,6 +544,8 @@ export function useCloudTask( setCursor(null); setErr(""); setInput(""); + setAtts([]); + attCountRef.current = 0; pinnedRef.current = true; let alive = true; void (async () => { @@ -592,8 +633,47 @@ export function useCloudTask( const send = () => { const text = input.trim(); if (!text || ended) return; + // 上传还没落定就发送,消息会带着半套附件出门:拦下并外显 + if (uploading > 0) { + setErr("附件上传中,请稍候再发送"); + return; + } setInput(""); - core.send(text); + const sendAtts = atts.map(({ url, filename }) => ({ url, filename })); + setAtts([]); + attCountRef.current = 0; + core.send(text, sendAtts); + }; + + // 附件逐个上传(与本地会话 addFiles 语义对齐:超限/失败经 err 外显, + // 成功即出现在待发条;上传中计数供发送拦截与 spinner) + const addFiles = (files: File[]) => { + if (ended) return; + void (async () => { + for (const f of files) { + if (attCountRef.current >= MAX_CLOUD_ATTS) { + setErr(`一条消息最多 ${MAX_CLOUD_ATTS} 个附件`); + break; + } + attCountRef.current += 1; + setUploading((n) => n + 1); + try { + const att = await uploadCloudFile(f); + setAtts((prev) => [...prev, att]); + setErr(""); + } catch (e) { + attCountRef.current -= 1; + setErr("附件上传失败: " + (e instanceof Error ? e.message : String(e))); + } finally { + setUploading((n) => n - 1); + } + } + })(); + }; + + const removeAtt = (i: number) => { + attCountRef.current = Math.max(0, attCountRef.current - 1); + setAtts((prev) => prev.filter((_, j) => j !== i)); }; // 任务结束时还压着排队消息:外显提醒,不静默丢 @@ -679,8 +759,14 @@ export function useCloudTask( input, setInput, queued, + queuedAtts: queuedAtts.length, clearQueued: () => core.clearQueued(), send, + atts, + uploading, + addFiles, + removeAtt, + notify: setErr, cancel: () => core.cancelRun(), stopTask, answerAsk: (askId, answers) => core.answerAsk(askId, answers),