🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(review-panel): group review changes by submodule (#15148)
Arvin Xub3d2d2fdbd55
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.tsindex b55de4dd72f..739ce7bbc11 100644--- a/apps/desktop/src/main/controllers/GitCtr.ts+++ b/apps/desktop/src/main/controllers/GitCtr.ts@@ -20,6 +20,7 @@ import type {GitWorkingTreePatch,GitWorkingTreePatches,GitWorkingTreeStatus,+ SubmoduleWorkingTreePatches,} from '@lobechat/electron-client-ipc';import { detectRepoType, resolveGitDir } from '@/utils/git';@@ -739,9 +740,73 @@ export default class GitController extends ControllerModule {** Per-file patches are capped at 256 KB; oversized or binary entries get an* empty `patch` string and a flag the renderer can use for a placeholder.+ *+ * Dirty submodules are detected via `git submodule status` and surfaced as+ * grouped `submodules[]` entries — their internal patches live under each+ * group, not in the parent's flat `patches` list. Nested submodules are not+ * traversed (phase 1).*/@IpcMethod()async getGitWorkingTreePatches(dirPath: string): Promise<GitWorkingTreePatches> {+ return this.collectWorkingTreePatches(dirPath, true);+ }++ /**+ * List paths of initialized submodules registered in `dirPath`. Uninitialized+ * entries (`-` prefix in `git submodule status`) are skipped — there's no+ * working tree to inspect for those. Failures (no submodules, shell errors)+ * return an empty set so callers gracefully fall back to the flat layout.+ *+ * Only direct submodules are listed; nested submodules would need+ * `--recursive` plus a tree-aware renderer we don't have in phase 1.+ */+ private async listSubmodulePaths(dirPath: string): Promise<Set<string>> {+ const execFileAsync = promisify(execFile);+ try {+ const { stdout } = await execFileAsync('git', ['submodule', 'status'], {+ cwd: dirPath,+ timeout: 5000,+ });+ const paths = new Set<string>();+ for (const line of stdout.split('\n')) {+ if (line.length < 2) continue;+ // Status char: ' ' (clean), '+' (modified content), '-' (uninit), 'U' (conflict).+ if (line[0] === '-') continue;+ // Format: "<status><sha> <path>[ (<describe>)]". Parse via string ops+ // rather than a single regex — combining `\s+` separators with a+ // greedy/lazy path capture trips eslint's ReDoS rule.+ const rest = line.slice(1);+ const firstSpace = rest.indexOf(' ');+ if (firstSpace < 0) continue;+ const sha = rest.slice(0, firstSpace);+ if (!/^[\da-f]{7,40}$/.test(sha)) continue;+ let path = rest.slice(firstSpace + 1);+ // Drop the trailing ` (<describe>)` suffix when present.+ if (path.endsWith(')')) {+ const describeStart = path.lastIndexOf(' (');+ if (describeStart > 0) path = path.slice(0, describeStart);+ }+ if (path) paths.add(path);+ }+ return paths;+ } catch (error: any) {+ logger.debug('[listSubmodulePaths] failed', {+ cwd: dirPath,+ stderr: error?.stderr?.toString?.() ?? error?.stderr,+ });+ return new Set();+ }+ }++ /**+ * Shared implementation for working-tree patch collection. The IPC entry+ * passes `recurseSubmodules: true`; recursive calls into each submodule pass+ * `false` to avoid traversing nested submodules (phase 1).+ */+ private async collectWorkingTreePatches(+ dirPath: string,+ recurseSubmodules: boolean,+ ): Promise<GitWorkingTreePatches> {const MAX_PATCH_BYTES = 256 * 1024;const execFileAsync = promisify(execFile);@@ -751,10 +816,19 @@ export default class GitController extends ControllerModule {status: GitFileDiffStatus;}+ // Step 0 — when recursion is enabled, learn which paths in the parent's+ // status are submodule roots. Their internal diffs are collected separately+ // (see Step 4) so we filter them out of the parent's flat patch list.+ const submodulePaths = recurseSubmodules+ ? await this.listSubmodulePaths(dirPath)+ : new Set<string>();+// Step 1 — classify every dirty path. Mirrors getGitWorkingTreeFiles but// also distinguishes untracked (`??`) from staged-add (`A`) so we can pick- // the right path (git diff vs raw read) per entry.+ // the right path (git diff vs raw read) per entry. Submodule entries are+ // siphoned into `submoduleDirtyEntries` for separate recursion in Step 4.const entries: Entry[] = [];+ const submoduleDirtyEntries: Entry[] = [];try {const { stdout } = await execFileAsync('git', ['status', '--porcelain', '-z'], {cwd: dirPath,@@ -772,20 +846,27 @@ export default class GitController extends ControllerModule {// R/C entries carry an extra source-path token we must consume.if (x === 'R' || x === 'C') i++;if (!filePath) continue;+ let parsed: Entry | null = null;if (x === '?' && y === '?') {- entries.push({ filePath, isUntracked: true, status: 'added' });+ parsed = { filePath, isUntracked: true, status: 'added' };} else if (x === '!' && y === '!') {// ignored} else if (x === 'D' || y === 'D') {- entries.push({ filePath, isUntracked: false, status: 'deleted' });+ parsed = { filePath, isUntracked: false, status: 'deleted' };} else if (x === 'A' || y === 'A') {- entries.push({ filePath, isUntracked: false, status: 'added' });+ parsed = { filePath, isUntracked: false, status: 'added' };+ } else {+ parsed = { filePath, isUntracked: false, status: 'modified' };+ }+ if (!parsed) continue;+ if (submodulePaths.has(filePath)) {+ submoduleDirtyEntries.push(parsed);} else {- entries.push({ filePath, isUntracked: false, status: 'modified' });+ entries.push(parsed);}}} catch (error: any) {- logger.warn('[getGitWorkingTreePatches] status failed', {+ logger.warn('[collectWorkingTreePatches] status failed', {cwd: dirPath,stderr: error?.stderr?.toString?.() ?? error?.stderr,});@@ -818,7 +899,7 @@ export default class GitController extends ControllerModule {30_000,);} catch (error: any) {- logger.warn('[getGitWorkingTreePatches] bulk diff failed; per-file fallback', {+ logger.warn('[collectWorkingTreePatches] bulk diff failed; per-file fallback', {cwd: dirPath,stderr: error?.stderr?.toString?.() ?? error?.stderr,});@@ -855,7 +936,33 @@ export default class GitController extends ControllerModule {const allPatches: GitWorkingTreePatch[] = [...trackedPatches.values(), ...untrackedPatches];allPatches.sort((a, b) => order[a.status] - order[b.status]);- return { patches: allPatches };+ // Step 4 — for each dirty submodule, recurse for its own patches + branch.+ // We only descend one level (`recurseSubmodules: false` on the inner call)+ // because phase 1's UI groups direct children; nested submodules would+ // need a tree view we don't have yet. Empty groups (pointer-only bumps)+ // are kept so the user still sees the submodule surfaced in the panel.+ let submodules: SubmoduleWorkingTreePatches[] | undefined;+ if (submoduleDirtyEntries.length > 0) {+ submodules = await Promise.all(+ submoduleDirtyEntries.map(async (entry) => {+ const absolutePath = path.resolve(dirPath, entry.filePath);+ const [sub, branchInfo] = await Promise.all([+ this.collectWorkingTreePatches(absolutePath, false),+ this.getGitBranch(absolutePath),+ ]);+ return {+ absolutePath,+ branch: branchInfo.branch,+ detached: branchInfo.detached,+ name: path.basename(entry.filePath),+ patches: sub.patches,+ relativePath: entry.filePath,+ };+ }),+ );+ }++ return { patches: allPatches, submodules };}/**@@ -876,7 +983,23 @@ export default class GitController extends ControllerModule {*/@IpcMethod()async getGitBranchDiff(payload: GetGitBranchDiffPayload): Promise<GitBranchDiffPatches> {- const { path: dirPath, baseRef: baseRefOverride } = payload;+ return this.collectBranchDiff(payload.path, payload.baseRef, true);+ }++ /**+ * Shared implementation for branch-diff collection. The IPC entry passes+ * `recurseSubmodules: true`; recursive calls into each submodule pass+ * `false` to avoid traversing nested submodules (phase 1). Each submodule's+ * base ref is resolved independently — we don't try to derive it from the+ * parent's base because (a) the parent's submodule pointer may not exist+ * as a branch ref inside the submodule and (b) "this submodule's branch+ * vs its own remote default" is what users typically want.+ */+ private async collectBranchDiff(+ dirPath: string,+ baseRefOverride: string | undefined,+ recurseSubmodules: boolean,+ ): Promise<GitBranchDiffPatches> {const MAX_PATCH_BYTES = 256 * 1024;const execFileAsync = promisify(execFile);@@ -930,7 +1053,7 @@ export default class GitController extends ControllerModule {30_000,);} catch (error: any) {- logger.warn('[getGitBranchDiff] diff failed', {+ logger.warn('[collectBranchDiff] diff failed', {baseRef,cwd: dirPath,stderr: error?.stderr?.toString?.() ?? error?.stderr,@@ -938,9 +1061,20 @@ export default class GitController extends ControllerModule {if (typeof error?.partialStdout === 'string') bulkDiff = error.partialStdout;}- // Step 4 — split + classify per-file from the diff preamble alone.+ // Step 4 — split per-file. When submodule recursion is enabled, peel out+ // any pointer-bump entries (block path matches a registered submodule)+ // into `pointerBumpPaths`; we'll surface those groups unconditionally in+ // Step 5 even if the submodule's own branch is clean.+ const submodulePaths = recurseSubmodules+ ? await this.listSubmodulePaths(dirPath)+ : new Set<string>();const patches: GitWorkingTreePatch[] = [];+ const pointerBumpPaths = new Set<string>();for (const block of splitBulkDiff(bulkDiff)) {+ if (submodulePaths.has(block.path)) {+ pointerBumpPaths.add(block.path);+ continue;+ }const status = detectDiffBlockStatus(block.patch);patches.push(buildTrackedPatch({ filePath: block.path, status }, block, MAX_PATCH_BYTES));}@@ -948,7 +1082,42 @@ export default class GitController extends ControllerModule {const order: Record<GitFileDiffStatus, number> = { added: 0, modified: 1, deleted: 2 };patches.sort((a, b) => order[a.status] - order[b.status]);- return { baseRef, headRef, patches };+ // Step 5 — recurse for EVERY registered submodule (not just those with+ // pointer-bumps) so we also surface submodules whose own branch diverges+ // from its own origin/HEAD even when the parent's pointer is unchanged.+ // Single-level only (`recurseSubmodules: false` on the inner call). A+ // group is kept when EITHER its pointer changed in the parent OR its own+ // branch diff has at least one patch; submodules that are clean on both+ // axes are dropped to keep the panel quiet. Submodule count is expected+ // to be small (single digits in practice), so per-submodule fetch + diff+ // in parallel is acceptable.+ let submodules: SubmoduleWorkingTreePatches[] | undefined;+ if (submodulePaths.size > 0) {+ const candidates = await Promise.all(+ Array.from(submodulePaths).map(async (relativePath) => {+ const absolutePath = path.resolve(dirPath, relativePath);+ const [sub, branchInfo] = await Promise.all([+ this.collectBranchDiff(absolutePath, undefined, false),+ this.getGitBranch(absolutePath),+ ]);+ return {+ group: {+ absolutePath,+ branch: branchInfo.branch,+ detached: branchInfo.detached,+ name: path.basename(relativePath),+ patches: sub.patches,+ relativePath,+ },+ keep: pointerBumpPaths.has(relativePath) || sub.patches.length > 0,+ };+ }),+ );+ const filtered = candidates.filter((c) => c.keep).map((c) => c.group);+ if (filtered.length > 0) submodules = filtered;+ }++ return { baseRef, headRef, patches, submodules };}/**diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 6c530714a86..5e974c1d087 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -999,6 +999,10 @@"workingPanel.review.empty.noBaseRef": "Couldn't determine the remote default branch. Run `git remote set-head origin --auto` in your terminal.","workingPanel.review.error": "Couldn't load this file's diff","workingPanel.review.expandAll": "Expand all",+ "workingPanel.review.group.collapseDiffs": "Collapse all diffs in this group",+ "workingPanel.review.group.expandDiffs": "Expand all diffs in this group",+ "workingPanel.review.group.fileCount": "{{count}} files",+ "workingPanel.review.group.submoduleClean": "No internal changes","workingPanel.review.mode.branch": "Branch","workingPanel.review.mode.unstaged": "Unstaged","workingPanel.review.more": "More options",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex afb7821ee29..d3eda4f0173 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -101,6 +101,8 @@"builtins.lobe-claude-code.task.updateDeleted": "Deleted","builtins.lobe-claude-code.task.updateInProgress": "Started","builtins.lobe-claude-code.task.updatePending": "Reset",+ "builtins.lobe-claude-code.task.updateSubject.completed": "Task updated",+ "builtins.lobe-claude-code.task.updateSubject.loading": "Updating task","builtins.lobe-claude-code.todoWrite.allDone": "All tasks completed","builtins.lobe-claude-code.todoWrite.currentStep": "Current step","builtins.lobe-claude-code.todoWrite.todos": "Todos",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 1d0e3d80ad6..429d4884bd5 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -999,6 +999,10 @@"workingPanel.review.empty.noBaseRef": "未找到远端默认分支,请在终端执行 `git remote set-head origin --auto`","workingPanel.review.error": "无法加载该文件的 diff","workingPanel.review.expandAll": "全部展开",+ "workingPanel.review.group.collapseDiffs": "折叠该分组的所有 diff",+ "workingPanel.review.group.expandDiffs": "展开该分组的所有 diff",+ "workingPanel.review.group.fileCount": "{{count}} 个文件",+ "workingPanel.review.group.submoduleClean": "子模块内部无变更","workingPanel.review.mode.branch": "分支","workingPanel.review.mode.unstaged": "未暂存","workingPanel.review.more": "更多选项",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 380f628827a..6fa5c659d54 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -101,6 +101,8 @@"builtins.lobe-claude-code.task.updateDeleted": "已删除","builtins.lobe-claude-code.task.updateInProgress": "开始执行","builtins.lobe-claude-code.task.updatePending": "重置为待办",+ "builtins.lobe-claude-code.task.updateSubject.completed": "已更新任务",+ "builtins.lobe-claude-code.task.updateSubject.loading": "正在更新任务","builtins.lobe-claude-code.todoWrite.allDone": "全部任务已完成","builtins.lobe-claude-code.todoWrite.currentStep": "当前步骤","builtins.lobe-claude-code.todoWrite.todos": "待办",diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsxindex b6fc3455636..61866602d1f 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Task.tsx@@ -248,6 +248,37 @@ export const TaskInspector = memo<BuiltinInspectorProps<TaskInspectorArgs, TaskP</div>);}++ // Subject-only edit (rename / initial subject set, no status flip): the+ // per-call signal IS the new subject — surface it like the status branch+ // does, otherwise we fall through to the aggregate "Todos: x/y" chip+ // which buries the per-row signal. Args wins over the pluginState+ // snapshot since this call IS the new value being set.+ const taskId = updateArgs?.taskId;+ const subject =+ updateArgs?.subject ??+ (taskId ? items.find((item) => item.id === taskId)?.text : undefined);+ if (subject) {+ const inFlight = isArgumentsStreaming || isLoading;+ const verb = t(+ inFlight+ ? 'builtins.lobe-claude-code.task.updateSubject.loading'+ : 'builtins.lobe-claude-code.task.updateSubject.completed',+ );+ return (+ <div className={cx(inspectorTextStyles.root, inFlight && shinyTextStyles.shinyText)}>+ <ProgressRing stats={stats} />+ {stats.total > 0 && (+ <span className={styles.countChip}>+ {stats.completed}/{stats.total}+ </span>+ )}+ <span style={{ marginInlineStart: stats.total > 0 ? 6 : 0 }}>+ {`${verb}: ${subject}`}+ </span>+ </div>+ );+ }}// No pluginState yet (args streaming or tool_use → tool_result gap):diff --git a/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsxindex a949e7a59c6..1d9a46b1685 100644--- a/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/Task/index.tsx@@ -230,34 +230,50 @@ const Task = memo<BuiltinRenderProps<TaskUpdateArgs | undefined, TaskPluginState}, [items]);const override = useMemo<TaskHeaderOverride | undefined>(() => {- if (apiName !== ClaudeCodeApiName.TaskUpdate || !args?.status) return undefined;- const { status, taskId, subject: argsSubject } = args;+ if (apiName !== ClaudeCodeApiName.TaskUpdate) return undefined;+ const status = args?.status;+ const taskId = args?.taskId;+ const argsSubject = args?.subject;const resolvedSubject =- (taskId ? items?.find((item) => item.id === taskId)?.text : undefined) ?? argsSubject;- const map = {- completed: {- color: cssVar.colorSuccess,- icon: CircleCheckBig,- label: t('builtins.lobe-claude-code.task.updateCompleted'),- },- deleted: {- color: cssVar.colorError,- icon: CircleX,- label: t('builtins.lobe-claude-code.task.updateDeleted'),- },- in_progress: {- color: cssVar.colorInfo,- icon: CircleArrowRight,- label: t('builtins.lobe-claude-code.task.updateInProgress'),- },- pending: {+ argsSubject ?? (taskId ? items?.find((item) => item.id === taskId)?.text : undefined);+ if (status) {+ const map = {+ completed: {+ color: cssVar.colorSuccess,+ icon: CircleCheckBig,+ label: t('builtins.lobe-claude-code.task.updateCompleted'),+ },+ deleted: {+ color: cssVar.colorError,+ icon: CircleX,+ label: t('builtins.lobe-claude-code.task.updateDeleted'),+ },+ in_progress: {+ color: cssVar.colorInfo,+ icon: CircleArrowRight,+ label: t('builtins.lobe-claude-code.task.updateInProgress'),+ },+ pending: {+ color: cssVar.colorTextSecondary,+ icon: RotateCcw,+ label: t('builtins.lobe-claude-code.task.updatePending'),+ },+ } as const;+ const entry = map[status];+ return { ...entry, detail: resolvedSubject };+ }+ // Subject-only edit: surface the new subject as the header detail so a+ // collapsed panel still reads "Task updated: <subject>" instead of the+ // generic todo aggregate.+ if (argsSubject) {+ return {color: cssVar.colorTextSecondary,- icon: RotateCcw,- label: t('builtins.lobe-claude-code.task.updatePending'),- },- } as const;- const entry = map[status];- return { ...entry, detail: resolvedSubject };+ detail: resolvedSubject,+ icon: ListTodo,+ label: t('builtins.lobe-claude-code.task.updateSubject.completed'),+ };+ }+ return undefined;}, [apiName, args, items, t]);if (!items || items.length === 0) return null;diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.tsindex 342d9a81407..7ae8440d0de 100644--- a/packages/electron-client-ipc/src/types/git.ts+++ b/packages/electron-client-ipc/src/types/git.ts@@ -73,13 +73,50 @@ export interface GitWorkingTreePatch {truncated: boolean;}+/**+ * Patches collected from a dirty submodule of the parent repo. The submodule+ * itself is a self-contained git repo, so its patches use the same+ * `GitWorkingTreePatch` shape; we only add metadata the renderer needs to tag+ * the group and route per-file ops (revert, etc.) into the right working dir.+ */+export interface SubmoduleWorkingTreePatches {+ /**+ * Absolute path on disk — used as the `cwd` for revert / branch operations+ * the renderer fires from inside the group.+ */+ absolutePath: string;+ /** Current branch short name inside the submodule, or short SHA when detached. */+ branch?: string;+ /** True when the submodule's HEAD is detached (no branch ref). */+ detached?: boolean;+ /**+ * Display name — the submodule's directory basename. Matches what users see+ * in `.gitmodules` and in tools like WebStorm's commit grouping.+ */+ name: string;+ /**+ * Per-file diff blocks inside this submodule, same ordering as the parent's+ * `patches`. Empty when the submodule's pointer moved in the parent but the+ * submodule's own working tree is clean.+ */+ patches: GitWorkingTreePatch[];+ /** Path relative to the parent repo root (e.g. `lobehub` or `packages/foo`). */+ relativePath: string;+}+export interface GitWorkingTreePatches {/**- * All dirty file patches, ordered added → modified → deleted to match the- * working-tree file listing. Each entry corresponds to one file path in- * GitWorkingTreeFiles.+ * All dirty file patches in the parent repo, ordered added → modified →+ * deleted. Submodule directories are filtered out of this list — their+ * internal diffs live under `submodules[]` instead.*/patches: GitWorkingTreePatch[];+ /**+ * One group per dirty submodule (pointer bumped, content changed, or both).+ * Undefined when the parent has no submodules with pending changes — lets+ * the renderer keep the flat single-repo layout in that common case.+ */+ submodules?: SubmoduleWorkingTreePatches[];}export interface GitRemoteBranchListItem {@@ -112,10 +149,18 @@ export interface GitBranchDiffPatches {*/headRef?: string;/**- * Per-file diff blocks, ordered added → modified → deleted. Same shape as- * GitWorkingTreePatch so the renderer can reuse the existing PatchDiff path.+ * Per-file diff blocks for the parent repo, ordered added → modified →+ * deleted. Submodule pointer-bump entries are filtered out and their+ * internal branch diffs live under `submodules[]` instead.*/patches: GitWorkingTreePatch[];+ /**+ * One group per submodule whose pointer differs between the parent's base+ * and HEAD. Each group carries the submodule's own branch diff (its HEAD+ * vs its own origin/HEAD). Undefined when no submodules differ — lets the+ * renderer keep the flat single-repo layout in that case.+ */+ submodules?: SubmoduleWorkingTreePatches[];}export interface GitCheckoutResult {diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex f290f37246e..9b3ec72fe89 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -1076,13 +1076,16 @@ export default {'workingPanel.review.copied': 'Path copied','workingPanel.review.copyPath': 'Copy file path','workingPanel.review.revealInTree': 'Reveal in tree',- 'workingPanel.review.revealNotFound': 'File not found in project index','workingPanel.review.empty': 'No working tree changes','workingPanel.review.empty.branch': 'No changes vs {{baseRef}}','workingPanel.review.empty.noBaseRef':"Couldn't determine the remote default branch. Run `git remote set-head origin --auto` in your terminal.",'workingPanel.review.error': "Couldn't load this file's diff",'workingPanel.review.expandAll': 'Expand all',+ 'workingPanel.review.group.collapseDiffs': 'Collapse all diffs in this group',+ 'workingPanel.review.group.expandDiffs': 'Expand all diffs in this group',+ 'workingPanel.review.group.fileCount': '{{count}} files',+ 'workingPanel.review.group.submoduleClean': 'No internal changes','workingPanel.review.mode.branch': 'Branch','workingPanel.review.mode.unstaged': 'Unstaged','workingPanel.review.more': 'More options',diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 99e33e23a6e..99be8f1e4c3 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -73,6 +73,8 @@ export default {'builtins.lobe-claude-code.task.updateDeleted': 'Deleted','builtins.lobe-claude-code.task.updateInProgress': 'Started','builtins.lobe-claude-code.task.updatePending': 'Reset',+ 'builtins.lobe-claude-code.task.updateSubject.completed': 'Task updated',+ 'builtins.lobe-claude-code.task.updateSubject.loading': 'Updating task','builtins.lobe-claude-code.todoWrite.allDone': 'All tasks completed','builtins.lobe-claude-code.todoWrite.currentStep': 'Current step','builtins.lobe-claude-code.todoWrite.todos': 'Todos',diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsxindex 3f4ddb7b2d7..66d463ca9c9 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx@@ -250,15 +250,15 @@ describe('Files — reveal request integration', () => {expect(messageSpy.warning).not.toHaveBeenCalled();});- it('(b) missing path triggers message.warning with localized key', async () => {+ it('(b) missing path is a silent no-op', async () => {render(<Files workingDirectory="/repo" />);setReveal('nonexistent/deep/file.ts', 1);- await vi.waitFor(() => {- expect(messageSpy.warning).toHaveBeenCalledWith('workingPanel.review.revealNotFound');- });+ // Give the effect a tick to run so we can assert nothing happened.+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(messageSpy.warning).not.toHaveBeenCalled();expect(handleSpies.setExpanded).not.toHaveBeenCalled();expect(handleSpies.select).not.toHaveBeenCalled();expect(handleSpies.focus).not.toHaveBeenCalled();diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsxindex 2ccb7062ed3..1ae5300ac36 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx@@ -140,23 +140,15 @@ const Files = memo<FilesProps>(({ workingDirectory }) => {const { path, nonce: _nonce } = revealRequest;const nodeIds = new Set(nodes.map((n) => n.id));- if (!nodeIds.has(path)) {- // Data may still be loading — retry silently instead of showing a warning.- if (!isLoading) {- void message.warning(t('workingPanel.review.revealNotFound'));- }- return;- }+ if (!nodeIds.has(path)) return;const ancestors = getAncestorIds(path);const nextExpanded = Array.from(new Set([...expandedIds, ...ancestors]));treeRef.current?.setExpanded(nextExpanded);treeRef.current?.select(path);treeRef.current?.focus(path);- // Re-run when nonce changes (user re-triggers) or when nodes/isLoading- // update (data arrives after initial reveal attempt).// eslint-disable-next-line react-hooks/exhaustive-deps- }, [revealRequest?.nonce, nodes, isLoading]);+ }, [revealRequest?.nonce, nodes]);const openLocalFile = useChatStore((s) => s.openLocalFile);diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsxnew file mode 100644index 00000000000..07f80cc7194--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsx@@ -0,0 +1,151 @@+'use client';++import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';+import { createStaticStyles } from 'antd-style';+import { ChevronRightIcon } from 'lucide-react';+import { AnimatePresence, m } from 'motion/react';+import { type KeyboardEvent, memo, useCallback } from 'react';++import FileItemBody, { FileItemHeader } from './FileItem';+import type { ReviewMode } from './useReviewPatches';++const styles = createStaticStyles(({ css, cssVar }) => ({+ item: css`+ /* Skip layout/paint of off-screen rows. Preserved from the previous+ implementation. */+ content-visibility: auto;+ contain-intrinsic-size: auto 32px;++ /* Every row carries its own top border — separates file-from-file AND+ file-from-header without doubling up when a group is collapsed. */+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ row: css`+ cursor: pointer;+ user-select: none;++ display: flex;+ gap: 6px;+ align-items: center;++ width: 100%;+ padding-block: 5px;+ padding-inline: 10px;++ transition: background 0.12s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ chevron: css`+ flex: none;+ color: ${cssVar.colorTextTertiary};+ transition: transform 0.2s;++ &[data-expanded='true'] {+ transform: rotate(90deg);+ }+ `,+}));++interface FileRowProps {+ entry: GitWorkingTreePatch;+ expanded: boolean;+ mode: ReviewMode;+ onReverted: () => void;+ onToggle: () => void;+ /** Absolute path of the owning repo — used as the working directory for+ * revert operations so submodule files revert inside the submodule, not+ * the parent repo. */+ repoAbsolutePath: string;+ textDiff: boolean;+ viewMode: 'unified' | 'split';+ wordWrap: boolean;+}++const FileRow = memo<FileRowProps>(+ ({+ entry,+ expanded,+ mode,+ onReverted,+ onToggle,+ repoAbsolutePath,+ textDiff,+ viewMode,+ wordWrap,+ }) => {+ const onKeyDown = useCallback(+ (e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onToggle();+ }+ },+ [onToggle],+ );+ return (+ <div className={styles.item}>+ <div+ data-review-row+ aria-expanded={expanded}+ className={styles.row}+ role={'button'}+ tabIndex={0}+ onClick={onToggle}+ onKeyDown={onKeyDown}+ >+ <ChevronRightIcon+ className={styles.chevron}+ data-expanded={expanded ? 'true' : 'false'}+ size={14}+ />+ <FileItemHeader+ additions={entry.additions}+ deletions={entry.deletions}+ filePath={entry.filePath}+ revertContext={mode === 'unstaged' ? { workingDirectory: repoAbsolutePath } : undefined}+ status={entry.status}+ onReverted={onReverted}+ />+ </div>+ <AnimatePresence initial={false}>+ {expanded && (+ <m.div+ animate={'open'}+ exit={'collapsed'}+ initial={'collapsed'}+ style={{ overflow: 'hidden' }}+ transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}+ variants={{+ collapsed: { height: 0, opacity: 0 },+ open: { height: 'auto', opacity: 1 },+ }}+ >+ <FileItemBody+ expanded+ filePath={entry.filePath}+ isBinary={entry.isBinary}+ patch={entry.patch}+ textDiff={textDiff}+ truncated={entry.truncated}+ viewMode={viewMode}+ wordWrap={wordWrap}+ />+ </m.div>+ )}+ </AnimatePresence>+ </div>+ );+ },+);++FileRow.displayName = 'AgentWorkingSidebarReviewFileRow';++export default FileRow;diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/GroupHeader.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/GroupHeader.tsxnew file mode 100644index 00000000000..48423093be6--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/GroupHeader.tsx@@ -0,0 +1,235 @@+'use client';++import { ActionIcon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { ChevronRightIcon, FoldVerticalIcon, UnfoldVerticalIcon } from 'lucide-react';+import { type KeyboardEvent, memo, type MouseEvent, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css, cssVar }) => ({+ // Sticky group header — appears once per repo (parent + each dirty submodule)+ // when the working tree spans multiple repositories. Mirrors WebStorm's+ // per-repo grouping: collapse chevron + name + file count + totals + branch+ // all left-aligned. Position: sticky keeps the header pinned while scrolling+ // within its group's rows. The whole header is a button — click anywhere to+ // collapse/expand the group's rows. Top-only border (no bottom border) so+ // collapsing a group can't produce a doubled-up line against the next+ // header's top border.+ header: css`+ cursor: pointer;+ user-select: none;++ position: sticky;+ z-index: 1;+ inset-block-start: 0;++ display: flex;+ gap: 6px;+ align-items: center;++ /* Fixed height accommodates the ActionIcon (size='small' is ~24px tall)+ so the header stays the same size whether or not the fold button is+ rendered. Without this, expanding/collapsing a group would jitter the+ sticky header height because the button toggles between rendered and+ not. padding-inline keeps the left-edge alignment with file rows. */+ block-size: 32px;+ padding-inline: 10px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillQuaternary};++ transition: background 0.12s;++ /* Separate non-first groups from the preceding group's last row.+ The first header sits against the list's own top border. */+ &:not(:first-child) {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ chevron: css`+ flex: none;+ color: ${cssVar.colorTextTertiary};+ transition: transform 0.2s;++ &[data-expanded='true'] {+ transform: rotate(90deg);+ }+ `,+ meta: css`+ overflow: hidden;+ display: inline-flex;+ flex: 1 1 auto;+ gap: 6px;+ align-items: center;++ min-width: 0;+ `,+ name: css`+ overflow: hidden;+ flex: 0 1 auto;++ min-width: 0;++ font-weight: 600;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ fileCount: css`+ flex-shrink: 0;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};+ `,+ stats: css`+ display: inline-flex;+ flex-shrink: 0;+ gap: 6px;+ align-items: center;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ `,+ additions: css`+ color: ${cssVar.colorSuccess};+ `,+ deletions: css`+ color: ${cssVar.colorError};+ `,+ branch: css`+ overflow: hidden;+ flex: 0 1 auto;++ min-width: 0;++ font-family: ${cssVar.fontFamilyCode};+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ // Hover-revealed fold-all-diffs button. Uses the standard ActionIcon, so+ // hover/focus visuals match the rest of the panel — we just gate visibility+ // via opacity bound to the parent header's hover/focus-within state.+ foldButton: css`+ margin-inline-start: auto;+ opacity: 0;+ transition: opacity 0.15s;++ [data-review-group-header]:hover &,+ [data-review-group-header]:focus-within & {+ opacity: 1;+ }+ `,+}));++export interface GroupHeaderProps {+ branch?: string;+ collapsed: boolean;+ /** True iff every file diff in the group is currently expanded — drives+ * the fold-button's icon + label. */+ diffsAllExpanded: boolean;+ /** Suppress the fold-all-diffs button (collapsed groups, empty groups). */+ hideFoldButton?: boolean;+ name: string;+ onToggleCollapsed: () => void;+ onToggleDiffs: () => void;+ patchCount: number;+ totalAdditions: number;+ totalDeletions: number;+}++const GroupHeader = memo<GroupHeaderProps>(+ ({+ branch,+ collapsed,+ diffsAllExpanded,+ hideFoldButton,+ name,+ onToggleCollapsed,+ onToggleDiffs,+ patchCount,+ totalAdditions,+ totalDeletions,+ }) => {+ const { t } = useTranslation('chat');+ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onToggleCollapsed();+ }+ },+ [onToggleCollapsed],+ );+ const handleFoldClick = useCallback(+ (e: MouseEvent) => {+ e.stopPropagation();+ onToggleDiffs();+ },+ [onToggleDiffs],+ );+ const foldLabel = diffsAllExpanded+ ? t('workingPanel.review.group.collapseDiffs')+ : t('workingPanel.review.group.expandDiffs');+ return (+ <div+ aria-expanded={!collapsed}+ className={styles.header}+ data-review-group-header={''}+ role={'button'}+ tabIndex={0}+ onClick={onToggleCollapsed}+ onKeyDown={handleKeyDown}+ >+ <div className={styles.meta}>+ <ChevronRightIcon+ className={styles.chevron}+ data-expanded={collapsed ? 'false' : 'true'}+ size={14}+ />+ <span className={styles.name}>{name}</span>+ <span className={styles.fileCount}>+ {t('workingPanel.review.group.fileCount', { count: patchCount })}+ </span>+ {(totalAdditions > 0 || totalDeletions > 0) && (+ <span className={styles.stats}>+ {totalAdditions > 0 && <span className={styles.additions}>+{totalAdditions}</span>}+ {totalDeletions > 0 && <span className={styles.deletions}>-{totalDeletions}</span>}+ </span>+ )}+ {branch && (+ <span className={styles.branch} title={branch}>+ {branch}+ </span>+ )}+ </div>+ {!hideFoldButton && (+ <ActionIcon+ aria-label={foldLabel}+ aria-pressed={diffsAllExpanded}+ className={styles.foldButton}+ icon={diffsAllExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}+ size={'small'}+ title={foldLabel}+ onClick={handleFoldClick}+ />+ )}+ </div>+ );+ },+);++GroupHeader.displayName = 'AgentWorkingSidebarReviewGroupHeader';++export default GroupHeader;diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsxindex 7174ae4dbdb..3f4db8417e2 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx@@ -1,11 +1,11 @@'use client';+import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';import { ActionIcon, Center, type DropdownItem, DropdownMenu, Empty, Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import {ArrowLeftIcon,ChevronDownIcon,- ChevronRightIcon,Columns2Icon,FoldVerticalIcon,GitCompareIcon,@@ -17,16 +17,27 @@ import {WholeWordIcon,WrapTextIcon,} from 'lucide-react';-import { AnimatePresence, m } from 'motion/react';-import { type KeyboardEvent, memo, useMemo, useState } from 'react';+import path from 'path-browserify-esm';+import { Fragment, memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import { useGitInfo } from '@/features/ChatInput/RuntimeConfig/useGitInfo';import { useLocalStorageState } from '@/hooks/useLocalStorageState';-import FileItemBody, { FileItemHeader } from './FileItem';+import FileRow from './FileRow';+import GroupHeader from './GroupHeader';import { type ReviewMode, useGitRemoteBranches, useReviewPatches } from './useReviewPatches';+interface RepoGroup {+ absolutePath: string;+ branch?: string;+ detached?: boolean;+ isParent: boolean;+ name: string;+ patches: GitWorkingTreePatch[];+}+const WORD_WRAP_STORAGE_KEY = 'lobechat-review-word-wrap';const TEXT_DIFF_STORAGE_KEY = 'lobechat-review-text-diff';const VIEW_MODE_STORAGE_KEY = 'lobechat-review-view-mode';@@ -42,8 +53,8 @@ interface ReviewProps {const DEFAULT_EXPAND_BYTE_BUDGET = 100 * 1024;const DEFAULT_EXPAND_MAX_COUNT = 50;-const itemKey = (entry: { filePath: string; status: string }) =>- `${entry.status}:${entry.filePath}`;+const itemKey = (groupPath: string, entry: { filePath: string; status: string }): string =>+ `${groupPath}|${entry.status}:${entry.filePath}`;const styles = createStaticStyles(({ css, cssVar }) => ({caret: css`@@ -67,48 +78,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({font-variant-numeric: tabular-nums;`,list: css`+ position: relative;border-block: 1px solid ${cssVar.colorBorderSecondary};- `,- item: css`- /* Skip layout/paint of off-screen rows. Preserved from the previous- implementation. */- content-visibility: auto;- contain-intrinsic-size: auto 32px;-- & + & {- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- }- `,- row: css`- cursor: pointer;- user-select: none;-- display: flex;- gap: 6px;- align-items: center;-- width: 100%;- padding-block: 5px;- padding-inline: 10px;-- transition: background 0.12s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }-- &:focus-visible {- outline: 2px solid ${cssVar.colorPrimary};- outline-offset: -2px;- }- `,- chevron: css`- flex: none;- color: ${cssVar.colorTextTertiary};- transition: transform 0.2s;- &[data-expanded='true'] {- transform: rotate(90deg);+ /* Strip the first visible row's own top border — the list's+ border-block-start already provides the separator under the subheader,+ so without this we'd render a doubled-up 2px line at the top. */+ & > :first-child {+ border-block-start: none;}`,arrow: css`@@ -202,6 +179,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({padding-block: 4px 8px;padding-inline: 8px;`,+ // Empty submodule group — pointer-only bump where the submodule's own+ // working tree is clean. We still surface the group so the user knows the+ // submodule pointer moved, just with a softer "no changes" line instead of+ // a list of files.+ groupEmpty: css`+ padding-block: 6px 10px;+ padding-inline: 10px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,}));const Review = memo<ReviewProps>(({ workingDirectory }) => {@@ -238,8 +227,15 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {// Memo-stabilise the fallback so downstream useMemo deps don't flap on// every render while the SWR result is undefined.const patches = useMemo(() => data?.patches ?? [], [data]);+ const submoduleGroups = useMemo(() => data?.submodules ?? [], [data]);const baseRef = data?.mode === 'branch' ? data.baseRef : undefined;const headRef = data?.mode === 'branch' ? data.headRef : undefined;+ // Parent branch — only needed for the group header label, so we only fetch+ // it when there's at least one submodule group to render alongside it.+ // SWR-deduped under the hood by `useGitInfo`'s own cache key.+ const { data: parentGitInfo } = useGitInfo(+ submoduleGroups.length > 0 ? workingDirectory : undefined,+ );const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(VIEW_MODE_STORAGE_KEY,'unified',@@ -249,25 +245,78 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {// so we default the persisted toggle to true to preserve current behaviour.const [textDiff, setTextDiff] = useLocalStorageState<boolean>(TEXT_DIFF_STORAGE_KEY, true);- // Default-expand by patch-size budget: take entries until cumulative patch- // bytes exceed DEFAULT_EXPAND_BYTE_BUDGET, capped at DEFAULT_EXPAND_MAX_COUNT.- // Every PatchDiff mounts a Shiki tokenizer synchronously, so expanding too- // much at once locks the renderer; size-based budget keeps small-diff cases- // generous while clamping repos with a few large refactors. Re-syncing on- // signature change auto-expands new entries within the cap; panels the user- // manually closed earlier stay closed because their key is already absent.- const signature = useMemo(() => patches.map(itemKey).join('|'), [patches]);+ // Build the per-repo group list. The parent always comes first; submodules+ // follow in the order the IPC returned them (which is the order they appear+ // in `git status`). The parent group is dropped when it has zero patches+ // *and* at least one submodule exists — we don't want an empty parent+ // header hovering above the submodule rows. Submodule groups with zero+ // patches (pointer-only bumps) are intentionally kept so the user still+ // sees the submodule surfaced.+ const groups = useMemo<RepoGroup[]>(() => {+ const result: RepoGroup[] = [];+ if (patches.length > 0 || submoduleGroups.length === 0) {+ result.push({+ absolutePath: workingDirectory,+ branch: parentGitInfo?.branch,+ detached: parentGitInfo?.detached,+ isParent: true,+ name: path.basename(workingDirectory) || workingDirectory,+ patches,+ });+ }+ for (const sub of submoduleGroups) {+ result.push({+ absolutePath: sub.absolutePath,+ branch: sub.branch,+ detached: sub.detached,+ isParent: false,+ name: sub.name,+ patches: sub.patches,+ });+ }+ return result;+ }, [workingDirectory, parentGitInfo?.branch, parentGitInfo?.detached, patches, submoduleGroups]);+ const showGroupHeaders = submoduleGroups.length > 0;+ const allEntries = useMemo(+ () => groups.flatMap((g) => g.patches.map((p) => ({ group: g, patch: p }))),+ [groups],+ );+ // Per-group collapse state — ephemeral (not persisted across reloads).+ // Stored as a set of repo absolutePaths; entries linger if a group later+ // disappears, which is harmless since nothing renders for missing paths.+ const [collapsedGroupPaths, setCollapsedGroupPaths] = useState<Set<string>>(() => new Set());+ const toggleGroupCollapsed = (absolutePath: string) => {+ setCollapsedGroupPaths((prev) => {+ const next = new Set(prev);+ if (next.has(absolutePath)) next.delete(absolutePath);+ else next.add(absolutePath);+ return next;+ });+ };++ // Default-expand by patch-size budget: take entries (across all groups in+ // order) until cumulative patch bytes exceed DEFAULT_EXPAND_BYTE_BUDGET,+ // capped at DEFAULT_EXPAND_MAX_COUNT. Every PatchDiff mounts a Shiki+ // tokenizer synchronously, so expanding too much at once locks the renderer;+ // size-based budget keeps small-diff cases generous while clamping repos+ // with a few large refactors. Re-syncing on signature change auto-expands+ // new entries within the cap; panels the user manually closed earlier stay+ // closed because their key is already absent.+ const signature = useMemo(+ () => allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)).join('|'),+ [allEntries],+ );const [seenSignature, setSeenSignature] = useState('');const [activeKeys, setActiveKeys] = useState<string[]>([]);if (signature !== seenSignature) {setSeenSignature(signature);const initialKeys: string[] = [];let budget = DEFAULT_EXPAND_BYTE_BUDGET;- for (const entry of patches) {+ for (const { group, patch } of allEntries) {if (initialKeys.length >= DEFAULT_EXPAND_MAX_COUNT) break;- const cost = entry.patch?.length ?? 0;+ const cost = patch.patch?.length ?? 0;if (initialKeys.length > 0 && cost > budget) break;- initialKeys.push(itemKey(entry));+ initialKeys.push(itemKey(group.absolutePath, patch));budget -= cost;}setActiveKeys(initialKeys);@@ -281,15 +330,18 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {);}- const allExpanded = patches.length > 0 && activeKeys.length === patches.length;+ const totalEntryCount = allEntries.length;+ const allExpanded = totalEntryCount > 0 && activeKeys.length === totalEntryCount;const handleToggleAll = () => {- setActiveKeys(allExpanded ? [] : patches.map(itemKey));+ setActiveKeys(+ allExpanded ? [] : allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)),+ );};- const totals = patches.reduce(- (acc, entry) => {- acc.additions += entry.additions ?? 0;- acc.deletions += entry.deletions ?? 0;+ const totals = allEntries.reduce(+ (acc, { patch }) => {+ acc.additions += patch.additions ?? 0;+ acc.deletions += patch.deletions ?? 0;return acc;},{ additions: 0, deletions: 0 },@@ -376,7 +428,10 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {},];- const isEmpty = patches.length === 0;+ // A pointer-only submodule bump produces a group with no file patches but is+ // still worth surfacing (the GroupHeader + "submodule clean" line), so don't+ // collapse into the global empty state when any submodule group is present.+ const isEmpty = totalEntryCount === 0 && submoduleGroups.length === 0;const emptyText =mode === 'branch'? baseRef@@ -435,7 +490,7 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {)}</Flexbox><Flexbox horizontal align={'center'} gap={2}>- {!isEmpty && (+ {totalEntryCount > 0 && (<ActionIconicon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}size={'small'}@@ -463,71 +518,78 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {</Center>) : (<Flexbox className={styles.list} style={{ overflow: 'auto' }} width={'100%'}>- {patches.map((entry) => {- const key = itemKey(entry);- const expanded = activeKeys.includes(key);- const toggle = () =>- setActiveKeys((prev) =>- prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],- );- const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- toggle();- }+ {groups.map((group) => {+ const groupTotals = group.patches.reduce(+ (acc, p) => {+ acc.additions += p.additions ?? 0;+ acc.deletions += p.deletions ?? 0;+ return acc;+ },+ { additions: 0, deletions: 0 },+ );+ const groupCollapsed = collapsedGroupPaths.has(group.absolutePath);+ const groupItemKeys = group.patches.map((p) => itemKey(group.absolutePath, p));+ const groupAllExpanded =+ groupItemKeys.length > 0 && groupItemKeys.every((k) => activeKeys.includes(k));+ const toggleGroupDiffs = () => {+ setActiveKeys((prev) => {+ if (groupAllExpanded) {+ const set = new Set(groupItemKeys);+ return prev.filter((k) => !set.has(k));+ }+ const next = new Set(prev);+ for (const k of groupItemKeys) next.add(k);+ return Array.from(next);+ });};return (- <div className={styles.item} key={key}>- <div- data-review-row- aria-expanded={expanded}- className={styles.row}- role={'button'}- tabIndex={0}- onClick={toggle}- onKeyDown={onKeyDown}- >- <ChevronRightIcon- className={styles.chevron}- data-expanded={expanded ? 'true' : 'false'}- size={14}- />- <FileItemHeader- additions={entry.additions}- deletions={entry.deletions}- filePath={entry.filePath}- revertContext={mode === 'unstaged' ? { workingDirectory } : undefined}- status={entry.status}- onReverted={() => void mutate()}+ <Fragment key={group.absolutePath}>+ {showGroupHeaders && (+ <GroupHeader+ branch={group.branch}+ collapsed={groupCollapsed}+ diffsAllExpanded={groupAllExpanded}+ hideFoldButton={groupCollapsed || group.patches.length === 0}+ name={group.name}+ patchCount={group.patches.length}+ totalAdditions={groupTotals.additions}+ totalDeletions={groupTotals.deletions}+ onToggleCollapsed={() => toggleGroupCollapsed(group.absolutePath)}+ onToggleDiffs={toggleGroupDiffs}/>- </div>- <AnimatePresence initial={false}>- {expanded && (- <m.div- animate={'open'}- exit={'collapsed'}- initial={'collapsed'}- style={{ overflow: 'hidden' }}- transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}- variants={{- collapsed: { height: 0, opacity: 0 },- open: { height: 'auto', opacity: 1 },- }}- >- <FileItemBody- expanded- filePath={entry.filePath}- isBinary={entry.isBinary}- patch={entry.patch}+ )}+ {showGroupHeaders &&+ !groupCollapsed &&+ !group.isParent &&+ group.patches.length === 0 && (+ <div className={styles.groupEmpty}>+ {t('workingPanel.review.group.submoduleClean')}+ </div>+ )}+ {!groupCollapsed &&+ group.patches.map((entry) => {+ const key = itemKey(group.absolutePath, entry);+ const expanded = activeKeys.includes(key);+ return (+ <FileRow+ entry={entry}+ expanded={expanded}+ key={key}+ mode={mode}+ repoAbsolutePath={group.absolutePath}textDiff={textDiff}- truncated={entry.truncated}viewMode={viewMode}wordWrap={wordWrap}+ onReverted={() => void mutate()}+ onToggle={() =>+ setActiveKeys((prev) =>+ prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],+ )+ }/>- </m.div>- )}- </AnimatePresence>- </div>+ );+ })}+ </Fragment>);})}</Flexbox>diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.tsindex 96c921c6a8a..ac50cacbab2 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts@@ -1,5 +1,8 @@import { isDesktop } from '@lobechat/const';-import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';+import type {+ GitWorkingTreePatch,+ SubmoduleWorkingTreePatches,+} from '@lobechat/electron-client-ipc';import { useClientDataSWR } from '@/libs/swr';import { electronGitService } from '@/services/electron/git';@@ -11,11 +14,18 @@ export interface ReviewPatchesData {headRef?: string;mode: ReviewMode;patches: GitWorkingTreePatch[];+ /**+ * Per-submodule patch groups. Undefined when the parent has no dirty+ * submodules (unstaged) or no submodule pointer differences (branch) — the+ * Review panel keeps its flat single-repo layout in that case. Branch-mode+ * groups carry the submodule's own branch diff against its own origin/HEAD.+ */+ submodules?: SubmoduleWorkingTreePatches[];}const fetchUnstaged = async (dirPath: string): Promise<ReviewPatchesData> => {const result = await electronGitService.getGitWorkingTreePatches(dirPath);- return { mode: 'unstaged', patches: result.patches };+ return { mode: 'unstaged', patches: result.patches, submodules: result.submodules };};const fetchBranch = async (@@ -28,6 +38,7 @@ const fetchBranch = async (headRef: result.headRef,mode: 'branch',patches: result.patches,+ submodules: result.submodules,};};diff --git a/src/server/services/agentDocuments/index.ts b/src/server/services/agentDocuments/index.tsindex 8cfc7f8a53c..3203bf5e389 100644--- a/src/server/services/agentDocuments/index.ts+++ b/src/server/services/agentDocuments/index.ts@@ -26,6 +26,7 @@ import { TopicDocumentModel } from '@/database/models/topicDocument';import { AgentDocumentVfsError } from '../agentDocumentVfs/errors';import { isManagedSkillDocument } from '../agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';import { DocumentService } from '../document';+import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';import {type AgentDocumentLiteXMLOperation,applyLiteXMLOperations,@@ -55,6 +56,34 @@ interface CreateAgentDocumentOptions {type AgentDocumentWithLiteXML = AgentDocument & { litexml?: string };+/**+ * Hide the auto-created `.tool-results/` archive (root folder + its children)+ * from user-facing document lists. Agents still discover archived entries via+ * the tool-oriented `listDocuments` / `listDocumentsForTopic` paths, which hit+ * the model directly.+ */+const excludeArchivedToolResults = <+ T extends Pick<AgentDocument, 'documentId' | 'parentId' | 'filename' | 'fileType'>,+>(+ docs: T[],+): T[] => {+ const archiveFolderIds = new Set(+ docs+ .filter(+ (d) =>+ d.filename === TOOL_RESULTS_DIR_NAME &&+ !d.parentId &&+ d.fileType === DOCUMENT_FOLDER_TYPE,+ )+ .map((d) => d.documentId),+ );+ if (archiveFolderIds.size === 0) return docs;+ return docs.filter(+ (d) =>+ !archiveFolderIds.has(d.documentId) && (!d.parentId || !archiveFolderIds.has(d.parentId)),+ );+};+/*** Service for managing agent documents with reusable template sets.* Document-level policy controls runtime behavior (context rendering/retrieval).@@ -234,7 +263,7 @@ export class AgentDocumentsService {async getAgentDocuments(agentId: string): Promise<AgentDocumentWithRules[]> {const docs = await this.agentDocumentModel.findByAgent(agentId);- return this.projectDocuments(docs);+ return this.projectDocuments(excludeArchivedToolResults(docs));}/**diff --git a/src/server/services/toolExecution/archiveToolResult.ts b/src/server/services/toolExecution/archiveToolResult.tsindex 340398bb7f8..a46308f0bdf 100644--- a/src/server/services/toolExecution/archiveToolResult.ts+++ b/src/server/services/toolExecution/archiveToolResult.ts@@ -8,7 +8,9 @@ import {truncateToolResult,} from '@/server/utils/truncateToolResult';-const TOOL_RESULTS_DIR = './.tool-results';+import { TOOL_RESULTS_DIR_NAME } from './constants';++const TOOL_RESULTS_DIR = `./${TOOL_RESULTS_DIR_NAME}`;export interface ToolResultArchiveOutcome {archived: boolean;diff --git a/src/server/services/toolExecution/constants.ts b/src/server/services/toolExecution/constants.tsnew file mode 100644index 00000000000..635b1e5b8e0--- /dev/null+++ b/src/server/services/toolExecution/constants.ts@@ -0,0 +1 @@+export const TOOL_RESULTS_DIR_NAME = '.tool-results';