π€― 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(chat): persist working directory metadata (#16675)
Arvin Xu310960d6a8fc
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkingDirs.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkingDirs.test.tsindex 944cc7db4bf..707e6d55d9e 100644--- a/apps/server/src/routers/lambda/__tests__/deviceWorkingDirs.test.ts+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkingDirs.test.ts@@ -24,6 +24,27 @@ describe('preserveWorkspaceCache', () => {]);});+ it('preserves incoming git metadata while re-attaching the server cache', () => {+ const incoming: WorkingDirEntry[] = [+ {+ git: { activeWorktree: '/proj-fix', branch: 'fix', isWorktree: true },+ path: '/proj',+ repoType: 'git',+ },+ ];+ const stored: WorkingDirEntry[] = [{ path: '/proj', workspace, workspaceScannedAt: 123 }];++ expect(preserveWorkspaceCache(incoming, stored)).toEqual([+ {+ git: { activeWorktree: '/proj-fix', branch: 'fix', isWorktree: true },+ path: '/proj',+ repoType: 'git',+ workspace,+ workspaceScannedAt: 123,+ },+ ]);+ });+it('drops the cache for a path no longer present (dir removed)', () => {const stored: WorkingDirEntry[] = [{ path: '/proj', workspace, workspaceScannedAt: 123 }];diff --git a/apps/server/src/routers/lambda/__tests__/workingDirSchema.test.ts b/apps/server/src/routers/lambda/__tests__/workingDirSchema.test.tsnew file mode 100644index 00000000000..5d8323294d9--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/workingDirSchema.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { workingDirConfigSchema } from '../workingDirSchema';++describe('workingDirConfigSchema', () => {+ it('preserves GitHub PR metadata under git.github', () => {+ const value = {+ git: {+ activeWorktree: '/repo-fix',+ branch: 'fix/worktree',+ github: {+ extraPullRequestCount: 1,+ pullRequest: {+ ciStatus: 'pending',+ isDraft: false,+ mergeStateStatus: 'CLEAN',+ mergeable: 'MERGEABLE',+ mergedAt: null,+ number: 123,+ reviewDecision: 'APPROVED',+ state: 'OPEN',+ title: 'Improve worktree handling',+ url: 'https://github.com/lobehub/lobehub/pull/123',+ },+ pullRequestStatus: 'ok',+ },+ isWorktree: true,+ },+ path: '/repo',+ repoType: 'github',+ };++ expect(workingDirConfigSchema.parse(value)).toEqual(value);+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 91fcdec0f9f..cb2c64ee9c6 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -29,6 +29,8 @@ import { AiChatService } from '@/server/services/aiChat';import { getFileProxyUrl } from '@/server/services/file';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';+import { workingDirConfigSchema } from './workingDirSchema';+const log = debug('lobe-server:ai-agent-router');const createUiMessageFileUrlResolver = () => {@@ -146,6 +148,7 @@ const ExecAgentSchema = z.object({repos: z.array(z.string()).optional(),workingDirectory: z.string().optional(),+ workingDirectoryConfig: workingDirConfigSchema.optional(),}).optional(),/**diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 195e100cdce..0492c594e33 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -18,6 +18,7 @@ import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGaimport { preserveWorkspaceCache } from './deviceWorkingDirs';import { assertWorkspaceRootApproved } from './deviceWorkspaceGuard';+import { workingDirConfigSchema } from './workingDirSchema';// Derive the zod enum from the canonical config so new platforms are// automatically covered without touching this file.@@ -741,24 +742,22 @@ export const deviceRouter = router({// Online but not yet persisted β transient until the client auto-registers.const ghosts = [...channelsByDevice.entries()].filter(([deviceId]) => !seen.has(deviceId))- .map(- ([deviceId, channels]): DeviceListItem => ({- channels,- defaultCwd: null,- deviceId,- // No row yet β no enroller; UI gates treat this as not-editable.- enroller: null,- friendlyName: null,- hostname: channels[0]?.hostname ?? null,- identitySource: null,- lastSeen: channels[0]?.connectedAt ?? new Date().toISOString(),- online: true,- platform: channels[0]?.platform ?? null,- registered: false,- scope,- workingDirs: [] as WorkingDirEntry[],- }),- );+ .map(([deviceId, channels]): DeviceListItem => ({+ channels,+ defaultCwd: null,+ deviceId,+ // No row yet β no enroller; UI gates treat this as not-editable.+ enroller: null,+ friendlyName: null,+ hostname: channels[0]?.hostname ?? null,+ identitySource: null,+ lastSeen: channels[0]?.connectedAt ?? new Date().toISOString(),+ online: true,+ platform: channels[0]?.platform ?? null,+ registered: false,+ scope,+ workingDirs: [] as WorkingDirEntry[],+ }));return [...fromDb, ...ghosts];};@@ -822,10 +821,7 @@ export const deviceRouter = router({defaultCwd: z.string().nullish(),deviceId: z.string(),friendlyName: z.string().max(100).nullish(),- workingDirs: z- .array(z.object({ path: z.string(), repoType: z.enum(['git', 'github']).optional() }))- .max(20)- .optional(),+ workingDirs: z.array(workingDirConfigSchema).max(20).optional(),}),).mutation(async ({ ctx, input }) => {@@ -910,16 +906,7 @@ export const deviceRouter = router({defaultCwd: z.string().nullish(),deviceId: z.string(),friendlyName: z.string().max(100).nullish(),- workingDirs: z- .array(- z.object({- git: z.object({ activeWorktree: z.string().optional() }).optional(),- path: z.string(),- repoType: z.enum(['git', 'github']).optional(),- }),- )- .max(20)- .optional(),+ workingDirs: z.array(workingDirConfigSchema).max(20).optional(),}),).mutation(async ({ ctx, input }) => {diff --git a/apps/server/src/routers/lambda/deviceWorkingDirs.ts b/apps/server/src/routers/lambda/deviceWorkingDirs.tsindex 44d39e8e502..58ac633fd82 100644--- a/apps/server/src/routers/lambda/deviceWorkingDirs.ts+++ b/apps/server/src/routers/lambda/deviceWorkingDirs.ts@@ -5,12 +5,12 @@ import type { WorkingDirEntry } from '@lobechat/types';* `workspaceScannedAt`) onto a client-supplied `workingDirs` list, matched by* `path`.*- * The `device.updateDevice` input only validates `{ path, repoType }` and zod- * strips everything else, so a client cwd save would otherwise overwrite the- * JSONB column with cache-less entries β wiping the scan written by- * `resolveWorkspaceInit` and forcing every later run to rescan. The cache is- * server-produced (the client never authors it), so we restore it here rather- * than trusting the client to round-trip it.+ * The device update inputs validate only user-owned directory metadata+ * (`path`, `repoType`, `git`) and zod strips everything else, so a client cwd+ * save would otherwise overwrite the JSONB column with cache-less entries β+ * wiping the scan written by `resolveWorkspaceInit` and forcing every later run+ * to rescan. The cache is server-produced (the client never authors it), so we+ * restore it here rather than trusting the client to round-trip it.** Entries dropped from `incoming` (e.g. the user removed a dir) lose their cache* by design; brand-new paths simply have none yet.diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 354ab1930a6..686fc0b721b 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -31,6 +31,7 @@ import {resolveContext,} from './_helpers/resolveContext';import { basicContextSchema } from './_schema/context';+import { workingDirConfigSchema } from './workingDirSchema';const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -647,6 +648,7 @@ export const topicRouter = router({metadata: z.object({boundDeviceId: z.string().optional(),heteroSessionId: z.string().optional(),+ heteroSessionIdByWorkingDirectory: z.record(z.string()).optional(),model: z.string().optional(),onboardingFeedback: z.object({@@ -693,6 +695,7 @@ export const topicRouter = router({.optional(),repos: z.array(z.string()).optional(),workingDirectory: z.string().optional(),+ workingDirectoryConfig: workingDirConfigSchema.optional(),}),}),)diff --git a/apps/server/src/routers/lambda/workingDirSchema.ts b/apps/server/src/routers/lambda/workingDirSchema.tsnew file mode 100644index 00000000000..f70f5ce7e3c--- /dev/null+++ b/apps/server/src/routers/lambda/workingDirSchema.ts@@ -0,0 +1,34 @@+import { z } from 'zod';++const gitLinkedPullRequestSchema = z.object({+ ciStatus: z.enum(['failure', 'pending', 'success', 'unknown']).optional(),+ isDraft: z.boolean().optional(),+ mergeable: z.string().optional(),+ mergeStateStatus: z.string().optional(),+ mergedAt: z.string().nullable().optional(),+ number: z.number(),+ reviewDecision: z.string().optional(),+ state: z.string(),+ title: z.string(),+ url: z.string(),+});++export const workingDirConfigSchema = z.object({+ git: z+ .object({+ activeWorktree: z.string().optional(),+ branch: z.string().optional(),+ detached: z.boolean().optional(),+ github: z+ .object({+ extraPullRequestCount: z.number().optional(),+ pullRequest: gitLinkedPullRequestSchema.nullable().optional(),+ pullRequestStatus: z.enum(['error', 'gh-missing', 'ok']).optional(),+ })+ .optional(),+ isWorktree: z.boolean().optional(),+ })+ .optional(),+ path: z.string(),+ repoType: z.enum(['git', 'github']).optional(),+});diff --git a/apps/server/src/services/aiAgent/__tests__/workspaceInitCache.test.ts b/apps/server/src/services/aiAgent/__tests__/workspaceInitCache.test.tsindex 67d947df2d4..a5e1d4743db 100644--- a/apps/server/src/services/aiAgent/__tests__/workspaceInitCache.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/workspaceInitCache.test.ts@@ -69,6 +69,27 @@ describe('upsertWorkspaceScan', () => {]);});+ it('updates a source entry with a worktree in place when upserted on its source path', () => {+ // Guards the worktree-scan fix: the caller resolves the MATCHED entry's+ // source path (not the bound worktree path), so a source entry keyed by+ // `/repo` with an active worktree is updated in place β no duplicate bare+ // worktree recent, and its git/worktree metadata survives.+ const dirs: WorkingDirEntry[] = [+ { git: { activeWorktree: '/repo-wt', isWorktree: true }, path: '/repo', repoType: 'git' },+ ];++ const result = upsertWorkspaceScan(dirs, '/repo', workspace, scannedAt);++ expect(result).toHaveLength(1);+ expect(result[0]).toEqual({+ git: { activeWorktree: '/repo-wt', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ workspace,+ workspaceScannedAt: scannedAt,+ });+ });+it('prepends a new most-recent-first entry when the cwd is unrecorded', () => {const dirs: WorkingDirEntry[] = [{ path: '/a' }];diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 206cef4c59c..e3c64bdc3c2 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -44,7 +44,13 @@ import type {UserInterventionConfig,WorkspaceInitResult,} from '@lobechat/types';-import { buildHeteroExecArgs, RequestTrigger, ThreadStatus, ThreadType } from '@lobechat/types';+import {+ buildHeteroExecArgs,+ getWorkingDirEffectivePath,+ RequestTrigger,+ ThreadStatus,+ ThreadType,+} from '@lobechat/types';import { nanoid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -126,7 +132,10 @@ import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';import { buildAllowedBuiltinTools, isDeviceToolIdentifier } from './deviceToolRegistry';import { ingestAttachment } from './ingestAttachment';import { pruneRegeneratedBranch } from './pruneRegeneratedBranch';-import { resolveDeviceWorkingDirectory } from './resolveDeviceWorkingDirectory';+import {+ resolveDeviceWorkingDirectory,+ resolveDeviceWorkingDirectoryConfig,+} from './resolveDeviceWorkingDirectory';import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache';const log = debug('lobe-server:ai-agent-service');@@ -605,12 +614,15 @@ export class AiAgentService {deviceDefaultCwd: device.defaultCwd,deviceId: activeDeviceId,topicWorkingDirectory: topic?.metadata?.workingDirectory,+ topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,workingDirByDevice: agencyConfig?.workingDirByDevice,});if (!boundCwd) return { workspace: empty };const workingDirs = device.workingDirs ?? [];- const cached = workingDirs.find((dir) => dir.path === boundCwd);+ const cached = workingDirs.find(+ (dir) => dir.path === boundCwd || getWorkingDirEffectivePath(dir) === boundCwd,+ );if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {log('execAgent: reusing cached workspace init for %s', boundCwd);@@ -637,7 +649,19 @@ export class AiAgentService {// a new MRU entry), keeping the JSONB payload bounded. Workspace devices// are owned by the workspace, not a userId β use the workspace-scoped// update path so the writeback actually lands.- const updated = upsertWorkspaceScan(workingDirs, boundCwd, scanned, Date.now());+ //+ // Update the MATCHED entry's path, not `boundCwd`: the lookup above can+ // match a source entry by its effective (worktree) path, so a selected+ // worktree reaches here with `boundCwd` = the worktree path while the+ // recorded entry is keyed by the source path. Upserting on `boundCwd`+ // would prepend a bare worktree recent and lose the source/worktree+ // metadata the picker relies on; upsert on the matched source path instead.+ const updated = upsertWorkspaceScan(+ workingDirs,+ cached?.path ?? boundCwd,+ scanned,+ Date.now(),+ );if (deviceWorkspaceId) {await deviceModel.updateWorkspaceDevice(activeDeviceId, { workingDirs: updated });} else {@@ -1254,6 +1278,9 @@ export class AiAgentService {...(initialTopicMeta?.workingDirectory && {workingDirectory: initialTopicMeta.workingDirectory,}),+ ...(initialTopicMeta?.workingDirectoryConfig && {+ workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,+ }),}: undefined;@@ -1847,20 +1874,26 @@ export class AiAgentService {const dispatchWorkspaceId = await this.resolveDeviceWorkspaceId(dispatchDeviceId);// Resolve via the shared precedence helper so dispatch, workspace-init,// and the new-topic backfill below all agree on the cwd.- const deviceCwd = resolveDeviceWorkingDirectory({+ const deviceCwdConfig = resolveDeviceWorkingDirectoryConfig({deviceDefaultCwd: boundDevice?.defaultCwd,deviceId: dispatchDeviceId,initialWorkingDirectory: appContext?.initialTopicMetadata?.workingDirectory,+ initialWorkingDirectoryConfig: appContext?.initialTopicMetadata?.workingDirectoryConfig,topicWorkingDirectory: topic?.metadata?.workingDirectory,+ topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,workingDirByDevice: agentConfig.agencyConfig?.workingDirByDevice,});+ const deviceCwd = getWorkingDirEffectivePath(deviceCwdConfig);// A brand-new topic has no pinned cwd yet: the directory was only// recorded at agent level (`workingDirByDevice`) when no topic existed.// Persist the resolved cwd onto the topic so the sidebar groups it// under the right project and the next turn reuses the same directory.if (isNewTopic && deviceCwd && deviceCwd !== topic?.metadata?.workingDirectory) {- await this.topicModel.updateMetadata(topicId, { workingDirectory: deviceCwd });+ await this.topicModel.updateMetadata(topicId, {+ workingDirectory: deviceCwd,+ ...(deviceCwdConfig ? { workingDirectoryConfig: deviceCwdConfig } : {}),+ });}// A device is the user's own persistent machine β build adiff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.tsindex 0f258697904..055d8c85af6 100644--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from 'vitest';-import { resolveDeviceWorkingDirectory } from './resolveDeviceWorkingDirectory';+import {+ resolveDeviceWorkingDirectory,+ resolveDeviceWorkingDirectoryConfig,+} from './resolveDeviceWorkingDirectory';describe('resolveDeviceWorkingDirectory', () => {it('prefers the existing topic override above everything else', () => {@@ -42,7 +45,11 @@ describe('resolveDeviceWorkingDirectory', () => {deviceDefaultCwd: '/default',deviceId: 'device-1',workingDirByDevice: {- 'device-1': { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },+ 'device-1': {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },},}),).toBe('/repo-fix');@@ -97,3 +104,39 @@ describe('resolveDeviceWorkingDirectory', () => {).toBeUndefined();});});++describe('resolveDeviceWorkingDirectoryConfig', () => {+ it('keeps topic rich config above all other sources', () => {+ const topicWorkingDirectoryConfig = {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git' as const,+ };++ expect(+ resolveDeviceWorkingDirectoryConfig({+ deviceDefaultCwd: '/default',+ deviceId: 'device-1',+ topicWorkingDirectory: '/repo-fix',+ topicWorkingDirectoryConfig,+ workingDirByDevice: { 'device-1': '/agent' },+ }),+ ).toEqual(topicWorkingDirectoryConfig);+ });++ it('returns the agent rich entry for new-topic backfill', () => {+ const agentChoice = {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git' as const,+ };++ expect(+ resolveDeviceWorkingDirectoryConfig({+ deviceDefaultCwd: '/default',+ deviceId: 'device-1',+ workingDirByDevice: { 'device-1': agentChoice },+ }),+ ).toEqual(agentChoice);+ });+});diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.tsindex 87bb6282e72..dcea804a733 100644--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts@@ -1,6 +1,13 @@-import type { WorkingDirConfigValue } from '@lobechat/types';+import type { WorkingDirConfig, WorkingDirConfigValue } from '@lobechat/types';import { getWorkingDirEffectivePath } from '@lobechat/types';+const toWorkingDirConfig = (+ value: WorkingDirConfigValue | null | undefined,+): WorkingDirConfig | undefined => {+ if (!value) return;+ return typeof value === 'string' ? { path: value } : value;+};+/*** Resolve the working directory for a device-bound run.*@@ -20,17 +27,30 @@ import { getWorkingDirEffectivePath } from '@lobechat/types';* when no topic existed yet.* - `deviceDefaultCwd` β the device's user-configured default.*/-export const resolveDeviceWorkingDirectory = (params: {+export const resolveDeviceWorkingDirectoryConfig = (params: {deviceDefaultCwd?: string | null;deviceId?: string;initialWorkingDirectory?: string;+ initialWorkingDirectoryConfig?: WorkingDirConfig;topicWorkingDirectory?: string;+ topicWorkingDirectoryConfig?: WorkingDirConfig;workingDirByDevice?: Record<string, WorkingDirConfigValue> | null;-}): string | undefined =>- params.topicWorkingDirectory ||- params.initialWorkingDirectory ||- getWorkingDirEffectivePath(+}): WorkingDirConfig | undefined => {+ if (params.topicWorkingDirectoryConfig) return params.topicWorkingDirectoryConfig;+ if (params.topicWorkingDirectory) return { path: params.topicWorkingDirectory };+ if (params.initialWorkingDirectoryConfig) return params.initialWorkingDirectoryConfig;+ if (params.initialWorkingDirectory) return { path: params.initialWorkingDirectory };++ const agentChoice = toWorkingDirConfig(params.deviceId ? params.workingDirByDevice?.[params.deviceId] : undefined,- ) ||- params.deviceDefaultCwd ||- undefined;+ );+ if (agentChoice) return agentChoice;+ if (params.deviceDefaultCwd) return { path: params.deviceDefaultCwd };+};++export const resolveDeviceWorkingDirectory = (+ params: Parameters<typeof resolveDeviceWorkingDirectoryConfig>[0],+): string | undefined => {+ const config = resolveDeviceWorkingDirectoryConfig(params);+ return getWorkingDirEffectivePath(config);+};diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 73366a082d9..52ce0449478 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -151,6 +151,15 @@"management.title": "Topics","management.view.card": "Card","management.view.list": "List",+ "metaCard.branchNote": "The chat branch reflects the active branch from your last session; sending a message updates it.",+ "metaCard.ci.failure": "CI failed",+ "metaCard.ci.none": "No CI checks",+ "metaCard.ci.pending": "CI running",+ "metaCard.ci.success": "CI passed",+ "metaCard.detached": "Detached HEAD at {{sha}}",+ "metaCard.pr.closed": "Closed",+ "metaCard.pr.merged": "Merged",+ "metaCard.pr.open": "Open","newTopic": "New Topic","projectStatus.failed_one": "{{count}} failed topic","projectStatus.failed_other": "{{count}} failed topics",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex 9735876d6dc..90779373ab6 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -151,6 +151,15 @@"management.title": "θ―ι’","management.view.card": "ε‘η","management.view.list": "ε葨",+ "metaCard.branchNote": "θ倩εζ―εζ δΈζ¬‘δ½Ώη¨ζΆηζ΄»ε¨εζ―οΌειζΆζ―ε°ζ΄ζ°θ倩εζ―",+ "metaCard.ci.failure": "CI ζͺιθΏ",+ "metaCard.ci.none": "ζ CI ζ£ζ₯",+ "metaCard.ci.pending": "CI θΏθ‘δΈ",+ "metaCard.ci.success": "CI ιθΏ",+ "metaCard.detached": "游离 HEAD δΊ {{sha}}",+ "metaCard.pr.closed": "ε·²ε ³ι",+ "metaCard.pr.merged": "ε·²εεΉΆ",+ "metaCard.pr.open": "εΌζΎδΈ","newTopic": "ζ°θ―ι’","projectStatus.failed_one": "{{count}} δΈͺιθ――θ―ι’","projectStatus.failed_other": "{{count}} δΈͺιθ――θ―ι’",diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.tsindex f566b56996e..7f46d068afc 100644--- a/packages/electron-client-ipc/src/types/git.ts+++ b/packages/electron-client-ipc/src/types/git.ts@@ -5,20 +5,30 @@ export interface GitBranchInfo {detached?: boolean;}+export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknown';+export interface GitLinkedPullRequest {+ ciStatus?: GitPullRequestCiStatus;+ isDraft?: boolean;+ mergeable?: string;+ mergedAt?: string | null;+ mergeStateStatus?: string;number: number;+ reviewDecision?: string;state: string;title: string;url: string;}+export type GitLinkedPullRequestLookupStatus = 'ok' | 'gh-missing' | 'error';+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';+ status: GitLinkedPullRequestLookupStatus;}export interface GitBranchListItem {diff --git a/packages/local-file-shell/src/git/info.ts b/packages/local-file-shell/src/git/info.tsindex 5782fb776d8..691acf75551 100644--- a/packages/local-file-shell/src/git/info.ts+++ b/packages/local-file-shell/src/git/info.ts@@ -8,13 +8,112 @@ import type {DeviceGitInfo,GitAheadBehind,GitBranchInfo,+ GitLinkedPullRequest,GitLinkedPullRequestResult,+ GitPullRequestCiStatus,GitWorkingTreeStatus,} from './types';const log = createLogger('local-file-shell:git');const execFileAsync = promisify(execFile);+type GithubStatusCheckRollupNode = {+ conclusion?: string | null;+ state?: string | null;+ status?: string | null;+};++type GithubPullRequestPayload = {+ isDraft?: boolean;+ mergeable?: string | null;+ mergeStateStatus?: string | null;+ mergedAt?: string | null;+ number: number;+ reviewDecision?: string | null;+ state: string;+ statusCheckRollup?: GithubStatusCheckRollupNode[] | null;+ title: string;+ url: string;+};++const failureConclusions = new Set([+ 'action_required',+ 'cancelled',+ 'failure',+ 'startup_failure',+ 'timed_out',+]);+const pendingStates = new Set([+ 'expected',+ 'in_progress',+ 'pending',+ 'queued',+ 'requested',+ 'waiting',+]);+const successConclusions = new Set(['neutral', 'skipped', 'success']);++const toLowerStatus = (value?: string | null) => value?.toLowerCase();++const resolveCiStatus = (+ checks?: GithubStatusCheckRollupNode[] | null,+): GitPullRequestCiStatus | undefined => {+ if (!Array.isArray(checks)) return undefined;+ if (checks.length === 0) return undefined;++ let hasPending = false;+ let hasUnknown = false;++ for (const check of checks) {+ const conclusion = toLowerStatus(check.conclusion);+ const state = toLowerStatus(check.state) ?? toLowerStatus(check.status);++ if (+ (conclusion && failureConclusions.has(conclusion)) ||+ state === 'failure' ||+ state === 'error'+ ) {+ return 'failure';+ }++ if (state && pendingStates.has(state)) {+ hasPending = true;+ continue;+ }++ if ((conclusion && successConclusions.has(conclusion)) || state === 'success') {+ continue;+ }++ hasUnknown = true;+ }++ if (hasPending) return 'pending';+ return hasUnknown ? 'unknown' : 'success';+};++const compactString = (value?: string | null) => value || undefined;++const normalizeGithubPullRequest = (pr: GithubPullRequestPayload): GitLinkedPullRequest => {+ const ciStatus = resolveCiStatus(pr.statusCheckRollup);+ const mergeable = compactString(pr.mergeable);+ const mergeStateStatus = compactString(pr.mergeStateStatus);+ const reviewDecision = compactString(pr.reviewDecision);++ return {+ ...(ciStatus ? { ciStatus } : {}),+ ...(pr.isDraft === undefined ? {} : { isDraft: pr.isDraft }),+ ...(mergeable ? { mergeable } : {}),+ ...(mergeStateStatus ? { mergeStateStatus } : {}),+ ...(pr.mergedAt === undefined ? {} : { mergedAt: pr.mergedAt }),+ number: pr.number,+ ...(reviewDecision ? { reviewDecision } : {}),+ state: pr.state,+ title: pr.title,+ url: pr.url,+ };+};+/** Current branch short name, or short SHA + `detached` for detached HEAD. */export const getGitBranch = async (dirPath: string): Promise<GitBranchInfo> => {try {@@ -56,18 +155,14 @@ export const getLinkedPullRequest = async (payload: {'--limit','5','--json',- 'number,url,title,state',+ 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup',],{ cwd: dirPath, timeout: 8000 },);- const parsed = JSON.parse(stdout.trim() || '[]') as Array<{- number: number;- state: string;- title: string;- url: string;- }>;+ const parsed = JSON.parse(stdout.trim() || '[]') as GithubPullRequestPayload[];if (parsed.length === 0) return { pullRequest: null, status: 'ok' };- const [primary, ...rest] = parsed;+ const [primaryRaw, ...rest] = parsed;+ const primary = normalizeGithubPullRequest(primaryRaw);return { extraCount: rest.length, pullRequest: primary, status: 'ok' };} catch (error: any) {const code = error?.code;diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.tsindex 2636dc0c5b6..a679c558908 100644--- a/packages/local-file-shell/src/git/types.ts+++ b/packages/local-file-shell/src/git/types.ts@@ -4,20 +4,30 @@ export interface GitBranchInfo {detached?: boolean;}+export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknown';+export interface GitLinkedPullRequest {+ ciStatus?: GitPullRequestCiStatus;+ isDraft?: boolean;+ mergeable?: string;+ mergedAt?: string | null;+ mergeStateStatus?: string;number: number;+ reviewDecision?: string;state: string;title: string;url: string;}+export type GitLinkedPullRequestLookupStatus = 'ok' | 'gh-missing' | 'error';+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' β succeeded; 'gh-missing' β gh CLI unavailable / not authed; 'error' β other. */- status: 'ok' | 'gh-missing' | 'error';+ status: GitLinkedPullRequestLookupStatus;}export interface GitWorkingTreeStatus {diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 33e0026a75f..b0ed2071096 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -31,6 +31,16 @@ export default {'duplicateSuccess': 'Topic Copied Successfully','failedStatusTip': 'This run hit an error β open it to take a look.','favorite': 'Favorite',+ 'metaCard.branchNote':+ 'The chat branch reflects the active branch from your last session; sending a message updates it.',+ 'metaCard.ci.failure': 'CI failed',+ 'metaCard.ci.none': 'No CI checks',+ 'metaCard.ci.pending': 'CI running',+ 'metaCard.ci.success': 'CI passed',+ 'metaCard.detached': 'Detached HEAD at {{sha}}',+ 'metaCard.pr.closed': 'Closed',+ 'metaCard.pr.merged': 'Merged',+ 'metaCard.pr.open': 'Open','filter.filter': 'Filter','filter.groupMode.byProject': 'By project','filter.groupMode.byStatus': 'By status',diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex 4feca146834..6e14ff66e83 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -506,9 +506,9 @@ export interface LobeAgentAgencyConfig {* > effective path of `workingDirByDevice[targetDeviceId]`* > `device.defaultCwd`*- * Legacy values are plain path strings. New git-aware values may carry- * `git.activeWorktree`; when present, that active worktree is the effective- * cwd while `path` remains the source/recent entry.+ * Legacy values are plain path strings. New git-aware values may carry `git`+ * metadata; when `git.activeWorktree` is present, that active worktree is the+ * effective cwd while `path` remains the source/recent entry.** Keyed per device so switching the bound device never resolves a path that* only exists on another machine. Persisted (server-synced) so the choicediff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 6fc55c5cc56..25107d54d1e 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -1,12 +1,9 @@+import type { WorkingDirConfig } from '../device';import type { TaskDetail, UIChatMessage } from '../message';import type { ChatTopic } from '../topic';export type AgentSignalOperationKind =- | 'memory'- | 'nightly-review'- | 'self-feedback-intent'- | 'self-reflection'- | 'skill';+ 'memory' | 'nightly-review' | 'self-feedback-intent' | 'self-reflection' | 'skill';/*** Run-scoped Agent Signal marker stamped onto a background agent operation at@@ -80,6 +77,7 @@ export interface ExecAgentAppContext {initialTopicMetadata?: {repos?: string[];workingDirectory?: string;+ workingDirectoryConfig?: WorkingDirConfig;};/*** Whether this operation is an isolated sub-agent execution. Used to disablediff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 6e8550bb2b3..9015957695d 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -59,19 +59,60 @@ export interface WorkspaceInitResult {/*** A working directory source a device has used. Structured (rather than a bare- * path string) so metadata such as the detected repo type and active git- * worktree survives β a remote client viewing this device can't re-probe its- * filesystem, so whatever isn't captured here at the source is lost. Mirrors- * the client-local `RecentDirEntry` shape.+ * path string) so metadata such as the detected repo type, active git+ * branch, and active git worktree survives β a remote client viewing this+ * device can't re-probe its filesystem, so whatever isn't captured here at the+ * source is lost.*/export type WorkingDirRepoType = 'git' | 'github';+export type DeviceGitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknown';++/** A GitHub pull request linked to a branch. */+export interface DeviceGitLinkedPullRequest {+ ciStatus?: DeviceGitPullRequestCiStatus;+ isDraft?: boolean;+ mergeable?: string;+ mergedAt?: string | null;+ mergeStateStatus?: string;+ number: number;+ reviewDecision?: string;+ state: string;+ title: string;+ url: string;+}++export type DeviceGitLinkedPullRequestLookupStatus = 'error' | 'gh-missing' | 'ok';++export interface WorkingDirGithubState {+ /** Additional open PRs targeting the same head branch, beyond the primary one. */+ extraPullRequestCount?: number;+ /** GitHub PR linked to the effective working directory's branch. */+ pullRequest?: DeviceGitLinkedPullRequest | null;+ /** Lookup status for the linked PR probe. */+ pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;+}+export interface WorkingDirGitState {/*** Active checkout selected under this git source. When absent, the source* path itself is the effective working directory.*/activeWorktree?: string;+ /**+ * Branch for the effective working directory. Undefined for detached HEAD or+ * when it has not been probed yet.+ */+ branch?: string;+ /** True when the effective working directory is currently detached. */+ detached?: boolean;+ /** GitHub-specific branch metadata such as linked PR and check status. */+ github?: WorkingDirGithubState;+ /**+ * True when the effective working directory is a linked worktree rather than+ * the source path itself.+ */+ isWorktree?: boolean;}export interface WorkingDirConfig {@@ -186,14 +227,6 @@ export interface DeviceGitBranchInfo {detached?: boolean;}-/** A GitHub pull request linked to a branch. */-export interface DeviceGitLinkedPullRequest {- number: number;- state: string;- title: string;- url: string;-}-/*** Result of the `getLinkedPullRequest` device RPC: the PR linked to a branch* (when the repo is a GitHub remote). Mirrors the desktop shape.@@ -204,7 +237,7 @@ export interface DeviceGitLinkedPullRequestResult {/** Null when no open PR is linked to the branch. */pullRequest: DeviceGitLinkedPullRequest | null;/** 'ok' β lookup succeeded; 'gh-missing' β gh CLI unavailable; 'error' β other failure. */- status: 'error' | 'gh-missing' | 'ok';+ status: DeviceGitLinkedPullRequestLookupStatus;}/**diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 9a6b6e9307f..dd19dd3550c 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -1,18 +1,14 @@import { z } from 'zod';import type { SerializedAgentHook } from '../agentHook';+import type { WorkingDirConfig } from '../device';import type { BaseDataModel } from '../meta';// Type definitionsexport type ShareVisibility = 'private' | 'link';export type TimeGroupId =- | 'today'- | 'yesterday'- | 'week'- | 'month'- | `${number}-${string}`- | `${number}`;+ 'today' | 'yesterday' | 'week' | 'month' | `${number}-${string}` | `${number}`;export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus';export type TopicSortBy = 'createdAt' | 'updatedAt';@@ -137,6 +133,15 @@ export interface ChatTopicMetadata {* `workingDirectory`.*/heteroSessionId?: string;+ /**+ * Heterogeneous-agent session ids scoped by effective working directory.+ * Claude Code stores native sessions under a cwd-specific project bucket, so+ * one topic may need different resume ids when the user switches worktrees.+ *+ * `heteroSessionId` remains the currently selected cwd's latest id for legacy+ * readers; this map lets the UI restore the right id when switching back.+ */+ heteroSessionIdByWorkingDirectory?: Record<string, string>;model?: string;/*** Free-form feedback collected after agent onboarding completion.@@ -189,6 +194,16 @@ export interface ChatTopicMetadata {* For sidebar grouping, topics are bucketed by this field (byProject mode).*/workingDirectory?: string;+ /**+ * Structured topic-level working directory snapshot.+ *+ * Kept as a single object, not a list. `workingDirectory` remains the+ * backwards-compatible effective path; this field preserves the source path+ * and git/worktree metadata needed to restore the same worktree when the user+ * switches back to the topic, and to render branch/worktree context in topic+ * lists without probing the device.+ */+ workingDirectoryConfig?: WorkingDirConfig;}export interface ChatTopicSummary {diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.tsindex 041941cce9f..c8388ebe324 100644--- a/packages/utils/src/client/topic.test.ts+++ b/packages/utils/src/client/topic.test.ts@@ -2,7 +2,14 @@ import type { ChatTopic } from '@lobechat/types';import dayjs from 'dayjs';import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';-import { groupTopicsByStatus, groupTopicsByTime, groupTopicsByUpdatedTime } from './topic';+import {+ getTopicWorkingDirectoryEffectivePath,+ getTopicWorkingDirectorySourcePath,+ groupTopicsByProject,+ groupTopicsByStatus,+ groupTopicsByTime,+ groupTopicsByUpdatedTime,+} from './topic';// Mock current date to ensure consistent test resultsconst NOW = '2024-01-15T12:00:00Z';@@ -215,6 +222,58 @@ describe('groupTopicsByUpdatedTime', () => {});});+describe('working directory topic helpers', () => {+ const createTopic = (+ id: string,+ metadata: ChatTopic['metadata'],+ updatedAt: number = 0,+ ): ChatTopic => ({+ createdAt: updatedAt,+ id,+ metadata,+ title: id,+ updatedAt,+ });++ it('preserves source and effective paths for worktree topics', () => {+ const topic = createTopic('worktree', {+ workingDirectory: '/repo-fix',+ workingDirectoryConfig: {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },+ });++ expect(getTopicWorkingDirectorySourcePath(topic)).toBe('/repo');+ expect(getTopicWorkingDirectoryEffectivePath(topic)).toBe('/repo-fix');+ });++ it('groups worktree topics under the source project', () => {+ const topics = [+ createTopic(+ 'worktree',+ {+ workingDirectory: '/repo-fix',+ workingDirectoryConfig: {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },+ },+ 2,+ ),+ createTopic('source', { workingDirectory: '/repo' }, 1),+ ];++ const result = groupTopicsByProject(topics, 'updatedAt');++ expect(result).toHaveLength(1);+ expect(result[0]).toMatchObject({ id: 'project:/repo', title: 'repo' });+ expect(result[0].children.map((topic) => topic.id)).toEqual(['worktree', 'source']);+ });+});+describe('groupTopicsByStatus', () => {const createTopic = (id: string,diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.tsindex 7889859bf94..b174eee5c65 100644--- a/packages/utils/src/client/topic.ts+++ b/packages/utils/src/client/topic.ts@@ -1,4 +1,11 @@-import type { ChatTopic, ChatTopicStatus, GroupedTopic, TimeGroupId } from '@lobechat/types';+import type {+ ChatTopic,+ ChatTopicMetadata,+ ChatTopicStatus,+ GroupedTopic,+ TimeGroupId,+} from '@lobechat/types';+import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';import dayjs from 'dayjs';import isToday from 'dayjs/plugin/isToday';import isYesterday from 'dayjs/plugin/isYesterday';@@ -106,7 +113,33 @@ const getProjectName = (dir: string): string => {return segments.at(-1) || dir;};-const normalizeWorkingDirectory = (dir: string): string => dir.replace(/[/\\]+$/, '').trim();+const normalizeWorkingDirectory = (dir: string): string => dir.trim().replace(/[/\\]+$/, '');++const normalizeOptionalWorkingDirectory = (dir: string | undefined): string | undefined => {+ if (!dir) return undefined;+ const normalized = normalizeWorkingDirectory(dir);+ return normalized || undefined;+};++export const getTopicMetadataWorkingDirectorySourcePath = (+ metadata?: ChatTopicMetadata,+): string | undefined =>+ normalizeOptionalWorkingDirectory(+ getWorkingDirSourcePath(metadata?.workingDirectoryConfig) ?? metadata?.workingDirectory,+ );++export const getTopicMetadataWorkingDirectoryEffectivePath = (+ metadata?: ChatTopicMetadata,+): string | undefined =>+ normalizeOptionalWorkingDirectory(+ getWorkingDirEffectivePath(metadata?.workingDirectoryConfig) ?? metadata?.workingDirectory,+ );++export const getTopicWorkingDirectorySourcePath = (topic: ChatTopic): string | undefined =>+ getTopicMetadataWorkingDirectorySourcePath(topic.metadata);++export const getTopicWorkingDirectoryEffectivePath = (topic: ChatTopic): string | undefined =>+ getTopicMetadataWorkingDirectoryEffectivePath(topic.metadata);export const groupTopicsByProject = (topics: ChatTopic[],@@ -117,8 +150,7 @@ export const groupTopicsByProject = (const groupsMap = new Map<string, { children: ChatTopic[]; path: string }>();for (const topic of topics) {- const raw = topic.metadata?.workingDirectory;- const normalized = raw ? normalizeWorkingDirectory(raw) : '';+ const normalized = getTopicWorkingDirectorySourcePath(topic) ?? '';const id = normalized ? `${PROJECT_GROUP_PREFIX}${normalized}` : NO_PROJECT_GROUP_ID;const existing = groupsMap.get(id);if (existing) {@@ -157,12 +189,7 @@ export const groupTopicsByProject = (// the sidebar surfaces "needs attention" in one place. The remaining buckets map// 1:1 to a status. The group `id` resolves its title via `groupTitle.byStatus.<id>`.export type TopicStatusBucket =- | 'pending'- | 'running'- | 'active'- | 'paused'- | 'completed'- | 'archived';+ 'pending' | 'running' | 'active' | 'paused' | 'completed' | 'archived';// Fixed priority order: `pending` (needs attention) comes first, then running,// then active; the remaining states fall below. Topics without a status arediff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsxindex e5f305d0d5c..c3291187b19 100644--- a/src/features/AgentTopicManager/index.tsx+++ b/src/features/AgentTopicManager/index.tsx@@ -1,6 +1,10 @@'use client';-import { groupTopicsByProject, groupTopicsByUpdatedTime } from '@lobechat/utils/client/topic';+import {+ getTopicWorkingDirectorySourcePath,+ groupTopicsByProject,+ groupTopicsByUpdatedTime,+} from '@lobechat/utils/client/topic';import { Flexbox, Skeleton } from '@lobehub/ui';import { memo, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -20,7 +24,7 @@ import Toolbar from './Toolbar';import TopicGrid from './TopicGrid';import TopicListView from './TopicListView';import {- getProjectLabel,+ getProjectFilterLabel,matchesGroup,matchesStatus,matchesTimeRange,@@ -144,9 +148,9 @@ const AgentTopicManager = memo(() => {const projects = useMemo(() => {const map = new Map<string, string>();for (const t of baseTopics) {- const wd = t.metadata?.workingDirectory;+ const wd = getTopicWorkingDirectorySourcePath(t);if (wd && !map.has(wd)) {- map.set(wd, getProjectLabel(t) ?? wd);+ map.set(wd, getProjectFilterLabel(t) ?? wd);}}return Array.from(map, ([value, label]) => ({ label, value }));diff --git a/src/features/AgentTopicManager/utils.test.ts b/src/features/AgentTopicManager/utils.test.tsnew file mode 100644index 00000000000..3499e4084d1--- /dev/null+++ b/src/features/AgentTopicManager/utils.test.ts@@ -0,0 +1,29 @@+import type { ChatTopic } from '@/types/topic';++import { getProjectFilterLabel, getProjectLabel, matchesGroup } from './utils';++const createTopic = (metadata: ChatTopic['metadata']): ChatTopic => ({+ createdAt: 1,+ id: 'topic-1',+ metadata,+ title: 'Topic',+ updatedAt: 1,+});++describe('AgentTopicManager utils', () => {+ it('matches project filters by source path while displaying active worktree context', () => {+ const topic = createTopic({+ workingDirectory: '/repo-fix',+ workingDirectoryConfig: {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },+ });++ expect(matchesGroup(topic, ['/repo'])).toBe(true);+ expect(matchesGroup(topic, ['/repo-fix'])).toBe(false);+ expect(getProjectFilterLabel(topic)).toBe('repo');+ expect(getProjectLabel(topic)).toBe('repo/repo-fix Β· fix');+ });+});diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.tsindex aaab8ce77f1..8a9bfc677f8 100644--- a/src/features/AgentTopicManager/utils.ts+++ b/src/features/AgentTopicManager/utils.ts@@ -1,3 +1,7 @@+import {+ getTopicWorkingDirectoryEffectivePath,+ getTopicWorkingDirectorySourcePath,+} from '@lobechat/utils/client/topic';import dayjs from 'dayjs';import type { ChatTopic } from '@/types/topic';@@ -31,9 +35,10 @@ export const matchesStatus = (topic: ChatTopic, status: StatusFilter): boolean =export const matchesGroup = (topic: ChatTopic, groupIds: string[]): boolean => {if (groupIds.length === 0) return true;- // ChatTopic doesn't surface groupId on the client type; fall back to metadata.workingDirectory- // as the project bucket key (matches sidebar ByProjectMode).- const project = topic.metadata?.workingDirectory ?? '';+ // ChatTopic doesn't surface groupId on the client type; fall back to the+ // working-directory source path as the project bucket key (matches sidebar+ // ByProjectMode). A selected git worktree still belongs to its source repo.+ const project = getTopicWorkingDirectorySourcePath(topic) ?? '';return groupIds.includes(project);};@@ -88,12 +93,25 @@ export const sortTopics = (topics: ChatTopic[], sortBy: SortBy): ChatTopic[] =>return sorted;};+const getPathName = (path: string): string => path.split(/[/\\]+/).findLast(Boolean) ?? path;++export const getProjectFilterLabel = (topic: ChatTopic): string | undefined => {+ const source = getTopicWorkingDirectorySourcePath(topic);+ return source ? getPathName(source) : undefined;+};+export const getProjectLabel = (topic: ChatTopic): string | undefined => {- const wd = topic.metadata?.workingDirectory;- if (!wd) return undefined;- // Show last segment of path for readability- const parts = wd.split('/').filter(Boolean);- return parts.at(-1) ?? wd;+ const source = getTopicWorkingDirectorySourcePath(topic);+ const effective = getTopicWorkingDirectoryEffectivePath(topic);+ const labelPath = effective ?? source;+ if (!labelPath) return undefined;++ const label = getPathName(labelPath);+ const sourceName = source ? getPathName(source) : undefined;+ const pathLabel = sourceName && sourceName !== label ? `${sourceName}/${label}` : label;+ const branch = topic.metadata?.workingDirectoryConfig?.git?.branch;++ return branch ? `${pathLabel} Β· ${branch}` : pathLabel;};/**diff --git a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsxindex 67d8166c2a9..7140ddc5406 100644--- a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx@@ -157,9 +157,14 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {// Only set workingDirectory when it hasn't been assigned yet (first selection).// Once set, it stays fixed so the topic keeps its sidebar grouping.- const patch: { repos: string[]; workingDirectory?: string } = { repos: nextRepos };+ const patch: {+ repos: string[];+ workingDirectory?: string;+ workingDirectoryConfig?: { path: string; repoType: 'github' };+ } = { repos: nextRepos };if (!currentWorkingDirectory && nextRepos.length > 0) {patch.workingDirectory = nextRepos[0];+ patch.workingDirectoryConfig = { path: nextRepos[0], repoType: 'github' };}await updateTopicMetadata(activeTopicId, patch);diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex 2d2657c0f77..2df97c39b19 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -1,13 +1,18 @@+import type { WorkingDirConfig, WorkingDirGithubState } from '@lobechat/types';+import { getWorkingDirEffectivePath } from '@lobechat/types';import { Icon, Tooltip } from '@lobehub/ui';import { toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';+import isEqual from 'fast-deep-equal';import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';-import { memo, useCallback, useState } from 'react';+import { memo, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import RingLoadingIcon from '@/components/RingLoading';import { electronSystemService } from '@/services/electron/system';-import { gitService } from '@/services/git';+import { type GitLinkedPRSummary, gitService } from '@/services/git';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import {useFetchGitAheadBehind,useFetchGitBranch,@@ -146,6 +151,16 @@ const styles = createStaticStyles(({ css }) => {};});+const toGithubMetadata = (prData?: GitLinkedPRSummary): WorkingDirGithubState | undefined => {+ if (!prData) return undefined;++ return {+ ...(prData.extraCount === undefined ? {} : { extraPullRequestCount: prData.extraCount }),+ pullRequest: prData.pullRequest ?? null,+ pullRequestStatus: prData.pullRequestStatus ?? (prData.ghMissing ? 'gh-missing' : 'ok'),+ };+};+interface GitStatusProps {/** When set, git status / branch switch / pull / push all run against this* remote device via RPC. Omit for the local machine (talks over IPC). */@@ -175,6 +190,11 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, dconst [switcherOpen, setSwitcherOpen] = useState(false);const [pulling, setPulling] = useState(false);const [pushing, setPushing] = useState(false);+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const activeTopicMetadata = useChatStore((s) =>+ s.activeTopicId ? topicSelectors.getTopicById(s.activeTopicId)(s)?.metadata : undefined,+ );+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);@@ -216,6 +236,53 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d[mutateBranch],);+ useEffect(() => {+ if (!activeTopicId || !activeTopicMetadata || !isGithub || !branch || detached || !prData) {+ return;+ }++ const currentConfig = activeTopicMetadata.workingDirectoryConfig;+ const currentWorkingDirectory =+ getWorkingDirEffectivePath(currentConfig) ?? activeTopicMetadata.workingDirectory;+ if (currentWorkingDirectory !== path) return;++ const github = toGithubMetadata(prData);+ if (!github) return;++ const source = currentConfig?.path ?? sourcePath ?? path;+ const isWorktree = source !== path;+ const git: NonNullable<WorkingDirConfig['git']> = {+ ...currentConfig?.git,+ branch,+ github,+ isWorktree,+ };+ if (detached === undefined) delete git.detached;+ else git.detached = detached;+ if (isWorktree) git.activeWorktree = path;+ else delete git.activeWorktree;++ const nextConfig: WorkingDirConfig = {+ ...currentConfig,+ git,+ path: source,+ repoType: 'github',+ };++ if (isEqual(currentConfig, nextConfig)) return;+ void updateTopicMetadata(activeTopicId, { workingDirectoryConfig: nextConfig });+ }, [+ activeTopicId,+ activeTopicMetadata,+ branch,+ detached,+ isGithub,+ path,+ prData,+ sourcePath,+ updateTopicMetadata,+ ]);+const syncBusy = pulling || pushing;const handlePull = useCallback(async () => {diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex aa6cfbd1c4c..91e0307b908 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -320,6 +320,9 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =const recents = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(targetDeviceId));const deviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(targetDeviceId));const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);+ const topicWorkingDirectoryConfig = useChatStore(+ (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,+ );const legacyAgentWorkingDirectory = useAgentStore((s) => s.localAgentWorkingDirectoryMap[agentId],);@@ -332,6 +335,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =deviceDefaultCwd,legacyAgentWorkingDirectory,topicWorkingDirectory,+ topicWorkingDirectoryConfig,});// Reset only makes sense when an agent-level override exists. The device-widediff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsxindex 87c4e13a015..0bee5f8bba4 100644--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -26,6 +26,12 @@ const gitHookMocks = vi.hoisted(() => ({useFetchGitWorktrees: vi.fn(),}));+const chatStoreMock = vi.hoisted(() => ({+ activeTopicId: undefined as string | undefined,+ topics: {} as Record<string, { metadata?: Record<string, unknown> }>,+ updateTopicMetadata: vi.fn(),+}));+vi.mock('../BranchSwitcher', () => ({default: ({ children }: { children: ReactNode }) => <>{children}</>,}));@@ -42,6 +48,16 @@ vi.mock('@/store/device', () => ({useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: typeof chatStoreMock) => unknown) => selector(chatStoreMock),+}));++vi.mock('@/store/chat/selectors', () => ({+ topicSelectors: {+ getTopicById: (id: string) => (state: typeof chatStoreMock) => state.topics[id],+ },+}));+vi.mock('@/store/global', () => ({useGlobalStore: (selector: (state: typeof globalStoreMock) => unknown) =>selector(globalStoreMock),@@ -97,6 +113,8 @@ vi.mock('react-i18next', () => ({beforeEach(() => {vi.clearAllMocks();+ chatStoreMock.activeTopicId = undefined;+ chatStoreMock.topics = {};globalStoreMock.status.showRightPanel = false;globalStoreMock.status.workingSidebarTab = 'resources';@@ -131,4 +149,61 @@ describe('GitStatus', () => {expect(globalStoreMock.setWorkingSidebarTab).toHaveBeenCalledWith('review');expect(globalStoreMock.toggleRightPanel).toHaveBeenCalledWith(true);});++ it('persists linked GitHub PR metadata into the active topic working directory config', async () => {+ chatStoreMock.activeTopicId = 'topic-1';+ chatStoreMock.topics = {+ 'topic-1': {+ metadata: {+ workingDirectory: '/repo',+ workingDirectoryConfig: {+ git: { branch: 'old-branch' },+ path: '/repo',+ repoType: 'github',+ },+ },+ },+ };+ gitHookMocks.useFetchGitLinkedPR.mockReturnValue({+ data: {+ pullRequest: {+ ciStatus: 'pending',+ mergeStateStatus: 'CLEAN',+ number: 123,+ state: 'OPEN',+ title: 'Improve worktree handling',+ url: 'https://github.com/lobehub/lobehub/pull/123',+ },+ pullRequestStatus: 'ok',+ },+ mutate: gitHookMocks.mutatePR,+ });++ render(<GitStatus isGithub agentId="agent-1" path="/repo" />);++ await waitFor(() => {+ expect(chatStoreMock.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ workingDirectoryConfig: {+ git: {+ branch: 'fix/remote-review',+ detached: false,+ github: {+ pullRequest: {+ ciStatus: 'pending',+ mergeStateStatus: 'CLEAN',+ number: 123,+ state: 'OPEN',+ title: 'Improve worktree handling',+ url: 'https://github.com/lobehub/lobehub/pull/123',+ },+ pullRequestStatus: 'ok',+ },+ isWorktree: false,+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });+ });});diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex 2424e98e244..48e44539875 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -4,13 +4,14 @@ import type {WorkingDirConfigValue,WorkingDirEntry,} from '@lobechat/types';-import { getWorkingDirEffectivePath } from '@lobechat/types';+import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';import { confirmModal } from '@lobehub/ui/base-ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import type { PartialDeep } from 'type-fest';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';+import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -23,13 +24,17 @@ const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | undif (!path) return undefined;const activeWorktree = entry.git?.activeWorktree?.trim();+ const branch = entry.git?.branch?.trim();const next: WorkingDirEntry = { ...entry, path };- if (activeWorktree) {- next.git = { ...entry.git, activeWorktree };- } else if (next.git) {- const git = { ...next.git };- delete git.activeWorktree;+ if (entry.git) {+ const git = { ...entry.git };+ if (activeWorktree) git.activeWorktree = activeWorktree;+ else delete git.activeWorktree;++ if (branch) git.branch = branch;+ else delete git.branch;+if (Object.keys(git).length > 0) next.git = git;else delete next.git;}@@ -60,12 +65,18 @@ const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({* and Clear would look dead.** Changing a topic's cwd invalidates its pinned CC session (sessions are keyed- * per-cwd), so warn before the implicit reset β same as the legacy pickers.+ * per-cwd), so warn before the reset and clear the stale session id as part of+ * the same metadata write β same as the legacy pickers.*/export const useCommitWorkingDirectory = (agentId: string) => {const { t } = useTranslation(['plugin', 'chat']);const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));+ // Heterogeneous CLI agents (Claude Code, Codex, β¦) store sessions per-cwd, so+ // their session cwd anchors to the SOURCE repo β a worktree switch (same repo,+ // different activeWorktree) must NOT change the session cwd or reset the+ // session. Non-hetero agents keep running in the effective (worktree) cwd.+ const isHetero = !!agencyConfig?.heterogeneousProvider;const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const updateAgentRuntimeEnvConfigById = useAgentStore((s) => s.updateAgentRuntimeEnvConfigById);const legacyAgentWorkingDirectory = useAgentStore(@@ -85,10 +96,30 @@ export const useCommitWorkingDirectory = (agentId: string) => {const writeCwd = useCallback(async (entry?: WorkingDirEntry) => {const effectivePath = getWorkingDirEffectivePath(entry);+ // The session cwd anchors to the source repo for hetero (stable across+ // worktree switches) and to the effective/worktree path otherwise.+ const sessionCwd = isHetero ? getWorkingDirSourcePath(entry) : effectivePath;// Topic override wins once a conversation exists; otherwise persist the// agent's per-device choice so a new topic inherits it.if (activeTopicId) {- await updateTopicMetadata(activeTopicId, { workingDirectory: effectivePath });+ const priorSessionCwd = isHetero+ ? (getWorkingDirSourcePath(activeTopic?.metadata?.workingDirectoryConfig) ??+ activeTopic?.metadata?.workingDirectory)+ : activeTopic?.metadata?.workingDirectory;+ const scopedHeteroSessionId = getHeteroSessionIdForWorkingDirectory(+ activeTopic?.metadata,+ sessionCwd,+ );+ // Only a change of session cwd (repo for hetero) invalidates the session;+ // a worktree switch within the same repo keeps it.+ const shouldUpdateHeteroSession =+ priorSessionCwd !== sessionCwd &&+ (!!activeTopic?.metadata?.heteroSessionId || !!scopedHeteroSessionId);+ await updateTopicMetadata(activeTopicId, {+ ...(shouldUpdateHeteroSession ? { heteroSessionId: scopedHeteroSessionId } : {}),+ workingDirectory: sessionCwd,+ workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,+ });} else {if (targetDeviceId) {const prev = agencyConfig?.workingDirByDevice ?? {};@@ -121,7 +152,9 @@ export const useCommitWorkingDirectory = (agentId: string) => {[agentId,agencyConfig,+ activeTopic,activeTopicId,+ isHetero,targetDeviceId,legacyAgentWorkingDirectory,updateAgentConfigById,@@ -137,7 +170,11 @@ export const useCommitWorkingDirectory = (agentId: string) => {// A topic override (when present) is the effective source β drop it first so// we fall back to the agent default rather than nuking everything.if (activeTopicId && activeTopic?.metadata?.workingDirectory) {- await updateTopicMetadata(activeTopicId, { workingDirectory: undefined });+ await updateTopicMetadata(activeTopicId, {+ ...(activeTopic.metadata.heteroSessionId ? { heteroSessionId: undefined } : {}),+ workingDirectory: undefined,+ workingDirectoryConfig: undefined,+ });return;}// No topic override: clear the agent-level default(s). Clearing sends@@ -182,9 +219,16 @@ export const useCommitWorkingDirectory = (agentId: string) => {const run = () => writeCwd(normalizedEntry);+ // Warn about losing the CLI session only when the SESSION cwd changes.+ // For hetero that's the source repo β a worktree switch within the same+ // repo keeps the session, so it must not trigger the reset warning.const priorSessionId = activeTopic?.metadata?.heteroSessionId;- const priorCwd = activeTopic?.metadata?.workingDirectory;- if (priorSessionId && priorCwd && priorCwd !== effectivePath) {+ const sessionCwd = isHetero ? getWorkingDirSourcePath(normalizedEntry) : effectivePath;+ const priorSessionCwd = isHetero+ ? (getWorkingDirSourcePath(activeTopic?.metadata?.workingDirectoryConfig) ??+ activeTopic?.metadata?.workingDirectory)+ : activeTopic?.metadata?.workingDirectory;+ if (priorSessionId && priorSessionCwd && priorSessionCwd !== sessionCwd) {confirmModal({cancelText: t('heteroAgent.switchCwd.cancel', { ns: 'chat' }),content: t('heteroAgent.switchCwd.content', { ns: 'chat' }),@@ -196,7 +240,7 @@ export const useCommitWorkingDirectory = (agentId: string) => {}await run();},- [activeTopic, t, writeCwd],+ [activeTopic, isHetero, t, writeCwd],);/**diff --git a/src/helpers/agentWorkingDirectory.test.ts b/src/helpers/agentWorkingDirectory.test.tsindex 5aac460b42e..beb3d93be39 100644--- a/src/helpers/agentWorkingDirectory.test.ts+++ b/src/helpers/agentWorkingDirectory.test.ts@@ -1,7 +1,11 @@import type { LobeAgentAgencyConfig } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { resolveAgentWorkingDirectory, resolveTargetDeviceId } from './agentWorkingDirectory';+import {+ resolveAgentWorkingDirectory,+ resolveAgentWorkingDirectoryConfig,+ resolveTargetDeviceId,+} from './agentWorkingDirectory';const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({ ...over });@@ -88,7 +92,11 @@ describe('resolveAgentWorkingDirectory', () => {const agencyConfig = cfg({executionTarget: 'local',workingDirByDevice: {- cur: { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },+ cur: {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },},});@@ -115,3 +123,38 @@ describe('resolveAgentWorkingDirectory', () => {expect(resolveAgentWorkingDirectory({})).toBeUndefined();});});++describe('resolveAgentWorkingDirectoryConfig', () => {+ it('keeps the topic-level rich config as a single structured directory', () => {+ const topicWorkingDirectoryConfig = {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git' as const,+ };++ expect(+ resolveAgentWorkingDirectoryConfig({+ agencyConfig: cfg({ workingDirByDevice: { cur: '/agent' } }),+ currentDeviceId: 'cur',+ topicWorkingDirectory: '/repo-fix',+ topicWorkingDirectoryConfig,+ }),+ ).toEqual(topicWorkingDirectoryConfig);+ });++ it('returns the agent rich entry so new topics can snapshot it', () => {+ const agentChoice = {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git' as const,+ };+ const agencyConfig = cfg({+ executionTarget: 'local',+ workingDirByDevice: { cur: agentChoice },+ });++ expect(resolveAgentWorkingDirectoryConfig({ agencyConfig, currentDeviceId: 'cur' })).toEqual(+ agentChoice,+ );+ });+});diff --git a/src/helpers/agentWorkingDirectory.ts b/src/helpers/agentWorkingDirectory.tsindex e7760c7fc3f..2239bf10886 100644--- a/src/helpers/agentWorkingDirectory.ts+++ b/src/helpers/agentWorkingDirectory.ts@@ -1,4 +1,8 @@-import type { LobeAgentAgencyConfig } from '@lobechat/types';+import type {+ LobeAgentAgencyConfig,+ WorkingDirConfig,+ WorkingDirConfigValue,+} from '@lobechat/types';import { getWorkingDirEffectivePath } from '@lobechat/types';/**@@ -17,6 +21,13 @@ export const resolveTargetDeviceId = (? currentDeviceId || agencyConfig?.boundDeviceId: currentDeviceId;+const toWorkingDirConfig = (+ value: WorkingDirConfigValue | null | undefined,+): WorkingDirConfig | undefined => {+ if (!value) return;+ return typeof value === 'string' ? { path: value } : value;+};+/*** Unified working-directory precedence (mirrors the server's resolution):*@@ -29,14 +40,15 @@ export const resolveTargetDeviceId = (* The legacy slot keeps existing desktop users' selections working until they* next pick a directory (which writes the new per-device map).*/-export const resolveAgentWorkingDirectory = (params: {+export const resolveAgentWorkingDirectoryConfig = (params: {agencyConfig?: LobeAgentAgencyConfig;currentDeviceId?: string;deviceDefaultCwd?: string;fallback?: string;legacyAgentWorkingDirectory?: string;topicWorkingDirectory?: string;-}): string | undefined => {+ topicWorkingDirectoryConfig?: WorkingDirConfig;+}): WorkingDirConfig | undefined => {const {agencyConfig,currentDeviceId,@@ -44,17 +56,24 @@ export const resolveAgentWorkingDirectory = (params: {fallback,legacyAgentWorkingDirectory,topicWorkingDirectory,+ topicWorkingDirectoryConfig,} = params;+ if (topicWorkingDirectoryConfig) return topicWorkingDirectoryConfig;+ if (topicWorkingDirectory) return { path: topicWorkingDirectory };+const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);- const agentChoice = targetDeviceId- ? getWorkingDirEffectivePath(agencyConfig?.workingDirByDevice?.[targetDeviceId])- : undefined;- return (- topicWorkingDirectory ||- agentChoice ||- legacyAgentWorkingDirectory ||- deviceDefaultCwd ||- fallback ||- undefined+ const agentChoice = toWorkingDirConfig(+ targetDeviceId ? agencyConfig?.workingDirByDevice?.[targetDeviceId] : undefined,);+ if (agentChoice) return agentChoice;+ if (legacyAgentWorkingDirectory) return { path: legacyAgentWorkingDirectory };+ if (deviceDefaultCwd) return { path: deviceDefaultCwd };+ if (fallback) return { path: fallback };+};++export const resolveAgentWorkingDirectory = (+ params: Parameters<typeof resolveAgentWorkingDirectoryConfig>[0],+): string | undefined => {+ const config = resolveAgentWorkingDirectoryConfig(params);+ return getWorkingDirEffectivePath(config);};diff --git a/src/helpers/heteroSessionByWorkingDirectory.ts b/src/helpers/heteroSessionByWorkingDirectory.tsnew file mode 100644index 00000000000..2d230896435--- /dev/null+++ b/src/helpers/heteroSessionByWorkingDirectory.ts@@ -0,0 +1,30 @@+import type { ChatTopicMetadata } from '@lobechat/types';++export const getHeteroWorkingDirectoryKey = (workingDirectory: string | undefined): string =>+ workingDirectory ?? '';++export const getHeteroSessionIdForWorkingDirectory = (+ metadata: ChatTopicMetadata | undefined,+ workingDirectory: string | undefined,+): string | undefined => {+ const key = getHeteroWorkingDirectoryKey(workingDirectory);+ return metadata?.heteroSessionIdByWorkingDirectory?.[key];+};++export const setHeteroSessionIdForWorkingDirectory = (+ metadata: ChatTopicMetadata | undefined,+ workingDirectory: string | undefined,+ sessionId: string,+): Record<string, string> => ({+ ...metadata?.heteroSessionIdByWorkingDirectory,+ [getHeteroWorkingDirectoryKey(workingDirectory)]: sessionId,+});++export const removeHeteroSessionIdForWorkingDirectory = (+ metadata: ChatTopicMetadata | undefined,+ workingDirectory: string | undefined,+): Record<string, string> => {+ const next = { ...metadata?.heteroSessionIdByWorkingDirectory };+ delete next[getHeteroWorkingDirectoryKey(workingDirectory)];+ return next;+};diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex 822df74b605..5f5127cb8b4 100644--- a/src/hooks/useEffectiveWorkingDirectory.ts+++ b/src/hooks/useEffectiveWorkingDirectory.ts@@ -39,6 +39,9 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefinagentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);+ const topicWorkingDirectoryConfig = useChatStore(+ (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,+ );const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);const deviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(targetDeviceId));@@ -54,5 +57,6 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefinfallback,legacyAgentWorkingDirectory,topicWorkingDirectory,+ topicWorkingDirectoryConfig,});};diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.tsxnew file mode 100644index 00000000000..2daa34ff440--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.tsx@@ -0,0 +1,221 @@+import type { ChatTopicMetadata, DeviceGitPullRequestCiStatus } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import type { Clock } from 'lucide-react';+import {+ CircleAlert,+ CircleCheck,+ CircleSlash,+ CircleX,+ GitBranchIcon,+ GitForkIcon,+ LoaderCircle,+} from 'lucide-react';+import type { ReactNode } from 'react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';++import { getPullRequestState, getTopicMetaCard, PR_STATE_VISUAL } from './metaCardData';++const styles = createStaticStyles(({ css }) => ({+ card: css`+ display: flex;+ flex-direction: column;+ gap: 8px;++ width: 300px;+ max-width: calc(100vw - 48px);+ `,+ header: css`+ display: flex;+ gap: 12px;+ align-items: baseline;+ justify-content: space-between;+ `,+ headerTime: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ headerTitle: css`+ overflow: hidden;++ font-size: 14px;+ font-weight: 500;+ line-height: 20px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ row: css`+ display: flex;+ gap: 8px;+ align-items: center;++ min-width: 0;++ font-size: 13px;+ line-height: 18px;+ color: ${cssVar.colorTextSecondary};+ `,+ rowIcon: css`+ flex: none;+ color: ${cssVar.colorTextTertiary};+ `,+ rowText: css`+ overflow: hidden;+ min-width: 0;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ warnRow: css`+ align-items: flex-start;+ color: ${cssVar.colorWarning};+ `,+ warnIcon: css`+ flex: none;+ margin-block-start: 1px;+ color: ${cssVar.colorWarning};+ `,+ warnText: css`+ min-width: 0;+ line-height: 18px;+ white-space: normal;+ `,+}));++interface CiVisual {+ color: string;+ icon: typeof Clock;+ labelKey: string;+}++const getCiVisual = (status?: DeviceGitPullRequestCiStatus): CiVisual => {+ switch (status) {+ case 'success': {+ return { color: cssVar.colorSuccess, icon: CircleCheck, labelKey: 'metaCard.ci.success' };+ }+ case 'failure': {+ return { color: cssVar.colorError, icon: CircleX, labelKey: 'metaCard.ci.failure' };+ }+ case 'pending': {+ return { color: cssVar.colorWarning, icon: LoaderCircle, labelKey: 'metaCard.ci.pending' };+ }+ default: {+ return { color: cssVar.colorTextTertiary, icon: CircleSlash, labelKey: 'metaCard.ci.none' };+ }+ }+};++interface DetailRowProps {+ children: ReactNode;+ icon: typeof Clock;+ iconColor?: string;+ title?: string;+}++const DetailRow = memo<DetailRowProps>(({ icon, iconColor, title, children }) => (+ <div className={styles.row}>+ <Icon+ className={styles.rowIcon}+ icon={icon}+ size={15}+ style={iconColor ? { color: iconColor } : undefined}+ />+ <span className={styles.rowText} title={title}>+ {children}+ </span>+ </div>+));++DetailRow.displayName = 'DetailRow';++interface MetaHoverCardProps {+ metadata: ChatTopicMetadata | undefined;+ time?: ReactNode;+ title: string;+}++/**+ * Codex-style hover detail card for a topic row: surfaces the persisted repo /+ * branch / worktree / linked-PR / CI context on the right of the sidebar without+ * cluttering the row itself.+ */+const MetaHoverCard = memo<MetaHoverCardProps>(({ metadata, title, time }) => {+ const { t } = useTranslation('topic');+ const card = getTopicMetaCard(metadata);+ if (!card) return null;++ const { repoName, repoType, branch, detached, worktreeName, pullRequest } = card;+ const ci = pullRequest ? getCiVisual(pullRequest.ciStatus) : undefined;++ return (+ <div className={styles.card}>+ <div className={styles.header}>+ <span className={styles.headerTitle}>{title}</span>+ {time !== undefined && <span className={styles.headerTime}>{time}</span>}+ </div>++ {repoName && (+ <div className={styles.row}>+ <DirIcon repoType={repoType} size={15} />+ <span className={styles.rowText} title={repoName}>+ {repoName}+ </span>+ </div>+ )}++ {branch && (+ <DetailRow icon={GitBranchIcon} title={branch}>+ {detached ? t('metaCard.detached', { sha: branch }) : branch}+ </DetailRow>+ )}++ {worktreeName && (+ <DetailRow icon={GitForkIcon} title={worktreeName}>+ {worktreeName}+ </DetailRow>+ )}++ <div className={`${styles.row} ${styles.warnRow}`}>+ <Icon className={styles.warnIcon} icon={CircleAlert} size={15} />+ <span className={styles.warnText}>{t('metaCard.branchNote')}</span>+ </div>++ {pullRequest &&+ (() => {+ const prState = getPullRequestState(pullRequest);+ const prVisual = PR_STATE_VISUAL[prState];+ return (+ <div className={styles.row}>+ <Icon+ className={styles.rowIcon}+ icon={prVisual.icon}+ size={15}+ style={{ color: prVisual.color }}+ />+ <span className={styles.rowText} title={pullRequest.title}>+ <span style={{ color: prVisual.color, fontWeight: 500 }}>+ {t(prVisual.labelKey)}+ </span>+ {pullRequest.title ? ` Β· ${pullRequest.title}` : ''}+ <span style={{ color: cssVar.colorTextTertiary }}>{` #${pullRequest.number}`}</span>+ </span>+ </div>+ );+ })()}++ {ci && (+ <DetailRow icon={ci.icon} iconColor={ci.color}>+ {t(ci.labelKey as 'metaCard.ci.none')}+ </DetailRow>+ )}+ </div>+ );+});++MetaHoverCard.displayName = 'MetaHoverCard';++export default MetaHoverCard;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsxindex a217e4a5955..547b9ac598e 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx@@ -2,7 +2,7 @@* @vitest-environment happy-dom*/import { render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';+import type { CSSProperties, ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';import TopicItem from './index';@@ -15,10 +15,15 @@ vi.mock('@lobehub/ui', () => ({<div {...props}>{children}</div>),Icon: () => <div data-testid="topic-item-icon" />,+ Popover: ({ children }: { children?: ReactNode }) => <>{children}</>,Skeleton: {Button: (props: Record<string, unknown>) => <div {...props} />,},Tag: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Text: ({ children, style }: { children?: ReactNode; style?: CSSProperties }) => (+ <span style={style}>{children}</span>+ ),+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,}));vi.mock('antd-style', () => ({@@ -57,21 +62,27 @@ vi.mock('@/const/version', () => ({ isDesktop: false }));vi.mock('@/features/NavPanel/components/NavItem', () => ({default: ({active,+ description,extra,href,title,}: {active?: boolean;+ description?: ReactNode;extra?: ReactNode;href?: string;title?: ReactNode;}) => (<div data-active={String(active)} data-href={href} data-testid="nav-item">{title}+ {description}{extra}</div>),}));+vi.mock('@/features/ChatInput/ControlBar/DirIcon', () => ({+ default: () => <span data-testid="dir-icon" />,+}));vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({useActiveWorkspaceSlug: () => 'team',}));@@ -106,6 +117,15 @@ vi.mock('@/store/electron', () => ({vi.mock('../../hooks/useTopicNavigation', () => ({useTopicNavigation: () => useTopicNavigationMock(),}));+vi.mock('./MetaHoverCard', () => ({+ default: () => null,+}));+vi.mock('./metaCardData', () => ({+ PR_STATE_VISUAL: {},+ getPullRequestState: () => 'open',+ // Return undefined so TopicItem skips the hover Popover wrapper in tests.+ getTopicMetaCard: () => undefined,+}));vi.mock('./Actions', () => ({default: () => null,}));@@ -188,4 +208,31 @@ describe('TopicItem active state', () => {expect(screen.getByText('00:33')).toBeInTheDocument();});++ it('shows the topic worktree and branch from structured metadata', () => {+ useTopicNavigationMock.mockReturnValue({+ isInAgentSubRoute: false,+ isInTopicContextRoute: false,+ navigateToTopic: vi.fn(),+ routeTopicId: undefined,+ });++ render(+ <TopicItem+ showWorkingDirectory+ id="tpc_test"+ title="Topic"+ metadata={{+ workingDirectory: '/repo-fix',+ workingDirectoryConfig: {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },+ }}+ />,+ );++ expect(screen.getByText('repo/repo-fix Β· fix')).toBeInTheDocument();+ });});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 ebc37ca98f3..3c2918f07f0 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@@ -1,7 +1,11 @@import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';import type { ChatTopicMetadata, ChatTopicStatus } from '@lobechat/types';import { formatElapsedClockTime } from '@lobechat/utils';-import { Flexbox, Icon, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui';+import {+ getTopicMetadataWorkingDirectoryEffectivePath,+ getTopicMetadataWorkingDirectorySourcePath,+} from '@lobechat/utils/client/topic';+import { Flexbox, Icon, Popover, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui';import { createStaticStyles, cssVar, keyframes, useTheme } from 'antd-style';import { CheckCircle2, Hand, HashIcon, MessageSquareDashed, TriangleAlert } from 'lucide-react';import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';@@ -27,6 +31,8 @@ import { useTopicNavigation } from '../../hooks/useTopicNavigation';import ThreadList from '../../TopicListContent/ThreadList';import Actions from './Actions';import Editing from './Editing';+import { getPullRequestState, getTopicMetaCard, PR_STATE_VISUAL } from './metaCardData';+import MetaHoverCard from './MetaHoverCard';import { useTopicItemDropdownMenu } from './useDropdownMenu';const rippleAnim = keyframes`@@ -104,6 +110,24 @@ const cancelPendingSingleClick = () => {// a web github URL (".../owner/repo" β "repo").const getDirName = (path: string) => path.split('/').findLast(Boolean) || path;+const getWorkingDirectoryDisplay = (metadata: ChatTopicMetadata | undefined) => {+ const config = metadata?.workingDirectoryConfig;+ const workingDirectory = getTopicMetadataWorkingDirectoryEffectivePath(metadata);+ if (!workingDirectory) return;++ const branch = config?.git?.branch;+ const dirName = getDirName(workingDirectory);+ const sourcePath = getTopicMetadataWorkingDirectorySourcePath(metadata);+ const sourceName =+ sourcePath && sourcePath !== workingDirectory ? getDirName(sourcePath) : undefined;+ const pathLabel = sourceName && sourceName !== dirName ? `${sourceName}/${dirName}` : dirName;++ return {+ label: branch ? `${pathLabel} Β· ${branch}` : pathLabel,+ repoType: config?.repoType ?? (isDesktop ? undefined : 'github'),+ };+};+interface RunningElapsedTimeProps {agentId?: string;topicId: string;@@ -256,15 +280,15 @@ const TopicItem = memo<TopicItemProps>(// By-status grouping mixes topics from different projects, so surface each// topic's working directory as a muted second line. Data is already on the- // topic (`metadata.workingDirectory`) β no fetch. On web it's a github repo- // URL; on desktop a local path shown with a plain folder icon.- const workingDirectory = metadata?.workingDirectory;+ // topic (`metadata.workingDirectoryConfig` / `workingDirectory`) β no fetch.+ // On web it's a github repo URL; on desktop a local path.+ const workingDirectoryDisplay = getWorkingDirectoryDisplay(metadata);const workingDirectoryNode =- showWorkingDirectory && workingDirectory ? (+ showWorkingDirectory && workingDirectoryDisplay ? (<Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>- <DirIcon repoType={isDesktop ? undefined : 'github'} size={13} />- <Text ellipsis fontSize={12} style={{ color: cssVar.colorTextDescription }}>- {getDirName(workingDirectory)}+ <DirIcon repoType={workingDirectoryDisplay.repoType} size={12} />+ <Text ellipsis fontSize={11} style={{ color: cssVar.colorTextDescription }}>+ {workingDirectoryDisplay.label}</Text></Flexbox>) : undefined;@@ -329,72 +353,105 @@ const TopicItem = memo<TopicItemProps>();}- return (- <Flexbox data-testid="topic-item" style={{ position: 'relative' }}>- <NavItem- actions={<Actions dropdownMenu={dropdownMenu} />}- active={isTopicActive}- contextMenuItems={dropdownMenu}- description={workingDirectoryNode}- disabled={editing}- extra={<RunningElapsedTime agentId={activeAgentId} topicId={id} />}- href={href}- slots={{ titlePrefix: draftPrefix }}- title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}- titleColor={cssVar.colorText}- icon={(() => {- if (isWaitingForHuman) {- return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorInfo }} />;- }- if (shouldShowRunningIcon) {- return (- <RingLoadingIcon- ringColor={loadingRingColor}- size={14}- style={{ color: cssVar.colorWarning }}- />- );- }- if (isFailed) {- return (- <Tooltip title={t('failedStatusTip')}>- <Icon icon={TriangleAlert} size={'small'} style={{ color: cssVar.colorError }} />- </Tooltip>- );- }- if (isCompleted) {- return (- <Icon- icon={CheckCircle2}- size={'small'}- style={{ color: cssVar.colorTextDescription }}- />- );- }- if (hasUnread) return unreadIcon;- if (metadata?.bot?.platform) {- const ProviderIcon = getPlatformIcon(metadata.bot!.platform);- if (ProviderIcon) {- return <ProviderIcon color={cssVar.colorTextDescription} size={16} />;- }- }+ // Codex-style hover detail card: when the topic carries git context, hovering+ // the row reveals a card on the right with repo / branch / worktree / PR / CI β+ // keeping the row itself clean.+ const metaCard = getTopicMetaCard(metadata);++ const navItem = (+ <NavItem+ actions={<Actions dropdownMenu={dropdownMenu} />}+ active={isTopicActive}+ contextMenuItems={dropdownMenu}+ description={workingDirectoryNode}+ disabled={editing}+ extra={<RunningElapsedTime agentId={activeAgentId} topicId={id} />}+ href={href}+ slots={{ titlePrefix: draftPrefix }}+ title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}+ titleColor={cssVar.colorText}+ icon={(() => {+ if (isWaitingForHuman) {+ return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorInfo }} />;+ }+ if (shouldShowRunningIcon) {+ return (+ <RingLoadingIcon+ ringColor={loadingRingColor}+ size={14}+ style={{ color: cssVar.colorWarning }}+ />+ );+ }+ if (isFailed) {+ return (+ <Tooltip title={t('failedStatusTip')}>+ <Icon icon={TriangleAlert} size={'small'} style={{ color: cssVar.colorError }} />+ </Tooltip>+ );+ }+ // GitHub PR state marker (open=green, merged=purple, closed=red),+ // like Codex. Sits below the attention/active states but above the+ // idle default so an idle topic surfaces its linked PR at a glance.+ if (metaCard?.pullRequest) {+ const prVisual = PR_STATE_VISUAL[getPullRequestState(metaCard.pullRequest)];+ return (+ <Tooltip title={t(prVisual.labelKey)}>+ <Icon icon={prVisual.icon} size={'small'} style={{ color: prVisual.color }} />+ </Tooltip>+ );+ }+ if (isCompleted) {return (<Icon- icon={HashIcon}+ icon={CheckCircle2}size={'small'}- style={{- color: cssVar.colorTextDescription,- // Heterogeneous agents (Claude Code, Codex, β¦) have no chat-style- // topic semantics, so suppress the `#` glyph while keeping its- // box so the title stays aligned with sibling rows.- visibility: isHeterogeneousAgent ? 'hidden' : undefined,- }}+ style={{ color: cssVar.colorTextDescription }}/>);- })()}- onClick={handleClick}- onDoubleClick={() => void handleDoubleClick()}- />+ }+ if (hasUnread) return unreadIcon;+ if (metadata?.bot?.platform) {+ const ProviderIcon = getPlatformIcon(metadata.bot!.platform);+ if (ProviderIcon) {+ return <ProviderIcon color={cssVar.colorTextDescription} size={16} />;+ }+ }+ return (+ <Icon+ icon={HashIcon}+ size={'small'}+ style={{+ color: cssVar.colorTextDescription,+ // Heterogeneous agents (Claude Code, Codex, β¦) have no chat-style+ // topic semantics, so suppress the `#` glyph while keeping its+ // box so the title stays aligned with sibling rows.+ visibility: isHeterogeneousAgent ? 'hidden' : undefined,+ }}+ />+ );+ })()}+ onClick={handleClick}+ onDoubleClick={() => void handleDoubleClick()}+ />+ );++ return (+ <Flexbox data-testid="topic-item" style={{ position: 'relative' }}>+ {metaCard ? (+ <Popover+ arrow={false}+ content={<MetaHoverCard metadata={metadata} title={title} />}+ mouseEnterDelay={0.4}+ placement={'right'}+ styles={{ content: { padding: 12 } }}+ trigger={'hover'}+ >+ <div>{navItem}</div>+ </Popover>+ ) : (+ navItem+ )}<Editing id={id} title={title} toggleEditing={toggleEditing} />{shouldShowThreadList && (<Suspensediff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/metaCardData.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/metaCardData.tsnew file mode 100644index 00000000000..97160a60b34--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/metaCardData.ts@@ -0,0 +1,66 @@+import type { ChatTopicMetadata, DeviceGitLinkedPullRequest } from '@lobechat/types';+import {+ getTopicMetadataWorkingDirectoryEffectivePath,+ getTopicMetadataWorkingDirectorySourcePath,+} from '@lobechat/utils/client/topic';+import { cssVar } from 'antd-style';+import type { LucideIcon } from 'lucide-react';+import { GitMerge, GitPullRequestArrow, GitPullRequestClosed } from 'lucide-react';++import { isDesktop } from '@/const/version';++const getDirName = (path: string) =>+ path.replaceAll('\\', '/').split('/').findLast(Boolean) || path;++export type PullRequestState = 'open' | 'merged' | 'closed';++/**+ * Resolve a GitHub PR's lifecycle state. GitHub's `state` is only open|closed;+ * "merged" is a closed PR carrying a `mergedAt`, so check that first.+ */+export const getPullRequestState = (pr: DeviceGitLinkedPullRequest): PullRequestState => {+ if (pr.mergedAt || pr.state === 'merged') return 'merged';+ if (pr.state === 'closed') return 'closed';+ return 'open';+};++// GitHub merged-PR purple. Kept as a constant since antd's token set has no+// semantic "merged" color; the green (success) / red (error) come from tokens.+const MERGED_PURPLE = '#8957e5';++export interface PullRequestStateVisual {+ color: string;+ icon: LucideIcon;+ labelKey: 'metaCard.pr.closed' | 'metaCard.pr.merged' | 'metaCard.pr.open';+}++export const PR_STATE_VISUAL: Record<PullRequestState, PullRequestStateVisual> = {+ closed: { color: cssVar.colorError, icon: GitPullRequestClosed, labelKey: 'metaCard.pr.closed' },+ merged: { color: MERGED_PURPLE, icon: GitMerge, labelKey: 'metaCard.pr.merged' },+ open: { color: cssVar.colorSuccess, icon: GitPullRequestArrow, labelKey: 'metaCard.pr.open' },+};++/**+ * Read the git / worktree / linked-PR context off a topic's persisted+ * `workingDirectoryConfig`. Returns `undefined` when the topic carries no git+ * context, so the caller can skip the hover card entirely (no probe).+ */+export const getTopicMetaCard = (metadata: ChatTopicMetadata | undefined) => {+ const config = metadata?.workingDirectoryConfig;+ const git = config?.git;+ if (!git) return undefined;++ const sourcePath = getTopicMetadataWorkingDirectorySourcePath(metadata);+ const effectivePath = getTopicMetadataWorkingDirectoryEffectivePath(metadata);+ const isWorktree =+ !!git.isWorktree || (!!git.activeWorktree && git.activeWorktree !== sourcePath);++ return {+ branch: git.branch,+ detached: git.detached,+ pullRequest: git.github?.pullRequest ?? undefined,+ repoName: sourcePath ? getDirName(sourcePath) : undefined,+ repoType: config.repoType ?? (isDesktop ? undefined : ('github' as const)),+ worktreeName: isWorktree && effectivePath ? getDirName(effectivePath) : undefined,+ };+};diff --git a/src/services/git.ts b/src/services/git.tsindex 87d6b7fec89..2458d8f148f 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -11,6 +11,7 @@ import type {DeviceGitCheckoutResult,DeviceGitDeleteBranchResult,DeviceGitLinkedPullRequest,+ DeviceGitLinkedPullRequestLookupStatus,DeviceGitRemoveWorktreeResult,DeviceGitRenameBranchResult,DeviceGitSyncResult,@@ -32,6 +33,7 @@ export interface GitLinkedPRSummary {extraCount?: number;ghMissing?: boolean;pullRequest?: DeviceGitLinkedPullRequest | null;+ pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;}/**@@ -186,6 +188,7 @@ class GitService {extraCount: pr.extraCount,ghMissing: pr.status === 'gh-missing',pullRequest: pr.pullRequest,+ pullRequestStatus: pr.status,};}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 81ac091b500..437fdfe2ddb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -623,6 +623,7 @@ describe('ConversationLifecycle actions', () => {metadata: {repos: [selectedRepo],workingDirectory: selectedRepo,+ workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },},}),);@@ -632,6 +633,7 @@ describe('ConversationLifecycle actions', () => {metadata: {repos: [selectedRepo],workingDirectory: selectedRepo,+ workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },},}),}),diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 9c8ab490c27..09b1780b0c5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -738,7 +738,11 @@ describe('GatewayActionImpl', () => {message: 'Create a project topic',optimisticTopic: {id: 'tmp-topic',- metadata: { repos: [selectedRepo], workingDirectory: selectedRepo },+ metadata: {+ repos: [selectedRepo],+ workingDirectory: selectedRepo,+ workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },+ },title: 'Create a project topic',},});@@ -749,7 +753,11 @@ describe('GatewayActionImpl', () => {nextId: 'topic-1',previousId: 'tmp-topic',value: {- metadata: { repos: [selectedRepo], workingDirectory: selectedRepo },+ metadata: {+ repos: [selectedRepo],+ workingDirectory: selectedRepo,+ workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },+ },sessionId: 'agent-1',title: 'Create a project topic',},diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.tsindex 54704aa2b12..7393227dab7 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heteroResume.test.ts@@ -4,6 +4,22 @@ import { describe, expect, it } from 'vitest';import { resolveHeteroResume } from '../transports/hetero/heteroResume';describe('resolveHeteroResume', () => {+ it('resumes from the session scoped to the current cwd', () => {+ const metadata: ChatTopicMetadata = {+ heteroSessionId: 'session-latest-other-cwd',+ heteroSessionIdByWorkingDirectory: {+ '/Users/me/projA': 'session-proj-a',+ '/Users/me/projB': 'session-proj-b',+ },+ workingDirectory: '/Users/me/projB',+ };++ expect(resolveHeteroResume(metadata, '/Users/me/projA')).toEqual({+ cwdChanged: false,+ resumeSessionId: 'session-proj-a',+ });+ });+it('resumes when saved cwd matches current cwd', () => {const metadata: ChatTopicMetadata = {heteroSessionId: 'session-123',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 104de5f72f3..26cfa79af36 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -15,6 +15,7 @@ import type * as LobeChatConst from '@lobechat/const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';import { createAdapter } from '@lobechat/heterogeneous-agents';+import type { ChatTopicMetadata } from '@lobechat/types';import { ThreadStatus } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -23,6 +24,7 @@ import { useChatStore } from '@/store/chat/store';import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';import type { HeterogeneousAgentExecutorParams } from '../transports/hetero/heterogeneousAgentExecutor';import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';+import { resolveHeteroResume } from '../transports/hetero/heteroResume';// βββ Mocks βββ@@ -1360,7 +1362,9 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {heteroSessionId: undefined,+ heteroSessionIdByWorkingDirectory: {},workingDirectory: '/Users/me/repo',+ workingDirectoryConfig: { path: '/Users/me/repo' },});ipc.emitRawLine('ipc-sess-2', { thread_id: 'thread_new_456', type: 'thread.started' });@@ -1373,7 +1377,105 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {heteroSessionId: 'thread_new_456',+ heteroSessionIdByWorkingDirectory: {+ '/Users/me/repo': 'thread_new_456',+ },workingDirectory: '/Users/me/repo',+ workingDirectoryConfig: { path: '/Users/me/repo' },+ });+ });++ // ββββββββββββββββββββββββββββββββββββββββββββββββββββ+ // Per-cwd session id lifecycle β executor keying primitive+ // ββββββββββββββββββββββββββββββββββββββββββββββββββββ+ it('keeps a per-cwd session id across cwds and resumes when a cwd recurs', async () => {+ // The executor keys sessions by the cwd it is handed (CC stores sessions+ // per-cwd). Runs one topic across cwd A β cwd B β back to A, driving the+ // REAL executor completion write + REAL resolveHeteroResume with real+ // evolving metadata; only the CLI/IPC is stubbed. Asserts a cwd change+ // never loses or misroutes a prior session id, and a recurring cwd resumes+ // its own session. (A worktree switch keeps the source cwd, so it stays on+ // one session β this guards the primitive that also backs multi-repo runs.)+ const cwdA = '/Users/me/repo';+ const cwdB = '/Users/me/other-repo';++ // A single topic whose metadata evolves across runs, like the real store:+ // updateTopicMetadata shallow-merges and getTopicMetadataById reads it back.+ let topicMeta: ChatTopicMetadata = {};+ const store = createMockStore({+ topicDataMap: { 'agent-1__main': { items: [{ id: 'topic-1', metadata: topicMeta }] } },+ });+ store.updateTopicMetadata = vi.fn(async (_id: string, patch: Partial<ChatTopicMetadata>) => {+ topicMeta = { ...topicMeta, ...patch };+ store.topicDataMap['agent-1__main'].items[0].metadata = topicMeta;+ });+ const get = vi.fn(() => store);++ // Drive one full CC turn: spawn β init(session id) + result β complete.+ // Returns the resumeSessionId the CLI was actually spawned with this turn.+ const runTurn = async (+ workingDirectory: string,+ resumeSessionId: string | undefined,+ agentSessionId: string,+ ): Promise<string | undefined> => {+ let resolveSendPrompt: () => void = () => {};+ mockSendPrompt.mockReturnValue(new Promise<void>((r) => (resolveSendPrompt = r)));+ mockStartSession.mockImplementation(async (params: any) => {+ ipc.setAgentType('ipc-sess-1', params.agentType ?? 'claude-code');+ return { sessionId: 'ipc-sess-1' };+ });++ const spawnedAt = mockStartSession.mock.calls.length;+ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ resumeSessionId,+ workingDirectory,+ });+ await flush();+ ipc.emitRawLine('ipc-sess-1', ccInit(agentSessionId));+ ipc.emitRawLine('ipc-sess-1', ccResult());+ ipc.emitComplete('ipc-sess-1');+ await flush();+ resolveSendPrompt();+ await flush();+ await executorPromise;+ await flush();+ return mockStartSession.mock.calls[spawnedAt]?.[0]?.resumeSessionId;+ };++ // ββ Turn 1: worktree A, no prior session β fresh spawn ββ+ const resumeForA1 = resolveHeteroResume(topicMeta, cwdA).resumeSessionId;+ expect(resumeForA1).toBeUndefined();+ const spawnedA1 = await runTurn(cwdA, resumeForA1, 'cc-session-A');+ expect(spawnedA1).toBeUndefined(); // no --resume on a fresh cwd+ expect(topicMeta.heteroSessionIdByWorkingDirectory).toEqual({ [cwdA]: 'cc-session-A' });+ expect(topicMeta.workingDirectory).toBe(cwdA);++ // ββ Switch to worktree B and send: must NOT resume A's session in B ββ+ const decisionB = resolveHeteroResume(topicMeta, cwdB);+ expect(decisionB).toEqual({+ cwdChanged: true,+ reason: 'cwd_changed',+ resumeSessionId: undefined,+ });+ const spawnedB = await runTurn(cwdB, decisionB.resumeSessionId, 'cc-session-B');+ expect(spawnedB).toBeUndefined(); // fresh session in B, not A's id+ // A's session id survives; B's is added alongside.+ expect(topicMeta.heteroSessionIdByWorkingDirectory).toEqual({+ [cwdA]: 'cc-session-A',+ [cwdB]: 'cc-session-B',+ });+ expect(topicMeta.workingDirectory).toBe(cwdB);++ // ββ Switch back to worktree A and send: A's session is found + resumed ββ+ const decisionA2 = resolveHeteroResume(topicMeta, cwdA);+ expect(decisionA2).toEqual({ cwdChanged: false, resumeSessionId: 'cc-session-A' });+ const spawnedA2 = await runTurn(cwdA, decisionA2.resumeSessionId, 'cc-session-A');+ expect(spawnedA2).toBe('cc-session-A'); // CLI actually --resumes A's session+ // Nothing lost by the detour: both worktrees keep their own session id.+ expect(topicMeta.heteroSessionIdByWorkingDirectory).toEqual({+ [cwdA]: 'cc-session-A',+ [cwdB]: 'cc-session-B',});});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex d6a35030a22..d7e0702da35 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -20,11 +20,13 @@ import type {SendMessageServerResponse,UIChatMessage,} from '@lobechat/types';+import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';import { nanoid } from '@lobechat/utils';import { TRPCClientError } from '@trpc/client';import { t } from 'i18next';import { message as antdMessage } from '@/components/AntdStaticMethods';+import { resolveAgentWorkingDirectoryConfig } from '@/helpers/agentWorkingDirectory';import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';@@ -565,14 +567,38 @@ export class ConversationLifecycleActionImpl {? topicSelectors.getTopicById(operationContext.topicId)(this.#get()): undefined;const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;+ const agentState = getAgentStoreState();const agentWorkingDirectory =runtimeType === 'hetero' && heterogeneousProvider- ? agentByIdSelectors.getAgentWorkingDirectoryById(- agentId,+ ? agentByIdSelectors.getAgentWorkingDirectoryById(agentId, currentDeviceId)(agentState)+ : undefined;+ const agencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(agentState);+ const agentWorkingDirectoryConfig =+ runtimeType === 'hetero' && heterogeneousProvider+ ? resolveAgentWorkingDirectoryConfig({+ agencyConfig,currentDeviceId,- )(getAgentStoreState())+ fallback: agentWorkingDirectory,+ legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],+ }): undefined;- const workingDirectory = existingTopic?.metadata?.workingDirectory || agentWorkingDirectory;+ // Heterogeneous CLI agents (Claude Code, Codex, β¦) store sessions per-cwd+ // (`~/.claude/projects/<encoded-cwd>/`). Anchor their session cwd to the+ // SOURCE repo, NOT the selected worktree, so switching worktree keeps cwd ++ // sessionId consistent and never drops the conversation context. The active+ // worktree lives only in `workingDirectoryConfig.git.activeWorktree` as a+ // record. Non-hetero runtimes keep the effective (worktree) path.+ const resolveWorkingDirPath =+ runtimeType === 'hetero' ? getWorkingDirSourcePath : getWorkingDirEffectivePath;+ const workingDirectory =+ resolveWorkingDirPath(existingTopic?.metadata?.workingDirectoryConfig) ??+ existingTopic?.metadata?.workingDirectory ??+ agentWorkingDirectory;+ const workingDirectoryConfig =+ existingTopic?.metadata?.workingDirectoryConfig ??+ (existingTopic?.metadata?.workingDirectory+ ? { path: existingTopic.metadata.workingDirectory }+ : agentWorkingDirectoryConfig);const pendingTopicRepos =runtimeType === 'gateway' && !operationContext.topicId && operationContext.agentId? getPendingTopicRepos(operationContext.agentId)@@ -581,9 +607,16 @@ export class ConversationLifecycleActionImpl {// until the server topic replaces `tmp_topic_*`.const optimisticTopicMetadata: ChatTopicMetadata | undefined =pendingTopicRepos.length > 0- ? { repos: pendingTopicRepos, workingDirectory: pendingTopicRepos[0] }+ ? {+ repos: pendingTopicRepos,+ workingDirectory: pendingTopicRepos[0],+ workingDirectoryConfig: { path: pendingTopicRepos[0], repoType: 'github' },+ }: workingDirectory- ? { workingDirectory }+ ? {+ workingDirectory,+ ...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),+ }: undefined;const optimisticTopic: OptimisticTopicPlaceholder | undefined =@@ -715,7 +748,12 @@ export class ConversationLifecycleActionImpl {newAssistantMessage: { provider: heterogeneousProvider.type },newTopic: !operationContext.topicId? {- metadata: workingDirectory ? { workingDirectory } : undefined,+ metadata: workingDirectory+ ? {+ workingDirectory,+ ...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),+ }+ : undefined,title: newTopicTitle,topicMessageIds: messages.map((m) => m.id),}@@ -877,6 +915,7 @@ export class ConversationLifecycleActionImpl {operationId: heteroOpId,resumeSessionId,workingDirectory,+ workingDirectoryConfig,});} catch (e) {console.error('[HeterogeneousAgent] Execution failed:', e);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex cd99697c391..1bfa7f09c7c 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -435,7 +435,11 @@ export class GatewayActionImpl {isCreateNewTopic && context.agentId ? getPendingTopicRepos(context.agentId) : [];const initialTopicMetadata =pendingRepos.length > 0- ? { repos: pendingRepos, workingDirectory: pendingRepos[0] }+ ? {+ repos: pendingRepos,+ workingDirectory: pendingRepos[0],+ workingDirectoryConfig: { path: pendingRepos[0], repoType: 'github' as const },+ }: undefined;// Honour user-initiated cancel during phase-1 init: while we await thediff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.tsindex 69c815812bb..294740d6991 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts@@ -1,5 +1,7 @@import type { ChatTopicMetadata } from '@lobechat/types';+import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';+export type HeteroResumeBlockedReason = 'cwd_changed' | 'missing_bound_cwd';export interface HeteroResumeDecision {@@ -17,11 +19,12 @@ export interface HeteroResumeDecision {* per-cwd under `~/.claude/projects/<encoded-cwd>/`, so resuming from a* different cwd blows up with "No conversation found with session ID".*- * Strict rule: only resume when the topic's bound `workingDirectory` is- * present AND equals the current cwd. Legacy topics (sessionId present,- * workingDirectory missing) are reset β we have no way to verify them,- * and silently passing a stale id is exactly what caused the original- * failure.+ * New topics keep a per-cwd session map so switching between worktrees can+ * restore that worktree's own CLI context. Legacy single-session topics still+ * resume only when the topic's bound `workingDirectory` is present AND equals+ * the current cwd. Legacy topics with no workingDirectory are reset β we have+ * no way to verify them, and silently passing a stale id is exactly what caused+ * the original failure.*/export const resolveHeteroResume = (metadata: ChatTopicMetadata | undefined,@@ -30,6 +33,14 @@ export const resolveHeteroResume = (const savedSessionId = metadata?.heteroSessionId;const savedCwd = metadata?.workingDirectory;const cwd = currentWorkingDirectory ?? '';+ const scopedSessionId = getHeteroSessionIdForWorkingDirectory(metadata, cwd);++ if (scopedSessionId) {+ return {+ cwdChanged: false,+ resumeSessionId: scopedSessionId,+ };+ }if (!savedSessionId) {return {diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 325567afe2a..e50c05515f6 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -20,11 +20,13 @@ import {import type {ChatMessageError,ChatToolPayload,+ ChatTopicMetadata,ChatTopicStatus,ConversationContext,HeterogeneousProviderConfig,MessageMapScope,UIChatMessage,+ WorkingDirConfig,} from '@lobechat/types';import {AgentRuntimeErrorType,@@ -36,6 +38,10 @@ import { createNanoId } from '@lobechat/utils';import { t } from 'i18next';import { message as antdMessage } from '@/components/AntdStaticMethods';+import {+ removeHeteroSessionIdForWorkingDirectory,+ setHeteroSessionIdForWorkingDirectory,+} from '@/helpers/heteroSessionByWorkingDirectory';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { messageService } from '@/services/message';import { threadService } from '@/services/thread';@@ -105,8 +111,7 @@ const maybeClassifyCliAuthRequiredError = (const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageError): boolean => {const errorBody = error.body as- | (HeterogeneousAgentSessionError & { clearEchoedContent?: boolean })- | undefined;+ (HeterogeneousAgentSessionError & { clearEchoedContent?: boolean }) | undefined;if (!errorBody?.clearEchoedContent &&errorBody?.code !== HeterogeneousAgentSessionErrorCode.AuthRequired@@ -201,8 +206,21 @@ export interface HeterogeneousAgentExecutorParams {/** CC session ID from previous execution in this topic (for --resume) */resumeSessionId?: string;workingDirectory?: string;+ workingDirectoryConfig?: WorkingDirConfig;}+const getTopicMetadataById = (+ store: ChatStore,+ topicId: string | undefined,+): ChatTopicMetadata | undefined => {+ if (!topicId) return;++ for (const topicData of Object.values(store.topicDataMap ?? {})) {+ const topic = topicData?.items?.find((item) => item.id === topicId);+ if (topic) return topic.metadata;+ }+};+/*** Map heterogeneousProvider.command to adapter type key.*/@@ -351,6 +369,7 @@ export const executeHeterogeneousAgent = async (operationId,resumeSessionId,workingDirectory,+ workingDirectoryConfig,} = params;const adapterType = resolveAdapterType(heterogeneousProvider);@@ -536,6 +555,17 @@ export const executeHeterogeneousAgent = async (const abortSignal = get().operations?.[operationId]?.abortController?.signal;const isAborted = () => !!abortSignal?.aborted;const updateTopicMetadata = get().updateTopicMetadata;+ const getPersistedWorkingDirectoryConfig = (+ topicMetadata: ChatTopicMetadata | undefined,+ ): WorkingDirConfig | undefined =>+ // Prefer the topic's CURRENT config: while the CLI runs, GitStatus may have+ // persisted richer branch/PR/CI (`git.github`) onto it. Falling back to the+ // run-start captured config would drop that enrichment on the completion+ // write until a status component re-probes. Captured config is only the+ // fallback for a topic that carries none yet.+ topicMetadata?.workingDirectoryConfig ??+ workingDirectoryConfig ??+ (workingDirectory === undefined ? undefined : { path: workingDirectory });const hasStreamedState = () =>sawStreamedEvent ||!!mainState.accContent ||@@ -546,9 +576,15 @@ export const executeHeterogeneousAgent = async (const clearStaleResumeMetadata = async () => {if (!context.topicId || !updateTopicMetadata) return;+ const topicMetadata = getTopicMetadataById(get(), context.topicId);await updateTopicMetadata(context.topicId, {heteroSessionId: undefined,+ heteroSessionIdByWorkingDirectory: removeHeteroSessionIdForWorkingDirectory(+ topicMetadata,+ workingDirectory,+ ),workingDirectory: workingDirectory ?? '',+ workingDirectoryConfig: getPersistedWorkingDirectoryConfig(topicMetadata),});};const writeTopicStatus = (status: ChatTopicStatus): void => {@@ -1501,6 +1537,7 @@ export const executeHeterogeneousAgent = async (.getSessionInfo(agentSessionId).catch(() => undefined);if (sessionInfo?.agentSessionId && context.topicId) {+ const topicMetadata = getTopicMetadataById(get(), context.topicId);// Best-effort: a rejected// metadata save must NOT throw past the queue drain below β guarding the// await here keeps the resume-id persistence from blocking the follow-up@@ -1508,7 +1545,13 @@ export const executeHeterogeneousAgent = async (// `resolveHeteroResume` reads the just-finished session id.await updateTopicMetadata?.(context.topicId, {heteroSessionId: sessionInfo.agentSessionId,+ heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(+ topicMetadata,+ workingDirectory,+ sessionInfo.agentSessionId,+ ),workingDirectory: workingDirectory ?? '',+ workingDirectoryConfig: getPersistedWorkingDirectoryConfig(topicMetadata),}).catch((err) =>console.error('[HeterogeneousAgent] Failed to persist resume session id:', err),);diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 5e87bc989c8..a85914978a4 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -1,4 +1,5 @@import { isDesktop } from '@lobechat/const';+import { getWorkingDirEffectivePath } from '@lobechat/types';import { t } from 'i18next';import {@@ -88,11 +89,20 @@ const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>const activeTopic = currentActiveTopic(s);if (!activeTopic) return;- if (isDesktop) return activeTopic.metadata?.workingDirectory;+ if (isDesktop) {+ return (+ getWorkingDirEffectivePath(activeTopic.metadata?.workingDirectoryConfig) ??+ activeTopic.metadata?.workingDirectory+ );+ }// Web: return primary repo from repos list, or workingDirectory if set directlyconst meta = activeTopic.metadata;- return meta?.repos?.[0] ?? meta?.workingDirectory;+ return (+ meta?.repos?.[0] ??+ getWorkingDirEffectivePath(meta?.workingDirectoryConfig) ??+ meta?.workingDirectory+ );};const isCreatingTopic = (s: ChatStoreState) => s.creatingTopic;diff --git a/src/store/device/deviceCwd.test.ts b/src/store/device/deviceCwd.test.tsindex 02b7adcdcb5..c8a5e3607da 100644--- a/src/store/device/deviceCwd.test.ts+++ b/src/store/device/deviceCwd.test.ts@@ -33,12 +33,20 @@ describe('nextWorkingDirs', () => {it('stores active worktree metadata on the source entry without duplicating the source', () => {const result = nextWorkingDirs(- { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },+ {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },[entry('/repo', 'git'), entry('/other')],);expect(result).toEqual([- { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },+ {+ git: { activeWorktree: '/repo-fix', branch: 'fix', isWorktree: true },+ path: '/repo',+ repoType: 'git',+ },entry('/other'),]);});