diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d4ce4f71..6434ba7b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,98 @@ # Changelog +## [v1.0.8] - 2026-10-19 + +- chore: bump version to 0.7.19 (81158b7e) +- style(markdown): 内联代码改用 flex 居中 + 细描边的紧凑 chip (8032ff23) +- style(markdown): 内联代码改成传统 chip 样式(等宽 + 淡底 + 内边距) (7120317f) +- style(markdown): 内联代码改成传统样式(等宽 + 淡底 chip,颜色继承正文) (236c65f9) +- fix(chat): 修掉文件夹拦截的两个漏洞(i18n 键位置 + 兜底把文件夹捞回来) (9e49a4cb) +- fix(chat): 拖入文件夹一律拦下,不再发起上传 (24956292) +- change(settings): HTML 渲染默认改为关闭 (ea9750d9) +- refactor(preview): 确认弹层去掉体积兜底,diff 永远照常渲染 (996ce0a9) +- refactor(preview): 确认弹层去掉「保存/放弃」的说明文案 (14b6118f) +- refactor(preview): 删掉编辑态的保存状态栏 (8b3af9f2) +- refactor(preview): 确认弹层改用工具卡片那套 DiffView(文件名/统计/全屏) (36e31e54) +- style(panels): 统一右侧面板标签头部动作图标的配色 (934818b2) +- fix(hooks): useAutoRefresh 真的调用 onFilesystemChanged(B4 之前是死代码) (8e24a6a3) +- test(preview): 补保存事务的自动化测试(需求三 F14 第一批) (627da35c) +- feat(preview): 写入安全边界 + 混合行尾兜底(需求三 E12/13、D10) (6a5b25cf) +- feat(preview): 关闭拦截 + 保存状态栏(需求三 C7/C8) (372a506f) +- feat(preview): 外部改动落到界面 + 写后校验(需求三 B4/B6) (601e24d0) +- feat(preview): 外部改动捕获 + 自写抑制(需求三 B4/B5 数据通路) (79f27baf) +- feat(preview): 保存 / 放弃改动都走带 diff 的二次确认 (2b662d17) +- fix(preview): 编辑态优先于预览类型分发,md/html 也能编辑保存 (38f9f897) +- feat(preview): 覆盖前备份 + tab 上的脏/冲突标记 (19bb128c) +- feat(preview): 文件预览编辑模式对齐 PiUI(显式编辑态 + 保存事务) (1d89e9c3) +- feat(preview): 文本预览改成可编辑(需求三 P2.1,保存事务未接入) (f6e8744d) +- refactor(codemirror): 拆出只读/可编辑共用的扩展工厂(行为不变) (fec41484) +- fix(chat): 请求区卡片的头部横线两端留空,与项目面板分隔线一致 (0340252a) +- fix(chat): 网页搜索的选择器补齐展开态细节,控件样式对齐设置页 (99c47a06) +- refactor(chat): 网页搜索源改用项目统一的 DropdownMenu,去掉原生 select (44fad2a6) +- fix(chat): 网页搜索表单改用与权限/提问同款 dock,可收起为胶囊 (c59af43e) +- fix(chat): 网页搜索表单与提问/权限同一个请求区,不再压在输入框上 (7744b014) +- chore: bump version to 0.7.18 (9f244dc4) +- feat(desktop): 桌面端附件改由 Rust 流式上传,桌面也拿到真实进度 (a3ff755f) +- feat(chat): 上传进度(浏览器走 XHR),整个胶囊当进度条 (7965fb93) +- test(chat): 补桌面端选择器内联媒体与模型不支持时的用例 (0ca88969) +- feat(chat): 桌面端「选文件」与拖入共用同一条附件判定 (d70bed82) +- feat(chat): 直引本机路径前先问服务端读不读得到 (888f379b) +- feat(chat): 本机实例拖入文件不再走上传(需求二) (662c56bd) +- fix(message): 气泡与回填不再显示附件的路径引用行 (e3ef17f5) +- feat(chat): 拖入任意文件走上传,失败可见可重试(Issue #182) (d758b3fa) +- feat(message): 路径型附件注入文本引用与 metadata.attachments(Issue #182) (8e321888) +- feat(api): 任意文件上传与附件三路分发(Issue #182) (f4f4d84f) +- feat(settings): 配置编辑器改为 OpenCode v2 配置 schema (7ae730d8) +- chore: bump version to 0.7.17 (df48d76f) +- fix(chat): 会话还 busy 时过程壳不再提前收成「已处理」 (6596015f) +- fix(message): step 完成信息改为消息级末尾一行,不再因末尾是正文而整块丢失 (42cdac7b) +- fix(chat): 进入会话时可靠对齐输入框模型 (5cb5c39c) +- fix(markdown): 修正 CJK 强调闭合、货币 $、脚注与任务列表解析 (19daea72) +- fix(message): 移动端不再把 agent 徽标撑高(内联紧凑按钮退出 32px 最小点击区域) (9176a514) +- feat(chat): 会话操作收进标题菜单,去掉弹窗头部横线 (f4a7d7c4) +- fix(sessions): 已回复的权限/提问不再被快照重放复活,清掉侧边栏残留徽标 (be027569) +- fix(ui): 边缘渐隐改用 mask,避开 Tailwind v4 渐变在 oklab 下的色带分层 (8e86eee6) +- feat(chat): 输入框 ↑↓ 优先翻阅当前会话自己的历史输入 (0fe07571) +- feat(settings): 新增「渲染 HTML 内容」开关,可关闭 AI 输出的 HTML 活渲染 (aae118ad) +- feat(sessions): shell 库存接入全局事件直写,挂载/摘下的实时性对齐官方 (1ed2b55f) +- fix(message): followShellOutput UTF-8 边界自愈,修流式输出的中文乱码 (cd3a793c) +- feat(message): bash/shell 工具卡运行中实时输出跟随 (31cb107a) +- feat(sessions): shell 输出弹窗复用信息流沉浸模式工具卡 (146db2a3) +- feat(sessions): 后台 shell 在跑的 idle 会话也算活跃,进活跃 tab (70db9fa8) +- fix(sessions): shell 库存按工作区目录取数,挂载覆盖文件夹/活跃列表 (2f204f26) +- feat(sessions): 后台 shell 挂到侧边栏父会话下,活着就算会话活跃 (aff816d5) +- chore: bump version to 0.7.16 (9796c8ee) +- fix(chat): 队列操作行插队按钮挪到行首 (80cb042f) +- fix(chat): 队列操作图标对齐用户消息 action bar 规格 (27adc4a9) +- fix(chat): 队列长文本折叠复用 CollapsibleUserText,不再搞特殊 (37a52d5e) +- fix(chat): @ 提及的附件 url 补 file:// scheme,修发送 400 (24e90dae) +- test(chat): 修 RetryStatusInline 倒计时测试的时序 flake (d19c9cfa) +- fix(chat): 队列气泡渲染附件胶囊,和普通用户消息同款 (de3269d8) +- refactor(chat): 会话移动菜单从下拉改成 Dialog (e3a79d35) +- feat(chat): 对话列/输入框左缘拖拽调宽(两个独立把手,dsh 样式) (622c0e32) +- feat(chat): 队列消息可折叠,默认折叠/展开有设置开关 (79db1df6) +- feat(chat): shell 模式给「真心想输入 !」留退路,并写进输入框提示 (78c9d12f) +- feat(chat): 发送改为官方时序——提交即清空、后台发送、失败恢复 (e253d45a) +- fix(chat): 失败 idle 标记不再被可见性过滤掉(错误不渲染的最后一环) (f1470a04) +- fix(chat): 会话级错误(失败 idle 标记)渲染成错误卡片 (054e554a) +- feat(plugins): 插件面板显示所有插件的来源位置,头部横线对齐 MCP 面板 (56e7ffb2) +- feat(changes): 文件变更面板改为事件驱动刷新,刷新无感 (e3650e30) +- fix(sessions): fork 出的新会话实时进列表,不用手动刷新 (62b01d92) +- fix(session): deep undo 刷新后正确隐藏已撤销消息并保留 redo (4efc8b60) +- fix(chat): fork 用户消息后新会话输入框预填恢复 (17979ef2) +- fix(session): 刷新后从 Session.Info.revert 重建 undo/redo 状态 (b9780d49) +- feat(message): 压缩消息补 step 完成信息,操作条按其下排列(对齐助手) (474c529c) +- fix(message): 压缩消息的 undo 按钮真正拿到 onUndo/canUndo (bc5a375c) +- feat(message): 压缩结果展开后支持 undo / 分叉 / 复制操作条 (e3d4c6f3) +- feat(message): 上下文压缩改为单标识 + 可收起 + 结束后自动收起 (49c63e64) +- fix(permissions): 他端批准权限后非文件权限卡片不再残留按钮 (77f8ac0c) +- fix(diff): patch 还原的合成间隙区域不再渲染折叠条 (f3a56376) +- fix(diff): ContentBlock/SessionChangesPanel 也按 @@ 绝对行号还原 (bafeb95d) +- fix(diff): 按 patch 的 @@ 绝对行号还原 before/after (6833baa4) +- fix(chat): truncate the load-error stack shown in the UI (b9dcdd7e) +- fix(permissions): show the diff preview before approving edit/write (1ca87a18) +- fix(startup): wait for the local service before loading a session (2c3b698e) + ## [v1.0.7] - 2026-10-17 - feat(sidebar): add Context usage tab as third right-sidebar page (8420e7af) diff --git a/package-lock.json b/package-lock.json index 4be67e2a6..06ab9d188 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "1.0.7", + "version": "1.0.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "1.0.7", + "version": "1.0.8", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index aab62ae54..c2e707921 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "1.0.7", + "version": "1.0.8", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 42b205602..9578ed199 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "1.0.7" +version = "1.0.8" dependencies = [ "futures-util", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7ca3b3a45..412076913 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "1.0.7" +version = "1.0.8" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" @@ -35,7 +35,7 @@ tauri-plugin-opener = "2" tauri-plugin-single-instance = "2" tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time", "process"] } tokio-tungstenite = { version = "0.24", features = ["rustls-tls-webpki-roots"] } -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } uuid = { version = "1", features = ["v4"] } [build-dependencies] diff --git a/src-tauri/src/app/commands/mod.rs b/src-tauri/src/app/commands/mod.rs index 6e3cf288a..cdea9abb8 100644 --- a/src-tauri/src/app/commands/mod.rs +++ b/src-tauri/src/app/commands/mod.rs @@ -5,6 +5,8 @@ pub mod opencode; pub mod service; #[cfg(not(target_os = "android"))] pub mod utils; +#[cfg(not(target_os = "android"))] +pub mod upload; #[cfg(target_os = "windows")] pub mod wsl_types; #[cfg(target_os = "windows")] diff --git a/src-tauri/src/app/commands/upload.rs b/src-tauri/src/app/commands/upload.rs new file mode 100644 index 000000000..9d7e07b9e --- /dev/null +++ b/src-tauri/src/app/commands/upload.rs @@ -0,0 +1,131 @@ +// ============================================ +// 附件上传(Issue #182):Rust 侧流式发送 + 进度事件 +// +// 为什么不在 webview 里用 XHR:桌面端 webview 的跨源请求受 CORS / 私有网络 +// 策略约束,不可靠;而经 tauri-plugin-http 的 fetch 又拿不到上传进度。 +// 这里由 Rust 直接发请求: +// - 不受 webview 的同源策略限制(请求由 Rust 进程发出) +// - 边读文件边发(`Body::wrap_stream`,chunked),不把整份文件读进内存 +// - 每读一块就通过 Channel 推一次进度 +// +// 服务端契约(已在真实 2.0.29 服务端验证): +// - `POST /api/experimental/fs/write?path=<目标>&location[directory]=<目录>` +// - body 为原始字节;**接受 chunked**(无 Content-Length 也可以) +// - 200 返回 `{ data: { path } }`,path 是服务端规范化后的绝对路径 +// - 密码走 Basic(用户名固定 opencode) +// ============================================ + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use futures_util::StreamExt; +use serde::Serialize; +use tauri::ipc::Channel; +use tokio_util::io::ReaderStream; + +#[derive(Clone, Serialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum UploadEvent { + Progress { loaded: u64, total: u64 }, +} + +#[derive(Serialize)] +pub struct UploadResult { + pub path: String, + pub size: u64, +} + +/// 把本机文件流式上传到服务端临时目录,返回服务端返回的规范化路径。 +/// +/// 错误文案与前端 `classifyUploadFailure` 的识别规则对齐: +/// - `Upload failed: network error (...)` → network +/// - `Upload failed with status 401/403/5xx` → unauthorized / server +#[tauri::command] +pub async fn upload_attachment( + url: String, + target: String, + source_path: String, + password: Option, + directory: Option, + on_event: Channel, +) -> Result { + let size = tokio::fs::metadata(&source_path) + .await + .map_err(|e| format!("Cannot read local file: {e}"))? + .len(); + + let file = tokio::fs::File::open(&source_path) + .await + .map_err(|e| format!("Cannot read local file: {e}"))?; + + let loaded = Arc::new(AtomicU64::new(0)); + let stream = ReaderStream::new(file).map({ + let loaded = Arc::clone(&loaded); + let on_event = on_event.clone(); + move |chunk| { + if let Ok(bytes) = &chunk { + let sent = loaded.fetch_add(bytes.len() as u64, Ordering::Relaxed) + bytes.len() as u64; + // 进度发失败(窗口已关)不影响上传本身 + let _ = on_event.send(UploadEvent::Progress { + loaded: sent, + total: size, + }); + } + chunk + } + }); + + let mut endpoint = + reqwest::Url::parse(&format!("{}/api/experimental/fs/write", url.trim_end_matches('/'))) + .map_err(|e| format!("Invalid server url: {e}"))?; + { + let mut query = endpoint.query_pairs_mut(); + query.append_pair("path", &target); + if let Some(directory) = directory.as_deref().filter(|value| !value.is_empty()) { + query.append_pair("location[directory]", directory); + } + } + + let client = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(15)) + .build() + .map_err(|e| format!("Failed to create HTTP client: {e}"))?; + + let mut request = client + .post(endpoint) + .header(reqwest::header::CONTENT_TYPE, "application/octet-stream") + .body(reqwest::Body::wrap_stream(stream)); + + if let Some(password) = password.as_deref().filter(|value| !value.is_empty()) { + request = request.basic_auth("opencode", Some(password)); + } + + let response = request + .send() + .await + .map_err(|e| format!("Upload failed: network error ({e})"))?; + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + + if !status.is_success() { + return Err(format!("Upload failed with status {}", status.as_u16())); + } + + let parsed: serde_json::Value = + serde_json::from_str(&body).map_err(|e| format!("Invalid upload response: {e}"))?; + let path = parsed + .get("data") + .and_then(|data| data.get("path")) + .and_then(|path| path.as_str()) + .unwrap_or(&target) + .to_string(); + + // 收尾补一个 100%,避免最后一个分块事件被合并掉时进度停在 99% + let _ = on_event.send(UploadEvent::Progress { + loaded: size, + total: size, + }); + + Ok(UploadResult { path, size }) +} diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs index cb52ff411..1be709c70 100644 --- a/src-tauri/src/app/mod.rs +++ b/src-tauri/src/app/mod.rs @@ -471,6 +471,8 @@ pub fn run() { commands::utils::get_dropped_paths_info, commands::utils::open_new_window, commands::utils::desktop_window_ready, + // 附件上传:Rust 侧流式发送(桌面端拿不到 webview 的上传进度) + commands::upload::upload_attachment, commands::opencode::check_opencode_service, commands::opencode::detect_opencode_binary, commands::opencode::start_opencode_service, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ce76175b7..d37d62adc 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "OpenCode", - "version": "1.0.7", + "version": "1.0.8", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", diff --git a/src/App.tsx b/src/App.tsx index ad0981a5f..1dc21328c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -916,7 +916,7 @@ function App() { handleToggleFocusedPaneFullscreen, ]) - const { showCloseDialog, handleCloseDialogConfirm, handleCloseDialogCancel } = useCloseServiceDialog() + const { showCloseDialog, handleCloseDialogConfirm, handleCloseDialogCancel, hasUnsavedChanges } = useCloseServiceDialog() return (
@@ -1112,6 +1112,7 @@ function App() { isOpen={showCloseDialog} onConfirm={handleCloseDialogConfirm} onCancel={handleCloseDialogCancel} + hasUnsavedChanges={hasUnsavedChanges} /> diff --git a/src/api/config.ts b/src/api/config.ts index bc5f69a9d..16659ff3e 100644 --- a/src/api/config.ts +++ b/src/api/config.ts @@ -26,7 +26,7 @@ import { getSDKClient } from './sdk' import { locationParam } from './location' -import type { ConfigSource, ConfigInfo, ConfigShellsResponse } from './types' +import type { ConfigDocument, ConfigSource, ConfigInfo, ConfigShellsResponse } from './types' /** * 获取配置来源清单。 @@ -49,19 +49,41 @@ export async function getConfig(directory?: string, serverId?: string): Promise< return mergeConfigInfo(sources) } +/** 官方探测的可写文档名,按优先级从低到高(写存在的最后一个)。 */ +const CONFIG_DOCUMENT_NAMES = ['opencode.json', 'opencode.jsonc'] + +function isDocument(source: ConfigSource): source is ConfigDocument { + return source.type === 'document' +} + /** - * 获取全局(无 location)配置。 + * 取全局来源(第一个 `type: 'directory'` 标记之前)。 * * 不带 location 的 `config.get()` 也会返回默认 location 的项目级来源, - * 「全局配置」只是第一个 `type: 'directory'` 标记**之前**的条目 - * (与官方 app 的 general settings 控制器一致),否则项目级配置会 - * 混进全局视图,保存时还可能写错文件。 + * 项目来源从那个 directory 条目开始(与官方 core 的 `Config.load` 一致)。 + */ +function globalSources(sources: ConfigSource[]): ConfigSource[] { + const boundary = sources.findIndex(source => source.type === 'directory') + return boundary === -1 ? sources : sources.slice(0, boundary) +} + +/** 拼一个配置文档路径,兼顾 Windows 与 POSIX 分隔符。 */ +function joinDocumentPath(directory: string, name: string): string { + const trimmed = directory.replace(/[\\/]+$/, '') + const separator = trimmed.includes('\\') ? '\\' : '/' + return `${trimmed}${separator}${name}` +} + +/** + * 获取全局(无 location)配置。 + * + * 只合并**有 `path` 的全局文档**:wellknown 远程文档没有 `path`, + * 把它们的值当成可编辑基线会让用户不小心写进本地文件。 */ export async function getGlobalConfig(serverId?: string): Promise { const sdk = getSDKClient(serverId) const sources = await sdk.config.get() - const boundary = sources.findIndex(source => source.type === 'directory') - return mergeConfigInfo(boundary === -1 ? sources : sources.slice(0, boundary)) + return mergeConfigInfo(globalSources(sources).filter(source => isDocument(source) && Boolean(source.path))) } /** @@ -92,47 +114,43 @@ export async function updateShell(shell: string | null, serverId?: string): Prom } /** - * 定位可写的配置文档。 + * 定位全局可写配置文档。 * - * v2 把可写配置收敛了:`config.update` 只接受 `{ shell }`, - * 任意字段的保存没有 API。但 `config.get()` 会返回文档及其 `path`, - * 因此「写配置」在 v2 里的原生做法是直接写那个文件。 + * 官方 `Config.update` 的写入目标是**全局配置目录**里的 + * `opencode.json` → `opencode.jsonc`,取其中存在的最后一个; + * 都不存在时新建 `opencode.jsonc`(见 core 的 `ConfigDiscovery.names` 与 `Config.update`)。 + * 这里与官方保持一致——不写项目级文档,避免编辑器把全局设置落到项目里。 * - * @returns 文档路径;找不到文档时为 undefined + * @returns 待写路径 */ -export async function findConfigDocumentPath( - directory?: string, - serverId?: string, -): Promise { - const sources = await getConfigSources(directory, serverId) - const documents = sources.filter( - (source): source is Extract => source.type === 'document', - ) - // 取最后一个文档:合并顺序里它优先级最高,写入它才不会被别的来源覆盖 - return documents[documents.length - 1]?.path +export async function findGlobalConfigDocumentPath(serverId?: string): Promise { + const sdk = getSDKClient(serverId) + const sources = await sdk.config.get() + const global = globalSources(sources) + // 优先级顺序里最后一个存在的文档,写入它才不会被更低的来源覆盖 + const target = global.filter(isDocument).filter(source => source.path).at(-1) + if (target?.path) return target.path + + const directory = global.find(source => source.type === 'directory') + if (directory) return joinDocumentPath(directory.path, CONFIG_DOCUMENT_NAMES[CONFIG_DOCUMENT_NAMES.length - 1]) + + throw new Error('No global config directory found') } /** - * 把配置对象写回其文档文件。 + * 把配置对象写回**全局**配置文档。 * * ⚠️ 这是整文件写入:会以标准 JSON 覆盖原文件,**JSONC 注释与原始排版会丢失**。 * v2 没有字段级写入接口,这是唯一能真正持久化配置的途径。 * * @returns 写入的路径 */ -export async function writeConfigDocument( - config: ConfigInfo, - directory?: string, - serverId?: string, -): Promise { - const path = await findConfigDocumentPath(directory, serverId) - if (!path) { - throw new Error('No writable config document found') - } +export async function writeGlobalConfigDocument(config: ConfigInfo, serverId?: string): Promise { + const path = await findGlobalConfigDocumentPath(serverId) const sdk = getSDKClient(serverId) const payload = new TextEncoder().encode(`${JSON.stringify(config, null, 2)}\n`) - await sdk.file.write({ path, payload, location: locationParam(directory, serverId) }) + await sdk.file.write({ path, payload }) return path } diff --git a/src/api/events.test.ts b/src/api/events.test.ts index 679356da4..963bd0fba 100644 --- a/src/api/events.test.ts +++ b/src/api/events.test.ts @@ -352,4 +352,33 @@ describe('v2 event dispatch', () => { unsubscribe() }) + + /** + * 从未连上过(本地 serve 启动竞态:初始拉取在端点就绪前已失败), + * 端点变更强制重连后的首个成功连接也必须广播补偿,否则失败态不自愈。 + */ + it('broadcasts onReconnected on first connect after reconnectServerSSE when never connected', async () => { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, reconnectServerSSE } = await import('./events') + const onReconnected = vi.fn() + const unsubscribe = subscribeToServerEvents('test-server', { onReconnected }) + await Promise.resolve() + + // 首条流不推任何事件 → hasConnectedBefore 保持 false(从未连上) + reconnectServerSSE('test-server') + await Promise.resolve() + expect(harnesses.length).toBe(2) + + harnesses[1].emit(v2Event('session.idle', { sessionID: 's1' })) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(onReconnected).toHaveBeenCalledWith('server-switch') + + unsubscribe() + }) }) diff --git a/src/api/events.ts b/src/api/events.ts index 0122f1ed4..eb4807bb7 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -66,6 +66,15 @@ const connectionListeners = new Map void>> /** 是否因为切换服务器而触发的重连(按 serverId) */ const serverSwitchFlags = new Map() +/** + * 端点变更(reconnectServerSSE)触发、但此前从未成功连接过的重连(按 serverId)。 + * 与 serverSwitchFlags 分开:subscribeToEvents 切服务器也用后者,那条链路的 + * 数据刷新由 server-change 监听器负责,首个连接不能重复广播;而这里针对的是 + * 「本地 serve 就绪地址回写 / WSL 换端口后,初始拉取已在端点就绪前失败」, + * 首个成功连接必须广播让订阅者补偿拉取,否则失败态没有重试入口。 + */ +const endpointReconnectFlags = new Map() + let lifecycleListenersRegistered = false let isInBackground = false let keepaliveTimer: ReturnType | null = null @@ -338,6 +347,15 @@ function dispatchEvent(callbacks: EventCallbacks, event: GlobalEvent): void { case 'session.shell.ended': callbacks.onShellEnded?.(event.data, facts) break + case 'shell.created': + callbacks.onShellInventoryCreated?.(event.data, event.location) + break + case 'shell.exited': + callbacks.onShellInventoryExited?.(event.data, event.location) + break + case 'shell.deleted': + callbacks.onShellInventoryDeleted?.(event.data, event.location) + break case 'session.skill.activated': callbacks.onSkillActivated?.(event.data, facts) break @@ -563,15 +581,20 @@ async function connectServer(serverId: string): Promise { if (!conn.hasConnectedBefore) { conn.hasConnectedBefore = true - // 首次连接不广播 onReconnected:初始加载由各订阅方自己拉取; - // 若本次连接是服务器切换后的重连,清掉标记即可(切服务器的 - // 数据刷新由 server-change 链路负责) + // 首次连接一般不广播 onReconnected:初始加载由各订阅方自己拉取。 + // 但端点变更触发的重连(本地 serve 就绪 / WSL 换端口),此前的初始 + // 拉取可能已在端点就绪前失败,必须广播让订阅者补偿拉取。 + const endpointReconnect = endpointReconnectFlags.get(serverId) === true + endpointReconnectFlags.delete(serverId) serverSwitchFlags.delete(serverId) updateConnectionState(serverId, { state: 'connected', reconnectAttempt: 0, error: undefined, }) + if (endpointReconnect) { + broadcastReconnected(conn, 'server-switch') + } } else if (conn.info.state !== 'connected') { updateConnectionState(serverId, { state: 'connected', reconnectAttempt: 0, error: undefined }) // 掉线后的**重连成功**:断线窗口错过的事件协议明确不补发, @@ -730,6 +753,9 @@ export function reconnectServerSSE(serverId: string): void { if (hadConnected) { conn.hasConnectedBefore = true serverSwitchFlags.set(serverId, true) + } else { + // 此前从未连上:首个成功连接也要走补偿广播(见 endpointReconnectFlags 注释) + endpointReconnectFlags.set(serverId, true) } if (conn.subscribers.size > 0) { connectServer(serverId) diff --git a/src/api/file.ts b/src/api/file.ts index 03fffa49a..be2dfc9a7 100644 --- a/src/api/file.ts +++ b/src/api/file.ts @@ -18,6 +18,9 @@ import { getSDKClient } from './sdk' import { locationParam } from './location' +import { getApiBaseUrl, getAuthHeader } from './http' +import { fileBaseName } from '../utils/pathUtils' +import { isTauri } from '../utils/tauri' import type { FileContent, FileNode, FileStatusItem } from './types' import { serverStore } from '../store/serverStore' @@ -191,6 +194,276 @@ export async function writeFileBytes( await sdk.file.write({ path, payload, location: locationParam(directory, serverId) }) } +// ============================================ +// 附件上传(Issue #182:拖入任意文件 → 服务端临时目录 → 路径附件) +// +// `fs.write` 是 experimental 且**不受 location 限制**:它能写到任意绝对 +// 路径、自动建父目录。附件上传是它唯一的新业务调用点,因此全部收口在本文件。 +// ============================================ + +/** 服务端临时目录(`server.info().paths.tmp`)按 serverId 缓存 */ +const serverTmpDirectoryCache = new Map() + +/** + * 取服务端的临时目录绝对路径。 + * + * 这是官方钦定的附件落点:core 的内置指令让模型优先使用它,默认 agent + * 权限里 `/*` 也是 allow(通配符跨目录分隔符)——因此模型读上传 + * 文件不会弹外部目录批准框。 + */ +export async function getServerTmpDirectory(serverId?: string): Promise { + const cacheKey = serverId ?? serverStore.getActiveServerId() + const cached = serverTmpDirectoryCache.get(cacheKey) + if (cached) return cached + + const sdk = getSDKClient(serverId) + const info = await sdk.server.info() + const tmp = info.paths?.tmp + if (!tmp) throw new Error('Server did not report a temporary directory') + + serverTmpDirectoryCache.set(cacheKey, tmp) + return tmp +} + +/** 清理临时目录缓存(服务器切换 / 单测) */ +export function clearServerTmpDirectoryCache(): void { + serverTmpDirectoryCache.clear() +} + +/** + * 生成上传目录名。 + * + * `crypto.randomUUID` 只在安全上下文可用,而本应用可能被局域网 http + * (`http://192.168.x.x`)访问,此时它是 undefined → 必须有兜底。 + */ +export function createUploadId(): string { + const cryptoApi = globalThis.crypto + if (cryptoApi && typeof cryptoApi.randomUUID === 'function') { + try { + return cryptoApi.randomUUID() + } catch { + // 非安全上下文:走下面的兜底 + } + } + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` +} + +/** 只保留最后一段文件名,去掉路径分隔符与各平台保留字符 */ +function sanitizeUploadFilename(filename: string): string { + const base = filename.split(/[/\\]/).pop() ?? '' + // 先剔除控制字符(避免正则里的控制字符类),再替换各平台保留字符 + const printable = Array.from(base) + .filter(char => char.charCodeAt(0) > 31) + .join('') + const cleaned = printable.replace(/[<>:"|?*]/g, '_').trim() + return cleaned || 'file' +} + +export interface UploadAttachmentOptions { + /** + * 上传进度(0~1)。 + * + * 给了它并且不在 Tauri 里时走 `XMLHttpRequest`:fetch 无法上报上传进度, + * 而 XHR 可以直接把 `File` 交给浏览器从磁盘流式发送(渲染进程不驻留整份文件)。 + * 桌面端仍走 SDK(`@tauri-apps/plugin-http`,经 Rust 发包,不受 CORS 限制), + * 代价是没有进度——要进度得在 Rust 侧实现。 + */ + onProgress?: (fraction: number) => void + signal?: AbortSignal +} + +/** + * 用 XHR 写文件(浏览器侧的唯一理由:真实上传进度 + 流式发 File)。 + * + * 官方 app 也是这么做的(packages/app/src/composer/attachments/destination.ts:43-61): + * "fetch cannot report upload progress and Chromium only streams request bodies over HTTP/2"。 + */ +function writeWithXhr(input: { + url: string + body: Blob + authorization?: string + onProgress: (fraction: number) => void + signal?: AbortSignal +}): Promise { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest() + xhr.open('POST', input.url) + xhr.responseType = 'json' + xhr.setRequestHeader('content-type', 'application/octet-stream') + if (input.authorization) xhr.setRequestHeader('authorization', input.authorization) + + xhr.upload.addEventListener('progress', event => { + const total = event.lengthComputable ? event.total : input.body.size + if (total > 0) input.onProgress(Math.min(1, event.loaded / total)) + }) + + xhr.addEventListener('load', () => { + if (xhr.status !== 200) { + reject(new Error(`Upload failed with status ${xhr.status}`)) + return + } + const resolved = (xhr.response as { data?: { path?: string } } | null)?.data?.path + resolve(resolved || '') + }) + xhr.addEventListener('error', () => reject(new Error('Upload failed: network error'))) + xhr.addEventListener('abort', () => reject(new DOMException('Upload aborted', 'AbortError'))) + + if (input.signal) { + if (input.signal.aborted) { + xhr.abort() + return + } + input.signal.addEventListener('abort', () => xhr.abort(), { once: true }) + } + + xhr.send(input.body) + }) +} + +/** 上传目标:`{tmp}/uploads//<清洗后的文件名>`(每次单独一层 uuid 目录) */ +async function buildUploadTarget(serverId: string | undefined, filename: string): Promise { + const tmp = await getServerTmpDirectory(serverId) + return `${tmp.replace(/[/\\]+$/, '')}/uploads/${createUploadId()}/${sanitizeUploadFilename(filename)}` +} + +/** Tauri 侧 Rust 上传命令的进度事件(见 src-tauri/src/app/commands/upload.rs) */ +interface RustUploadEvent { + type: 'progress' + loaded: number + total: number +} + +/** + * 上传**本机文件**(桌面端拖入 / 选择器拿到的是绝对路径)。 + * + * Tauri 下走 Rust 命令:reqwest 流式发送 + 进度事件。这样做有三个好处: + * 不把整份文件读进渲染进程、不受 webview 同源策略约束、有真实进度。 + * 非 Tauri 环境理论到不了这里(浏览器拿不到真实路径),退化为读字节上传。 + */ +export async function uploadLocalFile( + sourcePath: string, + filename: string, + directory?: string, + serverId?: string, + options: UploadAttachmentOptions = {}, +): Promise<{ path: string; size: number }> { + const target = await buildUploadTarget(serverId, filename) + + if (isTauri()) { + const { Channel, invoke } = await import('@tauri-apps/api/core') + + const channel = new Channel() + channel.onmessage = event => { + if (event.type === 'progress' && event.total > 0) { + options.onProgress?.(Math.min(1, event.loaded / event.total)) + } + } + + const auth = serverId ? serverStore.getServerAuth(serverId) : serverStore.getActiveAuth() + const result = await invoke<{ path: string; size: number }>('upload_attachment', { + url: getApiBaseUrl(serverId), + target, + sourcePath, + password: auth?.password ?? null, + directory: directory ?? null, + onEvent: channel, + }) + + return { path: result?.path || target, size: result?.size ?? 0 } + } + + const { readFile } = await import('@tauri-apps/plugin-fs') + const bytes = await readFile(sourcePath) + return uploadAttachment(bytes, filename, directory, serverId, options) +} + +/** + * 上传附件到服务端临时目录,返回**服务端上的绝对路径**与字节数。 + * + * 用响应的 `data.path`,不要用自己拼的路径:服务端会规范化分隔符 + * (Windows 路径尤其重要)。每次上传单独一层 uuid 目录,避免同名覆盖。 + */ +export async function uploadAttachment( + payload: Blob | Uint8Array, + filename: string, + directory?: string, + serverId?: string, + options: UploadAttachmentOptions = {}, +): Promise<{ path: string; size: number }> { + const target = await buildUploadTarget(serverId, filename) + + // 浏览器 + 要进度 → XHR(File 直接交给浏览器流式发送) + if (options.onProgress && !isTauri() && typeof XMLHttpRequest !== 'undefined') { + // 拷贝一份独立 buffer,避免 SharedArrayBuffer 后端类型与 BlobPart 不兼容 + const body: Blob = ArrayBuffer.isView(payload) + ? new Blob([payload.slice().buffer as ArrayBuffer]) + : payload + const base = getApiBaseUrl(serverId).replace(/\/+$/, '') + + // 目录缺省时不带 location,交给服务端回落自己的默认工作目录 + const params = new URLSearchParams({ path: target }) + if (directory) params.set('location[directory]', directory) + + const resolved = await writeWithXhr({ + url: `${base}/api/experimental/fs/write?${params}`, + body, + authorization: getAuthHeader(serverId)['Authorization'], + onProgress: options.onProgress, + signal: options.signal, + }) + + return { path: resolved || target, size: body.size } + } + + // ArrayBuffer.isView 是跨 realm 安全的 brand check(`instanceof Uint8Array` + // 在跨 window/worker 传进来的 typed array 上会失手) + const bytes = ArrayBuffer.isView(payload) + ? new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength) + : new Uint8Array(await payload.arrayBuffer()) + + const sdk = getSDKClient(serverId) + const result = await sdk.file.write({ + path: target, + payload: bytes, + location: locationParam(directory, serverId), + }) + + const resolved = result?.data?.path + return { path: resolved || target, size: bytes.byteLength } +} + +/** + * 服务端能不能读到这个路径。 + * + * 桌面端拖入的文件里存的是**客户端**的绝对路径;能不能直接把它交给服务端引用, + * 取决于服务端进程是否也看得见这个路径——这与「URL 是不是 localhost」并不等价: + * - 本机但用**局域网地址**连自己 → URL 判非本地,实际同机(能读到) + * - 容器把端口映射到回环 → URL 判本地,容器里读不到宿主路径(读不到) + * 所以直接问服务端最可靠:列一次父目录,看目标条目在不在。 + * + * 任何异常(目录不存在、无权限、服务端不可达)都按「读不到」处理。 + */ +export async function probeServerPath(path: string, directory?: string, serverId?: string): Promise { + const name = fileBaseName(path) + const separatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + if (!name || separatorIndex <= 0) return false + + const parent = path.slice(0, separatorIndex) + + try { + const sdk = getSDKClient(serverId) + const result = await sdk.file.list({ + location: locationParam(directory, serverId), + path: parent, + }) + // 条目 path 可能是 location 相对路径,也可能是绝对路径(越界列举时实测如此), + // 所以只比最后一段;symlink 也算读得到(服务端能顺着读)。 + return result.data.some(entry => entry.type !== 'directory' && fileBaseName(entry.path) === name) + } catch { + return false + } +} + /** * 获取文件的版本控制状态。 * diff --git a/src/api/file.upload.test.ts b/src/api/file.upload.test.ts new file mode 100644 index 000000000..80011f0b2 --- /dev/null +++ b/src/api/file.upload.test.ts @@ -0,0 +1,433 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +// ============================================ +// 附件上传(Issue #182) +// +// `fs.write` 是 experimental 且不受 location 限制:附件上传是它唯一的新 +// 业务调用点,因此路径拼装、tmp 目录缓存、文件名清洗、uuid 兜底都在 +// api/file.ts 收口,这里逐条锁住行为。 +// ============================================ + +const writeMock = vi.fn(async (_input: unknown) => ({ data: { path: '/srv/tmp/uploads/abc/report.zip' } })) +const infoMock = vi.fn(async () => ({ + version: '2.0.21', + pid: 1, + urls: [], + paths: { tmp: '/srv/tmp' }, +})) +const listMock = vi.fn(async (_input: unknown) => ({ data: [] as Array<{ path: string; type: string }> })) + +vi.mock('./sdk', () => ({ + getSDKClient: () => ({ + file: { write: writeMock, list: listMock }, + server: { info: infoMock }, + }), +})) + +// 进度上传走的是自建 XHR(绕过 SDK),这里只需要固定的 base/auth +vi.mock('./http', () => ({ + getApiBaseUrl: () => 'http://127.0.0.1:49374', + getAuthHeader: () => ({ Authorization: 'Basic test-token' }), +})) + +const readFileMock = vi.fn(async (_path: string) => new Uint8Array([1, 2, 3])) + +vi.mock('@tauri-apps/plugin-fs', () => ({ + readFile: (path: string) => readFileMock(path), +})) + +/** 最小 XHR 假件:记录请求,允许测试驱动 progress/load/error */ +class FakeXhr { + static instances: FakeXhr[] = [] + + method = '' + url = '' + status = 0 + response: unknown = null + responseType = '' + body: unknown = null + aborted = false + headers: Record = {} + + private listeners = new Map void>>() + upload = { + addEventListener: (type: string, handler: (event: { loaded: number; total: number }) => void) => { + this.uploadListeners.set(type, handler) + }, + listeners: new Map void>(), + } + + private uploadListeners = new Map< + string, + (event: { loaded: number; total: number; lengthComputable: boolean }) => void + >() + + constructor() { + FakeXhr.instances.push(this) + } + + open(method: string, url: string) { + this.method = method + this.url = url + } + + setRequestHeader(key: string, value: string) { + this.headers[key.toLowerCase()] = value + } + + addEventListener(type: string, handler: () => void) { + const list = this.listeners.get(type) ?? [] + list.push(handler) + this.listeners.set(type, list) + } + + send(body: unknown) { + this.body = body + } + + abort() { + this.aborted = true + this.emit('abort') + } + + emit(type: string) { + for (const handler of this.listeners.get(type) ?? []) handler() + } + + emitProgress(loaded: number, total: number, lengthComputable = true) { + this.uploadListeners.get('progress')?.({ + loaded, + total: lengthComputable ? total : 0, + lengthComputable, + }) + } + + static last() { + return FakeXhr.instances.at(-1)! + } + + static reset() { + FakeXhr.instances = [] + } +} + +const { clearServerTmpDirectoryCache, createUploadId, getServerTmpDirectory, probeServerPath, uploadAttachment, uploadLocalFile } = + await import('./file') + +function lastWriteInput() { + return writeMock.mock.calls.at(-1)?.[0] as { + path: string + payload: Uint8Array + location?: { directory?: string } + } +} + +describe('uploadAttachment', () => { + beforeEach(() => { + writeMock.mockClear() + infoMock.mockClear() + clearServerTmpDirectoryCache() + }) + + it('写到 {tmp}/uploads//,并返回服务端解析后的路径', async () => { + const payload = new TextEncoder().encode('zip-bytes') + const result = await uploadAttachment(payload, 'report.zip', undefined, 'local') + + const input = lastWriteInput() + expect(input.path.startsWith('/srv/tmp/uploads/')).toBe(true) + expect(input.path.endsWith('/report.zip')).toBe(true) + // 一层 uuid 目录,避免同名覆盖 + expect(input.path.split('/uploads/')[1]?.split('/')).toHaveLength(2) + // 交给 SDK 的是同一份内容(跨 realm 时会重新包一层视图,按字节比较) + expect(Array.from(input.payload)).toEqual(Array.from(payload)) + + // 用服务端回显的路径,而不是自己拼的 + expect(result.path).toBe('/srv/tmp/uploads/abc/report.zip') + expect(result.size).toBe(payload.byteLength) + }) + + it('服务端没回 data.path 时回落到自己拼的路径', async () => { + writeMock.mockResolvedValueOnce({} as never) + const result = await uploadAttachment(new Uint8Array([1, 2, 3]), 'a.bin', undefined, 'local') + expect(result.path).toBe(lastWriteInput().path) + expect(result.size).toBe(3) + }) + + it('tmp 目录按 serverId 缓存(只问一次 server.info)', async () => { + await uploadAttachment(new Uint8Array([1]), 'a.bin', undefined, 'local') + await uploadAttachment(new Uint8Array([1]), 'b.bin', undefined, 'local') + expect(infoMock).toHaveBeenCalledTimes(1) + + await getServerTmpDirectory('local') + expect(infoMock).toHaveBeenCalledTimes(1) + + await uploadAttachment(new Uint8Array([1]), 'c.bin', undefined, 'remote') + expect(infoMock).toHaveBeenCalledTimes(2) + }) + + it('服务端未报告 tmp 目录时明确失败(不静默写到根目录)', async () => { + infoMock.mockResolvedValueOnce({ version: '2.0.21', pid: 1, urls: [], paths: {} } as never) + await expect(uploadAttachment(new Uint8Array([1]), 'a.bin', undefined, 'local')).rejects.toThrow( + /temporary directory/i, + ) + }) + + it('文件名只保留最后一段并清洗保留字符', async () => { + await uploadAttachment(new Uint8Array([1]), '..\\evil/../../pa:|?*.zip', undefined, 'local') + const written = lastWriteInput().path + const name = written.split('/').pop() + + // 只取最后一段(路径穿越被吃掉),控制/保留字符替换为下划线 + expect(name).toBe('pa_th_____.zip') + expect(name).not.toMatch(/[<>:"|?*]/) + expect(written).not.toContain('..') + }) + + it('带目录时带上 location(与既有的 locationParam 收口一致)', async () => { + await uploadAttachment(new Uint8Array([1]), 'a.bin', '/repo/project', 'local') + expect(lastWriteInput().location).toEqual({ directory: '/repo/project' }) + }) +}) + +describe('createUploadId', () => { + it('优先用 crypto.randomUUID', () => { + expect(createUploadId()).toMatch(/^[0-9a-f-]{36}$/) + }) + + it('非安全上下文(randomUUID 抛错)时回落到时间戳 + 随机数', () => { + const original = Object.getOwnPropertyDescriptor(globalThis, 'crypto') + Object.defineProperty(globalThis, 'crypto', { + configurable: true, + value: { + randomUUID: () => { + throw new Error('insecure context') + }, + }, + }) + + try { + const id = createUploadId() + expect(id).toMatch(/^[0-9a-z]+-[0-9a-z]+$/) + expect(id).not.toContain('undefined') + } finally { + if (original) Object.defineProperty(globalThis, 'crypto', original) + } + }) +}) + +// ============================================ +// probeServerPath:服务端能不能读到这个本机路径 +// +// 「URL 是不是 localhost」回答不了这个问题(本机也可能用局域网地址连自己, +// 容器也会把端口映射到回环),所以直接问服务端。 +// ============================================ + +describe('probeServerPath', () => { + beforeEach(() => { + listMock.mockReset() + listMock.mockResolvedValue({ data: [] }) + }) + + it('父目录里存在同名文件 → 读得到(Windows 路径与 `../` 形态条目都能匹配)', async () => { + listMock.mockResolvedValue({ + data: [ + { path: '../../../Temp/opencode/uploads/u1/probe.zip', type: 'file' }, + { path: '../../../Temp/opencode/uploads/u1/sub', type: 'directory' }, + ], + }) + + await expect( + probeServerPath('C:\\Users\\x\\AppData\\Local\\Temp\\opencode\\uploads\\u1\\probe.zip', '/repo', 'local'), + ).resolves.toBe(true) + + expect(listMock).toHaveBeenCalledWith({ + location: { directory: '/repo' }, + path: 'C:\\Users\\x\\AppData\\Local\\Temp\\opencode\\uploads\\u1', + }) + }) + + it('目录里没有该条目 → 读不到', async () => { + listMock.mockResolvedValue({ data: [{ path: '../other/thing.zip', type: 'file' }] }) + await expect(probeServerPath('/host/dl/report.zip')).resolves.toBe(false) + }) + + it('同名但类型是目录 → 读不到', async () => { + listMock.mockResolvedValue({ data: [{ path: '../dl/report.zip', type: 'directory' }] }) + await expect(probeServerPath('/host/dl/report.zip')).resolves.toBe(false) + }) + + it('符号链接也算读得到(服务端能顺着读)', async () => { + listMock.mockResolvedValue({ data: [{ path: '../dl/report.zip', type: 'symlink' }] }) + await expect(probeServerPath('/host/dl/report.zip')).resolves.toBe(true) + }) + + it('服务端不可达 / 目录不存在 → 按读不到处理,不抛错', async () => { + listMock.mockRejectedValue(new Error('Failed to fetch')) + await expect(probeServerPath('/host/dl/report.zip')).resolves.toBe(false) + }) + + it('没有父目录的裸文件名 → 读不到(不去列服务端根目录)', async () => { + await expect(probeServerPath('report.zip')).resolves.toBe(false) + expect(listMock).not.toHaveBeenCalled() + }) +}) + +// ============================================ +// 带进度的上传(浏览器):fetch 报不了上传进度,所以要走 XHR +// 官方做法同款:packages/app/src/composer/attachments/destination.ts:43-61 +// ============================================ + +describe('uploadAttachment — XHR 进度传输', () => { + beforeEach(() => { + writeMock.mockClear() + infoMock.mockClear() + clearServerTmpDirectoryCache() + FakeXhr.reset() + vi.stubGlobal('XMLHttpRequest', FakeXhr) + }) + + function uploadWithProgress(onProgress: (fraction: number) => void, directory?: string) { + return uploadAttachment(new Blob(['zip-bytes']), 'report.zip', directory, 'local', { onProgress }) + } + + /** 起一个上传并等到**这一次**的 XHR 被创建(前面有 await,必须让微任务先跑) */ + async function startUpload(onProgress: (fraction: number) => void, directory?: string) { + const before = FakeXhr.instances.length + const pending = uploadWithProgress(onProgress, directory) + await vi.waitFor(() => { + expect(FakeXhr.instances.length).toBeGreaterThan(before) + }) + return { pending, xhr: FakeXhr.last() } + } + + it('交出 File/Blob 本体(浏览器能从磁盘流式发送),query 带 location 与 path', async () => { + const { pending, xhr } = await startUpload(vi.fn()) + + expect(xhr.method).toBe('POST') + expect(xhr.url).toContain('http://127.0.0.1:49374/api/experimental/fs/write?') + expect(xhr.url).toContain('path=') + expect(xhr.url).toContain('uploads') + expect(xhr.url).toContain('report.zip') + // 缺省不带 location(交给服务端回落默认工作目录) + expect(xhr.url).not.toContain('location%5Bdirectory%5D') + expect(xhr.headers['content-type']).toBe('application/octet-stream') + expect(xhr.headers['authorization']).toBe('Basic test-token') + expect(xhr.body).toBeInstanceOf(Blob) + + xhr.status = 200 + xhr.response = { data: { path: '/srv/tmp/uploads/u1/report.zip' } } + xhr.emit('load') + await expect(pending).resolves.toEqual({ path: '/srv/tmp/uploads/u1/report.zip', size: 9 }) + }) + + it('带目录时 query 里带上 location[directory]', async () => { + const { xhr } = await startUpload(vi.fn(), '/repo/project') + expect(xhr.url).toContain('location%5Bdirectory%5D=%2Frepo%2Fproject') + }) + + it('progress 事件换算成 0~1 的回调', async () => { + const onProgress = vi.fn() + const { xhr } = await startUpload(onProgress) + + xhr.emitProgress(0, 100) + xhr.emitProgress(25, 100) + xhr.emitProgress(100, 100) + + expect(onProgress.mock.calls.map(call => call[0])).toEqual([0, 0.25, 1]) + }) + + it('非 200 抛错(供失败分类识别状态码)', async () => { + const { pending, xhr } = await startUpload(vi.fn()) + + xhr.status = 500 + xhr.emit('load') + await expect(pending).rejects.toThrow('Upload failed with status 500') + }) + + it('网络错误与取消分别抛出可分类的错误', async () => { + const first = await startUpload(vi.fn()) + first.xhr.emit('error') + await expect(first.pending).rejects.toThrow(/network error/i) + + const second = await startUpload(vi.fn()) + second.xhr.abort() + await expect(second.pending).rejects.toThrow(/aborted/i) + }) + + it('Tauri 下即使要进度也不走 XHR(webview 的 CORS/网络策略不可靠,仍走 SDK)', async () => { + Object.defineProperty(window, '__TAURI_INTERNALS__', { value: {}, configurable: true }) + try { + await uploadAttachment(new Blob(['x']), 'report.zip', undefined, 'local', { onProgress: vi.fn() }) + expect(writeMock).toHaveBeenCalledTimes(1) + expect(FakeXhr.instances).toHaveLength(0) + } finally { + Reflect.deleteProperty(window, '__TAURI_INTERNALS__') + } + }) +}) + +// ============================================ +// 本机文件上传(桌面端):Tauri 下交给 Rust 流式发送,进度经 Channel 推回 +// ============================================ + +const invokeMock = vi.fn(async (_command: string, _args: Record) => ({ + path: '/srv/tmp/uploads/u7/piui-source.zip', + size: 4096, +})) + +vi.mock('@tauri-apps/api/core', () => ({ + Channel: class { + onmessage: ((event: { type: string; loaded: number; total: number }) => void) | null = null + }, + invoke: (command: string, args: Record) => invokeMock(command, args), +})) + +describe('uploadLocalFile', () => { + beforeEach(() => { + writeMock.mockClear() + infoMock.mockClear() + readFileMock.mockClear() + clearServerTmpDirectoryCache() + invokeMock.mockClear() + Reflect.deleteProperty(window, '__TAURI_INTERNALS__') + }) + + it('Tauri 下调用 Rust 命令,带上 URL / 目标 / 源路径 / 密码,并把进度事件换算成 0~1', async () => { + Object.defineProperty(window, '__TAURI_INTERNALS__', { value: {}, configurable: true }) + try { + const onProgress = vi.fn() + const result = await uploadLocalFile('C:\\dl\\piui-source.zip', 'piui-source.zip', '/repo', 'local', { + onProgress, + }) + + expect(result).toEqual({ path: '/srv/tmp/uploads/u7/piui-source.zip', size: 4096 }) + + const [command, args] = invokeMock.mock.calls[0] as [string, Record] + expect(command).toBe('upload_attachment') + expect(args.url).toContain('http://') + expect(args.sourcePath).toBe('C:\\dl\\piui-source.zip') + expect(args.directory).toBe('/repo') + expect(String(args.target)).toContain('uploads') + expect(String(args.target)).toContain('piui-source.zip') + expect(args.onEvent).toBeTruthy() + + // Rust 侧推事件 → JS 侧换算成比例 + const channel = args.onEvent as { onmessage: (event: unknown) => void } + channel.onmessage({ type: 'progress', loaded: 512, total: 4096 }) + channel.onmessage({ type: 'progress', loaded: 4096, total: 4096 }) + expect(onProgress.mock.calls.map(call => call[0])).toEqual([0.125, 1]) + } finally { + Reflect.deleteProperty(window, '__TAURI_INTERNALS__') + } + }) + + it('非 Tauri 环境退化为读字节后走通用上传(浏览器本来也拿不到真实路径)', async () => { + readFileMock.mockResolvedValue(new Uint8Array([1, 2, 3])) + + const result = await uploadLocalFile('/host/dl/report.zip', 'report.zip') + + expect(invokeMock).not.toHaveBeenCalled() + expect(writeMock).toHaveBeenCalledTimes(1) + expect(result.path).toBe('/srv/tmp/uploads/abc/report.zip') + }) +}) diff --git a/src/api/message.test.ts b/src/api/message.test.ts index 0cc167e5f..09b797c9f 100644 --- a/src/api/message.test.ts +++ b/src/api/message.test.ts @@ -35,6 +35,7 @@ vi.mock('./sdk', () => ({ const { sendMessage } = await import('./message') type PromptPayload = { + text?: string files?: Array<{ uri: string; name?: string; mention?: { start: number; end: number; text: string } }> agents?: Array<{ name: string; mention?: { start: number; end: number; text: string } }> skills?: Array<{ id: string; mention?: { start: number; end: number; text: string } }> @@ -219,3 +220,191 @@ describe('sendMessage — prompt 载荷(官方 request.ts + submit.ts:395-411 }) }) +// ============================================ +// 路径引用(Issue #182) +// +// files[].uri 只让服务端读到字节;model 能否看到取决于服务端嗅探出的 mime +//(core to-llm-message.ts:75-83 只放行 text/plain 与 image/pdf)。因此上传的 +// zip/docx 必须额外把绝对路径写进 prompt 文本,官方做法同款 +//(packages/app/src/composer/request.ts:173-182)。 +// ============================================ + +describe('sendMessage — 路径型附件的文本引用', () => { + beforeEach(() => { + calls.length = 0 + switchModelMock.mockClear() + switchAgentMock.mockClear() + promptMock.mockClear() + }) + + const uploadedAttachment = (overrides: Record = {}) => ({ + id: 'up1', + type: 'file', + displayName: 'report.zip', + url: 'file:///tmp/opencode/uploads/u1/report.zip', + mime: 'application/zip', + relativePath: '/tmp/opencode/uploads/u1/report.zip', + ...overrides, + }) + + it('路径型附件:uri 进 files[],绝对路径进文本与 metadata.attachments', async () => { + await sendMessage({ + ...baseParams(), + text: '帮我看看这个包', + attachments: [uploadedAttachment()] as never, + }) + + const payload = lastPromptPayload() + expect(payload.files).toEqual([ + { uri: 'file:///tmp/opencode/uploads/u1/report.zip', name: 'report.zip' }, + ]) + expect(payload.text).toBe('帮我看看这个包\nAttached file: `/tmp/opencode/uploads/u1/report.zip`') + expect(payload.metadata?.attachments).toEqual([ + { name: 'report.zip', mime: 'application/zip', path: '/tmp/opencode/uploads/u1/report.zip' }, + ]) + // displayText 保持用户原始输入(时间线展示不被污染) + expect(payload.metadata?.displayText).toBe('帮我看看这个包') + }) + + it('超过 20MB 的附件只作路径引用:不进 files[],但路径仍进文本', async () => { + await sendMessage({ + ...baseParams(), + text: '大文件', + attachments: [uploadedAttachment({ pathOnly: true })] as never, + }) + + const payload = lastPromptPayload() + expect(payload.files).toBeUndefined() + expect(payload.text).toBe('大文件\nAttached file: `/tmp/opencode/uploads/u1/report.zip`') + expect(payload.metadata?.attachments).toHaveLength(1) + }) + + it('带 mention 的附件(@ 引用)不额外注入路径', async () => { + await sendMessage({ + ...baseParams(), + text: '@src/foo.ts 看下', + attachments: [ + { + id: 'a1', + type: 'file', + displayName: 'foo.ts', + url: 'file:///proj/src/foo.ts', + textRange: { value: '@src/foo.ts', start: 0, end: 11 }, + }, + ] as never, + }) + + const payload = lastPromptPayload() + expect(payload.text).toBe('@src/foo.ts 看下') + expect(payload.metadata?.attachments).toBeUndefined() + }) + + it('revert 回填的文本里已有同一引用时不重复追加', async () => { + const path = '/tmp/opencode/uploads/u1/report.zip' + await sendMessage({ + ...baseParams(), + text: `帮我看看这个包\nAttached file: \`${path}\``, + attachments: [uploadedAttachment()] as never, + }) + + const payload = lastPromptPayload() + expect(payload.text).toBe(`帮我看看这个包\nAttached file: \`${path}\``) + expect(payload.text?.match(/Attached file:/g)).toHaveLength(1) + }) + + it('多个附件按顺序各占一行,且路径去重', async () => { + await sendMessage({ + ...baseParams(), + text: 'x', + attachments: [ + uploadedAttachment(), + uploadedAttachment({ id: 'up2', displayName: 'b.bin', url: 'file:///tmp/opencode/uploads/u2/b.bin', relativePath: '/tmp/opencode/uploads/u2/b.bin' }), + uploadedAttachment({ id: 'up3' }), + ] as never, + }) + + const payload = lastPromptPayload() + expect(payload.text).toBe( + 'x\nAttached file: `/tmp/opencode/uploads/u1/report.zip`\nAttached file: `/tmp/opencode/uploads/u2/b.bin`', + ) + expect(payload.metadata?.attachments).toHaveLength(2) + }) + + it('空文本只有引用行时不留前导换行', async () => { + await sendMessage({ + ...baseParams(), + text: '', + attachments: [uploadedAttachment()] as never, + }) + + expect(lastPromptPayload().text).toBe('Attached file: `/tmp/opencode/uploads/u1/report.zip`') + }) +}) + +// ============================================ +// 附件消息回填(Issue #182) +// +// 气泡/回填都不能露出管道信息:`text` 末尾那行路径引用是给模型读的, +// 用户原始输入在 metadata.displayText(官方 comment-note.ts:42-50 同款)。 +// ============================================ + +describe('extractUserMessageContent — 路径附件回填', () => { + const userMessage = (overrides: Record = {}) => + ({ + id: 'msg_u', + type: 'user', + text: '看看?\nAttached file: `C:/tmp/uploads/u1/report.zip`', + time: { created: 0 }, + metadata: { + displayText: '看看?', + attachments: [{ name: 'report.zip', mime: 'application/zip', path: 'C:/tmp/uploads/u1/report.zip' }], + }, + ...overrides, + }) as never + + it('回填用户原始输入,不带上追加的路径引用行', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent(userMessage()) + expect(restored.text).toBe('看看?') + }) + + it('只作路径引用的附件(超 20MB 未进 files[])从 metadata.attachments 还原', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent(userMessage()) + + expect(restored.attachments).toHaveLength(1) + expect(restored.attachments[0]).toMatchObject({ + type: 'file', + displayName: 'report.zip', + url: 'file:///C:/tmp/uploads/u1/report.zip', + relativePath: 'C:/tmp/uploads/u1/report.zip', + pathOnly: true, + }) + }) + + it('已在 files[] 里的附件不会因为 metadata 再重复一次', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent( + userMessage({ + files: [ + { + data: 'QQ==', + mime: 'application/zip', + source: { type: 'uri', uri: 'file:///C:/tmp/uploads/u1/report.zip' }, + name: 'report.zip', + }, + ], + }), + ) + + expect(restored.attachments).toHaveLength(1) + expect(restored.attachments[0]?.pathOnly).toBeUndefined() + }) + + it('没有 metadata 的旧消息回落到 message.text', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent(userMessage({ metadata: undefined })) + expect(restored.text).toBe('看看?\nAttached file: `C:/tmp/uploads/u1/report.zip`') + }) +}) + diff --git a/src/api/message.ts b/src/api/message.ts index 50c2c1688..d82d16482 100644 --- a/src/api/message.ts +++ b/src/api/message.ts @@ -17,6 +17,7 @@ import { getSDKClient } from './sdk' import type { JsonValue } from '@opencode/client/promise' import { resolveSessionTarget } from '../utils/sessionKey' +import { absolutePathToFileUrl, fileBaseName } from '../utils/pathUtils' import type { SessionMessage, UserMessage } from './types' import type { Attachment, RevertedMessage, SendMessageParams } from './types' @@ -108,11 +109,13 @@ export async function getSessionMessagesPage( */ export function extractUserMessageContent(message: UserMessage): RevertedMessage { const attachments: Attachment[] = [] + const seenPaths = new Set() for (const file of message.files ?? []) { const source = file.source const uri = source?.type === 'uri' ? source.uri : '' const displayName = file.name || uri || file.mime || 'attachment' + if (uri) seenPaths.add(uri) attachments.push({ id: crypto.randomUUID(), type: 'file', @@ -123,6 +126,30 @@ export function extractUserMessageContent(message: UserMessage): RevertedMessage }) } + // 只作路径引用的附件(超 20MB 未进 files[])不在 message.files 里, + // 只能从 metadata.attachments 还原——否则回填后模型拿不到这个文件。 + const metadata = message.metadata as Record | undefined + const references = Array.isArray(metadata?.['attachments']) ? metadata['attachments'] : [] + for (const reference of references) { + if (!reference || typeof reference !== 'object') continue + const { name, mime, path } = reference as { name?: unknown; mime?: unknown; path?: unknown } + if (typeof path !== 'string' || !path) continue + + const url = absolutePathToFileUrl(path) + if (seenPaths.has(url)) continue + seenPaths.add(url) + + attachments.push({ + id: crypto.randomUUID(), + type: 'file', + displayName: typeof name === 'string' && name ? name : fileBaseName(path), + url, + mime: typeof mime === 'string' ? mime : undefined, + relativePath: path, + pathOnly: true, + }) + } + for (const agent of message.agents ?? []) { attachments.push({ id: crypto.randomUUID(), @@ -132,7 +159,12 @@ export function extractUserMessageContent(message: UserMessage): RevertedMessage }) } - return { text: message.text ?? '', attachments } + // 回填用户原始输入(不含我们追加的路径引用行):再次发送时由 + // applyAttachmentReferences 依据附件重新生成,不会丢也不会重复。 + const displayText = metadata?.['displayText'] + const text = typeof displayText === 'string' ? displayText : message.text ?? '' + + return { text, attachments } } // ============================================ @@ -174,6 +206,10 @@ export function buildPromptParts(attachments: Attachment[]): { continue } + // 超过服务端 20MB 附件上限的文件只走路径引用(见 buildAttachmentReferences), + // 放进 files[] 会让整条 prompt 以 AttachmentError 失败。 + if (attachment.pathOnly) continue + const uri = attachment.url || '' if (!uri) { console.warn('Skipping attachment with empty URL:', attachment) @@ -189,6 +225,139 @@ export function buildPromptParts(attachments: Attachment[]): { return { files, agents, skills } } +// ============================================ +// 路径引用(Issue #182) +// +// 服务端 materialize 附件时只做两件事:按 uri 读字节、嗅探 mime。 +// 转到 LLM 时**只有 text/plain 与 image/pdf 会进上下文**,其余 mime +// (zip / docx / 二进制 → application/octet-stream)被整段丢弃——模型 +// 连路径都看不到。官方因此在 prompt 文本里补一行路径引用 +// (packages/app/src/composer/request.ts:173-182、comment-note.ts:52-54): +// +// Attached file: `<绝对路径>` +// +// 同时把 `{name, mime, path}` 写进 `metadata.attachments` 供 UI 还原。 +// 本项目照抄这一形状(queue.ts 的 queuedPromptAttachments 已经在按它读)。 +// ============================================ + +/** + * 路径引用(写进 `metadata.attachments`,形状对齐官方 request.ts:189 的 attachments)。 + * + * 交叉一个 `JsonValue` 索引签名,才能直接放进 `metadata: Record`。 + */ +export type PromptAttachmentReference = { + name: string + mime: string + path: string +} & { [key: string]: JsonValue } + +const ATTACHMENT_REFERENCE_PREFIX = 'Attached file: ' +const ATTACHMENT_REFERENCE_LINE = /^Attached file: `(.+)`$/gm + +/** 路径比较用归一化:分隔符与首尾空白 */ +function normalizeReferencePath(path: string): string { + return path.replace(/\\/g, '/').trim() +} + +/** `file://` URL → 绝对路径(反向于 features/mention 的 toFileUrl) */ +export function fileUrlToAbsolutePath(url: string): string | undefined { + try { + const parsed = new URL(url) + if (parsed.protocol !== 'file:') return undefined + const decoded = decodeURIComponent(parsed.pathname) + // Windows 盘符:/C:/dir/file → C:/dir/file + return /^\/[A-Za-z]:\//.test(decoded) ? decoded.slice(1) : decoded + } catch { + return undefined + } +} + +/** + * 路径型附件:`file://` 引用且**不带 mention**。 + * + * 带 mention 的附件(`@` 提及、侧边栏拖入)路径已经在文本里,再补一行 + * 路径引用纯属噪声——官方也是这么区分的(path 部件 vs file 部件)。 + */ +export function isPathReferenceAttachment(attachment: Attachment): boolean { + if (attachment.type !== 'file') return false + if (attachment.textRange) return false + return Boolean(attachment.url?.startsWith('file://')) +} + +/** 附件的服务端/本机绝对路径 */ +export function attachmentReferencePath(attachment: Attachment): string | undefined { + if (attachment.url?.startsWith('file://')) return fileUrlToAbsolutePath(attachment.url) + return attachment.relativePath || undefined +} + +/** 收集路径引用(去重、保序) */ +export function buildAttachmentReferences(attachments: Attachment[]): PromptAttachmentReference[] { + const references: PromptAttachmentReference[] = [] + + for (const attachment of attachments) { + if (!isPathReferenceAttachment(attachment)) continue + const path = attachmentReferencePath(attachment) + if (!path) continue + + references.push({ + name: attachment.displayName, + mime: attachment.mime ?? 'text/plain', + path, + }) + } + + return dedupeAttachmentReferences(references) +} + +/** 按归一化路径去重(保序、保留首次出现的 name/mime) */ +export function dedupeAttachmentReferences( + references: PromptAttachmentReference[], +): PromptAttachmentReference[] { + const result: PromptAttachmentReference[] = [] + const seen = new Set() + + for (const reference of references) { + const key = normalizeReferencePath(reference.path) + if (!key || seen.has(key)) continue + seen.add(key) + result.push(reference) + } + + return result +} + +/** 从文本里解析已存在的路径引用(用于 revert 重发时去重) */ +export function parseAttachmentReferencePaths(text: string): string[] { + const paths: string[] = [] + ATTACHMENT_REFERENCE_LINE.lastIndex = 0 + let match: RegExpExecArray | null + while ((match = ATTACHMENT_REFERENCE_LINE.exec(text)) !== null) { + if (match[1]) paths.push(match[1]) + } + return paths +} + +/** + * 把路径引用追加到 prompt 文本末尾。 + * + * 追加在**末尾**:文本中已有的 `@` mention 区间(mention.start/end) + * 因此不受影响。已经出现过的同路径引用会被跳过(revert / 队列编辑回填 + * 会把上次追加的行带回文本)。 + */ +export function applyAttachmentReferences(text: string, references: PromptAttachmentReference[]): string { + if (references.length === 0) return text + + const existing = new Set(parseAttachmentReferencePaths(text).map(normalizeReferencePath)) + const lines = references + .filter(reference => !existing.has(normalizeReferencePath(reference.path))) + .map(reference => `${ATTACHMENT_REFERENCE_PREFIX}\`${reference.path}\``) + + if (lines.length === 0) return text + + const separator = text.length === 0 || text.endsWith('\n') ? '' : '\n' + return `${text}${separator}${lines.join('\n')}` +} + /** * 构建 v2 的 prompt 入参(官方 composer/request.ts + submit.ts:395-411 同款)。 * @@ -213,12 +382,15 @@ function buildPromptInput( metadata?: Record } { const { files, agents, skills } = buildPromptParts(params.attachments) + // 路径型附件额外把绝对路径写进文本(官方 request.ts:173-182 同款): + // files[].uri 只让服务端读到字节,模型能否看到取决于 mime(见文件顶部说明)。 + const attachmentReferences = buildAttachmentReferences(params.attachments) return { sessionID, // 客户端铸造的 id:服务端原样采用,乐观行与 durable 行同 id 对账 ...(params.id ? { id: params.id } : {}), - text: params.text, + text: applyAttachmentReferences(params.text, attachmentReferences), // 投递方式:busy 时 'queue' 排队(服务端排空后自动投递)或 'steer' // 插队注入当前回合;idle 时不传走服务端默认(steer) //(官方 packages/core/src/session/prompt.ts:50 默认 steer) @@ -229,6 +401,7 @@ function buildPromptInput( // 选择快照 + 原始输入(官方 submit.ts:401-410 同款) metadata: { displayText: params.text, + ...(attachmentReferences.length > 0 ? { attachments: attachmentReferences } : {}), ...(params.agent ? { agent: params.agent } : {}), ...(params.model ? { diff --git a/src/api/queue.ts b/src/api/queue.ts index 4687705df..fa27c1253 100644 --- a/src/api/queue.ts +++ b/src/api/queue.ts @@ -14,6 +14,13 @@ import { getSDKClient } from './sdk' import { resolveSessionTarget } from '../utils/sessionKey' import { cancelInboxItem } from './session' import { createMessageId } from '../utils/identifier' +import { fileBaseName } from '../utils/pathUtils' +import { + applyAttachmentReferences, + buildAttachmentReferences, + dedupeAttachmentReferences, + fileUrlToAbsolutePath, +} from './message' import type { QueuedUserPrompt } from '../store/inboxStore' import type { Attachment } from './types' import type { PromptMention, JsonValue } from '@opencode/client/promise' @@ -151,6 +158,28 @@ export function buildEditedPromptInput(params: { mention: mention(file.mention), })) + // 路径引用(Issue #182):原条目里 uri 型文件的路径 + 编辑器当前的路径型附件。 + // 两者都要重新注入文本——编辑确认会重写 text,旧的那一行可能在 notes 里, + // 也可能被新文本顶掉;applyAttachmentReferences 会按路径去重,不会重复。 + const preservedReferences = (payload.files ?? []).flatMap(file => { + if (file.source.type !== 'uri') return [] + const path = fileUrlToAbsolutePath(file.source.uri) ?? file.source.uri + return [{ name: file.name ?? fileBaseName(path), mime: file.mime, path }] + }) + // 旧的 composer 路径附件形态是「无 url、有 relativePath」(queue 回填的条目), + // 保留兼容;新的上传附件带 file:// url,由 buildAttachmentReferences 收集。 + const composerReferences = [ + ...params.attachments + .filter(attachment => attachment.type === 'file' && !attachment.url && attachment.relativePath) + .map(attachment => ({ + name: attachment.displayName, + mime: attachment.mime ?? 'text/plain', + path: attachment.relativePath!, + })), + ...buildAttachmentReferences(params.attachments), + ] + const references = dedupeAttachmentReferences([...preservedReferences, ...composerReferences]) + const requestAgents = params.request.agents ?? [] const agents = [ ...(payload.agents ?? []).filter( @@ -169,19 +198,10 @@ export function buildEditedPromptInput(params: { ...requestSkills, ] - // 编辑器里的 path 附件(无 url 有 relativePath)回 metadata.attachments - const pathAttachments = params.attachments - .filter(attachment => attachment.type === 'file' && !attachment.url && attachment.relativePath) - .map(attachment => ({ - name: attachment.displayName, - mime: attachment.mime ?? 'text/plain', - path: attachment.relativePath!, - })) - return { sessionID: params.sessionId, id: createMessageId(), - text: params.text + notes, + text: applyAttachmentReferences(params.text + notes, references), delivery: params.delivery, files: [...preservedFiles, ...(params.request.files ?? [])], agents: agents.map(agent => ({ name: agent.name, mention: mention(agent.mention) ?? agent.mention })), @@ -189,7 +209,7 @@ export function buildEditedPromptInput(params: { metadata: { ...(payload.metadata as Record | undefined), displayText: params.text, - attachments: pathAttachments, + attachments: references, }, ...(params.delivery === 'queue' ? { resume: false } : {}), } diff --git a/src/api/shell.ts b/src/api/shell.ts index 05bbf615d..a78cba57b 100644 --- a/src/api/shell.ts +++ b/src/api/shell.ts @@ -11,10 +11,14 @@ import { getSDKClient } from './sdk' import type { ShellInfo } from '@opencode/client/promise' -/** 列出当前服务器的 shell(官方 data.shell.list) */ -export async function listShells(serverId?: string): Promise { +/** + * 列出指定工作区目录的 shell(官方 data.shell.list)。 + * serve --service 模式下 shell 按目录隔离,directory 必传—— + * 不带查的是服务根目录,永远空。 + */ +export async function listShells(directory: string, serverId?: string): Promise { const sdk = getSDKClient(serverId) - const result = await sdk.shell.list() + const result = await sdk.shell.list({ location: { directory } }) return result.data } @@ -36,3 +40,12 @@ export async function getShellOutput( }) return result.data } + +/** 终止 shell(官方 session-running-menu 的 stop:sdk.shell.remove) */ +export async function removeShell(id: string, directory?: string, serverId?: string): Promise { + const sdk = getSDKClient(serverId) + await sdk.shell.remove({ + id, + ...(directory ? { location: { directory } } : {}), + }) +} diff --git a/src/components/CloseServiceDialog.tsx b/src/components/CloseServiceDialog.tsx index 44690d9cf..638788694 100644 --- a/src/components/CloseServiceDialog.tsx +++ b/src/components/CloseServiceDialog.tsx @@ -10,12 +10,14 @@ import { Button } from './ui/Button' import { PlugIcon, SpinnerIcon } from './Icons' interface CloseServiceDialogProps { + /** 有未保存的文件编辑(需求三):退出会丢失,必须显式提醒 */ + hasUnsavedChanges?: boolean isOpen: boolean onConfirm: (stopService: boolean) => void onCancel: () => void } -export function CloseServiceDialog({ isOpen, onConfirm, onCancel }: CloseServiceDialogProps) { +export function CloseServiceDialog({ isOpen, onConfirm, onCancel, hasUnsavedChanges }: CloseServiceDialogProps) { const { t } = useTranslation(['components', 'common']) const [closing, setClosing] = useState(false) @@ -40,6 +42,11 @@ export function CloseServiceDialog({ isOpen, onConfirm, onCancel }: CloseService {/* Description */}

{t('closeService.description')} + {hasUnsavedChanges && ( +

+ {t('fileExplorer.unsavedCloseWarning')} +

+ )}

{/* Actions */} diff --git a/src/components/CodeMirrorReadonly.tsx b/src/components/CodeMirrorReadonly.tsx index fad7e93e1..6b0e931ef 100644 --- a/src/components/CodeMirrorReadonly.tsx +++ b/src/components/CodeMirrorReadonly.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react' -import { EditorState, type Extension } from '@codemirror/state' +import { Annotation, EditorState, Compartment, type Extension } from '@codemirror/state' import { openSearchPanel } from '@codemirror/search' import { EditorView } from '@codemirror/view' import type { HighlightTokens } from '../hooks/useSyntaxHighlight' @@ -28,10 +28,24 @@ interface CodeMirrorReadonlyProps { targetLine?: number | null targetKey?: string targetRanges?: readonly TargetLineRange[] + /** false = 可编辑(需求三:预览编辑器)。默认只读 */ + readOnly?: boolean + onChange?: (value: string) => void } const EMPTY_TARGET_RANGES: readonly TargetLineRange[] = [] const EMPTY_EXTENSIONS: Extension[] = [] +/** 标记"这次文档变更是外部同步进来的",便于将来区分用户输入与磁盘重载 */ +const externalCodeUpdate = Annotation.define() + +/** 变更监听:放在 Compartment 里,回调变化时 reconfigure 而不是重建视图 */ +function changeListener(onChange?: (value: string) => void): Extension { + return EditorView.updateListener.of(update => { + if (!update.docChanged) return + if (update.transactions.some(tr => tr.annotation(externalCodeUpdate))) return + onChange?.(update.state.doc.toString()) + }) +} export function CodeMirrorReadonly({ code, @@ -49,12 +63,21 @@ export function CodeMirrorReadonly({ targetLine, targetKey, targetRanges = EMPTY_TARGET_RANGES, + readOnly = true, + onChange, }: CodeMirrorReadonlyProps) { const hostRef = useRef(null) const viewRef = useRef(null) const constrainedHeight = maxHeight !== undefined const lineNumberWidth = useMemo(() => getLineNumberColumnWidth(getLineCount(code)), [code]) + // 只在**挂载时**用的初值:view 创建后由编辑器自己持有文档(非受控), + // 外部变更走下面的 dispatch 同步,避免每次按键重建视图(会丢光标/选区/撤销栈) + const initialCodeRef = useRef(code) + const initialTokensRef = useRef(null) + const initialOnChangeRef = useRef(onChange) + const changeCompartment = useMemo(() => new Compartment(), []) + const extensions = useMemo( () => createReadonlyCodeMirrorExtensions({ @@ -63,29 +86,57 @@ export function CodeMirrorReadonly({ showLineNumbers, maxHeight, editable: !constrainedHeight, + readOnly, lineNumberWidth, extraExtensions, }), - [wordWrap, lineHeight, showLineNumbers, maxHeight, constrainedHeight, lineNumberWidth, extraExtensions], + [wordWrap, lineHeight, showLineNumbers, maxHeight, constrainedHeight, lineNumberWidth, extraExtensions, readOnly], ) + // 同步创建 view 需要的初值(这个 effect 排在创建 view 的 layout effect 之前) + useLayoutEffect(() => { + initialCodeRef.current = code + initialTokensRef.current = tokensRef.current + initialOnChangeRef.current = onChange + }, [code, onChange, tokensRef]) + useLayoutEffect(() => { const host = hostRef.current if (!host) return const view = new EditorView({ parent: host, - state: EditorState.create({ doc: code, extensions }), + state: EditorState.create({ + doc: initialCodeRef.current, + extensions: [extensions, changeCompartment.of(changeListener(initialOnChangeRef.current))], + }), }) viewRef.current = view - dispatchShikiTokens(view, tokensRef.current) + dispatchShikiTokens(view, initialTokensRef.current) return () => { view.destroy() if (viewRef.current === view) viewRef.current = null } - }, [code, extensions, tokensRef]) + }, [changeCompartment, extensions]) + + // 回调变化只 reconfigure 这个 Compartment,不重建视图 + useEffect(() => { + const view = viewRef.current + if (!view) return + view.dispatch({ effects: changeCompartment.reconfigure(changeListener(onChange)) }) + }, [changeCompartment, onChange]) + + // 外部值同步(磁盘重载 / 放弃改动) + useEffect(() => { + const view = viewRef.current + if (!view || view.state.doc.toString() === code) return + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: code }, + annotations: externalCodeUpdate.of(true), + }) + }, [code]) useEffect(() => { const view = viewRef.current diff --git a/src/components/CodePreview.tsx b/src/components/CodePreview.tsx index 5c61495ee..f1be1e7b2 100644 --- a/src/components/CodePreview.tsx +++ b/src/components/CodePreview.tsx @@ -1,9 +1,12 @@ -import { useSyncExternalStore } from 'react' +import { useEffect, useState, useSyncExternalStore } from 'react' import { CodeMirrorReadonly } from './CodeMirrorReadonly' import { codeLineHeight, type TargetLineRange } from './codeMirrorReadonlyExtensions' import { useSyntaxHighlightRef } from '../hooks/useSyntaxHighlight' import { themeStore } from '../store/themeStore' +/** 编辑态高亮 debounce:每击键全量重高亮的代价太高 */ +const HIGHLIGHT_DEBOUNCE_MS = 200 + interface CodePreviewProps { code: string language: string @@ -15,6 +18,9 @@ interface CodePreviewProps { targetLine?: number | null targetKey?: string targetRanges?: readonly TargetLineRange[] + /** 默认只读;false = 可编辑预览(需求三) */ + readOnly?: boolean + onChange?: (value: string) => void } export function CodePreview({ @@ -28,10 +34,21 @@ export function CodePreview({ targetLine, targetKey, targetRanges, + readOnly = true, + onChange, }: CodePreviewProps) { const { codeWordWrap, codeFontScale } = useSyncExternalStore(themeStore.subscribe, themeStore.getSnapshot) const resolvedWordWrap = wordWrap ?? codeWordWrap - const { tokensRef, version } = useSyntaxHighlightRef(code, { + + // 编辑态:高亮跟着 debounce 后的文本走,避免每敲一个字符整文件重高亮 + const [highlightCode, setHighlightCode] = useState(code) + useEffect(() => { + if (readOnly) return + const timer = window.setTimeout(() => setHighlightCode(code), HIGHLIGHT_DEBOUNCE_MS) + return () => window.clearTimeout(timer) + }, [code, readOnly]) + + const { tokensRef, version } = useSyntaxHighlightRef(readOnly ? code : highlightCode, { lang: language, enabled: language !== 'text', }) @@ -50,6 +67,8 @@ export function CodePreview({ targetLine={targetLine} targetKey={targetKey} targetRanges={targetRanges} + readOnly={readOnly} + onChange={onChange} /> ) } diff --git a/src/components/ContentBlock.tsx b/src/components/ContentBlock.tsx index d9692e50c..2ebd7a0dc 100644 --- a/src/components/ContentBlock.tsx +++ b/src/components/ContentBlock.tsx @@ -16,7 +16,7 @@ import { DiffViewer, useDiffViewerData, type ViewMode } from './DiffViewer' import { CodePreview } from './CodePreview' import { detectLanguage } from '../utils/languageUtils' import { ViewModeSwitch } from './FullscreenViewer' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { useCompositorExpand } from '../hooks/useCompositorExpand' import { useDelayedRender } from '../hooks/useDelayedRender' import { useResponsiveMaxHeight } from '../hooks/useResponsiveMaxHeight' @@ -152,7 +152,9 @@ export const ContentBlock = memo(function ContentBlock({ const resolvedDiff = useMemo(() => { if (!diff) return null if (typeof diff === 'object') return diff - return extractContentFromUnifiedDiff(diff) + // 优先按 patch 的 @@ 绝对行号还原完整 before/after(行号正确); + // 失败(非标准 patch、超大等)退回片段提取(行号从 1 开始) + return reconstructBeforeAfterFromPatch(diff) ?? extractContentFromUnifiedDiff(diff) }, [diff]) const diffViewerData = useDiffViewerData(resolvedDiff?.before ?? '', resolvedDiff?.after ?? '', lang, false, isDiff) diff --git a/src/components/DiffView.test.tsx b/src/components/DiffView.test.tsx index 64888777b..d03e421de 100644 --- a/src/components/DiffView.test.tsx +++ b/src/components/DiffView.test.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from 'react' import { fireEvent, render, screen } from '@testing-library/react' +import { createTwoFilesPatch } from 'diff' import { describe, expect, it, vi } from 'vitest' import { DiffView } from './DiffView' import { FullscreenProvider } from '../contexts' @@ -36,4 +37,28 @@ describe('DiffView', () => { fireEvent.click(screen.getByTitle('Fullscreen')) expect(screen.getByTestId('fullscreen-viewer')).toBeInTheDocument() }) + + it('按 patch 的绝对行号还原:深处变更显示真实行号(旧的片段提取从 1 开始)', () => { + // 40 行文件、第 30 行改一处;内容纯字母,行号只出现在 gutter 里 + const lines = Array.from( + { length: 40 }, + (_, i) => `item_${String.fromCharCode(65 + Math.floor(i / 26))}${String.fromCharCode(65 + (i % 26))}`, + ) + const before = lines.join('\n') + const after = [...lines.slice(0, 29), 'REPLACED', ...lines.slice(30)].join('\n') + const patch = createTwoFilesPatch('app.ts', 'app.ts', before, after) + + const { container } = render( + + + , + ) + + // 变更内容渲染出来 + expect(screen.getByText('REPLACED')).toBeInTheDocument() + // gutter 出现真实行号 30(旧的片段提取从 1 开始,最大只到 9,不会有 30) + expect(screen.getAllByText('30').length).toBeGreaterThan(0) + // 合成前导区域不渲染折叠条(展开了也没有真实内容) + expect(container.querySelector('[data-separator="line-info"]')).toBeNull() + }) }) diff --git a/src/components/DiffView.tsx b/src/components/DiffView.tsx index 6664a8a0b..5daacc5be 100644 --- a/src/components/DiffView.tsx +++ b/src/components/DiffView.tsx @@ -4,7 +4,7 @@ import { diffLines } from 'diff' import { ChevronDownIcon, MaximizeIcon } from './Icons' import { clsx } from 'clsx' import { detectLanguage } from '../utils/languageUtils' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { ViewModeSwitch } from './FullscreenViewer' import { DiffViewer, useDiffViewerData, type ViewMode } from './DiffViewer' import { useFullscreenLayer } from '../contexts' @@ -59,7 +59,9 @@ export const DiffView = memo(function DiffView({ return { before, after } } if (diff) { - return extractContentFromUnifiedDiff(diff) + // 优先按 patch 的 @@ 绝对行号还原完整 before/after(行号正确); + // 失败(非标准 patch、超大等)退回片段提取(行号从 1 开始) + return reconstructBeforeAfterFromPatch(diff) ?? extractContentFromUnifiedDiff(diff) } return null }, [before, after, diff]) diff --git a/src/components/DiffViewer.test.tsx b/src/components/DiffViewer.test.tsx index e61609d83..69019b3cd 100644 --- a/src/components/DiffViewer.test.tsx +++ b/src/components/DiffViewer.test.tsx @@ -1,6 +1,8 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { createTwoFilesPatch } from 'diff' import { describe, expect, it, vi } from 'vitest' import { DiffViewer } from './DiffViewer' +import { reconstructBeforeAfterFromPatch } from '../utils/diffUtils' vi.mock('../store/themeStore', async importOriginal => { const actual = await importOriginal() @@ -94,4 +96,32 @@ describe('DiffViewer', () => { expect(container.textContent).toContain('if (!enabled) return') expect(container.textContent).not.toContain('returnn') }) + + it('patch 还原的合成区域不渲染折叠条,真实 diff 的折叠条正常', () => { + // 40 行文件、第 30 行改一处;内容纯字母,行号只出现在 gutter 里 + const lines = Array.from( + { length: 40 }, + (_, i) => `item_${String.fromCharCode(65 + Math.floor(i / 26))}${String.fromCharCode(65 + (i % 26))}`, + ) + const before = lines.join('\n') + const after = [...lines.slice(0, 29), 'REPLACED', ...lines.slice(30)].join('\n') + const patch = createTwoFilesPatch('a.ts', 'a.ts', before, after) + const rec = reconstructBeforeAfterFromPatch(patch)! + + const { container: synthetic } = render( + , + ) + // 变更内容渲染出来,且 gutter 是绝对行号 30 + expect(synthetic.textContent).toContain('REPLACED') + expect(screen.getAllByText('30').length).toBeGreaterThan(0) + // 合成区域不渲染折叠条(展开了也没有真实内容) + expect(synthetic.querySelector('[data-separator="line-info"]')).toBeNull() + + // 同样的变更,但给的是完整 before/after(真实内容)→ 折叠条正常且可展开 + const { container: real } = render( + , + ) + expect(real.querySelector('[data-separator="line-info"]')).not.toBeNull() + expect(real.querySelector('[data-expand-button]')).not.toBeNull() + }) }) diff --git a/src/components/DiffViewer.tsx b/src/components/DiffViewer.tsx index 8bc964efe..cb762bdb0 100644 --- a/src/components/DiffViewer.tsx +++ b/src/components/DiffViewer.tsx @@ -17,6 +17,7 @@ import { useDynamicVirtualScroll } from '../hooks/useDynamicVirtualScroll' import { themeStore } from '../store/themeStore' import type { DiffStyle } from '../store/themeStore' import { getLineCount, getLineNumberColumnWidth } from '../utils/lineNumberUtils' +import { isSyntheticPadLine } from '../utils/diffUtils' import { useUiState } from '../utils/uiDisclosureState' // ============================================ @@ -137,6 +138,15 @@ interface ExpansionRegion { function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMap): PairedLineOrCollapsed[] { if (lines.length === 0) return [] + // 被折叠区间是否含 patch 还原的合成占位行(展开了也没有真实内容) + const rangeHasSynthetic = (start: number, end: number): boolean => { + for (let j = start; j < end; j++) { + const line = lines[j] + if (isSyntheticPadLine(line.left.content) || isSyntheticPadLine(line.right.content)) return true + } + return false + } + const result: PairedLineOrCollapsed[] = [] let contextStart = -1 @@ -159,7 +169,9 @@ function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMa const suffixStart = Math.max(prefixCount, ctxLen - keepAfter - expanded.fromEnd) for (let j = contextStart; j < contextStart + prefixCount; j++) result.push(lines[j]) - if (suffixStart > prefixCount) { + // 合成区域(patch 还原的间隙占位行)不渲染折叠条:展开了也没有真实内容, + // 直接让两侧真实 context 行相邻,靠行号跳跃体现不连续(与 git diff 一致) + if (suffixStart > prefixCount && !rangeHasSynthetic(contextStart + prefixCount, contextStart + suffixStart)) { const count = suffixStart - prefixCount result.push({ collapsed: true, @@ -186,6 +198,14 @@ function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMa function collapseContextUnified(lines: UnifiedLine[], expandedRegions?: ReadonlyMap): UnifiedLineOrCollapsed[] { if (lines.length === 0) return [] + // 被折叠区间是否含 patch 还原的合成占位行(展开了也没有真实内容) + const rangeHasSynthetic = (start: number, end: number): boolean => { + for (let j = start; j < end; j++) { + if (isSyntheticPadLine(lines[j].content)) return true + } + return false + } + const result: UnifiedLineOrCollapsed[] = [] let contextStart = -1 @@ -208,7 +228,9 @@ function collapseContextUnified(lines: UnifiedLine[], expandedRegions?: Readonly const suffixStart = Math.max(prefixCount, ctxLen - keepAfter - expanded.fromEnd) for (let j = contextStart; j < contextStart + prefixCount; j++) result.push(lines[j]) - if (suffixStart > prefixCount) { + // 合成区域(patch 还原的间隙占位行)不渲染折叠条:展开了也没有真实内容, + // 直接让两侧真实 context 行相邻,靠行号跳跃体现不连续(与 git diff 一致) + if (suffixStart > prefixCount && !rangeHasSynthetic(contextStart + prefixCount, contextStart + suffixStart)) { const count = suffixStart - prefixCount result.push({ collapsed: true, diff --git a/src/components/EditConfirmDialog.test.tsx b/src/components/EditConfirmDialog.test.tsx new file mode 100644 index 000000000..b34fcd499 --- /dev/null +++ b/src/components/EditConfirmDialog.test.tsx @@ -0,0 +1,85 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { EditConfirmDialog } from './EditConfirmDialog' +import { FullscreenProvider } from '../contexts' + +// ============================================ +// 保存 / 放弃的二次确认弹层(需求三 A) +// +// 它现在包的是工具卡片那套 DiffView(同名 diff 组件),所以顺带继承: +// 头部显示文件名、+/- 统计、全屏按钮。这里锁住:文件名可见、diff 可见、 +// 冲突时多一行警告且主按钮变「覆盖」、改动过大不渲染 diff、确认键不自动聚焦。 +// 测试环境 i18n 是英文,断言走 testid / 英文按钮名。 +// ============================================ + +const base = { + isOpen: true, + fileName: 'app.ts', + before: 'const a = 1\n', + after: 'const a = 2\n', + language: 'text', + onConfirm: vi.fn(), + onCancel: vi.fn(), +} + +function renderDialog(props: Partial> = {}) { + return render( + + + , + ) +} + +describe('EditConfirmDialog', () => { + it('保存确认:展示带文件名的 diff + 两个动作', () => { + renderDialog() + + expect(screen.getByTestId('edit-confirm-dialog')).toBeTruthy() + expect(screen.getByTestId('edit-confirm-diff')).toBeTruthy() + // 文件名出现在 diff 头部(工具卡片同款) + expect(screen.getByText('app.ts')).toBeTruthy() + expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Cancel' })).toBeTruthy() + expect(screen.queryByTestId('edit-confirm-conflict')).toBeNull() + }) + + it('冲突保存:多一行警告,主按钮变成「覆盖」', () => { + renderDialog({ conflict: true }) + + expect(screen.getByTestId('edit-confirm-conflict')).toBeTruthy() + expect(screen.getByRole('button', { name: 'Overwrite' })).toBeTruthy() + }) + + it('放弃改动:按钮是危险色的「放弃」', () => { + renderDialog({ mode: 'discard' }) + + const discard = screen.getByRole('button', { name: 'Discard' }) + expect(discard).toBeTruthy() + expect(discard.className).toContain('bg-danger-100') + }) + + it('大 diff 也照常渲染(不做体积兜底)', () => { + const big = 'x'.repeat(220_000) + renderDialog({ before: big, after: `${big}y` }) + + expect(screen.getByTestId('edit-confirm-diff')).toBeTruthy() + }) + + it('确认键不自动聚焦(Enter 不该直接写盘 / 丢改动)', () => { + renderDialog() + + expect(screen.getByRole('button', { name: 'Save' })).not.toBe(document.activeElement) + }) + + it('确认 / 取消分别回调', () => { + const onConfirm = vi.fn() + const onCancel = vi.fn() + renderDialog({ onConfirm, onCancel }) + + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + expect(onConfirm).toHaveBeenCalledTimes(1) + + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(onCancel).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/components/EditConfirmDialog.tsx b/src/components/EditConfirmDialog.tsx new file mode 100644 index 000000000..bbb86daae --- /dev/null +++ b/src/components/EditConfirmDialog.tsx @@ -0,0 +1,98 @@ +import { useTranslation } from 'react-i18next' +import { Dialog } from './ui' +import { DiffView } from './DiffView' + +// ============================================ +// EditConfirmDialog — 保存 / 放弃改动的二次确认(需求三) +// +// 为什么不自己画 diff:工具调用卡片里的 `DiffView` 才是项目里 diff 的标准形态 +// —— 自带文件名、+/- 统计、折叠、**全屏**,把它搬进来就不用再维持第二套观感。 +// +// 误触一次就会写盘或丢改动,所以两条路都要先看一眼 diff;确认键**不做默认 +// 聚焦**(Enter 不会直接落盘),Esc = 取消。 +// ============================================ + +/** diff 区高度上限:够看,又不至于把动作按钮挤出屏幕 */ +const DIFF_MAX_HEIGHT = 520 + +export interface EditConfirmDialogProps { + isOpen: boolean + mode: 'save' | 'discard' + fileName: string + /** diff 前:保存 = 磁盘当前内容;放弃 = 我的草稿 */ + before: string + /** diff 后:保存 = 我的草稿;放弃 = 磁盘当前内容 */ + after: string + language?: string + /** 保存时的冲突标记(磁盘已被别人改过) */ + conflict?: boolean + busy?: boolean + onConfirm: () => void + onCancel: () => void +} + +export function EditConfirmDialog({ + isOpen, + mode, + fileName, + before, + after, + language = 'text', + conflict = false, + busy = false, + onConfirm, + onCancel, +}: EditConfirmDialogProps) { + const { t } = useTranslation(['components', 'common']) + + const title = + mode === 'save' + ? t('fileExplorer.confirmSaveTitle', { name: fileName }) + : t('fileExplorer.confirmDiscardTitle', { name: fileName }) + + return ( + +
+ {mode === 'save' && conflict && ( +

+ {t('fileExplorer.confirmSaveConflict')} +

+ )} + + {/* 与工具卡片同一个组件:头部有文件名 / +/- 统计 / 全屏按钮 */} +
+ +
+ +
+ + +
+
+
+ ) +} diff --git a/src/components/FileExplorer.tsx b/src/components/FileExplorer.tsx index fe2684e8b..9cd65d357 100644 --- a/src/components/FileExplorer.tsx +++ b/src/components/FileExplorer.tsx @@ -19,8 +19,13 @@ import { MaximizeIcon, SearchIcon, CloseIcon, + PencilIcon, + CheckIcon, } from './Icons' import { CodePreview } from './CodePreview' +import { setFileEditorDirty } from '../store/unsavedFileStore' +import { EditConfirmDialog } from './EditConfirmDialog' +import { hashBytes } from '../utils/textEncoding' import { HtmlFilePreviewFrame } from './HtmlFilePreviewFrame' import { PreviewTabsBar, type PreviewTabsBarItem } from './PreviewTabsBar' import { MarkdownRenderer } from './MarkdownRenderer' @@ -144,6 +149,9 @@ export const FileExplorer = memo(function FileExplorer({ previewLoading, previewError, loadPreview, + savePreview, + externalChange, + clearExternalChange, clearPreview, effectiveDirectory, fileStatus, @@ -483,6 +491,12 @@ export const FileExplorer = memo(function FileExplorer({ targetKey={scopedPreviewFile?.targetKey} targetRanges={scopedPreviewFile?.targetRanges} content={previewContent} + onSave={savePreview} + externalChange={externalChange} + onClearExternalChange={clearExternalChange} + onReload={async reloadPath => { + await loadPreview(reloadPath, true) + }} isLoading={previewLoading} error={previewError} onClose={handleClosePreview} @@ -744,6 +758,13 @@ interface FilePreviewProps { onActivatePreview: (path: string) => void onClosePreview: (path: string) => void onReorderPreview: (draggedPath: string, targetPath: string) => void + /** 保存(需求三:基线比对 + 保真写回);未提供则不可编辑保存 */ + onSave?: (path: string, text: string, baselineHash?: string, force?: boolean, unifyEol?: boolean) => Promise + /** 冲突时"重新载入":绕过缓存从磁盘重读 */ + onReload?: (path: string) => Promise | void + /** 正在预览的文件被外部改动过(agent / 别的编辑器) */ + externalChange?: { path: string } | null + onClearExternalChange?: () => void isResizing?: boolean directory?: string } @@ -761,12 +782,150 @@ function FilePreview({ onActivatePreview, onClosePreview, onReorderPreview, + onSave, + onReload, + externalChange, + onClearExternalChange, isResizing = false, directory, }: FilePreviewProps) { const { t } = useTranslation(['components', 'common']) const scrollRef = useRef(null) + // ============================================ + // 编辑模式(需求三,交互对齐 PiUI) + // + // 显式进入编辑态:铅笔 → ✓ 保存 / ✕ 取消。dirty = 草稿与磁盘内容不同; + // 保存失败在内容区顶部给横幅,冲突(STALE_REVISION)额外给"重新载入 / 覆盖"。 + // ============================================ + const [isEditing, setIsEditing] = useState(false) + const [draft, setDraft] = useState('') + const [isSaving, setIsSaving] = useState(false) + const [saveError, setSaveError] = useState(null) + const [saveConflict, setSaveConflict] = useState(false) + + /** 上次保存因混合行尾被拒(显示"按多数行尾统一"兜底按钮) */ + const [mixEolFallback, setMixEolFallback] = useState(false) + /** 进入编辑时的基线指纹:保存前用它判断磁盘是否被别人改过 */ + const [baselineHash, setBaselineHash] = useState() + + const originalText = content && !content.isBinary ? content.content : '' + + const beginEditing = useCallback(() => { + if (!content || content.isBinary) return + setDraft(content.content) + setSaveError(null) + setSaveConflict(false) + setBaselineHash(content.bytes ? hashBytes(content.bytes) : undefined) + setIsEditing(true) + }, [content]) + + const cancelEditing = useCallback(() => { + setIsEditing(false) + setDraft('') + setSaveError(null) + setSaveConflict(false) + }, []) + + const saveEditing = useCallback( + async (force = false, unifyEol = false) => { + if (!path || isSaving || !onSave) return + setIsSaving(true) + setSaveError(null) + try { + await onSave(path, draft, baselineHash, force, unifyEol) + setIsEditing(false) + setSaveConflict(false) + setMixEolFallback(false) + } catch (failure) { + setSaveError(failure instanceof Error ? failure.message : t('fileExplorer.saveFailed')) + setMixEolFallback(Boolean(failure && typeof failure === 'object' && 'code' in failure && failure.code === 'MIXED_EOL')) + setSaveConflict( + Boolean(failure && typeof failure === 'object' && 'code' in failure && failure.code === 'STALE_REVISION'), + ) + } finally { + setIsSaving(false) + } + }, + [baselineHash, draft, isSaving, onSave, path, t], + ) + + const isDirty = isEditing && draft !== originalText + + /** + * 二次确认:写盘前、丢改动前都先让人看一眼 diff(防误触)。 + * run 是"确认后才执行"的动作,所以切 tab / 关 tab 也能挂进来。 + */ + const [confirmState, setConfirmState] = useState<{ mode: 'save' | 'discard'; conflict?: boolean; run: () => void } | null>( + null, + ) + const requestSave = useCallback( + (force: boolean) => { + if (!isDirty && !force) return + setConfirmState({ mode: 'save', conflict: force || saveConflict, run: () => void saveEditing(force) }) + }, + [isDirty, saveConflict, saveEditing], + ) + const requestDiscard = useCallback( + (run: () => void) => { + if (!isDirty) { + run() + return + } + setConfirmState({ mode: 'discard', run }) + }, + [isDirty], + ) + + /** 外部改动的一次性轻提示(几秒后自己消失,不打断输入) */ + const [externalNotice, setExternalNotice] = useState(null) + useEffect(() => { + if (!externalChange || externalChange.path !== path) return + if (isDirty) { + // 我在改、磁盘也变了:不覆盖草稿,标成冲突,保存时基线比对会再确认一次 + setSaveConflict(true) + setSaveError(t('fileExplorer.saveConflict')) + } else { + setExternalNotice(t('fileExplorer.externalUpdated')) + } + onClearExternalChange?.() + }, [externalChange, isDirty, onClearExternalChange, path, t]) + + useEffect(() => { + if (!externalNotice) return + const timer = window.setTimeout(() => setExternalNotice(null), 4000) + return () => window.clearTimeout(timer) + }, [externalNotice]) + + // 应用级脏标记(关窗/离开前拦一道) + useEffect(() => { + if (!path) return + // editorId 带目录:不同工作区可能有同名文件,只按相对路径会串号 + const editorId = `${directory ?? ""}::${path}` + setFileEditorDirty(editorId, isDirty) + return () => setFileEditorDirty(editorId, false) + }, [directory, isDirty, path]) + + useEffect(() => { + if (!isDirty) return + const beforeUnload = (event: BeforeUnloadEvent) => event.preventDefault() + window.addEventListener('beforeunload', beforeUnload) + return () => window.removeEventListener('beforeunload', beforeUnload) + }, [isDirty]) + + // Ctrl/Cmd+S 保存(编辑器自身不绑,避免和输入框抢) + useEffect(() => { + if (!isEditing) return + const onKeyDown = (event: KeyboardEvent) => { + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { + event.preventDefault() + requestSave(false) + } + } + window.addEventListener('keydown', onKeyDown) + return () => window.removeEventListener('keydown', onKeyDown) + }, [isEditing, requestSave]) + // 获取文件名 const fileName = path?.split(/[/\\]/).pop() || 'Untitled' const language = path ? detectLanguage(path) : 'text' @@ -785,9 +944,19 @@ function FilePreview({ title: file.path, closeTitle: `${t('common:close')} ${file.name}`, iconPath: file.path, - label: {file.name}, + label: ( + + {file.path === path && isDirty && ( + + ● + + )} + {file.path === path && saveConflict && ⚠} + {file.name} + + ), })), - [previewFiles, t], + [isDirty, path, previewFiles, saveConflict, t], ) // 处理内容类型分发 @@ -962,14 +1131,46 @@ function FilePreview({ items={previewTabItems} activeId={path} closeAllTitle={t('common:closeAllTabs')} - onActivate={onActivatePreview} - onClose={onClosePreview} - onCloseAll={onClose} + onActivate={nextPath => requestDiscard(() => onActivatePreview(nextPath))} + onClose={closePath => requestDiscard(() => onClosePreview(closePath))} + onCloseAll={() => requestDiscard(() => onClose())} onReorder={onReorderPreview} tabWidthClassName="w-auto max-w-none min-w-max" rightActions={ content ? ( <> + {!content.isBinary && + (isEditing ? ( + <> + + + + ) : ( + + ))} + )} + {saveConflict && ( + + + + + )} +
+ )} +
+ +
+ ) : displayContent?.type === 'media' ? ( - displayContent?.type === 'text' ? ( + displayContent?.type === 'text' && !isEditing ? ( - ) : ( + ) : displayContent?.type === 'text' ? null : (
{t('common:noContent')}
diff --git a/src/components/MarkdownRenderer.test.tsx b/src/components/MarkdownRenderer.test.tsx index ab7573022..aa842aafc 100644 --- a/src/components/MarkdownRenderer.test.tsx +++ b/src/components/MarkdownRenderer.test.tsx @@ -1,6 +1,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MarkdownRenderer } from './MarkdownRenderer' +import { themeStore } from '../store/themeStore' import { clearMermaidRenderCache } from './mermaidRenderCache' const mermaidMocks = vi.hoisted(() => ({ @@ -71,6 +72,8 @@ vi.mock('./ui', () => ({ describe('MarkdownRenderer', () => { beforeEach(() => { + // raw HTML 的渲染/净化用例要显式打开这个开关:它的默认值已改为关闭 + themeStore.setRenderHtmlContent(true) themeMock.resolvedTheme = 'light' clearMermaidRenderCache() useInputCapabilitiesMock.mockReset() @@ -94,14 +97,22 @@ describe('MarkdownRenderer', () => { expect(codeEl.tagName).toBe('CODE') }) - it('renders inline code with accent text styling (no border/bg)', () => { + it('renders inline code as a muted monospace chip (no accent color)', () => { render() const codeEl = screen.getByText('code') - expect(codeEl.className).not.toMatch(/border/) - expect(codeEl.className).not.toMatch(/bg-accent-main/) + // chip 样式:等宽 + 淡底 + 细描边 + flex 垂直居中;颜色继承正文 expect(codeEl.className).toMatch(/font-mono/) - expect(codeEl.className).toMatch(/text-accent-main-100/) + expect(codeEl.className).not.toMatch(/text-text-\d/) + expect(codeEl.className).toMatch(/bg-bg-200/) + expect(codeEl.className).toMatch(/border-\[0\.5px\]/) + expect(codeEl.className).toMatch(/rounded-md/) + expect(codeEl.className).toMatch(/px-\[5px\]/) + // 纵向不能靠继承段落行高(leading-7=28px):chip 会高出一截,和正文对不上 + expect(codeEl.className).toMatch(/inline-flex/) + expect(codeEl.className).toMatch(/items-center/) + expect(codeEl.className).toMatch(/leading-tight/) + expect(codeEl.className).not.toMatch(/text-accent-main/) }) it('renders inline code inside list items as code elements', () => { @@ -111,7 +122,8 @@ describe('MarkdownRenderer', () => { expect(codeEl).toBeInTheDocument() expect(codeEl).toHaveTextContent('单行代码') expect(codeEl).toHaveClass('font-mono') - expect(codeEl).toHaveClass('text-accent-main-100') + expect(codeEl).toHaveClass('bg-bg-200') + expect(codeEl).toHaveClass('inline-flex') }) it('keeps inline emphasis styles on the markdown path', () => { @@ -235,6 +247,74 @@ $$ expect(checkbox).toBeInTheDocument() }) + it('renders one checkbox per task list item', () => { + const { container } = render() + + // marked 把 `[x]` 切成独立的 checkbox token,渲染器不能再自己加一个 + expect(container.querySelectorAll('input[type="checkbox"]')).toHaveLength(2) + expect(container.querySelector('li input[type="checkbox"][checked]')).toBeInTheDocument() + }) + + it('emphasizes CJK runs that close after punctuation right before a CJK character', () => { + const content = '**重点:**正文,**第二点。**继续,*斜体:*结尾,**(括号)**收尾' + const { container } = render() + + expect(Array.from(container.querySelectorAll('strong')).map(node => node.textContent)).toEqual([ + '重点:', + '第二点。', + '(括号)', + ]) + expect(container.querySelector('em')).toHaveTextContent('斜体:') + expect(container.textContent).not.toContain('**') + expect(container.textContent).not.toContain('*斜体') + }) + + it('keeps already-valid emphasis and intraword underscores literal', () => { + const { container } = render() + + expect(Array.from(container.querySelectorAll('strong')).map(node => node.textContent)).toEqual(['粗体', '重点']) + expect(container.textContent).toContain('snake_case_word') + }) + + it('keeps currency amounts literal instead of rendering them as math', () => { + const content = '价格是 $5 到 $10 之间,花费 $100 和 $200' + const { container } = render() + + expect(container.querySelector('.katex')).not.toBeInTheDocument() + expect(container.querySelector('p')).toHaveTextContent(content) + }) + + it('still renders inline dollar math', () => { + const { container } = render() + + expect(container.querySelector('.katex')).toBeInTheDocument() + expect(container.querySelector('p')).toHaveTextContent('公式') + expect(container.querySelector('p')).toHaveTextContent('成立') + }) + + it('renders footnotes when the definition follows the paragraph without a blank line', () => { + const { container } = render() + + // 不能退化成链接引用定义:`[^note]` 曾经被渲染成 href 是脚注内容的 + expect(container.querySelector('a[href="没有空行分隔的脚注"]')).toBeNull() + expect(container.querySelector('#fnref-note')).toHaveTextContent('note') + expect(container.querySelector('#fn-note')).toHaveTextContent('没有空行分隔的脚注') + expect(container.textContent).toContain('正文') + }) + + it('keeps the prose that follows footnote definitions', () => { + const { container } = render() + + expect(container.querySelector('#fn-a')).toHaveTextContent('甲') + expect(container.textContent).toContain('后续段落') + }) + + it('does not double escape html entities in text', () => { + const { container } = render() + + expect(container.querySelector('p')?.textContent).toBe('a & b') + }) + it('renders fenced code blocks via CodeBlock', () => { render() @@ -470,7 +550,8 @@ $$ expect(paragraph.className).toMatch(/text-text-400/) const codeEl = screen.getByText('code') - expect(codeEl.className).not.toMatch(/border/) + // chip 也有描边(0.5px 细边),但底色不能是强调色 + expect(codeEl.className).toMatch(/border-\[0\.5px\]/) expect(codeEl.className).not.toMatch(/bg-accent/) }) @@ -1512,3 +1593,55 @@ $$` expect(screen.queryByRole('link', { name: 'bad' })).not.toBeInTheDocument() }) }) + +describe('MarkdownRenderer HTML 渲染开关', () => { + beforeEach(() => { + themeStore.setRenderHtmlContent(false) + }) + afterEach(() => { + // 还原成默认值(已改为关闭) + themeStore.setRenderHtmlContent(false) + }) + + it('关闭后完整 HTML 文档按源码代码块展示,不起沙箱预览', () => { + render( + \n

Document

'} + />, + ) + + expect(screen.queryByTitle('HTML preview')).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:') + }) + + it('关闭后块级 HTML 不再渲染成活内容,直接展示源码', () => { + render(Rendered HTML'} />) + + expect(screen.queryByText('Rendered HTML')).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'View HTML source' })).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:
Rendered HTML
') + }) + + it('关闭后 html 代码块不再给预览,只按普通代码块展示', () => { + render(Run\n```'} />) + + expect(screen.queryByTitle('HTML preview')).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:') + }) + + it('关闭后正文里混的内联 HTML 转义成文本源码', () => { + const { container } = render( + inline HTML after.'} />, + ) + + expect(container.querySelector('span[style]')).toBeNull() + expect(container.textContent).toContain('inline HTML') + }) + + it('重新开启后恢复活渲染', () => { + themeStore.setRenderHtmlContent(true) + render(Rendered HTML'} />) + + expect(screen.getByText('Rendered HTML').tagName).toBe('STRONG') + }) +}) diff --git a/src/components/MarkdownRenderer.tsx b/src/components/MarkdownRenderer.tsx index a5bded441..c998c5ad7 100644 --- a/src/components/MarkdownRenderer.tsx +++ b/src/components/MarkdownRenderer.tsx @@ -8,6 +8,7 @@ import { useMemo, useRef, useState, + useSyncExternalStore, } from 'react' import morphdom from 'morphdom' import { CodeBlock } from './CodeBlock' @@ -22,6 +23,12 @@ import type { Tokens } from 'marked' import { isMarkupPreviewLanguage, projectMarkdownStream, stripLeadingHtmlComments, type MarkdownStreamProjection } from './markdownStream' import { renderMarkdownToHtml, renderKatexHtml } from './markdownHtmlRenderer' import { getFootnoteId, scanTextSegments } from './markdownSegments' +import { themeStore } from '../store/themeStore' + +/** 只订阅 renderHtmlContent 布尔值(useTheme 全量订阅会让每条消息的 markdown 跟着任何设置变动重渲染) */ +function useRenderHtmlContent(): boolean { + return useSyncExternalStore(themeStore.subscribe, () => themeStore.renderHtmlContent) +} import type { MarkdownSegment } from './markdownSegments' import { buildHtmlSandboxThemeCss, @@ -71,11 +78,11 @@ const PREFIXED_BLOCK_HTML_SOURCE_PATTERN = /^\s*<(?:style|script)\b[\s\S]*<(?:ad const ARTIFACT_HTML_SOURCE_PATTERN = /(?:= HTML_CACHE_MAX) { const firstKey = htmlCache.keys().next().value if (firstKey !== undefined) htmlCache.delete(firstKey) @@ -688,7 +695,18 @@ function renderInlineTokensToReact(tokens: unknown[], _isReasoning: boolean): Re if (item.type === 'del') { return {renderInlineTokensToReact((item.tokens as unknown[]) ?? [], _isReasoning)} } - if (item.type === 'codespan') return {String(item.text ?? '')} + if (item.type === 'codespan') { + // 与 markdownHtmlRenderer 的 codespan 保持一致(两条路径不一致的话, + // 同一条消息里会出现两种内联代码样式) + return ( + + {String(item.text ?? '')} + + ) + } if (item.type === 'link') { const href = typeof item.href === 'string' ? item.href : undefined if (isUnsafeHrefInline(href)) return {renderInlineTokensToReact((item.tokens as unknown[]) ?? [], _isReasoning)} [blocked] @@ -1243,10 +1261,12 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ src, isReasoning, isLive, + renderHtml, }: { src: string isReasoning: boolean isLive?: boolean + renderHtml: boolean }) { const rootRef = useRef(null) const appliedHtmlRef = useRef(null) @@ -1293,7 +1313,9 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ } // live 中间态不进 htmlCache(避免 64 槽被流式碎片挤爆);稳定块才缓存 - const html = isLive ? renderMarkdownToHtml(renderSrc, isReasoning) : getCachedHtml(renderSrc, isReasoning) + const html = isLive + ? renderMarkdownToHtml(renderSrc, isReasoning, renderHtml) + : getCachedHtml(renderSrc, isReasoning, renderHtml) if (appliedHtmlRef.current === html) { appliedSrcRef.current = renderSrc return @@ -1301,7 +1323,7 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ appliedHtmlRef.current = html appliedSrcRef.current = renderSrc applyMarkdownHtml(root, html) - }, [renderSrc, isReasoning, isLive]) + }, [renderSrc, isReasoning, isLive, renderHtml]) const handleClick = useCallback((event: React.MouseEvent) => { if (event.defaultPrevented) return @@ -1369,7 +1391,7 @@ function MarkdownHtmlIsland({ return ( setShowSource(true)}> - + ) } @@ -1383,6 +1405,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ complete, isReasoning, isStreaming, + renderHtml, }: { src: string mode: 'full' | 'live' | 'code' | 'table' @@ -1390,6 +1413,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ complete?: boolean isReasoning: boolean isStreaming: boolean + renderHtml: boolean }) { // 流式高亮/未完成态只对「未闭合 code」或 live 有意义;稳定 full 块 isStreaming 恒 false 以冻 memo const streamActive = isStreaming && (mode === 'live' || (mode === 'code' && !complete)) @@ -1412,7 +1436,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ ) } - if (isMarkupPreviewLanguage(language) && !isReasoning) { + if (renderHtml && isMarkupPreviewLanguage(language) && !isReasoning) { return (
@@ -1449,7 +1473,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ const isHtmlArtifact = ARTIFACT_HTML_SOURCE_PATTERN.test(src) && (BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart) || PREFIXED_BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) - if (!isReasoning && (isHtmlDocument || isHtmlArtifact)) { + if (renderHtml && !isReasoning && (isHtmlDocument || isHtmlArtifact)) { return (
@@ -1459,7 +1483,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ ) } - if (!isReasoning && BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) { + if (renderHtml && !isReasoning && BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) { return (
@@ -1467,9 +1491,22 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ ) } + // 关闭 HTML 渲染:HTML 文档/artifact/island 一律按源码代码块展示 + if (!renderHtml && !isReasoning && (isHtmlDocument || isHtmlArtifact || BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart))) { + return ( +
+
+
+ +
+
+
+ ) + } + return (
- +
) }) @@ -1525,7 +1562,8 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ }: MarkdownRendererProps) { const isReasoning = variant === 'reasoning' const projectionKey = useId() - const renderHtmlImmediately = isStreaming && STREAMING_HTML_CONTENT_PATTERN.test(content) + const renderHtml = useRenderHtmlContent() + const renderHtmlImmediately = isStreaming && renderHtml && STREAMING_HTML_CONTENT_PATTERN.test(content) const smoothedContent = useSmoothMarkdownStream(content, isStreaming && !renderHtmlImmediately) const renderedContent = renderHtmlImmediately ? content : isStreaming ? smoothedContent : content const streamBlocks = useMemo(() => { @@ -1552,6 +1590,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ language={block.language} complete={block.complete} isReasoning={isReasoning} + renderHtml={renderHtml} isStreaming={ isStreaming && (block.mode === 'live' || (block.mode === 'code' && !block.complete)) } diff --git a/src/components/McpPanel.tsx b/src/components/McpPanel.tsx index 392892e31..2c1f026ff 100644 --- a/src/components/McpPanel.tsx +++ b/src/components/McpPanel.tsx @@ -221,7 +221,7 @@ export const McpPanel = memo(function McpPanel({ isResizing: _isResizing }: McpP onClick={() => setShowAddForm(true)} disabled={showAddForm} aria-label={t('mcpPanel.addServer')} - className="inline-flex h-6 w-6 items-center justify-center hover:bg-bg-200/50 rounded-md text-text-300 hover:text-text-100 transition-colors disabled:opacity-50" + className="inline-flex h-6 w-6 items-center justify-center text-text-400 hover:bg-bg-200/50 rounded-md hover:text-text-100 transition-colors disabled:opacity-50" title={t('mcpPanel.addServer')} > @@ -231,7 +231,7 @@ export const McpPanel = memo(function McpPanel({ isResizing: _isResizing }: McpP onClick={handleRefresh} disabled={loading} aria-label={t('common:refresh')} - className="inline-flex h-6 w-6 items-center justify-center hover:bg-bg-200/50 rounded-md text-text-300 hover:text-text-100 transition-colors disabled:opacity-50" + className="inline-flex h-6 w-6 items-center justify-center text-text-400 hover:bg-bg-200/50 rounded-md hover:text-text-100 transition-colors disabled:opacity-50" title={t('common:refresh')} > diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx index c1059546f..d3414a343 100644 --- a/src/components/PluginsPanel.tsx +++ b/src/components/PluginsPanel.tsx @@ -67,11 +67,11 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing return (
- {/* Header */} -
-
+ {/* Header(横线风格与 McpPanel 一致:独立 h-px 细线、两侧内缩) */} +
+
- {t('pluginsPanel.title')} + {t('pluginsPanel.title')}
+
{/* List */} @@ -105,14 +106,27 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing
) : (
- {plugins.map(plugin => { - const label = pluginLabel(plugin) - const state = plugin.state - const failed = state.status === 'failed' - const source = plugin.source - const pkg = source.type === 'package' ? source : null - const outdated = pkg?.outdated === true - const updatingThis = updating !== null && pkg?.target === updating + {plugins.map(plugin => { + const label = pluginLabel(plugin) + const state = plugin.state + const failed = state.status === 'failed' + const source = plugin.source + const pkg = source.type === 'package' ? source : null + const outdated = pkg?.outdated === true + const updatingThis = updating !== null && pkg?.target === updating + // 来源位置:local → 路径;package → target@version;sdk → 类型标签。 + // 加载失败的插件没有 id,标题本身已回退成路径(即位置),所以失败时副标题留给错误信息; + // 正常加载的插件标题是 id(名字),位置要在副标题显示出来。 + const location = + source.type === 'local' + ? source.path + : pkg + ? pkg.version + ? `${pkg.target}@${pkg.version}` + : pkg.target + : t(`pluginsPanel.source.${source.type}`) + // 位置与标题相同(如无 id 的 local 插件)时不重复,退回类型标签 + const secondary = location === label ? t(`pluginsPanel.source.${source.type}`) : location return (
@@ -128,8 +142,8 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing {t('pluginsPanel.failed')}: {state.error} ) : ( - - {pkg?.version ? `${pkg.target}@${pkg.version}` : t(`pluginsPanel.source.${source.type}`)} + + {secondary} )}
diff --git a/src/components/SessionChangesPanel.tsx b/src/components/SessionChangesPanel.tsx index 08de5f8c9..850f0098d 100644 --- a/src/components/SessionChangesPanel.tsx +++ b/src/components/SessionChangesPanel.tsx @@ -16,7 +16,7 @@ import { getSessionDiff } from '../api/session' import { getVcsDiff, getVcsInfo } from '../api/vcs' import type { ApiProject, FileDiff, VcsInfo } from '../api/types' import { detectLanguage } from '../utils/languageUtils' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { sessionErrorHandler } from '../utils' import { PreviewTabsBar, type PreviewTabsBarItem } from './PreviewTabsBar' import { useVerticalSplitResize } from '../hooks/useVerticalSplitResize' @@ -106,6 +106,8 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ // 展开的目录 const [expandedDirs, setExpandedDirs] = useState>(new Set()) + // 已经出现过的目录路径:刷新时只把「新出现的目录」默认展开,不动用户手动展开/折叠的状态 + const seenDirPathsRef = useRef>(new Set()) const [fileContextMenu, setFileContextMenu] = useState<{ x: number; y: number; file: string } | null>(null) const projectRequestIdRef = useRef(0) @@ -162,6 +164,9 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ [branchDiffs, changeMode, gitDiffs, turnDiffs], ) const loading = projectLoading || loadingModes[changeMode] + // 仅「首次加载(还没数据)」才把内容区换成 loading 占位; + // 已有数据时的自动刷新保留现有列表与预览,新数据到了就地更新——刷新无感。 + const initialLoading = loading && diffs.length === 0 const focusChangeMenuOption = useCallback((mode: ChangeMode) => { changeMenuOptionRefs.current[mode]?.focus() @@ -399,6 +404,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ setSelectedFile(null) setMountedPreviewFiles(new Set()) setExpandedDirs(new Set()) + seenDirPathsRef.current = new Set() setChangeMenuOpen(false) resetSplitHeight() @@ -418,7 +424,19 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ }, [changeMode, changeOptions, loadDiffMode, project?.vcs]) useEffect(() => { - setExpandedDirs(collectExpandedDirPaths(buildChangesTree(diffs))) + // 刷新时保留用户手动展开/折叠:首次(seen 为空)全部默认展开; + // 之后只把「新出现的目录」默认展开,已有的展开/折叠状态不动。 + const currentDirs = collectExpandedDirPaths(buildChangesTree(diffs)) + const seen = seenDirPathsRef.current + setExpandedDirs(prev => { + const next = new Set(prev) + for (const dir of currentDirs) { + if (!seen.has(dir)) next.add(dir) + } + return next + }) + seenDirPathsRef.current = new Set([...seen, ...currentDirs]) + const { nextOpenFiles, nextActiveFile } = reconcileDiffPreviewState( diffs, openDiffFilesRef.current, @@ -438,8 +456,10 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ await loadDiffMode(changeMode, { force: true, project: nextProject }) }, [changeMode, loadDiffMode, loadProjectState]) - // 自动刷新:session idle / 窗口聚焦 / SSE 重连 - useAutoRefresh(consumerId, sessionId ?? null, handleRefresh, !!sessionId) + // 自动刷新:文件/分支变更事件 + session idle + SSE 重连(见 useAutoRefresh) + useAutoRefresh(consumerId, sessionId ?? null, handleRefresh, !!sessionId, { + watchDirectory: directory, + }) // 选中文件 const handleSelectFile = useCallback((file: string) => { @@ -548,7 +568,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ () => previewDiffs.filter(diff => diff.file === selectedFile || mountedPreviewFiles.has(diff.file)), [mountedPreviewFiles, previewDiffs, selectedFile], ) - const showPreview = !loading && selectedDiff !== null && !(error && diffs.length === 0) + const showPreview = !initialLoading && selectedDiff !== null && !(error && diffs.length === 0) if (projectLoading && !project) { return
{t('sessionChanges.loadingChanges')}
@@ -785,7 +805,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ {/* File List */}
- {loading ? ( + {initialLoading ? (
{t('sessionChanges.loadingChanges')}
) : error && diffs.length === 0 ? (
{error}
@@ -929,9 +949,9 @@ const DiffPreviewPanel = memo(function DiffPreviewPanel({ onClose, }: DiffPreviewPanelProps) { const language = detectLanguage(diff.file) || 'text' - // 优先用 patch 提取 before/after,回退到直接的 before/after 字段(旧版后端兼容) + // 优先用 patch 还原 before/after(带 @@ 绝对行号),回退到直接的 before/after 字段(旧版后端兼容) const { before, after } = useMemo(() => { - if (diff.patch) return extractContentFromUnifiedDiff(diff.patch) + if (diff.patch) return reconstructBeforeAfterFromPatch(diff.patch) ?? extractContentFromUnifiedDiff(diff.patch) if (diff.before !== undefined && diff.after !== undefined) return { before: diff.before, after: diff.after } return { before: '', after: '' } }, [diff.patch, diff.before, diff.after]) diff --git a/src/components/SkillPanel.tsx b/src/components/SkillPanel.tsx index 2fec0339b..d1f5ea46b 100644 --- a/src/components/SkillPanel.tsx +++ b/src/components/SkillPanel.tsx @@ -74,7 +74,7 @@ export const SkillPanel = memo(function SkillPanel({ isResizing: _isResizing }: onClick={loadSkills} disabled={loading} aria-label={t('common:refresh')} - className="inline-flex h-6 w-6 items-center justify-center hover:bg-bg-200/50 rounded-md text-text-300 hover:text-text-100 transition-colors disabled:opacity-50" + className="inline-flex h-6 w-6 items-center justify-center text-text-400 hover:bg-bg-200/50 rounded-md hover:text-text-100 transition-colors disabled:opacity-50" title={t('common:refresh')} > diff --git a/src/components/codeMirrorEditableExtensions.test.ts b/src/components/codeMirrorEditableExtensions.test.ts new file mode 100644 index 000000000..e933f4010 --- /dev/null +++ b/src/components/codeMirrorEditableExtensions.test.ts @@ -0,0 +1,49 @@ +import { EditorState } from '@codemirror/state' +import { EditorView, keymap } from '@codemirror/view' +import { describe, expect, it } from 'vitest' +import { createReadonlyCodeMirrorExtensions } from './codeMirrorReadonlyExtensions' + +// ============================================ +// 扩展工厂(需求三) +// +// 只读与可编辑共用一套扩展,差别只有 readOnly 开关与随之而来的撤销栈。 +// 这里锁住三件容易回归的事:默认仍是只读、readOnly=false 真的可编辑且有撤销、 +// 搜索面板两模式都在。 +// ============================================ + +const base = { wordWrap: false, lineHeight: 24, lineNumberWidth: 24 } + +function facets(extensions: ReturnType) { + const state = EditorState.create({ doc: 'hello', extensions }) + return { + readOnly: state.facet(EditorState.readOnly), + editable: state.facet(EditorView.editable), + bindings: state.facet(keymap).flat(), + } +} + +describe('CodeMirror 扩展工厂', () => { + it('默认只读:readOnly 恒真(原行为不变)', () => { + const { readOnly } = facets(createReadonlyCodeMirrorExtensions({ ...base })) + expect(readOnly).toBe(true) + }) + + it('readOnly=false:可写、可编辑,并带撤销栈快捷键', () => { + const { readOnly, editable, bindings } = facets(createReadonlyCodeMirrorExtensions({ ...base, readOnly: false })) + + expect(readOnly).toBe(false) + expect(editable).toBe(true) + + const keys = bindings.map(binding => binding.key) + expect(keys).toContain('Mod-z') + expect(keys).toContain('Mod-y') + }) + + it('两模式都有搜索面板(Mod-f)', () => { + const readonlyKeys = facets(createReadonlyCodeMirrorExtensions({ ...base })).bindings.map(b => b.key) + const editableKeys = facets(createReadonlyCodeMirrorExtensions({ ...base, readOnly: false })).bindings.map(b => b.key) + + expect(readonlyKeys).toContain('Mod-f') + expect(editableKeys).toContain('Mod-f') + }) +}) diff --git a/src/components/codeMirrorReadonlyExtensions.ts b/src/components/codeMirrorReadonlyExtensions.ts index e5aa56d12..dbd372415 100644 --- a/src/components/codeMirrorReadonlyExtensions.ts +++ b/src/components/codeMirrorReadonlyExtensions.ts @@ -1,4 +1,4 @@ -import { defaultKeymap } from '@codemirror/commands' +import { defaultKeymap, history, historyKeymap } from '@codemirror/commands' import { EditorState, StateEffect, StateField, type Extension, type Range } from '@codemirror/state' import { closeSearchPanel, @@ -16,6 +16,7 @@ import { Decoration, EditorView, drawSelection, + highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers, @@ -24,6 +25,16 @@ import { } from '@codemirror/view' import type { HighlightTokens } from '../hooks/useSyntaxHighlight' +/** 只读 / 可编辑两种模式共用的基础参数 */ +export interface CodeMirrorExtensionOptions { + wordWrap: boolean + lineHeight: number + showLineNumbers?: boolean + maxHeight?: number + lineNumberWidth: number + extraExtensions?: Extension[] +} + export function codeLineHeight(offset: number): number { return 24 + offset * 2 } @@ -34,23 +45,19 @@ export function createReadonlyCodeMirrorExtensions({ showLineNumbers = true, maxHeight, editable = true, + readOnly = true, lineNumberWidth, extraExtensions = [], -}: { - wordWrap: boolean - lineHeight: number - showLineNumbers?: boolean - maxHeight?: number - editable?: boolean - lineNumberWidth: number - extraExtensions?: Extension[] -}): Extension[] { +}: CodeMirrorExtensionOptions & { editable?: boolean; readOnly?: boolean }): Extension[] { const extensions: Extension[] = [ + // editable 的语义是「能否选中文本」(历史上与 maxHeight 绑定);能否编辑看 readOnly EditorView.editable.of(editable), - EditorState.readOnly.of(true), + EditorState.readOnly.of(readOnly), + // 可编辑态补上撤销栈与当前行高亮(只读态不需要) + ...(readOnly ? [] : [history(), highlightActiveLine()]), highlightActiveLineGutter(), drawSelection(), - keymap.of([...searchKeymap, ...defaultKeymap]), + keymap.of([...(readOnly ? [] : historyKeymap), ...searchKeymap, ...defaultKeymap]), search({ top: true, createPanel: createCodeMirrorSearchPanel }), highlightSelectionMatches(), shikiDecorationsField, diff --git a/src/components/markdownHtmlRenderer.ts b/src/components/markdownHtmlRenderer.ts index aa1e71d29..b1c41246b 100644 --- a/src/components/markdownHtmlRenderer.ts +++ b/src/components/markdownHtmlRenderer.ts @@ -4,11 +4,13 @@ import DOMPurify from 'dompurify' import katex from 'katex' import 'katex/dist/katex.min.css' import { inferImageDimensions } from './imageDimensions' -import { MATH_DELIMITERS, getFootnoteId, isEscapedAt, scanTextSegments } from './markdownSegments' +import { MATH_DELIMITERS, getFootnoteId, isDollarMathBoundary, isEscapedAt, scanTextSegments } from './markdownSegments' import type { MarkdownSegment } from './markdownSegments' const LOCAL_FILE_LINK_PREFIX = '#opencode-local-file:' +const ESCAPE_MAP: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } + function escapeHtml(value: string): string { return value .replace(/&/g, '&') @@ -18,6 +20,14 @@ function escapeHtml(value: string): string { .replace(/'/g, ''') } +// 正文文本转义:`&` 只有不再是实体(&、{、😀)时才转义, +// 否则 `a & b` 会被二次转义成 `a &amp; b`(显示成字面的 &)。 +const TEXT_ESCAPE_PATTERN = /[<>"']|&(?!(?:#\d{1,7}|#[Xx][0-9A-Fa-f]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});)/g + +function escapeMarkdownText(value: string): string { + return value.replace(TEXT_ESCAPE_PATTERN, char => ESCAPE_MAP[char] as string) +} + function escapeAttribute(value: string): string { return escapeHtml(value).replace(/`/g, '`') } @@ -124,14 +134,79 @@ const BLOCK_MATH_PATTERNS = MARKED_BLOCK_MATH_DELIMITERS.map(delimiter => ({ pattern: new RegExp(`^${escapeRegex(delimiter.left)}([\\s\\S]*?)${escapeRegex(delimiter.right)}`), })) const INLINE_MATH_PATTERNS = MARKED_INLINE_MATH_DELIMITERS.map(delimiter => ({ + left: delimiter.left, display: delimiter.display, - // `$` / `$$` 保持宽松(货币、简写也能渲染,与原 text 层行为一致); - // `\(` / `\[` 需要明显的公式内容(避免转义括号被误判)。 + // `\(` / `\[` 需要明显的公式内容(避免转义括号被误判); + // `$` 由边界规则兜底(货币、简写不误判)。 gate: delimiter.left.startsWith('\\'), pattern: new RegExp(`^${escapeRegex(delimiter.left)}${delimiter.left === '$' ? '(?!\\$)' : ''}(${delimiter.display ? '[\\s\\S]*?' : '[^\\n]*?'})${escapeRegex(delimiter.right)}`), })) +// ─── CJK 强调闭合 ──────────────────────────────────────────────── +// CommonMark 的 delimiter run 规则要求闭合符是 right-flanking:闭合符前一个字符是标点时, +// 它后面必须紧跟空白或标点,闭合才成立。中文里 `**重点:**正文`「闭合符在标点后、紧跟汉字」 +// 的写法因此不成立,整段退化成字面的 `**重点:**正文`(`**结论。**继续` 同理)。 +// 这里只在「默认规则必然失败」的形态下,把闭合符后那个汉字在 emStrong 的匹配副本里换成空格, +// 让闭合成立;原 src 不动,所以渲染结果不会多出空格。 +const CJK_CHARACTER = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u +const PUNCTUATION_OR_SYMBOL = /[\p{P}\p{S}]/u +const WHITESPACE = /\s/u + +type EmphasisRun = { char: string; length: number; start: number } + +function collectEmphasisRuns(src: string): EmphasisRun[] { + const runs: EmphasisRun[] = [] + for (let index = 0; index < src.length; index += 1) { + const char = src[index] + if (char !== '*' && char !== '_') continue + let end = index + while (end < src.length && src[end] === char) end += 1 + runs.push({ char, length: end - index, start: index }) + index = end - 1 + } + return runs +} + +export function maskCjkEmphasisClose(src: string): string { + if (!src.includes('*') && !src.includes('_')) return src + const openers = new Map() + const masked: number[] = [] + + for (const run of collectEmphasisRuns(src)) { + const prev = run.start > 0 ? (src[run.start - 1] as string) : '' + const next = src[run.start + run.length] ?? '' + const before = prev === '' || WHITESPACE.test(prev) || PUNCTUATION_OR_SYMBOL.test(prev) + const after = next === '' || WHITESPACE.test(next) || PUNCTUATION_OR_SYMBOL.test(next) + const leftFlanking = next !== '' && !WHITESPACE.test(next) && (!PUNCTUATION_OR_SYMBOL.test(next) || before) + const rightFlanking = prev !== '' && !WHITESPACE.test(prev) && (!PUNCTUATION_OR_SYMBOL.test(prev) || after) + const canOpen = run.char === '*' ? leftFlanking : leftFlanking && (!rightFlanking || before) + const canClose = run.char === '*' ? rightFlanking : rightFlanking && (!leftFlanking || after) + const key = `${run.char}${Math.min(run.length, 2)}` + const pending = openers.get(key) ?? 0 + + if (pending > 0 && PUNCTUATION_OR_SYMBOL.test(prev) && CJK_CHARACTER.test(next)) { + masked.push(run.start + run.length) + openers.set(key, pending - 1) + continue + } + if (canClose && pending > 0) { + openers.set(key, pending - 1) + continue + } + if (canOpen) openers.set(key, pending + 1) + } + + if (!masked.length) return src + const chars = src.split('') + for (const index of masked) { + if (!CJK_CHARACTER.test(chars[index] ?? '')) continue + chars[index] = ' ' + } + return chars.join('') +} + marked.use({ + hooks: { emStrongMask: maskCjkEmphasisClose }, tokenizer: { del(src: string) { const cap = /^~~(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))~~(?=[^~]|$)/.exec(src) @@ -188,11 +263,13 @@ marked.use({ return index }, tokenizer(src: string) { - for (const { display, gate, pattern } of INLINE_MATH_PATTERNS) { + for (const { left, display, gate, pattern } of INLINE_MATH_PATTERNS) { const match = pattern.exec(src) - if (match?.[1] && (!gate || looksLikeMath(match[1]))) { - return { type: 'math', raw: match[0], text: match[1], display } - } + if (!match?.[1]) continue + if (gate && !looksLikeMath(match[1])) continue + // 单个 `$`:货币/简写不当作公式(`$5 到 $10`、`$100 和 $200`) + if (left === '$' && !isDollarMathBoundary(src, 0, match[0].length - 1)) continue + return { type: 'math', raw: match[0], text: match[1], display } } return undefined }, @@ -219,7 +296,7 @@ function renderSegmentsToHtml(segments: MarkdownSegment[], isReasoning: boolean) .map(segment => { switch (segment.type) { case 'text': - return escapeHtml(segment.text) + return escapeMarkdownText(segment.text) case 'math': return renderKatexHtml(segment.latex, segment.display) case 'mark': { @@ -273,9 +350,17 @@ const MARKDOWN_ALERTS = { }, } as const -function createMarkdownHtmlRenderer(isReasoning: boolean) { +function createMarkdownHtmlRenderer(isReasoning: boolean, renderHtml: boolean) { const renderer = new marked.Renderer() + // 关闭 HTML 渲染时:markdown 里的裸 HTML(块级+内联)一律转义成文本源码, + // 不再活渲染(artifact/island 在 MarkdownRenderer 块级已被分流成代码块) + if (!renderHtml) { + renderer.html = function ({ text }) { + return escapeHtml(text) + } + } + renderer.heading = function ({ tokens, depth }) { const text = this.parser.parseInline(tokens) const className = isReasoning @@ -306,9 +391,20 @@ function createMarkdownHtmlRenderer(isReasoning: boolean) { } renderer.codespan = ({ text }) => { - const className = isReasoning - ? 'font-mono text-accent-main-100 text-[0.9em] align-baseline break-words' - : 'text-accent-main-100 text-[0.9em] font-mono align-baseline break-words' + // 内联代码 chip。要点: + // 1) **文字颜色继承正文**,不自己指定:正文是 text-text-200,给主题色或更亮的 + // 色阶都会比正文突出(看着像被"特意强调");继承还有个好处——reasoning 里 + // 正文变暗时它会自动跟着变暗 + // 2) **inline-flex + items-center,纵向 padding 为 0**:靠 padding 撑高会把 + // 行盒撑起来,同一行的中文和代码基线对不齐,整行看着起伏;改成 flex 居中 + // 后,高度跟着行走,纵向只留 0 + // 3) **淡底色 + 0.5px 细描边**:底色只是比页面底色抬一档,靠描边给边界; + // 只给底色(没有描边)在各主题下都会糊在一起 + // 4) **必须显式给 leading**:段落是 leading-7(28px),inline-flex 的盒子会 + // 把这个行高继承成自己的高度,于是 chip 高 28px、文字只有 12px,看着比 + // 正文高一截。给个紧凑行高 + 1px 纵向内边距,高度才和正文文字齐平 + const className = + 'inline-flex items-center font-mono text-[0.875em] leading-tight py-px break-words bg-bg-200 border-[0.5px] border-text-100/10 rounded-md px-[5px]' return `${escapeHtml(text)}` } @@ -389,13 +485,18 @@ function createMarkdownHtmlRenderer(isReasoning: boolean) { return `<${tag}${startAttr} class="${className}">${itemsHtml}` } - renderer.listitem = function ({ tokens, task, checked }) { + renderer.listitem = function ({ tokens }) { const className = isReasoning ? 'text-[length:var(--fs-sm)] text-text-400 pl-1 leading-5' : 'text-text-200 pl-1 leading-7' - const checkbox = task ? `` : '' const content = tokens ? this.parser.parse(tokens) : '' - return `
  • ${checkbox}${content}
  • ` + return `
  • ${content}
  • ` + } + + // 任务列表勾选框只在这里出一份:marked 会把 `- [x]` 的方括号切成独立的 checkbox token, + // 渲染器再自己加一个就会出现两个勾选框。统一由 checkbox 渲染。 + renderer.checkbox = ({ checked }) => { + return ` ` } renderer.hr = () => { @@ -408,20 +509,79 @@ function createMarkdownHtmlRenderer(isReasoning: boolean) { return renderer } -function renderFootnoteDefinitionsHtml(src: string, isReasoning: boolean): string | null { - const lines = src.trim().split(/\n+/) - const items: string[] = [] - const renderer = getRenderer(isReasoning) +const FOOTNOTE_DEFINITION_PATTERN = /^ {0,3}\[\^([^\]\s]+)\]:[ \t]*(.*)$/ +const FENCE_OPENING_PATTERN = /^ {0,3}(`{3,}|~{3,})/ + +export type FootnoteDefinition = { label: string; content: string } + +/** + * 把 GFM 脚注定义(`[^label]: 内容`)从正文里抽出来,交给正文末尾统一渲染。 + * marked 不认脚注语法:不抽出来的话 `[^1]: 注释` 会被当成链接引用定义, + * 正文里的 `[^1]` 就渲染成一个 href 是脚注内容的链接(正文与定义挤在同一个块时)。 + * 定义允许缩进续行(4 空格 / 制表符),代码围栏里的 `[^x]:` 不动。 + */ +export function extractFootnoteDefinitions(src: string): { body: string; definitions: FootnoteDefinition[] } { + const lines = src.split('\n') + const definitions: FootnoteDefinition[] = [] + const body: string[] = [] + let fence: string | null = null + let current: { label: string; lines: string[] } | null = null + + const flush = () => { + if (!current) return + definitions.push({ label: current.label, content: current.lines.join('\n').trim() }) + current = null + } for (const line of lines) { - const match = /^\[\^([^\]]+)\]:\s+([\s\S]+)$/.exec(line.trim()) - if (!match) return null - const [, label, content] = match + const fenceMatch = FENCE_OPENING_PATTERN.exec(line) + if (fenceMatch) { + const char = fenceMatch[1]![0]! + if (!fence) fence = char + else if (fence === char) fence = null + flush() + body.push(line) + continue + } + + if (!fence) { + const definition = FOOTNOTE_DEFINITION_PATTERN.exec(line) + if (definition) { + flush() + current = { label: definition[1]!, lines: [definition[2] ?? ''] } + continue + } + if (current) { + if (/^(?: {4}|\t)/.test(line)) { + current.lines.push(line.replace(/^(?: {4}|\t)/, '')) + continue + } + if (/^[ \t]*$/.test(line)) { + current.lines.push('') + continue + } + } + } + + flush() + body.push(line) + } + flush() + + if (definitions.length) { + while (body.length && !body[body.length - 1]!.trim()) body.pop() + } + return { body: body.join('\n'), definitions } +} + +function renderFootnoteSectionHtml(definitions: FootnoteDefinition[], isReasoning: boolean, renderHtml: boolean): string { + const renderer = getRenderer(isReasoning, renderHtml) + const items = definitions.map(({ label, content }) => { const id = getFootnoteId(label) - const body = marked.parseInline(content, { renderer }) as string + const markup = marked.parseInline(content, { renderer }) as string const className = isReasoning ? 'text-[length:var(--fs-sm)] text-text-400 leading-5' : 'text-text-300 leading-6' - items.push(`
  • ${escapeHtml(label)}. ${body} back
  • `) - } + return `
  • ${escapeHtml(label)}. ${markup} back
  • ` + }) const listClass = isReasoning ? 'my-2 list-decimal list-inside space-y-1 border-t border-border-200/30 pt-2' @@ -594,35 +754,38 @@ function sanitizeHtml(html: string): string { } // eslint-disable-next-line @typescript-eslint/no-explicit-any -let rendererCache: { default: any; reasoning: any } | null = null +let rendererCache: Record | null = null // eslint-disable-next-line @typescript-eslint/no-explicit-any -function getRenderer(isReasoning: boolean): any { +function getRenderer(isReasoning: boolean, renderHtml: boolean): any { if (!rendererCache) { rendererCache = { - default: createMarkdownHtmlRenderer(false), - reasoning: createMarkdownHtmlRenderer(true), + 'default:html': createMarkdownHtmlRenderer(false, true), + 'default:nohtml': createMarkdownHtmlRenderer(false, false), + 'reasoning:html': createMarkdownHtmlRenderer(true, true), + 'reasoning:nohtml': createMarkdownHtmlRenderer(true, false), } } - return isReasoning ? rendererCache.reasoning : rendererCache.default + return rendererCache[`${isReasoning ? 'reasoning' : 'default'}:${renderHtml ? 'html' : 'nohtml'}`] } -export function renderMarkdownToHtml(src: string, isReasoning: boolean): string { +export function renderMarkdownToHtml(src: string, isReasoning: boolean, renderHtml = true): string { const displayMath = getDisplayMathSource(src) if (displayMath != null) { const className = isReasoning ? 'my-2 overflow-x-auto text-text-400' : 'my-4 overflow-x-auto text-text-200' return `
    ${renderKatexHtml(displayMath, true)}
    ` } - const footnotes = renderFootnoteDefinitionsHtml(src, isReasoning) - if (footnotes != null) return sanitizeHtml(footnotes) - - const renderer = getRenderer(isReasoning) - const html = marked.parse(src, { renderer, async: false }) as string - return sanitizeHtml(html) + const renderer = getRenderer(isReasoning, renderHtml) + const { body, definitions } = extractFootnoteDefinitions(src) + if (!definitions.length) { + return sanitizeHtml(marked.parse(src, { renderer, async: false }) as string) + } + const bodyHtml = body.trim() ? (marked.parse(body, { renderer, async: false }) as string) : '' + return sanitizeHtml(`${bodyHtml}${renderFootnoteSectionHtml(definitions, isReasoning, renderHtml)}`) } -export function renderMarkdownInlineToHtml(src: string, isReasoning: boolean): string { - const renderer = getRenderer(isReasoning) +export function renderMarkdownInlineToHtml(src: string, isReasoning: boolean, renderHtml = true): string { + const renderer = getRenderer(isReasoning, renderHtml) const html = marked.parseInline(src, { renderer }) as string return sanitizeHtml(html) } diff --git a/src/components/markdownParsing.test.ts b/src/components/markdownParsing.test.ts new file mode 100644 index 000000000..8fd41d096 --- /dev/null +++ b/src/components/markdownParsing.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from 'vitest' +import { extractFootnoteDefinitions, maskCjkEmphasisClose } from './markdownHtmlRenderer' +import { isDollarMathBoundary, scanTextSegments } from './markdownSegments' + +describe('isDollarMathBoundary', () => { + it('rejects amounts whose closing dollar is preceded by whitespace', () => { + // 价格是 $5 到 $10 之间 + expect(isDollarMathBoundary('$5 到 $10 之间', 0, 5)).toBe(false) + }) + + it('accepts a tight formula', () => { + expect(isDollarMathBoundary('$a+b$ 成立', 0, 4)).toBe(true) + }) + + it('rejects an opening dollar followed by whitespace', () => { + expect(isDollarMathBoundary('$ a$ 文本', 0, 3)).toBe(false) + }) + + it('rejects a closing dollar followed by a digit', () => { + expect(isDollarMathBoundary('$1$2', 0, 2)).toBe(false) + }) +}) + +describe('scanTextSegments currency handling', () => { + it('keeps currency ranges as plain text', () => { + expect(scanTextSegments('价格 $5 到 $10')).toEqual([{ type: 'text', text: '价格 $5 到 $10' }]) + expect(scanTextSegments('花费 $100 和 $200')).toEqual([{ type: 'text', text: '花费 $100 和 $200' }]) + }) + + it('still scans real inline math', () => { + expect(scanTextSegments('公式 $a+b$ 成立')).toEqual([ + { type: 'text', text: '公式 ' }, + { type: 'math', latex: 'a+b', display: false }, + { type: 'text', text: ' 成立' }, + ]) + }) + + it('keeps a lone dollar literal', () => { + expect(scanTextSegments('成本 $5 左右')).toEqual([{ type: 'text', text: '成本 $5 左右' }]) + }) +}) + +describe('maskCjkEmphasisClose', () => { + it('relaxes the close when punctuation is followed by a CJK character', () => { + expect(maskCjkEmphasisClose('**重点:**正文')).toBe('**重点:** 文') + expect(maskCjkEmphasisClose('*重点:*正文')).toBe('*重点:* 文') + expect(maskCjkEmphasisClose('**(粗体)**后面')).toBe('**(粗体)** 面') + }) + + it('leaves a delimiter run that opens after punctuation untouched', () => { + expect(maskCjkEmphasisClose('说明:**重点**内容')).toBe('说明:**重点**内容') + }) + + it('leaves already-valid emphasis and intraword underscores untouched', () => { + expect(maskCjkEmphasisClose('**粗体**,继续')).toBe('**粗体**,继续') + expect(maskCjkEmphasisClose('snake_case_word')).toBe('snake_case_word') + expect(maskCjkEmphasisClose('a *b* c')).toBe('a *b* c') + }) +}) + +describe('extractFootnoteDefinitions', () => { + it('pulls every definition out of the body', () => { + expect(extractFootnoteDefinitions('[^a]: 甲\n[^b]: 乙')).toEqual({ + body: '', + definitions: [ + { label: 'a', content: '甲' }, + { label: 'b', content: '乙' }, + ], + }) + }) + + it('keeps indented continuation lines in the definition', () => { + expect(extractFootnoteDefinitions('[^a]: 一行\n 续行')).toEqual({ + body: '', + definitions: [{ label: 'a', content: '一行\n续行' }], + }) + }) + + it('separates the definition from surrounding prose', () => { + expect(extractFootnoteDefinitions('正文[^a]\n\n[^a]: 甲')).toEqual({ + body: '正文[^a]', + definitions: [{ label: 'a', content: '甲' }], + }) + }) + + it('ignores definition-shaped lines inside code fences', () => { + const source = '```md\n[^a]: 甲\n```' + expect(extractFootnoteDefinitions(source)).toEqual({ body: source, definitions: [] }) + }) +}) diff --git a/src/components/markdownSegments.ts b/src/components/markdownSegments.ts index 17832fb80..0b645cec1 100644 --- a/src/components/markdownSegments.ts +++ b/src/components/markdownSegments.ts @@ -67,6 +67,22 @@ export function getFootnoteId(label: string): string { return normalized || 'note' } +/** + * 单个 `$` 行内数学的边界判定,避免把货币金额当成公式(`$5 到 $10`、`$100 和 $200`): + * - 开 `$` 之后不能是空白(`$ 5$` 不是公式) + * - 闭 `$` 之前不能是空白(`$5 到 $` 不是公式) + * - 闭 `$` 之后不能紧跟数字(`$100$200` 是金额连写) + * `$$`(display)不做这层限制,允许 `$$ x $$` 写法。 + */ +export function isDollarMathBoundary(text: string, open: number, close: number): boolean { + const afterOpen = text[open + 1] + if (afterOpen === undefined || /\s/.test(afterOpen)) return false + const beforeClose = text[close - 1] + if (beforeClose === undefined || /\s/.test(beforeClose)) return false + if (isAsciiDigitAt(text, close + 1)) return false + return true +} + /** 尝试在 cursor 处匹配 $...$ / $$...$$ 数学 span(不匹配返回 null) */ function tryMatchMath(text: string, cursor: number): { type: 'math'; latex: string; display: boolean } | null { if (text[cursor] !== '$' || isEscapedAt(text, cursor)) return null @@ -78,6 +94,7 @@ function tryMatchMath(text: string, cursor: number): { type: 'math'; latex: stri const latex = text.slice(start, close) // 行内 $ 不允许跨行;$$ 允许(display) if (!display && (!latex || latex.includes('\n'))) return null + if (!display && !isDollarMathBoundary(text, cursor, close)) return null return { type: 'math', latex, display } } diff --git a/src/components/ui/Dialog.tsx b/src/components/ui/Dialog.tsx index fa32900e6..1f9cf566d 100644 --- a/src/components/ui/Dialog.tsx +++ b/src/components/ui/Dialog.tsx @@ -354,7 +354,7 @@ export function Dialog({ <> {/* Header */} {(title || showCloseButton) && ( -
    +
    {title}
    diff --git a/src/features/attachment/AttachmentItem.test.tsx b/src/features/attachment/AttachmentItem.test.tsx new file mode 100644 index 000000000..393330d45 --- /dev/null +++ b/src/features/attachment/AttachmentItem.test.tsx @@ -0,0 +1,63 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import { AttachmentItem } from './AttachmentItem' +import { FullscreenProvider } from '../../contexts' +import type { Attachment } from './types' + +// ============================================ +// 上传中的胶囊(Issue #182) +// +// 需求:整个胶囊当进度条(填充层 + 百分比),拿不到进度时才退回不确定态转圈。 +// 浏览器侧走 XHR 能拿到真实进度;桌面端经 Rust 发包拿不到。 +// ============================================ + +const uploaded: Attachment = { + id: 'a1', + type: 'file', + displayName: 'piui-source.zip', + relativePath: 'C:/Users/x/AppData/Local/Temp/opencode/uploads/u1/piui-source.zip', + size: 262, +} + +function renderItem(attachment: Attachment) { + return render( + + + , + ) +} + +describe('AttachmentItem 上传态', () => { + it('有进度 → 整个胶囊是进度条,显示百分比,不显示转圈', () => { + renderItem({ ...uploaded, uploadStatus: 'uploading', progress: 0.42 }) + + const fill = screen.getByTestId('attachment-progress-fill') + expect(fill).toHaveStyle({ width: '42%' }) + expect(screen.getByText('42%')).toBeTruthy() + expect(screen.queryByTestId('attachment-progress-spinner')).toBeNull() + }) + + it('拿不到进度(桌面端) → 保留不确定态转圈,不画进度条', () => { + renderItem({ ...uploaded, uploadStatus: 'uploading' }) + + expect(screen.queryByTestId('attachment-progress-fill')).toBeNull() + expect(screen.getByTestId('attachment-progress-spinner')).toBeTruthy() + }) + + it('进度值越界时夹到 0~100%', () => { + const { unmount } = renderItem({ ...uploaded, uploadStatus: 'uploading', progress: 1.8 }) + expect(screen.getByTestId('attachment-progress-fill')).toHaveStyle({ width: '100%' }) + unmount() + + renderItem({ ...uploaded, uploadStatus: 'uploading', progress: -1 }) + expect(screen.getByTestId('attachment-progress-fill')).toHaveStyle({ width: '0%' }) + }) + + it('上传完成后是普通胶囊:没有进度层,显示体积', () => { + renderItem(uploaded) + + expect(screen.queryByTestId('attachment-progress-fill')).toBeNull() + expect(screen.queryByTestId('attachment-progress-spinner')).toBeNull() + expect(screen.getByText('262 B')).toBeTruthy() + }) +}) diff --git a/src/features/attachment/AttachmentItem.tsx b/src/features/attachment/AttachmentItem.tsx index 0f8995330..5df623341 100644 --- a/src/features/attachment/AttachmentItem.tsx +++ b/src/features/attachment/AttachmentItem.tsx @@ -1,7 +1,8 @@ import { useState, useCallback, useRef, useEffect, memo } from 'react' import { useTranslation } from 'react-i18next' -import { CloseIcon, ChevronDownIcon, CopyIcon, CheckIcon, DownloadIcon, ExpandIcon } from '../../components/Icons' +import { CloseIcon, ChevronDownIcon, CopyIcon, CheckIcon, DownloadIcon, ExpandIcon, RetryIcon } from '../../components/Icons' import { getAttachmentIcon, hasExpandableContent } from './utils' +import { formatFileSize } from '../../utils/formatUtils' import { getMaterialIconUrl } from '../../utils/materialIcons' import { useDelayedRender } from '../../hooks/useDelayedRender' import { AttachmentDetailModal } from './AttachmentDetailModal' @@ -12,6 +13,8 @@ import type { Attachment } from './types' interface AttachmentItemProps { attachment: Attachment onRemove?: (id: string) => void + /** 上传失败后的重试入口(Issue #182) */ + onRetry?: (id: string) => void size?: 'sm' | 'md' expandable?: boolean className?: string @@ -20,6 +23,7 @@ interface AttachmentItemProps { function AttachmentItemComponent({ attachment, onRemove, + onRetry, size = 'md', expandable = false, className, @@ -33,6 +37,12 @@ function AttachmentItemComponent({ const { Icon, colorClass } = getAttachmentIcon(attachment) const canExpand = expandable && hasExpandableContent(attachment) + // 上传中:整个胶囊当进度条。浏览器侧能拿到真实进度(XHR),桌面端拿不到 → 不确定态转圈 + const progress = + attachment.uploadStatus === 'uploading' && typeof attachment.progress === 'number' + ? Math.min(1, Math.max(0, attachment.progress)) + : undefined + // file/folder 使用 material icon,其他类型用通用 SVG 图标 const useMaterialIcon = attachment.type === 'file' || attachment.type === 'folder' const materialIconUrl = useMaterialIcon @@ -54,9 +64,10 @@ function AttachmentItemComponent({ className || '' } ${isExpanded ? expandedWidth : collapsedWidth}`} > - {/* 标签头部 */} + {/* 标签头部 — 上传中时整个胶囊就是进度条:先铺填充层,内容层盖在上面 */}
    setIsExpanded(!isExpanded) : undefined} > + {progress !== undefined && ( +
    {/* 展开的详情面板 - grid-rows 动画(和 think tag 同源) */} diff --git a/src/features/attachment/AttachmentPreview.tsx b/src/features/attachment/AttachmentPreview.tsx index 40eba361e..5f38bb3bd 100644 --- a/src/features/attachment/AttachmentPreview.tsx +++ b/src/features/attachment/AttachmentPreview.tsx @@ -4,6 +4,8 @@ import type { Attachment } from './types' interface AttachmentPreviewProps { attachments: Attachment[] onRemove?: (id: string) => void + /** 上传失败后的重试入口(Issue #182) */ + onRetry?: (id: string) => void className?: string size?: 'sm' | 'md' expandable?: boolean @@ -19,6 +21,7 @@ interface AttachmentPreviewProps { export function AttachmentPreview({ attachments, onRemove, + onRetry, className = '', size = 'md', expandable = false, @@ -53,6 +56,7 @@ export function AttachmentPreview({ key={attachment.id} attachment={attachment} onRemove={onRemove} + onRetry={onRetry} size={size} expandable={expandable} className={itemClasses} diff --git a/src/features/attachment/types.ts b/src/features/attachment/types.ts index bbf2e21c4..fd95c1951 100644 --- a/src/features/attachment/types.ts +++ b/src/features/attachment/types.ts @@ -35,6 +35,22 @@ export interface Attachment { mime?: string // MIME 类型 relativePath?: string // 相对路径(用于显示和 source.path) + // 服务端上传附件(Issue #182) + /** 原始字节数,用于展示 */ + size?: number + /** + * 只作路径引用、**不进** `prompt.files[]`。 + * + * 服务端读 `files[].uri` 时有 20MB 硬上限,超限会让整条 prompt 失败 + * (core `SessionPrompt.readFileAttachment` 的 `MAX_ATTACHMENT_BYTES`)。 + * 超过该阈值的附件只把路径写进 prompt 文本,交给模型用工具访问。 + */ + pathOnly?: boolean + /** 上传生命周期(仅输入框内的临时态) */ + uploadStatus?: 'uploading' | 'failed' + /** 上传进度 0~1(仅 uploadStatus === 'uploading' 且浏览器侧能上报时有值) */ + progress?: number + // 文件内容(从 synthetic text part 获取) content?: string // 文件内容预览 diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 914b84eef..84897a061 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -19,7 +19,7 @@ import { getStreamingHotIndexes, getTimelineRowYClass, mergeVirtualRangeIndexes import { buildVisibleMessageEntries, getVisibleMessageForkTargetId } from './chatAreaVisibility' import { buildChatPageViewModel } from './useChatPageViewModel' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' -import { isAssistantMessage } from '../../types/api/message' +import { isAssistantMessage, isFailedIdleMessage, idleMessageError } from '../../types/api/message' /** 助手消息的 content(非助手返回空数组,测试断言里方便用) */ function contentOf(message: SessionMessageInfo): AssistantContent[] { @@ -87,6 +87,34 @@ function createTextPart(_id: string, _messageID: string, text: string): Assistan } describe('buildVisibleMessageEntries', () => { + it('keeps failed idle markers visible (session-level error must render)', () => { + // pre-promotion failure:只有 user + 失败 idle 标记,过滤掉它错误就永远不渲染 + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider.no-route', message: 'Model unavailable' }, + time: { created: 2 }, + } as SessionMessageInfo + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), failedIdle]) + + expect(entries.some(e => e.message.id === 'idle-1')).toBe(true) + }) + + it('hides succeeded / interrupted idle markers', () => { + const okIdle = { id: 'idle-ok', type: 'idle', outcome: 'succeeded', time: { created: 2 } } as SessionMessageInfo + const abortedIdle = { + id: 'idle-abort', + type: 'idle', + outcome: 'interrupted', + time: { created: 3 }, + } as SessionMessageInfo + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), okIdle, abortedIdle]) + + expect(entries.some(e => e.message.id === 'idle-ok')).toBe(false) + expect(entries.some(e => e.message.id === 'idle-abort')).toBe(false) + }) + it('keeps source ids for merged assistant tool messages', () => { const first = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')]) const second = createAssistantMessage('assistant-2', [createToolPart('tool-2', 'assistant-2')]) @@ -614,6 +642,104 @@ describe('buildProcessTimeline', () => { expect(timeline[0]).toMatchObject({ kind: 'message', key: 'user-1' }) }) + it('renders a failed idle marker as an error item (pre-promotion failure)', () => { + // 会话级失败:prompt 没能提升成 assistant 工作,只剩一条带 error 的失败 idle 标记。 + // 不渲染它,错误就永远不可见(官方 session-ui projection.ts 的 isFailedIdle)。 + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider.auth', message: 'Invalid API key' }, + time: { created: 1001 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + const errorItem = timeline.find(item => item.kind === 'message' && item.key === 'idle-1') + expect(errorItem).toBeTruthy() + if (errorItem?.kind === 'message') { + expect(isFailedIdleMessage(errorItem.message)).toBe(true) + expect(idleMessageError(errorItem.message)).toMatchObject({ type: 'provider.auth' }) + } + }) + + it('does not duplicate the error card when the last assistant already shows it', () => { + // assistant.error 已由 MessageErrorView 渲染 → idle 卡片跳过(官方同款去重) + const failedAssistant = createAssistantMessage( + 'assistant-1', + [createTextPart('text-1', 'assistant-1', 'oops')], + 1001, + 1002, + { type: 'provider', message: 'boom' }, + ) + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider', message: 'boom' }, + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), failedAssistant, failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.kind === 'message' && item.key === 'idle-1')).toBe(false) + }) + + it('still shows the idle error card when the assistant error was an interruption', () => { + // assistant 是被中断的(abort)→ 不算「已显示错误」,idle 卡片仍要渲染 + const aborted = createAssistantMessage( + 'assistant-1', + [createTextPart('text-1', 'assistant-1', 'partial')], + 1001, + 1002, + { type: 'MessageAbortedError', message: 'aborted' }, + ) + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider', message: 'boom' }, + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), aborted, failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.kind === 'message' && item.key === 'idle-1')).toBe(true) + }) + + it('ignores succeeded idle markers', () => { + const okIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'succeeded', + time: { created: 1001 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), okIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.key === 'idle-1')).toBe(false) + }) + it('keeps only the earliest pending Working shell when a later user is queued', () => { // 第一轮仍 live,第二轮 user 已发出 → 只挂 user-1 的 Working,user-2 暂不挂空壳 const mid = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')], 1001) @@ -693,27 +819,62 @@ describe('buildProcessTimeline', () => { expect(shells[1]).toMatchObject({ userMessageId: 'user-2', isActive: true }) }) - it('does not reopen a completed turn when session becomes busy before the next user lands', () => { - // 发送瞬间:streaming 已 true,新 user 还没进列表 → 已 Worked 的回合不能闪回 Working - const settled = createAssistantMessage( + it('keeps the last turn Working while the session is still busy (multi-step gap)', () => { + // 上一步已 completed、下一步还没到,但 session.status 仍是 busy —— 这是多步 agent 的常态。 + // 不能在这一刻判成 Worked 收壳,否则下一步内容到达时又要展开,看着像「提前收工」。 + const stepped = createAssistantMessage( 'assistant-1', - [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: 'done' }], + [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: '看一眼' }], 1001, 1500, ) - const messages = [createUserMessage('user-1', 1000), settled] - const timeline = buildProcessTimeline(messages, { + const messages = [createUserMessage('user-1', 1000), stepped] + + const busy = buildProcessTimeline(messages, { turnDurationMap: new Map([['assistant-1', 500]]), sessionIsStreaming: true, messageHasProcess: hasProcess, messageHasFinal: hasFinal, }) - expect(timeline.find(item => item.kind === 'process-shell')).toMatchObject({ + expect(busy.find(item => item.kind === 'process-shell')).toMatchObject({ + kind: 'process-shell', + isActive: true, + }) + + // busy 摘掉(idle)→ 收壳,并显示总耗时 + const settled = buildProcessTimeline(messages, { + turnDurationMap: new Map([['assistant-1', 500]]), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + expect(settled.find(item => item.kind === 'process-shell')).toMatchObject({ kind: 'process-shell', isActive: false, + durationMs: 500, }) }) + it('settles the previous turn once the next user turn lands, even while busy', () => { + // 发送瞬间:busy 已 true、新 user 已入列 → 上一轮立刻 Worked,不能闪回 Working + const settled = createAssistantMessage( + 'assistant-1', + [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: 'done' }], + 1001, + 1500, + ) + const messages = [createUserMessage('user-1', 1000), settled, createUserMessage('user-2', 2000)] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map([['assistant-1', 500]]), + sessionIsStreaming: true, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + const shells = timeline.filter(item => item.kind === 'process-shell') + expect(shells[0]).toMatchObject({ userMessageId: 'user-1', isActive: false }) + }) + it('settles shell with process inside and final answer outside', () => { const processOnly = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')], 1001, 1200) const finalAnswer = createAssistantMessage( diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 74840a2ab..c4e19a4a9 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -141,6 +141,8 @@ interface MessageBodyProps { isTurnLatestAssistant?: boolean allowStreamingLayoutAnimation: boolean processContentScope?: 'all' | 'process' | 'final' | 'inline' + /** step 完成信息是否由本实例渲染(壳内那截且壳外还有一份时传 false) */ + stepFinishVisible?: boolean onEntryGrowComplete?: (messageId: string) => void } @@ -155,10 +157,13 @@ const MessageBody = memo(function MessageBody({ isTurnLatestAssistant, allowStreamingLayoutAnimation, processContentScope = 'all', + stepFinishVisible, onEntryGrowComplete, }: MessageBodyProps) { const messageId = message.id const isUser = isUserMessage(message) + // undo 边界:用户消息,或 v2 的独立压缩消息(revert.stage 接受任意 messageID) + const undoable = isUser || message.type === 'compaction' return (
    registerMessage?.(messageId, node as HTMLDivElement | null)} @@ -173,10 +178,11 @@ const MessageBody = memo(function MessageBody({ turnDuration={turnDuration} isTurnLatestAssistant={isTurnLatestAssistant} processContentScope={processContentScope} - onUndo={isUser ? onUndo : undefined} + stepFinishVisible={stepFinishVisible} + onUndo={undoable ? onUndo : undefined} onFork={onFork} forkMessageId={forkMessageId} - canUndo={isUser ? canUndo : undefined} + canUndo={undoable ? canUndo : undefined} onEntryGrowComplete={isUser ? onEntryGrowComplete : undefined} />
    @@ -283,6 +289,8 @@ const VirtualRow = memo( isTurnLatestAssistant={turnLatestAssistantIds.has(child.message.id)} allowStreamingLayoutAnimation={allowStreamingLayoutAnimation} processContentScope={child.processContentScope} + // 这条消息的正文还在壳外单独渲染一份 → step 完成信息由壳外那份负责 + stepFinishVisible={item.finalMessage?.id !== child.message.id} /> ))} @@ -372,11 +380,13 @@ export const ChatArea = memo( ref, ) => { const { t } = useTranslation('chat') - const { isWideMode, processCollapseEnabled } = useTheme() + const { processCollapseEnabled } = useTheme() const { presentation } = useChatViewport() const atBottomThreshold = presentation.isCompact ? 150 : AT_BOTTOM_THRESHOLD_PX const paddingClass = presentation.isCompact ? 'px-3' : 'px-5' - const maxWidthClass = isWideMode ? 'max-w-[95%] xl:max-w-6xl' : 'max-w-2xl' + // 消息列宽统一引用 pane 根上的 CSS 变量(ChatPane 按 窄672/宽95%·6xl/拖拽自定义 解析), + // 变量缺席时回落 42rem(=原 max-w-2xl)。字符串恒定,VirtualRow memo 比较不受影响 + const maxWidthClass = 'max-w-[min(100%,var(--oc-chat-column-width,42rem))]' // ── 派生数据 ── const entries = useMemo( @@ -1098,6 +1108,7 @@ export const ChatArea = memo( items={queuedFollowUps} editingId={queueEditingId} mutation={queueMutation} + stateKey={sessionId ? `queue-bubbles:${sessionId}` : undefined} onSteer={onQueueSteer} onEdit={onQueueEdit} onRemove={onQueueRemove} diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index 905e04920..ab4b1a9a5 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -6,7 +6,7 @@ * compact viewport wrapper. */ -import { memo, useRef, useEffect, useState, useCallback, useMemo, useDeferredValue, useSyncExternalStore } from 'react' +import { memo, useRef, useEffect, useState, useCallback, useMemo, useDeferredValue, useSyncExternalStore, type CSSProperties } from 'react' import { Trans, useTranslation } from 'react-i18next' import { ChatArea, Header, InputBox, PermissionDialog, QuestionDialog, type ChatAreaHandle } from '.' @@ -15,9 +15,16 @@ import { type ModelSelectorHandle } from './ModelSelector' import { OutlineIndex } from '../../components/OutlineIndex' import { PaneHeader } from './PaneHeader' import { PaneDropOverlay, resolveDropZone, type DropZone, type PaneDropOverlayHandle } from './PaneDropOverlay' +import { + ChatWidthHandle, + CHAT_COLUMN_WIDTH_VAR, + CHAT_INPUT_WIDTH_VAR, + MIN_CHAT_CONTENT_WIDTH, + DEFAULT_INPUT_WIDTH, +} from './ChatWidthHandle' import { useFolderProjectDrop } from './useFolderProjectDrop' import { FolderProjectDropOverlay } from './FolderProjectDropOverlay' -import { useChatSession, useModels, useModelSelection } from '../../hooks' +import { useChatSession, useModels, useModelSelection, useSessionModelRestore } from '../../hooks' import { useServerStore } from '../../hooks/useServerStore' import { useCancelHint } from '../../hooks/useCancelHint' import { makeSessionKey, sessionKeyToServerId, splitSessionKey } from '../../utils/sessionKey' @@ -290,6 +297,7 @@ export const ChatPane = memo(function ChatPane({ routeSessionId, loadState, loadError, + sessionModel, hasMoreHistory, retryStatus, effectiveDirectory, @@ -361,7 +369,7 @@ export const ChatPane = memo(function ChatPane({ // 最新未完成 assistant 回合里有 running 的 shell/task 工具 → 允许转后台; // 并入服务端 running shells(官方 background.ts:100-109 同款) // ============================================ - const runningShells = useRunningShells(routeSessionId, isStreaming, paneServerId) + const runningShells = useRunningShells(routeSessionId, isStreaming, effectiveDirectory, paneServerId) const blockingBackgroundTasks = useMemo(() => { if (!isStreaming || !routeSessionId) return [] const { sessionId: rawSessionId } = splitSessionKey(routeSessionId) @@ -541,23 +549,17 @@ export const ChatPane = memo(function ChatPane({ // session 切换:只在 routeSessionId 变化时,恢复该会话当前的模型。 // v2 的用户消息**不带** model / agent(那是会话级状态,由 // session.model.selected / session.agent.selected 维护在 messageStore 上), - // 因此这里改读会话级状态,与 store 的 RevertHistoryItem 同一口径。 - const restoredSessionRef = useRef(null) - useEffect(() => { - // 没有 session、或者这个 session 已经恢复过了 → 跳过 - if (!routeSessionId || restoredSessionRef.current === routeSessionId) return - // 还没加载完(空会话也算:loadState 到达 loaded 即放行)→ 等下次 - if (messages.length === 0 && loadState !== 'loaded') return - - restoredSessionRef.current = routeSessionId - - const sessionModel = messageStore.getSessionState(routeSessionId)?.model - if (sessionModel) { - restoreFromMessage({ providerID: sessionModel.providerID, modelID: sessionModel.id }, sessionModel.variant) - } - // 依赖 routeSessionId 和 messages.length(等加载完),不依赖 messages 引用 - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [routeSessionId, messages.length, loadState, visibleModels, restoreFromMessage]) + // 因此这里读会话级状态(缺失时用最后一条助手消息的 model 兜底)。 + // 详见 useSessionModelRestore:快照/目录没就绪时不落锁,避免把「还没读到」 + // 当成「这个会话没有模型」而永远恢复不了。 + useSessionModelRestore({ + sessionId: routeSessionId, + messages, + loadState, + sessionModel, + models: visibleModels, + restoreFromMessage, + }) // ============================================ // Agent Restoration Effect @@ -825,8 +827,64 @@ export const ChatPane = memo(function ChatPane({ // ============================================ const [permissionCollapsed, setPermissionCollapsed] = useState(false) const [questionCollapsed, setQuestionCollapsed] = useState(false) + const [websearchCollapsed, setWebsearchCollapsed] = useState(false) - const { inlineToolRequests, outlineCurrentHighlight } = useTheme() + const { + inlineToolRequests, + outlineCurrentHighlight, + isWideMode, + chatContentWidth, + setChatContentWidth, + chatInputWidth, + setChatInputWidth, + } = useTheme() + + // ── 对话列/输入框宽度(左缘拖拽调宽,两个独立把手)── + // 样式与交互抄 dsh ConversationWidthControls,按需求收窄成左缘单把手 × 2: + // 把手(调整入口)只在桌面端单 panel / pane 全屏时挂载(分屏空间太碎不给拖), + // 但调出来的自定义宽度对所有场景生效,分屏小 panel 也按它渲染 + // (pane 装不下时由 CSS 的 min(100%,…) 收到 100%)。 + // 两个宽度走 pane 根上的两个 CSS 变量,ChatArea 消息列、InputBox、 + // 各级 dock 的 max-width 都引用它们,拖拽期间直接写变量零 React 渲染。 + // 恢复默认 = 设置里切换宽屏模式(开或关都会清掉两个自定义宽度,themeStore.setWideMode)。 + const isDesktopSurface = outerViewport ? !outerViewport.presentation.isCompact : false + const canAdjustChatWidth = isDesktopSurface && (displayMode === 'single' || isPaneFullscreen) + const [paneWidth, setPaneWidth] = useState(0) + useEffect(() => { + const el = paneRootRef.current + if (!el) return + const ro = new ResizeObserver(entries => { + const width = entries[0]?.contentRect.width + if (width) setPaneWidth(Math.round(width)) + }) + ro.observe(el) + return () => ro.disconnect() + }, []) + const outerViewportWidth = outerViewport?.layout.viewportWidth ?? 0 + // 默认宽度对齐原 Tailwind 类:窄 max-w-2xl(672);宽 max-w-[95%] xl:max-w-6xl + // (xl 断点看视口宽而非 pane 宽,≥1280 时才收 72rem=1152 的上限) + const defaultChatColumnWidth = isWideMode + ? paneWidth > 0 + ? outerViewportWidth >= 1280 + ? Math.min(paneWidth * 0.95, 1152) + : paneWidth * 0.95 + : 1152 + : 672 + const customChatColumnWidth = chatContentWidth + const customChatInputWidth = chatInputWidth + // 两侧各留 48px gutter:把手条带贴在内容列外 24px、宽 10px,拖拽到最宽时把手仍不贴边。 + // 只在可调模式 clamp——分屏等不可调场景保持原行为(CSS 的 min(100%,…) 自然兜住溢出) + const maxChatColumnWidth = + canAdjustChatWidth && paneWidth > 0 ? Math.max(MIN_CHAT_CONTENT_WIDTH, paneWidth - 96) : Number.MAX_SAFE_INTEGER + const chatColumnWidth = Math.min( + Math.max(customChatColumnWidth ?? defaultChatColumnWidth, MIN_CHAT_CONTENT_WIDTH), + maxChatColumnWidth, + ) + // 输入框宽度独立调整;默认固定 3xl(768) + const resolvedChatInputWidth = Math.min( + Math.max(customChatInputWidth ?? DEFAULT_INPUT_WIDTH, MIN_CHAT_CONTENT_WIDTH), + maxChatColumnWidth, + ) // inline 模式下未被任何工具卡片认领的 family 请求仍走底部会话级弹窗—— // 典型场景:刷新后运行中的子代理要权限(progress 不落库,metadata.sessionID @@ -879,12 +937,16 @@ export const ChatPane = memo(function ChatPane({ // 新请求出现(含 inline 模式底部兜底)时解除折叠 const permissionRequestId = visiblePermissionRequests[0]?.id const questionRequestId = visibleQuestionRequests[0]?.id + const websearchRequestId = visibleWebsearchRequest?.id useEffect(() => { if (permissionRequestId) setPermissionCollapsed(false) }, [permissionRequestId]) useEffect(() => { if (questionRequestId) setQuestionCollapsed(false) }, [questionRequestId]) + useEffect(() => { + if (websearchRequestId) setWebsearchCollapsed(false) + }, [websearchRequestId]) const inlineToolRequestCtx = useMemo( () => ({ @@ -1059,6 +1121,7 @@ export const ChatPane = memo(function ChatPane({ modelSelectorRef={modelSelectorRef} rootPath={effectiveDirectory} sessionId={routeSessionId} + serverId={paneServerId} revertedText={revertedMessage?.text} revertedAttachments={revertedMessage?.attachments} composerDraft={composerDraft} @@ -1096,7 +1159,29 @@ export const ChatPane = memo(function ChatPane({ } : undefined } + collapsedWebsearch={ + visibleWebsearchRequest && websearchCollapsed + ? { + label: t('chat:websearch.title'), + queueLength: 1, + onExpand: () => setWebsearchCollapsed(false), + } + : undefined + } /> + {/* 输入框左缘拖拽把手(与对话列把手独立,各调各的宽度) */} + {canAdjustChatWidth && paneWidth > 0 && ( + + )}
    )} - {/* websearch.provider 表单 → 专用 dock(官方 session-websearch-dock) */} + {/* websearch.provider 表单 → 与权限/提问同一个请求区(同款卡片、同样能收起成胶囊) */} {visibleWebsearchRequest && ( -
    -
    - -
    -
    + )} +
    ) @@ -1159,6 +1244,12 @@ export const ChatPane = memo(function ChatPane({
    )} {chatContent} + {canAdjustChatWidth && paneWidth > 0 && ( + + )}
    diff --git a/src/features/chat/ChatWidthHandle.test.tsx b/src/features/chat/ChatWidthHandle.test.tsx new file mode 100644 index 000000000..8cf81de3c --- /dev/null +++ b/src/features/chat/ChatWidthHandle.test.tsx @@ -0,0 +1,153 @@ +import { describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { useRef } from 'react' +import { + ChatWidthHandle, + CHAT_COLUMN_WIDTH_VAR, + CHAT_INPUT_WIDTH_VAR, + MIN_CHAT_CONTENT_WIDTH, +} from './ChatWidthHandle' + +function Harness({ + onCommit, + width = 672, + maxWidth = 1000, + cssVar = CHAT_COLUMN_WIDTH_VAR, +}: { + onCommit: (w: number) => void + width?: number + maxWidth?: number + cssVar?: string +}) { + const rootRef = useRef(null) + return ( +
    + +
    + ) +} + +// jsdom 没有 PointerEvent 构造器;React 的根监听按事件类型名分发, +// 用 MouseEvent 造 'pointerdown/move/up' 一样能走通整条链路 +function pointer(type: string, init: MouseEventInit = {}) { + return new MouseEvent(type, { bubbles: true, cancelable: true, ...init }) +} + +describe('ChatWidthHandle(左缘拖拽调宽)', () => { + it('拖拽左缘外移 → 宽度按 2|dx| 变大,写 CSS 变量,松手提交', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500, clientY: 100 })) + // 向左拖 50px → 宽度 672 + 100 = 772 + window.dispatchEvent(pointer('pointermove', { clientX: 450, clientY: 120 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('772px') + expect(onCommit).not.toHaveBeenCalled() + + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledWith(772) + }) + + it('向右拖变窄,并分别 clamp 到下限 MIN 和上限 maxWidth', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + // 向右拖 400px → 672 - 800 = -128 → clamp 到 MIN + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 900 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe(`${MIN_CHAT_CONTENT_WIDTH}px`) + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledWith(MIN_CHAT_CONTENT_WIDTH) + + // 向左拖 1000px → 672 + 2000 = 2672 → clamp 到 maxWidth 1000 + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: -500 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('1000px') + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledTimes(2) + expect(onCommit).toHaveBeenLastCalledWith(1000) + }) + + it('只点不拖(宽度没变化)不提交', () => { + const onCommit = vi.fn() + render() + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).not.toHaveBeenCalled() + }) + + it('右键按下不启动拖拽', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 2, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 400 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('') + expect(onCommit).not.toHaveBeenCalled() + }) + + it('两个把手各写各的变量(对话列 / 输入框独立调整)', () => { + const onCommitChat = vi.fn() + const onCommitInput = vi.fn() + + function TwoHandles() { + const rootRef = useRef(null) + return ( +
    + + +
    + ) + } + render() + const root = screen.getByTestId('root') + const [chatHandle, inputHandle] = screen.getAllByRole('separator') + + // 拖输入框把手:只写输入框变量、只提交输入框宽度 + inputHandle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 450 })) + expect(root.style.getPropertyValue(CHAT_INPUT_WIDTH_VAR)).toBe('868px') + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('') + window.dispatchEvent(pointer('pointerup')) + expect(onCommitInput).toHaveBeenCalledWith(868) + expect(onCommitChat).not.toHaveBeenCalled() + + // 拖对话列把手:只写对话列变量 + chatHandle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 520 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('632px') + expect(root.style.getPropertyValue(CHAT_INPUT_WIDTH_VAR)).toBe('868px') + window.dispatchEvent(pointer('pointerup')) + expect(onCommitChat).toHaveBeenCalledWith(632) + expect(onCommitInput).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/features/chat/ChatWidthHandle.tsx b/src/features/chat/ChatWidthHandle.tsx new file mode 100644 index 000000000..5026e5930 --- /dev/null +++ b/src/features/chat/ChatWidthHandle.tsx @@ -0,0 +1,112 @@ +// ============================================ +// ChatWidthHandle — 对话列 / 输入框左缘拖拽调宽把手 +// +// 样式与交互直接抄 dsh ConversationWidthControls: +// - 10px 热区条带贴在内容列左缘外 24px 的 gutter(right: calc(50% + 宽/2 + 24px)) +// - 辉光是 2px 短条,跟随指针 Y(16px 实心核、两侧各 28px 渐隐),不是整条竖线 +// - 平时 opacity 0 完全隐藏,hover / 拖拽中才显示 +// 与 dsh 的差异(按需求收窄): +// - 只有左缘把手(dsh 左右各一);列居中,左缘外移 dx → 宽度变化 2|dx| +// - 对话列和输入框是两个独立把手,各写各的 CSS 变量、各存各的偏好 +// - 只在桌面端单 panel / pane 全屏时由 ChatPane 挂载(分屏不调) +// - 拖拽期间直接写 pane 根上的 CSS 变量,零 React 渲染;松手才 onCommit 持久化 +// - 恢复默认 = 设置里切换宽屏模式(开或关都会清掉两个自定义宽度) +// ============================================ + +import { useEffect, useRef, useState } from 'react' + +/** pane 根上的 CSS 变量:对话列宽 / 输入框宽(ChatArea、InputBox 的 max-width 都引用它们) */ +export const CHAT_COLUMN_WIDTH_VAR = '--oc-chat-column-width' +export const CHAT_INPUT_WIDTH_VAR = '--oc-chat-input-width' +/** 把手元素上的变量:辉光跟随的指针 Y(百分比),样式在 index.css */ +const POINTER_Y_VAR = '--oc-width-handle-pointer-y' +/** 拖拽允许的最小宽度(px,对话列和输入框共用) */ +export const MIN_CHAT_CONTENT_WIDTH = 480 +/** 输入框默认宽度(px),未自定义时 = max-w-3xl */ +export const DEFAULT_INPUT_WIDTH = 768 + +export interface ChatWidthHandleProps { + /** pane 根元素:拖拽期间直接写 CSS 变量的目标 */ + rootRef: React.RefObject + /** 当前生效的宽度(已解析默认值/自定义值并 clamp) */ + width: number + /** 允许的最大宽度(pane 宽减去两侧 gutter) */ + maxWidth: number + /** 松手提交最终宽度(持久化) */ + onCommit: (width: number) => void + /** 拖拽期间写哪个 CSS 变量(对话列 / 输入框各传各的) */ + cssVar: string + /** 悬浮提示 */ + title: string + /** 纵向范围(对话列 top-10 bottom-0 避开头部;输入框 inset-y-0) */ + className?: string + /** 定位(right: calc(50% + var(宽)/2 + 24px),由调用方按目标宽度变量给出) */ + style?: React.CSSProperties +} + +export function ChatWidthHandle({ rootRef, width, maxWidth, onCommit, cssVar, title, className, style }: ChatWidthHandleProps) { + const [dragging, setDragging] = useState(false) + const stripRef = useRef(null) + const cleanupRef = useRef<(() => void) | null>(null) + + // 拖拽中途组件卸载(切会话/分屏)时摘掉全局监听 + useEffect(() => () => cleanupRef.current?.(), []) + + // 辉光跟随指针 Y(dsh 的 --dsh-width-handle-pointer-y 同款):百分比写在自己身上 + const publishPointerY = (clientY: number) => { + const el = stripRef.current + if (!el) return + const rect = el.getBoundingClientRect() + if (rect.height <= 0) return + const pct = Math.min(100, Math.max(0, ((clientY - rect.top) / rect.height) * 100)) + el.style.setProperty(POINTER_Y_VAR, `${pct}%`) + } + + const onPointerDown = (event: React.PointerEvent) => { + if (event.button !== 0) return + event.preventDefault() + const root = rootRef.current + if (!root) return + const startX = event.clientX + const base = width + let last = base + setDragging(true) + publishPointerY(event.clientY) + + const onMove = (ev: PointerEvent) => { + // 列居中:左缘左移 dx(负值)→ 左右各让出 |dx| → 宽度 +2|dx| + const dx = ev.clientX - startX + last = Math.min(Math.max(base - dx * 2, MIN_CHAT_CONTENT_WIDTH), maxWidth) + root.style.setProperty(cssVar, `${last}px`) + publishPointerY(ev.clientY) + } + const onUp = () => { + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onUp) + cleanupRef.current = null + setDragging(false) + const finalWidth = Math.round(last) + if (finalWidth !== Math.round(base)) onCommit(finalWidth) + } + cleanupRef.current = onUp + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onUp) + } + + return ( +
    publishPointerY(e.clientY)} + className={`chat-width-handle ${className ?? ''}`} + style={style} + /> + ) +} diff --git a/src/features/chat/Header.tsx b/src/features/chat/Header.tsx index 1d3daf77e..e60b7e0cd 100644 --- a/src/features/chat/Header.tsx +++ b/src/features/chat/Header.tsx @@ -8,11 +8,16 @@ import { SplitHorizontalIcon, MaximizeIcon, MinimizeIcon, + DownloadIcon, + GitWorktreeIcon, } from '../../components/Icons' -import { IconButton } from '../../components/ui' +import { DropdownMenu, IconButton, MenuItem } from '../../components/ui' import { ModelSelector, type ModelSelectorHandle } from './ModelSelector' -import { SessionMoveMenu } from './SessionMoveMenu' +import { SessionMoveDialog } from './SessionMoveDialog' import { ShareDialog } from './ShareDialog' +import { useSessionActiveEntry } from '../../store/activeSessionStore' +import { serverStore } from '../../store/serverStore' +import { makeSessionKey } from '../../utils/sessionKey' import { messageStore, useHeaderSessionMeta } from '../../store' import { useLayoutStore, layoutStore } from '../../store/layoutStore' import { useSessionContext } from '../../contexts/useSessionContext' @@ -48,8 +53,15 @@ interface SessionTitleControlProps { handleRename: () => void handleStartEdit: () => void onShare: () => void + onMove: () => void + /** 会话运行中:菜单里的「移动」置灰(官方 blocked while running) */ + moveDisabled: boolean clickToRenameTitle: string - shareTitle: string + moreActionsTitle: string + exportTitle: string + exportDesc: string + moveTitle: string + moveRunningTitle: string } function SessionTitleControl({ @@ -63,9 +75,44 @@ function SessionTitleControl({ handleRename, handleStartEdit, onShare, + onMove, + moveDisabled, clickToRenameTitle, - shareTitle, + moreActionsTitle, + exportTitle, + exportDesc, + moveTitle, + moveRunningTitle, }: SessionTitleControlProps) { + // 标题右侧的 chevron 是「会话操作」入口:导出 / 移动都收进这个菜单, + // 不再单独占一个按钮。 + const [menuOpen, setMenuOpen] = useState(false) + const triggerRef = useRef(null) + const menuRef = useRef(null) + + useEffect(() => { + if (!menuOpen) return + const onPointerDown = (event: MouseEvent) => { + const target = event.target as Node + if (triggerRef.current?.contains(target) || menuRef.current?.contains(target)) return + setMenuOpen(false) + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + setMenuOpen(false) + triggerRef.current?.focus() + } + document.addEventListener('mousedown', onPointerDown) + document.addEventListener('keydown', onKeyDown) + return () => { + document.removeEventListener('mousedown', onPointerDown) + document.removeEventListener('keydown', onKeyDown) + } + }, [menuOpen]) + + // 注意:进入重命名时菜单会自动收起——点击标题按钮属于「外部点击」, + // 上面的 mousedown 监听会先关掉菜单,无需额外 effect。 + const inputClass = compact ? 'px-2 py-1.5 text-[length:var(--fs-base)] font-medium text-text-100 bg-transparent border-none outline-none w-[160px] h-full' : 'px-3 py-1.5 text-[length:var(--fs-base)] font-medium text-text-100 bg-transparent border-none outline-none w-[200px] lg:w-[300px] h-full text-center' @@ -75,10 +122,15 @@ function SessionTitleControl({ const dividerClass = compact ? 'w-[1.5px] h-3 bg-border-200/50 mx-0.5 shrink-0' : 'w-[1.5px] h-3 bg-border-200/50 mx-0.5 shrink-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(any-pointer:coarse)]:opacity-100 transition-opacity' - const shareButtonClass = compact + const menuButtonClass = compact ? 'p-1 text-text-400 hover:text-text-100 transition-colors rounded-md hover:bg-bg-300/50 shrink-0' : 'p-1 text-text-400 hover:text-text-100 transition-colors rounded-md hover:bg-bg-300/50 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(any-pointer:coarse)]:opacity-100 shrink-0' + const pick = (action: () => void) => { + setMenuOpen(false) + action() + } + return (
    -
    - + +
    + } + onClick={() => pick(onShare)} + /> + } + disabled={moveDisabled} + onClick={() => pick(onMove)} + /> +
    +
    )}
    @@ -137,6 +221,7 @@ export function Header({ const { composerSelectorStyle } = useTheme() const [shareDialogOpen, setShareDialogOpen] = useState(false) + const [moveDialogOpen, setMoveDialogOpen] = useState(false) const [isEditingTitle, setIsEditingTitle] = useState(false) const [editTitle, setEditTitle] = useState('') const titleInputRef = useRef(null) @@ -144,6 +229,11 @@ export function Header({ const sessionTitle = currentSessionTitle || t('header.newChat') const isCompact = presentation.isCompact + // 会话运行中禁止移动(官方 blocked while running)——用活跃状态判断 + const activeSessionKey = sessionId ? makeSessionKey(serverStore.getActiveServerId(), sessionId) : '' + const activeEntry = useSessionActiveEntry(activeSessionKey) + const sessionRunning = activeEntry?.status?.type === 'busy' || activeEntry?.status?.type === 'retry' + useEffect(() => { document.title = currentSessionTitle ? `${currentSessionTitle} - OpenCode` : 'OpenCode' return () => { @@ -185,26 +275,26 @@ export function Header({ } const titleControl = ( - <> - setShareDialogOpen(true)} - clickToRenameTitle={t('header.clickToRename')} - shareTitle={t('header.shareSession')} - /> - {/* 会话移动到其他目录 / worktree(v2 session.move,官方 session-workspace-menu) */} - {sessionId && !isEditingTitle && ( - - )} - + setShareDialogOpen(true)} + onMove={() => setMoveDialogOpen(true)} + moveDisabled={sessionRunning} + clickToRenameTitle={t('header.clickToRename')} + moreActionsTitle={t('header.moreActions')} + exportTitle={t('header.shareSession')} + exportDesc={t('header.exportSessionDesc')} + moveTitle={t('sessionMove.title')} + moveRunningTitle={t('sessionMove.runningTitle')} + /> ) return ( @@ -284,7 +374,22 @@ export function Header({ setShareDialogOpen(false)} /> -
    + {sessionId && ( + setMoveDialogOpen(false)} + sessionId={sessionId} + directory={sessionDirectory || currentDirectory || ''} + /> + )} + + {/* 用纯色块 + mask 渐隐,而不是 bg-gradient:渐变类在 Tailwind v4 里默认走 oklab, + 从 bg-bg-100 插值到 transparent(透明黑)中间会带出灰,和内容叠起来就是分层。 + mask 只动 alpha,不插值颜色,任何主题下都干净。 */} +
    ) } diff --git a/src/features/chat/InlinePermission.tsx b/src/features/chat/InlinePermission.tsx index 3ce3d0e7f..61f311a67 100644 --- a/src/features/chat/InlinePermission.tsx +++ b/src/features/chat/InlinePermission.tsx @@ -12,6 +12,7 @@ import type { ApiPermissionRequest, PermissionReply } from '../../api' import { ContentBlock } from '../../components' import { autoApproveStore } from '../../store' import { themeStore } from '../../store/themeStore' +import { extractPermissionDiff } from './permissionDiff' interface InlinePermissionProps { request: ApiPermissionRequest @@ -34,23 +35,9 @@ export const InlinePermission = memo(function InlinePermission({ const { toolCardStyle } = useSyncExternalStore(themeStore.subscribe, themeStore.getSnapshot) const isCompact = toolCardStyle === 'compact' - const metadata = request.metadata - const diff = metadata?.diff as string | undefined - const filepath = metadata?.filepath as string | undefined - - let diffData: { before: string; after: string } | string | undefined - if (metadata?.filediff && typeof metadata.filediff === 'object') { - const fd = metadata.filediff as Record - // 上游优先返回 patch 格式 - if (typeof fd.patch === 'string') { - diffData = fd.patch - } else if (fd.before !== undefined && fd.after !== undefined) { - diffData = { before: String(fd.before), after: String(fd.after) } - } - } - if (!diffData && diff) { - diffData = diff - } + const { diff, before, after, filePath: filepath } = extractPermissionDiff(request.metadata) + const diffData: { before: string; after: string } | string | undefined = + diff ?? (before !== undefined && after !== undefined ? { before, after } : undefined) const isFileEdit = request.action === 'edit' || request.action === 'write' const hasPatterns = request.resources && request.resources.length > 0 diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index 1103cd625..c5a4d4361 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -90,6 +90,8 @@ vi.mock('../../hooks', () => ({ vi.mock('../../store/messageStoreHooks', () => ({ useMessages: () => messagesMock, + useCurrentSessionId: () => null, + useSessionPromptHistory: () => [], })) vi.mock('../../store/keybindingStore', () => ({ @@ -151,10 +153,13 @@ describe('InputBox slash command selection', () => { expect(onSend).toHaveBeenCalledWith('hello world', [], { agent: undefined, variant: undefined }) }) - expect(textarea.value).toBe('hello world') + // 官方同款失败恢复:输入框仍是空的,旧草稿被放回来 + await waitFor(() => { + expect(textarea.value).toBe('hello world') + }) }) - it('waits for send acknowledgement before clearing the draft', async () => { + it('clears the draft immediately on submit and sends in the background', async () => { let resolveSend: ((value: boolean) => void) | null = null const onSend = vi.fn( () => @@ -169,15 +174,43 @@ describe('InputBox slash command selection', () => { fireEvent.change(textarea, { target: { value: 'pending send' } }) fireEvent.click(screen.getByRole('button', { name: 'send' })) - expect(textarea.value).toBe('pending send') + // 官方 composer 时序:提交即清空,不等 POST RTT + expect(textarea.value).toBe('') await act(async () => { resolveSend?.(true) }) - await waitFor(() => { - expect(textarea.value).toBe('') + // 发送成功后草稿保持清空 + expect(textarea.value).toBe('') + }) + + it('does not clobber a newer draft when a background send fails', async () => { + let resolveSend: ((value: boolean) => void) | null = null + const onSend = vi.fn( + () => + new Promise(resolve => { + resolveSend = resolve + }), + ) + + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: 'first message' } }) + fireEvent.click(screen.getByRole('button', { name: 'send' })) + + expect(textarea.value).toBe('') + + // 上一条还在后台发,用户已经开始打下一条 + fireEvent.change(textarea, { target: { value: 'next draft' } }) + + // 上一条发送失败 → 不能覆盖正在打的新草稿 + await act(async () => { + resolveSend?.(false) }) + + expect(textarea.value).toBe('next draft') }) it('clears api slash command drafts immediately after keyboard submission', async () => { @@ -358,3 +391,83 @@ describe('InputBox slash command selection', () => { }) }) }) + +describe('InputBox shell mode', () => { + beforeEach(() => { + slashCommands = [] + messagesMock = [] + promptHistoryStore.reset() + }) + + it('enters shell mode when typing ! into an empty input', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + // `!` 被消费,不进文本 + expect(textarea.value).toBe('') + }) + + it('restores the consumed ! when exiting shell mode with backspace on empty input', async () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + + // 「其实想输入 !」的退路:空命令退格 → 退模式并把 ! 还回来 + fireEvent.keyDown(textarea, { key: 'Backspace' }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + + // 光标在末尾,好继续打(如 !这个很重要) + await waitFor(() => { + expect(textarea.selectionStart).toBe(1) + }) + + // 继续输入就是普通文本 + fireEvent.change(textarea, { target: { value: '!这个很重要' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!这个很重要') + }) + + it('does not re-enter shell mode when deleting back to a lone !', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + // 经退格还原拿到字面 ! 后,继续编辑再删回 ! 不该重新进 shell 模式 + fireEvent.change(textarea, { target: { value: '!x' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + + fireEvent.change(textarea, { target: { value: '!' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + }) + + it('exits shell mode with escape and discards the input', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + fireEvent.change(textarea, { target: { value: 'git status' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + + fireEvent.keyDown(textarea, { key: 'Escape' }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('') + }) + + it('does not enter shell mode without onShell support', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + }) +}) diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index c076db6fe..c7984b496 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -20,16 +20,32 @@ import { useMobileCollapse } from './input/useMobileCollapse' import { useAttachmentRail } from './input/useAttachmentRail' import { useInputHistory } from './input/useInputHistory' import { promptHistoryStore } from '../../store/promptHistoryStore' +import { useCurrentSessionId, useSessionPromptHistory } from '../../store/messageStoreHooks' import { usePersistedDraft, draftStorageKey, clearPersistedDraft, readPersistedDraft } from './input/usePersistedDraft' import { TEXT_STYLE, + MAX_UPLOAD_BYTES, bytesToDataUrl, detectSlashTrigger, ensureFileMime, getMimeFromPath, - isFileSupported, readFileAsDataUrl, + routeAttachment, } from './input/inputUtils' +import { formatFileSize } from '../../utils/formatUtils' +import { + canReferenceLocalPath, + splitDroppedItems, + uploadFileAsAttachment, + uploadPathAsAttachment, + decideNativeFileRoute, + type NativeFileDecision, + type UploadFailure, +} from './input/attachmentUpload' +import { createUploadId } from '../../api/file' +import { notificationStore } from '../../store/notificationStore' +import { LOCAL_SERVER_ID, serverStore } from '../../store/serverStore' +import { sessionKeyToServerId } from '../../utils/sessionKey' import { keybindingStore, matchesKeybinding } from '../../store/keybindingStore' import { themeStore } from '../../store/themeStore' import { useChatViewport } from './chatViewport' @@ -118,6 +134,30 @@ export interface CollapsedDialogInfo { onExpand: () => void } +/** + * 一次待上传的来源。 + * + * 浏览器/粘贴只能给 `File`;桌面端拖入与选择器给的是**本机绝对路径**—— + * 那条走 Rust 流式上传(不读进渲染进程,也有进度)。 + */ +type PendingUpload = + | { + kind: 'file' + file: File + filename: string + mime: string + size: number + pathOnly: boolean + } + | { + kind: 'path' + path: string + filename: string + mime: string + size: number + pathOnly: boolean + } + export interface InputBoxProps { paneId: string onSend: ( @@ -148,6 +188,8 @@ export interface InputBoxProps { modelSelectorRef?: React.RefObject rootPath?: string sessionId?: string | null + /** pane 绑定的服务器 id(附件上传目标;缺省回落到活动服务器) */ + serverId?: string // Undo/Redo revertedText?: string revertedAttachments?: Attachment[] @@ -185,6 +227,7 @@ export interface InputBoxProps { // Collapsed dialog capsules collapsedPermission?: CollapsedDialogInfo collapsedQuestion?: CollapsedDialogInfo + collapsedWebsearch?: CollapsedDialogInfo } // ============================================ @@ -216,6 +259,7 @@ function InputBoxComponent({ modelSelectorRef, rootPath = '', sessionId, + serverId: serverIdProp, revertedText, revertedAttachments, composerDraft, @@ -235,6 +279,7 @@ function InputBoxComponent({ onScrollToBottom, collapsedPermission, collapsedQuestion, + collapsedWebsearch, }: InputBoxProps) { const { t } = useTranslation('chat') // 合并文件能力:优先用 fileCapabilities,回退到 supportsImages @@ -250,8 +295,162 @@ function InputBoxComponent({ ) const { externalFileDropMode, queueDeliveryChipVisible } = useSyncExternalStore(themeStore.subscribe, themeStore.getSnapshot) - // 是否有任何文件附件能力 - const supportsAnyFile = fileCaps.image || fileCaps.pdf || fileCaps.audio || fileCaps.video + // 注意:这里**不再**有「模型无原生文件能力就丢弃文件」的闸门(旧 supportsAnyFile)。 + // 白名单外的文件现在会走服务端上传(Issue #182),能不能内联只影响形态,不影响能否添加。 + + // ============================================ + // 附件上传(Issue #182) + // ============================================ + + /** 上传目标:pane 绑定的服务器 + 当前工作目录 */ + const uploadTarget = useMemo( + () => ({ + serverId: serverIdProp ?? (sessionId ? sessionKeyToServerId(sessionId) : undefined), + directory: rootPath || undefined, + }), + [rootPath, serverIdProp, sessionId], + ) + + /** + * 服务端是否与客户端同机(需求二)。 + * + * 同机时**不走上传**:桌面端拖入的文件直接沿用原有的引用方式 + * (原生媒体内联;其余退化成 `@` 引用,服务端自己能读到那个路径)。 + * 浏览器里永远拿不到真实路径,所以同机也照旧上传(issue #182 的主场景)。 + */ + const serverIsLocal = useMemo(() => serverStore.isLocalServer(uploadTarget.serverId), [uploadTarget.serverId]) + + /** 应用自己拉起的服务(`local` 条目):必然同机,引用时免探测 */ + const pinnedLocalServer = useMemo( + () => (uploadTarget.serverId ?? serverStore.getActiveServerId()) === LOCAL_SERVER_ID, + [uploadTarget.serverId], + ) + + /** 在途上传(id → 完成信号)。发送前必须清空,避免把半个附件发出去 */ + const pendingUploadsRef = useRef(new Map>()) + /** 失败后可重试的上传源(id → 源 + 路由结果) */ + const uploadSourcesRef = useRef(new Map()) + const [uploadingCount, setUploadingCount] = useState(0) + + const notifyAttachmentError = useCallback( + (title: string, body: string) => { + notificationStore.push('error', title, body, sessionId ?? '', rootPath || undefined) + }, + [rootPath, sessionId], + ) + + /** 失败原因文案(拿不到具体原因时回落成服务端/浏览器给的原文) */ + const uploadFailureBody = useCallback( + (name: string, failure: UploadFailure) => + t('attachment.uploadFailed.body', { + name, + reason: t(`attachment.uploadFailed.reason.${failure.reason}`, { defaultValue: failure.message }), + }), + [t], + ) + + /** + * 跑一次上传:完成后把占位附件**原地替换**成路径型附件(保持 id,chip 不跳), + * 失败则标记 failed 并弹出可见错误——issue #182 明确要求不静默吞掉。 + */ + const runAttachmentUpload = useCallback( + (attachmentId: string, entry: PendingUpload) => { + const task = (async () => { + const options = { + ...uploadTarget, + pathOnly: entry.pathOnly, + // 浏览器走 XHR、桌面端走 Rust 命令,两条都能推真实进度; + // 拿不到进度时回调不触发 → 胶囊保持不确定态转圈 + onProgress: (fraction: number) => { + setAttachments(prev => + prev.map(item => { + if (item.id !== attachmentId) return item + // 百分比没变就不换引用,避免每个 progress 事件都触发重渲染 + if (item.progress !== undefined && Math.round(item.progress * 100) === Math.round(fraction * 100)) { + return item + } + return { ...item, progress: fraction } + }), + ) + }, + } + + const { attachment, failure } = + entry.kind === 'file' + ? await uploadFileAsAttachment(entry.file, options) + : await uploadPathAsAttachment(entry.path, entry.filename, entry.mime, options) + + if (attachment) { + setAttachments(prev => + prev.map(item => (item.id === attachmentId ? { ...attachment, id: attachmentId } : item)), + ) + return + } + + setAttachments(prev => + prev.map(item => (item.id === attachmentId ? { ...item, uploadStatus: 'failed' as const } : item)), + ) + notifyAttachmentError( + t('attachment.uploadFailed.title', { name: entry.filename }), + uploadFailureBody(entry.filename, failure ?? { reason: 'unknown', message: '' }), + ) + })() + + const settled = task.finally(() => { + pendingUploadsRef.current.delete(attachmentId) + setUploadingCount(count => Math.max(0, count - 1)) + }) + + pendingUploadsRef.current.set(attachmentId, settled) + setUploadingCount(count => count + 1) + void settled + }, + [notifyAttachmentError, t, uploadFailureBody, uploadTarget], + ) + + /** + * 插入占位附件并开始上传。 + * + * 顺序很重要:**先把占位插进 state,再开上传**。上传进度用的是函数式 + * `setAttachments`,React 会按入队顺序应用,因此这里不会出现"进度先到、 + * 占位还没落地 → 进度丢失"的竞态。 + */ + const startAttachmentUpload = useCallback( + (entry: PendingUpload) => { + const attachmentId = createUploadId() + uploadSourcesRef.current.set(attachmentId, entry) + + setAttachments(prev => [ + ...prev, + { + id: attachmentId, + type: 'file', + displayName: entry.filename, + mime: entry.mime, + size: entry.size, + uploadStatus: 'uploading', + ...(entry.pathOnly ? { pathOnly: true } : {}), + }, + ]) + + runAttachmentUpload(attachmentId, entry) + }, + [runAttachmentUpload], + ) + + /** 重试失败的上传(保留同一个 chip 与 id) */ + const retryAttachmentUpload = useCallback( + (attachmentId: string) => { + const entry = uploadSourcesRef.current.get(attachmentId) + if (!entry) return + + setAttachments(prev => + prev.map(item => (item.id === attachmentId ? { ...item, uploadStatus: 'uploading' as const } : item)), + ) + runAttachmentUpload(attachmentId, entry) + }, + [runAttachmentUpload], + ) // 文本状态 const [text, setText] = useState('') @@ -260,7 +459,6 @@ function InputBoxComponent({ const [shellMode, setShellMode] = useState(false) // 附件状态(图片、文件、文件夹、agent) const [attachments, setAttachments] = useState([]) - const [isSubmitting, setIsSubmitting] = useState(false) // @ Mention 状态 const [mentionOpen, setMentionOpen] = useState(false) @@ -310,16 +508,23 @@ function InputBoxComponent({ // ============================================ // 历史消息导航(类终端体验,逻辑在 useInputHistory hook 中) - // 数据源:全局持久化 prompt 历史(官方 composer/history 同款) + // 数据源:当前会话自己的历史用户输入(在该会话里翻这个会话发过的内容), + // 新会话/无消息时回退全局持久化 prompt 历史(官方 composer/history 同款) // + 当前会话/工作区的持久化草稿(空输入按 ↑ 先召回草稿) // ============================================ const draftKey = useMemo(() => draftStorageKey(sessionId, rootPath), [sessionId, rootPath]) const draftKeyRef = useRef(null) draftKeyRef.current = draftKey + const focusedSessionId = useCurrentSessionId() + const sessionPromptHistory = useSessionPromptHistory() + // shell 轨道没有会话内来源(shell 命令是独立消息类型),保持全局轨道 + const historyEntries = + !shellMode && sessionId && sessionId === focusedSessionId ? sessionPromptHistory : null const { handleHistoryKeyDown, handleHistoryChange, resetHistoryIndex } = useInputHistory({ textareaRef, mode: shellMode ? 'shell' : 'normal', recallDraft: useCallback(() => readPersistedDraft(draftKeyRef.current), []), + sessionEntries: historyEntries, }) // 草稿持久化(按会话/工作区作用域,官方 composer persistence 的存储维度; @@ -342,6 +547,7 @@ function InputBoxComponent({ registerInputBox, collapsedPermission, collapsedQuestion, + collapsedWebsearch, }) // 处理 revert 恢复 @@ -362,7 +568,7 @@ function InputBoxComponent({ textareaRef.current.setSelectionRange(revertedText.length, revertedText.length) } }) - } else if (prevRevertedTextRef.current !== undefined && revertedText === undefined && !isSubmitting) { + } else if (prevRevertedTextRef.current !== undefined && revertedText === undefined) { frameId = requestAnimationFrame(() => { setText('') setAttachments([]) @@ -376,7 +582,7 @@ function InputBoxComponent({ cancelAnimationFrame(frameId) } } - }, [revertedText, revertedAttachments, isSubmitting]) + }, [revertedText, revertedAttachments]) // 队列编辑草稿:装载(暂存当前输入)/ 恢复(取消编辑),nonce 为触发键 const draftStashRef = useRef<{ text: string; attachments: Attachment[] } | null>(null) @@ -491,7 +697,10 @@ function InputBoxComponent({ // 计算 const inputDisabled = !!disabled - const canSend = (text.trim().length > 0 || attachments.length > 0) && !inputDisabled + // 有在途上传时不允许发送:附件还没落到服务端,发出去的 prompt 会缺文件 + //(官方 composer 也是等 uploads.pending 清空才提交) + const hasPendingUploads = uploadingCount > 0 + const canSend = (text.trim().length > 0 || attachments.length > 0) && !inputDisabled && !hasPendingUploads // ============================================ // Handlers @@ -561,29 +770,42 @@ function InputBoxComponent({ [attachments, onClearRevert, onCommand, resetDraft, restoreDraft, text], ) - const runSubmit = useCallback( - async (submit: () => Promise | boolean | void, onSuccess?: () => void, onFailure?: () => void) => { - if (isSubmitting) return false - - setIsSubmitting(true) - try { - const result = await submit() - if (result === false) { - onFailure?.() - return false + /** + * 提交即清空、后台发送、失败恢复(官方 composer submit.ts 同款时序: + * clearSubmission → void sending → failSubmission(restore))。 + * + * 之前用 runSubmit 等 POST 落定(switchModel → switchAgent → prompt 三个 + * 串行 RTT)才清输入框,按回车后文本要在框里「粘」几百毫秒——不优雅的 + * 体感来源。现在提交瞬间清空,发送在后台跑;失败时输入框还没被新内容 + * 占用才恢复旧草稿(sendMessageNow 另有失败通知)。 + */ + const submitOptimistically = useCallback( + (submit: () => Promise | boolean | void, opts?: { onSuccess?: () => void; onFailure?: () => void }) => { + const draftSnapshot: HistoryEntry = { text, attachments: [...attachments] } + resetDraft() + void (async () => { + let ok: boolean + try { + ok = (await submit()) !== false + } catch { + ok = false } - - onSuccess?.() - return true - } finally { - setIsSubmitting(false) - } + if (ok) { + opts?.onSuccess?.() + return + } + opts?.onFailure?.() + const currentDraft = latestDraftRef.current + if (currentDraft.text.length === 0 && currentDraft.attachments.length === 0) { + restoreDraft(draftSnapshot) + } + })() }, - [isSubmitting], + [attachments, resetDraft, restoreDraft, text], ) const handleSend = useCallback(() => { - if (!canSend || isSubmitting) return + if (!canSend) return // shell mode:原样提交命令给 session.shell,保持 shell mode(类终端连续输入) if (shellMode) { @@ -591,11 +813,9 @@ function InputBoxComponent({ if (!command || !onShell) return // shell 轨道历史记账(官方 history.add 同款:发送即记账、失败移除) promptHistoryStore.add(command, [], 'shell') - void runSubmit( - () => onShell(command), - () => setText(''), - () => promptHistoryStore.remove(command, [], 'shell'), - ) + submitOptimistically(() => onShell(command), { + onFailure: () => promptHistoryStore.remove(command, [], 'shell'), + }) return } @@ -626,20 +846,21 @@ function InputBoxComponent({ // normal 轨道历史记账(官方 history.add 同款:发送即记账、失败移除) promptHistoryStore.add(text, attachments, 'normal') - void runSubmit( + submitOptimistically( () => onSend(text, attachments, { agent: agentObj?.id ?? agentRef, variant: selectedVariant, }), - () => { - // 队列编辑草稿发送成功 → 丢弃暂存(官方 confirmEdit 同款: - // 发送的内容就是编辑结果,不再恢复旧输入) - draftStashRef.current = null - resetDraft() - onClearRevert?.() + { + onSuccess: () => { + // 队列编辑草稿发送成功 → 丢弃暂存(官方 confirmEdit 同款: + // 发送的内容就是编辑结果,不再恢复旧输入) + draftStashRef.current = null + onClearRevert?.() + }, + onFailure: () => promptHistoryStore.remove(text, attachments, 'normal'), }, - () => promptHistoryStore.remove(text, attachments, 'normal'), ) } @@ -655,8 +876,7 @@ function InputBoxComponent({ .catch(() => false) .then(isCommand => { if (isCommand) { - void onCommand(trimmedText) - resetDraft() + submitCommandOptimistically(trimmedText) } else { // 不是已知命令 → 按普通消息发送 sendCurrent() @@ -670,18 +890,16 @@ function InputBoxComponent({ agents, attachments, canSend, - isSubmitting, onCommand, onClearRevert, onSend, onShell, - resetDraft, - runSubmit, + rootPath, selectedAgent, selectedVariant, shellMode, submitCommandOptimistically, - rootPath, + submitOptimistically, text, ]) @@ -715,7 +933,7 @@ function InputBoxComponent({ if (isImeComposing && (e.key === 'Enter' || e.key === 'Tab')) return - // shell mode(官方 machine.ts:203 + submit.ts:147):Enter 直接执行, + // shell mode(官方 machine.ts:232 + submit.ts:147):Enter 直接执行, // esc / 空文本退格退回普通模式 if (shellMode) { if (e.key === 'Escape') { @@ -727,6 +945,14 @@ function InputBoxComponent({ if (e.key === 'Backspace' && text.length === 0) { e.preventDefault() setShellMode(false) + // 「其实想输入 !」的退路:删掉 shell 模式,把进入时被消费的 `!` 还回来, + // 光标放到末尾好继续打(官方只退模式不还原,这里比官方宽容) + setText('!') + requestAnimationFrame(() => { + if (!textareaRef.current) return + textareaRef.current.focus() + textareaRef.current.setSelectionRange(1, 1) + }) return } if (e.key === 'Enter' && !e.shiftKey && !isImeComposing) { @@ -843,8 +1069,10 @@ function InputBoxComponent({ (e: React.ChangeEvent) => { const newText = e.target.value - // `!` 进入 shell mode(官方 machine.ts:203 同款:`!` 被消费,不进文本) - if (!shellMode && newText === '!' && onShell) { + // 空输入框敲入 `!` 进入 shell mode(官方 machine.ts:109 同款:`!` 被消费,不进文本)。 + // 额外要求之前是空文本(官方是 value === "!" 就触发):从 `!x` 删除回 `!` + // 不该重新进 shell——那是编辑普通文本,不是想跑命令。 + if (!shellMode && newText === '!' && text === '' && onShell) { setShellMode(true) setText('') setMentionOpen(false) @@ -905,7 +1133,7 @@ function InputBoxComponent({ } } }, - [handleHistoryChange, shellMode, onShell], + [handleHistoryChange, shellMode, onShell, text], ) const handleCompositionStart = useCallback(() => { @@ -955,13 +1183,16 @@ function InputBoxComponent({ const newText = beforeAt + mentionText + ' ' + afterQuery // 创建附件(reference 按目录附件插入,值为引用目录的绝对路径——官方 mime 是 application/x-directory) + // url 必须是合法 file:// URL(服务端 readFileAttachment 用 new URL + protocol==='file:' 校验, + // 裸绝对路径 `E:/...` 会被解析成 `e:` 协议直接 400——侧边栏拖入走 toFileUrl 所以没事, + // 这里对齐官方 request.ts:109 的 `file://${encodeFilePath(path)}`) const attachType = item.type === 'reference' ? 'folder' : item.type const attachment: Attachment = { id: crypto.randomUUID(), type: attachType, displayName: item.displayName, relativePath: item.type === 'reference' ? item.value : item.relativePath, - url: item.type !== 'agent' && item.type !== 'skill' ? item.value : undefined, + url: item.type !== 'agent' && item.type !== 'skill' ? toFileUrl(item.value) : undefined, mime: item.type === 'reference' ? 'application/x-directory' : item.type !== 'agent' ? 'text/plain' : undefined, agentName: item.type === 'agent' ? item.displayName : undefined, skillId: item.type === 'skill' ? item.value : undefined, @@ -1053,46 +1284,73 @@ function InputBoxComponent({ textareaRef.current?.focus() }, []) - // 通用文件上传 — 根据模型能力判断是否接受 + // 通用文件分发 — 原生媒体内联;其余(白名单外 / 超限)上传到服务端临时目录 + // 并以路径附件发送(Issue #182)。三路规则见 inputUtils.routeAttachment。 const handleFilesSelected = useCallback( async (files: File[]) => { - if (files.length === 0 || !supportsAnyFile || isSubmitting) return + if (files.length === 0) return - const nextAttachments: Attachment[] = [] + const inlineAttachments: Attachment[] = [] for (const rawFile of files) { const file = ensureFileMime(rawFile) + const mime = file.type || getMimeFromPath(file.name) || 'application/octet-stream' + + // 浏览器里永远拿不到文件的真实路径(安全边界),所以即使服务端在本机 + // 也只能上传——references 需要 nativePath,这里不传自然落到 upload。 + const route = routeAttachment({ mime, size: file.size, caps: fileCaps, serverIsLocal }) + + if (route.kind === 'inline') { + try { + const dataUrl = await readFileAsDataUrl(file) + + inlineAttachments.push({ + id: crypto.randomUUID(), + type: 'file', + displayName: file.name, + url: dataUrl, + mime: file.type, + size: file.size, + }) + } catch (err) { + console.warn('[InputBox] Failed to process file:', err) + notifyAttachmentError( + t('attachment.readFailed.title', { name: file.name }), + t('attachment.readFailed.body'), + ) + } + continue + } - // 按 MIME 类型检查模型能力 - if (!isFileSupported(file.type, fileCaps)) continue - - try { - const dataUrl = await readFileAsDataUrl(file) - - nextAttachments.push({ - id: crypto.randomUUID(), - type: 'file', - displayName: file.name, - url: dataUrl, - mime: file.type, - }) - } catch (err) { - console.warn('[InputBox] Failed to process file:', err) + if (route.kind === 'reject') { + notifyAttachmentError( + t('attachment.tooLarge.title', { name: file.name }), + t('attachment.tooLarge.body', { max: formatFileSize(MAX_UPLOAD_BYTES) }), + ) + continue } + + // 上传:占位与启动都在 startAttachmentUpload 里(保证进度不会先于占位落地) + startAttachmentUpload({ + kind: 'file', + file, + filename: file.name, + mime, + size: file.size, + pathOnly: route.pathOnly, + }) } - if (nextAttachments.length > 0) { - setAttachments(prev => [...prev, ...nextAttachments]) + if (inlineAttachments.length > 0) { + setAttachments(prev => [...prev, ...inlineAttachments]) } }, - [supportsAnyFile, fileCaps, isSubmitting], + [fileCaps, notifyAttachmentError, serverIsLocal, startAttachmentUpload, t], ) // 删除附件 const handleRemoveAttachment = useCallback( (id: string) => { - if (isSubmitting) return - const attachment = attachments.find(a => a.id === id) if (!attachment) return @@ -1104,15 +1362,17 @@ function InputBoxComponent({ setText(newText) } + // 失败/在途的上传源不再需要(在途任务完成时会自行丢弃结果) + uploadSourcesRef.current.delete(id) setAttachments(prev => prev.filter(a => a.id !== id)) }, - [attachments, isSubmitting, text], + [attachments, text], ) - // 粘贴处理 — 根据模型能力过滤可粘贴的文件类型 + // 粘贴处理 — 文件项交给三路分发(白名单外会上传到服务端,不再被丢弃) const handlePaste = useCallback( (e: React.ClipboardEvent) => { - if (supportsAnyFile) { + { const items = e.clipboardData?.items const files: File[] = [] @@ -1120,7 +1380,7 @@ function InputBoxComponent({ for (let i = 0; i < items.length; i++) { if (items[i].kind === 'file') { const file = items[i].getAsFile() - if (file && isFileSupported(ensureFileMime(file).type, fileCaps)) files.push(file) + if (file) files.push(file) } } } @@ -1134,7 +1394,7 @@ function InputBoxComponent({ // 文本粘贴:让 textarea 默认处理(天然支持换行和 undo) }, - [supportsAnyFile, fileCaps, handleFilesSelected], + [handleFilesSelected], ) // 拖拽文件到输入框 @@ -1143,11 +1403,11 @@ function InputBoxComponent({ e.preventDefault() e.stopPropagation() dragCounterRef.current++ - if (supportsAnyFile && e.dataTransfer.types.includes('Files')) { + if (e.dataTransfer.types.includes('Files')) { setIsDragging(true) } }, - [supportsAnyFile], + [], ) const handleDragOver = useCallback((e: React.DragEvent) => { @@ -1253,51 +1513,173 @@ function InputBoxComponent({ [rootPath], ) + /** + * 桌面端拖入的**本机文件** → 附件。 + * + * 桌面端拿到的是本机绝对路径,服务端可能在远端,所以只有「服务端与本机 + * 同机」时才谈得上直引(需求二)。本期一律走:原生媒体且未超限 → 读成 + * data URL 内联;其余 → 上传到服务端临时目录后作路径附件(Issue #182)。 + */ const createUploadAttachmentFromDroppedPath = useCallback( - async (fileInfo: DroppedPathInfo): Promise => { + async (fileInfo: DroppedPathInfo): Promise => { if (fileInfo.type !== 'file') return null + const name = fileInfo.name || getFileName(fileInfo.path) const mime = getMimeFromPath(fileInfo.path) - if (!isFileSupported(mime, fileCaps)) return null + + const rejectTooLarge = () => { + notifyAttachmentError( + t('attachment.tooLarge.title', { name }), + t('attachment.tooLarge.body', { max: formatFileSize(MAX_UPLOAD_BYTES) }), + ) + return 'skip' as const + } + + const inlineAttachment = (bytes: Uint8Array, byteLength: number): Attachment => ({ + id: crypto.randomUUID(), + type: 'file', + displayName: name, + url: bytesToDataUrl(bytes, mime), + mime, + size: byteLength, + }) try { - const { readFile } = await import('@tauri-apps/plugin-fs') + const { readFile, stat } = await import('@tauri-apps/plugin-fs') + + // 先探大小:内联判定与上传上限都要它,也避免把超大文件读进内存 + let size = -1 + try { + const info = await stat(fileInfo.path) + size = Number(info.size ?? -1) + } catch { + size = -1 + } + + const decideRoute = (byteLength: number) => + decideNativeFileRoute({ + mime, + size: byteLength, + caps: fileCaps, + serverIsLocal, + nativePath: fileInfo.path, + }) + + // 判定 + 确认,只算一次:'mention' 分支还要问服务端「这个路径你读得到吗」, + // 读不到就不能沿用本机引用(容器转发 / 真远端),改走上传。 + let decided: NativeFileDecision | null = null + const resolveRoute = async (byteLength: number) => { + if (!decided) { + const route = decideRoute(byteLength) + decided = + route.kind === 'mention' && !(await canReferenceLocalPath({ + path: fileInfo.path, + pinnedLocal: pinnedLocalServer, + directory: uploadTarget.directory, + serverId: uploadTarget.serverId, + })) + ? { kind: 'upload', pathOnly: true } + : route + } + return decided + } + + if (size >= 0) { + const route = await resolveRoute(size) + // 'mention' = 服务端读得到这个本机路径 → 交回调用方退化成 @ 引用(原行为) + if (route.kind === 'mention') return null + if (route.kind === 'reject') return rejectTooLarge() + if (route.kind === 'inline') return inlineAttachment(await readFile(fileInfo.path), size) + } + const bytes = await readFile(fileInfo.path) - return { - id: crypto.randomUUID(), - type: 'file', - displayName: fileInfo.name || getFileName(fileInfo.path), - url: bytesToDataUrl(bytes, mime), + size = size >= 0 ? size : bytes.byteLength + + const route = await resolveRoute(size) + if (route.kind === 'mention') return null + if (route.kind === 'reject') return rejectTooLarge() + if (route.kind === 'inline') return inlineAttachment(bytes, size) + + // 上传:不把字节交给渲染进程,直接把本机路径交给 Rust 流式发送 + // (占位 chip 与进度都由 startAttachmentUpload 负责) + startAttachmentUpload({ + kind: 'path', + path: fileInfo.path, + filename: name, mime, - } + size, + pathOnly: route.pathOnly, + }) + return 'skip' } catch (err) { - console.warn('[InputBox] Failed to read dropped file for upload:', err) + // 读取失败可能是权限/瞬时问题:退化为 @mention(本机服务端仍可能读到) + console.warn('[InputBox] Failed to process dropped file:', err) return null } }, - [fileCaps], + [ + fileCaps, + notifyAttachmentError, + pinnedLocalServer, + serverIsLocal, + startAttachmentUpload, + t, + uploadTarget, + ], ) - const handleTauriExternalDrop = useCallback( - async (paths: string[]) => { - if (paths.length === 0 || isSubmitting) return + /** + * 桌面端「拿到本机路径」的统一入口:拖入与点回形针选文件共用同一条判定链 + * (原生媒体内联 / 本机实例 `@` 引用 / 远端上传)。 + * + * `respectMentionMode`:只有拖入响应「拖入文件始终使用 @」设置;选择器是显式 + * 动作,一律按判定链走。 + */ + const addTauriPaths = useCallback( + async (paths: string[], options: { respectMentionMode: boolean }) => { + if (paths.length === 0) return try { - const droppedPaths = await getDroppedPathsInfo(paths) + const infos = await getDroppedPathsInfo(paths) const uploadAttachments: Attachment[] = [] const mentionFiles: DraggedFileInfo[] = [] - for (const droppedPath of droppedPaths) { - if (externalFileDropMode === 'mention') { - mentionFiles.push(buildDraggedFileInfo(droppedPath)) + for (const info of infos) { + if (options.respectMentionMode && externalFileDropMode === 'mention') { + mentionFiles.push(buildDraggedFileInfo(info)) continue } - const uploadAttachment = await createUploadAttachmentFromDroppedPath(droppedPath) - if (uploadAttachment) { - uploadAttachments.push(uploadAttachment) + const result = await createUploadAttachmentFromDroppedPath(info) + if (result === 'skip') { + // 两种「不用再加东西」的情况: + // 1) 走上传:占位 chip 已由 startAttachmentUpload 插入,进度也归它管 + // 2) 超限 / 上传失败:已弹过可见提示,不能再退化成 @mention + // (服务端在远端时那个本机路径读不到) + continue + } + if (result) { + uploadAttachments.push(result) + } else if (info.type === "folder") { + // 文件夹:不上传。只有服务端真能读到这个路径(本机实例)才退化为 @ 引用; + // 连远端实例时本机目录对它没有意义,明确拒绝,别塞一个没用的路径引用过去 + const readable = await canReferenceLocalPath({ + path: info.path, + pinnedLocal: serverIsLocal, + directory: uploadTarget.directory, + serverId: uploadTarget.serverId, + }) + if (readable) { + mentionFiles.push(buildDraggedFileInfo(info)) + } else { + notifyAttachmentError( + t('attachment.folderUnsupported.title'), + t('attachment.folderUnsupported.body', { names: info.name }), + ) + } } else { - mentionFiles.push(buildDraggedFileInfo(droppedPath)) + // 服务端读不到该路径:退化为 @ 引用 + mentionFiles.push(buildDraggedFileInfo(info)) } } @@ -1307,10 +1689,30 @@ function InputBoxComponent({ insertDraggedFiles(mentionFiles) } catch (err) { - console.warn('[InputBox] Failed to process Tauri dropped paths:', err) + console.warn('[InputBox] Failed to process dropped paths:', err) } }, - [buildDraggedFileInfo, createUploadAttachmentFromDroppedPath, externalFileDropMode, insertDraggedFiles, isSubmitting], + [ + buildDraggedFileInfo, + createUploadAttachmentFromDroppedPath, + externalFileDropMode, + insertDraggedFiles, + notifyAttachmentError, + serverIsLocal, + t, + uploadTarget, + ], + ) + + const handleTauriExternalDrop = useCallback( + (paths: string[]) => addTauriPaths(paths, { respectMentionMode: true }), + [addTauriPaths], + ) + + /** 桌面端点回形针选中的文件:与拖入同一条链路 */ + const handlePickedPaths = useCallback( + (paths: string[]) => addTauriPaths(paths, { respectMentionMode: false }), + [addTauriPaths], ) const handleTauriDragDropEvent = useCallback( @@ -1348,12 +1750,27 @@ function InputBoxComponent({ setIsDragging(false) // 原生文件拖拽(从操作系统拖入) - if (e.dataTransfer.files.length > 0) { + // 先按 entry 分流:文件夹(浏览器里表现为 size 0 的假 File)必须在上传前拦掉, + // 否则会得到一个空附件,请求还会被浏览器安全策略挡掉(ERR_ACCESS_DENIED)。 + // 注意兜底只给"没有 items 可用"的环境,不能在拣完只剩文件夹时回退到 files + const dropped = splitDroppedItems( + Array.from(e.dataTransfer.items ?? []), + Array.from(e.dataTransfer.files), + ) + + if (dropped.folderNames.length > 0) { + notifyAttachmentError( + t('attachment.folderUnsupported.title'), + t('attachment.folderUnsupported.body', { names: dropped.folderNames.join(', ') }), + ) + } + + if (dropped.files.length > 0) { if (Date.now() - lastTauriDropAtRef.current < 750) return - void handleFilesSelected(Array.from(e.dataTransfer.files)) + void handleFilesSelected(dropped.files) } }, - [handleFilesSelected], + [handleFilesSelected, notifyAttachmentError, t], ) // 滚动同步(备用,overlay 内部也监听了 scroll) @@ -1399,7 +1816,7 @@ function InputBoxComponent({ return (
    @@ -1530,17 +1948,18 @@ function InputBoxComponent({
    {attachmentsOverflowing && showAttachmentLeftFade && ( -
    +
    )} {attachmentsOverflowing && showAttachmentRightFade && ( -
    +
    )}
    @@ -1597,8 +2016,8 @@ function InputBoxComponent({ onVariantChange={onVariantChange} fileCapabilities={fileCaps} onFilesSelected={handleFilesSelected} + onPickedPaths={handlePickedPaths} isStreaming={isStreaming} - isSending={isSubmitting} busyDelivery={busyDelivery} onBusyDeliveryChange={onBusyDeliveryChange} deliveryChipVisible={queueDeliveryChipVisible} diff --git a/src/features/chat/InputBoxAttachments.test.tsx b/src/features/chat/InputBoxAttachments.test.tsx index 53b69e43e..b2bc78e4a 100644 --- a/src/features/chat/InputBoxAttachments.test.tsx +++ b/src/features/chat/InputBoxAttachments.test.tsx @@ -3,10 +3,60 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { InputBox } from './InputBox' let selectedFiles: File[] = [] +/** 桌面端选择器返回的本机路径 */ +let selectedPaths: string[] = [] + +const uploadAttachmentMock = vi.fn() +const uploadLocalFileMock = vi.fn() +const createUploadIdMock = vi.fn(() => `upload-${uploadAttachmentMock.mock.calls.length}`) +const notifyPushMock = vi.fn() +const getDroppedPathsInfoMock = vi.fn(async (paths: string[]) => + paths.map(path => ({ type: 'file' as const, path, name: path.split(/[/\\]/).pop() || 'file' })), +) + +vi.mock('../../lib/tauriDragDrop', () => ({ + getDroppedPathsInfo: (paths: string[]) => getDroppedPathsInfoMock(paths), + isTauriDropPointInsideElement: () => false, + subscribeTauriDragDrop: () => () => {}, +})) + +vi.mock('../../api/file', () => ({ + uploadAttachment: (...args: unknown[]) => uploadAttachmentMock(...args), + // 桌面端(本机路径)走 Rust 流式上传:这里只验证「路径被交给它」,不测 Rust + uploadLocalFile: (...args: unknown[]) => uploadLocalFileMock(...args), + createUploadId: () => createUploadIdMock(), + probeServerPath: vi.fn(async () => true), +})) + +vi.mock('../../store/notificationStore', () => ({ + notificationStore: { + push: (...args: unknown[]) => notifyPushMock(...args), + }, +})) vi.mock('../attachment', () => ({ - AttachmentPreview: ({ attachments }: { attachments: Array<{ id: string }> }) => ( -
    {attachments.length}
    + AttachmentPreview: ({ + attachments, + onRetry, + }: { + attachments: Array<{ id: string; url?: string; uploadStatus?: string; progress?: number }> + onRetry?: (id: string) => void + }) => ( +
    + {attachments.length} + {attachments.map(attachment => ( + + {`${attachment.url ?? ''}|${attachment.uploadStatus ?? ''}|${attachment.progress ?? ''}`} + + ))} + {attachments + .filter(attachment => attachment.uploadStatus === 'failed') + .map(attachment => ( + + ))} +
    ), })) @@ -29,7 +79,7 @@ vi.mock('../mention', () => ({ MentionMenu: () => null, detectMentionTrigger: () => null, normalizePath: (value: string) => value, - toFileUrl: (value: string) => value, + toFileUrl: (value: string) => `file://${value}`, })) vi.mock('../slash-command', () => ({ @@ -37,10 +87,21 @@ vi.mock('../slash-command', () => ({ })) vi.mock('./input/InputToolbar', () => ({ - InputToolbar: ({ onFilesSelected }: { onFilesSelected: (files: File[]) => void }) => ( - + InputToolbar: ({ + onFilesSelected, + onPickedPaths, + }: { + onFilesSelected: (files: File[]) => void + onPickedPaths?: (paths: string[]) => void + }) => ( + <> + + + ), })) @@ -48,6 +109,14 @@ vi.mock('./input/InputFooter', () => ({ InputFooter: () => null, })) +const statMock = vi.fn(async (_path: string) => ({ size: 262 })) +const readFileMock = vi.fn(async (_path: string) => new Uint8Array([1, 2, 3])) + +vi.mock('@tauri-apps/plugin-fs', () => ({ + stat: (path: string) => statMock(path), + readFile: (path: string) => readFileMock(path), +})) + vi.mock('./input/UndoStatus', () => ({ UndoStatus: () => null, })) @@ -59,6 +128,8 @@ vi.mock('../../hooks', () => ({ vi.mock('../../store/messageStoreHooks', () => ({ useMessages: () => [], + useCurrentSessionId: () => null, + useSessionPromptHistory: () => [], })) vi.mock('../../store/keybindingStore', () => ({ @@ -71,6 +142,14 @@ vi.mock('../../store/keybindingStore', () => ({ describe('InputBox attachment handling', () => { beforeEach(() => { selectedFiles = [] + selectedPaths = [] + uploadAttachmentMock.mockReset() + uploadLocalFileMock.mockReset() + createUploadIdMock.mockClear() + notifyPushMock.mockReset() + getDroppedPathsInfoMock.mockClear() + statMock.mockClear() + readFileMock.mockClear() }) it('accepts files whose mime is inferred from the filename extension', async () => { @@ -90,4 +169,202 @@ describe('InputBox attachment handling', () => { expect(screen.getByTestId('attachment-count')).toHaveTextContent('1') }) }) + + // ========================================== + // Issue #182:白名单外的文件不再被静默丢弃 + // ========================================== + + it('白名单外文件上传到服务端并成为路径附件(模型无任何原生能力时也成立)', async () => { + uploadAttachmentMock.mockResolvedValue({ path: '/srv/tmp/uploads/u1/report.zip', size: 3 }) + selectedFiles = [new File([new Uint8Array([1, 2, 3])], 'report.zip', { type: 'application/zip' })] + + render() + + fireEvent.click(screen.getByRole('button', { name: 'attach file' })) + + await waitFor(() => { + expect(uploadAttachmentMock).toHaveBeenCalledTimes(1) + }) + + // 上传的是原始 File,文件名原样传递 + expect(uploadAttachmentMock.mock.calls[0][1]).toBe('report.zip') + + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent( + 'file:///srv/tmp/uploads/u1/report.zip|', + ) + }) + expect(notifyPushMock).not.toHaveBeenCalled() + }) + + it('上传失败时保留失败态并弹出可见错误(不静默吞掉)', async () => { + uploadAttachmentMock.mockRejectedValue(new Error('Failed to fetch')) + selectedFiles = [new File([new Uint8Array([1])], 'report.zip', { type: 'application/zip' })] + + render() + + fireEvent.click(screen.getByRole('button', { name: 'attach file' })) + + await waitFor(() => { + expect(notifyPushMock).toHaveBeenCalledTimes(1) + }) + + const [type, title, body] = notifyPushMock.mock.calls[0] as [string, string, string] + expect(type).toBe('error') + expect(title).toMatch(/report\.zip/) + expect(body).toMatch(/report\.zip/) + + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('|failed') + }) + }) + + it('失败后可重试:重试成功则替换为路径附件', async () => { + uploadAttachmentMock.mockRejectedValueOnce(new Error('Failed to fetch')) + uploadAttachmentMock.mockResolvedValueOnce({ path: '/srv/tmp/uploads/u2/report.zip', size: 1 }) + selectedFiles = [new File([new Uint8Array([1])], 'report.zip', { type: 'application/zip' })] + + render() + + fireEvent.click(screen.getByRole('button', { name: 'attach file' })) + + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('|failed') + }) + + fireEvent.click(screen.getByRole('button', { name: 'retry upload' })) + + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent( + 'file:///srv/tmp/uploads/u2/report.zip|', + ) + }) + expect(uploadAttachmentMock).toHaveBeenCalledTimes(2) + }) + + it('超过上传上限的文件直接拒绝并提示,不做上传', async () => { + // 构造一个「体积超过 MAX_UPLOAD_BYTES」的 File(不真正分配内存) + const big = new File([new Uint8Array([1])], 'huge.bin', { type: 'application/octet-stream' }) + Object.defineProperty(big, 'size', { value: 300 * 1024 * 1024 }) + selectedFiles = [big] + + render() + + fireEvent.click(screen.getByRole('button', { name: 'attach file' })) + + await waitFor(() => { + expect(notifyPushMock).toHaveBeenCalledTimes(1) + }) + expect(uploadAttachmentMock).not.toHaveBeenCalled() + expect(screen.getByTestId('attachment-count')).toHaveTextContent('0') + }) + + it('上传过程中把进度透传给胶囊(整个胶囊当进度条)', async () => { + const deferred: { release?: () => void } = {} + uploadAttachmentMock.mockImplementation(async (_payload, _name, _dir, _serverId, options) => { + ;(options as { onProgress?: (fraction: number) => void } | undefined)?.onProgress?.(0.5) + return await new Promise(resolve => { + deferred.release = () => resolve({ path: '/srv/tmp/uploads/u5/report.zip', size: 3 }) + }) + }) + selectedFiles = [new File([new Uint8Array([1, 2, 3])], 'report.zip', { type: 'application/zip' })] + + render() + fireEvent.click(screen.getByRole('button', { name: 'attach file' })) + + // 上传还没回来:胶囊应该带着 0.5 的进度 + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('|uploading|0.5') + }) + + deferred.release?.() + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('file:///srv/tmp/uploads/u5/report.zip|') + }) + }) + + // ========================================== + // 桌面端点回形针选文件(Issue #182):与拖入共用同一条判定链 + // ========================================== + + it('本机实例选文件 → @ 引用,不上传', async () => { + selectedPaths = ['C:/dl/piui-source.zip'] + + // 不传 serverId:缺省用活动服务器(测试环境下就是内置的 local,必然同机) + render() + + fireEvent.click(screen.getByRole('button', { name: 'pick paths' })) + + await waitFor(() => { + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + expect(textarea.value).toContain('@C:/dl/piui-source.zip') + }) + + // 项目外的文件用绝对路径做引用;整条链路不碰上传 + expect(uploadAttachmentMock).not.toHaveBeenCalled() + expect(screen.getByTestId('attachment-count')).toHaveTextContent('1') + }) + + it('选中的是模型支持的媒体(图片)→ 内联,不占用 @,也不上传', async () => { + selectedPaths = ['C:/pics/photo.png'] + + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'pick paths' })) + + // 原生媒体走内联(与拖入、与服务器在哪台机器无关) + await waitFor(() => { + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('data:image/png;base64') + }) + expect(readFileMock).toHaveBeenCalledWith('C:/pics/photo.png') + expect(uploadAttachmentMock).not.toHaveBeenCalled() + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).not.toContain('@') + }) + + it('模型不支持图片时选中图片 → 本机实例仍按 @ 引用处理', async () => { + selectedPaths = ['C:/pics/photo.png'] + + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'pick paths' })) + + await waitFor(() => { + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toContain('@C:/pics/photo.png') + }) + expect(uploadAttachmentMock).not.toHaveBeenCalled() + }) + + it('非本机实例选文件 → 上传(本机路径对远端服务端无意义)', async () => { + selectedPaths = ['C:/dl/piui-source.zip'] + uploadLocalFileMock.mockResolvedValue({ path: '/srv/tmp/uploads/u9/piui-source.zip', size: 3 }) + + const { serverStore } = await import('../../store/serverStore') + const remote = serverStore.addServer({ name: 'lan', url: 'http://192.168.1.20:4096' }) + + render() + + fireEvent.click(screen.getByRole('button', { name: 'pick paths' })) + + await waitFor(() => { + expect(uploadLocalFileMock).toHaveBeenCalledTimes(1) + }) + // 桌面端把**本机路径**交给 Rust 流式上传(不再先读进渲染进程) + expect(uploadLocalFileMock.mock.calls[0][0]).toBe('C:/dl/piui-source.zip') + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).not.toContain('@') + expect(screen.getByTestId('attachment-meta')).toHaveTextContent('file:///srv/tmp/uploads/u9/piui-source.zip') + }) }) diff --git a/src/features/chat/PaneHeader.tsx b/src/features/chat/PaneHeader.tsx index 8a7261a97..6f6c5a141 100644 --- a/src/features/chat/PaneHeader.tsx +++ b/src/features/chat/PaneHeader.tsx @@ -315,7 +315,11 @@ export function PaneHeader({ )}
    -
    + {/* 同 Header:纯色块 + mask 渐隐,避开 Tailwind v4 渐变类的 oklab 插值分层 */} +
    ) } diff --git a/src/features/chat/PermissionDialog.tsx b/src/features/chat/PermissionDialog.tsx index ac7d72a69..64472caf2 100644 --- a/src/features/chat/PermissionDialog.tsx +++ b/src/features/chat/PermissionDialog.tsx @@ -5,6 +5,7 @@ import { DiffView } from '../../components/DiffView' import { ContentBlock } from '../../components' import { childSessionStore, autoApproveStore } from '../../store' import { makeSessionKey, splitSessionKey } from '../../utils/sessionKey' +import { extractPermissionDiff } from './permissionDiff' import { usePresence } from '../../hooks' import { useChatViewport } from './chatViewport' @@ -32,24 +33,8 @@ export function PermissionDialog({ const { t } = useTranslation(['chat', 'common']) const { presentation } = useChatViewport() const isCompact = presentation.isCompact - // 从 metadata 中提取 diff 信息 - const metadata = request.metadata - const filepath = metadata?.filepath as string | undefined - let diffData = metadata?.diff as string | undefined - - // Extract structured filediff if available - let before: string | undefined - let after: string | undefined - - if (metadata?.filediff && typeof metadata.filediff === 'object') { - const fd = metadata.filediff as Record - // 上游优先返回 patch 格式 - if (typeof fd.patch === 'string') { - diffData = fd.patch - } - before = fd.before !== undefined ? String(fd.before) : undefined - after = fd.after !== undefined ? String(fd.after) : undefined - } + // 从 metadata 中提取 diff 信息(兼容 v1 diff/filediff 与 v2 files[].patch) + const { diff: diffData, before, after, filePath: filepath } = extractPermissionDiff(request.metadata) // 判断是否是文件编辑类权限 const isFileEdit = request.action === 'edit' || request.action === 'write' @@ -77,7 +62,7 @@ export function PermissionDialog({ return (
    )} -
    + {/* 分隔线两端留空,跟内容同宽(项目里面板头部的 inset-x-3 同款做法, + 这里头部是 px-4 所以留 16px) */} +
    {/* Content */}
    diff --git a/src/features/chat/QuestionDialog.tsx b/src/features/chat/QuestionDialog.tsx index 4c1b5b306..6317f43e3 100644 --- a/src/features/chat/QuestionDialog.tsx +++ b/src/features/chat/QuestionDialog.tsx @@ -73,7 +73,7 @@ export function QuestionDialog({ return (
    -
    + {/* 分隔线两端留空,跟内容同宽(项目里面板头部的 inset-x-3 同款做法, + 这里头部是 px-4 所以留 16px) */} +
    {/* 字段 */}
    diff --git a/src/features/chat/QueueBubbles.test.tsx b/src/features/chat/QueueBubbles.test.tsx index 61b928b7b..ac45a8970 100644 --- a/src/features/chat/QueueBubbles.test.tsx +++ b/src/features/chat/QueueBubbles.test.tsx @@ -1,6 +1,9 @@ -import { describe, it, expect, vi } from 'vitest' -import { render, screen, fireEvent } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { QueueBubbles } from './QueueBubbles' +import { setUiDisclosureState } from '../../utils/uiDisclosureState' +import { themeStore } from '../../store/themeStore' +import { FullscreenProvider } from '../../contexts/FullscreenContext' import type { QueuedUserPrompt } from '../../store/inboxStore' function makeItem(id: string, text: string): QueuedUserPrompt { @@ -12,14 +15,22 @@ function makeItem(id: string, text: string): QueuedUserPrompt { } as unknown as QueuedUserPrompt } +/** 内容用例共用的展开态 key(折叠状态是模块级缓存,显式归位避免用例间串扰) */ +const EXPANDED_KEY = 'queue-bubbles:test-expanded' + describe('QueueBubbles(下轮队列虚线气泡)', () => { + beforeEach(() => { + themeStore.setQueueAutoCollapse(true) + setUiDisclosureState(EXPANDED_KEY, true) + }) + it('renders nothing when the queue is empty', () => { const { container } = render() expect(container.querySelector('[data-message-queue]')).not.toBeInTheDocument() }) it('renders one dashed bubble per queued item with the group label', () => { - render() + render() expect(screen.getByText('排队这条')).toBeInTheDocument() expect(screen.getByText('再排一条')).toBeInTheDocument() expect(document.querySelectorAll('[data-message-queue="queued"]')).toHaveLength(1) @@ -29,7 +40,7 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { it('prefers metadata.displayText over payload.text(官方 queuedPromptText)', () => { const item = makeItem('q1', 'raw text') ;(item.payload as Record).metadata = { displayText: '展示文本' } - render() + render() expect(screen.getByText('展示文本')).toBeInTheDocument() expect(screen.queryByText('raw text')).not.toBeInTheDocument() }) @@ -39,7 +50,7 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { const onEdit = vi.fn() const onRemove = vi.fn() const item = makeItem('q1', '排队这条') - render() + render() fireEvent.click(screen.getByTitle('Inject into current turn')) expect(onSteer).toHaveBeenCalledWith(item) fireEvent.click(screen.getByTitle('Retract to edit')) @@ -47,4 +58,74 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { fireEvent.click(screen.getByTitle('Remove from queue')) expect(onRemove).toHaveBeenCalledWith(item) }) + + it('renders attachment chips for queued files/agents(和普通用户消息同款)', () => { + const item = makeItem('q1', '带附件') + ;(item.payload as Record).files = [ + { data: 'aGVsbG8=', mime: 'text/plain', source: { type: 'uri', uri: 'file:///workspace/notes.txt' }, name: 'notes.txt' }, + ] + ;(item.payload as Record).agents = [{ name: 'reviewer' }] + // AttachmentItem 的详情弹窗要 FullscreenProvider 上下文 + render( + + + , + ) + expect(screen.getByText('notes.txt')).toBeInTheDocument() + expect(screen.getByText('reviewer')).toBeInTheDocument() + }) + + it('collapses bubbles by default and toggles on header click(compact 同款)', async () => { + render() + + // 默认折叠:只有标题行,气泡不渲染 + expect(screen.queryByText('排队这条')).not.toBeInTheDocument() + const header = screen.getByRole('button', { name: 'Next turn (1)' }) + expect(header).toHaveAttribute('aria-expanded', 'false') + + // 点击标题展开 + fireEvent.click(header) + expect(screen.getByText('排队这条')).toBeInTheDocument() + expect(header).toHaveAttribute('aria-expanded', 'true') + + // 再点收起(卸载有延迟,等它结束) + fireEvent.click(header) + await waitFor(() => { + expect(screen.queryByText('排队这条')).not.toBeInTheDocument() + }) + }) + + it('collapses long queued text like normal user messages(CollapsibleUserText 同款折叠)', () => { + // jsdom 的 scrollHeight 恒 0、--fs-base 读不到,mock 出"超长溢出"的环境 + const scrollHeightSpy = vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(9999) + const originalGetComputedStyle = window.getComputedStyle + const computedStyleSpy = vi.spyOn(window, 'getComputedStyle').mockImplementation((el, pseudo) => { + const styles = originalGetComputedStyle(el, pseudo) + return { + ...styles, + getPropertyValue: (name: string) => (name === '--fs-base' ? '14' : styles.getPropertyValue(name)), + } as CSSStyleDeclaration + }) + try { + const longText = Array.from({ length: 30 }, (_, i) => `第 ${i + 1} 行`).join('\n') + render() + + // 折叠态:展开按钮出现,正文 maxHeight 被限制(预览 8 行) + const toggle = screen.getByRole('button', { name: 'Show more' }) + expect(toggle).toBeInTheDocument() + + // 点击展开 → 按钮变 Show less + fireEvent.click(toggle) + expect(screen.getByRole('button', { name: 'Show less' })).toBeInTheDocument() + } finally { + scrollHeightSpy.mockRestore() + computedStyleSpy.mockRestore() + } + }) + + it('expands by default when the collapse setting is off(默认展开开关)', () => { + themeStore.setQueueAutoCollapse(false) + render() + expect(screen.getByText('排队这条')).toBeInTheDocument() + }) }) diff --git a/src/features/chat/QueueBubbles.tsx b/src/features/chat/QueueBubbles.tsx index 203890da2..d29c530c4 100644 --- a/src/features/chat/QueueBubbles.tsx +++ b/src/features/chat/QueueBubbles.tsx @@ -17,10 +17,16 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' -import { ArrowUpIcon, CloseIcon, GripVerticalIcon, PencilIcon, TrashIcon } from '../../components/Icons' +import { ArrowUpIcon, ChevronDownIcon, CloseIcon, GripVerticalIcon, PencilIcon, TrashIcon } from '../../components/Icons' import { CopyButton } from '../../components/ui' import { queuedPromptText, type QueuedUserPrompt } from '../../store/inboxStore' import { projectQueueItems, type QueueMutation } from './queueProjection' +import { useDisclosureScrollLock } from '../../hooks' +import { useTheme } from '../../hooks/useTheme' +import { useUiDisclosureState } from '../../utils/uiDisclosureState' +import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../message/messageExpand' +import { AgentPartView, FilePartView } from '../message/parts/AttachmentPartViews' +import { CollapsibleUserText } from '../message/CollapsibleUserText' interface QueueBubblesProps { /** 下轮队列条目(delivery='queue',等当前回合结束后由服务端投递) */ @@ -37,10 +43,14 @@ interface QueueBubblesProps { editingId?: string /** 队列 mutation 投影(编辑/重排期间显示期望形态,官方 rows() 同款) */ mutation?: QueueMutation | null + /** 折叠状态的记忆 key(按会话区分;缺省全局共享一个) */ + stateKey?: string } +// 和用户消息 action bar 同款规格:28×28 盒子 + 默认 16px 图标(CopyButton 也是 h-7 w-7), +// 之前队列自己缩成 14px 图标,和 CopyButton 摆一排大小不一 const ACTION_BTN_CLASS = - 'p-1.5 rounded-md text-text-400 hover:text-text-200 hover:bg-bg-200/50 transition-colors' + 'inline-flex items-center justify-center h-7 w-7 rounded-md text-text-400 hover:text-text-200 transition-colors' /** 官方 PointerActivationConstraints.Distance({ value: 4 }) 同款:4px 内不算拖拽 */ const DRAG_THRESHOLD = 4 @@ -74,6 +84,7 @@ export const QueueBubbles = memo(function QueueBubbles({ onReorder, editingId, mutation, + stateKey, }: QueueBubblesProps) { const { t } = useTranslation('chat') const listRef = useRef(null) @@ -81,6 +92,13 @@ export const QueueBubbles = memo(function QueueBubbles({ const dragRef = useRef<{ id: string; startY: number; active: boolean } | null>(null) const [dragTarget, setDragTarget] = useState(null) + // 折叠(compact 同款):默认折叠/展开由设置项 queueAutoCollapse 决定, + // 用户手动展开/收起后按 key 记住(uiDisclosureState touched 语义) + const { queueAutoCollapse, collapseUserMessages } = useTheme() + const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? 'queue-bubbles', !queueAutoCollapse) + const shouldRenderBody = useMessageExpandRender(expanded) + const { withScrollLock } = useDisclosureScrollLock() + // mutation 投影(官方 rows() 同款):编辑/重排期间显示期望形态, // 服务端 admit/cancel 事件落地时不抖(数量/位置/文本都稳) const rows = useMemo(() => projectQueueItems(items, mutation ?? null), [items, mutation]) @@ -145,82 +163,114 @@ export const QueueBubbles = memo(function QueueBubbles({ const label = t('queue.queuedLabel', { count: rows.length }) return (
    -
    + {/* 标题行兼折叠开关(compact 同款 chevron):点击展开/收起队列气泡 */} +
    -
    - {rows.map(({ item }, index) => { - const text = queuedPromptText(item) - const isEditing = item.id === editingId - const showInsertion = dragTarget !== null && dragTarget === index && dragRef.current?.active - return ( -
    - {/* 插入指示线:拖拽指针越过该条目中线时显示在其上方 */} - {showInsertion &&
    ) }) diff --git a/src/features/chat/RetryStatusInline.test.tsx b/src/features/chat/RetryStatusInline.test.tsx index 6dff17c56..aaf6e73d9 100644 --- a/src/features/chat/RetryStatusInline.test.tsx +++ b/src/features/chat/RetryStatusInline.test.tsx @@ -19,11 +19,17 @@ function makeStatus(overrides: Partial = {}): RetryStatus describe('RetryStatusInline', () => { it('把 next 当成绝对时间戳,算出剩余倒计时', () => { - render() - - // 5s → formatRemaining 走 <10s 分支,显示 "5.0s" - expect(screen.getByText(/5\.\ds/)).toBeTruthy() - expect(screen.getByText(/2/)).toBeTruthy() + // 冻结时间:测试与组件各自 Date.now() 之间差 >50ms 就会少显示 0.1s(并行负载下必现的 flake) + vi.useFakeTimers() + try { + render() + + // 5s → formatRemaining 走 <10s 分支,显示 "5.0s" + expect(screen.getByText(/5\.\ds/)).toBeTruthy() + expect(screen.getByText(/2/)).toBeTruthy() + } finally { + vi.useRealTimers() + } }) it('next 已经过去时不显示倒计时', () => { diff --git a/src/features/chat/SessionMoveDialog.tsx b/src/features/chat/SessionMoveDialog.tsx new file mode 100644 index 000000000..ec255e81f --- /dev/null +++ b/src/features/chat/SessionMoveDialog.tsx @@ -0,0 +1,189 @@ +// ============================================ +// SessionMoveDialog — 把会话移动到其他目录 / worktree +// +// 对应官方 session/timeline/session-workspace-menu.tsx: +// - 目标列表 = 项目根(本地)+ 现有 worktree +// - 会话运行中禁止移动(blocked while running),由入口是否可点判定 +// - 成功后服务端发 session.moved,各列表据此增删 +// +// 入口在 Header 的会话标题菜单里;这里只负责弹窗本体。 +// ============================================ + +import { useCallback, useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { FolderIcon, GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' +import { Button, Dialog } from '../../components/ui' +import { getCurrentProject, moveSession } from '../../api/client' +import { listWorktreeEntries, createWorktree } from '../../api/worktree' +import { isSameDirectory, normalizeToForwardSlash, uiErrorHandler } from '../../utils' + +interface SessionMoveDialogProps { + isOpen: boolean + onClose: () => void + /** 会话 id(可为 scoped key) */ + sessionId: string + /** 会话当前所在目录 */ + directory: string +} + +interface MoveTarget { + directory: string + label: string + kind: 'local' | 'worktree' +} + +export function SessionMoveDialog({ isOpen, onClose, sessionId, directory }: SessionMoveDialogProps) { + const { t } = useTranslation(['chat', 'common']) + const [loading, setLoading] = useState(false) + /** 正在移入的目标目录(行内 spinner,同时禁用其它行) */ + const [movingTo, setMovingTo] = useState(null) + const [targets, setTargets] = useState([]) + const [projectID, setProjectID] = useState(null) + const [newName, setNewName] = useState('') + const [creating, setCreating] = useState(false) + + const loadTargets = useCallback(async () => { + setLoading(true) + try { + const project = await getCurrentProject(directory || undefined) + if (!project) { + setTargets([]) + setProjectID(null) + return + } + setProjectID(project.id) + const root = normalizeToForwardSlash(project.canonical) + const current = normalizeToForwardSlash(directory) + const entries = await listWorktreeEntries(project.id) + const list: MoveTarget[] = [] + // 本地(项目根):当前不在根时才列出(官方同款) + if (!isSameDirectory(root, current)) { + list.push({ directory: root, label: t('chat:sessionMove.local'), kind: 'local' }) + } + for (const entry of entries) { + const dir = normalizeToForwardSlash(entry.directory) + if (isSameDirectory(dir, current) || isSameDirectory(dir, root)) continue + list.push({ directory: dir, label: dir.split('/').filter(Boolean).pop() ?? dir, kind: 'worktree' }) + } + setTargets(list) + } catch { + setTargets([]) + setProjectID(null) + } finally { + setLoading(false) + } + }, [directory, t]) + + // 打开时拉一次目标列表;关闭时清掉残留的在途状态 + useEffect(() => { + if (!isOpen) { + setMovingTo(null) + setCreating(false) + setNewName('') + return + } + void loadTargets() + }, [isOpen, loadTargets]) + + const handleMove = async (destination: string) => { + if (movingTo) return + setMovingTo(destination) + try { + await moveSession(sessionId, destination) + onClose() + // 列表增删由 session.moved 事件驱动(useSessions) + } catch (e) { + uiErrorHandler('move session', e) + } finally { + setMovingTo(null) + } + } + + const handleCreateAndMove = async () => { + const name = newName.trim() + if (!name || !projectID || creating) return + setCreating(true) + try { + const wt = await createWorktree({ projectID, name }) + setNewName('') + await handleMove(normalizeToForwardSlash(wt.directory)) + } catch (e) { + uiErrorHandler('create worktree', e) + } finally { + setCreating(false) + } + } + + return ( + +
    + {/* 目标列表:项目根 + 现有 worktree */} +
    + {loading ? ( +
    + +
    + ) : targets.length === 0 ? ( +
    + {t('chat:sessionMove.empty')} +
    + ) : ( + targets.map(target => ( + + )) + )} +
    + + {/* 新建 worktree 并移入(官方菜单的 "create" 项) */} + {projectID && ( +
    +
    {t('chat:sessionMove.newWorktreeSection')}
    +
    + setNewName(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') { + e.preventDefault() + void handleCreateAndMove() + } + }} + placeholder={t('chat:sessionMove.newWorktreePlaceholder')} + disabled={creating || movingTo !== null} + className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-lg px-3 py-2 text-[length:var(--fs-base)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" + /> + +
    +
    + )} +
    +
    + ) +} diff --git a/src/features/chat/SessionMoveMenu.tsx b/src/features/chat/SessionMoveMenu.tsx deleted file mode 100644 index 371787d87..000000000 --- a/src/features/chat/SessionMoveMenu.tsx +++ /dev/null @@ -1,202 +0,0 @@ -// ============================================ -// SessionMoveMenu — 把会话移动到其他目录 / worktree -// -// 对应官方 session/timeline/session-workspace-menu.tsx: -// - 目标列表 = 项目根(本地)+ 新建 worktree + 现有 worktree -// - 会话运行中禁止移动(blocked while running) -// - 成功后服务端发 session.moved,各列表据此增删 -// ============================================ - -import { useCallback, useEffect, useRef, useState } from 'react' -import { useTranslation } from 'react-i18next' -import { GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' -import { getCurrentProject, moveSession } from '../../api/client' -import { listWorktreeEntries, createWorktree } from '../../api/worktree' -import { useSessionActiveEntry } from '../../store/activeSessionStore' -import { serverStore } from '../../store/serverStore' -import { makeSessionKey } from '../../utils/sessionKey' -import { isSameDirectory, normalizeToForwardSlash } from '../../utils' -import { uiErrorHandler } from '../../utils' - -interface SessionMoveMenuProps { - /** 会话 id(可为 scoped key) */ - sessionId: string - /** 会话当前所在目录 */ - directory: string -} - -interface MoveTarget { - directory: string - label: string - kind: 'local' | 'worktree' -} - -export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) { - const { t } = useTranslation(['chat', 'common']) - const [open, setOpen] = useState(false) - const [loading, setLoading] = useState(false) - const [moving, setMoving] = useState(false) - const [targets, setTargets] = useState([]) - const [projectID, setProjectID] = useState(null) - const [newName, setNewName] = useState('') - const [creating, setCreating] = useState(false) - const boxRef = useRef(null) - - // 官方 blocked():会话运行中禁止移动 - const activeKey = makeSessionKey(serverStore.getActiveServerId(), sessionId) - const activeEntry = useSessionActiveEntry(activeKey) - const running = activeEntry?.status.type === 'busy' || activeEntry?.status.type === 'retry' - - const loadTargets = useCallback(async () => { - setLoading(true) - try { - const project = await getCurrentProject(directory || undefined) - if (!project) { - setTargets([]) - setProjectID(null) - return - } - setProjectID(project.id) - const root = normalizeToForwardSlash(project.canonical) - const current = normalizeToForwardSlash(directory) - const entries = await listWorktreeEntries(project.id) - const list: MoveTarget[] = [] - // 本地(项目根):当前不在根时才列出(官方同款) - if (!isSameDirectory(root, current)) { - list.push({ directory: root, label: t('chat:sessionMove.local'), kind: 'local' }) - } - for (const entry of entries) { - const dir = normalizeToForwardSlash(entry.directory) - if (isSameDirectory(dir, current) || isSameDirectory(dir, root)) continue - list.push({ directory: dir, label: dir.split('/').filter(Boolean).pop() ?? dir, kind: 'worktree' }) - } - setTargets(list) - } catch { - setTargets([]) - setProjectID(null) - } finally { - setLoading(false) - } - }, [directory, t]) - - // 点击外部关闭 - useEffect(() => { - if (!open) return - const onPointerDown = (e: PointerEvent) => { - if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false) - } - document.addEventListener('pointerdown', onPointerDown) - return () => document.removeEventListener('pointerdown', onPointerDown) - }, [open]) - - const handleMove = async (destination: string) => { - if (moving) return - setMoving(true) - try { - await moveSession(sessionId, destination) - setOpen(false) - // 列表增删由 session.moved 事件驱动(useSessions) - } catch (e) { - uiErrorHandler('move session', e) - } finally { - setMoving(false) - } - } - - const handleCreateAndMove = async () => { - const name = newName.trim() - if (!name || !projectID || creating) return - setCreating(true) - try { - const wt = await createWorktree({ projectID, name }) - setNewName('') - await handleMove(normalizeToForwardSlash(wt.directory)) - } catch (e) { - uiErrorHandler('create worktree', e) - } finally { - setCreating(false) - } - } - - return ( -
    - - - {open && ( -
    e.stopPropagation()} - > -
    - {t('chat:sessionMove.title')} -
    -
    - {loading ? ( -
    - -
    - ) : targets.length === 0 ? ( -
    {t('chat:sessionMove.empty')}
    - ) : ( - targets.map(target => ( - - )) - )} -
    - {/* 新建 worktree 并移入(官方菜单的 "create" 项) */} - {projectID && ( -
    - setNewName(e.target.value)} - onKeyDown={e => { - if (e.key === 'Enter') { - e.preventDefault() - void handleCreateAndMove() - } - }} - placeholder={t('chat:sessionMove.newWorktreePlaceholder')} - disabled={creating || moving} - className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-md px-2 py-1 text-[length:var(--fs-xs)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" - /> - -
    - )} -
    - )} -
    - ) -} diff --git a/src/features/chat/WebsearchDock.test.tsx b/src/features/chat/WebsearchDock.test.tsx new file mode 100644 index 000000000..3bdec6d5a --- /dev/null +++ b/src/features/chat/WebsearchDock.test.tsx @@ -0,0 +1,206 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { WebsearchDock } from './WebsearchDock' +import type { ApiFormInfo } from '../../api' + +// ============================================ +// 网页搜索 dock(Issue #182 之外的 #? 无关,属于请求区) +// +// 它必须和权限/提问两个 dock 是同一套设计:同款卡片、同款收起(收起后由 +// FloatingActions 显示胶囊)、同款全宽动作行 + Enter/Esc。 +// 之前它自己是一层 absolute z-[9] 的浮层,比输入框还低 → 和输入框重合。 +// ============================================ + +vi.mock('./chatViewport', () => ({ + useChatViewport: () => ({ presentation: { surfaceVariant: 'desktop', isCompact: false } }), +})) + +// jsdom 没有 Web Animations API;其它输入框相关测试也是这么处理 usePresence 的 +vi.mock('../../hooks', () => ({ + usePresence: (show: boolean) => ({ shouldRender: show, ref: { current: null } }), +})) + +const getWebsearchProvidersMock = vi.fn(async () => [ + { value: 'exa', label: 'Exa' }, + { value: 'brave', label: 'Brave' }, +]) + +vi.mock('../../api/client', () => ({ + getWebsearchProviders: (...args: unknown[]) => getWebsearchProvidersMock(...(args as [])), +})) + +function form(overrides: Partial = {}): ApiFormInfo { + return { + id: 'form-1', + sessionID: 'session-1', + title: '第三方网页搜索', + metadata: { kind: 'websearch.provider' }, + fields: [], + ...overrides, + } as ApiFormInfo +} + +describe('WebsearchDock', () => { + beforeEach(() => { + getWebsearchProvidersMock.mockClear() + }) + + it('与权限/提问同款:卡片 + 收起按钮,点击收起交给上层', async () => { + const onCollapsedChange = vi.fn() + render() + + expect(screen.getByText('Third-party web search')).toBeTruthy() + // 搜索源列表加载完成(触发器上出现当前值) + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Search provider' })).toHaveTextContent('Any') + }) + // 打开菜单能看到列表 + fireEvent.click(screen.getByRole('button', { name: 'Search provider' })) + expect(screen.getByRole('menuitemradio', { name: /Exa/ })).toBeTruthy() + + // 收起按钮存在(title 与权限/提问同款「最小化」) + const minimize = screen.getByTitle('Minimize') + fireEvent.click(minimize) + expect(onCollapsedChange).toHaveBeenCalledWith(true) + }) + + it('collapsed 时不渲染卡片(收起态由 FloatingActions 的胶囊接管)', () => { + const { container } = render() + expect(container.querySelector('[data-component="session-websearch-dock"]')).toBeNull() + }) + + it('搜索源用项目统一的 DropdownMenu + MenuItem(不是原生 select)', async () => { + const { container } = render() + + // 不允许出现原生下拉 + expect(container.querySelector('select')).toBeNull() + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Search provider' })).toBeTruthy() + }) + fireEvent.click(screen.getByRole('button', { name: 'Search provider' })) + + // 菜单是 role=menu + menuitemradio(与输入框 Build/High 同款) + expect(screen.getByRole('menu')).toBeTruthy() + expect(screen.getByRole('menuitemradio', { name: /Exa/ })).toBeTruthy() + expect(screen.getByRole('menuitemradio', { name: /Brave/ })).toBeTruthy() + }) + + it('头部下方的分隔线两端留空(与项目面板 inset-x-3 同款做法)', async () => { + const { container } = render() + + const divider = container.querySelector('.h-px') + expect(divider).toBeTruthy() + // 留空宽度 = 头部内容的 padding(px-4 → mx-4),不能整条填满 + expect(divider?.className).toContain('mx-4') + expect(divider?.className).not.toContain('border-t') + }) + + it('展开时箭头翻转(ComposerSeatMenu / ModelSelector 同款细节)', async () => { + render() + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Search provider' })).toBeTruthy() + }) + + const chevron = screen.getByTestId('websearch-provider-chevron') + expect(chevron.className).not.toContain('rotate-180') + + fireEvent.click(screen.getByRole('button', { name: 'Search provider' })) + expect(screen.getByTestId('websearch-provider-chevron').className).toContain('rotate-180') + + // 关闭后转回来 + fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' }) + await waitFor(() => { + expect(screen.getByTestId('websearch-provider-chevron').className).not.toContain('rotate-180') + }) + }) + + it('选「任意」启用 → 回 {choice: allow}', async () => { + const onReply = vi.fn(async () => true) + render() + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Search provider' })).toBeTruthy() + }) + fireEvent.click(screen.getByRole('button', { name: /Enable/ })) + + await waitFor(() => { + expect(onReply).toHaveBeenCalledWith(expect.anything(), { choice: 'allow' }) + }) + }) + + it('选「不使用搜索」→ 回 {choice: disable}', async () => { + const onReply = vi.fn(async () => true) + render() + + fireEvent.click(screen.getByRole('button', { name: /use search/ })) + + await waitFor(() => { + expect(onReply).toHaveBeenCalledWith(expect.anything(), { choice: 'disable' }) + }) + }) + + it('选具体搜索源 → 两段式:先 {choice: choose}', async () => { + const onReply = vi.fn(async () => true) + render() + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Search provider' })).toBeTruthy() + }) + // 项目统一的选择器:触发器 → DropdownMenu → MenuItem + fireEvent.click(screen.getByRole('button', { name: 'Search provider' })) + fireEvent.click(screen.getByRole('menuitemradio', { name: /Exa/ })) + fireEvent.click(screen.getByRole('button', { name: /Enable/ })) + + await waitFor(() => { + expect(onReply).toHaveBeenCalledWith(expect.anything(), { choice: 'choose' }) + }) + }) + + it('specific 表单(带 provider 字段)→ 直接回 {provider}', async () => { + const onReply = vi.fn(async () => true) + const specific = form({ + fields: [ + { + type: 'string', + key: 'provider', + options: [{ value: 'brave', label: 'Brave' }], + }, + ], + } as Partial) + + render() + + fireEvent.click(screen.getByRole('button', { name: /Enable/ })) + + await waitFor(() => { + expect(onReply).toHaveBeenCalledWith(expect.anything(), { provider: 'brave' }) + }) + // specific 形态没有「不使用搜索」(官方同款) + expect(screen.queryByRole('button', { name: /use search/ })).toBeNull() + }) + + it('Escape = 不使用搜索(与权限/提问的 Esc 行为一致)', async () => { + const onReply = vi.fn(async () => true) + const { container } = render() + + const root = container.firstElementChild as HTMLElement + fireEvent.keyDown(root, { key: 'Escape' }) + + await waitFor(() => { + expect(onReply).toHaveBeenCalledWith(expect.anything(), { choice: 'disable' }) + }) + }) + + it('回复失败时在卡片里可见提示(不静默)', async () => { + const onReply = vi.fn(async () => false) + render() + + fireEvent.click(screen.getByRole('button', { name: /use search/ })) + + await waitFor(() => { + expect(screen.getByText(/Could not save your choice/)).toBeTruthy() + }) + }) +}) diff --git a/src/features/chat/WebsearchDock.tsx b/src/features/chat/WebsearchDock.tsx index 589163708..79baa79cf 100644 --- a/src/features/chat/WebsearchDock.tsx +++ b/src/features/chat/WebsearchDock.tsx @@ -12,10 +12,14 @@ // - specific(带 provider string 字段 + options):直接回 {provider: 选中值}。 // ============================================ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' -import { SpinnerIcon } from '../../components/Icons' +import { ReturnIcon, SearchIcon, ChevronDownIcon, SpinnerIcon } from '../../components/Icons' +import { DropdownMenu, MenuItem } from '../../components/ui' import { getWebsearchProviders } from '../../api/client' +import { usePresence } from '../../hooks' +import { useChatViewport } from './chatViewport' +import { keybindingStore, matchesKeybinding } from '../../store/keybindingStore' import type { ApiFormInfo, FormAnswer } from '../../api' import type { FormStringField } from '@opencode/client/promise' @@ -24,6 +28,9 @@ interface WebsearchDockProps { /** 会话所在目录(providers 按 location 拉取) */ directory?: string onReply: (form: ApiFormInfo, answer: FormAnswer) => Promise + isReplying?: boolean + collapsed?: boolean + onCollapsedChange?: (collapsed: boolean) => void } /** 官方 webSearchProviderField:specific 表单判定 */ @@ -33,6 +40,9 @@ function providerField(form: ApiFormInfo): FormStringField | undefined { ) } +/** 搜索源菜单 id(触发器 aria-controls 指向它) */ +const PROVIDER_MENU_ID = 'websearch-provider-menu' + /** * 两段式链路的跨挂载状态(sessionID → 选中的 provider)。 * @@ -42,8 +52,17 @@ function providerField(form: ApiFormInfo): FormStringField | undefined { */ const pendingChooseProvider = new Map() -export function WebsearchDock({ form, directory, onReply }: WebsearchDockProps) { +export function WebsearchDock({ + form, + directory, + onReply, + isReplying = false, + collapsed = false, + onCollapsedChange, +}: WebsearchDockProps) { const { t } = useTranslation(['chat', 'common']) + const { presentation } = useChatViewport() + const isCompact = presentation.isCompact const specific = useMemo(() => providerField(form), [form]) const [selected, setSelected] = useState('random') const [options, setOptions] = useState<{ value: string; label: string }[]>([]) @@ -52,6 +71,43 @@ export function WebsearchDock({ form, directory, onReply }: WebsearchDockProps) const [sending, setSending] = useState(false) const [failed, setFailed] = useState(false) + // 搜索源选择用项目统一的 DropdownMenu + MenuItem(与输入框的 Build/High 同款), + // 不用原生 setSelected(e.target.value)} - disabled={sending || unavailable} - className="shrink-0 bg-bg-000 border border-border-200 rounded-md px-2 py-1.5 text-[length:var(--fs-sm)] text-text-100 focus:outline-none focus:border-accent-main-100/50 disabled:opacity-50 max-w-[180px]" +
    +
    +
    - {allOptions.map(option => ( - - ))} - -
    +
    + {/* Header —— 与权限/提问同款:图标 + 标题 + 收起 */} +
    +
    +
    + +
    +

    + {t('chat:websearch.title')} +

    +
    + +
    + + {/* 分隔线两端留空,跟内容同宽(项目里面板头部的 inset-x-3 同款做法, + 这里头部是 px-4 所以留 16px) */} +
    -
    -
    - {loading && ( - - - {t('common:loading')} - - )} - {!loading && failed && {t('chat:websearch.failed')}} - {!loading && !failed && loadFailed && ( - - {t('chat:websearch.loadFailed')} - + + + + +
    +
    + +
    + {loading && ( + + + {t('common:loading')} + + )} + {!loading && failed && {t('chat:websearch.failed')}} + {!loading && !failed && loadFailed && ( + + {t('chat:websearch.loadFailed')} + + + )} + {!loading && !failed && !loadFailed && options.length === 0 && ( + {t('chat:websearch.empty')} + )} +
    +
    + + {/* Actions —— 与权限/提问同款的全宽行按钮 */} +
    + - - )} - {!loading && !failed && !loadFailed && options.length === 0 && {t('chat:websearch.empty')}} -
    -
    - {!specific && ( - - )} - + + {!specific && ( + + )} +
    +
    - +
    ) } diff --git a/src/features/chat/backgroundTasks.ts b/src/features/chat/backgroundTasks.ts index 188d9c6dd..1a3a96394 100644 --- a/src/features/chat/backgroundTasks.ts +++ b/src/features/chat/backgroundTasks.ts @@ -77,17 +77,17 @@ export function mergeRunningShells( * 「移到后台」候选需要并入服务端 running shells——比如模型上一轮启动、 * 事件流尚未物化进消息工具态的 shell。 */ -export function useRunningShells(sessionId: string | null, active: boolean, serverId?: string): ShellInfo[] { +export function useRunningShells(sessionId: string | null, active: boolean, directory?: string, serverId?: string): ShellInfo[] { const [shells, setShells] = useState([]) useEffect(() => { - if (!sessionId || !active) { + if (!sessionId || !active || !directory) { setShells([]) return } let cancelled = false const load = async () => { try { - const list = await listShells(serverId) + const list = await listShells(directory, serverId) if (!cancelled) setShells(list) } catch { // 失败不影响主流程,下一轮再试 @@ -99,6 +99,6 @@ export function useRunningShells(sessionId: string | null, active: boolean, serv cancelled = true clearInterval(timer) } - }, [sessionId, active, serverId]) + }, [sessionId, active, directory, serverId]) return shells } diff --git a/src/features/chat/chatAreaVisibility.ts b/src/features/chat/chatAreaVisibility.ts index 33d2f8a6e..337308138 100644 --- a/src/features/chat/chatAreaVisibility.ts +++ b/src/features/chat/chatAreaVisibility.ts @@ -3,6 +3,7 @@ import { contentEntries, hasVisibleText, isAssistantMessage, + isFailedIdleMessage, isUserMessage, userMessageText, } from '../../types/api/message' @@ -59,6 +60,9 @@ function messageHasContent(message: SessionMessageInfo): boolean { if (isAssistantMessage(message) && message.error) { return isInterruptedError(message.error) ? hasRenderable : true } + // 失败 idle 标记(会话级错误,如 pre-promotion failure)始终可见: + // 它没有 assistant 消息,错误卡片就是它唯一的内容(官方 isFailedIdle → Error 卡片) + if (isFailedIdleMessage(message)) return true if (!hasAnyContent(message)) { // 任何角色的空消息都不可见:没有内容可展示 // 内容到达后自动进入可见列表;abort 后永远不会有内容 → 永远不可见 diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index cfb185c97..d99dcef25 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -1,5 +1,6 @@ import type { AssistantMessage, SessionMessageInfo, ToolState, UserMessage } from '../../types/api/message' -import { contentEntries, isAssistantMessage, isUserMessage, userMessageText } from '../../types/api/message' +import { contentEntries, isAssistantMessage, isFailedIdleMessage, isUserMessage, userMessageText } from '../../types/api/message' +import { isInterruptedError } from '../../utils/errorMessage' export const PAGE_MESSAGE_COUNT = 20 export const PAGE_EXTREME_RENDER_WEIGHT = 700 @@ -900,6 +901,11 @@ export function buildProcessTimeline( assistants: AssistantMessage[] /** 独立成行的消息(shell 命令等):不进任何回合壳,按原位平铺 */ standalone?: SessionMessageInfo + /** + * 会话级失败的 idle 标记(pre-promotion failure 等,官方 isFailedIdle)。 + * 不结束回合分组(重试的后续 assistant 仍归本回合),回合转换时追加成错误卡片。 + */ + failedIdle?: SessionMessageInfo } const turns: TurnBag[] = [] @@ -921,6 +927,13 @@ export function buildProcessTimeline( turns.push({ user: null, assistants: [], standalone: message }) continue } + // 失败的 idle 标记:会话级错误(如 prompt 没能提升成 assistant 工作)只在这条 + // 标记里,跳过它错误就永远不渲染。记到当前回合(没有就独立平铺),转换时追加。 + if (isFailedIdleMessage(message)) { + if (current) current.failedIdle = message + else items.push({ kind: 'message', key: message.id, message }) + continue + } if (!isAssistantMessage(message)) continue if (!current) { // 历史续段 / 页首无 user:直接平铺,不挂壳 @@ -958,9 +971,12 @@ export function buildProcessTimeline( // 空回合:idle 结束;或后面已有 assistant(被跳过) return !sessionIsStreaming || laterHasAssistant(index) } - // 全 completed 且无 live → 锁定 Worked。 - // 不要再用 sessionIsStreaming 重开:发送时 busy 常早于新 user 入列,会闪一下。 - // 工具循环间隙若下一助手还没到,会短暂 Worked;下一助手 live 后自然回到 Working。 + // 全 completed 但会话还 busy(服务端 session.status busy/retry)且这是最后一个用户回合: + // 只是同一回合「上一步已收尾、下一步还没到」的间隙(多步 agent 的常态), + // 不能判成 Worked —— 否则壳会先收起、等下一步内容到了再展开。 + // 等 idle 把 busy 摘掉,或下一轮 user 接手(index 不再是最后一个)才收。 + if (sessionIsStreaming && index === userTurns.length - 1) return false + // 确实收工(busy 已清 / 后面已有新一轮) return assistants.every(m => m.time.completed != null) } @@ -979,6 +995,16 @@ export function buildProcessTimeline( } } + // 回合末尾追加失败 idle 的错误卡片;错误已在末尾 assistant 上显示过就不重复 + // (官方 session-ui projection.ts:276 的同款去重:assistant.error 已渲染则跳过 idle 卡) + const appendFailedIdle = (turn: TurnBag) => { + const failedIdle = turn.failedIdle + if (!failedIdle) return + const last = turn.assistants.at(-1) + if (last?.error && !isInterruptedError(last.error)) return + items.push({ kind: 'message', key: failedIdle.id, message: failedIdle }) + } + for (const turn of turns) { if (turn.standalone) { items.push({ kind: 'message', key: turn.standalone.id, message: turn.standalone }) @@ -989,13 +1015,17 @@ export function buildProcessTimeline( } const assistants = turn.assistants - if (!turn.user && assistants.length === 0) continue + if (!turn.user && assistants.length === 0) { + appendFailedIdle(turn) + continue + } // 无 user 的续段:平铺 if (!turn.user) { for (const m of assistants) { items.push({ kind: 'message', key: m.id, message: m }) } + appendFailedIdle(turn) continue } @@ -1055,6 +1085,8 @@ export function buildProcessTimeline( items.push({ kind: 'message', key: m.id, message: m }) } } + + appendFailedIdle(turn) } return items diff --git a/src/features/chat/input/InputActions.tsx b/src/features/chat/input/InputActions.tsx index a9200228e..8baa8e994 100644 --- a/src/features/chat/input/InputActions.tsx +++ b/src/features/chat/input/InputActions.tsx @@ -1,6 +1,6 @@ import { memo, type ReactNode } from 'react' import { useTranslation } from 'react-i18next' -import { ArrowDownIcon, ArrowUpIcon, PermissionListIcon, QuestionIcon } from '../../../components/Icons' +import { ArrowDownIcon, ArrowUpIcon, PermissionListIcon, QuestionIcon, SearchIcon } from '../../../components/Icons' import { UndoStatus } from './UndoStatus' import { usePresence } from '../../../hooks' import type { CollapsedDialogInfo } from '../InputBox' @@ -60,6 +60,7 @@ interface FloatingActionsProps { onScrollToBottom?: () => void collapsedPermission?: CollapsedDialogInfo collapsedQuestion?: CollapsedDialogInfo + collapsedWebsearch?: CollapsedDialogInfo } export const FloatingActions = memo(function FloatingActions({ @@ -72,6 +73,7 @@ export const FloatingActions = memo(function FloatingActions({ onScrollToBottom, collapsedPermission, collapsedQuestion, + collapsedWebsearch, }: FloatingActionsProps) { return (
    @@ -109,6 +111,23 @@ export const FloatingActions = memo(function FloatingActions({ )} + {/* Collapsed Websearch Capsule(与权限/提问同款收起态) */} + + {collapsedWebsearch && ( + + )} + + {canRedo && } diff --git a/src/features/chat/input/InputToolbar.test.tsx b/src/features/chat/input/InputToolbar.test.tsx index 1b988bafe..ed5541f64 100644 --- a/src/features/chat/input/InputToolbar.test.tsx +++ b/src/features/chat/input/InputToolbar.test.tsx @@ -101,6 +101,26 @@ describe('InputToolbar file selection', () => { readFileMock.mockReset() }) + it('always offers the attach control and does not filter the file input by accept', () => { + // Issue #182:白名单外的文件会走服务端上传,所以附件入口不再受模型能力控制, + // 文件选择器也不能按 accept 过滤,否则用户根本选不到 zip/docx。 + const { container } = render( + , + ) + + expect(screen.getByRole('button', { name: 'Attach file' })).toBeTruthy() + + const input = container.querySelector('input[type="file"]') as HTMLInputElement + expect(input).toBeTruthy() + expect(input.hasAttribute('accept')).toBe(false) + }) + it('uses the browser file input on Tauri mobile', () => { useIsMobileMock.mockReturnValue(true) isTauriMock.mockReturnValue(true) @@ -162,6 +182,35 @@ describe('InputToolbar file selection', () => { expect(files[0].type).toBe('image/png') }) + it('hands native paths to onPickedPaths instead of reading bytes', async () => { + isTauriMock.mockReturnValue(true) + isTauriMobileMock.mockReturnValue(false) + openMock.mockResolvedValue(['C:\\dl\\piui-source.zip', 'C:\\dl\\notes.txt']) + + // Issue #182:桌面端选择器与拖入共用一条判定链(本机 → @ 引用 / 远端 → 上传), + // 所以要把路径原样交上去;读字节拼 File 会丢掉路径 + const onPickedPaths = vi.fn() + const onFilesSelected = vi.fn() + + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Attach file' })) + + await waitFor(() => { + expect(onPickedPaths).toHaveBeenCalledWith(['C:\\dl\\piui-source.zip', 'C:\\dl\\notes.txt']) + }) + expect(readFileMock).not.toHaveBeenCalled() + expect(onFilesSelected).not.toHaveBeenCalled() + }) + it('moves focus into the opened agent menu and exposes menu semantics', async () => { render( { await waitFor(() => { expect(trigger).toHaveAttribute('aria-expanded', 'false') - expect(screen.getByRole('button', { name: 'Send message' })).toHaveFocus() + // 下一个可聚焦控件是附件按钮(它现在恒常渲染,Issue #182) + expect(screen.getByRole('button', { name: 'Attach file' })).toHaveFocus() }) }) diff --git a/src/features/chat/input/InputToolbar.tsx b/src/features/chat/input/InputToolbar.tsx index f734812a1..f465daf3c 100644 --- a/src/features/chat/input/InputToolbar.tsx +++ b/src/features/chat/input/InputToolbar.tsx @@ -20,8 +20,16 @@ interface InputToolbarProps { selectedVariant?: string onVariantChange?: (variant: string | undefined) => void + /** @deprecated 选择器不再按能力过滤(Issue #182);内联判定在 InputBox 里做 */ fileCapabilities?: FileCapabilities onFilesSelected: (files: File[]) => void + /** + * 桌面端原生选择器选中的**本机路径**。 + * + * 与拖入共用一条判定链(本机实例 → `@` 引用,远端 → 上传)。浏览器里拿不到 + * `File` 的真实路径,所以只有 Tauri 下会走这里;给了它就不再读字节拼 `File`。 + */ + onPickedPaths?: (paths: string[]) => void isStreaming?: boolean isSending?: boolean @@ -53,8 +61,8 @@ export function InputToolbar({ variants = [], selectedVariant, onVariantChange, - fileCapabilities, onFilesSelected, + onPickedPaths, isStreaming, isSending = false, onAbort, @@ -78,43 +86,10 @@ export function InputToolbar({ const useSeatSelector = composerSelectorStyle === 'seat' const useBrowserFileInput = !isTauri() || isTauriMobile() - // 根据模型能力计算支持的文件类型 - const caps = fileCapabilities ?? { image: false, pdf: false, audio: false, video: false } - const supportsAnyFile = caps.image || caps.pdf || caps.audio || caps.video + // 附件选择不再按模型能力过滤(Issue #182):白名单外的文件会走服务端上传, + // 因此文件选择器必须能看到任意文件类型。`fileCapabilities` 仍由上层用于内联判定。 const controlsDisabled = isSending - // 动态构建 HTML accept 和 Tauri filter - const { acceptString, tauriFilters } = useMemo(() => { - const accept: string[] = [] - const extensions: string[] = [] - const filterNames: string[] = [] - - if (caps.image) { - accept.push('image/*') - extensions.push('png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg') - filterNames.push('Images') - } - if (caps.pdf) { - accept.push('application/pdf') - extensions.push('pdf') - filterNames.push('PDF') - } - if (caps.audio) { - accept.push('audio/*') - extensions.push('mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a') - filterNames.push('Audio') - } - if (caps.video) { - accept.push('video/*') - extensions.push('mp4', 'webm', 'mov', 'avi', 'mkv') - filterNames.push('Video') - } - - return { - acceptString: accept.join(','), - tauriFilters: extensions.length > 0 ? [{ name: filterNames.join(' / '), extensions }] : [], - } - }, [caps.image, caps.pdf, caps.audio, caps.video]) // State for menus const [agentMenuOpen, setAgentMenuOpen] = useState(false) const [variantMenuOpen, setVariantMenuOpen] = useState(false) @@ -238,14 +213,10 @@ export function InputToolbar({ } try { - const [{ open }, { readFile }] = await Promise.all([ - import('@tauri-apps/plugin-dialog'), - import('@tauri-apps/plugin-fs'), - ]) + const { open } = await import('@tauri-apps/plugin-dialog') const selected = await open({ multiple: true, - filters: tauriFilters, fileAccessMode: 'copy', }) @@ -254,6 +225,14 @@ export function InputToolbar({ const paths = Array.isArray(selected) ? selected : [selected] if (paths.length === 0) return + // 有原生路径就交给上层,与拖入共用同一条判定(本机 → @ 引用 / 远端 → 上传); + // 读字节拼 File 会丢掉路径,那条只作为没有上层的兜底 + if (onPickedPaths) { + onPickedPaths(paths) + return + } + + const { readFile } = await import('@tauri-apps/plugin-fs') const files: File[] = [] for (const path of paths) { const fileName = path.split(/[\\/]/).pop() || 'file' @@ -271,7 +250,7 @@ export function InputToolbar({ } catch (err) { console.warn('[InputToolbar] File picker error:', err) } - }, [onFilesSelected, tauriFilters, useBrowserFileInput]) + }, [onFilesSelected, onPickedPaths, useBrowserFileInput]) // Click outside logic useEffect(() => { @@ -570,14 +549,13 @@ export function InputToolbar({ {busyDelivery === 'steer' ? t('inputToolbar.steer') : t('inputToolbar.followUp')} - + <> - {/* 浏览器模式下的隐藏文件输入 */} + {/* 浏览器模式下的隐藏文件输入(不设 accept:任意文件都可上传,Issue #182) */} {useBrowserFileInput && ( { diff --git a/src/features/chat/input/attachmentUpload.test.ts b/src/features/chat/input/attachmentUpload.test.ts new file mode 100644 index 000000000..6e5f66198 --- /dev/null +++ b/src/features/chat/input/attachmentUpload.test.ts @@ -0,0 +1,258 @@ +import { describe, expect, it, vi } from 'vitest' +import { buildPathAttachment, canReferenceLocalPath, decideNativeFileRoute, splitDroppedItems } from './attachmentUpload' + +// ============================================ +// 桌面端拖入的本机文件该走哪条路(需求二) +// +// 服务端与客户端同机时**不上传**:原生媒体内联,其余沿用原有的 @ 引用 +// (服务端自己读得到那个路径)。服务端在远端时只能上传。 +// ============================================ + +const allCaps = { image: true, pdf: true, audio: true, video: true } +const noCaps = { image: false, pdf: false, audio: false, video: false } +const MB = 1024 * 1024 + +describe('decideNativeFileRoute', () => { + it('同机 + 原生媒体 → 内联(读本机字节,不上传)', () => { + expect( + decideNativeFileRoute({ + mime: 'image/png', + size: 1024, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/pics/a.png', + }), + ).toEqual({ kind: 'inline' }) + }) + + it('同机 + 白名单外(zip)→ 走原有的 @ 引用,不上传', () => { + expect( + decideNativeFileRoute({ + mime: 'application/zip', + size: 1024, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/dl/piui-source.zip', + }), + ).toEqual({ kind: 'mention' }) + }) + + it('同机 + 原生媒体但超过内联上限 → 也是 @ 引用(不上传)', () => { + expect( + decideNativeFileRoute({ + mime: 'image/png', + size: 21 * MB, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/pics/huge.png', + }), + ).toEqual({ kind: 'mention' }) + }) + + it('同机 + 超大文件也不拒绝(根本不上传,没有上限问题)', () => { + expect( + decideNativeFileRoute({ + mime: 'application/zip', + size: 500 * MB, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/dl/huge.zip', + }), + ).toEqual({ kind: 'mention' }) + }) + + it('远端 + 白名单外 → 上传', () => { + expect( + decideNativeFileRoute({ + mime: 'application/zip', + size: 1024, + caps: allCaps, + serverIsLocal: false, + nativePath: 'C:/dl/piui-source.zip', + }), + ).toEqual({ kind: 'upload', pathOnly: false }) + }) + + it('远端 + 超过 20MB → 上传但只作路径引用', () => { + expect( + decideNativeFileRoute({ + mime: 'application/zip', + size: 21 * MB, + caps: allCaps, + serverIsLocal: false, + nativePath: 'C:/dl/big.zip', + }), + ).toEqual({ kind: 'upload', pathOnly: true }) + }) + + it('远端 + 超过上传上限 → 拒绝', () => { + expect( + decideNativeFileRoute({ + mime: 'application/zip', + size: 300 * MB, + caps: allCaps, + serverIsLocal: false, + nativePath: 'C:/dl/huge.zip', + }), + ).toEqual({ kind: 'reject' }) + }) + + it('远端 + 模型没有原生能力 + 图片 → 上传(不丢弃)', () => { + expect( + decideNativeFileRoute({ + mime: 'image/png', + size: 1024, + caps: noCaps, + serverIsLocal: false, + nativePath: 'C:/pics/a.png', + }), + ).toEqual({ kind: 'upload', pathOnly: false }) + }) +}) + +describe('buildPathAttachment', () => { + it('用 file:// 引用服务端路径,原始文件名用于展示', () => { + expect( + buildPathAttachment({ + id: 'a1', + path: 'C:/Users/x/AppData/Local/Temp/opencode/uploads/u1/report.zip', + filename: 'report.zip', + mime: 'application/zip', + size: 262, + pathOnly: false, + }), + ).toEqual({ + id: 'a1', + type: 'file', + displayName: 'report.zip', + url: 'file:///C:/Users/x/AppData/Local/Temp/opencode/uploads/u1/report.zip', + mime: 'application/zip', + relativePath: 'C:/Users/x/AppData/Local/Temp/opencode/uploads/u1/report.zip', + size: 262, + }) + }) + + it('pathOnly 时标记出来(不进 prompt.files[])', () => { + const attachment = buildPathAttachment({ + id: 'a2', + path: '/tmp/uploads/u1/big.bin', + filename: 'big.bin', + mime: 'application/octet-stream', + size: 21 * MB, + pathOnly: true, + }) + expect(attachment.pathOnly).toBe(true) + expect(attachment.url).toBe('file:///tmp/uploads/u1/big.bin') + }) +}) + +// ============================================ +// 能否直接引用本机路径(「是不是本地」的最终判据) +// +// URL 判本地不够:本机也能用局域网地址连自己;容器也会把端口映射到回环。 +// 所以除了应用自己拉起的服务(必然同机,免探测),一律问服务端读不读得到。 +// ============================================ + +describe('canReferenceLocalPath', () => { + it('应用自己拉起的服务(local)必然同机:免探测直接可用', async () => { + const probe = vi.fn(async () => false) + + await expect( + canReferenceLocalPath({ path: 'C:/x/a.zip', pinnedLocal: true, probe }), + ).resolves.toBe(true) + expect(probe).not.toHaveBeenCalled() + }) + + it('本机但用局域网地址连自己:探测通过 → 可直接引用(不上传)', async () => { + const probe = vi.fn(async () => true) + + await expect( + canReferenceLocalPath({ path: 'C:/x/a.zip', pinnedLocal: false, serverId: 'lan', probe }), + ).resolves.toBe(true) + expect(probe).toHaveBeenCalledWith('C:/x/a.zip', undefined, 'lan') + }) + + it('容器/远端读不到宿主路径:探测失败 → 必须上传', async () => { + const probe = vi.fn(async () => false) + await expect(canReferenceLocalPath({ path: 'C:/x/a.zip', pinnedLocal: false, probe })).resolves.toBe(false) + }) + + it('探测本身抛错(服务端不可达):按读不到处理,不抛出去', async () => { + const probe = vi.fn(async () => { + throw new Error('Failed to fetch') + }) + await expect(canReferenceLocalPath({ path: 'C:/x/a.zip', pinnedLocal: false, probe })).resolves.toBe(false) + }) +}) + +// ============================================ +// 网页版拖入:文件夹必须在上传前被认出来 +// +// 浏览器把拖入的文件夹也塞进 dataTransfer.files,表现为 size 0、type 空的 File。 +// 直接上传会得到一个空附件,请求还会被安全策略挡掉(net::ERR_ACCESS_DENIED), +// 所以分流只能靠 webkitGetAsEntry().isDirectory。 +// ============================================ + +describe('splitDroppedItems', () => { + const file = (name: string) => new File(['x'], name, { type: 'text/plain' }) + const fileItem = (f: File | null) => ({ kind: 'file', webkitGetAsEntry: () => null, getAsFile: () => f }) + const folderItem = (name: string) => ({ + kind: 'file', + webkitGetAsEntry: () => ({ isDirectory: true, name }), + getAsFile: () => null, + }) + + it('文件夹被单独挑出来,不进 files(否则会传上空附件)', () => { + const result = splitDroppedItems([fileItem(file('a.txt')), folderItem('新建文件夹')]) + + expect(result.folderNames).toEqual(['新建文件夹']) + expect(result.files.map(f => f.name)).toEqual(['a.txt']) + }) + + it('混着拖:真文件照常收下', () => { + const result = splitDroppedItems([folderItem('dir'), fileItem(file('a.txt')), fileItem(file('b.zip'))]) + + expect(result.folderNames).toEqual(['dir']) + expect(result.files.map(f => f.name)).toEqual(['a.txt', 'b.zip']) + }) + + it('空文件是合法文件,不能被当成文件夹漏掉', () => { + const empty = new File([], 'empty.txt', { type: 'text/plain' }) + const result = splitDroppedItems([fileItem(empty)]) + + expect(result.folderNames).toEqual([]) + expect(result.files).toHaveLength(1) + }) + + it('没有 webkitGetAsEntry 的环境退回 getAsFile(老浏览器 / 非拖拽来源)', () => { + const result = splitDroppedItems([{ kind: 'file', getAsFile: () => file('a.txt') }]) + + expect(result.folderNames).toEqual([]) + expect(result.files.map(f => f.name)).toEqual(['a.txt']) + }) + + it('非文件条目(如拖入文本)忽略', () => { + const result = splitDroppedItems([{ kind: 'string', getAsFile: () => null }]) + + expect(result.folderNames).toEqual([]) + expect(result.files).toEqual([]) + }) + + it('只拖了文件夹时绝不回退到 fallback(否则文件夹又被捞回去上传)', () => { + // 浏览器里被拖入的文件夹同时存在于 items 和 files:files 里那个假 File + // 正是失败上传的来源(ERR_ACCESS_DENIED),所以有 items 时就不能用它兜底 + const folderAsFile = new File([], '新建文件夹', { type: '' }) + const result = splitDroppedItems([folderItem('新建文件夹')], [folderAsFile]) + + expect(result.folderNames).toEqual(['新建文件夹']) + expect(result.files).toEqual([]) + }) + + it('没有 items 可用时才用 fallback(拿不到 entry 的老环境)', () => { + const fallback = new File(['x'], 'a.txt', { type: 'text/plain' }) + const result = splitDroppedItems([], [fallback]) + + expect(result.folderNames).toEqual([]) + expect(result.files.map(f => f.name)).toEqual(['a.txt']) + }) +}) diff --git a/src/features/chat/input/attachmentUpload.ts b/src/features/chat/input/attachmentUpload.ts new file mode 100644 index 000000000..bbf57aa8c --- /dev/null +++ b/src/features/chat/input/attachmentUpload.ts @@ -0,0 +1,254 @@ +// ============================================ +// 附件上传编排(Issue #182) +// +// 把「浏览器 / 桌面端拖入的任意文件」变成服务端上的路径附件: +// 文件 → api/file.uploadAttachment → `{tmp}/uploads//` +// → Attachment{ url: file://..., relativePath: 绝对路径 } +// +// 这里只负责编排与错误分类,UI 状态(上传中 / 失败 / 重试)由输入框维护。 +// 注意 `files[].uri` 只让**服务端**读到字节,模型能否看到取决于服务端嗅探 +// 出的 mime;非文本/图片的附件靠 api/message 注入的路径文本被模型用工具 +// 访问(见 buildAttachmentReferences)。 +// ============================================ + +import { createUploadId, probeServerPath, uploadAttachment, uploadLocalFile } from '../../../api/file' +import { getMimeFromPath, routeAttachment } from './inputUtils' +import { toFileUrl } from '../../mention' +import type { FileCapabilities } from '../../../api' +import type { Attachment } from '../../attachment' + +export type UploadFailureReason = 'network' | 'unauthorized' | 'server' | 'unknown' + +export interface UploadFailure { + reason: UploadFailureReason + /** 原始错误摘要,用于日志与通知正文 */ + message: string +} + +export interface UploadOutcome { + attachment?: Attachment + failure?: UploadFailure +} + +export interface UploadOptions { + serverId?: string + directory?: string + /** 服务端 20MB 附件上限之外的文件只作路径引用(不进 prompt.files[]) */ + pathOnly: boolean + /** 上传进度(0~1):浏览器侧会走 XHR 才能真实上报(见 api/file.uploadAttachment) */ + onProgress?: (fraction: number) => void +} + +/** 从错误对象里抽出可读摘要(fetch 失败在浏览器里往往只有 "Failed to fetch") */ +function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message + if (typeof error === 'string') return error + return 'Unknown error' +} + +/** 把上传失败归类,供客户端选择文案 */ +export function classifyUploadFailure(error: unknown): UploadFailure { + const message = errorMessage(error) + const normalized = message.toLowerCase() + + if (/\b(401|403)\b|unauthor|forbidden/.test(normalized)) { + return { reason: 'unauthorized', message } + } + if (/\b5\d\d\b|internal|bad gateway|unavailable/.test(normalized)) { + return { reason: 'server', message } + } + if (/failed to fetch|networkerror|network request failed|load failed|timeout|timed out|aborted/.test(normalized)) { + return { reason: 'network', message } + } + return { reason: 'unknown', message } +} + +/** 构造路径型附件(displayName 用用户看到的原始文件名,不是服务端清洗过的) */ +export function buildPathAttachment(input: { + id: string + path: string + filename: string + mime: string + size: number + pathOnly: boolean +}): Attachment { + return { + id: input.id, + type: 'file', + displayName: input.filename, + url: toFileUrl(input.path), + mime: input.mime, + relativePath: input.path, + size: input.size, + ...(input.pathOnly ? { pathOnly: true } : {}), + } +} + +export type NativeFileDecision = + /** 原生媒体:读本机字节内联成 data URL(浏览器/桌面都走这条) */ + | { kind: 'inline' } + /** 服务端同机:交给原有的 `@` 引用,**不上传**(需求二) */ + | { kind: 'mention' } + /** 服务端在远端:必须上传 */ + | { kind: 'upload'; pathOnly: boolean } + /** 超过上传上限 */ + | { kind: 'reject' } + +/** + * 桌面端拖入的**本机文件**该走哪条路。 + * + * 桌面端拿得到真实路径(`getDroppedPathsInfo`),所以与服务端同机时可以不 + * 上传:原生媒体内联,其余沿用原有的 `@` 引用(服务端自己读得到那个路径)。 + * 服务端在远端时本机路径对它没有意义,只能上传。 + */ +export function decideNativeFileRoute(input: { + mime: string + size: number + caps: FileCapabilities + serverIsLocal: boolean + nativePath: string +}): NativeFileDecision { + const route = routeAttachment(input) + + switch (route.kind) { + case 'inline': + return { kind: 'inline' } + case 'reference': + return { kind: 'mention' } + case 'reject': + return { kind: 'reject' } + default: + return { kind: 'upload', pathOnly: route.pathOnly } + } +} + +/** + * 能否把本机路径直接交给服务端引用。 + * + * 「URL 是不是 localhost」不足以回答这个问题(本机也可以用局域网地址连自己, + * 容器也会把端口映射到回环),所以除了应用自己拉起的服务(必然同机)之外, + * 一律直接问服务端:这个路径你读得到吗(`probeServerPath`)。 + */ +export async function canReferenceLocalPath(input: { + path: string + /** 应用自己拉起的服务(`local` 条目):必然同机,免探测 */ + pinnedLocal: boolean + directory?: string + serverId?: string + /** 便于单测注入 */ + probe?: (path: string, directory?: string, serverId?: string) => Promise +}): Promise { + if (input.pinnedLocal) return true + + try { + return await (input.probe ?? probeServerPath)(input.path, input.directory, input.serverId) + } catch { + return false + } +} + +async function uploadAndBuild( + payload: File | Uint8Array, + filename: string, + mime: string, + fallbackSize: number, + options: UploadOptions, +): Promise { + try { + const { path, size } = await uploadAttachment(payload, filename, options.directory, options.serverId, { + onProgress: options.onProgress, + }) + return { + attachment: buildPathAttachment({ + id: createUploadId(), + path, + filename, + mime, + size: size || fallbackSize, + pathOnly: options.pathOnly, + }), + } + } catch (error) { + return { failure: classifyUploadFailure(error) } + } +} + +/** + * 上传 `File`(浏览器拖入 / 粘贴 / 文件选择)。 + * + * 永不抛错:失败通过 `failure` 返回,调用方负责可见提示与重试。 + */ +export async function uploadFileAsAttachment(file: File, options: UploadOptions): Promise { + const mime = file.type || getMimeFromPath(file.name) || 'application/octet-stream' + return uploadAndBuild(file, file.name, mime, file.size, options) +} + +/** + * 上传**本机文件**(桌面端拖入 / 选择器)。 + * + * Tauri 下由 Rust 流式发送并把进度推回来(见 api/file.uploadLocalFile), + * 所以这里不会把整份文件读进渲染进程。 + */ +export async function uploadPathAsAttachment( + sourcePath: string, + filename: string, + mime: string, + options: UploadOptions, +): Promise { + try { + const { path, size } = await uploadLocalFile(sourcePath, filename, options.directory, options.serverId, { + onProgress: options.onProgress, + }) + + return { + attachment: buildPathAttachment({ + id: createUploadId(), + path, + filename, + mime: mime || 'application/octet-stream', + size, + pathOnly: options.pathOnly, + }), + } + } catch (error) { + return { failure: classifyUploadFailure(error) } + } +} + +/** + * 把一次拖入拆成「真文件」和「文件夹」。 + * + * 为什么要按 entry 判断而不能看 dataTransfer.files:浏览器把拖入的文件夹也塞进 + * files,表现为一个 size 0、type 空的 File —— 直接上传会得到一个空附件,请求还 + * 常被浏览器安全策略挡掉(net::ERR_ACCESS_DENIED)。所以文件夹必须靠 + * webkitGetAsEntry().isDirectory 认出来,也不能用"大小为 0"来猜(空文件是合法的)。 + * + * fallbackFiles 只在**根本没有 items 可用**时兜底(老环境 / 合成事件)。注意不能在 + * "拣完只剩文件夹"时回退到它 —— 那会把文件夹重新捞回来,正是要拦的东西。 + */ +export interface DroppedItemLike { + kind: string + webkitGetAsEntry?: () => { isDirectory: boolean; name: string } | null + getAsFile?: () => File | null +} + +export function splitDroppedItems( + items: DroppedItemLike[], + fallbackFiles: File[] = [], +): { files: File[]; folderNames: string[] } { + if (items.length === 0) return { files: fallbackFiles, folderNames: [] } + + const files: File[] = [] + const folderNames: string[] = [] + for (const item of items) { + if (item.kind !== 'file') continue + const entry = item.webkitGetAsEntry?.() + if (entry?.isDirectory) { + folderNames.push(entry.name) + continue + } + const file = item.getAsFile?.() + if (file) files.push(file) + } + return { files, folderNames } +} diff --git a/src/features/chat/input/inputUtils.attachmentRouting.test.ts b/src/features/chat/input/inputUtils.attachmentRouting.test.ts new file mode 100644 index 000000000..d457fe8f3 --- /dev/null +++ b/src/features/chat/input/inputUtils.attachmentRouting.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' +import { MAX_INLINE_BYTES, MAX_UPLOAD_BYTES, isFileSupported, routeAttachment } from './inputUtils' + +// ============================================ +// 附件分发(Issue #182) +// +// 三路规则来自服务端的两条硬约束: +// 1. 读 `files[].uri` 时超过 20MB 直接 AttachmentError(整条 prompt 失败) +// 2. 非 text/image/pdf 的 mime 在转 LLM 时被丢弃 → 只能靠文本里的路径 +// 因此「原生媒体且未超限」内联;其余上传;超限只作路径引用/拒绝。 +// ============================================ + +const allCaps = { image: true, pdf: true, audio: true, video: true } +const noCaps = { image: false, pdf: false, audio: false, video: false } + +describe('routeAttachment', () => { + it('原生媒体且未超限 → 内联', () => { + expect(routeAttachment({ mime: 'image/png', size: 1024, caps: allCaps, serverIsLocal: false })).toEqual({ + kind: 'inline', + }) + expect(routeAttachment({ mime: 'application/pdf', size: MAX_INLINE_BYTES, caps: allCaps, serverIsLocal: false })).toEqual( + { kind: 'inline' }, + ) + }) + + it('白名单外(zip 等)→ 上传,且不是 pathOnly', () => { + expect( + routeAttachment({ mime: 'application/zip', size: 1024, caps: allCaps, serverIsLocal: false }), + ).toEqual({ kind: 'upload', pathOnly: false }) + }) + + it('原生媒体但超过 20MB → 上传且只作路径引用(不能进 files[])', () => { + expect( + routeAttachment({ mime: 'image/png', size: MAX_INLINE_BYTES + 1, caps: allCaps, serverIsLocal: false }), + ).toEqual({ kind: 'upload', pathOnly: true }) + }) + + it('模型没有任何文件能力时,图片也走上传(不再被丢弃)', () => { + expect(routeAttachment({ mime: 'image/png', size: 1024, caps: noCaps, serverIsLocal: false })).toEqual({ + kind: 'upload', + pathOnly: false, + }) + expect(isFileSupported('image/png', noCaps)).toBe(false) + }) + + it('超过上传上限 → 拒绝', () => { + expect( + routeAttachment({ mime: 'application/zip', size: MAX_UPLOAD_BYTES + 1, caps: allCaps, serverIsLocal: false }), + ).toEqual({ kind: 'reject', reason: 'too-large' }) + }) + + it('服务端同机 + 有原生路径 → 直引(需求二),超限时同样只作路径引用', () => { + expect( + routeAttachment({ + mime: 'application/zip', + size: 1024, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/data/report.zip', + }), + ).toEqual({ kind: 'reference', path: 'C:/data/report.zip', pathOnly: false }) + + expect( + routeAttachment({ + mime: 'application/zip', + size: MAX_INLINE_BYTES + 1, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/data/big.zip', + }), + ).toEqual({ kind: 'reference', path: 'C:/data/big.zip', pathOnly: true }) + }) + + it('服务端在远端时即使拿到本机路径也只能上传', () => { + expect( + routeAttachment({ + mime: 'application/zip', + size: 1024, + caps: allCaps, + serverIsLocal: false, + nativePath: 'C:/data/report.zip', + }), + ).toEqual({ kind: 'upload', pathOnly: false }) + }) +}) diff --git a/src/features/chat/input/inputUtils.ts b/src/features/chat/input/inputUtils.ts index 79b740525..3ead28d7c 100644 --- a/src/features/chat/input/inputUtils.ts +++ b/src/features/chat/input/inputUtils.ts @@ -88,3 +88,74 @@ export function readFileAsDataUrl(file: File): Promise { reader.readAsDataURL(file) }) } + +// ============================================ +// 附件分发(Issue #182:任意文件上传) +// +// `prompt.files[].uri` 只是「让服务端去读这个文件」的通道,**不是** +// 「让模型看到这个文件」的通道: +// - data URL / file:// 都会在服务端被整份读入内存; +// - 超过 20MB 直接 AttachmentError(整条 prompt 失败); +// - 嗅探出的 mime 不在 text/image/pdf 白名单时,转 LLM 阶段会被丢弃, +// 模型只能靠 prompt 文本里的路径去用工具读(见 api/message 的路径引用注入)。 +// 这三条决定了下面的分发规则与体积阈值。 +// ============================================ + +/** + * 服务端读 `files[].uri` 的硬上限:20MB。 + * + * 与 core `SessionPrompt` 的 `MAX_ATTACHMENT_BYTES` 等值,超出会让**整条 + * prompt 失败**,所以内联与引用都必须卡在这个阈值内。 + */ +export const MAX_INLINE_BYTES = 20 * 1024 * 1024 + +/** + * 单次上传体积上限。 + * + * 超过上限的文件连上传都不做(避免把服务端临时目录写满);产品需要更大 + * 文件时调这里,并同时考虑客户端内存(fetch 方案会把整份文件读进内存)。 + */ +export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024 + +export type AttachmentRoute = + /** 原生媒体且未超限:data URL 内联 */ + | { kind: 'inline' } + /** + * 服务端与客户端同机、且拿得到原生路径:**不走上传**,沿用本机引用方式 + * (当前实现:交给 `@` 引用,服务端自己读得到那个路径)。 + */ + | { kind: 'reference'; path: string; pathOnly: boolean } + /** 上传到服务端临时目录,返回的绝对路径作为附件 */ + | { kind: 'upload'; pathOnly: boolean } + /** 超过上传上限,拒绝 */ + | { kind: 'reject'; reason: 'too-large' } + +/** + * 决定一个文件的附件形态(纯函数,便于单测)。 + * + * `pathOnly` 表示「只把路径写进 prompt 文本、不进 `prompt.files[]`」—— + * 体积超过服务端 20MB 硬上限时唯一还能让模型拿到文件的方式。 + */ +export function routeAttachment(input: { + mime: string + size: number + caps: FileCapabilities + /** 服务端是否与客户端同机(决定本机路径能否直引) */ + serverIsLocal: boolean + /** 本机原生路径,仅桌面端可能拿到 */ + nativePath?: string +}): AttachmentRoute { + if (isFileSupported(input.mime, input.caps) && input.size <= MAX_INLINE_BYTES) { + return { kind: 'inline' } + } + + if (input.nativePath && input.serverIsLocal) { + return { kind: 'reference', path: input.nativePath, pathOnly: input.size > MAX_INLINE_BYTES } + } + + if (input.size > MAX_UPLOAD_BYTES) { + return { kind: 'reject', reason: 'too-large' } + } + + return { kind: 'upload', pathOnly: input.size > MAX_INLINE_BYTES } +} diff --git a/src/features/chat/input/useInputHistory.test.ts b/src/features/chat/input/useInputHistory.test.ts index 5f7e49043..a77435e29 100644 --- a/src/features/chat/input/useInputHistory.test.ts +++ b/src/features/chat/input/useInputHistory.test.ts @@ -111,3 +111,71 @@ describe('useInputHistory 草稿召回', () => { expect(again?.text).toBe('草稿行') }) }) + +describe('useInputHistory 会话内历史', () => { + beforeEach(() => { + localStorage.clear() + promptHistoryStore.reset() + }) + + function setupWithSessionEntries(sessionEntries: { text: string; attachments: [] }[] | null, globalHistory: string[] = []) { + localStorage.clear() + promptHistoryStore.reset() + for (const text of globalHistory) { + promptHistoryStore.add(text, [], 'normal') + } + const textarea = document.createElement('textarea') + const textareaRef = { current: textarea } + const { result } = renderHook(() => + useInputHistory({ + textareaRef, + mode: 'normal', + sessionEntries, + }), + ) + return { textarea, result } + } + + it('会话内历史非空时 ↑ 翻阅会话自己的输入,而不是全局最近输入', () => { + const { textarea, result } = setupWithSessionEntries( + [ + { text: '本会话最新一条', attachments: [] }, + { text: '本会话更早一条', attachments: [] }, + ], + ['别的会话的最近输入'], + ) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const first = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(first?.text).toBe('本会话最新一条') + + textarea.value = first!.text + textarea.setSelectionRange(0, 0) + const second = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), first!.text, []) + expect(second?.text).toBe('本会话更早一条') + }) + + it('会话内历史为空数组时回退全局持久化历史(新会话回忆最近输入)', () => { + const { textarea, result } = setupWithSessionEntries([], ['全局最近输入']) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const recalled = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(recalled?.text).toBe('全局最近输入') + }) + + it('会话内历史 ↓ 越过最新一条回到进入前的输入', () => { + const { textarea, result } = setupWithSessionEntries([{ text: '本会话消息', attachments: [] }]) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const up = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(up?.text).toBe('本会话消息') + + textarea.value = up!.text + textarea.setSelectionRange(textarea.value.length, textarea.value.length) + const down = result.current.handleHistoryKeyDown(keyEvent('ArrowDown'), up!.text, []) + expect(down).toEqual({ text: '', attachments: [], cursor: 'end' }) + }) +}) diff --git a/src/features/chat/input/useInputHistory.ts b/src/features/chat/input/useInputHistory.ts index 3feacc489..fad17dbd6 100644 --- a/src/features/chat/input/useInputHistory.ts +++ b/src/features/chat/input/useInputHistory.ts @@ -1,13 +1,15 @@ import { useRef, useCallback, useEffect } from 'react' -import { usePromptHistory, fromHistoryEntry } from '../../../store/promptHistoryStore' +import { usePromptHistory, fromHistoryEntry, type PromptHistoryEntry } from '../../../store/promptHistoryStore' import type { Attachment } from '../../attachment' // ============================================ // useInputHistory // 类终端的历史消息导航(↑↓ 翻阅已发送消息) // -// 数据源是**全局持久化**的 prompt 历史(官方 composer/history 同款: +// 默认数据源是**全局持久化**的 prompt 历史(官方 composer/history 同款: // 跨会话跨重启保留,normal/shell 分轨,发送即记账、失败移除)。 +// 传入 sessionEntries(当前会话自己的历史用户输入)时优先使用—— +// 在某个会话里翻的是这个会话发过的内容,而不是其它会话的最近输入。 // ============================================ interface HistoryEntry { @@ -25,6 +27,11 @@ interface UseInputHistoryOptions { * ↓ 越过最新一条历史时回到草稿。 */ recallDraft?: () => HistoryEntry | null + /** + * 会话内历史(当前会话已发送的用户输入,最新在前)。 + * 非空时替代全局历史;空数组/不传时回退全局持久化历史。 + */ + sessionEntries?: PromptHistoryEntry[] | null } interface UseInputHistoryReturn { @@ -45,13 +52,15 @@ interface UseInputHistoryReturn { resetHistoryIndex: () => void } -export function useInputHistory({ textareaRef, mode, recallDraft }: UseInputHistoryOptions): UseInputHistoryReturn { +export function useInputHistory({ textareaRef, mode, recallDraft, sessionEntries }: UseInputHistoryOptions): UseInputHistoryReturn { // store 条目最新在前;导航时下标 0 = 最新一条 const storeEntries = usePromptHistory(mode) - const historyRef = useRef(storeEntries) + // 会话内历史优先(该会话发过的输入);没有时回退全局「最近输入」 + const effectiveEntries = sessionEntries && sessionEntries.length > 0 ? sessionEntries : storeEntries + const historyRef = useRef(effectiveEntries) useEffect(() => { - historyRef.current = storeEntries - }, [storeEntries]) + historyRef.current = effectiveEntries + }, [effectiveEntries]) const recallDraftRef = useRef(recallDraft) useEffect(() => { diff --git a/src/features/chat/input/useMobileCollapse.ts b/src/features/chat/input/useMobileCollapse.ts index a0b892ead..e77b540f5 100644 --- a/src/features/chat/input/useMobileCollapse.ts +++ b/src/features/chat/input/useMobileCollapse.ts @@ -23,9 +23,10 @@ interface UseMobileCollapseOptions { footerRef: React.RefObject /** 注册输入框容器用于动画 */ registerInputBox?: (element: HTMLElement | null) => void - /** 收起态的 permission/question 对话框 */ + /** 收起态的 permission/question/websearch 对话框 */ collapsedPermission?: CollapsedDialogInfo collapsedQuestion?: CollapsedDialogInfo + collapsedWebsearch?: CollapsedDialogInfo } interface UseMobileCollapseReturn { @@ -54,6 +55,7 @@ export function useMobileCollapse({ registerInputBox, collapsedPermission, collapsedQuestion, + collapsedWebsearch, }: UseMobileCollapseOptions): UseMobileCollapseReturn { // 判断节点是否在输入区域内部(inputContainer / contentWrap / footer) const isInsideInputArea = useCallback( @@ -98,7 +100,7 @@ export function useMobileCollapse({ // 直接计算是否收起(纯派生值) // isAtBottom 语义是「用户未主动离底」(ChatArea 用 !userScrolled),不是几何 dist。 // 流式贴底跟随期间 dist 会抖,但 userScrolled 仍为 false → 不收起,Footer 不闪。 - const hasPendingDialogs = !!collapsedPermission || !!collapsedQuestion + const hasPendingDialogs = !!collapsedPermission || !!collapsedQuestion || !!collapsedWebsearch const isCollapsed = enabled && !isAtBottom && !hasContent && !isFocused && !hasPendingDialogs && !justCleared // 展开态内容区高度(用于收起时占位,防 isAtBottom 反馈循环) diff --git a/src/features/chat/permissionDiff.test.ts b/src/features/chat/permissionDiff.test.ts new file mode 100644 index 000000000..fa3a13dd7 --- /dev/null +++ b/src/features/chat/permissionDiff.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { extractPermissionDiff } from './permissionDiff' + +describe('extractPermissionDiff', () => { + it('returns empty when metadata is missing', () => { + expect(extractPermissionDiff(undefined)).toEqual({}) + }) + + it('reads v1 unified diff string', () => { + expect(extractPermissionDiff({ diff: '@@ -1 +1 @@', filepath: 'a.ts' })).toEqual({ + diff: '@@ -1 +1 @@', + filePath: 'a.ts', + }) + }) + + it('prefers v1 filediff patch over diff string', () => { + const result = extractPermissionDiff({ + filediff: { patch: 'PATCH', additions: 1, deletions: 1 }, + diff: 'DIFF', + }) + expect(result.diff).toBe('PATCH') + }) + + it('reads v1 filediff before/after when no patch', () => { + const result = extractPermissionDiff({ filediff: { before: 'old', after: 'new' } }) + expect(result).toEqual({ before: 'old', after: 'new' }) + }) + + it('reads v2 files[].patch and file (FileDiff.Info)', () => { + const result = extractPermissionDiff({ + files: [{ file: 'src/a.ts', patch: 'PATCH2', additions: 2, deletions: 0, status: 'modified' }], + }) + expect(result).toEqual({ diff: 'PATCH2', filePath: 'src/a.ts' }) + }) + + it('prefers filediff over files, and files over top-level diff', () => { + // filediff 优先 + expect( + extractPermissionDiff({ + filediff: { patch: 'FD' }, + files: [{ file: 'a', patch: 'F' }], + }).diff, + ).toBe('FD') + // files 优先于顶层 diff + expect( + extractPermissionDiff({ + files: [{ file: 'a', patch: 'F' }], + diff: 'D', + }).diff, + ).toBe('F') + }) + + it('skips files entries without a patch and falls back to top-level diff', () => { + const result = extractPermissionDiff({ files: [{ file: 'a' }], diff: 'D' }) + expect(result.diff).toBe('D') + }) + + it('uses files[].file over top-level filepath', () => { + const result = extractPermissionDiff({ + files: [{ file: 'from-files.ts', patch: 'P' }], + filepath: 'top-level.ts', + }) + expect(result.filePath).toBe('from-files.ts') + }) +}) diff --git a/src/features/chat/permissionDiff.ts b/src/features/chat/permissionDiff.ts new file mode 100644 index 000000000..0840877f0 --- /dev/null +++ b/src/features/chat/permissionDiff.ts @@ -0,0 +1,57 @@ +/** + * 权限请求 metadata 的 diff 提取。 + * + * v1 时代是 `metadata.diff`(unified diff 字符串)或 `metadata.filediff` + * (`{ patch }` 或 `{ before, after }`);v2 改为 + * `metadata.files: [FileDiff.Info]`(官方 edit.ts:180 / write.ts:82 的 + * permission.assert),单文件形状是 `{ file, patch, additions, deletions, status }`。 + * + * 三条来源按优先级取:filediff > files[].patch > diff。 + */ + +export interface PermissionDiffData { + /** unified / patch 字符串 */ + diff?: string + before?: string + after?: string + filePath?: string +} + +export function extractPermissionDiff(metadata: Record | undefined): PermissionDiffData { + const result: PermissionDiffData = {} + if (!metadata) return result + + // v1.4.0+:filediff(优先 patch 字符串,其次 before/after) + if (metadata.filediff && typeof metadata.filediff === 'object') { + const fd = metadata.filediff as Record + if (typeof fd.patch === 'string') result.diff = fd.patch + if (fd.before !== undefined) result.before = String(fd.before) + if (fd.after !== undefined) result.after = String(fd.after) + } + + // v2:files: [FileDiff.Info],取第一个带 patch/diff 的文件 + if (!result.diff && Array.isArray(metadata.files)) { + for (const entry of metadata.files as Record[]) { + if (!entry || typeof entry !== 'object') continue + const patch = + typeof entry.patch === 'string' ? entry.patch : typeof entry.diff === 'string' ? entry.diff : undefined + if (!patch) continue + result.diff = patch + const file = entry.file ?? entry.filePath + if (typeof file === 'string') result.filePath = file + break + } + } + + // v1 旧:unified diff 字符串 + if (!result.diff && typeof metadata.diff === 'string') { + result.diff = metadata.diff + } + + // filePath 兜底:v1 顶层 filepath + if (!result.filePath && typeof metadata.filepath === 'string') { + result.filePath = metadata.filepath + } + + return result +} diff --git a/src/features/chat/sidebar/ActiveSessionItem.tsx b/src/features/chat/sidebar/ActiveSessionItem.tsx index fbfbefbf5..79f917ea4 100644 --- a/src/features/chat/sidebar/ActiveSessionItem.tsx +++ b/src/features/chat/sidebar/ActiveSessionItem.tsx @@ -21,9 +21,10 @@ export function ActiveSessionItem({ entry, resolvedSession, isSelected, onSelect // 目录优先从 resolvedSession 取 const directory = resolvedSession?.location?.directory || entry.directory - // 状态显示:permission > question > retry > working - const statusConfig = - pending?.type === 'permission' + // 状态显示:backgroundOnly(仅后台 shell 活跃)> permission > question > retry > working + const statusConfig = entry.backgroundOnly + ? { label: t('activeSession.backgroundRunning'), color: 'text-success-100', dotColor: 'bg-success-100', pulse: true } + : pending?.type === 'permission' ? { label: t('activeSession.awaitingPermission'), color: 'text-warning-100', diff --git a/src/features/chat/sidebar/FolderRecentList.tsx b/src/features/chat/sidebar/FolderRecentList.tsx index b00dd4cdd..8660259ca 100644 --- a/src/features/chat/sidebar/FolderRecentList.tsx +++ b/src/features/chat/sidebar/FolderRecentList.tsx @@ -25,6 +25,7 @@ import { pinnedSessionsStore, type PinnedSessionEntry } from '../../../store/pin import { SessionListItem } from '../../sessions' import { getSelectionRoundClass } from '../../sessions/selectionRound' import { SessionChildrenSlot } from './SessionChildrenSlot' +import { SessionShellsSlot } from './SessionShellsSlot' const DIRECTORY_PAGE_SIZE = 5 @@ -719,6 +720,7 @@ function PinnedFolderSection({ onToggleSessionSelection={onToggleSessionSelection} /> )} +
    ) })} @@ -1157,6 +1159,7 @@ function FolderRecentSection({ onToggleSessionSelection={onToggleSessionSelection} /> )} +
    ) })} diff --git a/src/features/chat/sidebar/SessionShellsSlot.test.tsx b/src/features/chat/sidebar/SessionShellsSlot.test.tsx new file mode 100644 index 000000000..aa966f6d6 --- /dev/null +++ b/src/features/chat/sidebar/SessionShellsSlot.test.tsx @@ -0,0 +1,102 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ShellInfo } from '@opencode/client/promise' +import { createSessionPlaceholder } from '../../../utils/sessionPlaceholder' +import { FullscreenProvider } from '../../../contexts/FullscreenContext' + +const { listShellsMock, removeShellMock, getShellOutputMock } = vi.hoisted(() => ({ + listShellsMock: vi.fn(), + removeShellMock: vi.fn(), + getShellOutputMock: vi.fn(), +})) + +vi.mock('../../../api/shell', () => ({ + listShells: (directory: string) => listShellsMock(directory), + removeShell: (...args: unknown[]) => removeShellMock(...args), + getShellOutput: (...args: unknown[]) => getShellOutputMock(...args), +})) + +import { shellInventoryStore } from '../../../store/shellInventoryStore' +import { SessionShellsSlot } from './SessionShellsSlot' + +function makeShell(id: string, sessionID: string, command = `cmd-${id}`): ShellInfo { + return { + id, + status: 'running', + command, + cwd: '/repo', + shell: 'bash', + file: '', + metadata: { sessionID }, + time: { started: 1 }, + } as ShellInfo +} + +const parent = createSessionPlaceholder({ id: 'session-1', title: 'Parent', directory: '/workspace' }) + +describe('SessionShellsSlot(后台 shell 挂载)', () => { + beforeEach(() => { + listShellsMock.mockReset() + removeShellMock.mockReset() + removeShellMock.mockResolvedValue(undefined) + }) + + it('父会话下有 running shell → 挂载行;别的会话的 shell 不出现', async () => { + listShellsMock.mockResolvedValue([ + makeShell('sh-1', 'session-1', 'npm run dev'), + makeShell('sh-2', 'session-1', 'pytest'), + makeShell('sh-3', 'session-2', 'other'), + { ...makeShell('sh-4', 'session-1'), status: 'exited' } as ShellInfo, + ]) + + render() + + await waitFor(() => expect(screen.getByText('npm run dev')).toBeInTheDocument()) + expect(screen.getByText('pytest')).toBeInTheDocument() + expect(screen.queryByText('other')).not.toBeInTheDocument() + expect(screen.queryByText('cmd-sh-4')).not.toBeInTheDocument() + }) + + it('没有 running shell → 什么都不渲染', async () => { + listShellsMock.mockResolvedValue([makeShell('sh-9', 'session-2')]) + const { container } = render() + await waitFor(() => expect(listShellsMock).toHaveBeenCalled()) + expect(container).toBeEmptyDOMElement() + }) + + it('行尾 × 停止:调 removeShell 并请求库存重取', async () => { + listShellsMock.mockResolvedValue([makeShell('sh-1', 'session-1', 'npm run dev')]) + render() + + const stopButton = await screen.findByTitle('Stop this shell') + const callsBefore = listShellsMock.mock.calls.length + fireEvent.click(stopButton) + + await waitFor(() => expect(removeShellMock).toHaveBeenCalledWith('sh-1', '/workspace', undefined)) + // 停止后请求重取库存(500ms 防抖后触发) + await waitFor(() => expect(listShellsMock.mock.calls.length).toBeGreaterThan(callsBefore), { timeout: 2000 }) + }) + + it('点击行打开输出弹窗(工具卡 UI + 快照,shell 退出列表后弹窗不闪关)', async () => { + getShellOutputMock.mockResolvedValue({ output: 'hello\n', cursor: 6, size: 6, truncated: false }) + listShellsMock.mockResolvedValue([makeShell('sh-1', 'session-1', 'npm run dev')]) + // 工具卡的 BashRenderer 需要 FullscreenProvider(app 根部有,测试自己包) + render( + + + , + ) + + fireEvent.click(await screen.findByText('npm run dev')) + // 信息流同款工具卡:running 起始展开,实时输出直接可见 + await screen.findByText(/hello/) + + // shell 退出 → 离开 running 列表(挂载行消失),但弹窗靠快照继续开着 + listShellsMock.mockResolvedValue([{ ...makeShell('sh-1', 'session-1'), status: 'exited', exit: 0 } as ShellInfo]) + shellInventoryStore.requestRefresh() + await waitFor(() => expect(screen.queryByTitle('Stop this shell')).not.toBeInTheDocument(), { timeout: 2000 }) + // 弹窗仍在,底部行随后续库存刷新出现退出码 + expect(screen.getByRole('dialog')).toBeInTheDocument() + await screen.findByText('Exit code 0', {}, { timeout: 2000 }) + }) +}) diff --git a/src/features/chat/sidebar/SessionShellsSlot.tsx b/src/features/chat/sidebar/SessionShellsSlot.tsx new file mode 100644 index 000000000..530511c2c --- /dev/null +++ b/src/features/chat/sidebar/SessionShellsSlot.tsx @@ -0,0 +1,102 @@ +// ============================================ +// SessionShellsSlot — 挂在父会话下的后台 shell 子项 +// +// 设计(和子会话挂载位同款,ml-3 缩进): +// - 数据来自 shellInventoryStore(listShells 初始 + shell.started/ended +// 事件重取 + 15s 兜底),按 metadata.sessionID 挂到父会话 +// - shell 不是 session:行是专用的(终端图标 + 命令 + running 脉冲点), +// 点击开输出弹窗(ShellOutputDialog),行尾 × 停止 +// - shell 退出即消失(完成结果由转写里的 synthetic 消息回流,列表不留尸) +// - 父会话活跃判定由 SessionList 读同一批数据(后台 shell 活着 = 会话活跃) +// ============================================ + +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import type { ApiSession } from '../../../api' +import type { ShellInfo } from '@opencode/client/promise' +import { CloseIcon, TerminalIcon } from '../../../components/Icons' +import { removeShell } from '../../../api/shell' +import { shellInventoryStore, useRunningShellsForSession } from '../../../store/shellInventoryStore' +import { uiErrorHandler } from '../../../utils' +import { ShellOutputDialog } from './ShellOutputDialog' + +interface SessionShellsSlotProps { + parentSession: ApiSession + /** 父 session 所属服务器(缺省用活动服务器) */ + serverId?: string +} + +export function SessionShellsSlot({ parentSession, serverId }: SessionShellsSlotProps) { + const { t } = useTranslation(['commands']) + // 打开时存快照:shell 退出后会离开 running 列表,但弹窗不能因为列表刷新被闪关 + //(最新状态由弹窗自己跟库存,exited shell 仍留在库存里) + const [openShell, setOpenShell] = useState(null) + const [stoppingId, setStoppingId] = useState(null) + + // shell 按工作区目录隔离:挂到哪取哪,目录即会话的 location.directory + const directory = parentSession.location?.directory + const shells = useRunningShellsForSession(parentSession.id, directory) + + const handleStop = async (e: React.MouseEvent, shellId: string) => { + e.stopPropagation() + if (stoppingId) return + setStoppingId(shellId) + try { + await removeShell(shellId, directory, serverId) + shellInventoryStore.requestRefresh() + } catch (err) { + uiErrorHandler('stop shell', err) + } finally { + setStoppingId(null) + } + } + + // 注意:弹窗不能放在 shells.length === 0 的早退之后——shell 退出会离开 running 列表, + // 但打开中的弹窗靠快照继续展示(状态由弹窗自己跟库存) + return ( + <> + {shells.length > 0 && ( +
    + {shells.map(shell => ( +
    setOpenShell(shell)} + onKeyDown={e => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault() + setOpenShell(shell) + } + }} + title={shell.command} + className="group flex items-center gap-2 px-2 py-1.5 cursor-default rounded-md text-text-400 hover:bg-bg-200/40 hover:text-text-300 transition-colors duration-150 select-none" + > + {/* running 脉冲点(和会话活跃标识同款) */} + + + + + + {shell.command} + +
    + ))} +
    + )} + + {openShell && ( + setOpenShell(null)} serverId={serverId} /> + )} + + ) +} diff --git a/src/features/chat/sidebar/ShellOutputDialog.tsx b/src/features/chat/sidebar/ShellOutputDialog.tsx new file mode 100644 index 000000000..c3dbaaecd --- /dev/null +++ b/src/features/chat/sidebar/ShellOutputDialog.tsx @@ -0,0 +1,144 @@ +// ============================================ +// ShellOutputDialog — 后台 shell 的输出查看弹窗 +// +// UI 直接复用信息流里的 shell 工具卡(ToolPartView): +// 把 ShellInfo + 实时输出投影成 ToolViewPart,和 ShellMessageView +// (`!` shell 命令消息)同款投影逻辑——running 展开跟输出, +// 结束后折叠、点头行展开,交互与信息流完全一致。 +// 卡片不管的事弹窗自己补:cwd 展示 + 停止按钮(shell.remove)。 +// ============================================ + +import { useEffect, useMemo, useState } from 'react' +import { useTranslation } from 'react-i18next' +import type { JsonValue, ShellInfo } from '@opencode/client/promise' +import { Button, Dialog } from '../../../components/ui' +import { removeShell } from '../../../api/shell' +import { shellInventoryStore, useShellsForDir } from '../../../store/shellInventoryStore' +import { followShellOutput } from '../../message/shellOutput' +import { ToolPartView } from '../../message/parts' +import type { ToolViewPart } from '../../message/tools' +import { uiErrorHandler } from '../../../utils' + +interface ShellOutputDialogProps { + /** 打开时的 shell(状态以库存里的最新值为准) */ + shell: ShellInfo + /** shell 所在工作区目录(库存/输出/停止都按目录路由) */ + directory?: string + onClose: () => void + serverId?: string +} + +export function ShellOutputDialog({ shell, directory, onClose, serverId }: ShellOutputDialogProps) { + const { t } = useTranslation(['commands', 'common', 'chat']) + const [output, setOutput] = useState('') + const [stopping, setStopping] = useState(false) + + // 状态以库存最新值为准(exited/退出码会随后台刷新到达;被 remove 后回落到传入快照) + const inventory = useShellsForDir(directory) + const live = useMemo(() => inventory.find(item => item.id === shell.id) ?? shell, [inventory, shell]) + const running = live.status === 'running' + + // 实时输出跟随(游标增量;组件卸载即停) + useEffect(() => { + return followShellOutput({ + id: shell.id, + directory, + serverId, + running: true, + onOutput: setOutput, + }) + }, [shell.id, directory, serverId]) + + const handleStop = async () => { + if (stopping) return + setStopping(true) + try { + await removeShell(shell.id, directory, serverId) + shellInventoryStore.requestRefresh() + } catch (e) { + uiErrorHandler('stop shell', e) + } finally { + setStopping(false) + } + } + + // ShellInfo → ToolViewPart 投影(ShellMessageView 同款: + // input=command、output=输出文本、metadata 带 exit)。 + // 注意 metadata 不放 shellID:BashRenderer 看到 shellID 会用全局 + // currentDirectory 自己起一路跟随——弹窗的 shell 可能属于别的工作区, + // 错目录轮询会把共享缓存毒成 missing,反而卡死弹窗自己这路正确的跟随。 + // 弹窗的实时输出由本组件的 followShellOutput(正确目录)喂进 metadata.output。 + const part = useMemo(() => { + const input = { command: live.command } + const metadata: Record = {} + let state: ToolViewPart['state'] + if (live.status === 'running') { + state = { + status: 'running', + input, + metadata: output ? { ...metadata, output } : metadata, + } + } else if (live.status === 'timeout' || live.status === 'killed') { + state = { + status: 'error', + input, + error: { + type: 'ShellError', + message: t(live.status === 'timeout' ? 'chat:shellMessage.timeout' : 'chat:shellMessage.killed'), + }, + ...(output ? { content: [{ type: 'text' as const, text: output }] } : {}), + metadata, + } + } else { + if (typeof live.exit === 'number') metadata.exit = live.exit + state = { + status: 'completed', + input, + content: [{ type: 'text' as const, text: output }], + metadata, + } + } + return { + type: 'tool', + id: live.id, + name: 'shell', + // messageID 用 shell.id:折叠状态 key(message::tool:)与信息流里 + // 的同 shell 卡片(mid=消息 id)天然隔开,两边展开状态互不影响 + messageID: live.id, + state, + time: { created: live.time.started, completed: live.time.completed }, + } + }, [live, output, t]) + + return ( + +
    + {/* 信息流沉浸模式同款 shell 工具卡:头行(名称+命令+耗时)+ 输出体 */} + + + {/* 卡片不管的:cwd + 退出码 + 停止 */} +
    + {typeof live.exit === 'number' && ( + + {t('commands:sessions.shell.exitCode', { code: live.exit })} + + )} + + {live.cwd} + + {running && ( + + )} +
    +
    +
    + ) +} diff --git a/src/features/chat/sidebar/SidePanel.tsx b/src/features/chat/sidebar/SidePanel.tsx index 51530d457..ea0747455 100644 --- a/src/features/chat/sidebar/SidePanel.tsx +++ b/src/features/chat/sidebar/SidePanel.tsx @@ -4,6 +4,8 @@ import { SessionList } from '../../sessions' import { FolderRecentList } from './FolderRecentList' import { MultiServerFolderList } from './MultiServerFolderList' import { SearchResults } from './SearchResults' +import { SessionShellsSlot } from './SessionShellsSlot' +import { shellInventoryStore, useShellActiveSessionIds } from '../../../store/shellInventoryStore' import { multiServerStore } from '../../../store/multiServerStore' import { useSidebarServerScope } from './useSidebarServerScope' import { getProjectGroupIdentity } from './projectGrouping' @@ -32,7 +34,7 @@ import { useDirectory, useKeybindingLabel, useVcsInfo } from '../../../hooks' import { globalScopeDirectory, sessionMatchesListScope } from '../../../utils/globalSessionScope' import { useSessionContext } from '../../../contexts/useSessionContext' import { useLayoutStore, childSessionStore } from '../../../store' -import { useBusySessions, useBusyCount } from '../../../store/activeSessionStore' +import { useBusySessions, useBusyCount, type ActiveSessionEntry } from '../../../store/activeSessionStore' import { notificationStore, useNotifications, useUnreadNotificationCount } from '../../../store/notificationStore' import { pinnedSessionsStore } from '../../../store/pinnedSessionsStore' import { serverStore } from '../../../store/serverStore' @@ -300,7 +302,6 @@ export function SidePanel({ // Notification history const notifications = useNotifications() const unreadNotificationCount = useUnreadNotificationCount() - const attentionCount = busyCount + unreadNotificationCount useEffect(() => { return subscribeToConnectionState(setConnectionState) @@ -335,6 +336,50 @@ export function SidePanel({ return map }, [sessions, fetchedSessions]) + // 活跃 tab 要发现「idle 但后台 shell 在跑」的会话:库存按目录隔离且只拉 + // 登记过的目录,挂载行只登记自己可见的——这里把所有已知会话的目录都登记上, + // 否则那些目录的库存根本不会出现(先有鸡先有蛋) + const sessionDirectoriesKey = useMemo(() => { + const dirs = new Set() + for (const session of sessionLookup.values()) { + const dir = session.location?.directory + if (dir) dirs.add(dir) + } + return [...dirs].sort().join('\n') + }, [sessionLookup]) + useEffect(() => { + if (!sessionDirectoriesKey) return + const untracks = sessionDirectoriesKey.split('\n').map(dir => shellInventoryStore.trackDirectory(dir)) + return () => untracks.forEach(untrack => untrack()) + }, [sessionDirectoriesKey]) + + // 后台 shell 在跑但不在 busy 名单里的会话 → 合成活跃条目(backgroundOnly)。 + // 会话对象必须能从 lookup 解析(否则标题/目录都没有,挂出来也是死行) + const shellActiveSessionIds = useShellActiveSessionIds() + const shellActiveEntries = useMemo(() => { + const busyRawIds = new Set(busySessions.map(entry => splitSessionKey(entry.sessionId).sessionId)) + const entries: ActiveSessionEntry[] = [] + for (const rawId of shellActiveSessionIds) { + if (busyRawIds.has(rawId)) continue + const session = sessionLookup.get(rawId) + if (!session) continue + entries.push({ + sessionId: makeSessionKey(serverStore.getActiveServerId(), rawId), + status: { type: 'idle' }, + backgroundOnly: true, + title: session.title, + directory: session.location?.directory, + }) + } + return entries + }, [shellActiveSessionIds, busySessions, sessionLookup]) + + const mergedBusySessions = useMemo( + () => [...busySessions, ...shellActiveEntries], + [busySessions, shellActiveEntries], + ) + const attentionCount = busyCount + shellActiveEntries.length + unreadNotificationCount + const orderedSessions = useMemo(() => { const inScope = (session: ApiSession) => !!currentDirectory || sessionMatchesListScope(session.location?.directory, currentDirectory, pathInfo) @@ -551,8 +596,8 @@ export function SidePanel({ ]) const activeSessionTree = useMemo( - () => buildActiveSessionTree(busySessions, findParentId), - [busySessions, findParentId], + () => buildActiveSessionTree(mergedBusySessions, findParentId), + [mergedBusySessions, findParentId], ) // worktree 不合并进项目:每个已保存目录都是独立文件夹(见 projectGrouping.ts) @@ -823,6 +868,8 @@ export function SidePanel({ handleSelectActive({ ...session, serverId } as ApiSession & { serverId?: string }) } /> + {/* 活跃列表也挂后台 shell(resolvedSession 带 location.directory,数据按目录取) */} + {resolvedSession && } {childEntries.map(childEntry => renderActiveSessionNode(childEntry, level + 1))}
    ) @@ -1343,7 +1390,7 @@ export function SidePanel({ {attentionCount > 0 && ( busyCount + unreadNotificationCount > 0 ? 'bg-accent-main-100/10 text-accent-main-100' : 'bg-success-100/10 text-success-100' }`} @@ -1463,7 +1510,7 @@ export function SidePanel({ {/* Active Sessions Tab */} {sidebarTab === 'active' && (
    - {busySessions.length === 0 && notifications.length === 0 ? ( + {mergedBusySessions.length === 0 && notifications.length === 0 ? (

    {t('sidebar.noActiveSessions')}

    @@ -1530,7 +1577,7 @@ export function SidePanel({ {/* Divider + actions between busy and notifications */} {notifications.length > 0 && (
    0 ? 'mt-2 pt-2 border-t border-border-200/30' : ''}`} + className={`flex items-center justify-between gap-2 ${mergedBusySessions.length > 0 ? 'mt-2 pt-2 border-t border-border-200/30' : ''}`} > {t('sidebar.notifications')} diff --git a/src/features/mention/utils.ts b/src/features/mention/utils.ts index f03a284c0..7c00efbcc 100644 --- a/src/features/mention/utils.ts +++ b/src/features/mention/utils.ts @@ -4,6 +4,7 @@ import type { MentionType, MentionItem, ParsedSegment } from './types' import { getMentionPattern } from './types' +import { absolutePathToFileUrl } from '../../utils/pathUtils' /** * 规范化路径(统一使用 /,移除重复斜杠) @@ -43,19 +44,12 @@ export function toAbsolutePath(relativePath: string, rootPath: string): string { /** * 将文件路径转换为 file:// URL * Windows 路径需要用 file:/// 格式 + * + * 与 api 层的回填共用一个实现(utils/pathUtils),避免两处对 Windows/Unix + * 的斜杠规则产生分歧。 */ export function toFileUrl(filePath: string): string { - const normalized = normalizePath(filePath) - // Windows 路径 (C:/...) 需要 file:/// - if (/^[a-zA-Z]:/.test(normalized)) { - return `file:///${normalized}` - } - // Unix 绝对路径 (/...) - if (normalized.startsWith('/')) { - return `file://${normalized}` - } - // 相对路径(不应该出现,但保险起见) - return `file:///${normalized}` + return absolutePathToFileUrl(filePath) } /** diff --git a/src/features/message/CollapsibleUserText.tsx b/src/features/message/CollapsibleUserText.tsx new file mode 100644 index 000000000..696209858 --- /dev/null +++ b/src/features/message/CollapsibleUserText.tsx @@ -0,0 +1,129 @@ +// ============================================ +// CollapsibleUserText — 用户长文本气泡(超长折叠,预览 8 行) +// +// 原本私有于 MessageRenderer,抽出来给队列气泡(QueueBubbles)复用: +// 正文/折叠/遮罩/展开按钮逻辑共享,气泡外壳(className)、正文颜色 +// (textClassName)、渐变遮罩底色(maskClassName)按场景配。 +// ============================================ + +import { memo, useLayoutEffect, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { MarkdownRenderer } from '../../components/MarkdownRenderer' +import { useDisclosureScrollLock } from '../../hooks' +import { useUiDisclosureState } from '../../utils/uiDisclosureState' + +/** 默认预览 8 行 */ +const COLLAPSE_PREVIEW_LINES = 8 +const LEADING_RELAXED = 1.625 +/** 用户消息里的 HTML artifact 判定(CollapsibleUserText 与 UserMessageView 共用) */ +export const USER_HTML_ARTIFACT_PATTERN = + /(?:```(?:html|htm)\b|() + +export interface CollapsibleUserTextProps { + text: string + collapseEnabled: boolean + renderMarkdown: boolean + /** 折叠/溢出状态的缓存 key(用户消息用消息 id,队列气泡用 queue:条目id) */ + messageId: string + /** 气泡外壳;默认普通用户消息的实心灰泡 */ + className?: string + /** 正文颜色等;默认 text-text-100 */ + textClassName?: string + /** 底部渐变遮罩的底色类;默认 bg-bg-300(与默认外壳底色一致) */ + maskClassName?: string + /** 是否显示底部渐变遮罩(半透明底色的气泡没有能严丝合缝的底色,可关掉) */ + showMask?: boolean +} + +export const CollapsibleUserText = memo(function CollapsibleUserText({ + text, + collapseEnabled, + renderMarkdown, + messageId, + className = 'px-4 py-2.5 bg-bg-300 rounded-2xl max-w-full', + textClassName = 'text-text-100', + maskClassName = 'bg-bg-300', + showMask = true, +}: CollapsibleUserTextProps) { + const { t } = useTranslation('message') + const contentRef = useRef(null) + const { rootRef, headerRef, withScrollLock } = useDisclosureScrollLock() + const overflowCacheKey = `${messageId}:${renderMarkdown ? 'markdown' : 'plain'}` + const [expanded, setExpanded] = useUiDisclosureState(`message:${messageId}:user-text`, false) + const [isOverflow, setIsOverflow] = useState(() => overflowStateCache.get(overflowCacheKey) ?? false) + + useLayoutEffect(() => { + const el = contentRef.current + if (!el) return + + let disposed = false + const measure = () => { + if (disposed) return + const fsBase = Number.parseFloat(window.getComputedStyle(el).getPropertyValue('--fs-base')) + if (!Number.isFinite(fsBase) || fsBase <= 0) return + const collapsedHeight = fsBase * LEADING_RELAXED * COLLAPSE_PREVIEW_LINES + const next = el.scrollHeight > collapsedHeight + 1 + overflowStateCache.set(overflowCacheKey, next) + setIsOverflow(prev => (prev === next ? prev : next)) + } + + measure() + const resizeObserver = new ResizeObserver(measure) + resizeObserver.observe(el) + document.fonts?.ready?.then(measure) + + return () => { + disposed = true + resizeObserver.disconnect() + } + }, [text, overflowCacheKey]) + + const hasHtmlArtifact = renderMarkdown && USER_HTML_ARTIFACT_PATTERN.test(text) + const showCollapse = collapseEnabled && !hasHtmlArtifact && isOverflow + const isCollapsed = collapseEnabled && !hasHtmlArtifact && !expanded + + return ( +
    +
    +
    { + contentRef.current = node + headerRef(node) + }} + className={`m-0 break-words text-[length:var(--fs-base)] ${textClassName} leading-relaxed${ + renderMarkdown ? '' : ' whitespace-pre-wrap' + }${isCollapsed ? ' overflow-hidden' : ''}`} + style={ + isCollapsed + ? { + maxHeight: `calc(var(--fs-base) * ${LEADING_RELAXED} * ${COLLAPSE_PREVIEW_LINES})`, + contain: 'layout paint', + } + : undefined + } + > + {renderMarkdown ? : text} +
    + {/* 底部渐变遮罩 */} + {showMask && showCollapse && isCollapsed && ( +
    + )} +
    + {showCollapse && ( + + )} +
    + ) +}) diff --git a/src/features/message/MessageActionBar.tsx b/src/features/message/MessageActionBar.tsx new file mode 100644 index 000000000..0b6ceb562 --- /dev/null +++ b/src/features/message/MessageActionBar.tsx @@ -0,0 +1,82 @@ +import { memo, useCallback, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { SpinnerIcon, SplitIcon, UndoIcon } from '../../components/Icons' +import { useInputCapabilities } from '../../hooks/useInputCapabilities' +import type { SessionMessageInfo } from '@opencode/client/promise' + +/** + * 消息操作条(undo / fork / copy)共享样式与按钮。 + * + * 从 MessageRenderer 抽出来,供 UserMessageView / AssistantMessageView / + * CompactionPartView 共用——后者不能反向 import MessageRenderer(循环依赖)。 + */ + +/** PC 精细指针:默认隐藏,悬浮消息/聚焦时显示;触控优先设备始终显示 */ +export function useMessageActionBarClass() { + const { preferTouchUi } = useInputCapabilities() + return preferTouchUi + ? 'flex items-center gap-1 transition-opacity' + : 'flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-within:opacity-100 pointer-events-none group-hover:pointer-events-auto group-focus-within:pointer-events-auto focus-within:pointer-events-auto transition-opacity' +} + +interface UndoActionButtonProps { + /** 回退目标消息 id(用户消息或 compaction 等可回退边界) */ + messageId: string + onUndo?: (messageId: string) => void + canUndo?: boolean +} + +/** 回退到这条消息(revert 边界) */ +export const UndoActionButton = memo(function UndoActionButton({ messageId, onUndo, canUndo }: UndoActionButtonProps) { + const { t } = useTranslation('message') + if (!canUndo || !onUndo) return null + return ( + + ) +}) + +interface ForkActionButtonProps { + message: SessionMessageInfo + onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void + forkMessageId?: string +} + +export const ForkActionButton = memo(function ForkActionButton({ message, onFork, forkMessageId }: ForkActionButtonProps) { + const { t } = useTranslation('message') + const [isForking, setIsForking] = useState(false) + + const handleFork = useCallback(async () => { + if (!onFork || isForking) return + + setIsForking(true) + + try { + await onFork(message, forkMessageId) + } catch { + // 业务错误由上层统一处理 + } finally { + setIsForking(false) + } + }, [forkMessageId, isForking, message, onFork]) + + if (!onFork) return null + + return ( + + ) +}) diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index b212dfd4e..2a02d9118 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -2,11 +2,9 @@ import { memo, useState, useRef, useEffect, useLayoutEffect, useMemo, useCallbac import { useTranslation } from 'react-i18next' import { diffLines } from 'diff' import { animate } from 'motion/mini' -import { ChevronDownIcon, ChevronRightIcon, SplitIcon, SpinnerIcon, UndoIcon } from '../../components/Icons' +import { ChevronDownIcon, ChevronRightIcon } from '../../components/Icons' import { CopyButton, SmoothHeight } from '../../components/ui' -import { MarkdownRenderer } from '../../components/MarkdownRenderer' import { useCompositorExpand, useDisclosureScrollLock } from '../../hooks' -import { useInputCapabilities } from '../../hooks/useInputCapabilities' import { useNow } from '../../hooks/useNow' import { useTheme } from '../../hooks/useTheme' import { useDirectory } from '../../hooks' @@ -29,12 +27,14 @@ import { MessageErrorView, type StepFinishInfo, } from './parts' +import { CollapsibleUserText, USER_HTML_ARTIFACT_PATTERN } from './CollapsibleUserText' import { extractToolData, type ToolViewPart } from './tools' +import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from './MessageActionBar' import { MSG_SPACING } from './messageSpacing' import { MessageExpandPanel, useMessageExpandRender } from './messageExpand' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' import type { JsonValue } from '@opencode/client/promise' -import { contentEntries, hasVisibleText, userMessageText, type ContentEntry } from '../../types/api/message' +import { contentEntries, hasVisibleText, idleMessageError, userMessageText, type ContentEntry } from '../../types/api/message' import { currentToolFailed } from '../../types/api/toolState' import { resolveTaskChildSessionRef } from '../../utils/taskChildBinding' import { expandCodeModeSubCalls } from './parts/executeSubCallSummary' @@ -273,6 +273,12 @@ interface MessageRendererProps { isTurnLatestAssistant?: boolean /** 过程折叠时的内容范围 */ processContentScope?: ProcessContentScope + /** + * 本条消息的 step 完成信息是否由本实例渲染。 + * 过程折叠时,末尾助手的「过程」截在壳内渲染、正文在壳外单独渲染一份, + * 这时壳内那份传 false,避免同一条消息出现两行用量。 + */ + stepFinishVisible?: boolean onUndo?: (userMessageId: string) => void onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void forkMessageId?: string @@ -287,6 +293,7 @@ export const MessageRenderer = memo(function MessageRenderer({ turnDuration, isTurnLatestAssistant = true, processContentScope = 'all', + stepFinishVisible = true, onUndo, onFork, forkMessageId, @@ -310,7 +317,13 @@ export const MessageRenderer = memo(function MessageRenderer({ if (message.type === 'compaction') { return (
    - +
    ) } @@ -320,6 +333,21 @@ export const MessageRenderer = memo(function MessageRenderer({ return } + // 失败的 idle 标记:会话级错误(pre-promotion failure 等)渲染成错误卡片 + // (官方 session-ui projection.ts 的 isFailedIdle → Error 卡片)。 + // 这类失败没有任何 assistant 消息,不渲染的话错误永远不可见。 + if (message.type === 'idle') { + const idleError = idleMessageError(message) + if (message.outcome === 'failed' && idleError) { + return ( +
    + +
    + ) + } + return null + } + if (message.type !== 'assistant') return null return ( @@ -329,6 +357,7 @@ export const MessageRenderer = memo(function MessageRenderer({ turnDuration={turnDuration} isTurnLatestAssistant={isTurnLatestAssistant} processContentScope={processContentScope} + stepFinishVisible={stepFinishVisible} onFork={onFork} forkMessageId={forkMessageId} /> @@ -482,146 +511,6 @@ function useEntryGrowAnimation( // Collapsible User Text // ============================================ -/** 默认预览 8 行 */ -const COLLAPSE_PREVIEW_LINES = 8 -const LEADING_RELAXED = 1.625 -const USER_HTML_ARTIFACT_PATTERN = - /(?:```(?:html|htm)\b|() - -const CollapsibleUserText = memo(function CollapsibleUserText({ - text, - collapseEnabled, - renderMarkdown, - messageId, -}: { - text: string - collapseEnabled: boolean - renderMarkdown: boolean - messageId: string -}) { - const { t } = useTranslation('message') - const contentRef = useRef(null) - const { rootRef, headerRef, withScrollLock } = useDisclosureScrollLock() - const overflowCacheKey = `${messageId}:${renderMarkdown ? 'markdown' : 'plain'}` - const [expanded, setExpanded] = useUiDisclosureState(`message:${messageId}:user-text`, false) - const [isOverflow, setIsOverflow] = useState(() => overflowStateCache.get(overflowCacheKey) ?? false) - - useLayoutEffect(() => { - const el = contentRef.current - if (!el) return - - let disposed = false - const measure = () => { - if (disposed) return - const fsBase = Number.parseFloat(window.getComputedStyle(el).getPropertyValue('--fs-base')) - if (!Number.isFinite(fsBase) || fsBase <= 0) return - const collapsedHeight = fsBase * LEADING_RELAXED * COLLAPSE_PREVIEW_LINES - const next = el.scrollHeight > collapsedHeight + 1 - overflowStateCache.set(overflowCacheKey, next) - setIsOverflow(prev => (prev === next ? prev : next)) - } - - measure() - const resizeObserver = new ResizeObserver(measure) - resizeObserver.observe(el) - document.fonts?.ready?.then(measure) - - return () => { - disposed = true - resizeObserver.disconnect() - } - }, [text, overflowCacheKey]) - - const hasHtmlArtifact = renderMarkdown && USER_HTML_ARTIFACT_PATTERN.test(text) - const showCollapse = collapseEnabled && !hasHtmlArtifact && isOverflow - const isCollapsed = collapseEnabled && !hasHtmlArtifact && !expanded - - return ( -
    -
    -
    { - contentRef.current = node - headerRef(node) - }} - className={`m-0 break-words text-[length:var(--fs-base)] text-text-100 leading-relaxed${ - renderMarkdown ? '' : ' whitespace-pre-wrap' - }${isCollapsed ? ' overflow-hidden' : ''}`} - style={ - isCollapsed - ? { - maxHeight: `calc(var(--fs-base) * ${LEADING_RELAXED} * ${COLLAPSE_PREVIEW_LINES})`, - contain: 'layout paint', - } - : undefined - } - > - {renderMarkdown ? : text} -
    - {/* 底部渐变遮罩 */} - {showCollapse && isCollapsed && ( -
    - )} -
    - {showCollapse && ( - - )} -
    - ) -}) - -interface ForkActionButtonProps { - message: SessionMessageInfo - onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void - forkMessageId?: string -} - -const ForkActionButton = memo(function ForkActionButton({ message, onFork, forkMessageId }: ForkActionButtonProps) { - const { t } = useTranslation('message') - const [isForking, setIsForking] = useState(false) - - const handleFork = useCallback(async () => { - if (!onFork || isForking) return - - setIsForking(true) - - try { - await onFork(message, forkMessageId) - } catch { - // 业务错误由上层统一处理 - } finally { - setIsForking(false) - } - }, [forkMessageId, isForking, message, onFork]) - - if (!onFork) return null - - return ( - - ) -}) - // ============================================ // User Message View // ============================================ @@ -635,14 +524,6 @@ interface UserMessageViewProps { onEntryGrowComplete?: (messageId: string) => void } -/** PC 精细指针:默认隐藏,悬浮消息/聚焦时显示;触控优先设备始终显示 */ -function useMessageActionBarClass() { - const { preferTouchUi } = useInputCapabilities() - return preferTouchUi - ? 'flex items-center gap-1 transition-opacity' - : 'flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-within:opacity-100 pointer-events-none group-hover:pointer-events-auto group-focus-within:pointer-events-auto focus-within:pointer-events-auto transition-opacity' -} - const UserMessageView = memo(function UserMessageView({ message, onUndo, @@ -651,7 +532,6 @@ const UserMessageView = memo(function UserMessageView({ canUndo, onEntryGrowComplete, }: UserMessageViewProps) { - const { t } = useTranslation('message') const { collapseUserMessages, renderUserMarkdown } = useTheme() const actionBarClass = useMessageActionBarClass() @@ -694,16 +574,7 @@ const UserMessageView = memo(function UserMessageView({ {/* Action buttons — PC 悬浮消息显示;触控设备始终显示 */}
    - {/* Undo button */} - {canUndo && onUndo && ( - - )} + {/* Copy button */} {messageText && } @@ -723,6 +594,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ turnDuration, isTurnLatestAssistant = true, processContentScope = 'all', + stepFinishVisible = true, onFork, forkMessageId, }: { @@ -731,6 +603,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ turnDuration?: number isTurnLatestAssistant?: boolean processContentScope?: ProcessContentScope + stepFinishVisible?: boolean onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void forkMessageId?: string }) { @@ -799,10 +672,9 @@ const AssistantMessageView = memo(function AssistantMessageView({ const agent = message.agent || undefined const modelLabel = message.model?.id || undefined - // v2 没有 step-finish part:tokens / cost / finish 都在消息上, - // 因此「步骤完成」信息由消息级数据合成,只有一份。 + // step 完成信息(v2 一个 assistant 消息 = 一个 step,tokens / cost / finish 全在消息上) const stepFinish = useMemo(() => toStepFinishInfo(message), [message]) - const showStepFinish = allowStepFinishOnMessage && stepFinish != null + const showStepFinish = allowStepFinishOnMessage && stepFinishVisible && stepFinish != null const hasStepFinishData = stepFinish != null const showTurnDurationFooter = @@ -834,9 +706,6 @@ const AssistantMessageView = memo(function AssistantMessageView({ return null } - // step 完成信息只挂在本条消息最后一个可见条目上 - const lastRenderIdx = findLastRenderableIndex(renderItems) - return (
    {/* 流式增高走 SmoothHeight 0.12s 补间:贴底跟随时内容丝滑生长。 @@ -844,27 +713,14 @@ const AssistantMessageView = memo(function AssistantMessageView({ 否则壳内文本每 chunk 瞬时撑开,行高抖动且丢失生长动画 */}
    - {renderItems.map((item: RenderItem, idx: number) => { - const isLastItem = idx === lastRenderIdx - // latestOnly 开:整轮最后一条 assistant 的 step 才显示 - // latestOnly 关:本消息也显示(旧行为) - const itemShowsStepFinish = showStepFinish && isLastItem - // duration / turnDuration / completedAt 始终只挂在本消息最后一个 step - const showTiming = itemShowsStepFinish - + {renderItems.map((item: RenderItem) => { if (item.type === 'tool-group') { return ( ) } @@ -888,6 +744,22 @@ const AssistantMessageView = memo(function AssistantMessageView({ return null } })} + + {/* step 完成信息:v2 里一个助手消息就是一整个 step,tokens / cost / finish + 全挂在消息上,所以固定放在本消息内容末尾一行。 + + 以前挂「最后一个可见条目」:末尾是正文(最常见)时整块数据跟着丢, + 只有工具组收尾才显示,过程折叠时还会藏在壳里。 */} + {stepFinish && showStepFinish && ( + + )}
    @@ -931,13 +803,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ interface ToolGroupProps { tools: ToolEntry[] messageContext: { messageID: string; created: number; completed?: number } - stepFinish?: StepFinishInfo - duration?: number - turnDuration?: number isStreaming?: boolean - agent?: string - modelLabel?: string - completedAt?: number } /** 用户需要阅读/交互的工具:沉浸模式下这些工具完成后保持展开 */ @@ -947,17 +813,7 @@ function isReadableTool(toolName: string): boolean { return READABLE_TOOL_PATTERNS.test(toolName.toLowerCase()) } -const ToolGroup = memo(function ToolGroup({ - tools, - messageContext, - stepFinish, - duration, - turnDuration, - isStreaming, - agent, - modelLabel, - completedAt, -}: ToolGroupProps) { +const ToolGroup = memo(function ToolGroup({ tools, messageContext, isStreaming }: ToolGroupProps) { const { t } = useTranslation('message') const { descriptiveToolSteps, inlineToolRequests, immersiveMode, processCollapseEnabled } = useTheme() const { serverId, pendingPermissions, pendingQuestions } = useInlineToolRequests() @@ -1142,11 +998,6 @@ const ToolGroup = memo(function ToolGroup({ ? t('stepsCount', { done: totalCount, total: totalCount }) : t('stepsCount', { done: doneCount, total: totalCount })} - {!effectiveExpanded && stepFinish && ( - - {formatTokens(stepFinish.tokens, t)} - - )} ))} @@ -1164,19 +1015,6 @@ const ToolGroup = memo(function ToolGroup({ ) : (
    {toolParts}
    )} - - {stepFinish && ( -
    - -
    - )}
    ) }) @@ -1185,17 +1023,6 @@ const ToolGroup = memo(function ToolGroup({ // Helpers // ============================================ -function formatTokens( - tokens: StepFinishInfo['tokens'], - t: (key: string, opts?: Record) => string, -): string { - const total = tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write - if (total >= 1000) { - return t('tokensK', { count: (total / 1000).toFixed(1) }) - } - return `${total} ${t('tokens')}` -} - /** * 消息级「步骤完成」信息。 * @@ -1512,16 +1339,3 @@ function groupContentForRender(message: AssistantMessage): RenderItem[] { flushToolGroup() return result } - -/** - * 最后一个「会真正渲染出内容」的条目下标。 - * step 完成信息只挂在它上面(对齐旧行为:只挂在本消息最后一个 step-finish)。 - */ -function findLastRenderableIndex(items: RenderItem[]): number { - for (let i = items.length - 1; i >= 0; i--) { - const item = items[i] - if (item.type === 'tool-group') return i - if (hasVisibleText(item.content)) return i - } - return -1 -} diff --git a/src/features/message/messageSpacing.ts b/src/features/message/messageSpacing.ts index fc60a12da..3a995a928 100644 --- a/src/features/message/messageSpacing.ts +++ b/src/features/message/messageSpacing.ts @@ -4,7 +4,6 @@ * - item: 列表项之间只靠 top 间距(根节点不加 pb) * - body: header 下方展开内容 * - stack: 消息内 parts 纵向 gap(0.5rem) - * - finish: ToolGroup 内 tools → StepFinish(与 stack 等距,无 list gap 时用) * - processBody: 过程壳内多助手列表;gap 与 stack / 扁平连续助手 8px 同距 * - toolBodyInset: compact/timeline 工具 body 左右缩进 + body 顶距 * - inner: 工具 body 内权限/提问等子块 @@ -20,8 +19,6 @@ export const MSG_SPACING = { item: 'pt-1', body: 'pt-1', stack: STACK_GAP, - /** 与 stack 的 0.5rem 等距;ToolGroup 内无 list gap,用 top 补 */ - finish: 'pt-2', processBody: `flex flex-col ${STACK_GAP} pt-1`, toolBodyInset: 'pl-2 pr-2.5 pt-1', inner: 'pt-2', diff --git a/src/features/message/parts/CompactionPartView.test.tsx b/src/features/message/parts/CompactionPartView.test.tsx index 2aaf2a9e3..fb1544844 100644 --- a/src/features/message/parts/CompactionPartView.test.tsx +++ b/src/features/message/parts/CompactionPartView.test.tsx @@ -1,8 +1,21 @@ -import { describe, expect, it } from 'vitest' -import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' import { CompactionPartView } from './SystemPartViews' import type { SessionMessageCompaction } from '@opencode/client/promise' +// 隔离滚动锁定(jsdom 不需要),但保留 useDelayedRender 真实以还原收起/展开行为 +vi.mock('../../../hooks', async importOriginal => { + const actual = await importOriginal() + return { + ...actual, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), + } +}) + function compaction(overrides: Record): SessionMessageCompaction { return { id: 'msg-c1', @@ -13,18 +26,20 @@ function compaction(overrides: Record): SessionMessageCompactio } as unknown as SessionMessageCompaction } -describe('CompactionPartView(官方 SessionCompactionMessage 同款)', () => { - it('running:started 分隔线 + 流式摘要 + 进行中指示', () => { - render() +// 每个用例用独立 id,避免 disclosure 缓存跨用例泄漏 +describe('CompactionPartView(单标识 + 可收起)', () => { + it('running:started 标识 + 流式摘要,不再有转圈指示', () => { + render() expect(screen.getByText('Compacting context', { selector: 'span' })).toBeInTheDocument() expect(screen.getByText('正在总结前半段…')).toBeInTheDocument() - expect(screen.getByRole('status')).toHaveTextContent('Compacting context…') + expect(screen.queryByRole('status')).not.toBeInTheDocument() }) - it('completed:结果分隔线 + token 用量(含 cache)', () => { + it('completed:标识变成结果+用量,摘要默认收起、点击展开', () => { render( ) // input = 1000+2000+500=3500 → 3.5K;output = 200+100=300 expect(screen.getByText(/History compacted · 3\.5K in · 300 out/)).toBeInTheDocument() + // 默认自动收起:摘要不在 DOM + expect(screen.queryByText('压缩完成')).not.toBeInTheDocument() + // 点击标识展开 + fireEvent.click(screen.getByRole('button', { name: /History compacted/ })) expect(screen.getByText('压缩完成')).toBeInTheDocument() }) @@ -41,6 +60,7 @@ describe('CompactionPartView(官方 SessionCompactionMessage 同款)', () => render( expect(screen.getByText('Provider compaction')).toBeInTheDocument() }) - it('failed:失败标签 + 错误详情,不显示摘要', () => { + it('failed:失败标签,点击展开看错误详情,不显示摘要', () => { render( , ) expect(screen.getByText(/Compaction failed/)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /Compaction failed/ })) expect(screen.getByText('provider 503')).toBeInTheDocument() }) - it('failed + aborted → 已取消且不显示错误详情', () => { + it('failed + aborted → 已取消,无内容为纯分隔线(不可点)', () => { render( ) expect(screen.getByText('Compaction cancelled')).toBeInTheDocument() expect(screen.queryByText('user cancelled')).not.toBeInTheDocument() + expect(screen.queryByRole('button')).not.toBeInTheDocument() }) it('failed + interrupted → 被中断标签', () => { render( ) expect(screen.getByText('Compaction interrupted')).toBeInTheDocument() }) + + it('completed:undo/分叉/复制操作条不随摘要收起,undo 回传消息 id', () => { + const onUndo = vi.fn() + const onFork = vi.fn() + render( + , + ) + // 与助手消息同一逻辑:操作条始终渲染(悬浮显现),不随摘要收起 + const undoBtn = screen.getByRole('button', { name: 'Undo from here' }) + fireEvent.click(undoBtn) + expect(onUndo).toHaveBeenCalledWith('c-actions') + expect(screen.getByRole('button', { name: 'Fork from here' })).toBeInTheDocument() + }) + + it('step 完成信息在操作条上面(与助手消息同一顺序)', () => { + render( + , + ) + // step 信息:tokens 总数 1000+200+100+2000+500=3800 → 3.8k + const stepInfo = screen.getByText('3.8k tokens') + const undoBtn = screen.getByRole('button', { name: 'Undo from here' }) + // step 信息在 undo 按钮之前(内容 → step 信息 → 操作条) + expect(stepInfo.compareDocumentPosition(undoBtn) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + }) }) diff --git a/src/features/message/parts/SystemPartViews.tsx b/src/features/message/parts/SystemPartViews.tsx index 4299fa294..220f6ee7c 100644 --- a/src/features/message/parts/SystemPartViews.tsx +++ b/src/features/message/parts/SystemPartViews.tsx @@ -1,12 +1,16 @@ -import { memo } from 'react' +import { memo, useEffect, useRef } from 'react' import { useTranslation } from 'react-i18next' -import { RetryIcon, ChevronDownIcon, SpinnerIcon } from '../../../components/Icons' +import { RetryIcon, ChevronDownIcon } from '../../../components/Icons' +import { CopyButton } from '../../../components/ui' import { MarkdownRenderer } from '../../../components/MarkdownRenderer' import { useDisclosureScrollLock } from '../../../hooks' -import type { SessionMessageAssistant, SessionMessageCompaction } from '@opencode/client/promise' +import { useTheme } from '../../../hooks/useTheme' +import type { SessionMessageAssistant, SessionMessageCompaction, SessionMessageInfo } from '@opencode/client/promise' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' import { unwrapErrorMessage } from '../../../utils/errorMessage' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../messageExpand' +import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from '../MessageActionBar' +import { StepFinishPartView, type StepFinishInfo } from './StepFinishPartView' // ============================================ // Retry Part View - 显示重试状态 @@ -89,6 +93,10 @@ export const RetryPartView = memo(function RetryPartView({ retry, stateKey }: Re interface CompactionPartViewProps { /** 原生压缩消息(`status` / `summary` / `tokens` / `error` …) */ message: SessionMessageCompaction + onUndo?: (messageId: string) => void + onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void + forkMessageId?: string + canUndo?: boolean } /** 官方 TimelineSeparator 同款:细分隔线 + 中间标签 */ @@ -108,13 +116,21 @@ function compactNumber(value: number, locale: string): string { } /** - * 压缩消息视图(官方 SessionCompactionMessage 同款): - * --- compaction started --- - * [摘要文本(running 时随 delta 流式增长)] - * [running:进行中指示] / [--- 结果 · 用量 ---] + * 压缩消息视图:单标识 + 可收起。 + * - 头部是唯一分隔线:running 时显示"开始压缩上下文",结束后变成"结果 · 用量", + * 不再额外渲染第二条结果分隔线,也不显示流式中的转圈指示。 + * - 摘要内容可点击头部收起/展开;流式输出结束后默认自动收起(设置里可关)。 */ -export const CompactionPartView = memo(function CompactionPartView({ message }: CompactionPartViewProps) { +export const CompactionPartView = memo(function CompactionPartView({ + message, + onUndo, + onFork, + forkMessageId, + canUndo, +}: CompactionPartViewProps) { const { t, i18n } = useTranslation('message') + const { compactionAutoCollapse } = useTheme() + const actionBarClass = useMessageActionBarClass() const isRunning = message.status === 'running' const isFailed = message.status === 'failed' const summary = isFailed ? '' : message.summary @@ -154,30 +170,99 @@ export const CompactionPartView = memo(function CompactionPartView({ message }: return message.error?.message ?? '' })() + // 唯一标识:running 时是"开始压缩上下文",结束后变成"结果 · 用量" + const headerLabel = isRunning ? t('system.compactionStarted') : outcomeLabel + const hasContent = !!(summary.trim() || failureDetail) + + // step 完成信息(对齐助手消息):model + tokens + cost。 + // 注意 v2 压缩消息只记录 time.created(官方不持久化完成时间), + // 所以助手那种"耗时 / 完成时刻"没有数据,这里不显示。 + const stepFinish = ((): StepFinishInfo | undefined => { + if (isRunning) return undefined + const tokens = message.tokens + const cost = message.cost ?? 0 + if (!tokens && cost <= 0) return undefined + return { + tokens: { + input: tokens?.input ?? 0, + output: tokens?.output ?? 0, + reasoning: tokens?.reasoning ?? 0, + cache: { read: tokens?.cache?.read ?? 0, write: tokens?.cache?.write ?? 0 }, + }, + cost, + } + })() + const stepFinishModel = message.status === 'completed' ? message.model?.id : undefined + + // 收起状态:running 时展开看流式;结束后默认收起(可在设置里关掉自动收起) + const stateKey = `message:compaction:${message.id}` + const [expanded, setExpanded] = useUiDisclosureState(stateKey, isRunning || !compactionAutoCollapse) + const shouldRenderBody = useMessageExpandRender(expanded) + const { rootRef, headerRef, withScrollLock } = useDisclosureScrollLock() + + // 流式结束(running → done)自动收起;respectUser 尊重用户手动展开/收起 + const wasRunningRef = useRef(isRunning) + useEffect(() => { + const wasRunning = wasRunningRef.current + wasRunningRef.current = isRunning + if (wasRunning && !isRunning && compactionAutoCollapse) { + setExpanded(false, { touched: false, respectUser: true }) + } + }, [isRunning, compactionAutoCollapse, setExpanded]) + + // 无内容可收起(如 aborted 空消息)→ 纯分隔线 + if (!hasContent) { + return ( +
    + +
    + ) + } + return ( -
    - +
    + - {summary.trim() && ( -
    - -
    - )} + + {shouldRenderBody && ( + <> + {summary.trim() && ( +
    + +
    + )} + {failureDetail && ( +
    {failureDetail}
    + )} + + )} +
    - {isRunning && ( -
    - - {t('system.compactionRunning')} + {/* step 完成信息(model + tokens + cost),与助手消息一致:内容下方、始终显示 */} + {stepFinish && ( +
    +
    )} - {!isRunning && ( - <> - - {failureDetail && ( -
    {failureDetail}
    - )} - + {/* 操作条:undo / 分叉 / 复制,在 step 信息下面(与助手消息同一逻辑,悬浮显现) */} + {!isRunning && (onUndo || onFork || summary.trim()) && ( +
    + + + {summary.trim() && } +
    )}
    ) diff --git a/src/features/message/parts/ToolPartView.permission.test.tsx b/src/features/message/parts/ToolPartView.permission.test.tsx new file mode 100644 index 000000000..a89b7e289 --- /dev/null +++ b/src/features/message/parts/ToolPartView.permission.test.tsx @@ -0,0 +1,145 @@ +import { act, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ToolPartView } from './ToolPartView' +import type { ToolViewPart } from '../tools' +import type { ApiPermissionRequest } from '../../../api' + +// 可控 mock:按用例决定当前是否还有待批准权限,并记录 InlinePermission 收到的 props +const { findPermissionMock, inlinePermissionSpy } = vi.hoisted(() => ({ + findPermissionMock: vi.fn<() => ApiPermissionRequest | undefined>(() => undefined), + inlinePermissionSpy: vi.fn(), +})) + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})) + +vi.mock('../../../hooks', () => ({ + useDelayedRender: (show: boolean) => show, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), + useCompositorExpand: (open: boolean) => ({ + contentRef: { current: null }, + layoutOpen: open, + keepMounted: open, + panelClassName: '', + }), +})) + +vi.mock('../../../hooks/useTheme', () => ({ + useTheme: () => ({ + inlineToolRequests: true, + immersiveMode: false, + compactInlinePermission: false, + }), +})) + +vi.mock('../../../store/serverStore', () => ({ + serverStore: { getActiveCalibratedNow: () => undefined }, +})) + +vi.mock('../../chat/InlineToolRequestContext', () => ({ + useInlineToolRequests: () => ({ + serverId: 'local', + pendingPermissions: [], + pendingQuestions: [], + onPermissionReply: vi.fn(), + onFormReply: vi.fn(), + onFormCancel: vi.fn(), + isReplying: false, + }), + findPermissionRequestForTool: () => findPermissionMock(), + findQuestionRequestForTool: () => undefined, +})) + +vi.mock('../../chat/InlinePermission', () => ({ + InlinePermission: (props: { resolved?: boolean }) => { + inlinePermissionSpy(props) + return
    + }, +})) + +vi.mock('../../chat/InlineQuestion', () => ({ + InlineQuestion: () => null, +})) + +vi.mock('../tools', () => ({ + getToolIcon: () => , + extractToolData: () => ({}), + getToolConfig: () => undefined, + DefaultRenderer: () => null, + TaskRenderer: () => null, +})) + +function createRunningTool(name: string): ToolViewPart { + return { + type: 'tool', + id: 'tool-1', + name, + messageID: 'message-1', + state: { status: 'running', input: {}, metadata: {} }, + time: { created: 0 }, + } +} + +function createPermission(action: string): ApiPermissionRequest { + return { id: 'perm-1', sessionID: 'session-1', action, resources: [] } as unknown as ApiPermissionRequest +} + +const CONTEXT = { messageID: 'message-1', created: 0 } + +describe('ToolPartView 权限他端批准后的残留', () => { + beforeEach(() => { + findPermissionMock.mockReset() + inlinePermissionSpy.mockClear() + // rAF 同步执行,让缓存 effect 立即落地 + vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { + cb(0) + return 0 + }) + vi.stubGlobal('cancelAnimationFrame', () => {}) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('bash 权限被他端批准后卡片立即消失(不再残留按钮)', () => { + const part = createRunningTool('bash') + findPermissionMock.mockReturnValue(createPermission('bash')) + + const { rerender } = render() + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + + // 他端批准:服务端广播 permission.replied,pending 列表不再有该请求。 + // 真实应用里靠 context 变化触发重渲染;测试里用新 context 引用破掉 memo。 + findPermissionMock.mockReturnValue(undefined) + act(() => { + rerender() + }) + + // 非文件权限立即清缓存 → 权限组件卸载 + expect(screen.queryByTestId('inline-permission')).toBeNull() + }) + + it('edit 权限批准后保留 resolved 预览直到工具完成', () => { + const part = createRunningTool('edit') + findPermissionMock.mockReturnValue(createPermission('edit')) + + const { rerender } = render() + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + + findPermissionMock.mockReturnValue(undefined) + act(() => { + rerender() + }) + + // edit 保留缓存避免画面跳动:仍渲染,且为 resolved 态(无按钮) + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + const lastProps = inlinePermissionSpy.mock.calls.at(-1)?.[0] as { resolved?: boolean } + expect(lastProps?.resolved).toBe(true) + }) +}) diff --git a/src/features/message/parts/ToolPartView.tsx b/src/features/message/parts/ToolPartView.tsx index 317f5e8cc..28ce7ea77 100644 --- a/src/features/message/parts/ToolPartView.tsx +++ b/src/features/message/parts/ToolPartView.tsx @@ -16,6 +16,7 @@ import { } from '../../chat/InlineToolRequestContext' import { InlinePermission } from '../../chat/InlinePermission' import { InlineQuestion } from '../../chat/InlineQuestion' +import { extractPermissionDiff } from '../../chat/permissionDiff' import { getToolIcon, extractToolData, @@ -101,9 +102,16 @@ export const ToolPartView = memo(function ToolPartView({ frameId = requestAnimationFrame(() => { setCachedPermissionRequest(permissionRequest) }) - } else if (toolDone) { + } else { + // 权限已处理(本端或他端批准/拒绝):edit/write 等工具完成再清缓存, + // 避免 "权限消失→空白→结果出现" 的跳动;其余权限立即清缓存让卡片消失, + // 命令/输出交给 ToolBody 展示,否则按钮会一直残留到工具跑完。 frameId = requestAnimationFrame(() => { - setCachedPermissionRequest(undefined) + setCachedPermissionRequest(prev => { + if (!prev) return prev + const cachedIsFile = prev.action === 'edit' || prev.action === 'write' + return cachedIsFile && !toolDone ? prev : undefined + }) }) } @@ -122,13 +130,20 @@ export const ToolPartView = memo(function ToolPartView({ // 精简模式:非 edit/write 权限时不隐藏 ToolBody(ToolBody 已经渲染了命令内容) const isEditWritePermission = permissionRequest?.action === 'edit' || permissionRequest?.action === 'write' || permissionResolved - const hideToolBodyForPermission = isEditWritePermission + // metadata 里有 diff → 交给 InlinePermission 显示(藏 ToolBody,避免重复渲染); + // metadata 缺 diff(官方 edit 多匹配未给 preview)→ ToolBody 用 input 派生兜底。 + const permissionDiff = isEditWritePermission ? extractPermissionDiff(effectivePermissionRequest?.metadata) : null + const permissionHasDiff = !!( + permissionDiff && + (permissionDiff.diff || (permissionDiff.before !== undefined && permissionDiff.after !== undefined)) + ) + const hideToolBodyForPermission = isEditWritePermission && permissionHasDiff // 精简模式:ToolBody 已渲染时,InlinePermission 只显示按钮 // task/subagent 工具除外:其 renderer 无法显示详细的工具请求内容,需要完整展示权限信息 const toolNameLower = toolName.toLowerCase() const isTaskTool = toolNameLower === 'task' || toolNameLower === 'subagent' const permissionContentHidden = - compactInlinePermission && !isEditWritePermission && !isTaskTool && !!permissionRequest + compactInlinePermission && !isTaskTool && !!permissionRequest && (isEditWritePermission ? !permissionHasDiff : true) const isReadable = isReadableTool(toolName) const shouldStartExpanded = isActive || diff --git a/src/features/message/shellOutput.test.ts b/src/features/message/shellOutput.test.ts index 5d0bbae78..8c8dad99a 100644 --- a/src/features/message/shellOutput.test.ts +++ b/src/features/message/shellOutput.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { followShellOutput, SHELL_OUTPUT_TAIL_BYTES } from './shellOutput' const loadMock = vi.fn() @@ -93,3 +93,98 @@ describe('followShellOutput(官方 shell-output.ts 同款)', () => { expect(loadMock.mock.calls.at(-1)?.[1]).toBe(5) }) }) + +// ============================================ +// UTF-8 边界自愈 +// 服务端 shell.output 按字节区间独立 decode(core/shell.ts), +// 多字节字符跨区间会被切成 U+FFFD。这里按字节流精确模拟分页, +// 验证累计文本永远干净。 +// ============================================ + +// 'ab流cd' 的字节布局:a b [E4 B5 81] c d(流 = 3 字节) +function page(output: string, cursor: number, size: number) { + return { output, cursor, size, truncated: false } +} + +describe('followShellOutput UTF-8 边界自愈', () => { + beforeEach(() => { + loadMock.mockReset() + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('页尾切在字符第 1 字节后(r=1):剥离回退,下页从 lead 字节干净续上', async () => { + const outputs: string[] = [] + loadMock + // [0,3):'a','b',E4 → decode 'ab�',游标 3 + .mockResolvedValueOnce(page('ab�', 3, 3)) + // 自愈后游标 2:[2,7) 从 lead 字节开始 → '流cd' + .mockResolvedValueOnce(page('流cd', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-r1', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + expect(outputs.at(-1)).toBe('ab') + expect(loadMock.mock.calls[0][1]).toBe(0) + + await vi.advanceTimersByTimeAsync(1000) + // 第二轮请求用的是剥离后的游标 2 + expect(loadMock.mock.calls[1][1]).toBe(2) + expect(outputs.at(-1)).toBe('ab流cd') + dispose() + }) + + it('页尾切在第 2 字节后(r=2,猜测回退过头):页头检查回滚存档点整段重读', async () => { + const outputs: string[] = [] + loadMock + // [0,4):'a','b',E4,B5 → decode 'ab�',游标 4;剥离 1 符 → 游标 3(落在字符中间) + .mockResolvedValueOnce(page('ab�', 4, 4)) + // [3,7):从 continuation 字节开始 → decode '�cd' → 页头检查失败,回滚到 0 + .mockResolvedValueOnce(page('�cd', 7, 7)) + // [0,7) 整段重读 → 干净 + .mockResolvedValueOnce(page('ab流cd', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-r2', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + expect(outputs.at(-1)).toBe('ab') + + // 第二轮:游标 3 落在字符中间 → 页头检查 → 回滚到存档点 0 + await vi.advanceTimersByTimeAsync(1000) + expect(loadMock.mock.calls[1][1]).toBe(3) + + // 第三轮:从存档点 0 整段重读,文本自愈 + await vi.advanceTimersByTimeAsync(1000) + expect(loadMock.mock.calls[2][1]).toBe(0) + expect(outputs.at(-1)).toBe('ab流cd') + expect(outputs.at(-1)).not.toContain('�') + dispose() + }) + + it('输出本身含 U+FFFD:同一位置不重复自愈,原样接受避免死循环', async () => { + const outputs: string[] = [] + loadMock + // 文件里真的有 U+FFFD(3 字节 EF BF BD),页尾恰好切在它后面 + .mockResolvedValueOnce(page('ab�', 5, 5)) + // 剥离 1 符游标 4 → [4,...) 从真实 U+FFFD 的第 3 字节开始 → 页头又是 � + .mockResolvedValueOnce(page('�x', 7, 7)) + // 回滚到 0 重读:同样的页尾,同样剥离 → 游标又到 4 → 页头又失败 + .mockResolvedValueOnce(page('ab�', 5, 5)) + // 同一位置第二次 → 原样接受 + .mockResolvedValueOnce(page('�x', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-real', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(1000) + + // 最终接受原样内容:真实 U+FFFD 恰好恢复一次(不多不少),且轮询没有卡死 + expect(outputs.at(-1)).toBe('ab�x') + dispose() + }) +}) diff --git a/src/features/message/shellOutput.ts b/src/features/message/shellOutput.ts index 3909ff23f..9ea9a5e23 100644 --- a/src/features/message/shellOutput.ts +++ b/src/features/message/shellOutput.ts @@ -46,6 +46,17 @@ export function followShellOutput(input: { let text = cached?.output ?? '' let loading = false let disposed = false + // ── UTF-8 边界自愈 ── + // 服务端按字节区间独立 decode(core/shell.ts: buffer.subarray(...).toString('utf8')), + // 多字节字符被区间边界切开就永久变成 U+FFFD(逐字打印中文的场景必现)。 + // 自愈规则: + // 1. 页头出现 U+FFFD → 上次「页尾剥离」猜错了回退字节数,游标落在字符中间。 + // 回滚到追加前的存档点,等字符写全后整段重读(存档点一定是干净边界) + // 2. 页尾出现 U+FFFD → 区间终点切在字符中间:剥掉替换符,游标按每符 1 字节 + // 回退(猜少了会被下一轮的规则 1 抓回来) + // 3. 输出本身含 U+FFFD 的极端情况:同一位置只自愈一次,再失败原样接受,不死循环 + let savepoint = { cursor, text } + let recoveredAt = -1 const read = async () => { if (loading) return loading = true @@ -62,9 +73,30 @@ export function followShellOutput(input: { break } if (!page) break - const advanced = page.cursor > cursor - cursor = Math.max(cursor, page.cursor) - text = (text + page.output).slice(-SHELL_OUTPUT_TAIL_BYTES) + + // 规则 1:页头替换符 → 游标在字符中间,回滚到存档点整段重读 + if (page.output.startsWith('�') && recoveredAt !== cursor) { + recoveredAt = cursor + cursor = savepoint.cursor + text = savepoint.text + remember(input.id, { cursor, output: text, state: 'partial' }) + break + } + + // 规则 2:页尾替换符 → 剥掉,游标按每符 1 字节回退 + let output = page.output + let pageCursor = page.cursor + const tail = output.match(/�+$/) + if (tail) { + output = output.slice(0, -tail[0].length) + pageCursor -= tail[0].length + } + + // 追加前存档(下一轮的页头检查若失败,回滚到这里) + savepoint = { cursor, text } + const advanced = pageCursor > cursor + cursor = Math.max(cursor, pageCursor) + text = (text + output).slice(-SHELL_OUTPUT_TAIL_BYTES) const complete = !input.running && cursor >= page.size remember(input.id, { cursor, output: text, state: complete ? 'complete' : 'partial' }) input.onOutput(text) diff --git a/src/features/message/stepFinishPlacement.test.tsx b/src/features/message/stepFinishPlacement.test.tsx new file mode 100644 index 000000000..463b1fc3c --- /dev/null +++ b/src/features/message/stepFinishPlacement.test.tsx @@ -0,0 +1,178 @@ +import type { ReactNode } from 'react' +import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { MessageRenderer } from './MessageRenderer' +import type { AssistantContent, AssistantMessage } from '../../types/api/message' + +/** + * step 完成信息(tokens / cost / 耗时 / agent / model)的挂载位置。 + * + * v2 一个助手消息 = 一个 step,数据全在消息上,所以固定挂在本消息内容末尾。 + * 这里刻意**保留真的 StepFinishPartView**(其它 part 都是空实现), + * 旧代码把信息挂在「最后一个可见条目」上,末尾是正文时整块数据会跟着丢。 + */ + +vi.mock('motion/mini', () => ({ + animate: () => Promise.resolve(), +})) + +vi.mock('../../hooks', async importOriginal => ({ + ...(await importOriginal()), + useDelayedRender: (show: boolean) => show, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), +})) + +vi.mock('../../hooks/useInputCapabilities', () => ({ + useInputCapabilities: () => ({ preferTouchUi: false, canHover: true, hasCoarsePointer: false, hasTouch: false }), +})) + +vi.mock('../../hooks/useTheme', () => ({ + useTheme: () => ({ + collapseUserMessages: false, + renderUserMarkdown: false, + stepFinishDisplay: { + latestOnly: true, + turnDuration: true, + tokens: true, + cache: true, + cost: true, + duration: true, + agent: false, + model: false, + completedAt: false, + }, + completedAtFormat: 'time', + actionsOnLatestAssistantOnly: true, + descriptiveToolSteps: false, + inlineToolRequests: false, + immersiveMode: false, + processCollapseEnabled: false, + }), +})) + +vi.mock('../../components/MarkdownRenderer', () => ({ + MarkdownRenderer: ({ content }: { content: string }) =>
    {content}
    , +})) + +vi.mock('../../components/ui', () => ({ + CopyButton: ({ text }: { text: string }) => , + SmoothHeight: ({ children }: { children: ReactNode }) => <>{children}, +})) + +vi.mock('./parts', async () => { + const { StepFinishPartView } = await import('./parts/StepFinishPartView') + return { + TextPartView: ({ part }: { part: { text: string } }) =>
    {part.text}
    , + ReasoningPartView: () => null, + ToolPartView: () => null, + StepFinishPartView, + RetryPartView: () => null, + MessageErrorView: () => null, + CompactionPartView: () => null, + } +}) + +/** 133228 tokens → 展示成 133.2k;缓存命中 132480 → 132.5k */ +const USAGE = { input: 477, output: 195, reasoning: 66, cache: { read: 132480, write: 10 } } + +function assistant(content: AssistantContent[], usage = true): AssistantMessage { + return { + type: 'assistant', + id: 'assistant-1', + agent: 'build', + model: { id: 'model-1', providerID: 'provider-1' }, + content, + time: { created: 1000, streamed: 9000, completed: 12000 }, + ...(usage ? { tokens: USAGE, cost: 0.0123 } : { tokens: undefined, cost: undefined }), + } as AssistantMessage +} + +const text = (value: string): AssistantContent => ({ type: 'text', text: value }) +const reasoning = (value: string): AssistantContent => ({ type: 'reasoning', text: value }) +const tool = (name: string): AssistantContent => ({ + type: 'tool', + id: `tool-${name}`, + name, + state: { + status: 'completed', + input: { command: 'pwd' }, + content: [{ type: 'text', text: 'ok' }], + metadata: { title: 'pwd' }, + }, + time: { created: 1, completed: 2 }, +}) + +describe('step 完成信息挂载位置', () => { + it('消息末尾是正文时照样渲染(旧代码会整块丢掉)', () => { + render() + + expect(screen.getByText('答案')).toBeInTheDocument() + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + expect(screen.getByText(/11\.0s total/)).toBeInTheDocument() + }) + + it('只有正文、末尾没有工具组时也渲染', () => { + render() + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('消息末尾是工具组时渲染', () => { + render() + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('工具组在前、正文在末时渲染,且只渲染一次', () => { + render() + + expect(screen.getAllByText(/133\.2k/)).toHaveLength(1) + }) + + it('壳内那截且壳外还有一份时(stepFinishVisible=false)不渲染,避免重复', () => { + const { container } = render( + , + ) + + expect(container.textContent).not.toContain('133.2k') + }) + + it('壳内那截没有壳外副本时照常渲染', () => { + render( + , + ) + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it("壳外 final 正文渲染", () => { + render( + , + ) + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('latestOnly 开启且不是整轮最后一条时不渲染', () => { + const { container } = render() + + expect(container.textContent).not.toContain('133.2k') + }) + + it('没有 tokens/cost 时回落到回合耗时一行', () => { + render() + + expect(screen.getByText('中断了')).toBeInTheDocument() + expect(screen.getByText(/11\.0s total/)).toBeInTheDocument() + }) +}) diff --git a/src/features/message/tools/renderers/BashRenderer.test.tsx b/src/features/message/tools/renderers/BashRenderer.test.tsx new file mode 100644 index 000000000..6a5e8cf22 --- /dev/null +++ b/src/features/message/tools/renderers/BashRenderer.test.tsx @@ -0,0 +1,92 @@ +import { render, screen } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { JsonValue } from '@opencode/client/promise' +import { BashRenderer } from './BashRenderer' +import { FullscreenProvider } from '../../../../contexts' +import { DirectoryContext, type DirectoryContextValue } from '../../../../contexts/DirectoryContext.shared' +import type { ToolViewPart } from '../index' + +const { getShellOutputMock } = vi.hoisted(() => ({ + getShellOutputMock: vi.fn(), +})) + +vi.mock('../../../../api/shell', () => ({ + getShellOutput: (...args: unknown[]) => getShellOutputMock(...args), + listShells: vi.fn(), + removeShell: vi.fn(), +})) + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string) => key, + }), +})) + +function runningPart(metadata: Record): ToolViewPart { + return { + type: 'tool', + id: 'tool-1', + name: 'shell', + messageID: 'message-1', + state: { + status: 'running', + input: { command: 'npm run dev' }, + metadata, + }, + time: { created: 1_000 }, + } +} + +const directoryValue = { currentDirectory: '/repo' } as unknown as DirectoryContextValue + +function renderBash(part: ToolViewPart, data: Parameters[0]['data']) { + return render( + + + + + , + ) +} + +describe('BashRenderer 运行中流式输出(官方 followShellOutput 同款)', () => { + beforeEach(() => { + getShellOutputMock.mockReset() + }) + + it('running + metadata.shellID → 游标轮询实时输出并显示', async () => { + getShellOutputMock.mockResolvedValue({ output: 'vite dev ready\nlistening on 5173\n', cursor: 34, size: 34, truncated: false }) + renderBash(runningPart({ shellID: 'sh-1' }), { input: 'npm run dev' }) + + // 实时输出直接出现在输出区(不等工具结束) + await screen.findByText(/listening on 5173/) + expect(getShellOutputMock).toHaveBeenCalledWith('sh-1', 0, '/repo', undefined) + }) + + it('running 但没有 shellID → 不轮询(拿不到 shell 句柄,只能等结束)', async () => { + renderBash(runningPart({}), { input: 'npm run dev' }) + // 给可能的轮询留时间(首轮是立即发起的) + await new Promise(resolve => setTimeout(resolve, 100)) + expect(getShellOutputMock).not.toHaveBeenCalled() + }) + + it('completed → 不轮询,显示 content 里的最终输出', async () => { + const part: ToolViewPart = { + type: 'tool', + id: 'tool-1', + name: 'bash', + messageID: 'message-1', + state: { + status: 'completed', + input: { command: 'echo done' }, + metadata: { shellID: 'sh-1', exit: 0 }, + content: [{ type: 'text', text: 'done' }], + }, + time: { created: 1_000, completed: 2_000 }, + } + renderBash(part, { input: 'echo done', output: 'done' }) + await screen.findByText('done') + await new Promise(resolve => setTimeout(resolve, 100)) + expect(getShellOutputMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/features/message/tools/renderers/BashRenderer.tsx b/src/features/message/tools/renderers/BashRenderer.tsx index eb062540b..92b3da992 100644 --- a/src/features/message/tools/renderers/BashRenderer.tsx +++ b/src/features/message/tools/renderers/BashRenderer.tsx @@ -8,13 +8,17 @@ * - exit code 内联在输出末尾 */ -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { MaximizeIcon, MinimizeIcon } from '../../../../components/Icons' import { useFullscreen } from '../../../../contexts' +import { DirectoryContext } from '../../../../contexts/DirectoryContext.shared' +import { useInlineToolRequests } from '../../../chat/InlineToolRequestContext' import { useSyntaxHighlight } from '../../../../hooks/useSyntaxHighlight' import { useResponsiveMaxHeight } from '../../../../hooks/useResponsiveMaxHeight' import { parseAnsi, type AnsiSegment } from '../../../../utils/ansiUtils' +import { currentToolMetadata } from '../../../../types/api' +import { followShellOutput } from '../../shellOutput' import { copyTextToClipboard, clipboardErrorHandler } from '../../../../utils' import type { ToolRendererProps } from '../types' @@ -28,7 +32,30 @@ export function BashRenderer({ part, data, onFullscreenChange }: ToolRendererPro const isActive = state.status === 'running' || state.status === 'streaming' const hasError = !!data.error const command = data.input?.trim() - const output = data.output?.trim() + // 运行中 shell 的实时输出跟随(官方 session-ui shell 渲染器同款): + // v2 shell 工具一启动就 progress({ shellID }),事件流只在结束时给最终 + // output,存活期间靠 shell.output 游标轮询。目录上下文用可选读取—— + // 没有 DirectoryProvider 的环境(部分测试)不启用跟随,而不是炸掉。 + const shellID = (() => { + const metadata = currentToolMetadata(part) + return typeof metadata.shellID === 'string' ? metadata.shellID : undefined + })() + const directoryContext = useContext(DirectoryContext) + const currentDirectory = directoryContext?.currentDirectory + const { serverId } = useInlineToolRequests() + const [streamedOutput, setStreamedOutput] = useState('') + useEffect(() => { + if (!isActive || !shellID || !currentDirectory) return + return followShellOutput({ + id: shellID, + directory: currentDirectory, + serverId: serverId || undefined, + running: true, + onOutput: setStreamedOutput, + }) + }, [isActive, shellID, currentDirectory, serverId]) + // 存活期间以流式输出为准;结束后 content 里的最终 output 是权威 + const output = (isActive && shellID ? streamedOutput.trim() : '') || data.output?.trim() const cwd = data.cwd?.trim() const exitCode = data.exitCode const maxHeight = useResponsiveMaxHeight() diff --git a/src/features/message/tools/renderers/TaskRenderer.tsx b/src/features/message/tools/renderers/TaskRenderer.tsx index ddc5f6e29..d1c9bac0f 100644 --- a/src/features/message/tools/renderers/TaskRenderer.tsx +++ b/src/features/message/tools/renderers/TaskRenderer.tsx @@ -278,6 +278,7 @@ export const TaskHeader = memo(function TaskHeader({ {sessionId ? (
    ) })} @@ -334,6 +338,7 @@ export function SessionList({ onToggleSessionSelection={onToggleSessionSelection} /> )} + {showUnavailableAfter && unavailablePinnedEntries.map(entry => ( @@ -431,6 +436,9 @@ export function SessionListItem({ // 单服务器模式 session.id 是原始 id,需用活动服务器合成复合 key 查询) const activeQueryKey = activeSessionKey ?? makeSessionKey(serverStore.getActiveServerId(), session.id) const activeEntry = useSessionActiveEntry(activeQueryKey) + // 后台 shell 活着 = 会话仍活跃(store 自己订阅,不用列表层层喂 props; + // 库存按工作区目录隔离,用会话自己的 location.directory 查) + const hasBackgroundWork = useHasBackgroundShells(session.id, session.location?.directory) const activeStatus = activeEntry ? activeEntry.pendingAction?.type === 'permission' ? { dot: 'bg-warning-100', label: t('chat:activeSession.awaitingPermission'), pulse: false } @@ -439,7 +447,10 @@ export function SessionListItem({ : activeEntry.status.type === 'retry' ? { dot: 'bg-warning-100', label: t('chat:activeSession.retrying'), pulse: false } : { dot: 'bg-success-100', label: t('chat:activeSession.working'), pulse: true } - : null + : // 会话本身 idle 但有后台 shell 在跑 → 仍算活跃(绿点脉冲,标签区分) + hasBackgroundWork + ? { dot: 'bg-success-100', label: t('chat:activeSession.backgroundRunning'), pulse: true } + : null const hasUnreadCompletedNotification = useHasUnreadCompletedNotification(activeQueryKey) const itemRef = useRef(null) const isCompact = density === 'compact' diff --git a/src/features/settings/components/AgentSettings.tsx b/src/features/settings/components/AgentSettings.tsx index 8d4597200..55f0b97d7 100644 --- a/src/features/settings/components/AgentSettings.tsx +++ b/src/features/settings/components/AgentSettings.tsx @@ -16,6 +16,8 @@ export function AgentSettings() { const [toolCardStyle, setToolCardStyle] = useState(themeStore.toolCardStyle) const [immersiveMode, setImmersiveMode] = useState(themeStore.immersiveMode) const [compactInlinePermission, setCompactInlinePermission] = useState(themeStore.compactInlinePermission) + const [compactionAutoCollapse, setCompactionAutoCollapse] = useState(themeStore.compactionAutoCollapse) + const [queueAutoCollapse, setQueueAutoCollapse] = useState(themeStore.queueAutoCollapse) const [processCollapseEnabled, setProcessCollapseEnabled] = useState(themeStore.processCollapseEnabled) const handleAlwaysAllowModeChange = (mode: AlwaysAllowMode) => { @@ -83,6 +85,18 @@ export function AgentSettings() { themeStore.setCompactInlinePermission(next) } + const toggleCompactionAutoCollapse = () => { + const next = !compactionAutoCollapse + setCompactionAutoCollapse(next) + themeStore.setCompactionAutoCollapse(next) + } + + const toggleQueueAutoCollapse = () => { + const next = !queueAutoCollapse + setQueueAutoCollapse(next) + themeStore.setQueueAutoCollapse(next) + } + return (
    @@ -165,6 +179,22 @@ export function AgentSettings() { + + + + + + + +
    setRenderUserMarkdown(!renderUserMarkdown)} /> + setRenderHtmlContent(!renderHtmlContent)} + > + setRenderHtmlContent(!renderHtmlContent)} /> + + ({ getGlobalConfig: vi.fn(), getConfig: vi.fn(), - // v2:config.providers() 被 model.list() 取代;写配置改走文档写入 + // v2:config.providers() 被 model.list() / provider.list() 取代;写配置改走全局文档写入 getActiveModels: vi.fn(), - writeConfigDocument: vi.fn(), + getProviders: vi.fn(), + writeGlobalConfigDocument: vi.fn(), listAvailableShells: vi.fn(), })) @@ -25,22 +26,19 @@ describe('ConfigSettings search', () => { // v2 的配置顶层键是 providers(复数) providers: { openai: { - options: { baseURL: 'https://gateway.example.com' }, + name: 'Gateway OpenAI', }, }, }) api.getConfig.mockResolvedValue({}) api.getActiveModels.mockResolvedValue([]) - api.writeConfigDocument.mockResolvedValue('/repo/opencode.json') + api.getProviders.mockResolvedValue([{ id: 'openai', name: 'OpenAI' }]) + api.writeGlobalConfigDocument.mockResolvedValue('/repo/opencode.jsonc') api.listAvailableShells.mockResolvedValue([]) Element.prototype.scrollIntoView = vi.fn() Element.prototype.scrollTo = vi.fn() }) - // 阻塞:与 configEditorDrill 的 provider 用例同因——v2 的配置顶层键是 - // `providers`(复数),而配置编辑器(ProvidersSection / configEditorValidation / - // 搜索索引)仍按 v1 的 `provider` 读取,因此搜不到 providers 下的字段。 - // 待把该组顶层键改成 `providers` 后再启用(夹具已改为复数)。 it('searches a raw JSON value and opens its nested field', async () => { render() fireEvent.click(screen.getByRole('button', { name: 'Open Config Editor' })) @@ -48,12 +46,12 @@ describe('ConfigSettings search', () => { const input = screen.getByRole('combobox', { name: 'Search config fields...' }) fireEvent.focus(input) - fireEvent.change(input, { target: { value: 'gateway.example.com' } }) - const result = await screen.findByRole('option', { name: /providers\.openai\.options\.baseURL/ }) + fireEvent.change(input, { target: { value: 'Gateway OpenAI' } }) + const result = await screen.findByRole('option', { name: /providers\.openai\.name/ }) fireEvent.click(result) await waitFor(() => expect(screen.getByRole('tab', { name: 'Providers & Models' })).toHaveAttribute('aria-selected', 'true')) - const field = await screen.findByDisplayValue('https://gateway.example.com') + const field = await screen.findByDisplayValue('Gateway OpenAI') await waitFor(() => expect(field.closest('[data-config-field]')).toHaveClass('settings-search-highlight')) expect(field).toHaveFocus() // 单跑 0.5s 就过;但本文件要挂载完整 ConfigSettings + 配置编辑器弹窗(jsdom 冷启动最重的路径之一), diff --git a/src/features/settings/components/ConfigSettings.tsx b/src/features/settings/components/ConfigSettings.tsx index 2104bc388..cb238e282 100644 --- a/src/features/settings/components/ConfigSettings.tsx +++ b/src/features/settings/components/ConfigSettings.tsx @@ -12,7 +12,12 @@ import { KeyboardIcon, LayersIcon, PlugIcon, - SunIcon, + CodeIcon, + ImageIcon, + TerminalIcon, + LightbulbIcon, + ShieldIcon, + PencilIcon, QuestionIcon, CogIcon, } from '../../../components/Icons' @@ -22,8 +27,9 @@ import { getConfig, getGlobalConfig, getActiveModels, + getProviders, listAvailableShells, - writeConfigDocument, + writeGlobalConfigDocument, } from '../../../api' import type { Config } from '../../../types/api/config' import { useCurrentDirectory, useIsMobile } from '../../../hooks' @@ -39,28 +45,26 @@ import { clone, getObject, sameValue, tx } from './configEditorUtils' const CONFIG_TAB_ICONS: Record = { general: , - server: , - providers: , - agents: , commands: , skills: , plugins: , - mcp: , - permissions: , - formatters: , - lsp: , - attachments: , - runtime: , - experimental: , - compatibility: , - advanced: , + providers: , + agents: , + mcp: , + permissions: , + formatters: , + lsp: , + media: , + runtime: , + experimental: , + advanced: , } const CONFIG_SECTION_GROUPS: { en: string; zh: string; sections: SectionID[] }[] = [ - { en: 'Core', zh: '核心', sections: ['general', 'server'] }, + { en: 'Core', zh: '核心', sections: ['general'] }, { en: 'Extensions', zh: '扩展', sections: ['commands', 'skills', 'plugins', 'providers', 'agents', 'mcp'] }, { en: 'Tools', zh: '工具', sections: ['permissions', 'formatters', 'lsp'] }, - { en: 'Advanced', zh: '高级', sections: ['attachments', 'runtime', 'experimental', 'compatibility', 'advanced'] }, + { en: 'Advanced', zh: '高级', sections: ['media', 'runtime', 'experimental', 'advanced'] }, ] function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) { @@ -170,12 +174,14 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () setValidationErrors([]) setValidationDrillTarget(null) try { - const [global, nextEffective, shellList, providerModels] = await Promise.all([ + const [global, nextEffective, shellList, providerModels, providers] = await Promise.all([ getGlobalConfig(), getConfig(directory), listAvailableShells(directory).catch(() => []), // v2 删除了 config.providers(),模型清单改由 model.list() 提供 getActiveModels(directory).catch(() => []), + // provider 元信息(显示名)来自 provider.list() + getProviders(directory).catch(() => []), ]) const modelChoices: Choice[] = providerModels.map(model => ({ @@ -183,14 +189,18 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () label: `${model.providerID}/${model.id}`, })) + const catalog: JsonRecord = {} + for (const provider of providers) { + catalog[provider.id] = { name: provider.name } + } + if (request !== loadRequestRef.current) return setOriginal(clone(global)) setConfig(clone(global)) setJsonDraftErrors(new Set()) setDraftErrors(new Set()) setEffective(nextEffective) - // v2 没有 provider 目录接口,这里留空(仅供 provider 元信息展示的旧路径) - setProviderCatalog({}) + setProviderCatalog(catalog) setShells([ { value: '', label: t('config.shellAuto') }, ...shellList.map((shell: { path: string; name: string; acceptable: boolean }) => ({ @@ -275,16 +285,16 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () setSaving(true) try { // v2 的 config.update 只接受 { shell },任意字段的保存没有 API。 - // 原生做法是直接把合并结果写回配置文档文件(见 api/config 的说明)。 - const savedPath = await writeConfigDocument(snapshot, directory) + // 原生做法是直接把合并结果写回**全局**配置文档(见 api/config 的说明)。 + const savedPath = await writeGlobalConfigDocument(snapshot) if (request !== saveRequestRef.current) return const saved = await getGlobalConfig().catch(() => snapshot) setOriginal(clone(saved)) setConfig(current => (sameValue(current, snapshot) ? clone(saved) : current)) setSchemaWarning( tx( - `Saved to ${savedPath}. Note: v2 has no field-level config API, so the file is rewritten as plain JSON — comments and original formatting are lost.`, - `已保存到 ${savedPath}。注意:v2 没有字段级配置接口,此操作会以纯 JSON 重写文件,注释与原始排版会丢失。`, + `Saved to ${savedPath}. Note: v2 has no field-level config API, so the global document is rewritten as plain JSON — comments and original formatting are lost.`, + `已保存到 ${savedPath}。注意:v2 没有字段级配置接口,此操作会以纯 JSON 重写全局配置文档,注释与原始排版会丢失。`, lang, ), ) @@ -311,8 +321,8 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () 'plan', 'general', 'explore', - ...Object.keys(getObject(config, 'agent')), - ...Object.keys(getObject(effective, 'agent')), + ...Object.keys(getObject(config, 'agents')), + ...Object.keys(getObject(effective, 'agents')), ]) return Array.from(names) .sort() diff --git a/src/features/settings/components/configEditorAgentFields.tsx b/src/features/settings/components/configEditorAgentFields.tsx index 94c79b103..db804c553 100644 --- a/src/features/settings/components/configEditorAgentFields.tsx +++ b/src/features/settings/components/configEditorAgentFields.tsx @@ -1,36 +1,95 @@ -import { BoolField, KeyValueField, NumberField, PositiveIntegerField, Select, TextArea, TextField } from './configEditorControls' -import type { FieldDef } from './configEditorFields' -import { PermissionEditor, ToolToggleMap } from './configEditorPermissions' +import { BoolField, KeyValueField, PositiveIntegerField, Select, StringMapField, TextArea, TextField } from './configEditorControls' +import { DrillFields, type FieldDef } from './configEditorFields' +import { PermissionEditor } from './configEditorPermissions' import { enumChoices } from './configEditorSectionTypes' import type { Choice, JsonRecord, Lang } from './configEditorTypes' -import { previewValue, tx } from './configEditorUtils' +import { isRecord, modelSelectionText, previewValue, tx } from './configEditorUtils' +/** + * v2 的 agent 字段(对应 `ConfigAgent.Info`)。 + * + * 相比 v1:`prompt`→`system`、`disable`→`disabled`、`maxSteps`→`steps`, + * `temperature`/`top_p` 等采样参数进 `request.body`,`tools` 与 + * `permission` 合并成有序规则集 `permissions`,`variant` 并入 `model` 选择。 + */ export function buildAgentConfigFields({ value, - setField, + onChange, lang, models, }: { value: JsonRecord - setField: (key: string, value: unknown) => void + onChange: (next: JsonRecord) => void lang: Lang models: Choice[] }): FieldDef[] { + const set = (key: string, v: unknown) => onChange({ ...value, [key]: v }) + const unset = (key: string) => { + const next = { ...value } + delete next[key] + onChange(next) + } return [ - { key: 'description', label: 'description', desc: tx('Description of when to use the agent.', '何时使用该 agent 的说明。', lang), control: setField('description', v)} /> }, - { key: 'mode', label: 'mode', desc: tx("Agent mode: 'primary', 'subagent' or 'all'.", "agent 模式:primary、subagent 或 all。", lang), control: setField('model', v)} /> }, - { key: 'variant', label: 'variant', desc: tx("Default model variant (only with the agent's configured model).", '默认模型 variant(仅对该 agent 配置的模型生效)。', lang), control: setField('variant', v)} /> }, - { key: 'prompt', label: 'prompt', block: true, desc: tx('System prompt override for this agent.', '该 agent 的系统提示词覆盖。', lang), control: