From 5eac3f64e5b25bf7eaf93da1f874fb99a044c4e4 Mon Sep 17 00:00:00 2001 From: xiaomakuaiz Date: Thu, 23 Jul 2026 14:39:13 +0000 Subject: [PATCH] fix(desktop): scope diffs to git changes tab --- desktop/src/repo.rs | 65 +++++++++++++++++--- desktop/ui/src/App.tsx | 2 +- desktop/ui/src/filesdrawer.test.tsx | 38 ++++++++++++ desktop/ui/src/filesdrawer.tsx | 93 ++++++++++++++++------------- desktop/ui/src/useSession.ts | 14 ++++- 5 files changed, 163 insertions(+), 49 deletions(-) create mode 100644 desktop/ui/src/filesdrawer.test.tsx diff --git a/desktop/src/repo.rs b/desktop/src/repo.rs index ef291506..304d745d 100644 --- a/desktop/src/repo.rs +++ b/desktop/src/repo.rs @@ -89,10 +89,17 @@ impl RepoCtx { /// 统一入口:kind 分派,返回 {result} 或 {error}(与内核 call-response 载荷同构)。 pub fn dispatch(ctx: &RepoCtx, kind: &str, payload: &Value) -> Value { let path = payload.get("path").and_then(|v| v.as_str()).unwrap_or(""); + if kind == "repo_file_changes" { + return match file_changes(ctx) { + Ok((changes, is_git_repo)) => { + json!({ "result": changes, "is_git_repo": is_git_repo }) + } + Err(e) => json!({ "error": e }), + }; + } let r = match kind { "repo_file_list" => list_files(ctx, path), "repo_read_file" => read_file(ctx, path), - "repo_file_changes" => file_changes(ctx), "repo_file_diff" => file_diff(ctx, path), "repo_reveal" => reveal(ctx, path), _ => Err(format!("未知 call kind: {kind}")), @@ -144,12 +151,13 @@ fn read_file(ctx: &RepoCtx, rel: &str) -> Result { Ok(json!({ "path": rel, "content": String::from_utf8_lossy(&data) })) } -/// 相对 HEAD 的变更列表(含未跟踪文件)。非 git 仓库返回空。 +/// 相对 HEAD 的变更列表(含未跟踪文件),同时返回工作区是否属于 git 仓库。 /// 路径统一为相对 workdir(porcelain 输出仓库根相对路径,须剥前缀); /// quotepath 关闭,否则非 ASCII 文件名被转成八进制转义乱码。 -fn file_changes(ctx: &RepoCtx) -> Result { - if !ctx.is_git_repo() { - return Ok(Value::Array(vec![])); +fn file_changes(ctx: &RepoCtx) -> Result<(Value, bool), String> { + let is_git_repo = ctx.is_git_repo(); + if !is_git_repo { + return Ok((Value::Array(vec![]), false)); } let prefix = ctx.git(&["rev-parse", "--show-prefix"]).unwrap_or_default().trim().to_string(); let out = ctx @@ -184,8 +192,9 @@ fn file_changes(ctx: &RepoCtx) -> Result { changes.push((path, status)); } changes.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(Value::Array( - changes.into_iter().map(|(p, s)| json!({ "path": p, "status": s })).collect(), + Ok(( + Value::Array(changes.into_iter().map(|(p, s)| json!({ "path": p, "status": s })).collect()), + true, )) } @@ -237,3 +246,45 @@ fn reveal(ctx: &RepoCtx, rel: &str) -> Result { r.map_err(|e| format!("打开文件管理器失败: {e}"))?; Ok(json!({ "ok": true })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changes_response_marks_non_git_workspace() { + let dir = std::env::temp_dir().join(format!("mc-non-git-changes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ctx = RepoCtx { + workdir: dir.to_string_lossy().into_owned(), + wsl_distro: None, + }; + + let response = dispatch(&ctx, "repo_file_changes", &json!({})); + + assert_eq!(response["is_git_repo"], false); + assert_eq!(response["result"], json!([])); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn changes_response_marks_git_workspace() { + let dir = std::env::temp_dir().join(format!("mc-git-changes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let initialized = Command::new("git").args(["init", "-q"]).current_dir(&dir).status().unwrap(); + assert!(initialized.success()); + std::fs::write(dir.join("new.txt"), b"new").unwrap(); + let ctx = RepoCtx { + workdir: dir.to_string_lossy().into_owned(), + wsl_distro: None, + }; + + let response = dispatch(&ctx, "repo_file_changes", &json!({})); + + assert_eq!(response["is_git_repo"], true); + assert_eq!(response["result"], json!([{ "path": "new.txt", "status": "A" }])); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/desktop/ui/src/App.tsx b/desktop/ui/src/App.tsx index b122c91f..273ebfd6 100644 --- a/desktop/ui/src/App.tsx +++ b/desktop/ui/src/App.tsx @@ -627,11 +627,11 @@ export default function App() { onClose={() => setDrawer(null)} initialTab={drawer} changes={changes} + showChangesTab={session.isGitRepo === true} externalErr={session.changesErr} resizable errPad="0 20px 8px" dirChangeBadges - ghostDeleted emptyRootState={
diff --git a/desktop/ui/src/filesdrawer.test.tsx b/desktop/ui/src/filesdrawer.test.tsx new file mode 100644 index 00000000..eb144aef --- /dev/null +++ b/desktop/ui/src/filesdrawer.test.tsx @@ -0,0 +1,38 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import { FilesDrawer, type FsAdapter } from "./filesdrawer"; + +const adapter: FsAdapter = { + listDir: async () => [], + readFile: async () => ({ content: "" }), + diff: async () => "", + diffTransientKind: "diff", +}; + +const renderDrawer = (showChangesTab: boolean, initialTab: "files" | "changes" = "files") => + renderToStaticMarkup( + {}} + initialTab={initialTab} + changes={[]} + showChangesTab={showChangesTab} + errPad="0" + changesEmptyText="没有文件改动" + viewerCloseTitle="关闭预览" + />, + ); + +describe("FilesDrawer tabs", () => { + it("hides the changes tab for a non-git workspace", () => { + const html = renderDrawer(false, "changes"); + + expect(html).toContain(">文件"); + expect(html).not.toContain(">改动"); + }); + + it("shows the changes tab for a git workspace", () => { + expect(renderDrawer(true)).toContain(">改动"); + }); +}); diff --git a/desktop/ui/src/filesdrawer.tsx b/desktop/ui/src/filesdrawer.tsx index 7358a806..5e8c2b54 100644 --- a/desktop/ui/src/filesdrawer.tsx +++ b/desktop/ui/src/filesdrawer.tsx @@ -3,7 +3,7 @@ // 各持一份九成相同的实现、靠注释对表,现收敛于此;两侧数据协议同名 // (repo_file_list / repo_read_file / repo_file_diff / repo_file_changes), // 载荷细节(base64 解码、超时参数、离线文案)与两侧的历史差异 -// (调宽/分栏拖拽、目录改动计数、幽灵行、预览头扩展位)走 FsAdapter 与 props。 +// (调宽/分栏拖拽、目录改动计数、预览头扩展位)走 FsAdapter 与 props。 import { Fragment, useEffect, useRef, useState, type CSSProperties, type MutableRefObject, type ReactNode } from "react"; import { basename } from "./chat"; import { CodeView, DiffPanel, MONO } from "./components"; @@ -95,11 +95,11 @@ export function FilesDrawer({ onClose, initialTab = "files", changes, + showChangesTab = true, externalErr, resizable, errPad, dirChangeBadges, - ghostDeleted, emptyRootState, changesEmptyText, changesLoadingText, @@ -113,6 +113,8 @@ export function FilesDrawer({ initialTab?: "files" | "changes"; /** 改动列表(null = 未加载;数据归属在调用方——本地随会话轮次刷新) */ changes: FsChange[] | null; + /** 非 Git 工作区关闭此项,仅保留文件浏览。 */ + showChangesTab?: boolean; /** 适配层外部渠道的错误(本地: 改动查询失败;云端: 控制流放弃重连) */ externalErr?: string; /** 抽屉宽度 + 列表/预览分栏可拖拽调整并记忆(本地;云端固定 600) */ @@ -121,8 +123,6 @@ export function FilesDrawer({ errPad: string; /** 树中目录行显示其下改动计数「N 处改动」(本地) */ dirChangeBadges?: boolean; - /** 本层已删除文件以划线幽灵行缀在末尾(本地) */ - ghostDeleted?: boolean; /** 根目录为空时的整块空态(本地「工作区是空的」;缺省用「(空)」行) */ emptyRootState?: ReactNode; changesEmptyText: string; @@ -136,7 +136,9 @@ export function FilesDrawer({ /** Esc 处理挂点:预览打开时关预览并返回 true,否则返回 false(调用方关抽屉) */ escRef?: MutableRefObject<(() => boolean) | null>; }) { - const [tab, setTab] = useState<"files" | "changes">(initialTab); + const [tab, setTab] = useState<"files" | "changes">( + initialTab === "changes" && !showChangesTab ? "files" : initialTab, + ); // 树形浏览:目录 → 子项缓存("" = 工作区根),展开集合,按目录粒度的加载中标记 const [tree, setTree] = useState>(new Map()); const [expanded, setExpanded] = useState>(new Set()); @@ -158,16 +160,35 @@ export function FilesDrawer({ }); const [splitDragging, setSplitDragging] = useState(false); const listRef = useRef(null); // 分栏拖拽的定位基准 + const previewRequest = useRef(0); // 切文件/Tab/关闭时使旧异步读取结果失效 // 适配层经 ref 转接:调用方每次渲染的新对象不搅动 mount effect const adapterRef = useRef(adapter); adapterRef.current = adapter; + const closeViewer = () => { + previewRequest.current++; + setViewer(null); + }; + const selectTab = (next: "files" | "changes") => { + if (next === tab || (next === "changes" && !showChangesTab)) return; + closeViewer(); + setTab(next); + }; + + // Git 状态异步探测完成后,非 Git 工作区可能从“未知”变为 false。 + useEffect(() => { + if (showChangesTab || tab !== "changes") return; + previewRequest.current++; + setViewer(null); + setTab("files"); + }, [showChangesTab, tab]); + // Esc 挂点:先关预览再关抽屉(闭包取最新 viewer,卸载时清挂点) if (escRef) escRef.current = () => { if (viewer) { - setViewer(null); + closeViewer(); return true; } return false; @@ -220,19 +241,24 @@ export function FilesDrawer({ }; const showDiff = async (path: string) => { + const request = ++previewRequest.current; setViewer({ path, kind: adapter.diffTransientKind, text: "加载中…" }); try { const text = await adapterRef.current.diff(path); - setViewer({ path, kind: "diff", text }); + if (request === previewRequest.current) setViewer({ path, kind: "diff", text }); } catch (e) { - setViewer({ path, kind: adapterRef.current.diffTransientKind, text: "✗ " + (e instanceof Error ? e.message : e) }); + if (request === previewRequest.current) { + setViewer({ path, kind: adapterRef.current.diffTransientKind, text: "✗ " + (e instanceof Error ? e.message : e) }); + } } }; const showFile = async (en: FsEntry) => { + const request = ++previewRequest.current; setViewer({ path: en.path, kind: "plain", text: "加载中…" }); try { const r = await adapterRef.current.readFile(en); + if (request !== previewRequest.current) return; if ("plain" in r) { setViewer({ path: en.path, kind: "plain", text: r.plain }); return; @@ -242,7 +268,9 @@ export function FilesDrawer({ else if (content.includes("\0")) setViewer({ path: en.path, kind: "plain", text: "二进制文件,不支持预览" }); else setViewer({ path: en.path, kind: "code", text: content }); } catch (e) { - setViewer({ path: en.path, kind: "plain", text: "✗ " + (e instanceof Error ? e.message : e) }); + if (request === previewRequest.current) { + setViewer({ path: en.path, kind: "plain", text: "✗ " + (e instanceof Error ? e.message : e) }); + } } }; @@ -309,7 +337,7 @@ export function FilesDrawer({ const viewerKind = viewerSt ? CHANGE_KIND[viewerSt] : undefined; // 树形文件列表:展开的文件夹原地铺开子项,层级用缩进表达(每层 16px)。 - // 本层已删除的文件以划线幽灵行缀在末尾(本地);子项懒加载,加载中给骨架行。 + // 已删除文件只属于“改动”页;文件页仅展示当前真实存在的文件。 const renderTree = (dir: string, depth: number): ReactNode[] => { const pad = 10 + depth * 16; const rows: ReactNode[] = []; @@ -338,7 +366,7 @@ export function FilesDrawer({ key={en.path} className={active ? undefined : "hv"} title={en.path} - onClick={() => (en.isDir ? toggleDir(en.path) : kind ? void showDiff(en.path) : void showFile(en))} + onClick={() => (en.isDir ? toggleDir(en.path) : void showFile(en))} style={{ ...fileRow, paddingLeft: pad, background: active ? "var(--hov)" : "transparent" }} > @@ -367,24 +395,7 @@ export function FilesDrawer({ ); if (open) rows.push(...renderTree(en.path, depth + 1)); } - const ghosts = ghostDeleted - ? (changes ?? []).filter( - (c) => c.status === "D" && (c.path.includes("/") ? c.path.slice(0, c.path.lastIndexOf("/")) : "") === dir, - ) - : []; - for (const c of ghosts) { - rows.push( -
void showDiff(c.path)} style={{ ...fileRow, paddingLeft: pad }}> - - - - {basename(c.path)} - - {CHANGE_KIND.D.text} -
, - ); - } - if (items.length === 0 && ghosts.length === 0) { + if (items.length === 0) { if (dir === "" && emptyRootState) { rows.push({emptyRootState}); } else { @@ -423,17 +434,19 @@ export function FilesDrawer({ )} {/* 头部:文件/改动下划线 tab(共用下方预览窗格),hairline 与主体分层 */}
- - + {showChangesTab && ( + + )} {headerExtra}
- {/* 文件查看器:改动文件看 diff,其余看内容;✕/esc 回到列表 */} + {/* 文件查看器:文件页看当前内容,改动页看 diff;✕/esc 回到列表 */} {viewer && ( <> {resizable && ( @@ -529,7 +542,7 @@ export function FilesDrawer({