🤯 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(channel): move a branch into its own worktree when its directory is taken (#22855)
Arvin Xu722d8d17d67c
diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.tsindex fcffcb06455..2adcf5fe26e 100644--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts@@ -3,20 +3,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelCoordinator } from './ChannelCoordinator';-const { executions, execAgent, notifyChannel } = vi.hoisted(() => ({- executions: {- accepted: vi.fn(),- candidates: vi.fn(),- heartbeat: vi.fn(),- claim: vi.fn(),- finishDispatch: vi.fn(),- input: vi.fn(),- primaryReply: vi.fn(),- recentContext: vi.fn(),- },- execAgent: vi.fn(),- notifyChannel: vi.fn(),-}));+const { createChannelWorktree, executions, execAgent, getScopedOnlineDevices, notifyChannel } =+ vi.hoisted(() => ({+ createChannelWorktree: vi.fn(),+ executions: {+ accepted: vi.fn(),+ assignWorktree: vi.fn(),+ candidates: vi.fn(),+ heartbeat: vi.fn(),+ claim: vi.fn(),+ finishDispatch: vi.fn(),+ input: vi.fn(),+ primaryReply: vi.fn(),+ recentContext: vi.fn(),+ worktreeCandidate: vi.fn(),+ worktreeUnavailable: vi.fn(),+ },+ execAgent: vi.fn(),+ getScopedOnlineDevices: vi.fn(),+ notifyChannel: vi.fn(),+ }));vi.mock('@/database/repositories/channel', () => ({ChannelExecutionRepository: class {constructor() {@@ -31,9 +37,7 @@ vi.mock('@/server/services/aiAgent', () => ({}));vi.mock('@/server/globalConfig', () => ({ getServerDefaultAgentConfig: () => ({}) }));vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));-vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({- getScopedOnlineDevices: vi.fn().mockResolvedValue([]),-}));+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({ getScopedOnlineDevices }));vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => false }));vi.mock('./attachments', () => ({ resolveChannelAttachments: vi.fn().mockResolvedValue({}) }));vi.mock('./ChannelRoutingService', () => ({@@ -43,8 +47,9 @@ vi.mock('./ChannelRoutingService', () => ({}));vi.mock('./notify', () => ({ notifyChannel }));vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));+vi.mock('./worktree', () => ({ createChannelWorktree }));-const coordinator = (count = 3, recovering = false) => {+const coordinator = (count = 3, recovering = false, members: unknown[] = []) => {const pending = Array.from({ length: count }, (_, index) => ({id: `job-${index}`,memberId: `job-${index}`,@@ -68,13 +73,14 @@ const coordinator = (count = 3, recovering = false) => {const select = vi.fn().mockReturnValueOnce(query([{ id: 'channel', workspaceId: null }]))- .mockReturnValueOnce(query([]));+ .mockReturnValueOnce(query(members));return new ChannelCoordinator({ select } as never);};describe('Channel concurrent startup', () => {beforeEach(() => {vi.resetAllMocks();+ getScopedOnlineDevices.mockResolvedValue([]);executions.input.mockResolvedValue([]);executions.recentContext.mockResolvedValue({ messages: [], omitted: 0 });executions.primaryReply.mockResolvedValue(null);@@ -207,4 +213,63 @@ describe('Channel concurrent startup', () => {expect(prompt).toContain('<channel_reply from="Coder" type="agent"');expect(prompt).toContain('Fixed in the tokenizer.');});++ describe('a job waiting on its directory', () => {+ const candidate = {+ branch: 'lobe-channel/0123456789ab-main',+ deviceId: 'device-1',+ deviceUserId: 'owner',+ memberId: 'job-0',+ sourceDirectory: '/repo',+ threadId: null,+ };+ const online = () => {+ getScopedOnlineDevices.mockResolvedValue([{ deviceId: 'device-1', online: true }]);+ return [{ config: { deviceId: 'device-1', deviceOwnerId: 'owner' } }];+ };++ it('moves its branch into a worktree and starts it there', async () => {+ const claim = executions.claim.getMockImplementation()!;+ executions.claim.mockResolvedValueOnce(null).mockImplementation(claim);+ executions.worktreeCandidate.mockResolvedValue(candidate);+ executions.assignWorktree.mockResolvedValue(true);+ createChannelWorktree.mockResolvedValue({ path: '/home/.lobehub/worktrees/repo/wt' });++ await coordinator(1, false, online()).advance('channel');++ expect(createChannelWorktree).toHaveBeenCalledWith(candidate, null);+ expect(executions.assignWorktree).toHaveBeenCalledWith(+ 'channel',+ candidate,+ '/home/.lobehub/worktrees/repo/wt',+ );+ expect(executions.claim).toHaveBeenCalledTimes(2);+ expect(execAgent).toHaveBeenCalledTimes(1);+ });++ it('keeps waiting when the directory cannot host a worktree', async () => {+ executions.claim.mockResolvedValue(null);+ executions.worktreeCandidate.mockResolvedValue(candidate);+ createChannelWorktree.mockResolvedValue({ error: 'not a git repository' });++ await coordinator(1, false, online()).advance('channel');++ expect(executions.worktreeUnavailable).toHaveBeenCalledWith(+ 'channel',+ candidate,+ 'not a git repository',+ );+ expect(executions.claim).toHaveBeenCalledTimes(1);+ expect(execAgent).not.toHaveBeenCalled();+ });++ it('does not ask an offline device for a worktree', async () => {+ executions.claim.mockResolvedValue(null);+ executions.worktreeCandidate.mockResolvedValue(candidate);++ await coordinator(1).advance('channel');++ expect(createChannelWorktree).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex d6e6a81d6a2..22ec603a8dc 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -28,6 +28,7 @@ import { resolveChannelAttachments } from './attachments';import { ChannelRoutingService } from './ChannelRoutingService';import { notifyChannel } from './notify';import { registerLocalChannelAdvance, wakeChannel } from './queue';+import { createChannelWorktree } from './worktree';const LEASE_MS = 60_000;// Limit startup IO, not the number of Agents that may execute concurrently.@@ -87,12 +88,19 @@ export class ChannelCoordinator {await this.complete(channelId, job.id, job.operationId ?? undefined);continue;}- const claim = await this.executions.claim(channelId, job.id, {- leaseMs: LEASE_MS,- leaseOwner: crypto.randomUUID(),- onlineDeviceIds,- serverDefaultAgentConfig: getServerDefaultAgentConfig(),- });+ const claimNow = () =>+ this.executions.claim(channelId, job.id, {+ leaseMs: LEASE_MS,+ leaseOwner: crypto.randomUUID(),+ onlineDeviceIds,+ serverDefaultAgentConfig: getServerDefaultAgentConfig(),+ });+ let claim = await claimNow();+ if (+ !claim &&+ (await this.moveToWorktree(channelId, job.id, channel.workspaceId, onlineDeviceIds))+ )+ claim = await claimNow();await Promise.all([notifyChannel(this.db, channelId),claim ? this.dispatch(claim, channel.workspaceId) : undefined,@@ -106,6 +114,28 @@ export class ChannelCoordinator {}};+ /**+ * A job held back only because another run uses its member's directory moves its branch into+ * a worktree of that directory instead of waiting. Returns whether the branch got one; a+ * directory that cannot host one (not a git repo, device too old) keeps the job waiting.+ */+ private async moveToWorktree(+ channelId: string,+ jobId: string,+ workspaceId: string | null,+ onlineDeviceIds: string[],+ ) {+ const candidate = await this.executions.worktreeCandidate(channelId, jobId);+ if (!candidate || !onlineDeviceIds.includes(candidate.deviceId)) return false;+ // A device call, so it runs outside the channel lock; assignment rechecks the member.+ const created = await createChannelWorktree(candidate, workspaceId);+ if (created.path === undefined) {+ await this.executions.worktreeUnavailable(channelId, candidate, created.error);+ return false;+ }+ return this.executions.assignWorktree(channelId, candidate, created.path);+ }+private async dispatch({ job, member, topic }: ChannelClaim, workspaceId: string | null) {if (!job.operationId ||diff --git a/apps/server/src/services/channel/worktree.test.ts b/apps/server/src/services/channel/worktree.test.tsnew file mode 100644index 00000000000..6ac1ed3e05e--- /dev/null+++ b/apps/server/src/services/channel/worktree.test.ts@@ -0,0 +1,170 @@+// @vitest-environment node+import { deriveWorktreePath } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceGateway } from '@/server/services/deviceGateway';++import { createChannelWorktree } from './worktree';++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ addGitWorktree: vi.fn(),+ listGitWorktrees: vi.fn(),+ queryDeviceSystemInfo: vi.fn(),+ statPath: vi.fn(),+ },+}));++const gateway = vi.mocked(deviceGateway);++const candidate = {+ branch: 'lobe-channel/0123456789ab-main',+ deviceId: 'device-1',+ deviceUserId: 'owner-1',+ memberId: 'member-1',+ sourceDirectory: '/code/lobehub',+ threadId: null,+};++const sourceCheckout = { branch: 'main', current: true, path: '/code/lobehub' };++beforeEach(() => {+ vi.resetAllMocks();+ gateway.queryDeviceSystemInfo.mockResolvedValue({ homePath: '/Users/me' } as never);+ gateway.listGitWorktrees.mockResolvedValue([sourceCheckout]);+});++describe('createChannelWorktree', () => {+ it('cuts the branch from the source directory under ~/.lobehub/worktrees', async () => {+ gateway.addGitWorktree.mockImplementation(async ({ worktreePath }) => ({+ success: true,+ worktreePath,+ }));++ const result = await createChannelWorktree(candidate, 'ws-1');++ expect(result.path).toMatch(+ /^\/Users\/me\/\.lobehub\/worktrees\/lobehub-[\da-f]{8}\/lobe-channel-0123456789ab-main$/,+ );+ expect(gateway.addGitWorktree).toHaveBeenCalledWith({+ branch: candidate.branch,+ deviceId: 'device-1',+ path: '/code/lobehub',+ userId: 'owner-1',+ workspaceId: 'ws-1',+ worktreePath: result.path,+ });+ });++ it('reuses the checkout an earlier attempt already created', async () => {+ const worktreePath = deriveWorktreePath(candidate.sourceDirectory, candidate.branch, {+ homeDir: '/Users/me',+ });+ gateway.listGitWorktrees.mockResolvedValue([+ sourceCheckout,+ { branch: candidate.branch, current: false, path: worktreePath },+ ]);++ expect(await createChannelWorktree(candidate, null)).toEqual({ path: worktreePath });+ expect(gateway.addGitWorktree).not.toHaveBeenCalled();+ });++ it('keeps a subdirectory configuration in the same subdirectory of the checkout', async () => {+ gateway.addGitWorktree.mockImplementation(async ({ worktreePath }) => ({+ success: true,+ worktreePath,+ }));+ gateway.statPath.mockResolvedValue({ isDirectory: true } as never);+ const worktreeRoot = deriveWorktreePath('/code/lobehub', candidate.branch, {+ homeDir: '/Users/me',+ });++ const result = await createChannelWorktree(+ { ...candidate, sourceDirectory: '/code/lobehub/packages/app' },+ null,+ );++ expect(result).toEqual({ path: `${worktreeRoot}/packages/app` });+ // The checkout itself is keyed by the repository, not the subdirectory.+ expect(gateway.addGitWorktree).toHaveBeenCalledWith(+ expect.objectContaining({ path: '/code/lobehub/packages/app', worktreePath: worktreeRoot }),+ );+ });++ it('places the directory through the realpath of a checkout git spells differently', async () => {+ gateway.addGitWorktree.mockImplementation(async ({ worktreePath }) => ({+ success: true,+ worktreePath,+ }));+ // Git reports the symlinked root; the configured directory is already its realpath.+ gateway.listGitWorktrees.mockResolvedValue([{ ...sourceCheckout, path: '/link/lobehub' }]);+ gateway.statPath+ .mockResolvedValueOnce({ canonicalPath: '/code/lobehub', isDirectory: true } as never)+ .mockResolvedValue({ isDirectory: true } as never);+ const worktreeRoot = deriveWorktreePath('/link/lobehub', candidate.branch, {+ homeDir: '/Users/me',+ });++ expect(+ await createChannelWorktree(+ { ...candidate, sourceDirectory: '/code/lobehub/packages/app' },+ null,+ ),+ ).toEqual({ path: `${worktreeRoot}/packages/app` });+ });++ it('keeps waiting when the subdirectory is not part of the new checkout', async () => {+ gateway.addGitWorktree.mockImplementation(async ({ worktreePath }) => ({+ success: true,+ worktreePath,+ }));+ // An untracked or ignored directory exists in the source but not in a fresh checkout.+ gateway.statPath.mockResolvedValue(undefined);++ expect(+ await createChannelWorktree(+ { ...candidate, sourceDirectory: '/code/lobehub/packages/new-app' },+ null,+ ),+ ).toEqual({ error: 'The directory is not part of the repository checkout' });+ });++ it('keeps waiting when the directory cannot be placed inside its checkout', async () => {+ gateway.listGitWorktrees.mockResolvedValue([{ ...sourceCheckout, path: '/elsewhere' }]);++ expect(await createChannelWorktree(candidate, null)).toEqual({+ error: 'Could not locate the directory inside its repository',+ });+ expect(gateway.addGitWorktree).not.toHaveBeenCalled();+ });++ it('never asks a directory outside git to add a worktree', async () => {+ gateway.listGitWorktrees.mockResolvedValue([]);++ expect(await createChannelWorktree(candidate, null)).toEqual({+ error: 'The directory is not a git repository',+ });+ // The device creates the target's parent folder before git refuses.+ expect(gateway.addGitWorktree).not.toHaveBeenCalled();+ });++ it('reports why when git refuses the worktree', async () => {+ gateway.addGitWorktree.mockResolvedValue({+ error: "fatal: a branch named 'x' already exists",+ success: false,+ });++ expect(await createChannelWorktree(candidate, null)).toEqual({+ error: "fatal: a branch named 'x' already exists",+ });+ });++ it('does not fall back next to the repo when the device home is unknown', async () => {+ gateway.queryDeviceSystemInfo.mockResolvedValue(undefined);++ expect(await createChannelWorktree(candidate, null)).toEqual({+ error: 'The device did not report its home directory',+ });+ expect(gateway.addGitWorktree).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/channel/worktree.ts b/apps/server/src/services/channel/worktree.tsnew file mode 100644index 00000000000..ff188dabd79--- /dev/null+++ b/apps/server/src/services/channel/worktree.ts@@ -0,0 +1,102 @@+import { deriveWorktreePath } from '@lobechat/types';++import type { ChannelWorktreeCandidate } from '@/database/repositories/channel';+import { deviceGateway } from '@/server/services/deviceGateway';++/** Same freshness the device router accepts for the home directory. */+const HOME_MAX_AGE_MS = 10 * 60 * 1000;++export type ChannelWorktreeResult =+ { error: string; path?: never } | { error?: never; path: string };++const isSep = (ch: string | undefined) => ch === '/' || ch === '\\';++/** `dir` relative to `root` ('' for the root itself), or undefined when it lies outside. */+const offsetIn = (root: string, dir: string) => {+ let end = root.length;+ while (end > 0 && isSep(root[end - 1])) end -= 1;+ const base = root.slice(0, end);+ if (dir === base) return '';+ if (dir.startsWith(base) && isSep(dir[base.length])) return dir.slice(base.length + 1);+};++/** The same place inside another checkout, in that checkout's separator style. */+const inCheckout = (checkout: string, offset: string) => {+ if (!offset) return checkout;+ const sep = checkout.includes('\\') && !checkout.includes('/') ? '\\' : '/';+ return `${checkout}${sep}${offset.replaceAll(/[/\\]/g, sep)}`;+};++/**+ * Asks the device to cut the candidate's branch from its configured directory's HEAD, under+ * `~/.lobehub/worktrees/`. The path is derived here, never taken from the device. A checkout+ * left by an earlier attempt whose assignment was lost is reused. A directory inside the+ * repository keeps its place: the run works in the same subdirectory of the new checkout.+ */+export const createChannelWorktree = async (+ candidate: ChannelWorktreeCandidate,+ workspaceId: string | null,+): Promise<ChannelWorktreeResult> => {+ const scope = {+ deviceId: candidate.deviceId,+ userId: candidate.deviceUserId,+ workspaceId: workspaceId ?? undefined,+ };+ const systemInfo = await deviceGateway.queryDeviceSystemInfo(+ scope.userId,+ scope.deviceId,+ scope.workspaceId,+ { maxAgeMs: HOME_MAX_AGE_MS },+ );+ // Without the home directory the path would fall back next to the repo; keep waiting instead.+ if (!systemInfo?.homePath) return { error: 'The device did not report its home directory' };++ // A repository always lists its own checkout. Asking first keeps a directory outside git from+ // reaching `addGitWorktree`, which creates the target's parent folder before git can refuse.+ const listed = await deviceGateway.listGitWorktrees({+ ...scope,+ path: candidate.sourceDirectory,+ });+ if (!listed?.length) return { error: 'The directory is not a git repository' };++ // The checkout holding the configured directory, and where that directory sits inside it.+ // The configured directory is the device's realpath; git may spell its checkout otherwise+ // (a symlinked root), so a lexical miss is retried against the checkout's realpath.+ const source = listed.find((worktree) => worktree.current);+ let offset = source && offsetIn(source.path, candidate.sourceDirectory);+ if (source && offset === undefined) {+ const canonical = await deviceGateway.statPath({ ...scope, path: source.path });+ if (canonical?.canonicalPath)+ offset = offsetIn(canonical.canonicalPath, candidate.sourceDirectory);+ }+ if (!source || offset === undefined)+ return { error: 'Could not locate the directory inside its repository' };++ const worktreePath = deriveWorktreePath(source.path, candidate.branch, {+ homeDir: systemInfo.homePath,+ });+ // An untracked or ignored subdirectory is not in a fresh checkout; running there would fail+ // and the assignment would keep sending later replies to it, so keep waiting instead.+ const relocate = async (checkout: string): Promise<ChannelWorktreeResult> => {+ const path = inCheckout(checkout, offset);+ if (!offset) return { path };+ const stat = await deviceGateway.statPath({ ...scope, path });+ return stat?.isDirectory+ ? { path }+ : { error: 'The directory is not part of the repository checkout' };+ };++ const existing = listed.find(+ (worktree) => worktree.path === worktreePath && worktree.branch === candidate.branch,+ );+ if (existing) return relocate(existing.path);++ const added = await deviceGateway.addGitWorktree({+ ...scope,+ branch: candidate.branch,+ path: candidate.sourceDirectory,+ worktreePath,+ });+ if (added.success) return relocate(added.worktreePath ?? worktreePath);+ return { error: added.error || 'Could not create a worktree' };+};diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 1ac3826c2b8..0ff887746fc 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -155,6 +155,7 @@"receipt.errorReason": "Failure reason","receipt.errorUnavailable": "No detailed reason was recorded. Check the Agent’s model and device settings before sending again.","receipt.failedHint": "Mention it again to retry.",+ "receipt.worktree": "Working in its own worktree · {{branch}}","recipients.all": "All {{count}} Agents will reply","recipients.automatic": "The decision model will choose which Agents reply","recipients.many": "{{first}}, {{second}} and {{count}} more will reply",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 80947b7ceab..19f4092692e 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -155,6 +155,7 @@"receipt.errorReason": "失败原因","receipt.errorUnavailable": "未记录具体原因,请检查 Agent 的模型与设备设置后重新发送。","receipt.failedHint": "再次 @ 它即可重试。",+ "receipt.worktree": "在独立 worktree 中工作 · {{branch}}","recipients.all": "全部 {{count}} 位 Agent 都会回复","recipients.automatic": "将由决策模型选择回复的 Agent","recipients.many": "{{first}}、{{second}} 等 {{total}} 位 Agent 会回复",diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.mdindex 7964cb3f9cc..6dc9d1c4348 100644--- a/packages/database/src/repositories/channel/README.md+++ b/packages/database/src/repositories/channel/README.md@@ -170,6 +170,15 @@ all-candidate fallback. Stopping a reply still fences it; root completion neverOperation completion is not proof that a device process ended. Only `releaseWriter` afterconfirmed termination, or `retireReservation` for an untouched operation, releases the writer.Isolation frees the member but keeps the device/directory lock. Never retry an unknown delivery.+- A job blocked only by another writer in its member's directory moves its conversation branch+ (a Thread, or the main timeline) into a git worktree instead of waiting: the coordinator asks+ the device to cut `lobe-channel/<member>-<branch>` from that directory's HEAD under+ `~/.lobehub/worktrees/` (`deriveWorktreePath`), records it in the member's+ `metadata.worktrees`, and claims again. The worktree then is the job's working directory and+ directory lock, and the branch keeps it for later replies until the member's device or+ directory changes. The grant still checks the configured directory it was cut from. Work stays+ on the worktree branch; nothing merges it back. A directory that cannot host one (not a git+ repo, device without a home path) keeps the job waiting and is not retried for 10 minutes.- Existing hard-delete paths already reach Channel rows: Agent deletion (including trash purge,session and group deletion) cascades direct conversations, `UserModel.deleteUser` removespersonal channels and direct conversations, and workspace deletion cascades every channel in it.diff --git a/packages/database/src/repositories/channel/__tests__/worktree.test.ts b/packages/database/src/repositories/channel/__tests__/worktree.test.tsnew file mode 100644index 00000000000..18102ca7ebb--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/worktree.test.ts@@ -0,0 +1,140 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { channelMembers } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ChannelExecutionRepository } from '..';+import { worktreeBranch } from '../worktree';+import { createChannelFixture, deviceConfig, jobById, jobsOf, lease } from './testUtils';++const db: LobeChatDatabase = await getTestDB();+const fixture = createChannelFixture(db, 'channel-worktree');+const execution = new ChannelExecutionRepository(db);++beforeEach(fixture.setup);+afterEach(fixture.cleanup);++/** Two Agents configured on the same device directory, both mentioned at once. */+const sharedDirectory = async () => {+ const { asMember, channel } = await fixture.createTeamChannel();+ const first = await fixture.addAgent(channel.id, 'First', deviceConfig());+ const second = await fixture.addAgent(channel.id, 'Second', deviceConfig());+ const message = await asMember.send(channel.id, {+ content: 'Both of you',+ mentions: [first.id, second.id],+ requestKey: 'req-1',+ routing: 'decision',+ });+ const jobs = await jobsOf(db, message.id);+ const firstJob = jobs.find((job) => job.memberId === first.id)!;+ const secondJob = jobs.find((job) => job.memberId === second.id)!;+ expect(await execution.claim(channel.id, firstJob.id, lease)).not.toBeNull();+ expect(await execution.claim(channel.id, secondJob.id, lease)).toBeNull();+ return { asMember, channel, first, firstJob, second, secondJob };+};++const memberMetadata = async (memberId: string) => {+ const [member] = await db.select().from(channelMembers).where(eq(channelMembers.id, memberId));+ return member.metadata;+};++describe('channel worktrees', () => {+ it('offers a job blocked by another run in its directory for a worktree', async () => {+ const { channel, second, secondJob } = await sharedDirectory();++ expect(await execution.worktreeCandidate(channel.id, secondJob.id)).toEqual({+ branch: expect.stringMatching(+ new RegExp(`^lobe-channel/${second.id.replaceAll('-', '').slice(0, 12)}-main-[\\da-f]{8}$`),+ ),+ deviceId: 'device-1',+ deviceUserId: fixture.memberId,+ memberId: second.id,+ sourceDirectory: '/repo',+ threadId: null,+ });+ });++ it('runs the branch in its worktree once assigned, under its own directory lock', async () => {+ const { channel, second, secondJob } = await sharedDirectory();+ const candidate = (await execution.worktreeCandidate(channel.id, secondJob.id))!;++ expect(await execution.assignWorktree(channel.id, candidate, '/home/.lobehub/wt')).toBe(true);+ const claim = await execution.claim(channel.id, secondJob.id, lease);++ expect(claim?.job).toMatchObject({+ blockedCode: null,+ status: 'running',+ workingDirectory: '/home/.lobehub/wt',+ writerHeld: true,+ });+ expect(claim?.job.executionConfig).toMatchObject({+ workingDirectory: '/home/.lobehub/wt',+ worktreeBranch: candidate.branch,+ });+ // The branch has its worktree now; nothing more to create.+ expect(await memberMetadata(second.id)).toMatchObject({+ worktrees: { main: { branch: candidate.branch, path: '/home/.lobehub/wt' } },+ });+ });++ it('keeps the branch on its worktree for later replies', async () => {+ const { asMember, channel, second, secondJob } = await sharedDirectory();+ const candidate = (await execution.worktreeCandidate(channel.id, secondJob.id))!;+ await execution.assignWorktree(channel.id, candidate, '/home/.lobehub/wt');+ await execution.claim(channel.id, secondJob.id, lease);+ await execution.releaseWriter(channel.id, secondJob.id);++ const next = await asMember.send(channel.id, {+ content: 'Again',+ mentions: [second.id],+ requestKey: 'req-2',+ routing: 'decision',+ });+ const [nextJob] = await jobsOf(db, next.id);+ const claim = await execution.claim(channel.id, nextJob.id, lease);++ expect(claim?.job.workingDirectory).toBe('/home/.lobehub/wt');+ });++ it('ignores a worktree cut from a directory the member no longer uses', async () => {+ const { channel, second, secondJob } = await sharedDirectory();+ const candidate = (await execution.worktreeCandidate(channel.id, secondJob.id))!;+ await db+ .update(channelMembers)+ .set({ config: { deviceId: 'device-1', workingDirectory: '/other' } })+ .where(eq(channelMembers.id, second.id));++ expect(await execution.assignWorktree(channel.id, candidate, '/home/.lobehub/wt')).toBe(false);+ const claim = await execution.claim(channel.id, secondJob.id, lease);+ expect(claim?.job.workingDirectory).toBe('/other');+ });++ it('leaves a directory that cannot host a worktree alone for a while', async () => {+ const { channel, secondJob } = await sharedDirectory();+ const candidate = (await execution.worktreeCandidate(channel.id, secondJob.id))!;++ await execution.worktreeUnavailable(channel.id, candidate, 'not a git repository');++ expect(await execution.worktreeCandidate(channel.id, secondJob.id)).toBeUndefined();+ expect(await jobById(db, secondJob.id)).toMatchObject({+ blockedCode: 'directory_locked',+ status: 'queued',+ });+ });++ it('does not offer a job that waits on something other than its directory', async () => {+ const { channel, firstJob } = await sharedDirectory();++ expect(await execution.worktreeCandidate(channel.id, firstJob.id)).toBeUndefined();+ });++ it("names a later environment's worktree apart from the branch an earlier one created", () => {+ const first = worktreeBranch('member-1', null, 'device-1', '/repo');++ expect(worktreeBranch('member-1', null, 'device-1', '/repo')).toBe(first);+ expect(worktreeBranch('member-1', null, 'device-1', '/repo-other-checkout')).not.toBe(first);+ expect(worktreeBranch('member-1', null, 'device-2', '/repo')).not.toBe(first);+ });+});diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex 6076e874923..b655080a37c 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -21,6 +21,7 @@ import { AWAITING_PRIMARY_REASON, findThread } from './delivery';import { buildManifest } from './manifest';import { resolveTopic } from './topic';import { audit } from './transaction';+import { assignedWorktree } from './worktree';export interface ChannelClaimOptions {/** How long the claimer may go without a heartbeat before reconcile takes over. */@@ -126,12 +127,12 @@ const deviceBlock = async (return { code: 'unavailable', reason: 'The device owner did not allow this environment' };};-/** Another channel's live writer in the same device directory. */+/** Another live writer in the same device directory, from any channel or member. */const directoryBlock = async (tx: Transaction,- member: ChannelMemberItem,+ deviceId: string | undefined,+ workingDirectory: string | undefined,): Promise<Block | undefined> => {- const { deviceId, workingDirectory } = member.config ?? {};if (!deviceId || !workingDirectory) return;const [busy] = await tx@@ -316,13 +317,20 @@ export const claimJob = async (return null;}- const executionConfig = await resolveExecutionConfig(+ const resolved = await resolveExecutionConfig(tx,channel,member,requester.userId,options.serverDefaultAgentConfig,);+ // A branch that moved into its own worktree runs there; the grant still covers the+ // configured directory it was cut from.+ const worktree = assignedWorktree(member, job.threadId);+ const executionConfig =+ resolved && worktree+ ? { ...resolved, workingDirectory: worktree.path, worktreeBranch: worktree.branch }+ : resolved;if (!executionConfig) {await block(tx, job, 'unavailable', 'The Agent is unavailable');return null;@@ -334,7 +342,9 @@ export const claimJob = async (return null;}- const blocked = (await deviceBlock(tx, channel, member)) ?? (await directoryBlock(tx, member));+ const blocked =+ (await deviceBlock(tx, channel, member)) ??+ (await directoryBlock(tx, member.config.deviceId, executionConfig.workingDirectory));if (blocked) {await block(tx, job, blocked.code, blocked.reason);return null;@@ -399,7 +409,7 @@ export const claimJob = async (operationId,topicId: topic.id,status: 'running',- workingDirectory: member.config!.workingDirectory,+ workingDirectory: executionConfig.workingDirectory,writerHeld: true,}).where(eq(channelJobs.id, job.id))diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex ff3c31d6c77..acefe3fc7cc 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -24,6 +24,8 @@ import { resolveRouting } from './routing';import type { ChannelStopScope } from './stop';import { stopScope } from './stop';import { audit, withChannelLock } from './transaction';+import type { ChannelWorktreeCandidate } from './worktree';+import { assignWorktree, findWorktreeCandidate, markWorktreeUnavailable } from './worktree';import { advanceOperation, isolateWriter, isOpenJob, operationStatus } from './writer';/**@@ -230,6 +232,24 @@ export class ChannelExecutionRepository {): Promise<ChannelClaim | null> =>withChannelLock(this.db, channelId, (tx, channel) => claimJob(tx, channel, jobId, options));+ /** A job waiting only on its directory whose branch could move into its own worktree. */+ worktreeCandidate = async (channelId: string, jobId: string) =>+ withChannelLock(this.db, channelId, (tx) => findWorktreeCandidate(tx, channelId, jobId));++ /** Records the worktree the device created for the candidate's branch. */+ assignWorktree = async (channelId: string, candidate: ChannelWorktreeCandidate, path: string) =>+ withChannelLock(this.db, channelId, (tx) => assignWorktree(tx, channelId, candidate, path));++ /** The device could not create the worktree; leave the directory alone for a while. */+ worktreeUnavailable = async (+ channelId: string,+ candidate: ChannelWorktreeCandidate,+ reason: string,+ ) =>+ withChannelLock(this.db, channelId, (tx) =>+ markWorktreeUnavailable(tx, channelId, candidate, reason),+ );+/*** The triggering request and its explicit quote; see `recentContext` for the rest. Reads* without the channel lock, since nothing at or before the cutoff changes after the claim.diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 5d7bf0f5a95..9f7f495d4f1 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -56,6 +56,7 @@ export type { AppliedChannelRouting, ChannelRoutingDecision } from './routing';export type { ChannelSendInput } from './send';export type { ChannelStopScope } from './stop';export type { ChannelAccess, ChannelWriteOptions } from './types';+export type { ChannelWorktreeCandidate } from './worktree';/** Recycle-bin row title: the start of the thread's root message. */const CHANNEL_THREAD_TITLE_LENGTH = 120;diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 6c4651a636e..2c186d910da 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -158,6 +158,7 @@ export const readChannelView = async (errorMessage: sql<string | null>`CASE WHEN ${channelJobs.status} = 'failed'THEN left(${agentOperations.error}->>'message', 2000) ELSE NULL END`,writerHeld: channelJobs.writerHeld,+ worktreeBranch: sql<string | null>`${channelJobs.executionConfig}->>'worktreeBranch'`,operationStatus: agentOperations.status,createdAt: channelJobs.createdAt,publicationRevoked: channelJobs.publicationRevoked,diff --git a/packages/database/src/repositories/channel/worktree.ts b/packages/database/src/repositories/channel/worktree.tsnew file mode 100644index 00000000000..b18a169d1fe--- /dev/null+++ b/packages/database/src/repositories/channel/worktree.ts@@ -0,0 +1,204 @@+import type { ChannelMemberMetadata, ChannelMemberWorktree } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import type { ChannelMemberItem } from '../../schemas';+import { channelJobs, channelMembers } from '../../schemas';+import type { Transaction } from '../../type';+import { audit } from './transaction';++/**+ * A conversation branch whose member directory is taken by another run moves into its own git+ * worktree instead of queueing. The worktree belongs to the (member, branch) pair, so later+ * replies in the same branch keep the same checkout and session; nothing is merged back.+ */++/** How long a directory that could not host a worktree is left alone before retrying. */+export const WORKTREE_RETRY_MS = 10 * 60 * 1000;++/** Key of a conversation branch: its Thread, or the main timeline. */+export const worktreeKey = (threadId: string | null) => threadId ?? 'main';++/** 32-bit FNV-1a as 8 hex chars; only tells environments apart, not a security boundary. */+const shortHash = (input: string) => {+ let hash = 0x81_1c_9d_c5;+ for (let i = 0; i < input.length; i += 1) {+ hash ^= input.charCodeAt(i);+ hash = Math.imul(hash, 0x01_00_01_93);+ }+ return (hash >>> 0).toString(16).padStart(8, '0');+};++/**+ * Git branch for the member's worktree. Member ids are unique across all channels; the+ * environment hash keeps a later environment (another checkout of the same repository) from+ * colliding with the branch an earlier one already created, which `git worktree add -b` refuses.+ */+export const worktreeBranch = (+ memberId: string,+ threadId: string | null,+ deviceId: string,+ sourceDirectory: string,+) =>+ `lobe-channel/${memberId.replaceAll('-', '').slice(0, 12)}-${worktreeKey(threadId)}-${shortHash(+ `${deviceId}\0${sourceDirectory}`,+ )}`;++/** The branch's worktree, while the member still runs in the directory it was cut from. */+export const assignedWorktree = (+ member: Pick<ChannelMemberItem, 'config' | 'metadata'>,+ threadId: string | null,+): ChannelMemberWorktree | undefined => {+ const { deviceId, workingDirectory } = member.config ?? {};+ const worktree = (member.metadata as ChannelMemberMetadata | null)?.worktrees?.[+ worktreeKey(threadId)+ ];+ if (+ worktree &&+ deviceId &&+ worktree.deviceId === deviceId &&+ worktree.sourceDirectory === workingDirectory+ )+ return worktree;+};++export interface ChannelWorktreeCandidate {+ branch: string;+ deviceId: string;+ /** Device calls route by the device owner, else the requester. */+ deviceUserId: string;+ memberId: string;+ sourceDirectory: string;+ threadId: string | null;+}++/**+ * A queued job held back only by another run in its member's directory, whose branch has no+ * worktree yet. The caller holds the channel lock.+ */+export const findWorktreeCandidate = async (+ tx: Transaction,+ channelId: string,+ jobId: string,+): Promise<ChannelWorktreeCandidate | undefined> => {+ const [row] = await tx+ .select({ job: channelJobs, member: channelMembers })+ .from(channelJobs)+ .innerJoin(channelMembers, eq(channelMembers.id, channelJobs.memberId))+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.id, jobId),+ eq(channelJobs.status, 'queued'),+ eq(channelJobs.blockedCode, 'directory_locked'),+ eq(channelMembers.status, 'active'),+ ),+ );+ if (!row) return;+ const { job, member } = row;+ const { deviceId, deviceOwnerId, workingDirectory } = member.config ?? {};+ if (!deviceId || !workingDirectory || assignedWorktree(member, job.threadId)) return;++ const unavailable = (member.metadata as ChannelMemberMetadata | null)?.worktreeUnavailable;+ if (+ unavailable?.deviceId === deviceId &&+ unavailable.sourceDirectory === workingDirectory &&+ Date.now() - new Date(unavailable.at).getTime() < WORKTREE_RETRY_MS+ )+ return;++ const [requester] = await tx+ .select({ userId: channelMembers.userId })+ .from(channelMembers)+ .where(eq(channelMembers.id, job.requesterMemberId));+ const deviceUserId = deviceOwnerId ?? requester?.userId;+ if (!deviceUserId) return;++ return {+ branch: worktreeBranch(member.id, job.threadId, deviceId, workingDirectory),+ deviceId,+ deviceUserId,+ memberId: member.id,+ sourceDirectory: workingDirectory,+ threadId: job.threadId,+ };+};++/** Reads the member and checks it still runs where the worktree was cut from. */+const currentMember = async (+ tx: Transaction,+ channelId: string,+ candidate: Pick<ChannelWorktreeCandidate, 'deviceId' | 'memberId' | 'sourceDirectory'>,+) => {+ const [member] = await tx+ .select()+ .from(channelMembers)+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.id, candidate.memberId)));+ if (+ member?.config?.deviceId !== candidate.deviceId ||+ member.config.workingDirectory !== candidate.sourceDirectory+ )+ return;+ return member;+};++/**+ * Records the branch's worktree. Returns false when the member's environment changed while+ * the device created it; that checkout is then simply unused.+ */+export const assignWorktree = async (+ tx: Transaction,+ channelId: string,+ candidate: ChannelWorktreeCandidate,+ path: string,+): Promise<boolean> => {+ const member = await currentMember(tx, channelId, candidate);+ if (!member) return false;+ const metadata = (member.metadata ?? {}) as ChannelMemberMetadata;+ const worktree: ChannelMemberWorktree = {+ branch: candidate.branch,+ deviceId: candidate.deviceId,+ path,+ sourceDirectory: candidate.sourceDirectory,+ };+ await tx+ .update(channelMembers)+ .set({+ metadata: {+ ...metadata,+ worktrees: { ...metadata.worktrees, [worktreeKey(candidate.threadId)]: worktree },+ },+ })+ .where(eq(channelMembers.id, member.id));+ await audit(tx, channelId, 'worktree_assigned', member.id, {+ branch: candidate.branch,+ threadId: candidate.threadId,+ });+ return true;+};++/** The directory could not host a worktree; the job keeps waiting for the directory. */+export const markWorktreeUnavailable = async (+ tx: Transaction,+ channelId: string,+ candidate: ChannelWorktreeCandidate,+ reason: string,+) => {+ const member = await currentMember(tx, channelId, candidate);+ if (!member) return;+ await tx+ .update(channelMembers)+ .set({+ metadata: {+ ...member.metadata,+ worktreeUnavailable: {+ at: new Date().toISOString(),+ deviceId: candidate.deviceId,+ sourceDirectory: candidate.sourceDirectory,+ },+ },+ })+ .where(eq(channelMembers.id, member.id));+ await audit(tx, channelId, 'worktree_unavailable', member.id, {+ reason: reason.slice(0, 500),+ });+};diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 807b2b4bc57..3850777b7bf 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -135,6 +135,7 @@ export default {'routing.receiving': 'Agents receiving your message…','routing.unassigned': 'No Agent picked this up. Mention one to get a reply.','receipt.failedHint': 'Mention it again to retry.',+ 'receipt.worktree': 'Working in its own worktree · {{branch}}','recipients.all': 'All {{count}} Agents will reply','recipients.named': '{{names}} will reply','recipients.many': '{{first}}, {{second}} and {{count}} more will reply',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 915bb2f97e9..3b4c2310b35 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -147,8 +147,27 @@ export interface ChannelConfig {wake?: Record<string, unknown>;}+/**+ * A git worktree a member's conversation branch moved into when another run held its+ * configured directory. Cut from that directory's HEAD; the branch keeps working there until+ * the member's environment changes.+ */+export interface ChannelMemberWorktree {+ branch: string;+ deviceId: string;+ /** Absolute path under `~/.lobehub/worktrees/`, see `deriveWorktreePath`. */+ path: string;+ /** The member's configured directory it was cut from. */+ sourceDirectory: string;+}+/** Free-form member state that does not need its own column. */-export type ChannelMemberMetadata = Record<string, unknown>;+export type ChannelMemberMetadata = Record<string, unknown> & {+ /** Worktree per conversation branch: a Thread id, or `main` for the main timeline. */+ worktrees?: Record<string, ChannelMemberWorktree>;+ /** The configured directory could not host a worktree (e.g. not a git repo); retried later. */+ worktreeUnavailable?: { at: string; deviceId: string; sourceDirectory: string };+};/** Free-form channel state that does not need its own column. */export type ChannelMetadata = Record<string, unknown>;@@ -166,6 +185,8 @@ export type ChannelMessageMetadata = Record<string, unknown>;export interface ChannelExecutionConfig extends LobeAgentConfig, ChannelMemberConfig {provider: string;runtime: ChannelRuntime;+ /** Set when the run works in its branch's worktree; `workingDirectory` is then that worktree. */+ worktreeBranch?: string;}/**@@ -402,6 +423,8 @@ export interface ChannelPublicJob {publicationRevoked: boolean;status: ChannelJobStatus;threadId: string | null;+ /** Git branch of the worktree the run works in, instead of the member's own directory. */+ worktreeBranch?: string | null;writerHeld: boolean;}diff --git a/src/features/Channels/MessageReceipts.tsx b/src/features/Channels/MessageReceipts.tsxindex 28d8c36eca1..089e3cce1cb 100644--- a/src/features/Channels/MessageReceipts.tsx+++ b/src/features/Channels/MessageReceipts.tsx@@ -99,6 +99,11 @@ export function ReplyDetail({</Flexbox><ChannelStatus label={t(channelJobStatus(job))} tone={channelJobTone(job)} /></Flexbox>+ {job.worktreeBranch && (+ <Text ellipsis fontSize={12} title={job.worktreeBranch} type="secondary">+ {t('receipt.worktree', { branch: job.worktreeBranch })}+ </Text>+ )}{job.status === 'failed' && (<Flexbox gap={4}><Text weight={500}>{t('receipt.errorReason')}</Text>