🤯 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(heterogeneous-agent): git-aware runtime config + topic rename modal + inspectors (#13951)
Arvin Xu7d5889a7ed6b
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex 2a40b0109bf..8026c19a845 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -1,8 +1,18 @@+import { execFile } from 'node:child_process';import { readFile } from 'node:fs/promises';import path from 'node:path';import process from 'node:process';--import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';+import { promisify } from 'node:util';++import type {+ ElectronAppState,+ GitBranchInfo,+ GitBranchListItem,+ GitCheckoutResult,+ GitLinkedPullRequestResult,+ GitWorkingTreeStatus,+ ThemeMode,+} from '@lobechat/electron-client-ipc';import { app, dialog, nativeTheme, shell } from 'electron';import { macOS } from 'electron-is';import { pathExists, readdir } from 'fs-extra';@@ -235,7 +245,8 @@ export default class SystemController extends ControllerModule {}}- private async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {+ @IpcMethod()+ async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {const gitConfigPath = path.join(dirPath, '.git', 'config');try {const config = await readFile(gitConfigPath, 'utf8');@@ -246,6 +257,213 @@ export default class SystemController extends ControllerModule {}}+ /**+ * Read current git branch from `.git/HEAD`. Returns short sha on detached HEAD.+ * Handles both standard `.git` directories and `.git` worktree pointer files.+ */+ @IpcMethod()+ async getGitBranch(dirPath: string): Promise<GitBranchInfo> {+ try {+ const gitDir = await this.resolveGitDir(dirPath);+ if (!gitDir) return {};++ const head = (await readFile(path.join(gitDir, 'HEAD'), 'utf8')).trim();+ const refMatch = /^ref:\s*refs\/heads\/(.+)$/.exec(head);+ if (refMatch) {+ return { branch: refMatch[1] };+ }+ // Detached HEAD — HEAD file contains the full sha+ if (/^[\da-f]{40}$/i.test(head)) {+ return { branch: head.slice(0, 7), detached: true };+ }+ return {};+ } catch {+ return {};+ }+ }++ /**+ * Query `gh` CLI for an open pull request whose head branch matches `branch`.+ * Returns status = 'gh-missing' when `gh` is not installed / not authenticated,+ * so the UI can render a helpful tooltip instead of an error.+ */+ @IpcMethod()+ async getLinkedPullRequest(payload: {+ branch: string;+ path: string;+ }): Promise<GitLinkedPullRequestResult> {+ const { path: dirPath, branch } = payload;+ if (!branch) {+ return { pullRequest: null, status: 'ok' };+ }++ const execFileAsync = promisify(execFile);+ try {+ const { stdout } = await execFileAsync(+ 'gh',+ [+ 'pr',+ 'list',+ '--head',+ branch,+ '--state',+ 'open',+ '--limit',+ '5',+ '--json',+ 'number,url,title,state',+ ],+ { cwd: dirPath, timeout: 8000 },+ );+ const parsed = JSON.parse(stdout.trim() || '[]') as Array<{+ number: number;+ state: string;+ title: string;+ url: string;+ }>;+ if (parsed.length === 0) {+ return { pullRequest: null, status: 'ok' };+ }+ const [primary, ...rest] = parsed;+ return {+ extraCount: rest.length,+ pullRequest: primary,+ status: 'ok',+ };+ } catch (error: any) {+ const code = error?.code;+ const stderr: string = error?.stderr ?? '';+ // `gh` binary not on PATH+ if (code === 'ENOENT') {+ return { pullRequest: null, status: 'gh-missing' };+ }+ // gh reports auth issues via stderr; treat as a soft-fail+ if (/auth\s+login|not\s+logged\s+in|authentication/i.test(stderr)) {+ return { pullRequest: null, status: 'gh-missing' };+ }+ logger.debug('[getLinkedPullRequest] failed', { branch, code, stderr });+ return { pullRequest: null, status: 'error' };+ }+ }++ /**+ * List local git branches ordered by most recent commit.+ * `current` is true for the checked-out branch.+ */+ @IpcMethod()+ async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {+ const execFileAsync = promisify(execFile);+ try {+ const { stdout } = await execFileAsync(+ 'git',+ [+ 'for-each-ref',+ '--sort=-committerdate',+ '--format=%(HEAD)%09%(refname:short)%09%(upstream:short)',+ 'refs/heads',+ ],+ { cwd: dirPath, timeout: 5000 },+ );+ return stdout+ .replaceAll('\r', '')+ .split('\n')+ .filter((line) => line.length > 0)+ .map((line) => {+ // Line format: "<HEAD-marker>\t<branch>\t<upstream>" where HEAD-marker is '*' or ' '+ const [head, name, upstream] = line.split('\t');+ return {+ current: head === '*',+ name: name ?? '',+ upstream: upstream || undefined,+ };+ })+ .filter((b) => b.name);+ } catch (error: any) {+ logger.warn('[listGitBranches] git command failed', {+ code: error?.code,+ cwd: dirPath,+ message: error?.message,+ stderr: error?.stderr?.toString?.() ?? error?.stderr,+ });+ return [];+ }+ }++ /**+ * Count unstaged / staged / untracked files via `git status --porcelain`.+ */+ @IpcMethod()+ async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {+ const execFileAsync = promisify(execFile);+ try {+ const { stdout } = await execFileAsync('git', ['status', '--porcelain'], {+ cwd: dirPath,+ timeout: 5000,+ });+ const lines = stdout.split('\n').filter((line) => line.trim().length > 0);+ return { clean: lines.length === 0, modified: lines.length };+ } catch {+ return { clean: true, modified: 0 };+ }+ }++ /**+ * Check out (or create + check out) a branch.+ * Relies on git itself to reject unsafe checkouts (dirty tree, non-fast-forward, etc.)+ * and surfaces git's stderr so the UI can display a meaningful error.+ */+ @IpcMethod()+ async checkoutGitBranch(payload: {+ branch: string;+ create?: boolean;+ path: string;+ }): Promise<GitCheckoutResult> {+ const { path: dirPath, branch, create } = payload;+ if (!branch?.trim()) {+ return { error: 'Branch name is required', success: false };+ }+ // Reject obviously invalid refs early to avoid a confusing git error+ if (/[\s~^:?*[\\]/.test(branch) || branch.startsWith('-') || branch.includes('..')) {+ return { error: `Invalid branch name: ${branch}`, success: false };+ }++ const execFileAsync = promisify(execFile);+ const args = create ? ['checkout', '-b', branch] : ['checkout', branch];+ try {+ await execFileAsync('git', args, { cwd: dirPath, timeout: 10_000 });+ return { success: true };+ } catch (error: any) {+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();+ logger.debug('[checkoutGitBranch] failed', { args, stderr });+ return { error: stderr || 'git checkout failed', success: false };+ }+ }++ /**+ * Resolve the actual `.git` directory for a working tree.+ * Supports both standard layouts and worktree pointer files (`.git` as a regular file).+ */+ private async resolveGitDir(dirPath: string): Promise<string | undefined> {+ const gitPath = path.join(dirPath, '.git');+ try {+ const content = await readFile(gitPath, 'utf8');+ const worktreeMatch = /^gitdir:\s*(\S.*)$/m.exec(content.trim());+ if (worktreeMatch) {+ const resolved = worktreeMatch[1].trim();+ return path.isAbsolute(resolved) ? resolved : path.resolve(dirPath, resolved);+ }+ } catch {+ // `.git` is a directory (EISDIR) or missing — fall through+ }+ try {+ const stat = await readdir(gitPath);+ if (stat.length > 0) return gitPath;+ } catch {+ return undefined;+ }+ return undefined;+ }+private async setSystemThemeMode(themeMode: ThemeMode) {nativeTheme.themeSource = themeMode;}diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex e59e4ddb808..bc783450f62 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -65,6 +65,9 @@"builtins.lobe-agent-management.render.installPlugin.plugin": "Plugin","builtins.lobe-agent-management.render.installPlugin.success": "Installed successfully","builtins.lobe-agent-management.title": "Agent Manager",+ "builtins.lobe-claude-code.todoWrite.allDone": "All tasks completed",+ "builtins.lobe-claude-code.todoWrite.currentStep": "Current step",+ "builtins.lobe-claude-code.todoWrite.todos": "Todos","builtins.lobe-cloud-sandbox.apiName.editLocalFile": "Edit file","builtins.lobe-cloud-sandbox.apiName.executeCode": "Execute code","builtins.lobe-cloud-sandbox.apiName.exportFile": "Export file",@@ -432,18 +435,34 @@"loading.plugin": "Skill running…","localSystem.workingDirectory.agentDescription": "Default working directory for all conversations with this Agent","localSystem.workingDirectory.agentLevel": "Agent Working Directory",+ "localSystem.workingDirectory.branchSearchPlaceholder": "Search branches",+ "localSystem.workingDirectory.branchesEmpty": "No local branches",+ "localSystem.workingDirectory.branchesHeading": "Branches",+ "localSystem.workingDirectory.branchesLoading": "Loading branches…",+ "localSystem.workingDirectory.branchesNoMatch": "No matching branches",+ "localSystem.workingDirectory.cancel": "Cancel",+ "localSystem.workingDirectory.checkoutAction": "Checkout",+ "localSystem.workingDirectory.checkoutFailed": "Checkout failed","localSystem.workingDirectory.chooseDifferentFolder": "Choose a different folder",+ "localSystem.workingDirectory.createBranchAction": "Checkout new branch…","localSystem.workingDirectory.current": "Current working directory",+ "localSystem.workingDirectory.detachedHead": "Detached HEAD at {{sha}}",+ "localSystem.workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests",+ "localSystem.workingDirectory.newBranchPlaceholder": "feature/new-branch-name","localSystem.workingDirectory.noRecent": "No recent directories","localSystem.workingDirectory.notSet": "Click to set working directory","localSystem.workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects",+ "localSystem.workingDirectory.prTooltipWithExtra": "{{title}} (+{{count}} more open PR on this branch)","localSystem.workingDirectory.recent": "Recent",+ "localSystem.workingDirectory.refreshGitStatus": "Refresh branch & PR status","localSystem.workingDirectory.removeRecent": "Remove from recent","localSystem.workingDirectory.selectFolder": "Select folder","localSystem.workingDirectory.title": "Working Directory","localSystem.workingDirectory.topicDescription": "Override Agent default for this conversation only","localSystem.workingDirectory.topicLevel": "Conversation override","localSystem.workingDirectory.topicOverride": "Override for this conversation",+ "localSystem.workingDirectory.uncommittedChanges_one": "Uncommitted changes: {{count}} file",+ "localSystem.workingDirectory.uncommittedChanges_other": "Uncommitted changes: {{count}} files","mcpEmpty.deployment": "No deployment options","mcpEmpty.prompts": "No prompts","mcpEmpty.resources": "No resources",diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 9604e4b5ac2..dac71643c52 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -41,6 +41,8 @@"importSuccess": "Successfully imported {{count}} messages","loadMore": "Load More","newTopic": "New Topic",+ "renameModal.description": "Keep it short and easy to recognize.",+ "renameModal.title": "Rename Topic","searchPlaceholder": "Search Topics...","searchResultEmpty": "No search results found.","temp": "Temporary",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex b66fc7535c3..00939535a34 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -65,6 +65,9 @@"builtins.lobe-agent-management.render.installPlugin.plugin": "插件","builtins.lobe-agent-management.render.installPlugin.success": "安装成功","builtins.lobe-agent-management.title": "代理管理器",+ "builtins.lobe-claude-code.todoWrite.allDone": "全部任务已完成",+ "builtins.lobe-claude-code.todoWrite.currentStep": "当前步骤",+ "builtins.lobe-claude-code.todoWrite.todos": "待办","builtins.lobe-cloud-sandbox.apiName.editLocalFile": "编辑文件","builtins.lobe-cloud-sandbox.apiName.executeCode": "执行代码","builtins.lobe-cloud-sandbox.apiName.exportFile": "导出文件",@@ -432,18 +435,34 @@"loading.plugin": "技能运行中…","localSystem.workingDirectory.agentDescription": "该助手下所有对话的默认工作目录","localSystem.workingDirectory.agentLevel": "代理工作目录",+ "localSystem.workingDirectory.branchSearchPlaceholder": "搜索分支",+ "localSystem.workingDirectory.branchesEmpty": "暂无本地分支",+ "localSystem.workingDirectory.branchesHeading": "分支",+ "localSystem.workingDirectory.branchesLoading": "加载分支中…",+ "localSystem.workingDirectory.branchesNoMatch": "没有匹配的分支",+ "localSystem.workingDirectory.cancel": "取消",+ "localSystem.workingDirectory.checkoutAction": "切换分支",+ "localSystem.workingDirectory.checkoutFailed": "切换分支失败","localSystem.workingDirectory.chooseDifferentFolder": "选择其他文件夹",+ "localSystem.workingDirectory.createBranchAction": "检出新分支…","localSystem.workingDirectory.current": "当前工作目录",+ "localSystem.workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}",+ "localSystem.workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",+ "localSystem.workingDirectory.newBranchPlaceholder": "feature/新分支名称","localSystem.workingDirectory.noRecent": "暂无最近目录","localSystem.workingDirectory.notSet": "点击设置工作目录","localSystem.workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects",+ "localSystem.workingDirectory.prTooltipWithExtra": "{{title}}(此分支还有 {{count}} 个开放 PR)","localSystem.workingDirectory.recent": "最近使用",+ "localSystem.workingDirectory.refreshGitStatus": "刷新分支与 PR 状态","localSystem.workingDirectory.removeRecent": "从最近目录中移除","localSystem.workingDirectory.selectFolder": "选择文件夹","localSystem.workingDirectory.title": "工作目录","localSystem.workingDirectory.topicDescription": "仅覆盖当前对话的工作目录","localSystem.workingDirectory.topicLevel": "对话覆盖","localSystem.workingDirectory.topicOverride": "为当前对话覆盖设置",+ "localSystem.workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件",+ "localSystem.workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件","mcpEmpty.deployment": "暂无部署选项","mcpEmpty.prompts": "该技能暂无提示词","mcpEmpty.resources": "该技能暂无资源",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex 3e155d83803..ac91719307a 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -41,6 +41,8 @@"importSuccess": "已导入 {{count}} 条消息","loadMore": "更多","newTopic": "新话题",+ "renameModal.description": "保持简短且易于识别。",+ "renameModal.title": "重命名话题","searchPlaceholder": "搜索话题…","searchResultEmpty": "暂无搜索结果","temp": "临时",diff --git a/packages/builtin-tool-claude-code/src/client/Inspector.tsx b/packages/builtin-tool-claude-code/src/client/Inspector.tsxindex f1764d0615c..fafb1efe35c 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector.tsx+++ b/packages/builtin-tool-claude-code/src/client/Inspector.tsx@@ -11,6 +11,7 @@ import { ClaudeCodeApiName } from '../types';import { ReadInspector } from './ReadInspector';import { SkillInspector } from './SkillInspector';import { TodoWriteInspector } from './TodoWriteInspector';+import { ToolSearchInspector } from './ToolSearchInspector';import { WriteInspector } from './WriteInspector';// CC's own tool names (Bash / Edit / Glob / Grep / Read / Write) are already@@ -32,5 +33,6 @@ export const ClaudeCodeInspectors = {[ClaudeCodeApiName.Read]: ReadInspector,[ClaudeCodeApiName.Skill]: SkillInspector,[ClaudeCodeApiName.TodoWrite]: TodoWriteInspector,+ [ClaudeCodeApiName.ToolSearch]: ToolSearchInspector,[ClaudeCodeApiName.Write]: WriteInspector,};diff --git a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsxindex a4e62451e08..e4370c312b0 100644--- a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx@@ -1,10 +1,12 @@'use client';+import { highlightTextStyles } from '@lobechat/shared-tool-ui/styles';import type { BuiltinRenderProps } from '@lobechat/types';-import { Block, Checkbox, Icon, Text } from '@lobehub/ui';+import { Block, Checkbox, Icon } from '@lobehub/ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import { CircleArrowRight, CircleCheckBig, ListTodo } from 'lucide-react';import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';import type { ClaudeCodeTodoItem, TodoWriteArgs } from '../../../types';@@ -22,9 +24,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,headerLabel: css`overflow: hidden;+ display: flex;flex: 1;+ gap: 0;+ align-items: center;- color: ${cssVar.colorText};+ min-width: 0;++ color: ${cssVar.colorTextSecondary};text-overflow: ellipsis;white-space: nowrap;`,@@ -78,7 +85,7 @@ const TodoRow = memo<TodoRowProps>(({ item }) => {if (status === 'in_progress') {return (<div className={cx(styles.itemRow, styles.processingRow)}>- <Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorPrimary }} />+ <Icon icon={CircleArrowRight} size={17} style={{ color: cssVar.colorInfo }} /><span className={styles.textProcessing}>{activeForm || content}</span></div>);@@ -114,32 +121,35 @@ interface TodoHeaderProps {}const TodoHeader = memo<TodoHeaderProps>(({ completed, total, inProgress }) => {+ const { t } = useTranslation('plugin');const allDone = total > 0 && completed === total;- const { icon, color, label } = inProgress- ? {- color: cssVar.colorPrimary,- icon: CircleArrowRight,- label: inProgress.activeForm || inProgress.content,- }+ const icon = inProgress ? CircleArrowRight : allDone ? CircleCheckBig : ListTodo;+ const color = inProgress+ ? cssVar.colorInfo+ : allDone+ ? cssVar.colorSuccess+ : cssVar.colorTextSecondary;++ const label = inProgress+ ? t('builtins.lobe-claude-code.todoWrite.currentStep'): allDone- ? {- color: cssVar.colorSuccess,- icon: CircleCheckBig,- label: 'All tasks completed',- }- : {- color: cssVar.colorTextSecondary,- icon: ListTodo,- label: 'Todos',- };+ ? t('builtins.lobe-claude-code.todoWrite.allDone')+ : t('builtins.lobe-claude-code.todoWrite.todos');+ const detail = inProgress ? inProgress.activeForm || inProgress.content : undefined;return (<div className={styles.header}><Icon icon={icon} size={16} style={{ color, flexShrink: 0 }} />- <Text className={styles.headerLabel} strong={!!inProgress}>- {label}- </Text>+ <div className={styles.headerLabel}>+ <span>{label}</span>+ {detail && (+ <>+ <span>: </span>+ <span className={highlightTextStyles.primary}>{detail}</span>+ </>+ )}+ </div><span className={styles.headerCount}>{completed}/{total}</span>diff --git a/packages/builtin-tool-claude-code/src/client/TodoWriteInspector.tsx b/packages/builtin-tool-claude-code/src/client/TodoWriteInspector.tsxindex 8b77d89f1f1..aa694f55a92 100644--- a/packages/builtin-tool-claude-code/src/client/TodoWriteInspector.tsx+++ b/packages/builtin-tool-claude-code/src/client/TodoWriteInspector.tsx@@ -10,7 +10,7 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { ClaudeCodeApiName, type ClaudeCodeTodoItem, type TodoWriteArgs } from '../types';+import { type ClaudeCodeTodoItem, type TodoWriteArgs } from '../types';const RING_SIZE = 14;const RING_STROKE = 2;@@ -47,7 +47,7 @@ const ProgressRing = memo<ProgressRingProps>(({ stats }) => {const { completed, total } = stats;const ratio = total > 0 ? completed / total : 0;const allDone = total > 0 && completed === total;- const color = allDone ? cssVar.colorSuccess : cssVar.colorPrimary;+ const color = allDone ? cssVar.colorSuccess : cssVar.colorInfo;return (<svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>@@ -86,19 +86,24 @@ const computeStats = (args?: TodoWriteArgs): TodoStats => {};};-const getSummary = (stats: TodoStats): string | undefined => {- if (stats.total === 0) return undefined;- if (stats.inProgress) return stats.inProgress.activeForm || stats.inProgress.content;- return `${stats.completed}/${stats.total}`;-};-export const TodoWriteInspector = memo<BuiltinInspectorProps<TodoWriteArgs>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');- const label = t(ClaudeCodeApiName.TodoWrite as any);const stats = useMemo(() => computeStats(args || partialArgs), [args, partialArgs]);- const summary = getSummary(stats);+ const allDone = stats.total > 0 && stats.completed === stats.total;++ const label = stats.inProgress+ ? t('builtins.lobe-claude-code.todoWrite.currentStep')+ : allDone+ ? t('builtins.lobe-claude-code.todoWrite.allDone')+ : t('builtins.lobe-claude-code.todoWrite.todos');++ const detail = stats.inProgress+ ? stats.inProgress.activeForm || stats.inProgress.content+ : stats.total > 0 && !allDone+ ? `${stats.completed}/${stats.total}`+ : undefined;if (isArgumentsStreaming && stats.total === 0) {return <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>{label}</div>;@@ -113,10 +118,10 @@ export const TodoWriteInspector = memo<BuiltinInspectorProps<TodoWriteArgs>>(>{stats.total > 0 && <ProgressRing stats={stats} />}<span>{label}</span>- {summary && (+ {detail && (<><span>: </span>- <span className={highlightTextStyles.primary}>{summary}</span>+ <span className={highlightTextStyles.primary}>{detail}</span></>)}</div>diff --git a/packages/builtin-tool-claude-code/src/client/ToolSearchInspector.tsx b/packages/builtin-tool-claude-code/src/client/ToolSearchInspector.tsxnew file mode 100644index 00000000000..6d8ee794d9d--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/ToolSearchInspector.tsx@@ -0,0 +1,62 @@+'use client';++import {+ highlightTextStyles,+ inspectorTextStyles,+ shinyTextStyles,+} from '@lobechat/shared-tool-ui/styles';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { ClaudeCodeApiName, type ToolSearchArgs } from '../types';++const SELECT_PREFIX = 'select:';++/**+ * `select:A,B,C` → `A, B, C` (names the model is loading by exact match).+ * Keyword queries pass through unchanged.+ */+const formatQuery = (query?: string): string | undefined => {+ if (!query) return undefined;+ const trimmed = query.trim();+ if (!trimmed.toLowerCase().startsWith(SELECT_PREFIX)) return trimmed;+ const names = trimmed+ .slice(SELECT_PREFIX.length)+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ return names.length > 0 ? names.join(', ') : trimmed;+};++export const ToolSearchInspector = memo<BuiltinInspectorProps<ToolSearchArgs>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');+ const label = t(ClaudeCodeApiName.ToolSearch as any);+ const query = formatQuery(args?.query || partialArgs?.query);++ if (isArgumentsStreaming && !query) {+ return <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>{label}</div>;+ }++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>{label}</span>+ {query && (+ <>+ <span>: </span>+ <span className={highlightTextStyles.primary}>{query}</span>+ </>+ )}+ </div>+ );+ },+);++ToolSearchInspector.displayName = 'ClaudeCodeToolSearchInspector';diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.tsindex 189a50cca20..a84b6afddbc 100644--- a/packages/builtin-tool-claude-code/src/types.ts+++ b/packages/builtin-tool-claude-code/src/types.ts@@ -18,6 +18,7 @@ export enum ClaudeCodeApiName {Read = 'Read',Skill = 'Skill',TodoWrite = 'TodoWrite',+ ToolSearch = 'ToolSearch',Write = 'Write',}@@ -48,3 +49,14 @@ export interface TodoWriteArgs {export interface SkillArgs {skill?: string;}++/**+ * Arguments for CC's built-in `ToolSearch` tool. CC invokes this to load+ * schemas for deferred tools before calling them. `query` is either+ * `select:<name>[,<name>...]` for direct fetch, or keyword search with+ * optional `+term` to require a keyword.+ */+export interface ToolSearchArgs {+ max_results?: number;+ query?: string;+}diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.tsindex d29c07a1d90..cb8d2eae313 100644--- a/packages/electron-client-ipc/src/types/system.ts+++ b/packages/electron-client-ipc/src/types/system.ts@@ -27,3 +27,43 @@ export interface UserPathData {export type ThemeMode = 'system' | 'dark' | 'light';export type ThemeAppearance = 'dark' | 'light' | string;++export interface GitBranchInfo {+ /** Branch short name, or short SHA when in detached HEAD state */+ branch?: string;+ /** True when HEAD is detached (no branch ref) */+ detached?: boolean;+}++export interface GitLinkedPullRequest {+ number: number;+ state: string;+ title: string;+ url: string;+}++export interface GitLinkedPullRequestResult {+ /** Additional open PRs targeting the same head branch, beyond the primary one */+ extraCount?: number;+ /** Null when no open PR is linked to the branch */+ pullRequest: GitLinkedPullRequest | null;+ /** 'ok' — lookup succeeded; 'gh-missing' — gh CLI unavailable / not authed; 'error' — other failure */+ status: 'ok' | 'gh-missing' | 'error';+}++export interface GitBranchListItem {+ current: boolean;+ name: string;+ upstream?: string;+}++export interface GitWorkingTreeStatus {+ clean: boolean;+ /** Count of modified / staged / untracked files (each file counted once) */+ modified: number;+}++export interface GitCheckoutResult {+ error?: string;+ success: boolean;+}diff --git a/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx b/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsxindex da390500dad..d6341075514 100644--- a/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx+++ b/packages/shared-tool-ui/src/Inspector/GlobLocalFiles/index.tsx@@ -7,13 +7,28 @@ import { Check, X } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '../../styles';+import { inspectorTextStyles, shinyTextStyles } from '../../styles';-const styles = createStaticStyles(({ css }) => ({+const styles = createStaticStyles(({ css, cssVar }) => ({+ baseline: css`+ align-items: baseline;+ `,statusIcon: css`- margin-block-end: -2px;+ align-self: center;margin-inline-start: 4px;`,+ tag: css`+ margin-inline-start: 6px;+ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorText};++ background: ${cssVar.colorFillTertiary};+ `,}));interface GlobFilesArgs {@@ -37,9 +52,9 @@ export const createGlobLocalFilesInspector = (translationKey: string) => {);return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t(translationKey as any)}: </span>- <span className={highlightTextStyles.primary}>{pattern}</span>+ <div className={cx(inspectorTextStyles.root, styles.baseline, shinyTextStyles.shinyText)}>+ <span>{t(translationKey as any)}:</span>+ <span className={styles.tag}>{pattern}</span></div>);}@@ -47,18 +62,22 @@ export const createGlobLocalFilesInspector = (translationKey: string) => {const hasFiles = (pluginState?.totalCount ?? 0) > 0;return (- <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span style={{ marginInlineStart: 2 }}>- <span>{t(translationKey as any)}: </span>- {pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}- {isLoading ? null : pluginState ? (- hasFiles ? (- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />- ) : (- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />- )- ) : null}- </span>+ <div+ className={cx(+ inspectorTextStyles.root,+ styles.baseline,+ isLoading && shinyTextStyles.shinyText,+ )}+ >+ <span>{t(translationKey as any)}:</span>+ {pattern && <span className={styles.tag}>{pattern}</span>}+ {isLoading ? null : pluginState ? (+ hasFiles ? (+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />+ ) : (+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />+ )+ ) : null}</div>);},diff --git a/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx b/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsxindex b188e40bf19..fccc4fdbcc6 100644--- a/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx+++ b/packages/shared-tool-ui/src/Inspector/GrepContent/index.tsx@@ -3,11 +3,66 @@import type { GrepContentState } from '@lobechat/tool-runtime';import type { BuiltinInspectorProps } from '@lobechat/types';import { Text } from '@lobehub/ui';-import { cssVar, cx } from 'antd-style';-import { memo } from 'react';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Fragment, memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '../../styles';+import { inspectorTextStyles, shinyTextStyles } from '../../styles';++const styles = createStaticStyles(({ css, cssVar }) => ({+ baseline: css`+ align-items: baseline;+ `,+ separator: css`+ margin-inline: 2px;+ color: ${cssVar.colorTextQuaternary};+ `,+ tag: css`+ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorText};++ background: ${cssVar.colorFillTertiary};+ `,+ tagsList: css`+ display: inline-flex;+ flex-shrink: 1;+ gap: 4px;+ align-items: center;++ min-width: 0;+ margin-inline-start: 6px;++ white-space: nowrap;+ `,+}));++const splitPattern = (pattern: string): string[] =>+ pattern+ .split('|')+ .map((part) => part.trim())+ .filter(Boolean);++const PatternTags = memo<{ pattern: string }>(({ pattern }) => {+ const parts = splitPattern(pattern);+ if (parts.length === 0) return null;++ return (+ <span className={styles.tagsList}>+ {parts.map((part, index) => (+ <Fragment key={`${index}-${part}`}>+ {index > 0 && <span className={styles.separator}>|</span>}+ <span className={styles.tag}>{part}</span>+ </Fragment>+ ))}+ </span>+ );+});+PatternTags.displayName = 'GrepPatternTags';interface GrepContentArgs {directory?: string;@@ -39,9 +94,9 @@ export const createGrepContentInspector = ({);return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t(translationKey as any)}: </span>- <span className={highlightTextStyles.primary}>{pattern}</span>+ <div className={cx(inspectorTextStyles.root, styles.baseline, shinyTextStyles.shinyText)}>+ <span>{t(translationKey as any)}:</span>+ <PatternTags pattern={pattern} /></div>);}@@ -50,9 +105,15 @@ export const createGrepContentInspector = ({const hasResults = resultCount > 0;return (- <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span>{t(translationKey as any)}: </span>- {pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}+ <div+ className={cx(+ inspectorTextStyles.root,+ styles.baseline,+ isLoading && shinyTextStyles.shinyText,+ )}+ >+ <span>{t(translationKey as any)}:</span>+ {pattern && <PatternTags pattern={pattern} />}{!isLoading &&pluginState &&(hasResults ? (diff --git a/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx b/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsxindex cfc762cff16..969fe9f2dbf 100644--- a/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx+++ b/packages/shared-tool-ui/src/Inspector/RunCommand/index.tsx@@ -3,17 +3,36 @@import type { RunCommandState } from '@lobechat/tool-runtime';import type { BuiltinInspectorProps } from '@lobechat/types';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { Check, X } from 'lucide-react';+import { Check, SquareChevronRight, X } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '../../styles';+import { inspectorTextStyles, shinyTextStyles } from '../../styles';-const styles = createStaticStyles(({ css }) => ({+const styles = createStaticStyles(({ css, cssVar }) => ({+ baseline: css`+ align-items: baseline;+ `,+ command: css`+ overflow: hidden;++ min-width: 0;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ `,statusIcon: css`- margin-block-end: -2px;+ align-self: center;margin-inline-start: 4px;`,+ terminalIcon: css`+ flex-shrink: 0;+ align-self: center;+ margin-inline: 6px 4px;+ color: ${cssVar.colorTextDescription};+ `,}));interface RunCommandArgs {@@ -40,15 +59,16 @@ export const RunCommandInspector = memo<RunCommandInspectorProps>(if (isArgumentsStreaming) {if (!description)return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <div className={cx(inspectorTextStyles.root, styles.baseline, shinyTextStyles.shinyText)}><span>{t(translationKey as any)}</span></div>);return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t(translationKey as any)}: </span>- <span className={highlightTextStyles.primary}>{description}</span>+ <div className={cx(inspectorTextStyles.root, styles.baseline, shinyTextStyles.shinyText)}>+ <span>{t(translationKey as any)}:</span>+ <SquareChevronRight className={styles.terminalIcon} size={14} />+ <span className={styles.command}>{description}</span></div>);}@@ -56,18 +76,27 @@ export const RunCommandInspector = memo<RunCommandInspectorProps>(const isSuccess = pluginState?.success || pluginState?.exitCode === 0;return (- <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>- <span style={{ marginInlineStart: 2 }}>- <span>{t(translationKey as any)}: </span>- {description && <span className={highlightTextStyles.primary}>{description}</span>}- {isLoading ? null : pluginState?.success !== undefined ? (- isSuccess ? (- <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />- ) : (- <X className={styles.statusIcon} color={cssVar.colorError} size={14} />- )- ) : null}- </span>+ <div+ className={cx(+ inspectorTextStyles.root,+ styles.baseline,+ isLoading && shinyTextStyles.shinyText,+ )}+ >+ <span>{t(translationKey as any)}:</span>+ {description && (+ <>+ <SquareChevronRight className={styles.terminalIcon} size={14} />+ <span className={styles.command}>{description}</span>+ </>+ )}+ {isLoading ? null : pluginState?.success !== undefined ? (+ isSuccess ? (+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />+ ) : (+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />+ )+ ) : null}</div>);},diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex 916ca8ccd7b..6ff419ab0f4 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -11,7 +11,7 @@ export interface HeterogeneousProviderConfig {/** Custom environment variables */env?: Record<string, string>;/** Agent runtime type */- type: 'claudecode';+ type: 'claude-code';}/**diff --git a/packages/types/src/home.ts b/packages/types/src/home.tsindex 3cbcd8142a3..239ad3dc92a 100644--- a/packages/types/src/home.ts+++ b/packages/types/src/home.ts@@ -33,7 +33,7 @@ export interface SidebarAgentItem {*/groupAvatar?: string | null;/**- * Heterogeneous agent runtime type (e.g. `claudecode`) when the agent is+ * Heterogeneous agent runtime type (e.g. `claude-code`) when the agent is* driven by an external CLI. `null` / absent means it's a regular LobeHub* agent. Present so sidebar / list items can render an "External" tag* without per-item agent config lookups.diff --git a/src/components/DotsLoading/index.tsx b/src/components/DotsLoading/index.tsxnew file mode 100644index 00000000000..1c6b78cd1e4--- /dev/null+++ b/src/components/DotsLoading/index.tsx@@ -0,0 +1,59 @@+import { createStyles, keyframes } from 'antd-style';+import { type CSSProperties, memo } from 'react';++const fade = keyframes`+ 0%, 100% {+ opacity: 0.3;+ }+ 50% {+ opacity: 1;+ }+`;++interface StyleParams {+ color?: string;+ gap: number;+ size: number;+}++const useStyles = createStyles(({ css, token }, { size, gap, color }: StyleParams) => ({+ container: css`+ display: inline-flex;+ flex-direction: row;+ gap: ${gap}px;+ align-items: center;+ `,+ dot: css`+ width: ${size}px;+ height: ${size}px;+ border-radius: 50%;++ background-color: ${color || token.colorTextSecondary};++ animation: ${fade} 1.2s ease-in-out infinite;+ `,+}));++interface StyleArgs {+ color?: string;+ gap?: number;+ size?: number;+}++interface DotsLoadingProps extends StyleArgs {+ className?: string;+ style?: CSSProperties;+}++const DotsLoading = memo<DotsLoadingProps>(({ size = 4, gap = 3, color, className, style }) => {+ const { styles: s, cx } = useStyles({ color, gap, size });+ return (+ <div className={cx(s.container, className)} style={style}>+ <div className={s.dot} style={{ animationDelay: '0s' }} />+ <div className={s.dot} style={{ animationDelay: '0.15s' }} />+ <div className={s.dot} style={{ animationDelay: '0.3s' }} />+ </div>+ );+});++export default DotsLoading;diff --git a/src/components/RenameModal/index.tsx b/src/components/RenameModal/index.tsxnew file mode 100644index 00000000000..ea79ffa1dbd--- /dev/null+++ b/src/components/RenameModal/index.tsx@@ -0,0 +1,100 @@+'use client';++import { Button, Flexbox, Input, Text } from '@lobehub/ui';+import { createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { type InputRef } from 'antd';+import { t } from 'i18next';+import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface RenameModalContentProps {+ defaultValue: string;+ description?: string;+ onSave: (newTitle: string) => void | Promise<void>;+}++const RenameModalContent = memo<RenameModalContentProps>(+ ({ defaultValue, description, onSave }) => {+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ const [value, setValue] = useState(defaultValue);+ const [loading, setLoading] = useState(false);+ const inputRef = useRef<InputRef>(null);++ useEffect(() => {+ queueMicrotask(() => {+ inputRef.current?.focus({ cursor: 'all' });+ });+ }, []);++ const handleSave = useCallback(async () => {+ if (loading) return;+ const next = value.trim();+ if (!next || next === defaultValue) {+ close();+ return;+ }+ setLoading(true);+ try {+ await onSave(next);+ close();+ } finally {+ setLoading(false);+ }+ }, [close, defaultValue, loading, onSave, value]);++ return (+ <Flexbox gap={20}>+ {description ? (+ <Text style={{ marginTop: -8 }} type={'secondary'}>+ {description}+ </Text>+ ) : null}+ <Input+ ref={inputRef}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onPressEnter={handleSave}+ />+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={loading} onClick={close}>+ {tCommon('cancel')}+ </Button>+ <Button loading={loading} type={'primary'} onClick={handleSave}>+ {tCommon('save')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ },+);++RenameModalContent.displayName = 'RenameModalContent';++export interface OpenRenameModalProps {+ defaultValue: string;+ description?: string;+ onSave: (newTitle: string) => void | Promise<void>;+ title?: string;+}++export const openRenameModal = ({+ defaultValue,+ description,+ onSave,+ title,+}: OpenRenameModalProps): ModalInstance =>+ createModal({+ content: (+ <RenameModalContent defaultValue={defaultValue} description={description} onSave={onSave} />+ ),+ footer: null,+ maskClosable: true,+ styles: {+ header: { borderBottom: 'none' },+ },+ title: title ?? t('rename', { ns: 'common' }),+ width: 'min(90vw, 480px)',+ });++export default openRenameModal;diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 53caedc3406..a0426c5d4a4 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -167,6 +167,10 @@ const InputEditor = memo<{ defaultRows?: number; placeholder?: ReactNode }>(if (!input.trim()) return null;+ // Skip when cursor is not at end of paragraph — inserting a placeholder+ // mid-text causes nested editor updates that freeze the input+ if (afterText.trim()) return null;+const { enabled: _, ...config } = systemAgentSelectors.inputCompletion(useUserStore.getState(),);diff --git a/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsx b/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsxnew file mode 100644index 00000000000..2a4c54509b4--- /dev/null+++ b/src/features/ChatInput/RuntimeConfig/BranchSwitcher.tsx@@ -0,0 +1,397 @@+import type { GitBranchListItem } from '@lobechat/electron-client-ipc';+import { Button, Icon, Input } from '@lobehub/ui';+import {+ DropdownMenuItem,+ DropdownMenuPopup,+ DropdownMenuPortal,+ DropdownMenuPositioner,+ DropdownMenuRoot,+ DropdownMenuTrigger,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ CheckIcon,+ GitBranchIcon,+ GitBranchPlusIcon,+ LoaderIcon,+ RefreshCwIcon,+ SearchIcon,+} from 'lucide-react';+import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { message } from '@/components/AntdStaticMethods';+import { electronSystemService } from '@/services/electron/system';++const styles = createStaticStyles(({ css }) => ({+ branchLabel: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ container: css`+ display: flex;+ flex-direction: column;++ width: 320px;+ height: 380px;++ /* Cancel DropdownMenuPopup's default 4px padding so our sections align edge-to-edge */+ margin: -4px;+ `,+ createFooter: css`+ display: flex;+ gap: 8px;+ align-items: center;++ padding: 8px;+ border-block-start: 1px solid ${cssVar.colorSplit};+ `,+ createItemWrapper: css`+ padding: 4px;+ border-block-start: 1px solid ${cssVar.colorSplit};+ `,+ createInput: css`+ flex: 1;+ `,+ emptyState: css`+ padding-block: 16px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-align: center;+ `,+ item: css`+ display: flex;+ gap: 8px;+ align-items: flex-start;++ padding-block: 8px;+ padding-inline: 10px;+ border-radius: 6px;++ font-size: 13px;+ color: ${cssVar.colorText};+ `,+ itemCheck: css`+ flex: none;+ color: ${cssVar.colorPrimary};+ `,+ itemIcon: css`+ flex: none;+ margin-block-start: 2px;+ color: ${cssVar.colorTextSecondary};+ `,+ itemMain: css`+ overflow: hidden;+ flex: 1;+ min-width: 0;+ `,+ itemMeta: css`+ margin-block-start: 2px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ list: css`+ overflow-y: auto;+ flex: 1;+ padding: 4px;+ `,+ searchBar: css`+ padding: 8px;+ `,+ refreshButton: css`+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 20px;+ height: 20px;+ border-radius: 4px;++ color: ${cssVar.colorTextTertiary};++ transition: all 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ section: css`+ flex: 1;++ font-size: 11px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};+ text-transform: uppercase;+ `,+ sectionRow: css`+ display: flex;+ gap: 4px;+ align-items: center;++ padding-block: 6px 2px;+ padding-inline: 10px;+ `,+ spinning: css`+ animation: branch-switcher-spin 0.8s linear infinite;++ @keyframes branch-switcher-spin {+ to {+ transform: rotate(360deg);+ }+ }+ `,+}));++interface BranchSwitcherProps {+ children: ReactElement;+ currentBranch?: string;+ onAfterCheckout?: () => void;+ onExternalRefresh?: () => void | Promise<void>;+ onOpenChange: (open: boolean) => void;+ open: boolean;+ path: string;+}++const BranchSwitcher = memo<BranchSwitcherProps>(+ ({ path, currentBranch, open, onOpenChange, onAfterCheckout, onExternalRefresh, children }) => {+ const { t } = useTranslation('plugin');+ const [search, setSearch] = useState('');+ const [isCreating, setIsCreating] = useState(false);+ const [newBranch, setNewBranch] = useState('');+ const [busyBranch, setBusyBranch] = useState<string | null>(null);+ const createInputRef = useRef<HTMLInputElement>(null);++ const {+ data: branches = [],+ isLoading,+ error: branchesError,+ mutate: mutateBranches,+ } = useSWR(+ open ? ['git-branches', path] : null,+ () => electronSystemService.listGitBranches(path),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );+ const { data: workingStatus, mutate: mutateWorkingStatus } = useSWR(+ open ? ['git-status', path] : null,+ () => electronSystemService.getGitWorkingTreeStatus(path),+ { revalidateOnFocus: false },+ );+ const [isRefreshing, setIsRefreshing] = useState(false);++ const handleRefresh = useCallback(async () => {+ if (isRefreshing) return;+ setIsRefreshing(true);+ try {+ await Promise.all([+ mutateBranches(),+ mutateWorkingStatus(),+ Promise.resolve(onExternalRefresh?.()),+ ]);+ } finally {+ setIsRefreshing(false);+ }+ }, [isRefreshing, mutateBranches, mutateWorkingStatus, onExternalRefresh]);++ useEffect(() => {+ if (!open) {+ setSearch('');+ setIsCreating(false);+ setNewBranch('');+ }+ }, [open]);++ useEffect(() => {+ if (isCreating) {+ createInputRef.current?.focus();+ }+ }, [isCreating]);++ const filtered = useMemo(() => {+ const query = search.trim().toLowerCase();+ if (!query) return branches;+ return branches.filter((b) => b.name.toLowerCase().includes(query));+ }, [branches, search]);++ const handleCheckout = useCallback(+ async (branch: string, create = false) => {+ if (busyBranch) return;+ if (!create && branch === currentBranch) {+ onOpenChange(false);+ return;+ }+ setBusyBranch(branch);+ try {+ const result = await electronSystemService.checkoutGitBranch({+ branch,+ create,+ path,+ });+ if (result.success) {+ onAfterCheckout?.();+ onOpenChange(false);+ } else {+ message.error(result.error || t('localSystem.workingDirectory.checkoutFailed'));+ }+ } finally {+ setBusyBranch(null);+ }+ },+ [busyBranch, currentBranch, onAfterCheckout, onOpenChange, path, t],+ );++ const handleCreateSubmit = useCallback(() => {+ const name = newBranch.trim();+ if (!name) return;+ void handleCheckout(name, true);+ }, [handleCheckout, newBranch]);++ return (+ <DropdownMenuRoot open={open} onOpenChange={onOpenChange}>+ <DropdownMenuTrigger>{children}</DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuPositioner placement="topLeft" sideOffset={8}>+ <DropdownMenuPopup>+ <div className={styles.container}>+ <div className={styles.searchBar}>+ <Input+ autoFocus+ placeholder={t('localSystem.workingDirectory.branchSearchPlaceholder')}+ prefix={<Icon icon={SearchIcon} size={14} />}+ size="small"+ value={search}+ variant="filled"+ onChange={(e) => setSearch(e.target.value)}+ />+ </div>++ <div className={styles.list}>+ <div className={styles.sectionRow}>+ <div className={styles.section}>+ {t('localSystem.workingDirectory.branchesHeading')}+ </div>+ <div className={styles.refreshButton} role="button" onClick={handleRefresh}>+ <Icon+ className={cx(isRefreshing && styles.spinning)}+ icon={RefreshCwIcon}+ size={12}+ />+ </div>+ </div>++ {isLoading && branches.length === 0 && (+ <div className={styles.emptyState}>+ {t('localSystem.workingDirectory.branchesLoading')}+ </div>+ )}++ {!isLoading && branchesError && (+ <div className={styles.emptyState}>+ {(branchesError as Error)?.message ||+ t('localSystem.workingDirectory.branchesEmpty')}+ </div>+ )}++ {!isLoading && !branchesError && filtered.length === 0 && (+ <div className={styles.emptyState}>+ {search.trim()+ ? t('localSystem.workingDirectory.branchesNoMatch')+ : t('localSystem.workingDirectory.branchesEmpty')}+ </div>+ )}++ {filtered.map((branch: GitBranchListItem) => {+ const isCurrent = branch.name === currentBranch;+ const isBusy = busyBranch === branch.name;+ return (+ <DropdownMenuItem+ className={styles.item}+ closeOnClick={false}+ key={branch.name}+ onClick={() => handleCheckout(branch.name)}+ >+ <Icon+ className={cx(styles.itemIcon, isBusy && styles.spinning)}+ icon={isBusy ? LoaderIcon : GitBranchIcon}+ size={14}+ />+ <div className={styles.itemMain}>+ <div className={styles.branchLabel}>{branch.name}</div>+ {isCurrent && workingStatus && !workingStatus.clean && (+ <div className={styles.itemMeta}>+ {t('localSystem.workingDirectory.uncommittedChanges', {+ count: workingStatus.modified,+ })}+ </div>+ )}+ </div>+ {isCurrent && (+ <Icon className={styles.itemCheck} icon={CheckIcon} size={14} />+ )}+ </DropdownMenuItem>+ );+ })}+ </div>++ {isCreating ? (+ <div className={styles.createFooter}>+ <Input+ className={styles.createInput}+ placeholder={t('localSystem.workingDirectory.newBranchPlaceholder')}+ ref={createInputRef as any}+ size="small"+ value={newBranch}+ variant="filled"+ onChange={(e) => setNewBranch(e.target.value)}+ onPressEnter={handleCreateSubmit}+ />+ <Button+ disabled={!newBranch.trim() || !!busyBranch}+ loading={!!busyBranch}+ size="small"+ type="primary"+ onClick={handleCreateSubmit}+ >+ {t('localSystem.workingDirectory.checkoutAction')}+ </Button>+ <Button+ size="small"+ type="text"+ onClick={() => {+ setIsCreating(false);+ setNewBranch('');+ }}+ >+ {t('localSystem.workingDirectory.cancel')}+ </Button>+ </div>+ ) : (+ <div className={styles.createItemWrapper}>+ <DropdownMenuItem+ className={styles.item}+ closeOnClick={false}+ onClick={() => setIsCreating(true)}+ >+ <Icon className={styles.itemIcon} icon={GitBranchPlusIcon} size={14} />+ <div className={styles.itemMain}>+ {t('localSystem.workingDirectory.createBranchAction')}+ </div>+ </DropdownMenuItem>+ </div>+ )}+ </div>+ </DropdownMenuPopup>+ </DropdownMenuPositioner>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ );+ },+);++BranchSwitcher.displayName = 'BranchSwitcher';++export default BranchSwitcher;diff --git a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx b/src/features/ChatInput/RuntimeConfig/GitStatus.tsxnew file mode 100644index 00000000000..311d73d0749--- /dev/null+++ b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx@@ -0,0 +1,145 @@+import { Icon, Tooltip } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { GitBranchIcon, GitPullRequest } from 'lucide-react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { electronSystemService } from '@/services/electron/system';++import BranchSwitcher from './BranchSwitcher';+import { useGitInfo } from './useGitInfo';++const styles = createStaticStyles(({ css }) => ({+ branchLabel: css`+ overflow: hidden;+ max-width: 160px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ prTrigger: css`+ cursor: pointer;++ display: flex;+ gap: 4px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 4px;+ border-radius: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ transition: background 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ separator: css`+ width: 1px;+ height: 10px;+ background: ${cssVar.colorSplit};+ `,+ trigger: css`+ cursor: pointer;++ display: flex;+ gap: 4px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 4px;+ border-radius: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ transition: background 0.2s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+}));++interface GitStatusProps {+ isGithub: boolean;+ path: string;+}++const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {+ const { t } = useTranslation('plugin');+ const { data, mutate } = useGitInfo(path, isGithub);+ const [switcherOpen, setSwitcherOpen] = useState(false);++ const handleOpenPr = useCallback(() => {+ if (data?.pullRequest?.url) {+ void electronSystemService.openExternalLink(data.pullRequest.url);+ }+ }, [data?.pullRequest?.url]);++ if (!data?.branch) return null;++ const branchTooltip = data.detached+ ? t('localSystem.workingDirectory.detachedHead', { sha: data.branch })+ : data.branch;++ const prTooltip = data.pullRequest+ ? data.extraCount+ ? t('localSystem.workingDirectory.prTooltipWithExtra', {+ count: data.extraCount,+ title: data.pullRequest.title,+ })+ : data.pullRequest.title+ : data.ghMissing+ ? t('localSystem.workingDirectory.ghMissing')+ : undefined;++ const branchTrigger = (+ <div className={styles.trigger}>+ <Icon icon={GitBranchIcon} size={12} />+ <span className={styles.branchLabel}>{data.branch}</span>+ </div>+ );++ return (+ <>+ <div className={styles.separator} />+ {data.detached ? (+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>+ ) : (+ <BranchSwitcher+ currentBranch={data.branch}+ open={switcherOpen}+ path={path}+ onOpenChange={setSwitcherOpen}+ onAfterCheckout={() => {+ void mutate();+ }}+ onExternalRefresh={async () => {+ await mutate();+ }}+ >+ {branchTrigger}+ </BranchSwitcher>+ )}+ {data.pullRequest && (+ <>+ <div className={styles.separator} />+ <Tooltip title={prTooltip}>+ <div className={styles.prTrigger} role="button" onClick={handleOpenPr}>+ <Icon icon={GitPullRequest} size={12} />+ <span>#{data.pullRequest.number}</span>+ </div>+ </Tooltip>+ </>+ )}+ </>+ );+});++GitStatus.displayName = 'GitStatus';++export default GitStatus;diff --git a/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx b/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsxindex 9e46d80b9ee..709cab9cf5b 100644--- a/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx+++ b/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx@@ -83,6 +83,7 @@ const styles = createStaticStyles(({ css }) => ({}`,sectionTitle: css`+ padding-block: 6px 2px;padding-inline: 8px;font-size: 11px;diff --git a/src/features/ChatInput/RuntimeConfig/index.tsx b/src/features/ChatInput/RuntimeConfig/index.tsxindex 49266265cc2..a06ee1529f9 100644--- a/src/features/ChatInput/RuntimeConfig/index.tsx+++ b/src/features/ChatInput/RuntimeConfig/index.tsx@@ -23,7 +23,8 @@ import { topicSelectors } from '@/store/chat/selectors';import { useAgentId } from '../hooks/useAgentId';import { useUpdateAgentConfig } from '../hooks/useUpdateAgentConfig';import ApprovalMode from './ApprovalMode';-import { getRecentDirs } from './recentDirs';+import GitStatus from './GitStatus';+import { useRepoType } from './useRepoType';import WorkingDirectory from './WorkingDirectory';const MODE_ICONS: Record<RuntimeEnvMode, typeof LaptopIcon> = {@@ -114,14 +115,14 @@ const RuntimeConfig = memo(() => {);const effectiveWorkingDirectory = topicWorkingDirectory || agentWorkingDirectory;+ const repoType = useRepoType(effectiveWorkingDirectory);+const dirIconNode = useMemo((): ReactNode => {if (!effectiveWorkingDirectory) return <Icon icon={SquircleDashed} size={14} />;- const dirs = getRecentDirs();- const match = dirs.find((d) => d.path === effectiveWorkingDirectory);- if (match?.repoType === 'github') return <Github size={14} />;- if (match?.repoType === 'git') return <Icon icon={GitBranchIcon} size={14} />;+ if (repoType === 'github') return <Github size={14} />;+ if (repoType === 'git') return <Icon icon={GitBranchIcon} size={14} />;return <Icon icon={FolderIcon} size={14} />;- }, [effectiveWorkingDirectory]);+ }, [effectiveWorkingDirectory, repoType]);const switchMode = useCallback(async (mode: RuntimeEnvMode) => {@@ -228,26 +229,35 @@ const RuntimeConfig = memo(() => {const rightContent = () => {if (runtimeMode === 'local') {return (- <Popover- content={<WorkingDirectory agentId={agentId} onClose={() => setDirPopoverOpen(false)} />}- open={dirPopoverOpen}- placement="bottomLeft"- styles={{ content: { padding: 4 } }}- trigger="click"- onOpenChange={setDirPopoverOpen}- >- <div>- {dirPopoverOpen ? (- dirButton- ) : (- <Tooltip- title={effectiveWorkingDirectory || tPlugin('localSystem.workingDirectory.notSet')}- >- {dirButton}- </Tooltip>- )}- </div>- </Popover>+ <>+ <Popover+ open={dirPopoverOpen}+ placement="bottomLeft"+ styles={{ content: { padding: 4 } }}+ trigger="click"+ content={+ <WorkingDirectory agentId={agentId} onClose={() => setDirPopoverOpen(false)} />+ }+ onOpenChange={setDirPopoverOpen}+ >+ <div>+ {dirPopoverOpen ? (+ dirButton+ ) : (+ <Tooltip+ title={+ effectiveWorkingDirectory || tPlugin('localSystem.workingDirectory.notSet')+ }+ >+ {dirButton}+ </Tooltip>+ )}+ </div>+ </Popover>+ {effectiveWorkingDirectory && repoType && (+ <GitStatus isGithub={repoType === 'github'} path={effectiveWorkingDirectory} />+ )}+ </>);}diff --git a/src/features/ChatInput/RuntimeConfig/recentDirs.ts b/src/features/ChatInput/RuntimeConfig/recentDirs.tsindex 811a032b397..a843f3306dc 100644--- a/src/features/ChatInput/RuntimeConfig/recentDirs.ts+++ b/src/features/ChatInput/RuntimeConfig/recentDirs.ts@@ -34,3 +34,20 @@ export const removeRecentDir = (path: string): RecentDirEntry[] => {localStorage.setItem(RECENT_DIRS_KEY, JSON.stringify(updated));return updated;};++/**+ * Backfill `repoType` on an existing entry without reordering the list.+ * No-op when the path isn't in recents (avoids polluting recents with+ * implicitly-set working directories from agent config).+ */+export const setRecentDirRepoType = (+ path: string,+ repoType: 'git' | 'github' | undefined,+): void => {+ const dirs = getRecentDirs();+ const idx = dirs.findIndex((d) => d.path === path);+ if (idx === -1) return;+ if (dirs[idx].repoType === repoType) return;+ dirs[idx] = { ...dirs[idx], repoType };+ localStorage.setItem(RECENT_DIRS_KEY, JSON.stringify(dirs));+};diff --git a/src/features/ChatInput/RuntimeConfig/useGitInfo.ts b/src/features/ChatInput/RuntimeConfig/useGitInfo.tsnew file mode 100644index 00000000000..5eabb6303e4--- /dev/null+++ b/src/features/ChatInput/RuntimeConfig/useGitInfo.ts@@ -0,0 +1,42 @@+import { isDesktop } from '@lobechat/const';+import type { GitLinkedPullRequest } from '@lobechat/electron-client-ipc';++import { useClientDataSWR } from '@/libs/swr';+import { electronSystemService } from '@/services/electron/system';++export interface GitInfo {+ branch?: string;+ detached?: boolean;+ extraCount?: number;+ ghMissing?: boolean;+ pullRequest?: GitLinkedPullRequest | null;+}++const fetchGitInfo = async (dirPath: string, isGithub: boolean): Promise<GitInfo> => {+ const { branch, detached } = await electronSystemService.getGitBranch(dirPath);+ if (!branch) return {};++ // Skip PR lookup for detached HEAD or non-github repos+ if (detached || !isGithub) return { branch, detached };++ const prResult = await electronSystemService.getLinkedPullRequest({ branch, path: dirPath });+ return {+ branch,+ detached,+ extraCount: prResult.extraCount,+ ghMissing: prResult.status === 'gh-missing',+ pullRequest: prResult.pullRequest,+ };+};++export const useGitInfo = (dirPath?: string, isGithub: boolean = false) => {+ const key = isDesktop && dirPath ? ['git-info', dirPath, isGithub] : null;++ return useClientDataSWR<GitInfo>(key, () => fetchGitInfo(dirPath!, isGithub), {+ // Prevent gh spam: dedupe within 60s + throttle focus revalidation to 60s+ dedupingInterval: 60 * 1000,+ focusThrottleInterval: 60 * 1000,+ // gh may not be installed — don't retry aggressively+ shouldRetryOnError: false,+ });+};diff --git a/src/features/ChatInput/RuntimeConfig/useRepoType.ts b/src/features/ChatInput/RuntimeConfig/useRepoType.tsnew file mode 100644index 00000000000..96c1a628e00--- /dev/null+++ b/src/features/ChatInput/RuntimeConfig/useRepoType.ts@@ -0,0 +1,42 @@+import { isDesktop } from '@lobechat/const';+import { useEffect, useMemo } from 'react';+import useSWR from 'swr';++import { electronSystemService } from '@/services/electron/system';++import { getRecentDirs, setRecentDirRepoType } from './recentDirs';++export type RepoType = 'git' | 'github' | undefined;++/**+ * Resolve the repo type for a working directory.+ *+ * Cached entries from `recentDirs` (populated when the user picks a folder)+ * are used as a fast path. Legacy/string entries and agent-config-driven+ * paths that never went through the picker have no cached `repoType`, so+ * we probe the filesystem via IPC and backfill the cache.+ */+export const useRepoType = (path?: string): RepoType => {+ const cached = useMemo<RepoType>(() => {+ if (!path) return undefined;+ return getRecentDirs().find((d) => d.path === path)?.repoType;+ }, [path]);++ const shouldProbe = isDesktop && !!path && !cached;++ const { data: probed } = useSWR(+ shouldProbe ? ['detect-repo-type', path] : null,+ () => electronSystemService.detectRepoType(path!),+ {+ dedupingInterval: 60 * 1000,+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ },+ );++ useEffect(() => {+ if (path && probed !== undefined) setRecentDirRepoType(path, probed);+ }, [path, probed]);++ return cached ?? probed;+};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsxindex e13df2a315d..1f799e538ec 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx@@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { useAutoScroll } from '@/hooks/useAutoScroll';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { shinyTextStyles } from '@/styles';import { messageStateSelectors, useConversationStore } from '../../../store';@@ -125,6 +127,13 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(const isGenerating = useConversationStore(messageStateSelectors.isMessageGenerating(assistantMessageId),);+ /** Earliest op startTime for this message — anchors the working timer so+ * it reflects wall-clock since the op began, not since the component mounted. */+ const opStartTime = useChatStore((s) => {+ const ops = operationSelectors.getOperationsByMessage(assistantMessageId)(s);+ if (ops.length === 0) return undefined;+ return ops.reduce((min, op) => Math.min(min, op.metadata.startTime), Infinity);+ });const allComplete = toolsPhaseComplete && (workflowChromeComplete || !isGenerating);const summaryText = useMemo(() => getWorkflowSummaryText(blocks), [blocks]);@@ -235,7 +244,11 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(}if (activeWorkingStartedAtRef.current === null) {- activeWorkingStartedAtRef.current = Date.now();+ // Initial/remount seeds from op start so elapsed reflects wall-clock+ // since the op began. Intervention resume seeds from now so pause+ // time stays excluded from the accumulator.+ const isInitial = accumulatedWorkingMsRef.current === 0;+ activeWorkingStartedAtRef.current = isInitial && opStartTime ? opStartTime : Date.now();}const tick = () => {@@ -251,7 +264,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(const interval = setInterval(tick, 1000);return () => clearInterval(interval);- }, [pendingInterventionPresent, streaming]);+ }, [opStartTime, pendingInterventionPresent, streaming]);const showWorkingElapsed =!pendingInterventionPresent &&diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 20dc89f4daf..b84d2531f87 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -51,6 +51,9 @@ export default {'builtins.lobe-agent-management.render.installPlugin.plugin': 'Plugin','builtins.lobe-agent-management.render.installPlugin.success': 'Installed successfully','builtins.lobe-agent-management.title': 'Agent Manager',+ 'builtins.lobe-claude-code.todoWrite.allDone': 'All tasks completed',+ 'builtins.lobe-claude-code.todoWrite.currentStep': 'Current step',+ 'builtins.lobe-claude-code.todoWrite.todos': 'Todos','builtins.lobe-cloud-sandbox.apiName.editLocalFile': 'Edit file','builtins.lobe-cloud-sandbox.apiName.executeCode': 'Execute code','builtins.lobe-cloud-sandbox.apiName.exportFile': 'Export file',@@ -438,12 +441,28 @@ export default {'localSystem.workingDirectory.agentDescription':'Default working directory for all conversations with this Agent','localSystem.workingDirectory.agentLevel': 'Agent Working Directory',+ 'localSystem.workingDirectory.branchesEmpty': 'No local branches',+ 'localSystem.workingDirectory.branchesHeading': 'Branches',+ 'localSystem.workingDirectory.branchesLoading': 'Loading branches…',+ 'localSystem.workingDirectory.branchesNoMatch': 'No matching branches',+ 'localSystem.workingDirectory.branchSearchPlaceholder': 'Search branches',+ 'localSystem.workingDirectory.cancel': 'Cancel',+ 'localSystem.workingDirectory.checkoutAction': 'Checkout',+ 'localSystem.workingDirectory.checkoutFailed': 'Checkout failed',+ 'localSystem.workingDirectory.createBranchAction': 'Checkout new branch…','localSystem.workingDirectory.current': 'Current working directory','localSystem.workingDirectory.chooseDifferentFolder': 'Choose a different folder',+ 'localSystem.workingDirectory.detachedHead': 'Detached HEAD at {{sha}}',+ 'localSystem.workingDirectory.ghMissing':+ 'Install and log in to the GitHub CLI (`gh`) to see linked pull requests',+ 'localSystem.workingDirectory.newBranchPlaceholder': 'feature/new-branch-name','localSystem.workingDirectory.noRecent': 'No recent directories','localSystem.workingDirectory.notSet': 'Click to set working directory','localSystem.workingDirectory.placeholder': 'Enter directory path, e.g. /Users/name/projects',+ 'localSystem.workingDirectory.prTooltipWithExtra':+ '{{title}} (+{{count}} more open PR on this branch)','localSystem.workingDirectory.recent': 'Recent',+ 'localSystem.workingDirectory.refreshGitStatus': 'Refresh branch & PR status','localSystem.workingDirectory.removeRecent': 'Remove from recent','localSystem.workingDirectory.selectFolder': 'Select folder','localSystem.workingDirectory.title': 'Working Directory',@@ -451,6 +470,8 @@ export default {'Override Agent default for this conversation only','localSystem.workingDirectory.topicLevel': 'Conversation override','localSystem.workingDirectory.topicOverride': 'Override for this conversation',+ 'localSystem.workingDirectory.uncommittedChanges_one': 'Uncommitted changes: {{count}} file',+ 'localSystem.workingDirectory.uncommittedChanges_other': 'Uncommitted changes: {{count}} files','mcpEmpty.deployment': 'No deployment options','mcpEmpty.prompts': 'No prompts','mcpEmpty.resources': 'No resources',diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.tsindex cd0c40b8237..6fabd72dca1 100644--- a/src/locales/default/topic.ts+++ b/src/locales/default/topic.ts@@ -43,6 +43,8 @@ export default {'importSuccess': 'Successfully imported {{count}} messages','loadMore': 'Load More','newTopic': 'New Topic',+ 'renameModal.description': 'Keep it short and easy to recognize.',+ 'renameModal.title': 'Rename Topic','searchPlaceholder': 'Search Topics...','searchResultEmpty': 'No search results found.','temp': 'Temporary',diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsxindex a456db5c6b0..f61161403a4 100644--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx@@ -32,10 +32,8 @@ const AgentIdSync = () => {useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });}}- // Clear unread completion indicator for the agent being viewed- if (params.aid) {- useChatStore.getState().clearUnreadCompletedAgent(params.aid);- }+ // Note: we no longer clear all unread topics on agent visit — the badge counts+ // unread topics and is cleared per-topic when the user actually opens each one.}, [params.aid, prevAgentId]);useMount(() => {diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 6923a4068e4..110e4dde162 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -4,6 +4,7 @@ import { HashIcon, MessageSquareDashed } from 'lucide-react';import { memo, Suspense, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import DotsLoading from '@/components/DotsLoading';import RingLoadingIcon from '@/components/RingLoading';import { isDesktop } from '@/const/version';import { pluginRegistry } from '@/features/Electron/titlebar/RecentlyViewed/plugins';@@ -137,7 +138,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metaconst { dropdownMenu } = useTopicItemDropdownMenu({fav,id,- toggleEditing,+ title,});const hasUnread = id && isUnreadCompleted;@@ -191,7 +192,6 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metacontextMenuItems={dropdownMenu}disabled={editing}href={href}- title={title}icon={(() => {if (isLoading) {return (@@ -213,6 +213,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta<Icon icon={HashIcon} size={'small'} style={{ color: cssVar.colorTextDescription }} />);})()}+ title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}onClick={handleClick}onDoubleClick={handleDoubleClick}/>diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsxindex ec411b0c260..7d5bd70b1ae 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx@@ -16,6 +16,7 @@ import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';+import { openRenameModal } from '@/components/RenameModal';import { isDesktop } from '@/const/version';import { pluginRegistry } from '@/features/Electron/titlebar/RecentlyViewed/plugins';import { openShareModal } from '@/features/ShareModal';@@ -27,14 +28,10 @@ import { useGlobalStore } from '@/store/global';interface TopicItemDropdownMenuProps {fav?: boolean;id?: string;- toggleEditing: (visible?: boolean) => void;+ title: string;}-export const useTopicItemDropdownMenu = ({- fav,- id,- toggleEditing,-}: TopicItemDropdownMenuProps) => {+export const useTopicItemDropdownMenu = ({ fav, id, title }: TopicItemDropdownMenuProps) => {const { t } = useTranslation(['topic', 'common']);const { modal, message } = App.useApp();const navigate = useNavigate();@@ -43,12 +40,14 @@ export const useTopicItemDropdownMenu = ({const activeAgentId = useAgentStore((s) => s.activeAgentId);const addTab = useElectronStore((s) => s.addTab);- const [autoRenameTopicTitle, duplicateTopic, removeTopic, favoriteTopic] = useChatStore((s) => [- s.autoRenameTopicTitle,- s.duplicateTopic,- s.removeTopic,- s.favoriteTopic,- ]);+ const [autoRenameTopicTitle, duplicateTopic, removeTopic, favoriteTopic, updateTopicTitle] =+ useChatStore((s) => [+ s.autoRenameTopicTitle,+ s.duplicateTopic,+ s.removeTopic,+ s.favoriteTopic,+ s.updateTopicTitle,+ ]);const handleOpenShareModal = useCallback(() => {if (!id) return;@@ -83,7 +82,14 @@ export const useTopicItemDropdownMenu = ({key: 'rename',label: t('rename', { ns: 'common' }),onClick: () => {- toggleEditing(true);+ openRenameModal({+ defaultValue: title,+ description: t('renameModal.description', { ns: 'topic' }),+ onSave: async (newTitle) => {+ await updateTopicTitle(id, newTitle);+ },+ title: t('renameModal.title', { ns: 'topic' }),+ });},},{@@ -169,15 +175,16 @@ export const useTopicItemDropdownMenu = ({}, [id,fav,+ title,activeAgentId,autoRenameTopicTitle,duplicateTopic,favoriteTopic,removeTopic,+ updateTopicTitle,openTopicInNewWindow,addTab,navigate,- toggleEditing,t,modal,message,diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsxindex b375254a581..20e737cc33b 100644--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx@@ -4,8 +4,6 @@ import { ActionIcon, DropdownMenu } from '@lobehub/ui';import { MoreHorizontal } from 'lucide-react';import { memo } from 'react';-import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';-import { useMenu } from './useMenu';const HeaderActions = memo(() => {@@ -13,7 +11,7 @@ const HeaderActions = memo(() => {return (<DropdownMenu items={menuItems}>- <ActionIcon icon={MoreHorizontal} size={DESKTOP_HEADER_ICON_SMALL_SIZE} />+ <ActionIcon icon={MoreHorizontal} size={'small'} /></DropdownMenu>);});diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsxindex 624bb2f1971..42d3fd5ece2 100644--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx@@ -2,10 +2,11 @@import { type DropdownItem, Icon } from '@lobehub/ui';import { App } from 'antd';-import { Copy, Hash, Maximize2, PencilLine, Star, Trash } from 'lucide-react';+import { Copy, Hash, Maximize2, PencilLine, Star, Trash, Wand2 } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { openRenameModal } from '@/components/RenameModal';import { isDesktop } from '@/const/version';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -23,9 +24,15 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {const activeTopic = useChatStore(topicSelectors.currentActiveTopic);const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);- const [favoriteTopic, removeTopic] = useChatStore((s) => [s.favoriteTopic, s.removeTopic]);+ const [autoRenameTopicTitle, favoriteTopic, removeTopic, updateTopicTitle] = useChatStore((s) => [+ s.autoRenameTopicTitle,+ s.favoriteTopic,+ s.removeTopic,+ s.updateTopicTitle,+ ]);const topicId = activeTopic?.id;+ const topicTitle = activeTopic?.title ?? '';const isFavorite = !!activeTopic?.favorite;const menuItems = useMemo<DropdownItem[]>(() => {@@ -41,12 +48,28 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {favoriteTopic(topicId, !isFavorite);},},+ { type: 'divider' as const },+ {+ icon: <Icon icon={Wand2} />,+ key: 'autoRename',+ label: t('actions.autoRename', { ns: 'topic' }),+ onClick: () => {+ autoRenameTopicTitle(topicId);+ },+ },{icon: <Icon icon={PencilLine} />,key: 'rename',label: t('rename', { ns: 'common' }),onClick: () => {- useChatStore.setState({ topicRenamingId: topicId });+ openRenameModal({+ defaultValue: topicTitle,+ description: t('renameModal.description', { ns: 'topic' }),+ onSave: async (newTitle) => {+ await updateTopicTitle(topicId, newTitle);+ },+ title: t('renameModal.title', { ns: 'topic' }),+ });},},{ type: 'divider' as const },@@ -112,11 +135,14 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {return items;}, [topicId,+ topicTitle,isFavorite,workingDirectory,wideScreen,+ autoRenameTopicTitle,favoriteTopic,removeTopic,+ updateTopicTitle,toggleWideScreen,t,modal,diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsxindex 47da452e31f..afe2b67f158 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx@@ -8,7 +8,8 @@ import { memo, type ReactNode, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';-import { getRecentDirs } from '@/features/ChatInput/RuntimeConfig/recentDirs';+import GitStatus from '@/features/ChatInput/RuntimeConfig/GitStatus';+import { useRepoType } from '@/features/ChatInput/RuntimeConfig/useRepoType';import WorkingDirectoryContent from '@/features/ChatInput/RuntimeConfig/WorkingDirectory';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -17,6 +18,7 @@ import { topicSelectors } from '@/store/chat/selectors';const styles = createStaticStyles(({ css }) => ({bar: css`+ gap: 4px;padding-block: 0;padding-inline: 4px;`,@@ -27,18 +29,17 @@ const styles = createStaticStyles(({ css }) => ({gap: 6px;align-items: center;- height: 28px;- padding-inline: 8px;- border-radius: 6px;+ padding-block: 2px;+ padding-inline: 4px;+ border-radius: 4px;font-size: 12px;color: ${cssVar.colorTextSecondary};- transition: all 0.2s;+ transition: background 0.2s;&:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillSecondary};+ background: ${cssVar.colorFillTertiary};}`,}));@@ -55,14 +56,14 @@ const WorkingDirectoryBar = memo(() => {const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);const effectiveWorkingDirectory = topicWorkingDirectory || agentWorkingDirectory;+ const repoType = useRepoType(effectiveWorkingDirectory);+const dirIconNode = useMemo((): ReactNode => {if (!effectiveWorkingDirectory) return <Icon icon={SquircleDashed} size={14} />;- const dirs = getRecentDirs();- const match = dirs.find((d) => d.path === effectiveWorkingDirectory);- if (match?.repoType === 'github') return <Github size={14} />;- if (match?.repoType === 'git') return <Icon icon={GitBranchIcon} size={14} />;+ if (repoType === 'github') return <Github size={14} />;+ if (repoType === 'git') return <Icon icon={GitBranchIcon} size={14} />;return <Icon icon={FolderIcon} size={14} />;- }, [effectiveWorkingDirectory]);+ }, [effectiveWorkingDirectory, repoType]);if (!agentId || isLoading) {return (@@ -104,6 +105,9 @@ const WorkingDirectoryBar = memo(() => {)}</div></Popover>+ {effectiveWorkingDirectory && repoType && (+ <GitStatus isGithub={repoType === 'github'} path={effectiveWorkingDirectory} />+ )}</Flexbox>);});diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex 51375c4e851..ad3b9e87f68 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -5,6 +5,7 @@ import { AnimatePresence, m } from 'motion/react';import { memo, Suspense, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import DotsLoading from '@/components/DotsLoading';import { isDesktop } from '@/const/version';import { pluginRegistry } from '@/features/Electron/titlebar/RecentlyViewed/plugins';import NavItem from '@/features/NavPanel/components/NavItem';@@ -207,7 +208,6 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) =>contextMenuItems={dropdownMenu}disabled={editing}href={!editing ? href : undefined}- title={title}icon={isLoading ? (<Icon spin icon={Loader2Icon} size={'small'} style={{ color: cssVar.colorWarning }} />@@ -218,6 +218,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) =>slots={{iconPostfix: unreadNode,}}+ title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}onClick={handleClick}onDoubleClick={handleDoubleClick}/>diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsxindex 04157426da8..bdd45c1c1aa 100644--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx@@ -1,7 +1,7 @@import { SESSION_CHAT_URL } from '@lobechat/const';import { type SidebarAgentItem } from '@lobechat/types';import { ActionIcon, Flexbox, Icon, Tag } from '@lobehub/ui';-import { cssVar } from 'antd-style';+import { createStaticStyles, cssVar } from 'antd-style';import { Loader2, PinIcon } from 'lucide-react';import { type CSSProperties, type DragEvent } from 'react';import { memo, useCallback, useMemo, useState } from 'react';@@ -21,6 +21,37 @@ import Actions from '../Item/Actions';import Avatar from './Avatar';import { useAgentDropdownMenu } from './useDropdownMenu';+const styles = createStaticStyles(({ css, cssVar }) => ({+ badge: css`+ pointer-events: none;++ position: absolute;+ inset-block-end: -3px;+ inset-inline-end: -3px;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ min-width: 14px;+ height: 14px;+ padding-inline: 3px;+ border: 1.5px solid ${cssVar.colorBgContainer};+ border-radius: 999px;++ font-size: 9px;+ font-weight: 600;+ line-height: 1;+ color: #fff;++ background: ${cssVar.colorError};+ `,+ wrapper: css`+ position: relative;+ display: inline-flex;+ `,+}));+interface AgentItemProps {className?: string;item: SidebarAgentItem;@@ -39,6 +70,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {// Separate loading state from chat store - only show loading for this specific agentconst isLoading = useChatStore(operationSelectors.isAgentRunning(id));+ const unreadCount = useChatStore(operationSelectors.agentUnreadCount(id));// Get display title with fallbackconst displayTitle = title || t('untitledAgent');@@ -100,19 +132,30 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {[pinned],);- // Memoize avatar icon (show loader when updating)+ // Memoize avatar icon (show loader when updating, unread badge at bottom-right)const avatarIcon = useMemo(() => {if (isUpdating) {return <Icon spin color={cssVar.colorTextDescription} icon={Loader2} size={18} />;}- return (+ const avatarNode = (<Avataravatar={typeof avatar === 'string' ? avatar : undefined}avatarBackground={backgroundColor || undefined}/>);- }, [isUpdating, avatar, backgroundColor]);++ if (unreadCount > 0) {+ return (+ <span className={styles.wrapper}>+ {avatarNode}+ <span className={styles.badge}>{unreadCount > 99 ? '99+' : unreadCount}</span>+ </span>+ );+ }++ return avatarNode;+ }, [isUpdating, avatar, backgroundColor, unreadCount]);const dropdownMenu = useAgentDropdownMenu({anchor,diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsxindex bd30261d6bb..6ebfca35de8 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx@@ -210,7 +210,7 @@ export const useCreateMenuItems = () => {agencyConfig: {heterogeneousProvider: {command: 'claude',- type: 'claudecode' as const,+ type: 'claude-code' as const,},},avatar:diff --git a/src/services/electron/system.ts b/src/services/electron/system.tsindex d9de537e263..6c559709fb6 100644--- a/src/services/electron/system.ts+++ b/src/services/electron/system.ts@@ -1,5 +1,10 @@import {type ElectronAppState,+ type GitBranchInfo,+ type GitBranchListItem,+ type GitCheckoutResult,+ type GitLinkedPullRequestResult,+ type GitWorkingTreeStatus,type WindowMinimumSizeParams,type WindowSizeParams,} from '@lobechat/electron-client-ipc';@@ -73,6 +78,37 @@ class ElectronSystemService {}): Promise<{ path: string; repoType?: 'git' | 'github' } | undefined> {return this.ipc.system.selectFolder(params);}++ async getGitBranch(dirPath: string): Promise<GitBranchInfo> {+ return this.ipc.system.getGitBranch(dirPath);+ }++ async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {+ return this.ipc.system.detectRepoType(dirPath);+ }++ async getLinkedPullRequest(params: {+ branch: string;+ path: string;+ }): Promise<GitLinkedPullRequestResult> {+ return this.ipc.system.getLinkedPullRequest(params);+ }++ async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {+ return this.ipc.system.listGitBranches(dirPath);+ }++ async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {+ return this.ipc.system.getGitWorkingTreeStatus(dirPath);+ }++ async checkoutGitBranch(params: {+ branch: string;+ create?: boolean;+ path: string;+ }): Promise<GitCheckoutResult> {+ return this.ipc.system.checkoutGitBranch(params);+ }}// Export a singleton instance of the servicediff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 7918b064ff3..25ff34ac640 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -107,7 +107,7 @@ const defaultContext = {const defaultParams = {assistantMessageId: 'ast-initial',context: defaultContext,- heterogeneousProvider: { command: 'claude', type: 'claudecode' as const },+ heterogeneousProvider: { command: 'claude', type: 'claude-code' as const },message: 'test prompt',operationId: 'op-1',};diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex 62b748130f1..265252c7b3a 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -346,17 +346,16 @@ export class ConversationLifecycleActionImpl {// Per-agent heterogeneousProvider config takes priority over the global gateway mode.const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;- if (isDesktop && heterogeneousProvider?.type === 'claudecode') {+ if (isDesktop && heterogeneousProvider?.type === 'claude-code') {// Persist messages to DB first (same as client mode)let heteroData: SendMessageServerResponse | undefined;try {- const { model, provider } =- agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());+ const { model } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());heteroData = await aiChatService.sendMessageInServer({agentId: operationContext.agentId,groupId: operationContext.groupId ?? undefined,- newAssistantMessage: { model, provider: provider! },+ newAssistantMessage: { model, provider: 'claude-code' },newTopic: !operationContext.topicId? {title: message.slice(0, 20) || t('defaultTitle', { ns: 'topic' }),diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex e3a07e0ab2c..5a2749091fb 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -8,6 +8,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';+import { DEFAULT_TOPIC_UNREAD_KEY } from './initialState';import {type AfterCompletionCallback,AI_RUNTIME_OPERATION_TYPES,@@ -644,50 +645,78 @@ export class OperationActionsImpl {markUnreadCompleted = (agentId: string, topicId?: string | null): void => {const { activeAgentId, activeTopicId } = this.#get();- // Only mark when user is NOT currently viewing this agent/topic- const isViewingAgent = activeAgentId === agentId;- const isViewingTopic = isViewingAgent && (activeTopicId ?? null) === (topicId ?? null);-- if (!isViewingAgent) {- this.#set(- produce((state: ChatStore) => {- state.unreadCompletedAgentIds.add(agentId);- }),- false,- n(`markUnreadCompleted/agent/${agentId}`),- );- }+ // Only mark when user is NOT currently viewing this exact (agent, topic) pair.+ // The default (no-topic) conversation is represented by DEFAULT_TOPIC_UNREAD_KEY.+ const isViewingTopic =+ activeAgentId === agentId && (activeTopicId ?? null) === (topicId ?? null);+ if (isViewingTopic) return;- if (topicId && !isViewingTopic) {- this.#set(- produce((state: ChatStore) => {- state.unreadCompletedTopicIds.add(topicId);- }),- false,- n(`markUnreadCompleted/topic/${topicId}`),- );- }+ const key = topicId ?? DEFAULT_TOPIC_UNREAD_KEY;+ this.#set(+ produce((state: ChatStore) => {+ const existing = state.unreadCompletedTopicsByAgent[agentId];+ if (existing) {+ existing.add(key);+ } else {+ state.unreadCompletedTopicsByAgent[agentId] = new Set([key]);+ }+ }),+ false,+ n(`markUnreadCompleted/${agentId}/${key || 'default'}`),+ );};clearUnreadCompletedAgent = (agentId: string): void => {- if (!this.#get().unreadCompletedAgentIds.has(agentId)) return;+ if (!this.#get().unreadCompletedTopicsByAgent[agentId]) return;this.#set(produce((state: ChatStore) => {- state.unreadCompletedAgentIds.delete(agentId);+ delete state.unreadCompletedTopicsByAgent[agentId];}),false,n(`clearUnreadCompleted/agent/${agentId}`),);};- clearUnreadCompletedTopic = (topicId: string): void => {- if (!this.#get().unreadCompletedTopicIds.has(topicId)) return;+ /**+ * Remove the given topicIds from every agent's unread set.+ * Used when topics are deleted and we don't know which agents marked them unread+ * (e.g. group conversations where the bot's agentId — not activeAgentId — owns the entry).+ */+ purgeUnreadTopics = (topicIds: string[]): void => {+ if (topicIds.length === 0) return;+ const map = this.#get().unreadCompletedTopicsByAgent;+ const keys = new Set(topicIds);+ const affected = Object.entries(map).some(([, set]) => {+ for (const id of keys) if (set.has(id)) return true;+ return false;+ });+ if (!affected) return;++ this.#set(+ produce((state: ChatStore) => {+ for (const [agentId, set] of Object.entries(state.unreadCompletedTopicsByAgent)) {+ for (const id of keys) set.delete(id);+ if (set.size === 0) delete state.unreadCompletedTopicsByAgent[agentId];+ }+ }),+ false,+ n(`purgeUnreadTopics/count=${topicIds.length}`),+ );+ };++ clearUnreadCompletedTopic = (agentId: string, topicId?: string | null): void => {+ const key = topicId ?? DEFAULT_TOPIC_UNREAD_KEY;+ const set = this.#get().unreadCompletedTopicsByAgent[agentId];+ if (!set?.has(key)) return;this.#set(produce((state: ChatStore) => {- state.unreadCompletedTopicIds.delete(topicId);+ const target = state.unreadCompletedTopicsByAgent[agentId];+ if (!target) return;+ target.delete(key);+ if (target.size === 0) delete state.unreadCompletedTopicsByAgent[agentId];}),false,- n(`clearUnreadCompleted/topic/${topicId}`),+ n(`clearUnreadCompleted/${agentId}/${key || 'default'}`),);};// ━━━ Message Queue Actions ━━━diff --git a/src/store/chat/slices/operation/initialState.ts b/src/store/chat/slices/operation/initialState.tsindex c663f431766..66704102a1b 100644--- a/src/store/chat/slices/operation/initialState.ts+++ b/src/store/chat/slices/operation/initialState.ts@@ -43,16 +43,19 @@ export interface ChatOperationState {queuedMessages: Record<string, QueuedMessage[]>;/**- * Agent IDs with unread completed generation+ * Per-agent unread completed topics.+ * key: agentId, value: Set of topicId (use DEFAULT_TOPIC_UNREAD_KEY for the default/empty topic)+ * Agent-level unread count is derived from `set.size`.*/- unreadCompletedAgentIds: Set<string>;-- /**- * Topic IDs with unread completed generation- */- unreadCompletedTopicIds: Set<string>;+ unreadCompletedTopicsByAgent: Record<string, Set<string>>;}+/**+ * Sentinel topicId used inside `unreadCompletedTopicsByAgent` Sets to represent+ * the agent's default (no-topic) conversation, so agent-level counts include it.+ */+export const DEFAULT_TOPIC_UNREAD_KEY = '';+export const initialOperationState: ChatOperationState = {messageOperationMap: {},operations: {},@@ -60,6 +63,5 @@ export const initialOperationState: ChatOperationState = {operationsByMessage: {},operationsByType: {} as Record<OperationType, string[]>,queuedMessages: {},- unreadCompletedAgentIds: new Set(),- unreadCompletedTopicIds: new Set(),+ unreadCompletedTopicsByAgent: {},};diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex c2b7809f569..5911d2d0908 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -521,21 +521,35 @@ const isSendingMessage = (s: ChatStoreState): boolean => {// === Unread Completion ===/**- * Check if an agent has unread completed generation+ * Number of topics with unread completed generation for the given agent.+ * Drives the agent-level badge count.+ */+const agentUnreadCount =+ (agentId: string) =>+ (s: ChatStoreState): number => {+ return s.unreadCompletedTopicsByAgent[agentId]?.size ?? 0;+ };++/**+ * Whether the agent has any unread completed generation.*/const isAgentUnreadCompleted =(agentId: string) =>(s: ChatStoreState): boolean => {- return s.unreadCompletedAgentIds.has(agentId);+ return (s.unreadCompletedTopicsByAgent[agentId]?.size ?? 0) > 0;};/**- * Check if a topic has unread completed generation+ * Whether a specific topic has unread completed generation.+ * Scans across agents since topic items don't carry agentId in scope here.*/const isTopicUnreadCompleted =(topicId: string) =>(s: ChatStoreState): boolean => {- return s.unreadCompletedTopicIds.has(topicId);+ for (const set of Object.values(s.unreadCompletedTopicsByAgent)) {+ if (set.has(topicId)) return true;+ }+ return false;};// ━━━ Message Queue Selectors ━━━@@ -594,6 +608,8 @@ export const operationSelectors = {/** @deprecated Use isAgentRuntimeRunning instead */isAIGenerating: isAgentRuntimeRunning,+ agentUnreadCount,+isAborting,isAgentRunning,diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex d15cc3ead80..389ceb7d149 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -532,8 +532,8 @@ export class ChatTopicActionImpl {n('toggleTopic'),);- if (id) {- this.#get().clearUnreadCompletedTopic(id);+ if (activeAgentId) {+ this.#get().clearUnreadCompletedTopic(activeAgentId, id ?? null);}if (opts.skipRefreshMessage) return;@@ -541,10 +541,11 @@ export class ChatTopicActionImpl {};removeSessionTopics = async (): Promise<void> => {- const { switchTopic, activeAgentId, refreshTopic } = this.#get();+ const { switchTopic, activeAgentId, refreshTopic, clearUnreadCompletedAgent } = this.#get();if (!activeAgentId) return;await topicService.removeTopicsByAgentId(activeAgentId);+ clearUnreadCompletedAgent(activeAgentId);await refreshTopic();// switch to default topic@@ -552,7 +553,7 @@ export class ChatTopicActionImpl {};removeGroupTopics = async (groupId: string): Promise<void> => {- const { switchTopic, refreshTopic } = this.#get();+ const { switchTopic, refreshTopic, purgeUnreadTopics } = this.#get();// Get topics for this specific group from the topic map using topicMapKeyconst key = topicMapKey({ groupId });@@ -561,6 +562,7 @@ export class ChatTopicActionImpl {if (topicIds.length > 0) {await topicService.batchRemoveTopics(topicIds);+ purgeUnreadTopics(topicIds);}await refreshTopic();@@ -573,16 +575,25 @@ export class ChatTopicActionImpl {const { refreshTopic } = this.#get();await topicService.removeAllTopic();+ this.#set({ unreadCompletedTopicsByAgent: {} }, false, n('removeAllTopics/clearUnread'));await refreshTopic();};removeTopic = async (id: string): Promise<void> => {- const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = this.#get();+ const {+ activeAgentId,+ activeGroupId,+ activeTopicId,+ switchTopic,+ refreshTopic,+ purgeUnreadTopics,+ } = this.#get();// Allow deletion when either agentId or groupId is activeif (!activeAgentId && !activeGroupId) return;// remove topicawait topicService.removeTopic(id);+ purgeUnreadTopics([id]);await refreshTopic();// switch back to default topic@@ -590,10 +601,12 @@ export class ChatTopicActionImpl {};removeUnstarredTopic = async (): Promise<void> => {- const { refreshTopic, switchTopic } = this.#get();+ const { refreshTopic, switchTopic, purgeUnreadTopics } = this.#get();const topics = topicSelectors.currentUnFavTopics(this.#get());+ const topicIds = topics.map((t) => t.id);- await topicService.batchRemoveTopics(topics.map((t) => t.id));+ await topicService.batchRemoveTopics(topicIds);+ purgeUnreadTopics(topicIds);await refreshTopic();// Switch to default topic