diff --git a/CHANGELOG.md b/CHANGELOG.md index d244d531..be8de0c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,62 @@ # Changelog +## [v1.0.10] - 2026-10-26 + +- chore: bump version to 0.7.24 (3cc22e8c) +- feat(appearance): 抓取间隔改成可调滑杆 (d8a3565e) +- fix(appearance): 主操作按钮改成半透明磨砂 (9177c56d) +- feat(appearance): 抓屏背景支持录屏,并统一浮层材质 (a0e6f49a) +- feat(appearance): 桌面背景抓取(自绘档)与窗口背景模式 (83422e6c) +- fix(appearance): 权限/提问/websearch 弹窗与 Dialog 同一块玻璃 (fad989bd) +- chore: bump version to 0.7.23 (43c5d161) +- fix(chat): 「移到后台」不再统计上一回合遗留的 shell (2952ccae) +- fix(input): 换行到顶时输入框工具条不再被裁掉 (15739390) +- fix(message): 折叠遮罩只作用于超长折叠消息 (af7eaafc) +- fix(appearance): 玻璃下主按钮、标签栏与状态点的质感 (c90cfd4e) +- chore(window): 记录最终选中的窗口材质,方便真机排查 (5fa185ed) +- feat(appearance): 窗口材质加降级链,无模糊时抬高染色 (86f21896) +- feat(appearance): 桌面端玻璃直接透出窗口背后的桌面 (7b88b3fc) +- fix(input): 忙碌时输入框底色不再被抬高 (bd1ae610) +- fix(input): 输入框单行高度不再随首字跳动 (abbc785e) +- style(appearance): 提高输入框描边光的色彩可见度 (95d473a6) +- fix(appearance): 全屏预览改用淡色叠层 (acfa4bfe) +- style(appearance): 输入框描边光放缓坡度并拉长光带 (e7359457) +- fix(appearance): 玻璃改用文字色叠层,开启时切深色 (833dde1a) +- feat(appearance): 补齐组件、浮层、编辑器与终端 (1f67c0d9) +- feat(appearance): 输入框与按钮改用中性玻璃质感 (f3c14549) +- feat(appearance): 玻璃外观与自定义壁纸 (46184e96) +- chore: bump version to 0.7.22 (73290287) +- refactor(input): Android IME 兜底收敛为 useAndroidImeSafeTextarea (5b599f46) +- fix(input): Android WebView 全选删除后重建 textarea 节点 (69617707) +- fix(attachment): skill 附件展开后补上类型和技能 ID (1bf39b22) +- fix(message): 渲染用户消息里的 skill 附件 (acf287d6) +- fix(timeline): 文件变更收敛为描述性一行,diff 复用工具卡 (6c9c3387) +- fix(timeline): 压缩消息独立成行,失败提示不再被开关隐藏 (0418523f) +- fix(timeline): 文件 diff 改为行下展开,去掉套娃卡片 (e956ad4e) +- fix(timeline): 回合文件变更改为正文末尾的卡片 (d9ee30c4) +- chore(preview): 增加时间线 UI 的浏览器预览页 (e921d91b) +- fix(timeline): 提示行统一为分隔线样式,并新增默认关闭开关 (af50264c) +- feat(session): 实时处理 session.moved 并渲染移动提示 (45bf6945) +- feat(timeline): 补齐切换记录、压缩排队与回合 diff 的渲染 (8c9e02e1) +- fix(message): 重试卡片显示实时倒计时 (9d5e40c8) +- fix(attachment): file:// 附件地址按段编码 (95e19efc) +- fix(files): 切换预览标签不再改变标签顺序 (5b8be80d) +- fix(events): 切回前台复核半开连接,短时切屏保持懒连接 (f8490164) +- perf(session-list): 目录补拉按官方页大小一次拿满 (9e20a5ea) +- refactor(session-list): 搜索改官方口径,本地匹配 + 会话 ID 回读 (73874945) +- fix(session-list): 搜索补全结果跟服务器绑定,切服务器不串 (1414f17a) +- docs(session-list): 记录 session.list 的实测语义 (9ae6b1e7) +- fix(session-list): 索引没覆盖的旧会话也能搜到 (a60ff2a5) +- fix(session-list): 重连撞上在途拉取时,落地后再补一次 (58282d64) +- fix(session-list): 服务器被删除时释放索引与事件订阅 (6ec8625e) +- fix(session-list): 翻页以当前目录为准,去掉 2000 条硬上限 (ff89068c) +- perf(session-list): 首屏只拉一页 200 条,不再自动续页 (a5fee557) +- fix(session-list): 当前目录被挤出索引时按目录补拉一次 (4b9c4119) +- fix(session-list): 展开量跟随目录,切走再切回来不跳 (eeeee4f9) +- perf(session-list): 每台服务器一份会话索引,切目录不再发请求 (ddec0aad) +- perf(session): 进会话复用列表元信息并预取首屏,恢复动作让出首屏路径 (c8f8bfe6) +- fix(api): 相对 baseUrl 补全为绝对地址 (1c78fed7) + ## [v1.0.9] - 2026-10-21 - build: 去掉 Docker 镜像打包,Linux 改出 AppImage (2e3fba5a) diff --git a/package-lock.json b/package-lock.json index 1ad490b6..5bf567d6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "1.0.9", + "version": "1.0.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "1.0.9", + "version": "1.0.10", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index d374f77e..fc5bd9b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "1.0.9", + "version": "1.0.10", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/preview.html b/preview.html new file mode 100644 index 00000000..6cd2ad85 --- /dev/null +++ b/preview.html @@ -0,0 +1,12 @@ + + + + + + Timeline UI Preview + + +
+ + + diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c0c08a4a..19df3a7d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "1.0.9" +version = "1.0.10" dependencies = [ "futures-util", "log", @@ -2749,6 +2749,7 @@ dependencies = [ "tokio-tungstenite", "tokio-util", "uuid", + "windows 0.61.3", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4c5cd9e8..504f4020 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "1.0.9" +version = "1.0.10" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" @@ -24,7 +24,7 @@ reqwest = { version = "0.12", default-features = false, features = [ ] } serde = { version = "1", features = ["derive"] } serde_json = "1" -tauri = { version = "2", features = ["devtools"] } +tauri = { version = "2", features = ["devtools", "macos-private-api"] } tauri-plugin-decorum = "1.1.1" tauri-plugin-dialog = "2" tauri-plugin-fs = "2" @@ -41,6 +41,23 @@ uuid = { version = "1", features = ["v4"] } [build-dependencies] tauri-build = { version = "2", features = [] } +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D11", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", + "Win32_Graphics_Gdi", + "Win32_UI_WindowsAndMessaging", +] } + +# 依赖在 dev 下也开优化(它们只在首次编译,之后一直用缓存): +# 抓屏路径里用到的图像/系统库在纯 debug 下慢一个数量级。 +# 我们自己的 crate 不开优化——否则每次改一行 Rust 都要重新优化编译几分钟。 +[profile.dev.package."*"] +opt-level = 2 + [profile.release] strip = true lto = true diff --git a/src-tauri/src/app/commands/backdrop.rs b/src-tauri/src/app/commands/backdrop.rs new file mode 100644 index 00000000..fc4291a0 --- /dev/null +++ b/src-tauri/src/app/commands/backdrop.rs @@ -0,0 +1,227 @@ +//! 桌面背景抓取。 +//! +//! 玻璃外观要“窗口背后那张图”,但 WebView2 的 backdrop-filter 采不到窗口外, +//! 所以只能把窗口背后那块桌面抓下来,缩到很小的尺寸交给页面当底图。 +//! 页面拿到的是页面内的图片,我们自己的材质就能正常糊它。 +//! +//! 抓取走 DXGI 桌面复制:桌面在合成器里本来就是一帧 GPU 纹理, +//! 只把窗口那一块复制回 CPU,比 GDI 整屏读回快一个数量级(2ms vs 12ms)。 +//! +//! 把自己排除出捕获这件事不在这里做,由档位开关统一管(见 window_backdrop.rs): +//! 那个标记要等 DWM 重新合成一帧才生效,逐帧开关会一帧干净一帧带影子。 + +#[tauri::command] +pub fn capture_desktop_backdrop( + window: tauri::WebviewWindow, + width: u32, + height: u32, + margin: u32, + toggle: bool, +) -> Result { + #[cfg(target_os = "windows")] + { + let hwnd = window.hwnd().map_err(|err| err.to_string())?; + let raw = hwnd.0 as *mut std::ffi::c_void; + // 这条命令跑在 WebView2 的 COM 回调里,panic 没法 unwind,会直接把进程带走。 + // 兜一层,任何内部错误都退化成「这一帧没变」。 + let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + windows_capture::grab(raw, width, height, margin, toggle) + })) + .unwrap_or_else(|_| { + log::error!("[backdrop] 抓屏内部异常"); + Err("抓屏内部异常".to_string()) + })?; + return Ok(tauri::ipc::Response::new(frame)); + } + + #[cfg(not(target_os = "windows"))] + { + let _ = (window, width, height, margin, toggle); + Err("只有 Windows 支持抓取桌面背景".into()) + } +} + +#[cfg(target_os = "windows")] +mod windows_capture { + use std::ffi::c_void; + use std::sync::Mutex; + + use windows::Win32::Foundation::HWND; + use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, IsIconic, IsWindowVisible}; + + use super::super::backdrop_dxgi::dxgi::Duplication; + + /// 抓窗口背后那块桌面,缩到 `width` × `height` 的 RGBA。 + /// 返回 1 字节表示这一帧桌面没变,页面不用重绘。 + pub fn grab( + hwnd: *mut c_void, + width: u32, + height: u32, + margin: u32, + toggle: bool, + ) -> Result, String> { + if width == 0 || height == 0 || width > 4096 || height > 4096 { + return Err("目标尺寸不合法".into()); + } + let hwnd = HWND(hwnd); + + // 最小化 / 隐藏时抓到的是一团垃圾,直接让前端沿用上一帧 + if !unsafe { IsWindowVisible(hwnd).as_bool() } || unsafe { IsIconic(hwnd).as_bool() } { + return Err("窗口不可见".into()); + } + + let mut rect = windows::Win32::Foundation::RECT::default(); + // SAFETY: hwnd 来自当前 Tauri 窗口,调用期间有效 + unsafe { GetWindowRect(hwnd, &mut rect) }.map_err(|err| err.to_string())?; + let src_w = rect.right - rect.left; + let src_h = rect.bottom - rect.top; + if src_w <= 0 || src_h <= 0 { + return Err("窗口尺寸为 0".into()); + } + // 往外多抓一圈:页面那层模糊的边缘会往外扩散, + // 抓满这一圈,模糊的衰减就落在窗口外面,画面保持 1:1 不用放大。 + let margin = margin as i32; + let left = rect.left - margin; + let top = rect.top - margin; + let grab_w = src_w + margin * 2; + let grab_h = src_h + margin * 2; + + // toggle = true:只在抓这一瞬排除自己,抓完恢复可见(能截图能录屏,但要等一帧合成) + // toggle = false:排除标记已经由窗口模式常驻,这里直接抓(能跑满帧率) + if toggle { + set_exclusion(hwnd, true); + dwm_flush(); + } + let grabbed = capture_region(left, top, grab_w, grab_h); + if toggle { + set_exclusion(hwnd, false); + } + + let t0 = std::time::Instant::now(); + let Some((bgra, cap_w, cap_h)) = grabbed? else { + return Ok(vec![0u8]); + }; + let t_grab = t0.elapsed(); + let pixels = downscale(&bgra, cap_w, cap_h, width, height); + let t_scale = t0.elapsed(); + + if !mark_changed(&pixels) { + return Ok(vec![0u8]); + } + log_cost(src_w, src_h, width, height, t_grab, t_scale - t_grab); + Ok(pixels) + } + + fn set_exclusion(hwnd: HWND, excluded: bool) { + #[link(name = "user32")] + extern "system" { + fn SetWindowDisplayAffinity(hwnd: *mut c_void, affinity: u32) -> i32; + } + const WDA_NONE: u32 = 0; + const WDA_EXCLUDEFROMCAPTURE: u32 = 0x11; + let affinity = if excluded { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }; + let _ = unsafe { SetWindowDisplayAffinity(hwnd.0, affinity) }; + } + + /// 等 DWM 完成一次合成。标记生效需要一帧,不等就会抓到上一帧。 + fn dwm_flush() { + #[link(name = "dwmapi")] + extern "system" { + fn DwmFlush() -> i32; + } + let _ = unsafe { DwmFlush() }; + } + + /// 用 DXGI 抓窗口那块区域。`None` 表示桌面这一帧没变。 + fn capture_region( + left: i32, + top: i32, + width: i32, + height: i32, + ) -> Result, u32, u32)>, String> { + static DUP: Mutex> = Mutex::new(None); + + let mut guard = DUP.lock().map_err(|_| "捕获状态锁坏了".to_string())?; + let cx = left + width / 2; + let cy = top + height / 2; + // 窗口换显示器 / 分辨率变了就重建 + let need_rebuild = match guard.as_ref() { + Some(dup) => { + let (ox, oy) = dup.offset(); + let (ow, oh) = dup.size(); + cx < ox || cy < oy || cx >= ox + ow as i32 || cy >= oy + oh as i32 + } + None => true, + }; + if need_rebuild { + *guard = Some(Duplication::new_for_point(cx, cy)?); + } + let Some(dup) = guard.as_mut() else { + return Ok(None); + }; + + match dup.grab(left, top, width as u32, height as u32) { + Ok(frame) => Ok(frame), + Err(err) => { + // 分辨率切换、显示器热插拔之后会 ACCESS_LOST,丢掉重建 + *guard = None; + Err(err) + } + } + } + + /// 最近邻缩小 + BGRA → RGBA。后面还有一道盒式模糊,锯齿会被抹平。 + fn downscale(bgra: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec { + let mut out = vec![0u8; (dw * dh * 4) as usize]; + if sw == 0 || sh == 0 || dw == 0 || dh == 0 { + return out; + } + // 防御:尺寸对不上时不要越界(这个 panic 会把整个进程带崩) + if bgra.len() < (sw as usize * sh as usize * 4) { + return out; + } + for y in 0..dh { + let sy = (y as u64 * sh as u64 / dh as u64) as u32; + let src_row = (sy * sw) as usize; + let dst_row = (y * dw) as usize; + for x in 0..dw { + let sx = (x as u64 * sw as u64 / dw as u64) as usize; + let si = (src_row + sx) * 4; + let di = (dst_row + x as usize) * 4; + out[di] = bgra[si + 2]; + out[di + 1] = bgra[si + 1]; + out[di + 2] = bgra[si]; + out[di + 3] = 255; + } + } + out + } + + /// 每 120 帧打一条耗时,定位延迟落在哪一段 + fn log_cost(src_w: i32, src_h: i32, w: u32, h: u32, grab: std::time::Duration, scale: std::time::Duration) { + use std::sync::atomic::{AtomicU64, Ordering}; + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n % 120 == 0 { + log::info!( + "[backdrop] src={src_w}x{src_h} -> {w}x{h} grab={:?} scale={:?}", + grab, + scale + ); + } + } + + /// 上一帧的像素,用来判断画面有没有变。变了才发 IPC,没变就发哨兵。 + fn mark_changed(pixels: &[u8]) -> bool { + static LAST: Mutex> = Mutex::new(Vec::new()); + let Ok(mut last) = LAST.lock() else { + return true; + }; + if last.as_slice() == pixels { + return false; + } + last.clear(); + last.extend_from_slice(pixels); + true + } +} diff --git a/src-tauri/src/app/commands/backdrop_dxgi.rs b/src-tauri/src/app/commands/backdrop_dxgi.rs new file mode 100644 index 00000000..2df71d99 --- /dev/null +++ b/src-tauri/src/app/commands/backdrop_dxgi.rs @@ -0,0 +1,209 @@ +//! DXGI 桌面复制。 +//! +//! GDI 抓屏每帧要把整块屏幕像素拷回 CPU(实测 11–15ms), +//! 而桌面在合成器里本来就是一帧 GPU 纹理,DXGI 直接拿。 +//! 这里只把「窗口那一块」复制到一张 staging 纹理上回读, +//! 不碰整屏,也不缩放(缩放和模糊交给后面的 CPU 那一步,那一步才 1.5ms)。 + +#[cfg(target_os = "windows")] +pub mod dxgi { + use windows::core::Interface; + use windows::Win32::Foundation::HMODULE; + use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0}; + use windows::Win32::Graphics::Direct3D11::{ + D3D11_BOX, D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ, + D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING, + D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, + }; + use windows::Win32::Graphics::Dxgi::{ + DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_FRAME_INFO, + IDXGIDevice, IDXGIOutput1, IDXGIOutputDuplication, IDXGIResource, + }; + + pub struct Duplication { + device: ID3D11Device, + context: ID3D11DeviceContext, + dup: IDXGIOutputDuplication, + /// 该输出在虚拟桌面里的左上角 + offset: (i32, i32), + /// 该输出的像素尺寸 + size: (u32, u32), + staging: Option<(ID3D11Texture2D, u32, u32)>, + } + + impl Duplication { + /// 按窗口中心所在的显示器建复制。 + pub fn new_for_point(point_x: i32, point_y: i32) -> Result { + unsafe { + let mut device: Option = None; + let mut context: Option = None; + D3D11CreateDevice( + None, + D3D_DRIVER_TYPE_HARDWARE, + HMODULE::default(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + Some(&[D3D_FEATURE_LEVEL_11_0]), + D3D11_SDK_VERSION, + Some(&mut device), + None, + Some(&mut context), + ) + .map_err(|err| format!("D3D11CreateDevice: {err}"))?; + let device = device.ok_or("没有拿到 D3D11 设备")?; + let context = context.ok_or("没有拿到 D3D11 上下文")?; + let dxgi_device: IDXGIDevice = device.cast().map_err(|err| err.to_string())?; + let adapter = dxgi_device.GetAdapter().map_err(|err| err.to_string())?; + + let mut chosen = None; + let mut index = 0; + while let Ok(output) = adapter.EnumOutputs(index) { + if let Ok(desc) = output.GetDesc() { + let r = desc.DesktopCoordinates; + if point_x >= r.left && point_x < r.right && point_y >= r.top && point_y < r.bottom { + chosen = Some(output); + break; + } + } + index += 1; + } + let output = chosen.ok_or("没找到窗口所在的显示器")?; + let desc = output.GetDesc().map_err(|err| err.to_string())?; + let output1: IDXGIOutput1 = output.cast().map_err(|err| err.to_string())?; + let dup = output1 + .DuplicateOutput(&device) + .map_err(|err| format!("DuplicateOutput: {err}"))?; + let rect = desc.DesktopCoordinates; + Ok(Self { + device, + context, + dup, + offset: (rect.left, rect.top), + size: ((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32), + staging: None, + }) + } + } + + pub fn size(&self) -> (u32, u32) { + self.size + } + + pub fn offset(&self) -> (i32, i32) { + self.offset + } + + /// 抓一块区域,返回 BGRA 字节(每行紧密排列)和**实际**尺寸。 + /// + /// 请求的区域可能有一部分在屏幕外(最大化窗口就是 -8,-8 起), + /// 这里会裁剪,所以返回的宽高可能比请求的小——调用方必须用返回值, + /// 不能拿请求尺寸当图的实际大小。 + /// `Ok(None)` 表示这一帧桌面没变(或暂时拿不到帧),调用方沿用上一帧。 + pub fn grab( + &mut self, + left: i32, + top: i32, + width: u32, + height: u32, + ) -> Result, u32, u32)>, String> { + if width == 0 || height == 0 { + return Ok(None); + } + unsafe { + let mut info = DXGI_OUTDUPL_FRAME_INFO::default(); + let mut resource: Option = None; + match self.dup.AcquireNextFrame(0, &mut info, &mut resource) { + Ok(()) => {} + Err(err) if err.code() == DXGI_ERROR_WAIT_TIMEOUT || err.code() == DXGI_ERROR_ACCESS_LOST => { + return Ok(None); + } + Err(err) => return Err(format!("AcquireNextFrame: {err}")), + } + + let result = (|| -> Result, u32, u32)>, String> { + let resource = resource.ok_or("没有拿到桌面资源")?; + let texture: ID3D11Texture2D = resource.cast().map_err(|err| err.to_string())?; + + // 窗口坐标 → 该输出的本地坐标 + let x = left - self.offset.0; + let y = top - self.offset.1; + let x0 = x.clamp(0, self.size.0 as i32); + let y0 = y.clamp(0, self.size.1 as i32); + let x1 = (x + width as i32).clamp(0, self.size.0 as i32); + let y1 = (y + height as i32).clamp(0, self.size.1 as i32); + let copy_w = (x1 - x0) as u32; + let copy_h = (y1 - y0) as u32; + if copy_w == 0 || copy_h == 0 { + return Ok(None); + } + + let staging = self.staging_texture(copy_w, copy_h)?; + let region = D3D11_BOX { + left: x0 as u32, + top: y0 as u32, + front: 0, + right: x1 as u32, + bottom: y1 as u32, + back: 1, + }; + self.context.CopySubresourceRegion( + &staging, + 0, + 0, + 0, + 0, + &texture, + 0, + Some(®ion), + ); + + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + self.context + .Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped)) + .map_err(|err| format!("Map: {err}"))?; + let mut out = Vec::with_capacity((copy_w * copy_h * 4) as usize); + for row in 0..copy_h { + let src = (mapped.pData as *const u8).add((row * mapped.RowPitch) as usize); + out.extend_from_slice(std::slice::from_raw_parts(src, (copy_w * 4) as usize)); + } + let _ = self.context.Unmap(&staging, 0); + Ok(Some((out, copy_w, copy_h))) + })(); + + let _ = self.dup.ReleaseFrame(); + result + } + } + + fn staging_texture(&mut self, w: u32, h: u32) -> Result { + if let Some((texture, sw, sh)) = &self.staging { + if *sw == w && *sh == h { + return Ok(texture.clone()); + } + } + let desc = D3D11_TEXTURE2D_DESC { + Width: w, + Height: h, + MipLevels: 1, + ArraySize: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_STAGING, + BindFlags: 0, + CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32, + MiscFlags: 0, + }; + let mut texture: Option = None; + unsafe { + self.device + .CreateTexture2D(&desc, None, Some(&mut texture)) + .map_err(|err| format!("CreateTexture2D: {err}"))?; + } + let texture = texture.ok_or("建 staging 纹理失败")?; + self.staging = Some((texture.clone(), w, h)); + Ok(texture) + } + } +} diff --git a/src-tauri/src/app/commands/mod.rs b/src-tauri/src/app/commands/mod.rs index cdea9abb..c8de646e 100644 --- a/src-tauri/src/app/commands/mod.rs +++ b/src-tauri/src/app/commands/mod.rs @@ -1,4 +1,7 @@ +pub mod backdrop; +pub mod backdrop_dxgi; pub mod bridge; +pub mod window_backdrop; #[cfg(not(target_os = "android"))] pub mod opencode; #[cfg(not(target_os = "android"))] diff --git a/src-tauri/src/app/commands/utils.rs b/src-tauri/src/app/commands/utils.rs index 8427d08b..641a2cae 100644 --- a/src-tauri/src/app/commands/utils.rs +++ b/src-tauri/src/app/commands/utils.rs @@ -31,7 +31,9 @@ pub async fn open_new_window(app: tauri::AppHandle, directory: Option) { #[cfg(not(target_os = "android"))] #[tauri::command] pub fn desktop_window_ready(window: tauri::Window) -> Result<(), String> { - crate::app::mark_window_ready(&window).map_err(|err| err.to_string()) + crate::app::mark_window_ready(&window).map_err(|err| err.to_string())?; + super::window_backdrop::reapply_on_shown(&window); + Ok(()) } /// 获取拖入路径的基础信息,用于前端区分文件/目录并生成 @ 引用。 diff --git a/src-tauri/src/app/commands/window_backdrop.rs b/src-tauri/src/app/commands/window_backdrop.rs new file mode 100644 index 00000000..5d96e92c --- /dev/null +++ b/src-tauri/src/app/commands/window_backdrop.rs @@ -0,0 +1,281 @@ +//! 窗口背景模式。 +//! +//! 玻璃外观在桌面端有三种底: +//! +//! - `native`:窗口透明,底图交给系统材质(DWM acrylic)。 +//! - `page`:窗口不透明,页面自己画背景(跟着桌面的抓屏、或用户选的壁纸)。 +//! - `none`:不透明兜底色,没有玻璃底。 +//! +//! `page` 模式必须把 WebView2 的背景色设成不透明:窗口背景透明时 +//! Chromium 建不出 backdrop root,页面里所有 `backdrop-filter` 都会静默失效, +//! 弹窗和菜单就只剩一层色。这也是之前 dialog 一直没质感的原因。 + + +/// 当前窗口是否挂着系统材质,用于首帧后补一次。 +#[cfg(target_os = "windows")] +static GLASS_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// DWM 材质调用。 +/// +/// 不用 window_vibrancy 是有原因的:它在 Win11 上只要系统版本够就返回 Ok, +/// 根本不看 DwmSetWindowAttribute 的结果,前端因此误以为材质挂上了。 +/// 这里自己调,把 HRESULT 记下来,挂没挂上一看日志就知道。 +#[cfg(target_os = "windows")] +mod dwm { + use std::ffi::c_void; + + #[repr(C)] + struct Margins { + cx_left_width: i32, + cx_right_width: i32, + cy_top_height: i32, + cy_bottom_height: i32, + } + + #[repr(C)] + struct BlurBehind { + flags: u32, + enable: i32, + blur_region: *mut c_void, + transition_on_maximized: i32, + } + + const DWM_BB_ENABLE: u32 = 0x1; + const DWMWA_SYSTEMBACKDROP_TYPE: u32 = 38; + /// 1 = 关,2 = Mica(只取壁纸),3 = Acrylic(连后面窗口一起糊),4 = Tabbed + const DWMSBT_NONE: i32 = 1; + const DWMSBT_TRANSIENTWINDOW: i32 = 3; + + #[link(name = "user32")] + extern "system" { + fn GetWindowLongPtrW(hwnd: *mut c_void, index: i32) -> isize; + fn SetWindowLongPtrW(hwnd: *mut c_void, index: i32, value: isize) -> isize; + } + + const GWL_STYLE: i32 = -16; + /// WS_CAPTION = WS_BORDER | WS_DLGFRAME + const WS_CAPTION: isize = 0x00C0_0000; + + /// 去掉窗口的标题栏样式。 + /// + /// 我们把 DWM 边框扩到了整个客户区,只要窗口还带 WS_CAPTION, + /// DWM 就会在客户区里画原生标题栏(最小化/最大化/关闭)。 + /// 玻璃下标题栏是透明的,这三个按钮就从背后透出来,看着像多了一套。 + fn strip_caption(hwnd: *mut c_void) { + unsafe { + let style = GetWindowLongPtrW(hwnd, GWL_STYLE); + if style & WS_CAPTION != 0 { + SetWindowLongPtrW(hwnd, GWL_STYLE, style & !WS_CAPTION); + log::info!("[window] stripped WS_CAPTION: {style:#x} -> {:#x}", style & !WS_CAPTION); + } + } + } + + #[link(name = "dwmapi")] + extern "system" { + fn DwmSetWindowAttribute( + hwnd: *mut c_void, + attribute: u32, + value: *const c_void, + size: u32, + ) -> i32; + fn DwmExtendFrameIntoClientArea(hwnd: *mut c_void, margins: *const Margins) -> i32; + fn DwmEnableBlurBehindWindow(hwnd: *mut c_void, data: *const BlurBehind) -> i32; + } + + fn backdrop(hwnd: *mut c_void, kind: i32) -> i32 { + unsafe { + DwmSetWindowAttribute( + hwnd, + DWMWA_SYSTEMBACKDROP_TYPE, + &kind as *const _ as *const c_void, + std::mem::size_of::() as u32, + ) + } + } + + pub fn apply(hwnd: *mut c_void) -> bool { + strip_caption(hwnd); + // tao 为了做全透明,给窗口挂过旧的 blur-behind(空模糊区)。 + // 那个状态和系统材质互斥,先关掉,否则材质永远不会出现。 + let blur_off = BlurBehind { + flags: DWM_BB_ENABLE, + enable: 0, + blur_region: std::ptr::null_mut(), + transition_on_maximized: 0, + }; + let clear = unsafe { DwmEnableBlurBehindWindow(hwnd, &blur_off) }; + + // 材质画在 DWM 边框里,无装饰窗口不扩这一下就没地方落笔 + let margins = Margins { + cx_left_width: -1, + cx_right_width: -1, + cy_top_height: -1, + cy_bottom_height: -1, + }; + let extend = unsafe { DwmExtendFrameIntoClientArea(hwnd, &margins) }; + + let applied = backdrop(hwnd, DWMSBT_TRANSIENTWINDOW); + log::info!( + "[window] dwm acrylic: blur-behind={clear:#x} extend-frame={extend:#x} backdrop={applied:#x}" + ); + applied == 0 + } + + pub fn clear(hwnd: *mut c_void) { + let result = backdrop(hwnd, DWMSBT_NONE); + log::info!("[window] dwm backdrop cleared: {result:#x}"); + } +} + +/// 开关「窗口是否参与屏幕捕获」。 +/// +/// 自绘档要靠抓屏当背景,抓的时候必须把自己摘掉;但这个标记要等 DWM +/// 重新合成一帧才生效,逐帧开关会一帧干净一帧带影子(看起来在闪), +/// 所以它跟着档位常驻。代价:自绘档开着的时候,应用不会出现在截图/录屏里。 +#[cfg(target_os = "windows")] +fn apply_capture_exclusion(hwnd: *mut std::ffi::c_void, excluded: bool) { + #[link(name = "user32")] + extern "system" { + fn SetWindowDisplayAffinity(hwnd: *mut std::ffi::c_void, affinity: u32) -> i32; + } + const WDA_NONE: u32 = 0; + const WDA_EXCLUDEFROMCAPTURE: u32 = 0x11; + let affinity = if excluded { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }; + let ok = unsafe { SetWindowDisplayAffinity(hwnd, affinity) }; + log::info!("[window] capture excluded={excluded} ({ok})"); +} + +/// 首帧之前窗口是隐藏的,材质可能没落到可见窗口上,这里补一次。 +pub fn reapply_on_shown(window: &tauri::Window) { + #[cfg(target_os = "windows")] + if GLASS_ENABLED.load(std::sync::atomic::Ordering::Relaxed) { + if let Ok(hwnd) = window.hwnd() { + dwm::apply(hwnd.0 as *mut std::ffi::c_void); + } + } + #[cfg(not(target_os = "windows"))] + let _ = window; +} + +#[derive(Clone, Copy, PartialEq)] +pub enum BackdropMode { + Native, + Page, + None, +} + +impl BackdropMode { + pub fn parse(value: &str) -> Self { + match value { + "native" => BackdropMode::Native, + "page" => BackdropMode::Page, + _ => BackdropMode::None, + } + } +} + +fn parse_hex_color(value: &str) -> (u8, u8, u8) { + let hex = value.trim_start_matches('#'); + if hex.len() < 6 { + return (16, 16, 18); + } + let parse = |range: std::ops::Range| u8::from_str_radix(&hex[range], 16).unwrap_or(16); + (parse(0..2), parse(2..4), parse(4..6)) +} + +/// 切换窗口背景模式,返回系统材质是否真的挂上(只有 `native` 有意义)。 +#[cfg(not(target_os = "android"))] +#[tauri::command] +pub fn set_window_backdrop( + window: tauri::WebviewWindow, + mode: String, + color: String, +) -> bool { + let mode = BackdropMode::parse(&mode); + let (r, g, b) = parse_hex_color(&color); + + #[cfg(target_os = "windows")] + { + use std::sync::atomic::Ordering; + + let Ok(hwnd) = window.hwnd() else { + log::warn!("[window] no hwnd, skip backdrop"); + return false; + }; + let raw = hwnd.0 as *mut std::ffi::c_void; + + match mode { + BackdropMode::Native => { + apply_capture_exclusion(raw, false); + GLASS_ENABLED.store(true, Ordering::Relaxed); + let _ = window.set_background_color(Some(tauri::window::Color(0, 0, 0, 0))); + let applied = dwm::apply(raw); + log::info!("[window] backdrop=native acrylic({applied})"); + return applied; + } + BackdropMode::Page => { + GLASS_ENABLED.store(false, Ordering::Relaxed); + dwm::clear(raw); + // 不透明的 webview 背景:让页面里的 backdrop-filter 重新工作 + match window.set_background_color(Some(tauri::window::Color(r, g, b, 255))) { + Ok(()) => log::info!("[window] webview background set {r},{g},{b}"), + Err(err) => log::warn!("[window] set_background_color failed: {err}"), + } + // 排除标记由抓屏那一步临时开关(设完 DwmFlush 再抓), + // 这里不常驻,否则应用会从所有截图/录屏里消失。 + apply_capture_exclusion(raw, false); + log::info!("[window] backdrop=page"); + return true; + } + BackdropMode::None => { + GLASS_ENABLED.store(false, Ordering::Relaxed); + dwm::clear(raw); + let _ = window.set_background_color(Some(tauri::window::Color(r, g, b, 255))); + apply_capture_exclusion(raw, false); + log::info!("[window] backdrop=none"); + return true; + } + } + } + + #[cfg(target_os = "macos")] + { + use tauri::window::{Color, Effect, EffectsBuilder}; + match mode { + BackdropMode::Native => { + let _ = window.set_background_color(Some(Color(0, 0, 0, 0))); + let applied = window + .set_effects( + EffectsBuilder::new() + .effect(Effect::UnderWindowBackground) + .build(), + ) + .is_ok(); + log::info!("[window] backdrop=native vibrancy({applied})"); + return applied; + } + _ => { + let _ = window.set_effects(None); + let _ = window.set_background_color(Some(Color(r, g, b, 255))); + return true; + } + } + } + + #[cfg(target_os = "linux")] + { + let _ = window.set_background_color(Some(if mode == BackdropMode::Native { + tauri::window::Color(0, 0, 0, 0) + } else { + tauri::window::Color(r, g, b, 255) + })); + true + } + + #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] + { + let _ = (window, r, g, b, mode); + false + } +} diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs index 1be709c7..c36411e5 100644 --- a/src-tauri/src/app/mod.rs +++ b/src-tauri/src/app/mod.rs @@ -291,7 +291,15 @@ pub(crate) fn create_new_window(app: &tauri::AppHandle, directory: Option>( window_builder: tauri::WebviewWindowBuilder<'a, R, M>, ) -> tauri::WebviewWindowBuilder<'a, R, M> { - let window_builder = window_builder; + // 窗口本身保持透明,是否真的透出桌面由前端决定(页面画不画底色)。 + let window_builder = window_builder.transparent(true); + + // Windows:透明窗口如果没给背景色,WebView2 在窗口重新激活时会先出一帧 + // 默认白色底再补页面内容,看着就是闪一下白。这里给窗口表面一个深色底, + // 只在 Windows 生效,不影响 macOS 的系统材质。 + #[cfg(target_os = "windows")] + let window_builder = window_builder + .background_color(tauri::window::Color(16, 16, 20, 255)); #[cfg(target_os = "macos")] let window_builder = window_builder @@ -471,6 +479,8 @@ pub fn run() { commands::utils::get_dropped_paths_info, commands::utils::open_new_window, commands::utils::desktop_window_ready, + commands::window_backdrop::set_window_backdrop, + commands::backdrop::capture_desktop_backdrop, // 附件上传:Rust 侧流式发送(桌面端拿不到 webview 的上传进度) commands::upload::upload_attachment, commands::opencode::check_opencode_service, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e8cd8875..46229e6e 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.9", + "version": "1.0.10", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", @@ -11,6 +11,7 @@ }, "app": { "withGlobalTauri": true, + "macOSPrivateApi": true, "windows": [ { "label": "main", @@ -20,6 +21,7 @@ "height": 600, "titleBarStyle": "Overlay", "hiddenTitle": true, + "transparent": true, "trafficLightPosition": { "x": 12, "y": 14 diff --git a/src/App.tsx b/src/App.tsx index 69bbd12d..063756b4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -41,9 +41,13 @@ import { serverStore } from './store/serverStore' import { initNotificationSound } from './utils/notificationSoundBridge' import { useSessionTerminals } from './hooks/useSessionTerminals' import { useServerStore } from './hooks/useServerStore' +import { prefetchSessionMessages } from './api/messagePrefetch' +import { isCompleteSessionInfo, sessionInfoCache } from './store/sessionInfoCache' +import { INITIAL_MESSAGE_LIMIT } from './constants' import type { SettingsTab } from './features/settings/SettingsDialog' import { isTauri, isTauriMobile } from './utils/tauri' import { InternalDragLayer } from './components/InternalDragLayer' +import { LiveBackdrop } from './features/appearance/LiveBackdrop' const SettingsDialog = lazy(() => import('./features/settings/SettingsDialog').then(module => ({ default: module.SettingsDialog })), @@ -224,7 +228,15 @@ function App() { (session: { id: string; serverId?: string; directory?: string; location?: { directory?: string } }) => { const paneId = paneLayout.focusedPaneId ?? paneLayoutStore.getFocusedPaneId() if (!paneId) return - const sessionKey = makeSessionKey(session.serverId ?? serverStore.getActiveServerId(), session.id) + const serverId = session.serverId ?? serverStore.getActiveServerId() + const sessionKey = makeSessionKey(serverId, session.id) + + // 点击即出发:把列表里已有的元信息留给会话页(省掉 session.get), + // 同时预取首屏消息。两者都只是写缓存 / 发请求,不等待结果, + // 页面照常立刻导航(官方 home/sessions/controller.tsx:348 同款时机)。 + if (isCompleteSessionInfo(session)) sessionInfoCache.remember(serverId, session) + prefetchSessionMessages(serverId, session.id, INITIAL_MESSAGE_LIMIT) + // v2 的目录在 location.directory;扁平 directory 只有命令面板等少数路径会带。 // 全局下打开主目录会话不写 dir,否则选择器会从「全局」跳成该文件夹。 const directory = directoryForSessionOpen(readRouteDirectory(), sessionRouteDirectory(session), globalDirectory) @@ -234,7 +246,9 @@ function App() { ) // 命令面板混合搜索的会话/文件数据源(官方 palette.ts 同款: - // 命令之外还能搜到会话与文件) + // 命令之外还能搜到会话与文件)。 + // 面板只读 id/title/directory,所以这里只挑这三个字段;点击时再按 id + // 从 allSessions 取回完整记录(见 handlePaletteOpenSession)。 const { sessions: allSessions } = useSessionContext() const paletteSessions = useMemo( () => @@ -245,6 +259,16 @@ function App() { })), [allSessions], ) + + // 面板只回传 id + directory(它并不关心完整记录),这里按 id 补回列表里的 + // 完整 SessionInfo:元信息交接缓存与目录解析都依赖完整字段。 + const handlePaletteOpenSession = useCallback( + (session: { id: string; directory?: string }) => { + const full = allSessions.find(item => item.id === session.id) + handleSelectSession(full ?? session) + }, + [allSessions, handleSelectSession], + ) const handlePaletteOpenFile = useCallback( (path: string) => { const name = path.split(/[\\/]/).pop() ?? path @@ -919,87 +943,165 @@ function App() { handleToggleFocusedPaneFullscreen, ]) - const { showCloseDialog, handleCloseDialogConfirm, handleCloseDialogCancel, hasUnsavedChanges } = useCloseServiceDialog() + const { showCloseDialog, handleCloseDialogConfirm, handleCloseDialogCancel, hasUnsavedChanges } = + useCloseServiceDialog() return ( -
- - - -
- {isMobilePanelLayout ? ( - <> -
-
+ {/* 桌面背景层放在 .app-shell 之前:两者都是定位元素, + 靠文档顺序决定谁在上,图要垫在整层染色底下 */} + +
+ + + +
+ {isMobilePanelLayout ? ( + <> +
- -
+
+ +
+ +
+
+
+ +
+ + -
+ {sidebarExpanded && ( +
+ +
+ +
+
+ + + + ) : ( + <> + + +
- - {sidebarExpanded && ( -
- -
-
-
- - - - ) : ( - <> - - -
-
-
- -
- -
- - -
- - )} - - -
- - - - setCommandPaletteOpen(false)} - commands={commands} - directory={focusedDirectory || currentDirectory || undefined} - sessions={paletteSessions} - onOpenSession={handleSelectSession} - onOpenFile={handlePaletteOpenFile} - /> - - - - - -
-
+ + )} + + + + + + + setCommandPaletteOpen(false)} + commands={commands} + directory={focusedDirectory || currentDirectory || undefined} + sessions={paletteSessions} + onOpenSession={handlePaletteOpenSession} + onOpenFile={handlePaletteOpenFile} + /> + + + + + + + + ) } diff --git a/src/api/events.test.ts b/src/api/events.test.ts index 6234597c..51e65a4b 100644 --- a/src/api/events.test.ts +++ b/src/api/events.test.ts @@ -69,6 +69,11 @@ function v2Event(type: string, data: unknown) { return { id: `evt-${type}`, created: Date.now(), type, data } } +/** jsdom 不提供真实的可见性切换:临时覆盖 document.visibilityState 再派发事件 */ +function setDocumentVisibility(state: 'visible' | 'hidden') { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + describe('v2 event dispatch', () => { beforeEach(() => { vi.resetModules() @@ -363,6 +368,88 @@ describe('v2 event dispatch', () => { } }) + /** + * 切后台再切回来(Issue #184):后台期间 JS 定时器被冻结,看门狗不 tick, + * 半开连接的状态会一直停在 connected。回到前台必须主动复核一次静默时长, + * 否则用户要等最多 45s 才看到刷新。 + * + * 但复核不能见 connected 就重连:短时间切屏、连接还活着的时候应该保持 + * 懒连接,所以静默不足一个心跳阈值时什么都不做。 + */ + it('keeps the connection when the app returns quickly from background', async () => { + vi.useFakeTimers() + try { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, getServerConnectionInfo } = await import('./events') + const unsubscribe = subscribeToServerEvents('test-server', {}) + await Promise.resolve() + + harnesses[0].emit(v2Event('session.idle', { sessionID: 's1' })) + await vi.advanceTimersByTimeAsync(0) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + // 短暂切屏:累计静默远小于一个心跳阈值 + await vi.advanceTimersByTimeAsync(5_000) + setDocumentVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) + setDocumentVisibility('visible') + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(5_000) + + expect(subscribeMock.mock.calls.length).toBe(1) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + unsubscribe() + } finally { + setDocumentVisibility('visible') + vi.useRealTimers() + } + }) + + it('reconnects on returning from a long background instead of waiting for the watchdog', async () => { + vi.useFakeTimers() + try { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, getServerConnectionInfo } = await import('./events') + const unsubscribe = subscribeToServerEvents('test-server', {}) + await Promise.resolve() + + harnesses[0].emit(v2Event('session.idle', { sessionID: 's1' })) + await vi.advanceTimersByTimeAsync(0) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + // 后台期间心跳停了,但还没到看门狗阈值(45s)——确保救场的不是看门狗 + await vi.advanceTimersByTimeAsync(25_000) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + setDocumentVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) + setDocumentVisibility('visible') + document.dispatchEvent(new Event('visibilitychange')) + + // 复核窗口 + 半开连接复位兜底 + 退避重连 + await vi.advanceTimersByTimeAsync(3_000) + await vi.advanceTimersByTimeAsync(6_000) + + expect(subscribeMock.mock.calls.length).toBeGreaterThanOrEqual(2) + unsubscribe() + } finally { + setDocumentVisibility('visible') + vi.useRealTimers() + } + }) + /** * 端点变更重连必须广播 onReconnected:否则订阅者不做补偿拉取, * WSL 端口变化等场景下状态/权限/消息全部陈旧。 diff --git a/src/api/events.ts b/src/api/events.ts index 072c3fe7..45ac74fd 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -81,6 +81,8 @@ const endpointReconnectFlags = new Map() let lifecycleListenersRegistered = false let isInBackground = false let keepaliveTimer: ReturnType | null = null +/** 切回前台后的静默复核定时器(见 RESUME_PROBE_DELAY_MS) */ +let resumeProbeTimer: ReturnType | null = null // ============================================ // 常量 @@ -116,6 +118,13 @@ const CONNECT_STALL_TIMEOUT = 15_000 * 刚收到心跳就被误判。 */ const ONLINE_RESUME_SILENCE_MS = 20_000 +/** + * 切回前台后的静默复核延迟(Issue #184)。 + * + * 后台期间 JS 定时器会被冻结,回到前台时「静默时长」天然偏大,不能立刻 + * 据此判死连接——先留一小段时间让恢复后缓冲的事件/心跳落地,再复核。 + */ +const RESUME_PROBE_DELAY_MS = 2_000 const DEFAULT_CONNECTION_INFO: ConnectionInfo = { state: 'disconnected', @@ -207,8 +216,8 @@ function getReconnectDelay(attempt: number): number { // splice 掉 id >= to 的消息(data.ts:1076-1092),本端没做,因此 // 多客户端同时操作时可能不同步。单客户端使用不受影响。 // session.moved -// → 官方会插入 location-switched 消息并更新会话 location;本端切换 -// worktree 走的是整表重拉,因此没做。**已知偏差**,同上属多客户端场景。 +// → 已接入:更新会话 location 并插入 location-switched 消息 +// (官方 data.ts 同款;消息流里显示为“移动”提示行)。 // filesystem.changed // → 真机验证(v2.0.14):在监听目录里创建/修改/删除文件,12 秒内 // **没有**收到该事件(只有 server.connected)。因此"没消费它"目前 @@ -703,6 +712,65 @@ function disconnectServerConnection(conn: ServerConnection): void { // 生命周期 / keepalive // ============================================ +/** + * 掐断半开连接,交给重连循环。 + * + * abort 后底层 fetch 通常会让 for-await 退出;但挂起的读可能不认 abort, + * isConnecting 会卡在 true 吞掉所有重连入口。5s 后仍卡在同一代次就作废 + * 本代次强制复位(与看门狗的同款兜底)。 + */ +function dropSilentConnection(conn: ServerConnection): void { + conn.watchdogDrop = true + conn.controller?.abort() + const generation = conn.generation + setTimeout(() => { + if (generation !== conn.generation) return + if (!conn.isConnecting) return + conn.generation += 1 + conn.isConnecting = false + conn.watchdogDrop = false + conn.connectStartedAt = 0 + updateConnectionState(conn.serverId, { state: 'disconnected' }) + scheduleReconnect(conn) + }, 5_000) +} + +/** + * 连接自愈:网络恢复(online)与切回前台(visibilitychange)共用。 + * + * - 没连上:立刻建连,不等退避定时器; + * - 状态还是 connected 但已静默超过一个心跳:说明是半开连接,主动掐断重连。 + * + * 状态停在 connected 不等于连着:断网时 TCP 常常是半开的——流既不报错也 + * 不结束,状态就一直挂着,只能等看门狗 45s 才发现。网络恢复 / 回到前台 + * 都是外部事实,此时按「静默超过一个心跳就判可疑」主动校准,而不是相信 + * state === 'connected'。阈值取得比看门狗短得多:断网期间心跳必然收不到, + * 恢复后按心跳间隔算早该有几个了。 + * + * 静默不足阈值的直接放过——短时间切屏、网络没变时保持懒连接(Issue #184)。 + */ +function revalidateConnections(): void { + for (const conn of connections.values()) { + if (conn.subscribers.size === 0) continue + + if (conn.info.state !== 'connected') { + if (conn.isConnecting) continue + // 退避定时器可能排到 30s 后,回前台时没有干等的必要 + if (conn.reconnectTimer) { + clearTimeout(conn.reconnectTimer) + conn.reconnectTimer = null + } + connectServer(conn.serverId) + continue + } + + const silentFor = Date.now() - conn.info.lastEventTime + if (conn.info.lastEventTime > 0 && silentFor > ONLINE_RESUME_SILENCE_MS) { + dropSilentConnection(conn) + } + } +} + function registerLifecycleListeners(): void { if (lifecycleListenersRegistered) return if (typeof document === 'undefined') return @@ -712,45 +780,28 @@ function registerLifecycleListeners(): void { isInBackground = document.visibilityState === 'hidden' if (isInBackground) { startBackgroundKeepalive() - } else { - stopBackgroundKeepalive() + return } + + /** + * 后台期间 JS 定时器会被冻结,看门狗不会 tick;回到前台若连接已是半开, + * 状态还停在 connected,用户要等最多 45s 才看到界面恢复。 + * + * 先留一个很短的窗口让恢复后缓冲的事件/心跳落地,再复核静默时长: + * 连接好好的时候,不该因为「后台没跑定时器」就白重连一次。 + */ + stopBackgroundKeepalive() + if (resumeProbeTimer) clearTimeout(resumeProbeTimer) + resumeProbeTimer = setTimeout(() => { + resumeProbeTimer = null + // 复核前又切走了:交给后台 keepalive,别在这里抢先重连 + if (document.visibilityState === 'hidden') return + revalidateConnections() + }, RESUME_PROBE_DELAY_MS) }) window.addEventListener('online', () => { - for (const conn of connections.values()) { - if (conn.subscribers.size === 0) continue - - if (conn.info.state !== 'connected') { - connectServer(conn.serverId) - continue - } - - /** - * 状态停在 connected 不等于连着:断网时 TCP 常常是半开的——流既不报错 - * 也不结束,状态就一直挂着,直到看门狗 45s 后才发现。等那么久,用户看到 - * 的就是「网回来了但界面不动,得刷新」。 - * - * 网络恢复是外部事实:此时若已有一段时间没收到任何字节(含心跳), - * 就当作可疑连接主动掐断重连。阈值取得比看门狗短得多——断网期间心跳 - * 必然收不到,恢复后按心跳间隔算早该有几个了。 - */ - const silentFor = Date.now() - conn.info.lastEventTime - if (conn.info.lastEventTime > 0 && silentFor > ONLINE_RESUME_SILENCE_MS) { - conn.watchdogDrop = true - conn.controller?.abort() - setTimeout(() => { - if (conn.isConnecting) { - conn.generation += 1 - conn.isConnecting = false - conn.watchdogDrop = false - conn.connectStartedAt = 0 - updateConnectionState(conn.serverId, { state: 'disconnected' }) - scheduleReconnect(conn) - } - }, 5_000) - } - } + revalidateConnections() }) } diff --git a/src/api/http.test.ts b/src/api/http.test.ts index 99ee10be..11bba741 100644 --- a/src/api/http.test.ts +++ b/src/api/http.test.ts @@ -1,5 +1,34 @@ import { describe, expect, it } from 'vitest' -import { buildQueryString } from './http' +import { buildQueryString, toAbsoluteBaseUrl } from './http' + +// ============================================ +// toAbsoluteBaseUrl 测试 +// ============================================ + +describe('toAbsoluteBaseUrl', () => { + it('resolves a same-origin prefix against the page origin', () => { + expect(toAbsoluteBaseUrl('/api')).toBe(`${window.location.origin}/api`) + }) + + it('strips trailing slashes from a resolved relative URL', () => { + expect(toAbsoluteBaseUrl('/api/')).toBe(`${window.location.origin}/api`) + }) + + it('resolves a protocol-relative URL against the page protocol', () => { + expect(toAbsoluteBaseUrl('//example.com/api')).toBe(`${window.location.protocol}//example.com/api`) + }) + + it('leaves absolute URLs unchanged', () => { + expect(toAbsoluteBaseUrl('http://127.0.0.1:4096')).toBe('http://127.0.0.1:4096') + expect(toAbsoluteBaseUrl('https://opencode.example.com:51133/api')).toBe( + 'https://opencode.example.com:51133/api', + ) + }) + + it('returns an empty value unchanged', () => { + expect(toAbsoluteBaseUrl('')).toBe('') + }) +}) // ============================================ // buildQueryString 测试 diff --git a/src/api/http.ts b/src/api/http.ts index dd04413e..0deefff8 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -5,13 +5,38 @@ import { serverStore, makeBasicAuthHeader } from '../store/serverStore' +/** + * 把相对 API 地址补成绝对地址。 + * + * `@opencode/client` 内部用 `new URL(options.baseUrl)` 构造请求地址, + * 只接受绝对 URL。Docker / standalone 镜像把 `VITE_API_BASE_URL` 设为 + * 同源前缀 `/api`,原样交给 SDK 会在**发请求前**抛 `Invalid URL`: + * 健康检查走原生 fetch(支持相对路径)显示在线,但会话、模型、消息、 + * 终端等所有 SDK 请求全部失败。 + * + * 这里按当前页面 origin 补全,既保留反代下的 `/api` 前缀部署方式, + * 也兼容 Tauri / 桌面端直接配置绝对地址的场景。 + */ +export function toAbsoluteBaseUrl(baseUrl: string): string { + if (!baseUrl) return baseUrl + // 已是绝对 URL(带 scheme)就原样返回,不去尾部斜杠,避免改掉用户配置 + if (/^[a-z][a-z\d+.-]*:\/\//i.test(baseUrl)) return baseUrl + if (typeof window === 'undefined') return baseUrl + // file:// 等非标准页面的 origin 是字符串 'null',不能作为 URL base + const origin = window.location.origin + if (!origin || origin === 'null') return baseUrl + return new URL(baseUrl, origin).toString().replace(/\/+$/, '') +} + /** * 获取 API Base URL * 优先使用 serverStore 中的活动服务器,回退到常量 + * 返回值保证是绝对地址(SDK / PTY 都要求完整 URL) * @param serverId 指定服务器(缺省用活动服务器) */ export function getApiBaseUrl(serverId?: string): string { - return serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) } /** diff --git a/src/api/messagePrefetch.test.ts b/src/api/messagePrefetch.test.ts new file mode 100644 index 00000000..d0539838 --- /dev/null +++ b/src/api/messagePrefetch.test.ts @@ -0,0 +1,96 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { messageStore } from '../store/messageStore' +import { makeSessionKey } from '../utils/sessionKey' + +const { getSessionMessagesPageMock } = vi.hoisted(() => ({ getSessionMessagesPageMock: vi.fn() })) + +vi.mock('./message', () => ({ + getSessionMessagesPage: (...args: unknown[]) => getSessionMessagesPageMock(...args), +})) + +const { + clearSessionMessagesPrefetch, + prefetchSessionMessages, + takeSessionMessagesPrefetch, +} = await import('./messagePrefetch') + +const SERVER = 'local' +const SESSION = 'ses_a' +const LIMIT = 20 + +const emptyPage = { messages: [], nextCursor: null } + +describe('messagePrefetch', () => { + beforeEach(() => { + clearSessionMessagesPrefetch() + getSessionMessagesPageMock.mockReset() + getSessionMessagesPageMock.mockResolvedValue(emptyPage) + }) + + it('预取后会话页取走同一个请求,不会重发', async () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + const taken = takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + + expect(taken).toBeDefined() + await expect(taken).resolves.toEqual(emptyPage) + expect(getSessionMessagesPageMock).toHaveBeenCalledTimes(1) + expect(getSessionMessagesPageMock).toHaveBeenCalledWith(SESSION, { limit: LIMIT }, SERVER) + }) + + it('一次性:取走后再次获取为 undefined(由调用方正常请求)', () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('重复预取复用同一个请求(连点列表不会打两次)', async () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + await takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + expect(getSessionMessagesPageMock).toHaveBeenCalledTimes(1) + }) + + it('未预取时返回 undefined', () => { + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('按服务器与会话隔离', () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + expect(takeSessionMessagesPrefetch('remote', SESSION, LIMIT)).toBeUndefined() + expect(takeSessionMessagesPrefetch(SERVER, 'ses_other', LIMIT)).toBeUndefined() + }) + + it('会话已有可渲染缓存时不预取(切过去根本不会请求)', () => { + messageStore.setMessages(makeSessionKey(SERVER, SESSION), [], { directory: '/workspace/demo' }) + messageStore.setMessages( + makeSessionKey(SERVER, SESSION), + [{ id: 'msg-1', type: 'user', text: 'hi', time: { created: 1 } }] as never, + { directory: '/workspace/demo' }, + ) + + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + expect(getSessionMessagesPageMock).not.toHaveBeenCalled() + messageStore.clearSession(makeSessionKey(SERVER, SESSION)) + }) + + it('请求失败会清理槽位,且不产生 unhandled rejection', async () => { + getSessionMessagesPageMock.mockRejectedValueOnce(new Error('boom')) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + // 没人取走:等待微任务让 catch 跑道 + await Promise.resolve() + await Promise.resolve() + + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('取走失败请求时调用方仍能拿到真实错误', async () => { + const failure = new Error('boom') + getSessionMessagesPageMock.mockRejectedValueOnce(failure) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + await expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).rejects.toBe(failure) + }) +}) diff --git a/src/api/messagePrefetch.ts b/src/api/messagePrefetch.ts new file mode 100644 index 00000000..ff53320d --- /dev/null +++ b/src/api/messagePrefetch.ts @@ -0,0 +1,100 @@ +// ============================================ +// 会话首屏消息预取 +// +// 点击列表项到 ChatPane 的 effect 真正执行之间,隔着一次 React 提交。 +// 官方 app 在点击回调里就发出 `message.sync`(home/sessions/controller.tsx:348), +// 这里做同一件事:导航入口先发请求,会话页再「取走」这个 in-flight promise。 +// +// 复用而不是并行重发:会话页拿到的是同一个请求,不会因为预取而多打一次。 +// 未被取走的预取在 TTL 后自然失效;promise 上的 catch 保证不会产生 +// unhandled rejection(调用方 await 时仍能拿到真实错误)。 +// +// TTL 取「点击 → effect 执行」这个量级(10s),而不是元信息缓存的 30s: +// 这里存的是会话内容,宁可偶尔多打一次请求,也不要让用户看到十秒前 +// 的转写(期间可能正在流式输出)。 +// ============================================ + +import { getSessionMessagesPage } from './message' +import { messageStore } from '../store/messageStore' +import { makeSessionKey, splitSessionKey } from '../utils/sessionKey' + +type MessagePage = Awaited> + +const TTL_MS = 10_000 +const MAX_INFLIGHT = 32 + +interface Entry { + promise: Promise + startedAt: number +} + +const inflight = new Map() + +/** + * 归一化会话标识:导航入口传原始 id(列表项的 session.id), + * 会话页传复合 key(serverId::sessionId),两者必须落到同一个槽位。 + */ +function normalizeTarget(serverId: string, sessionId: string): { serverId: string; sessionId: string } { + return sessionId.includes('::') ? splitSessionKey(sessionId) : { serverId, sessionId } +} + +function cacheKey(serverId: string, sessionId: string, limit: number): string { + const target = normalizeTarget(serverId, sessionId) + return `${target.serverId}\0${target.sessionId}\0${limit}` +} + +function prune(now: number): void { + for (const [key, entry] of inflight) { + if (now - entry.startedAt > TTL_MS) inflight.delete(key) + } + // 极端情况下(一直被导航打断)按插入顺序丢最早的一批 + while (inflight.size > MAX_INFLIGHT) { + const oldest = inflight.keys().next().value + if (oldest === undefined) break + inflight.delete(oldest) + } +} + +/** + * 预取会话首屏消息;重复调用复用同一个请求。 + * + * 已经有可用缓存视图(切过去不会再请求)时直接跳过:白白发一次请求, + * 而且 request 的结果没人取,只会在槽位里留到过期。 + */ +export function prefetchSessionMessages(serverId: string, sessionId: string, limit: number): void { + const target = normalizeTarget(serverId, sessionId) + // 已有可用缓存视图时,会话页根本不会再请求:预取纯属浪费 + if (messageStore.hasRenderableCache(makeSessionKey(target.serverId, target.sessionId))) return + const key = cacheKey(serverId, sessionId, limit) + if (inflight.has(key)) return + + prune(Date.now()) + const promise = getSessionMessagesPage(sessionId, { limit }, serverId) + // 失败时清理槽位,并吞掉「没人取走」场景下的 rejection + promise.catch(() => { + if (inflight.get(key)?.promise === promise) inflight.delete(key) + }) + inflight.set(key, { promise, startedAt: Date.now() }) +} + +/** + * 取走预取结果(一次性)。过期则视为未命中,由调用方重新请求。 + * 返回 undefined 表示没有可用的预取。 + */ +export function takeSessionMessagesPrefetch( + serverId: string, + sessionId: string, + limit: number, +): Promise | undefined { + const key = cacheKey(serverId, sessionId, limit) + const entry = inflight.get(key) + if (!entry) return undefined + inflight.delete(key) + if (Date.now() - entry.startedAt > TTL_MS) return undefined + return entry.promise +} + +/** 测试用:清空预取槽位 */ +export function clearSessionMessagesPrefetch(): void { + inflight.clear() +} diff --git a/src/api/sdk.test.ts b/src/api/sdk.test.ts index 6f8d2132..be11ad51 100644 --- a/src/api/sdk.test.ts +++ b/src/api/sdk.test.ts @@ -62,6 +62,19 @@ describe('v2 client request lifecycle', () => { expect(client.__options.baseUrl).toBe('http://127.0.0.1:4096') }) + it('resolves a relative base URL before handing it to the SDK', async () => { + // 回归:standalone 镜像把 VITE_API_BASE_URL 设成 `/api`,SDK 内部 + // `new URL('/api')` 会抛 Invalid URL。必须按页面 origin 补全。 + getActiveBaseUrlMock.mockReturnValue('/api') + + const { getSDKClient } = await import('./sdk') + const client = getSDKClient() as unknown as MockClient + + expect(client.__options.baseUrl).toBe(`${window.location.origin}/api`) + // 缓存 key 也用补全后的地址,重复调用必须命中同一实例 + expect(getSDKClient()).toBe(client) + }) + it('aborts in-flight requests when the server endpoint changes', async () => { const { abortInFlightApiRequests, getSDKClient } = await import('./sdk') const client = getSDKClient() as unknown as MockClient diff --git a/src/api/sdk.ts b/src/api/sdk.ts index a8c921e4..56fe5059 100644 --- a/src/api/sdk.ts +++ b/src/api/sdk.ts @@ -14,6 +14,7 @@ import { OpenCode } from '@opencode/client/promise' import type { OpenCodeClient } from '@opencode/client/promise' import { serverStore, makeBasicAuthHeader } from '../store/serverStore' import { isTauri } from '../utils/tauri' +import { toAbsoluteBaseUrl } from './http' /** v2 客户端实例(内部 API 层的唯一形状) */ export type ServerApi = OpenCodeClient @@ -151,8 +152,20 @@ interface CachedClientEntry { const _cachedClients = new Map() +/** + * 读取当前服务器的 baseUrl,并补成 SDK 要求的绝对地址。 + * + * standalone 部署的 `VITE_API_BASE_URL=/api` 是相对前缀,直接用会被 + * `new URL('/api')` 判为 Invalid URL;缓存 key 也必须用补全后的值, + * 否则相对/绝对两种写法会各建一份客户端。 + */ +function resolveClientBaseUrl(serverId?: string): string { + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) +} + function buildCacheKey(serverId?: string): string { - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const auth = serverId ? serverStore.getServerAuth(serverId) : serverStore.getActiveAuth() const authPart = auth?.password ? `${auth.username}:${auth.password}` : '' return `${baseUrl}|${authPart}` @@ -179,7 +192,7 @@ export function getSDKClient(serverId?: string): ServerApi { return cached.client } - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const headers = buildHeaders(serverId) const generation = _apiRequestGeneration diff --git a/src/api/session.ts b/src/api/session.ts index 3e12a27d..3bcc8f97 100644 --- a/src/api/session.ts +++ b/src/api/session.ts @@ -27,6 +27,7 @@ import { inboxStore } from '../store/inboxStore' import { normalizeFileDiffs } from '../types/api/file' import type { FileDiff, Session, SessionListParams, SessionRevert, SessionStatusMap } from './types' import type { SessionTransferData, SessionInboxInfo } from '@opencode/client/promise' +import { sessionInfoCache } from '../store/sessionInfoCache' // ============================================ // 会话状态 @@ -76,16 +77,54 @@ export async function getSessionDiff(sessionId: string, serverId?: string): Prom return normalizeFileDiffs(diffs) } +/** 单轮 diff 的 in-flight 去重(虚拟列表来回挂载时不重复请求) */ +const inflightTurnDiffs = new Map>() + +/** + * 取某一轮(从指定 user message 起)的文件 diff。 + * + * 官方 timeline 的 TurnDiff 行用 `session.diff({ sessionID, from })`, + * `from` 是该轮用户消息 id。返回的 patch 可直接交给 DiffView 渲染。 + */ +export async function getTurnDiff(sessionId: string, from: string, serverId?: string): Promise { + const target = resolveSessionTarget(sessionId, serverId) + const key = `${target.serverId}:${target.sessionId}:${from}` + const inflight = inflightTurnDiffs.get(key) + if (inflight) return inflight + + const request = (async () => { + try { + const sdk = getSDKClient(target.serverId) + const diffs = await sdk.session.diff({ sessionID: target.sessionId, from }) + return normalizeFileDiffs(diffs) + } finally { + inflightTurnDiffs.delete(key) + } + })() + inflightTurnDiffs.set(key, request) + return request +} + // ============================================ // 会话 CRUD // ============================================ +/** 一页会话列表;`next` 是下一页游标(null = 到底) */ +export interface SessionListPage { + data: Session[] + next: string | null +} + /** - * 获取会话列表。 + * 获取一页会话列表,保留服务端游标。 * - * v2 返回 `{ data, cursor }`;调用点普遍期望数组,这里返回 `data`。 + * 翻页(loadMore)走这里:cursor 分页只取新增的一页,不必把整张表 + * 重新拉一遍(旧实现靠 limit 递增重拉,越翻越慢)。 */ -export async function getSessions(params: SessionListParams = {}, serverId?: string): Promise { +export async function listSessionsPage( + params: SessionListParams = {}, + serverId?: string, +): Promise { const sdk = getSDKClient(serverId) const { directory, parentID, search, limit, order, cursor, project, subpath } = params const result = await sdk.session.list({ @@ -98,7 +137,18 @@ export async function getSessions(params: SessionListParams = {}, serverId?: str project, subpath, }) - return result.data + return { data: result.data, next: result.cursor?.next ?? null } +} + +/** + * 获取会话列表(数组形态)。 + * + * 只要第一页的调用点(搜索、e2e)继续用它;需要翻页的列表走 + * `listSessionsPage` 或 `sessionIndexStore`。 + */ +export async function getSessions(params: SessionListParams = {}, serverId?: string): Promise { + const page = await listSessionsPage(params, serverId) + return page.data } /** @@ -120,7 +170,10 @@ export async function getSessionChildren( export async function getSession(sessionId: string, _directory?: string, serverId?: string): Promise { const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) - return await sdk.session.get({ sessionID: target.sessionId }) + const session = await sdk.session.get({ sessionID: target.sessionId }) + // 权威读顺手刷新交接缓存:从任何路径回读到的最新元信息都能被下一次进入命中 + sessionInfoCache.remember(target.serverId, session) + return session } /** @@ -177,7 +230,9 @@ export async function updateSession( title: params.title, }) // v2 的 update 返回 void,回读一次保证调用点拿到最新会话 - return await sdk.session.get({ sessionID: target.sessionId }) + const session = await sdk.session.get({ sessionID: target.sessionId }) + sessionInfoCache.remember(target.serverId, session) + return session } /** 删除会话(v1 的 delete → v2 的 remove) */ @@ -185,6 +240,8 @@ export async function deleteSession(sessionId: string, _directory?: string, serv const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) await sdk.session.remove({ sessionID: target.sessionId }) + // 删掉的会话不该在 TTL 内还命中交接缓存 + sessionInfoCache.forget(target.serverId, sessionId) return true } @@ -198,6 +255,8 @@ export async function moveSession(sessionId: string, directory: string, serverId const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) await sdk.session.move({ sessionID: target.sessionId, directory }) + // 目录归属变了:交接缓存里的 location 立刻作废,避免进会话用错目录 + sessionInfoCache.forget(target.serverId, sessionId) } /** diff --git a/src/components/ContentBlock.tsx b/src/components/ContentBlock.tsx index 2ebd7a0d..45020b92 100644 --- a/src/components/ContentBlock.tsx +++ b/src/components/ContentBlock.tsx @@ -34,8 +34,12 @@ export interface ContentBlockProps { labelIcon?: ReactNode /** 隐藏标签文本,仅保留图标 / 文件名 */ hideLabel?: boolean + /** 隐藏折叠箭头(外层已有展开控制时用) */ + hideChevron?: boolean /** 文件路径 */ filePath?: string + /** header 显示完整路径(默认只显示文件名) */ + showFullPath?: boolean /** 语言 */ language?: string /** 样式变体 */ @@ -80,7 +84,9 @@ export const ContentBlock = memo(function ContentBlock({ label, labelIcon, hideLabel = false, + hideChevron = false, filePath, + showFullPath = false, language, variant = 'default', defaultCollapsed = false, @@ -117,7 +123,7 @@ export const ContentBlock = memo(function ContentBlock({ const hasContent = !!content?.trim() || isDiff || stats?.exit !== undefined const canCollapse = !compact && collapsible && hasContent const lang = language || (filePath ? detectLanguage(filePath) : 'text') - const fileName = filePath?.split(/[/\\]/).pop() + const fileName = filePath ? (showFullPath ? filePath : filePath.split(/[/\\]/).pop()) : undefined const resolvedFullscreenId = fullscreenId ?? `content-block:${generatedFullscreenId}` const collapsed = compact ? false : cachedCollapsed @@ -283,7 +289,7 @@ export const ContentBlock = memo(function ContentBlock({ > {/* Left: chevron + label + filename */}
- {canCollapse && ( + {canCollapse && !hideChevron && ( {collapsed ? : } diff --git a/src/components/DiffView.tsx b/src/components/DiffView.tsx index 5daacc5b..a637a1e0 100644 --- a/src/components/DiffView.tsx +++ b/src/components/DiffView.tsx @@ -24,6 +24,8 @@ interface DiffViewProps { maxHeight?: number /** Explicit language */ language?: string + /** 去掉外层卡片 / 头部 / 边框,只渲染 diff 正文(挂在文件行下面时用) */ + bare?: boolean } /** 轻量统计 additions/deletions,不做高亮 */ @@ -45,8 +47,9 @@ export const DiffView = memo(function DiffView({ after, filePath, defaultCollapsed = false, - maxHeight = 300, + maxHeight, language: explicitLanguage, + bare = false, }: DiffViewProps) { const { t } = useTranslation(['components', 'common']) const [collapsed, setCollapsed] = useState(defaultCollapsed) @@ -126,6 +129,27 @@ export const DiffView = memo(function DiffView({ return () => window.removeEventListener('resize', checkWidth) }, [fullscreenOpen]) + if (bare) { + if (!content) { + return diff ? ( +
{diff}
+ ) : null + } + return ( +
+ +
+ ) + } + // Fallback for unified diff string only if (!hasContent && diff) { return ( @@ -184,7 +208,7 @@ export const DiffView = memo(function DiffView({ after={content.after} language={language} viewMode="unified" - maxHeight={maxHeight} + maxHeight={maxHeight ?? 300} data={diffViewerData} />
diff --git a/src/components/PreviewTabsBar.tsx b/src/components/PreviewTabsBar.tsx index 5bd0d187..0be60a4b 100644 --- a/src/components/PreviewTabsBar.tsx +++ b/src/components/PreviewTabsBar.tsx @@ -84,7 +84,7 @@ export const PreviewTabsBar = memo(function PreviewTabsBar({ }, []) return ( -
+
{ - webglAddon.dispose() - logger.log('[Terminal] WebGL context lost, falling back to DOM renderer') - }) - try { - terminal.loadAddon(webglAddon) - } catch { - webglAddon.dispose() - logger.log('[Terminal] WebGL not available, using DOM renderer') + // 若 WebGL 不可用则静默回退到内置 DOM 渲染器。 + // 玻璃外观下不挂 WebGL:它会用 theme.background 自己清屏,透明失效。 + let webglAddon: WebglAddon | null = null + if (!isGlass) { + webglAddon = new WebglAddon() + webglAddon.onContextLoss(() => { + webglAddon?.dispose() + logger.log('[Terminal] WebGL context lost, falling back to DOM renderer') + }) + try { + terminal.loadAddon(webglAddon) + } catch { + webglAddon.dispose() + webglAddon = null + logger.log('[Terminal] WebGL not available, using DOM renderer') + } } const textarea = terminal.textarea @@ -973,7 +978,7 @@ export const Terminal = memo(function Terminal({ fitAddon.dispose() serializeAddon.dispose() webLinksAddon.dispose() - webglAddon.dispose() + webglAddon?.dispose() terminal.dispose() terminalRef.current = null fitAddonRef.current = null @@ -1159,9 +1164,10 @@ export const Terminal = memo(function Terminal({ useEffect(() => { const observer = new MutationObserver(mutations => { for (const mutation of mutations) { - if (mutation.attributeName === 'data-mode') { + if (mutation.attributeName === 'data-mode' || mutation.attributeName === 'data-appearance') { if (terminalRef.current) { - terminalRef.current.options.theme = getTerminalTheme(isDarkMode()) + const glass = document.documentElement.getAttribute('data-appearance') === 'glass' + terminalRef.current.options.theme = getTerminalTheme(isDarkMode(), glass) } // --font-mono 可能随主题变:跟着重新应用字体设置 applyFontOptions() @@ -1172,7 +1178,7 @@ export const Terminal = memo(function Terminal({ observer.observe(document.documentElement, { attributes: true, - attributeFilter: ['data-mode'], + attributeFilter: ['data-mode', 'data-appearance'], }) return () => observer.disconnect() diff --git a/src/components/ui/Button.tsx b/src/components/ui/Button.tsx index ac23c156..e2ec9d67 100644 --- a/src/components/ui/Button.tsx +++ b/src/components/ui/Button.tsx @@ -33,6 +33,7 @@ export const Button = forwardRef(
@@ -194,6 +207,7 @@ const MessageBody = memo(function MessageBody({ interface RowProps { virtualItem: VirtualItem item: ProcessTimelineItem + sessionId: string | null maxWidthClass: string paddingClass: string rowYClass: string @@ -213,6 +227,7 @@ const VirtualRow = memo( function VirtualRow({ virtualItem, item, + sessionId, maxWidthClass, paddingClass, rowYClass, @@ -265,6 +280,8 @@ const VirtualRow = memo( } allowStreamingLayoutAnimation={allowStreamingLayoutAnimation} processContentScope={item.processContentScope ?? 'all'} + turnDiff={item.turnDiff} + sessionId={sessionId} onEntryGrowComplete={onEntryGrowComplete} /> ) : ( @@ -307,6 +324,16 @@ const VirtualRow = memo( isTurnLatestAssistant allowStreamingLayoutAnimation={allowStreamingLayoutAnimation} processContentScope="final" + turnDiff={item.turnDiff} + sessionId={sessionId} + /> + )} + {!item.finalMessage && item.turnDiff && ( + )}
@@ -321,6 +348,7 @@ const VirtualRow = memo( prev.virtualItem.start === next.virtualItem.start && prev.virtualItem.size === next.virtualItem.size && prev.item === next.item && + prev.sessionId === next.sessionId && prev.maxWidthClass === next.maxWidthClass && prev.paddingClass === next.paddingClass && prev.rowYClass === next.rowYClass && @@ -367,6 +395,7 @@ export const ChatArea = memo( registerMessage, retryStatus = null, queuedFollowUps = EMPTY_QUEUE, + queuedCompactions = EMPTY_COMPACTIONS, queueEditingId, queueMutation, onQueueSteer, @@ -380,7 +409,7 @@ export const ChatArea = memo( ref, ) => { const { t } = useTranslation('chat') - const { processCollapseEnabled } = useTheme() + const { processCollapseEnabled, showTimelineNotices, showTurnDiff } = useTheme() const { presentation } = useChatViewport() const atBottomThreshold = presentation.isCompact ? 150 : AT_BOTTOM_THRESHOLD_PX const paddingClass = presentation.isCompact ? 'px-3' : 'px-5' @@ -390,8 +419,8 @@ export const ChatArea = memo( // ── 派生数据 ── const entries = useMemo( - () => visibleMessageEntriesProp ?? buildVisibleMessageEntries(messages), - [messages, visibleMessageEntriesProp], + () => visibleMessageEntriesProp ?? buildVisibleMessageEntries(messages, { showNotices: showTimelineNotices }), + [messages, visibleMessageEntriesProp, showTimelineNotices], ) const visibleMessages = useMemo( () => visibleMessagesProp ?? entries.map(e => e.message), @@ -422,17 +451,14 @@ export const ChatArea = memo( }>({ processCollapseEnabled }) const timeline = useMemo(() => { const next = !processCollapseEnabled - ? visibleMessages.map(message => ({ - kind: 'message' as const, - key: message.id, - message, - })) + ? buildFlatTimeline(visibleMessages, isStreaming, showTurnDiff) : buildProcessTimeline(visibleMessages, { turnDurationMap, sessionIsStreaming: isStreaming, messageHasProcess: messageHasProcessContent, messageHasFinal: messageHasFinalContent, isUserEntryReady: emptyShellGate.isReady, + turnDiff: showTurnDiff, }) const previous = previousTimelineRef.current.processCollapseEnabled === processCollapseEnabled @@ -448,6 +474,7 @@ export const ChatArea = memo( visibleMessages, turnDurationMap, isStreaming, + showTurnDiff, emptyShellGate.version, emptyShellGate.isReady, ]) @@ -892,7 +919,7 @@ export const ChatArea = memo( // retry/error 出现消失、输入框高度变 → 底部 footer 高度变,贴底时要跟着滚 // 否则重试条进出后 scrollTop 停在旧位置,看起来没贴底 - const footerPinKey = `${retryStatus ? 'r' : ''}|${loadError || connectionError ? 'e' : ''}|${queuedFollowUps.map(item => item.id).join('')}|${spacerHeight}` + const footerPinKey = `${retryStatus ? 'r' : ''}|${loadError || connectionError ? 'e' : ''}|${queuedCompactions.map(item => item.id).join('')}|${queuedFollowUps.map(item => item.id).join('')}|${spacerHeight}` useLayoutEffect(() => { if (!shouldAnchorBottom() || prependLoading.current) return pinToBottom() @@ -1083,6 +1110,7 @@ export const ChatArea = memo( key={item.key} virtualItem={item} item={timelineItem} + sessionId={sessionId ?? null} maxWidthClass={maxWidthClass} paddingClass={paddingClass} rowYClass={getTimelineRowYClass(timelineItem, timeline[item.index - 1], timeline[item.index + 1])} @@ -1101,6 +1129,15 @@ export const ChatArea = memo( })}
+ {/* 已入队未开始的压缩:官方 CompactionQueued 行,排在待投递输入之前 */} + {queuedCompactions.length > 0 && ( +
+ {queuedCompactions.map(item => ( + + ))} +
+ )} + {/* 队列气泡:融在消息流尾部(PiUI 同款位置:虚拟行之后、重试提示之前) */} {queuedFollowUps.length > 0 && (
@@ -1117,7 +1154,7 @@ export const ChatArea = memo(
)} - {/* 顺序必须是:消息 → 队列 → 重试/错误提示 → 输入框占位。 + {/* 顺序必须是:消息 → 压缩排队 → 队列 → 重试/错误提示 → 输入框占位。 旧 Virtuoso Footer 就是这样;换 virtualizer 后 paddingEnd 在前、提示在后,会叠到输入框下。 */} {retryStatus && (
diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index 3521fe78..e339d999 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -6,7 +6,17 @@ * compact viewport wrapper. */ -import { memo, useRef, useEffect, useState, useCallback, useMemo, useDeferredValue, useSyncExternalStore, type CSSProperties } 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 '.' @@ -29,7 +39,11 @@ import { useServerStore } from '../../hooks/useServerStore' import { useCancelHint } from '../../hooks/useCancelHint' import { makeSessionKey, sessionKeyToServerId, splitSessionKey } from '../../utils/sessionKey' import { serverStore } from '../../store/serverStore' -import { InlineToolRequestContext, partitionUnclaimedRequests, type InlineToolRequestContextValue } from './InlineToolRequestContext' +import { + InlineToolRequestContext, + partitionUnclaimedRequests, + type InlineToolRequestContextValue, +} from './InlineToolRequestContext' import { ChatViewportProvider, canUseSplitPane, useChatViewportMaybe, type ChatViewportValue } from './chatViewport' import { useChatPageViewModel } from './useChatPageViewModel' import { findBlockingBackgroundTasks, mergeRunningShells, useRunningShells } from './backgroundTasks' @@ -307,6 +321,7 @@ export const ChatPane = memo(function ChatPane({ pendingQuestionRequests, pendingWebsearchRequest, queuedPrompts, + queuedCompactions, inboxUserPrompts, busyDelivery, setBusyDelivery, @@ -371,23 +386,61 @@ export const ChatPane = memo(function ChatPane({ // 并入服务端 running shells(官方 background.ts:100-109 同款) // ============================================ const runningShells = useRunningShells(routeSessionId, isStreaming, effectiveDirectory, paneServerId) + + // 当前回合开始的时间点:这之前启动、还挂在后台的 shell 属于上一回合, + // 不能算作阻塞当前回合、也不该继续提示「移到后台」。 + const currentTurnStartedAt = useMemo(() => { + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i] + if (message.type === 'user' && typeof message.time?.created === 'number') return message.time.created + } + return undefined + }, [messages]) + + // 刚被移到后台的任务:服务端 shell 仍是 running,本地先摘掉,避免入口一直挂着。 + const [movedBackgroundKeys, setMovedBackgroundKeys] = useState>(() => new Set()) + useEffect(() => { + setMovedBackgroundKeys(new Set()) + }, [routeSessionId, currentTurnStartedAt]) + const blockingBackgroundTasks = useMemo(() => { if (!isStreaming || !routeSessionId) return [] const { sessionId: rawSessionId } = splitSessionKey(routeSessionId) - return mergeRunningShells(findBlockingBackgroundTasks(messages), runningShells, rawSessionId ?? routeSessionId) - }, [isStreaming, routeSessionId, messages, runningShells]) + const merged = mergeRunningShells( + findBlockingBackgroundTasks(messages), + runningShells, + rawSessionId ?? routeSessionId, + { notBefore: currentTurnStartedAt }, + ) + if (movedBackgroundKeys.size === 0) return merged + return merged.filter( + task => !movedBackgroundKeys.has(`${task.type}:${task.id}`) && !movedBackgroundKeys.has(`label:${task.label}`), + ) + }, [isStreaming, routeSessionId, messages, runningShells, currentTurnStartedAt, movedBackgroundKeys]) + const [backgroundMoving, setBackgroundMoving] = useState(false) const handleMoveToBackground = useCallback(async () => { if (!routeSessionId || backgroundMoving) return + const snapshot = blockingBackgroundTasks setBackgroundMoving(true) try { await backgroundSession(routeSessionId, paneServerId) + if (snapshot.length > 0) { + setMovedBackgroundKeys(prev => { + const next = new Set(prev) + for (const task of snapshot) { + next.add(`${task.type}:${task.id}`) + next.add(`label:${task.label}`) + } + return next + }) + } } catch (e) { uiErrorHandler('background session', e) } finally { setBackgroundMoving(false) } - }, [routeSessionId, paneServerId, backgroundMoving]) + }, [routeSessionId, paneServerId, backgroundMoving, blockingBackgroundTasks]) const messageView = useMemo(() => ({ sessionId: routeSessionId, messages }), [routeSessionId, messages]) // Streaming never consumes the deferred value, so do not feed every token into a // second low-priority render lane. @@ -410,10 +463,12 @@ export const ChatPane = memo(function ChatPane({ loadState, messageCount: messages.length, }) - const chatAreaMountKey = messagesReady ? (routeSessionId ?? 'home') : null + // 已有可显示消息就先挂出来(官方 createTimelineModel 的 ready 同款: + // 任意一条非 pending 消息即视为可渲染,enrich 之后补)。 + // 缓存命中 / SSE 先到 / 重连刷新时,没必要为了一次元信息回读让整页空白。 + const hasRenderableMessages = renderedMessages.length > 0 + const chatAreaMountKey = messagesReady || hasRenderableMessages ? (routeSessionId ?? 'home') : null const inputDisabled = !!routeSessionId && loadState === 'error' && messages.length === 0 - const chatPageViewModel = useChatPageViewModel(projectedMessages) - // 切 session remount 时默认视为贴底,避免回底按钮闪一下 useEffect(() => { if (chatAreaMountKey == null) return @@ -846,8 +901,13 @@ export const ChatPane = memo(function ChatPane({ setChatContentWidth, chatInputWidth, setChatInputWidth, + showTimelineNotices, + showQueuedCompaction, } = useTheme() + // 提示行开关参与可见性过滤:关掉后这些消息不进入时间线 + const chatPageViewModel = useChatPageViewModel(projectedMessages, showTimelineNotices) + // ── 对话列/输入框宽度(左缘拖拽调宽,两个独立把手)── // 样式与交互抄 dsh ConversationWidthControls,按需求收窄成左缘单把手 × 2: // 把手(调整入口)只在桌面端单 panel / pane 全屏时挂载(分屏空间太碎不给拖), @@ -904,25 +964,22 @@ export const ChatPane = memo(function ChatPane({ () => (pendingWebsearchRequest ? [...pendingQuestionRequests, pendingWebsearchRequest] : pendingQuestionRequests), [pendingQuestionRequests, pendingWebsearchRequest], ) - const unclaimed = useMemo( - () => { - // childSessionVersion 是绑定表版本号:卡片↔子会话绑定变化不改任何入参引用, - // 但认领判定会变——引用它让依赖数组语义完整(也让 memo 正确失效) - void childSessionVersion - return inlineToolRequests && routeSessionId - ? partitionUnclaimedRequests(messages, pendingPermissionRequests, allPendingForms, paneServerId, routeSessionId) - : { permissions: [], questions: [] } - }, - [ - inlineToolRequests, - routeSessionId, - messages, - pendingPermissionRequests, - allPendingForms, - paneServerId, - childSessionVersion, - ], - ) + const unclaimed = useMemo(() => { + // childSessionVersion 是绑定表版本号:卡片↔子会话绑定变化不改任何入参引用, + // 但认领判定会变——引用它让依赖数组语义完整(也让 memo 正确失效) + void childSessionVersion + return inlineToolRequests && routeSessionId + ? partitionUnclaimedRequests(messages, pendingPermissionRequests, allPendingForms, paneServerId, routeSessionId) + : { permissions: [], questions: [] } + }, [ + inlineToolRequests, + routeSessionId, + messages, + pendingPermissionRequests, + allPendingForms, + paneServerId, + childSessionVersion, + ]) const isWebsearchForm = (form: (typeof allPendingForms)[number]) => (form.metadata as Record | undefined)?.kind === 'websearch.provider' // inline 模式底部只渲染未认领的;非 inline 模式维持原样(全量会话级弹窗)。 @@ -1064,10 +1121,13 @@ export const ChatPane = memo(function ChatPane({ registerMessage={registerMessage} retryStatus={retryStatus} queuedFollowUps={queuedPrompts} + queuedCompactions={showQueuedCompaction ? queuedCompactions : undefined} queueEditingId={queueEditing?.item.id} queueMutation={queueMutation} onQueueSteer={handleSteerQueuedPrompt} - onQueueEdit={item => (queueEditing?.item.id === item.id ? handleCancelQueueEdit() : handleEditQueuedPrompt(item))} + onQueueEdit={item => + queueEditing?.item.id === item.id ? handleCancelQueueEdit() : handleEditQueuedPrompt(item) + } onQueueRemove={item => handleCancelQueuedPrompt(item.id)} onQueueReorder={handleReorderQueuedPrompts} bottomPadding={inputBoxHeight} @@ -1244,7 +1304,6 @@ export const ChatPane = memo(function ChatPane({ onCollapsedChange={setWebsearchCollapsed} /> )} -
) diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index c5a4d436..0e067b15 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -108,6 +108,32 @@ describe('InputBox slash command selection', () => { promptHistoryStore.reset() }) + it('Android 全选删除后重建 textarea 节点', async () => { + const userAgent = vi + .spyOn(navigator, 'userAgent', 'get') + .mockReturnValue( + 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36', + ) + + render() + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + + textarea.focus() + fireEvent.input(textarea, { target: { value: 'hello' } }) + textarea.setSelectionRange(0, textarea.value.length) + document.dispatchEvent(new Event('selectionchange')) + + fireEvent.input(textarea, { target: { value: '' } }) + + await waitFor(() => { + const next = screen.getByRole('textbox') as HTMLTextAreaElement + expect(next).not.toBe(textarea) + expect(next.value).toBe('') + }) + + userAgent.mockRestore() + }) + it('executes frontend commands immediately on selection', async () => { slashCommands = [{ name: 'compact', description: 'Compact session', source: 'frontend' }] const onCommand = vi.fn() diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index fd9f9ef8..20192033 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -17,6 +17,7 @@ import type { ModelSelectorHandle } from './ModelSelector' import { InputFooter } from './input/InputFooter' import { FloatingActions, CollapsedCapsule } from './input/InputActions' import { useMobileCollapse } from './input/useMobileCollapse' +import { useAndroidImeSafeTextarea } from './input/useAndroidImeSafeTextarea' import { useAttachmentRail } from './input/useAttachmentRail' import { useInputHistory } from './input/useInputHistory' import { promptHistoryStore } from '../../store/promptHistoryStore' @@ -639,25 +640,40 @@ function InputBoxComponent({ const updateComposerHeightBudget = useCallback(() => { const paneHeight = getComposerPaneHeight(inputContainerRef.current ?? contentWrapRef.current) const nextComposerMaxHeight = getComposerMaxHeight(paneHeight, isCompact) - const attachmentHeight = attachments.length > 0 ? (attachmentSectionRef.current?.offsetHeight ?? 0) : 0 const toolbarHeight = toolbarRef.current?.offsetHeight || INPUT_TOOLBAR_FALLBACK_HEIGHT const footerHeight = isCollapsed ? 0 : footerRef.current?.offsetHeight || INPUT_FOOTER_FALLBACK_HEIGHT - const inputContainerChrome = attachmentHeight + toolbarHeight + TEXTAREA_VERTICAL_CHROME + + // 输入框里除 textarea 之外的固定高度:上方留白 + 间距 + 工具条 + 边框。 + // 用常量估会差几像素,内容到顶时工具条就会被 overflow 裁掉,所以直接按布局位置量。 + const containerEl = inputContainerRef.current + const textareaEl = textareaRef.current + const toolbarEl = toolbarRef.current + let containerChrome = TEXTAREA_MIN_HEIGHT + TEXTAREA_VERTICAL_CHROME + toolbarHeight + if (containerEl && textareaEl && toolbarEl) { + const boxRect = containerEl.getBoundingClientRect() + const textareaRect = textareaEl.getBoundingClientRect() + const toolbarRect = toolbarEl.getBoundingClientRect() + const style = getComputedStyle(containerEl) + const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth) + containerChrome = + Math.max(0, textareaRect.top - boxRect.top) + + Math.max(0, toolbarRect.top - textareaRect.bottom) + + toolbarRect.height + + border + } + const nextInputContainerMaxHeight = Math.max( - TEXTAREA_MIN_HEIGHT + TEXTAREA_VERTICAL_CHROME + toolbarHeight, + TEXTAREA_MIN_HEIGHT + containerChrome, nextComposerMaxHeight - footerHeight, ) - const nextTextareaMaxHeight = Math.max( - TEXTAREA_MIN_HEIGHT, - nextInputContainerMaxHeight - inputContainerChrome, - ) + const nextTextareaMaxHeight = Math.max(TEXTAREA_MIN_HEIGHT, nextInputContainerMaxHeight - containerChrome) setComposerMaxHeight(prev => (Math.abs(prev - nextComposerMaxHeight) < 1 ? prev : nextComposerMaxHeight)) setInputContainerMaxHeight(prev => Math.abs(prev - nextInputContainerMaxHeight) < 1 ? prev : nextInputContainerMaxHeight, ) setTextareaMaxHeight(prev => (Math.abs(prev - nextTextareaMaxHeight) < 1 ? prev : nextTextareaMaxHeight)) - }, [attachments.length, isCollapsed, isCompact]) + }, [isCollapsed, isCompact]) useLayoutEffect(() => { updateComposerHeightBudget() @@ -694,20 +710,39 @@ function InputBoxComponent({ } }, [updateComposerHeightBudget]) + // Android WebView 的 IME 兜底:全选删除后重建 textarea 节点 + const clearImeText = useCallback(() => setText(''), []) + const { imeResetKey } = useAndroidImeSafeTextarea({ textareaRef, onCleared: clearImeText }) + // 自动调整 textarea 高度 useLayoutEffect(() => { const textarea = textareaRef.current if (!textarea) return + // 一行的高度必须跟着真实行高走。TEXTAREA_MIN_HEIGHT 是 24, + // 但字号调大后一行会超过 24,输入第一个字就会把盒子撑高, + // 看起来像"没换行却变高"。 + const computed = getComputedStyle(textarea) + const lineHeight = Number.parseFloat(computed.lineHeight) + const fontSize = Number.parseFloat(computed.fontSize) + const oneLine = Math.max( + TEXTAREA_MIN_HEIGHT, + Math.ceil( + Number.isFinite(lineHeight) ? lineHeight : Number.isFinite(fontSize) ? fontSize * 1.43 : TEXTAREA_MIN_HEIGHT, + ), + ) + + textarea.style.minHeight = `${oneLine}px` + // 只有真正空字符串时才重置高度;保留仅空格/空行时的换行高度 if (text.length === 0) { - textarea.style.height = `${TEXTAREA_MIN_HEIGHT}px` + textarea.style.height = `${oneLine}px` return } textarea.style.height = 'auto' const scrollHeight = textarea.scrollHeight - textarea.style.height = Math.max(TEXTAREA_MIN_HEIGHT, Math.min(scrollHeight, textareaMaxHeight)) + 'px' + textarea.style.height = Math.max(oneLine, Math.min(scrollHeight, textareaMaxHeight)) + 'px' }, [text, textareaMaxHeight]) // 计算 @@ -1920,6 +1955,7 @@ function InputBoxComponent({ ref={inputContainerRef} data-input-box data-pane-id={paneId} + data-busy={isStreaming || undefined} onPointerDown={handleContainerPointerDown} onDragEnter={handleDragEnter} onDragOver={handleDragOver} @@ -1941,6 +1977,9 @@ function InputBoxComponent({ )} + {/* 忙碌时的描边光:模糊光晕层,玻璃外观下才可见 */} + +
{/* Attachments Preview - 显示在输入框上方 */} @@ -1991,6 +2030,7 @@ function InputBoxComponent({
)}