Skip to content

🤯 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.

🐛 fix(chat): persist first sends before creating worktrees (#23295)

Bryan73d9f1dce961
diff --git a/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduledTopicDispatch.test.ts b/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduledTopicDispatch.test.ts
index 5f5ba021201..bce555cfcab 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduledTopicDispatch.test.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduledTopicDispatch.test.ts
@@ -95,6 +95,16 @@ describe('scheduledTopicDispatch', () => {
mocks.findById.mockImplementation(async (id: string) => ({ content: 'summarize my PRs', id }));
});
+ it('limits a worktree wakeup to the topic in the queue envelope', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([]);
+ const response = await createApp().request('/scheduled-topic-dispatch', {
+ body: JSON.stringify({ payload: { topicId: 'topic-to-wake' } }),
+ method: 'POST',
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.getDueScheduledTopics).toHaveBeenCalledWith({}, expect.any(Date), 'topic-to-wake');
+ });
+
it('runs a delayed start off its pre-persisted user turn, without writing it twice', async () => {
mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduledTopicDispatch.ts b/apps/server/src/router-hono/workflows/task/handlers/scheduledTopicDispatch.ts
index 763c3eb6e41..ddbf72c012c 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/scheduledTopicDispatch.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/scheduledTopicDispatch.ts
@@ -1,126 +1,15 @@
-import { randomUUID } from 'node:crypto';
-
-import { parseTopicScheduledRun } from '@lobechat/types';
-import debug from 'debug';
import type { Context } from 'hono';
-import { TopicModel } from '@/database/models/topic';
-import { getServerDB } from '@/database/server';
-
-import { dispatchScheduledRun } from './scheduledRunKinds';
-
-const log = debug('lobe-server:workflows:task:scheduled-topic-dispatch');
-
-/** How long a claim lease is held before another tick may re-claim the topic. */
-const CLAIM_LEASE_MS = 5 * 60 * 1000;
+import {
+ dispatchDueScheduledTopics,
+ type ScheduledTopicDispatchPayload,
+} from '@/server/services/aiAgent/pipeline/scheduledTopicDispatch';
-export interface ScheduledTopicDispatchPayload {
- /** When true, only report which topics are due without claiming/dispatching. */
- dryRun?: boolean;
-}
-
-/**
- * Cron-style dispatcher for deferred runs on pure (non-Task) topics. Registered
- * as a QStash Schedule (e.g. `*\/10 * * * *`) pointing at this endpoint. On each
- * tick:
- *
- * 1. Loads topics with `status = 'scheduled'` whose `scheduledRun.runAt` has
- * passed and that aren't under a live claim.
- * 2. Atomically claims each (a lease on `metadata.scheduledRun.claim`) so two
- * ticks / replicas never dispatch the same run twice.
- * 3. Hands the run to its kind handler, which re-enters
- * `AiAgentService.execAgent` — the same execution engine as a normal agent
- * run, which already routes remote runs to the topic's bound device via the
- * device gateway.
- *
- * Everything here is kind-agnostic: scanning, the lease and clearing state are
- * shared, and a {@link dispatchScheduledRun} handler decides only *what* to run.
- *
- * This intentionally does NOT enter TaskLifecycle — a pure topic just runs its
- * agent. On success the scheduled state is cleared; on failure (e.g. the device
- * is offline) the topic stays `scheduled` and the claim lease expires so the next
- * tick retries — the scheduled state is never lost.
- *
- * Signature verification is handled by the `qstashAuth` middleware on the route.
- */
export async function scheduledTopicDispatch(c: Context) {
try {
- const body = (await c.req.json().catch(() => ({}))) as ScheduledTopicDispatchPayload;
- const { dryRun = false } = body ?? {};
-
- const db = await getServerDB();
- const now = new Date();
- const due = await TopicModel.getDueScheduledTopics(db, now);
-
- log('scan: due=%d dryRun=%s', due.length, dryRun);
-
- if (dryRun || due.length === 0) {
- return c.json({ claimed: 0, dispatched: 0, dryRun, due: due.length, success: true });
- }
-
- let claimed = 0;
- let dispatched = 0;
- let discarded = 0;
- for (const topic of due) {
- // Reads the current payload and the pre-`kind` legacy one alike — the due
- // query selects both, so this must dispatch both.
- const run = parseTopicScheduledRun(topic.metadata?.scheduledRun);
- if (!run) {
- // A due topic whose payload we can't dispatch would re-surface on every
- // tick forever, so drop the schedule instead of skipping it. Back to
- // `active`: the topic itself is intact, only the schedule is unusable.
- console.error(
- '[scheduled-topic-dispatch] discarding unparseable scheduledRun topic=%s: %O',
- topic.id,
- topic.metadata?.scheduledRun,
- );
- await TopicModel.clearScheduledRun(db, topic.id, 'active').catch(() => undefined);
- discarded += 1;
- continue;
- }
-
- const claim = {
- claimedAt: now.toISOString(),
- expiresAt: new Date(now.getTime() + CLAIM_LEASE_MS).toISOString(),
- id: randomUUID(),
- };
-
- const won = await TopicModel.claimScheduledTopic(db, topic.id, claim, now).catch((err) => {
- console.error('[scheduled-topic-dispatch] claim failed topic=%s: %O', topic.id, err);
- return false;
- });
- if (!won) continue;
- claimed += 1;
-
- const workspaceId = topic.workspaceId ?? undefined;
- try {
- const result = await dispatchScheduledRun(run, {
- claimId: claim.id,
- db,
- topic,
- workspaceId,
- });
- if (!result.success) {
- throw new Error(result.error || result.message || 'Scheduled run dispatch failed');
- }
-
- // Success — execAgent now owns the run; clear the scheduled state.
- await TopicModel.clearScheduledRun(db, topic.id, 'running', claim.id);
- dispatched += 1;
- log(
- 'dispatched topic=%s kind=%s device=%s',
- topic.id,
- run.kind,
- topic.metadata?.boundDeviceId,
- );
- } catch (err) {
- // Leave the topic `scheduled` (e.g. device offline). The claim lease
- // expires and the next tick retries — scheduled state is never lost.
- console.error('[scheduled-topic-dispatch] dispatch failed topic=%s: %O', topic.id, err);
- }
- }
-
- return c.json({ claimed, discarded, dispatched, due: due.length, success: true });
+ const body = (await c.req.json().catch(() => ({}))) as
+ (ScheduledTopicDispatchPayload & { payload?: ScheduledTopicDispatchPayload }) | null;
+ return c.json(await dispatchDueScheduledTopics(body?.payload ?? body ?? {}));
} catch (error) {
console.error('[task/scheduled-topic-dispatch] Error:', error);
return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.ts
index e3f6cc49dac..923453f0855 100644
--- a/apps/server/src/routers/lambda/aiAgent/exec.ts
+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts
@@ -1,29 +1,42 @@
import { randomUUID } from 'node:crypto';
import type { ExecAgentResult } from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
+import {
+ ComposerUserMessageSchema,
+ entityIdPattern,
+ firstSendWorktreeSchema,
+ RequestTrigger,
+ UserInterventionConfigSchema,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import pMap from 'p-map';
+import { z } from 'zod';
import {
type AgentInterventionShareVisitorScope,
type AgentInterventionSourceAction,
resolveAgentInterventionBySource,
} from '@/business/server/agent-run/agentInterventionReview';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import type { MessageModel } from '@/database/models/message';
import { HumanApprovalAlreadyResolvedError } from '@/database/models/message';
+import { TopicRepository } from '@/database/repositories/topic';
import { router } from '@/libs/trpc/lambda';
import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { startComposerRun } from '@/server/services/aiAgent/composerRun';
+import { createAgentConfigResolver } from '@/server/services/aiAgent/pipeline/precreatedTopic';
+import { wakeWorktreeTurn } from '@/server/services/aiAgent/pipeline/scheduledTopicDispatch';
+import { submitWorktreeTurn } from '@/server/services/aiAgent/pipeline/submitWorktreeTurn';
import { RequestedDeviceIgnoredError } from '@/server/services/aiAgent/pipeline/turnSetup';
import { AgentRelayHopLimitError } from '@/server/services/aiAgent/sourceAttribution';
import {
ForeignLiveRunError,
TopicStartReservationError,
} from '@/server/services/aiAgent/topicStartReservation';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import type { ExecAgentInput } from './execSchemas';
import {
@@ -42,6 +55,23 @@ import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './utils';
const log = debug('lobe-server:ai-agent-router');
+const SubmitWorktreeTurnSchema = z.object({
+ agentId: z.string().min(1),
+ assistantMessageId: z.string().regex(entityIdPattern('messages')),
+ fileIds: z.array(z.string()).optional(),
+ mentionedAgents: z.array(z.object({ id: z.string(), name: z.string() })).optional(),
+ prompt: z.string(),
+ projectId: z.string().optional(),
+ projectWorkingDirectoryId: z.string().optional(),
+ selectedSkillIds: z.array(z.string()).optional(),
+ selectedToolIds: z.array(z.string()).optional(),
+ topicId: z.string().regex(entityIdPattern('topics')),
+ userInterventionConfig: UserInterventionConfigSchema.optional(),
+ userMessage: ComposerUserMessageSchema.optional(),
+ userMessageId: z.string().regex(entityIdPattern('messages')),
+ worktree: firstSendWorktreeSchema,
+});
+
/**
* Cross-version bridge: older Web clients call execAgent directly with resume
* payloads and know nothing about the v2 source endpoint. Recover the
@@ -391,6 +421,84 @@ export const execRouter = router({
});
}
}),
+
+ submitWorktreeTurn: aiAgentWriteProcedure
+ .input(SubmitWorktreeTurnSchema)
+ .mutation(async ({ ctx, input }) => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+ await assertCanUseWorkspaceAgent({
+ agentId: input.agentId,
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ const result = await submitWorktreeTurn(
+ {
+ db: ctx.serverDB,
+ resolveAgentConfigOrThrow: createAgentConfigResolver(
+ ctx.serverDB,
+ ctx.userId,
+ workspaceId,
+ ),
+ userId: ctx.userId,
+ workspaceId,
+ },
+ input,
+ );
+ if (result.topic.status === 'scheduled') {
+ afterUnscoped(() =>
+ wakeWorktreeTurn(result.topic.id).catch((error) => {
+ console.error('[aiAgent:submitWorktreeTurn] wakeup failed', error);
+ }),
+ );
+ }
+ return result;
+ }),
+
+ cancelWorktreeTurn: aiAgentWriteProcedure
+ .input(z.object({ topicId: z.string() }))
+ .mutation(({ ctx, input }) =>
+ new TopicRepository(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).cancelWorktreeStart(input.topicId),
+ ),
+
+ retryWorktreeTurn: aiAgentWriteProcedure
+ .input(z.object({ topicId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const topic = await ctx.topicModel.findOwnTopicById(input.topicId);
+ const run = topic?.metadata?.scheduledRun;
+ if (!topic || run?.kind !== 'worktree_start' || !topic.agentId)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Worktree send not found.' });
+ const workspaceId = ctx.workspaceId ?? undefined;
+ await assertCanUseWorkspaceAgent({
+ agentId: topic.agentId,
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+ const operation = await new AgentOperationModel(
+ ctx.serverDB,
+ ctx.userId,
+ workspaceId,
+ ).findById(run.operationId);
+ if (operation?.status !== 'idle' || operation.topicId !== topic.id)
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The worktree send has already been dispatched.',
+ });
+ const scheduledRun = await ctx.topicModel.retryWorktreeStart(topic.id);
+ if (!scheduledRun) return false;
+ afterUnscoped(() =>
+ wakeWorktreeTurn(topic.id, scheduledRun.runAt).catch((error) => {
+ console.error('[aiAgent:retryWorktreeTurn] wakeup failed', error);
+ }),
+ );
+ return true;
+ }),
/**
* Batch execute multiple agents
* Supports parallel or sequential execution
diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
index 64ee8837041..d4c1c314f0f 100644
--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
@@ -23,6 +23,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {
['beginLocalHeteroRunFee', 'mutation'],
['beginServerDefaultHeterogeneousOperation', 'mutation'],
['cancelServerDefaultHeterogeneousOperation', 'mutation'],
+ ['cancelWorktreeTurn', 'mutation'],
['createClientGroupAgentTaskThread', 'mutation'],
['createClientTaskThread', 'mutation'],
['describeServerDefaultHeterogeneousModel', 'mutation'],
@@ -54,6 +55,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {
['resolveAgentInterventionBySource', 'mutation'],
['resolveHeteroIntervention', 'mutation'],
['resumeClientLlmWait', 'mutation'],
+ ['retryWorktreeTurn', 'mutation'],
['returnHeteroSteer', 'mutation'],
['scheduleAgentRun', 'mutation'],
['setQueuedMessages', 'mutation'],
@@ -61,6 +63,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {
['stopHeteroBackgroundTask', 'mutation'],
['stopPendingApproval', 'mutation'],
['submitHeteroIntervention', 'mutation'],
+ ['submitWorktreeTurn', 'mutation'],
['updateClientTaskThreadStatus', 'mutation'],
['waitHeteroSteer', 'mutation'],
['waitInterventionResponse', 'query'],
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
index e4f61080e27..2583d528e6d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
@@ -1,4 +1,4 @@
-import { ChatErrorType } from '@lobechat/types';
+import { ChatErrorType, RequestTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
@@ -290,6 +290,29 @@ describe('AiAgentService.execAgent - external agent run fee', () => {
expect(fees.releaseAgentRunFee).not.toHaveBeenCalled();
});
+ it('grants goal management to a saved chat turn without inserting another user message', async () => {
+ topicMock.findById.mockResolvedValue({ id: 'topic-1', metadata: {} });
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ parentMessageId: 'msg_saved',
+ persistedUserMessageId: 'msg_saved',
+ prompt: 'Create a goal to fix the bug',
+ suppressUserMessage: true,
+ trigger: RequestTrigger.Chat,
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockSignHeteroOperationJWT).toHaveBeenCalledWith(
+ expect.objectContaining({ capabilities: expect.arrayContaining(['goal:manage']) }),
+ );
+ expect(mockMessageCreate).toHaveBeenCalledTimes(1);
+ expect(mockMessageCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ parentId: 'msg_saved', role: 'assistant' }),
+ undefined,
+ );
+ });
+
it('leaves a refused dispatch’s fee to the completion that settles its error', async () => {
heteroAgentConfig.agencyConfig = {
...heteroAgentConfig.agencyConfig,
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/submitWorktreeTurn.integration.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/submitWorktreeTurn.integration.test.ts
new file mode 100644
index 00000000000..3f6fc468cc6
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/submitWorktreeTurn.integration.test.ts
@@ -0,0 +1,268 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { generateEntityId } from '@lobechat/utils';
+import { eq } from 'drizzle-orm';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import { TopicRepository } from '@/database/repositories/topic';
+import { agents, messages, topics, users } from '@/database/schemas';
+
+import { submitWorktreeTurn } from '../submitWorktreeTurn';
+
+vi.mock('../precreatedTopic', () => ({
+ resolvePrecreatedTopicSnapshot: async () => ({
+ agentConfig: { agencyConfig: { executionTarget: 'auto' } },
+ snapshot: { model: 'test-model', provider: 'test-provider' },
+ }),
+}));
+
+const db = await getTestDB();
+const userId = 'worktree-turn-test-user';
+const agentId = generateEntityId('agents');
+const deps = { db, resolveAgentConfigOrThrow: vi.fn(), userId };
+const topicModel = new TopicModel(db, userId);
+const topicRepo = new TopicRepository(db, userId);
+const messageModel = new MessageModel(db, userId);
+const operationModel = new AgentOperationModel(db, userId);
+
+const request = () => ({
+ agentId,
+ assistantMessageId: generateEntityId('messages'),
+ prompt: 'Run from this branch',
+ topicId: generateEntityId('topics'),
+ userMessageId: generateEntityId('messages'),
+ worktree: {
+ baseBranch: 'release',
+ deviceId: 'dev_1',
+ path: '/repo',
+ repoType: 'git' as const,
+ sourcePath: '/repo',
+ },
+});
+
+beforeAll(async () => {
+ await db.insert(users).values({ id: userId });
+ await db.insert(agents).values({ id: agentId, userId });
+});
+
+afterAll(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe('submitWorktreeTurn', () => {
+ it('commits the first message and worktree intent together and accepts a repeat of the same request', async () => {
+ const input = request();
+ const { topic } = await submitWorktreeTurn(deps, input);
+ const run = topic.metadata?.scheduledRun;
+
+ expect(topic.status).toBe('scheduled');
+ expect(run).toMatchObject({ kind: 'worktree_start', userMessageId: input.userMessageId });
+ expect(await messageModel.findById(input.userMessageId)).toMatchObject({
+ content: input.prompt,
+ role: 'user',
+ topicId: input.topicId,
+ });
+ expect(
+ await operationModel.findById(run!.kind === 'worktree_start' ? run!.operationId : ''),
+ ).toMatchObject({
+ metadata: { firstSendWorktree: { worktree: input.worktree } },
+ status: 'idle',
+ topicId: input.topicId,
+ });
+
+ await expect(submitWorktreeTurn(deps, input)).resolves.toMatchObject({
+ topic: { id: input.topicId },
+ });
+ expect((await topicModel.findById(input.topicId))?.metadata?.scheduledRun).toEqual(run);
+ });
+
+ it('keeps the worktree request when the run consumes its reservation', async () => {
+ const input = request();
+ await submitWorktreeTurn(deps, input);
+ const operationId = `op_worktree_${input.topicId}`;
+ await operationModel.recordStart({
+ agentId,
+ metadata: { assistantMessageId: input.assistantMessageId },
+ operationId,
+ requireReservation: true,
+ topicId: input.topicId,
+ });
+ await expect(operationModel.findById(operationId)).resolves.toMatchObject({
+ metadata: {
+ assistantMessageId: input.assistantMessageId,
+ firstSendWorktree: { worktree: input.worktree },
+ },
+ status: 'running',
+ });
+ });
+
+ it('persists the selected worktree device as explicit for later turns of an auto agent', async () => {
+ const input = request();
+ await submitWorktreeTurn(deps, input);
+
+ expect((await topicModel.findById(input.topicId))?.metadata).toMatchObject({
+ boundDeviceId: input.worktree.deviceId,
+ deviceBindingPinned: true,
+ });
+ });
+
+ it('rolls back the topic when the first message cannot be inserted', async () => {
+ const input = request();
+ const otherTopic = request().topicId;
+ await db.insert(topics).values({ agentId, id: otherTopic, userId });
+ await messageModel.create(
+ { agentId, content: 'already exists', role: 'user', topicId: otherTopic },
+ input.userMessageId,
+ );
+
+ await expect(submitWorktreeTurn(deps, input)).rejects.toThrow();
+ expect(await topicModel.findById(input.topicId)).toBeUndefined();
+ expect(await operationModel.findById(`op_worktree_${input.topicId}`)).toBeNull();
+ });
+
+ it('cancels an offline wait without deleting the message or allowing a late dispatch', async () => {
+ const input = request();
+ await submitWorktreeTurn(deps, input);
+ const { topicId, userMessageId } = input;
+ const operationId = `op_worktree_${topicId}`;
+ const now = new Date();
+ const claim = {
+ claimedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + 5000).toISOString(),
+ id: 'offline-check',
+ };
+ await expect(TopicModel.claimScheduledTopic(db, topicId, claim, now)).resolves.toBe(true);
+ await expect(topicRepo.cancelWorktreeStart(topicId)).resolves.toBe('busy');
+
+ const retryAt = new Date(now.getTime() + 30_000);
+ await TopicModel.finishWorktreeStart(db, topicId, claim.id, {
+ retryAt: retryAt.toISOString(),
+ success: false,
+ });
+ await expect(
+ new TopicRepository(db, 'foreign-user').cancelWorktreeStart(topicId),
+ ).resolves.toBe('unchanged');
+ await expect(topicRepo.cancelWorktreeStart(topicId)).resolves.toBe('cancelled');
+ await expect(topicRepo.cancelWorktreeStart(topicId)).resolves.toBe('unchanged');
+ expect(await TopicModel.getDueScheduledTopics(db, retryAt, topicId)).toHaveLength(0);
+ await expect(TopicModel.claimScheduledTopic(db, topicId, claim, retryAt)).resolves.toBe(false);
+ await expect(topicModel.findById(topicId)).resolves.toMatchObject({
+ metadata: { scheduledRun: null },
+ status: 'active',
+ });
+ await expect(messageModel.findById(userMessageId)).resolves.toMatchObject({
+ content: input.prompt,
+ role: 'user',
+ });
+ await expect(operationModel.findById(operationId)).resolves.toMatchObject({
+ status: 'interrupted',
+ });
+ });
+
+ it.each(['archived', 'trashed'] as const)(
+ 'records a late checkout for cleanup after the topic is %s',
+ async (trigger) => {
+ const input = request();
+ await submitWorktreeTurn(deps, input);
+ const now = new Date();
+ const claim = {
+ claimedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + 5000).toISOString(),
+ id: 'checkout-worker',
+ };
+ await expect(TopicModel.claimScheduledTopic(db, input.topicId, claim, now)).resolves.toBe(
+ true,
+ );
+ await db
+ .update(topics)
+ .set(trigger === 'trashed' ? { isDeleted: true } : { status: 'completed' })
+ .where(eq(topics.id, input.topicId));
+ const path = '/checkout/late';
+ await expect(
+ topicModel.recordFirstSendWorktreeCheckout(input.topicId, {
+ claimId: claim.id,
+ deviceId: input.worktree.deviceId,
+ workingDirectoryConfig: {
+ git: {
+ activeWorktree: path,
+ autoCreated: true,
+ branch: 'lobehub/late',
+ ownerNonce: 'saved-nonce',
+ },
+ path: input.worktree.sourcePath,
+ repoType: 'git',
+ sessionPath: path,
+ },
+ }),
+ ).resolves.toEqual({ canDispatch: false, cleanupTrigger: trigger });
+ const [owned] = await topicModel.findOwnedWorktreeTopics([input.topicId]);
+ expect(owned.status).toBe(trigger === 'trashed' ? 'active' : 'completed');
+ expect(owned.metadata).toMatchObject({
+ ownedWorktrees: [
+ {
+ cleanup: { state: 'pending', trigger },
+ deviceId: input.worktree.deviceId,
+ ownerNonce: 'saved-nonce',
+ path,
+ },
+ ],
+ scheduledRun: null,
+ });
+ expect(owned.metadata?.workingDirectoryConfig).toBeUndefined();
+ await expect(
+ db.query.messages.findFirst({ where: eq(messages.id, input.userMessageId) }),
+ ).resolves.toMatchObject({ content: input.prompt, topicId: input.topicId });
+ },
+ );
+
+ it('shows a startup failure after the running marker has been rolled back', async () => {
+ const input = request();
+ await submitWorktreeTurn(deps, input);
+ const now = new Date();
+ const claim = {
+ claimedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + 5000).toISOString(),
+ id: 'startup-worker',
+ };
+ await expect(TopicModel.claimScheduledTopic(db, input.topicId, claim, now)).resolves.toBe(true);
+ await db.update(topics).set({ status: 'active' }).where(eq(topics.id, input.topicId));
+
+ await TopicModel.finishWorktreeStart(db, input.topicId, claim.id, {
+ error: 'Could not prepare the resume session',
+ success: false,
+ });
+ await expect(topicModel.findById(input.topicId)).resolves.toMatchObject({
+ metadata: { scheduledRun: { error: 'Could not prepare the resume session' } },
+ status: 'failed',
+ });
+ });
+
+ it('leases a pending turn to one background worker and keeps it due after the device reconnects', async () => {
+ const { topic } = await submitWorktreeTurn(deps, request());
+ const now = new Date();
+ const claim = {
+ claimedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + 5000).toISOString(),
+ id: 'first-worker',
+ };
+ await expect(TopicModel.claimScheduledTopic(db, topic.id, claim, now)).resolves.toBe(true);
+ await expect(
+ TopicModel.claimScheduledTopic(db, topic.id, { ...claim, id: 'other-worker' }, now),
+ ).resolves.toBe(false);
+ await TopicModel.finishWorktreeStart(db, topic.id, 'other-worker', { success: true });
+ expect((await topicModel.findById(topic.id))?.status).toBe('scheduled');
+
+ const retryAt = new Date(now.getTime() + 30_000);
+ await TopicModel.finishWorktreeStart(db, topic.id, claim.id, {
+ retryAt: retryAt.toISOString(),
+ success: false,
+ });
+ expect(await TopicModel.getDueScheduledTopics(db, now, topic.id)).toHaveLength(0);
+ expect(await TopicModel.getDueScheduledTopics(db, retryAt, topic.id)).toMatchObject([
+ { metadata: { scheduledRun: { waitingForDevice: true } }, status: 'scheduled' },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/createFirstSendWorktree.ts b/apps/server/src/services/aiAgent/pipeline/createFirstSendWorktree.ts
new file mode 100644
index 00000000000..6cdd4e5fa7a
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/createFirstSendWorktree.ts
@@ -0,0 +1,69 @@
+import { WORKTREE_BRANCH_PREFIX } from '@lobechat/const';
+import type { WorkingDirConfig } from '@lobechat/types';
+import { deriveWorktreePath } from '@lobechat/types';
+
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import type { WorktreeTurnJob } from './submitWorktreeTurn';
+
+/** Create the checkout selected by a persisted first send, on the selected device. */
+export const createFirstSendWorktree = async (
+ worktree: WorktreeTurnJob['worktree'] & { branch: string },
+ principal: { userId: string; workspaceId?: string },
+): Promise<WorkingDirConfig> => {
+ const { baseBranch, branch, deviceId, ownerNonce, ownerToken, path, repoType, sourcePath } =
+ worktree;
+ const scope = { ...principal, deviceId };
+ const info = await deviceGateway.queryDeviceSystemInfo(
+ scope.userId,
+ deviceId,
+ scope.workspaceId,
+ {
+ maxAgeMs: 10 * 60 * 1000,
+ },
+ );
+ const startPoint = baseBranch;
+ if (startPoint) {
+ // An older device may silently fork from HEAD. Check that it recognizes
+ // named refs before issuing the write, just like the interactive picker.
+ const comparison = await deviceGateway.gitAheadBehind({ ...scope, branch: startPoint, path });
+ if (!comparison) throw new Error('The device could not verify the selected base branch.');
+ if (comparison.branch !== startPoint)
+ throw new Error('Update the device client to create a worktree from a selected branch.');
+ }
+
+ const homeDir = info?.homePath;
+ const worktreePath = deriveWorktreePath(homeDir ? sourcePath : path, branch, {
+ homeDir,
+ stripBranchPrefix: WORKTREE_BRANCH_PREFIX,
+ });
+ const created = await deviceGateway.addGitWorktree({
+ ...scope,
+ branch,
+ ownerToken,
+ path,
+ startPoint,
+ worktreePath,
+ });
+ if (
+ !created.success ||
+ !created.worktreePath ||
+ (startPoint && created.startPoint !== startPoint)
+ )
+ throw new Error(created.error || 'The device did not create the requested worktree.');
+
+ return {
+ git: {
+ activeWorktree: created.worktreePath,
+ autoCreated: true,
+ autoCreatedAt: new Date().toISOString(),
+ branch,
+ isWorktree: true,
+ ownBranch: branch,
+ ...(ownerToken && created.ownerToken === ownerToken && { ownerNonce, ownerToken }),
+ },
+ path: sourcePath,
+ repoType,
+ sessionPath: created.worktreePath,
+ };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.test.ts b/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.test.ts
new file mode 100644
index 00000000000..c7673aa0d50
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.test.ts
@@ -0,0 +1,311 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { WorktreeStartRun } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { dispatchWorktreeTurn } from './dispatchWorktreeTurn';
+
+const mocks = vi.hoisted(() => ({
+ authorize: vi.fn(),
+ createCheckout: vi.fn(),
+ devices: vi.fn(),
+ execAgent: vi.fn(),
+ listBranches: vi.fn(),
+ message: vi.fn(),
+ mergeMetadata: vi.fn(),
+ operation: vi.fn(),
+ recordDispatchFailure: vi.fn(),
+ saveCheckout: vi.fn(),
+ scheduleCleanup: vi.fn(),
+ updateMessage: vi.fn(),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: class {
+ findById = mocks.operation;
+ mergeMetadata = mocks.mergeMetadata;
+ recordDispatchFailure = mocks.recordDispatchFailure;
+ },
+}));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: class {
+ findById = mocks.message;
+ update = mocks.updateMessage;
+ },
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: class {
+ recordFirstSendWorktreeCheckout = mocks.saveCheckout;
+ },
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ execAgent = mocks.execAgent;
+ },
+}));
+vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({
+ assertCanUseWorkspaceAgent: vi.fn(),
+}));
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: mocks.authorize,
+}));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: mocks.devices,
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { listGitBranches: mocks.listBranches },
+}));
+vi.mock('./createFirstSendWorktree', () => ({ createFirstSendWorktree: mocks.createCheckout }));
+vi.mock('@/server/services/worktreeCleanup', () => ({
+ scheduleWorktreeCleanup: mocks.scheduleCleanup,
+}));
+
+const now = '2026-11-17T18:00:00.000Z';
+const run: WorktreeStartRun = {
+ claim: { claimedAt: now, expiresAt: now, id: 'claim-1' },
+ createdAt: now,
+ kind: 'worktree_start',
+ operationId: 'op_1',
+ runAt: now,
+ updatedAt: now,
+ userMessageId: 'msg_1',
+};
+const topic = {
+ agentId: 'agt_1',
+ id: 'tpc_1',
+ metadata: { scheduledRun: run },
+ status: 'scheduled',
+ userId: 'usr_1',
+};
+const request = {
+ baseBranch: 'release',
+ branch: 'lobehub/new',
+ deviceId: 'dev_1',
+ path: '/repo',
+ repoType: 'git',
+ sourcePath: '/repo',
+};
+const { branch: _branch, ...unassignedWorktree } = request;
+const checkout = {
+ git: { activeWorktree: '/checkout/new', branch: 'lobehub/new', isWorktree: true },
+ path: '/repo',
+ repoType: 'git',
+ sessionPath: '/checkout/new',
+};
+const operation = {
+ agentId: topic.agentId,
+ id: run.operationId,
+ metadata: {
+ firstSendWorktree: {
+ assistantMessageId: 'msg_2',
+ userMessageId: run.userMessageId,
+ worktree: request,
+ },
+ },
+ status: 'idle',
+ topicId: topic.id,
+ userId: topic.userId,
+};
+const dispatch = () => dispatchWorktreeTurn(run, { db: {} as LobeChatDatabase, topic });
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.operation.mockResolvedValue(operation);
+ mocks.message.mockResolvedValue({
+ content: 'Use the selected branch',
+ id: run.userMessageId,
+ role: 'user',
+ topicId: topic.id,
+ userId: topic.userId,
+ });
+ mocks.devices.mockResolvedValue([{ deviceId: request.deviceId, online: true }]);
+ mocks.saveCheckout.mockResolvedValue({ canDispatch: true });
+ mocks.recordDispatchFailure.mockResolvedValue(true);
+ mocks.mergeMetadata.mockResolvedValue(true);
+ mocks.updateMessage.mockResolvedValue(undefined);
+ mocks.listBranches.mockResolvedValue([{ name: 'lobehub' }]);
+ mocks.createCheckout.mockResolvedValue(checkout);
+ mocks.execAgent.mockResolvedValue({ success: true });
+});
+
+describe('dispatchWorktreeTurn', () => {
+ it('saves a non-conflicting branch before checkout and reuses it on retry', async () => {
+ const job = { ...operation.metadata.firstSendWorktree, worktree: unassignedWorktree };
+ mocks.operation.mockResolvedValue({
+ ...operation,
+ metadata: { firstSendWorktree: job },
+ });
+ mocks.createCheckout.mockRejectedValueOnce(new Error('Device disconnected'));
+
+ await expect(dispatch()).resolves.toMatchObject({ retryable: true, success: false });
+ expect(mocks.listBranches).toHaveBeenCalledWith({
+ deviceId: request.deviceId,
+ path: request.path,
+ userId: topic.userId,
+ workspaceId: undefined,
+ });
+ expect(mocks.mergeMetadata).toHaveBeenCalledBefore(mocks.createCheckout);
+ const persisted = mocks.mergeMetadata.mock.calls[0][1];
+ const selected = persisted.firstSendWorktree.worktree;
+ expect(selected.branch).toMatch(/^lobehub-/);
+ expect(mocks.createCheckout).toHaveBeenCalledWith(selected, expect.any(Object));
+
+ mocks.operation.mockResolvedValue({ ...operation, metadata: persisted });
+ mocks.listBranches.mockResolvedValue([{ name: 'lobehub' }, { name: selected.branch }]);
+ await expect(dispatch()).resolves.toEqual({ success: true });
+ expect(mocks.listBranches).toHaveBeenCalledTimes(1);
+ expect(mocks.createCheckout).toHaveBeenLastCalledWith(selected, expect.any(Object));
+ });
+
+ it('does not mutate Git when it cannot read the refs or save the branch choice', async () => {
+ mocks.operation.mockResolvedValue({
+ ...operation,
+ metadata: {
+ firstSendWorktree: {
+ ...operation.metadata.firstSendWorktree,
+ worktree: unassignedWorktree,
+ },
+ },
+ });
+ mocks.listBranches.mockResolvedValueOnce(undefined);
+ await expect(dispatch()).resolves.toMatchObject({ retryable: true, success: false });
+ expect(mocks.mergeMetadata).not.toHaveBeenCalled();
+
+ mocks.mergeMetadata.mockResolvedValueOnce(false);
+ await expect(dispatch()).resolves.toMatchObject({ retryable: true, success: false });
+ expect(mocks.createCheckout).not.toHaveBeenCalled();
+ });
+
+ it('uses the saved message and binds the checkout before dispatching to the selected device', async () => {
+ await expect(dispatch()).resolves.toEqual({ success: true });
+ expect(mocks.createCheckout).toHaveBeenCalledWith(request, {
+ userId: topic.userId,
+ workspaceId: undefined,
+ });
+ expect(mocks.saveCheckout).toHaveBeenCalledBefore(mocks.execAgent);
+ expect(mocks.saveCheckout).toHaveBeenCalledWith(topic.id, {
+ claimId: run.claim!.id,
+ deviceId: request.deviceId,
+ workingDirectoryConfig: checkout,
+ });
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: { topicId: topic.id },
+ deviceId: request.deviceId,
+ parentMessageId: run.userMessageId,
+ persistedUserMessageId: run.userMessageId,
+ prompt: 'Use the selected branch',
+ requireDevice: true,
+ reservedOperationId: run.operationId,
+ suppressUserMessage: true,
+ }),
+ );
+ });
+
+ it('keeps an offline device’s turn pending without using another device', async () => {
+ mocks.devices.mockResolvedValue([{ deviceId: 'other-device', online: true }]);
+ await expect(dispatch()).resolves.toEqual({ retryAt: expect.any(String), success: false });
+ expect(mocks.createCheckout).not.toHaveBeenCalled();
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('uses the saved device scope independently of the conversation workspace', async () => {
+ const db = {} as LobeChatDatabase;
+ const workspaceId = 'ws_1';
+ await expect(dispatchWorktreeTurn(run, { db, topic, workspaceId })).resolves.toEqual({
+ success: true,
+ });
+ expect(mocks.devices).toHaveBeenCalledWith(db, topic.userId, undefined);
+ expect(mocks.createCheckout).toHaveBeenCalledWith(request, {
+ userId: topic.userId,
+ workspaceId: undefined,
+ });
+
+ mocks.operation.mockResolvedValue({
+ ...operation,
+ metadata: {
+ firstSendWorktree: {
+ ...operation.metadata.firstSendWorktree,
+ deviceWorkspaceId: workspaceId,
+ },
+ },
+ });
+ await expect(dispatchWorktreeTurn(run, { db, topic, workspaceId })).resolves.toEqual({
+ success: true,
+ });
+ expect(mocks.devices).toHaveBeenLastCalledWith(db, topic.userId, workspaceId);
+ expect(mocks.createCheckout).toHaveBeenLastCalledWith(request, {
+ userId: topic.userId,
+ workspaceId,
+ });
+ });
+
+ it('does not report success or dispatch again for a consumed reservation without a handoff', async () => {
+ mocks.operation.mockResolvedValue({ ...operation, status: 'running' });
+ await expect(dispatch()).resolves.toMatchObject({ success: false });
+ expect(mocks.createCheckout).not.toHaveBeenCalled();
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('uses the durable handoff receipt to acknowledge a redelivery', async () => {
+ await expect(dispatch()).resolves.toMatchObject({ success: true });
+ expect(mocks.mergeMetadata).toHaveBeenLastCalledWith(run.operationId, {
+ firstSendWorktreeHandedOff: true,
+ });
+ mocks.operation.mockResolvedValue({
+ ...operation,
+ metadata: { firstSendWorktreeHandedOff: true },
+ status: 'running',
+ });
+ await expect(dispatch()).resolves.toMatchObject({ success: true });
+ expect(mocks.execAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('settles a startup failure after consuming the reservation', async () => {
+ mocks.execAgent.mockImplementationOnce(async () => {
+ mocks.operation.mockResolvedValue({ ...operation, status: 'running' });
+ throw new Error('Could not prepare the resume session');
+ });
+
+ await expect(dispatch()).resolves.toMatchObject({
+ error: 'Could not prepare the resume session',
+ retryable: false,
+ success: false,
+ });
+ expect(mocks.recordDispatchFailure).toHaveBeenCalledWith(
+ run.operationId,
+ 'Could not prepare the resume session',
+ );
+ expect(mocks.updateMessage).toHaveBeenCalledWith(
+ 'msg_2',
+ expect.objectContaining({ error: expect.any(Object) }),
+ );
+ });
+
+ it.each(['archived', 'trashed'])(
+ 'queues cleanup for a checkout completed after retirement (%s)',
+ async (trigger) => {
+ mocks.saveCheckout.mockResolvedValue({ canDispatch: false, cleanupTrigger: trigger });
+ await expect(dispatch()).resolves.toMatchObject({ success: false });
+ expect(mocks.scheduleCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({ topicIds: [topic.id], trigger, userId: topic.userId }),
+ );
+ expect(mocks.mergeMetadata).toHaveBeenCalledWith(
+ run.operationId,
+ expect.objectContaining({ firstSendWorktree: expect.objectContaining({ checkout }) }),
+ );
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ },
+ );
+
+ it('returns the checkout error and leaves the saved message available', async () => {
+ const error = new Error('Base branch no longer exists');
+ mocks.createCheckout.mockRejectedValue(error);
+ await expect(dispatch()).resolves.toEqual({
+ error: error.message,
+ retryable: true,
+ success: false,
+ });
+ expect(mocks.saveCheckout).not.toHaveBeenCalled();
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.ts b/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.ts
new file mode 100644
index 00000000000..9be9818026a
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/dispatchWorktreeTurn.ts
@@ -0,0 +1,192 @@
+import { generateWorktreeBranchName } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ExecAgentResult, WorktreeStartRun } from '@lobechat/types';
+import { RequestTrigger, toComposerUserMessage } from '@lobechat/types';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
+import { scheduleWorktreeCleanup } from '@/server/services/worktreeCleanup';
+
+import { createFirstSendWorktree } from './createFirstSendWorktree';
+import type { WorktreeTurnJob } from './submitWorktreeTurn';
+
+/** Execute the saved first turn against its checkout, even when no client is connected. */
+export const dispatchWorktreeTurn = async (
+ run: WorktreeStartRun,
+ {
+ db,
+ topic,
+ workspaceId,
+ }: {
+ db: LobeChatDatabase;
+ topic: { agentId: string | null; id: string; userId: string };
+ workspaceId?: string;
+ },
+): Promise<{ error?: string; retryAt?: string; retryable?: boolean; success: boolean }> => {
+ const { agentId, userId } = topic;
+ const topics = new TopicModel(db, userId, workspaceId);
+ const messages = new MessageModel(db, userId, workspaceId);
+ const operations = new AgentOperationModel(db, userId, workspaceId);
+ const [operation, message] = await Promise.all([
+ operations.findById(run.operationId),
+ messages.findById(run.userMessageId),
+ ]);
+ if (
+ !agentId ||
+ operation?.topicId !== topic.id ||
+ operation.userId !== userId ||
+ operation.agentId !== agentId ||
+ message?.topicId !== topic.id ||
+ message.role !== 'user' ||
+ message.userId !== userId
+ ) {
+ return { error: 'The queued conversation or message no longer exists.', success: false };
+ }
+ // The reserved id is consumed by execAgent. A redelivered job must never
+ // start a second turn after another worker has consumed that reservation.
+ if (operation.status !== 'idle') {
+ const succeeded =
+ operation.status === 'done' || operation.metadata?.firstSendWorktreeHandedOff === true;
+ return {
+ error: succeeded
+ ? undefined
+ : (operation.error?.message ?? 'The queued turn could not be confirmed as dispatched.'),
+ success: succeeded,
+ };
+ }
+ let job = operation.metadata?.firstSendWorktree as WorktreeTurnJob | undefined;
+ if (!job || job.userMessageId !== message.id)
+ return { error: 'The worktree request no longer exists.', success: false };
+
+ const { deviceId } = job.worktree;
+ const deviceWorkspaceId = job.deviceWorkspaceId;
+ try {
+ await assertCanUseWorkspaceAgent({ agentId, db, userId, workspaceId });
+ } catch (error) {
+ console.error('[dispatchWorktreeTurn] execution permission changed', error);
+ return { error: 'You can no longer use this agent.', success: false };
+ }
+ if (await resolveDeviceDispatchAuthorizationFailure(db, userId, deviceId, deviceWorkspaceId))
+ return {
+ error: 'The selected device is no longer available in this workspace.',
+ success: false,
+ };
+ const devices = await getScopedOnlineDevices(db, userId, deviceWorkspaceId);
+ if (!devices.some((device) => device.deviceId === deviceId && device.online))
+ return { retryAt: new Date(Date.now() + 30_000).toISOString(), success: false };
+
+ let workingDirectory = job.checkout;
+ try {
+ if (!workingDirectory) {
+ const principal = { userId, workspaceId: deviceWorkspaceId };
+ let branch = job.worktree.branch;
+ if (!branch) {
+ const refs = await deviceGateway.listGitBranches({
+ ...principal,
+ deviceId,
+ path: job.worktree.path,
+ });
+ if (!refs) throw new Error('The device could not list the repository’s branches.');
+ branch = generateWorktreeBranchName({
+ exclude: refs.map(({ name }) => name),
+ now: new Date(run.createdAt),
+ });
+ job = { ...job, worktree: { ...job.worktree, branch } };
+ // Retrying a write with an ambiguous result must target the same checkout.
+ const saved = await operations.mergeMetadata(operation.id, { firstSendWorktree: job });
+ if (!saved) throw new Error('Could not save the branch for the queued worktree.');
+ }
+ workingDirectory = await createFirstSendWorktree({ ...job.worktree, branch }, principal);
+ }
+ } catch (error) {
+ console.error('[dispatchWorktreeTurn] could not create worktree', error);
+ return {
+ error: error instanceof Error ? error.message : String(error),
+ retryable: true,
+ success: false,
+ };
+ }
+
+ const { canDispatch, cleanupTrigger } = await topics.recordFirstSendWorktreeCheckout(topic.id, {
+ claimId: run.claim?.id,
+ deviceId,
+ workingDirectoryConfig: workingDirectory,
+ });
+ if (cleanupTrigger) {
+ scheduleWorktreeCleanup({
+ db,
+ topicIds: [topic.id],
+ trigger: cleanupTrigger,
+ userId,
+ workspaceId,
+ });
+ }
+ if (!job.checkout)
+ await operations.mergeMetadata(operation.id, {
+ firstSendWorktree: { ...job, checkout: workingDirectory },
+ });
+
+ if (!canDispatch)
+ return { error: 'The queued worktree turn lost its dispatch claim.', success: false };
+
+ let result: ExecAgentResult;
+ try {
+ result = await new AiAgentService(db, userId, {
+ withholdGatewayToken: true,
+ workspaceId,
+ }).execAgent({
+ agentId,
+ appContext: { topicId: topic.id },
+ deviceId,
+ fileIds: job.fileIds,
+ mentionedAgents: job.mentionedAgents,
+ markTopicRunning: true,
+ parentMessageId: message.id,
+ persistedUserMessageId: message.id,
+ prompt: message.content ?? '',
+ requireDevice: true,
+ reservedAssistantMessageId: job.assistantMessageId,
+ reservedOperationId: operation.id,
+ selectedSkillIds: job.selectedSkillIds,
+ selectedToolIds: job.selectedToolIds,
+ suppressUserMessage: true,
+ trigger: RequestTrigger.Chat,
+ userInterventionConfig: job.userInterventionConfig,
+ userMessage: toComposerUserMessage({
+ editorData: message.editorData,
+ metadata: message.metadata,
+ }),
+ });
+ } catch (error) {
+ const current = await operations.findById(operation.id);
+ if (current?.status === 'done') return { success: true };
+ const reason = error instanceof Error ? error.message : String(error);
+ if (current?.status === 'running') {
+ if (!(await operations.recordDispatchFailure(operation.id, reason))) throw error;
+ await messages
+ .update(job.assistantMessageId, {
+ error: { message: reason, type: 'AgentRuntimeError' },
+ })
+ .catch((updateError) => {
+ console.error(
+ '[dispatchWorktreeTurn] could not update the failed assistant message',
+ updateError,
+ );
+ });
+ }
+ return {
+ error: reason,
+ retryable: current?.status === 'idle',
+ success: false,
+ };
+ }
+ if (result.success)
+ await operations.mergeMetadata(operation.id, { firstSendWorktreeHandedOff: true });
+ return result;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 8821b292901..1cf92b29551 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -441,7 +441,7 @@ export const execAgentTurn = async (
botContext,
botSender,
clientIds,
- continuationAssistantId,
+ continuationAssistantId: continuationAssistantId ?? params.reservedAssistantMessageId,
conversationAgentId,
createdThreadId,
externalOrigin,
@@ -451,10 +451,17 @@ export const execAgentTurn = async (
modelOverride,
operationTaskId,
parentMessageId,
+ persistedUserMessageId:
+ suppressUserMessage &&
+ !effectiveResume &&
+ params.persistedUserMessageId === parentMessageId
+ ? params.persistedUserMessageId
+ : undefined,
prompt,
providerOverride,
requestedDeviceId,
requireDevice,
+ reservedOperationId: params.reservedOperationId,
resolvedAgentId,
resume,
runFromHistory,
@@ -528,7 +535,10 @@ export const execAgentTurn = async (
userMessageId: turn.userMessageId,
// Exactly what the user row was persisted with, so every stage reads the
// message the way a later turn reads it back from history.
- userMessageMetadata: turn.userMessageId ? turn.requestTriggerMetadata : undefined,
+ userMessageMetadata:
+ turn.userMessageId || params.reservedAssistantMessageId
+ ? turn.requestTriggerMetadata
+ : undefined,
};
// Every caller that is not the plain composer (bots, group members,
@@ -593,7 +603,10 @@ export const execAgentTurn = async (
requestTrigger: requestTriggerMetadata.trigger,
requestedDeviceId: turn.requestedDeviceId,
runAttachments,
- selfMessageIds,
+ selfMessageIds:
+ params.reservedAssistantMessageId && parentMessageId
+ ? new Set([...selfMessageIds, parentMessageId])
+ : selfMessageIds,
topicStartOwnerOperationId: params.topicStartOwnerOperationId,
},
),
diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts b/apps/server/src/services/aiAgent/pipeline/scheduledRunKinds.ts
similarity index 97%
rename from apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts
rename to apps/server/src/services/aiAgent/pipeline/scheduledRunKinds.ts
index 1827fa8e4a7..5086ac64557 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts
+++ b/apps/server/src/services/aiAgent/pipeline/scheduledRunKinds.ts
@@ -5,19 +5,18 @@ import { RequestTrigger } from '@lobechat/types';
import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
-import type { TopicItem } from '@/database/schemas/topic';
import { AiAgentService } from '@/server/services/aiAgent';
export interface ScheduledRunContext {
/** The dispatcher's claim lease id — fences post-dispatch writes against stale attempts. */
claimId: string;
db: LobeChatDatabase;
- topic: TopicItem;
+ topic: { agentId: string | null; id: string; userId: string };
workspaceId?: string;
}
type ScheduledRunHandlers = {
- [K in TopicScheduledRunKind]: (
+ [K in Exclude<TopicScheduledRunKind, 'worktree_start'>]: (
run: Extract<TopicScheduledRun, { kind: K }>,
ctx: ScheduledRunContext,
) => Promise<ExecAgentResult>;
@@ -153,7 +152,7 @@ const HANDLERS: ScheduledRunHandlers = {
* {@link TopicScheduledRun} and an entry here; the type forces the pairing.
*/
export const dispatchScheduledRun = (
- run: TopicScheduledRun,
+ run: Exclude<TopicScheduledRun, { kind: 'worktree_start' }>,
ctx: ScheduledRunContext,
): Promise<ExecAgentResult> => {
const handler = HANDLERS[run.kind] as (
diff --git a/apps/server/src/services/aiAgent/pipeline/scheduledTopicDispatch.ts b/apps/server/src/services/aiAgent/pipeline/scheduledTopicDispatch.ts
new file mode 100644
index 00000000000..eb7f73ef909
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/scheduledTopicDispatch.ts
@@ -0,0 +1,158 @@
+import { randomUUID } from 'node:crypto';
+
+import { parseTopicScheduledRun } from '@lobechat/types';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+import { getServerDB } from '@/database/server';
+import { appEnv } from '@/envs/app';
+import { QueueService } from '@/server/services/queue';
+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+
+import { dispatchWorktreeTurn } from './dispatchWorktreeTurn';
+import { dispatchScheduledRun } from './scheduledRunKinds';
+
+const log = debug('lobe-server:workflows:task:scheduled-topic-dispatch');
+
+/** How long a claim lease is held before another tick may re-claim the topic. */
+const CLAIM_LEASE_MS = 5 * 60 * 1000;
+
+export interface ScheduledTopicDispatchPayload {
+ /** When true, only report which topics are due without claiming/dispatching. */
+ dryRun?: boolean;
+ /** An immediate wakeup can target one topic; a scheduled sweep targets all. */
+ topicId?: string;
+}
+
+/**
+ * Cron-style dispatcher for deferred runs on pure (non-Task) topics. Registered
+ * as a QStash Schedule (e.g. `*\/10 * * * *`) pointing at this endpoint. On each
+ * tick:
+ *
+ * 1. Loads topics with `status = 'scheduled'` whose `scheduledRun.runAt` has
+ * passed and that aren't under a live claim.
+ * 2. Atomically claims each (a lease on `metadata.scheduledRun.claim`) so two
+ * ticks / replicas never dispatch the same run twice.
+ * 3. Hands the run to its kind handler, which re-enters
+ * `AiAgentService.execAgent` — the same execution engine as a normal agent
+ * run, which already routes remote runs to the topic's bound device via the
+ * device gateway.
+ *
+ * Everything here is kind-agnostic: scanning, the lease and clearing state are
+ * shared, and a {@link dispatchScheduledRun} handler decides only *what* to run.
+ *
+ * This intentionally does NOT enter TaskLifecycle — a pure topic just runs its
+ * agent. On success the scheduled state is cleared; on failure (e.g. the device
+ * is offline) the topic stays `scheduled` and the claim lease expires so the next
+ * tick retries — the scheduled state is never lost.
+ */
+export async function dispatchDueScheduledTopics({
+ dryRun = false,
+ topicId,
+}: ScheduledTopicDispatchPayload = {}) {
+ const db = await getServerDB();
+ const now = new Date();
+ const due = topicId
+ ? await TopicModel.getDueScheduledTopics(db, now, topicId)
+ : await TopicModel.getDueScheduledTopics(db, now);
+
+ log('scan: due=%d dryRun=%s', due.length, dryRun);
+
+ if (dryRun || due.length === 0) {
+ return { claimed: 0, dispatched: 0, dryRun, due: due.length, success: true };
+ }
+
+ let claimed = 0;
+ let dispatched = 0;
+ let discarded = 0;
+ for (const topic of due) {
+ // Reads the current payload and the pre-`kind` legacy one alike — the due
+ // query selects both, so this must dispatch both.
+ const run = parseTopicScheduledRun(topic.metadata?.scheduledRun);
+ if (!run) {
+ // A due topic whose payload we can't dispatch would re-surface on every
+ // tick forever, so drop the schedule instead of skipping it. Back to
+ // `active`: the topic itself is intact, only the schedule is unusable.
+ console.error(
+ '[scheduled-topic-dispatch] discarding unparseable scheduledRun topic=%s: %O',
+ topic.id,
+ topic.metadata?.scheduledRun,
+ );
+ await TopicModel.clearScheduledRun(db, topic.id, 'active').catch(() => undefined);
+ discarded += 1;
+ continue;
+ }
+
+ const claim = {
+ claimedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + CLAIM_LEASE_MS).toISOString(),
+ id: randomUUID(),
+ };
+
+ const won = await TopicModel.claimScheduledTopic(db, topic.id, claim, now).catch((err) => {
+ console.error('[scheduled-topic-dispatch] claim failed topic=%s: %O', topic.id, err);
+ return false;
+ });
+ if (!won) continue;
+ claimed += 1;
+
+ const workspaceId = topic.workspaceId ?? undefined;
+ try {
+ if (run.kind === 'worktree_start') {
+ const result = await dispatchWorktreeTurn({ ...run, claim }, { db, topic, workspaceId });
+ await TopicModel.finishWorktreeStart(db, topic.id, claim.id, result);
+ if (result.success) dispatched += 1;
+ if (result.retryAt) await wakeWorktreeTurn(topic.id, result.retryAt);
+ continue;
+ }
+ const result = await dispatchScheduledRun(run, {
+ claimId: claim.id,
+ db,
+ topic,
+ workspaceId,
+ });
+ if (!result.success) {
+ throw new Error(result.error || result.message || 'Scheduled run dispatch failed');
+ }
+
+ // Success — execAgent now owns the run; clear the scheduled state.
+ await TopicModel.clearScheduledRun(db, topic.id, 'running', claim.id);
+ dispatched += 1;
+ log(
+ 'dispatched topic=%s kind=%s device=%s',
+ topic.id,
+ run.kind,
+ topic.metadata?.boundDeviceId,
+ );
+ } catch (err) {
+ // Leave the topic `scheduled` (e.g. device offline). The claim lease
+ // expires and the next tick retries — scheduled state is never lost.
+ console.error('[scheduled-topic-dispatch] dispatch failed topic=%s: %O', topic.id, err);
+ }
+ }
+
+ return { claimed, discarded, dispatched, due: due.length, success: true };
+}
+
+/** Fast path. The scheduled-topic scan can also recover a committed send after an enqueue failure. */
+export const wakeWorktreeTurn = async (topicId: string, runAt?: string): Promise<void> => {
+ const queue = new QueueService();
+ const impl = queue.getImpl();
+ if (impl instanceof LocalQueueServiceImpl) {
+ impl.setExecutionCallback(async () => {
+ await dispatchDueScheduledTopics({ topicId });
+ });
+ }
+ await queue.scheduleMessage({
+ deduplicationId: `first-send-worktree:${topicId}:${runAt ?? 'now'}`,
+ delay: runAt ? Math.max(1000, new Date(runAt).getTime() - Date.now() + 1000) : undefined,
+ endpoint: new URL(
+ '/api/workflows/task/scheduled-topic-dispatch',
+ appEnv.INTERNAL_APP_URL || appEnv.APP_URL,
+ ).toString(),
+ operationId: topicId,
+ payload: { topicId },
+ retries: 3,
+ stepIndex: 0,
+ });
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/submitWorktreeTurn.ts b/apps/server/src/services/aiAgent/pipeline/submitWorktreeTurn.ts
new file mode 100644
index 00000000000..a40ca215a22
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/submitWorktreeTurn.ts
@@ -0,0 +1,189 @@
+import type {
+ ComposerUserMessage,
+ FirstSendWorktree,
+ WorkingDirConfig,
+ WorktreeStartRun,
+} from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { sql } from 'drizzle-orm';
+
+import { DeviceModel } from '@/database/models/device';
+import { MessageModel } from '@/database/models/message';
+import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
+import { TopicModel } from '@/database/models/topic';
+import { agentOperations } from '@/database/schemas/agentOperations';
+import { issueWorktreeReceipt } from '@/server/services/worktreeCleanup/receipt';
+import { toTitleText } from '@/utils/markdownToTxt';
+
+import type { InternalExecAgentParams } from '../types';
+import { type PrecreatedTopicDeps, resolvePrecreatedTopicSnapshot } from './precreatedTopic';
+import { resolveTurnProjectId } from './topicProject';
+
+export interface SubmitWorktreeTurnInput {
+ agentId: string;
+ assistantMessageId: string;
+ fileIds?: string[];
+ mentionedAgents?: InternalExecAgentParams['mentionedAgents'];
+ projectId?: string;
+ projectWorkingDirectoryId?: string;
+ prompt: string;
+ selectedSkillIds?: string[];
+ selectedToolIds?: string[];
+ topicId: string;
+ userInterventionConfig?: InternalExecAgentParams['userInterventionConfig'];
+ userMessage?: ComposerUserMessage;
+ userMessageId: string;
+ worktree: FirstSendWorktree;
+}
+
+export type WorktreeTurnJob = Pick<
+ SubmitWorktreeTurnInput,
+ | 'assistantMessageId'
+ | 'fileIds'
+ | 'mentionedAgents'
+ | 'selectedSkillIds'
+ | 'selectedToolIds'
+ | 'userInterventionConfig'
+> & {
+ checkout?: WorkingDirConfig;
+ deviceWorkspaceId?: string;
+ userMessageId: string;
+ worktree: FirstSendWorktree & { branch?: string; ownerNonce?: string; ownerToken?: string };
+};
+
+/** Persist the conversation, first message and dispatch reservation together. */
+export const submitWorktreeTurn = async (
+ deps: PrecreatedTopicDeps,
+ input: SubmitWorktreeTurnInput,
+) => {
+ const { db, userId, workspaceId } = deps;
+ const { agentId, fileIds, prompt, topicId, userMessage, userMessageId, worktree } = input;
+ let deviceWorkspaceId: string | undefined;
+ if (workspaceId) {
+ const devices = new DeviceModel(db, userId, workspaceId);
+ if (await devices.findWorkspaceDeviceById(worktree.deviceId)) deviceWorkspaceId = workspaceId;
+ else if (!(await devices.findPersonalByDeviceId(worktree.deviceId)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found.' });
+ }
+ const { agentConfig, snapshot } = await resolvePrecreatedTopicSnapshot(deps, agentId);
+ const config = agentConfig.agencyConfig;
+ if (config?.heterogeneousProvider?.authMode === 'api') {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'This agent uses a provider binding that requires local Desktop execution.',
+ });
+ }
+ const directory = input.projectWorkingDirectoryId
+ ? await new ProjectWorkingDirectoryModel(db, userId, workspaceId).resolve(
+ input.projectWorkingDirectoryId,
+ )
+ : undefined;
+ if (directory && directory.deviceId !== worktree.deviceId)
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'The worktree must use the project directory’s device.',
+ });
+ const projectId = await resolveTurnProjectId(deps, {
+ directoryProjectId: directory?.projectId,
+ requestedProjectId: input.projectId,
+ });
+ if (
+ config?.executionTargetSelectionPolicy === 'fixed' &&
+ (config.executionTarget !== 'device' || config.boundDeviceId !== worktree.deviceId)
+ ) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'The agent is fixed to another execution target.',
+ });
+ }
+
+ const now = new Date();
+ const at = now.toISOString();
+ const operationId = `op_worktree_${topicId}`;
+ const scheduledRun: WorktreeStartRun = {
+ createdAt: at,
+ kind: 'worktree_start',
+ operationId,
+ runAt: at,
+ updatedAt: at,
+ userMessageId,
+ };
+ const receipt = issueWorktreeReceipt(userId);
+ const job: WorktreeTurnJob = {
+ assistantMessageId: input.assistantMessageId,
+ deviceWorkspaceId,
+ fileIds,
+ mentionedAgents: input.mentionedAgents,
+ selectedSkillIds: input.selectedSkillIds,
+ selectedToolIds: input.selectedToolIds,
+ userInterventionConfig: input.userInterventionConfig,
+ userMessageId,
+ worktree: {
+ ...worktree,
+ ownerNonce: receipt?.nonce,
+ ownerToken: receipt?.token,
+ },
+ };
+ const title = toTitleText(prompt).slice(0, 50);
+
+ return db.transaction(async (tx) => {
+ // The client keeps these ids when retrying an ambiguous HTTP response.
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${operationId}))`);
+ const topics = new TopicModel(tx, userId, workspaceId);
+ const messages = new MessageModel(tx, userId, workspaceId);
+ const existing = await topics.findOwnTopicById(topicId);
+ if (existing) {
+ const persisted = await messages.findById(userMessageId);
+ if (
+ persisted?.topicId !== topicId ||
+ existing.agentId !== agentId ||
+ existing.userId !== userId
+ )
+ throw new TRPCError({ code: 'CONFLICT', message: 'This conversation already exists.' });
+ return { topic: existing, userMessageId };
+ }
+
+ const topic = await topics.create(
+ {
+ ...snapshot,
+ agentId,
+ metadata: {
+ ...snapshot.metadata,
+ boundDeviceId: worktree.deviceId,
+ deviceBindingPinned: true,
+ scheduledRun,
+ },
+ projectId,
+ projectWorkingDirectoryId: directory?.id,
+ status: 'scheduled',
+ title,
+ trigger: RequestTrigger.Chat,
+ },
+ topicId,
+ );
+ await messages.create(
+ {
+ agentId,
+ content: prompt,
+ editorData: userMessage?.editorData,
+ files: fileIds,
+ metadata: { ...userMessage?.metadata, trigger: RequestTrigger.Chat },
+ role: 'user',
+ topicId,
+ },
+ userMessageId,
+ );
+ await tx.insert(agentOperations).values({
+ agentId,
+ id: operationId,
+ metadata: { firstSendWorktree: job },
+ status: 'idle',
+ topicId,
+ trigger: RequestTrigger.Chat,
+ userId,
+ workspaceId,
+ });
+ return { topic, userMessageId };
+ });
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 591e882809c..4a96445fcec 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -359,11 +359,13 @@ export interface TurnSetupInput {
modelOverride?: string;
operationTaskId?: string;
parentMessageId?: string;
+ persistedUserMessageId?: string;
prompt: string;
providerOverride?: string;
requestedDeviceId?: string;
/** See `InternalExecAgentParams.requireDevice`. */
requireDevice?: boolean;
+ reservedOperationId?: string;
resolvedAgentId: string;
/** Raw resume flag — a resume run must land on an existing topic. */
resume?: boolean;
@@ -471,10 +473,12 @@ export const setupTurn = async (
modelOverride,
operationTaskId,
parentMessageId,
+ persistedUserMessageId,
prompt,
providerOverride,
requestedDeviceId,
requireDevice,
+ reservedOperationId,
resolvedAgentId,
resume,
runFromHistory,
@@ -716,6 +720,17 @@ export const setupTurn = async (
// The pinned model lives in the top-level `topics.model`/`provider` columns
// (config source of truth), NOT in metadata.
const existingTopic = await deps.topicModel.findById(topicId);
+ const pendingRun = existingTopic?.metadata?.scheduledRun;
+ if (
+ existingTopic?.status === 'scheduled' &&
+ pendingRun?.kind === 'worktree_start' &&
+ pendingRun.operationId !== reservedOperationId
+ ) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'This conversation is preparing its worktree.',
+ });
+ }
topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
turnProjectId = await resolveTurnProjectId(deps, {
shareGate,
@@ -1146,6 +1161,6 @@ export const setupTurn = async (
topicBoundDeviceId,
topicEditingGroupId,
topicId,
- userMessageId: userMessageRecord?.id,
+ userMessageId: userMessageRecord?.id ?? persistedUserMessageId,
};
};
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 218142ffb1e..c57e305af8a 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -247,6 +247,8 @@ export interface InternalExecAgentParams extends ExecAgentParams {
onOperationCreated?: (operationId: string) => Promise<void>;
/** Parent message ID to continue from. Only takes effect when resume is true */
parentMessageId?: string;
+ /** User turn already saved and verified by a trusted server dispatcher. */
+ persistedUserMessageId?: string;
/**
* A server-started turn that takes over where a finished run left off (the
* server-side drain of queued follow-ups). Non-interactive thread starts
@@ -263,6 +265,8 @@ export interface InternalExecAgentParams extends ExecAgentParams {
* device is a preference the target policy may override.
*/
requireDevice?: boolean;
+ /** Stable assistant row for a worker dispatching a pre-persisted worktree turn. */
+ reservedAssistantMessageId?: string;
/** An idle operation reserved by the dispatcher for this exact Agent, topic and requester. */
reservedOperationId?: string;
/** Whether to continue execution from an existing persisted message */
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index 663d3dac73b..18a73125ba6 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -18,6 +18,7 @@
"workingDirectory.browseDescription": "Choose a folder on the connected device.",
"workingDirectory.browseFolders": "Browse folders",
"workingDirectory.cancel": "Cancel",
+ "workingDirectory.cancelWorktreeSend": "Cancel send",
"workingDirectory.checkoutAction": "Checkout",
"workingDirectory.checkoutFailed": "Checkout failed",
"workingDirectory.chooseDifferentFolder": "Choose a folder...",
@@ -177,14 +178,19 @@
"workingDirectory.unselected": "Not selected",
"workingDirectory.useFolder": "Use this folder",
"workingDirectory.useFolderFailed": "Couldn’t use this folder.",
+ "workingDirectory.worktreeCancelFailed": "Could not cancel the send",
+ "workingDirectory.worktreeCancelTooLate": "This send can no longer be cancelled",
"workingDirectory.worktreeCreateFailed": "Could not create the worktree",
+ "workingDirectory.worktreeDeviceRequired": "Connect this device before sending with a new worktree.",
"workingDirectory.worktreeSearchPlaceholder": "Search worktrees",
+ "workingDirectory.worktreeSendCancelled": "Send cancelled",
"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.worktreeWaitingForDevice": "Waiting for the device to connect…",
"workingDirectory.worktreesEmpty": "No worktrees found",
"workingDirectory.worktreesHeading": "Worktrees",
"workingDirectory.worktreesNoMatch": "No matching worktrees"
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 51d0606105e..8a2e275348c 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -18,6 +18,7 @@
"workingDirectory.browseDescription": "选择已连接设备上的文件夹。",
"workingDirectory.browseFolders": "浏览文件夹",
"workingDirectory.cancel": "取消",
+ "workingDirectory.cancelWorktreeSend": "取消发送",
"workingDirectory.checkoutAction": "切换分支",
"workingDirectory.checkoutFailed": "切换分支失败",
"workingDirectory.chooseDifferentFolder": "选择其他文件夹",
@@ -177,14 +178,19 @@
"workingDirectory.unselected": "未选择",
"workingDirectory.useFolder": "选择此文件夹",
"workingDirectory.useFolderFailed": "无法使用此文件夹。",
+ "workingDirectory.worktreeCancelFailed": "无法取消发送",
+ "workingDirectory.worktreeCancelTooLate": "这条消息已无法取消发送",
"workingDirectory.worktreeCreateFailed": "无法创建工作树",
+ "workingDirectory.worktreeDeviceRequired": "请先连接此设备,再使用新工作树发送消息。",
"workingDirectory.worktreeSearchPlaceholder": "搜索 worktree",
+ "workingDirectory.worktreeSendCancelled": "已取消发送",
"workingDirectory.worktreeToggle": "新建工作树",
"workingDirectory.worktreeToggleOffHint": "开启后,这个话题会在新的分支和工作树中进行",
"workingDirectory.worktreeToggleOn": "新建工作树:已开启",
"workingDirectory.worktreeToggleOnHint": "发送时基于 {{branch}} 新建分支和工作树,当前目录保持不变",
"workingDirectory.worktreeToggleSaveFailed": "无法保存「新建工作树」设置",
"workingDirectory.worktreeUnavailable": "不可用",
+ "workingDirectory.worktreeWaitingForDevice": "正在等待设备连接…",
"workingDirectory.worktreesEmpty": "未发现 worktree",
"workingDirectory.worktreesHeading": "Worktree",
"workingDirectory.worktreesNoMatch": "无匹配的 worktree"
diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.ts
index 7d51941a3d7..e047f744d83 100644
--- a/packages/const/src/apiKeyScope.test.ts
+++ b/packages/const/src/apiKeyScope.test.ts
@@ -150,6 +150,17 @@ describe('requiredApiKeyScopeForTrpc', () => {
});
});
+ it('enforces chat and model permissions on worktree turns that start a run', () => {
+ for (const path of ['aiAgent.submitWorktreeTurn', 'aiAgent.retryWorktreeTurn']) {
+ expect(requiredApiKeyScopeForTrpc(path, 'mutation')).toEqual({
+ scopes: ['agent:write', 'chat:write', 'model:invoke'],
+ });
+ }
+ expect(requiredApiKeyScopeForTrpc('aiAgent.cancelWorktreeTurn', 'mutation')).toEqual({
+ scopes: ['agent:write', 'chat:write'],
+ });
+ });
+
it('separates installing an account credential from managing the account', () => {
// Reading and managing an agent's identity assets rides the agent domain…
expect(requiredApiKeyScopeForTrpc('agentAccount.list', 'query')).toEqual({
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 2e77ed5edc4..961fe4ca6c2 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -401,6 +401,8 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {
'aiAgent.finishLocalHeteroRunFee': AGENT_RUN_SCOPES,
'aiAgent.scheduleAgentRun': AGENT_RUN_SCOPES,
'aiAgent.startExecution': AGENT_RUN_SCOPES,
+ 'aiAgent.submitWorktreeTurn': AGENT_RUN_SCOPES,
+ 'aiAgent.retryWorktreeTurn': AGENT_RUN_SCOPES,
// a queued follow-up is a deferred composer send: the run that drains it
// starts a model turn and writes the user message
'agentSteerQueue.append': AGENT_RUN_SCOPES,
@@ -408,6 +410,7 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {
// returns the queued prompts and attachments, i.e. conversation content
'agentSteerQueue.list': ['chat:read'],
// thread/message state writes without starting a run
+ 'aiAgent.cancelWorktreeTurn': ['chat:write'],
'aiAgent.createClientGroupAgentTaskThread': ['chat:write'],
'aiAgent.createClientTaskThread': ['chat:write'],
'aiAgent.interruptTask': ['chat:write'],
diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
index a0cf8b4fdf4..fdcf2afee24 100644
--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
@@ -88,11 +88,13 @@ const PUBLIC_METHODS = [
'queryTopics',
'rank',
'recomputeUsage',
+ 'recordFirstSendWorktreeCheckout',
'releaseTaskCallbackReservation',
'removeRunningOperationChild',
'repairAgentInterventionContinuation',
'resetMemoryExtractStatus',
'restore',
+ 'retryWorktreeStart',
'settleRunningOperation',
'settleRunningStatus',
'softDelete',
diff --git a/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts b/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts
index acf2031fb2f..b53cc5c60f0 100644
--- a/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts
@@ -357,6 +357,39 @@ describe('TopicModel scheduled-run guards', () => {
expect(await readMetadata(otherTopicId)).toEqual({});
});
+ it('only re-arms a failed worktree turn for its owner and keeps the same reservation', async () => {
+ const at = '2026-10-01T00:00:00.000Z';
+ const run = {
+ createdAt: at,
+ error: 'Checkout failed',
+ kind: 'worktree_start',
+ operationId,
+ retryable: true,
+ runAt: at,
+ updatedAt: at,
+ userMessageId: 'msg_saved',
+ } as const;
+ await serverDB.insert(topics).values([
+ { id: topicId, metadata: { scheduledRun: run }, status: 'failed', userId },
+ {
+ id: otherTopicId,
+ metadata: { scheduledRun: run },
+ status: 'failed',
+ userId: otherUserId,
+ },
+ ]);
+
+ expect(await topicModel.retryWorktreeStart(otherTopicId)).toBeUndefined();
+ expect(await readStatus(otherTopicId)).toBe('failed');
+ expect((await readMetadata(otherTopicId))?.scheduledRun).toEqual(run);
+ await expect(topicModel.retryWorktreeStart(topicId)).resolves.toMatchObject({
+ operationId,
+ userMessageId: run.userMessageId,
+ });
+ expect(await readStatus()).toBe('scheduled');
+ expect((await readMetadata())?.scheduledRun).not.toHaveProperty('error');
+ });
+
it('will not claim a scheduled topic that carries no scheduled run', async () => {
await serverDB
.insert(topics)
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 74a22afe6a6..ce0d1c0dbcf 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -208,7 +208,12 @@ export class AgentOperationModel {
if (params.requireReservation) {
const [started] = await this.db
.update(agentOperations)
- .set(values)
+ .set({
+ ...values,
+ ...(params.metadata && {
+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify(params.metadata)}::jsonb`,
+ }),
+ })
.where(reservationIdentity)
.returning({ id: agentOperations.id });
if (!started) throw new Error('Operation reservation is no longer available');
diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.ts
index bd6d14ce9b6..1c9e9f71a3b 100644
--- a/packages/database/src/models/topic/index.ts
+++ b/packages/database/src/models/topic/index.ts
@@ -146,6 +146,7 @@ export class TopicModel {
findWaitingCleanupTopicsUnder = this.withContext(ownedWorktree.findWaitingCleanupTopicsUnder);
countLiveTopicsUsingWorktree = this.withContext(ownedWorktree.countLiveTopicsUsingWorktree);
updateOwnedWorktree = this.withContext(ownedWorktree.updateOwnedWorktree);
+ recordFirstSendWorktreeCheckout = this.withContext(ownedWorktree.recordFirstSendWorktreeCheckout);
// **************** Agent Share (visitor-scoped) *************** //
@@ -213,6 +214,7 @@ export class TopicModel {
cancelRateLimitContinuation = this.withContext(scheduledRun.cancelRateLimitContinuation);
armScheduledRun = this.withContext(scheduledRun.armScheduledRun);
+ retryWorktreeStart = this.withContext(scheduledRun.retryWorktreeStart);
// **************** Memory extraction *************** //
@@ -224,6 +226,8 @@ export class TopicModel {
static getDueScheduledTopics = scheduledRun.getDueScheduledTopics;
+ static finishWorktreeStart = scheduledRun.finishWorktreeStart;
+
static claimScheduledTopic = scheduledRun.claimScheduledTopic;
static clearScheduledRun = scheduledRun.clearScheduledRun;
diff --git a/packages/database/src/models/topic/ownedWorktree.ts b/packages/database/src/models/topic/ownedWorktree.ts
index b64169ed15f..c681a8cf02a 100644
--- a/packages/database/src/models/topic/ownedWorktree.ts
+++ b/packages/database/src/models/topic/ownedWorktree.ts
@@ -1,5 +1,15 @@
-import type { ChatTopicMetadata, OwnedWorktree, OwnedWorktreeTopicRow } from '@lobechat/types';
-import { claimAutoCreatedWorktree, resolveOwnedWorktrees } from '@lobechat/types';
+import type {
+ ChatTopicMetadata,
+ OwnedWorktree,
+ OwnedWorktreeTopicRow,
+ WorkingDirConfig,
+} from '@lobechat/types';
+import {
+ claimAutoCreatedWorktree,
+ getWorkingDirEffectivePath,
+ isRetiredTopicStatus,
+ resolveOwnedWorktrees,
+} from '@lobechat/types';
import { and, eq, inArray, notInArray, or, type SQL, sql } from 'drizzle-orm';
import { topics } from '../../schemas';
@@ -49,6 +59,64 @@ export const carriedOwnedWorktrees = (
return owned.length > 0 ? { ownedWorktrees: owned } : {};
};
+/** Attach a checkout under the dispatch claim, or record it for cleanup if the topic retired meanwhile. */
+export const recordFirstSendWorktreeCheckout = async (
+ ctx: TopicModelContext,
+ id: string,
+ {
+ claimId,
+ deviceId,
+ workingDirectoryConfig,
+ }: { claimId?: string; deviceId: string; workingDirectoryConfig: WorkingDirConfig },
+): Promise<{ canDispatch: boolean; cleanupTrigger?: 'archived' | 'trashed' }> =>
+ ctx.db.transaction(async (tx) => {
+ const ownedTopic = and(eq(topics.id, id), eq(topics.userId, ctx.userId), ctx.trashScope());
+ const [row] = await tx.select(rowColumns).from(topics).where(ownedTopic).for('update');
+ if (!row) return { canDispatch: false };
+
+ const run = row.metadata?.scheduledRun;
+ const ownsClaim = !!claimId && run?.kind === 'worktree_start' && run.claim?.id === claimId;
+ const cleanupTrigger: 'archived' | 'trashed' | undefined = row.isDeleted
+ ? 'trashed'
+ : isRetiredTopicStatus(row.status)
+ ? 'archived'
+ : undefined;
+ const canDispatch = !cleanupTrigger && ownsClaim && row.status === 'scheduled';
+ const checkout = claimAutoCreatedWorktree({
+ ...row.metadata,
+ ...carriedOwnedWorktrees(row.metadata),
+ boundDeviceId: deviceId,
+ workingDirectory: getWorkingDirEffectivePath(workingDirectoryConfig),
+ workingDirectoryConfig,
+ });
+ const ownedWorktrees = checkout.ownedWorktrees?.map((entry) =>
+ cleanupTrigger && !entry.cleanup && entry.path === workingDirectoryConfig.git?.activeWorktree
+ ? {
+ ...entry,
+ cleanup: {
+ at: new Date().toISOString(),
+ state: 'pending' as const,
+ trigger: cleanupTrigger,
+ },
+ }
+ : entry,
+ );
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...(canDispatch ? checkout : row.metadata),
+ ...(ownedWorktrees && { ownedWorktrees }),
+ ...(cleanupTrigger && ownsClaim && { scheduledRun: null }),
+ },
+ ...(cleanupTrigger === 'trashed' &&
+ ownsClaim &&
+ row.status === 'scheduled' && { status: 'active' as const }),
+ })
+ .where(ownedTopic);
+ return { canDispatch, cleanupTrigger };
+ });
+
/** Topics by id with their owned-worktree data, trashed ones included. */
export const findOwnedWorktreeTopics = async (
ctx: TopicModelContext,
diff --git a/packages/database/src/models/topic/scheduledRun.ts b/packages/database/src/models/topic/scheduledRun.ts
index a8901b6faf3..024d4055a2e 100644
--- a/packages/database/src/models/topic/scheduledRun.ts
+++ b/packages/database/src/models/topic/scheduledRun.ts
@@ -6,7 +6,7 @@ import {
} from '@lobechat/types';
import { and, eq, or, sql } from 'drizzle-orm';
-import { type TopicItem, topics } from '../../schemas';
+import { topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { notTrashed } from '../../utils/softDelete';
import type { TopicModelContext } from './context';
@@ -69,6 +69,34 @@ export const armScheduledRun = async (
});
};
+/** Re-arm the same persisted turn and reservation after a failed checkout. */
+export const retryWorktreeStart = async (ctx: TopicModelContext, id: string) =>
+ ctx.db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ metadata: topics.metadata, status: topics.status })
+ .from(topics)
+ .where(and(eq(topics.id, id), ctx.ownership(), notTrashed(topics.isDeleted)))
+ .for('update');
+ const run = row?.metadata?.scheduledRun;
+ if (row?.status !== 'failed' || run?.kind !== 'worktree_start' || !run.retryable) return;
+
+ const now = new Date().toISOString();
+ const scheduledRun = {
+ ...run,
+ claim: undefined,
+ error: undefined,
+ retryable: undefined,
+ runAt: now,
+ updatedAt: now,
+ waitingForDevice: false,
+ };
+ await tx
+ .update(topics)
+ .set({ metadata: { ...row.metadata, scheduledRun }, status: 'scheduled' })
+ .where(and(eq(topics.id, id), ctx.ownership()));
+ return scheduledRun;
+ });
+
/**
* Topics with a scheduled run that has come due.
* System-level sweep (no ownership filter) used by the cron dispatcher.
@@ -90,7 +118,8 @@ export const armScheduledRun = async (
export async function getDueScheduledTopics(
db: LobeChatDatabase,
now: Date = new Date(),
-): Promise<TopicItem[]> {
+ topicId?: string,
+) {
const nowIso = now.toISOString();
const nowEpochSeconds = Math.floor(now.getTime() / 1000);
@@ -105,6 +134,7 @@ export async function getDueScheduledTopics(
.where(
and(
eq(topics.status, 'scheduled'),
+ topicId ? eq(topics.id, topicId) : undefined,
notTrashed(topics.isDeleted),
or(
// `''` is the absent-runAt sentinel, and it never satisfies this pair —
@@ -126,6 +156,50 @@ export async function getDueScheduledTopics(
);
}
+/** Complete only the worker that still owns this first send's claim. */
+export async function finishWorktreeStart(
+ db: LobeChatDatabase,
+ id: string,
+ claimId: string,
+ result: { error?: string; retryAt?: string; retryable?: boolean; success: boolean },
+): Promise<void> {
+ await db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ metadata: topics.metadata, status: topics.status })
+ .from(topics)
+ .where(eq(topics.id, id))
+ .for('update');
+ const run = row?.metadata?.scheduledRun;
+ if (run?.kind !== 'worktree_start' || run.claim?.id !== claimId) return;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: {
+ ...row.metadata,
+ scheduledRun: result.success
+ ? null
+ : result.retryAt
+ ? { ...run, claim: undefined, runAt: result.retryAt, waitingForDevice: true }
+ : {
+ ...run,
+ claim: undefined,
+ error: result.error ?? '',
+ retryable: result.retryable,
+ },
+ },
+ status:
+ (row.status === 'scheduled' || (row.status === 'active' && !result.success)) &&
+ !result.retryAt
+ ? result.success
+ ? 'running'
+ : 'failed'
+ : row.status,
+ })
+ .where(eq(topics.id, id));
+ });
+}
+
/**
* Atomically claim a scheduled topic before dispatch, so two concurrent cron
* ticks can't trigger the same continuation twice. Serializes on the row with
@@ -155,6 +229,7 @@ export async function claimScheduledTopic(
const scheduledRun = row.metadata?.scheduledRun;
if (!scheduledRun) return false;
+ if (scheduledRun.kind === 'worktree_start' && new Date(scheduledRun.runAt) > now) return false;
const existingClaim = scheduledRun.claim;
const claimLive = existingClaim && new Date(existingClaim.expiresAt) > now;
@@ -165,7 +240,11 @@ export async function claimScheduledTopic(
.set({
metadata: {
...row.metadata,
- scheduledRun: { ...scheduledRun, claim },
+ scheduledRun: {
+ ...scheduledRun,
+ ...(scheduledRun.kind === 'worktree_start' && { waitingForDevice: false }),
+ claim,
+ },
} as ChatTopicMetadata,
})
.where(eq(topics.id, id));
diff --git a/packages/database/src/repositories/topic/index.ts b/packages/database/src/repositories/topic/index.ts
index 38719162c17..f6b7929c9e2 100644
--- a/packages/database/src/repositories/topic/index.ts
+++ b/packages/database/src/repositories/topic/index.ts
@@ -2,7 +2,7 @@ import type { ChatTopicMetadata } from '@lobechat/types';
import { and, eq, sql } from 'drizzle-orm';
import type { CreateTopicParams, ModelTimingContext } from '../../models/topic';
-import { messageGroups, messages, topics } from '../../schemas';
+import { agentOperations, messageGroups, messages, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { copyMessagesInDatabase } from '../../utils/copyMessagesInDatabase';
import { idGenerator } from '../../utils/idGenerator';
@@ -26,10 +26,11 @@ const BRANCH_TOPIC_METADATA_KEYS = [
'workingDirectoryConfig',
] as const satisfies readonly (keyof ChatTopicMetadata)[];
/**
- * Owns atomic writes spanning a topic and its copied conversation.
+ * Owns atomic writes spanning a topic and related conversation rows or run records.
*
* Use when:
* - Edit/resend must create a topic and message ancestry together.
+ * - Cancelling a queued first send must retire both its schedule and its operation.
*
* Expects:
* - The caller's database and workspace scope.
@@ -78,6 +79,40 @@ export class TopicRepository {
batchMoveToAgent = (topicIds: string[], targetAgentId: string) =>
batchMoveToAgent(this.scope, topicIds, targetAgentId);
+ /** Withdraw a queued worktree send while preserving the conversation and its user message. */
+ cancelWorktreeStart = async (id: string) =>
+ this.db.transaction(async (tx) => {
+ const ownedTopic = and(eq(topics.id, id), eq(topics.userId, this.userId), this.ownership());
+ const [row] = await tx
+ .select({ metadata: topics.metadata, status: topics.status })
+ .from(topics)
+ .where(ownedTopic)
+ .for('update');
+
+ const run = row?.metadata?.scheduledRun;
+ if (row?.status !== 'scheduled' || run?.kind !== 'worktree_start')
+ return 'unchanged' as const;
+ // A worker holding a claim may already be touching Git or starting the agent.
+ if (run.claim) return 'busy' as const;
+
+ await tx
+ .update(agentOperations)
+ .set({ completedAt: new Date(), completionReason: 'interrupted', status: 'interrupted' })
+ .where(
+ and(
+ eq(agentOperations.id, run.operationId),
+ eq(agentOperations.topicId, id),
+ eq(agentOperations.userId, this.userId),
+ eq(agentOperations.status, 'idle'),
+ ),
+ );
+ await tx
+ .update(topics)
+ .set({ metadata: { ...row.metadata, scheduledRun: null }, status: 'active' })
+ .where(ownedTopic);
+ return 'cancelled' as const;
+ });
+
private ownership = () => topicOwnership(this.scope);
private messageOwnership = () => messageOwnership(this.scope);
diff --git a/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts b/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts
index 19d70d0e9a1..05e9e828e07 100644
--- a/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts
+++ b/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts
@@ -107,6 +107,25 @@ describe('addGitWorktree', () => {
expect(git(repo, 'branch', '--list', 'feat/x')).toBe('');
});
+ it('reuses only the checkout created by the same persisted worktree request', async () => {
+ const worktreePath = deriveWorktreePath(repo, 'feat/x');
+ const request = {
+ branch: 'feat/x',
+ ownerToken: 'same-request-owner-token',
+ path: repo,
+ worktreePath,
+ };
+ const result = await addGitWorktree(request);
+ expect(result.success).toBe(true);
+ await expect(addGitWorktree(request)).resolves.toEqual(result);
+ await expect(
+ addGitWorktree({ ...request, ownerToken: 'some-other-owner-token' }),
+ ).resolves.toMatchObject({ success: false });
+ await expect(addGitWorktree({ ...request, branch: 'feat/y' })).resolves.toMatchObject({
+ success: false,
+ });
+ });
+
it('reports an unwritable worktree root', async () => {
// A file where the `.lobehub` folder should be makes the mkdir fail even
// when the tests run as root (where permission bits are ignored).
diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.ts
index 4f1dc51f9f5..1f130c874c0 100644
--- a/packages/local-file-shell/src/git/worktrees.ts
+++ b/packages/local-file-shell/src/git/worktrees.ts
@@ -6,7 +6,7 @@ import { promisify } from 'node:util';
import { isInvalidBranchRef, qualifyStartPoint } from './branches';
import { getGitWorkingTreeStatus } from './info';
-import { isValidOwnerToken, writeOwnerMarker } from './ownerMarker';
+import { isValidOwnerToken, readOwnerMarker, writeOwnerMarker } from './ownerMarker';
import type {
GitAddWorktreeResult,
GitRemoveWorktreeResult,
@@ -205,8 +205,19 @@ export const addGitWorktree = async (payload: {
if (!path.isAbsolute(worktreePath))
return { error: `Worktree path must be absolute: ${worktreePath}`, success: false };
- if (existsSync(worktreePath))
+ if (existsSync(worktreePath)) {
+ if (ownerToken) {
+ const existing = await findListedWorktree(dirPath, worktreePath);
+ if (
+ existing?.branch === normalizeBranchRef(branch) &&
+ !existing.prunable &&
+ (await readOwnerMarker(existing.path).catch(() => undefined)) === ownerToken
+ ) {
+ return { ownerToken, startPoint, success: true, worktreePath: existing.path };
+ }
+ }
return { error: `Worktree folder already exists: ${worktreePath}`, success: false };
+ }
const parent = path.dirname(worktreePath);
try {
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 21e597e1a98..0b3dbb7c2f5 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -48,6 +48,7 @@ export default {
'workingDirectory.branchesLoading': 'Loading branches…',
'workingDirectory.branchesNoMatch': 'No matching branches',
'workingDirectory.cancel': 'Cancel',
+ 'workingDirectory.cancelWorktreeSend': 'Cancel send',
'workingDirectory.checkoutAction': 'Checkout',
'workingDirectory.checkoutFailed': 'Checkout failed',
'workingDirectory.chooseDifferentFolder': 'Choose a folder...',
@@ -210,7 +211,12 @@ export default {
'workingDirectory.switchRiskUncommitted_one': 'Uncommitted changes may be lost ({{count}} file).',
'workingDirectory.switchRiskUncommitted_other':
'Uncommitted changes may be lost ({{count}} files).',
+ 'workingDirectory.worktreeCancelFailed': 'Could not cancel the send',
+ 'workingDirectory.worktreeCancelTooLate': 'This send can no longer be cancelled',
'workingDirectory.worktreeCreateFailed': 'Could not create the worktree',
+ 'workingDirectory.worktreeDeviceRequired':
+ 'Connect this device before sending with a new worktree.',
+ 'workingDirectory.worktreeSendCancelled': 'Send cancelled',
'workingDirectory.worktreeToggle': 'New worktree',
'workingDirectory.worktreeToggleOffHint':
'Turn on to run this topic in a new branch and worktree',
@@ -218,4 +224,5 @@ export default {
'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.worktreeWaitingForDevice': 'Waiting for the device to connect…',
};
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
index ab0bd848954..da885dd61d0 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 { FirstSendWorktree } from '../../topic';
import type { WorkingDirConfig } from '../../workingDir';
import type { ChatMessageError } from '../common/base';
import { ChatMessageErrorSchema } from '../common/base';
@@ -134,6 +135,10 @@ export interface SendMessageParams {
/** Lexical editor JSON state for rich text rendering */
editorData?: Record<string, any>;
files?: UploadFileItem[];
+ /**
+ * Create this worktree on the device after the server has accepted the first send.
+ */
+ firstSendWorktree?: FirstSendWorktree;
/**
* Force the agent runtime regardless of the agent's local/cloud/hetero
* config. Injected straight into `selectRuntimeType` as `parentRuntime`,
@@ -154,16 +159,12 @@ export interface SendMessageParams {
* This decouples sendMessage from store selectors.
*/
messages?: UIChatMessage[];
+
/**
* Additional metadata for the message (e.g., mentioned users)
*/
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.
- */
+ /** A checkout already prepared for this new topic by the Desktop client. */
newTopicWorkingDirectory?: WorkingDirConfig;
onlyAddUserMessage?: boolean;
/**
diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.ts
index 4545ec8709f..20cb91b75ae 100644
--- a/packages/types/src/topic/topic.test.ts
+++ b/packages/types/src/topic/topic.test.ts
@@ -215,6 +215,19 @@ describe('parseTopicScheduledRun', () => {
expect(parseTopicScheduledRun(run)).toEqual(run);
});
+ it('preserves the operation reservation for a first send awaiting a worktree', () => {
+ const run = {
+ createdAt: legacy.createdAt,
+ kind: 'worktree_start',
+ operationId: 'operation-1',
+ runAt: legacy.createdAt,
+ updatedAt: legacy.updatedAt,
+ userMessageId: legacy.userMessageId,
+ };
+
+ expect(parseTopicScheduledRun(run)).toEqual(run);
+ });
+
it('upgrades a legacy rate-limit payload, deriving runAt from the reset window', () => {
// resetsAt is epoch SECONDS — the gate is the instant the window reopens.
expect(parseTopicScheduledRun(legacy)).toMatchObject({
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 16de7a4e324..cbd6ea412a6 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -593,6 +593,23 @@ const delayedStartRunSchema = topicScheduledRunBaseSchema.extend({
userMessageId: z.string(),
});
+export const firstSendWorktreeSchema = z.object({
+ baseBranch: z.string().min(1).max(1024).optional(),
+ deviceId: z.string().min(1).max(256),
+ path: z.string().min(1).max(4096),
+ repoType: z.enum(['git', 'github']),
+ sourcePath: z.string().min(1).max(4096),
+});
+
+const worktreeStartRunSchema = topicScheduledRunBaseSchema.extend({
+ error: z.string().optional(),
+ kind: z.literal('worktree_start'),
+ operationId: z.string(),
+ retryable: z.boolean().optional(),
+ userMessageId: z.string(),
+ waitingForDevice: z.boolean().optional(),
+});
+
/**
* A deferred agent run on a topic: *when* to run (`runAt`), a lease so only one
* replica dispatches it (`claim`), and *what* to run (the `kind` variant).
@@ -607,11 +624,14 @@ const delayedStartRunSchema = topicScheduledRunBaseSchema.extend({
export const topicScheduledRunSchema = z.discriminatedUnion('kind', [
resumeAfterRateLimitRunSchema,
delayedStartRunSchema,
+ worktreeStartRunSchema,
]);
export type TopicScheduledRunClaim = z.infer<typeof topicScheduledRunClaimSchema>;
export type ResumeAfterRateLimitRun = z.infer<typeof resumeAfterRateLimitRunSchema>;
export type DelayedStartRun = z.infer<typeof delayedStartRunSchema>;
+export type FirstSendWorktree = z.infer<typeof firstSendWorktreeSchema>;
+export type WorktreeStartRun = z.infer<typeof worktreeStartRunSchema>;
export type TopicScheduledRun = z.infer<typeof topicScheduledRunSchema>;
/**
diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
index 28fd09355aa..232b14fad9a 100644
--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
@@ -1,9 +1,11 @@
-import { DEVICE_GIT_OUTDATED, getWorktreeModeKey } from '@lobechat/types';
+import type * as LobechatConstModule from '@lobechat/const';
+import { 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 { useAgentStore } from '@/store/agent';
import { useGitStatusStore } from '@/store/device/gitStatus/store';
import { useUserStore } from '@/store/user';
@@ -22,6 +24,15 @@ import {
snapshotDraftGit,
} from './prepareSend';
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof LobechatConstModule>()),
+ isDesktop: true,
+}));
+
+vi.mock('@/services/ownedWorktree', () => ({
+ issueWorktreeReceipt: async () => undefined,
+}));
+
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
getActiveWorkspaceId: () => null,
useActiveWorkspaceId: () => null,
@@ -43,12 +54,6 @@ vi.mock('@/services/git', async (importOriginal) => {
};
});
-// The server-signed creation receipt for a new worktree.
-const issueWorktreeReceipt = vi.hoisted(() =>
- vi.fn(async () => ({ nonce: 'nonce-1', token: 'signed-token-0123456789' })),
-);
-vi.mock('@/services/ownedWorktree', () => ({ issueWorktreeReceipt }));
-
vi.mock('@/services/device', () => ({
deviceService: { countRunningTopicsInDirectory: vi.fn() },
}));
@@ -92,6 +97,7 @@ const pick = (branch: string) => setDraftBranch(draftBranchKey(target), branch);
beforeEach(() => {
vi.clearAllMocks();
+ useAgentStore.setState({ agentMap: {} });
useDraftGitStore.setState({ selections: {}, targets: {} });
useGitStatusStore.setState({ gitAheadBehindMap: {} });
registerDraftGitTarget(target);
@@ -348,119 +354,90 @@ describe('prepareDraftGitSend — switch in place', () => {
});
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)}`,
- }));
- });
+ beforeEach(() => setWorktreeMode(true));
- it('forks the picked branch into a new worktree that becomes the topic directory', async () => {
+ it('captures the picked branch and device before handing the send to the server', 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,
- // The send created the branch: the run end may look its PR up.
- ownBranch: call.branch,
- },
+ firstSendWorktree: {
+ baseBranch: 'feat',
+ deviceId: 'dev-1',
path: '/code/lobehub',
repoType: 'github',
- sessionPath: expect.stringContaining('/.lobehub/worktrees/'),
+ sourcePath: '/code/lobehub',
},
ok: true,
+ onMessagePersisted: expect.any(Function),
});
- // 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('records the server-signed receipt only once the device echoes it back', async () => {
- vi.mocked(gitService.addGitWorktree).mockImplementation(async ({ branch, ownerToken }) => ({
- ownerToken,
- success: true,
- worktreePath: `/Users/me/.lobehub/worktrees/lobehub-0000beef/${branch.split('/').at(-1)}`,
- }));
- const recorded = await prepareDraftGitSend(context, { prompts: prompts(), t });
- expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].ownerToken).toBe(
- 'signed-token-0123456789',
- );
- expect(recorded.ok && recorded.newTopicWorkingDirectory?.git).toMatchObject({
- ownerNonce: 'nonce-1',
- ownerToken: 'signed-token-0123456789',
- });
-
- // A device too old to write it echoes nothing: no receipt is claimed.
- vi.mocked(gitService.addGitWorktree).mockImplementation(async ({ branch }) => ({
- success: true,
- worktreePath: `/Users/me/.lobehub/worktrees/lobehub-0000beef/${branch.split('/').at(-1)}`,
- }));
- const older = await prepareDraftGitSend(context, { prompts: prompts(), t });
- expect(older.ok && older.newTopicWorkingDirectory?.git?.ownerToken).toBeUndefined();
-
- // No receipt from the server: the worktree is still created, without one.
- issueWorktreeReceipt.mockResolvedValueOnce(undefined as any);
- vi.mocked(gitService.addGitWorktree).mockClear();
- const unsigned = await prepareDraftGitSend(context, { prompts: prompts(), t });
- expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].ownerToken).toBeUndefined();
- expect(unsigned.ok).toBe(true);
+ expect(gitService.getGitBranch).not.toHaveBeenCalled();
+ expect(gitService.addGitWorktree).not.toHaveBeenCalled();
+ expect(p.showProgress).not.toHaveBeenCalled();
+ expect(getDraftBranch(draftBranchKey(target))).toBe('feat');
+ if (result.ok) result.onMessagePersisted?.();
+ expect(getDraftBranch(draftBranchKey(target))).toBeUndefined();
});
- it('forks from HEAD without a start point when nothing else was picked', async () => {
- await prepareDraftGitSend(context, { prompts: prompts(), t });
+ it('uses the local desktop gateway id when the repository is on this machine', async () => {
+ registerDraftGitTarget({ ...target, deviceId: undefined });
+ const result = await prepareDraftGitSend(context, { prompts: prompts(), t });
- expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].startPoint).toBeUndefined();
- expect(gitService.getGitAheadBehind).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ firstSendWorktree: { deviceId: 'dev-1' }, ok: true });
+ expect(result.ok && result.firstSendWorktree?.baseBranch).toBeUndefined();
});
- 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,
- });
+ it('keeps the draft when the local device is not registered with the gateway', async () => {
+ registerDraftGitTarget({ ...target, deviceId: undefined, keyDeviceId: undefined });
+ useUserStore.setState({
+ preference: {
+ ...useUserStore.getState().preference,
+ worktreeModeDirs: [getWorktreeModeKey('local', target.path)],
+ },
+ } as any);
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',
+ description: 'workingDirectory.worktreeDeviceRequired',
title: 'workingDirectory.worktreeCreateFailed',
});
- expect(getDraftBranch(draftBranchKey(target))).toBe('feat');
+ expect(gitService.addGitWorktree).not.toHaveBeenCalled();
});
- it('says to update the device when it ignored the start point', async () => {
- pick('feat');
+ it('creates a Desktop API-bound agent checkout in-process without a gateway registration', async () => {
+ useAgentStore.setState({
+ agentMap: {
+ [target.agentId]: {
+ agencyConfig: { heterogeneousProvider: { authMode: 'api', type: 'claude-code' } },
+ },
+ },
+ });
+ const localTarget = { ...target, deviceId: undefined, keyDeviceId: undefined };
+ const checkoutPath = '/local/checkout';
vi.mocked(gitService.addGitWorktree).mockResolvedValue({
- error: 'outdated',
- reason: DEVICE_GIT_OUTDATED,
- success: false,
+ success: true,
+ worktreePath: checkoutPath,
+ });
+ const result = await prepareDraftGitSend(context, {
+ prompts: prompts(),
+ snapshot: { picked: 'feat', target: localTarget, worktreeMode: true },
+ t,
});
- const p = prompts();
- expect(await prepareDraftGitSend(context, { prompts: p, t })).toEqual({ ok: false });
- expect(p.notifyError).toHaveBeenCalledWith(
- expect.objectContaining({ description: 'workingDirectory.deviceOutdated' }),
+ expect(gitService.addGitWorktree).toHaveBeenCalledWith(
+ expect.objectContaining({ path: target.path, startPoint: 'feat' }),
);
+ expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].deviceId).toBeUndefined();
+ expect(result).not.toHaveProperty('firstSendWorktree');
+ expect(result).toMatchObject({
+ newTopicWorkingDirectory: {
+ git: { activeWorktree: checkoutPath, autoCreated: true },
+ path: target.sourcePath,
+ sessionPath: checkoutPath,
+ },
+ ok: true,
+ });
});
});
diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
index d99a822b6bc..543e3323a1e 100644
--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
@@ -1,11 +1,13 @@
-import { generateWorktreeBranchName, WORKTREE_BRANCH_PREFIX } from '@lobechat/const';
-import type { ConversationContext, WorkingDirConfig } from '@lobechat/types';
+import { generateWorktreeBranchName, isDesktop, WORKTREE_BRANCH_PREFIX } from '@lobechat/const';
+import type { ConversationContext, FirstSendWorktree, 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 { issueWorktreeReceipt } from '@/services/ownedWorktree';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
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';
@@ -52,8 +54,10 @@ export type DraftGitSendResult =
* on it: the composer may have changed hands in the meantime.
*/
acted?: boolean;
+ firstSendWorktree?: FirstSendWorktree;
newTopicWorkingDirectory?: WorkingDirConfig;
ok: true;
+ onMessagePersisted?: () => void;
};
const PASS: DraftGitSendResult = { ok: true };
@@ -117,51 +121,64 @@ const countRunningTopics = async ({ keyDeviceId, path }: DraftGitTarget): Promis
}
};
-const createWorktree = async (
+const snapshotWorktree = (
target: DraftGitTarget,
- base: string | undefined,
- headBranch: string | undefined,
+ baseBranch: string | undefined,
+ { prompts, t }: { prompts: DraftGitSendPrompts; t: TFunction<'device'> },
+): DraftGitSendResult => {
+ const deviceId = target.deviceId ?? target.keyDeviceId;
+ if (!deviceId) {
+ prompts.notifyError({
+ description: t('workingDirectory.worktreeDeviceRequired'),
+ title: t('workingDirectory.worktreeCreateFailed'),
+ });
+ return STOP;
+ }
+ const key = draftBranchKey(target);
+ return {
+ firstSendWorktree: {
+ baseBranch,
+ deviceId,
+ path: target.path,
+ repoType: target.isGithub ? 'github' : 'git',
+ sourcePath: target.sourcePath,
+ },
+ ok: true,
+ onMessagePersisted: () => {
+ if (getDraftBranch(key) === baseBranch) setDraftBranch(key, undefined);
+ },
+ };
+};
+
+/** API-bound agents must run in this Desktop, even without a gateway registration. */
+const createLocalWorktree = async (
+ target: DraftGitTarget,
+ picked: string | undefined,
{ prompts, t }: { prompts: DraftGitSendPrompts; t: TFunction<'device'> },
): Promise<DraftGitSendResult> => {
+ const { path, sourcePath } = target;
+ const title = t('workingDirectory.worktreeCreateFailed');
const fail = (description: string) => {
- prompts.notifyError({ description, title: t('workingDirectory.worktreeCreateFailed') });
+ prompts.notifyError({ description, title });
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) });
- // The creation receipt, signed by the server for this user: the device
- // writes it into the worktree, and only a cleanup presenting it — which the
- // server does only for this user's topics — may later remove the folder.
- const receipt = await issueWorktreeReceipt();
- const ownerToken = receipt?.token;
- const homeDir = target.deviceId
- ? undefined
- : desktopStateSelectors.userHomePath(getElectronStoreState()) || undefined;
const dismiss = prompts.showProgress(t('workingDirectory.preparingWorktree'));
try {
+ const [refs, receipt] = await Promise.all([listBranchNames(target), issueWorktreeReceipt()]);
+ const branch = generateWorktreeBranchName({ exclude: refs });
+ const homeDir = desktopStateSelectors.userHomePath(getElectronStoreState()) || undefined;
+ const ownerToken = receipt?.token;
const result = await gitService.addGitWorktree({
branch,
- deviceId: target.deviceId,
ownerToken,
- 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,
- }),
+ path,
+ startPoint: picked,
+ worktreePath: deriveWorktreePath(sourcePath, branch, {
+ homeDir,
+ stripBranchPrefix: WORKTREE_BRANCH_PREFIX,
+ }),
});
- if (!result.success || !result.worktreePath)
- return fail(describeGitFailure(result, t, t('workingDirectory.worktreeCreateFailed')));
+ if (!result.success || !result.worktreePath) return fail(describeGitFailure(result, t, title));
return {
acted: true,
@@ -170,20 +187,21 @@ const createWorktree = async (
activeWorktree: result.worktreePath,
autoCreated: true,
autoCreatedAt: new Date().toISOString(),
- // Only what the device confirms it recorded.
- ...(ownerToken &&
- result.ownerToken === ownerToken && { ownerNonce: receipt?.nonce, ownerToken }),
branch,
isWorktree: true,
- // The send created this branch: the run end may look its PR up.
ownBranch: branch,
+ ...(ownerToken &&
+ result.ownerToken === ownerToken && { ownerNonce: receipt?.nonce, ownerToken }),
},
- path: target.sourcePath,
+ path: sourcePath,
repoType: target.isGithub ? 'github' : 'git',
sessionPath: result.worktreePath,
},
ok: true,
};
+ } catch (error) {
+ console.error('[prepareDraftGitSend] could not create Desktop worktree', error);
+ return fail(isDeviceGitOutdated(error) ? t('workingDirectory.deviceOutdated') : title);
} finally {
dismiss();
}
@@ -245,20 +263,6 @@ const switchInPlace = async (
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)
@@ -312,7 +316,19 @@ export const prepareDraftGitSend = async (
if (!snap) return PASS;
const { picked, target, worktreeMode } = snap;
const key = draftBranchKey(target);
- if (!picked && !worktreeMode) return PASS;
+ if (worktreeMode) {
+ const provider =
+ isDesktop && !target.deviceId
+ ? agentSelectors.getAgentConfigById(target.agentId)(getAgentStoreState())?.agencyConfig
+ ?.heterogeneousProvider
+ : undefined;
+ if (provider?.authMode !== 'api') return snapshotWorktree(target, picked, { prompts, t });
+
+ const result = await createLocalWorktree(target, picked, { prompts, t });
+ if (result.ok && getDraftBranch(key) === picked) setDraftBranch(key, undefined);
+ return result;
+ }
+ if (!picked) return PASS;
// Act on what the directory is on now, not on the bar's last read.
const head = await gitService
@@ -320,11 +336,7 @@ export const prepareDraftGitSend = async (
.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;
+ const result = 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);
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 523e61738c1..a351630ce82 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -277,6 +277,12 @@ const ChatInput = memo<ChatInputProps>(
const isSendDispatchPending = useChatStore((s) =>
operationSelectors.isSendDispatchPendingByContext(context)(s),
);
+ const isWorktreePending = useChatStore((s) => {
+ const topic = topicId ? topicSelectors.getTopicById(topicId)(s) : undefined;
+ return (
+ topic?.status === 'scheduled' && topic.metadata?.scheduledRun?.kind === 'worktree_start'
+ );
+ });
const pendingInterventions = usePendingInterventions();
const hasPendingInterventions = pendingInterventions.length > 0;
@@ -314,7 +320,8 @@ const ChatInput = memo<ChatInputProps>(
// disableSend hard-blocks regardless of content (host surface is read-only).
// Uploads in flight do not block: the send is queued until they settle (see
// `queueSendWhileUploading`).
- const disabled = isInputEmpty || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
+ const disabled =
+ isInputEmpty || isWorktreePending || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
// `disabled` above lags the editor: `inputMessage` mirrors content through
// the editor's debounced onChange, so a fast type→Enter arrives while the
@@ -323,7 +330,7 @@ const ChatInput = memo<ChatInputProps>(
// at trigger time, so this only mirrors the visual disabled semantics.
const customDisabled = customSendButtonProps?.disabled;
const resolveSendBlocked = useCallback(() => {
- if (disableSend) return true;
+ if (disableSend || isWorktreePending) return true;
const { context: liveContext, editor } = storeApi.getState();
const liveContextKey = messageMapKey(liveContext);
@@ -341,7 +348,7 @@ const ChatInput = memo<ChatInputProps>(
const hasContextSelections =
fileChatSelectors.chatContextSelections(liveContextKey)(fileStore).length > 0;
return !hasText && !hasFiles && !hasContextSelections;
- }, [customDisabled, disableQueue, disableSend, storeApi]);
+ }, [customDisabled, disableQueue, disableSend, isWorktreePending, storeApi]);
const businessAlerts = useBusinessChatInputAlerts();
const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);
@@ -350,7 +357,7 @@ const ChatInput = memo<ChatInputProps>(
async ({ clearContent, getMarkdownContent, getEditorData }) => {
// Host surface is read-only (e.g. page locked) — block Enter too, not
// just the grayed-out button.
- if (disableSend) return;
+ if (disableSend || isWorktreePending) return;
// Get instant values from stores at trigger time
const fileStore = useFileStore.getState();
@@ -435,16 +442,15 @@ const ChatInput = memo<ChatInputProps>(
return;
}
- // 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.
+ // A branch switch may need confirmation before sending. A worktree
+ // send carries its captured device and branch into persistence.
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,
+ acted: !!gitPrep.acted || !!gitPrep.firstSendWorktree,
editorUnchanged: getMarkdownContent() === message,
stillHere: messageMapKey(storeApi.getState().context) === messageMapKey(sendContext),
});
@@ -461,10 +467,10 @@ const ChatInput = memo<ChatInputProps>(
editorData,
files: currentFileList,
message,
- ...(gitPrep.newTopicWorkingDirectory
- ? { newTopicWorkingDirectory: gitPrep.newTopicWorkingDirectory }
- : {}),
+ ...(gitPrep.firstSendWorktree ? { firstSendWorktree: gitPrep.firstSendWorktree } : {}),
+ newTopicWorkingDirectory: gitPrep.newTopicWorkingDirectory,
...(handoff.sendToOrigin ? { conversationContext: sendContext } : {}),
+ onMessagePersisted: gitPrep.onMessagePersisted,
onPreflightFailure: () => {
const store = useFileStore.getState();
// The composer was cleared up front; a send rejected before any
@@ -477,7 +483,16 @@ const ChatInput = memo<ChatInputProps>(
pageSelections,
});
},
- [contextKey, sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked, t],
+ [
+ contextKey,
+ sendMessage,
+ storeApi,
+ disableQueue,
+ disableSend,
+ isInputQueueBlocked,
+ isWorktreePending,
+ t,
+ ],
);
const sendButtonProps: SendButtonProps = getConversationSendButtonProps(
@@ -495,6 +510,7 @@ const ChatInput = memo<ChatInputProps>(
const handleVoiceMessageSend = useCallback(
(recording: VoiceMessageRecording) => {
+ if (isWorktreePending) return false;
if (operationSelectors.isInputVisiblyLoadingByContext(context)(useChatStore.getState())) {
return false;
}
@@ -527,7 +543,7 @@ const ChatInput = memo<ChatInputProps>(
}),
);
},
- [context, sendMessage],
+ [context, isWorktreePending, sendMessage],
);
const defaultContent = (
diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts
index d7b6ff998a5..5526fc332e7 100644
--- a/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts
+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.test.ts
@@ -166,16 +166,36 @@ describe('sendVoiceMessage', () => {
// 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 firstSendWorktree = {
+ deviceId: 'dev-1',
+ path: '/repo',
+ repoType: 'git' as const,
+ sourcePath: '/repo',
+ };
const sendMessage = vi.fn(async (params: SendMessageParams) => {
params.onMessageAccepted?.();
});
await sendVoiceMessage(sendMessage, voiceFile, {
- prepare: async () => ({ newTopicWorkingDirectory, ok: true }),
+ prepare: async () => ({ firstSendWorktree, ok: true }),
});
- expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ newTopicWorkingDirectory }));
+ expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({ firstSendWorktree }));
+ });
+
+ it('passes a prepared Desktop checkout to the first voice send', async () => {
+ const checkout = { path: '/repo', sessionPath: '/checkout' };
+ const sendMessage = vi.fn(async (params: SendMessageParams) => {
+ params.onMessageAccepted?.();
+ });
+
+ await sendVoiceMessage(sendMessage, voiceFile, {
+ prepare: async () => ({ newTopicWorkingDirectory: checkout, ok: true }),
+ });
+
+ expect(sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ newTopicWorkingDirectory: checkout }),
+ );
});
it('sends nothing, and keeps the recording retryable, when the git step stops', async () => {
diff --git a/src/features/Conversation/ChatInput/sendVoiceMessage.ts b/src/features/Conversation/ChatInput/sendVoiceMessage.ts
index 81509cce25e..0d6bac2d9db 100644
--- a/src/features/Conversation/ChatInput/sendVoiceMessage.ts
+++ b/src/features/Conversation/ChatInput/sendVoiceMessage.ts
@@ -1,9 +1,6 @@
-import {
- type ConversationContext,
- type SendMessageParams,
- type UploadFileItem,
- type WorkingDirConfig,
-} from '@lobechat/types';
+import type { ConversationContext, SendMessageParams, UploadFileItem } from '@lobechat/types';
+
+import type { DraftGitSendResult } from '@/features/ChatInput/ControlBar/DraftGit/prepareSend';
type SendMessage = (
params: SendMessageParams & { conversationContext?: ConversationContext },
@@ -17,9 +14,7 @@ interface SendVoiceMessageOptions {
* 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 }
- >;
+ prepare?: () => Promise<DraftGitSendResult>;
signal?: AbortSignal;
/**
* Resolve the turn text from the uploaded recording. Runtimes that cannot take audio input
@@ -66,10 +61,14 @@ export const sendVoiceMessage = async (
accepted = true;
resolve();
},
- preserveComposer: true,
- ...(prepared?.ok && prepared.newTopicWorkingDirectory
- ? { newTopicWorkingDirectory: prepared.newTopicWorkingDirectory }
+ ...(prepared?.ok
+ ? {
+ firstSendWorktree: prepared.firstSendWorktree,
+ newTopicWorkingDirectory: prepared.newTopicWorkingDirectory,
+ onMessagePersisted: prepared.onMessagePersisted,
+ }
: {}),
+ preserveComposer: true,
...(context ? { conversationContext: context } : {}),
...(optimisticUserMessageId ? { optimisticUserMessageId } : {}),
...(signal ? { signal } : {}),
diff --git a/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx b/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx
index 3c51ab01082..40d30240f5f 100644
--- a/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx
+++ b/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx
@@ -1,11 +1,13 @@
'use client';
-import { ActionIcon, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { ActionIcon, Button, cssVar, Flexbox, Icon, Text, toast } from '@lobehub/ui';
import dayjs from 'dayjs';
-import { BanIcon, ClockIcon } from 'lucide-react';
-import { memo } from 'react';
+import { BanIcon, ClockIcon, LoaderCircleIcon } from 'lucide-react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
+import { aiAgentService } from '@/services/aiAgent';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -26,26 +28,114 @@ interface ScheduledRunFooterProps {
*/
const ScheduledRunFooter = memo<ScheduledRunFooterProps>(({ id }) => {
const { t } = useTranslation('chat');
+ const { t: tDevice } = useTranslation('device');
+ const { t: tCommon } = useTranslation('common');
+ const topicId = useConversationStore((s) => s.context.topicId);
+ const [cancelling, setCancelling] = useState(false);
+ const [retrying, setRetrying] = useState(false);
- const runAt = useChatStore((s) => {
- const topic = topicSelectors.currentActiveTopic(s);
- if (topic?.status !== 'scheduled') return;
-
- const scheduledRun = topic.metadata?.scheduledRun;
- if (scheduledRun?.kind !== 'delayed_start' || scheduledRun.userMessageId !== id) return;
-
- return scheduledRun.runAt;
+ const run = useChatStore((s) => {
+ if (!topicId) return;
+ const topic = topicSelectors.getTopicById(topicId)(s);
+ const scheduledRun = topic?.metadata?.scheduledRun;
+ if (!scheduledRun || scheduledRun.userMessageId !== id) return;
+ if (
+ topic.status === 'scheduled' ||
+ (topic.status === 'failed' &&
+ scheduledRun.kind === 'worktree_start' &&
+ scheduledRun.error !== undefined)
+ )
+ return scheduledRun;
});
const cancelScheduledRun = useConversationStore((s) => s.cancelScheduledRun);
+ const cancelWorktree = async () => {
+ if (!topicId) return;
+ setCancelling(true);
+ try {
+ const outcome = await aiAgentService.cancelWorktreeTurn(topicId);
+ if (outcome === 'cancelled') {
+ toast.success(tDevice('workingDirectory.worktreeSendCancelled'));
+ } else {
+ toast.info(tDevice('workingDirectory.worktreeCancelTooLate'));
+ }
+ await useChatStore
+ .getState()
+ .refreshTopicDetail(topicId, true)
+ .catch((error) => {
+ console.error('[ScheduledRunFooter] refresh after cancellation failed', error);
+ });
+ } catch (error) {
+ console.error('[ScheduledRunFooter] cancel worktree send failed', error);
+ toast.error(tDevice('workingDirectory.worktreeCancelFailed'));
+ } finally {
+ setCancelling(false);
+ }
+ };
+
+ const retryWorktree = async () => {
+ if (!topicId) return;
+ setRetrying(true);
+ try {
+ await aiAgentService.retryWorktreeTurn(topicId);
+ await useChatStore.getState().refreshTopicDetail(topicId, true);
+ } catch (error) {
+ console.error('[ScheduledRunFooter] retry worktree failed', error);
+ toast.error(tDevice('workingDirectory.worktreeCreateFailed'));
+ } finally {
+ setRetrying(false);
+ }
+ };
+
+ if (run?.kind === 'worktree_start') {
+ if (run.error !== undefined) {
+ return (
+ <Flexbox horizontal justify={'flex-end'}>
+ <AsyncError
+ align={'start'}
+ description={''}
+ details={run.error}
+ variant={'inline'}
+ action={
+ run.retryable && (
+ <Button loading={retrying} size={'small'} type={'text'} onClick={retryWorktree}>
+ {tCommon('retry')}
+ </Button>
+ )
+ }
+ title={
+ <Text as={'span'} type={'danger'}>
+ {tDevice('workingDirectory.worktreeCreateFailed')}
+ </Text>
+ }
+ />
+ </Flexbox>
+ );
+ }
- if (!runAt) return null;
+ return (
+ <Flexbox horizontal align={'center'} gap={6} justify={'flex-end'} paddingBlock={4}>
+ <Icon spin icon={LoaderCircleIcon} size={14} />
+ <Text role={'status'} style={{ fontSize: 12 }} type={'secondary'}>
+ {run.waitingForDevice
+ ? tDevice('workingDirectory.worktreeWaitingForDevice')
+ : tDevice('workingDirectory.preparingWorktree')}
+ </Text>
+ {!run.claim && (
+ <Button loading={cancelling} size={'small'} type={'text'} onClick={cancelWorktree}>
+ {tDevice('workingDirectory.cancelWorktreeSend')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+ }
+ if (run?.kind !== 'delayed_start') return null;
return (
<Flexbox horizontal align={'center'} gap={4} justify={'flex-end'} paddingBlock={4}>
<Icon icon={ClockIcon} size={14} style={{ color: cssVar.colorTextQuaternary }} />
<Text style={{ fontSize: 12 }} type={'secondary'}>
- {t('input.schedule.pending', { time: dayjs(runAt).format('MM-DD HH:mm') })}
+ {t('input.schedule.pending', { time: dayjs(run.runAt).format('MM-DD HH:mm') })}
</Text>
<ActionIcon
icon={BanIcon}
diff --git a/src/hooks/useScheduledRunWatch.ts b/src/hooks/useScheduledRunWatch.ts
index 265aaf1935a..10e1c24c130 100644
--- a/src/hooks/useScheduledRunWatch.ts
+++ b/src/hooks/useScheduledRunWatch.ts
@@ -6,6 +6,7 @@ import { topicSelectors } from '@/store/chat/selectors';
/** Poll cadence once the run is due — the cron dispatcher ticks every ~10 min. */
const POLL_INTERVAL_MS = 30_000;
+const WORKTREE_POLL_INTERVAL_MS = 1500;
/** Start polling slightly before `runAt` so the first due tick isn't missed. */
const POLL_LEAD_MS = 60_000;
@@ -40,6 +41,12 @@ export const useScheduledRunWatch = (topicId: string | null | undefined) => {
if (topic?.status !== 'scheduled') return undefined;
return topic.metadata?.scheduledRun?.runAt ?? null;
});
+ const startingWorktree = useChatStore((s) =>
+ Boolean(
+ topicId &&
+ topicSelectors.getTopicById(topicId)(s)?.metadata?.scheduledRun?.kind === 'worktree_start',
+ ),
+ );
useSWR(
topicId && scheduledRunAt !== undefined ? topicKeys.scheduledRunWatch(topicId) : null,
@@ -47,6 +54,7 @@ export const useScheduledRunWatch = (topicId: string | null | undefined) => {
{
refreshInterval: () => {
if (scheduledRunAt === undefined) return 0;
+ if (startingWorktree) return WORKTREE_POLL_INTERVAL_MS;
const dueAt = scheduledRunAt ? new Date(scheduledRunAt).getTime() - POLL_LEAD_MS : 0;
const untilDue = dueAt - Date.now();
return untilDue > POLL_INTERVAL_MS ? untilDue : POLL_INTERVAL_MS;
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 24aa417bac0..ef257720cf4 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -398,10 +398,23 @@ class AiAgentService {
return await lambdaClient.agentSteerQueue.remove.mutate(params);
}
- /**
- * Defer an agent run to a future time. Creates an empty `scheduled` topic that
- * the backend cron fires once `runAt` passes; nothing runs now.
- */
+ /** Persist a first send before the device checkout starts. */
+ async submitWorktreeTurn(
+ params: Parameters<typeof lambdaClient.aiAgent.submitWorktreeTurn.mutate>[0],
+ workspaceId: string | null,
+ ) {
+ return createWorkspaceLambdaClient(workspaceId).aiAgent.submitWorktreeTurn.mutate(params);
+ }
+
+ async cancelWorktreeTurn(topicId: string) {
+ return lambdaClient.aiAgent.cancelWorktreeTurn.mutate({ topicId });
+ }
+
+ async retryWorktreeTurn(topicId: string) {
+ return lambdaClient.aiAgent.retryWorktreeTurn.mutate({ topicId });
+ }
+
+ /** Persist a scheduled turn for the backend to dispatch at the selected time. */
async scheduleAgentRun(params: ScheduleAgentRunParams): Promise<ScheduleAgentRunResult> {
return await lambdaClient.aiAgent.scheduleAgentRun.mutate(params);
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
index 1cf4cbf72d8..369b4200996 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
@@ -3,6 +3,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { agentService } from '@/services/agent';
+import { aiAgentService } from '@/services/aiAgent';
import { aiChatService } from '@/services/aiChat';
import { deviceService } from '@/services/device';
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
@@ -88,6 +89,52 @@ afterEach(() => {
});
describe('sendMessage in a project directory', () => {
+ it('submits a self-mention first send with its worktree and staged project directory', async () => {
+ deviceAgent();
+ const agentId = TEST_IDS.SESSION_ID;
+ const worktree = {
+ deviceId: DEVICE_ID,
+ path: PROJECT_PATH,
+ repoType: 'git' as const,
+ sourcePath: PROJECT_PATH,
+ };
+ const submit = vi
+ .spyOn(aiAgentService, 'submitWorktreeTurn')
+ .mockRejectedValue(new Error('offline'));
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ isGatewayModeEnabled: () => true,
+ pendingNewTopicDirectory: { agentId, projectWorkingDirectoryId: 'dir-85' },
+ });
+
+ await act(async () => {
+ await useChatStore.getState().sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ { label: 'Agent', metadata: { id: agentId, type: 'agent' }, type: 'mention' },
+ { text: ' work in isolation', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ },
+ },
+ firstSendWorktree: worktree,
+ message: '@Agent work in isolation',
+ });
+ });
+
+ expect(submit).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId, projectWorkingDirectoryId: 'dir-85', worktree }),
+ null,
+ );
+ });
+
// Regression: the new topic's optimistic metadata took the agent's own
// per-device directory, and the send-time git snapshot wrote that config back
// over the server's project binding — the composer then showed another repo's
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index 7cad3287823..d9a14e614bd 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -71,7 +71,10 @@ import {
sendQueuedTurn,
} from '@/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp';
import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';
-import { buildQueuedFollowUpRequest } from '@/store/chat/slices/agentRun/actions/transports/gateway/execRequest';
+import {
+ buildQueuedFollowUpRequest,
+ resolveUserInterventionConfig,
+} from '@/store/chat/slices/agentRun/actions/transports/gateway/execRequest';
import {
canQueueOnServer,
findServerHeldQueueKey,
@@ -130,6 +133,7 @@ import { getOptimisticMessageMedia } from './optimisticMessageMedia';
import { findRunningBlockingOp } from './queueBlockingOp';
import { resolveSendProjectRun, resolveSendRunCwd, type SourceTopicDirectory } from './runCwd';
import { showSendErrorInContext } from './sendErrorNotice';
+import { submitFirstSendWorktree } from './submitFirstSendWorktree';
/**
* Extended params for sendMessage with context
@@ -264,6 +268,7 @@ export class ConversationLifecycleActionImpl {
contextSelections,
inputEditor,
messages: inputMessages,
+ firstSendWorktree,
newTopicWorkingDirectory,
optimisticUserMessageId,
parentId: inputParentId,
@@ -436,7 +441,7 @@ export class ConversationLifecycleActionImpl {
agencyConfig,
boundDirectoryId: boundTopic?.projectWorkingDirectoryId,
context,
- directMentionRoute: !!directMentionRoute,
+ directMentionRoute: !!directMentionRoute && !(agentId === ownerAgentId && firstSendWorktree),
isGatewayMode,
ownerAgentId,
pendingDirectory,
@@ -535,21 +540,8 @@ export class ConversationLifecycleActionImpl {
// for a topic that does not exist on the server yet.
const willCreateNewTopic = !context.topicId;
- /**
- * The id this send's topic will be created under, minted up front and
- * adopted by the WHOLE send: the operation context, the optimistic message
- * bucket, `activeTopicId` and the sidebar row all use it from the first
- * frame, and the server honours it verbatim (`newTopic.id` / `clientIds`).
- *
- * This removes the server-confirmation re-key: optimistic messages use the
- * final topic key immediately, so the virtualized list does not repaint from
- * an empty viewport when the server responds. The composer still pivots once
- * from `_new` to this minted key below, and its pending context is migrated
- * before that switch.
- *
- * Isolated-topic callers keep the legacy flow (they re-subscribe via
- * `onTopicCreated` and never render the main conversation surface).
- */
+ // The optimistic topic, its messages and the server share one final id.
+ // Isolated callers re-subscribe via onTopicCreated instead.
const mintedTopicId =
willCreateNewTopic && !context.isolatedTopic ? generateEntityId('topics') : undefined;
@@ -1071,8 +1063,6 @@ export class ConversationLifecycleActionImpl {
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,
@@ -1150,50 +1140,19 @@ export class ConversationLifecycleActionImpl {
: undefined;
let optimisticTopicActive = false;
- const addResolvedTopicPlaceholder = (
- topicId: string,
- title: string,
- action: string,
- extra?: {
- metadata?: ChatTopicMetadata;
- model?: string;
- /**
- * True only for the client-only placeholder inserted before the server
- * has created the topic. The topic slice keeps those ids so a refetch
- * landing mid-send re-prepends the row instead of wiping it.
- */
- optimistic?: boolean;
- provider?: string;
- },
- ) => {
- this.#get().internal_dispatchTopic(
- {
- ...optimisticTopicScope,
- ...(extra?.optimistic ? { optimistic: true } : {}),
- type: 'addTopic',
- value: {
- id: topicId,
- ...(extra?.metadata ? { metadata: extra.metadata } : {}),
- ...(extra?.model ? { model: extra.model, provider: extra.provider } : {}),
- ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
- title,
- },
- },
- action,
- );
- };
-
const resolveOptimisticTopic = (topicId: string, title = optimisticTopic?.title) => {
+ const value = {
+ ...(optimisticTopic?.metadata ? { metadata: optimisticTopic.metadata } : {}),
+ ...(optimisticTopic?.model
+ ? { model: optimisticTopic.model, provider: optimisticTopic.provider }
+ : {}),
+ ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
+ title: title || t('defaultTitle', { ns: 'topic' }),
+ };
if (!optimisticTopic || !optimisticTopicActive) {
- addResolvedTopicPlaceholder(
- topicId,
- title || t('defaultTitle', { ns: 'topic' }),
+ this.#get().internal_dispatchTopic(
+ { ...optimisticTopicScope, type: 'addTopic', value: { ...value, id: topicId } },
'sendMessage/reconcileOptimisticTopic/add',
- {
- metadata: optimisticTopic?.metadata,
- model: optimisticTopic?.model,
- provider: optimisticTopic?.provider,
- },
);
return;
}
@@ -1202,14 +1161,7 @@ export class ConversationLifecycleActionImpl {
...optimisticTopicScope,
nextId: topicId,
previousId: optimisticTopic.id,
- value: {
- ...(optimisticTopic.metadata ? { metadata: optimisticTopic.metadata } : {}),
- ...(optimisticTopic.model
- ? { model: optimisticTopic.model, provider: optimisticTopic.provider }
- : {}),
- ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
- title: title || t('defaultTitle', { ns: 'topic' }),
- },
+ value,
});
optimisticTopicActive = false;
};
@@ -1264,6 +1216,44 @@ export class ConversationLifecycleActionImpl {
optimisticTopicActive = true;
}
+ if (firstSendWorktree && willCreateNewTopic && ownerAgentId === agentId) {
+ return submitFirstSendWorktree(this.#get, {
+ abandon: (error) => {
+ restoreComposerAfterFailedSend(error);
+ cleanupTempMessages({ preserveOptimisticUser: Boolean(optimisticUserMessageId) });
+ detachUnacceptedCallerAbort();
+ rollbackOptimisticTopic('sendMessage/worktreeSubmissionFailed');
+ restoreUnacceptedVoiceMessageContext();
+ },
+ accepted: () => hasNotifiedMessageAccepted,
+ complete: () => {
+ optimisticTopicActive = false;
+ cleanupTempMessages({ preserveOptimisticUser: true });
+ },
+ mintedTopicId,
+ onMessagePersisted: notifyMessagePersisted,
+ onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,
+ operationId,
+ request: () => ({
+ ...newTopicProject,
+ agentId,
+ assistantMessageId: tempAssistantId,
+ fileIds: fileIdList,
+ mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
+ prompt: message,
+ selectedSkillIds: selectedSkills.map(({ identifier }) => identifier),
+ selectedToolIds: selectedTools.map(({ identifier }) => identifier),
+ topicId: mintedTopicId ?? generateEntityId('topics'),
+ userInterventionConfig: resolveUserInterventionConfig(),
+ userMessage: toComposerUserMessage({ editorData, metadata: userMessageMetadata }),
+ userMessageId: tempId,
+ worktree: firstSendWorktree,
+ }),
+ scope: optimisticTopicScope,
+ workspaceId: sendOriginWorkspaceId,
+ });
+ }
+
// ── External agent mode: delegate to heterogeneous agent CLI (desktop only) ──
// Per-agent heterogeneousProvider config takes priority over the global gateway mode.
if (runtimeType === 'hetero' && heterogeneousProvider) {
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.ts
index 9abdf9a12c1..691928621c6 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.test.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.test.ts
@@ -37,29 +37,47 @@ const base = {
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 });
+const existingTopic = {
+ metadata: { boundDeviceId: 'dev-1', workingDirectoryConfig: worktree },
+};
+
+describe('resolveSendRunCwd with a pinned worktree', () => {
+ it('starts a Desktop API-bound session in its newly created checkout', async () => {
+ const result = await resolveSendRunCwd({
+ ...base,
+ agencyConfig: { executionTarget: 'local' },
+ draftWorkingDirectory: worktree,
+ heterogeneousProvider: { authMode: 'api', type: 'claude-code' },
+ inheritedTopic: { metadata: { workingDirectoryConfig: { path: '/code/old' } } },
+ stagedDirectoryPath: worktree.path,
+ });
+
+ expect(result.workingDirectoryConfig).toEqual(worktree);
+ expect(result.workingDirectory).toBe(worktree.sessionPath);
+ });
+
+ it('keeps a device-bound topic in its saved worktree', async () => {
+ const result = await resolveSendRunCwd({ ...base, existingTopic });
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 () => {
+ it('continues a local CLI agent’s session in the same worktree', async () => {
const result = await resolveSendRunCwd({
...base,
- draftWorkingDirectory: worktree,
+ existingTopic,
heterogeneousProvider: { type: 'claude-code' },
});
expect(result.workingDirectory).toBe(worktree.git!.activeWorktree);
});
- it('outranks the staged project directory', async () => {
+ it('keeps an existing topic’s worktree instead of taking a staged project directory', async () => {
const result = await resolveSendRunCwd({
...base,
- draftWorkingDirectory: worktree,
+ existingTopic,
stagedDirectoryPath: '/code/lobehub',
});
@@ -72,7 +90,6 @@ describe('resolveSendRunCwd with a directory prepared by the composer', () => {
};
const result = await resolveSendRunCwd({
...base,
- draftWorkingDirectory: worktree,
existingTopic,
});
@@ -80,7 +97,7 @@ describe('resolveSendRunCwd with a directory prepared by the composer', () => {
expect(result.workingDirectory).toBe('/code/other');
});
- it('keeps the agent default without one', async () => {
+ it('keeps the agent default for topics without a pinned directory', 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.ts
index 147025a62a3..49eedb6d76e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts
@@ -189,11 +189,6 @@ export const resolveSendRunCwd = async ({
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;
@@ -281,7 +276,7 @@ export const resolveSendRunCwd = async ({
agentWorkingDirectoryConfig,
existingTopic,
inheritedTopic:
- !stagedDirectoryPath && !draftWorkingDirectory && resolvesRunCwd ? inheritedTopic : undefined,
+ !draftWorkingDirectory && !stagedDirectoryPath && resolvesRunCwd ? inheritedTopic : undefined,
resolvePath: resolveWorkingDirPath,
runMachine: { deviceId: runCwdDeviceId, target: runEffectiveTarget },
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/submitFirstSendWorktree.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/submitFirstSendWorktree.ts
new file mode 100644
index 00000000000..7c431567b82
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/submitFirstSendWorktree.ts
@@ -0,0 +1,69 @@
+import { aiAgentService } from '@/services/aiAgent';
+import type { ChatStore } from '@/store/chat/store';
+
+type SubmitRequest = Parameters<typeof aiAgentService.submitWorktreeTurn>[0];
+type TopicListScope = Pick<
+ Parameters<ChatStore['internal_replaceTopicId']>[0],
+ 'agentId' | 'groupId'
+>;
+
+interface SubmitFirstSendWorktreeParams {
+ abandon: (error: unknown) => void;
+ accepted: () => boolean;
+ complete: () => void;
+ mintedTopicId?: string;
+ onMessagePersisted: () => void;
+ onTopicCreated?: (topicId: string) => void | Promise<void>;
+ operationId: string;
+ request: () => SubmitRequest;
+ scope: TopicListScope;
+ workspaceId: string | null;
+}
+
+/** Finish the client send when the server takes ownership of the pending worktree turn. */
+export const submitFirstSendWorktree = async (
+ get: () => ChatStore,
+ {
+ abandon,
+ accepted,
+ complete,
+ mintedTopicId,
+ onMessagePersisted,
+ onTopicCreated,
+ operationId,
+ request,
+ scope,
+ workspaceId,
+ }: SubmitFirstSendWorktreeParams,
+) => {
+ try {
+ const input = request();
+ const { topic } = await aiAgentService.submitWorktreeTurn(input, workspaceId);
+ onMessagePersisted();
+ get().internal_replaceTopicId({
+ ...scope,
+ nextId: topic.id,
+ previousId: mintedTopicId ?? topic.id,
+ value: {
+ metadata: topic.metadata ?? undefined,
+ status: topic.status,
+ title: topic.title ?? undefined,
+ },
+ });
+ complete();
+ get().completeOperation(operationId);
+ if (onTopicCreated) await onTopicCreated(topic.id);
+ return {
+ assistantMessageId: input.assistantMessageId,
+ createdTopicId: topic.id,
+ userMessageId: input.userMessageId,
+ };
+ } catch (error) {
+ if (accepted()) throw error;
+ get().failOperation(operationId, {
+ message: error instanceof Error ? error.message : String(error),
+ type: 'GatewayError',
+ });
+ abandon(error);
+ }
+};
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 7308d68a5ba..eced616c1d8 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -1202,20 +1202,9 @@ export class ChatTopicActionImpl {
};
/**
- * Re-read a `scheduled` topic from the server and fold any dispatch back into
- * the store. The cron dispatcher (`scheduledTopicDispatch`) mutates only the
- * DB when `runAt` passes — status → 'running', `scheduledRun` cleared,
- * `runningOperation` seeded, the parked error card cleared off the failed
- * message — and no push channel tells a client that is already sitting on the
- * topic. This is the pull side: `useScheduledRunWatch` calls it on topic entry
- * and on a short poll around `runAt`.
- *
- * When the server has moved past `scheduled`, the fresh row is patched into
- * the topic map (so `useGatewayReconnect` sees `runningOperation` and attaches
- * to the live stream) and the message list is refetched (so the stale
- * rate-limit card drops and the continuation's assistant row appears).
- *
- * Returns whether a dispatch was observed and folded in.
+ * Fold scheduled work's server-side transition into the topic map. The watcher
+ * calls this on entry and while the schedule is due. A dispatch also refreshes
+ * the transcript so gateway reconnect can anchor to the new assistant row.
*/
syncScheduledTopicRun = async (topicId: string): Promise<boolean> => {
const stored = topicSelectors.getTopicById(topicId)(this.#get());
@@ -1237,8 +1226,18 @@ export class ChatTopicActionImpl {
const fresh = this.#pendingTopicStatusWrites.apply(fetched, 'server');
if (fresh.status !== fetched.status) return false;
- // Server still parked — nothing to fold in.
- if (fresh.status === 'scheduled' && fresh.metadata?.scheduledRun) return false;
+ // A first send can wait for its device before it starts creating the checkout.
+ const stillScheduled = fresh.status === 'scheduled' && !!fresh.metadata?.scheduledRun;
+ if (stillScheduled) {
+ const pending = fresh.metadata?.scheduledRun;
+ const previous = stored.metadata?.scheduledRun;
+ if (
+ pending?.kind !== 'worktree_start' ||
+ previous?.kind !== 'worktree_start' ||
+ !!pending.waitingForDevice === !!previous.waitingForDevice
+ )
+ return false;
+ }
// Re-check after the await: a topic/agent switch mid-flight means the
// active bucket no longer holds this row — don't patch a foreign bucket.
@@ -1256,7 +1255,7 @@ export class ChatTopicActionImpl {
// The dispatcher also rewrote messages before handing off (cleared/deleted
// the failed step, created the continuation's placeholder), so the list
// must be refetched before the gateway reconnect anchors on it.
- await this.#get().refreshMessages();
+ if (!stillScheduled) await this.#get().refreshMessages();
return true;
};