🤯 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(coding): pick a branch for a new topic and switch or fork a worktree when sending (#23175)
Bryan2e51f205813a
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.tsindex 5f378a77019..fcc2b589125 100644--- a/apps/desktop/src/main/controllers/GitCtr.ts+++ b/apps/desktop/src/main/controllers/GitCtr.ts@@ -155,9 +155,13 @@ export default class GitController extends ControllerModule {}@IpcMethod()- async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {+ async getGitAheadBehind(+ payload: string | { branch?: string; path: string },+ ): Promise<GitAheadBehind> {const { getGitAheadBehind: computeGitAheadBehind } = await loadGit();- return computeGitAheadBehind(dirPath);+ // Older renderers send the bare path; newer ones may name a branch.+ if (typeof payload === 'string') return computeGitAheadBehind(payload);+ return computeGitAheadBehind(payload.path, { branch: payload.branch });}@IpcMethod()@@ -165,6 +169,7 @@ export default class GitController extends ControllerModule {branch: string;create?: boolean;path: string;+ startPoint?: string;}): Promise<GitCheckoutResult> {const { checkoutGitBranch: runCheckoutGitBranch } = await loadGit();return runCheckoutGitBranch(payload);@@ -199,6 +204,7 @@ export default class GitController extends ControllerModule {async addGitWorktree(payload: {branch: string;path: string;+ startPoint?: string;worktreePath: string;}): Promise<GitAddWorktreeResult> {const { addGitWorktree: runAddGitWorktree } = await loadGit();@@ -206,13 +212,13 @@ export default class GitController extends ControllerModule {}@IpcMethod()- async pullGitBranch(payload: { path: string }): Promise<GitPullResult> {+ async pullGitBranch(payload: { branch?: string; path: string }): Promise<GitPullResult> {const { pullGitBranch: runPullGitBranch } = await loadGit();return runPullGitBranch(payload);}@IpcMethod()- async pushGitBranch(payload: { path: string }): Promise<GitPushResult> {+ async pushGitBranch(payload: { branch?: string; path: string }): Promise<GitPushResult> {const { pushGitBranch: runPushGitBranch } = await loadGit();return runPushGitBranch(payload);}diff --git a/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.ts b/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.tsindex f6b859de08c..41ccaf598e6 100644--- a/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.ts+++ b/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { WORKTREE_BRANCH_PREFIX } from '@lobechat/const';import { deriveWorktreePath } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -92,4 +93,32 @@ describe('device.addGitWorktree', () => {expect(mocks.addGitWorktree.mock.calls[0][0].worktreePath).toBe('/code/lobehub-feat-x');});++ it('forwards the start point to the device', async () => {+ await caller.addGitWorktree({+ branch: 'feat/x',+ deviceId: 'device',+ path: '/code/lobehub',+ startPoint: 'canary',+ });++ expect(mocks.addGitWorktree.mock.calls[0][0]).toMatchObject({ startPoint: 'canary' });+ });++ // The flag only picks between two server-derived folders: the namespace that+ // is dropped is the server's constant, never a client string.+ it('drops the app branch namespace from the folder only when asked', async () => {+ const branch = `${WORKTREE_BRANCH_PREFIX}/202611170300-quiet-hill`;+ await caller.addGitWorktree({+ branch,+ deviceId: 'device',+ path: '/code/lobehub',+ stripBranchPrefix: true,+ });+ await caller.addGitWorktree({ branch, deviceId: 'device', path: '/code/lobehub' });++ const [stripped, plain] = mocks.addGitWorktree.mock.calls.map((call) => call[0].worktreePath);+ expect(stripped).toMatch(/\/lobehub-[\da-f]{8}\/202611170300-quiet-hill$/);+ expect(plain).toBe(deriveWorktreePath('/code/lobehub', branch, { homeDir: '/Users/me' }));+ });});diff --git a/apps/server/src/routers/lambda/__tests__/deviceRunningTopics.test.ts b/apps/server/src/routers/lambda/__tests__/deviceRunningTopics.test.tsnew file mode 100644index 00000000000..bd2c6562bfb--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceRunningTopics.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({ countInFlightInDirectory: vi.fn(), topicModelArgs: vi.fn() }));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));+vi.mock('@/database/models/topic', () => ({+ TopicModel: class {+ constructor(...args: unknown[]) {+ mocks.topicModelArgs(...args);+ }+ countInFlightInDirectory = mocks.countInFlightInDirectory;+ },+}));++describe('device.countRunningTopicsInDirectory', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.countInFlightInDirectory.mockResolvedValue(2);+ });++ it('returns only the count for the directory on that device', async () => {+ const caller = deviceRouter.createCaller({ userId: 'user' } as never);++ await expect(+ caller.countRunningTopicsInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).resolves.toBe(2);+ expect(mocks.countInFlightInDirectory).toHaveBeenCalledWith({+ deviceId: 'dev-1',+ path: '/code/lobehub',+ });+ // Personal mode: scoped to the caller, no workspace.+ expect(mocks.topicModelArgs).toHaveBeenCalledWith(expect.anything(), 'user', undefined);+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/user.worktreeMode.test.ts b/apps/server/src/routers/lambda/__tests__/user.worktreeMode.test.tsnew file mode 100644index 00000000000..3ab15285910--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/user.worktreeMode.test.ts@@ -0,0 +1,37 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { UserModel } from '@/database/models/user';++import { userRouter } from '../user';++vi.mock('@/database/models/user');+vi.mock('@/database/server', () => ({ serverDB: {} }));+vi.mock('@/server/modules/KeyVaultsEncrypt');+vi.mock('@/server/modules/S3');++describe('user.setWorktreeModeDir', () => {+ const ctx = { userId: 'user-1' } as any;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('stores one directory switch through the locked model write', async () => {+ const setWorktreeModeDir = vi.fn().mockResolvedValue(['dev::/code/a']);+ vi.mocked(UserModel).mockImplementation(function () {+ return { setWorktreeModeDir } as any;+ });++ await expect(+ userRouter.createCaller(ctx).setWorktreeModeDir({ enabled: true, key: 'dev::/code/a' }),+ ).resolves.toEqual(['dev::/code/a']);+ expect(setWorktreeModeDir).toHaveBeenCalledWith('dev::/code/a', true);+ });++ it('rejects an empty key', async () => {+ await expect(+ userRouter.createCaller(ctx).setWorktreeModeDir({ enabled: false, key: '' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts b/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.tsindex 264fe7a7d43..fcfe95faeaa 100644--- a/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts+++ b/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts@@ -10,9 +10,11 @@ vi.mock('@/database/core/db-adaptor', () => ({}));const mockUpdatePreference = vi.fn();+const mockSetWorktreeModeDir = vi.fn();vi.mock('@/database/models/workspaceUserSettings', () => ({WorkspaceUserSettingsModel: vi.fn(function () {return {+ setWorktreeModeDir: mockSetWorktreeModeDir,updatePreference: mockUpdatePreference,};}),@@ -180,3 +182,22 @@ describe('workspaceUserSettingsRouter.updatePreference', () => {});});});++describe('workspaceUserSettingsRouter.setWorktreeModeDir', () => {+ const ctx: any = { serverDB: {}, userId: 'user-member', workspaceId: 'ws-1' };++ it('stores one directory switch through the model and returns the list', async () => {+ mockSetWorktreeModeDir.mockResolvedValue(['dev::/code/a']);+ const caller = workspaceUserSettingsRouter.createCaller(ctx);++ await expect(+ caller.setWorktreeModeDir({ enabled: true, key: 'dev::/code/a' }),+ ).resolves.toEqual(['dev::/code/a']);+ expect(mockSetWorktreeModeDir).toHaveBeenCalledWith('dev::/code/a', true);+ });++ it('rejects an empty key', async () => {+ const caller = workspaceUserSettingsRouter.createCaller(ctx);+ await expect(caller.setWorktreeModeDir({ enabled: true, key: '' })).rejects.toThrow();+ });+});diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsindex 8f25f09226b..2e30a6dd0d6 100644--- a/apps/server/src/routers/lambda/device/git.ts+++ b/apps/server/src/routers/lambda/device/git.ts@@ -1,9 +1,11 @@+import { WORKTREE_BRANCH_PREFIX } from '@lobechat/const';import { deriveWorktreePath } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';+import { TopicModel } from '@/database/models/topic';import { router } from '@/libs/trpc/lambda';import { deviceGateway } from '@/server/services/deviceGateway';@@ -130,9 +132,17 @@ export const gitRouter = router({return result ?? null;}),gitAheadBehind: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))+ .input(+ z.object({+ /** Count this local branch instead of HEAD; the device echoes it back. */+ branch: z.string().optional(),+ deviceId: z.string(),+ path: z.string(),+ }),+ ).query(async ({ ctx, input }) => {const result = await deviceGateway.gitAheadBehind({+ branch: input.branch,deviceId: input.deviceId,path: input.path,userId: ctx.userId,@@ -140,6 +150,19 @@ export const gitRouter = router({});return result ?? null;}),+ /**+ * How many conversations are running in a directory on a device, so the+ * composer can confirm before a send switches that checkout's branch. Spans+ * every member's conversations in a workspace and returns only a count —+ * never which topics, or whose. Reads the database, not the device, so it+ * answers for an offline device too.+ */+ countRunningTopicsInDirectory: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string().min(1) }))+ .query(async ({ ctx, input }) => {+ const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ return topicModel.countInFlightInDirectory({ deviceId: input.deviceId, path: input.path });+ }),/*** List the git worktrees attached to the same repository as a directory on a* remote device, via the device's `listGitWorktrees` RPC. Lets the web/remote@@ -190,6 +213,8 @@ export const gitRouter = router({create: z.boolean().optional(),deviceId: z.string(),path: z.string(),+ /** With `create`, cut the new branch from this branch instead of HEAD. */+ startPoint: z.string().optional(),}),).mutation(async ({ ctx, input }) =>@@ -198,6 +223,7 @@ export const gitRouter = router({create: input.create,deviceId: input.deviceId,path: input.path,+ startPoint: input.startPoint,userId: ctx.userId,workspaceId: ctx.workspaceId,}),@@ -289,6 +315,15 @@ export const gitRouter = router({path: z.string(),/** The repo's main checkout, which keys the folder; `path` may be a linked worktree. */sourcePath: z.string().optional(),+ /** Fork the worktree's branch from this branch instead of HEAD. */+ startPoint: z.string().optional(),+ /**+ * Name the folder after the branch without the app's own namespace+ * (`lobehub/x` → `…/x`). A flag rather than a prefix string: the server+ * owns which namespace is dropped, so the request can only choose+ * between two server-derived folders under the same root.+ */+ stripBranchPrefix: z.boolean().optional(),}),).mutation(async ({ ctx, input }) => {@@ -310,9 +345,13 @@ export const gitRouter = router({branch: input.branch,deviceId: input.deviceId,path: input.path,+ startPoint: input.startPoint,userId: ctx.userId,workspaceId: ctx.workspaceId,- worktreePath: deriveWorktreePath(keyPath, input.branch, { homeDir }),+ worktreePath: deriveWorktreePath(keyPath, input.branch, {+ homeDir,+ stripBranchPrefix: input.stripBranchPrefix ? WORKTREE_BRANCH_PREFIX : undefined,+ }),});}),/**@@ -320,9 +359,17 @@ export const gitRouter = router({* the device's `pullGitBranch` RPC.*/pullGitBranch: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))+ .input(+ z.object({+ /** Sync this local branch instead of HEAD; the device echoes it back. */+ branch: z.string().optional(),+ deviceId: z.string(),+ path: z.string(),+ }),+ ).mutation(async ({ ctx, input }) =>deviceGateway.pullGitBranch({+ branch: input.branch,deviceId: input.deviceId,path: input.path,userId: ctx.userId,@@ -334,9 +381,17 @@ export const gitRouter = router({* `pushGitBranch` RPC.*/pushGitBranch: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))+ .input(+ z.object({+ /** Sync this local branch instead of HEAD; the device echoes it back. */+ branch: z.string().optional(),+ deviceId: z.string(),+ path: z.string(),+ }),+ ).mutation(async ({ ctx, input }) =>deviceGateway.pushGitBranch({+ branch: input.branch,deviceId: input.deviceId,path: input.path,userId: ctx.userId,diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.tsindex 6e64b1c3d35..df6c312b35f 100644--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts@@ -42,6 +42,7 @@ function expected(): Array<['closeTerminal', 'mutation', 12],['copyAssetForPublish', 'mutation', 15],['copyProjectFiles', 'mutation', 15],+ ['countRunningTopicsInDirectory', 'query', 12],['createDirectory', 'mutation', 12],['createProjectDirectory', 'mutation', 15],['createProjectFile', 'mutation', 15],diff --git a/apps/server/src/routers/lambda/user/index.procedures.test.ts b/apps/server/src/routers/lambda/user/index.procedures.test.tsindex 827d1709e01..3c42675e2e0 100644--- a/apps/server/src/routers/lambda/user/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/user/index.procedures.test.ts@@ -49,6 +49,7 @@ function expected(): Array<['reviseOnboardingUnderstanding', 'mutation', 14],['saveUserQuestion', 'mutation', 11],['sendOnboardingFirstMessage', 'mutation', 11],+ ['setWorktreeModeDir', 'mutation', 11],['startOnboardingUnderstanding', 'mutation', 14],['updateAgentOnboarding', 'mutation', 11],['updateAvatar', 'mutation', 11],diff --git a/apps/server/src/routers/lambda/user/settings.ts b/apps/server/src/routers/lambda/user/settings.tsindex 9d0d8ef06ac..e0c51d6f65d 100644--- a/apps/server/src/routers/lambda/user/settings.ts+++ b/apps/server/src/routers/lambda/user/settings.ts@@ -61,6 +61,14 @@ export const settingsRouter = router({updatePreference: userProcedure.input(UserPreferenceSchema).mutation(async ({ ctx, input }) => {return ctx.userModel.updatePreference(input);}),+ /**+ * Personal-mode "New worktree" switch for one directory. Its own mutation:+ * `updatePreference` deep-merges arrays by index, and the list's cap must be+ * applied against the stored copy, not a client's.+ */+ setWorktreeModeDir: userProcedure+ .input(z.object({ enabled: z.boolean(), key: z.string().min(1).max(4096) }))+ .mutation(async ({ ctx, input }) => ctx.userModel.setWorktreeModeDir(input.key, input.enabled)),/*** Personal chat-assist preferences (follow-up chips, input completion). They* act on the caller's own chat surface, so — unlike the rest ofdiff --git a/apps/server/src/routers/lambda/workspaceUserSettings.ts b/apps/server/src/routers/lambda/workspaceUserSettings.tsindex 456511fdde0..929c81b28b9 100644--- a/apps/server/src/routers/lambda/workspaceUserSettings.ts+++ b/apps/server/src/routers/lambda/workspaceUserSettings.ts@@ -67,6 +67,16 @@ export const workspaceUserSettingsRouter = router({},),+ /**+ * This member's "New worktree" switch for one directory in this workspace.+ * The list's cap is applied server-side, against the stored copy.+ */+ setWorktreeModeDir: workspaceUserSettingsProcedure+ .input(z.object({ enabled: z.boolean(), key: z.string().min(1).max(4096) }))+ .mutation(async ({ ctx, input }) =>+ ctx.workspaceUserSettingsModel.setWorktreeModeDir(input.key, input.enabled),+ ),+/*** Merge `input` on top of the caller's current preference and persist via* UPSERT. First call for a `(workspace, user)` pair creates the row.diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.tsindex 91fe0f90f6e..03e54376182 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts@@ -1,6 +1,6 @@import { claudeCodeAgentEnvPicksLogin } from '@lobechat/heterogeneous-agents/quota';import type { ExecAgentResult } from '@lobechat/types';-import { getWorkingDirSourcePath } from '@lobechat/types';+import { getWorkingDirSessionPath } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -212,11 +212,14 @@ export const dispatchToCliDevice = async (// The active worktree is a record the agent may already have deleted:// spawning in it would lose the session, or fail the run outright once the// directory is gone. The agent is told about it in the system context instead.- const deviceCwd = getWorkingDirSourcePath(deviceCwdConfig);+ // A worktree the app created on the first send is where the session starts+ // (`getWorkingDirSessionPath`), so it needs no description.+ const deviceCwd = getWorkingDirSessionPath(deviceCwdConfig);const worktreePath = deviceCwdConfig?.git?.activeWorktree;- const worktreeContext = worktreePath- ? { activeWorktree: { path: worktreePath, sourceDirectory: deviceCwd } }- : {};+ const worktreeContext =+ worktreePath && worktreePath !== deviceCwd+ ? { activeWorktree: { path: worktreePath, sourceDirectory: deviceCwd } }+ : {};// An unbound topic has no pinned cwd yet: the directory was only// recorded at agent level (`workingDirByDevice`) when no topic existed.diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.tsindex e5bc7438f41..a055138767a 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts@@ -708,6 +708,38 @@ describe('dispatchHeteroAgent — local CLI agents', () => {);});+ it('spawns in a worktree the app created on the first send, without describing it', async () => {+ // Fixed before the first turn, so the CLI session starts — and stays — there.+ const workingDirectoryConfig = {+ git: { activeWorktree: '/wt/quiet-hill', autoCreated: true, branch: 'lobehub/quiet-hill' },+ path: '/repo',+ repoType: 'github' as const,+ sessionPath: '/wt/quiet-hill',+ };+ const { deps, topicModel } = createDeps();+ topicModel.findById.mockResolvedValue({+ metadata: {+ boundDeviceId: 'dev-1',+ workingDirectory: '/wt/quiet-hill',+ workingDirectoryConfig,+ },+ });++ await dispatchHeteroAgent(+ deps,+ createCtx({+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ }),+ createInput('claude-code'),+ );++ const dispatched = mocks.dispatchAgentRun.mock.calls[0][0];+ expect(dispatched.cwd).toBe('/wt/quiet-hill');+ expect(dispatched.systemContext ?? '').not.toContain('<active_worktree>');+ });+it('keeps a timed-out dispatch alive and settles it later as a device timeout', async () => {// Whether the run started is unknowable after a timeout: the device may// have received it before the ack was lost, and its CLI may already bediff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.tsnew file mode 100644index 00000000000..be79e888da3--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts@@ -0,0 +1,76 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { buildNewTopicMetadata } from './newTopicMetadata';++const worktree = '/Users/me/.lobehub/worktrees/lobehub-0000beef/quiet-hill';+const prepared = {+ git: {+ activeWorktree: worktree,+ autoCreated: true,+ autoCreatedAt: '2026-11-17T00:00:00.000Z',+ branch: 'lobehub/quiet-hill',+ isWorktree: true,+ },+ path: '/code/lobehub/',+};++describe('buildNewTopicMetadata — project directory', () => {+ it('pins a plain project topic to the project directory', () => {+ const metadata = buildNewTopicMetadata({+ appContext: { initialTopicMetadata: { workingDirectory: '/elsewhere' } } as any,+ projectDirectory: { path: '/code/lobehub' },+ });++ expect(metadata).toMatchObject({+ workingDirectory: '/code/lobehub',+ workingDirectoryConfig: { path: '/code/lobehub' },+ });+ });++ // The composer cut a worktree from the project directory on the first send:+ // the topic runs there, with the project directory as its source.+ it('keeps a worktree prepared from the same project directory', () => {+ const metadata = buildNewTopicMetadata({+ appContext: {+ initialTopicMetadata: { workingDirectory: worktree, workingDirectoryConfig: prepared },+ } as any,+ projectDirectory: { path: '/code/lobehub' },+ });++ expect(metadata).toMatchObject({+ workingDirectory: worktree,+ workingDirectoryConfig: { ...prepared, path: '/code/lobehub' },+ });+ });++ it('ignores a worktree prepared from another directory', () => {+ const metadata = buildNewTopicMetadata({+ appContext: {+ initialTopicMetadata: {+ workingDirectory: worktree,+ workingDirectoryConfig: { ...prepared, path: '/code/other' },+ },+ } as any,+ projectDirectory: { path: '/code/lobehub' },+ });++ expect(metadata).toMatchObject({+ workingDirectory: '/code/lobehub',+ workingDirectoryConfig: { path: '/code/lobehub' },+ });+ });++ it('ignores a picked worktree that the app did not create', () => {+ const metadata = buildNewTopicMetadata({+ appContext: {+ initialTopicMetadata: {+ workingDirectoryConfig: { git: { activeWorktree: worktree }, path: '/code/lobehub' },+ },+ } as any,+ projectDirectory: { path: '/code/lobehub' },+ });++ expect(metadata?.workingDirectoryConfig).toEqual({ path: '/code/lobehub' });+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.tsindex 3b672124ba4..dffe7290abc 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -1,3 +1,6 @@+import type { WorkingDirConfig } from '@lobechat/types';+import { normalizeDirectoryPath } from '@lobechat/types';+import type { InternalExecAgentParams } from '../types';import { pickSandboxPlacement } from './sandboxPlacement';@@ -15,6 +18,23 @@ export interface NewTopicMetadataInput {webhookThread?: InternalExecAgentParams['webhookThread'];}+/**+ * The worktree the composer created for this topic on its first send+ * (Better Coding Experience "New worktree"), when it was cut from the project+ * directory the topic is born in. The project directory still names the+ * source; the worktree is where the topic runs, so it must survive the+ * project override below.+ */+const preparedProjectWorktree = (+ supplied: WorkingDirConfig | undefined,+ projectPath: string,+): WorkingDirConfig | undefined =>+ supplied?.git?.autoCreated &&+ supplied.git.activeWorktree &&+ normalizeDirectoryPath(supplied.path) === normalizeDirectoryPath(projectPath)+ ? supplied+ : undefined;+/*** Metadata a NEW topic is written with: cronJobId, taskId, botContext, the* generic webhook thread, bound device, and any client-supplied initial metadata (e.g. repos selected before@@ -34,11 +54,19 @@ export const buildNewTopicMetadata = ({topicBoundDeviceId,webhookThread,}: NewTopicMetadataInput) => {+ const preparedWorktree = projectDirectory+ ? preparedProjectWorktree(+ appContext?.initialTopicMetadata?.workingDirectoryConfig,+ projectDirectory.path,+ )+ : undefined;const initialTopicMeta = projectDirectory? {...appContext?.initialTopicMetadata,- workingDirectory: projectDirectory.path,- workingDirectoryConfig: { path: projectDirectory.path },+ workingDirectory: preparedWorktree?.git?.activeWorktree ?? projectDirectory.path,+ workingDirectoryConfig: preparedWorktree+ ? { ...preparedWorktree, path: projectDirectory.path }+ : { path: projectDirectory.path },}: appContext?.initialTopicMetadata;// Builder conversations are owned by a builtin builder agent and get nodiff --git a/apps/server/src/services/deviceGateway/gitRead.ts b/apps/server/src/services/deviceGateway/gitRead.tsindex 5665b20df51..705414107a6 100644--- a/apps/server/src/services/deviceGateway/gitRead.ts+++ b/apps/server/src/services/deviceGateway/gitRead.ts@@ -153,10 +153,18 @@ export function gitWorkingTreeStatus(/** Ahead/behind commit counts for a directory on a remote device. */export function gitAheadBehind(getClient: DeviceClientGetter,- params: { deviceId: string; path: string; userId: string; workspaceId?: string },+ params: {+ /** Count this branch instead of HEAD. */+ branch?: string;+ deviceId: string;+ path: string;+ userId: string;+ workspaceId?: string;+ },) {return invokeDeviceRead<DeviceGitAheadBehind>(getClient, 'getGitAheadBehind', params, {path: params.path,+ ...(params.branch ? { branch: params.branch } : {}),});}diff --git a/apps/server/src/services/deviceGateway/gitWrite.ts b/apps/server/src/services/deviceGateway/gitWrite.tsindex 8529d82fbc4..b26f68af352 100644--- a/apps/server/src/services/deviceGateway/gitWrite.ts+++ b/apps/server/src/services/deviceGateway/gitWrite.ts@@ -29,19 +29,33 @@ export async function checkoutGitBranch(create?: boolean;deviceId: string;path: string;+ /** Cut the new branch from this branch instead of HEAD (needs `create`). */+ startPoint?: string;timeout?: number;userId: string;workspaceId?: string;},): Promise<DeviceGitCheckoutResult> {- const { userId, deviceId, branch, create, path, timeout = 30_000, workspaceId } = params;+ const {+ userId,+ deviceId,+ branch,+ create,+ path,+ startPoint,+ timeout = 30_000,+ workspaceId,+ } = params;const client = getClient();if (!client) return { error: 'Device gateway not configured', success: false };try {const result = await client.invokeRpc<DeviceGitCheckoutResult>({ deviceId, timeout, userId, workspaceId },- { method: 'checkoutGitBranch', params: { branch, create, path } },+ {+ method: 'checkoutGitBranch',+ params: { branch, create, path, ...(startPoint ? { startPoint } : {}) },+ },);if (!result.success || !result.data) {@@ -178,20 +192,34 @@ export async function addGitWorktree(branch: string;deviceId: string;path: string;+ /** Fork the worktree's branch from this branch instead of HEAD. */+ startPoint?: string;timeout?: number;userId: string;workspaceId?: string;worktreePath: string;},): Promise<DeviceGitAddWorktreeResult> {- const { userId, deviceId, branch, path, worktreePath, workspaceId, timeout = 30_000 } = params;+ const {+ userId,+ deviceId,+ branch,+ path,+ startPoint,+ worktreePath,+ workspaceId,+ timeout = 30_000,+ } = params;const client = getClient();if (!client) return { error: 'Device gateway not configured', success: false };try {const result = await client.invokeRpc<DeviceGitAddWorktreeResult>({ deviceId, timeout, userId, workspaceId },- { method: 'addGitWorktree', params: { branch, path, worktreePath } },+ {+ method: 'addGitWorktree',+ params: { branch, path, worktreePath, ...(startPoint ? { startPoint } : {}) },+ },);if (!result.success || !result.data) {@@ -213,6 +241,8 @@ export async function addGitWorktree(export async function pullGitBranch(getClient: DeviceClientGetter,params: {+ /** Sync this branch instead of HEAD. */+ branch?: string;deviceId: string;path: string;timeout?: number;@@ -220,14 +250,14 @@ export async function pullGitBranch(workspaceId?: string;},): Promise<DeviceGitSyncResult> {- const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;+ const { userId, deviceId, branch, path, timeout = 65_000, workspaceId } = params;const client = getClient();if (!client) return { error: 'Device gateway not configured', success: false };try {const result = await client.invokeRpc<DeviceGitSyncResult>({ deviceId, timeout, userId, workspaceId },- { method: 'pullGitBranch', params: { path } },+ { method: 'pullGitBranch', params: { path, ...(branch ? { branch } : {}) } },);if (!result.success || !result.data) {@@ -249,6 +279,8 @@ export async function pullGitBranch(export async function pushGitBranch(getClient: DeviceClientGetter,params: {+ /** Sync this branch instead of HEAD. */+ branch?: string;deviceId: string;path: string;timeout?: number;@@ -256,14 +288,14 @@ export async function pushGitBranch(workspaceId?: string;},): Promise<DeviceGitSyncResult> {- const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;+ const { userId, deviceId, branch, path, timeout = 65_000, workspaceId } = params;const client = getClient();if (!client) return { error: 'Device gateway not configured', success: false };try {const result = await client.invokeRpc<DeviceGitSyncResult>({ deviceId, timeout, userId, workspaceId },- { method: 'pushGitBranch', params: { path } },+ { method: 'pushGitBranch', params: { path, ...(branch ? { branch } : {}) } },);if (!result.success || !result.data) {diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.tsindex 35b68abfde7..eba1a7de0ec 100644--- a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts@@ -155,6 +155,13 @@ const cases: RpcCase[] = [name: 'gitAheadBehind',payload: { method: 'getGitAheadBehind', params: { path: '/p' } },},+ {+ address: address(15_000),+ call: (g) => g.gitAheadBehind({ ...base, branch: 'feat', path: '/p' }),+ failure: UNDEFINED,+ name: 'gitAheadBehind (named branch)',+ payload: { method: 'getGitAheadBehind', params: { branch: 'feat', path: '/p' } },+ },{address: address(15_000),call: (g) => g.listGitWorktrees({ ...base, path: '/p' }),@@ -205,6 +212,17 @@ const cases: RpcCase[] = [name: 'checkoutGitBranch',payload: { method: 'checkoutGitBranch', params: { branch: 'b', create: true, path: '/p' } },},+ {+ address: address(30_000),+ call: (g) =>+ g.checkoutGitBranch({ ...base, branch: 'b', create: true, path: '/p', startPoint: 's' }),+ failure: errorResult('Checkout failed'),+ name: 'checkoutGitBranch (start point)',+ payload: {+ method: 'checkoutGitBranch',+ params: { branch: 'b', create: true, path: '/p', startPoint: 's' },+ },+ },{address: address(30_000),call: (g) => g.renameGitBranch({ ...base, from: 'a', path: '/p', to: 'b' }),@@ -236,6 +254,31 @@ const cases: RpcCase[] = [params: { branch: 'b', path: '/p', worktreePath: '/w' },},},+ {+ address: address(30_000),+ call: (g) =>+ g.addGitWorktree({ ...base, branch: 'b', path: '/p', startPoint: 's', worktreePath: '/w' }),+ failure: errorResult('Add worktree failed'),+ name: 'addGitWorktree (start point)',+ payload: {+ method: 'addGitWorktree',+ params: { branch: 'b', path: '/p', startPoint: 's', worktreePath: '/w' },+ },+ },+ {+ address: address(65_000),+ call: (g) => g.pullGitBranch({ ...base, branch: 'feat', path: '/p' }),+ failure: errorResult('Pull failed'),+ name: 'pullGitBranch (named branch)',+ payload: { method: 'pullGitBranch', params: { branch: 'feat', path: '/p' } },+ },+ {+ address: address(65_000),+ call: (g) => g.pushGitBranch({ ...base, branch: 'feat', path: '/p' }),+ failure: errorResult('Push failed'),+ name: 'pushGitBranch (named branch)',+ payload: { method: 'pushGitBranch', params: { branch: 'feat', path: '/p' } },+ },{address: address(65_000),call: (g) => g.pullGitBranch({ ...base, path: '/p' }),diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdxindex f88535586db..6dcc2269cdb 100644--- a/docs/self-hosting/advanced/feature-flags.mdx+++ b/docs/self-hosting/advanced/feature-flags.mdx@@ -34,32 +34,32 @@ You can achieve various feature combinations using the above configuration syntatheir default values).</Callout>-| Configuration Item | Description | Default Value |-| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |-| `check_updates` | Allows checking for updates. | Enabled |-| `provider_settings` | Controls model provider settings display. | Enabled |-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |-| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |-| `agent_deferred_init` | Returns a plain chat send as soon as its messages are saved and runs tool discovery and context assembly in the first agent step, so sending feels instant. Requires the queue agent runtime. | Disabled |-| `agent_deferred_hetero_dispatch` | Returns a plain chat send to a heterogeneous agent (Claude Code, Codex, …) on an online device before the device accepts the run; the dispatch runs after the response, and a failure is shown on the assistant message. | Disabled |-| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |-| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled |+| Configuration Item | Description | Default Value |+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |+| `check_updates` | Allows checking for updates. | Enabled |+| `provider_settings` | Controls model provider settings display. | Enabled |+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |+| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |+| `agent_deferred_init` | Returns a plain chat send as soon as its messages are saved and runs tool discovery and context assembly in the first agent step, so sending feels instant. Requires the queue agent runtime. | Disabled |+| `agent_deferred_hetero_dispatch` | Returns a plain chat send to a heterogeneous agent (Claude Code, Codex, …) on an online device before the device accepts the run; the dispatch runs after the response, and a failure is shown on the assistant message. | Disabled |+| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |+| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled || `webhook` | Inbound webhooks wake Agents. MCP Events: an Agent subscribes to remote connector events and runs in the original Topic; subscribing follows the user's tool approval settings. Agent webhooks: URLs under Agent Profile → Webhook that any outside system calls to run the Agent. Each event or call uses credits. Requires a public `APP_URL` and secret encryption; MCP Events also needs an authenticated MCP server offering webhook events. When off, the entries are hidden and deliveries are still recorded but run nothing. | Disabled |-| `edit_agent` | Allows users to edit assistants. | Enabled |-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |-| `token_counter` | Reserved for token counter display. | Enabled |-| `welcome_suggest` | Displays welcome suggestions. | Enabled |-| `changelog` | Controls changelog modal/page display. | Enabled |-| `market` | Enables the assistant market functionality. | Enabled |-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |+| `edit_agent` | Allows users to edit assistants. | Enabled |+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |+| `token_counter` | Reserved for token counter display. | Enabled |+| `welcome_suggest` | Displays welcome suggestions. | Enabled |+| `changelog` | Controls changelog modal/page display. | Enabled |+| `market` | Enables the assistant market functionality. | Enabled |+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |## Interactive Agent Sharing: Deployment and Rollout Boundariesdiff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdxindex 49568c6bf3a..fa718d13a3f 100644--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx@@ -32,32 +32,32 @@ tags:关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。</Callout>-| 配置项 | 解释 | 默认值 |-| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --- |-| `check_updates` | 允许检查更新。 | 开启 |-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |-| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |-| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |-| `agent_deferred_hetero_dispatch` | 普通聊天发给在线设备上的异构助理(Claude Code、Codex 等)时,不等设备接收任务就立即返回;派发在响应后执行,失败会显示在助理消息上。 | 关闭 |-| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |-| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |+| 配置项 | 解释 | 默认值 |+| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- |+| `check_updates` | 允许检查更新。 | 开启 |+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |+| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |+| `agent_deferred_hetero_dispatch` | 普通聊天发给在线设备上的异构助理(Claude Code、Codex 等)时,不等设备接收任务就立即返回;派发在响应后执行,失败会显示在助理消息上。 | 关闭 |+| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |+| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 || `webhook` | 入站 Webhook 唤醒 Agent。MCP Events:Agent 订阅远程连接器事件,并在原 Topic 中运行;创建订阅遵循用户的工具审批设置。Agent Webhook:在助理档案 → Webhook 中管理、任意外部系统都能调用的 URL,调用即运行 Agent。每次事件或调用会消耗额度。需公网 `APP_URL` 与密钥加密配置;MCP Events 还需支持 webhook 事件的已认证 MCP 服务器。关闭后入口隐藏,投递仍会记录但不运行。 | 关闭 |-| `edit_agent` | 允许用户编辑助手。 | 开启 |-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |-| `speech_to_text` | 启用语音转文本功能。 | 开启 |-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |-| `welcome_suggest` | 显示欢迎建议。 | 开启 |-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |-| `market` | 启用助手市场功能。 | 开启 |-| `knowledge_base` | 启用知识库功能。 | 开启 |-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |+| `edit_agent` | 允许用户编辑助手。 | 开启 |+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |+| `speech_to_text` | 启用语音转文本功能。 | 开启 |+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |+| `welcome_suggest` | 显示欢迎建议。 | 开启 |+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |+| `market` | 启用助手市场功能。 | 开启 |+| `knowledge_base` | 启用知识库功能。 | 开启 |+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |## 交互式助理分享:部署与灰度边界diff --git a/docs/usage/agent/webhooks.mdx b/docs/usage/agent/webhooks.mdxindex 99661296737..6c5a6faac80 100644--- a/docs/usage/agent/webhooks.mdx+++ b/docs/usage/agent/webhooks.mdx@@ -41,13 +41,13 @@ curl -X POST 'https://your-lobehub/api/webhooks/inbound/<id>' \A successful call returns `202 {"id": "...", "status": "accepted"}` right away; the agent runs in the background. Other answers:-| Status | Meaning |-| ------ | ----------------------------------------------------------- |-| `401` | The key is missing or wrong, or was replaced by a new one. |-| `409` | The webhook is paused. |-| `410` | The webhook was deleted. |-| `413` | The body is larger than 256 KB. |-| `415` | File uploads (`multipart/form-data`) are not supported. |+| Status | Meaning |+| ------ | ----------------------------------------------------------------------- |+| `401` | The key is missing or wrong, or was replaced by a new one. |+| `409` | The webhook is paused. |+| `410` | The webhook was deleted. |+| `413` | The body is larger than 256 KB. |+| `415` | File uploads (`multipart/form-data`) are not supported. || `429` | Too many calls this minute in the workspace; retry after `Retry-After`. |## Follow what happeneddiff --git a/docs/usage/agent/webhooks.zh-CN.mdx b/docs/usage/agent/webhooks.zh-CN.mdxindex cc81b79d1c5..d950df869dd 100644--- a/docs/usage/agent/webhooks.zh-CN.mdx+++ b/docs/usage/agent/webhooks.zh-CN.mdx@@ -41,13 +41,13 @@ curl -X POST 'https://your-lobehub/api/webhooks/inbound/<id>' \调用成功时立即返回 `202 {"id": "...", "status": "accepted"}`,助理在后台运行。其它返回:-| 状态码 | 含义 |-| ----- | ----------------------------------- |-| `401` | 缺少密钥、密钥不对,或已被新密钥替换。 |-| `409` | Webhook 已停用。 |-| `410` | Webhook 已删除。 |-| `413` | 请求体超过 256 KB。 |-| `415` | 不支持文件上传(`multipart/form-data`)。 |+| 状态码 | 含义 |+| ----- | --------------------------------- |+| `401` | 缺少密钥、密钥不对,或已被新密钥替换。 |+| `409` | Webhook 已停用。 |+| `410` | Webhook 已删除。 |+| `413` | 请求体超过 256 KB。 |+| `415` | 不支持文件上传(`multipart/form-data`)。 || `429` | 本分钟内工作区的调用太多,请按 `Retry-After` 重试。 |## 查看运行情况diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex 5ba8219e752..c54808b8f13 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -6,6 +6,7 @@"workingDirectory.agentDescription": "Default working directory for all conversations with this Agent","workingDirectory.agentLevel": "Agent Working Directory","workingDirectory.bareWorktree": "bare",+ "workingDirectory.branchCheckedOutHere": "Checked out here","workingDirectory.branchConfirming": "Confirming the current branch…","workingDirectory.branchInWorktree": "In worktree {{name}}","workingDirectory.branchSearchPlaceholder": "Search branches",@@ -40,6 +41,7 @@"workingDirectory.detachedHead": "Detached HEAD at {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.deviceOutdated": "The LobeHub app or lh CLI on this device is too old for this. Update it and try again.","workingDirectory.deviceWakeFailed": "Could not wake this cloud device. Try again.","workingDirectory.deviceWakeSlow": "The cloud device is still starting. Try again in a moment.","workingDirectory.deviceWaking": "Waking the cloud device… This can take up to two minutes.",@@ -108,16 +110,24 @@"workingDirectory.noMatch": "No matching directories","workingDirectory.noRecent": "No directories yet","workingDirectory.notSet": "Click to set working directory",+ "workingDirectory.occupiedBranchConfirm": "Create branch and send",+ "workingDirectory.occupiedBranchDesc": "{{branch}} is checked out in worktree {{name}}, so it cannot be checked out here. A new branch will be created from it instead.",+ "workingDirectory.occupiedBranchNameLabel": "New branch name",+ "workingDirectory.occupiedBranchTitle": "Create a branch from {{branch}}","workingDirectory.openPath": "Open","workingDirectory.parentFolder": "Parent folder","workingDirectory.pathNotDirectory": "This path is not a directory","workingDirectory.pathNotExist": "This path doesn't exist on the device","workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects","workingDirectory.prTooltipWithExtra": "{{title}} (+{{count}} more open PR on this branch)",+ "workingDirectory.preparingSwitch": "Switching to {{branch}}…",+ "workingDirectory.preparingWorktree": "Creating worktree…","workingDirectory.prunableWorktree": "prunable","workingDirectory.pullAction": "Click to pull {{count}} commit(s) from {{upstream}}",+ "workingDirectory.pullCheckedOutElsewhere": "{{branch}} is checked out in worktree {{name}}. Pull it there.","workingDirectory.pullFailed": "Pull failed","workingDirectory.pullInProgress": "Pulling…",+ "workingDirectory.pullNoUpstream": "{{branch}} has no upstream branch to pull from","workingDirectory.pullNoop": "Already up to date","workingDirectory.pullSuccess": "Pulled successfully","workingDirectory.pushAction": "Click to push {{count}} commit(s) to {{target}}",@@ -142,12 +152,20 @@"workingDirectory.renameBranchTitle": "Rename branch","workingDirectory.renameFailed": "Rename failed","workingDirectory.rollBranchName": "Roll another branch name",+ "workingDirectory.scheduleGitUnsupported": "Send later can't switch branches or create a worktree. Send now, or pick the current branch and turn off New worktree.","workingDirectory.searchPlaceholder": "Search directories","workingDirectory.selectFolder": "Select folder","workingDirectory.setDefault": "Set as default","workingDirectory.staleResetToSource": "Switch back to {{name}}","workingDirectory.staleSnapshot": "The directory recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.","workingDirectory.staleWorktreeSnapshot": "The worktree “{{name}}” recorded for this conversation no longer exists — showing the Git snapshot saved on the topic.",+ "workingDirectory.switchFailed": "Could not switch to {{branch}}",+ "workingDirectory.switchRiskConfirm": "Switch and send",+ "workingDirectory.switchRiskRunning_one": "{{count}} topic is still running in this directory. Switching the branch will affect it.",+ "workingDirectory.switchRiskRunning_other": "{{count}} topics are still running in this directory. Switching the branch will affect them.",+ "workingDirectory.switchRiskTitle": "Switch to {{branch}} and send?",+ "workingDirectory.switchRiskUncommitted_one": "Uncommitted changes may be lost ({{count}} file).",+ "workingDirectory.switchRiskUncommitted_other": "Uncommitted changes may be lost ({{count}} files).","workingDirectory.title": "Working Directory","workingDirectory.topicDescription": "Override Agent default for this conversation only","workingDirectory.topicLevel": "Conversation override",@@ -158,7 +176,13 @@"workingDirectory.unselected": "Not selected","workingDirectory.useFolder": "Use this folder","workingDirectory.useFolderFailed": "Couldn’t use this folder.",+ "workingDirectory.worktreeCreateFailed": "Could not create the worktree","workingDirectory.worktreeSearchPlaceholder": "Search worktrees",+ "workingDirectory.worktreeToggle": "New worktree",+ "workingDirectory.worktreeToggleOffHint": "Turn on to run this topic in a new branch and worktree",+ "workingDirectory.worktreeToggleOn": "New worktree: on",+ "workingDirectory.worktreeToggleOnHint": "Sending creates a new branch and worktree from {{branch}}; this directory stays as it is",+ "workingDirectory.worktreeToggleSaveFailed": "Could not save the New worktree setting","workingDirectory.worktreeUnavailable": "unavailable","workingDirectory.worktreesEmpty": "No worktrees found","workingDirectory.worktreesHeading": "Worktrees",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex dc900b54ee8..6e5dc469cf4 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -6,6 +6,7 @@"workingDirectory.agentDescription": "该助手下所有对话的默认工作目录","workingDirectory.agentLevel": "代理工作目录","workingDirectory.bareWorktree": "bare",+ "workingDirectory.branchCheckedOutHere": "当前已签出","workingDirectory.branchConfirming": "正在确认当前分支…","workingDirectory.branchInWorktree": "位于工作树 {{name}}","workingDirectory.branchSearchPlaceholder": "搜索分支",@@ -40,6 +41,7 @@"workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.deviceOutdated": "这台设备上的 LobeHub 应用或 lh CLI 版本过旧,不支持此操作。请升级后重试。","workingDirectory.deviceWakeFailed": "无法唤醒该云端设备,请重试。","workingDirectory.deviceWakeSlow": "云端设备仍在启动,请稍后重试。","workingDirectory.deviceWaking": "正在唤醒云端设备,最多需要 2 分钟…",@@ -108,16 +110,24 @@"workingDirectory.noMatch": "没有匹配的目录","workingDirectory.noRecent": "暂无工作目录","workingDirectory.notSet": "点击设置工作目录",+ "workingDirectory.occupiedBranchConfirm": "新建分支并发送",+ "workingDirectory.occupiedBranchDesc": "{{branch}} 已在工作树 {{name}} 中签出,无法在这里签出。将基于它新建一个分支。",+ "workingDirectory.occupiedBranchNameLabel": "新分支名称",+ "workingDirectory.occupiedBranchTitle": "基于 {{branch}} 新建分支","workingDirectory.openPath": "打开","workingDirectory.parentFolder": "上一级","workingDirectory.pathNotDirectory": "该路径不是一个目录","workingDirectory.pathNotExist": "该设备上不存在此路径","workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects","workingDirectory.prTooltipWithExtra": "{{title}}(此分支还有 {{count}} 个开放 PR)",+ "workingDirectory.preparingSwitch": "正在切换到 {{branch}}…",+ "workingDirectory.preparingWorktree": "正在创建工作树…","workingDirectory.prunableWorktree": "prunable","workingDirectory.pullAction": "点击从 {{upstream}} 拉取 {{count}} 个提交",+ "workingDirectory.pullCheckedOutElsewhere": "{{branch}} 已在工作树 {{name}} 中签出,请在那里拉取。","workingDirectory.pullFailed": "拉取失败","workingDirectory.pullInProgress": "拉取中…",+ "workingDirectory.pullNoUpstream": "{{branch}} 没有可拉取的上游分支","workingDirectory.pullNoop": "已是最新","workingDirectory.pullSuccess": "拉取成功","workingDirectory.pushAction": "点击推送 {{count}} 个提交到 {{target}}",@@ -142,12 +152,20 @@"workingDirectory.renameBranchTitle": "重命名分支","workingDirectory.renameFailed": "重命名失败","workingDirectory.rollBranchName": "换一个分支名",+ "workingDirectory.scheduleGitUnsupported": "「稍后发送」无法切换分支或创建工作树。请立即发送,或选回当前分支并关闭「新建工作树」。","workingDirectory.searchPlaceholder": "搜索工作目录","workingDirectory.selectFolder": "选择文件夹","workingDirectory.setDefault": "设为默认","workingDirectory.staleResetToSource": "切回 {{name}}","workingDirectory.staleSnapshot": "此对话记录的工作目录已不存在,展示的是话题保存的 Git 快照。","workingDirectory.staleWorktreeSnapshot": "此对话记录的工作树「{{name}}」已不存在,展示的是话题保存的 Git 快照。",+ "workingDirectory.switchFailed": "无法切换到 {{branch}}",+ "workingDirectory.switchRiskConfirm": "切换并发送",+ "workingDirectory.switchRiskRunning_one": "这个目录还有 {{count}} 个话题在运行,切换分支会影响它们。",+ "workingDirectory.switchRiskRunning_other": "这个目录还有 {{count}} 个话题在运行,切换分支会影响它们。",+ "workingDirectory.switchRiskTitle": "切换到 {{branch}} 并发送?",+ "workingDirectory.switchRiskUncommitted_one": "未提交的改动可能会丢失({{count}} 个文件)。",+ "workingDirectory.switchRiskUncommitted_other": "未提交的改动可能会丢失({{count}} 个文件)。","workingDirectory.title": "工作目录","workingDirectory.topicDescription": "仅覆盖当前对话的工作目录","workingDirectory.topicLevel": "对话覆盖",@@ -158,7 +176,13 @@"workingDirectory.unselected": "未选择","workingDirectory.useFolder": "选择此文件夹","workingDirectory.useFolderFailed": "无法使用此文件夹。",+ "workingDirectory.worktreeCreateFailed": "无法创建工作树","workingDirectory.worktreeSearchPlaceholder": "搜索 worktree",+ "workingDirectory.worktreeToggle": "新建工作树",+ "workingDirectory.worktreeToggleOffHint": "开启后,这个话题会在新的分支和工作树中进行",+ "workingDirectory.worktreeToggleOn": "新建工作树:已开启",+ "workingDirectory.worktreeToggleOnHint": "发送时基于 {{branch}} 新建分支和工作树,当前目录保持不变",+ "workingDirectory.worktreeToggleSaveFailed": "无法保存「新建工作树」设置","workingDirectory.worktreeUnavailable": "不可用","workingDirectory.worktreesEmpty": "未发现 worktree","workingDirectory.worktreesHeading": "Worktree",diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsindex 17281023dfb..d7c5da79434 100644--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -53,6 +53,7 @@ const PUBLIC_METHODS = ['cancelRateLimitContinuation','count','countBySender',+ 'countInFlightInDirectory','countShareVisitors','countTopicsForMemoryExtractor','create',diff --git a/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.ts b/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.tsnew file mode 100644index 00000000000..0d0d5850896--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.ts@@ -0,0 +1,167 @@+// @vitest-environment node+import type { ChatTopicMetadata } from '@lobechat/types';+import { inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { topics, users, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-inflight-user';+const memberId = 'topic-inflight-member';+const strangerId = 'topic-inflight-stranger';+const workspaceId = 'topic-inflight-ws';++const insert = (+ id: string,+ metadata: ChatTopicMetadata,+ extra: { status?: 'active' | 'running'; userId?: string; workspaceId?: string | null } = {},+) =>+ serverDB.insert(topics).values({+ id,+ metadata,+ status: extra.status ?? 'running',+ userId: extra.userId ?? userId,+ workspaceId: extra.workspaceId ?? null,+ });++const inRepo = (path: string, extra: Partial<ChatTopicMetadata> = {}): ChatTopicMetadata => ({+ boundDeviceId: 'dev-1',+ workingDirectoryConfig: { path },+ ...extra,+});++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: memberId }, { id: strangerId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: 'topic-inflight-ws' });+});++afterEach(async () => {+ await serverDB.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));+ await serverDB.delete(users).where(inArray(users.id, [userId, memberId, strangerId]));+});++describe('TopicModel.countInFlightInDirectory', () => {+ const personal = () => new TopicModel(serverDB, userId);++ it('counts running topics in the same directory, however the path is spelled', async () => {+ await insert('t-1', inRepo('/code/lobehub'));+ await insert('t-2', { boundDeviceId: 'dev-1', workingDirectory: '/code/lobehub/' });++ expect(+ await personal().countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub/' }),+ ).toBe(2);+ });++ it('counts a picked worktree against both checkouts a run may use', async () => {+ // A native agent works in the worktree, but a local CLI process starts in+ // the source repository.+ await insert(+ 't-wt',+ inRepo('/code/lobehub', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/home/.lobehub/worktrees/x' },+ path: '/code/lobehub',+ },+ }),+ );++ const model = personal();+ expect(await model.countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' })).toBe(+ 1,+ );+ expect(+ await model.countInFlightInDirectory({+ deviceId: 'dev-1',+ path: '/home/.lobehub/worktrees/x',+ }),+ ).toBe(1);+ });++ it('counts a worktree made on the first send only against itself', async () => {+ await insert(+ 't-auto',+ inRepo('/code/lobehub', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/home/.lobehub/worktrees/y', autoCreated: true },+ path: '/code/lobehub',+ sessionPath: '/home/.lobehub/worktrees/y',+ },+ }),+ );++ const model = personal();+ expect(await model.countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' })).toBe(+ 0,+ );+ expect(+ await model.countInFlightInDirectory({+ deviceId: 'dev-1',+ path: '/home/.lobehub/worktrees/y',+ }),+ ).toBe(1);+ });++ it('counts a live run marker even when the status is not running', async () => {+ await insert(+ 't-op',+ inRepo('/code/lobehub', {+ runningOperation: { assistantMessageId: 'm', operationId: 'op', threadId: null },+ }),+ { status: 'active' },+ );++ expect(+ await personal().countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).toBe(1);+ });++ it('ignores idle topics, other devices and other directories', async () => {+ await insert('t-idle', inRepo('/code/lobehub'), { status: 'active' });+ await insert('t-dev', { ...inRepo('/code/lobehub'), boundDeviceId: 'dev-2' });+ await insert('t-dir', inRepo('/code/other'));++ expect(+ await personal().countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).toBe(0);+ });++ it('follows the device a run was dispatched to over the pin', async () => {+ await insert(+ 't-moved',+ inRepo('/code/lobehub', {+ boundDeviceId: 'dev-2',+ runningOperation: {+ assistantMessageId: 'm',+ deviceId: 'dev-1',+ operationId: 'op',+ threadId: null,+ },+ }),+ );++ expect(+ await personal().countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).toBe(1);+ });++ it('spans every member in a workspace but nothing outside it', async () => {+ await insert('t-me', inRepo('/code/lobehub'), { workspaceId });+ await insert('t-member', inRepo('/code/lobehub'), { userId: memberId, workspaceId });+ await insert('t-personal', inRepo('/code/lobehub'));+ await insert('t-stranger', inRepo('/code/lobehub'), { userId: strangerId });++ const inWorkspace = new TopicModel(serverDB, userId, workspaceId);+ expect(+ await inWorkspace.countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).toBe(2);+ expect(+ await personal().countInFlightInDirectory({ deviceId: 'dev-1', path: '/code/lobehub' }),+ ).toBe(1);+ });+});diff --git a/packages/database/src/models/__tests__/worktreeModeDirs.test.ts b/packages/database/src/models/__tests__/worktreeModeDirs.test.tsnew file mode 100644index 00000000000..b066aaef47f--- /dev/null+++ b/packages/database/src/models/__tests__/worktreeModeDirs.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { WORKTREE_MODE_DIRS_LIMIT } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users, workspaces, workspaceUserSettings } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { UserModel } from '../user';+import { WorkspaceUserSettingsModel } from '../workspaceUserSettings';++const serverDB: LobeChatDatabase = await getTestDB();++const workspaceId = 'ws-worktree-mode-test';+const userId = 'user-worktree-mode-test';++const cleanup = async () => {+ await serverDB.delete(workspaceUserSettings);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values({ id: userId, preference: { topicGroupMode: 'byTime' } });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: 'ws-worktree' });+});++afterEach(cleanup);++describe('UserModel.setWorktreeModeDir', () => {+ const model = () => new UserModel(serverDB, userId);+ const readPreference = async () =>+ (await serverDB.query.users.findFirst({ where: eq(users.id, userId) }))?.preference as Record<+ string,+ unknown+ >;++ it('stores directories switched on, newest first, and keeps other fields', async () => {+ await model().setWorktreeModeDir('d::/a', true);+ expect(await model().setWorktreeModeDir('d::/b', true)).toEqual(['d::/b', 'd::/a']);+ expect(await readPreference()).toMatchObject({+ topicGroupMode: 'byTime',+ worktreeModeDirs: ['d::/b', 'd::/a'],+ });+ });++ it('drops a directory switched off', async () => {+ await model().setWorktreeModeDir('d::/a', true);+ expect(await model().setWorktreeModeDir('d::/a', false)).toEqual([]);+ });++ it('survives a generic preference write', async () => {+ await model().setWorktreeModeDir('d::/a', true);+ await model().updatePreference({ topicSortBy: 'updatedAt' });+ expect((await readPreference()).worktreeModeDirs).toEqual(['d::/a']);+ });++ it('caps the list at the limit', async () => {+ await serverDB+ .update(users)+ .set({+ preference: {+ worktreeModeDirs: Array.from({ length: WORKTREE_MODE_DIRS_LIMIT }, (_, i) => `k${i}`),+ },+ })+ .where(eq(users.id, userId));++ const stored = await model().setWorktreeModeDir('newest', true);+ expect(stored).toHaveLength(WORKTREE_MODE_DIRS_LIMIT);+ expect(stored[0]).toBe('newest');+ });+});++describe('WorkspaceUserSettingsModel.setWorktreeModeDir', () => {+ const model = () => new WorkspaceUserSettingsModel(serverDB, userId, workspaceId);++ it('creates the row on first use and keeps sibling fields on later writes', async () => {+ expect(await model().setWorktreeModeDir('d::/a', true)).toEqual(['d::/a']);+ await model().updatePreference({ agentModeOverrides: { agentX: true } });+ expect(await model().setWorktreeModeDir('d::/b', true)).toEqual(['d::/b', 'd::/a']);++ expect(await model().getPreference()).toEqual({+ agentModeOverrides: { agentX: true },+ worktreeModeDirs: ['d::/b', 'd::/a'],+ });+ });++ it('keeps workspaces apart from the personal preference', async () => {+ await model().setWorktreeModeDir('d::/a', true);+ const user = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });+ expect((user?.preference as Record<string, unknown>).worktreeModeDirs).toBeUndefined();+ });+});diff --git a/packages/database/src/models/topic/inFlight.ts b/packages/database/src/models/topic/inFlight.tsnew file mode 100644index 00000000000..b3fc2126443--- /dev/null+++ b/packages/database/src/models/topic/inFlight.ts@@ -0,0 +1,87 @@+import type { ChatTopicMetadata } from '@lobechat/types';+import { normalizeDirectoryPath } from '@lobechat/types';+import { and, eq, isNull, or, sql } from 'drizzle-orm';++import { topics } from '../../schemas';+import type { TopicModelContext } from './context';+import { getTopicDeviceId } from './runningOperation';+import { hasLiveTaskCallbackReservation } from './taskCallback';++/**+ * Every checkout a topic may be running in. A worktree picked mid-conversation+ * is where a native agent works, but a local CLI agent's process still starts+ * in the source repository (`getWorkingDirSessionPath`), so both count. A+ * topic born in a worktree the app created runs its CLI there instead+ * (`sessionPath`), and nothing of it runs in the source. Over-counting only adds a confirmation; missing a+ * directory would let a branch switch run under a live agent.+ */+export const getTopicRunDirectories = (+ metadata: ChatTopicMetadata | null | undefined,+): string[] => {+ const config = metadata?.workingDirectoryConfig;+ const worktree = config?.git?.activeWorktree;+ // Born in the app's worktree: the CLI starts there (`sessionPath`), never in+ // the source, and the agent works wherever the topic's worktree is now.+ if (config?.sessionPath)+ return [worktree, config.sessionPath].filter((dir): dir is string => !!dir);+ return [worktree, config?.path, metadata?.workingDirectory].filter((dir): dir is string => !!dir);+};++/**+ * Same test as the project-directory guards (`isTopicInFlight`): a running+ * status, a live run marker, or a turn start that holds the short reservation.+ */+const isInFlight = (topic: { metadata: ChatTopicMetadata | null; status: string | null }) =>+ topic.status === 'running' ||+ !!topic.metadata?.runningOperation ||+ hasLiveTaskCallbackReservation(topic.metadata);++/**+ * How many conversations are running in `path` on `deviceId` right now, so the+ * composer can warn before a send switches that directory's branch under them.+ *+ * Spans every member's conversations in a workspace (they share its devices)+ * and the caller's own in personal mode; private and trashed rows count too,+ * since they run on the same checkout. Only a number leaves this function.+ *+ * The SQL narrows to the device and to rows that may be in flight (`status`+ * uses `topics_status_idx`); the exact in-flight rule and the path comparison,+ * which must normalize both sides, run on the few rows that remain. A soft+ * signal: the caller confirms, never blocks, because a stale marker can+ * over-count.+ */+export const countInFlightInDirectory = async (+ ctx: TopicModelContext,+ { deviceId, path }: { deviceId: string; path: string },+): Promise<number> => {+ const target = normalizeDirectoryPath(path);+ if (!target) return 0;++ const scope = ctx.workspaceId+ ? eq(topics.workspaceId, ctx.workspaceId)+ : and(eq(topics.userId, ctx.userId), isNull(topics.workspaceId));++ const rows = await ctx.db+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(+ and(+ scope,+ sql`COALESCE(${topics.metadata} -> 'runningOperation' ->> 'deviceId', ${topics.metadata} ->> 'boundDeviceId') = ${deviceId}`,+ // Key existence, never `-> 'x' IS NOT NULL`: that shape crashes the+ // pg_search planner on bm25-indexed tables (see jsonbNullTest).+ or(+ eq(topics.status, 'running'),+ sql`COALESCE(jsonb_exists(${topics.metadata}, 'runningOperation'), false)`,+ sql`COALESCE(jsonb_exists(${topics.metadata}, 'taskCallbackReservation'), false)`,+ ),+ ),+ );++ return rows.filter((row) => {+ const metadata = row.metadata ?? null;+ if (!isInFlight({ metadata, status: row.status })) return false;+ if (getTopicDeviceId(metadata) !== deviceId) return false;+ return getTopicRunDirectories(metadata).some((dir) => normalizeDirectoryPath(dir) === target);+ }).length;+};diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.tsindex 496785bde62..d77280ea7f9 100644--- a/packages/database/src/models/topic/index.ts+++ b/packages/database/src/models/topic/index.ts@@ -5,6 +5,7 @@ import { createTopicModelContext } from './context';import * as create from './create';import * as remove from './delete';import * as find from './find';+import * as inFlight from './inFlight';import * as list from './list';import * as memoryExtractor from './memoryExtractor';import * as runningOperation from './runningOperation';@@ -136,6 +137,7 @@ export class TopicModel {rank = this.withContext(find.rank);queryRecent = this.withContext(find.queryRecent);getCronTopicsGroupedByCronJob = this.withContext(find.getCronTopicsGroupedByCronJob);+ countInFlightInDirectory = this.withContext(inFlight.countInFlightInDirectory);// **************** Agent Share (visitor-scoped) *************** //diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 2ac033265cf..b97132538c3 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -10,6 +10,7 @@ import type {UserSettings,WidgetDryRunGrant,} from '@lobechat/types';+import { applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { TRPCError } from '@trpc/server';import dayjs from 'dayjs';@@ -575,6 +576,17 @@ export class UserModel {};})) ?? [];+ /**+ * Personal-mode "New worktree" switch for one directory; returns the stored+ * list. Same row lock as every other preference writer, and the cap is+ * applied here (see `applyWorktreeModeDir`).+ */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ (await this.mutatePreference((prev) => {+ const worktreeModeDirs = applyWorktreeModeDir(prev.worktreeModeDirs, key, enabled);+ return { next: { ...prev, worktreeModeDirs }, result: worktreeModeDirs };+ })) ?? [];+/*** Normalize unique user fields so empty strings become null, keeping unique constraints safe.*/diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.tsindex 23bac729a16..bc17316efdc 100644--- a/packages/database/src/models/workspaceUserSettings.ts+++ b/packages/database/src/models/workspaceUserSettings.ts@@ -1,4 +1,5 @@import type { WorkspaceUserPreference } from '@lobechat/types';+import { applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { and, eq } from 'drizzle-orm';@@ -149,4 +150,35 @@ export class WorkspaceUserSettingsModel {.returning();return row;};++ /**+ * Turn the composer's "New worktree" switch on or off for one directory and+ * return the stored list. Read → apply → write under the row lock, so the+ * cap (see `applyWorktreeModeDir`) is enforced here rather than trusted from a+ * client copy that may be stale.+ */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ this.db.transaction(async (trx) => {+ const [row] = await trx+ .select({ preference: workspaceUserSettings.preference })+ .from(workspaceUserSettings)+ .where(+ and(+ eq(workspaceUserSettings.workspaceId, this.workspaceId),+ eq(workspaceUserSettings.userId, this.userId),+ ),+ )+ .for('update');+ const current = row?.preference ?? {};+ const worktreeModeDirs = applyWorktreeModeDir(current.worktreeModeDirs, key, enabled);+ const next: WorkspaceUserPreference = { ...current, worktreeModeDirs };+ await trx+ .insert(workspaceUserSettings)+ .values({ preference: next, userId: this.userId, workspaceId: this.workspaceId })+ .onConflictDoUpdate({+ set: { preference: next, updatedAt: new Date() },+ target: [workspaceUserSettings.workspaceId, workspaceUserSettings.userId],+ });+ return worktreeModeDirs;+ });}diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex bd94542d8c4..2021b796a00 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -424,7 +424,8 @@ export const executeDeviceRpc = async (}case 'getGitAheadBehind': {- return getGitAheadBehind((params as { path: string }).path);+ const { branch, path } = params as { branch?: string; path: string };+ return getGitAheadBehind(path, { branch });}case 'listGitBranches': {@@ -440,7 +441,9 @@ export const executeDeviceRpc = async (}case 'checkoutGitBranch': {- return checkoutGitBranch(params as { branch: string; create?: boolean; path: string });+ return checkoutGitBranch(+ params as { branch: string; create?: boolean; path: string; startPoint?: string },+ );}case 'renameGitBranch': {@@ -456,15 +459,17 @@ export const executeDeviceRpc = async (}case 'addGitWorktree': {- return addGitWorktree(params as { branch: string; path: string; worktreePath: string });+ return addGitWorktree(+ params as { branch: string; path: string; startPoint?: string; worktreePath: string },+ );}case 'pullGitBranch': {- return pullGitBranch(params as { path: string });+ return pullGitBranch(params as { branch?: string; path: string });}case 'pushGitBranch': {- return pushGitBranch(params as { path: string });+ return pushGitBranch(params as { branch?: string; path: string });}case 'revertGitFile': {diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.tsindex bed692bf7c7..f604e6b6dec 100644--- a/packages/electron-client-ipc/src/types/git.ts+++ b/packages/electron-client-ipc/src/types/git.ts@@ -319,6 +319,8 @@ export interface GitBranchDiffPatches {export interface GitCheckoutResult {error?: string;+ /** Echo of the start point the new branch was cut from, when one was requested. */+ startPoint?: string;success: boolean;}@@ -344,19 +346,31 @@ export interface GitRemoveWorktreeResult {export interface GitAddWorktreeResult {error?: string;+ /** Echo of the start point the worktree's branch was cut from, when one was requested. */+ startPoint?: string;success: boolean;/** Absolute path of the created worktree, echoed back so the UI can switch to it. */worktreePath?: string;}+/** Why a named-branch pull was refused before git ran. */+export type GitSyncRefusal = 'checkedOutElsewhere' | 'noUpstream';+export interface GitPullResult {+ /** Echo of the named branch that was pulled; absent for a HEAD pull. */+ branch?: string;error?: string;/** True when `git pull` reported the branch was already up-to-date */noop?: boolean;+ reason?: GitSyncRefusal;success: boolean;+ /** The worktree holding the branch, for `reason: 'checkedOutElsewhere'`. */+ worktreePath?: string;}export interface GitPushResult {+ /** Echo of the named branch that was pushed; absent for a HEAD push. */+ branch?: string;error?: string;/** True when `git push` reported everything is already up-to-date */noop?: boolean;@@ -368,6 +382,8 @@ export interface GitAheadBehind {ahead: number;/** Commits in upstream not in HEAD — pull count */behind: number;+ /** Echo of the named branch the counts describe; absent when they describe HEAD. */+ branch?: string;/** True when the branch has an upstream tracking ref configured */hasUpstream: boolean;/**diff --git a/packages/local-file-shell/src/git/__tests__/branches.test.ts b/packages/local-file-shell/src/git/__tests__/branches.test.tsindex 82f9a97224a..9437af966f8 100644--- a/packages/local-file-shell/src/git/__tests__/branches.test.ts+++ b/packages/local-file-shell/src/git/__tests__/branches.test.ts@@ -11,12 +11,11 @@ import {deleteGitBranch,listGitBranches,listGitRemoteBranches,- pullGitBranch,- pushGitBranch,renameGitBranch,revertGitFile,} from '../branches';import { getGitAheadBehind, getGitBranch } from '../info';+import { pullGitBranch, pushGitBranch } from '../sync';import { getGitBranchDiff, getGitWorkingTreeFiles, getGitWorkingTreePatches } from '../workingTree';import { listGitWorktrees, parseGitWorktreeList, removeGitWorktree } from '../worktrees';diff --git a/packages/local-file-shell/src/git/__tests__/namedBranch.test.ts b/packages/local-file-shell/src/git/__tests__/namedBranch.test.tsnew file mode 100644index 00000000000..6c043bf2725--- /dev/null+++ b/packages/local-file-shell/src/git/__tests__/namedBranch.test.ts@@ -0,0 +1,278 @@+import { execFileSync } from 'node:child_process';+import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { checkoutGitBranch, isInvalidBranchRef } from '../branches';+import { getGitAheadBehind, getGitBranch } from '../info';+import { pullGitBranch, pushGitBranch } from '../sync';+import { addGitWorktree } from '../worktrees';++const git = (cwd: string, ...args: string[]): string =>+ execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();++const commit = async (dir: string, file: string, body: string) => {+ await writeFile(path.join(dir, file), body);+ git(dir, 'add', file);+ git(dir, 'commit', '-m', `edit ${file}`);+};++const configure = (dir: string) => {+ git(dir, 'config', 'user.email', '[email protected]');+ git(dir, 'config', 'user.name', 'Test');+ git(dir, 'config', 'commit.gpgsign', 'false');+};++const cleanup: string[] = [];+const tempDir = async (prefix: string) => {+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), prefix)));+ cleanup.push(dir);+ return dir;+};++/**+ * A working repo on `main` that tracks a bare `origin`, plus a `feature` branch+ * (also tracking origin) one commit ahead of `main`.+ */+let repo: string;+let origin: string;++beforeEach(async () => {+ origin = await tempDir('lfs-origin-');+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init', '--bare', origin]);+ repo = await tempDir('lfs-repo-');+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: repo });+ configure(repo);+ await commit(repo, 'a.txt', 'hello\n');+ git(repo, 'remote', 'add', 'origin', origin);+ git(repo, 'push', '-u', 'origin', 'main');+ git(repo, 'checkout', '-b', 'feature');+ await commit(repo, 'b.txt', 'feature\n');+ git(repo, 'push', '-u', 'origin', 'feature');+ git(repo, 'checkout', 'main');+});++afterEach(async () => {+ await Promise.all(cleanup.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));+});++/** Advance `branch` on origin by one commit from a throwaway clone. */+const advanceOnOrigin = async (branch: string) => {+ const clone = await tempDir('lfs-clone-');+ execFileSync('git', ['clone', '--branch', branch, origin, clone]);+ configure(clone);+ await commit(clone, 'c.txt', `${branch} upstream\n`);+ git(clone, 'push', 'origin', branch);+};++describe('isInvalidBranchRef', () => {+ it('rejects reflog / upstream syntax', () => {+ expect(isInvalidBranchRef('main@{upstream}')).toBe(true);+ expect(isInvalidBranchRef('lobehub/quiet-hill')).toBe(false);+ });+});++describe('checkoutGitBranch with a start point', () => {+ it('cuts the new branch from the start point, not HEAD, and echoes it', async () => {+ const result = await checkoutGitBranch({+ branch: 'lobehub/x',+ create: true,+ path: repo,+ startPoint: 'feature',+ });++ expect(result).toEqual({ startPoint: 'feature', success: true });+ expect(await getGitBranch(repo)).toMatchObject({ branch: 'lobehub/x' });+ expect(git(repo, 'rev-parse', 'HEAD')).toBe(git(repo, 'rev-parse', 'feature'));+ });++ it('carries uncommitted changes across, like a plain git checkout', async () => {+ await writeFile(path.join(repo, 'a.txt'), 'dirty\n');+ const result = await checkoutGitBranch({+ branch: 'lobehub/y',+ create: true,+ path: repo,+ startPoint: 'feature',+ });++ expect(result.success).toBe(true);+ expect(git(repo, 'status', '--porcelain')).toContain('a.txt');+ });++ it('rejects a start point without a new branch', async () => {+ const result = await checkoutGitBranch({ branch: 'feature', path: repo, startPoint: 'main' });+ expect(result).toEqual({ error: 'A start point needs a new branch', success: false });+ });++ it('echoes nothing when no start point was asked for', async () => {+ expect(await checkoutGitBranch({ branch: 'z', create: true, path: repo })).toEqual({+ success: true,+ });+ });+});++describe('a start point sharing its name with a tag', () => {+ // The picker hands over a LOCAL branch; a same-named tag must not make git+ // refuse it as ambiguous.+ it('reads the local branch for both the checkout and the worktree', async () => {+ git(repo, 'tag', 'feature', 'main');++ expect(+ await checkoutGitBranch({ branch: 'mine', create: true, path: repo, startPoint: 'feature' }),+ ).toEqual({ startPoint: 'feature', success: true });+ expect(git(repo, 'rev-parse', 'HEAD')).toBe(git(repo, 'rev-parse', 'refs/heads/feature'));++ git(repo, 'checkout', 'main');+ const worktreePath = path.join(await tempDir('lfs-wt-'), 'tagged');+ const result = await addGitWorktree({+ branch: 'lobehub/tagged',+ path: repo,+ startPoint: 'feature',+ worktreePath,+ });+ expect(result).toMatchObject({ startPoint: 'feature', success: true });+ expect(git(worktreePath, 'rev-parse', 'HEAD')).toBe(+ git(repo, 'rev-parse', 'refs/heads/feature'),+ );+ });++ it('still takes a commit sha as given', async () => {+ const sha = git(repo, 'rev-parse', 'feature');+ expect(+ await checkoutGitBranch({ branch: 'from-sha', create: true, path: repo, startPoint: sha }),+ ).toEqual({ startPoint: sha, success: true });+ });+});++describe('addGitWorktree with a start point', () => {+ it('forks the worktree branch from the start point and echoes it', async () => {+ const worktreePath = path.join(await tempDir('lfs-wt-'), 'quiet-hill');+ const result = await addGitWorktree({+ branch: 'lobehub/quiet-hill',+ path: repo,+ startPoint: 'feature',+ worktreePath,+ });++ expect(result).toEqual({ startPoint: 'feature', success: true, worktreePath });+ expect(git(worktreePath, 'rev-parse', 'HEAD')).toBe(git(repo, 'rev-parse', 'feature'));+ // The source checkout is untouched.+ expect(await getGitBranch(repo)).toMatchObject({ branch: 'main' });+ });+});++describe('getGitAheadBehind for a named branch', () => {+ it('counts the named branch against its own upstream while HEAD is elsewhere', async () => {+ await advanceOnOrigin('feature');+ // HEAD (main) is level with origin/main; feature is one behind origin/feature.+ expect(await getGitAheadBehind(repo, { branch: 'feature' })).toMatchObject({+ ahead: 0,+ behind: 1,+ branch: 'feature',+ hasUpstream: true,+ pushTarget: 'origin/feature',+ pushTargetExists: true,+ upstream: 'origin/feature',+ });+ expect(await getGitAheadBehind(repo)).toMatchObject({ ahead: 0, behind: 0 });+ });++ it('echoes the branch even when it tracks nothing', async () => {+ git(repo, 'branch', 'local-only');+ expect(await getGitAheadBehind(repo, { branch: 'local-only' })).toEqual({+ ahead: 0,+ behind: 0,+ branch: 'local-only',+ hasUpstream: false,+ });+ });+});++describe('pullGitBranch for a named branch', () => {+ it('fast-forwards a branch that is not checked out, without switching to it', async () => {+ await advanceOnOrigin('feature');+ git(repo, 'fetch', 'origin');+ const result = await pullGitBranch({ branch: 'feature', path: repo });++ expect(result).toEqual({ branch: 'feature', noop: false, success: true });+ expect(git(repo, 'rev-parse', 'feature')).toBe(git(repo, 'rev-parse', 'origin/feature'));+ expect(await getGitBranch(repo)).toMatchObject({ branch: 'main' });+ });++ it('reports a no-op when the branch is already level', async () => {+ expect(await pullGitBranch({ branch: 'feature', path: repo })).toEqual({+ branch: 'feature',+ noop: true,+ success: true,+ });+ });++ it('pulls the current branch the normal way', async () => {+ await advanceOnOrigin('main');+ const result = await pullGitBranch({ branch: 'main', path: repo });+ expect(result).toMatchObject({ branch: 'main', noop: false, success: true });+ });++ it('refuses a branch another worktree has checked out, naming that worktree', async () => {+ const worktreePath = path.join(await tempDir('lfs-wt-'), 'feature');+ git(repo, 'worktree', 'add', worktreePath, 'feature');+ const result = await pullGitBranch({ branch: 'feature', path: repo });++ expect(result).toMatchObject({+ branch: 'feature',+ reason: 'checkedOutElsewhere',+ success: false,+ });+ expect(await realpath(result.worktreePath!)).toBe(await realpath(worktreePath));+ });++ it('refuses a branch with no upstream', async () => {+ git(repo, 'branch', 'local-only');+ expect(await pullGitBranch({ branch: 'local-only', path: repo })).toMatchObject({+ branch: 'local-only',+ reason: 'noUpstream',+ success: false,+ });+ });++ it('rejects a non-fast-forward instead of rewriting the branch', async () => {+ await advanceOnOrigin('feature');+ git(repo, 'checkout', 'feature');+ await commit(repo, 'd.txt', 'diverged\n');+ git(repo, 'checkout', 'main');+ const local = git(repo, 'rev-parse', 'feature');++ const result = await pullGitBranch({ branch: 'feature', path: repo });+ expect(result).toMatchObject({ branch: 'feature', success: false });+ expect(git(repo, 'rev-parse', 'feature')).toBe(local);+ });+});++describe('pushGitBranch for a named branch', () => {+ it('pushes the named branch while HEAD is on another one', async () => {+ git(repo, 'checkout', 'feature');+ await commit(repo, 'e.txt', 'new work\n');+ git(repo, 'checkout', 'main');++ const result = await pushGitBranch({ branch: 'feature', path: repo });+ expect(result).toEqual({ branch: 'feature', noop: false, success: true });+ expect(git(origin, 'rev-parse', 'feature')).toBe(git(repo, 'rev-parse', 'feature'));+ });++ it('pushes a branch that shares its name with a tag', async () => {+ git(repo, 'tag', 'feature', 'main');+ git(repo, 'checkout', 'feature');+ await commit(repo, 'f.txt', 'tagged name\n');+ git(repo, 'checkout', 'main');++ expect(await pushGitBranch({ branch: 'feature', path: repo })).toMatchObject({+ branch: 'feature',+ success: true,+ });+ expect(git(origin, 'rev-parse', 'refs/heads/feature')).toBe(+ git(repo, 'rev-parse', 'refs/heads/feature'),+ );+ });+});diff --git a/packages/local-file-shell/src/git/branches.ts b/packages/local-file-shell/src/git/branches.tsindex 8daad4df76a..09cf77e7bf2 100644--- a/packages/local-file-shell/src/git/branches.ts+++ b/packages/local-file-shell/src/git/branches.ts@@ -9,8 +9,6 @@ import type {GitCheckoutResult,GitDeleteBranchResult,GitFileRevertResult,- GitPullResult,- GitPushResult,GitRemoteBranchListItem,GitRenameBranchResult,} from './types';@@ -20,7 +18,29 @@ const execFileAsync = promisify(execFile);/** Reject obviously invalid branch refs early to avoid a confusing git error. */export const isInvalidBranchRef = (name: string): boolean =>- /[\s~^:?*[\\]/.test(name) || name.startsWith('-') || name.includes('..');+ /[\s~^:?*[\\]/.test(name) ||+ name.startsWith('-') ||+ name.includes('..') ||+ // `<ref>@{…}` is reflog / upstream syntax, never part of a branch name — and+ // the ahead/behind read appends `@{upstream}` to the name it is given.+ name.includes('@{');++/**+ * A start point as git should read it: `refs/heads/<name>` when a local branch+ * of that name exists, so a tag (or remote ref) sharing the name cannot make+ * it ambiguous; anything else (a commit sha) as given.+ */+export const qualifyStartPoint = async (dirPath: string, startPoint: string): Promise<string> => {+ try {+ await execFileAsync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${startPoint}`], {+ cwd: dirPath,+ timeout: 5000,+ });+ return `refs/heads/${startPoint}`;+ } catch {+ return startPoint;+ }+};/*** List local git branches ordered by most recent commit. `current` is true for@@ -109,24 +129,43 @@ export const listGitRemoteBranches = async (* Check out (or create + check out) a branch. Relies on git itself to reject* unsafe checkouts (dirty tree, non-fast-forward, etc.) and surfaces git's* stderr so the UI can display a meaningful error.+ *+ * `startPoint` (with `create`) cuts the new branch from that branch instead of+ * HEAD — `git checkout -b <branch> <startPoint>` — and is echoed back on success+ * so a caller can tell this device honoured it (an older one ignores the field).+ * Uncommitted changes travel with the checkout under git's own rules: no stash,+ * no force, and a conflicting change makes git refuse.*/export const checkoutGitBranch = async (payload: {branch: string;create?: boolean;path: string;+ startPoint?: string;}): Promise<GitCheckoutResult> => {- const { path: dirPath, branch, create } = payload;+ const { path: dirPath, branch, create, startPoint } = payload;if (!branch?.trim()) {return { error: 'Branch name is required', success: false };}if (isInvalidBranchRef(branch)) {return { error: `Invalid branch name: ${branch}`, success: false };}+ if (startPoint !== undefined) {+ if (!create) return { error: 'A start point needs a new branch', success: false };+ if (!startPoint.trim() || isInvalidBranchRef(startPoint))+ return { error: `Invalid start point: ${startPoint}`, success: false };+ }- const args = create ? ['checkout', '-b', branch] : ['checkout', branch];+ const args = create+ ? [+ 'checkout',+ '-b',+ branch,+ ...(startPoint ? [await qualifyStartPoint(dirPath, startPoint)] : []),+ ]+ : ['checkout', branch];try {await execFileAsync('git', args, { cwd: dirPath, timeout: 10_000 });- return { success: true };+ return startPoint ? { startPoint, success: true } : { success: true };} catch (error: any) {const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();log.debug('[checkoutGitBranch] failed', { args, stderr });@@ -189,48 +228,6 @@ export const deleteGitBranch = async (payload: {}};-/**- * Pull the current branch's upstream via fast-forward only. `--ff-only` avoids- * accidental merge commits when the local branch has diverged.- */-export const pullGitBranch = async (payload: { path: string }): Promise<GitPullResult> => {- const { path: dirPath } = payload;- try {- const { stdout } = await execFileAsync('git', ['pull', '--ff-only'], {- cwd: dirPath,- timeout: 60_000,- });- const noop = /Already up to date/i.test(stdout);- return { noop, success: true };- } catch (error: any) {- const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();- log.debug('[pullGitBranch] failed', { stderr });- return { error: stderr || 'git pull failed', success: false };- }-};--/**- * Push the current branch to its same-named remote on `origin`. Uses- * `git push -u origin HEAD` so the action works even when the local branch name- * differs from the configured upstream.- */-export const pushGitBranch = async (payload: { path: string }): Promise<GitPushResult> => {- const { path: dirPath } = payload;- try {- const { stderr } = await execFileAsync('git', ['push', '-u', 'origin', 'HEAD'], {- cwd: dirPath,- timeout: 60_000,- });- // git push writes progress/status to stderr even on success- const noop = /Everything up-to-date/i.test(stderr);- return { noop, success: true };- } catch (error: any) {- const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();- log.debug('[pushGitBranch] failed', { stderr });- return { error: stderr || 'git push failed', success: false };- }-};-/*** Revert a single working-tree change. Mirrors "Discard changes" in GitHub* Desktop / VSCode SCM: restore the file to its HEAD state, dropping anydiff --git a/packages/local-file-shell/src/git/index.ts b/packages/local-file-shell/src/git/index.tsindex dc82eb35276..a005f5982a2 100644--- a/packages/local-file-shell/src/git/index.ts+++ b/packages/local-file-shell/src/git/index.ts@@ -2,6 +2,7 @@ export * from './branches';export * from './info';export * from './pullRequest';export * from './repoType';+export * from './sync';export * from './types';export * from './upstream';export * from './workingTree';diff --git a/packages/local-file-shell/src/git/info.ts b/packages/local-file-shell/src/git/info.tsindex eb5e908430a..cb41cf19a49 100644--- a/packages/local-file-shell/src/git/info.ts+++ b/packages/local-file-shell/src/git/info.ts@@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises';import { promisify } from 'node:util';import { createLogger } from '../logger';+import { isInvalidBranchRef } from './branches';import { resolveGitDir } from './repoType';import type {DeviceGitInfo,@@ -353,11 +354,25 @@ export const getGitWorkingTreeStatus = async (dirPath: string): Promise<GitWorki};/**- * Count commits HEAD is ahead/behind its upstream. Does a best-effort `git fetch`- * first; swallows fetch failures (offline / no creds) and computes against cached- * refs. Returns `hasUpstream: false` when no upstream is configured.+ * Count commits a branch is ahead/behind its upstream. Does a best-effort+ * `git fetch` first; swallows fetch failures (offline / no creds) and computes+ * against cached refs. Returns `hasUpstream: false` when no upstream is+ * configured.+ *+ * Without `branch` this describes HEAD (`@{u}...HEAD`). With one it describes+ * that local branch wherever HEAD is (`<branch>@{upstream}...refs/heads/<branch>`)+ * and echoes the branch back, so a caller can tell an older device — which+ * ignores the option and counts HEAD — from one that answered for the branch.*/-export const getGitAheadBehind = async (dirPath: string): Promise<GitAheadBehind> => {+export const getGitAheadBehind = async (+ dirPath: string,+ options: { branch?: string } = {},+): Promise<GitAheadBehind> => {+ const { branch: requested } = options;+ const echo = requested === undefined ? {} : { branch: requested };+ const none: GitAheadBehind = { ahead: 0, behind: 0, hasUpstream: false, ...echo };+ if (requested !== undefined && (!requested.trim() || isInvalidBranchRef(requested))) return none;+try {await execFileAsync('git', ['fetch', '--no-tags', '--quiet', 'origin'], {cwd: dirPath,@@ -369,52 +384,66 @@ export const getGitAheadBehind = async (dirPath: string): Promise<GitAheadBehindtry {const { stdout: upstreamOut } = await execFileAsync('git',- ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],+ [+ 'rev-parse',+ '--abbrev-ref',+ '--symbolic-full-name',+ requested ? `${requested}@{upstream}` : '@{u}',+ ],{ cwd: dirPath, timeout: 5000 },);const upstream = upstreamOut.trim();- if (!upstream) return { ahead: 0, behind: 0, hasUpstream: false };+ if (!upstream) return none;const { stdout } = await execFileAsync('git',- ['rev-list', '--left-right', '--count', `${upstream}...HEAD`],+ [+ 'rev-list',+ '--left-right',+ '--count',+ `${upstream}...${requested ? `refs/heads/${requested}` : 'HEAD'}`,+ ],{ cwd: dirPath, timeout: 5000 },);const [behindStr, aheadStr] = stdout.trim().split(/\s+/);const behind = Number.parseInt(behindStr ?? '0', 10) || 0;const ahead = Number.parseInt(aheadStr ?? '0', 10) || 0;- // `git push -u origin HEAD` always targets origin/<current-branch-name>,- // which may differ from upstream (the branched-off-canary case).+ // The push action targets origin/<branch-name> (`git push -u origin HEAD`,+ // or `… origin <branch>` for a named branch), which may differ from+ // upstream (the branched-off-canary case).let pushTarget: string | undefined;let pushTargetExists = false;- try {- const { stdout: branchOut } = await execFileAsync(- 'git',- ['symbolic-ref', '--short', 'HEAD'],- { cwd: dirPath, timeout: 5000 },- );- const branch = branchOut.trim();- if (branch) {- pushTarget = `origin/${branch}`;- try {- await execFileAsync(- 'git',- ['rev-parse', '--verify', '--quiet', `refs/remotes/${pushTarget}`],- { cwd: dirPath, timeout: 5000 },- );- pushTargetExists = true;- } catch {- pushTargetExists = false;- }+ let branch = requested;+ if (!branch) {+ try {+ const { stdout: branchOut } = await execFileAsync(+ 'git',+ ['symbolic-ref', '--short', 'HEAD'],+ { cwd: dirPath, timeout: 5000 },+ );+ branch = branchOut.trim() || undefined;+ } catch {+ // detached HEAD — leave pushTarget undefined+ }+ }+ if (branch) {+ pushTarget = `origin/${branch}`;+ try {+ await execFileAsync(+ 'git',+ ['rev-parse', '--verify', '--quiet', `refs/remotes/${pushTarget}`],+ { cwd: dirPath, timeout: 5000 },+ );+ pushTargetExists = true;+ } catch {+ pushTargetExists = false;}- } catch {- // detached HEAD — leave pushTarget undefined}- return { ahead, behind, hasUpstream: true, pushTarget, pushTargetExists, upstream };+ return { ahead, behind, hasUpstream: true, pushTarget, pushTargetExists, upstream, ...echo };} catch {- return { ahead: 0, behind: 0, hasUpstream: false };+ return none;}};diff --git a/packages/local-file-shell/src/git/sync.ts b/packages/local-file-shell/src/git/sync.tsnew file mode 100644index 00000000000..630ca1dde70--- /dev/null+++ b/packages/local-file-shell/src/git/sync.ts@@ -0,0 +1,170 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++import { createLogger } from '../logger';+import { isInvalidBranchRef } from './branches';+import type { GitPullResult, GitPushResult } from './types';+import { parseGitWorktreeList } from './worktrees';++const log = createLogger('local-file-shell:git');+const execFileAsync = promisify(execFile);++const stderrOf = (error: any, fallback: string): string =>+ (error?.stderr ?? error?.message ?? '').toString().trim() || fallback;++const readGit = async (args: string[], cwd: string): Promise<string | undefined> => {+ try {+ const { stdout } = await execFileAsync('git', args, { cwd, timeout: 5000 });+ return stdout.trim();+ } catch {+ return undefined;+ }+};++/** The branch HEAD is on, or undefined when detached / unreadable. */+const readCurrentBranch = (dirPath: string) =>+ readGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], dirPath);++const readBranchSha = (dirPath: string, branch: string) =>+ readGit(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], dirPath);++/** The worktree that has `branch` checked out, other than `dirPath`'s own. */+const findOtherWorktreeHolding = async (+ dirPath: string,+ branch: string,+): Promise<string | undefined> => {+ const stdout = await readGit(['worktree', 'list', '--porcelain', '-z'], dirPath);+ if (!stdout) return undefined;+ return parseGitWorktreeList(stdout).find(+ (worktree) => worktree.branch === branch && !worktree.bare && !worktree.prunable,+ )?.path;+};++/** `{ remote, ref }` the branch pulls from, e.g. `{ remote: 'origin', ref: 'refs/heads/main' }`. */+const readUpstream = async (+ dirPath: string,+ branch: string,+): Promise<{ ref: string; remote: string } | undefined> => {+ const stdout = await readGit(+ [+ 'for-each-ref',+ '--format=%(upstream:remotename)%09%(upstream:remoteref)',+ `refs/heads/${branch}`,+ ],+ dirPath,+ );+ const [remote, ref] = (stdout?.split('\n')[0] ?? '').split('\t');+ return remote && ref ? { ref, remote } : undefined;+};++const pullHead = async (dirPath: string): Promise<GitPullResult> => {+ try {+ const { stdout } = await execFileAsync('git', ['pull', '--ff-only'], {+ cwd: dirPath,+ timeout: 60_000,+ });+ const noop = /Already up to date/i.test(stdout);+ return { noop, success: true };+ } catch (error: any) {+ const stderr = stderrOf(error, 'git pull failed');+ log.debug('[pullGitBranch] failed', { stderr });+ return { error: stderr, success: false };+ }+};++/**+ * Fast-forward a branch from its upstream.+ *+ * Without `branch` this is the historical HEAD pull (`git pull --ff-only`).+ * With one, the named branch is updated without switching to it:+ * `git fetch <remote> <upstream>:<branch>` — a refspec without `+` only ever+ * fast-forwards. That is refused by git for a branch another worktree has+ * checked out, so that case is reported up front as `checkedOutElsewhere`+ * instead of git's terse refusal. A branch HEAD is on is pulled the normal way.+ * The branch is echoed back so a caller can tell an older device, which+ * ignores the field and pulls HEAD, from one that honoured it.+ */+export const pullGitBranch = async (payload: {+ branch?: string;+ path: string;+}): Promise<GitPullResult> => {+ const { path: dirPath, branch } = payload;+ if (branch === undefined) return pullHead(dirPath);+ if (!branch.trim() || isInvalidBranchRef(branch))+ return { error: `Invalid branch name: ${branch}`, success: false };++ if ((await readCurrentBranch(dirPath)) === branch) {+ return { ...(await pullHead(dirPath)), branch };+ }++ const holder = await findOtherWorktreeHolding(dirPath, branch);+ if (holder) {+ return {+ branch,+ error: `Branch ${branch} is checked out at ${holder}; pull it there`,+ reason: 'checkedOutElsewhere',+ success: false,+ worktreePath: holder,+ };+ }++ const upstream = await readUpstream(dirPath, branch);+ if (!upstream) {+ return {+ branch,+ error: `Branch ${branch} has no upstream to pull from`,+ reason: 'noUpstream',+ success: false,+ };+ }++ const before = await readBranchSha(dirPath, branch);+ try {+ await execFileAsync(+ 'git',+ ['fetch', '--no-tags', upstream.remote, `${upstream.ref}:refs/heads/${branch}`],+ { cwd: dirPath, timeout: 60_000 },+ );+ } catch (error: any) {+ const stderr = stderrOf(error, 'git fetch failed');+ log.debug('[pullGitBranch] fetch failed', { branch, stderr });+ return { branch, error: stderr, success: false };+ }+ const after = await readBranchSha(dirPath, branch);+ return { branch, noop: !!before && before === after, success: true };+};++/**+ * Push a branch to its same-named remote on `origin`.+ *+ * Without `branch` this is the historical `git push -u origin HEAD`, which works+ * even when the local branch name differs from the configured upstream. With+ * one, `git push -u origin <branch>` pushes that branch from wherever HEAD is —+ * pushing never needs a checkout. The branch is echoed back on success, like+ * {@link pullGitBranch}.+ */+export const pushGitBranch = async (payload: {+ branch?: string;+ path: string;+}): Promise<GitPushResult> => {+ const { path: dirPath, branch } = payload;+ if (branch !== undefined && (!branch.trim() || isInvalidBranchRef(branch)))+ return { error: `Invalid branch name: ${branch}`, success: false };++ // A named branch is spelled as its full ref: a tag sharing the name would+ // otherwise make the refspec match more than one source.+ const refspec = branch ? `refs/heads/${branch}` : 'HEAD';+ try {+ const { stderr } = await execFileAsync('git', ['push', '-u', 'origin', refspec], {+ cwd: dirPath,+ timeout: 60_000,+ });+ // git push writes progress/status to stderr even on success+ const noop = /Everything up-to-date/i.test(stderr);+ return branch ? { branch, noop, success: true } : { noop, success: true };+ } catch (error: any) {+ const stderr = stderrOf(error, 'git push failed');+ log.debug('[pushGitBranch] failed', { branch, stderr });+ return branch ? { branch, error: stderr, success: false } : { error: stderr, success: false };+ }+};diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.tsindex 0f1442f40ec..a503364966e 100644--- a/packages/local-file-shell/src/git/types.ts+++ b/packages/local-file-shell/src/git/types.ts@@ -183,6 +183,13 @@ export interface GitWorktreeListItem {export interface GitAheadBehind {ahead: number;behind: number;+ /**+ * The branch the counts describe, echoed back when the caller asked about a+ * named branch rather than HEAD. A device that predates the parameter ignores+ * it and counts HEAD instead, so callers must treat a missing or different+ * echo as "this device cannot answer for that branch".+ */+ branch?: string;hasUpstream: boolean;pushTarget?: string;pushTargetExists?: boolean;@@ -314,6 +321,12 @@ export interface GitBranchDiffPatches {export interface GitCheckoutResult {error?: string;+ /**+ * The start point the new branch was actually cut from, echoed back only when+ * the caller passed one. A device that predates `startPoint` silently forks+ * from HEAD and echoes nothing — callers verify this before trusting the result.+ */+ startPoint?: string;success: boolean;}@@ -339,19 +352,37 @@ export interface GitRemoveWorktreeResult {export interface GitAddWorktreeResult {error?: string;+ /** Echo of the start point the worktree's branch was cut from; see {@link GitCheckoutResult.startPoint}. */+ startPoint?: string;success: boolean;/** Absolute path of the created worktree, echoed back so the UI can switch to it. */worktreePath?: string;}+/**+ * Why a pull / push of a named branch was refused before git ran, so the UI can+ * say it in the user's language instead of relaying git's stderr.+ * - `checkedOutElsewhere`: another worktree has the branch checked out, and git+ * refuses to fast-forward a ref under a working tree it does not own.+ * - `noUpstream`: the branch tracks nothing, so there is nothing to pull from.+ */+export type GitSyncRefusal = 'checkedOutElsewhere' | 'noUpstream';+export interface GitPullResult {+ /** Echo of the named branch that was pulled; absent for a HEAD pull. */+ branch?: string;error?: string;/** True when `git pull` reported the branch was already up-to-date */noop?: boolean;+ reason?: GitSyncRefusal;success: boolean;+ /** The worktree holding the branch, for `reason: 'checkedOutElsewhere'`. */+ worktreePath?: string;}export interface GitPushResult {+ /** Echo of the named branch that was pushed; absent for a HEAD push. */+ branch?: string;error?: string;/** True when `git push` reported everything is already up-to-date */noop?: boolean;diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.tsindex b3d3ba434df..ba71c6e461f 100644--- a/packages/local-file-shell/src/git/worktrees.ts+++ b/packages/local-file-shell/src/git/worktrees.ts@@ -4,7 +4,7 @@ import { mkdir, realpath } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';-import { isInvalidBranchRef } from './branches';+import { isInvalidBranchRef, qualifyStartPoint } from './branches';import { getGitWorkingTreeStatus } from './info';import type {GitAddWorktreeResult,@@ -171,7 +171,9 @@ export const removeGitWorktree = async (payload: {/*** Add a linked worktree checked out on a fresh branch, mirroring the branch* switcher's "create branch" flow (`git worktree add -b <branch> <path>`). The- * new branch forks from the repo's current HEAD; the caller supplies the target+ * new branch forks from `startPoint` when given (echoed back on success, so a+ * caller can tell an older device that ignored it and forked from HEAD), else+ * from the repo's current HEAD; the caller supplies the target* directory (`deriveWorktreePath`, under `~/.lobehub/worktrees/`). The missing* parent folders are created first, and an existing target or an unwritable* root is reported as such instead of git's generic failure. Returns the@@ -180,14 +182,17 @@ export const removeGitWorktree = async (payload: {export const addGitWorktree = async (payload: {branch: string;path: string;+ startPoint?: string;worktreePath: string;}): Promise<GitAddWorktreeResult> => {- const { path: dirPath, branch, worktreePath } = payload;+ const { path: dirPath, branch, startPoint, worktreePath } = payload;if (!dirPath?.trim()) return { error: 'Working directory is required', success: false };if (!branch?.trim()) return { error: 'Branch name is required', success: false };if (!worktreePath?.trim()) return { error: 'Worktree path is required', success: false };if (isInvalidBranchRef(branch))return { error: `Invalid branch name: ${branch}`, success: false };+ if (startPoint !== undefined && (!startPoint.trim() || isInvalidBranchRef(startPoint)))+ return { error: `Invalid start point: ${startPoint}`, success: false };if (!path.isAbsolute(worktreePath))return { error: `Worktree path must be absolute: ${worktreePath}`, success: false };@@ -203,11 +208,21 @@ export const addGitWorktree = async (payload: {}try {- await execFileAsync('git', ['worktree', 'add', '-b', branch, worktreePath], {- cwd: dirPath,- timeout: 30_000,- });- return { success: true, worktreePath };+ await execFileAsync(+ 'git',+ [+ 'worktree',+ 'add',+ '-b',+ branch,+ worktreePath,+ ...(startPoint ? [await qualifyStartPoint(dirPath, startPoint)] : []),+ ],+ { cwd: dirPath, timeout: 30_000 },+ );+ return startPoint+ ? { startPoint, success: true, worktreePath }+ : { success: true, worktreePath };} catch (error: any) {const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();return { error: stderr || 'git worktree add failed', success: false };diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 639e675d47c..615fce62a9b 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -182,4 +182,38 @@ export default {'workingDirectory.drive.drives.personal': 'Personal drive','workingDirectory.drive.rebuildInPersonal':'Private environment folders ({{names}}) are hidden here. Their owners can rebuild them on their personal drives.',+ // Better Coding Experience: branch picked for a new topic, switched or forked on send.+ 'workingDirectory.branchCheckedOutHere': 'Checked out here',+ 'workingDirectory.deviceOutdated':+ 'The LobeHub app or lh CLI on this device is too old for this. Update it and try again.',+ 'workingDirectory.occupiedBranchConfirm': 'Create branch and send',+ 'workingDirectory.occupiedBranchDesc':+ '{{branch}} is checked out in worktree {{name}}, so it cannot be checked out here. A new branch will be created from it instead.',+ 'workingDirectory.occupiedBranchNameLabel': 'New branch name',+ 'workingDirectory.occupiedBranchTitle': 'Create a branch from {{branch}}',+ 'workingDirectory.preparingSwitch': 'Switching to {{branch}}…',+ 'workingDirectory.preparingWorktree': 'Creating worktree…',+ 'workingDirectory.pullCheckedOutElsewhere':+ '{{branch}} is checked out in worktree {{name}}. Pull it there.',+ 'workingDirectory.pullNoUpstream': '{{branch}} has no upstream branch to pull from',+ 'workingDirectory.scheduleGitUnsupported':+ "Send later can't switch branches or create a worktree. Send now, or pick the current branch and turn off New worktree.",+ 'workingDirectory.switchFailed': 'Could not switch to {{branch}}',+ 'workingDirectory.switchRiskConfirm': 'Switch and send',+ 'workingDirectory.switchRiskRunning_one':+ '{{count}} topic is still running in this directory. Switching the branch will affect it.',+ 'workingDirectory.switchRiskRunning_other':+ '{{count}} topics are still running in this directory. Switching the branch will affect them.',+ 'workingDirectory.switchRiskTitle': 'Switch to {{branch}} and send?',+ 'workingDirectory.switchRiskUncommitted_one': 'Uncommitted changes may be lost ({{count}} file).',+ 'workingDirectory.switchRiskUncommitted_other':+ 'Uncommitted changes may be lost ({{count}} files).',+ 'workingDirectory.worktreeCreateFailed': 'Could not create the worktree',+ 'workingDirectory.worktreeToggle': 'New worktree',+ 'workingDirectory.worktreeToggleOffHint':+ 'Turn on to run this topic in a new branch and worktree',+ 'workingDirectory.worktreeToggleOn': 'New worktree: on',+ 'workingDirectory.worktreeToggleOnHint':+ 'Sending creates a new branch and worktree from {{branch}}; this directory stays as it is',+ 'workingDirectory.worktreeToggleSaveFailed': 'Could not save the New worktree setting',};diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.tsindex 1ea8724226f..6e2661f14b5 100644--- a/packages/types/src/device.test.ts+++ b/packages/types/src/device.test.ts@@ -2,7 +2,12 @@ import { describe, expect, expectTypeOf, it } from 'vitest';import type { z } from 'zod';import type { DeviceActivityOrder, WorkingDirConfig } from './device';-import { deriveWorktreePath, sortDevicesByActivity, workingDirConfigSchema } from './device';+import {+ deriveWorktreePath,+ getWorkingDirSessionPath,+ sortDevicesByActivity,+ workingDirConfigSchema,+} from './device';describe('sortDevicesByActivity', () => {const device = (@@ -233,4 +238,81 @@ describe('deriveWorktreePath', () => {);expect(deriveWorktreePath('/code/lobehub', '')).toBe('/code/lobehub');});++ // Better Coding Experience names the folder after the branch's own name: the+ // app's `lobehub/` namespace is dropped, every other name folds as before.+ describe('stripBranchPrefix', () => {+ const root = () => `/Users/me/.lobehub/worktrees/${key('/code/lobehub')}`;+ const opts = { homeDir: home, stripBranchPrefix: 'lobehub' };++ it('drops a leading namespace segment from the folder name', () => {+ expect(deriveWorktreePath('/code/lobehub', 'lobehub/202611170300-quiet-hill', opts)).toBe(+ `${root()}/202611170300-quiet-hill`,+ );+ });++ it('folds any other branch exactly as without the option', () => {+ expect(deriveWorktreePath('/code/lobehub', 'feat/foo', opts)).toBe(`${root()}/feat-foo`);+ expect(deriveWorktreePath('/code/lobehub', 'lobehubx/foo', opts)).toBe(+ `${root()}/lobehubx-foo`,+ );+ // A branch called exactly the namespace keeps its name.+ expect(deriveWorktreePath('/code/lobehub', 'lobehub', opts)).toBe(`${root()}/lobehub`);+ });++ it('keeps the repo key folder and the traversal guard', () => {+ expect(deriveWorktreePath('/code/lobehub', 'lobehub/../..', opts)).toBe(`${root()}/worktree`);+ });++ it('leaves the result unchanged when not asked to strip', () => {+ expect(deriveWorktreePath('/code/lobehub', 'lobehub/x', { homeDir: home })).toBe(+ `${root()}/lobehub-x`,+ );+ });+ });+});++describe('getWorkingDirSessionPath', () => {+ const worktree = '/Users/me/.lobehub/worktrees/lobehub-0000beef/quiet-hill';++ it('starts in the source repo for a worktree picked mid-conversation', () => {+ expect(+ getWorkingDirSessionPath({ git: { activeWorktree: worktree }, path: '/code/lobehub' }),+ ).toBe('/code/lobehub');+ });++ it('starts in the worktree a topic was born in, even after it moved on', () => {+ const born: WorkingDirConfig = {+ git: { activeWorktree: worktree, autoCreated: true },+ path: '/code/lobehub',+ sessionPath: worktree,+ };+ expect(getWorkingDirSessionPath(born)).toBe(worktree);+ // An agent forked another worktree later: the marker went, the session stays.+ expect(getWorkingDirSessionPath({ ...born, git: { activeWorktree: '/wt/other' } })).toBe(+ worktree,+ );+ });++ it('keeps bare and empty entries as they are', () => {+ expect(getWorkingDirSessionPath('/code/lobehub')).toBe('/code/lobehub');+ expect(getWorkingDirSessionPath(undefined)).toBeUndefined();+ // The ownership marker alone does not move the session.+ expect(getWorkingDirSessionPath({ git: { autoCreated: true }, path: '/code/a' })).toBe(+ '/code/a',+ );+ });++ it('keeps the auto-created marker and session path through the config schema', () => {+ const value = {+ git: {+ activeWorktree: worktree,+ autoCreated: true,+ autoCreatedAt: '2026-11-17T00:00:00.000Z',+ },+ path: '/code/lobehub',+ sessionPath: worktree,+ };+ expect(workingDirConfigSchema.parse(value)).toEqual(value);+ });});diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex bdb87d302a9..83aee2fa8ff 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -1,8 +1,12 @@-import { z } from 'zod';-import type { DeviceLocalFilePreviewFailure } from './deviceFilePreviewFailure';import type { ManagedDevicePhase } from './managedDevice';import type { DeviceClient } from './tool/builtin';+import type {+ DeviceGitLinkedPullRequest,+ DeviceGitLinkedPullRequestLookupStatus,+ DeviceGitUpstreamRef,+ WorkingDirConfig,+} from './workingDir';/** Structured context for an unavailable logical device. */export interface DeviceUnavailableErrorData {@@ -83,115 +87,7 @@ export interface WorkspaceInitResult {skills: ProjectSkillMeta[];}-/**- * A working directory source a device has used. Structured (rather than a bare- * 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 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;-}--/**- * The remote ref a local branch publishes to.- *- * Recorded because the local branch name is a DEVICE-LOCAL label: a worktree- * generates its own (`worktree-feat+foo`), and a push with an explicit refspec- * (`git push origin local:remote`) renames the branch in flight. Carrying the- * local name to another machine — or to `gh pr list --head` — yields nothing.- * The remote ref is the only branch identity that survives leaving this machine,- * which also makes it the handle for re-fetching the topic's output elsewhere.- */-export interface DeviceGitUpstreamRef {- /** Branch name ON the remote (`feat/x`), never the local name. */- branch: string;- /** Remote name (`origin`). */- remote: string;-}--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;- /**- * Remote ref {@link branch} publishes to. Dropped alongside {@link github}- * whenever the branch changes — a stale remote ref would bind the topic to- * another branch's PR, which is worse than having none.- */- upstream?: DeviceGitUpstreamRef;-}--export interface WorkingDirConfig {- /**- * The code environment picked with this folder. Metadata only on a device:- * nothing clones or bootstraps there; the association is kept for later.- */- environmentId?: string;- git?: WorkingDirGitState;- path: string;- repoType?: WorkingDirRepoType;-}--export type WorkingDirConfigValue = string | WorkingDirConfig;--export const getWorkingDirSourcePath = (- entry?: WorkingDirConfigValue | null,-): string | undefined => {- if (!entry) return undefined;- return typeof entry === 'string' ? entry : entry.path;-};--export const getWorkingDirEffectivePath = (- entry?: WorkingDirConfigValue | null,-): string | undefined => {- if (!entry) return undefined;- if (typeof entry === 'string') return entry;- return entry.git?.activeWorktree || entry.path;-};-+export * from './workingDir';export { deriveWorktreePath, type DeriveWorktreePathOptions } from './worktreePath';export interface WorkingDirEntry extends WorkingDirConfig {@@ -610,6 +506,12 @@ export interface DeviceGitWorktreeListItem {export interface DeviceGitAheadBehind {ahead: number;behind: number;+ /**+ * Echo of the named branch the counts describe. Absent when they describe+ * HEAD — and from a device that predates the `branch` parameter, which+ * silently counts HEAD instead.+ */+ branch?: string;hasUpstream: boolean;pushTarget?: string;pushTargetExists?: boolean;@@ -630,18 +532,39 @@ export interface DeviceGitBranchListItem {/** Result of the `checkoutGitBranch` device RPC. Mirrors the desktop shape. */export interface DeviceGitCheckoutResult {error?: string;+ reason?: typeof DEVICE_GIT_OUTDATED;+ /**+ * Echo of the start point the new branch was cut from. A device that predates+ * `startPoint` forks from HEAD and echoes nothing, so a caller that asked for+ * one must treat a missing or different echo as a device to upgrade.+ */+ startPoint?: string;success: boolean;}+/**+ * Set by the client on a git result it rejected because the device did not+ * honour a newer parameter (`startPoint` / `branch`): device RPCs carry no+ * version or capability negotiation, so an older `lh connect` or desktop build+ * ignores the field and silently acts on HEAD instead.+ */+export const DEVICE_GIT_OUTDATED = 'deviceOutdated' as const;+/*** Result of the `pullGitBranch` / `pushGitBranch` device RPCs. Mirrors the* desktop `GitPullResult` / `GitPushResult` (identical shapes).*/export interface DeviceGitSyncResult {+ /** Echo of the named branch that was synced; absent for a HEAD pull / push. */+ branch?: string;error?: string;/** True when git reported the branch was already up-to-date. */noop?: boolean;+ /** Why a named-branch pull was refused before git ran. */+ reason?: 'checkedOutElsewhere' | 'noUpstream' | typeof DEVICE_GIT_OUTDATED;success: boolean;+ /** The worktree holding the branch, for `reason: 'checkedOutElsewhere'`. */+ worktreePath?: string;}/**@@ -748,6 +671,9 @@ export interface DeviceGitRemoveWorktreeResult {/** Result of the `addGitWorktree` device RPC. Mirrors the desktop shape. */export interface DeviceGitAddWorktreeResult {error?: string;+ reason?: typeof DEVICE_GIT_OUTDATED;+ /** Echo of the start point; see {@link DeviceGitCheckoutResult.startPoint}. */+ startPoint?: string;success: boolean;/** Absolute path of the created worktree, echoed back so the UI can switch to it. */worktreePath?: string;@@ -995,48 +921,6 @@ export interface DeviceListClaudeCodeMemoryResult {memoryDir: string;}-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({- environmentId: z.string().max(255).optional(),- 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(),- // Mirrors `WorkingDirGitState.upstream`. A field missing here is not merely- // unvalidated — zod strips it, so it would never survive a write.- upstream: z- .object({- branch: z.string(),- remote: z.string(),- })- .optional(),- })- .optional(),- path: z.string(),- repoType: z.enum(['git', 'github']).optional(),-});-/** One TCP port a device is listening on that a tunnel can reach. */export interface DeviceListeningPort {command?: string;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex d288ea37112..9aedd4ae2a1 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -107,4 +107,5 @@ export * from './trace';export * from './understanding';export * from './userMemory';export * from './util';+export * from './worktreeMode';export * from './zustand';diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex 34fb7fbe90c..a50a8ef14a3 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -2,6 +2,7 @@ import { z } from 'zod';import type { UploadFileItem } from '../../files';import type { MessageSemanticSearchChunk } from '../../rag';+import type { WorkingDirConfig } from '../../workingDir';import type { ChatMessageError } from '../common/base';import { ChatMessageErrorSchema } from '../common/base';import type {@@ -158,6 +159,12 @@ export interface SendMessageParams {*/metadata?: Record<string, any>;+ /**+ * The working directory a topic this send creates runs in, prepared by the+ * composer right before sending (a worktree it just created). Ignored when+ * the send lands in an existing topic, whose directory is its own.+ */+ newTopicWorkingDirectory?: WorkingDirConfig;onlyAddUserMessage?: boolean;/*** Called once the send lifecycle owns the turn, either by persisting the user message or bydiff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 869f13563c5..e7519e96e60 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -138,6 +138,13 @@ export interface WorkspaceUserPreference {* nothing reads or writes this key.*/topicOnlyMine?: boolean;+ /**+ * Directories (`<deviceId>::<path>`, see `getWorktreeModeKey`) where this+ * member keeps the composer's "New worktree" switch on, most recent first and+ * capped. Written only through `workspaceUserSettings.setWorktreeModeDir`,+ * which applies the cap server-side.+ */+ worktreeModeDirs?: string[];}export interface LobeUser {@@ -411,6 +418,13 @@ export interface UserPreference {useCmdEnterToSend?: boolean;/** This user's own view over the workspaces they belong to. */workspace?: UserWorkspacePreference;+ /**+ * Personal-mode counterpart of {@link WorkspaceUserPreference.worktreeModeDirs}.+ * Written only through `user.setWorktreeModeDir`; deliberately absent from+ * {@link UserPreferenceSchema} for the same reason as `islandDismissals` —+ * `updatePreference` deep-merges arrays by index, which would scramble it.+ */+ worktreeModeDirs?: string[];}export type ReferralStatusString =diff --git a/packages/types/src/workingDir.ts b/packages/types/src/workingDir.tsnew file mode 100644index 00000000000..72d4826ab5b--- /dev/null+++ b/packages/types/src/workingDir.ts@@ -0,0 +1,213 @@+import { z } from 'zod';++/**+ * Working-directory configuration: what a device, an agent default or a topic+ * records about the folder a run works in — source path, repo type and git+ * state (branch, selected worktree, linked PR). Re-exported from `./device`.+ */++/**+ * A working directory source a device has used. Structured (rather than a bare+ * 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 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;+}++/**+ * The remote ref a local branch publishes to.+ *+ * Recorded because the local branch name is a DEVICE-LOCAL label: a worktree+ * generates its own (`worktree-feat+foo`), and a push with an explicit refspec+ * (`git push origin local:remote`) renames the branch in flight. Carrying the+ * local name to another machine — or to `gh pr list --head` — yields nothing.+ * The remote ref is the only branch identity that survives leaving this machine,+ * which also makes it the handle for re-fetching the topic's output elsewhere.+ */+export interface DeviceGitUpstreamRef {+ /** Branch name ON the remote (`feat/x`), never the local name. */+ branch: string;+ /** Remote name (`origin`). */+ remote: string;+}++export interface WorkingDirGitState {+ /**+ * Active checkout selected under this git source. When absent, the source+ * path itself is the effective working directory.+ */+ activeWorktree?: string;+ /**+ * True when {@link activeWorktree} was created by the app on the topic's+ * first send (Better Coding Experience "New worktree"), not picked by the+ * user. Such a worktree belongs to this one conversation — the record a+ * later cleanup keys on. Ownership only: where a CLI session starts is+ * {@link WorkingDirConfig.sessionPath}, which outlives a later move.+ */+ autoCreated?: boolean;+ /** ISO time the app created {@link activeWorktree}; set with {@link autoCreated}. */+ autoCreatedAt?: 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;+ /**+ * Remote ref {@link branch} publishes to. Dropped alongside {@link github}+ * whenever the branch changes — a stale remote ref would bind the topic to+ * another branch's PR, which is worse than having none.+ */+ upstream?: DeviceGitUpstreamRef;+}++export interface WorkingDirConfig {+ /**+ * The code environment picked with this folder. Metadata only on a device:+ * nothing clones or bootstraps there; the association is kept for later.+ */+ environmentId?: string;+ git?: WorkingDirGitState;+ path: string;+ repoType?: WorkingDirRepoType;+ /**+ * Where local CLI agents start their session, when that is not {@link path}:+ * set once, to the worktree the app created before the topic's first turn.+ * Never moved by a later worktree change — a CLI keys its sessions by cwd,+ * so moving it would drop the conversation's session.+ */+ sessionPath?: string;+}++export type WorkingDirConfigValue = string | WorkingDirConfig;++/**+ * Keep the {@link WorkingDirGitState.autoCreated} marker only while the topic is+ * still on the worktree the app created. Once a writer moves `activeWorktree`+ * (an agent forking another worktree, or leaving it), the marker would point a+ * later cleanup at the wrong checkout. The CLI session cwd is unaffected: it+ * lives in `sessionPath`. Mutates and returns `git`.+ */+export const dropStaleAutoCreated = <T extends WorkingDirGitState>(+ git: T,+ previousWorktree: string | undefined,+): T => {+ if (git.activeWorktree !== previousWorktree) {+ delete git.autoCreated;+ delete git.autoCreatedAt;+ }+ return git;+};++export const getWorkingDirSourcePath = (+ entry?: WorkingDirConfigValue | null,+): string | undefined => {+ if (!entry) return undefined;+ return typeof entry === 'string' ? entry : entry.path;+};++export const getWorkingDirEffectivePath = (+ entry?: WorkingDirConfigValue | null,+): string | undefined => {+ if (!entry) return undefined;+ if (typeof entry === 'string') return entry;+ return entry.git?.activeWorktree || entry.path;+};++/**+ * Where a local CLI agent (Claude Code, Codex…) starts, which is also the key+ * of its per-cwd session store. Normally the SOURCE repo: a worktree picked+ * mid-conversation must not move the session, so it is only described to the+ * agent. A topic born in a worktree the app created records that worktree as+ * {@link WorkingDirConfig.sessionPath}: the session starts there, keeps+ * starting there whatever worktree the topic moves to later, and the+ * conversation's work stays out of the source checkout.+ */+export const getWorkingDirSessionPath = (+ entry?: WorkingDirConfigValue | null,+): string | undefined => {+ if (!entry) return undefined;+ if (typeof entry === 'string') return entry;+ return entry.sessionPath || entry.path;+};++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({+ environmentId: z.string().max(255).optional(),+ git: z+ .object({+ activeWorktree: z.string().optional(),+ autoCreated: z.boolean().optional(),+ autoCreatedAt: 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(),+ // Mirrors `WorkingDirGitState.upstream`. A field missing here is not merely+ // unvalidated — zod strips it, so it would never survive a write.+ upstream: z+ .object({+ branch: z.string(),+ remote: z.string(),+ })+ .optional(),+ })+ .optional(),+ path: z.string(),+ repoType: z.enum(['git', 'github']).optional(),+ sessionPath: z.string().optional(),+});diff --git a/packages/types/src/worktreeMode.test.ts b/packages/types/src/worktreeMode.test.tsnew file mode 100644index 00000000000..85d1a5d8f0a--- /dev/null+++ b/packages/types/src/worktreeMode.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import {+ applyWorktreeModeDir,+ getWorktreeModeKey,+ normalizeDirectoryPath,+ WORKTREE_MODE_DIRS_LIMIT,+} from './worktreeMode';++describe('normalizeDirectoryPath', () => {+ it('drops surrounding space and trailing separators', () => {+ expect(normalizeDirectoryPath(' /code/lobehub/ ')).toBe('/code/lobehub');+ expect(normalizeDirectoryPath('C:\\code\\lobehub\\\\')).toBe('C:\\code\\lobehub');+ });++ it('keeps a bare root', () => {+ expect(normalizeDirectoryPath('/')).toBe('/');+ });+});++describe('getWorktreeModeKey', () => {+ it('keys the same directory identically however it is spelled', () => {+ expect(getWorktreeModeKey('dev-1', '/code/lobehub/')).toBe(+ getWorktreeModeKey('dev-1', '/code/lobehub'),+ );+ });++ it('keeps devices and directories apart', () => {+ expect(getWorktreeModeKey('dev-1', '/code/a')).not.toBe(getWorktreeModeKey('dev-2', '/code/a'));+ expect(getWorktreeModeKey('dev-1', '/code/a')).not.toBe(getWorktreeModeKey('dev-1', '/code/b'));+ });+});++describe('applyWorktreeModeDir', () => {+ it('moves a key set on to the front without duplicating it', () => {+ expect(applyWorktreeModeDir(['a', 'b'], 'b', true)).toEqual(['b', 'a']);+ expect(applyWorktreeModeDir(undefined, 'a', true)).toEqual(['a']);+ });++ it('drops a key set off', () => {+ expect(applyWorktreeModeDir(['a', 'b'], 'a', false)).toEqual(['b']);+ expect(applyWorktreeModeDir([], 'a', false)).toEqual([]);+ });++ it('evicts the least recently set directory past the cap', () => {+ const full = Array.from({ length: WORKTREE_MODE_DIRS_LIMIT }, (_, i) => `k${i}`);+ const next = applyWorktreeModeDir(full, 'new', true);+ expect(next).toHaveLength(WORKTREE_MODE_DIRS_LIMIT);+ expect(next[0]).toBe('new');+ expect(next).not.toContain(`k${WORKTREE_MODE_DIRS_LIMIT - 1}`);+ });+});diff --git a/packages/types/src/worktreeMode.ts b/packages/types/src/worktreeMode.tsnew file mode 100644index 00000000000..2bc4bcaf292--- /dev/null+++ b/packages/types/src/worktreeMode.ts@@ -0,0 +1,42 @@+/**+ * The per-directory "New worktree" switch of the Better Coding Experience lab.+ *+ * Remembered per workspace + user (the preference bucket it is stored in) and+ * per device + directory (the key). Deliberately NOT on the device's shared+ * `workingDirs`: a workspace device is used by every member, while this switch+ * is one member's habit.+ *+ * Stored as the list of keys whose switch is ON, most recently set first. Off+ * is the default, so only "on" carries information; a list rather than a map+ * because jsonb does not keep object key order, and the cap evicts the least+ * recently set directory.+ */+export const WORKTREE_MODE_DIRS_LIMIT = 200;++const isSep = (ch: string): boolean => ch === '/' || ch === '\\';++/**+ * A directory path in the one spelling used for comparisons: trimmed, without+ * trailing separators (a bare root keeps its separator). Linear scan rather than+ * an anchored regex — this runs on the server over untrusted input.+ */+export const normalizeDirectoryPath = (path: string): string => {+ const trimmed = path.trim();+ let end = trimmed.length;+ while (end > 1 && isSep(trimmed[end - 1])) end -= 1;+ return trimmed.slice(0, end);+};++/** `<deviceId>::<normalized path>` — `deviceId` is the real one, also for this machine. */+export const getWorktreeModeKey = (deviceId: string, path: string): string =>+ `${deviceId}::${normalizeDirectoryPath(path)}`;++/** The list after setting `key`: moved to the front when on, dropped when off, capped. */+export const applyWorktreeModeDir = (+ current: readonly string[] | undefined,+ key: string,+ enabled: boolean,+): string[] => {+ const rest = (current ?? []).filter((entry) => entry !== key);+ return (enabled ? [key, ...rest] : rest).slice(0, WORKTREE_MODE_DIRS_LIMIT);+};diff --git a/packages/types/src/worktreePath.ts b/packages/types/src/worktreePath.tsindex 319de4c370e..299d75207b5 100644--- a/packages/types/src/worktreePath.ts+++ b/packages/types/src/worktreePath.ts@@ -44,13 +44,29 @@ const shortHash = (input: string): string => {export interface DeriveWorktreePathOptions {/** Home directory of the machine that owns the repo; omitted → sibling layout. */homeDir?: string;+ /**+ * A branch namespace (e.g. `lobehub`) to leave out of the folder name:+ * `lobehub/quiet-hill` lands in `…/quiet-hill` instead of+ * `…/lobehub-quiet-hill`. Only a leading `<prefix>/` segment is dropped, so any+ * other name (`feat/foo` → `feat-foo`) folds exactly as before.+ */+ stripBranchPrefix?: string;}+const stripNamespace = (branch: string, prefix: string | undefined): string => {+ const namespace = prefix?.trim();+ if (!namespace) return branch;+ const trimmed = branch.trim();+ const head = `${namespace}/`;+ return trimmed.startsWith(head) ? trimmed.slice(head.length) : trimmed;+};+export const deriveWorktreePath = (sourcePath: string,- branch: string,- { homeDir }: DeriveWorktreePathOptions = {},+ rawBranch: string,+ { homeDir, stripBranchPrefix }: DeriveWorktreePathOptions = {},): string => {+ const branch = stripNamespace(rawBranch, stripBranchPrefix);const sep = sourcePath.includes('\\') && !sourcePath.includes('/') ? '\\' : '/';// Strip trailing path separators, then the leading/trailing '-' of the folded// branch, both with linear scans rather than anchored /[…]+$/ quantifiers —diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsxindex ecc13ffa707..a735786f5c7 100644--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx@@ -52,6 +52,9 @@ import { useBranchList } from './useBranchList';import { useSwitchWorktree } from './useSwitchWorktree';import { findWorktreeForBranch, getPathName } from './worktreeHelpers';+/** Rows the pick-only list shows before it scrolls (fits the 360px popup). */+const PICK_LIST_MAX_ROWS = 8;+const spin = stylex.keyframes({ to: { transform: 'rotate(360deg)' } });const styles = stylex.create({@@ -108,6 +111,9 @@ const styles = stylex.create({width: '300px',height: '360px',},+ // Pick-only mode has no footer: the popup hugs a short list instead of+ // leaving the fixed height blank under it.+ popupFit: { height: 'auto', maxHeight: '360px' },refreshButton: {cursor: 'pointer',display: 'flex',@@ -188,6 +194,18 @@ interface BranchSwitcherProps {path: string;/** Dropdown placement — the runtime bar opens upward, embedding panels open downward. */placement?: 'topLeft' | 'bottomLeft' | 'bottomRight';+ /**+ * Pick-only mode (Better Coding Experience, before a topic's first send): a+ * click records `onSelect` instead of checking out — the send switches, or+ * forks a worktree — and the create / rename / delete actions and the+ * footer are gone. A branch another worktree holds is pickable too; the send+ * handles it.+ */+ selection?: {+ /** The picked branch, which carries the checkmark. */+ branch?: string;+ onSelect: (branch: string) => void;+ };/** The repo the conversation is anchored to (worktrees hang off it). */sourcePath: string;/** The conversation the switch is recorded on; omitted, the global active topic. */@@ -209,6 +227,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(onExternalRefresh,onOptimisticCheckout,placement = 'topLeft',+ selection,sourcePath,topicId,worktrees,@@ -272,13 +291,14 @@ const BranchSwitcher = memo<BranchSwitcherProps>(// popup mounts at scrollTop=0, so a checked branch below the fold would read// as "nothing selected". Keyed on branches.length so it fires once the async// list has painted.+ const checkedBranch = selection ? selection.branch : currentBranch;useEffect(() => {if (!open) return;const raf = requestAnimationFrame(() => {currentRowRef.current?.scrollIntoView({ block: 'nearest' });});return () => cancelAnimationFrame(raf);- }, [open, branches.length, currentBranch]);+ }, [open, branches.length, checkedBranch]);const filtered = useMemo(() => {const query = search.trim().toLowerCase();@@ -288,6 +308,11 @@ const BranchSwitcher = memo<BranchSwitcherProps>(const handleCheckout = useCallback(async (branch: string, create = false) => {+ if (selection) {+ selection.onSelect(branch);+ onOpenChange(false);+ return;+ }if (busyBranch) return;if (!create && branch === currentBranch) {onOpenChange(false);@@ -333,6 +358,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(onOptimisticCheckout,onOpenChange,path,+ selection,switchWorktree,t,worktrees,@@ -440,7 +466,9 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</DropdownMenuTrigger><DropdownMenuPortal><DropdownMenuPositioner placement={placement} sideOffset={8}>- <DropdownMenuPopup className={stylex.props(styles.popup).className}>+ <DropdownMenuPopup+ className={stylex.props(styles.popup, selection && styles.popupFit).className}+ ><DropdownMenuHeader className={stylex.props(styles.header).className}><div {...stylex.props(styles.searchBar)}><Input@@ -499,9 +527,15 @@ const BranchSwitcher = memo<BranchSwitcherProps>(// branch, last) undrawn. Remount when the count changes.key={filtered.length}listItemHeight={32}+ style={+ selection+ ? { height: Math.min(filtered.length, PICK_LIST_MAX_ROWS) * 32 + 8 }+ : undefined+ }>{filtered.map((branch) => {const isCurrent = branch.name === currentBranch;+ const isChecked = branch.name === checkedBranch;const isBusy = busyBranch === branch.name;// A branch another worktree holds can't be checked out here// (clicking routes into that worktree) and can't be deleted.@@ -511,7 +545,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(className={stylex.props(stylex.defaultMarker(), styles.item).className}closeOnClick={false}key={branch.name}- ref={isCurrent ? currentRowRef : undefined}+ ref={isChecked ? currentRowRef : undefined}onClick={() => handleCheckout(branch.name)}><Icon@@ -523,6 +557,11 @@ const BranchSwitcher = memo<BranchSwitcherProps>(/><div {...stylex.props(styles.itemMain)}><div {...stylex.props(styles.branchLabel)}>{branch.name}</div>+ {isCurrent && selection && !isChecked && (+ <div {...stylex.props(styles.itemMeta)}>+ {t('workingDirectory.branchCheckedOutHere')}+ </div>+ )}{isCurrent && workingStatus && !workingStatus.clean && (<div {...stylex.props(styles.itemMeta)}>{t('workingDirectory.uncommittedChanges', {@@ -538,7 +577,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</div>)}</div>- {isCurrent && (+ {isChecked && (<IconclassName={stylex.props(styles.itemCheck).className}icon={CheckIcon}@@ -556,16 +595,18 @@ const BranchSwitcher = memo<BranchSwitcherProps>(<Icon icon={CopyIcon} size={13} /></div></Tooltip>- <Tooltip title={t('workingDirectory.renameBranchAction')}>- <div- {...stylex.props(styles.rowAction)}- role="button"- onClick={(e) => handleRename(e, branch.name)}- >- <Icon icon={PencilIcon} size={13} />- </div>- </Tooltip>- {!isCurrent && !owner && (+ {!selection && (+ <Tooltip title={t('workingDirectory.renameBranchAction')}>+ <div+ {...stylex.props(styles.rowAction)}+ role="button"+ onClick={(e) => handleRename(e, branch.name)}+ >+ <Icon icon={PencilIcon} size={13} />+ </div>+ </Tooltip>+ )}+ {!selection && !isCurrent && !owner && (<Tooltip title={t('workingDirectory.deleteBranchAction')}><div{...stylex.props(styles.rowAction, styles.rowActionDanger)}@@ -583,21 +624,23 @@ const BranchSwitcher = memo<BranchSwitcherProps>(</DropdownMenuScrollViewport>)}- <DropdownMenuFooter className={stylex.props(styles.footer).className}>- <DropdownMenuItem- className={stylex.props(styles.item).className}- onClick={openCreateBranch}- >- <Icon- className={stylex.props(styles.itemIcon).className}- icon={GitBranchPlusIcon}- size={14}- />- <div {...stylex.props(styles.itemMain)}>- {t('workingDirectory.createBranchAction')}- </div>- </DropdownMenuItem>- </DropdownMenuFooter>+ {!selection && (+ <DropdownMenuFooter className={stylex.props(styles.footer).className}>+ <DropdownMenuItem+ className={stylex.props(styles.item).className}+ onClick={openCreateBranch}+ >+ <Icon+ className={stylex.props(styles.itemIcon).className}+ icon={GitBranchPlusIcon}+ size={14}+ />+ <div {...stylex.props(styles.itemMain)}>+ {t('workingDirectory.createBranchAction')}+ </div>+ </DropdownMenuItem>+ </DropdownMenuFooter>+ )}</DropdownMenuPopup></DropdownMenuPositioner></DropdownMenuPortal>diff --git a/src/features/ChatInput/ControlBar/DraftGit/WorktreeToggle.tsx b/src/features/ChatInput/ControlBar/DraftGit/WorktreeToggle.tsxnew file mode 100644index 00000000000..a150b7562d6--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/WorktreeToggle.tsx@@ -0,0 +1,86 @@+'use client';++import { Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { FolderGit2Icon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useWorktreeMode } from './useWorktreeMode';++const styles = stylex.create({+ off: {+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ },+ on: {+ color: cssVar.colorPrimary,+ backgroundColor: { 'default': cssVar.colorPrimaryBg, ':hover': cssVar.colorPrimaryBgHover },+ },+ pending: { cursor: 'progress', opacity: 0.5 },+ toggle: {+ cursor: 'pointer',+ display: 'inline-flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '22px',+ height: '22px',+ borderRadius: '4px',+ transition: 'background 0.2s, color 0.2s',+ backgroundImage: 'none',+ },+ tooltip: { display: 'flex', flexDirection: 'column', gap: '2px' },+ tooltipHint: { fontSize: '12px', opacity: 0.75 },+});++interface WorktreeToggleProps {+ /** The branch the new worktree would be cut from, named in the tooltip. */+ baseBranch?: string;+ keyDeviceId?: string;+ path: string;+}++/**+ * The new-topic composer's "New worktree" switch. A git-folder icon, not a+ * fork: the fork reads as a branch, and this creates a working directory. On, the first send cuts a+ * new `lobehub/…` branch from the picked branch into its own worktree and runs+ * the topic there, leaving this directory untouched. Remembered per directory.+ */+export const WorktreeToggle = ({ baseBranch, keyDeviceId, path }: WorktreeToggleProps) => {+ const { t } = useTranslation('device');+ const { enabled, ready, setEnabled } = useWorktreeMode(keyDeviceId, path);+ const label = t('workingDirectory.worktreeToggle');++ return (+ <Tooltip+ title={+ <div {...stylex.props(styles.tooltip)}>+ <span>{enabled ? t('workingDirectory.worktreeToggleOn') : label}</span>+ <span {...stylex.props(styles.tooltipHint)}>+ {enabled+ ? t('workingDirectory.worktreeToggleOnHint', { branch: baseBranch ?? '' })+ : t('workingDirectory.worktreeToggleOffHint')}+ </span>+ </div>+ }+ >+ <div+ aria-busy={!ready}+ aria-label={label}+ aria-pressed={enabled}+ role="button"+ tabIndex={0}+ {...stylex.props(styles.toggle, enabled ? styles.on : styles.off, !ready && styles.pending)}+ onClick={ready ? () => void setEnabled(!enabled) : undefined}+ onKeyDown={(event) => {+ if (!ready || (event.key !== 'Enter' && event.key !== ' ')) return;+ event.preventDefault();+ void setEnabled(!enabled);+ }}+ >+ <Icon icon={FolderGit2Icon} size={13} />+ </div>+ </Tooltip>+ );+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.test.ts b/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.test.tsnew file mode 100644index 00000000000..ef56a4f34b1--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { resolveComposerHandoff } from './composerHandoff';++describe('resolveComposerHandoff', () => {+ it('clears as before when the send waited on no git step', () => {+ expect(+ resolveComposerHandoff({ acted: false, editorUnchanged: false, stillHere: false }),+ ).toEqual({ clearEditor: true, sendToOrigin: false });+ });++ it('clears the draft that was sent from the same conversation', () => {+ expect(resolveComposerHandoff({ acted: true, editorUnchanged: true, stillHere: true })).toEqual(+ { clearEditor: true, sendToOrigin: false },+ );+ });++ it('keeps text typed while git ran', () => {+ expect(+ resolveComposerHandoff({ acted: true, editorUnchanged: false, stillHere: true }).clearEditor,+ ).toBe(false);+ });++ it('sends to the original conversation and leaves the one now open alone', () => {+ expect(+ resolveComposerHandoff({ acted: true, editorUnchanged: true, stillHere: false }),+ ).toEqual({ clearEditor: false, sendToOrigin: true });+ });+});diff --git a/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.ts b/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.tsnew file mode 100644index 00000000000..dcd70f873f3--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/composerHandoff.ts@@ -0,0 +1,23 @@+/**+ * What a send may still do to the composer once the git step returns.+ *+ * When git actually ran, the send waited seconds on it, in which the user may+ * have opened another conversation or kept typing. The captured draft still+ * goes to the conversation it was written in (`sendToOrigin`), and only that+ * draft leaves the composer: one now showing another conversation, or holding+ * newer text, keeps what it has. A send that waited on nothing clears as before.+ */+export const resolveComposerHandoff = ({+ acted,+ editorUnchanged,+ stillHere,+}: {+ acted: boolean;+ /** The editor still holds exactly the text that is being sent. */+ editorUnchanged: boolean;+ /** The composer still belongs to the conversation the send started in. */+ stillHere: boolean;+}) => ({+ clearEditor: !acted || (stillHere && editorUnchanged),+ sendToOrigin: acted && !stillHere,+});diff --git a/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.ts b/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.tsnew file mode 100644index 00000000000..129cecef3c4--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.ts@@ -0,0 +1,77 @@+import { normalizeDirectoryPath } from '@lobechat/types';+import { createWithEqualityFn } from 'zustand/traditional';++/**+ * The git directory a new topic's composer shows, as the send needs it.+ * Registered by the control bar that renders it, so the send acts on exactly+ * the directory the user sees — never a re-derivation that could disagree.+ */+export interface DraftGitTarget {+ agentId: string;+ /** Remote device for RPC; `undefined` is this machine over Electron IPC. */+ deviceId?: string;+ isGithub: boolean;+ /**+ * The real device id, also for this machine (its gateway device id). Keys+ * the worktree switch and matches other topics' `boundDeviceId`; undefined+ * only on a desktop that never registered with the gateway.+ */+ keyDeviceId?: string;+ /** The directory git runs in (the effective one, a worktree included). */+ path: string;+ /** The repository's main checkout; worktrees are recorded against it. */+ sourcePath: string;+}++/**+ * Before the first send, picking a branch only records it (Better Coding+ * Experience): the checkout or worktree happens when the message is sent. The+ * pick lives here, per agent + device + directory, so it survives the switcher+ * closing but not a reload — it is a draft, never persisted.+ */+interface DraftGitState {+ /** `draftBranchKey` → the branch picked for the next send. */+ selections: Record<string, string>;+ /** agentId → the directory its new-topic composer currently shows. */+ targets: Record<string, DraftGitTarget>;+}++export const useDraftGitStore = createWithEqualityFn<DraftGitState>()(() => ({+ selections: {},+ targets: {},+}));++export const draftBranchKey = ({+ agentId,+ keyDeviceId,+ path,+}: Pick<DraftGitTarget, 'agentId' | 'keyDeviceId' | 'path'>) =>+ `${agentId}\u0000${keyDeviceId ?? 'local'}\u0000${normalizeDirectoryPath(path)}`;++export const setDraftBranch = (key: string, branch: string | undefined) =>+ useDraftGitStore.setState((state) => {+ const selections = { ...state.selections };+ if (branch) selections[key] = branch;+ else delete selections[key];+ return { selections };+ });++export const getDraftBranch = (key: string): string | undefined =>+ useDraftGitStore.getState().selections[key];++export const registerDraftGitTarget = (target: DraftGitTarget) =>+ useDraftGitStore.setState((state) => ({+ targets: { ...state.targets, [target.agentId]: target },+ }));++/** Drop the registration, unless another bar has since replaced it. */+export const unregisterDraftGitTarget = (target: DraftGitTarget) =>+ useDraftGitStore.setState((state) => {+ if (state.targets[target.agentId] !== target) return state;+ const targets = { ...state.targets };+ delete targets[target.agentId];+ return { targets };+ });++export const getDraftGitTarget = (agentId: string): DraftGitTarget | undefined =>+ useDraftGitStore.getState().targets[agentId];diff --git a/src/features/ChatInput/ControlBar/DraftGit/gitErrors.ts b/src/features/ChatInput/ControlBar/DraftGit/gitErrors.tsnew file mode 100644index 00000000000..1fa82c10101--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/gitErrors.ts@@ -0,0 +1,34 @@+import type { DeviceGitSyncResult } from '@lobechat/types';+import { DEVICE_GIT_OUTDATED } from '@lobechat/types';+import type { TFunction } from 'i18next';++import { getPathName } from '../worktreeHelpers';++/**+ * The user-facing reason for a failed git write. Refusals the device reports+ * as a reason code (an outdated device, a branch held by another worktree, no+ * upstream) are said in the user's language; anything else is git's own text.+ */+export const describeGitFailure = (+ result: Pick<DeviceGitSyncResult, 'branch' | 'error' | 'reason' | 'worktreePath'>,+ t: TFunction<'device'>,+ fallback: string,+): string => {+ switch (result.reason) {+ case DEVICE_GIT_OUTDATED: {+ return t('workingDirectory.deviceOutdated');+ }+ case 'checkedOutElsewhere': {+ return t('workingDirectory.pullCheckedOutElsewhere', {+ branch: result.branch ?? '',+ name: result.worktreePath ? getPathName(result.worktreePath) : '',+ });+ }+ case 'noUpstream': {+ return t('workingDirectory.pullNoUpstream', { branch: result.branch ?? '' });+ }+ default: {+ return result.error || fallback;+ }+ }+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/index.test.ts b/src/features/ChatInput/ControlBar/DraftGit/index.test.tsnew file mode 100644index 00000000000..848036c5d40--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/index.test.ts@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { prepareComposerGitSend } from './index';+import { prepareDraftGitSend, snapshotDraftGit } from './prepareSend';++vi.mock('./prepareSend', () => ({+ prepareDraftGitSend: vi.fn(),+ snapshotDraftGit: vi.fn(),+}));+vi.mock('./sendPrompts', () => ({ draftGitSendPrompts: {} }));++const snap = (agentId: string) => ({+ picked: 'feat',+ target: { agentId, isGithub: true, path: '/repo', sourcePath: '/repo' },+ worktreeMode: false,+});++beforeEach(() => {+ vi.clearAllMocks();+});++describe('prepareComposerGitSend', () => {+ it('passes a send with nothing to prepare without waiting on another composer', async () => {+ let release!: (value: { ok: true }) => void;+ vi.mocked(snapshotDraftGit).mockImplementation((context) =>+ context.agentId === 'agent-a' ? snap('agent-a') : undefined,+ );+ vi.mocked(prepareDraftGitSend).mockReturnValue(new Promise((resolve) => (release = resolve)));++ const slow = prepareComposerGitSend({ agentId: 'agent-a', topicId: null });+ // Another conversation (an existing topic, another agent) sends meanwhile.+ await expect(prepareComposerGitSend({ agentId: 'agent-b', topicId: 'tpc_1' })).resolves.toEqual(+ { ok: true },+ );++ release({ ok: true });+ await expect(slow).resolves.toEqual({ ok: true });+ });++ it('refuses a second send from the same composer while its git step runs', async () => {+ let release!: (value: { ok: true }) => void;+ vi.mocked(snapshotDraftGit).mockReturnValue(snap('agent-a'));+ vi.mocked(prepareDraftGitSend).mockReturnValue(new Promise((resolve) => (release = resolve)));++ const first = prepareComposerGitSend({ agentId: 'agent-a', topicId: null });+ await expect(prepareComposerGitSend({ agentId: 'agent-a', topicId: null })).resolves.toEqual({+ ok: false,+ });++ release({ ok: true });+ await first;+ // Released once it settles.+ vi.mocked(prepareDraftGitSend).mockResolvedValue({ ok: true });+ await expect(prepareComposerGitSend({ agentId: 'agent-a', topicId: null })).resolves.toEqual({+ ok: true,+ });+ });++ it('uses the snapshot taken at send time, not the composer as it is later', async () => {+ vi.mocked(prepareDraftGitSend).mockResolvedValue({ acted: true, ok: true });+ const snapshot = snap('agent-a');++ await prepareComposerGitSend({ agentId: 'agent-a', topicId: null }, { snapshot });++ expect(snapshotDraftGit).not.toHaveBeenCalled();+ expect(prepareDraftGitSend).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ snapshot }),+ );+ });++ it('does nothing when there was nothing to prepare at send time', async () => {+ await expect(+ prepareComposerGitSend({ agentId: 'agent-a', topicId: null }, { snapshot: null }),+ ).resolves.toEqual({ ok: true });+ expect(snapshotDraftGit).not.toHaveBeenCalled();+ expect(prepareDraftGitSend).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ChatInput/ControlBar/DraftGit/index.ts b/src/features/ChatInput/ControlBar/DraftGit/index.tsnew file mode 100644index 00000000000..c725871fffe--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/index.ts@@ -0,0 +1,52 @@+import type { ConversationContext } from '@lobechat/types';+import i18next from 'i18next';++import {+ type DraftGitSendResult,+ type DraftGitSnapshot,+ prepareDraftGitSend,+ snapshotDraftGit,+} from './prepareSend';+import { draftGitSendPrompts } from './sendPrompts';++/** Agents whose new-topic composer is switching a branch or creating a worktree now. */+const inFlight = new Set<string>();++/**+ * The composer's entry to the send-time git step (see `prepareDraftGitSend`),+ * with the real prompts. Sends with nothing to prepare (an existing topic, the+ * lab off, another agent's composer) pass straight through; only a second send+ * from the same composer while its git step runs is refused, rather than+ * racing it.+ */+export { needsSendTimeGit, snapshotDraftGit } from './prepareSend';++export const prepareComposerGitSend = async (+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,+ options: {+ editorData?: Record<string, any>;+ /**+ * Taken when the user sent, for a send that runs later (a voice turn);+ * `null` means there was nothing to prepare then. Omitted, it is read now.+ */+ snapshot?: DraftGitSnapshot | null;+ } = {},+): Promise<DraftGitSendResult> => {+ const { editorData } = options;+ const snapshot =+ options.snapshot === undefined ? snapshotDraftGit(context, editorData) : options.snapshot;+ if (!snapshot) return { ok: true };+ const { target } = snapshot;+ if (inFlight.has(target.agentId)) return { ok: false };+ inFlight.add(target.agentId);+ try {+ return await prepareDraftGitSend(context, {+ editorData,+ prompts: draftGitSendPrompts,+ snapshot,+ t: i18next.getFixedT(null, 'device'),+ });+ } finally {+ inFlight.delete(target.agentId);+ }+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.tsnew file mode 100644index 00000000000..cfab4fcd013--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts@@ -0,0 +1,427 @@+import { DEVICE_GIT_OUTDATED, getWorktreeModeKey } from '@lobechat/types';+import type { TFunction } from 'i18next';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceService } from '@/services/device';+import { DeviceGitOutdatedError, gitService } from '@/services/git';+import { useGitStatusStore } from '@/store/device/gitStatus/store';+import { useUserStore } from '@/store/user';++import {+ draftBranchKey,+ type DraftGitTarget,+ getDraftBranch,+ registerDraftGitTarget,+ setDraftBranch,+ useDraftGitStore,+} from './draftGitStore';+import {+ type DraftGitSendPrompts,+ needsSendTimeGit,+ prepareDraftGitSend,+ snapshotDraftGit,+} from './prepareSend';++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => null,+ useActiveWorkspaceId: () => null,+}));++vi.mock('@/services/git', async (importOriginal) => {+ const original = await importOriginal<Record<string, unknown>>();+ return {+ ...original,+ gitService: {+ addGitWorktree: vi.fn(),+ checkoutGitBranch: vi.fn(),+ getGitAheadBehind: vi.fn(),+ getGitBranch: vi.fn(),+ getGitWorkingTreeStatus: vi.fn(),+ listGitBranches: vi.fn(),+ listGitWorktrees: vi.fn(),+ },+ };+});++vi.mock('@/services/device', () => ({+ deviceService: { countRunningTopicsInDirectory: vi.fn() },+}));++const t = ((key: string) => key) as unknown as TFunction<'device'>;++const target: DraftGitTarget = {+ agentId: 'agent-1',+ deviceId: 'dev-1',+ isGithub: true,+ keyDeviceId: 'dev-1',+ path: '/code/lobehub',+ sourcePath: '/code/lobehub',+};+const context = { agentId: 'agent-1', topicId: null };++const prompts = (): DraftGitSendPrompts & { [K in keyof DraftGitSendPrompts]: any } => ({+ askBranchName: vi.fn(async ({ defaultName }) => defaultName),+ confirmSwitchRisks: vi.fn(async () => true),+ notifyError: vi.fn(),+ showProgress: vi.fn(() => () => {}),+});++const setLab = (on: boolean) =>+ useUserStore.setState({+ preference: {+ ...useUserStore.getState().preference,+ lab: { enableBetterCodingExperience: on },+ },+ } as any);++const setWorktreeMode = (on: boolean) =>+ useUserStore.setState({+ preference: {+ ...useUserStore.getState().preference,+ worktreeModeDirs: on ? [getWorktreeModeKey('dev-1', target.path)] : [],+ },+ } as any);++const pick = (branch: string) => setDraftBranch(draftBranchKey(target), branch);++beforeEach(() => {+ vi.clearAllMocks();+ useDraftGitStore.setState({ selections: {}, targets: {} });+ useGitStatusStore.setState({ gitAheadBehindMap: {} });+ registerDraftGitTarget(target);+ setLab(true);+ setWorktreeMode(false);+ vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'main' });+ vi.mocked(gitService.listGitWorktrees).mockResolvedValue([+ { current: true, path: '/code/lobehub', branch: 'main' },+ ]);+ vi.mocked(gitService.listGitBranches).mockResolvedValue([+ { current: true, name: 'main' },+ { current: false, name: 'feat' },+ ]);+ vi.mocked(gitService.getGitWorkingTreeStatus).mockResolvedValue({+ added: 0,+ clean: true,+ deleted: 0,+ modified: 0,+ total: 0,+ });+ vi.mocked(gitService.checkoutGitBranch).mockResolvedValue({ success: true });+ vi.mocked(gitService.getGitAheadBehind).mockImplementation(async ({ branch }) => ({+ ahead: 0,+ behind: 0,+ branch,+ hasUpstream: true,+ }));+ vi.mocked(deviceService.countRunningTopicsInDirectory).mockResolvedValue(0);+});++describe('prepareDraftGitSend — nothing to do', () => {+ it('passes without touching git when the lab is off', async () => {+ setLab(false);+ pick('feat');+ expect(await prepareDraftGitSend(context, { prompts: prompts(), t })).toEqual({ ok: true });+ expect(gitService.getGitBranch).not.toHaveBeenCalled();+ });++ it('passes for an existing topic', async () => {+ pick('feat');+ const result = await prepareDraftGitSend(+ { agentId: 'agent-1', topicId: 'tpc_1' },+ { prompts: prompts(), t },+ );+ expect(result).toEqual({ ok: true });+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ });++ it('does nothing when the picked branch is the current one', async () => {+ pick('main');+ expect(await prepareDraftGitSend(context, { prompts: prompts(), t })).toEqual({ ok: true });+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ });+});++describe('prepareDraftGitSend — direct @Agent route', () => {+ const mentionOf = (id: string) => ({+ root: {+ children: [+ {+ children: [+ { label: 'B', metadata: { id, type: 'agent' }, type: 'mention' },+ { text: ' do it', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ });++ it('leaves git alone when the message runs another agent', async () => {+ pick('feat');+ setWorktreeMode(true);+ const result = await prepareDraftGitSend(context, {+ editorData: mentionOf('agent-2'),+ prompts: prompts(),+ t,+ });++ expect(result).toEqual({ ok: true });+ expect(gitService.addGitWorktree).not.toHaveBeenCalled();+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ });+});++describe('prepareDraftGitSend — snapshot taken at send time', () => {+ it('acts on the snapshot even after the composer dropped the directory', async () => {+ pick('feat');+ const snapshot = snapshotDraftGit(context)!;+ // The user moved to another topic: the bar unregistered, the pick is gone.+ useDraftGitStore.setState({ selections: {}, targets: {} });++ expect(await prepareDraftGitSend(context, { prompts: prompts(), snapshot, t })).toEqual({+ acted: true,+ ok: true,+ });+ expect(gitService.checkoutGitBranch).toHaveBeenCalledWith(+ expect.objectContaining({ branch: 'feat', path: '/code/lobehub' }),+ );+ });+});++describe('needsSendTimeGit', () => {+ it('is set only by a branch pick or the worktree switch', () => {+ expect(needsSendTimeGit(snapshotDraftGit(context))).toBe(false);+ pick('feat');+ expect(needsSendTimeGit(snapshotDraftGit(context))).toBe(true);+ setDraftBranch(draftBranchKey(target), undefined);+ setWorktreeMode(true);+ expect(needsSendTimeGit(snapshotDraftGit(context))).toBe(true);+ expect(needsSendTimeGit(undefined)).toBe(false);+ });+});++describe('prepareDraftGitSend — switch in place', () => {+ it('checks out the picked branch and clears the pick', async () => {+ pick('feat');+ const result = await prepareDraftGitSend(context, { prompts: prompts(), t });++ expect(result).toEqual({ acted: true, ok: true });+ expect(gitService.checkoutGitBranch).toHaveBeenCalledWith({+ branch: 'feat',+ deviceId: 'dev-1',+ path: '/code/lobehub',+ });+ expect(getDraftBranch(draftBranchKey(target))).toBeUndefined();+ });++ it('warns about uncommitted changes and running topics in one confirmation', async () => {+ pick('feat');+ vi.mocked(gitService.getGitWorkingTreeStatus).mockResolvedValue({+ added: 1,+ clean: false,+ deleted: 0,+ modified: 2,+ total: 3,+ });+ vi.mocked(deviceService.countRunningTopicsInDirectory).mockResolvedValue(2);+ const p = prompts();++ await prepareDraftGitSend(context, { prompts: p, t });++ expect(deviceService.countRunningTopicsInDirectory).toHaveBeenCalledWith('dev-1', target.path);+ expect(p.confirmSwitchRisks).toHaveBeenCalledWith({+ branch: 'feat',+ running: 2,+ uncommitted: 3,+ });+ expect(gitService.checkoutGitBranch).toHaveBeenCalled();+ });++ it('keeps the draft and does not switch when the warning is declined', async () => {+ pick('feat');+ vi.mocked(deviceService.countRunningTopicsInDirectory).mockResolvedValue(1);+ const p = prompts();+ p.confirmSwitchRisks.mockResolvedValue(false);++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ expect(getDraftBranch(draftBranchKey(target))).toBe('feat');+ });++ it('does not ask when the directory is clean and nothing else runs there', async () => {+ pick('feat');+ const p = prompts();+ await prepareDraftGitSend(context, { prompts: p, t });+ expect(p.confirmSwitchRisks).not.toHaveBeenCalled();+ });++ it('still switches when the running-topic count cannot be read', async () => {+ pick('feat');+ vi.mocked(deviceService.countRunningTopicsInDirectory).mockRejectedValue(new Error('down'));+ expect(await prepareDraftGitSend(context, { prompts: prompts(), t })).toEqual({+ acted: true,+ ok: true,+ });+ });++ it('reports a refused checkout and keeps the draft', async () => {+ pick('feat');+ vi.mocked(gitService.checkoutGitBranch).mockResolvedValue({+ error: 'error: Your local changes would be overwritten by checkout',+ success: false,+ });+ const p = prompts();++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(p.notifyError).toHaveBeenCalledWith({+ description: 'error: Your local changes would be overwritten by checkout',+ title: 'workingDirectory.switchFailed',+ });+ expect(getDraftBranch(draftBranchKey(target))).toBe('feat');+ });++ it('cuts a named branch from a branch another worktree holds', async () => {+ pick('feat');+ vi.mocked(gitService.listGitWorktrees).mockResolvedValue([+ { branch: 'main', current: true, path: '/code/lobehub' },+ { branch: 'feat', current: false, path: '/wt/feat' },+ ]);+ vi.mocked(gitService.checkoutGitBranch).mockResolvedValue({+ startPoint: 'feat',+ success: true,+ });+ const p = prompts();+ p.askBranchName.mockResolvedValue('lobehub/mine');++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({+ acted: true,+ ok: true,+ });+ expect(p.askBranchName).toHaveBeenCalledWith(+ expect.objectContaining({ branch: 'feat', holder: 'feat' }),+ );+ expect(p.askBranchName.mock.calls[0][0].defaultName).toMatch(/\//);+ expect(gitService.checkoutGitBranch).toHaveBeenCalledWith({+ branch: 'lobehub/mine',+ create: true,+ deviceId: 'dev-1',+ path: '/code/lobehub',+ startPoint: 'feat',+ });+ });++ it('stops when the branch-name prompt is cancelled', async () => {+ pick('feat');+ vi.mocked(gitService.listGitWorktrees).mockResolvedValue([+ { branch: 'feat', current: false, path: '/wt/feat' },+ ]);+ const p = prompts();+ p.askBranchName.mockResolvedValue(undefined);++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ });++ it('refuses before mutating on a device too old for a start point', async () => {+ pick('feat');+ vi.mocked(gitService.listGitWorktrees).mockResolvedValue([+ { branch: 'feat', current: false, path: '/wt/feat' },+ ]);+ vi.mocked(gitService.getGitAheadBehind).mockRejectedValue(+ new DeviceGitOutdatedError('"branch"'),+ );+ const p = prompts();++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ expect(p.notifyError).toHaveBeenCalledWith(+ expect.objectContaining({ description: 'workingDirectory.deviceOutdated' }),+ );+ });+});++describe('prepareDraftGitSend — new worktree', () => {+ beforeEach(() => {+ setWorktreeMode(true);+ vi.mocked(gitService.addGitWorktree).mockImplementation(async ({ branch, startPoint }) => ({+ ...(startPoint ? { startPoint } : {}),+ success: true,+ worktreePath: `/Users/me/.lobehub/worktrees/lobehub-0000beef/${branch.split('/').at(-1)}`,+ }));+ });++ it('forks the picked branch into a new worktree that becomes the topic directory', async () => {+ pick('feat');+ const p = prompts();+ const result = await prepareDraftGitSend(context, { prompts: p, t });++ const call = vi.mocked(gitService.addGitWorktree).mock.calls[0][0];+ expect(call).toMatchObject({+ deviceId: 'dev-1',+ path: '/code/lobehub',+ sourcePath: '/code/lobehub',+ startPoint: 'feat',+ stripBranchPrefix: true,+ });+ expect(call.branch).toMatch(/^[a-z]+\/\d{12}-[a-z]+-[a-z]+$/);+ expect(result).toEqual({+ acted: true,+ newTopicWorkingDirectory: {+ git: {+ activeWorktree: expect.stringContaining('/.lobehub/worktrees/'),+ autoCreated: true,+ autoCreatedAt: expect.any(String),+ branch: call.branch,+ isWorktree: true,+ },+ path: '/code/lobehub',+ repoType: 'github',+ sessionPath: expect.stringContaining('/.lobehub/worktrees/'),+ },+ ok: true,+ });+ // Nothing touches the source directory, so nothing is asked.+ expect(gitService.checkoutGitBranch).not.toHaveBeenCalled();+ expect(p.confirmSwitchRisks).not.toHaveBeenCalled();+ expect(deviceService.countRunningTopicsInDirectory).not.toHaveBeenCalled();+ });++ it('forks from HEAD without a start point when nothing else was picked', async () => {+ await prepareDraftGitSend(context, { prompts: prompts(), t });++ expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].startPoint).toBeUndefined();+ expect(gitService.getGitAheadBehind).not.toHaveBeenCalled();+ });++ it('reports a failed worktree and sends nothing', async () => {+ pick('feat');+ vi.mocked(gitService.addGitWorktree).mockResolvedValue({+ error: 'fatal: a branch named x already exists',+ success: false,+ });+ const p = prompts();++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(p.notifyError).toHaveBeenCalledWith({+ description: 'fatal: a branch named x already exists',+ title: 'workingDirectory.worktreeCreateFailed',+ });+ expect(getDraftBranch(draftBranchKey(target))).toBe('feat');+ });++ it('says to update the device when it ignored the start point', async () => {+ pick('feat');+ vi.mocked(gitService.addGitWorktree).mockResolvedValue({+ error: 'outdated',+ reason: DEVICE_GIT_OUTDATED,+ success: false,+ });+ const p = prompts();++ expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });+ expect(p.notifyError).toHaveBeenCalledWith(+ expect.objectContaining({ description: 'workingDirectory.deviceOutdated' }),+ );+ });+});diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.tsnew file mode 100644index 00000000000..8ce3ad0286d--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts@@ -0,0 +1,320 @@+import { generateWorktreeBranchName, WORKTREE_BRANCH_PREFIX } from '@lobechat/const';+import type { ConversationContext, WorkingDirConfig } from '@lobechat/types';+import { deriveWorktreePath } from '@lobechat/types';+import type { TFunction } from 'i18next';++import { deviceService } from '@/services/device';+import { gitService, isDeviceGitOutdated } from '@/services/git';+import { parseSingleAgentMentionDirectRoute } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';+import { gitStatusKey } from '@/store/device/gitStatus/projection';+import { getGitStatusStoreState } from '@/store/device/gitStatus/store';+import { getElectronStoreState } from '@/store/electron';+import { desktopStateSelectors } from '@/store/electron/selectors';+import { getUserStoreState } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++import { findWorktreeForBranch, getPathName } from '../worktreeHelpers';+import {+ draftBranchKey,+ type DraftGitTarget,+ getDraftBranch,+ getDraftGitTarget,+ setDraftBranch,+} from './draftGitStore';+import { describeGitFailure } from './gitErrors';+import { isWorktreeModeOn, worktreeModeKeyOf } from './useWorktreeMode';++/** The questions the send may have to ask, injected so the flow stays testable. */+export interface DraftGitSendPrompts {+ /** Name the branch cut from one another worktree holds; `undefined` cancels. */+ askBranchName: (params: {+ branch: string;+ defaultName: string;+ holder: string;+ }) => Promise<string | undefined>;+ /** Confirm a switch that may cost uncommitted work or disturb running topics. */+ confirmSwitchRisks: (params: {+ branch: string;+ running: number;+ uncommitted: number;+ }) => Promise<boolean>;+ notifyError: (params: { description: string; title: string }) => void;+ /** Show that the send is waiting on git; returns the dismiss callback. */+ showProgress: (label: string) => () => void;+}++export type DraftGitSendResult =+ | { ok: false }+ | {+ /**+ * Git was actually run (a switch or a new worktree), so the send waited+ * on it: the composer may have changed hands in the meantime.+ */+ acted?: boolean;+ newTopicWorkingDirectory?: WorkingDirConfig;+ ok: true;+ };++const PASS: DraftGitSendResult = { ok: true };+const STOP: DraftGitSendResult = { ok: false };++/**+ * The directory the send acts on, when it should act at all: the lab is on and+ * the send starts a new topic in an agent's composer that shows a git directory.+ */+export const resolveDraftGitTarget = (+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,+ editorData?: Record<string, any>,+): DraftGitTarget | undefined => {+ if (!labPreferSelectors.enableBetterCodingExperience(getUserStoreState())) return;+ if (context.topicId || context.groupId || context.threadId || !context.agentId) return;+ // A message that starts with a single `@Agent` runs that agent, on its own+ // device and directory: the composer's directory is not where it runs.+ const route = parseSingleAgentMentionDirectRoute(editorData);+ if (route && route.agent.id !== context.agentId) return;+ return getDraftGitTarget(context.agentId);+};++/**+ * Whether the device honours a start point other than HEAD. Device RPCs have+ * no version negotiation and an older device forks from HEAD regardless, so+ * ask before mutating: a named-branch ahead/behind read echoes the branch only+ * on a device new enough for both. The composer usually has that read cached.+ */+const deviceHonoursBranch = async (target: DraftGitTarget, branch: string): Promise<boolean> => {+ const { deviceId, path } = target;+ const cached =+ getGitStatusStoreState().gitAheadBehindMap[gitStatusKey({ branch, deviceId, path })];+ if (cached?.value?.branch === branch) return true;+ try {+ await gitService.getGitAheadBehind({ branch, deviceId, path });+ return true;+ } catch (error) {+ if (isDeviceGitOutdated(error)) return false;+ // Any other failure is the write's to report, with git's own message.+ return true;+ }+};++const listBranchNames = async ({ deviceId, path }: DraftGitTarget): Promise<string[]> => {+ try {+ return (await gitService.listGitBranches({ deviceId, path })).map((branch) => branch.name);+ } catch {+ // A colliding name is refused by git at create time; the draw just can't avoid it.+ return [];+ }+};++const countRunningTopics = async ({ keyDeviceId, path }: DraftGitTarget): Promise<number> => {+ if (!keyDeviceId) return 0;+ try {+ return await deviceService.countRunningTopicsInDirectory(keyDeviceId, path);+ } catch (error) {+ // A soft warning only: failing to count must not block the send.+ console.warn('[prepareDraftGitSend] could not count running topics', error);+ return 0;+ }+};++const createWorktree = async (+ target: DraftGitTarget,+ base: string | undefined,+ headBranch: string | undefined,+ { prompts, t }: { prompts: DraftGitSendPrompts; t: TFunction<'device'> },+): Promise<DraftGitSendResult> => {+ const fail = (description: string) => {+ prompts.notifyError({ description, title: t('workingDirectory.worktreeCreateFailed') });+ return STOP;+ };+ // Forking from HEAD needs nothing new from the device; only a different+ // start point does, so only then is it passed (and the device checked).+ const startPoint = base && base !== headBranch ? base : undefined;+ if (startPoint && !(await deviceHonoursBranch(target, startPoint)))+ return fail(t('workingDirectory.deviceOutdated'));++ const branch = generateWorktreeBranchName({ exclude: await listBranchNames(target) });+ const homeDir = target.deviceId+ ? undefined+ : desktopStateSelectors.userHomePath(getElectronStoreState()) || undefined;+ const dismiss = prompts.showProgress(t('workingDirectory.preparingWorktree'));+ try {+ const result = await gitService.addGitWorktree({+ branch,+ deviceId: target.deviceId,+ path: target.path,+ sourcePath: target.sourcePath,+ startPoint,+ stripBranchPrefix: true,+ // Local only: a remote device's folder is derived by the server.+ worktreePath: target.deviceId+ ? ''+ : deriveWorktreePath(target.sourcePath, branch, {+ homeDir,+ stripBranchPrefix: WORKTREE_BRANCH_PREFIX,+ }),+ });+ if (!result.success || !result.worktreePath)+ return fail(describeGitFailure(result, t, t('workingDirectory.worktreeCreateFailed')));++ return {+ acted: true,+ newTopicWorkingDirectory: {+ git: {+ activeWorktree: result.worktreePath,+ autoCreated: true,+ autoCreatedAt: new Date().toISOString(),+ branch,+ isWorktree: true,+ },+ path: target.sourcePath,+ repoType: target.isGithub ? 'github' : 'git',+ sessionPath: result.worktreePath,+ },+ ok: true,+ };+ } finally {+ dismiss();+ }+};++const switchInPlace = async (+ target: DraftGitTarget,+ picked: string,+ { prompts, t }: { prompts: DraftGitSendPrompts; t: TFunction<'device'> },+): Promise<DraftGitSendResult> => {+ const { deviceId, path } = target;+ const title = t('workingDirectory.switchFailed', { branch: picked });+ const fail = (description: string) => {+ prompts.notifyError({ description, title });+ return STOP;+ };++ // Git checks a branch out in one worktree at most. One held elsewhere is cut+ // into a new branch here instead, named by the user.+ const worktrees = await gitService.listGitWorktrees({ deviceId, path }).catch(() => []);+ const holder = findWorktreeForBranch(worktrees, picked);+ let checkout: { branch: string; create?: boolean; startPoint?: string } = { branch: picked };+ if (holder) {+ const name = await prompts.askBranchName({+ branch: picked,+ defaultName: generateWorktreeBranchName({ exclude: await listBranchNames(target) }),+ holder: getPathName(holder.path),+ });+ if (!name) return STOP;+ if (!(await deviceHonoursBranch(target, picked)))+ return fail(t('workingDirectory.deviceOutdated'));+ checkout = { branch: name, create: true, startPoint: picked };+ }++ const [status, running] = await Promise.all([+ gitService.getGitWorkingTreeStatus({ deviceId, path }).catch(() => undefined),+ countRunningTopics(target),+ ]);+ const uncommitted = status && !status.clean ? status.total : 0;+ if (+ (uncommitted > 0 || running > 0) &&+ !(await prompts.confirmSwitchRisks({ branch: checkout.branch, running, uncommitted }))+ )+ return STOP;++ const dismiss = prompts.showProgress(+ t('workingDirectory.preparingSwitch', { branch: checkout.branch }),+ );+ try {+ // Git's own rules: no stash, no force. Uncommitted changes travel with the+ // checkout, and a conflicting one makes git refuse — shown as is.+ const result = await gitService.checkoutGitBranch({ deviceId, path, ...checkout });+ if (!result.success)+ return fail(describeGitFailure(result, t, t('workingDirectory.checkoutFailed')));+ } finally {+ dismiss();+ }+ await getGitStatusStoreState().revalidateGitStatus(deviceId, path);+ return { acted: true, ok: true };+};++/**+ * The git half of a new topic's first send under Better Coding Experience,+ * run before the user message is saved. The picked branch is acted on now:+ *+ * - "New worktree" on: a new `lobehub/…` branch is cut from it into its own+ * worktree, which becomes the new topic's directory; this directory is left+ * alone, so there is nothing to warn about.+ * - Off: this directory switches to it — through a new branch when another+ * worktree holds it — after warning about uncommitted changes and other+ * topics running here.+ *+ * Any failure or cancellation returns `ok: false`: the caller does not send+ * and keeps the draft.+ */+/**+ * What the send will act on, read from the composer at the moment the user+ * sends. A send that runs later (a voice turn, after upload and transcription)+ * takes this snapshot along: by then the composer may show another+ * conversation and have dropped this directory's registration.+ */+export interface DraftGitSnapshot {+ picked?: string;+ target: DraftGitTarget;+ worktreeMode: boolean;+}++export const snapshotDraftGit = (+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,+ editorData?: Record<string, any>,+): DraftGitSnapshot | undefined => {+ const target = resolveDraftGitTarget(context, editorData);+ if (!target) return;+ return {+ picked: getDraftBranch(draftBranchKey(target)),+ target,+ worktreeMode: isWorktreeModeOn(worktreeModeKeyOf(target.keyDeviceId, target.path)),+ };+};++/**+ * Whether the snapshot asks the send to run git (switch to a picked branch, or+ * fork a worktree). A deferred send ("Send later") cannot: the scheduled run+ * creates its topic server-side, long after the composer, from the agent's+ * defaults — so the composer refuses to schedule instead of dropping the choice.+ */+export const needsSendTimeGit = (snapshot: DraftGitSnapshot | undefined): boolean =>+ !!snapshot && (!!snapshot.picked || snapshot.worktreeMode);++export const prepareDraftGitSend = async (+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,+ {+ editorData,+ prompts,+ snapshot,+ t,+ }: {+ editorData?: Record<string, any>;+ prompts: DraftGitSendPrompts;+ /** Taken when the user sent; read from the composer now when absent. */+ snapshot?: DraftGitSnapshot;+ t: TFunction<'device'>;+ },+): Promise<DraftGitSendResult> => {+ const snap = snapshot ?? snapshotDraftGit(context, editorData);+ if (!snap) return PASS;+ const { picked, target, worktreeMode } = snap;+ const key = draftBranchKey(target);+ if (!picked && !worktreeMode) return PASS;++ // Act on what the directory is on now, not on the bar's last read.+ const head = await gitService+ .getGitBranch({ deviceId: target.deviceId, path: target.path })+ .catch(() => undefined);+ const headBranch = head?.detached ? undefined : head?.branch;++ const result = worktreeMode+ ? await createWorktree(target, picked ?? head?.branch, headBranch, { prompts, t })+ : picked && picked !== headBranch+ ? await switchInPlace(target, picked, { prompts, t })+ : PASS;++ // Done with: the pick now describes the directory (or its new worktree).+ if (result.ok) setDraftBranch(key, undefined);+ return result;+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/sendPrompts.tsx b/src/features/ChatInput/ControlBar/DraftGit/sendPrompts.tsxnew file mode 100644index 00000000000..abad0976242--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/sendPrompts.tsx@@ -0,0 +1,156 @@+'use client';++import { Button, createModal, Flexbox, Input, Text, toast, useModalContext } from '@lobehub/ui';+import { t } from 'i18next';+import { type ReactNode, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { DraftGitSendPrompts } from './prepareSend';++/**+ * Open a modal whose content settles a promise; dismissing it any other way+ * (Esc, backdrop, ✕) settles it with `fallback`.+ */+const ask = <T,>(+ title: ReactNode,+ render: (settle: (value: T) => void) => ReactNode,+ fallback: T,+): Promise<T> =>+ new Promise<T>((resolve) => {+ let settled = false;+ const settle = (value: T) => {+ if (settled) return;+ settled = true;+ resolve(value);+ };+ createModal({+ content: render(settle),+ footer: null,+ maskClosable: true,+ onOpenChangeComplete: (open) => {+ if (!open) settle(fallback);+ },+ styles: { header: { borderBottom: 'none' } },+ title,+ width: 'min(90vw, 480px)',+ });+ });++interface BranchNameContentProps {+ branch: string;+ defaultName: string;+ holder: string;+ onDone: (name: string | undefined) => void;+}++const BranchNameContent = ({ branch, defaultName, holder, onDone }: BranchNameContentProps) => {+ const { t: tDevice } = useTranslation('device');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ const [value, setValue] = useState(defaultName);+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ queueMicrotask(() => inputRef.current?.select());+ }, []);++ const finish = (name: string | undefined) => {+ onDone(name);+ close();+ };+ const submit = () => {+ const name = value.trim();+ if (name) finish(name);+ };++ return (+ <Flexbox gap={16}>+ <Text type={'secondary'}>+ {tDevice('workingDirectory.occupiedBranchDesc', { branch, name: holder })}+ </Text>+ <Flexbox gap={6}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {tDevice('workingDirectory.occupiedBranchNameLabel')}+ </Text>+ <Input+ ref={inputRef}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onPressEnter={submit}+ />+ </Flexbox>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={() => finish(undefined)}>{tCommon('cancel')}</Button>+ <Button disabled={!value.trim()} type={'primary'} onClick={submit}>+ {tDevice('workingDirectory.occupiedBranchConfirm')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};++interface SwitchRiskContentProps {+ onDone: (confirmed: boolean) => void;+ running: number;+ uncommitted: number;+}++const SwitchRiskContent = ({ onDone, running, uncommitted }: SwitchRiskContentProps) => {+ const { t: tDevice } = useTranslation('device');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();++ const finish = (confirmed: boolean) => {+ onDone(confirmed);+ close();+ };++ return (+ <Flexbox gap={16}>+ <Flexbox gap={8}>+ {uncommitted > 0 && (+ <Text>{tDevice('workingDirectory.switchRiskUncommitted', { count: uncommitted })}</Text>+ )}+ {running > 0 && (+ <Text>{tDevice('workingDirectory.switchRiskRunning', { count: running })}</Text>+ )}+ </Flexbox>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={() => finish(false)}>{tCommon('cancel')}</Button>+ <Button danger={uncommitted > 0} type={'primary'} onClick={() => finish(true)}>+ {tDevice('workingDirectory.switchRiskConfirm')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};++/** The send-time prompts, as modals and toasts. */+export const draftGitSendPrompts: DraftGitSendPrompts = {+ askBranchName: ({ branch, defaultName, holder }) =>+ ask<string | undefined>(+ t('workingDirectory.occupiedBranchTitle', { branch, ns: 'device' }),+ (settle) => (+ <BranchNameContent+ branch={branch}+ defaultName={defaultName}+ holder={holder}+ onDone={settle}+ />+ ),+ undefined,+ ),+ confirmSwitchRisks: ({ branch, running, uncommitted }) =>+ ask<boolean>(+ t('workingDirectory.switchRiskTitle', { branch, ns: 'device' }),+ (settle) => <SwitchRiskContent running={running} uncommitted={uncommitted} onDone={settle} />,+ false,+ ),+ notifyError: ({ description, title }) => {+ toast.error({ description, title });+ },+ showProgress: (label) => {+ const instance = toast.loading(label);+ return () => instance.close();+ },+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.test.ts b/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.test.tsnew file mode 100644index 00000000000..274ee8c3819--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.test.ts@@ -0,0 +1,66 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { draftBranchKey, getDraftGitTarget, useDraftGitStore } from './draftGitStore';+import { useDraftBranch } from './useDraftBranch';++const base = {+ agentId: 'agent-1',+ currentBranch: 'main',+ isGithub: true,+ path: '/code/lobehub',+ sourcePath: '/code/lobehub',+};++beforeEach(() => {+ useDraftGitStore.setState({ selections: {}, targets: {} });+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-mac' } } as any);+});++describe('useDraftBranch', () => {+ it('defaults the pick to HEAD and records another branch without checking out', () => {+ const { result } = renderHook(() => useDraftBranch({ ...base, enabled: true }));+ expect(result.current.selectedBranch).toBe('main');++ act(() => result.current.select('feat'));+ expect(result.current.selectedBranch).toBe('feat');++ // Picking HEAD's branch again clears the pick, so the draft follows HEAD.+ act(() => result.current.select('main'));+ expect(useDraftGitStore.getState().selections).toEqual({});+ });++ it('registers the directory under the real device id, also for this machine', () => {+ const { unmount } = renderHook(() => useDraftBranch({ ...base, enabled: true }));+ expect(getDraftGitTarget('agent-1')).toMatchObject({+ deviceId: undefined,+ keyDeviceId: 'this-mac',+ path: '/code/lobehub',+ });++ unmount();+ expect(getDraftGitTarget('agent-1')).toBeUndefined();+ });++ it('keeps picks per device and directory apart', () => {+ const { result, rerender } = renderHook((props) => useDraftBranch(props), {+ initialProps: { ...base, enabled: true },+ });+ act(() => result.current.select('feat'));++ rerender({ ...base, enabled: true, path: '/code/other', sourcePath: '/code/other' });+ expect(result.current.selectedBranch).toBe('main');+ expect(+ useDraftGitStore.getState().selections[+ draftBranchKey({ agentId: 'agent-1', keyDeviceId: 'this-mac', path: '/code/lobehub' })+ ],+ ).toBe('feat');+ });++ it('registers nothing for an existing topic', () => {+ renderHook(() => useDraftBranch({ ...base, enabled: false }));+ expect(getDraftGitTarget('agent-1')).toBeUndefined();+ });+});diff --git a/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.ts b/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.tsnew file mode 100644index 00000000000..276303ae668--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/useDraftBranch.ts@@ -0,0 +1,69 @@+import { useCallback, useEffect, useMemo } from 'react';++import { useElectronStore } from '@/store/electron';++import {+ draftBranchKey,+ type DraftGitTarget,+ registerDraftGitTarget,+ setDraftBranch,+ unregisterDraftGitTarget,+ useDraftGitStore,+} from './draftGitStore';++interface UseDraftBranchOptions {+ agentId: string;+ /** HEAD's branch in `path`, which the pick defaults to. */+ currentBranch?: string;+ deviceId?: string;+ /** False leaves nothing registered (an existing topic, or the lab off). */+ enabled: boolean;+ isGithub: boolean;+ path: string;+ sourcePath: string;+}++/**+ * The branch picked for a new topic's first send, and the registration that+ * lets the send find this directory. Picking HEAD's branch clears the pick, so+ * an untouched draft keeps following whatever HEAD is.+ */+export const useDraftBranch = ({+ agentId,+ currentBranch,+ deviceId,+ enabled,+ isGithub,+ path,+ sourcePath,+}: UseDraftBranchOptions) => {+ const localDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const keyDeviceId = deviceId ?? localDeviceId;++ const target = useMemo<DraftGitTarget | undefined>(+ () =>+ enabled && path+ ? { agentId, deviceId, isGithub, keyDeviceId, path, sourcePath: sourcePath || path }+ : undefined,+ [agentId, deviceId, enabled, isGithub, keyDeviceId, path, sourcePath],+ );++ useEffect(() => {+ if (!target) return;+ registerDraftGitTarget(target);+ return () => unregisterDraftGitTarget(target);+ }, [target]);++ const key = target ? draftBranchKey(target) : undefined;+ const picked = useDraftGitStore((s) => (key ? s.selections[key] : undefined));++ const select = useCallback(+ (branch: string) => {+ if (!key) return;+ setDraftBranch(key, branch === currentBranch ? undefined : branch);+ },+ [currentBranch, key],+ );++ return { keyDeviceId, select, selectedBranch: picked ?? currentBranch, target };+};diff --git a/src/features/ChatInput/ControlBar/DraftGit/useWorktreeMode.ts b/src/features/ChatInput/ControlBar/DraftGit/useWorktreeMode.tsnew file mode 100644index 00000000000..30744b9740b--- /dev/null+++ b/src/features/ChatInput/ControlBar/DraftGit/useWorktreeMode.ts@@ -0,0 +1,60 @@+import { getWorktreeModeKey } from '@lobechat/types';+import { toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import {+ getActiveWorkspaceId,+ useActiveWorkspaceId,+} from '@/business/client/hooks/useActiveWorkspaceId';+import { getUserStoreState, useUserStore } from '@/store/user';+import type { UserState } from '@/store/user/initialState';++/**+ * The stored "New worktree" directories of whoever is acting now: this member's+ * workspace bucket inside a workspace, `users.preference` in personal mode.+ * `undefined` while the workspace bucket has not loaded — not "all off".+ */+const selectWorktreeModeDirs =+ (workspaceId: string | null | undefined) =>+ (state: UserState): string[] | undefined => {+ if (!workspaceId) return state.preference.worktreeModeDirs ?? [];+ return state.workspaceUserPreferenceWorkspaceId === workspaceId+ ? (state.workspaceUserPreference.worktreeModeDirs ?? [])+ : undefined;+ };++/** Whether the switch is on for `key`, read at send time. Unknown reads as off. */+export const isWorktreeModeOn = (key: string): boolean =>+ !!selectWorktreeModeDirs(getActiveWorkspaceId())(getUserStoreState())?.includes(key);++export const worktreeModeKeyOf = (keyDeviceId: string | undefined, path: string) =>+ getWorktreeModeKey(keyDeviceId ?? 'local', path);++/**+ * The composer's "New worktree" switch for one device + directory. Remembered+ * per workspace + user (see `setWorktreeModeDir`), so another directory, or the+ * same directory in another workspace, keeps its own state.+ */+export const useWorktreeMode = (keyDeviceId: string | undefined, path: string) => {+ const { t } = useTranslation('device');+ const workspaceId = useActiveWorkspaceId();+ useUserStore((s) => s.useFetchWorkspaceUserPreference)();+ const key = worktreeModeKeyOf(keyDeviceId, path);+ const dirs = useUserStore(selectWorktreeModeDirs(workspaceId));+ const setWorktreeModeDir = useUserStore((s) => s.setWorktreeModeDir);++ const setEnabled = useCallback(+ async (enabled: boolean) => {+ try {+ await setWorktreeModeDir(key, enabled);+ } catch (error) {+ console.error('[useWorktreeMode] save failed', error);+ toast.error(t('workingDirectory.worktreeToggleSaveFailed'));+ }+ },+ [key, setWorktreeModeDir, t],+ );++ return { enabled: !!dirs?.includes(key), key, ready: dirs !== undefined, setEnabled };+};diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex c244e6de33e..958d6299f2c 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -2,12 +2,12 @@ import type { WorkingDirGitState } from '@lobechat/types';import { Icon, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { ArrowDownIcon, ArrowUpIcon, GitPullRequest } from 'lucide-react';+import { ArrowDownIcon, ArrowUpIcon, GitPullRequest, TriangleAlertIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import RingLoadingIcon from '@/components/RingLoading';-import { gitService } from '@/services/git';+import { gitService, isDeviceGitOutdated } from '@/services/git';import {deviceSelectors,useDeviceStore,@@ -20,9 +20,14 @@ import {} from '@/store/device';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import BranchSwitcher from './BranchSwitcher';+import { describeGitFailure } from './DraftGit/gitErrors';+import { useDraftBranch } from './DraftGit/useDraftBranch';+import { WorktreeToggle } from './DraftGit/WorktreeToggle';import { gitChipStyles } from './gitChipStyles';import StaleGitSnapshot from './StaleGitSnapshot';import WorktreeSwitcher from './WorktreeSwitcher';@@ -45,6 +50,13 @@ const styles = stylex.create({textOverflow: 'ellipsis',whiteSpace: 'nowrap',},+ // An existing topic's branch under Better Coding Experience: a label, not a control.+ branchStatic: {+ cursor: 'default',+ backgroundColor: { 'default': null, ':hover': 'transparent' },+ backgroundImage: { 'default': null, ':hover': 'none' },+ },+ outdatedStat: { cursor: 'default', color: cssVar.colorWarning },diffStat: {display: 'inline-flex',flexShrink: 0,@@ -161,10 +173,30 @@ const GitStatus = memo<GitStatusProps>(!sourceWorktrees.some((worktree) => worktree.path === path && !worktree.prunable);const isStale =probeFoundNothing && (!!fallbackGit?.branch || (!!recordedWorktree && recordedWorktreeGone));+ // Better Coding Experience: before a topic's first send the branch is only+ // picked (the send switches or forks a worktree); an existing topic's+ // branch is shown but no longer switched from here.+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);+ const isDraft = betterCoding && !topicId;+ const draft = useDraftBranch({+ agentId,+ currentBranch: detached ? undefined : branch,+ deviceId,+ enabled: isDraft && !isStale,+ isGithub,+ path,+ sourcePath: sourcePath ?? path,+ });+ // The picked branch when it is not HEAD's: counts, pull and push follow it.+ // When it is HEAD's they read HEAD, exactly as without the lab.+ const syncBranch =+ isDraft && draft.selectedBranch && draft.selectedBranch !== branch+ ? draft.selectedBranch+ : undefined;const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(deviceId,path,- branch,+ syncBranch ?? branch,isGithub,);// The remaining reads are all disabled once the directory is gone: nothing@@ -185,9 +217,11 @@ const GitStatus = memo<GitStatusProps>(const livePath = isStale ? undefined : path;const {data: aheadBehind,+ error: aheadBehindError,isConfirmed: aheadBehindConfirmed,mutate: mutateAheadBehind,- } = useFetchGitAheadBehind(deviceId, livePath);+ } = useFetchGitAheadBehind(deviceId, livePath, syncBranch);+ const deviceOutdated = !!syncBranch && isDeviceGitOutdated(aheadBehindError);const {data: worktrees = [],isConfirmed: worktreesConfirmed,@@ -207,6 +241,7 @@ const GitStatus = memo<GitStatusProps>(prData !== undefined? prData.pullRequest: isGithub &&+ !syncBranch &&(!branch || branch === fallbackGit?.branch) &&fallbackGit?.github?.pullRequest? fallbackGit.github.pullRequest@@ -265,7 +300,11 @@ const GitStatus = memo<GitStatusProps>(if (pulling || pushing) return;setPulling(true);try {- const result = await gitService.pullGitBranch({ deviceId, path });+ const result = await gitService.pullGitBranch({+ deviceId,+ path,+ ...(syncBranch ? { branch: syncBranch } : {}),+ });if (result.success) {if (result.noop) {toast.info(t('workingDirectory.pullNoop'));@@ -274,18 +313,22 @@ const GitStatus = memo<GitStatusProps>(}await refreshAfterSync();} else {- toast.error(result.error || t('workingDirectory.pullFailed'));+ toast.error(describeGitFailure(result, t, t('workingDirectory.pullFailed')));}} finally {setPulling(false);}- }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);+ }, [deviceId, path, pulling, pushing, refreshAfterSync, syncBranch, t]);const handlePush = useCallback(async () => {if (pulling || pushing) return;setPushing(true);try {- const result = await gitService.pushGitBranch({ deviceId, path });+ const result = await gitService.pushGitBranch({+ deviceId,+ path,+ ...(syncBranch ? { branch: syncBranch } : {}),+ });if (result.success) {if (result.noop) {toast.info(t('workingDirectory.pushNoop'));@@ -294,12 +337,12 @@ const GitStatus = memo<GitStatusProps>(}await refreshAfterSync();} else {- toast.error(result.error || t('workingDirectory.pushFailed'));+ toast.error(describeGitFailure(result, t, t('workingDirectory.pushFailed')));}} finally {setPushing(false);}- }, [deviceId, path, pulling, pushing, refreshAfterSync, t]);+ }, [deviceId, path, pulling, pushing, refreshAfterSync, syncBranch, t]);const liveDiffStats = useMemo(() => {const patches = [@@ -402,12 +445,18 @@ const GitStatus = memo<GitStatusProps>(const pushTargetExists = !!aheadBehind?.pushTargetExists;const branchTrigger = (- <div {...stylex.props(gitChipStyles.trigger)}>- <span {...stylex.props(styles.branchLabel)}>{branch}</span>+ <div+ {...stylex.props(gitChipStyles.trigger, betterCoding && !isDraft && styles.branchStatic)}+ >+ <span {...stylex.props(styles.branchLabel)}>+ {(isDraft && draft.selectedBranch) || branch}+ </span></div>);- const hasWorktreeMenu = worktrees.length > 0;+ // The worktree menu is gone under the lab: a new topic forks its worktree+ // on send instead (the toggle below), and an existing one keeps its own.+ const hasWorktreeMenu = !betterCoding && worktrees.length > 0;const worktreeNode = hasWorktreeMenu ? (<WorktreeSwitcher@@ -425,40 +474,47 @@ const GitStatus = memo<GitStatusProps>(/>) : null;- const branchNode = detached ? (- // Detached HEAD → plain branch label (nothing to switch to).- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>- ) : !pickersReady ? (- // Hydrated from the last session: hold the checkout entry until this- // session's branch AND worktree probes answer, so the switcher's "current"- // branch and its worktree routing are not stale guesses.- <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>- ) : (- // Local switches over IPC; a remote device switches over RPC (deviceId set).- <BranchSwitcher- agentId={agentId}- currentBranch={branch}- deviceId={deviceId}- isGithub={isGithub}- open={switcherOpen}- path={path}- sourcePath={sourcePath ?? path}- topicId={topicId}- worktrees={worktrees}- onExternalRefresh={refreshAfterSync}- onOpenChange={setSwitcherOpen}- onOptimisticCheckout={handleOptimisticCheckout}- onAfterCheckout={() => {- void mutateBranch();- void mutatePR();- void mutateReviewPatches();- void mutateAheadBehind();- void mutateWorktrees();- }}- >+ const branchNode =+ betterCoding && !isDraft ? (+ // An existing topic stays on its branch; start a new topic to move.<Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>- </BranchSwitcher>- );+ ) : detached && !isDraft ? (+ // Detached HEAD → plain branch label (nothing to switch to).+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>+ ) : !pickersReady ? (+ // Hydrated from the last session: hold the checkout entry until this+ // session's branch AND worktree probes answer, so the switcher's "current"+ // branch and its worktree routing are not stale guesses.+ <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>+ ) : (+ // Local switches over IPC; a remote device switches over RPC (deviceId set).+ <BranchSwitcher+ agentId={agentId}+ currentBranch={branch}+ deviceId={deviceId}+ isGithub={isGithub}+ open={switcherOpen}+ path={path}+ selection={isDraft ? { branch: draft.selectedBranch, onSelect: draft.select } : undefined}+ sourcePath={sourcePath ?? path}+ topicId={topicId}+ worktrees={worktrees}+ onExternalRefresh={refreshAfterSync}+ onOpenChange={setSwitcherOpen}+ onOptimisticCheckout={handleOptimisticCheckout}+ onAfterCheckout={() => {+ void mutateBranch();+ void mutatePR();+ void mutateReviewPatches();+ void mutateAheadBehind();+ void mutateWorktrees();+ }}+ >+ <Tooltip title={isDraft ? draft.selectedBranch || branchTooltip : branchTooltip}>+ {branchTrigger}+ </Tooltip>+ </BranchSwitcher>+ );const pullTooltip = pulling? t('workingDirectory.pullInProgress')@@ -516,6 +572,22 @@ const GitStatus = memo<GitStatusProps>(</Tooltip>);+ const outdatedNode = deviceOutdated && (+ <Tooltip title={t('workingDirectory.deviceOutdated')}>+ <div {...stylex.props(styles.syncTrigger, styles.outdatedStat)}>+ <Icon icon={TriangleAlertIcon} size={11} />+ </div>+ </Tooltip>+ );++ const worktreeToggleNode = isDraft && (+ <WorktreeToggle+ baseBranch={draft.selectedBranch}+ keyDeviceId={draft.keyDeviceId}+ path={path}+ />+ );+const diffNode = (() => {if (!hasChanges) return null;const diffButton = (@@ -547,6 +619,8 @@ const GitStatus = memo<GitStatusProps>(</div>{pullNode}{pushNode}+ {outdatedNode}+ {worktreeToggleNode}{diffNode}{pullRequest && (<>diff --git a/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsxindex b72c67f6d46..de478991e01 100644--- a/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx+++ b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx@@ -9,8 +9,12 @@ import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { useFetchGitBranch } from '@/store/device';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import BranchSwitcher from './BranchSwitcher';+import { useDraftBranch } from './DraftGit/useDraftBranch';+import { WorktreeToggle } from './DraftGit/WorktreeToggle';import { gitChipStyles } from './gitChipStyles';import { getStagedBranchState } from './stagedBranchState';import { useStagedProjectGitTarget } from './useStagedProjectGitTarget';@@ -53,6 +57,18 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {const target = useStagedProjectGitTarget(agentId);const { data, isConfirmed, mutate } = useFetchGitBranch(target?.deviceId, target?.path);const [open, setOpen] = useState(false);+ // Better Coding Experience: the branch is only picked here; the first send+ // switches to it, or forks a worktree from it.+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);+ const draft = useDraftBranch({+ agentId,+ currentBranch: data?.detached ? undefined : data?.branch,+ deviceId: target?.deviceId,+ enabled: betterCoding && !!target,+ isGithub: !!target?.isGithub,+ path: target?.path ?? '',+ sourcePath: target?.path ?? '',+ });const handleOptimisticCheckout = useCallback((branch: string) => {@@ -64,10 +80,11 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {const state = getStagedBranchState(data, isConfirmed);if (!target || state === 'hidden') return null;const branch = data!.branch!;+ const label = (betterCoding && draft.selectedBranch) || branch;const trigger = (<div {...stylex.props(gitChipStyles.trigger)}>- <span {...stylex.props(styles.branchLabel)}>{branch}</span>+ <span {...stylex.props(styles.branchLabel)}>{label}</span></div>);@@ -78,7 +95,7 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {<span {...stylex.props(styles.branchIcon)}><Icon icon={GitBranchIcon} size={13} /></span>- {state === 'detached' ? (+ {state === 'detached' && !betterCoding ? (<Tooltip title={t('workingDirectory.detachedHead', { sha: branch })}>{trigger}</Tooltip>) : state === 'confirming' ? (<Tooltip title={t('workingDirectory.branchConfirming')}>{trigger}</Tooltip>@@ -93,14 +110,24 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {sourcePath={target.path}topicId={null}worktrees={NO_WORKTREES}+ selection={+ betterCoding ? { branch: draft.selectedBranch, onSelect: draft.select } : undefined+ }onAfterCheckout={() => void mutate()}onOpenChange={setOpen}onOptimisticCheckout={handleOptimisticCheckout}>- <Tooltip title={branch}>{trigger}</Tooltip>+ <Tooltip title={label}>{trigger}</Tooltip></BranchSwitcher>)}</div>+ {betterCoding && (+ <WorktreeToggle+ baseBranch={draft.selectedBranch}+ keyDeviceId={draft.keyDeviceId}+ path={target.path}+ />+ )}</>);});diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsxindex 299ce110cc7..705929a04d2 100644--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx@@ -492,7 +492,12 @@ describe('GitStatus', () => {undefined,false,);- expect(gitHookMocks.useFetchGitAheadBehind).toHaveBeenCalledWith(undefined, undefined);+ // No branch either: the counts describe HEAD, as without the lab.+ expect(gitHookMocks.useFetchGitAheadBehind).toHaveBeenCalledWith(+ undefined,+ undefined,+ undefined,+ );expect(gitHookMocks.useFetchGitWorktrees).toHaveBeenCalledWith(undefined, undefined);});diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex c0ca5419776..059bde26ba0 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -7,6 +7,7 @@ import {type ChatInputProps as EditorChatInputProps,} from '@lobehub/editor/react';import { type DropdownItem, Flexbox, toast } from '@lobehub/ui';+import i18next from 'i18next';import { type ReactNode } from 'react';import { memo, useCallback, useEffect, useMemo, useRef } from 'react';@@ -16,6 +17,12 @@ import {} from '@/business/client/hooks/useBusinessChatInputSendAreaPrefix';import type { ActionKeys, ChatInputFeature } from '@/features/ChatInput';import { ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';+import {+ needsSendTimeGit,+ prepareComposerGitSend,+ snapshotDraftGit,+} from '@/features/ChatInput/ControlBar/DraftGit';+import { resolveComposerHandoff } from '@/features/ChatInput/ControlBar/DraftGit/composerHandoff';import {type SendButtonHandler,type SendButtonProps,@@ -392,13 +399,33 @@ const ChatInput = memo<ChatInputProps>(// the request failed) leaves no message row to recover the text from, so// an up-front clear would simply lose it.if (storeApi.getState().scheduledSendAt) {+ // The scheduled run is created server-side later and cannot switch+ // the picked branch or fork a worktree: refuse rather than drop them.+ if (needsSendTimeGit(snapshotDraftGit(sendContext, editorData))) {+ toast.error(i18next.t('workingDirectory.scheduleGitUnsupported', { ns: 'device' }));+ return;+ }const scheduled = await storeApi.getState().commitScheduledSend(message, currentFileList);if (scheduled) clearComposer();return;}- // Clear content immediately for responsive UX- clearComposer();+ // A new topic's first send acts on the branch picked in the composer+ // (switch, or fork a worktree) before any message exists. Cancelled or+ // failed, nothing is sent and the draft stays.+ const gitPrep = await prepareComposerGitSend(sendContext, { editorData });+ if (!gitPrep.ok) return;++ // Clear content immediately for responsive UX — unless a git step ran+ // and the composer changed hands meanwhile (see `resolveComposerHandoff`).+ const handoff = resolveComposerHandoff({+ acted: !!gitPrep.acted,+ editorUnchanged: getMarkdownContent() === message,+ stillHere: messageMapKey(storeApi.getState().context) === messageMapKey(sendContext),+ });+ if (handoff.clearEditor) clearContent();+ fileStore.clearChatUploadFileList(contextKey);+ fileStore.clearChatContextSelections(contextKey);const { contextSelections, pageSelections } =buildMessageContextSelections(currentContextList);@@ -409,6 +436,10 @@ const ChatInput = memo<ChatInputProps>(editorData,files: currentFileList,message,+ ...(gitPrep.newTopicWorkingDirectory+ ? { newTopicWorkingDirectory: gitPrep.newTopicWorkingDirectory }+ : {}),+ ...(handoff.sendToOrigin ? { conversationContext: sendContext } : {}),onPreflightFailure: () => {const store = useFileStore.getState();// The composer was cleared up front; a send rejected before any@@ -441,6 +472,11 @@ const ChatInput = memo<ChatInputProps>(return false;}+ // Read the branch pick and worktree switch now: the send runs after+ // upload and transcription, by when the composer may show another+ // conversation.+ const gitSnapshot = snapshotDraftGit(context) ?? null;+return Boolean(useChatStore.getState().sendVoiceMessage({canSend: canSendVoiceMessage,@@ -450,6 +486,9 @@ const ChatInput = memo<ChatInputProps>(sendVoiceMessage(sendMessage, file, {context: targetContext,optimisticUserMessageId: messageId,+ // The same send-time git step as a typed first message.+ prepare: () =>+ prepareComposerGitSend(targetContext ?? context, { snapshot: gitSnapshot }),signal,...(isVoiceMessageTranscribed(targetContext)? {diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.test.tsindex 4b3756f1712..d7b6ff998a5 100644--- a/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts@@ -163,4 +163,45 @@ describe('sendVoiceMessage', () => {).rejects.toMatchObject({ name: 'AbortError' });expect(sendMessage).not.toHaveBeenCalled();});++ // A new topic's first turn runs the composer's git step first, like a typed send.+ it('sends into the worktree the git step prepared', async () => {+ const newTopicWorkingDirectory = { git: { activeWorktree: '/wt/x' }, path: '/repo' };+ const sendMessage = vi.fn(async (params: SendMessageParams) => {+ params.onMessageAccepted?.();+ });++ await sendVoiceMessage(sendMessage, voiceFile, {+ prepare: async () => ({ newTopicWorkingDirectory, ok: true }),+ });++ expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ newTopicWorkingDirectory }));+ });++ it('sends nothing, and keeps the recording retryable, when the git step stops', async () => {+ const sendMessage = vi.fn();++ await expect(+ sendVoiceMessage(sendMessage, voiceFile, {+ prepare: async () => ({ ok: false }),+ transcribe: async () => 'hello',+ }),+ ).rejects.toThrow();+ expect(sendMessage).not.toHaveBeenCalled();+ });++ // A failed transcript is retried; the git step must not have run for it.+ it('transcribes before the git step, so a failed transcript spends no branch pick', async () => {+ const prepare = vi.fn(async () => ({ ok: true as const }));++ await expect(+ sendVoiceMessage(vi.fn(), voiceFile, {+ prepare,+ transcribe: async () => {+ throw new Error('asr down');+ },+ }),+ ).rejects.toThrow('asr down');+ expect(prepare).not.toHaveBeenCalled();+ });});diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.tsindex a92d55d1e87..81509cce25e 100644--- a/src/features/Conversation/ChatInput/sendVoiceMessage.ts+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.ts@@ -2,6 +2,7 @@ import {type ConversationContext,type SendMessageParams,type UploadFileItem,+ type WorkingDirConfig,} from '@lobechat/types';type SendMessage = (@@ -11,6 +12,14 @@ type SendMessage = (interface SendVoiceMessageOptions {context?: ConversationContext;optimisticUserMessageId?: string;+ /**+ * Run before anything is dispatched — the composer's send-time git step for a+ * new topic. `ok: false` (cancelled or failed) rejects the send, which keeps+ * the recording as a retryable failed turn.+ */+ prepare?: () => Promise<+ { ok: false } | { newTopicWorkingDirectory?: WorkingDirConfig; ok: true }+ >;signal?: AbortSignal;/*** Resolve the turn text from the uploaded recording. Runtimes that cannot take audio input@@ -33,12 +42,20 @@ export const sendVoiceMessage = async (file: UploadFileItem,options: SendVoiceMessageOptions = {},) => {- const { context, optimisticUserMessageId, signal, transcribe } = options;+ const { context, optimisticUserMessageId, prepare, signal, transcribe } = options;if (signal?.aborted) throw getAbortError(signal);const message = transcribe ? await transcribe(file, signal) : '';if (signal?.aborted) throw getAbortError(signal);+ // After transcription, the last step that can fail before dispatch: a retry+ // after a failed transcript must still find the branch pick unspent and no+ // worktree made for it.+ const prepared = prepare ? await prepare() : undefined;+ if (prepared && !prepared.ok)+ throw new Error('Voice message was not sent: git step did not complete');+ if (signal?.aborted) throw getAbortError(signal);+return new Promise<void>((resolve, reject) => {let accepted = false;@@ -50,6 +67,9 @@ export const sendVoiceMessage = async (resolve();},preserveComposer: true,+ ...(prepared?.ok && prepared.newTopicWorkingDirectory+ ? { newTopicWorkingDirectory: prepared.newTopicWorkingDirectory }+ : {}),...(context ? { conversationContext: context } : {}),...(optimisticUserMessageId ? { optimisticUserMessageId } : {}),...(signal ? { signal } : {}),diff --git a/src/services/device.ts b/src/services/device.tsindex e5b13ec4d90..b0fce3dcf92 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -65,6 +65,14 @@ class DeviceService {* `statPath` RPC). Returns `null` when the device is unreachable — callers* treat "can't verify" as non-blocking.*/+ /**+ * Conversations running in `path` on `deviceId` (every member's, in a+ * workspace). Read from the database, so an offline device still answers.+ */+ countRunningTopicsInDirectory(deviceId: string, path: string): Promise<number> {+ return lambdaClient.device.countRunningTopicsInDirectory.query({ deviceId, path });+ }+statPath(deviceId: string, path: string) {return lambdaClient.device.statPath.query({ deviceId, path });}diff --git a/src/services/electron/git.ts b/src/services/electron/git.tsindex 2c9dda3a698..ed65c2c1b4e 100644--- a/src/services/electron/git.ts+++ b/src/services/electron/git.ts@@ -114,23 +114,30 @@ class ElectronGitService {return this.ipc.git.getGitBranchDiff(payload);}- async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {- return this.ipc.git.getGitAheadBehind(dirPath);+ /**+ * Counts for HEAD, or for `branch` when named. A HEAD read keeps sending the+ * bare path so a main process that predates the branch option still answers.+ */+ async getGitAheadBehind(dirPath: string, branch?: string): Promise<GitAheadBehind> {+ return this.ipc.git.getGitAheadBehind(+ branch === undefined ? dirPath : { branch, path: dirPath },+ );}async checkoutGitBranch(params: {branch: string;create?: boolean;path: string;+ startPoint?: string;}): Promise<GitCheckoutResult> {return this.ipc.git.checkoutGitBranch(params);}- async pullGitBranch(params: { path: string }): Promise<GitPullResult> {+ async pullGitBranch(params: { branch?: string; path: string }): Promise<GitPullResult> {return this.ipc.git.pullGitBranch(params);}- async pushGitBranch(params: { path: string }): Promise<GitPushResult> {+ async pushGitBranch(params: { branch?: string; path: string }): Promise<GitPushResult> {return this.ipc.git.pushGitBranch(params);}@@ -160,6 +167,7 @@ class ElectronGitService {async addGitWorktree(params: {branch: string;path: string;+ startPoint?: string;worktreePath: string;}): Promise<GitAddWorktreeResult> {return this.ipc.git.addGitWorktree(params);diff --git a/src/services/git.test.ts b/src/services/git.test.tsnew file mode 100644index 00000000000..0a52a7cfc22--- /dev/null+++ b/src/services/git.test.ts@@ -0,0 +1,184 @@+import { DEVICE_GIT_OUTDATED } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGitOutdatedError, gitService, isDeviceGitOutdated } from './git';++const mocks = vi.hoisted(() => ({+ addWorktreeIpc: vi.fn(),+ addWorktreeRpc: vi.fn(),+ aheadBehindIpc: vi.fn(),+ aheadBehindRpc: vi.fn(),+ checkoutIpc: vi.fn(),+ checkoutRpc: vi.fn(),+ pullRpc: vi.fn(),+ pushIpc: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ device: {+ addGitWorktree: { mutate: mocks.addWorktreeRpc },+ checkoutGitBranch: { mutate: mocks.checkoutRpc },+ gitAheadBehind: { query: mocks.aheadBehindRpc },+ pullGitBranch: { mutate: mocks.pullRpc },+ },+ },+}));++vi.mock('@/services/electron/git', () => ({+ electronGitService: {+ addGitWorktree: mocks.addWorktreeIpc,+ checkoutGitBranch: mocks.checkoutIpc,+ getGitAheadBehind: mocks.aheadBehindIpc,+ pushGitBranch: mocks.pushIpc,+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+});++/**+ * Device RPCs have no capability negotiation: an older device ignores a new+ * parameter and acts on HEAD. The service must turn such an answer into a+ * failure instead of a silent downgrade.+ */+describe('gitService device echo checks', () => {+ it('accepts a checkout whose start point the device echoed', async () => {+ mocks.checkoutRpc.mockResolvedValue({ startPoint: 'feat', success: true });+ const result = await gitService.checkoutGitBranch({+ branch: 'lobehub/x',+ create: true,+ deviceId: 'd',+ path: '/repo',+ startPoint: 'feat',+ });++ expect(result).toEqual({ startPoint: 'feat', success: true });+ expect(mocks.checkoutRpc).toHaveBeenCalledWith({+ branch: 'lobehub/x',+ create: true,+ deviceId: 'd',+ path: '/repo',+ startPoint: 'feat',+ });+ });++ it('rejects a checkout from a device that ignored the start point', async () => {+ mocks.checkoutIpc.mockResolvedValue({ success: true });+ const result = await gitService.checkoutGitBranch({+ branch: 'lobehub/x',+ create: true,+ path: '/repo',+ startPoint: 'feat',+ });++ expect(result).toMatchObject({ reason: DEVICE_GIT_OUTDATED, success: false });+ expect(isDeviceGitOutdated(result)).toBe(true);+ });++ it('leaves a plain checkout alone', async () => {+ mocks.checkoutIpc.mockResolvedValue({ success: true });+ expect(await gitService.checkoutGitBranch({ branch: 'main', path: '/repo' })).toEqual({+ success: true,+ });+ expect(mocks.checkoutIpc).toHaveBeenCalledWith({+ branch: 'main',+ create: undefined,+ path: '/repo',+ });+ });++ it('passes a git failure through untouched', async () => {+ mocks.checkoutIpc.mockResolvedValue({ error: 'conflict', success: false });+ expect(+ await gitService.checkoutGitBranch({+ branch: 'x',+ create: true,+ path: '/repo',+ startPoint: 'feat',+ }),+ ).toEqual({ error: 'conflict', success: false });+ });++ it('rejects a worktree whose start point does not match', async () => {+ mocks.addWorktreeRpc.mockResolvedValue({+ startPoint: 'main',+ success: true,+ worktreePath: '/w',+ });+ const result = await gitService.addGitWorktree({+ branch: 'lobehub/x',+ deviceId: 'd',+ path: '/repo',+ startPoint: 'feat',+ stripBranchPrefix: true,+ worktreePath: '',+ });++ expect(result).toMatchObject({ reason: DEVICE_GIT_OUTDATED, success: false });+ expect(mocks.addWorktreeRpc).toHaveBeenCalledWith(+ expect.objectContaining({ startPoint: 'feat', stripBranchPrefix: true }),+ );+ });++ it('accepts a worktree with a matching echo on the local route', async () => {+ mocks.addWorktreeIpc.mockResolvedValue({+ startPoint: 'feat',+ success: true,+ worktreePath: '/w',+ });+ const result = await gitService.addGitWorktree({+ branch: 'lobehub/x',+ path: '/repo',+ startPoint: 'feat',+ worktreePath: '/w',+ });++ expect(result).toMatchObject({ success: true, worktreePath: '/w' });+ expect(mocks.addWorktreeIpc).toHaveBeenCalledWith({+ branch: 'lobehub/x',+ path: '/repo',+ startPoint: 'feat',+ worktreePath: '/w',+ });+ });++ it('rejects a named-branch pull / push that came back without the branch', async () => {+ mocks.pullRpc.mockResolvedValue({ noop: true, success: true });+ mocks.pushIpc.mockResolvedValue({ noop: false, success: true });++ expect(+ await gitService.pullGitBranch({ branch: 'feat', deviceId: 'd', path: '/repo' }),+ ).toMatchObject({ reason: DEVICE_GIT_OUTDATED, success: false });+ expect(await gitService.pushGitBranch({ branch: 'feat', path: '/repo' })).toMatchObject({+ reason: DEVICE_GIT_OUTDATED,+ success: false,+ });+ });++ it('reads named-branch counts only when the device echoes the branch', async () => {+ mocks.aheadBehindRpc.mockResolvedValueOnce({+ ahead: 1,+ behind: 0,+ branch: 'feat',+ hasUpstream: true,+ });+ await expect(+ gitService.getGitAheadBehind({ branch: 'feat', deviceId: 'd', path: '/repo' }),+ ).resolves.toMatchObject({ ahead: 1, branch: 'feat' });++ mocks.aheadBehindIpc.mockResolvedValueOnce({ ahead: 3, behind: 0, hasUpstream: true });+ await expect(+ gitService.getGitAheadBehind({ branch: 'feat', path: '/repo' }),+ ).rejects.toBeInstanceOf(DeviceGitOutdatedError);+ expect(mocks.aheadBehindIpc).toHaveBeenCalledWith('/repo', 'feat');+ });++ it('keeps an unreachable device as "no answer", not as outdated', async () => {+ mocks.aheadBehindRpc.mockResolvedValue(null);+ await expect(+ gitService.getGitAheadBehind({ branch: 'feat', deviceId: 'd', path: '/repo' }),+ ).resolves.toBeUndefined();+ });+});diff --git a/src/services/git.ts b/src/services/git.tsindex 2e46bae7960..2044e0c4fb2 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -25,10 +25,51 @@ import type {DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';+import { DEVICE_GIT_OUTDATED } from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';import { electronGitService } from '@/services/electron/git';+/**+ * The device answered without honouring a newer parameter. Device RPCs carry no+ * version negotiation, so an older `lh connect` / desktop build ignores+ * `startPoint` / `branch` and acts on HEAD — every caller that passes one checks+ * the echo and refuses to treat such an answer as success.+ */+export class DeviceGitOutdatedError extends Error {+ readonly reason = DEVICE_GIT_OUTDATED;+ constructor(what: string) {+ super(`The device did not honour ${what}; update the LobeHub app or lh CLI on it.`);+ this.name = 'DeviceGitOutdatedError';+ }+}++export const isDeviceGitOutdated = (value: unknown): boolean =>+ value instanceof DeviceGitOutdatedError ||+ (!!value &&+ typeof value === 'object' &&+ (value as { reason?: string }).reason === DEVICE_GIT_OUTDATED);++/**+ * Reject a successful result whose echo does not match what was asked for. A+ * failed result is passed through: git's own error is the better message.+ */+const verifyEcho = <T extends { error?: string; reason?: string; success: boolean }>(+ result: T,+ field: 'branch' | 'startPoint',+ requested: string | undefined,+): T => {+ if (requested === undefined || !result.success) return result;+ const echoed = (result as Record<string, unknown>)[field];+ if (echoed === requested) return result;+ return {+ ...result,+ error: new DeviceGitOutdatedError(`"${field}"`).message,+ reason: DEVICE_GIT_OUTDATED,+ success: false,+ };+};+/** Current branch + detached-HEAD state for a working directory (cheap read). */export interface GitBranchSummary {branch?: string;@@ -69,21 +110,29 @@ class GitService {: electronGitService.listGitBranches(path);}- /** Checkout (or create) a branch in a working directory. */- checkoutGitBranch({+ /**+ * Checkout (or create) a branch in a working directory. With `startPoint`+ * (and `create`) the new branch is cut from that branch instead of HEAD; the+ * device's echo is verified, see {@link DeviceGitOutdatedError}.+ */+ async checkoutGitBranch({branch,create,deviceId,path,+ startPoint,}: {branch: string;create?: boolean;deviceId?: string;path: string;+ startPoint?: string;}): Promise<DeviceGitCheckoutResult> {- return deviceId- ? lambdaClient.device.checkoutGitBranch.mutate({ branch, create, deviceId, path })- : electronGitService.checkoutGitBranch({ branch, create, path });+ const params = { branch, create, path, ...(startPoint ? { startPoint } : {}) };+ const result = deviceId+ ? await lambdaClient.device.checkoutGitBranch.mutate({ ...params, deviceId })+ : await electronGitService.checkoutGitBranch(params);+ return verifyEcho(result, 'startPoint', startPoint);}/** Rename a branch in a working directory. */@@ -139,11 +188,13 @@ class GitService {* (never trusting a client-supplied absolute path), so `worktreePath` is only* forwarded on the local IPC route where this machine owns the filesystem.*/- addGitWorktree({+ async addGitWorktree({branch,deviceId,path,sourcePath,+ startPoint,+ stripBranchPrefix,worktreePath,}: {branch: string;@@ -151,37 +202,64 @@ class GitService {path: string;/** The repo's main checkout; the server keys the target folder on it. */sourcePath?: string;+ /** Fork the new branch from this branch instead of HEAD; the echo is verified. */+ startPoint?: string;+ /**+ * Remote only: have the server drop the app's branch namespace from the+ * folder it derives. The local route already passes the final `worktreePath`.+ */+ stripBranchPrefix?: boolean;worktreePath: string;}): Promise<DeviceGitAddWorktreeResult> {- return deviceId- ? lambdaClient.device.addGitWorktree.mutate({ branch, deviceId, path, sourcePath })- : electronGitService.addGitWorktree({ branch, path, worktreePath });+ const start = startPoint ? { startPoint } : {};+ const result = deviceId+ ? await lambdaClient.device.addGitWorktree.mutate({+ branch,+ deviceId,+ path,+ sourcePath,+ ...start,+ ...(stripBranchPrefix ? { stripBranchPrefix } : {}),+ })+ : await electronGitService.addGitWorktree({ branch, path, worktreePath, ...start });+ return verifyEcho(result, 'startPoint', startPoint);}- /** Pull (`--ff-only`) the current branch of a working directory. */- pullGitBranch({+ /**+ * Fast-forward the current branch of a working directory, or `branch` without+ * switching to it (the device's echo is verified).+ */+ async pullGitBranch({+ branch,deviceId,path,}: {+ branch?: string;deviceId?: string;path: string;}): Promise<DeviceGitSyncResult> {- return deviceId- ? lambdaClient.device.pullGitBranch.mutate({ deviceId, path })- : electronGitService.pullGitBranch({ path });+ const params = { path, ...(branch ? { branch } : {}) };+ const result = deviceId+ ? await lambdaClient.device.pullGitBranch.mutate({ ...params, deviceId })+ : await electronGitService.pullGitBranch(params);+ return verifyEcho(result, 'branch', branch);}- /** Push the current branch of a working directory. */- pushGitBranch({+ /** Push the current branch of a working directory, or `branch` (echo verified). */+ async pushGitBranch({+ branch,deviceId,path,}: {+ branch?: string;deviceId?: string;path: string;}): Promise<DeviceGitSyncResult> {- return deviceId- ? lambdaClient.device.pushGitBranch.mutate({ deviceId, path })- : electronGitService.pushGitBranch({ path });+ const params = { path, ...(branch ? { branch } : {}) };+ const result = deviceId+ ? await lambdaClient.device.pushGitBranch.mutate({ ...params, deviceId })+ : await electronGitService.pushGitBranch(params);+ return verifyEcho(result, 'branch', branch);}/**@@ -329,17 +407,32 @@ class GitService {: electronGitService.getGitWorkingTreeStatus(path);}- /** Ahead/behind commit counts for the current branch vs its upstream. */+ /**+ * Ahead/behind commit counts for the current branch vs its upstream — or for+ * `branch`, wherever HEAD is. A named-branch answer without the matching echo+ * came from a device that counted HEAD instead and throws+ * {@link DeviceGitOutdatedError}; an unreachable device still resolves+ * `undefined`.+ */async getGitAheadBehind({+ branch,deviceId,path,}: {+ branch?: string;deviceId?: string;path: string;}): Promise<DeviceGitAheadBehind | undefined> {- return deviceId- ? ((await lambdaClient.device.gitAheadBehind.query({ deviceId, path })) ?? undefined)- : electronGitService.getGitAheadBehind(path);+ const result = deviceId+ ? ((await lambdaClient.device.gitAheadBehind.query({+ ...(branch ? { branch } : {}),+ deviceId,+ path,+ })) ?? undefined)+ : await electronGitService.getGitAheadBehind(path, branch);+ if (branch !== undefined && result && result.branch !== branch)+ throw new DeviceGitOutdatedError('"branch"');+ return result;}/** Working-tree (unstaged) per-file patches for a working directory. */diff --git a/src/services/user/index.ts b/src/services/user/index.tsindex 5070a5879b8..31f1128ad6b 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -133,6 +133,11 @@ export class UserService {return lambdaClient.user.updatePreference.mutate(preference);};+ /** Personal-mode "New worktree" switch for one directory; resolves to the stored list. */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> => {+ return lambdaClient.user.setWorktreeModeDir.mutate({ enabled, key });+ };+updateGuide = async (guide: Partial<UserGuide>) => {return lambdaClient.user.updateGuide.mutate(guide);};diff --git a/src/services/workspaceUserSettings.ts b/src/services/workspaceUserSettings.tsindex 2a29899f94d..28f2b9aa44d 100644--- a/src/services/workspaceUserSettings.ts+++ b/src/services/workspaceUserSettings.ts@@ -16,6 +16,10 @@ export class WorkspaceUserSettingsService {updatePreference = async (patch: Partial<WorkspaceUserPreference>): Promise<void> => {await lambdaClient.workspaceUserSettings.updatePreference.mutate(patch);};++ /** One directory's "New worktree" switch; resolves to the stored (capped) list. */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ lambdaClient.workspaceUserSettings.setWorktreeModeDir.mutate({ enabled, key });}export const workspaceUserSettingsService = new WorkspaceUserSettingsService();diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 5340a8817fb..92e31788001 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -3,10 +3,7 @@ import { createCallAgentManifest } from '@lobechat/builtin-tool-agent-managementimport { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';import { isDesktop, isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';-import {- collectHeteroAttachedFiles,- isRemoteHeterogeneousType,-} from '@lobechat/heterogeneous-agents';+import { collectHeteroAttachedFiles } from '@lobechat/heterogeneous-agents';import type {ChatAudioItem,ChatImageItem,@@ -19,8 +16,6 @@ import type {} from '@lobechat/types';import {applyTopicModelToHeterogeneousProvider,- getWorkingDirEffectivePath,- getWorkingDirSourcePath,resolveAgentAgencyConfig,toComposerUserMessage,} from '@lobechat/types';@@ -35,19 +30,11 @@ import {ensureAgentManagementAccess,getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';-import {- resolveAgentWorkingDirectory,- resolveAgentWorkingDirectoryConfig,- resolveTargetDeviceId,-} from '@/helpers/agentWorkingDirectory';import {applyTopicDeviceBinding,getTopicBoundDeviceId,- resolveExecutionTarget,- resolveToolMode,resolveWorkspaceScoped,} from '@/helpers/executionTarget';-import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { agentService } from '@/services/agent';import { aiAgentService, MAX_CLIENT_OPERATION_SNAPSHOT } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';@@ -113,7 +100,6 @@ import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';import { topicMapKey } from '@/store/chat/utils/topicMapKey';-import { deviceSelectors, getDeviceStoreState } from '@/store/device';import { getElectronStoreState } from '@/store/electron';import { getFileStoreState } from '@/store/file/store';import { useGlobalStore } from '@/store/global';@@ -143,7 +129,7 @@ import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../pimport { resolveExistingTopicForRun } from '../resolveExistingTopic';import { type ContextCompressionOptions, executeContextCompression } from './compression';import { findRunningBlockingOp } from './queueBlockingOp';-import { resolveRunCwd, resolveSendProjectRun, type SourceTopicDirectory } from './runCwd';+import { resolveSendProjectRun, resolveSendRunCwd, type SourceTopicDirectory } from './runCwd';import { showSendErrorInContext } from './sendErrorNotice';/**@@ -279,6 +265,7 @@ export class ConversationLifecycleActionImpl {contextSelections,inputEditor,messages: inputMessages,+ newTopicWorkingDirectory,optimisticUserMessageId,parentId: inputParentId,pageSelections,@@ -1111,87 +1098,23 @@ export class ConversationLifecycleActionImpl {topicId: willCreateNewTopic ? undefined : operationContext.topicId,});const currentDeviceId = await getElectronStoreState().resolveGatewayDeviceId();- // Resolve the cwd for every run that lands on a MACHINE — a hetero CLI- // (in-process `hetero` runtime) and a NATIVE agent alike, as long as the- // effective target routes to a device. The server can only honour a cwd the- // client resolved (per-user legacy slot included) if it rides along as the- // new topic's initial metadata, and a topic that is born unbound renders- // under "No directory" while every later turn re-resolves the agent-level- // default. Sandbox/none targets must NOT resolve one: the desktop/home- // fallback is a local machine path that doesn't exist in an ephemeral cloud- // sandbox and would pollute the topic's metadata. Plain-chat agents have no- // execution environment at all, so they stay unbound too.- const isHeteroRun = !!heterogeneousProvider;- const runEffectiveTarget =- isHeteroRun || resolveToolMode(agentConfig?.chatConfig) !== 'chat'- ? resolveExecutionTarget(agencyConfig, {- clientExecutionAvailable: isDesktop,- // A web client can't run tools in-process, but its backend may still- // route a bound `local` target to the user's machine — where the cwd- // does apply.- deviceRoutingAvailable: isGatewayMode,- isHetero: isHeteroRun,- workspaceScoped,- })- : undefined;- const resolvesRunCwd =- runEffectiveTarget === 'local' ||- runEffectiveTarget === 'device' ||- runEffectiveTarget === 'auto';- // Same precedence as `useEffectiveWorkingDirectory` (and the server's- // `resolveDeviceWorkingDirectoryConfig`), but over the MERGED config — the- // agent selector reads the raw shared row internally, which could fall back- // to a cwd registered for another member's device.- const runCwdDeviceId = resolvesRunCwd- ? resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped })- : undefined;- // Desktop/home is the last resort for hetero CLIs ONLY: they always spawn in- // some directory, so an unconfigured agent still needs one. A native agent- // with nothing configured stays unbound instead — pinning it to `~/Desktop`- // would file every desktop conversation under a project the user never- // picked.- const heteroCwdContext =- resolvesRunCwd && isHeteroRun && isDesktop- ? globalAgentContextManager.getContext()- : undefined;- const runCwdParams = resolvesRunCwd- ? {- agencyConfig,- currentDeviceId,- deviceDefaultCwd:- deviceSelectors.getDeviceDefaultCwd(runCwdDeviceId)(getDeviceStoreState()),- fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,- legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],- // A project's staged directory, not the agent default, is the new topic's cwd.- topicWorkingDirectory: stagedDirectory?.path,- workspaceScoped,- }- : undefined;- const agentWorkingDirectory = runCwdParams && resolveAgentWorkingDirectory(runCwdParams);- const agentWorkingDirectoryConfig =- runCwdParams && resolveAgentWorkingDirectoryConfig(runCwdParams);- // 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. The per-cwd session store is a LOCAL CLI trait — remote platform- // agents (openclaw / hermes) run through the gateway with no such- // constraint, so they (like non-hetero runtimes) keep the effective- // (worktree) path.- const isLocalCliHetero =- !!heterogeneousProvider && !isRemoteHeterogeneousType(heterogeneousProvider.type);- const resolveWorkingDirPath = isLocalCliHetero- ? getWorkingDirSourcePath- : getWorkingDirEffectivePath;- const { workingDirectory, workingDirectoryConfig } = await resolveRunCwd({- agentWorkingDirectory,- agentWorkingDirectoryConfig,- existingTopic,- inheritedTopic: !stagedDirectory && resolvesRunCwd ? inheritedTopic : undefined,- resolvePath: resolveWorkingDirPath,- runMachine: { deviceId: runCwdDeviceId, target: runEffectiveTarget },- });+ const { runCwdDeviceId, runEffectiveTarget, workingDirectory, workingDirectoryConfig } =+ await resolveSendRunCwd({+ agencyConfig,+ chatConfig: agentConfig?.chatConfig,+ currentDeviceId,+ // Prepared on the composer agent's machine: a send routed to another+ // agent (`@Agent` direct route) resolves its own device and directory.+ draftWorkingDirectory:+ willCreateNewTopic && agentId === ownerAgentId ? newTopicWorkingDirectory : undefined,+ existingTopic,+ heterogeneousProvider,+ inheritedTopic,+ isGatewayMode,+ legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],+ stagedDirectoryPath: stagedDirectory?.path,+ workspaceScoped,+ });// Record which machine a new conversation runs on, so its next turn — and// the device picker — stay on it after the agent default changes. `auto`// has not picked a machine yet; the server stamps the one it routes to.diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.test.tsnew file mode 100644index 00000000000..9abdf9a12c1--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.test.ts@@ -0,0 +1,87 @@+import type { WorkingDirConfig } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { resolveSendRunCwd } from './runCwd';++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal()),+ isDesktop: true,+}));++const worktree: WorkingDirConfig = {+ git: {+ activeWorktree: '/Users/me/.lobehub/worktrees/lobehub-0000beef/quiet-hill',+ autoCreated: true,+ autoCreatedAt: '2026-11-17T00:00:00.000Z',+ branch: 'lobehub/quiet-hill',+ },+ path: '/code/lobehub',+ repoType: 'github',+ sessionPath: '/Users/me/.lobehub/worktrees/lobehub-0000beef/quiet-hill',+};++const base = {+ agencyConfig: {+ boundDeviceId: 'dev-1',+ executionTarget: 'device' as const,+ workingDirByDevice: { 'dev-1': { path: '/code/lobehub' } },+ },+ chatConfig: undefined,+ currentDeviceId: 'dev-local',+ existingTopic: undefined,+ heterogeneousProvider: undefined,+ inheritedTopic: undefined,+ isGatewayMode: true,+ legacyAgentWorkingDirectory: undefined,+ stagedDirectoryPath: undefined,+ workspaceScoped: false,+};++describe('resolveSendRunCwd with a directory prepared by the composer', () => {+ it('runs a new topic in the worktree made just before sending', async () => {+ const result = await resolveSendRunCwd({ ...base, draftWorkingDirectory: worktree });++ expect(result.runCwdDeviceId).toBe('dev-1');+ expect(result.workingDirectoryConfig).toEqual(worktree);+ expect(result.workingDirectory).toBe(worktree.git!.activeWorktree);+ });++ it('runs a local CLI agent in that worktree too: its session has not started yet', async () => {+ const result = await resolveSendRunCwd({+ ...base,+ draftWorkingDirectory: worktree,+ heterogeneousProvider: { type: 'claude-code' },+ });++ expect(result.workingDirectory).toBe(worktree.git!.activeWorktree);+ });++ it('outranks the staged project directory', async () => {+ const result = await resolveSendRunCwd({+ ...base,+ draftWorkingDirectory: worktree,+ stagedDirectoryPath: '/code/lobehub',+ });++ expect(result.workingDirectoryConfig).toEqual(worktree);+ });++ it('never moves an existing topic', async () => {+ const existingTopic = {+ metadata: { boundDeviceId: 'dev-1', workingDirectoryConfig: { path: '/code/other' } },+ };+ const result = await resolveSendRunCwd({+ ...base,+ draftWorkingDirectory: worktree,+ existingTopic,+ });++ expect(result.workingDirectoryConfig).toEqual({ path: '/code/other' });+ expect(result.workingDirectory).toBe('/code/other');+ });++ it('keeps the agent default without one', async () => {+ const result = await resolveSendRunCwd(base);+ expect(result.workingDirectoryConfig).toEqual({ path: '/code/lobehub' });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.tsindex 8528399ddaf..147025a62a3 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts@@ -1,8 +1,25 @@import { isDesktop } from '@lobechat/const';-import type { ChatTopic, ConversationContext, WorkingDirConfig } from '@lobechat/types';+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import type {+ ChatTopic,+ ConversationContext,+ HeterogeneousProviderConfig,+ LobeAgentAgencyConfig,+ LobeAgentChatConfig,+ WorkingDirConfig,+} from '@lobechat/types';+import { getWorkingDirEffectivePath, getWorkingDirSessionPath } from '@lobechat/types';+import {+ resolveAgentWorkingDirectory,+ resolveAgentWorkingDirectoryConfig,+ resolveTargetDeviceId,+} from '@/helpers/agentWorkingDirectory';+import { resolveExecutionTarget, resolveToolMode } from '@/helpers/executionTarget';+import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { deviceService } from '@/services/device';import type { PendingNewTopicDirectory } from '@/store/chat/slices/topic/initialState';+import { deviceSelectors, getDeviceStoreState } from '@/store/device';import { ensureElectronIpc } from '@/utils/electron/ipc';import { resolveProjectDirectoryRun } from '../resolveProjectDirectoryRun';@@ -150,3 +167,124 @@ export const resolveRunCwd = async (params: {: params.agentWorkingDirectoryConfig),};};++/**+ * Where a send runs: the effective execution target, the machine it lands on,+ * and the cwd (plus its structured config) for that machine. Moved out of+ * `sendMessage` as one pipeline stage.+ */+export const resolveSendRunCwd = async ({+ agencyConfig,+ chatConfig,+ currentDeviceId,+ draftWorkingDirectory,+ existingTopic,+ heterogeneousProvider,+ inheritedTopic,+ isGatewayMode,+ legacyAgentWorkingDirectory,+ stagedDirectoryPath,+ workspaceScoped,+}: {+ agencyConfig: LobeAgentAgencyConfig | undefined;+ chatConfig: LobeAgentChatConfig | undefined;+ currentDeviceId: string | undefined;+ /**+ * The directory the composer prepared for a topic this send creates (a+ * worktree made just before sending). Outranks the staged project directory+ * and any handoff source: it is where the user chose to start.+ */+ draftWorkingDirectory?: WorkingDirConfig;+ existingTopic: Pick<ChatTopic, 'metadata'> | undefined;+ heterogeneousProvider: HeterogeneousProviderConfig | undefined;+ inheritedTopic: SourceTopicDirectory | undefined;+ isGatewayMode: boolean;+ legacyAgentWorkingDirectory: string | undefined;+ /** A project's staged directory, which a blank conversation runs in. */+ stagedDirectoryPath: string | undefined;+ workspaceScoped: boolean | undefined;+}) => {+ // Resolve the cwd for every run that lands on a MACHINE — a hetero CLI+ // (in-process `hetero` runtime) and a NATIVE agent alike, as long as the+ // effective target routes to a device. The server can only honour a cwd the+ // client resolved (per-user legacy slot included) if it rides along as the+ // new topic's initial metadata, and a topic that is born unbound renders+ // under "No directory" while every later turn re-resolves the agent-level+ // default. Sandbox/none targets must NOT resolve one: the desktop/home+ // fallback is a local machine path that doesn't exist in an ephemeral cloud+ // sandbox and would pollute the topic's metadata. Plain-chat agents have no+ // execution environment at all, so they stay unbound too.+ const isHeteroRun = !!heterogeneousProvider;+ const runEffectiveTarget =+ isHeteroRun || resolveToolMode(chatConfig) !== 'chat'+ ? resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ // A web client can't run tools in-process, but its backend may still+ // route a bound `local` target to the user's machine — where the cwd+ // does apply.+ deviceRoutingAvailable: isGatewayMode,+ isHetero: isHeteroRun,+ workspaceScoped,+ })+ : undefined;+ const resolvesRunCwd =+ runEffectiveTarget === 'local' ||+ runEffectiveTarget === 'device' ||+ runEffectiveTarget === 'auto';+ // Same precedence as `useEffectiveWorkingDirectory` (and the server's+ // `resolveDeviceWorkingDirectoryConfig`), but over the MERGED config — the+ // agent selector reads the raw shared row internally, which could fall back+ // to a cwd registered for another member's device.+ const runCwdDeviceId = resolvesRunCwd+ ? resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped })+ : undefined;+ // Desktop/home is the last resort for hetero CLIs ONLY: they always spawn in+ // some directory, so an unconfigured agent still needs one. A native agent+ // with nothing configured stays unbound instead — pinning it to `~/Desktop`+ // would file every desktop conversation under a project the user never+ // picked.+ const heteroCwdContext =+ resolvesRunCwd && isHeteroRun && isDesktop ? globalAgentContextManager.getContext() : undefined;+ const runCwdParams = resolvesRunCwd+ ? {+ agencyConfig,+ currentDeviceId,+ deviceDefaultCwd:+ deviceSelectors.getDeviceDefaultCwd(runCwdDeviceId)(getDeviceStoreState()),+ fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,+ legacyAgentWorkingDirectory,+ // A project's staged directory, not the agent default, is the new topic's cwd.+ topicWorkingDirectory: stagedDirectoryPath,+ topicWorkingDirectoryConfig: existingTopic ? undefined : draftWorkingDirectory,+ workspaceScoped,+ }+ : undefined;+ const agentWorkingDirectory = runCwdParams && resolveAgentWorkingDirectory(runCwdParams);+ const agentWorkingDirectoryConfig =+ runCwdParams && resolveAgentWorkingDirectoryConfig(runCwdParams);+ // 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. The per-cwd session store is a LOCAL CLI trait — remote platform+ // agents (openclaw / hermes) run through the gateway with no such+ // constraint, so they (like non-hetero runtimes) keep the effective+ // (worktree) path.+ const isLocalCliHetero =+ !!heterogeneousProvider && !isRemoteHeterogeneousType(heterogeneousProvider.type);+ const resolveWorkingDirPath = isLocalCliHetero+ ? getWorkingDirSessionPath+ : getWorkingDirEffectivePath;+ const { workingDirectory, workingDirectoryConfig } = await resolveRunCwd({+ agentWorkingDirectory,+ agentWorkingDirectoryConfig,+ existingTopic,+ inheritedTopic:+ !stagedDirectoryPath && !draftWorkingDirectory && resolvesRunCwd ? inheritedTopic : undefined,+ resolvePath: resolveWorkingDirPath,+ runMachine: { deviceId: runCwdDeviceId, target: runEffectiveTarget },+ });++ return { runCwdDeviceId, runEffectiveTarget, workingDirectory, workingDirectoryConfig };+};diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.tsindex 12b264112a7..519a5560303 100644--- a/src/store/chat/utils/topicWorkingDirGit.ts+++ b/src/store/chat/utils/topicWorkingDirGit.ts@@ -5,7 +5,7 @@ import type {WorkingDirConfig,WorkingDirGithubState,} from '@lobechat/types';-import { getWorkingDirEffectivePath } from '@lobechat/types';+import { dropStaleAutoCreated, getWorkingDirEffectivePath } from '@lobechat/types';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import type { GitLinkedPRSummary } from '@/services/git';@@ -107,6 +107,7 @@ export const mergeWorkingDirGithubState = ({delete git.detached;if (isWorktree) git.activeWorktree = path;else delete git.activeWorktree;+ dropStaleAutoCreated(git, currentConfig?.git?.activeWorktree);// A probe that resolved no remote ref means the branch is unpushed or its trace is// gone — not that a previously recorded ref is wrong. Keep the old one rather thandiff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex ffe24c6ecba..71dda81fb8c 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -262,10 +262,14 @@ const useGitStatusRead = <T>(path: string | undefined,schedule: ReplicaSyncSchedule,enabled = true,+ branch?: string,): GitStatusReadResult<T> => {const params = useMemo(- () => (enabled && isEnabled(deviceId, path) ? { deviceId, path } : null),- [enabled, deviceId, path],+ () =>+ enabled && isEnabled(deviceId, path)+ ? { deviceId, path, ...(branch ? { branch } : {}) }+ : null,+ [enabled, deviceId, path, branch],);const key = params ? gitStatusKey(params) : undefined;const stored = useGitStatusStore((s) => (key ? selectMap(s)[key] : undefined));@@ -457,10 +461,17 @@ export const useFetchGitWorkingTreeStatus = (deviceId: string | undefined, path?);/**- * Ahead/behind commit counts. Each load piggybacks a best-effort `git fetch`- * inside the read, so focus revalidation (5s throttle) surfaces remote updates.+ * Ahead/behind commit counts — of HEAD, or of `branch` when given (the branch+ * picked for a new topic, wherever HEAD is). Each load piggybacks a best-effort+ * `git fetch` inside the read, so focus revalidation (5s throttle) surfaces+ * remote updates. A named-branch read from a device too old to honour the+ * branch errors with `DeviceGitOutdatedError` instead of counting HEAD.*/-export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: string) =>+export const useFetchGitAheadBehind = (+ deviceId: string | undefined,+ path?: string,+ branch?: string,+) =>useGitStatusRead<DeviceGitAheadBehind>(useGitStatusStore.getState().slices.aheadBehind,selectAheadBehindMap,@@ -468,6 +479,8 @@ export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: strideviceId,path,{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true },+ true,+ branch,);/**diff --git a/src/store/device/gitStatus/projection.ts b/src/store/device/gitStatus/projection.tsindex 17ecbf035ff..97e9b0009d0 100644--- a/src/store/device/gitStatus/projection.ts+++ b/src/store/device/gitStatus/projection.ts@@ -21,14 +21,21 @@ import type { GitBranchSummary } from '@/services/git';* state.*/export interface GitStatusParams {+ /**+ * A local branch the read describes instead of HEAD. Only the ahead/behind+ * read takes one (the composer counts the branch picked for a new topic,+ * which is not checked out yet); a branchless key is unchanged, so rows+ * persisted before this field keep their keys.+ */+ branch?: string;/** Remote device; `undefined` reads this machine over Electron IPC. */deviceId?: string;path: string;}/** `local` stands for this machine, like the SWR device keys. */-export const gitStatusKey = ({ deviceId, path }: GitStatusParams) =>- `${deviceId ?? 'local'}\u0000${path}`;+export const gitStatusKey = ({ branch, deviceId, path }: GitStatusParams) =>+ `${deviceId ?? 'local'}\u0000${path}${branch ? `\u0000${branch}` : ''}`;/*** One answered read. The value is wrapped so a read that answered with nothingdiff --git a/src/store/device/gitStatus/store.test.ts b/src/store/device/gitStatus/store.test.tsindex 72f8e1de785..1ceadc7e18a 100644--- a/src/store/device/gitStatus/store.test.ts+++ b/src/store/device/gitStatus/store.test.ts@@ -391,4 +391,30 @@ describe('git status replicas', () => {await waitFor(() => expect(result.current.data).toMatchObject({ ahead: 3 }));});++ // The composer counts the branch picked for a new topic, which is not checked+ // out: its row must never paint HEAD's counts, nor HEAD's its.+ it('keys a named-branch ahead/behind apart from HEAD and asks the device for that branch', async () => {+ vi.mocked(gitService.getGitAheadBehind).mockImplementation(async (params: any) =>+ params.branch+ ? ({ ahead: 0, behind: 4, branch: params.branch, hasUpstream: true } as any)+ : ({ ahead: 1, behind: 0, hasUpstream: true } as any),+ );+ const { result } = renderHook(+ () => ({+ head: useFetchGitAheadBehind('device-1', '/repo'),+ named: useFetchGitAheadBehind('device-1', '/repo', 'feat'),+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.named.data).toMatchObject({ behind: 4 }));+ await waitFor(() => expect(result.current.head.data).toMatchObject({ ahead: 1 }));+ expect(gitService.getGitAheadBehind).toHaveBeenCalledWith(+ expect.objectContaining({ branch: 'feat', deviceId: 'device-1', path: '/repo' }),+ );+ expect(gitStatusKey({ branch: 'feat', deviceId: 'device-1', path: '/repo' })).not.toBe(+ gitStatusKey({ deviceId: 'device-1', path: '/repo' }),+ );+ });});diff --git a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.test.ts b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.test.tsnew file mode 100644index 00000000000..55af526ba8e--- /dev/null+++ b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.test.ts@@ -0,0 +1,78 @@+import type { WorkingDirConfig } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ applyBranchToConfig,+ applyWorktreeAddToConfig,+ applyWorktreeExitToConfig,+} from './worktreeConfigEffects';++/** A topic whose worktree the app created on its first send. */+const autoCreated: WorkingDirConfig = {+ git: {+ activeWorktree: '/wt/quiet-hill',+ autoCreated: true,+ autoCreatedAt: '2026-11-17T00:00:00.000Z',+ branch: 'lobehub/quiet-hill',+ isWorktree: true,+ },+ path: '/repo',+};++describe('the auto-created worktree marker', () => {+ it('stays while the topic is still on that worktree', () => {+ const next = applyBranchToConfig(autoCreated, '/repo', 'lobehub/renamed');+ expect(next.git).toMatchObject({+ autoCreated: true,+ autoCreatedAt: autoCreated.git!.autoCreatedAt,+ });+ });++ it('is dropped when an agent moves the topic to another worktree', () => {+ const next = applyWorktreeAddToConfig(autoCreated, '/repo', {+ branch: 'feat/x',+ path: '/wt/other',+ });+ expect(next.git?.activeWorktree).toBe('/wt/other');+ expect(next.git).not.toHaveProperty('autoCreated');+ expect(next.git).not.toHaveProperty('autoCreatedAt');+ });++ it('is dropped when the topic leaves the worktree', () => {+ const next = applyWorktreeExitToConfig(autoCreated, '/repo');+ expect(next.git).not.toHaveProperty('autoCreated');+ expect(next.git).not.toHaveProperty('activeWorktree');+ });+});++describe('leaving a worktree when the CLI session started in another one', () => {+ const born: WorkingDirConfig = {+ git: { activeWorktree: '/wt/a', isWorktree: true },+ path: '/repo',+ sessionPath: '/wt/a',+ };+ const movedOn: WorkingDirConfig = {+ git: { activeWorktree: '/wt/b', branch: 'feat/b', isWorktree: true },+ path: '/repo',+ sessionPath: '/wt/a',+ };++ it('returns to the session worktree, where the CLI runs, after leaving another', () => {+ const next = applyWorktreeExitToConfig(movedOn, '/repo', { removed: true });+ expect(next.git?.activeWorktree).toBe('/wt/a');+ expect(next.sessionPath).toBe('/wt/a');+ expect(next.git?.branch).toBeUndefined();+ });++ it('falls back to the source when the session worktree itself is removed', () => {+ const next = applyWorktreeExitToConfig(born, '/repo', { removed: true });+ expect(next.git?.activeWorktree).toBeUndefined();+ expect(next).not.toHaveProperty('sessionPath');+ expect(next.path).toBe('/repo');+ });++ it('keeps the session worktree when it is left but kept on disk', () => {+ const next = applyWorktreeExitToConfig(born, '/repo');+ expect(next.sessionPath).toBe('/wt/a');+ });+});diff --git a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.tsindex 1a3f69e6413..4727e94cdd8 100644--- a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts+++ b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts@@ -3,6 +3,7 @@ import type {DeviceGitUpstreamRef,WorkingDirConfig,} from '@lobechat/types';+import { dropStaleAutoCreated } from '@lobechat/types';/*** How each detected git / gh side effect rewrites a topic's working-directory@@ -140,6 +141,7 @@ export const applyWorktreeAddToConfig = (delete git.github;delete git.upstream;}+ dropStaleAutoCreated(git, currentConfig?.git?.activeWorktree);return {...currentConfig,@@ -159,6 +161,7 @@ export const applyWorktreeAddToConfig = (export const applyWorktreeExitToConfig = (currentConfig: WorkingDirConfig | undefined,source: string,+ { removed = false }: { removed?: boolean } = {},): WorkingDirConfig => {const git: NonNullable<WorkingDirConfig['git']> = {...currentConfig?.git,@@ -171,16 +174,28 @@ export const applyWorktreeExitToConfig = (const leftWorktree =!!currentConfig?.git?.isWorktree || (!!activeWorktree && activeWorktree !== source);delete git.activeWorktree;+ dropStaleAutoCreated(git, activeWorktree);if (leftWorktree) {delete git.branch;delete git.github;delete git.upstream;}+ // A topic born in the app's worktree runs its CLI there (`sessionPath`), not+ // in the source. Leaving ANOTHER worktree returns it there; removing that very+ // worktree leaves nothing to start in, so the session falls back to the source.+ const { sessionPath, ...rest } = currentConfig ?? ({} as Partial<WorkingDirConfig>);+ const sessionGone = !!sessionPath && removed && sessionPath === activeWorktree;+ if (sessionPath && !sessionGone && sessionPath !== activeWorktree) {+ git.activeWorktree = sessionPath;+ git.isWorktree = true;+ }+return {- ...currentConfig,+ ...rest,git,path: source,...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),+ ...(sessionPath && !sessionGone ? { sessionPath } : {}),};};diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex 797451acb25..bcaeca56b53 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -948,7 +948,7 @@ export const recordGitCommandEffects = async (params: {if (activeWorktree && removesWorktree(command, activeWorktree, source)) {const worktrees = await listDeviceWorktrees(source, topic?.metadata?.boundDeviceId);if (isWorktreeGone(worktrees, activeWorktree, nextConfig?.git?.branch))- nextConfig = applyWorktreeExitToConfig(nextConfig, source);+ nextConfig = applyWorktreeExitToConfig(nextConfig, source, { removed: true });}const branchSwitch = parseGitBranchSwitch(command, resultContent);diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 387e19536cb..42b72d69c9d 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -1,4 +1,5 @@import type { WorkspaceUserPreference } from '@lobechat/types';+import { applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import isEqual from 'fast-deep-equal';import type { ReplicaSlice } from 'local-replica/zustand';@@ -9,6 +10,7 @@ import {useActiveWorkspaceId,} from '@/business/client/hooks/useActiveWorkspaceId';import { createReplicaSlice, type ReplicaLens, revalidateReplica } from '@/libs/replica';+import { userService } from '@/services/user';import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';import { type StoreSetter } from '@/store/types';@@ -261,6 +263,69 @@ export class WorkspaceUserSettingsActionImpl {// has no overrides, so the early return above needs no refresh.)if (patch.agentDeviceOverrides) void refreshAgentDeviceBindings();};++ /**+ * Turn the composer's "New worktree" switch on or off for one directory+ * (`getWorktreeModeKey`). Inside a workspace it lives in this member's+ * workspace bucket, in personal mode in `users.preference`. Applied+ * optimistically so the switch flips at once, rolled back if the write fails+ * (rethrown, so the caller can say so); the server applies the cap.+ */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<void> => {+ const workspaceId = getActiveWorkspaceId();++ if (!workspaceId) {+ const previous = this.#get().preference;+ this.#set(+ {+ preference: {+ ...previous,+ worktreeModeDirs: applyWorktreeModeDir(previous.worktreeModeDirs, key, enabled),+ },+ },+ false,+ n('setWorktreeModeDir'),+ );+ try {+ const worktreeModeDirs = await userService.setWorktreeModeDir(key, enabled);+ this.#set(+ { preference: { ...this.#get().preference, worktreeModeDirs } },+ false,+ n('setWorktreeModeDir/confirmed'),+ );+ } catch (error) {+ this.#set(+ {+ preference: {+ ...this.#get().preference,+ worktreeModeDirs: previous.worktreeModeDirs,+ },+ },+ false,+ n('setWorktreeModeDir/rollback'),+ );+ throw error;+ }+ return;+ }++ const replica = this.#replica();+ if (replica.getConfirmed(workspaceId) === undefined) {+ await replica.hydrate({ workspaceId });+ if (getActiveWorkspaceId() !== workspaceId) return;+ }+ const previous = this.#get().workspaceUserPreference;+ replica.update(workspaceId, (data) => data ?? previous, { persist: false });+ await replica.optimistic(+ workspaceId,+ (data) => ({+ ...data,+ worktreeModeDirs: applyWorktreeModeDir(data.worktreeModeDirs, key, enabled),+ }),+ () => workspaceUserSettingsService.setWorktreeModeDir(key, enabled),+ { revalidate: true },+ );+ };}export type WorkspaceUserSettingsAction = Pick<diff --git a/src/store/user/slices/workspaceUserSettings/action.worktreeMode.test.ts b/src/store/user/slices/workspaceUserSettings/action.worktreeMode.test.tsnew file mode 100644index 00000000000..9f2138f2ed0--- /dev/null+++ b/src/store/user/slices/workspaceUserSettings/action.worktreeMode.test.ts@@ -0,0 +1,92 @@+import type { WorkspaceUserPreference } from '@lobechat/types';+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { userService } from '@/services/user';+import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';+import { useUserStore } from '@/store/user';++const active = vi.hoisted(() => ({ id: 'workspace-1' as string | null }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => active.id,+ useActiveWorkspaceId: () => active.id,+}));++vi.mock('@/services/workspaceUserSettings', () => ({+ workspaceUserSettingsService: {+ getPreference: vi.fn(),+ setWorktreeModeDir: vi.fn(),+ updatePreference: vi.fn(),+ },+}));++vi.mock('@/services/user', async (importOriginal) => {+ const original = await importOriginal<{ userService: object }>();+ return { ...original, userService: { ...original.userService, setWorktreeModeDir: vi.fn() } };+});++const state = () => useUserStore.getState();++const seed = (preference: WorkspaceUserPreference) =>+ useUserStore.setState({+ workspaceUserPreference: preference,+ workspaceUserPreferenceWorkspaceId: 'workspace-1',+ });++describe('setWorktreeModeDir', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ active.id = 'workspace-1';+ useUserStore.setState({+ preference: { worktreeModeDirs: ['dev::/personal'] } as any,+ workspaceUserPreference: {},+ workspaceUserPreferenceWorkspaceId: null,+ });+ });++ it('writes the workspace bucket inside a workspace and leaves the personal list alone', async () => {+ seed({ agentModeOverrides: { a: true }, worktreeModeDirs: ['dev::/old'] });+ vi.mocked(workspaceUserSettingsService.setWorktreeModeDir).mockResolvedValue([+ 'dev::/new',+ 'dev::/old',+ ]);++ await act(() => state().setWorktreeModeDir('dev::/new', true));++ expect(workspaceUserSettingsService.setWorktreeModeDir).toHaveBeenCalledWith('dev::/new', true);+ expect(state().workspaceUserPreference).toMatchObject({+ agentModeOverrides: { a: true },+ worktreeModeDirs: ['dev::/new', 'dev::/old'],+ });+ expect(state().preference.worktreeModeDirs).toEqual(['dev::/personal']);+ expect(userService.setWorktreeModeDir).not.toHaveBeenCalled();+ });++ it('rolls the workspace bucket back and rethrows when the write fails', async () => {+ seed({ worktreeModeDirs: ['dev::/old'] });+ vi.mocked(workspaceUserSettingsService.setWorktreeModeDir).mockRejectedValue(new Error('down'));++ await expect(state().setWorktreeModeDir('dev::/old', false)).rejects.toThrow('down');+ expect(state().workspaceUserPreference.worktreeModeDirs).toEqual(['dev::/old']);+ });++ it('writes users.preference in personal mode', async () => {+ active.id = null;+ vi.mocked(userService.setWorktreeModeDir).mockResolvedValue(['dev::/a', 'dev::/personal']);++ await act(() => state().setWorktreeModeDir('dev::/a', true));++ expect(userService.setWorktreeModeDir).toHaveBeenCalledWith('dev::/a', true);+ expect(state().preference.worktreeModeDirs).toEqual(['dev::/a', 'dev::/personal']);+ expect(workspaceUserSettingsService.setWorktreeModeDir).not.toHaveBeenCalled();+ });++ it('rolls the personal list back and rethrows when the write fails', async () => {+ active.id = null;+ vi.mocked(userService.setWorktreeModeDir).mockRejectedValue(new Error('down'));++ await expect(state().setWorktreeModeDir('dev::/a', true)).rejects.toThrow('down');+ expect(state().preference.worktreeModeDirs).toEqual(['dev::/personal']);+ });+});