Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 任务信息可选显示 worktree 徽标 (#3032)
Dash1ab1828ec0d0
diff --git a/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.tsindex 7f1a46cebe..1fecab2a2d 100644--- a/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts+++ b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts@@ -9,7 +9,7 @@ describe('git-context remote IPC security contract', () => {const guard = ipcSource.indexOf('assertTrustedAppRendererEvent(event);');const remoteLookup = ipcSource.indexOf('if (deviceLinkInvoke || requestedRemoteHostId)');- expect(ipcSource).toContain("if (requestedRemoteHostId !== null && !deviceLinkInvoke)");+ expect(ipcSource).toContain('if (requestedRemoteHostId !== null && !deviceLinkInvoke)');expect(guard).toBeGreaterThanOrEqual(0);expect(remoteLookup).toBeGreaterThan(guard);});@@ -19,6 +19,18 @@ describe('git-context remote IPC security contract', () => {expect(ipcSource).toContain('const deviceLinkInvoke = isDeviceLinkInvoke();');});+ it('keeps find-linked-worktree local-only, sender-guarded, and sessionId-validated', () => {+ const handler = ipcSource.indexOf('GIT_CONTEXT_INVOKE.FIND_LINKED_WORKTREE');+ const deviceNull = ipcSource.indexOf('if (isDeviceLinkInvoke()) return null;', handler);+ const guard = ipcSource.indexOf('assertTrustedAppRendererEvent(event);', handler);+ const requireId = ipcSource.indexOf("requireString(obj?.sessionId, 'sessionId')", handler);+ expect(ipcSource).toContain("FIND_LINKED_WORKTREE: 'git-context:find-linked-worktree'");+ expect(handler).toBeGreaterThanOrEqual(0);+ expect(deviceNull).toBeGreaterThan(handler);+ expect(guard).toBeGreaterThan(deviceNull);+ expect(requireId).toBeGreaterThan(guard);+ });+it('fails closed when device-link PR refs lookup is unavailable', () => {const lookup = ipcSource.indexOf('const refs = await listPrRefs(remoteSessionId);');const clear = ipcSource.indexOf('return [];', lookup);diff --git a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.tsindex da33dbd705..e5d5c73f38 100644--- a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts+++ b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts@@ -10,6 +10,7 @@ import { describe, it, expect } from 'vitest';import type { GitHeadInfo } from '../git-context/headReader';import {extractDirCandidate,+ findLiveLinkedWorktree,posixDriveToWin32,resolveSessionGitDir,type ResolveSessionGitDirDeps,@@ -188,3 +189,69 @@ describe('resolveSessionGitDir', () => {expect(res).toEqual({ workdir: null, head: null, source: null });});});++describe('findLiveLinkedWorktree', () => {+ it('skips the latest main checkout and keeps an older live linked worktree', async () => {+ const res = await findLiveLinkedWorktree('s', {+ recentToolUseContents: async () => [+ toolUse('exec', { command: 'git status', cwd: '/Users/x/main' }),+ toolUse('exec', { command: 'git status', cwd: '/Users/x/wt-a' }),+ ],+ resolveLinkedWorktreeRoot: async (dir) =>+ dir === path.resolve('/Users/x/wt-a') ? path.resolve('/Users/x/wt-a') : null,+ probeGitDir: async (dir) =>+ dir === path.resolve('/Users/x/wt-a') ? branchHead('feat/a') : branchHead('main'),+ });+ expect(res).toEqual({+ workdir: path.resolve('/Users/x/wt-a'),+ branch: 'feat/a',+ });+ });++ it('canonicalizes a nested telemetry cwd to the worktree root', async () => {+ const res = await findLiveLinkedWorktree('s', {+ recentToolUseContents: async () => [+ toolUse('exec', { command: 'git status', cwd: '/Users/x/wt-a/src' }),+ ],+ resolveLinkedWorktreeRoot: async (dir) =>+ dir === path.resolve('/Users/x/wt-a/src') ? path.resolve('/Users/x/wt-a') : null,+ probeGitDir: async (dir) =>+ dir === path.resolve('/Users/x/wt-a') ? branchHead('feat/a') : null,+ });+ expect(res).toEqual({+ workdir: path.resolve('/Users/x/wt-a'),+ branch: 'feat/a',+ });+ });++ it('looks past many recent checkout dirs to find an older live worktree', async () => {+ const recent = Array.from({ length: 21 }, (_, i) =>+ toolUse('exec', { command: 'git status', cwd: `/Users/x/main/pkg-${i}` }),+ );+ const res = await findLiveLinkedWorktree('s', {+ recentToolUseContents: async () => [+ ...recent,+ toolUse('exec', { command: 'git status', cwd: '/Users/x/wt-a' }),+ ],+ resolveLinkedWorktreeRoot: async (dir) =>+ dir === path.resolve('/Users/x/wt-a') ? path.resolve('/Users/x/wt-a') : null,+ probeGitDir: async (dir) =>+ dir === path.resolve('/Users/x/wt-a') ? branchHead('feat/a') : branchHead('main'),+ });+ expect(res).toEqual({+ workdir: path.resolve('/Users/x/wt-a'),+ branch: 'feat/a',+ });+ });++ it('clears the candidate when every telemetry worktree is gone', async () => {+ const res = await findLiveLinkedWorktree('s', {+ recentToolUseContents: async () => [+ toolUse('exec', { command: 'git status', cwd: '/Users/x/wt-gone' }),+ ],+ resolveLinkedWorktreeRoot: async () => null,+ probeGitDir: async () => null,+ });+ expect(res).toBeNull();+ });+});diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.tsindex 11e308b63c..56738f1e93 100644--- a/apps/desktop/src/main/git-context/ipc.ts+++ b/apps/desktop/src/main/git-context/ipc.ts@@ -30,6 +30,7 @@ import { optionalNullableString, requireString, throwIpcError } from '../utils/iimport { getSharedGhCliTokenSource } from './ghCliTokenSource.js';import { GitContextService } from './GitContextService.js';import {+ findLiveLinkedWorktreeLive,getSessionGitTelemetryCandidateLive,resolveSessionGitDirLive,} from './sessionDirResolver.js';@@ -60,6 +61,7 @@ const log = createLogger('git-context/ipc');export const GIT_CONTEXT_INVOKE = {GET: 'git-context:get',GET_FOR_SESSION: 'git-context:get-for-session',+ FIND_LINKED_WORKTREE: 'git-context:find-linked-worktree',WATCH: 'git-context:watch',UNWATCH: 'git-context:unwatch',PR_REFS_LIST: 'git-context:pr-refs:list',@@ -112,7 +114,12 @@ async function fetchUnresolvedCount(client: GithubClient, q: PrStatusQuery): Proasync function fetchPrRemote(token: string, q: PrStatusQuery): Promise<PrRemoteState> {// fetchImpl:api.github.com 是境外端点,走吃系统代理的通道(见 maker-host/outbound-fetch)。- const client = new GithubClient({ token, owner: q.owner, repo: q.repo, fetchImpl: outboundFetch });+ const client = new GithubClient({+ token,+ owner: q.owner,+ repo: q.repo,+ fetchImpl: outboundFetch,+ });// 核心状态走 REST(所有 token 类型通用);未解决数走 GraphQL 增强信号,// 失败(老 fine-grained PAT 不支持 GraphQL 等)降级 null,不拖垮整条状态。const [pr, unresolved] = await Promise.all([@@ -238,6 +245,16 @@ export function registerGitContextIpc(): void {return resolveSessionGitDirLive({ sessionId, fallbackWorktreePath, fallbackWorkingDir });});+ // 侧栏任务信息 worktree 徽标:本机 Desktop 专用。扫遥测里仍活着的 linked worktree,+ // 不跟 get-for-session 的「只看最近一次」语义。device-link / SSH 不走这条。+ ipcMain.handle(GIT_CONTEXT_INVOKE.FIND_LINKED_WORKTREE, async (event, payload: unknown) => {+ if (isDeviceLinkInvoke()) return null;+ assertTrustedAppRendererEvent(event);+ const obj = payload as { sessionId?: unknown };+ const sessionId = requireString(obj?.sessionId, 'sessionId');+ return findLiveLinkedWorktreeLive(sessionId);+ });+ipcMain.handle(GIT_CONTEXT_INVOKE.WATCH, async (_e, workdir: unknown) => {const dir = requireString(workdir, 'workdir');await gitContextService!.watch(dir);diff --git a/apps/desktop/src/main/git-context/sessionDirResolver.ts b/apps/desktop/src/main/git-context/sessionDirResolver.tsindex 6771d44fbf..de51f0f234 100644--- a/apps/desktop/src/main/git-context/sessionDirResolver.ts+++ b/apps/desktop/src/main/git-context/sessionDirResolver.ts@@ -24,11 +24,12 @@import path from 'node:path';-import { and, desc, eq, gt, isNull } from 'drizzle-orm';+import { and, desc, eq, gt, isNull, lt, or, sql } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current';import { messages, sessions } from '../localDb/schema';import { createLogger } from '../logger.js';+import { detectCwd } from '../worktree/WorktreeManager.js';import { readGitHead, type GitHeadInfo } from './headReader.js';const log = createLogger('git-context/session-dir');@@ -56,6 +57,9 @@ export function posixDriveToWin32(p: string, platform: NodeJS.Platform = process/** 倒序扫描的 tool-use 上限——只为找到最近一条带候选目录的;200 足够穿过连续的 Read。 */const SCAN_LIMIT = 200;+/** 侧栏/composer 回溯 linked worktree 时最多翻这么多条 tool-use,避免「用过但超出 200 条窗口」丢标。 */+const MAX_LINKED_WORKTREE_SCAN = 2000;+const messageRowid = sql<number>`"messages"."rowid"`;/** 解析结果:目录 + 其 HEAD + 来源(决定徽标对分支的信任度)。 */export interface SessionGitDirResult {@@ -117,6 +121,58 @@ export interface ResolveSessionGitDirDeps {probeGitDir: (dir: string) => Promise<GitHeadInfo | null>;}+export interface FindLiveLinkedWorktreeDeps {+ recentToolUseContents: (sessionId: string) => Promise<string[]>;+ /** 若 dir 在 linked worktree 内,返回该 worktree 的 repo root(`rev-parse --show-toplevel`)。 */+ resolveLinkedWorktreeRoot: (dir: string) => Promise<string | null>;+ probeGitDir: (dir: string) => Promise<GitHeadInfo | null>;+}++/** 按 recency 去重收集 tool-use 目录。纯函数,便于单测。 */+export function collectUniqueTelemetryDirs(+ contents: string[],+ pathPlatform: NodeJS.Platform = process.platform,+): string[] {+ const seen = new Set<string>();+ const dirs: string[] = [];+ for (const content of contents) {+ const candidate = extractDirCandidate(content, pathPlatform);+ if (!candidate) continue;+ let resolved: string;+ try {+ resolved = path.resolve(candidate);+ } catch {+ continue;+ }+ if (seen.has(resolved)) continue;+ seen.add(resolved);+ dirs.push(resolved);+ }+ return dirs;+}++/**+ * 侧栏 worktree 徽标专用:在遥测目录里找**仍然活着的 linked worktree**。+ * 与 resolveSessionGitDir 不同——后者只看最近一次 git 目录、删了不往回翻(防主仓冒充)。+ * 这里要的是「任务里用过、现在还在」:跳过主 checkout,继续看更早的候选,直到目录没了。+ */+export async function findLiveLinkedWorktree(+ sessionId: string,+ deps: FindLiveLinkedWorktreeDeps,+): Promise<{ workdir: string; branch: string | null } | null> {+ const contents = await deps.recentToolUseContents(sessionId);+ for (const dir of collectUniqueTelemetryDirs(contents)) {+ const root = await deps.resolveLinkedWorktreeRoot(dir);+ if (!root) continue;+ const head = await deps.probeGitDir(root);+ return {+ workdir: root,+ branch: head?.kind === 'branch' ? head.branch : null,+ };+ }+ return null;+}+/*** 编排解析逻辑(纯依赖注入,可单测)。优先级:遥测 → app worktree → working_dir。*/@@ -165,8 +221,11 @@ export async function resolveSessionGitDir(return { workdir: null, head: null, source: null };}-/** 查该 session 可见的 tool-use 消息 content,createdAt 降序、bounded(可见性同 prRefsStore)。 */-export async function queryRecentToolUseContents(sessionId: string): Promise<string[]> {+/** 查该 session 可见的 tool-use 消息 content,createdAt+rowid 降序、bounded(可见性同 prRefsStore)。 */+export async function queryRecentToolUseContentRows(+ sessionId: string,+ opts?: { limit?: number; before?: { createdAt: number; rowid: number } },+): Promise<Array<{ content: string; createdAt: number; rowid: number }>> {const db = getDbClient().drizzle;const [sessionRow] = await db.select({ clearedAt: sessions.clearedAt })@@ -174,6 +233,7 @@ export async function queryRecentToolUseContents(sessionId: string): Promise<str.where(eq(sessions.id, sessionId)).limit(1);const clearedAt = sessionRow?.clearedAt ?? null;+ const limit = opts?.limit ?? SCAN_LIMIT;const conds = [eq(messages.sessionId, sessionId),@@ -181,16 +241,50 @@ export async function queryRecentToolUseContents(sessionId: string): Promise<strisNull(messages.rewindAt),];if (clearedAt !== null) conds.push(gt(messages.createdAt, clearedAt));+ if (opts?.before) {+ const { createdAt, rowid } = opts.before;+ conds.push(+ or(+ lt(messages.createdAt, createdAt),+ and(eq(messages.createdAt, createdAt), lt(messageRowid, rowid)),+ )!,+ );+ }- const rows = await db- .select({ content: messages.content })+ return db+ .select({+ content: messages.content,+ createdAt: messages.createdAt,+ rowid: messageRowid,+ }).from(messages).where(and(...conds))- .orderBy(desc(messages.createdAt))- .limit(SCAN_LIMIT);+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(limit);+}++export async function queryRecentToolUseContents(sessionId: string): Promise<string[]> {+ const rows = await queryRecentToolUseContentRows(sessionId, { limit: SCAN_LIMIT });return rows.map((r) => r.content);}+async function queryLinkedWorktreeTelemetryContents(sessionId: string): Promise<string[]> {+ const contents: string[] = [];+ let before: { createdAt: number; rowid: number } | undefined;+ while (contents.length < MAX_LINKED_WORKTREE_SCAN) {+ const page = await queryRecentToolUseContentRows(sessionId, {+ limit: SCAN_LIMIT,+ before,+ });+ if (page.length === 0) break;+ for (const row of page) contents.push(row.content);+ const last = page[page.length - 1];+ before = { createdAt: last.createdAt, rowid: last.rowid };+ if (page.length < SCAN_LIMIT) break;+ }+ return contents;+}+/*** Live wrapper used by remote probes: return only the newest telemetry-derived* directory, without touching the local filesystem. The path is meaningful on@@ -239,3 +333,36 @@ export async function resolveSessionGitDirLive(input: {probeGitDir: (dir) => readGitHead(dir),});}++/** 本机 Desktop 侧栏 worktree 徽标:遥测里仍活着的 linked worktree。永不抛错。 */+export async function findLiveLinkedWorktreeLive(+ sessionId: string,+): Promise<{ workdir: string; branch: string | null } | null> {+ try {+ return await findLiveLinkedWorktree(sessionId, {+ recentToolUseContents: async (sid) => {+ try {+ return await queryLinkedWorktreeTelemetryContents(sid);+ } catch {+ return [];+ }+ },+ resolveLinkedWorktreeRoot: async (dir) => {+ try {+ const detected = await detectCwd(dir);+ if (!detected.isInsideWorktree) return null;+ return detected.repoRoot ?? path.resolve(dir);+ } catch {+ return null;+ }+ },+ probeGitDir: (dir) => readGitHead(dir),+ });+ } catch (err) {+ log.warn('find live linked worktree failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 00a892148a..b9142dca37 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -64,9 +64,7 @@ import {type TerminateAgentProcessRequest,type TerminateAgentProcessResult,} from '../shared/processMonitor';-import {- RESOURCE_USAGE_WINDOW_OPEN_CHANNEL,-} from '../shared/resourceUsageWindow';+import { RESOURCE_USAGE_WINDOW_OPEN_CHANNEL } from '../shared/resourceUsageWindow';import { SESSION_ATTENTION_CLEARED_CHANNEL } from '../shared/sessionAttention';import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../shared/voiceInputPowerIpc';import {@@ -1081,8 +1079,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedPackageSha256: string;expectedInstalledApproval: string;},- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:update', lizFilePath, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),cindyPrefsSync: (id: string,): {@@ -1148,7 +1145,9 @@ contextBridge.exposeInMainWorld('electronAPI', {iconDataUrl?: string;}> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),/** 本地包第三条恢复路径:从已装目录读确认卡事实(零副作用)。 */- reapproveInspect: (id: string): Promise<{+ reapproveInspect: (+ id: string,+ ): Promise<{manifest: unknown;trust: unknown;manifestSha256: string;@@ -1166,8 +1165,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedInstalledApproval: string;inspectTicket: string;},- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:reapprove-installed', id, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:reapprove-installed', id, opts),uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),/** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */export: (@@ -2325,8 +2323,7 @@ contextBridge.exposeInMainWorld('electronAPI', {enableBeta: boolean;isCustomized?: boolean;}> => ipcRenderer.invoke('update-channel-settings-reset'),- relaunchForChannelChange: (): Promise<void> =>- ipcRenderer.invoke('update-channel-relaunch'),+ relaunchForChannelChange: (): Promise<void> => ipcRenderer.invoke('update-channel-relaunch'),probeBetaChannel: (): Promise<{ available: boolean }> =>ipcRenderer.invoke('update-channel-probe-beta'),setUpdateRelaunchTheme: (theme: 'light' | 'dark'): void => {@@ -4193,9 +4190,17 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ ok: true; daemonReady: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:cc-mgr-force-upgrade', { hostId, sessionId, agent }),ccMgrListPendingUpgrades: (): Promise<{- pending: Array<{ hostId: string; currentVersion: string; availableVersion: string; agent: 'cc' | 'pi' }>;+ pending: Array<{+ hostId: string;+ currentVersion: string;+ availableVersion: string;+ agent: 'cc' | 'pi';+ }>;}> => ipcRenderer.invoke('maker:remote-ssh:cc-mgr-list-pending-upgrades'),- ccMgrDismissPendingUpgrade: (hostId: string, agent: 'cc' | 'pi' = 'cc'): Promise<{ ok: true }> =>+ ccMgrDismissPendingUpgrade: (+ hostId: string,+ agent: 'cc' | 'pi' = 'cc',+ ): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:remote-ssh:cc-mgr-dismiss-pending-upgrade', { hostId, agent }),// ── Codex auth sync (Phase B+) ────────────────────────────────────────@@ -4435,6 +4440,9 @@ contextBridge.exposeInMainWorld('electronAPI', {worktreePath: string | null;remoteHostId?: string | null;}): Promise<unknown> => ipcRenderer.invoke('git-context:get-for-session', input),+ /** 本机:任务遥测里仍活着的 linked worktree。远程/未找到返回 null。 */+ findLinkedWorktree: (input: { sessionId: string }): Promise<unknown> =>+ ipcRenderer.invoke('git-context:find-linked-worktree', input),/** 开始监听该 workdir 的 HEAD 变化(refcount;变化经 onChanged 推送)。 */watch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:watch', workdir),unwatch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:unwatch', workdir),@@ -5206,9 +5214,7 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<void> =>ipcRenderer.invoke('maker:model-visibility:sync', dataOwnerId, ownerGeneration, map),claimLegacyModelVisibilityOwner: (): ModelVisibilityLegacyOwnerClaim => {- const value: unknown = ipcRenderer.sendSync(- 'maker:model-visibility:legacy-owner-claim-sync',- );+ const value: unknown = ipcRenderer.sendSync('maker:model-visibility:legacy-owner-claim-sync');return isModelVisibilityLegacyOwnerClaim(value)? value: {@@ -6268,8 +6274,7 @@ contextBridge.exposeInMainWorld('electronAPI', {messages: Array<{ role: string; content: string }>;workingDir?: string;turnGen: number;- }): Promise<{ prompt: string | null }> =>- ipcRenderer.invoke('maker:predict-prompt', request),+ }): Promise<{ prompt: string | null }> => ipcRenderer.invoke('maker:predict-prompt', request),helpAsk: (request: import('../shared/helpTypes').HelpAskRequest,): Promise<import('../shared/helpTypes').HelpAnswerResult> =>diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.tsindex e271726131..706b12113d 100644--- a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts+++ b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts@@ -174,9 +174,10 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不"labelKey: 'ccAgent.sidebar.viewStyleListWide', Icon: LayoutList",);- // 任务信息四项各配数据类型图标;时间用 Clock 而非 Timer(后者是自动任务专用字形)。+ // 任务信息各项各配数据类型图标;时间用 Clock 而非 Timer(后者是自动任务专用字形)。expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.time', Icon: Clock");expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.pr', Icon: GitPullRequest");+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.worktree', Icon: Folders");expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.tokens', Icon: Coins");expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.cost', Icon: Wallet");expect(filterSource).not.toMatch(/taskInfo\.time', Icon: Timer/);@@ -350,6 +351,8 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不expect(infoMetaSource).toContain("if (field === 'pr' && hasPrRef)");expect(infoMetaSource).toContain("pieces.push({ key: 'pr', text: '' })");expect(infoMetaSource).toContain("piece.key === 'pr' ?");+ expect(infoMetaSource).toContain("if (field === 'worktree' && hasWorktree)");+ expect(infoMetaSource).toContain("piece.key === 'worktree' ?");// 菜单摘要的图标串同样按勾选顺序(遍历 taskInfoFields,不是遍历选项表)。const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');expect(filterSource).toContain('{taskInfoFields.map((field) => {');diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.tsindex 7d4cc0f88f..c27d6a5512 100644--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts@@ -54,13 +54,17 @@ describe('sidebar remote project icon', () => {expect(sessionHeaderSource).toContain('connectionStatus={remoteIconConnectionStatus}');});+ it('does not let nested card controls keyboard-activate the session row', () => {+ expect(sessionCardSource).toContain('if (e.target !== e.currentTarget) return');+ });+it('keeps remote session icons next to titles instead of in the right-side time slots', () => {expect(sessionItemSource).toMatch(/<span[\s\S]*?className="min-w-0 flex flex-1 items-center gap-1\.5"[\s\S]*?<SidebarTitleMarquee[\s\S]*?\{remoteIconKind && \([\s\S]*?<RemoteProjectIcon/,);// C 期起右侧时间槽由 SessionInfoMeta 承担(任务信息复选),仍在同一让位容器内。expect(sessionItemSource).toMatch(- /<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end">[\s\S]*?<WorktreeBadge[\s\S]*?<SessionInfoMeta/,+ /<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end">[\s\S]*?<SessionInfoMeta[\s\S]*?worktree=\{infoWorktree \?\? undefined\}/,);expect(sessionCardSource).toContain('function TimeActionsSlot');expect(sessionCardSource).not.toMatch(/function TimeActionsSlot[\s\S]*?remoteIconKind/);diff --git a/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts b/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.tsindex 784be790de..7f94ea894c 100644--- a/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts@@ -97,7 +97,8 @@ describe('SessionItem activity time', () => {expect(sessionItemSource).toMatch(/buildSessionInfoPieces\(\s*session,\s*taskInfoFields,\s*activityIso,\s*t,/,);- expect(sessionItemSource).toContain('<SessionInfoMeta pieces={infoPieces}');+ expect(sessionItemSource).toContain('<SessionInfoMeta');+ expect(sessionItemSource).toContain('pieces={infoPieces}');expect(sessionInfoMetaSource).toContain('formatSidebarTime(activityIso, t)');expect(sessionInfoMetaSource).toContain('text-sidebar-action-icon');expect(sessionItemSource).toContain('transition-opacity');@@ -111,7 +112,7 @@ describe('SessionItem activity time', () => {expect(sessionItemSource).not.toMatch(/group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14/,);- expect(sessionItemSource).toContain('<WorktreeBadge sessionId={session.id}');+ expect(sessionItemSource).toContain('worktree={infoWorktree ?? undefined}');expect(sessionItemSource).toContain('canQuickArchive && archivePending &&');expect(sessionItemSource).toContain("!archivePending && 'group-hover:opacity-0 group-focus-within/slot:opacity-0'",diff --git a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.tsindex fab3ce4420..9f1c4381cd 100644--- a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts@@ -299,8 +299,8 @@ describe('taskInfoFields(任务行右侧信息复选)', () => {});it('persist → load round-trips and drops illegal / duplicate entries', () => {- persistTaskInfoFields(['pr', 'tokens', 'cost', 'time']);- expect(loadTaskInfoFields()).toEqual(['pr', 'tokens', 'cost', 'time']);+ persistTaskInfoFields(['pr', 'worktree', 'tokens', 'cost', 'time']);+ expect(loadTaskInfoFields()).toEqual(['pr', 'worktree', 'tokens', 'cost', 'time']);localStorage.setItem(TASK_INFO_KEY, JSON.stringify(['time', 'bogus', 'time', 42, 'cost']));expect(loadTaskInfoFields()).toEqual(['time', 'cost']);});diff --git a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsxindex f94bc875a5..fdfa588d65 100644--- a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx+++ b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx@@ -20,6 +20,7 @@ vi.mock('@/lib/logger', () => ({const mocks = {worktreeListAll: vi.fn(),+ worktreeDetectCwd: vi.fn(),listeners: new Set<(payload: { sessionId: string }) => void>(),};@@ -34,11 +35,18 @@ function Probe() {beforeEach(() => {mocks.worktreeListAll.mockReset();+ mocks.worktreeDetectCwd.mockReset();+ mocks.worktreeDetectCwd.mockResolvedValue({+ isInsideWorktree: true,+ isGitRepo: true,+ gitInstalled: true,+ });mocks.listeners.clear();Object.defineProperty(window, 'electronAPI', {configurable: true,value: {worktreeListAll: mocks.worktreeListAll,+ worktreeDetectCwd: mocks.worktreeDetectCwd,onWorktreeChanged: (cb: (payload: { sessionId: string }) => void) => {mocks.listeners.add(cb);return () => mocks.listeners.delete(cb);@@ -68,9 +76,7 @@ describe('WorktreeContext recycle refresh', () => {});// 回收链跑完,store 里已经没有那条了。- mocks.worktreeListAll.mockResolvedValueOnce([- { sessionId: 'other', path: '/tmp/wt/other' },- ]);+ mocks.worktreeListAll.mockResolvedValueOnce([{ sessionId: 'other', path: '/tmp/wt/other' }]);await act(async () => {emitWorktreeChanged('archived-one');});@@ -103,9 +109,29 @@ describe('WorktreeContext recycle refresh', () => {configurable: true,value: { worktreeListAll: mocks.worktreeListAll },});+ mocks.worktreeListAll.mockResolvedValue([{ sessionId: 'only', path: '/tmp/wt/only' }]);++ const view = render(+ <WorktreeProvider>+ <Probe />+ </WorktreeProvider>,+ );++ await waitFor(() => {+ expect(view.getByTestId('ids').textContent).toBe('only');+ });+ });++ it('drops store entries whose directories are no longer linked worktrees', async () => {mocks.worktreeListAll.mockResolvedValue([- { sessionId: 'only', path: '/tmp/wt/only' },+ { sessionId: 'gone', path: '/tmp/wt/gone' },+ { sessionId: 'live', path: '/tmp/wt/live' },]);+ mocks.worktreeDetectCwd.mockImplementation(async ({ cwd }: { cwd: string }) => ({+ isInsideWorktree: cwd === '/tmp/wt/live',+ isGitRepo: true,+ gitInstalled: true,+ }));const view = render(<WorktreeProvider>@@ -114,7 +140,7 @@ describe('WorktreeContext recycle refresh', () => {);await waitFor(() => {- expect(view.getByTestId('ids').textContent).toBe('only');+ expect(view.getByTestId('ids').textContent).toBe('live');});});});diff --git a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx b/apps/desktop/src/renderer/contexts/WorktreeContext.tsxindex 7dc4d664d4..a25d7ea53b 100644--- a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx+++ b/apps/desktop/src/renderer/contexts/WorktreeContext.tsx@@ -29,6 +29,18 @@ import { createLogger } from '@/lib/logger';const log = createLogger('WorktreeContext');+/** store 仍可能留着已被 `git worktree remove` 的路径;探测失败不摘标,避免 IPC 抖动清空侧栏。 */+async function isLiveOfficialPath(cwd: string): Promise<boolean> {+ const detect = window.electronAPI?.worktreeDetectCwd;+ if (!detect) return true;+ try {+ const result = await detect({ cwd });+ return Boolean(result?.isInsideWorktree);+ } catch {+ return true;+ }+}+interface WorktreeContextValue {/** sessionId → meta;非 null 即代表此 session 正绑定一个 worktree。 */metas: Record<string, WorktreeMeta>;@@ -50,9 +62,15 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {// 中间发生了更新的 refresh,丢弃本次结果if (myTurn !== inflightRef.current) return;const next: Record<string, WorktreeMeta> = {};- for (const m of list ?? []) {- if (m && m.sessionId) next[m.sessionId] = m;- }+ await Promise.all(+ (list ?? []).map(async (meta) => {+ if (!meta?.sessionId || !meta.path) return;+ if (!(await isLiveOfficialPath(meta.path))) return;+ if (myTurn !== inflightRef.current) return;+ next[meta.sessionId] = meta;+ }),+ );+ if (myTurn !== inflightRef.current) return;setMetas(next);} catch (err) {log.warn('refresh failed:', err);@@ -61,6 +79,11 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {useEffect(() => {void refresh();+ const onFocus = () => {+ void refresh();+ };+ window.addEventListener('focus', onFocus);+ return () => window.removeEventListener('focus', onFocus);}, [refresh]);// 复用 sessionsBus 的 refresh 事件 —— delete / archive 完成后会触发一次,@@ -84,24 +107,15 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {});}, [refresh]);- const value = useMemo<WorktreeContextValue>(- () => ({ metas, refresh }),- [metas, refresh],- );+ const value = useMemo<WorktreeContextValue>(() => ({ metas, refresh }), [metas, refresh]);- return (- <WorktreeContext.Provider value={value}>- {children}- </WorktreeContext.Provider>- );+ return <WorktreeContext.Provider value={value}>{children}</WorktreeContext.Provider>;}function useCtx(): WorktreeContextValue {const ctx = useContext(WorktreeContext);if (!ctx) {- throw new Error(- '[WorktreeContext] missing provider — wrap your tree in <WorktreeProvider>',- );+ throw new Error('[WorktreeContext] missing provider — wrap your tree in <WorktreeProvider>');}return ctx;}@@ -112,9 +126,7 @@ export function useWorktrees(): Record<string, WorktreeMeta> {}/** 单条快捷查询;徽标 (M4) / 各 session 视图都用它。 */-export function useWorktreeForSession(- sessionId: string | null | undefined,-): WorktreeMeta | null {+export function useWorktreeForSession(sessionId: string | null | undefined): WorktreeMeta | null {const { metas } = useCtx();if (!sessionId) return null;return metas[sessionId] ?? null;diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 83ea9e4304..143f35535a 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -170,7 +170,11 @@ import { subscribeChatTaskFocus } from '@/features/right-sidebar/plugins/backgroimport { canFocusWithoutJumpLoad } from '@/lib/searchJumpTargeting';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';import { useWorktreeCreation, worktreeCreationStore } from '@/lib/worktreeCreationStore';-import { useWorktreeForSession } from '@/contexts/WorktreeContext';+import {+ composerWorkingDirPath,+ formatWorktreeChipText,+ useTaskInfoWorktree,+} from '@/features/cc-agent/sidebar/sessionWorktreeInfo';import {getSessionRouteOwnerId,isOrcaLeadSession,@@ -787,7 +791,18 @@ export function CCAgentSessionView({// worktree meta:当前 session 跑在某个 worktree 里时返回 { baseRepo, name, branch, path };// 否则 null。workingDir chip 用这个把显示从单一 "feat-button-ui" 升级成// "xdt-maker (feat-button-ui)",一眼看出这是 baseRepo xdt-maker 上的 worktree。- const worktreeMeta = useWorktreeForSession(sessionId);+ const liveWorktree = useTaskInfoWorktree(+ session ?? {+ id: sessionId ?? '',+ workingDir: null,+ worktreePath: null,+ deviceLinkDeviceId: undefined,+ remoteHostId: undefined,+ },+ Boolean(session),+ { observeTelemetry: true },+ );+ const isRemoteWorktreeSession = Boolean(session?.deviceLinkDeviceId || session?.remoteHostId);// Fetch fresh session data from server whenever sessionId changes.useEffect(() => {@@ -1213,12 +1228,15 @@ export function CCAgentSessionView({// local only:remote session 的 chip 仅作展示,不响应点击(见下方 remoteHostId 早返 +// 渲染处的条件 onClick)。const handleOpenWorkingDir = useCallback(async () => {- const wd = session?.workingDir;+ const wd = composerWorkingDirPath({+ workingDir: session?.workingDir,+ liveWorktree,+ isRemote: isRemoteWorktreeSession,+ });if (!wd) return;- // remote session 的 workingDir 是远端主机上的路径,本机 openPath 只会打开错误的- // 本地同名目录或直接报错。远端文件能力接入前,remote chip 不响应点击(仅作信息- // 展示,完整路径 + Host 仍在 hover Tip 里)。- if (session?.remoteHostId) return;+ // SSH / device-link 的 workingDir 是远端路径,本机 openPath 会打开错误目录。+ // 远端文件能力接入前,remote chip 不响应点击(仅作信息展示)。+ if (isRemoteWorktreeSession) return;try {const result = await window.electronAPI.openPath(wd);if (!result.success) toast.error(result.error || t('ccAgent.common.openFolderFailed'));@@ -1226,7 +1244,7 @@ export function CCAgentSessionView({log.error('[open workingDir]', err);toast.error(t('ccAgent.common.openFolderFailed'));}- }, [session?.workingDir, session?.remoteHostId, t]);+ }, [session?.workingDir, isRemoteWorktreeSession, liveWorktree, t]);const handleReturnToDispatcher = useCallback(() => {if (!ownsWindowRoute) {@@ -1475,15 +1493,7 @@ export function CCAgentSessionView({log.error('recover persisted deferred Worker assignment after session mount failed', err);toast.error(t('newChat.collaboration.assignmentFailed'));});- }, [- historyLoaded,- isOrcaLeadSessionView,- messages,- remoteConn,- remoteDeviceId,- sessionId,- t,- ]);+ }, [historyLoaded, isOrcaLeadSessionView, messages, remoteConn, remoteDeviceId, sessionId, t]);useEffect(() => {return subscribeWorkLouderCodexAction((action) => {if (action.type !== 'command') return false;@@ -2591,9 +2601,8 @@ export function CCAgentSessionView({): Promise<{ handled: boolean; accepted: boolean; message: string }> => {const slashMatch = message.match(/^\/(\S+)(?:\s+(.*))?$/s);const agentKind = dbToMakerAgentKind(session?.agentKind);- const leading = !slashMatch && agentKind === 'pi'- ? leadingSlashInvocation(message)- : undefined;+ const leading =+ !slashMatch && agentKind === 'pi' ? leadingSlashInvocation(message) : undefined;if (!slashMatch && !leading) return { handled: false, accepted: false, message };const cmdName = (slashMatch?.[1] ?? leading!.name).toLowerCase();const args = slashMatch?.[2] ?? '';@@ -3557,8 +3566,7 @@ export function CCAgentSessionView({continueAsSingleSession: true,}),),- onAssignmentUnconfirmed: () =>- toast.error(t('newChat.collaboration.assignmentFailed')),+ onAssignmentUnconfirmed: () => toast.error(t('newChat.collaboration.assignmentFailed')),});if (remoteCollab.ok) {deferredUiAssignment = remoteCollab.deferredUiAssignment;@@ -3726,8 +3734,7 @@ export function CCAgentSessionView({continueAsSingleSession: true,}),),- onAssignmentUnconfirmed: () =>- toast.error(t('newChat.collaboration.assignmentFailed')),+ onAssignmentUnconfirmed: () => toast.error(t('newChat.collaboration.assignmentFailed')),});if (remoteCollab.ok) {deferredUiAssignment = remoteCollab.deferredUiAssignment;@@ -3836,13 +3843,18 @@ export function CCAgentSessionView({// - /clear 之后留在空 ChatView 已经在用,体验没问题,本来就跟"空 session"等价// 现在所有空消息流/有消息流都走同一套布局(全高 scroll container + sticky bottom// overlay),自然消除 view 翻转带来的 layout shift。+ const composerDir = composerWorkingDirPath({+ workingDir: session?.workingDir,+ liveWorktree,+ isRemote: isRemoteWorktreeSession,+ });const workingDirLabel = !session?.workingDir? '\u00A0': session.workspaceKind === 'dialogue'? `${t('ccAgent.layout.dialogueLabel')} ${basename(session.workingDir).slice(0, 8)}`- : worktreeMeta- ? `${basename(worktreeMeta.baseRepo)} (${worktreeMeta.name})`- : basename(session.workingDir);+ : liveWorktree+ ? formatWorktreeChipText(liveWorktree)+ : basename(composerDir ?? session.workingDir);const workingDirChipContent = (<><Monitor size={12} className="shrink-0 text-[var(--workingdir-icon)]" />@@ -3850,10 +3862,8 @@ export function CCAgentSessionView({"<dialogueLabel> <first-8-chars>" so the chip carriessemantic meaning while keeping inter-session distinguishability.Full path stays in the hover tip.- Worktree-mode: 走 baseRepo basename + worktree name 的两段式- "xdt-maker (feat-button-ui)" —— 单段 basename 只显示 worktree- 名字,看不出是哪个 repo 的 worktree;两段式让用户一眼定位到 repo,- 括号里再补 worktree 标识。完整 worktree 绝对路径仍在 hover tip 里。 */}+ Worktree-mode: 官方与识别出的非官方都走 repo (worktree) 两段式,+ 例如 "cindy (steady-goodall)"。完整路径仍在 hover tip 里。 */}<span className="block min-w-0 truncate text-12 font-medium leading-none text-[var(--workingdir-text)]">{workingDirLabel}</span>@@ -4348,15 +4358,16 @@ export function CCAgentSessionView({agent 区分 pending)。内部会订阅 ccMgrUpgradeStore, 该 host 无 pending时自渲染 null (零开销)。sessionId 传给 banner 用于 U3 — 升级完成后自动重发该 session 的 last user message。 */}- {(session?.agentKind === 'cc' || session?.agentKind === 'pi') && session?.remoteHostId && (- <UpgradeBanner- hostId={session.remoteHostId}- agent={session.agentKind === 'pi' ? 'pi' : 'cc'}- sessionId={session.id}- style={{ width: inputWidth }}- className="py-1"- />- )}+ {(session?.agentKind === 'cc' || session?.agentKind === 'pi') &&+ session?.remoteHostId && (+ <UpgradeBanner+ hostId={session.remoteHostId}+ agent={session.agentKind === 'pi' ? 'pi' : 'cc'}+ sessionId={session.id}+ style={{ width: inputWidth }}+ className="py-1"+ />+ )}{/* 零可用模型引导条:与首屏引导卡共享判定与 dismiss(useProviderOnboarding),组件自判 visible、不可见渲染 null。device-link 远程会话不出——连接态在被控端。 */}@@ -4661,24 +4672,24 @@ export function CCAgentSessionView({) : (<Tiptext={- session?.workingDir ? (+ composerDir ? (session?.remoteHostId ? (// 远端 session: Tip 顶部加一行 "Host: <alias>" 让用户在// 同 workingDir 跨多 host 撞合场景下也能区分。hostId 即// SSH alias (HostConfig.id), 不需要额外 lookup。<><div>Host: {session.remoteHostId}</div>- <div>{session.workingDir}</div>+ <div>{composerDir}</div></>) : (- session.workingDir+ composerDir)) : null}monoside="top">- {session?.remoteHostId ? (+ {isRemoteWorktreeSession ? (<div className="flex min-w-0 items-center gap-1.5">{workingDirChipContent}</div>@@ -4761,9 +4772,7 @@ export function CCAgentSessionView({{!isMac &&(ownsRoute || showRsbToggle) &&rightSidebarCollapsed &&- rightSidebarSide === 'right' && (- <div aria-hidden className="h-7 w-7 shrink-0" />- )}+ rightSidebarSide === 'right' && <div aria-hidden className="h-7 w-7 shrink-0" />}</TopRightChipStack></section></>diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.tsindex aa1e1cbc0f..3253fdc7e8 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts@@ -76,9 +76,9 @@ export function nextSortByAfterGroupByChange(}/*** 任务行右侧信息项(复选)。存储数组的顺序 = 用户勾选先后(nextTaskInfoAfterToggle- * 按序追加),列表行据此渲染(2026-08-12 用户裁决);菜单里四个选项的排列另有固定顺序。+ * 按序追加),列表行据此渲染(2026-08-12 用户裁决);菜单里选项的排列另有固定顺序。*/-export type TaskInfoField = 'time' | 'pr' | 'tokens' | 'cost';+export type TaskInfoField = 'time' | 'pr' | 'worktree' | 'tokens' | 'cost';export type ManualProjectDropPosition = 'before' | 'after';const STATUS_VALUES: ReadonlySet<string> = new Set<FilterStatus>(['active', 'archived', 'all']);@@ -499,6 +499,7 @@ export function persistSortBy(sortBy: FilterSortBy): void {const TASK_INFO_VALUES: ReadonlySet<string> = new Set<TaskInfoField>(['time','pr',+ 'worktree','tokens','cost',]);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex 47ae668f04..8079c8f910 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -33,7 +33,6 @@ import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';import { cn } from '@/lib/utils';-import { WorktreeBadge } from '@/components/sidebar/WorktreeBadge';import { SessionStatusIcon } from './SessionStatusIcon';import { ScheduleBindingBadge } from './ScheduleBindingBadge';import { AutomationTimerIcon } from './AutomationTimerIcon';@@ -62,7 +61,9 @@ import { buildSessionDeepLink } from '@/lib/deepLink';import { createLogger } from '@/lib/logger';import type { Session } from '@/lib/ccAgent.types';import { usePrActions, usePrRefsForSession } from '@/contexts/PrRefsContext';-import { buildSessionInfoPieces, SessionInfoMeta } from './SessionInfoMeta';+import { buildSessionInfoPieces, SessionInfoMeta, type SessionInfoPiece } from './SessionInfoMeta';+import { useTaskInfoWorktree, type SessionWorktreeInfo } from './sessionWorktreeInfo';+import type { SessionPrRef } from '@/lib/gitContext.types';import { useTaskInfoFields } from '../hooks/useTaskInfoFields';import { highlightSegments } from '../lib/highlightSegments';import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';@@ -87,10 +88,7 @@ import {scheduleFocusPath,} from '@/features/scheduler/lib/scheduleSessionBinding';import { loadScheduleSidebarIndexRuns } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';-import {- projectSidebarSessionActivity,- resolveSidebarRightStatus,-} from './sidebarRightStatus';+import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';import { Tip } from '@/components/ui/tooltip';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';@@ -236,13 +234,15 @@ export function SessionCard({const { fields: taskInfoFields } = useTaskInfoFields();const cardPrRefs = usePrRefsForSession(session.id);const cardInfoPrRef = taskInfoFields.includes('pr') ? cardPrRefs[0] : undefined;- // 传 hasPrRef 让 PR 参与「按勾选顺序」排列(否则它恒在最前)。+ const cardInfoWorktree = useTaskInfoWorktree(session, taskInfoFields.includes('worktree'));+ // 传 hasPrRef / hasWorktree 让它们参与「按勾选顺序」排列。const cardInfoPieces = buildSessionInfoPieces(session,taskInfoFields,activityIso,t,cardInfoPrRef != null,+ cardInfoWorktree != null,);// 勾选 pr 且行渲染时注册为 PR 消费者:注册即拉取(远程会话含引用补拉),// 此后 Provider 周期/聚焦统一刷新,失败自愈(与 SessionItem 同一条路径)。@@ -636,6 +636,7 @@ export function SessionCard({onClick={handleClick}onDoubleClick={handleDoubleClick}onKeyDown={(e) => {+ if (e.target !== e.currentTarget) return;if (!isEditing && (e.key === 'Enter' || e.key === ' ')) {e.preventDefault();onClick(session.id);@@ -794,9 +795,9 @@ export function SessionCard({Agent 身份图标留在标题左侧,状态指示器改由下方右下角承担。 */}{!isEditing && (<TimeActionsSlot- sessionId={session.id}- session={session}- activityIso={activityIso}+ pieces={cardInfoPieces}+ prRef={cardInfoPrRef}+ worktree={cardInfoWorktree ?? undefined}isActive={isActive}isArchived={isArchived}canQuickArchive={canQuickArchive}@@ -1006,11 +1007,11 @@ export function SessionCard({}/>)}- <WorktreeBadge sessionId={session.id} size={11} className="size-3.5" />- {/* 任务信息复选(C / C' 期):卡片版右下角与 list/text 同源;默认仅 time 与旧渲染等价。 */}+ {/* 任务信息复选:卡片版右下角与 list/text 同源;默认仅 time 与旧渲染等价。 */}<SessionInfoMetapieces={cardInfoPieces}prRef={cardInfoPrRef}+ worktree={cardInfoWorktree ?? undefined}isActive={isActive}className={cn('ml-auto shrink-0 text-11 font-medium leading-none',@@ -1176,9 +1177,9 @@ export function SessionCard({* 交互逻辑与对话列表(SessionItem)一致。Agent 身份 / 草稿由左侧 SessionStatusIcon 承担;* list 的右下状态指示器由 SidebarRightStatusIndicator 单独承担。 */function TimeActionsSlot({- sessionId,- session,- activityIso,+ pieces,+ prRef,+ worktree,isActive,isArchived,canQuickArchive,@@ -1193,10 +1194,9 @@ function TimeActionsSlot({yieldToOrdinalBadge = false,ordinalBadgeLabel,}: {- sessionId: string;- /** 任务信息复选(C 期)需要读 totalTokenUsage / totalMoney 等字段。 */- session: Session;- activityIso: string;+ pieces: readonly SessionInfoPiece[];+ prRef?: SessionPrRef;+ worktree?: SessionWorktreeInfo;isActive: boolean;isArchived: boolean;canQuickArchive: boolean;@@ -1213,18 +1213,6 @@ function TimeActionsSlot({ordinalBadgeLabel?: string | null;}) {const { t } = useTranslation();- // 任务信息复选(C / C' 期):与 SessionItem 的时间槽同源;默认仅 time 与旧渲染等价。- const { fields: taskInfoFields } = useTaskInfoFields();- const prRefs = usePrRefsForSession(session.id);- const infoPrRef = taskInfoFields.includes('pr') ? prRefs[0] : undefined;- // 传 hasPrRef 让 PR 参与「按勾选顺序」排列(否则它恒在最前)。- const infoPieces = buildSessionInfoPieces(- session,- taskInfoFields,- activityIso,- t,- infoPrRef != null,- );return (<div className="group/slot relative ml-auto flex h-[22px] shrink-0 items-center justify-end"><div className="grid h-[22px] grid-cols-[max-content] items-center justify-items-end">@@ -1239,10 +1227,10 @@ function TimeActionsSlot({archivePending && 'invisible opacity-0',)}>- <WorktreeBadge sessionId={sessionId} size={11} className="size-3.5" /><SessionInfoMeta- pieces={infoPieces}- prRef={infoPrRef}+ pieces={pieces}+ prRef={prRef}+ worktree={worktree}isActive={isActive}className="leading-none"/>diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsxindex 85939fa37b..9054050743 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx@@ -7,6 +7,8 @@* 全不选渲染 null(行右侧留空)。** 数据口径:+ * - worktree:Cindy 官方仍登记且目录还在,或本机任务遥测里仍活着的 linked+ * worktree(可回溯,不只最近 cwd)。Folders + 短名;官方可点开目录,外部只展示。* - pr:session_pr_refs 的最新一条(lastSeenAt 降序首位),显示「状态 icon +* 等宽 `#号`」,与会话顶栏 GitContextBadge 的 PrChip 同款(2026-08-12 用户* 裁决:仿顶栏,状态颜色只上在 icon 上,`#号` 文字用信息槽常规灰):形状表@@ -33,15 +35,17 @@*/import { useEffect, useState } from 'react';-import { GitPullRequest } from 'lucide-react';+import { Folders, GitPullRequest } from 'lucide-react';import { formatCompactTokens } from '@cindy/maker-shared/usage-format';import { useTranslation } from 'react-i18next';import { useIsDarkMode } from '@/components/markdown/useIsDarkMode';+import { Tip } from '@/components/ui/tooltip';import { usePrActions, usePrStatus } from '@/contexts/PrRefsContext';import { cn } from '@/lib/utils';import type { Session } from '@/lib/ccAgent.types';import type { SessionPrRef } from '@/lib/gitContext.types';+import { createLogger } from '@/lib/logger';import { formatMoney, formatUsd } from '@/lib/usageFormat';import { prStatusKey } from '@/lib/prStatus';import {@@ -53,6 +57,9 @@ import {} from '../gitContextPrVisuals';import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';import type { TaskInfoField } from '../hooks/useTaskInfoFields';+import type { SessionWorktreeInfo } from './sessionWorktreeInfo';++const log = createLogger('SessionInfoMeta');type TFunc = (key: string, options?: Record<string, unknown>) => string;@@ -79,6 +86,8 @@ export function buildSessionInfoPieces(t: TFunc,/** 该会话是否有 PR 引用;有才为 'pr' 排一个占位(无 PR 的行不占位)。 */hasPrRef = false,+ /** 该会话是否有可显示的 worktree;有才为 'worktree' 排一个占位。 */+ hasWorktree = false,): SessionInfoPiece[] {const pieces: SessionInfoPiece[] = [];for (const field of fields) {@@ -122,6 +131,10 @@ export function buildSessionInfoPieces(// 占位:PR 徽标要单独订阅状态缓存(见 PrNumberPiece),内容由 SessionInfoMeta// 渲染时替换。放进 pieces 只为让它参与「按勾选顺序」排列。pieces.push({ key: 'pr', text: '' });+ continue;+ }+ if (field === 'worktree' && hasWorktree) {+ pieces.push({ key: 'worktree', text: '' });}}return pieces;@@ -219,19 +232,62 @@ function PrNumberPiece({ prRef, isActive }: { prRef: SessionPrRef; isActive?: bo* prRef 的位置由 pieces 里的 'pr' 占位决定(= 用户勾选顺序);兼容未传* hasPrRef 的旧调用:那时 pieces 里没有占位,PR 仍前置渲染。*/+function WorktreePiece({ info }: { info: SessionWorktreeInfo }) {+ const { t } = useTranslation();+ const openLabel = t('ccAgent.sidebar.taskInfo.openWorktree');+ const detail = info.branch ? `${info.branch} · ${info.path}` : info.path;+ const icon = <Folders size={11} strokeWidth={1.75} className="block" />;+ if (!info.canReveal) {+ return (+ <Tip text={detail} mono>+ <span className="flex shrink-0 items-center">{icon}</span>+ </Tip>+ );+ }+ return (+ <Tip text={`${openLabel} · ${detail}`} mono>+ <button+ type="button"+ aria-label={openLabel}+ onClick={(event) => {+ event.stopPropagation();+ void window.electronAPI+ .worktreeReveal({ path: info.path })+ .then((result) => {+ if (result && result.ok === false) {+ log.warn('reveal rejected:', result.error?.message ?? 'unknown');+ }+ })+ .catch((err) => {+ log.warn('reveal failed:', err);+ });+ }}+ onPointerDown={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ className="flex shrink-0 items-center"+ >+ {icon}+ </button>+ </Tip>+ );+}+export function SessionInfoMeta({pieces,prRef,+ worktree,isActive,className,}: {pieces: readonly SessionInfoPiece[];/** 勾选了 pr 且该会话有 PR 引用时传入(最新一条);否则 undefined 不占位。 */prRef?: SessionPrRef;+ /** 勾选了 worktree 且该会话有 live / 路径形态 worktree 时传入。 */+ worktree?: SessionWorktreeInfo;isActive?: boolean;className?: string;}) {- if (pieces.length === 0 && !prRef) return null;+ if (pieces.length === 0 && !prRef && !worktree) return null;return (<spanclassName={cn(@@ -240,14 +296,19 @@ export function SessionInfoMeta({className,)}>- {/* 顺序完全由 pieces 决定(= 用户勾选顺序);'pr' 是占位,这里换成徽标。- 兼容旧调用:未把 pr 排进 pieces 时(hasPrRef 未传),仍按老样子前置。 */}+ {/* 顺序完全由 pieces 决定(= 用户勾选顺序);'pr' / 'worktree' 是占位,这里换成徽标。+ 兼容旧调用:未把字段排进 pieces 时,仍按老样子前置。 */}{prRef && !pieces.some((piece) => piece.key === 'pr') && (<PrNumberPiece prRef={prRef} isActive={isActive} />)}+ {worktree && !pieces.some((piece) => piece.key === 'worktree') && (+ <WorktreePiece info={worktree} />+ )}{pieces.map((piece, index) => (<span key={piece.key} className="flex shrink-0 items-center gap-1" title={piece.title}>- {(index > 0 || (prRef && !pieces.some((p) => p.key === 'pr'))) && (+ {(index > 0 ||+ (prRef && !pieces.some((p) => p.key === 'pr')) ||+ (worktree && !pieces.some((p) => p.key === 'worktree'))) && (<span aria-hidden className="opacity-50">·</span>@@ -256,6 +317,10 @@ export function SessionInfoMeta({prRef ? (<PrNumberPiece prRef={prRef} isActive={isActive} />) : null+ ) : piece.key === 'worktree' ? (+ worktree ? (+ <WorktreePiece info={worktree} />+ ) : null) : piece.dateTime ? (<time dateTime={piece.dateTime}>{piece.text}</time>) : (diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex 53eabe9d77..b8818deb3c 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -38,7 +38,6 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import type { Session } from '@/lib/ccAgent.types';import { makerChatStore } from '@/lib/makerChatStore';-import { WorktreeBadge } from '@/components/sidebar/WorktreeBadge';import { SessionStatusIcon } from './SessionStatusIcon';import { SessionRenameInput } from '../SessionRenameInput';import { usePrActions, usePrRefsForSession } from '@/contexts/PrRefsContext';@@ -64,6 +63,7 @@ import { toast } from '@/lib/toast';import { buildSessionDeepLink } from '@/lib/deepLink';import { createLogger } from '@/lib/logger';import { buildSessionInfoPieces, SessionInfoMeta } from './SessionInfoMeta';+import { useTaskInfoWorktree } from './sessionWorktreeInfo';import { useTaskInfoFields } from '../hooks/useTaskInfoFields';import { highlightSegments } from '../lib/highlightSegments';import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';@@ -94,10 +94,7 @@ import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';import { useAgentIslandActivity } from '@/state/agentIslandActivity';-import {- projectSidebarSessionActivity,- resolveSidebarRightStatus,-} from './sidebarRightStatus';+import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';import { AutomationTimerIcon } from './AutomationTimerIcon';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';import {@@ -363,13 +360,15 @@ export const SessionItem = memo(function SessionItem({: session.updatedAt;// PR 信息(C' 期):勾选且有引用时取最新一条(prRefs 已按 lastSeenAt 降序)。const infoPrRef = taskInfoFields.includes('pr') ? prRefs[0] : undefined;- // 传 hasPrRef 让 PR 参与「按勾选顺序」排列(否则它恒在最前)。+ const infoWorktree = useTaskInfoWorktree(session, taskInfoFields.includes('worktree'));+ // 传 hasPrRef / hasWorktree 让它们参与「按勾选顺序」排列。const infoPieces = buildSessionInfoPieces(session,taskInfoFields,activityIso,t,infoPrRef != null,+ infoWorktree != null,);// 右侧状态指示器五档优先级(高→低),色表全端统一(侧栏 / 卡片 / 灵动岛同一张表):// 1. error(出错终止 / 定时任务失败未读)→ 红点 —— 红专职表示"坏了"@@ -1072,19 +1071,17 @@ export const SessionItem = memo(function SessionItem({</span>)}- {/* 右侧 WorktreeBadge + 最近活动时间 + Archive 快捷按钮。+ {/* 右侧任务信息 + Archive 快捷按钮。时间使用 sidebar 排序同一时间轴 session.updatedAt(scheduler 自动 fire也会 bump,不用 userSendAt 避免被绑定给定时任务的会话时间冻结)。- WorktreeBadge 紧贴时间左侧(仅在 WorktreeContext map 中存在 sessionId 时- 渲染), 与时间同步 hover-fade 让位给 action buttons —— 让右侧只看到一组- 视觉元素, 不和 action buttons 共存。+ worktree 并入任务信息复选,与 PR / 费用同一槽,不再常驻分叉图标。archive 快捷按钮 hover/focus 时进同一格文档流,标题 truncate 让位;完整菜单仍走右键。槽宽跟可见内容走:平时信息槽有多宽占多宽,「任务信息 =无」且无状态、无 worktree 时宽度归零。hover / 菜单打开时按钮入流,槽宽取信息层与按钮的较大值——不再绝对定位盖到标题上。 */}{!isEditing && (<div className="group/slot relative ml-auto flex h-6 shrink-0 items-center justify-end">- {/* WorktreeBadge + time 同步 fade-out:hover/菜单打开/archivePending 时+ {/* 任务信息同步 fade-out:hover/菜单打开/archivePending 时一起让位,确保只有 action buttons 占住右侧。fade 容器复用同一份条件,避免两个元素 fade 时机不一致产生闪烁。focus 隐藏条件用命名 group(/slot) 收窄到本槽位:行本身是@@ -1104,13 +1101,17 @@ export const SessionItem = memo(function SessionItem({ordinalBadgeLabel != null && 'opacity-0',)}>- <WorktreeBadge sessionId={session.id} size={12} className="size-4" />{showRightStatus ? (<SidebarRightStatusIndicator kind={rightStatusKind} isActive={isActive} />) : (- // 任务信息复选(C 期):按用户勾选拼装 pr / tokens / cost / time;默认仅+ // 任务信息复选:按用户勾选拼装 pr / worktree / tokens / cost / time;默认仅// time,与旧时间槽渲染等价。全不选 → SessionInfoMeta 渲染 null,槽宽归零。- <SessionInfoMeta pieces={infoPieces} prRef={infoPrRef} isActive={isActive} />+ <SessionInfoMeta+ pieces={infoPieces}+ prRef={infoPrRef}+ worktree={infoWorktree ?? undefined}+ isActive={isActive}+ />)}</div>diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsxindex 9759db5ee5..5f027c4809 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx@@ -7,7 +7,7 @@* alphabetic 已删除)* - 筛选:一级只占一行,右侧显示摘要(「无」/「N 项生效」),展开二级子菜单* 承载 Status / Project / Agent / Last activity 四维度 + 重置筛选- * - 显示:主列表形态(文字/列表)+ 任务信息复选(time / pr / tokens / cost)+ * - 显示:主列表形态(文字/列表)+ 任务信息复选(time / pr / worktree / tokens / cost)** 入口仍复用 sliders-horizontal 图标;内容为行式菜单 + 子菜单。*@@ -32,6 +32,7 @@ import {Coins,Filter,Folder,+ Folders,GitPullRequest,Globe,Info,@@ -131,14 +132,16 @@ const PROJECT_SORT_BY_OPTIONS: ReadonlyArray<Option<FilterSortBy>> = [];/**- * 本表的顺序 = 菜单里四个复选项的排列顺序(固定)。列表行的**渲染顺序**另算:+ * 本表的顺序 = 菜单里复选项的排列顺序(固定)。列表行的**渲染顺序**另算:* 按用户勾选先后(2026-08-12 用户裁决),见 SessionInfoMeta。* 图标对应各自的数据类型:时间=Clock(Timer 已被自动任务独占,不复用避免撞义)、- * PR=GitPullRequest(与顶栏 / 侧栏徽标未知态同一个字形)、token=Coins、费用=Wallet。+ * PR=GitPullRequest、worktree=Folders(独立工作副本,不跟 PR 的 git 分叉抢形)、+ * token=Coins、费用=Wallet。*/const TASK_INFO_OPTIONS: ReadonlyArray<Option<TaskInfoField>> = [{ value: 'time', labelKey: 'ccAgent.sidebar.taskInfo.time', Icon: Clock },{ value: 'pr', labelKey: 'ccAgent.sidebar.taskInfo.pr', Icon: GitPullRequest },+ { value: 'worktree', labelKey: 'ccAgent.sidebar.taskInfo.worktree', Icon: Folders },{ value: 'tokens', labelKey: 'ccAgent.sidebar.taskInfo.tokens', Icon: Coins },{ value: 'cost', labelKey: 'ccAgent.sidebar.taskInfo.cost', Icon: Wallet },];diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.tsindex 6393166ed3..e1bab2a389 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts@@ -97,6 +97,10 @@ vi.mock('@/components/sidebar/WorktreeBadge', () => ({: null,}));+vi.mock('@/contexts/WorktreeContext', () => ({+ useWorktreeForSession: () => null,+}));+vi.mock('@/state/agentIslandActivity', () => ({useAgentIslandActivity: (sessionId: string) => {const compactDetail = mocks.runningDetailBySession.get(sessionId);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionInfoMetaWorktree.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionInfoMetaWorktree.test.tsnew file mode 100644index 0000000000..35d3d15ff8--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionInfoMetaWorktree.test.ts@@ -0,0 +1,70 @@+// @vitest-environment jsdom++import { createElement } from 'react';+import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { SessionInfoMeta } from '../SessionInfoMeta';+import type { SessionWorktreeInfo } from '../sessionWorktreeInfo';++const reveal = vi.fn();++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('@/contexts/PrRefsContext', () => ({+ usePrActions: () => ({ fetchStatusesForSession: vi.fn() }),+ usePrStatus: () => undefined,+}));++beforeEach(() => {+ Object.assign(window, {+ electronAPI: {+ worktreeReveal: reveal,+ },+ });+});++afterEach(() => {+ cleanup();+ reveal.mockReset();+});++const managed: SessionWorktreeInfo = {+ path: '/repo/.cindy-worktrees/steady-goodall',+ name: 'steady-goodall',+ branch: 'cindy/steady-goodall',+ source: 'managed',+ canReveal: true,+};++describe('SessionInfoMeta worktree 徽标', () => {+ it('shows only the worktree icon in task info, not the name', () => {+ render(+ createElement(SessionInfoMeta, {+ pieces: [{ key: 'worktree', text: '' }],+ worktree: managed,+ }),+ );+ expect(screen.getByLabelText('ccAgent.sidebar.taskInfo.openWorktree')).toBeTruthy();+ expect(screen.queryByText('steady-goodall')).toBeNull();+ });++ it('does not make observed worktree icons an action control', () => {+ render(+ createElement(SessionInfoMeta, {+ pieces: [{ key: 'worktree', text: '' }],+ worktree: {+ ...managed,+ source: 'observed',+ canReveal: false,+ },+ }),+ );+ expect(screen.queryByRole('button')).toBeNull();+ expect(screen.queryByLabelText('ccAgent.sidebar.taskInfo.openWorktree')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.tsindex 6154efc2ff..f7cd665583 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts@@ -88,6 +88,10 @@ vi.mock('@/components/sidebar/WorktreeBadge', () => ({WorktreeBadge: () => null,}));+vi.mock('@/contexts/WorktreeContext', () => ({+ useWorktreeForSession: () => null,+}));+vi.mock('@/lib/toast', () => ({toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },}));diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfo.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfo.test.tsnew file mode 100644index 0000000000..c94f6d2e9b--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfo.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest';++import {+ composerWorkingDirPath,+ formatWorktreeChipText,+ observedWorktreeFromTelemetry,+ pathBasename,+ resolveManagedWorktree,+ selectDisplayedWorktree,+} from '../sessionWorktreeInfo';++describe('sessionWorktreeInfo', () => {+ it('maps an official store entry', () => {+ expect(+ resolveManagedWorktree({+ path: '/repo/.cindy-worktrees/steady-goodall',+ name: 'steady-goodall',+ branch: 'cindy/steady-goodall',+ }),+ ).toEqual({+ path: '/repo/.cindy-worktrees/steady-goodall',+ name: 'steady-goodall',+ branch: 'cindy/steady-goodall',+ source: 'managed',+ canReveal: true,+ });+ expect(resolveManagedWorktree(null)).toBeNull();+ });++ it('only observes telemetry that landed in a live linked worktree', () => {+ expect(+ observedWorktreeFromTelemetry({+ source: 'telemetry',+ workdir: '/repo/.worktrees/dash-slug',+ branch: 'dash/slug',+ isInsideWorktree: true,+ }),+ ).toMatchObject({+ path: '/repo/.worktrees/dash-slug',+ name: 'dash-slug',+ source: 'observed',+ canReveal: false,+ });+ });++ it('ignores the session workingDir fallback even when it is a git repo', () => {+ expect(+ observedWorktreeFromTelemetry({+ source: 'workingDir',+ workdir: '/repo',+ branch: 'main',+ isInsideWorktree: false,+ }),+ ).toBeNull();+ });++ it('ignores telemetry that is still the main checkout', () => {+ expect(+ observedWorktreeFromTelemetry({+ source: 'telemetry',+ workdir: '/repo',+ branch: 'main',+ isInsideWorktree: false,+ }),+ ).toBeNull();+ });++ it('does not offer reveal on observed worktrees', () => {+ expect(+ observedWorktreeFromTelemetry({+ source: 'telemetry',+ workdir: '/repo/.worktrees/dash-slug',+ branch: null,+ isInsideWorktree: true,+ }),+ ).toMatchObject({ canReveal: false });+ });++ it('keeps windows path names', () => {+ expect(pathBasename('D:\\repo\\.cindy-worktrees\\feat-win\\')).toBe('feat-win');+ });++ it('hides the badge when the official worktree directory is gone', () => {+ const managed = resolveManagedWorktree({+ path: '/repo/.cindy-worktrees/steady-goodall',+ name: 'steady-goodall',+ branch: 'cindy/steady-goodall',+ });+ expect(+ selectDisplayedWorktree({+ enabled: true,+ managed,+ officialStillLive: false,+ observed: null,+ }),+ ).toBeNull();+ expect(+ selectDisplayedWorktree({+ enabled: true,+ managed,+ officialStillLive: true,+ observed: null,+ }),+ ).toEqual(managed);+ });++ it('formats the composer chip as repo (worktree)', () => {+ expect(+ formatWorktreeChipText({+ path: '/Users/dash/Code/Cindy/cindy/.cindy-worktrees/steady-goodall',+ name: 'steady-goodall',+ branch: 'cindy/steady-goodall',+ source: 'managed',+ canReveal: true,+ }),+ ).toBe('cindy (steady-goodall)');+ expect(+ formatWorktreeChipText({+ path: '/Users/dash/Code/Cindy/cindy-my-task',+ name: 'cindy-my-task',+ branch: 'dash/my-task',+ source: 'observed',+ canReveal: false,+ }),+ ).toBe('cindy-my-task');+ });++ it('opens the displayed worktree path, not the session workingDir fallback', () => {+ const observed = {+ path: '/repo/.worktrees/dash-slug',+ name: 'dash-slug',+ branch: 'dash/slug',+ source: 'observed' as const,+ canReveal: false,+ };+ expect(+ composerWorkingDirPath({+ workingDir: '/repo',+ liveWorktree: observed,+ isRemote: false,+ }),+ ).toBe('/repo/.worktrees/dash-slug');+ expect(+ composerWorkingDirPath({+ workingDir: '/remote/repo',+ liveWorktree: observed,+ isRemote: true,+ }),+ ).toBe('/remote/repo');+ });++ it('treats device-link the same as SSH: never open a remote path locally', () => {+ expect(+ composerWorkingDirPath({+ workingDir: '/Users/other/project',+ liveWorktree: {+ path: '/Users/other/.cindy-worktrees/foo',+ name: 'foo',+ branch: 'cindy/foo',+ source: 'managed',+ canReveal: true,+ },+ isRemote: true,+ }),+ ).toBe('/Users/other/project');+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.tsnew file mode 100644index 0000000000..3788c42aad--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts@@ -0,0 +1,215 @@+/**+ * 任务信息里的 worktree 徽标:认「这条任务开过 / 用过 worktree」,不认路径长什么样。+ *+ * managed = Cindy 官方 create 仍登记在 store 里,且目录还是 linked worktree+ * observed = 本机任务遥测里仍活着的 linked worktree(可回溯,不只最近一次 cwd)+ *+ * 本机 Desktop 专用。SSH / device-link / Mobile 第一期不显示。+ * 侧栏任务信息只读官方 store(共享快照,不每行扫 Git);打开中的任务才回溯遥测。+ * 不写 store、不改变回收。目录没了摘掉徽标。外部 observed 不可 reveal。+ */++import { useEffect, useState } from 'react';++import { groupingWorktreeBaseRepo } from '@cindy/maker-shared/worktree-paths';++import { useWorktreeForSession } from '@/contexts/WorktreeContext';+import type { Session } from '@/lib/ccAgent.types';+import type { GitContextDirSource } from '@/lib/gitContext.types';+import type { DetectCwdResp, WorktreeMeta } from '@/lib/worktree.types';++export interface SessionWorktreeInfo {+ path: string;+ name: string;+ branch: string | null;+ source: 'managed' | 'observed';+ canReveal: boolean;+}++const DETECT_CWD_CHANNEL = 'worktree:detect-cwd';++export function resolveManagedWorktree(+ official: Pick<WorktreeMeta, 'path' | 'name' | 'branch'> | null,+): SessionWorktreeInfo | null {+ if (!official?.path) return null;+ return {+ path: official.path,+ name: official.name || pathBasename(official.path),+ branch: official.branch ?? null,+ source: 'managed',+ canReveal: true,+ };+}++/** 只有 tool-use 遥测指向 linked worktree 才算「任务里开过」;workingDir 兜底不算。 */+export function observedWorktreeFromTelemetry(opts: {+ source: GitContextDirSource;+ workdir: string | null;+ branch: string | null;+ isInsideWorktree: boolean;+}): SessionWorktreeInfo | null {+ if (opts.source !== 'telemetry' || !opts.workdir || !opts.isInsideWorktree) return null;+ return {+ path: opts.workdir,+ name: pathBasename(opts.workdir),+ branch: opts.branch,+ source: 'observed',+ canReveal: false,+ };+}++export function selectDisplayedWorktree(opts: {+ enabled: boolean;+ managed: SessionWorktreeInfo | null;+ officialStillLive: boolean;+ observed: SessionWorktreeInfo | null;+}): SessionWorktreeInfo | null {+ if (!opts.enabled) return null;+ if (opts.managed && opts.officialStillLive) return opts.managed;+ return opts.observed;+}++export function pathBasename(value: string): string {+ const trimmed = value.replace(/[\\/]+$/, '');+ const parts = trimmed.split(/[\\/]/);+ return parts[parts.length - 1] || trimmed;+}++/** 聊天框底部 workingDir chip: `repo (worktree)`;认不出 base repo 时只显示短名。 */+export function formatWorktreeChipText(info: SessionWorktreeInfo): string {+ const base = groupingWorktreeBaseRepo(info.path);+ if (base) return `${pathBasename(base)} (${info.name})`;+ return info.name;+}++/** chip 文案、hover、打开目录共用这一条路径,避免显示 worktree 却打开主仓。远端仍用 session.workingDir。 */+export function composerWorkingDirPath(opts: {+ workingDir: string | null | undefined;+ liveWorktree: SessionWorktreeInfo | null;+ isRemote: boolean;+}): string | null {+ if (opts.isRemote) return opts.workingDir ?? null;+ return opts.liveWorktree?.path ?? opts.workingDir ?? null;+}++export function useTaskInfoWorktree(+ session: Pick<+ Session,+ 'id' | 'workingDir' | 'worktreePath' | 'deviceLinkDeviceId' | 'remoteHostId'+ >,+ enabled: boolean,+ opts?: { observeTelemetry?: boolean },+): SessionWorktreeInfo | null {+ const official = useWorktreeForSession(session.id);+ const managed = resolveManagedWorktree(official);+ const [observed, setObserved] = useState<SessionWorktreeInfo | null>(null);+ const [officialStillLive, setOfficialStillLive] = useState(true);+ const officialPath = official?.path ?? null;+ const deviceId = session.deviceLinkDeviceId ?? null;+ const isRemote = Boolean(deviceId || session.remoteHostId);+ const observeTelemetry = Boolean(opts?.observeTelemetry);++ useEffect(() => {+ setObserved(null);+ if (!enabled || isRemote || !observeTelemetry) {+ setOfficialStillLive(!isRemote);+ return;+ }+ let cancelled = false;+ let generation = 0;+ let inflight: Promise<void> | null = null;+ let queued = false;+ const refreshOnce = async () => {+ const gen = ++generation;+ if (officialPath) {+ const live = await probeIsInsideWorktree(officialPath, deviceId);+ if (cancelled || gen !== generation) return;+ setOfficialStillLive(live);+ if (live) {+ setObserved(null);+ return;+ }+ } else if (gen === generation) {+ setOfficialStillLive(false);+ }+ if (isRemote) {+ if (!cancelled && gen === generation) setObserved(null);+ return;+ }+ const next = await discoverObservedWorktree(session.id);+ if (!cancelled && gen === generation) setObserved(next);+ };+ const refresh = () => {+ if (inflight) {+ queued = true;+ return inflight;+ }+ inflight = refreshOnce().finally(() => {+ inflight = null;+ if (cancelled) return;+ if (queued) {+ queued = false;+ void refresh();+ }+ });+ return inflight;+ };+ void refresh();+ const unsubscribe = window.electronAPI.onWorktreeChanged?.(() => {+ void refresh();+ });+ const onFocus = () => {+ void refresh();+ };+ window.addEventListener('focus', onFocus);+ return () => {+ cancelled = true;+ unsubscribe?.();+ window.removeEventListener('focus', onFocus);+ };+ }, [enabled, officialPath, deviceId, isRemote, observeTelemetry, session.id]);++ if (isRemote) return null;+ if (!observeTelemetry) {+ return selectDisplayedWorktree({+ enabled,+ managed,+ officialStillLive: true,+ observed: null,+ });+ }+ return selectDisplayedWorktree({+ enabled,+ managed,+ officialStillLive,+ observed,+ });+}++async function probeIsInsideWorktree(cwd: string, deviceId: string | null): Promise<boolean> {+ try {+ const detect: DetectCwdResp = deviceId+ ? ((await window.electronAPI.deviceLink.invoke(deviceId, DETECT_CWD_CHANNEL, [+ { cwd },+ ])) as DetectCwdResp)+ : await window.electronAPI.worktreeDetectCwd({ cwd });+ return Boolean(detect?.isInsideWorktree);+ } catch {+ return false;+ }+}++async function discoverObservedWorktree(sessionId: string): Promise<SessionWorktreeInfo | null> {+ try {+ const found = await window.electronAPI.gitContext.findLinkedWorktree({ sessionId });+ if (!found?.workdir) return null;+ return observedWorktreeFromTelemetry({+ source: 'telemetry',+ workdir: found.workdir,+ branch: found.branch,+ isInsideWorktree: true,+ });+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b7ca0c9da5..dcaeb4bede 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7637,6 +7637,8 @@"taskInfo": {"time": "Time","pr": "PR status",+ "worktree": "worktree",+ "openWorktree": "Open worktree folder","tokens": "Tokens","cost": "Cost"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 8cf33c012e..9441ad2fc5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7652,6 +7652,8 @@"taskInfo": {"time": "時間","pr": "PR ステータス",+ "worktree": "worktree",+ "openWorktree": "worktree フォルダーを開く","tokens": "トークン","cost": "コスト"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 56fc05b4eb..11c9574b72 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7652,6 +7652,8 @@"taskInfo": {"time": "시간","pr": "PR 상태",+ "worktree": "worktree",+ "openWorktree": "worktree 폴더 열기","tokens": "토큰","cost": "비용"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 60aa346ec2..2bb79a96cb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7625,6 +7625,8 @@"taskInfo": {"time": "时间","pr": "PR 状态",+ "worktree": "worktree",+ "openWorktree": "打开 worktree 文件夹","tokens": "Token","cost": "费用"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0780e36a9e..4383b83568 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7652,6 +7652,8 @@"taskInfo": {"time": "時間","pr": "PR 狀態",+ "worktree": "worktree",+ "openWorktree": "開啟 worktree 資料夾","tokens": "Token","cost": "費用"},diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex f3c5917fb8..2421658443 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3964,6 +3964,10 @@ interface ElectronAPI {worktreePath: string | null;remoteHostId?: string | null;}) => Promise<import('@/lib/gitContext.types').SessionGitDirResult>;+ findLinkedWorktree: (input: { sessionId: string }) => Promise<{+ workdir: string;+ branch: string | null;+ } | null>;watch: (workdir: string) => Promise<void>;unwatch: (workdir: string) => Promise<void>;listPrRefs: (sessionId: string) => Promise<import('@/lib/gitContext.types').SessionPrRef[]>;diff --git a/docs/product-rules/sidebar-redesign-plan.md b/docs/product-rules/sidebar-redesign-plan.mdindex cabc269d8f..fb501c8c1e 100644--- a/docs/product-rules/sidebar-redesign-plan.md+++ b/docs/product-rules/sidebar-redesign-plan.md@@ -209,13 +209,14 @@- **任务信息**(一行入口,二级复选菜单):决定任务行标题右侧显示哪些信息,**顺序 = 用户勾选先后**(2026-08-12 用户裁决,推翻原「固定 PR · token · 费用 ·时间」),以「·」分隔——先勾时间再勾费用就显示「时间 · 费用」,反过来即相反。- 勾选状态本身按顺序存储,PR 也参与排列;菜单里四个复选项自身的排列顺序不变。+ 勾选状态本身按顺序存储,PR / worktree 也参与排列;菜单里复选项自身的排列顺序不变。一行入口右侧用**已选项的图标串**表示当前选择(不罗列短词):| 项 | 默认 | 形态 ||---|---|---|| 最近活动时间 | **勾** | 现状行为 || PR 状态 | | 状态 icon + 等宽 `#号`(与顶栏 PrChip 同款,2026-08-12 用户裁决):状态颜色只上在 icon 上(形状 + 颜色双编码,四态见 `gitContextPrVisuals`;open 绿按表面取 `#2EA043` / `#3FB950`,2026-08-17);`#号` 文字用信息槽常规灰;open/draft 且有未解决 review thread 时 icon 右上角 5px `--status-bar-accent` 静点;文字状态放 hover;无 PR 的任务不显示不占位 |+| worktree | | Folders 图标,不写短名;默认不勾。仅本机 Desktop。侧栏只认 Cindy 官方 store(共享快照);打开中的任务才回溯遥测,短名在聊天框底部 `仓库 (worktree)`。SSH / device-link / Mobile 不显示。外部 observed 不可从侧栏 reveal。目录没了摘标。 || 累计 token | | `1.4M` / `320k` 缩写,无单位 || 费用 | | 按 `totalCostCurrency` 显示 $/¥;无数据(如订阅模式)留空 |