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.

✨ feat(task): let a task pin its own run location and working directory (#19799)

Arvin Xu311459f65f71
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 355f1c848bd..83c978c496f 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -120,6 +120,9 @@ const updateSchema = z.object({
assigneeUserId: z.string().nullish(),
automationMode: z.enum(['heartbeat', 'schedule']).nullish(),
config: z.record(z.string(), z.unknown()).optional(),
+ // Deep-merged into `config` under the update's row lock rather than
+ // replacing it — for a client editing one config key alongside columns.
+ configPatch: z.record(z.string(), z.unknown()).optional(),
context: z.record(z.string(), z.unknown()).optional(),
description: z.string().optional(),
editorData: z.unknown().optional(),
@@ -1375,7 +1378,7 @@ export const taskRouter = router({
update: taskProcedureWrite
.input(idInput.merge(updateSchema).extend({ actorAgentId: z.string().optional() }))
.mutation(async ({ input, ctx }) => {
- const { actorAgentId, id, parentTaskId, status, ...data } = input;
+ const { actorAgentId, configPatch, id, parentTaskId, status, ...data } = input;
try {
const model = ctx.taskModel;
const actor = await resolveActivityActor(ctx, actorAgentId);
@@ -1404,6 +1407,7 @@ export const taskRouter = router({
resolved.id,
normalizedUpdateData,
actor,
+ { configPatch },
);
if (!updated) return null;
@@ -1414,6 +1418,7 @@ export const taskRouter = router({
resolved.id,
normalizedUpdateData,
actor,
+ { configPatch },
);
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
// Only an actual assignee change notifies — re-saving the same assignee
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index b68a784f5c2..b2cf8fbce91 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -989,6 +989,9 @@ export const dispatchHeteroAgent = async (
devicePlatform: boundDevice?.platform,
initialWorkingDirectory: appContext?.initialTopicMetadata?.workingDirectory,
initialWorkingDirectoryConfig: appContext?.initialTopicMetadata?.workingDirectoryConfig,
+ // The run's repos, so a directory that IS one of them is skipped: this
+ // device cannot have it (`owner/repo` is a cloud repo identifier).
+ repos: topicRepos,
topicDeviceId: topic?.metadata?.boundDeviceId,
topicWorkingDirectory: topic?.metadata?.workingDirectory,
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index 00bd56059cb..f1a046a8b58 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -267,6 +267,9 @@ const resolveWorkspaceInit = async (
deviceDefaultCwd: device.defaultCwd,
deviceId: activeDeviceId,
devicePlatform: device.platform,
+ // A directory that is one of the topic's repos is not a path on this
+ // machine — skip it (see the resolver) and scan what the device has.
+ repos: topic?.metadata?.repos,
topicDeviceId: topic?.metadata?.boundDeviceId,
topicWorkingDirectory,
topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
index 8413efbab1f..1de78e322d2 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
@@ -193,3 +193,78 @@ describe('resolveDeviceWorkingDirectoryConfig', () => {
).toEqual(agentChoice);
});
});
+
+describe('repo identifiers are never a device cwd', () => {
+ const repos = ['lobehub/lobehub'];
+
+ it('skips an initial repo-derived directory and falls through to the machine', () => {
+ // A Task can carry a repo selection whose assignee agent is later switched
+ // to a device (or a cloud-surface topic can be resumed on one). `owner/repo`
+ // is not a path on that machine, and the initial metadata sits ABOVE the
+ // device default in the precedence — so the run would spawn its CLI in a
+ // directory that does not exist instead of the device's own default.
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ initialWorkingDirectory: 'lobehub/lobehub',
+ repos,
+ }),
+ ).toBe('/Users/me/app');
+ });
+
+ it('skips a rich initial config whose path is a repo', () => {
+ expect(
+ resolveDeviceWorkingDirectoryConfig({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ initialWorkingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ repos,
+ }),
+ ).toEqual({ path: '/Users/me/app' });
+ });
+
+ it('prefers the agent per-device pick over a skipped repo directory', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ initialWorkingDirectory: 'lobehub/lobehub',
+ repos,
+ workingDirByDevice: { 'device-1': '/Users/me/project' },
+ }),
+ ).toBe('/Users/me/project');
+ });
+
+ it('skips a topic-level repo identifier, so a resumed topic cannot pin a machine to it', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ repos,
+ topicWorkingDirectory: 'lobehub/lobehub',
+ }),
+ ).toBe('/Users/me/app');
+ });
+
+ it('only skips a directory the run actually declares as a repo', () => {
+ // Machine paths are absolute, so shape-matching would be wrong: the guard
+ // has to be the run's own repo list, not "looks like owner/repo".
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ initialWorkingDirectory: '/Users/me/lobehub/lobehub',
+ repos,
+ }),
+ ).toBe('/Users/me/lobehub/lobehub');
+
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/Users/me/app',
+ deviceId: 'device-1',
+ initialWorkingDirectory: 'lobehub/lobehub',
+ }),
+ ).toBe('lobehub/lobehub');
+ });
+});
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
index 1d0bd12ef12..bdf2e6d840c 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
@@ -54,6 +54,9 @@ const topicPinFitsDevice = (
* - `workingDirByDevice[deviceId]` — the agent's per-device pick from the picker
* when no topic existed yet.
* - `deviceDefaultCwd` — the device's user-configured default.
+ *
+ * A source that holds a REPO IDENTIFIER is skipped rather than trusted: see
+ * `isRepoIdentifier` below — the selection's unit has to match the run's target.
*/
export const resolveDeviceWorkingDirectoryConfig = (params: {
deviceDefaultCwd?: string | null;
@@ -61,17 +64,33 @@ export const resolveDeviceWorkingDirectoryConfig = (params: {
devicePlatform?: string | null;
initialWorkingDirectory?: string;
initialWorkingDirectoryConfig?: WorkingDirConfig;
+ /** Repos this run carries (`topic.metadata.repos`, seeded from a Task's own selection). */
+ repos?: string[];
topicDeviceId?: string;
topicWorkingDirectory?: string;
topicWorkingDirectoryConfig?: WorkingDirConfig;
workingDirByDevice?: Record<string, WorkingDirConfigValue> | null;
}): WorkingDirConfig | undefined => {
+ // `owner/repo` is a repo, not a directory on this machine: taking one as the
+ // device cwd would override the machine's own choice with a path that does not
+ // exist here, and the spawned CLI would start in it. A real machine path is
+ // absolute, so it can never equal a repo entry; skipping these costs nothing
+ // when the run is genuinely cloud-bound (the sandbox reads `repos`, not the cwd).
+ const isRepoIdentifier = (path?: string): boolean =>
+ !!path && (params.repos ?? []).includes(path);
+
const topicPin =
params.topicWorkingDirectoryConfig ??
(params.topicWorkingDirectory ? { path: params.topicWorkingDirectory } : undefined);
- if (topicPin && topicPinFitsDevice(topicPin.path, params)) return topicPin;
- if (params.initialWorkingDirectoryConfig) return params.initialWorkingDirectoryConfig;
- if (params.initialWorkingDirectory) return { path: params.initialWorkingDirectory };
+ if (topicPin && topicPinFitsDevice(topicPin.path, params) && !isRepoIdentifier(topicPin.path)) {
+ return topicPin;
+ }
+
+ const initialConfig = params.initialWorkingDirectoryConfig;
+ if (initialConfig && !isRepoIdentifier(initialConfig.path)) return initialConfig;
+ if (params.initialWorkingDirectory && !isRepoIdentifier(params.initialWorkingDirectory)) {
+ return { path: params.initialWorkingDirectory };
+ }
const agentChoice = toWorkingDirConfig(
params.deviceId ? params.workingDirByDevice?.[params.deviceId] : undefined,
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 79957be27f3..48a66d4f207 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -2191,6 +2191,7 @@ describe('TaskService', () => {
'task_001',
{ assigneeAgentId: 'agt_new' },
{ agentId: 'agt_actor', userId: 'user_actor' },
+ {},
);
});
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 8d3cce5f53f..cdb4a6ccc12 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -936,9 +936,10 @@ export class TaskService {
taskId: string,
data: Parameters<TaskModel['update']>[1],
actor: { agentId?: string | null; userId?: string | null } = {},
+ options: Parameters<TaskModel['updateWithLog']>[3] = {},
): Promise<TaskItem | null> {
return this.withAssigneeUserLock(data.assigneeUserId, (db) =>
- new TaskModel(db, this.userId, this.workspaceId).updateWithLog(taskId, data, actor),
+ new TaskModel(db, this.userId, this.workspaceId).updateWithLog(taskId, data, actor, options),
);
}
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index d52d569b601..7dc4db1fa5d 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -3,6 +3,7 @@ import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-
import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
import { INBOX_SESSION_ID } from '@lobechat/const';
import type { ExecAgentResult, TaskItem, TaskRunTrigger } from '@lobechat/types';
+import { readTaskExecutionConfig } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -11,12 +12,18 @@ import { AgentModel } from '@/database/models/agent';
import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
import { TaskLifecycleService } from '@/server/services/taskLifecycle';
import { buildTaskPrompt } from './buildTaskPrompt';
+import {
+ resolveRunDeviceId,
+ resolveTaskRunExecution,
+ resolveTopicExecutionPatch,
+} from './resolveRunExecution';
const log = debug('task-runner');
@@ -56,6 +63,7 @@ export class TaskRunnerService {
private taskLifecycle: TaskLifecycleService;
private taskModel: TaskModel;
private taskTopicModel: TaskTopicModel;
+ private topicModel: TopicModel;
private userId: string;
private workspaceId?: string;
@@ -67,10 +75,33 @@ export class TaskRunnerService {
this.agentModel = new AgentModel(db, userId, workspaceId);
this.taskModel = new TaskModel(db, userId, workspaceId);
this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
+ this.topicModel = new TopicModel(db, userId, workspaceId);
this.briefModel = new BriefModel(db, userId, workspaceId);
this.taskLifecycle = new TaskLifecycleService(db, userId, workspaceId);
}
+ /**
+ * Mirror a task's execution selection onto a topic one of its runs continues.
+ *
+ * Deliberately NOT swallowed: the topic's stored directory outranks the
+ * selection this run brings, so an unsynced topic means the run may start in
+ * the previous machine's directory — failing the kickoff (and letting the
+ * caller's error path restore the task's resting state) is better than
+ * running somewhere the user did not pin.
+ */
+ private async syncTopicExecution(
+ topicId: string,
+ taskConfig: Record<string, unknown>,
+ runDeviceId: string | undefined,
+ ): Promise<void> {
+ const topic = await this.topicModel.findById(topicId);
+ const patch = resolveTopicExecutionPatch(topic?.metadata, taskConfig, runDeviceId);
+ if (!patch) return;
+
+ await this.topicModel.updateMetadata(topicId, patch);
+ log('runTask: synced topic %s execution metadata', topicId);
+ }
+
async runTask(params: RunTaskParams): Promise<RunTaskResult> {
const {
additionalPluginIds,
@@ -228,6 +259,31 @@ export class TaskRunnerService {
}
}
+ // The execution selection the task itself carries — a pinned device and/or
+ // a working directory. Undefined when the task pins nothing, in which case
+ // the run keeps inheriting the assignee agent's target and cwd.
+ const taskExecution = readTaskExecutionConfig(taskConfig);
+ // The device the run will actually use. It differs from the task's pin
+ // when the author FIXED the agent's target, and that difference decides
+ // whether the directory may travel: see `resolveTaskRunExecution`.
+ const runDeviceId = taskExecution
+ ? resolveRunDeviceId(
+ taskExecution,
+ await this.agentModel.getAgentAgencyConfig(agentRef),
+ this.workspaceId,
+ )
+ : undefined;
+ const runExecution = resolveTaskRunExecution(taskExecution, runDeviceId);
+
+ // A continued topic keeps its own metadata (`turnSetup` stamps
+ // `initialTopicMetadata` only for a topic it creates) and those stored
+ // values outrank what this run brings — the directory this task pins would
+ // be ignored, and the previous machine's kept. Stamp the task's selection
+ // onto the topic first; see `resolveTopicExecutionPatch`.
+ if (continueTopicId) {
+ await this.syncTopicExecution(continueTopicId, taskConfig, runDeviceId);
+ }
+
log('runTask: %s (continue=%s)', taskIdentifier, continueTopicId);
const result = await aiAgentService.execAgent({
@@ -270,7 +326,25 @@ export class TaskRunnerService {
title: extraPrompt ? extraPrompt.slice(0, 100) : task.name || task.identifier,
trigger: TopicTrigger.RunTask,
userInterventionConfig: { approvalMode: 'headless' },
- ...(continueTopicId && { appContext: { topicId: continueTopicId } }),
+ // The task's own pin, when it has one. `deviceId` forces device routing
+ // unless the agent's selection policy is `fixed` (author-controlled
+ // targets stay authoritative — same rule the chat picker follows), and
+ // the directory rides into the topic this run creates.
+ ...(runExecution?.deviceId ? { deviceId: runExecution.deviceId } : {}),
+ ...(continueTopicId || runExecution?.initialTopicMetadata
+ ? {
+ appContext: {
+ ...(continueTopicId && { topicId: continueTopicId }),
+ // A continued topic keeps its own metadata (the server ignores
+ // this for an existing topic), so it is only meaningful on a
+ // fresh run — sent anyway so the task's intent is not lost if
+ // that ever changes.
+ ...(runExecution?.initialTopicMetadata && {
+ initialTopicMetadata: runExecution.initialTopicMetadata,
+ }),
+ },
+ }
+ : {}),
});
if (!result.success) {
diff --git a/apps/server/src/services/taskRunner/resolveRunExecution.test.ts b/apps/server/src/services/taskRunner/resolveRunExecution.test.ts
new file mode 100644
index 00000000000..e855f062944
--- /dev/null
+++ b/apps/server/src/services/taskRunner/resolveRunExecution.test.ts
@@ -0,0 +1,316 @@
+// @vitest-environment node
+import type { LobeAgentAgencyConfig, TaskExecutionConfig } from '@lobechat/types';
+import { applyTaskDirectorySelection, toTaskExecutionConfigPatch } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ resolveRunDeviceId,
+ resolveTaskRunExecution,
+ resolveTopicExecutionPatch,
+} from './resolveRunExecution';
+
+describe('resolveTaskRunExecution', () => {
+ it('keeps a directory picked on an inherited device on that device', () => {
+ // Picked while following an agent bound to device-a; the agent is later
+ // fixed to device-b by its author.
+ const execution = applyTaskDirectorySelection(undefined, { path: '/srv/app' }, 'device-a');
+ const movedAgent = {
+ boundDeviceId: 'device-b',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ } as const;
+ const runDeviceId = resolveRunDeviceId(execution, movedAgent, 'ws-1');
+
+ expect(runDeviceId).toBe('device-b');
+ // device-a's path must not be forwarded to device-b.
+ expect(resolveTaskRunExecution(execution, runDeviceId)?.initialTopicMetadata).toBeUndefined();
+ });
+
+ it('returns nothing for a task that pins nothing, so the run inherits the agent', () => {
+ expect(resolveTaskRunExecution(undefined, undefined)).toBeUndefined();
+ expect(resolveTaskRunExecution({} as TaskExecutionConfig, undefined)).toBeUndefined();
+ });
+
+ it('forwards a device pin as the run deviceId', () => {
+ expect(resolveTaskRunExecution({ boundDeviceId: 'device-a' }, 'device-a')).toEqual({
+ deviceId: 'device-a',
+ });
+ });
+
+ it('carries a local working directory with its repo type', () => {
+ expect(
+ resolveTaskRunExecution(
+ {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/Users/me/Code/lobehub',
+ workingDirectoryConfig: { path: '/Users/me/Code/lobehub', repoType: 'github' },
+ },
+ 'device-a',
+ ),
+ ).toEqual({
+ deviceId: 'device-a',
+ initialTopicMetadata: {
+ workingDirectory: '/Users/me/Code/lobehub',
+ workingDirectoryConfig: { path: '/Users/me/Code/lobehub', repoType: 'github' },
+ },
+ });
+ });
+
+ it('falls back to the primary repo when only repos were selected', () => {
+ expect(resolveTaskRunExecution({ repos: ['lobehub/lobehub'] }, undefined)).toEqual({
+ initialTopicMetadata: {
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ },
+ });
+ });
+
+ it('lets an explicit directory config win over the path and the repos', () => {
+ expect(
+ resolveTaskRunExecution(
+ {
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/tmp/ignored',
+ workingDirectoryConfig: { path: '/Users/me/Code/other', repoType: 'git' },
+ },
+ undefined,
+ ),
+ ).toEqual({
+ initialTopicMetadata: {
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/Users/me/Code/other',
+ workingDirectoryConfig: { path: '/Users/me/Code/other', repoType: 'git' },
+ },
+ });
+ });
+
+ it('keeps the directory when the run lands on the machine it was picked for', () => {
+ // The policy-fixed device and the task's pin are the same machine, so the
+ // directory is exactly where the run goes.
+ expect(
+ resolveTaskRunExecution(
+ { boundDeviceId: 'device-a', workingDirectory: '/a/project' },
+ 'device-a',
+ ),
+ ).toEqual({
+ deviceId: 'device-a',
+ initialTopicMetadata: {
+ workingDirectory: '/a/project',
+ workingDirectoryConfig: { path: '/a/project' },
+ },
+ });
+ });
+
+ it('leaves a pinned machine directory behind when the run lands elsewhere', () => {
+ // The workspace author fixed the agent to another machine AFTER the task
+ // picked A with `/a/project`. The pin is dropped for routing, so its path
+ // has to go with it: the topic gets stamped with the EFFECTIVE device, which
+ // makes the residency check in `resolveDeviceWorkingDirectoryConfig` read
+ // another machine's absolute path as this run's own.
+ expect(
+ resolveTaskRunExecution(
+ { boundDeviceId: 'device-a', workingDirectory: '/a/project' },
+ 'device-b',
+ ),
+ ).toEqual({ deviceId: 'device-a' });
+
+ // …and the same when the fixed target is the sandbox, where no device-local
+ // path can be used at all.
+ expect(
+ resolveTaskRunExecution(
+ { boundDeviceId: 'device-a', workingDirectory: '/a/project' },
+ undefined,
+ ),
+ ).toEqual({ deviceId: 'device-a' });
+ });
+
+ it('keeps the repos of a task pinned to a device the run does not use', () => {
+ // `repos` belong to the assignee agent's provider env, not to a machine, so
+ // they are the part of the selection a run elsewhere can still act on.
+ expect(
+ resolveTaskRunExecution(
+ { boundDeviceId: 'device-a', repos: ['lobehub/lobehub'] },
+ 'device-b',
+ ),
+ ).toEqual({
+ deviceId: 'device-a',
+ initialTopicMetadata: {
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ },
+ });
+ });
+});
+
+describe('resolveTopicExecutionPatch', () => {
+ it('writes nothing when the topic already carries the selection', () => {
+ // The common case: a task that has not been retargeted continues its topic
+ // without paying for a write.
+ expect(
+ resolveTopicExecutionPatch(
+ {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: { path: '/srv/app' },
+ },
+ { execution: { boundDeviceId: 'device-a', workingDirectory: '/srv/app' } },
+ 'device-a',
+ ),
+ ).toBeUndefined();
+
+ expect(resolveTopicExecutionPatch({}, {}, undefined)).toBeUndefined();
+ });
+
+ it('moves a continued topic to the machine the task now pins', () => {
+ // The bug this guards: a topic created on device A keeps routing with A's
+ // directory because the topic's own metadata outranks the run's.
+ expect(
+ resolveTopicExecutionPatch(
+ {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/a/project',
+ workingDirectoryConfig: { path: '/a/project' },
+ },
+ { execution: { boundDeviceId: 'device-b', workingDirectory: '/b/project' } },
+ 'device-b',
+ ),
+ ).toEqual({
+ boundDeviceId: 'device-b',
+ repos: undefined,
+ workingDirectory: '/b/project',
+ workingDirectoryConfig: { path: '/b/project' },
+ });
+ });
+
+ it('replaces a device directory with the repo the task now selects', () => {
+ expect(
+ resolveTopicExecutionPatch(
+ {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/a/project',
+ workingDirectoryConfig: { path: '/a/project' },
+ },
+ { execution: { repos: ['lobehub/lobehub'] } },
+ undefined,
+ ),
+ ).toEqual({
+ boundDeviceId: undefined,
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ });
+ });
+
+ it('clears the axes a task no longer pins, so "inherit the agent" wins', () => {
+ // A cleared selection is persisted as `null` axes (`toTaskExecutionConfigPatch`).
+ expect(
+ resolveTopicExecutionPatch(
+ {
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ },
+ { execution: toTaskExecutionConfigPatch(undefined) },
+ undefined,
+ ),
+ ).toEqual({
+ boundDeviceId: undefined,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+
+ it('clears a continued topic directory whose machine the run no longer uses', () => {
+ // Same hazard as the fresh-topic case, one run later: the topic was written
+ // on A with `/a/project`, but the run now goes elsewhere, so the stored path
+ // must not survive the sync — the topic's own values outrank the run's.
+ expect(
+ resolveTopicExecutionPatch(
+ { boundDeviceId: 'device-a', workingDirectory: '/a/project' },
+ { execution: { boundDeviceId: 'device-a', workingDirectory: '/a/project' } },
+ 'device-b',
+ ),
+ ).toEqual({
+ boundDeviceId: 'device-a',
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+
+ it('leaves a continued topic alone when the task never selected a run location', () => {
+ // Legacy and untouched tasks carry no `execution` block. Their topic's device
+ // and directory are where the continued CLI session lives; clearing them
+ // would let a since-changed agent target move the run and lose the session.
+ const topic = {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/a/project',
+ workingDirectoryConfig: { path: '/a/project' },
+ };
+
+ expect(resolveTopicExecutionPatch(topic, {}, undefined)).toBeUndefined();
+ expect(resolveTopicExecutionPatch(topic, null, undefined)).toBeUndefined();
+ expect(
+ resolveTopicExecutionPatch(topic, { model: 'gpt-4o', provider: 'openai' }, undefined),
+ ).toBeUndefined();
+ });
+
+ it('leaves the rest of the topic metadata to the merge', () => {
+ const patch = resolveTopicExecutionPatch(
+ { boundDeviceId: 'device-a', cronJobId: 'cron-1', workingDirectory: '/a' },
+ { execution: { boundDeviceId: 'device-b' } },
+ 'device-b',
+ );
+
+ // Only the execution axes are asserted on; `updateMetadata` merges, so the
+ // patch must not carry (or drop) anything else.
+ expect(Object.keys(patch ?? {}).sort()).toEqual([
+ 'boundDeviceId',
+ 'repos',
+ 'workingDirectory',
+ 'workingDirectoryConfig',
+ ]);
+ });
+});
+
+describe('resolveRunDeviceId', () => {
+ const fixedDevice: LobeAgentAgencyConfig = {
+ boundDeviceId: 'device-b',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ };
+
+ it('keeps the task pin while members pick the target', () => {
+ expect(
+ resolveRunDeviceId(
+ { boundDeviceId: 'device-a' },
+ { boundDeviceId: 'device-b', executionTarget: 'device' },
+ 'ws-1',
+ ),
+ ).toBe('device-a');
+ });
+
+ it("uses the agent's fixed device instead of the task pin", () => {
+ expect(resolveRunDeviceId({ boundDeviceId: 'device-a' }, fixedDevice, 'ws-1')).toBe('device-b');
+ });
+
+ it('names no device when the fixed target is not a device', () => {
+ expect(
+ resolveRunDeviceId(
+ { boundDeviceId: 'device-a' },
+ { executionTarget: 'sandbox', executionTargetSelectionPolicy: 'fixed' },
+ 'ws-1',
+ ),
+ ).toBeUndefined();
+ });
+
+ it('ignores a fixed policy outside a workspace', () => {
+ // The policy is a workspace contract; a personal agent's own member
+ // preference is what its runs follow, so the task pin stands.
+ expect(resolveRunDeviceId({ boundDeviceId: 'device-a' }, fixedDevice)).toBe('device-a');
+ });
+});
diff --git a/apps/server/src/services/taskRunner/resolveRunExecution.ts b/apps/server/src/services/taskRunner/resolveRunExecution.ts
new file mode 100644
index 00000000000..541c12cec9e
--- /dev/null
+++ b/apps/server/src/services/taskRunner/resolveRunExecution.ts
@@ -0,0 +1,177 @@
+import type {
+ ChatTopicMetadata,
+ LobeAgentAgencyConfig,
+ TaskExecutionConfig,
+ WorkingDirConfig,
+} from '@lobechat/types';
+import { readTaskExecutionConfig } from '@lobechat/types';
+
+/**
+ * What a task's own execution selection contributes to ONE run.
+ *
+ * Kept separate from {@link TaskExecutionConfig} because the two answer
+ * different questions: the stored config says what the user picked, this says
+ * what the run should be told. Only the latter has to know that the device
+ * rides as `deviceId` and the directory as `initialTopicMetadata`.
+ */
+export interface TaskRunExecution {
+ /** `ExecAgentParams.deviceId` — pins the run's execution plan to this machine. */
+ deviceId?: string;
+ /** Stamped onto the topic this run creates; see `ExecAgentAppContext`. */
+ initialTopicMetadata?: {
+ repos?: string[];
+ workingDirectory?: string;
+ workingDirectoryConfig?: WorkingDirConfig;
+ };
+}
+
+/**
+ * The device a task's run will ACTUALLY use, once the assignee agent's own
+ * target policy has had its say.
+ *
+ * A workspace author can fix the agent's execution target
+ * (`executionTargetSelectionPolicy: 'fixed'`), and `turnSetup` then drops
+ * whatever device the run asks for and routes to the agent's own target
+ * instead (`effectiveRequestedDeviceId`, `topicBoundDeviceId`). This mirrors
+ * that derivation, because the task side has to tell a pin the run will use
+ * from one it will not — see `resolveTaskRunExecution`.
+ *
+ * `undefined` means the run does not land on a device at all (the sandbox).
+ */
+export const resolveRunDeviceId = (
+ execution: TaskExecutionConfig | undefined,
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ workspaceId?: string,
+): string | undefined => {
+ const isFixedSelection =
+ !!workspaceId && agencyConfig?.executionTargetSelectionPolicy === 'fixed';
+
+ // A member-selected target is exactly the task-level pin, so nothing replaces it.
+ if (!isFixedSelection) return execution?.boundDeviceId;
+
+ // Only a `device` fixed target names a machine; a fixed sandbox names none.
+ return agencyConfig?.executionTarget === 'device' ? agencyConfig.boundDeviceId : undefined;
+};
+
+/**
+ * Map a task's stored execution selection onto run parameters.
+ *
+ * Returns `undefined` when the task pins nothing, so callers spread it away and
+ * the run keeps the assignee agent's own target and cwd — the behaviour every
+ * task had before a task could carry a selection. Never returns an empty
+ * `initialTopicMetadata`: an empty object would still count as "client-supplied
+ * metadata" at the topic-creation site and change how the topic row is built.
+ */
+export const resolveTaskRunExecution = (
+ execution: TaskExecutionConfig | undefined,
+ /**
+ * The device this run will use — `resolveRunDeviceId`. Required, not optional:
+ * it decides whether the directory may travel, and a caller that forgot it
+ * would silently drop the directory of every pinned task.
+ */
+ runDeviceId: string | undefined,
+): TaskRunExecution | undefined => {
+ if (!execution) return undefined;
+
+ const { boundDeviceId, repos, workingDirectory, workingDirectoryConfig } = execution;
+
+ // Directory precedence: an explicit config, then an explicit path, then the
+ // primary repo. The last step mirrors the chat gateway, which also treats a
+ // repo selection as the run's directory (as a github repo) so a task that
+ // only picked repos still starts somewhere — the cloud repo surface has no
+ // absolute path to offer.
+ const deviceDirectory =
+ workingDirectoryConfig ?? (workingDirectory ? { path: workingDirectory } : undefined);
+
+ // A directory is picked FOR a machine — `TaskWorkingDirectoryChip` offers the
+ // run target's OWN directories — so it may only travel with that machine. When
+ // the run does not land on the pinned device (a fixed agent target replaced
+ // it, or the run goes to the sandbox), the path has to stay behind with the
+ // pin. Nothing downstream can catch it: the topic carries the EFFECTIVE
+ // device, so `resolveDeviceWorkingDirectoryConfig` sees matching run/topic
+ // device ids and accepts another machine's absolute path as this one's.
+ const isDeviceDirectoryUsable = !boundDeviceId || boundDeviceId === runDeviceId;
+
+ const directoryConfig: WorkingDirConfig | undefined =
+ (isDeviceDirectoryUsable ? deviceDirectory : undefined) ??
+ (repos && repos.length > 0 ? { path: repos[0], repoType: 'github' } : undefined);
+
+ const initialTopicMetadata = {
+ ...(repos && repos.length > 0 ? { repos } : {}),
+ ...(directoryConfig
+ ? { workingDirectory: directoryConfig.path, workingDirectoryConfig: directoryConfig }
+ : {}),
+ };
+
+ const runExecution: TaskRunExecution = {
+ ...(boundDeviceId ? { deviceId: boundDeviceId } : {}),
+ ...(Object.keys(initialTopicMetadata).length > 0 ? { initialTopicMetadata } : {}),
+ };
+
+ return Object.keys(runExecution).length > 0 ? runExecution : undefined;
+};
+
+/** The execution axes a topic carries, in the shape the readers expect. */
+const topicExecutionOf = (metadata?: ChatTopicMetadata | null): string =>
+ JSON.stringify({
+ boundDeviceId: metadata?.boundDeviceId ?? null,
+ repos: metadata?.repos ?? null,
+ workingDirectory: metadata?.workingDirectory ?? null,
+ workingDirectoryConfig: metadata?.workingDirectoryConfig ?? null,
+ });
+
+/**
+ * The execution metadata a CONTINUED topic has to carry before this run.
+ *
+ * A topic's own values outrank everything a later run brings: `turnSetup` stamps
+ * `initialTopicMetadata` only when it CREATES the topic, `heteroDispatch`'s cwd
+ * resolver reads `topic.metadata.workingDirectory` above the run's initial
+ * metadata (and above the agent's per-device pick and the device default), and
+ * `topic.metadata.boundDeviceId` is what project grouping and the client's
+ * worktree probes read. So a task retargeted since its topic was written would
+ * continue on the machine it now pins with the PREVIOUS machine's directory —
+ * a path that may not exist there — while the UI kept filing the topic under the
+ * old machine.
+ *
+ * The task's own selection is the one statement that covers EVERY run of it, so
+ * mirror it onto the topic before dispatching. Axes the task does not pin are
+ * CLEARED, because "inherit the agent" is a decision too: a pin the user removed
+ * must stop deciding where the run goes.
+ *
+ * Only a task that has EVER made a selection gets that treatment. A task with no
+ * `execution` block at all — every task written before this existed, and every
+ * one nobody pinned — never said anything about where it runs, so its topic's
+ * own device and directory stand: that is where the continued topic's CLI session
+ * and cwd live, and `turnSetup` keeps routing the continuation there. Clearing
+ * them would let a since-changed agent target move the run to another machine
+ * and lose the session. A selection the user cleared is still persisted (as
+ * `null` axes, see `toTaskExecutionConfigPatch`), so the two stay tellable apart.
+ *
+ * Returns `undefined` when there is nothing to write — the topic already agrees
+ * (the common case: a continuation should not pay for a write it does not need)
+ * or the task never selected anything.
+ */
+export const resolveTopicExecutionPatch = (
+ topicMetadata: ChatTopicMetadata | null | undefined,
+ /** The task's raw `config` — the block's PRESENCE matters, not only its values. */
+ taskConfig: null | Record<string, unknown> | undefined,
+ /** The device this run will use — see {@link resolveTaskRunExecution}. */
+ runDeviceId: string | undefined,
+): ChatTopicMetadata | undefined => {
+ const stored = taskConfig?.execution;
+ if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return undefined;
+
+ const execution = readTaskExecutionConfig(taskConfig);
+ const initial = resolveTaskRunExecution(execution, runDeviceId)?.initialTopicMetadata;
+
+ const next: ChatTopicMetadata = {
+ // `undefined` clears the axis: `TopicModel.updateMetadata` shallow-merges, so
+ // the key is dropped rather than kept at its previous value.
+ boundDeviceId: execution?.boundDeviceId,
+ repos: initial?.repos,
+ workingDirectory: initial?.workingDirectory,
+ workingDirectoryConfig: initial?.workingDirectoryConfig,
+ };
+
+ return topicExecutionOf(topicMetadata) === topicExecutionOf(next) ? undefined : next;
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 82f5dd443b2..12a08a2e1d1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2018,6 +2018,11 @@
"taskDetail.topicSource": "From {{identifier}}",
"taskDetail.untitled": "Untitled",
"taskDetail.updateFailed": "Failed to update task",
+ "taskExecution.fixedTip": "The execution environment is fixed in the Agent Profile.",
+ "taskExecution.followAgent": "Follow the agent",
+ "taskExecution.followAgentDesc": "Use the assignee agent's execution environment",
+ "taskExecution.runLocation": "Run location",
+ "taskExecution.workingDirectory": "Working directory",
"taskIntent.analyzing": "Reading…",
"taskIntent.answersHeading": "Clarifications",
"taskIntent.back": "Edit draft",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d66bfe97135..39aff427b69 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2018,6 +2018,11 @@
"taskDetail.topicSource": "来自 {{identifier}}",
"taskDetail.untitled": "无标题",
"taskDetail.updateFailed": "任务更新失败",
+ "taskExecution.fixedTip": "执行环境已在助理档案中固定。",
+ "taskExecution.followAgent": "跟随 Agent",
+ "taskExecution.followAgentDesc": "使用被指派 Agent 的执行环境",
+ "taskExecution.runLocation": "运行位置",
+ "taskExecution.workingDirectory": "工作目录",
"taskIntent.analyzing": "正在理解…",
"taskIntent.answersHeading": "补充说明",
"taskIntent.back": "返回修改",
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 1ca0ab2dd64..fb7b69bdd30 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -1,4 +1,9 @@
// @vitest-environment node
+import {
+ applyTaskReposSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+} from '@lobechat/types';
import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -1522,6 +1527,27 @@ describe('TaskModel', () => {
expect(config.checkpoint.topic.before).toBe(true);
});
+ it('keeps every key when config writers race on the same task', async () => {
+ // The run-location chip, the review/verify toggles and the model picker all
+ // merge into this one column. Without a lock both writers read the same
+ // snapshot and the later whole-column write drops the other's key.
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ await Promise.all([
+ model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch({ boundDeviceId: 'device-a' }),
+ }),
+ model.updateReviewConfig(task.id, { enabled: true }),
+ model.updateVerifyConfig(task.id, { enabled: true }),
+ ]);
+
+ const config = (await model.findById(task.id))!.config as Record<string, any>;
+ expect(config.execution?.boundDeviceId).toBe('device-a');
+ expect(config.review).toEqual({ enabled: true });
+ expect(config.verify).toEqual({ enabled: true });
+ });
+
it('should return null for non-existent task', async () => {
const model = new TaskModel(serverDB, userId);
const result = await model.updateTaskConfig('non-existent-id', { model: 'gpt-4' });
@@ -1821,6 +1847,200 @@ describe('TaskModel', () => {
expect(await model.getActivities(task.id)).toHaveLength(0);
});
+ it('merges a config patch under the lock instead of replacing the column', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({
+ automationMode: 'schedule',
+ instruction: 'Test',
+ schedulePattern: '0 9 * * *',
+ });
+ // Another tab / member saved a different key after this client loaded.
+ await model.updateTaskConfig(task.id, { checkpoint: { onAgentRequest: true } });
+
+ const updated = await model.updateWithLog(
+ task.id,
+ { schedulePattern: '0 18 * * *' },
+ { userId },
+ { configPatch: { schedule: { maxExecutions: 3 } } },
+ );
+
+ expect(updated!.config).toEqual({
+ checkpoint: { onAgentRequest: true },
+ schedule: { maxExecutions: 3 },
+ });
+ expect(updated!.schedulePattern).toBe('0 18 * * *');
+ const [activity] = await model.getActivities(task.id);
+ expect(activity.type).toBe('automation');
+ expect((activity.payload as any).to.maxExecutions).toBe(3);
+ });
+
+ it('drops the previous assignee cloud-repo selection when the task is reassigned', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_repos_a');
+ await createAgent('agt_repos_b');
+ const task = await model.create({ assigneeAgentId: 'agt_repos_a', instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ });
+
+ const updated = await model.updateWithLog(
+ task.id,
+ { assigneeAgentId: 'agt_repos_b' },
+ { userId },
+ );
+
+ // `repos` resolve against the assignee agent's provider env, so agent B
+ // must not inherit agent A's: every later run would start in a directory
+ // agent B cannot open.
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)).toBeUndefined();
+ expect((updated?.config as { execution: unknown }).execution).toEqual({
+ boundDeviceId: null,
+ repos: null,
+ workingDirectory: null,
+ workingDirectoryConfig: null,
+ });
+ });
+
+ it('keeps a machine-local selection across a reassignment', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_keep_a');
+ await createAgent('agt_keep_b');
+ const task = await model.create({ assigneeAgentId: 'agt_keep_a', instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch({
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ }),
+ });
+
+ const updated = await model.updateWithLog(
+ task.id,
+ { assigneeAgentId: 'agt_keep_b' },
+ { userId },
+ );
+
+ // A device pin and a path on that machine are the user's own, not the
+ // agent's — only the cloud-repo axis is tied to the assignee.
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)).toEqual({
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ });
+ });
+
+ it('keeps the repo selection when the assignee does not move', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_stable');
+ const task = await model.create({ assigneeAgentId: 'agt_stable', instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ });
+
+ const updated = await model.updateWithLog(task.id, { name: 'Renamed' }, { userId });
+
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)?.repos).toEqual([
+ 'lobehub/lobehub',
+ ]);
+ });
+
+ it('keeps the repos the runner fallback inherits, since nobody chose a new agent', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_fallback');
+ const task = await model.create({ instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ });
+
+ // The runner assigns the inbox agent to make an unassigned task runnable.
+ // Dropping the selection there would strip the directory the run is about
+ // to use, in the same breath as starting it.
+ const updated = await model.updateWithLog(task.id, { assigneeAgentId: 'agt_fallback' }, {});
+
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)?.repos).toEqual([
+ 'lobehub/lobehub',
+ ]);
+ });
+
+ it('keeps the execution this update states for the new assignee', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_stated_a');
+ await createAgent('agt_stated_b');
+ const task = await model.create({ assigneeAgentId: 'agt_stated_a', instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ });
+
+ const updated = await model.updateWithLog(
+ task.id,
+ {
+ assigneeAgentId: 'agt_stated_b',
+ config: {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/other']),
+ ),
+ },
+ },
+ { userId },
+ );
+
+ // Moving the assignee and naming a directory in one write means the new
+ // agent's run — the caller's intent, not a leftover to clean up.
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)?.repos).toEqual([
+ 'lobehub/other',
+ ]);
+ });
+
+ it('drops stale repos when a coordinator reassigns through the plain update', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_coord_a');
+ await createAgent('agt_coord_b');
+ const task = await model.create({ assigneeAgentId: 'agt_coord_a', instruction: 'Test' });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ });
+
+ // The goal coordinator's handoff / restart hands work on with a plain
+ // `update` — no activity row, and no second chance to clean up: the repos
+ // agent A's provider env resolved must not follow the task to agent B.
+ const updated = await model.update(task.id, { assigneeAgentId: 'agt_coord_b' });
+
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)).toBeUndefined();
+ });
+
+ it('keeps a machine-local selection when a coordinator reassigns', async () => {
+ const model = new TaskModel(serverDB, userId);
+ await createAgent('agt_coord_keep_a');
+ await createAgent('agt_coord_keep_b');
+ const task = await model.create({
+ assigneeAgentId: 'agt_coord_keep_a',
+ instruction: 'Test',
+ });
+ await model.updateTaskConfig(task.id, {
+ execution: toTaskExecutionConfigPatch({
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ }),
+ });
+
+ const updated = await model.update(task.id, { assigneeAgentId: 'agt_coord_keep_b' });
+
+ // A pin and a path on that machine are the user's own, not the previous
+ // assignee's to hand over — only the repo axis is tied to the agent.
+ expect(readTaskExecutionConfig(updated?.config as Record<string, unknown>)).toEqual({
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ });
+ });
+
it('records an actorless row for a system assignment', async () => {
const model = new TaskModel(serverDB, userId);
const task = await model.create({ instruction: 'Test' });
@@ -2904,6 +3124,37 @@ describe('TaskModel', () => {
expect((await model.findById(root.id))!.status).toBe('completed');
});
+ it('should drop the run location when the copy crosses into another scope', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const agentId = await createAgent('copy-execution-agent');
+ const root = await model.create({
+ assigneeAgentId: agentId,
+ config: {
+ execution: toTaskExecutionConfigPatch({
+ boundDeviceId: 'device-of-the-copier',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/Users/copier/code/lobehub',
+ workingDirectoryConfig: { path: '/Users/copier/code/lobehub', repoType: 'git' },
+ }),
+ review: { enabled: true },
+ },
+ instruction: 'Root',
+ name: 'Pinned task',
+ });
+
+ const { rootId } = await model.copyToWorkspace(root.id, wsId, userId);
+ const cloned = await new TaskModel(serverDB, userId, wsId).findById(rootId);
+
+ // The pin named a machine and a path in the SOURCE scope, and the repos
+ // were resolved by an assignee the clone does not have — none of it can be
+ // resolved by the destination's runs. The first assignment there cannot
+ // clean up after the fact either (it has no previous assignee to diff
+ // against), so the copy itself must not carry the selection over.
+ expect(readTaskExecutionConfig(cloned!.config as Record<string, unknown>)).toBeUndefined();
+ // …while the rest of the config still copies.
+ expect((cloned!.config as Record<string, any>).review.enabled).toBe(true);
+ });
+
it('should clone a workspace task into the personal scope (null target)', async () => {
const wsModel = new TaskModel(serverDB, userId, wsId);
const root = await wsModel.create({ instruction: 'WS Root' });
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 22418671465..b9355c17884 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -537,6 +537,24 @@ export class AgentModel {
return { model: row.model, provider: row.provider };
};
+ /**
+ * Single-SELECT lookup of an agent's `agencyConfig`.
+ *
+ * The task runner needs the target the agent would use on its own — and
+ * whether a workspace author FIXED it — to tell a task-level pin the run will
+ * use from one the runtime replaces (see `resolveRunDeviceId`). The enriched
+ * `getAgentConfig` would drag knowledge/file queries into every run.
+ */
+ getAgentAgencyConfig = async (idOrSlug: string): Promise<LobeAgentAgencyConfig | null> => {
+ const rows = await this.db
+ .select({ agencyConfig: agents.agencyConfig })
+ .from(agents)
+ .where(and(this.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
+ .limit(1);
+
+ return rows[0]?.agencyConfig ?? null;
+ };
+
/**
* Single-SELECT lookup of the fields `TaskService.createTask` needs in one
* round-trip: the model/provider snapshot (for `task.config`) and the
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 2310d571bec..9b25c5013f3 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -12,6 +12,12 @@ import type {
WorkspaceDocNode,
WorkspaceTreeNode,
} from '@lobechat/types';
+import {
+ clearTaskReposSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+ withoutTaskExecutionSelection,
+} from '@lobechat/types';
import {
and,
desc,
@@ -131,6 +137,49 @@ const normalizeTaskRefs = <
return normalized;
};
+/**
+ * The data to write when a task moves to another assignee, with the previous
+ * assignee's cloud-repo selection dropped in the same write.
+ *
+ * `repos` resolve against the assignee agent's provider env, so they belong to
+ * the agent they were picked for: carrying them to another agent leaves every
+ * later run pointing at a repository the new assignee cannot open. The
+ * machine-local axes (the device pin and a path on that machine) are the user's
+ * own and stay.
+ *
+ * Only a change of the AGENT counts, and only when the write does not state an
+ * execution of its own — a writer that moves the assignee AND names a directory
+ * is describing the new assignee's run on purpose. Returns `data` untouched when
+ * there is nothing to drop.
+ */
+const withStaleReposCleared = (
+ before: { assigneeAgentId: string | null; config: unknown },
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+): Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>> => {
+ // Nothing to drop for a task that had no assignee to begin with (the runner's
+ // "unassigned → inbox agent" fallback), nor for a write that keeps it.
+ if (!before.assigneeAgentId) return data;
+ if (data.assigneeAgentId === undefined || data.assigneeAgentId === before.assigneeAgentId) {
+ return data;
+ }
+
+ const statedExecution = (data.config as Record<string, unknown> | undefined)?.execution;
+ if (statedExecution !== undefined) return data;
+
+ const currentConfig = (before.config ?? {}) as Record<string, unknown>;
+ const cleared = clearTaskReposSelection(readTaskExecutionConfig(currentConfig));
+ if (cleared === readTaskExecutionConfig(currentConfig)) return data;
+
+ return {
+ ...data,
+ config: {
+ ...currentConfig,
+ ...(data.config as Record<string, unknown> | undefined),
+ execution: toTaskExecutionConfigPatch(cleared),
+ },
+ };
+};
+
export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {
const message = error instanceof Error ? error.message : String(error);
const code =
@@ -478,7 +527,37 @@ export class TaskModel {
): Promise<TaskItem | null> {
if (Object.keys(data).length === 0) return this.findById(id);
- const updated = await this.db
+ // A reassignment is not a plain column write: the row being moved away from
+ // decides whether the previous assignee's cloud-repo selection has to go,
+ // so read it under a lock — a config write landing between the read and the
+ // merge below would be lost. Every writer of the assignee column comes
+ // through here (`updateWithLog`, the update procedure, the coordinator's
+ // handoff/restart, the runner's inbox fallback), so this is the one place
+ // the invariant has to hold; `updateWithLog` locks its own read for the
+ // activity log and then delegates.
+ if (data.assigneeAgentId === undefined) return this.writeRow(this.db, id, data);
+
+ return this.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
+ const [before] = await runner
+ .select({ assigneeAgentId: tasks.assigneeAgentId, config: tasks.config })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), this.ownership()))
+ .for('update')
+ .limit(1);
+ if (!before) return null;
+
+ return this.writeRow(runner, id, withStaleReposCleared(before, data));
+ });
+ }
+
+ /** The column write itself — the assignee rule lives in `update`. */
+ private async writeRow(
+ db: LobeChatDatabase,
+ id: string,
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+ ): Promise<TaskItem | null> {
+ const updated = await db
.update(tasks)
.set({ ...normalizeTaskRefs(data), updatedAt: new Date() })
.where(and(eq(tasks.id, id), this.ownership()))
@@ -1382,15 +1461,40 @@ export class TaskModel {
/**
* Safely merge-update the task's config object.
- * Reads the current config, shallow-merges the incoming partial, and writes back.
+ * Reads the current config, deep-merges the incoming partial, and writes back.
+ *
+ * The read is taken under a row lock: several independent writers merge into
+ * this one column (model, run location, checkpoint, review, verify), and two
+ * of them reading the same snapshot would let the later whole-column write
+ * silently drop the other's key.
*/
async updateTaskConfig(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
- const task = await this.findById(id);
- if (!task) return null;
+ return this.rewriteConfig(id, (current) => merge(current, partial));
+ }
- const current = (task.config as Record<string, unknown>) || {};
- const config = merge(current, partial);
- return this.update(id, { config });
+ /**
+ * Read-modify-write of the `config` column under a row lock. Every writer that
+ * derives the next config from the current one must come through here, so two
+ * of them cannot read the same snapshot and drop each other's key.
+ */
+ private async rewriteConfig(
+ id: string,
+ next: (current: Record<string, any>) => Record<string, unknown>,
+ ): Promise<TaskItem | null> {
+ return this.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
+ const [task] = await runner
+ .select({ config: tasks.config })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), this.ownership()))
+ .for('update')
+ .limit(1);
+ if (!task) return null;
+
+ return this.writeRow(runner, id, {
+ config: next((task.config as Record<string, any>) || {}),
+ });
+ });
}
// ========== Context (runtime state) ==========
@@ -1487,18 +1591,16 @@ export class TaskModel {
id: string,
patch: { [K in keyof TaskVerifyConfig]?: TaskVerifyConfig[K] | null },
): Promise<TaskItem | null> {
- const task = await this.findById(id);
- if (!task) return null;
+ return this.rewriteConfig(id, (config) => {
+ const next: Record<string, any> = { ...(config.verify as TaskVerifyConfig | undefined) };
- const config = (task.config as Record<string, any>) || {};
- const next: Record<string, any> = { ...(config.verify as TaskVerifyConfig | undefined) };
-
- for (const [key, value] of Object.entries(patch)) {
- if (value === null) delete next[key];
- else if (value !== undefined) next[key] = value;
- }
+ for (const [key, value] of Object.entries(patch)) {
+ if (value === null) delete next[key];
+ else if (value !== undefined) next[key] = value;
+ }
- return this.update(id, { config: { ...config, verify: next } });
+ return { ...config, verify: next };
+ });
}
// Check if a task should pause after a topic completes
@@ -2092,8 +2194,18 @@ export class TaskModel {
id: string,
data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
actor: { agentId?: string | null; userId?: string | null },
+ options: {
+ /**
+ * Deep-merged into the `config` column under this update's row lock,
+ * instead of replacing it. A client that edits one key (the schedule
+ * cap) must not send back a whole-config snapshot that can predate
+ * another tab's or member's write of a different key.
+ */
+ configPatch?: Record<string, unknown>;
+ } = {},
): Promise<TaskItem | null> {
- const touched = TRACKED_TASK_COLUMNS.some((col) => data[col] !== undefined);
+ const { configPatch } = options;
+ const touched = !!configPatch || TRACKED_TASK_COLUMNS.some((col) => data[col] !== undefined);
// Nothing to diff against: an ordinary rename should not pay for a lock.
if (!touched) return this.update(id, data);
@@ -2118,7 +2230,21 @@ export class TaskModel {
if (!before) return null;
const scoped = new TaskModel(runner, this.userId, this.workspaceId);
- const updated = await scoped.update(id, data);
+
+ // The reassignment rule — dropping the previous assignee's cloud-repo
+ // selection — lives in `update`, which is the only writer of the assignee
+ // column, so this locked read is kept for the activity-log diff only and
+ // the write below re-checks the rule in the same transaction.
+ const writeData = configPatch
+ ? {
+ ...data,
+ config: merge(
+ ((data.config ?? before.config) as Record<string, unknown> | null) ?? {},
+ configPatch,
+ ),
+ }
+ : data;
+ const updated = await scoped.update(id, writeData);
if (!updated) return null;
const events: { payload: TaskActivityLogPayload; type: TaskActivityLogType }[] = [];
@@ -2379,7 +2505,14 @@ export class TaskModel {
assigneeAgentId: null,
assigneeUserId: null,
automationMode: original.automationMode,
- config: original.config ?? {},
+ // The run location is dropped the way the other cross-scope refs
+ // are: a pinned machine, a path on it and a repo set all name
+ // something in the scope this task came from, and the clone's first
+ // assignment cannot clean them up later (it has no previous assignee
+ // to diff against — see `updateWithLog`).
+ config: withoutTaskExecutionSelection(
+ original.config as null | Record<string, unknown>,
+ ),
context: {
...(original.context as Record<string, unknown>),
duplicatedFrom: original.id,
diff --git a/packages/database/src/schemas/task.ts b/packages/database/src/schemas/task.ts
index 36fe1197f78..c7d8fd15295 100644
--- a/packages/database/src/schemas/task.ts
+++ b/packages/database/src/schemas/task.ts
@@ -92,7 +92,7 @@ export const tasks = pgTable(
// Context & config (each task independent, no inheritance from parent)
context: jsonb('context').default({}),
- config: jsonb('config').default({}), // CheckpointConfig, ReviewConfig, etc.
+ config: jsonb('config').default({}), // CheckpointConfig, ReviewConfig, TaskExecutionConfig, etc.
error: text('error'),
// Visibility (mirrors agent.visibility semantics). Workspace-mode rows can be
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1c72bfc16c8..c95bebe3f4c 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -210,6 +210,11 @@ export default {
'goalProcess.deliverables.from': 'From “{{title}}”',
'goalProcess.deliverables.title': 'Deliverables',
'goalProcess.deliverables.untitled': 'Untitled',
+ 'taskExecution.fixedTip': 'The execution environment is fixed in the Agent Profile.',
+ 'taskExecution.followAgent': 'Follow the agent',
+ 'taskExecution.followAgentDesc': "Use the assignee agent's execution environment",
+ 'taskExecution.runLocation': 'Run location',
+ 'taskExecution.workingDirectory': 'Working directory',
'taskList.truncated': 'Showing the first {{loaded}} of {{total}} tasks',
'workingPanel.deployments.copy': 'Copy URL',
'workingPanel.deployments.copyDebugId': 'Copy debug ID',
diff --git a/packages/types/src/task/execution.test.ts b/packages/types/src/task/execution.test.ts
new file mode 100644
index 00000000000..990c5b48da2
--- /dev/null
+++ b/packages/types/src/task/execution.test.ts
@@ -0,0 +1,267 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyTaskDirectorySelection,
+ applyTaskReposSelection,
+ applyTaskTargetSelection,
+ clearTaskDirectorySelection,
+ clearTaskReposSelection,
+ hasTaskExecutionSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+ withoutTaskExecutionSelection,
+} from './execution';
+
+describe('readTaskExecutionConfig', () => {
+ it('returns nothing when the task carries no selection', () => {
+ expect(readTaskExecutionConfig(undefined)).toBeUndefined();
+ expect(readTaskExecutionConfig(null)).toBeUndefined();
+ expect(readTaskExecutionConfig({})).toBeUndefined();
+ expect(readTaskExecutionConfig({ model: 'gpt-4' })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: {} })).toBeUndefined();
+ });
+
+ it('reads back a pin and a working directory', () => {
+ expect(
+ readTaskExecutionConfig({
+ execution: {
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/Users/me/Code/lobehub',
+ workingDirectoryConfig: { path: '/Users/me/Code/lobehub', repoType: 'github' },
+ },
+ }),
+ ).toEqual({
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/Users/me/Code/lobehub',
+ workingDirectoryConfig: { path: '/Users/me/Code/lobehub', repoType: 'github' },
+ });
+ });
+
+ it('treats the nulls a patch writes as "inherit", not as values', () => {
+ expect(
+ readTaskExecutionConfig({ execution: toTaskExecutionConfigPatch(undefined) }),
+ ).toBeUndefined();
+ });
+
+ it('degrades malformed entries to inheritance instead of failing the run', () => {
+ expect(readTaskExecutionConfig({ execution: 'device-a' })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: ['device-a'] })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: { boundDeviceId: '' } })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: { boundDeviceId: 42 } })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: { repos: 'lobehub/lobehub' } })).toBeUndefined();
+ expect(readTaskExecutionConfig({ execution: { repos: ['', 'lobehub/lobehub'] } })).toEqual({
+ repos: ['lobehub/lobehub'],
+ });
+ // A working-directory config without a path cannot describe a directory.
+ expect(
+ readTaskExecutionConfig({ execution: { workingDirectoryConfig: { repoType: 'github' } } }),
+ ).toBeUndefined();
+ });
+});
+
+describe('hasTaskExecutionSelection', () => {
+ it('is false for nothing and for an object of empty values', () => {
+ expect(hasTaskExecutionSelection(undefined)).toBe(false);
+ expect(hasTaskExecutionSelection({})).toBe(false);
+ expect(hasTaskExecutionSelection({ boundDeviceId: undefined })).toBe(false);
+ });
+
+ it('is true as soon as one axis is set', () => {
+ expect(hasTaskExecutionSelection({ boundDeviceId: 'device-a' })).toBe(true);
+ expect(hasTaskExecutionSelection({ repos: ['lobehub/lobehub'] })).toBe(true);
+ });
+});
+
+describe('toTaskExecutionConfigPatch', () => {
+ it('writes every axis, because the task config is updated by a deep merge', () => {
+ // An omitted key would keep its previous value under the merge, so a
+ // cleared axis has to be written as an explicit null.
+ expect(toTaskExecutionConfigPatch(undefined)).toEqual({
+ boundDeviceId: null,
+ repos: null,
+ workingDirectory: null,
+ workingDirectoryConfig: null,
+ });
+ });
+
+ it('round-trips a selection through the reader', () => {
+ const execution = { boundDeviceId: 'device-a', repos: ['lobehub/lobehub'] };
+ expect(readTaskExecutionConfig({ execution: toTaskExecutionConfigPatch(execution) })).toEqual(
+ execution,
+ );
+ });
+});
+
+describe('directory axis', () => {
+ it('a repo selection writes the directory as a github repo', () => {
+ expect(applyTaskReposSelection({ boundDeviceId: 'device-a' }, ['lobehub/lobehub'])).toEqual({
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ workingDirectoryConfig: { path: 'lobehub/lobehub', repoType: 'github' },
+ });
+ });
+
+ it('a directory selection drops the repo — a path is not a repo', () => {
+ // The bug this guards: pinning a machine while keeping a repo selection
+ // stores a repo identifier as the run's directory on that machine.
+ expect(
+ applyTaskDirectorySelection(
+ { boundDeviceId: 'device-a', repos: ['lobehub/lobehub'] },
+ { path: '/srv/app' },
+ ),
+ ).toEqual({
+ boundDeviceId: 'device-a',
+ repos: undefined,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: { path: '/srv/app' },
+ });
+ });
+
+ it('pins the inherited machine a directory was picked on', () => {
+ // Following an agent bound to device-a: the path exists on device-a only,
+ // so it must not travel once the agent moves to another machine.
+ expect(applyTaskDirectorySelection(undefined, { path: '/srv/app' }, 'device-a')).toEqual({
+ boundDeviceId: 'device-a',
+ repos: undefined,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: { path: '/srv/app' },
+ });
+ // An explicit pin is the user's own and is never replaced.
+ expect(
+ applyTaskDirectorySelection({ boundDeviceId: 'device-b' }, { path: '/srv/app' }, 'device-a')
+ .boundDeviceId,
+ ).toBe('device-b');
+ // Clearing the directory pins nothing.
+ expect(applyTaskDirectorySelection(undefined, undefined, 'device-a').boundDeviceId).toBe(
+ undefined,
+ );
+ });
+
+ it('clearing the directory keeps the target', () => {
+ expect(
+ clearTaskDirectorySelection({
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: 'lobehub/lobehub',
+ }),
+ ).toEqual({
+ boundDeviceId: 'device-a',
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+});
+
+describe('applyTaskTargetSelection', () => {
+ it('clears the directory when the target really changes', () => {
+ const pinnedA = applyTaskReposSelection({ boundDeviceId: 'device-a' }, ['lobehub/lobehub']);
+
+ expect(applyTaskTargetSelection(pinnedA, 'device-b')).toEqual({
+ boundDeviceId: 'device-b',
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+
+ it('is a no-op when the target in force is re-picked', () => {
+ // A task following an agent bound to a device can hold a directory on that
+ // machine; clicking the checked row must not delete it.
+ const followingWithDirectory = applyTaskDirectorySelection(undefined, { path: '/srv/app' });
+ const pinnedA = applyTaskDirectorySelection(
+ { boundDeviceId: 'device-a' },
+ { path: '/srv/app' },
+ );
+
+ expect(applyTaskTargetSelection(followingWithDirectory, undefined)).toBe(
+ followingWithDirectory,
+ );
+ expect(applyTaskTargetSelection(pinnedA, 'device-a')).toBe(pinnedA);
+ expect(applyTaskTargetSelection(undefined, undefined)).toBeUndefined();
+ });
+
+ it('clears the directory when a pin starts following the agent again', () => {
+ const pinnedA = applyTaskDirectorySelection(
+ { boundDeviceId: 'device-a' },
+ { path: '/srv/app' },
+ );
+
+ expect(applyTaskTargetSelection(pinnedA, undefined)).toEqual({
+ boundDeviceId: undefined,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+});
+
+describe('clearTaskReposSelection', () => {
+ it('drops a repo selection together with the directory it wrote', () => {
+ // Reassigning a task must not carry the previous agent's repos into the new
+ // agent's runs — the identifier is resolved by that agent's provider env.
+ expect(
+ clearTaskReposSelection(
+ applyTaskReposSelection({ boundDeviceId: 'device-a' }, ['lobehub/lobehub']),
+ ),
+ ).toEqual({
+ boundDeviceId: 'device-a',
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ });
+ });
+
+ it('keeps a machine-local selection: a device pin and a path on that machine', () => {
+ const selection = applyTaskDirectorySelection(
+ { boundDeviceId: 'device-a' },
+ {
+ path: '/srv/app',
+ },
+ );
+
+ expect(clearTaskReposSelection(selection)).toBe(selection);
+ });
+
+ it('returns the input unchanged when there is nothing to drop', () => {
+ // Callers skip the write on reference equality, so this must not build a
+ // fresh object for a selection that has no repo axis.
+ const pin = { boundDeviceId: 'device-a' };
+
+ expect(clearTaskReposSelection(pin)).toBe(pin);
+ expect(clearTaskReposSelection(undefined)).toBeUndefined();
+ });
+});
+
+describe('withoutTaskExecutionSelection', () => {
+ it('drops the whole selection, keeping the rest of the config', () => {
+ // A cross-scope copy restarts from inheritance: the machine, the path on it
+ // and the assignee-resolved repos all belong to the scope the task came
+ // from, and the clone's first assignment cannot clear them later.
+ expect(
+ withoutTaskExecutionSelection({
+ execution: {
+ boundDeviceId: 'device-a',
+ repos: ['lobehub/lobehub'],
+ workingDirectory: '/Users/me/Code/lobehub',
+ },
+ model: 'gpt-4',
+ review: { enabled: true },
+ }),
+ ).toEqual({ model: 'gpt-4', review: { enabled: true } });
+ });
+
+ it('returns the input unchanged when there is nothing to drop', () => {
+ const config = { model: 'gpt-4' };
+
+ expect(withoutTaskExecutionSelection(config)).toBe(config);
+ });
+
+ it('degrades absent config to an empty one', () => {
+ expect(withoutTaskExecutionSelection(undefined)).toEqual({});
+ expect(withoutTaskExecutionSelection(null)).toEqual({});
+ });
+});
diff --git a/packages/types/src/task/execution.ts b/packages/types/src/task/execution.ts
new file mode 100644
index 00000000000..f4723daa852
--- /dev/null
+++ b/packages/types/src/task/execution.ts
@@ -0,0 +1,257 @@
+import type { WorkingDirConfig, WorkingDirRepoType } from '../device';
+
+/**
+ * Where a Task's runs execute — the machine and the working directory/repo set
+ * it is anchored to. Persisted under `tasks.config.execution`.
+ *
+ * A Task is long-lived and runs more than once (manual / schedule / heartbeat),
+ * so this selection cannot live on a topic (one per run) or in client state
+ * (unreadable from a scheduled tick) the way the chat composer's equivalent
+ * does. Stored on the task row, it is read by `TaskRunnerService.runTask` and
+ * handed to the run itself.
+ *
+ * Absent fields mean INHERIT, not "unset": a task with no `execution` block
+ * behaves exactly as tasks did before this existed — the assignee agent's own
+ * execution target and working directory decide. Clearing a field returns that
+ * axis to inheritance; it never means "run nowhere".
+ *
+ * Only the device axis is expressed as a pin. The run contract routes a device
+ * by id (`requestedDeviceId` forces device routing unless the agent's policy is
+ * `fixed`), and deliberately has no way to force the cloud sandbox, so a task
+ * can pin a machine but cannot override an agent's stored target to `sandbox`.
+ */
+export interface TaskExecutionConfig {
+ /**
+ * Device every run is pinned to. Absent → the assignee agent's own
+ * `agencyConfig` (execution target + bound device) decides. Ignored when the
+ * agent's `executionTargetSelectionPolicy` is `fixed` — an author-controlled
+ * target is not overridable, the same rule the chat picker follows.
+ */
+ boundDeviceId?: string;
+ /**
+ * Repos pre-selected for every run's topic. Feeds the agent's repo-aware
+ * surfaces; meaningful for cloud / heterogeneous agents whose available repos
+ * come from the agent's provider env.
+ */
+ repos?: string[];
+ /** Primary working directory every run starts in (device-bound runs). */
+ workingDirectory?: string;
+ /** Path + repo type written alongside {@link workingDirectory}. */
+ workingDirectoryConfig?: WorkingDirConfig;
+}
+
+const isNonEmptyString = (value: unknown): value is string =>
+ typeof value === 'string' && value.trim().length > 0;
+
+/**
+ * Read the execution selection out of a free-form task config.
+ *
+ * `tasks.config` is untyped jsonb written by several callers across releases,
+ * so this validates every field instead of trusting the shape — a malformed
+ * entry must degrade to "inherit", never to a broken run.
+ */
+export const readTaskExecutionConfig = (
+ config: null | Record<string, unknown> | undefined,
+): TaskExecutionConfig | undefined => {
+ const raw = config?.execution;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+
+ const { boundDeviceId, repos, workingDirectory, workingDirectoryConfig } = raw as Record<
+ string,
+ unknown
+ >;
+
+ const execution: TaskExecutionConfig = {};
+
+ if (isNonEmptyString(boundDeviceId)) execution.boundDeviceId = boundDeviceId;
+
+ if (Array.isArray(repos)) {
+ const validRepos = repos.filter(isNonEmptyString);
+ if (validRepos.length > 0) execution.repos = validRepos;
+ }
+
+ if (isNonEmptyString(workingDirectory)) execution.workingDirectory = workingDirectory;
+
+ if (workingDirectoryConfig && typeof workingDirectoryConfig === 'object') {
+ const { path, repoType } = workingDirectoryConfig as Record<string, unknown>;
+ if (isNonEmptyString(path)) {
+ execution.workingDirectoryConfig = {
+ path,
+ ...(isNonEmptyString(repoType) && { repoType: repoType as WorkingDirRepoType }),
+ };
+ }
+ }
+
+ return Object.keys(execution).length > 0 ? execution : undefined;
+};
+
+/**
+ * Whether this task pins anything of its own, i.e. does not purely inherit.
+ *
+ * Checks the values, not the key count: callers build the next selection by
+ * spreading the previous one (`{ ...value, boundDeviceId: undefined }` to
+ * unpin), so an object with every axis present but empty is the normal shape of
+ * "nothing selected" and must not be persisted as a selection.
+ */
+export const hasTaskExecutionSelection = (execution?: TaskExecutionConfig): boolean =>
+ !!execution &&
+ (!!execution.boundDeviceId ||
+ !!execution.workingDirectory ||
+ !!execution.workingDirectoryConfig ||
+ (execution.repos?.length ?? 0) > 0);
+
+/**
+ * Apply a repo selection to an execution selection, keeping the working
+ * directory in step.
+ *
+ * A repo selection IS the run's directory on the cloud surface, written exactly
+ * the way the chat composer writes it when the first message creates the topic
+ * (`workingDirectory` + a `github` config). Shared by every surface that offers
+ * the repo picker so a task set up from the task list and one set up from the
+ * task detail cannot end up with different stored shapes.
+ */
+export const applyTaskReposSelection = (
+ execution: TaskExecutionConfig | undefined,
+ repos?: string[],
+): TaskExecutionConfig => ({
+ ...execution,
+ repos,
+ workingDirectory: repos?.[0],
+ workingDirectoryConfig: repos?.[0] ? { path: repos[0], repoType: 'github' } : undefined,
+});
+
+/**
+ * Point the directory axis at an explicit directory on the run's machine.
+ *
+ * The device surface's counterpart of {@link applyTaskReposSelection}: there the
+ * directory is an absolute path on the device, so a repo selection is dropped —
+ * a repo identifier means nothing to a run that is not in the cloud sandbox.
+ *
+ * An absolute path belongs to one machine, so picking one also pins the machine
+ * it was picked on (`deviceId`, the run's effective device) when the task only
+ * inherited it from the agent. Without the pin the path carries no device
+ * affinity: once the agent moved to another machine, was reassigned, or was
+ * fixed to the sandbox, the next run would forward this machine's path there.
+ * With it, the runner drops the path whenever the run lands elsewhere.
+ */
+export const applyTaskDirectorySelection = (
+ execution: TaskExecutionConfig | undefined,
+ config?: WorkingDirConfig,
+ deviceId?: string,
+): TaskExecutionConfig => ({
+ ...execution,
+ ...(config && deviceId && !execution?.boundDeviceId ? { boundDeviceId: deviceId } : {}),
+ repos: undefined,
+ workingDirectory: config?.path,
+ workingDirectoryConfig: config,
+});
+
+/**
+ * Drop the cloud-repo axis, keeping a machine-local selection.
+ *
+ * A repo identifier is resolved by the assignee agent's provider env, so it
+ * belongs to the agent it was chosen for — the same identifier can be
+ * unavailable to another agent and leave the run with a directory it cannot
+ * open. Both assignee-change paths use this: picking another agent while
+ * creating a task, and reassigning an existing one (there the server applies it
+ * inside the write that moves the assignee, see `TaskModel.updateWithLog`).
+ *
+ * A device pin and a path on a machine are the user's own, so they survive the
+ * change — only the repo's own directory (written by
+ * {@link applyTaskReposSelection}) is dropped with it.
+ *
+ * Returns the SAME reference when there is nothing to drop, so callers can tell
+ * "nothing to do" without comparing fields.
+ */
+export const clearTaskReposSelection = (
+ execution?: TaskExecutionConfig,
+): TaskExecutionConfig | undefined =>
+ execution?.repos
+ ? {
+ ...execution,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ }
+ : execution;
+
+/**
+ * Drop the directory axis entirely.
+ *
+ * Used when the run's TARGET changes, because the two axes describe the same
+ * thing in different units: `lobehub/lobehub` is a cloud repo, `/srv/app` is a
+ * directory on one machine. Carrying either one across a target change would
+ * leave a selection that silently describes a machine the run is no longer on.
+ */
+export const clearTaskDirectorySelection = (
+ execution: TaskExecutionConfig | undefined,
+): TaskExecutionConfig => ({
+ ...execution,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+});
+
+/**
+ * Point the run-location axis at a machine, or back at the assignee's own target.
+ *
+ * Re-selecting the target already in force is a NO-OP — the same reference comes
+ * back — because the directory is dropped only when the target actually CHANGES:
+ * the two axes describe the same thing in different units (`lobehub/lobehub` is
+ * a cloud repo, `/srv/app` is a path on one machine), so a change invalidates the
+ * directory, while re-picking the checked row must not delete one the task
+ * legitimately keeps. That case is real: a task following an agent that is bound
+ * to a device can hold an explicit directory on that machine, and clicking the
+ * checked "Follow the agent" row — or the already-pinned device — used to wipe it.
+ */
+export const applyTaskTargetSelection = (
+ execution: TaskExecutionConfig | undefined,
+ deviceId?: string,
+): TaskExecutionConfig | undefined =>
+ deviceId === execution?.boundDeviceId
+ ? execution
+ : clearTaskDirectorySelection({ ...execution, boundDeviceId: deviceId });
+
+/**
+ * Drop the whole selection when a task's config moves into another scope.
+ *
+ * Every axis names something that only resolves where the task was set up: the
+ * machine belongs to the copier (or to the source workspace's pool), the path
+ * lives on that machine, and `repos` are resolved by the assignee agent a
+ * cross-scope copy does not carry over either. Dropping the selection restores
+ * plain inheritance, the only state a run in the destination can act on — the
+ * first assignment there cannot clean up after the fact, because it has no
+ * previous assignee to diff against (see `TaskModel.updateWithLog`).
+ *
+ * Returns the SAME config when there is nothing to drop, so a caller can tell
+ * "nothing to do" without comparing jsonb.
+ */
+export const withoutTaskExecutionSelection = (
+ config: null | Record<string, unknown> | undefined,
+): Record<string, unknown> => {
+ if (!config || config.execution === undefined) return config ?? {};
+
+ const { execution: _dropped, ...rest } = config;
+ return rest;
+};
+
+/**
+ * The persisted shape of an execution selection.
+ *
+ * Every axis is written explicitly and a cleared axis becomes `null`, because
+ * the task config is updated by a DEEP MERGE (`TaskModel.updateTaskConfig`):
+ * a key left out of the patch keeps its previous value, so an omitted axis
+ * would leave the old device/directory in place and the control would look
+ * like it did nothing. `null` is the "inherit" value the reader already
+ * ignores. Writers must go through this — `config` set via `task.update`
+ * replaces the whole column instead, taking model / brief / review /
+ * checkpoint with it.
+ */
+export const toTaskExecutionConfigPatch = (
+ execution?: TaskExecutionConfig,
+): Record<string, unknown> => ({
+ boundDeviceId: execution?.boundDeviceId ?? null,
+ repos: execution?.repos ?? null,
+ workingDirectory: execution?.workingDirectory ?? null,
+ workingDirectoryConfig: execution?.workingDirectoryConfig ?? null,
+});
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index a2a549832db..e5dcf5d2dfa 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -1,6 +1,8 @@
import type { BriefArtifacts } from '../brief';
import type { ChatFileItem } from '../message/ui/chat';
+export * from './execution';
+
// ── Task type aliases ──
export type TaskStatus =
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
index 8a7699f295a..97ec6cb7a31 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
@@ -8,6 +8,7 @@ import TaskDetailAssignee from './TaskDetailAssignee';
import { taskDetailLayoutStyles as styles } from './taskDetailLayoutStyles';
import TaskDetailRunPauseAction from './TaskDetailRunPauseAction';
import TaskDetailTitleInput from './TaskDetailTitleInput';
+import TaskExecutionConfig from './TaskExecutionConfig';
import TaskInstruction from './TaskInstruction';
import TaskModelConfig from './TaskModelConfig';
import TaskParentBar from './TaskParentBar';
@@ -31,6 +32,7 @@ const TaskDetailSections = memo(() => {
<TaskDetailRunPauseAction />
<TaskDetailAssignee />
<TaskModelConfig />
+ <TaskExecutionConfig />
</Flexbox>
</Flexbox>
<div className={styles.side}>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
new file mode 100644
index 00000000000..24162e0070f
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import type { TaskExecutionConfig } from '@lobechat/types';
+import { readTaskExecutionConfig } from '@lobechat/types';
+import { memo, useCallback, useMemo } from 'react';
+
+import { usePermission } from '@/hooks/usePermission';
+import { useTaskStore } from '@/store/task';
+import { taskDetailSelectors } from '@/store/task/selectors';
+
+import TaskExecutionControls from '../features/TaskExecutionControls';
+
+/**
+ * Where a task's runs go, on the task detail.
+ *
+ * Sits in the header's main column next to the assignee it inherits from, not
+ * in the properties rail: the run location is what the run action above it will
+ * do, and the directory follows from that target, so the three read as one
+ * cluster. The rail keeps the independent properties (status, priority,
+ * visibility, schedule).
+ *
+ * Read-only members still see it — knowing a task is pinned to another machine
+ * is exactly the context they need — with the controls inert.
+ */
+const TaskExecutionConfig = memo(() => {
+ const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
+ const assigneeAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
+ const taskConfig = useTaskStore((s) => taskDetailSelectors.activeTaskDetail(s)?.config);
+ const updateTaskExecution = useTaskStore((s) => s.updateTaskExecution);
+ const { allowed: canEditTask } = usePermission('create_content');
+
+ // Derived from the raw `config` reference so the reader runs once per config
+ // change: it builds a fresh object, which as a store selector would report a
+ // change on every unrelated update.
+ const execution = useMemo(() => readTaskExecutionConfig(taskConfig), [taskConfig]);
+
+ const handleChange = useCallback(
+ (next?: TaskExecutionConfig) => {
+ if (taskId) void updateTaskExecution(taskId, next);
+ },
+ [taskId, updateTaskExecution],
+ );
+
+ if (!assigneeAgentId) return null;
+
+ return (
+ <TaskExecutionControls
+ assigneeAgentId={assigneeAgentId}
+ disabled={!canEditTask}
+ value={execution}
+ onChange={handleChange}
+ />
+ );
+});
+
+TaskExecutionConfig.displayName = 'TaskExecutionConfig';
+
+export default TaskExecutionConfig;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
index 5b25e02691e..e1a9c523c97 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
@@ -138,6 +138,10 @@ const TaskProperties = memo(() => {
</AssigneeMemberSelector>
)}
+ {/* Where the runs go lives in the detail header's main column, next to the
+ assignee it inherits from — not in this rail. See
+ `TaskExecutionConfig`. */}
+
<TaskScheduleConfig>
<Block
clickable
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
index 0f4b608f1ad..4e78cc54a4f 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -177,6 +177,35 @@ vi.mock('../features/TaskPriorityTag', () => ({
),
}));
+/**
+ * The run-location / working-directory cluster talks to the device list, the
+ * workspace preference and the agent store. Stubbed here so this suite stays
+ * about the composer's own contract — which is that whatever the cluster hands
+ * over is what reaches `createTask`, and that an untouched composer sends
+ * nothing at all. The cluster's own rendering is covered by its own suite.
+ */
+const executionControlsMock = vi.hoisted(() => ({
+ value: undefined as undefined | { boundDeviceId?: string },
+}));
+
+vi.mock('../features/TaskExecutionControls', () => ({
+ default: ({
+ onChange,
+ value,
+ }: {
+ onChange: (execution?: { boundDeviceId?: string }) => void;
+ value?: { boundDeviceId?: string };
+ }) => {
+ executionControlsMock.value = value;
+ return (
+ <div data-pinned={value?.boundDeviceId ?? ''} data-testid="execution-controls">
+ <span data-testid="pin-device" onClick={() => onChange({ boundDeviceId: 'device-a' })} />
+ <span data-testid="unpin-device" onClick={() => onChange(undefined)} />
+ </div>
+ );
+ },
+}));
+
vi.mock('../features/AssigneeAgentSelector', () => ({
default: ({
children,
@@ -377,6 +406,68 @@ describe('CreateTaskInlineEntry', () => {
});
});
+ it('creates the task with no execution config when no run location is pinned', async () => {
+ editorMarkdownMock.value = 'Coordinate the release';
+ render(<CreateTaskInlineEntry variant="hero" />);
+
+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });
+
+ // The whole point of the contract: an untouched composer must create the
+ // ordinary task it always did — the run inherits the assignee agent.
+ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));
+ expect('config' in createTaskMock.mock.calls[0][0]).toBe(false);
+ });
+
+ it('sends the pinned device as the task execution config', async () => {
+ editorMarkdownMock.value = 'Coordinate the release';
+ render(<CreateTaskInlineEntry variant="hero" />);
+
+ fireEvent.click(screen.getByTestId('pin-device'));
+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });
+
+ await waitFor(() =>
+ expect(createTaskMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ config: {
+ execution: {
+ boundDeviceId: 'device-a',
+ repos: null,
+ workingDirectory: null,
+ workingDirectoryConfig: null,
+ },
+ },
+ }),
+ ),
+ );
+ });
+
+ it('keeps the pinned device in the draft and drops it when unpinned', async () => {
+ // The draft is only written once there is something to restore.
+ editorMarkdownMock.value = 'Coordinate the release';
+ const { rerender } = render(<CreateTaskInlineEntry variant="hero" />);
+ fireEvent.click(screen.getByTestId('pin-device'));
+
+ await waitFor(() => {
+ const draft = JSON.parse(
+ localStorage.getItem('lobehub:task-create-draft:workspace-1:all') || '{}',
+ );
+ expect(draft.execution).toEqual({ boundDeviceId: 'device-a' });
+ });
+
+ rerender(<CreateTaskInlineEntry placeholder="reload" variant="hero" />);
+ fireEvent.click(screen.getByTestId('unpin-device'));
+
+ await waitFor(() =>
+ expect(screen.getByTestId('execution-controls')).toHaveAttribute('data-pinned', ''),
+ );
+ await waitFor(() => {
+ const draft = JSON.parse(
+ localStorage.getItem('lobehub:task-create-draft:workspace-1:all') || '{}',
+ );
+ expect(draft.execution).toBeUndefined();
+ });
+ });
+
it('resets member assignment and draft persistence when the workspace changes', async () => {
editorMarkdownMock.value = 'Coordinate the release';
const { rerender } = render(<CreateTaskInlineEntry variant="hero" />);
@@ -405,6 +496,36 @@ describe('CreateTaskInlineEntry', () => {
});
});
+ it('drops the previous scope’s run location when the destination has no draft', async () => {
+ // The composer stays mounted across a workspace/agent switch, and the reset
+ // runs before the destination draft is read — a scope with no draft returns
+ // early, so the run location has to be part of the baseline. Otherwise the
+ // new scope inherits a device (or a directory) picked for the old one and
+ // creates its task there, where it may not even be reachable.
+ editorMarkdownMock.value = 'Coordinate the release';
+ const { rerender } = render(<CreateTaskInlineEntry variant="hero" />);
+
+ fireEvent.click(screen.getByTestId('pin-device'));
+ await waitFor(() =>
+ expect(screen.getByTestId('execution-controls')).toHaveAttribute('data-pinned', 'device-a'),
+ );
+
+ activeWorkspaceMock.id = 'workspace-3';
+ // The real workspace hook publishes a store update. Change one prop here as
+ // well so the memoized test component observes the mocked hook value.
+ rerender(<CreateTaskInlineEntry placeholder="Empty workspace" variant="hero" />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId('execution-controls')).toHaveAttribute('data-pinned', ''),
+ );
+ await waitFor(() => {
+ const draft = JSON.parse(
+ localStorage.getItem('lobehub:task-create-draft:workspace-3:all') || '{}',
+ );
+ expect(draft.execution).toBeUndefined();
+ });
+ });
+
it('drops an incompatible restored member when the assigned agent is private', async () => {
localStorage.setItem(
'lobehub:task-create-draft:workspace-1:all',
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index 5dbdfdec3b7..cfd0a981800 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -1,7 +1,8 @@
'use client';
import { canWorkspaceRoleBeTaskAssignee } from '@lobechat/const/rbac';
-import type { TaskIntentAnalysis } from '@lobechat/types';
+import type { TaskExecutionConfig, TaskIntentAnalysis } from '@lobechat/types';
+import { readTaskExecutionConfig, toTaskExecutionConfigPatch } from '@lobechat/types';
import { useEditor } from '@lobehub/editor/react';
import { Block, DropdownMenu, Flexbox } from '@lobehub/ui';
import { ActionIcon, Button, Text, toast } from '@lobehub/ui/base-ui';
@@ -34,6 +35,7 @@ import AssigneeAgentSelector from '../features/AssigneeAgentSelector';
import AssigneeAvatar from '../features/AssigneeAvatar';
import AssigneeMemberSelector from '../features/AssigneeMemberSelector';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
+import TaskExecutionControls from '../features/TaskExecutionControls';
import TaskPriorityTag from '../features/TaskPriorityTag';
import TaskVisibilityChipLabel from '../features/TaskVisibilityChipLabel';
import TaskVisibilityTag from '../features/TaskVisibilityTag';
@@ -117,6 +119,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const [assigneeUserId, setAssigneeUserId] = useState<string | undefined>();
const [instruction, setInstruction] = useState('');
const [hasAttachments, setHasAttachments] = useState(false);
+ // Where this task will run, if not simply wherever the assignee agent runs.
+ // Undefined = inherit; it is only sent when the user actually pinned
+ // something, so an untouched composer creates exactly what it used to.
+ const [execution, setExecution] = useState<TaskExecutionConfig | undefined>();
// Default to workspace-visible (or the parent's visibility for subtasks).
// In personal mode the chip is hidden and the value is never sent.
const [visibility, setVisibility] = useState<'private' | 'public'>(defaultVisibility);
@@ -180,6 +186,19 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const handleAgentChange = useCallback((nextAgentId: string | null) => {
setAssigneeAgentId(nextAgentId ?? undefined);
+ // The repo list is the assignee's own (its provider env), so a selection
+ // made for the previous agent must not silently carry over to another one.
+ // A pinned device is the user's machine and stays valid across agents.
+ setExecution((current) =>
+ current?.repos
+ ? {
+ ...current,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ }
+ : current,
+ );
}, []);
const handleMemberChange = useCallback((nextUserId: string | null) => {
setAssigneeUserId(nextUserId ?? undefined);
@@ -217,10 +236,15 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
if (draftHydratedKey === draftStorageKey) return;
setDraftHydratedKey(draftStorageKey);
- // Reset to baseline for the new scope before hydrating.
+ // Reset to baseline for the new scope before hydrating. The run location is
+ // part of that baseline: a device or directory picked for the previous
+ // scope's agents may not even be reachable in the new one, and this
+ // component stays mounted across the switch (the `return` below skips
+ // hydration only — it must not keep the previous scope's selection).
editor.cleanDocument?.();
setPriority(0);
setVisibility(defaultVisibility);
+ setExecution(undefined);
if (!lockAssignee) setAssigneeAgentId(agentId);
setAssigneeUserId(undefined);
@@ -235,6 +259,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const draft = JSON.parse(raw) as {
assigneeAgentId?: string;
assigneeUserId?: string;
+ execution?: unknown;
markdown?: string;
priority?: number;
visibility?: 'private' | 'public';
@@ -242,6 +267,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
if (draft.markdown) editor.setDocument?.('markdown', draft.markdown);
if (typeof draft.priority === 'number') setPriority(draft.priority);
if (!lockAssignee && draft.assigneeAgentId) setAssigneeAgentId(draft.assigneeAgentId);
+ // Re-validated rather than trusted: the draft is a browser string that a
+ // previous release (or another tab) may have written in another shape, and
+ // a malformed run location must degrade to "inherit", never reach a create.
+ setExecution(readTaskExecutionConfig({ execution: draft.execution }));
if (
draft.assigneeUserId &&
(!activeWorkspaceId || assignableMemberIds.has(draft.assigneeUserId))
@@ -280,6 +309,9 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// `lockAssignee` locks only the scoped Agent. The responsible
// member remains an independent draft field and must survive reloads.
assigneeUserId,
+ // `undefined` (the whole selection is `undefined`) drops the key, so
+ // an untouched composer writes the same draft shape as before.
+ execution,
markdown,
priority,
visibility,
@@ -294,6 +326,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
draftHydratedKey,
draftStorageKey,
editor,
+ execution,
instruction,
lockAssignee,
priority,
@@ -327,6 +360,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
setAssigneeAgentId(agentId);
setAssigneeUserId(undefined);
setInstruction('');
+ setExecution(undefined);
setVisibility(defaultVisibility);
setAnalysis(null);
setIntentAnswers({});
@@ -391,6 +425,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const result = await createTask({
assigneeAgentId,
assigneeUserId,
+ // Only present when the user pinned a run location / directory. Left
+ // out otherwise so the task inherits the assignee agent entirely,
+ // which is what tasks did before they could carry a selection.
+ ...(execution ? { config: { execution: toTaskExecutionConfigPatch(execution) } } : {}),
editorData: draft.editorJson,
instruction: draft.instruction,
name: draft.name,
@@ -463,6 +501,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
assigneeAgentId,
assigneeUserId,
createTask,
+ execution,
navigate,
onCreated,
parentTaskId,
@@ -816,6 +855,13 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
</AssigneeAgentSelector>
)}
+ <TaskExecutionControls
+ assigneeAgentId={assigneeAgentId}
+ disabled={!canCreateTask}
+ value={execution}
+ onChange={setExecution}
+ />
+
<ActionIcon
icon={Paperclip}
size={'small'}
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index c766e6c8c95..de3d1286422 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -1,5 +1,7 @@
'use client';
+import type { TaskExecutionConfig } from '@lobechat/types';
+import { toTaskExecutionConfigPatch } from '@lobechat/types';
import { useEditor } from '@lobehub/editor/react';
import { Block, Flexbox } from '@lobehub/ui';
import { ActionIcon, Button, Text, toast, useModalContext } from '@lobehub/ui/base-ui';
@@ -24,6 +26,7 @@ import AssigneeAgentSelector from '../features/AssigneeAgentSelector';
import AssigneeAvatar from '../features/AssigneeAvatar';
import AssigneeMemberSelector from '../features/AssigneeMemberSelector';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
+import TaskExecutionControls from '../features/TaskExecutionControls';
import TaskPriorityTag from '../features/TaskPriorityTag';
import TaskVisibilityChipLabel from '../features/TaskVisibilityChipLabel';
import TaskVisibilityTag from '../features/TaskVisibilityTag';
@@ -64,6 +67,10 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const [priority, setPriority] = useState(0);
const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);
const [assigneeUserId, setAssigneeUserId] = useState<string | undefined>();
+ // Where this task will run, if not simply wherever the assignee runs.
+ // Undefined = inherit, and then nothing is sent, so an untouched modal
+ // creates exactly the task it always did.
+ const [execution, setExecution] = useState<TaskExecutionConfig | undefined>();
// Default to workspace-visible: workspace tasks are team work by default,
// and going private stays one click away. In personal mode the field is
// irrelevant and the chip is hidden anyway.
@@ -95,6 +102,19 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const handleAgentChange = useCallback((nextAgentId: string | null) => {
setAssigneeAgentId(nextAgentId ?? undefined);
+ // The repo list belongs to the assignee (its provider env), so a
+ // selection made for the previous agent must not carry over. A pinned
+ // device is the user's machine and stays valid across agents.
+ setExecution((current) =>
+ current?.repos
+ ? {
+ ...current,
+ repos: undefined,
+ workingDirectory: undefined,
+ workingDirectoryConfig: undefined,
+ }
+ : current,
+ );
}, []);
const handleMemberChange = useCallback((nextUserId: string | null) => {
setAssigneeUserId(nextUserId ?? undefined);
@@ -129,6 +149,9 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const result = await createTask({
assigneeAgentId,
assigneeUserId,
+ // Only present when the user pinned a run location / directory —
+ // otherwise the task inherits the assignee agent entirely.
+ ...(execution ? { config: { execution: toTaskExecutionConfigPatch(execution) } } : {}),
editorData: editorJson,
instruction: instruction || title.trim(),
name: title.trim() || undefined,
@@ -155,6 +178,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
assigneeUserId,
canCreateTask,
close,
+ execution,
createTask,
editor,
onCreated,
@@ -347,6 +371,13 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
</TaskVisibilityTag>
)}
+ <TaskExecutionControls
+ assigneeAgentId={assigneeAgentId}
+ disabled={!canCreateTask}
+ value={execution}
+ onChange={setExecution}
+ />
+
<ActionIcon
icon={Paperclip}
title={t('upload.action.tooltip')}
diff --git a/src/features/AgentTasks/features/TaskDeviceChip.tsx b/src/features/AgentTasks/features/TaskDeviceChip.tsx
new file mode 100644
index 00000000000..883dab43e0a
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskDeviceChip.tsx
@@ -0,0 +1,221 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { Block, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { CheckIcon, ChevronDownIcon, FolderIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatLockedControlTooltip } from '@/features/ChatInput/utils/lockedControlTooltip';
+import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+
+import { taskExecutionStyles as styles } from './taskExecutionStyles';
+import TaskPickerOption from './TaskPickerOption';
+import { deviceLabel, useTaskRunTarget } from './useTaskRunTarget';
+
+interface TaskDeviceChipProps {
+ /** The assignee whose execution environment is inherited when nothing is pinned. */
+ agentId: string;
+ /**
+ * Row class for the trigger. Omitted → the composer's compact chip; the task
+ * detail's header row passes its own chip-sized class instead.
+ */
+ className?: string;
+ /**
+ * The directory the run will use, rendered as a muted line inside the popover.
+ * The directory axis is only choosable for some targets, so for the rest the
+ * state has to be legible HERE — next to the target that determines it —
+ * instead of nowhere.
+ */
+ directoryHint?: string;
+ disabled?: boolean;
+ /** Pinned device, or `undefined` to inherit the assignee agent's target. */
+ onChange: (deviceId: string | undefined) => void;
+ value?: string;
+}
+
+/**
+ * Where a task's runs execute.
+ *
+ * Deliberately NOT a copy of the composer's five-option execution-target
+ * picker: the run contract can only express "pin this machine"
+ * (`requestedDeviceId` forces device routing), and has no way to force the
+ * cloud sandbox over an agent's stored target. So the two honest choices are
+ * "inherit the agent" and "pin a device" — offering "Cloud Sandbox" as a third
+ * row would be a control that silently does nothing whenever the agent's own
+ * target is a device.
+ *
+ * The machines are listed flat. There are at most a handful, they are all the
+ * same kind of thing, and the grouping our chat picker needs (personal vs the
+ * workspace pool, where a workspace agent's list is *filtered* by group) has no
+ * counterpart here — a task pins a specific machine the user can see.
+ */
+const TaskDeviceChip = memo<TaskDeviceChipProps>(
+ ({ agentId, className, directoryHint, disabled, onChange, value }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+
+ const { canSelect, devices, inheritedLabel, inheritedTarget, isPending, pinnedDeviceId } =
+ useTaskRunTarget(agentId, value);
+
+ // The agent's policy is author-controlled: the server's resolver would drop
+ // this pin, so the control must not pretend it can set one.
+ const isLocked = disabled || isPending || !canSelect;
+
+ // Read the EFFECTIVE pin, never the raw prop: an author-fixed policy makes
+ // the run side drop a requested device, and showing the stored one would
+ // name a machine this task's runs never reach.
+ const pinned = pinnedDeviceId
+ ? devices?.find((device) => device.deviceId === pinnedDeviceId)
+ : undefined;
+ const unknownLabel = t('heteroAgent.executionTarget.unknownDevice');
+ const isInheriting = !pinnedDeviceId;
+ // A pin whose device is not in the pool at all — unshared, deleted, or
+ // enrolled under another identity — must still read as a PINNED run:
+ // falling back to the inherited label would describe a target the run does
+ // not use, and would hide the one control that can clear it. While the list
+ // is still loading that is indistinguishable from "not here yet", so the
+ // inherited label stays until it settles.
+ const pinnedLabel = pinned
+ ? deviceLabel(pinned, unknownLabel)
+ : isPending
+ ? inheritedLabel
+ : unknownLabel;
+
+ const handleSelect = useCallback(
+ (deviceId: string | undefined) => {
+ if (isLocked) return;
+ onChange(deviceId);
+ setOpen(false);
+ },
+ [isLocked, onChange],
+ );
+
+ const renderDeviceRow = (device: DeviceListItem) => {
+ const isActive = device.deviceId === pinnedDeviceId;
+ return (
+ <TaskPickerOption
+ checked={isActive}
+ disabled={isLocked}
+ key={device.deviceId}
+ onSelect={() => handleSelect(device.deviceId)}
+ >
+ <ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{deviceLabel(device, unknownLabel)}</div>
+ <div className={styles.rowDesc}>
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t('heteroAgent.executionTarget.offline')}
+ online={device.online}
+ onlineLabel={t('heteroAgent.executionTarget.online')}
+ />
+ </div>
+ </Flexbox>
+ {isActive && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+ );
+ };
+
+ const content = (
+ <Flexbox
+ aria-label={t('taskExecution.runLocation')}
+ gap={4}
+ role={'group'}
+ style={{ minWidth: 280 }}
+ >
+ <div className={styles.sectionTitle}>{t('taskExecution.runLocation')}</div>
+ <TaskPickerOption
+ checked={isInheriting}
+ disabled={isLocked}
+ onSelect={() => handleSelect(undefined)}
+ >
+ <ExecutionTargetIcon target={inheritedTarget} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{t('taskExecution.followAgent')}</div>
+ <div className={styles.rowDesc}>
+ {`${t('taskExecution.followAgentDesc')} · ${inheritedLabel}`}
+ </div>
+ </Flexbox>
+ {isInheriting && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+
+ {isPending && (
+ <div className={styles.sectionTitle}>{t('heteroAgent.executionTarget.loading')}</div>
+ )}
+ {!isPending && devices && devices.length > 0 && (
+ <div className={styles.scroll}>{devices.map(renderDeviceRow)}</div>
+ )}
+ {!isPending && devices?.length === 0 && (
+ <div className={styles.emptyHint}>{t('heteroAgent.executionTarget.noDevices')}</div>
+ )}
+
+ {directoryHint && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.hint}
+ gap={4}
+ style={{ paddingBlock: 6 }}
+ >
+ <Icon icon={FolderIcon} size={12} />
+ <span>{t('taskExecution.workingDirectory')}</span>
+ <span className={styles.hintValue}>· {directoryHint}</span>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+
+ const chip = (
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={cx(className ?? styles.chip, isLocked && styles.triggerDisabled)}
+ gap={6}
+ variant={'borderless'}
+ >
+ {pinnedDeviceId ? (
+ <ExecutionTargetIcon devicePlatform={pinned?.platform} target={'device'} />
+ ) : (
+ <ExecutionTargetIcon target={inheritedTarget} />
+ )}
+ <Text ellipsis className={styles.chipLabel} fontSize={12}>
+ {pinnedDeviceId ? pinnedLabel : inheritedLabel}
+ </Text>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </Block>
+ );
+
+ if (isLocked) {
+ return (
+ <Tooltip
+ title={formatLockedControlTooltip(
+ t('taskExecution.runLocation'),
+ t('taskExecution.fixedTip'),
+ )}
+ >
+ {chip}
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Popover
+ content={content}
+ open={open}
+ placement="bottomLeft"
+ styles={{ content: { padding: 4 } }}
+ trigger="click"
+ onOpenChange={setOpen}
+ >
+ {chip}
+ </Popover>
+ );
+ },
+);
+
+TaskDeviceChip.displayName = 'TaskDeviceChip';
+
+export default TaskDeviceChip;
diff --git a/src/features/AgentTasks/features/TaskExecutionControls.tsx b/src/features/AgentTasks/features/TaskExecutionControls.tsx
new file mode 100644
index 00000000000..ff203b89caa
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskExecutionControls.tsx
@@ -0,0 +1,165 @@
+'use client';
+
+import type { TaskExecutionConfig, WorkingDirConfig } from '@lobechat/types';
+import {
+ applyTaskDirectorySelection,
+ applyTaskReposSelection,
+ applyTaskTargetSelection,
+ getWorkingDirEffectivePath,
+ hasTaskExecutionSelection,
+} from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { FolderIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useEffectiveAgentMode } from '@/features/ChatInput/hooks/useEffectiveAgentMode';
+import {
+ getWorkingDirectoryName,
+ getWorkingDirectoryPathString,
+} from '@/helpers/workingDirectoryPath';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+import TaskDeviceChip from './TaskDeviceChip';
+import { taskExecutionStyles as styles } from './taskExecutionStyles';
+import TaskRepoChip from './TaskRepoChip';
+import TaskWorkingDirectoryChip from './TaskWorkingDirectoryChip';
+import { useTaskRunTarget } from './useTaskRunTarget';
+
+interface TaskExecutionControlsProps {
+ /** The assignee whose execution environment a task inherits by default. */
+ assigneeAgentId?: string;
+ disabled?: boolean;
+ onChange: (execution?: TaskExecutionConfig) => void;
+ /** The task's current selection; empty means "inherit the agent". */
+ value?: TaskExecutionConfig;
+}
+
+/**
+ * Where this task will run, next to the other task properties.
+ *
+ * Two axes, and the second one is decided by the first:
+ *
+ * - **run location** — pin a machine, or follow the assignee agent.
+ * - **working directory** — expressed in the units of the target the run lands
+ * on: an absolute path when it lands on a machine, a cloud repo identifier
+ * when it lands in the sandbox. When the target leaves nothing choosable the
+ * directory is reported as a muted line instead of an interactive control.
+ *
+ * Everything the task leaves unset falls back to the assignee agent, so a task
+ * created without touching either axis behaves exactly as tasks did before this
+ * existed. Changing the target clears the directory, because the two describe
+ * the same thing in different units — a leftover selection would be a path the
+ * cloud run cannot use, or a repo name nothing on the machine resolves. Re-picking
+ * the target already in force is a no-op, so the checked row never deletes a
+ * directory the task holds.
+ */
+const TaskExecutionControls = memo<TaskExecutionControlsProps>((props) => {
+ const { assigneeAgentId } = props;
+ if (!assigneeAgentId) return null;
+ return <TaskExecutionControlsInner {...props} assigneeAgentId={assigneeAgentId} />;
+});
+
+const TaskExecutionControlsInner = memo<
+ Omit<TaskExecutionControlsProps, 'assigneeAgentId'> & { assigneeAgentId: string }
+>(({ assigneeAgentId, disabled, onChange, value }) => {
+ const { t } = useTranslation('chat');
+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(assigneeAgentId));
+ const { isAgentRuntimeMode, isPreferenceLoading } = useEffectiveAgentMode(assigneeAgentId);
+ // Heterogeneous agents always execute somewhere; a plain agent only has an
+ // execution environment in agent mode (chat mode means "no tools, no device").
+ // Same gate the chat composer uses for this cluster.
+ const canExecuteSomewhere = isHetero || isAgentRuntimeMode;
+
+ const target = useTaskRunTarget(assigneeAgentId, value?.boundDeviceId);
+
+ // Both callbacks funnel through here so callers only ever receive `undefined`
+ // ("inherit everything") or a selection with at least one real axis set —
+ // never an object of empty values that would be persisted as a no-op.
+ const emit = useCallback(
+ (next?: TaskExecutionConfig) => {
+ onChange(next && hasTaskExecutionSelection(next) ? next : undefined);
+ },
+ [onChange],
+ );
+
+ const handleDeviceChange = useCallback(
+ (deviceId?: string) => {
+ const next = applyTaskTargetSelection(value, deviceId);
+ // Re-picking the target already in force is a no-op: the directory is
+ // dropped on a target CHANGE, and a no-op that cleared it would delete a
+ // directory the task legitimately holds (an explicit directory on an
+ // agent-bound device, or the checked "Follow the agent" row).
+ if (next === value) return;
+ emit(next);
+ },
+ [emit, value],
+ );
+
+ const handleReposChange = useCallback(
+ (repos?: string[]) => {
+ emit(applyTaskReposSelection(value, repos));
+ },
+ [emit, value],
+ );
+
+ const handleDirectoryChange = useCallback(
+ (config?: WorkingDirConfig) => {
+ // The path lives on the run's machine; pin it so the directory never
+ // travels to another target the agent later moves to.
+ emit(applyTaskDirectorySelection(value, config, target.deviceId));
+ },
+ [emit, target.deviceId, value],
+ );
+
+ if (isPreferenceLoading || !canExecuteSomewhere) return null;
+
+ // What the run actually starts in: the task's own choice first, then the
+ // chain the runtime falls back to. Shown as the muted hint so "inherit" is
+ // legible as a concrete directory instead of a black box.
+ const selectedDirectory =
+ getWorkingDirEffectivePath(value?.workingDirectoryConfig) ??
+ getWorkingDirectoryPathString(value?.workingDirectory);
+ const effectiveDirectory = selectedDirectory ?? target.inheritedDirectory?.path;
+ const directorySummary = effectiveDirectory
+ ? (getWorkingDirectoryName(effectiveDirectory) ?? effectiveDirectory)
+ : t('taskExecution.followAgent');
+
+ return (
+ <>
+ <TaskDeviceChip
+ agentId={assigneeAgentId}
+ directoryHint={directorySummary}
+ disabled={disabled}
+ value={value?.boundDeviceId}
+ onChange={handleDeviceChange}
+ />
+ {target.directoryKind === 'device' && target.deviceId ? (
+ <TaskWorkingDirectoryChip
+ deviceId={target.deviceId}
+ disabled={disabled}
+ value={value?.workingDirectoryConfig}
+ onChange={handleDirectoryChange}
+ />
+ ) : target.directoryKind === 'repo' ? (
+ <TaskRepoChip
+ agentId={assigneeAgentId}
+ disabled={disabled}
+ value={value?.repos}
+ onChange={handleReposChange}
+ />
+ ) : (
+ <Flexbox horizontal align={'center'} className={styles.hint} gap={4}>
+ <Icon icon={FolderIcon} size={12} />
+ <span>{t('taskExecution.workingDirectory')}</span>
+ <span className={styles.hintValue}>· {directorySummary}</span>
+ </Flexbox>
+ )}
+ </>
+ );
+});
+
+TaskExecutionControlsInner.displayName = 'TaskExecutionControls.Inner';
+
+export default TaskExecutionControls;
diff --git a/src/features/AgentTasks/features/TaskPickerOption.tsx b/src/features/AgentTasks/features/TaskPickerOption.tsx
new file mode 100644
index 00000000000..c8443a85290
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskPickerOption.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { type ReactNode } from 'react';
+
+import { taskExecutionStyles as styles } from './taskExecutionStyles';
+
+interface TaskPickerOptionProps {
+ /**
+ * Selection state, reported as `aria-pressed`. Omit it for a row that TRIGGERS
+ * something instead of holding a state (the directory picker's "add folder"):
+ * the row is still a button, it just has nothing to be "on".
+ */
+ checked?: boolean;
+ children: ReactNode;
+ disabled?: boolean;
+ onSelect: () => void;
+}
+
+/**
+ * A selectable row inside a task picker popover.
+ *
+ * A real `<button>`, because these rows used to be plain `Flexbox` divs with an
+ * `onClick`: no role, no tab stop and no activation key, so a keyboard user
+ * could open a picker and then had no way to choose or clear anything in it. The
+ * native element gives the row its semantics, its focus stop and Enter/Space
+ * activation for free, in the one place the device, repository and directory
+ * pickers share — so they cannot drift apart into three different keyboard
+ * stories again.
+ *
+ * `aria-pressed` reports the selection. It fits both shapes these lists take
+ * (one-of for a run target, many-of for repositories), so one row serves both
+ * instead of each picker inventing its own state semantics.
+ */
+export const TaskPickerOption = ({
+ checked,
+ children,
+ disabled,
+ onSelect,
+}: TaskPickerOptionProps) => (
+ <button
+ aria-pressed={checked === undefined ? undefined : checked}
+ className={`${styles.row} ${checked ? styles.rowActive : ''}`}
+ disabled={disabled}
+ type={'button'}
+ onClick={onSelect}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ {children}
+ </Flexbox>
+ </button>
+);
+
+export default TaskPickerOption;
diff --git a/src/features/AgentTasks/features/TaskRepoChip.tsx b/src/features/AgentTasks/features/TaskRepoChip.tsx
new file mode 100644
index 00000000000..43c2f19a260
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskRepoChip.tsx
@@ -0,0 +1,182 @@
+'use client';
+
+import { Github } from '@lobehub/icons';
+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { Checkbox, Text } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { CheckIcon, ChevronDownIcon, SquircleDashed } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatLockedControlTooltip } from '@/features/ChatInput/utils/lockedControlTooltip';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+import { taskExecutionStyles as styles } from './taskExecutionStyles';
+import TaskPickerOption from './TaskPickerOption';
+
+interface TaskRepoChipProps {
+ /** The assignee whose configured repos are offered. */
+ agentId: string;
+ /**
+ * Row class for the trigger. Omitted → the composer's compact chip; the task
+ * detail's header row passes its own chip-sized class instead.
+ */
+ className?: string;
+ disabled?: boolean;
+ /** Selected repos, or `undefined` to inherit (the agent's own directory). */
+ onChange: (repos: string[] | undefined) => void;
+ value?: string[];
+}
+
+const getRepoName = (repo: string) => repo.split('/').findLast(Boolean) || repo;
+
+/**
+ * The working directory a task's runs start in, expressed as a repo selection.
+ *
+ * Only offered when the run lands in the cloud sandbox — the caller decides
+ * that from the task's TARGET, because a repo identifier is the directory only
+ * there. On a machine the directory is a path, and a repo name stored as one
+ * would be a value the run cannot use.
+ *
+ * Reads the same source the chat composer's repo switcher does — the agent's
+ * `heterogeneousProvider.env.GITHUB_REPOS` — so the two surfaces cannot offer
+ * different repo sets for the same agent. An empty selection means "inherit":
+ * the run falls back to the agent's per-device directory and then the device
+ * default.
+ */
+const TaskRepoChip = memo<TaskRepoChipProps>(
+ ({ agentId, className, disabled, onChange, value }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+
+ const availableRepos: string[] = useAgentStore((s) => {
+ const env = agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.env;
+ try {
+ return JSON.parse(env?.GITHUB_REPOS ?? '[]');
+ } catch {
+ return [];
+ }
+ });
+
+ // Memoized so `toggleRepo` stays stable — `value ?? []` would mint a new
+ // array on every render and invalidate the callback each time.
+ const selected = useMemo(() => value ?? [], [value]);
+
+ const toggleRepo = useCallback(
+ (repo: string) => {
+ if (disabled) return;
+ const next = selected.includes(repo)
+ ? selected.filter((item) => item !== repo)
+ : [...selected, repo];
+ // An empty selection is inheritance, not "no directory" — collapse it
+ // back to undefined so only the intent is persisted.
+ onChange(next.length > 0 ? next : undefined);
+ },
+ [disabled, onChange, selected],
+ );
+
+ // No configured repos means no repo surface for this agent at all — better
+ // absent than an empty picker that can only ever say "nothing here".
+ if (availableRepos.length === 0) return null;
+
+ const chipLabel =
+ selected.length === 0
+ ? t('taskExecution.followAgent')
+ : selected.length === 1
+ ? getRepoName(selected[0])
+ : t('heteroAgent.cloudRepo.multiSelected', { count: selected.length });
+
+ const content = (
+ <Flexbox
+ aria-label={t('heteroAgent.cloudRepo.sectionTitle')}
+ gap={4}
+ role={'group'}
+ style={{ minWidth: 280 }}
+ >
+ <div className={styles.sectionTitle}>{t('heteroAgent.cloudRepo.sectionTitle')}</div>
+ <TaskPickerOption
+ checked={selected.length === 0}
+ disabled={disabled}
+ onSelect={() => onChange(undefined)}
+ >
+ <Icon className={styles.icon} icon={SquircleDashed} size={16} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{t('taskExecution.followAgent')}</div>
+ <div className={styles.rowDesc}>{t('taskExecution.followAgentDesc')}</div>
+ </Flexbox>
+ {selected.length === 0 && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+ <div className={styles.scroll}>
+ {availableRepos.map((repo) => {
+ const isChecked = selected.includes(repo);
+ return (
+ <TaskPickerOption
+ checked={isChecked}
+ disabled={disabled}
+ key={repo}
+ onSelect={() => toggleRepo(repo)}
+ >
+ {/* The row is the control; the box reports the state. Rendered
+ through the design-system checkbox so the glyph, the corner
+ and the contrast follow the theme instead of a hand-rolled
+ box that only looked right in one of them. */}
+ <span className={styles.checkboxSlot}>
+ <Checkbox checked={isChecked} />
+ </span>
+ <span className={styles.icon}>
+ <Github size={16} />
+ </span>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{getRepoName(repo)}</div>
+ <div className={styles.rowDesc}>{repo}</div>
+ </Flexbox>
+ </TaskPickerOption>
+ );
+ })}
+ </div>
+ </Flexbox>
+ );
+
+ // The muted directory trigger, not a chip — see `directoryTrigger`.
+ const trigger = (
+ <div className={cx(className ?? styles.directoryTrigger, disabled && styles.triggerDisabled)}>
+ {selected.length > 0 ? <Github size={14} /> : <Icon icon={SquircleDashed} size={14} />}
+ <Text ellipsis className={styles.chipLabel} fontSize={12}>
+ {chipLabel}
+ </Text>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
+
+ if (disabled) {
+ return (
+ <Tooltip
+ title={formatLockedControlTooltip(
+ t('taskExecution.workingDirectory'),
+ t('taskExecution.fixedTip'),
+ )}
+ >
+ {trigger}
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Popover
+ content={content}
+ open={open}
+ placement="bottomLeft"
+ styles={{ content: { padding: 4 } }}
+ trigger="click"
+ onOpenChange={setOpen}
+ >
+ {trigger}
+ </Popover>
+ );
+ },
+);
+
+TaskRepoChip.displayName = 'TaskRepoChip';
+
+export default TaskRepoChip;
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
new file mode 100644
index 00000000000..e59bc5c536e
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
@@ -0,0 +1,214 @@
+'use client';
+
+import type { WorkingDirConfig, WorkingDirEntry } from '@lobechat/types';
+import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';
+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { CheckIcon, ChevronDownIcon, FolderPlusIcon, SquircleDashed } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
+import { formatLockedControlTooltip } from '@/features/ChatInput/utils/lockedControlTooltip';
+import { openAddWorkingDirModal } from '@/features/WorkingDirectory';
+import {
+ getWorkingDirectoryName,
+ getWorkingDirectoryPathString,
+} from '@/helpers/workingDirectoryPath';
+import { deviceService } from '@/services/device';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+
+import { taskExecutionStyles as styles } from './taskExecutionStyles';
+import TaskPickerOption from './TaskPickerOption';
+
+interface TaskWorkingDirectoryChipProps {
+ /** Row class for the trigger. Omitted → the composer's compact chip. */
+ className?: string;
+ /** The machine this task's runs land on — the picker offers ITS directories. */
+ deviceId: string;
+ disabled?: boolean;
+ /** Selected directory, or `undefined` to inherit the agent's own. */
+ onChange: (config?: WorkingDirConfig) => void;
+ value?: WorkingDirConfig;
+}
+
+/**
+ * The directory a task's runs start in, for a run pinned to a machine.
+ *
+ * This is the device-side counterpart of {@link TaskRepoChip}, and which of the
+ * two a task gets is decided by its TARGET, never by taste: a run on a machine
+ * starts in an absolute path on that machine, so offering a cloud repo
+ * identifier here would store a value the run cannot use.
+ *
+ * Recents are the device's own (`device.workingDirs`) — the same list the chat
+ * composer's picker reads — and a new one is added through the shared modal,
+ * which validates the path against that device when it can reach it.
+ */
+const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
+ ({ className, deviceId, disabled, onChange, value }) => {
+ const { t } = useTranslation('chat');
+ const { t: tDevice } = useTranslation('device');
+ const [open, setOpen] = useState(false);
+
+ const rawRecents = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(deviceId));
+ const rawDeviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(deviceId));
+ const deviceDefaultCwd = getWorkingDirectoryPathString(rawDeviceDefaultCwd);
+
+ const recents = useMemo(
+ () => rawRecents.filter((entry) => !!getWorkingDirectoryPathString(entry.path)),
+ [rawRecents],
+ );
+
+ const selectedPath = getWorkingDirEffectivePath(value);
+
+ const apply = useCallback(
+ (config?: WorkingDirConfig) => {
+ onChange(config);
+ setOpen(false);
+ },
+ [onChange],
+ );
+
+ const handlePick = useCallback(
+ (entry: WorkingDirEntry) => {
+ const path = getWorkingDirectoryPathString(entry.path);
+ if (!path) return;
+ apply({ path, ...(entry.repoType && { repoType: entry.repoType }) });
+ },
+ [apply],
+ );
+
+ const handleAdd = useCallback(() => {
+ setOpen(false);
+ openAddWorkingDirModal({
+ defaultPath: selectedPath ?? deviceDefaultCwd,
+ deviceId,
+ onSubmit: async (path) => {
+ // An unreachable device returns null; that is "can't verify", not
+ // "wrong", so the path is accepted without a repoType rather than
+ // blocked — the same rule the chat picker follows.
+ const result = await deviceService.statPath(deviceId, path).catch(() => undefined);
+ if (result) {
+ if (!result.exists) return tDevice('workingDirectory.pathNotExist');
+ if (!result.isDirectory) return tDevice('workingDirectory.pathNotDirectory');
+ }
+ onChange({ path, ...(result?.repoType && { repoType: result.repoType }) });
+ return undefined;
+ },
+ });
+ }, [deviceDefaultCwd, deviceId, onChange, selectedPath, tDevice]);
+
+ const chipLabel = selectedPath
+ ? (getWorkingDirectoryName(selectedPath) ?? selectedPath)
+ : t('taskExecution.followAgent');
+
+ const content = (
+ <Flexbox
+ aria-label={t('taskExecution.workingDirectory')}
+ gap={4}
+ role={'group'}
+ style={{ maxWidth: 'calc(100vw - 48px)', width: 320 }}
+ >
+ <div className={styles.sectionTitle}>{t('taskExecution.workingDirectory')}</div>
+ <TaskPickerOption
+ checked={!selectedPath}
+ disabled={disabled}
+ onSelect={() => apply(undefined)}
+ >
+ <Icon className={styles.icon} icon={SquircleDashed} size={16} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{t('taskExecution.followAgent')}</div>
+ <div className={styles.rowDesc}>{t('taskExecution.followAgentDesc')}</div>
+ </Flexbox>
+ {!selectedPath && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+ <div className={styles.scroll}>
+ {recents.length === 0 ? (
+ <div className={styles.emptyHint}>
+ {t('workingDirectory.noRecent', { ns: 'device' })}
+ </div>
+ ) : (
+ recents.map((entry) => {
+ const path = getWorkingDirectoryPathString(entry.path)!;
+ const isActive = path === selectedPath;
+ const isDefault =
+ !!deviceDefaultCwd && getWorkingDirSourcePath(entry) === deviceDefaultCwd;
+ return (
+ <TaskPickerOption
+ checked={isActive}
+ disabled={disabled}
+ key={entry.path}
+ onSelect={() => handlePick(entry)}
+ >
+ <DirIcon repoType={entry.repoType} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <div className={styles.rowTitle}>{getWorkingDirectoryName(path) ?? path}</div>
+ {isDefault && (
+ <span className={styles.badge}>
+ {t('workingDirectory.defaultBadge', { ns: 'device' })}
+ </span>
+ )}
+ </Flexbox>
+ <div className={styles.rowDesc}>{path}</div>
+ </Flexbox>
+ {isActive && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+ );
+ })
+ )}
+ </div>
+ <TaskPickerOption disabled={disabled} onSelect={() => handleAdd()}>
+ <Icon className={styles.icon} icon={FolderPlusIcon} size={16} />
+ <div className={styles.rowTitle}>{t('workingDirectory.addFolder', { ns: 'device' })}</div>
+ </TaskPickerOption>
+ </Flexbox>
+ );
+
+ // The muted directory trigger, not a chip — see `directoryTrigger`.
+ const trigger = (
+ <div className={cx(className ?? styles.directoryTrigger, disabled && styles.triggerDisabled)}>
+ {selectedPath ? (
+ <DirIcon repoType={value?.repoType} size={14} />
+ ) : (
+ <Icon icon={SquircleDashed} size={14} />
+ )}
+ <Text ellipsis className={styles.chipLabel} fontSize={12}>
+ {chipLabel}
+ </Text>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
+
+ if (disabled) {
+ return (
+ <Tooltip
+ title={formatLockedControlTooltip(
+ t('taskExecution.workingDirectory'),
+ t('taskExecution.fixedTip'),
+ )}
+ >
+ {trigger}
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Popover
+ content={content}
+ open={open}
+ placement="bottomLeft"
+ styles={{ content: { padding: 4 } }}
+ trigger="click"
+ onOpenChange={setOpen}
+ >
+ {trigger}
+ </Popover>
+ );
+ },
+);
+
+TaskWorkingDirectoryChip.displayName = 'TaskWorkingDirectoryChip';
+
+export default TaskWorkingDirectoryChip;
diff --git a/src/features/AgentTasks/features/taskExecutionStyles.ts b/src/features/AgentTasks/features/taskExecutionStyles.ts
new file mode 100644
index 00000000000..244a184aea6
--- /dev/null
+++ b/src/features/AgentTasks/features/taskExecutionStyles.ts
@@ -0,0 +1,217 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+/**
+ * Shared look for the task-side execution chips (run location + working
+ * directory) and their popover rows.
+ *
+ * They live in one module for the reason the chat side keeps `gitChipStyles`:
+ * the two chips sit next to each other in the same bar, so any drift between
+ * two copies of these rules reads as a rendering bug rather than a choice.
+ */
+export const taskExecutionStyles = createStaticStyles(({ css }) => ({
+ /**
+ * The compact chip used in the create composer's action bar. A caller that
+ * wants its own row idiom (the task detail's properties rail does) passes a
+ * class of its own instead — the two then never fight over the same box,
+ * which inline sizing and a caller class would.
+ */
+ chip: css`
+ flex: none;
+
+ height: 24px;
+ padding-block: 3px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+ `,
+ chipLabel: css`
+ overflow: hidden;
+ max-width: 160px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ /**
+ * The directory axis' trigger — deliberately NOT the chip the run location
+ * wears.
+ *
+ * Where a run goes is the task's one real decision; the directory follows from
+ * that target and is inherited most of the time. Giving the two the same
+ * weight reads as two equal choices. This is the muted text affordance the
+ * chat composer's own directory / repo pickers use, so the two surfaces agree
+ * on the hierarchy as well.
+ */
+ directoryTrigger: css`
+ cursor: pointer;
+
+ display: flex;
+ flex: none;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ padding-block: 2px;
+ padding-inline: 6px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ check: css`
+ flex: none;
+ margin-inline-start: auto;
+ color: ${cssVar.colorPrimary};
+ `,
+ /** Provenance tag on a directory row (the device's own default). */
+ badge: css`
+ flex: none;
+
+ padding-inline: 5px;
+ border-radius: 999px;
+
+ font-size: 10px;
+ line-height: 15px;
+ color: ${cssVar.colorTextTertiary};
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ /**
+ * Slot for the design-system checkbox in a clickable row: the ROW is the
+ * control, so the box must not take the click a second time.
+ */
+ checkboxSlot: css`
+ pointer-events: none;
+ display: inline-flex;
+ flex: none;
+ `,
+ emptyHint: css`
+ padding-block: 12px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ text-align: center;
+ `,
+ /**
+ * A selection the task does NOT own, reported rather than offered.
+ *
+ * The directory axis follows the target: on a machine it is a path, in the
+ * cloud it is a repo, and when the task's target leaves nothing choosable the
+ * honest answer is a muted line saying what the run will use — not an
+ * interactive chip that looks like it can change something.
+ */
+ hint: css`
+ display: flex;
+ flex: none;
+ gap: 4px;
+ align-items: center;
+
+ min-width: 0;
+ padding-inline: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ white-space: nowrap;
+ `,
+ hintValue: css`
+ overflow: hidden;
+ max-width: 200px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ icon: css`
+ flex: none;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ /**
+ * A trigger the caller may not use (no edit permission, or the agent's
+ * execution environment is author-fixed). Dimmed and cursor-stopped so a chip
+ * that cannot open its picker does not read as one that can.
+ */
+ triggerDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.55;
+
+ &:hover {
+ background: transparent;
+ }
+ `,
+ /**
+ * A picker row. Rendered on a native `<button>` (see `TaskPickerOption`), so
+ * the reset below is what keeps it looking like the plain row it replaced:
+ * without it the platform's button chrome, centring and font would show
+ * through the popover.
+ *
+ * No focus style here: the design system draws one global keyboard ring
+ * (`ConfigProvider` installs it) around whatever is focused, so a local
+ * outline would only draw a second ring inside it.
+ */
+ row: css`
+ cursor: pointer;
+
+ display: block;
+
+ box-sizing: border-box;
+ width: 100%;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border: none;
+ border-radius: ${cssVar.borderRadius};
+
+ font: inherit;
+ color: inherit;
+ text-align: start;
+
+ background: transparent;
+
+ transition: background-color 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ }
+ `,
+ rowActive: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ rowDesc: css`
+ overflow: hidden;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextDescription};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ rowTitle: css`
+ overflow: hidden;
+
+ font-size: 13px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ scroll: css`
+ overflow-y: auto;
+ max-height: 320px;
+ `,
+ sectionTitle: css`
+ padding-block: 6px 2px;
+ padding-inline: 8px;
+
+ font-size: 11px;
+ font-weight: 500;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+}));
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.test.ts b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
new file mode 100644
index 00000000000..cc10832a017
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
@@ -0,0 +1,201 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskRunTarget } from './useTaskRunTarget';
+
+const DEVICE_AGENT_BOUND = 'device-agent-bound';
+const DEVICE_TASK_PIN = 'device-task-pin';
+
+const PERSONAL_DEVICE = { deviceId: 'device-personal', scope: 'personal' } as const;
+const WORKSPACE_DEVICE = {
+ deviceId: 'device-workspace',
+ scope: 'workspace',
+ visibility: 'public',
+} as const;
+
+const mocks = vi.hoisted(() => ({
+ agency: {
+ agencyConfig: {} as Record<string, unknown>,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: false,
+ },
+ /**
+ * What the hook resolves when it applies the ACTIVE chat topic's machine
+ * binding (no `topicId: null`), standing in for an open conversation bound
+ * to a different device than the agent.
+ */
+ activeTopicAgency: undefined as undefined | { agencyConfig: Record<string, unknown> },
+ agentState: { agentMap: {} as Record<string, { workspaceId?: string }> },
+ devices: [] as { deviceId: string; scope?: string; visibility?: string }[],
+ deviceState: { defaultCwd: {} as Record<string, string>, workingDirs: {} as Record<string, []> },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+ useDeviceList: () => ({ data: mocks.devices, isLoading: false }),
+}));
+
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: (_agentId?: string, options: { topicId?: string | null } = {}) =>
+ options.topicId === null || !mocks.activeTopicAgency
+ ? mocks.agency
+ : { ...mocks.agency, ...mocks.activeTopicAgency },
+}));
+
+vi.mock('@/helpers/gatewayMode', () => ({
+ useIsGatewayModeEnabled: () => false,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) =>
+ selector({ agentMap: mocks.agentState.agentMap, localAgentWorkingDirectoryMap: {} }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: { isAgentHeterogeneousById: () => () => true },
+}));
+
+vi.mock('@/store/device', () => ({
+ deviceSelectors: {
+ getDeviceDefaultCwd: (deviceId?: string) => (state: (typeof mocks)['deviceState']) =>
+ state.defaultCwd[deviceId ?? ''],
+ getDeviceWorkingDirs: (deviceId?: string) => (state: (typeof mocks)['deviceState']) =>
+ state.workingDirs[deviceId ?? ''] ?? [],
+ },
+ useDeviceStore: (selector: (state: (typeof mocks)['deviceState']) => unknown) =>
+ selector(mocks.deviceState),
+}));
+
+const deviceBoundAgent = {
+ boundDeviceId: DEVICE_AGENT_BOUND,
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+};
+
+beforeEach(() => {
+ mocks.activeTopicAgency = undefined;
+ mocks.agency.agencyConfig = {};
+ mocks.agency.canSelectExecutionTarget = true;
+ mocks.agency.isPreferenceLoading = false;
+ mocks.agentState.agentMap = {};
+ mocks.devices = [];
+ mocks.deviceState = { defaultCwd: {}, workingDirs: {} };
+});
+
+describe('useTaskRunTarget', () => {
+ // A task's runs never carry the open chat topic's binding, so the machine
+ // shown for a task must not follow whatever conversation happens to be active.
+ it('ignores the active chat topic device binding', () => {
+ mocks.agency.agencyConfig = deviceBoundAgent;
+ mocks.activeTopicAgency = {
+ agencyConfig: { ...deviceBoundAgent, boundDeviceId: 'device-chat-topic' },
+ };
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
+ });
+
+ it('offers the directory control when the machine comes from the AGENT, not the task', () => {
+ // The machine the run lands on may be the assignee's own bound device. This
+ // used to report `none`, so the task showed a non-interactive hint and had
+ // no way to pick a directory even though the runner supports one.
+ mocks.agency.agencyConfig = deviceBoundAgent;
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
+ expect(result.current.directoryKind).toBe('device');
+ expect(result.current.pinnedDeviceId).toBeUndefined();
+ });
+
+ it('ignores a task pin the run side would drop for a fixed selection policy', () => {
+ // `resolveExecutionPlan` clears `requestedDeviceId` when the policy is
+ // fixed, so showing that pin would name a machine the run never reaches —
+ // and would offer that machine's paths, which still reach the topic.
+ mocks.agency.agencyConfig = {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+ mocks.agency.canSelectExecutionTarget = false;
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+
+ expect(result.current.pinnedDeviceId).toBeUndefined();
+ expect(result.current.isDeviceTarget).toBe(false);
+ expect(result.current.deviceId).not.toBe(DEVICE_TASK_PIN);
+ expect(result.current.directoryKind).not.toBe('device');
+ });
+
+ it('falls back to the agent device when a pin is dropped by a fixed policy', () => {
+ mocks.agency.agencyConfig = deviceBoundAgent;
+ mocks.agency.canSelectExecutionTarget = false;
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+
+ expect(result.current.pinnedDeviceId).toBeUndefined();
+ expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
+ });
+
+ it('honours a task pin when the policy allows selection', () => {
+ mocks.agency.agencyConfig = {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+
+ expect(result.current.pinnedDeviceId).toBe(DEVICE_TASK_PIN);
+ expect(result.current.isDeviceTarget).toBe(true);
+ expect(result.current.effectiveTarget).toBe('device');
+ expect(result.current.deviceId).toBe(DEVICE_TASK_PIN);
+ expect(result.current.directoryKind).toBe('device');
+ });
+
+ it('offers a workspace agent only the workspace pool', () => {
+ // A deviceId carries the identity it was enrolled under, so a personal
+ // machine is not resolvable by a workspace agent's run — and a Task's
+ // scheduled runs use the workspace principal, not the member looking at it.
+ // The pin itself still stands (the run routes to it), which is why the chip
+ // has to render it as a device rather than silently falling back.
+ mocks.agentState.agentMap = { 'agent-1': { workspaceId: 'ws-1' } };
+ mocks.devices = [PERSONAL_DEVICE, WORKSPACE_DEVICE];
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', PERSONAL_DEVICE.deviceId));
+
+ expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
+ WORKSPACE_DEVICE.deviceId,
+ ]);
+ expect(result.current.pinnedDeviceId).toBe(PERSONAL_DEVICE.deviceId);
+ });
+
+ it('offers a shared task only public workspace devices', () => {
+ // Automated runs execute as the task's creator, who cannot resolve a
+ // colleague's private workspace device — so a private row is not pinnable.
+ mocks.agentState.agentMap = { 'agent-1': { workspaceId: 'ws-1' } };
+ mocks.devices = [
+ { deviceId: 'device-private', scope: 'workspace', visibility: 'private' },
+ WORKSPACE_DEVICE,
+ ];
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
+ WORKSPACE_DEVICE.deviceId,
+ ]);
+ });
+
+ it('offers an agent outside a workspace only its own machines', () => {
+ mocks.devices = [PERSONAL_DEVICE, WORKSPACE_DEVICE];
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
+ PERSONAL_DEVICE.deviceId,
+ ]);
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.ts b/src/features/AgentTasks/features/useTaskRunTarget.ts
new file mode 100644
index 00000000000..f9341749fca
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts
@@ -0,0 +1,203 @@
+'use client';
+
+import { isDesktop } from '@lobechat/const';
+import type { DeviceExecutionTarget, DeviceListItem, WorkingDirConfig } from '@lobechat/types';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { resolveWorkspaceSurface } from '@/features/ChatInput/ControlBar/useWorkspaceSurface';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import { devicePoolForAgent, devicePoolForTask } from '@/features/ExecutionTargetPicker';
+import { resolveAgentWorkingDirectoryConfig } from '@/helpers/agentWorkingDirectory';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+
+export type DeviceLabelSource = Pick<DeviceListItem, 'deviceId' | 'friendlyName' | 'hostname'>;
+
+export const deviceLabel = (device: DeviceLabelSource, unknownLabel: string) =>
+ device.friendlyName || device.hostname || unknownLabel;
+
+/**
+ * What the directory axis can offer, which is a property of the TARGET and not
+ * of the task: a cloud repo identifier and a path on a machine are the same
+ * axis in different units, so the control has to follow where the run goes.
+ *
+ * - `device` — the run lands on a machine, so the directory is an absolute path
+ * on it (a repo identifier would mean nothing there).
+ * - `repo` — the run lands in the server cloud sandbox, where the identifier
+ * IS the directory.
+ * - `none` — nothing choosable here; report the inherited state as a hint
+ * rather than offering a control that cannot take effect.
+ */
+export type TaskDirectoryKind = 'device' | 'none' | 'repo';
+
+export interface TaskRunTarget {
+ /** Whether the task may pick a target at all — the assignee's policy owns this. */
+ canSelect: boolean;
+ /** The machine the run lands on (task pin → agent bound device). */
+ deviceId?: string;
+ /**
+ * The devices this task may pin — the pool its runs can reach, not every
+ * device the caller can see (see `devicePoolForAgent`).
+ */
+ devices?: DeviceListItem[];
+ directoryKind: TaskDirectoryKind;
+ /** Where the run lands: the task's pin if it has one, else the agent's own target. */
+ effectiveTarget: DeviceExecutionTarget;
+ /**
+ * The directory the run will start in when the task does not choose one,
+ * resolved through the same chain the runtime uses. Shown as the greyed hint
+ * so inheritance is legible instead of a black box.
+ */
+ inheritedDirectory?: WorkingDirConfig;
+ /** Label for the target the task inherits — the same wording the chat chip uses. */
+ inheritedLabel: string;
+ /**
+ * What the run would do with no pin. Kept alongside {@link effectiveTarget} so
+ * the "follow the agent" row can show the inherited glyph even while the task
+ * is pinned somewhere else.
+ */
+ inheritedTarget: DeviceExecutionTarget;
+ /** Whether a task-level pin is what puts the run on {@link deviceId}. */
+ isDeviceTarget: boolean;
+ isPending: boolean;
+ /**
+ * The task's own pin, and only when the assignee's policy lets it take
+ * effect. Callers must read this rather than the raw stored value: a pin the
+ * run side drops must not be shown as the target.
+ */
+ pinnedDeviceId?: string;
+}
+
+/**
+ * Resolve where a task's runs go, and what its directory axis may offer.
+ *
+ * One source of truth for the two chips and the hint between them, so the run
+ * location control and the directory control cannot disagree about the machine
+ * in force — which is exactly how a task ends up storing a repo as the
+ * directory of a device run.
+ *
+ * The task's own pin wins over the agent's target: the run contract routes a
+ * `requestedDeviceId` regardless of the agent's stored target. An author-`fixed`
+ * policy is the exception — the run side drops the requested device for it, so
+ * this reports the inherited target instead of the stored pin.
+ */
+export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): TaskRunTarget => {
+ const { t } = useTranslation('chat');
+ const { data: devices, isLoading: isDevicesLoading } = useDeviceList();
+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
+ // Agent-level, not the active chat topic's: a task run carries no topic
+ // binding, so the conversation that happens to be open must not move it.
+ const { agencyConfig, canSelectExecutionTarget, isPreferenceLoading, workspaceScoped } =
+ useEffectiveAgencyConfig(agentId, { topicId: null });
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
+ const legacyAgentWorkingDirectory = useAgentStore(
+ (s) => s.localAgentWorkingDirectoryMap[agentId],
+ );
+ const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
+
+ // The pool a task may pin from must be the pool its runs can reach: a deviceId
+ // carries the identity it was enrolled under, so a workspace agent cannot run
+ // on a personal machine (and vice versa) — and a Task's scheduled runs execute
+ // under the workspace principal, not under whoever is looking at it, so a pin
+ // outside the pool is one automation can never resolve. Same rule the chat
+ // picker applies, shared through `devicePoolForAgent` so the two cannot drift.
+ // A task narrows it further to public workspace devices: its automated runs
+ // execute as the task's creator, who cannot resolve a colleague's private
+ // machine (see `devicePoolForTask`).
+ const agentPool = devicePoolForAgent(devices, !!agentWorkspaceId);
+ const pool = devicePoolForTask(devices, !!agentWorkspaceId);
+
+ const inheritedTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
+ workspaceScoped,
+ });
+
+ // A `fixed` selection policy is an author-controlled contract, and the run
+ // side already honours it: the planner drops a requested device for it
+ // (`resolveExecutionPlan`), and `turnSetup` writes no topic-bound device. So a
+ // pin left on the task must NOT be presented as the run's target — nor used to
+ // resolve a directory on a machine the run never reaches, which the topic
+ // metadata would then still carry.
+ const pinApplies = !!pinnedDeviceId && canSelectExecutionTarget;
+ const isDeviceTarget = pinApplies;
+ const effectiveTarget: DeviceExecutionTarget = pinApplies ? 'device' : inheritedTarget;
+ const deviceId = pinApplies
+ ? pinnedDeviceId
+ : inheritedTarget === 'device'
+ ? agencyConfig?.boundDeviceId
+ : undefined;
+
+ const rawDeviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(deviceId));
+ const deviceDefaultCwd = getWorkingDirectoryPathString(rawDeviceDefaultCwd);
+
+ // Only a device run has a machine whose default could apply; asking for one
+ // otherwise would describe a directory the cloud run never uses.
+ const inheritedDirectory = useMemo(
+ () =>
+ deviceId
+ ? resolveAgentWorkingDirectoryConfig({
+ agencyConfig,
+ // The machine in force decides which per-device choice applies.
+ currentDeviceId: deviceId,
+ deviceDefaultCwd,
+ legacyAgentWorkingDirectory,
+ workspaceScoped,
+ })
+ : undefined,
+ [agencyConfig, deviceDefaultCwd, deviceId, legacyAgentWorkingDirectory, workspaceScoped],
+ );
+
+ const surface = resolveWorkspaceSurface({
+ agencyConfig,
+ alwaysShowWorkspace: isHetero,
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
+ workspaceScoped,
+ });
+
+ // The machine in force can come from the task's own pin OR from the assignee
+ // (a bound `device` target) — both mean the run starts in a path on that
+ // machine, so both must offer the directory control. Requiring a TASK-level
+ // pin here left an inherited device run with a non-interactive hint and no way
+ // to choose a directory, even though the stored config and the runner support
+ // a directory without one.
+ const directoryKind: TaskDirectoryKind = deviceId
+ ? 'device'
+ : surface === 'cloudRepo'
+ ? 'repo'
+ : 'none';
+
+ const unknownLabel = t('heteroAgent.executionTarget.unknownDevice');
+ const inheritedLabel = (() => {
+ if (inheritedTarget === 'device') {
+ // The agent's own binding may be a private device: label it from the
+ // agent's pool, not the narrower set a task may pin.
+ const bound = agentPool.find((device) => device.deviceId === agencyConfig?.boundDeviceId);
+ return bound ? deviceLabel(bound, unknownLabel) : unknownLabel;
+ }
+ return t(`heteroAgent.executionTarget.${inheritedTarget}`);
+ })();
+
+ return {
+ canSelect: canSelectExecutionTarget,
+ deviceId,
+ devices: pool,
+ directoryKind,
+ effectiveTarget,
+ inheritedDirectory,
+ inheritedLabel,
+ inheritedTarget,
+ isDeviceTarget,
+ isPending: isPreferenceLoading || isDevicesLoading,
+ pinnedDeviceId: pinApplies ? pinnedDeviceId : undefined,
+ };
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index b96036c7cfe..3a8d6daba27 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -26,6 +26,7 @@ import { useLocalSandboxCapability } from '@/features/ChatInput/hooks/useLocalSa
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
+ devicePoolForAgent,
ExecutionTargetDeviceStatus,
ExecutionTargetIcon,
groupExecutionTargetDevices,
@@ -716,9 +717,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// Empty-state accounting must use the rows the CURRENT agent can actually
// pick (post scope filtering) — a workspace agent whose members only have
// personal devices would otherwise render neither devices nor an empty state.
- const deviceRows = isWorkspaceAgent
- ? [...privateDevices, ...workspaceDevices]
- : [...personalOnlyDevices];
+ // The pool rule itself lives in `devicePoolForAgent`, shared with every other
+ // surface that lists devices for an agent (e.g. the Task run-location chip).
+ const deviceRows = devicePoolForAgent(devices, isWorkspaceAgent);
const hasNoDevices = deviceRows.length === 0;
// On web with no device, the prominent download card below replaces the small
// header link — avoid showing the same CTA twice. Workspace agents get the
diff --git a/src/features/ExecutionTargetPicker/index.test.ts b/src/features/ExecutionTargetPicker/index.test.ts
index 9ac1c2a8684..b71b9500d9d 100644
--- a/src/features/ExecutionTargetPicker/index.test.ts
+++ b/src/features/ExecutionTargetPicker/index.test.ts
@@ -2,6 +2,8 @@ import type { DeviceListItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
+ devicePoolForAgent,
+ devicePoolForTask,
executionTargetValue,
groupExecutionTargetDevices,
isSharedExecutionTarget,
@@ -116,3 +118,37 @@ describe('ExecutionTargetPicker helpers', () => {
expect(isSharedExecutionTarget('local')).toBe(false);
});
});
+
+describe('devicePoolForAgent', () => {
+ const personal = device({ deviceId: 'personal' });
+ const privateWorkspace = device({
+ deviceId: 'private',
+ scope: 'workspace',
+ visibility: 'private',
+ });
+ const publicWorkspace = device({ deviceId: 'public', scope: 'workspace', visibility: 'public' });
+ const all = [personal, privateWorkspace, publicWorkspace];
+
+ it('gives a workspace agent the whole workspace pool, private rows first', () => {
+ // Both pools are keyed by the identity they were enrolled under
+ // (`sha256(machineUUID + userId)` vs `… + workspace:<id>`), so a workspace
+ // run can only resolve the workspace rows — and it resolves every one of
+ // them, whoever enrolled the machine.
+ expect(devicePoolForAgent(all, true)).toEqual([privateWorkspace, publicWorkspace]);
+ });
+
+ it('gives an agent outside a workspace the caller’s personal machines', () => {
+ expect(devicePoolForAgent(all, false)).toEqual([personal]);
+ });
+
+ it('survives an unloaded list', () => {
+ expect(devicePoolForAgent(undefined, true)).toEqual([]);
+ expect(devicePoolForAgent(undefined, false)).toEqual([]);
+ });
+
+ it('lets a workspace task pin only public workspace devices', () => {
+ expect(devicePoolForTask(all, true)).toEqual([publicWorkspace]);
+ expect(devicePoolForTask(all, false)).toEqual([personal]);
+ expect(devicePoolForTask(undefined, true)).toEqual([]);
+ });
+});
diff --git a/src/features/ExecutionTargetPicker/index.tsx b/src/features/ExecutionTargetPicker/index.tsx
index 79a698dac07..bdcc3bc8d38 100644
--- a/src/features/ExecutionTargetPicker/index.tsx
+++ b/src/features/ExecutionTargetPicker/index.tsx
@@ -109,6 +109,49 @@ export const groupExecutionTargetDevices = (devices: DeviceListItem[] | undefine
),
});
+/**
+ * The devices an agent's runs can actually reach.
+ *
+ * A deviceId encodes the identity it was enrolled under
+ * (`sha256(machineUUID + userId)` for personal, `… + workspace:<id>` for
+ * workspace), so the two pools are not interchangeable: a workspace agent
+ * cannot resolve a personal machine, nor a personal agent a workspace one.
+ * Offering the other pool would let a user pin a machine the run can never use
+ * — and a Task makes that worse than a chat, because its scheduled runs execute
+ * under the workspace principal rather than whoever is looking at it.
+ *
+ * Order is the picker's: the workspace pool lists private rows before public
+ * ones, the personal pool is flat.
+ */
+export const devicePoolForAgent = (
+ devices: DeviceListItem[] | undefined,
+ workspaceAgent: boolean,
+): DeviceListItem[] => {
+ const { personal, privateWorkspace, workspace } = groupExecutionTargetDevices(devices);
+
+ return workspaceAgent ? [...privateWorkspace, ...workspace] : personal;
+};
+
+/**
+ * The devices a Task may pin.
+ *
+ * Narrower than {@link devicePoolForAgent} for a workspace agent: a Task's
+ * scheduled and heartbeat runs execute as the task's creator, and a private
+ * workspace device is only resolvable by the member who enrolled it
+ * (`DeviceModel.findWorkspaceDeviceById`). A collaborator's private machine
+ * pinned on a shared task is therefore unreachable for automation — and the
+ * creator's private machine is unreachable for a collaborator's manual run — so
+ * only public workspace devices are offered.
+ */
+export const devicePoolForTask = (
+ devices: DeviceListItem[] | undefined,
+ workspaceAgent: boolean,
+): DeviceListItem[] => {
+ const { personal, publicWorkspace } = groupExecutionTargetDevices(devices);
+
+ return workspaceAgent ? publicWorkspace : personal;
+};
+
interface ExecutionTargetIconProps {
devicePlatform?: string | null;
size?: number;
diff --git a/src/services/task.ts b/src/services/task.ts
index ec3a1149714..2b8499c8a2d 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -133,6 +133,8 @@ class TaskService {
// Automation mode; null = no automation
automationMode?: TaskAutomationMode | null;
config?: Record<string, unknown>;
+ /** Deep-merged into `config` server-side under the row lock (vs. `config`, which replaces). */
+ configPatch?: Record<string, unknown>;
context?: Record<string, unknown>;
description?: string;
editorData?: unknown;
diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.ts
index 66eaa688436..955e8e70446 100644
--- a/src/store/task/slices/config/action.test.ts
+++ b/src/store/task/slices/config/action.test.ts
@@ -14,6 +14,7 @@ vi.mock('@/services/task', () => ({
updateCheckpoint: vi.fn(),
updateConfig: vi.fn(),
updateReview: vi.fn(),
+ updateVerifyConfig: vi.fn(),
},
}));
@@ -22,6 +23,11 @@ vi.mock('@/libs/swr', () => ({
useClientDataSWR: vi.fn(),
}));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
const mockDetail = {
checkpoint: { onAgentRequest: false },
identifier: 'T-1',
@@ -49,13 +55,52 @@ describe('TaskConfigSliceAction', () => {
expect(taskService.updateCheckpoint).toHaveBeenCalledWith('T-1', checkpoint);
});
- it('should refresh on error', async () => {
+ it('keeps config.checkpoint in sync so a later schedule edit does not restore the old one', async () => {
+ vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ ...mockDetail,
+ config: { checkpoint: { onAgentRequest: false }, schedule: { maxExecutions: null } },
+ schedule: { pattern: '0 9 * * *', timezone: 'UTC' },
+ },
+ },
+ });
+
+ await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });
+ await useTaskStore.getState().updateSchedule('T-1', {
+ maxExecutions: null,
+ pattern: '0 18 * * *',
+ timezone: 'UTC',
+ });
+
+ expect(useTaskStore.getState().taskDetailMap['T-1'].config?.checkpoint).toEqual({
+ onAgentRequest: true,
+ });
+ // The schedule save sends only its own key, never a config snapshot that
+ // could carry a stale checkpoint back to the server.
+ expect(vi.mocked(taskService.update).mock.calls[0][1]).not.toHaveProperty('config');
+ });
+
+ it('rolls back and marks the save failed when the PUT rejects', async () => {
const { mutate } = await import('@/libs/swr');
+ const { toast } = await import('@lobehub/ui/base-ui');
vi.mocked(taskService.updateCheckpoint).mockRejectedValue(new Error('fail'));
await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });
- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);
+ // The optimistic patch is replayed back; a failure must never leave the
+ // toggle looking saved, and it must not depend on a refetch to say so.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual({
+ onAgentRequest: false,
+ });
+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');
+ expect(toast.error).toHaveBeenCalled();
+ const refreshes = vi
+ .mocked(mutate)
+ .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');
+ expect(refreshes).toHaveLength(0);
});
});
@@ -72,6 +117,92 @@ describe('TaskConfigSliceAction', () => {
});
});
+ describe('review / verify writes', () => {
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+
+ it.each([
+ [
+ 'updateReview',
+ () => useTaskStore.getState().updateReview('T-1', { enabled: true } as any),
+ () => taskService.updateReview,
+ ],
+ [
+ 'updateVerifyConfig',
+ () => useTaskStore.getState().updateVerifyConfig('T-1', { enabled: true }),
+ () => taskService.updateVerifyConfig,
+ ],
+ ] as const)(
+ '%s queues behind an in-flight run-location write on the same config column',
+ async (_name, write, service) => {
+ // The server merges `tasks.config` read-modify-write, and this writer's
+ // follow-up refetch would otherwise land on top of the run-location
+ // chip's optimistic state while its PUT is still in flight.
+ let settleExecution!: () => void;
+ vi.mocked(taskService.updateConfig).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settleExecution = () => resolve({ success: true } as any);
+ }),
+ );
+ vi.mocked(service()).mockResolvedValue({ success: true } as any);
+
+ const store = useTaskStore.getState();
+ const p1 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
+ const p2 = write();
+
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(1);
+ expect(service()).not.toHaveBeenCalled();
+
+ settleExecution();
+ await Promise.all([p1, p2]);
+ expect(service()).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('keeps an edit queued behind a review write when the review refetch lands', async () => {
+ const { mutate } = await import('@/libs/swr');
+ let settleReview!: () => void;
+ vi.mocked(taskService.updateReview).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settleReview = () => resolve({ success: true } as any);
+ }),
+ );
+ vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);
+ // The refetch returns server data that predates the queued checkpoint edit.
+ vi.mocked(mutate).mockImplementation(async () => {
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': { ...mockDetail, checkpoint: { onAgentRequest: false } },
+ },
+ });
+ });
+
+ const store = useTaskStore.getState();
+ const review = store.updateReview('T-1', { enabled: true } as any);
+ await flush();
+ const checkpoint = store.updateCheckpoint('T-1', { onAgentRequest: true });
+ settleReview();
+ await Promise.all([review, checkpoint]);
+
+ expect(taskService.updateCheckpoint).toHaveBeenCalledOnce();
+ expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual({
+ onAgentRequest: true,
+ });
+ vi.mocked(mutate).mockReset();
+ });
+
+ it('updateVerifyConfig still rejects so multi-step callers can abort', async () => {
+ vi.mocked(taskService.updateVerifyConfig).mockRejectedValue(new Error('fail'));
+
+ await expect(
+ useTaskStore.getState().updateVerifyConfig('T-1', { enabled: true }),
+ ).rejects.toThrow('fail');
+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');
+ });
+ });
+
describe('runReview', () => {
it('should call service and refresh detail', async () => {
const { mutate } = await import('@/libs/swr');
@@ -98,7 +229,7 @@ describe('TaskConfigSliceAction', () => {
});
describe('updateTaskModelConfig', () => {
- it('should call updateConfig with model/provider and refresh detail', async () => {
+ it('should call updateConfig with model/provider and never refetch', async () => {
const { mutate } = await import('@/libs/swr');
vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);
@@ -110,7 +241,179 @@ describe('TaskConfigSliceAction', () => {
model: 'claude-sonnet-4-6',
provider: 'anthropic',
});
- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);
+ expect(useTaskStore.getState().taskDetailMap['T-1'].config).toMatchObject({
+ model: 'claude-sonnet-4-6',
+ provider: 'anthropic',
+ });
+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');
+ // A refresh here is an async write that could land after the user's next
+ // run-location pick and replace it.
+ const refreshes = vi
+ .mocked(mutate)
+ .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');
+ expect(refreshes).toHaveLength(0);
+ });
+
+ it('serializes with the run-location writes they share a config column with', async () => {
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+ const settlers: Array<() => void> = [];
+ vi.mocked(taskService.updateConfig).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settlers.push(() => resolve({ success: true } as any));
+ }),
+ );
+
+ // Both writes merge into `tasks.config` server-side with a
+ // read-modify-write, so two in flight let the later one erase the other.
+ const store = useTaskStore.getState();
+ const p1 = store.updateTaskModelConfig('T-1', { model: 'claude-sonnet-4-6' });
+ const p2 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
+
+ // Both are already visible, and only the first PUT is on the wire.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].config).toMatchObject({
+ execution: { boundDeviceId: 'device-a' },
+ model: 'claude-sonnet-4-6',
+ });
+
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(1);
+
+ settlers[0]();
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(2);
+
+ settlers[1]();
+ await Promise.all([p1, p2]);
+
+ expect(vi.mocked(taskService.updateConfig).mock.calls.map((call) => call[1])).toEqual([
+ { model: 'claude-sonnet-4-6' },
+ {
+ execution: {
+ boundDeviceId: 'device-a',
+ repos: null,
+ workingDirectory: null,
+ workingDirectoryConfig: null,
+ },
+ },
+ ]);
+ });
+ });
+
+ describe('updateTaskExecution', () => {
+ // Macrotask flush — enough for OptimisticEngine to resolve the previous PUT,
+ // run its post-await steps, and kick off the next mutation's PUT.
+ const flush = () => new Promise((r) => setTimeout(r, 0));
+
+ const executionOf = (id = 'T-1') =>
+ useTaskStore.getState().taskDetailMap[id].config?.execution as Record<string, unknown>;
+
+ it('serializes rapid device + directory edits, keeps the last one, and never refetches', async () => {
+ const { mutate } = await import('@/libs/swr');
+ const settlers: Array<() => void> = [];
+ vi.mocked(taskService.updateConfig).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ settlers.push(() => resolve({ success: true } as any));
+ }),
+ );
+
+ // Every call writes a COMPLETE four-axis patch, so the older PUT landing
+ // last would put the previous selection back — silently moving the run.
+ const store = useTaskStore.getState();
+ const p1 = store.updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
+ const p2 = store.updateTaskExecution('T-1', {
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ });
+ const p3 = store.updateTaskExecution('T-1', {
+ boundDeviceId: 'device-b',
+ workingDirectory: '/srv/app',
+ });
+
+ // The last click is already on screen while the first PUT is in flight.
+ expect(executionOf()).toEqual({
+ boundDeviceId: 'device-b',
+ repos: null,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: null,
+ });
+
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(1);
+
+ settlers[0]();
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(2);
+
+ settlers[1]();
+ await flush();
+ expect(taskService.updateConfig).toHaveBeenCalledTimes(3);
+
+ settlers[2]();
+ await Promise.all([p1, p2, p3]);
+
+ expect(
+ vi
+ .mocked(taskService.updateConfig)
+ .mock.calls.map((call) => (call[1] as any).execution.boundDeviceId),
+ ).toEqual(['device-a', 'device-a', 'device-b']);
+ expect(executionOf()).toEqual({
+ boundDeviceId: 'device-b',
+ repos: null,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: null,
+ });
+
+ const refreshes = vi
+ .mocked(mutate)
+ .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');
+ expect(refreshes).toHaveLength(0);
+ });
+
+ it('rolls the optimistic patch back, marks the save failed, and offers a retry', async () => {
+ const { toast } = await import('@lobehub/ui/base-ui');
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ ...mockDetail,
+ config: { execution: { boundDeviceId: 'device-a' }, model: 'x' },
+ },
+ },
+ });
+ vi.mocked(taskService.updateConfig).mockRejectedValue(new Error('boom'));
+
+ await useTaskStore.getState().updateTaskExecution('T-1', { boundDeviceId: 'device-b' });
+
+ // Engine replayed the inverse patch: the stored selection is back, and the
+ // other config pockets were never touched.
+ expect(useTaskStore.getState().taskDetailMap['T-1'].config).toEqual({
+ execution: { boundDeviceId: 'device-a' },
+ model: 'x',
+ });
+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');
+
+ const toastOptions = vi.mocked(toast.error).mock.calls.at(-1)?.[0];
+ if (!toastOptions || typeof toastOptions === 'string') {
+ throw new Error('Expected the failed save toast to expose a Retry action.');
+ }
+ expect(toastOptions.actions?.[0]).toBeDefined();
+ });
+
+ it('marks the save saved when the write lands', async () => {
+ vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);
+
+ await useTaskStore.getState().updateTaskExecution('T-1', { boundDeviceId: 'device-a' });
+
+ expect(taskService.updateConfig).toHaveBeenCalledWith('T-1', {
+ execution: {
+ boundDeviceId: 'device-a',
+ repos: null,
+ workingDirectory: null,
+ workingDirectoryConfig: null,
+ },
+ });
+ expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');
});
});
@@ -486,7 +789,7 @@ describe('TaskConfigSliceAction', () => {
});
expect((detail.config as any).schedule.maxExecutions).toBe(5);
expect(taskService.update).toHaveBeenCalledWith('T-1', {
- config: { schedule: { maxExecutions: 5 } },
+ configPatch: { schedule: { maxExecutions: 5 } },
schedulePattern: '0 9 * * 1-5',
scheduleTimezone: 'Asia/Shanghai',
});
diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.ts
index 56561f33a47..06aa6ea7789 100644
--- a/src/store/task/slices/config/action.ts
+++ b/src/store/task/slices/config/action.ts
@@ -3,14 +3,16 @@ import type {
TaskAutomationMode,
TaskAutomationSnapshot,
TaskDetailData,
+ TaskExecutionConfig,
} from '@lobechat/types';
+import { toTaskExecutionConfigPatch } from '@lobechat/types';
+import type { Draft } from 'immer';
import { taskService } from '@/services/task';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { OptimisticEngine } from '@/store/utils/optimisticEngine';
-import { runMutation } from '@/store/utils/runMutation';
import { saveToast } from '@/store/utils/saveToast';
import type { TaskStore } from '../../store';
@@ -19,11 +21,11 @@ import {
buildOptimisticPropertyActivity,
} from '../detail/optimisticActivity';
-// Slice of TaskStore that the OptimisticEngine for setAutomationMode reads/writes.
+// Slice of TaskStore that the OptimisticEngine for detail writes reads/writes.
// Keeping it narrow ensures `extractAffectedPaths` produces `taskDetailMap.<id>`
-// keys so concurrent toggles for the same task serialize, while toggles for
+// keys so concurrent writes for the same task serialize, while writes for
// different tasks stay parallel.
-interface AutomationModeOptimisticState {
+interface TaskDetailWriteState {
taskDetailMap: Record<string, TaskDetailData>;
}
@@ -63,10 +65,10 @@ export class TaskConfigSliceActionImpl {
readonly #get: () => TaskStore;
readonly #set: Setter;
// Lazily-initialized engine shared by every action that mutates a task's
- // `taskDetailMap` entry (setAutomationMode, updateSchedule). Per-task path
- // conflicts serialize rapid edits for the same task while different tasks
- // stay parallel.
- #automationEngine?: OptimisticEngine<AutomationModeOptimisticState>;
+ // `taskDetailMap` entry (setAutomationMode, updateSchedule, updateCheckpoint,
+ // updateReview, updateVerifyConfig, updateTaskExecution, updateTaskModelConfig). Per-task path conflicts
+ // serialize rapid edits for the same task while different tasks stay parallel.
+ #detailWriteEngine?: OptimisticEngine<TaskDetailWriteState>;
constructor(set: Setter, get: () => TaskStore, _api?: unknown) {
void _api;
@@ -77,17 +79,76 @@ export class TaskConfigSliceActionImpl {
// `getState` exposes only the taskDetailMap slice so the engine's patches
// refer to keys under it — needed for `extractAffectedPaths` to produce
// `taskDetailMap.<id>` conflict keys.
- #getAutomationEngine = (): OptimisticEngine<AutomationModeOptimisticState> => {
- if (this.#automationEngine) return this.#automationEngine;
- this.#automationEngine = new OptimisticEngine(
+ #getDetailWriteEngine = (): OptimisticEngine<TaskDetailWriteState> => {
+ if (this.#detailWriteEngine) return this.#detailWriteEngine;
+ this.#detailWriteEngine = new OptimisticEngine(
{
getState: () => ({ taskDetailMap: this.#get().taskDetailMap }),
setState: (next) =>
- this.#set(next as Partial<TaskStore>, false, 'taskConfig/automationEngine'),
+ this.#set(next as Partial<TaskStore>, false, 'taskConfig/detailWriteEngine'),
},
{ maxRetries: 0 },
);
- return this.#automationEngine;
+ return this.#detailWriteEngine;
+ };
+
+ /**
+ * Commit one write to the task's `config` column.
+ *
+ * Every writer of that column goes through the detail-write engine so they
+ * serialize per task on `taskDetailMap.<id>`. That matters because the server
+ * merges the column with a read-modify-write (`TaskModel.updateTaskConfig`):
+ * two in-flight writes can read the same snapshot and let the later one
+ * silently drop the other's key — and the fields a user edits in one sitting
+ * (model, run location, checkpoint) all live in that one column.
+ *
+ * The optimistic patch is applied synchronously and a failure replays exactly
+ * its inverse, so there is deliberately NO refetch: a refresh is an async SWR
+ * write that can land after the user's next edit and replace it. The writers
+ * whose detail is derived server-side (review, verify) refetch INSIDE `mutate`,
+ * which keeps that refresh serialized with the other writes too.
+ *
+ * Resolves on failure unless `rethrow` is set, for multi-step callers that
+ * must abort when the write did not land.
+ */
+ #commitConfigWrite = async (
+ id: string,
+ write: {
+ mutate: () => Promise<unknown>;
+ name: string;
+ onError: (error: unknown) => void | Promise<void>;
+ optimistic: (draft: Draft<TaskDetailWriteState>) => void;
+ rethrow?: boolean;
+ },
+ ): Promise<void> => {
+ const engine = this.#getDetailWriteEngine();
+ const tx = engine.createTransaction(`${write.name}(${id})`);
+ tx.set(write.optimistic);
+ tx.mutation = write.mutate;
+ tx.onError = write.onError;
+
+ this.#get().internal_setTaskSaveStatus(id, 'saving');
+ try {
+ await tx.commit();
+ this.#get().internal_setTaskSaveStatus(id, 'saved');
+ } catch (error) {
+ // The engine already replayed the inverse patch and `onError` surfaced the
+ // failure — never leave the write looking idle.
+ this.#get().internal_setTaskSaveStatus(id, 'failed');
+ if (write.rethrow) throw error;
+ }
+ };
+
+ /**
+ * Refetch a task's detail from inside a serialized config write. Edits queued
+ * behind this write (run location, model, checkpoint) have already applied
+ * their optimistic patch but not reached the server, so the refetch predates
+ * them; re-apply their patches on top, since none of them refetches when it
+ * lands.
+ */
+ #refreshDetailKeepingQueuedEdits = async (id: string): Promise<void> => {
+ await this.#get().internal_refreshTaskDetail(id);
+ this.#getDetailWriteEngine().reapplyPending();
};
markBriefRead = async (briefId: string): Promise<void> => {
@@ -117,48 +178,78 @@ export class TaskConfigSliceActionImpl {
};
updateCheckpoint = async (id: string, checkpoint: CheckpointConfig): Promise<void> => {
- this.#get().internal_dispatchTaskDetail({
- id,
- type: 'updateTaskDetail',
- value: { checkpoint },
+ await this.#commitConfigWrite(id, {
+ mutate: () => taskService.updateCheckpoint(id, checkpoint),
+ name: 'updateCheckpoint',
+ onError: (error) => {
+ console.error('[TaskStore] Failed to update checkpoint:', error);
+ saveToast(error, { retry: () => void this.#get().updateCheckpoint(id, checkpoint) });
+ },
+ optimistic: (draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.checkpoint = checkpoint;
+ // `config.checkpoint` is the same column the whole-config writers
+ // (updateSchedule → task.update) spread back to the server; leaving it
+ // stale would let the next schedule edit restore the old checkpoint.
+ target.config = { ...target.config, checkpoint };
+ },
});
-
- try {
- await taskService.updateCheckpoint(id, checkpoint);
- await this.#get().internal_refreshTaskDetail(id);
- } catch (error) {
- console.error('[TaskStore] Failed to update checkpoint:', error);
- await this.#get().internal_refreshTaskDetail(id);
- }
};
updateReview = async (
id: string,
review: Parameters<typeof taskService.updateReview>[0]['review'],
): Promise<void> => {
- try {
- await taskService.updateReview({ id, review });
- await this.#get().internal_refreshTaskDetail(id);
- } catch (error) {
- console.error('[TaskStore] Failed to update review:', error);
- await this.#get().internal_refreshTaskDetail(id);
- }
+ // Same column as the run location / model / checkpoint writers, so it goes
+ // through the same serialized path; the refetch stays inside the mutation
+ // (the review detail is derived server-side) so it cannot land on top of a
+ // later write's optimistic state.
+ await this.#commitConfigWrite(id, {
+ mutate: async () => {
+ await taskService.updateReview({ id, review });
+ await this.#refreshDetailKeepingQueuedEdits(id);
+ },
+ name: 'updateReview',
+ onError: async (error) => {
+ console.error('[TaskStore] Failed to update review:', error);
+ await this.#get().internal_refreshTaskDetail(id);
+ },
+ optimistic: (draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.config = { ...target.config, review };
+ },
+ });
};
updateVerifyConfig = async (
id: string,
verify: Parameters<typeof taskService.updateVerifyConfig>[0]['verify'],
): Promise<void> => {
- try {
- await taskService.updateVerifyConfig({ id, verify });
- await this.#get().internal_refreshTaskDetail(id);
- } catch (error) {
- console.error('[TaskStore] Failed to update verify config:', error);
- await this.#get().internal_refreshTaskDetail(id);
- // Rethrow so multi-step callers (e.g. acceptance removal) can abort
- // instead of proceeding as if the config write landed.
- throw error;
- }
+ // Serialized with every other `config` writer — see `updateReview`.
+ await this.#commitConfigWrite(id, {
+ mutate: async () => {
+ await taskService.updateVerifyConfig({ id, verify });
+ await this.#refreshDetailKeepingQueuedEdits(id);
+ },
+ name: 'updateVerifyConfig',
+ onError: async (error) => {
+ console.error('[TaskStore] Failed to update verify config:', error);
+ await this.#get().internal_refreshTaskDetail(id);
+ },
+ // The server applies `verify` as a per-key patch (`null` clears), which the
+ // refetch reflects; the optimistic write only has to claim the task's slot
+ // so this write queues behind — and ahead of — the other config writers.
+ optimistic: (draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.config = { ...target.config };
+ },
+ // Multi-step callers (e.g. acceptance removal) abort instead of proceeding
+ // as if the config write landed.
+ rethrow: true,
+ });
};
// Safely merges model/provider into config via task.updateConfig without overwriting checkpoint/review
@@ -166,26 +257,56 @@ export class TaskConfigSliceActionImpl {
id: string,
modelConfig: { model?: string; provider?: string },
): Promise<void> => {
- // Optimistic update — immediately reflect new model/provider in UI
- this.#get().internal_dispatchTaskDetail({
- id,
- type: 'updateTaskDetail',
- value: { config: { ...this.#get().taskDetailMap[id]?.config, ...modelConfig } },
- });
- await runMutation(this.#set, this.#get, {
- mutate: async () => {
- await taskService.updateConfig(id, modelConfig);
- await this.#get().internal_refreshTaskDetail(id);
- },
+ // Serialized with every other `config` writer, and with no refetch: switching
+ // the model while picking a run location is the same column, and a late
+ // refresh would replace the run-location chip's optimistic state.
+ await this.#commitConfigWrite(id, {
+ mutate: () => taskService.updateConfig(id, modelConfig),
name: 'updateTaskModelConfig',
- onError: async (error) => {
+ onError: (error) => {
console.error('[TaskStore] Failed to update task model config:', error);
- await this.#get().internal_refreshTaskDetail(id);
saveToast(error, { retry: () => void this.#get().updateTaskModelConfig(id, modelConfig) });
},
- // Best-effort toggle — the toast + refetch surface the failure, callers don't rethrow.
- rethrow: false,
- setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),
+ optimistic: (draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.config = { ...target.config, ...modelConfig };
+ },
+ });
+ };
+
+ /**
+ * Set where this task's runs execute — a pinned device and/or a working
+ * directory. `undefined` (or an axis set to `undefined`) returns that axis to
+ * inheritance, so a task that pins nothing runs wherever its assignee agent
+ * does.
+ *
+ * Written through `task.updateConfig`, which DEEP MERGES, and never through
+ * `task.update`: that one replaces the whole `config` column and would take
+ * model / brief / review / checkpoint down with it. `toTaskExecutionConfigPatch`
+ * therefore writes every axis explicitly, `null` for a cleared one — under a
+ * merge an omitted key keeps its previous value, which would leave the old
+ * device or directory in place while the control reads "follow the agent".
+ */
+ updateTaskExecution = async (id: string, execution?: TaskExecutionConfig): Promise<void> => {
+ const patch = toTaskExecutionConfigPatch(execution);
+
+ // Every axis is written explicitly on every call, so two of these in flight
+ // can put the previous selection back if the older one lands last — hence the
+ // shared config-write path (`#commitConfigWrite`), same as the model and
+ // checkpoint writers, which merge into the same column.
+ await this.#commitConfigWrite(id, {
+ mutate: () => taskService.updateConfig(id, { execution: patch }),
+ name: 'updateTaskExecution',
+ onError: (error) => {
+ console.error('[TaskStore] Failed to update task execution:', error);
+ saveToast(error, { retry: () => void this.#get().updateTaskExecution(id, execution) });
+ },
+ optimistic: (draft) => {
+ const target = draft.taskDetailMap[id];
+ if (!target) return;
+ target.config = { ...target.config, execution: patch };
+ },
});
};
@@ -232,7 +353,7 @@ export class TaskConfigSliceActionImpl {
// The patch also mirrors every server-bound field locally, so no post-PUT
// refresh is needed — refresh would be an async SWR write that could land
// after the user's next click and clobber their latest state.
- const engine = this.#getAutomationEngine();
+ const engine = this.#getDetailWriteEngine();
const tx = engine.createTransaction(`setAutomationMode(${id})`);
// The feed row for this change rides the same optimistic patch as the
// fields themselves — there is deliberately no refetch here (see below),
@@ -318,7 +439,7 @@ export class TaskConfigSliceActionImpl {
// normalized store copy), so we don't need a follow-up refresh — that
// refresh used to be the race source: an async SWR write that could
// arrive after the user's next click and overwrite their input.
- const engine = this.#getAutomationEngine();
+ const engine = this.#getDetailWriteEngine();
const tx = engine.createTransaction(`updateSchedule(${id})`);
// The server logs a pattern / timezone edit as an automation change when
// the schedule is on; this path never refetches, so the feed row has to
@@ -362,8 +483,11 @@ export class TaskConfigSliceActionImpl {
};
});
tx.mutation = async () => {
+ // Send only the key this edit owns, merged server-side under the row
+ // lock: a whole-config snapshot from this tab can predate another tab's
+ // or member's write (an execution pin, a model) and would erase it.
await taskService.update(id, {
- config: nextConfig,
+ configPatch: { schedule: { maxExecutions: schedule.maxExecutions } },
schedulePattern: schedule.pattern,
scheduleTimezone: schedule.timezone,
});
diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.ts
index b954b461987..3faf2699314 100644
--- a/src/store/task/slices/detail/action.test.ts
+++ b/src/store/task/slices/detail/action.test.ts
@@ -1,3 +1,8 @@
+import {
+ applyTaskReposSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+} from '@lobechat/types';
import { toast } from '@lobehub/ui/base-ui';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -247,6 +252,98 @@ describe('TaskDetailSliceAction', () => {
await pending;
});
+ it('drops the previous agent’s repo selection when the task is reassigned', async () => {
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ agentId: 'agt_a',
+ config: {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ model: 'claude-code',
+ },
+ identifier: 'T-1',
+ instruction: 'x',
+ status: 'backlog',
+ },
+ },
+ });
+ // Hold the PUT open so only the optimistic render is observed — the chip
+ // must not keep showing the old agent's repo while the write is in flight.
+ let release!: () => void;
+ vi.mocked(taskService.update).mockReturnValue(
+ new Promise((resolve) => {
+ release = () => resolve({ success: true } as any);
+ }),
+ );
+
+ const pending = useTaskStore.getState().updateTask('T-1', { assigneeAgentId: 'agt_b' });
+
+ const config = useTaskStore.getState().taskDetailMap['T-1'].config as Record<string, unknown>;
+ expect(readTaskExecutionConfig(config)).toBeUndefined();
+ // Only the repo axis follows the assignee; the other config pockets stay.
+ expect(config.model).toBe('claude-code');
+
+ release();
+ await pending;
+ });
+
+ it('keeps a device pin and a machine directory when the task is reassigned', async () => {
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ agentId: 'agt_a',
+ config: {
+ execution: toTaskExecutionConfigPatch({
+ boundDeviceId: 'device-a',
+ workingDirectory: '/srv/app',
+ }),
+ },
+ identifier: 'T-1',
+ instruction: 'x',
+ status: 'backlog',
+ },
+ },
+ });
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ await useTaskStore.getState().updateTask('T-1', { assigneeAgentId: 'agt_b' });
+
+ expect(
+ readTaskExecutionConfig(
+ useTaskStore.getState().taskDetailMap['T-1'].config as Record<string, unknown>,
+ ),
+ ).toEqual({ boundDeviceId: 'device-a', workingDirectory: '/srv/app' });
+ });
+
+ it('keeps the repo selection when the assignee does not change', async () => {
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ agentId: 'agt_a',
+ config: {
+ execution: toTaskExecutionConfigPatch(
+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),
+ ),
+ },
+ identifier: 'T-1',
+ instruction: 'x',
+ status: 'backlog',
+ },
+ },
+ });
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ await useTaskStore.getState().updateTask('T-1', { name: 'Renamed' });
+
+ expect(
+ readTaskExecutionConfig(
+ useTaskStore.getState().taskDetailMap['T-1'].config as Record<string, unknown>,
+ )?.repos,
+ ).toEqual(['lobehub/lobehub']);
+ });
+
it('revalidates goal graphs when the assignee changes, so a goal page shows the new executor', async () => {
useTaskStore.setState({
taskDetailMap: { 'T-1': { identifier: 'T-1', instruction: 'x', status: 'backlog' } },
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index ef17a581927..f4bde34ea94 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -1,4 +1,9 @@
import type { TaskDetailActivityAuthor, TaskDetailData, TaskDetailSubtask } from '@lobechat/types';
+import {
+ clearTaskReposSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+} from '@lobechat/types';
import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
@@ -476,10 +481,27 @@ export class TaskDetailSliceActionImpl {
[...(current?.activities ?? []), ...optimisticActivities],
priorityRow,
);
+ // Mirror the server's reassign rule (`TaskModel.updateWithLog`) so the
+ // run-location cluster stops showing the previous agent's repos the moment
+ // the assignee flips, instead of one refetch later: `repos` belong to the
+ // assignee's provider env, and the run those repos imply is the sandbox
+ // directory the new agent may not be able to open. Same helper as the
+ // server, so the two cannot drift.
+ const reassignedAgent =
+ assigneeAgentId !== undefined && !!current?.agentId && assigneeAgentId !== current.agentId;
+ const currentExecution = reassignedAgent ? readTaskExecutionConfig(current?.config) : undefined;
+ const clearedExecution = reassignedAgent
+ ? clearTaskReposSelection(currentExecution)
+ : undefined;
+ const clearedConfig =
+ reassignedAgent && clearedExecution !== currentExecution
+ ? { ...current?.config, execution: toTaskExecutionConfigPatch(clearedExecution) }
+ : undefined;
const optimistic: Partial<TaskDetailData> = {
...optimisticRest,
...(assigneeAgentId !== undefined ? { agentId: assigneeAgentId } : {}),
...(assigneeUserId !== undefined ? { userId: assigneeUserId } : {}),
+ ...(clearedConfig ? { config: clearedConfig } : {}),
...(optimisticActivities.length > 0 || priorityRow ? { activities } : {}),
};
const payload = options?.actorAgentId ? { ...data, actorAgentId: options.actorAgentId } : data;
diff --git a/src/store/utils/optimisticEngine.ts b/src/store/utils/optimisticEngine.ts
index f19d85b9d71..b5b7a8316b2 100644
--- a/src/store/utils/optimisticEngine.ts
+++ b/src/store/utils/optimisticEngine.ts
@@ -243,6 +243,37 @@ class MutationQueue {
});
}
+ /**
+ * Re-apply the optimistic patches of every mutation still waiting to run.
+ * A server refresh replaces the state those patches were applied to, and a
+ * queued mutation never refetches after it lands — so without this its edit
+ * would vanish from the UI until some later refresh.
+ */
+ reapplyPending() {
+ const pending = this.queue
+ .filter((mutation) => mutation.status === 'pending' && !this.inflightIds.has(mutation.id))
+ .sort((a, b) => a.timestamp - b.timestamp);
+ const stores = new Set<AnyStore>();
+ for (const mutation of pending) {
+ for (const store of mutation.storePatches.keys()) stores.add(store);
+ }
+
+ for (const store of stores) {
+ let nextState = store.getState();
+ for (const mutation of pending) {
+ const entry = mutation.storePatches.get(store);
+ if (!entry) continue;
+ try {
+ nextState = applyPatches(nextState, entry.patches);
+ } catch {
+ // The refreshed state no longer has the patched path (e.g. the entry
+ // is gone); nothing left to re-apply this edit to.
+ }
+ }
+ store.setState(nextState);
+ }
+ }
+
async flush(): Promise<void> {
this.processNext();
@@ -494,4 +525,9 @@ export class OptimisticEngine<S extends StoreState = Record<string, never>> {
async flush(): Promise<void> {
await this.queue.flush();
}
+
+ /** See {@link MutationQueue.reapplyPending}: call right after a refresh lands. */
+ reapplyPending(): void {
+ this.queue.reapplyPending();
+ }
}