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): make "Follow the agent" one switch for device and working directory (#21932)

AmAzing-2bc4823a9115
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 95bdce2dc2f..3031eb806e9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2551,10 +2551,13 @@
"taskDetail.topicSource": "From {{identifier}}",
"taskDetail.untitled": "Untitled",
"taskDetail.updateFailed": "Failed to update task",
+ "taskExecution.agentDefault": "Agent default",
+ "taskExecution.environment": "Execution environment",
"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.followAgentDesc": "Use the agent's device and working directory",
"taskExecution.runLocation": "Run location",
+ "taskExecution.selectDirectory": "Choose a folder",
"taskExecution.workingDirectory": "Working directory",
"taskIntent.analyzing": "Reading…",
"taskIntent.answersHeading": "Clarifications",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 03207708e0f..3d08b59e361 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2551,10 +2551,13 @@
"taskDetail.topicSource": "来自 {{identifier}}",
"taskDetail.untitled": "无标题",
"taskDetail.updateFailed": "任务更新失败",
+ "taskExecution.agentDefault": "Agent 默认",
+ "taskExecution.environment": "执行环境",
"taskExecution.fixedTip": "执行环境已在助理档案中固定。",
"taskExecution.followAgent": "跟随 Agent",
- "taskExecution.followAgentDesc": "使用被指派 Agent 的执行环境",
+ "taskExecution.followAgentDesc": "使用 Agent 的设备和工作目录",
"taskExecution.runLocation": "运行位置",
+ "taskExecution.selectDirectory": "选择工作目录",
"taskExecution.workingDirectory": "工作目录",
"taskIntent.analyzing": "正在理解…",
"taskIntent.answersHeading": "补充说明",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 67da95e9ce5..c4e642037f4 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -393,10 +393,13 @@ export default {
'taskCard.field.reviewRubrics': 'Review rubrics',
'taskCard.field.subtasks': 'Subtasks',
'taskCard.field.workspace': 'Workspace',
+ 'taskExecution.agentDefault': 'Agent default',
+ 'taskExecution.environment': 'Execution environment',
'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.followAgentDesc': "Use the agent's device and working directory",
'taskExecution.runLocation': 'Run location',
+ 'taskExecution.selectDirectory': 'Choose a folder',
'taskExecution.workingDirectory': 'Working directory',
'taskList.truncated': 'Showing the first {{loaded}} of {{total}} tasks',
'workingPanel.deployments.copy': 'Copy URL',
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
index 24162e0070f..ceef897db17 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
@@ -43,10 +43,13 @@ const TaskExecutionConfig = memo(() => {
if (!assigneeAgentId) return null;
+ // Keyed per task: a "not following" state with nothing picked yet belongs to
+ // the task it was set on, not to the next one opened in this view.
return (
<TaskExecutionControls
assigneeAgentId={assigneeAgentId}
disabled={!canEditTask}
+ key={taskId}
value={execution}
onChange={handleChange}
/>
diff --git a/src/features/AgentTasks/features/TaskDeviceChip.tsx b/src/features/AgentTasks/features/TaskDeviceChip.tsx
index a549e6916df..38d16481db9 100644
--- a/src/features/AgentTasks/features/TaskDeviceChip.tsx
+++ b/src/features/AgentTasks/features/TaskDeviceChip.tsx
@@ -1,7 +1,7 @@
'use client';
import type { DeviceListItem } from '@lobechat/types';
-import { Block, cx, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';
+import { Block, cx, Flexbox, Icon, Popover, Switch, Text, Tooltip } from '@lobehub/ui';
import { CheckIcon, ChevronDownIcon, FolderIcon } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,29 +21,38 @@ interface TaskDeviceChipProps {
* detail's header row passes its own chip-sized class instead.
*/
className?: string;
+ disabled?: boolean;
/**
- * 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.
+ * The directory the agent's own environment starts in, shown under the switch
+ * while the task follows it — "follow" has to read as a concrete machine and
+ * folder, not a black box.
*/
- directoryHint?: string;
- disabled?: boolean;
- /** Pinned device, or `undefined` to inherit the assignee agent's target. */
+ followDirectory?: string;
+ /** The task inherits the agent's device AND directory; nothing is picked here. */
+ following: boolean;
+ /** Pinned device, or `undefined` to run on the assignee agent's own target. */
onChange: (deviceId: string | undefined) => void;
+ onFollowChange: (following: boolean) => void;
value?: string;
}
/**
- * Where a task's runs execute.
+ * The task's execution environment: follow the assignee agent, or pick a
+ * machine of its own.
+ *
+ * Following is one switch for both axes, because the agent's environment IS a
+ * machine plus a folder on it — following one and picking the other was two
+ * controls for a single decision. While the switch is on there is nothing to
+ * pick; turning it off lists the machines here, and the caller shows the
+ * directory control next to this chip.
*
* 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.
+ * cloud sandbox over an agent's stored target. So the agent's own target is
+ * offered only when it is not one of the listed machines, as the row that
+ * removes the pin — never as a "Cloud Sandbox" row that would silently do
+ * 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
@@ -51,7 +60,16 @@ interface TaskDeviceChipProps {
* counterpart here — a task pins a specific machine the user can see.
*/
const TaskDeviceChip = memo<TaskDeviceChipProps>(
- ({ agentId, className, directoryHint, disabled, onChange, value }) => {
+ ({
+ agentId,
+ className,
+ disabled,
+ followDirectory,
+ following,
+ onChange,
+ onFollowChange,
+ value,
+ }) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
@@ -59,6 +77,8 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
canSelect,
devices,
devicesFailed,
+ directoryKind,
+ inheritedDeviceId,
inheritedLabel,
inheritedTarget,
isPending,
@@ -66,9 +86,15 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
retryDevices,
} = 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 lockReason = getTaskDeviceLockReason({ canSelect, disabled, isPending });
+ // An author-fixed target still leaves the directory choosable, so the switch
+ // only locks when neither axis is. A task already off the agent keeps the
+ // switch, so it can always return to following.
+ const canCustomize = canSelect || directoryKind !== 'none';
+ const lockReason = getTaskDeviceLockReason({
+ canSelect: canCustomize || !following,
+ disabled,
+ isPending,
+ });
const isLocked = !!lockReason;
// Read the EFFECTIVE pin, never the raw prop: an author-fixed policy makes
@@ -78,7 +104,6 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
? 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
@@ -90,14 +115,20 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
: isPending
? inheritedLabel
: unknownLabel;
+ // The agent's own target needs a row of its own only when no listed machine
+ // stands for it (the cloud sandbox, or a machine outside the task pool), or
+ // when the policy fixes it and the list cannot be picked from at all.
+ const isAgentTargetListed =
+ !!inheritedDeviceId && !!devices?.some((device) => device.deviceId === inheritedDeviceId);
+ const showAgentTargetRow = !canSelect || !isAgentTargetListed;
const handleSelect = useCallback(
(deviceId: string | undefined) => {
- if (isLocked) return;
+ if (isLocked || !canSelect) return;
onChange(deviceId);
setOpen(false);
},
- [isLocked, onChange],
+ [canSelect, isLocked, onChange],
);
const renderDeviceRow = (device: DeviceListItem) => {
@@ -111,7 +142,12 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
>
<ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />
<Flexbox flex={1} style={{ minWidth: 0 }}>
- <div className={styles.rowTitle}>{deviceLabel(device, unknownLabel)}</div>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <div className={styles.rowTitle}>{deviceLabel(device, unknownLabel)}</div>
+ {device.deviceId === inheritedDeviceId && (
+ <span className={styles.badge}>{t('taskExecution.agentDefault')}</span>
+ )}
+ </Flexbox>
<div className={styles.rowDesc}>
<ExecutionTargetDeviceStatus
offlineLabel={t('heteroAgent.executionTarget.offline')}
@@ -127,60 +163,88 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
);
};
+ const followRow = (
+ <Flexbox horizontal align={'center'} className={styles.switchRow} gap={12}>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{t('taskExecution.followAgent')}</div>
+ <div className={styles.rowDesc}>{t('taskExecution.followAgentDesc')}</div>
+ {following && (
+ <Flexbox horizontal align={'center'} className={styles.followSummary} gap={4}>
+ <ExecutionTargetIcon target={inheritedTarget} />
+ <span className={styles.hintValue}>{inheritedLabel}</span>
+ {followDirectory && (
+ <>
+ <span>·</span>
+ <Icon icon={FolderIcon} size={12} />
+ <span className={styles.hintValue}>{followDirectory}</span>
+ </>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ <Switch
+ aria-label={t('taskExecution.followAgent')}
+ checked={following}
+ size={'small'}
+ onChange={onFollowChange}
+ />
+ </Flexbox>
+ );
+
+ const deviceSection = (
+ <>
+ <div className={styles.sectionTitle}>{t('taskExecution.runLocation')}</div>
+ {showAgentTargetRow && (
+ <TaskPickerOption
+ checked={!pinnedDeviceId}
+ disabled={isLocked || !canSelect}
+ onSelect={() => handleSelect(undefined)}
+ >
+ <ExecutionTargetIcon target={inheritedTarget} />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <div className={styles.rowTitle}>{inheritedLabel}</div>
+ <div className={styles.rowDesc}>
+ {canSelect ? t('taskExecution.agentDefault') : t('taskExecution.fixedTip')}
+ </div>
+ </Flexbox>
+ {!pinnedDeviceId && <Icon className={styles.check} icon={CheckIcon} size={14} />}
+ </TaskPickerOption>
+ )}
+
+ {canSelect && (
+ <>
+ {isPending && (
+ <div className={styles.sectionTitle}>{t('heteroAgent.executionTarget.loading')}</div>
+ )}
+ {devicesFailed && (
+ <div className={styles.emptyHint}>
+ {t('heteroAgent.executionTarget.loadFailed')}{' '}
+ <a role="button" onClick={retryDevices}>
+ {t('retry', { ns: 'common' })}
+ </a>
+ </div>
+ )}
+ {!isPending && !devicesFailed && devices && devices.length > 0 && (
+ <div className={styles.scroll}>{devices.map(renderDeviceRow)}</div>
+ )}
+ {!isPending && !devicesFailed && devices?.length === 0 && (
+ <div className={styles.emptyHint}>{t('heteroAgent.executionTarget.noDevices')}</div>
+ )}
+ </>
+ )}
+ </>
+ );
+
const content = (
<Flexbox
- aria-label={t('taskExecution.runLocation')}
+ aria-label={t('taskExecution.environment')}
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>
- )}
- {devicesFailed && (
- <div className={styles.emptyHint}>
- {t('heteroAgent.executionTarget.loadFailed')}{' '}
- <a role="button" onClick={retryDevices}>
- {t('retry', { ns: 'common' })}
- </a>
- </div>
- )}
- {!isPending && !devicesFailed && devices && devices.length > 0 && (
- <div className={styles.scroll}>{devices.map(renderDeviceRow)}</div>
- )}
- {!isPending && !devicesFailed && 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>
- )}
+ <div className={styles.sectionTitle}>{t('taskExecution.environment')}</div>
+ {followRow}
+ {!following && deviceSection}
</Flexbox>
);
@@ -193,13 +257,17 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
gap={6}
variant={'borderless'}
>
- {pinnedDeviceId ? (
+ {!following && pinnedDeviceId ? (
<ExecutionTargetIcon devicePlatform={pinned?.platform} target={'device'} />
) : (
<ExecutionTargetIcon target={inheritedTarget} />
)}
<Text ellipsis className={styles.chipLabel} fontSize={12}>
- {pinnedDeviceId ? pinnedLabel : inheritedLabel}
+ {following
+ ? t('taskExecution.followAgent')
+ : pinnedDeviceId
+ ? pinnedLabel
+ : inheritedLabel}
</Text>
<Icon icon={ChevronDownIcon} size={12} />
</Block>
@@ -209,7 +277,7 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
return (
<Tooltip
title={formatLockedControlTooltip(
- t('taskExecution.runLocation'),
+ t('taskExecution.environment'),
lockReason === 'pending'
? t('heteroAgent.executionTarget.presenceChecking')
: t('taskExecution.fixedTip'),
diff --git a/src/features/AgentTasks/features/TaskExecutionControls.tsx b/src/features/AgentTasks/features/TaskExecutionControls.tsx
index ffdf3fdb49f..fd281ac260a 100644
--- a/src/features/AgentTasks/features/TaskExecutionControls.tsx
+++ b/src/features/AgentTasks/features/TaskExecutionControls.tsx
@@ -1,29 +1,16 @@
'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 type { TaskExecutionConfig } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
+import { memo } from 'react';
-import {
- getWorkingDirectoryName,
- getWorkingDirectoryPathString,
-} from '@/helpers/workingDirectoryPath';
+import { getWorkingDirectoryName } from '@/helpers/workingDirectoryPath';
import TaskDeviceChip from './TaskDeviceChip';
-import { taskExecutionStyles as styles } from './taskExecutionStyles';
import TaskRepoChip from './TaskRepoChip';
import TaskWorkingDirectoryChip from './TaskWorkingDirectoryChip';
import { useTaskExecutionAvailability } from './useTaskExecutionAvailability';
-import { useTaskRunTarget } from './useTaskRunTarget';
+import { useTaskExecutionSelection } from './useTaskExecutionSelection';
interface TaskExecutionControlsProps {
/** The assignee whose execution environment a task inherits by default. */
@@ -37,118 +24,81 @@ interface TaskExecutionControlsProps {
/**
* Where this task will run, next to the other task properties.
*
- * Two axes, and the second one is decided by the first:
+ * One switch decides it: **follow the agent**, and the task runs on the
+ * assignee's machine in the assignee's folder — both axes, because the agent's
+ * environment is one thing; or **don't**, and the task picks both itself:
*
- * - **run location** — pin a machine, or follow the assignee agent.
+ * - **run location** — a machine from the task's pool (or the agent's own
+ * target when that is not a machine, e.g. the cloud sandbox).
* - **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.
+ * when it lands in the sandbox.
*
- * 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.
+ * A task left on "follow" stores nothing, so it 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. See {@link useTaskExecutionSelection} for the state behind it.
*/
const TaskExecutionControls = memo<TaskExecutionControlsProps>((props) => {
const { assigneeAgentId } = props;
if (!assigneeAgentId) return null;
- return <TaskExecutionControlsInner {...props} assigneeAgentId={assigneeAgentId} />;
+ // Keyed by the assignee: "not following" is a decision about ONE agent's
+ // environment, and must not carry over to the next agent picked.
+ return (
+ <TaskExecutionControlsInner
+ key={assigneeAgentId}
+ {...props}
+ assigneeAgentId={assigneeAgentId}
+ />
+ );
});
const TaskExecutionControlsInner = memo<
Omit<TaskExecutionControlsProps, 'assigneeAgentId'> & { assigneeAgentId: string }
>(({ assigneeAgentId, disabled, onChange, value }) => {
- const { t } = useTranslation('chat');
const canExecuteSomewhere = useTaskExecutionAvailability(assigneeAgentId);
-
- 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],
- );
+ const { changeDevice, changeDirectory, changeFollowing, changeRepos, following, target } =
+ useTaskExecutionSelection({ agentId: assigneeAgentId, onChange, value });
if (!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');
+ // While following, `inheritedDirectory` is the agent's own folder on its own
+ // machine — shown under the switch so "follow" reads as a concrete place.
+ const followDirectory = getWorkingDirEffectivePath(target.inheritedDirectory);
return (
<>
<TaskDeviceChip
agentId={assigneeAgentId}
- directoryHint={directorySummary}
disabled={disabled}
+ following={following}
value={value?.boundDeviceId}
- onChange={handleDeviceChange}
+ followDirectory={
+ followDirectory
+ ? (getWorkingDirectoryName(followDirectory) ?? followDirectory)
+ : undefined
+ }
+ onChange={changeDevice}
+ onFollowChange={changeFollowing}
/>
- {target.directoryKind === 'device' && target.deviceId ? (
- <TaskWorkingDirectoryChip
- deviceId={target.deviceId}
- disabled={disabled || target.isPending}
- 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>
- )}
+ {!following &&
+ (target.directoryKind === 'device' && target.deviceId ? (
+ <TaskWorkingDirectoryChip
+ deviceId={target.deviceId}
+ disabled={disabled || target.isPending}
+ fallback={target.inheritedDirectory}
+ value={value?.workingDirectoryConfig}
+ onChange={changeDirectory}
+ />
+ ) : target.directoryKind === 'repo' ? (
+ <TaskRepoChip
+ agentId={assigneeAgentId}
+ disabled={disabled}
+ value={value?.repos}
+ onChange={changeRepos}
+ />
+ ) : null)}
</>
);
});
diff --git a/src/features/AgentTasks/features/TaskRepoChip.tsx b/src/features/AgentTasks/features/TaskRepoChip.tsx
index 7157f6ae2f9..b2326ea70cf 100644
--- a/src/features/AgentTasks/features/TaskRepoChip.tsx
+++ b/src/features/AgentTasks/features/TaskRepoChip.tsx
@@ -2,7 +2,7 @@
import { Github } from '@lobehub/icons';
import { Checkbox, cx, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';
-import { CheckIcon, ChevronDownIcon, SquircleDashed } from 'lucide-react';
+import { ChevronDownIcon, SquircleDashed } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,7 +22,7 @@ interface TaskRepoChipProps {
*/
className?: string;
disabled?: boolean;
- /** Selected repos, or `undefined` to inherit (the agent's own directory). */
+ /** Selected repos, or `undefined` for none (the agent's own directory). */
onChange: (repos: string[] | undefined) => void;
value?: string[];
}
@@ -35,11 +35,12 @@ const getRepoName = (repo: string) => repo.split('/').findLast(Boolean) || repo;
* 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.
+ * would be a value the run cannot use. Like the directory picker it appears
+ * once the task stops following the agent, so it carries no "follow" row.
*
* 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":
+ * different repo sets for the same agent. An empty selection picks no repo:
* the run falls back to the agent's per-device directory and then the device
* default.
*/
@@ -67,8 +68,8 @@ const TaskRepoChip = memo<TaskRepoChipProps>(
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.
+ // An empty selection is "no repo", not an empty list — collapse it back
+ // to undefined so only the intent is persisted.
onChange(next.length > 0 ? next : undefined);
},
[disabled, onChange, selected],
@@ -80,7 +81,7 @@ const TaskRepoChip = memo<TaskRepoChipProps>(
const chipLabel =
selected.length === 0
- ? t('taskExecution.followAgent')
+ ? t('heteroAgent.cloudRepo.notSet')
: selected.length === 1
? getRepoName(selected[0])
: t('heteroAgent.cloudRepo.multiSelected', { count: selected.length });
@@ -93,18 +94,6 @@ const TaskRepoChip = memo<TaskRepoChipProps>(
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);
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
index ea5d02f0ae5..d887ee8ce58 100644
--- a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
@@ -46,4 +46,22 @@ describe('TaskWorkingDirectoryChip', () => {
expect(screen.getByText('/repos/notification-center')).toBeInTheDocument();
});
+
+ // An unset directory is the machine's default folder, not a blank: the trigger
+ // names it and the list checks it, even before it is one of the recents.
+ it('shows and checks the fallback folder when the task picks none', () => {
+ render(
+ <TaskWorkingDirectoryChip
+ deviceId="device-1"
+ fallback={{ path: '/repos/default-home' }}
+ onChange={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole('button', { name: /\/repos\/default-home/ })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(screen.getAllByText('default-home').length).toBeGreaterThan(1);
+ });
});
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
index d970577a0c7..b26d60eafa5 100644
--- a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
@@ -3,7 +3,7 @@
import type { WorkingDirConfig, WorkingDirEntry } from '@lobechat/types';
import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';
import { cx, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';
-import { CheckIcon, ChevronDownIcon, FolderPlusIcon, SquircleDashed } from 'lucide-react';
+import { CheckIcon, ChevronDownIcon, FolderPlusIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,7 +26,13 @@ interface TaskWorkingDirectoryChipProps {
/** 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. */
+ /**
+ * Where the run starts while the task picks no directory: the device's default
+ * chain for this machine. Shown and checked as the current value, so an unset
+ * directory still reads as a concrete folder.
+ */
+ fallback?: WorkingDirConfig;
+ /** Selected directory, or `undefined` to start in {@link fallback}. */
onChange: (config?: WorkingDirConfig) => void;
value?: WorkingDirConfig;
}
@@ -34,6 +40,10 @@ interface TaskWorkingDirectoryChipProps {
/**
* The directory a task's runs start in, for a run pinned to a machine.
*
+ * Shown only once the task stops following the agent — following covers the
+ * directory as well, so there is no "follow" row here: every row is a folder on
+ * this machine, and the one the run uses is checked.
+ *
* 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
@@ -44,7 +54,7 @@ interface TaskWorkingDirectoryChipProps {
* which validates the path against that device when it can reach it.
*/
const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
- ({ className, deviceId, disabled, onChange, value }) => {
+ ({ className, deviceId, disabled, fallback, onChange, value }) => {
const { t } = useTranslation('chat');
const { t: tDevice } = useTranslation('device');
const [open, setOpen] = useState(false);
@@ -57,12 +67,24 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
const deviceDefaultCwd = getWorkingDirectoryPathString(device?.defaultCwd ?? undefined);
const rawRecents = device?.workingDirs;
- const recents = useMemo(
- () => (rawRecents ?? []).filter((entry) => !!getWorkingDirectoryPathString(entry.path)),
- [rawRecents],
- );
-
const selectedPath = getWorkingDirEffectivePath(value);
+ // The folder the run starts in: the task's own pick, else the machine's default.
+ const current = selectedPath ? value : fallback;
+ const currentPath = getWorkingDirEffectivePath(current);
+
+ // The folder in use leads the list when it is not a recent (a device default
+ // nobody has opened yet), so the checked state always has a row to land on.
+ const recents = useMemo<WorkingDirEntry[]>(() => {
+ const entries = (rawRecents ?? []).filter(
+ (entry) => !!getWorkingDirectoryPathString(entry.path),
+ );
+ if (
+ !currentPath ||
+ entries.some((entry) => getWorkingDirectoryPathString(entry.path) === currentPath)
+ )
+ return entries;
+ return [{ path: currentPath, repoType: current?.repoType }, ...entries];
+ }, [current?.repoType, currentPath, rawRecents]);
const apply = useCallback(
(config?: WorkingDirConfig) => {
@@ -84,7 +106,7 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
const handleAdd = useCallback(() => {
setOpen(false);
openAddWorkingDirModal({
- defaultPath: selectedPath ?? deviceDefaultCwd,
+ defaultPath: currentPath ?? deviceDefaultCwd,
deviceId,
onSubmit: async (path) => {
// An unreachable device returns null; that is "can't verify", not
@@ -99,11 +121,11 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
return undefined;
},
});
- }, [deviceDefaultCwd, deviceId, onChange, selectedPath, tDevice]);
+ }, [currentPath, deviceDefaultCwd, deviceId, onChange, tDevice]);
- const chipLabel = selectedPath
- ? (getWorkingDirectoryName(selectedPath) ?? selectedPath)
- : t('taskExecution.followAgent');
+ const chipLabel = currentPath
+ ? (getWorkingDirectoryName(currentPath) ?? currentPath)
+ : t('taskExecution.selectDirectory');
const content = (
<Flexbox
@@ -113,18 +135,6 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
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}>
@@ -133,7 +143,7 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
) : (
recents.map((entry) => {
const path = getWorkingDirectoryPathString(entry.path)!;
- const isActive = path === selectedPath;
+ const isActive = path === currentPath;
const isDefault =
!!deviceDefaultCwd && getWorkingDirSourcePath(entry) === deviceDefaultCwd;
return (
@@ -171,11 +181,7 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
// 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} />
- )}
+ <DirIcon repoType={current?.repoType} size={14} />
<Text ellipsis className={styles.chipLabel} fontSize={12}>
{chipLabel}
</Text>
diff --git a/src/features/AgentTasks/features/taskExecutionStyles.ts b/src/features/AgentTasks/features/taskExecutionStyles.ts
index b6d44f209ce..901a3d194d8 100644
--- a/src/features/AgentTasks/features/taskExecutionStyles.ts
+++ b/src/features/AgentTasks/features/taskExecutionStyles.ts
@@ -1,7 +1,7 @@
import { createStaticStyles, cssVar } from '@lobehub/ui';
/**
- * Shared look for the task-side execution chips (run location + working
+ * Shared look for the task-side execution chips (environment + working
* directory) and their popover rows.
*
* They live in one module for the reason the chat side keeps `gitChipStyles`:
@@ -37,8 +37,8 @@ export const taskExecutionStyles = createStaticStyles(({ css }) => ({
* 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
+ * that target and only shows once the task stops following the agent. 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.
*/
@@ -92,6 +92,18 @@ export const taskExecutionStyles = createStaticStyles(({ css }) => ({
display: inline-flex;
flex: none;
`,
+ /** What "follow the agent" resolves to, under the switch's description. */
+ followSummary: css`
+ min-width: 0;
+ padding-block-start: 2px;
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ /** The "follow the agent" row: a label block and its switch, aligned with the picker rows. */
+ switchRow: css`
+ padding-block: 6px;
+ padding-inline: 8px;
+ `,
emptyHint: css`
padding-block: 12px;
padding-inline: 8px;
@@ -100,27 +112,6 @@ export const taskExecutionStyles = createStaticStyles(({ css }) => ({
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;
diff --git a/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts b/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts
new file mode 100644
index 00000000000..5fc1ca9374d
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts
@@ -0,0 +1,171 @@
+import type { TaskExecutionConfig } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { seedTaskExecutionSelection, useTaskExecutionSelection } from './useTaskExecutionSelection';
+
+const DEVICE_AGENT = { deviceId: 'device-agent' };
+const DEVICE_OTHER = { deviceId: 'device-other' };
+const AGENT_DIRECTORY = { path: '/repos/lobehub', repoType: 'git' as const };
+
+const mocks = vi.hoisted(() => ({
+ target: {} as Record<string, unknown>,
+}));
+
+vi.mock('./useTaskRunTarget', () => ({
+ useTaskRunTarget: (_agentId: string, pinnedDeviceId?: string) => ({
+ ...mocks.target,
+ deviceId: pinnedDeviceId ?? mocks.target.inheritedDeviceId,
+ }),
+}));
+
+const deviceAgent = () => {
+ mocks.target = {
+ devices: [DEVICE_AGENT, DEVICE_OTHER],
+ inheritedDeviceId: DEVICE_AGENT.deviceId,
+ inheritedDirectory: AGENT_DIRECTORY,
+ };
+};
+
+const cloudAgent = () => {
+ mocks.target = { devices: [DEVICE_OTHER] };
+};
+
+const renderSelection = (value?: TaskExecutionConfig) => {
+ const onChange = vi.fn();
+ const hook = renderHook(
+ ({ current }: { current?: TaskExecutionConfig }) =>
+ useTaskExecutionSelection({ agentId: 'agent-1', onChange, value: current }),
+ { initialProps: { current: value } },
+ );
+ return { onChange, ...hook };
+};
+
+beforeEach(() => {
+ deviceAgent();
+});
+
+describe('useTaskExecutionSelection', () => {
+ // The device and the directory used to carry a "Follow the agent" option each,
+ // so a task could read as "this machine, the agent's folder" while both were
+ // in fact the agent's. Following is one decision covering both axes.
+ it('follows the agent while the task stores no selection', () => {
+ expect(renderSelection().result.current.following).toBe(true);
+ });
+
+ it('is off the agent as soon as either axis belongs to the task', () => {
+ expect(renderSelection({ boundDeviceId: DEVICE_OTHER.deviceId }).result.current.following).toBe(
+ false,
+ );
+ expect(renderSelection({ repos: ['lobehub/lobehub'] }).result.current.following).toBe(false);
+ });
+
+ it('starts from the agent machine and folder when the task stops following', () => {
+ const { onChange, result } = renderSelection();
+
+ act(() => result.current.changeFollowing(false));
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ boundDeviceId: DEVICE_AGENT.deviceId,
+ repos: undefined,
+ workingDirectory: AGENT_DIRECTORY.path,
+ workingDirectoryConfig: AGENT_DIRECTORY,
+ });
+ });
+
+ it('returns both axes to the agent when following is switched back on', () => {
+ const { onChange, result } = renderSelection({
+ boundDeviceId: DEVICE_OTHER.deviceId,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: { path: '/srv/app' },
+ });
+
+ act(() => result.current.changeFollowing(true));
+
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ });
+
+ // A cloud agent has no machine to start from, so nothing is stored yet — the
+ // pickers must still open instead of snapping back to "follow".
+ it('stays off the agent for a cloud agent that has nothing to seed', () => {
+ cloudAgent();
+ const { onChange, result } = renderSelection();
+
+ act(() => result.current.changeFollowing(false));
+
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ expect(result.current.following).toBe(false);
+ });
+
+ it('stays off the agent when the only pin is removed', () => {
+ cloudAgent();
+ const { onChange, rerender, result } = renderSelection();
+
+ act(() => result.current.changeFollowing(false));
+ rerender({ current: { boundDeviceId: DEVICE_OTHER.deviceId } });
+ act(() => result.current.changeDevice(undefined));
+ rerender({ current: undefined });
+
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ expect(result.current.following).toBe(false);
+ });
+
+ // A task reopened with a saved selection mounts as "not following" from the
+ // stored value alone; clearing its last pick in a picker must not flip it back
+ // to following and hide that picker.
+ it('stays off the agent when a restored task clears its last repo', () => {
+ cloudAgent();
+ const { onChange, rerender, result } = renderSelection({ repos: ['lobehub/lobehub'] });
+
+ act(() => result.current.changeRepos(undefined));
+ rerender({ current: undefined });
+
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ expect(result.current.following).toBe(false);
+ });
+
+ it('stays off the agent when a restored task removes its device pin', () => {
+ cloudAgent();
+ const { rerender, result } = renderSelection({ boundDeviceId: DEVICE_OTHER.deviceId });
+
+ act(() => result.current.changeDevice(undefined));
+ rerender({ current: undefined });
+
+ expect(result.current.following).toBe(false);
+ });
+
+ it('pins the machine in force when a folder is picked', () => {
+ const { onChange, result } = renderSelection({ boundDeviceId: DEVICE_OTHER.deviceId });
+
+ act(() => result.current.changeDirectory({ path: '/srv/app' }));
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ boundDeviceId: DEVICE_OTHER.deviceId,
+ repos: undefined,
+ workingDirectory: '/srv/app',
+ workingDirectoryConfig: { path: '/srv/app' },
+ });
+ });
+});
+
+describe('seedTaskExecutionSelection', () => {
+ it('pins the machine without a folder when the agent has none there', () => {
+ expect(
+ seedTaskExecutionSelection({
+ devices: [DEVICE_AGENT] as never,
+ inheritedDeviceId: DEVICE_AGENT.deviceId,
+ }),
+ ).toEqual({ boundDeviceId: DEVICE_AGENT.deviceId });
+ });
+
+ // A workspace task's runs cannot reach a member's private machine.
+ it('pins nothing when the agent machine is outside the task pool', () => {
+ expect(
+ seedTaskExecutionSelection({
+ devices: [DEVICE_OTHER] as never,
+ inheritedDeviceId: DEVICE_AGENT.deviceId,
+ inheritedDirectory: AGENT_DIRECTORY,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskExecutionSelection.ts b/src/features/AgentTasks/features/useTaskExecutionSelection.ts
new file mode 100644
index 00000000000..807e6dad355
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskExecutionSelection.ts
@@ -0,0 +1,130 @@
+'use client';
+
+import type { TaskExecutionConfig, WorkingDirConfig } from '@lobechat/types';
+import {
+ applyTaskDirectorySelection,
+ applyTaskReposSelection,
+ applyTaskTargetSelection,
+ hasTaskExecutionSelection,
+} from '@lobechat/types';
+import { useCallback, useState } from 'react';
+
+import { type TaskRunTarget, useTaskRunTarget } from './useTaskRunTarget';
+
+/**
+ * The selection a task starts from when it stops following the agent: the
+ * machine and folder its runs use right now, written down as the task's own.
+ * Turning "follow" off therefore moves nothing until the user picks something
+ * else — and from then on the agent changing its own environment no longer
+ * moves the task.
+ *
+ * A machine outside the task's pool is left unpinned: a workspace task's
+ * automated runs cannot reach a member's private device, and pinning it would
+ * point every run at a machine they never resolve.
+ */
+export const seedTaskExecutionSelection = (
+ target: Pick<TaskRunTarget, 'devices' | 'inheritedDeviceId' | 'inheritedDirectory'>,
+): TaskExecutionConfig | undefined => {
+ const { devices, inheritedDeviceId, inheritedDirectory } = target;
+ if (!inheritedDeviceId || !devices?.some((device) => device.deviceId === inheritedDeviceId))
+ return undefined;
+
+ return inheritedDirectory
+ ? applyTaskDirectorySelection(undefined, inheritedDirectory, inheritedDeviceId)
+ : { boundDeviceId: inheritedDeviceId };
+};
+
+interface UseTaskExecutionSelectionParams {
+ agentId: string;
+ onChange: (execution?: TaskExecutionConfig) => void;
+ value?: TaskExecutionConfig;
+}
+
+/**
+ * The state behind the task execution controls: whether the task follows the
+ * assignee agent, and how each picker turns into the next stored selection.
+ *
+ * One switch decides both axes — the agent's environment is a machine plus a
+ * folder on it, so following one while picking the other was two controls for a
+ * single decision. Following stores nothing; not following starts from the
+ * agent's current machine and folder ({@link seedTaskExecutionSelection}).
+ */
+export const useTaskExecutionSelection = ({
+ agentId,
+ onChange,
+ value,
+}: UseTaskExecutionSelectionParams) => {
+ const target = useTaskRunTarget(agentId, value?.boundDeviceId);
+ const { deviceId, devices, inheritedDeviceId, inheritedDirectory } = target;
+
+ // "Not following" with nothing picked yet — a cloud agent before any repo, or
+ // a pin just removed — stores nothing, which is indistinguishable from
+ // following. Held here so the pickers stay open until the user switches back:
+ // only the switch returns a task to the agent, never clearing a picker.
+ const [customizing, setCustomizing] = useState(false);
+ const following = !customizing && !hasTaskExecutionSelection(value);
+
+ // Every callback funnels 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],
+ );
+
+ // A picker is only on screen while the task is off the agent, so every pick
+ // keeps it there — including one that clears the last selection of a task
+ // restored with a saved device or repo, which would otherwise read as
+ // "following" and hide the very picker being used.
+ const emitPick = useCallback(
+ (next?: TaskExecutionConfig) => {
+ setCustomizing(true);
+ emit(next);
+ },
+ [emit],
+ );
+
+ const changeFollowing = useCallback(
+ (follow: boolean) => {
+ setCustomizing(!follow);
+ emit(
+ follow
+ ? undefined
+ : seedTaskExecutionSelection({ devices, inheritedDeviceId, inheritedDirectory }),
+ );
+ },
+ [devices, emit, inheritedDeviceId, inheritedDirectory],
+ );
+
+ const changeDevice = useCallback(
+ (nextDeviceId?: string) => {
+ const next = applyTaskTargetSelection(value, nextDeviceId);
+ // 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.
+ if (next === value) return;
+ emitPick(next);
+ },
+ [emitPick, value],
+ );
+
+ const changeRepos = useCallback(
+ (repos?: string[]) => {
+ emitPick(applyTaskReposSelection(value, repos));
+ },
+ [emitPick, value],
+ );
+
+ const changeDirectory = 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.
+ emitPick(applyTaskDirectorySelection(value, config, deviceId));
+ },
+ [deviceId, emitPick, value],
+ );
+
+ return { changeDevice, changeDirectory, changeFollowing, changeRepos, following, target };
+};
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.ts b/src/features/AgentTasks/features/useTaskRunTarget.ts
index 76c428bd229..fc977b94246 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts
@@ -74,6 +74,11 @@ export interface TaskRunTarget {
directoryKind: TaskDirectoryKind;
/** Where the run lands: the task's pin if it has one, else the agent's own target. */
effectiveTarget: DeviceExecutionTarget;
+ /**
+ * The machine the assignee agent's own target lands on, when it names one. The
+ * "follow the agent" state starts from it, and the device list marks it.
+ */
+ inheritedDeviceId?: string;
/**
* 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
@@ -188,13 +193,13 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
// dead "Follow agent" hint, although the run starts in a path on a machine.
// Picking a directory then pins this machine (`applyTaskDirectorySelection`),
// so the run is routed to where the path exists.
- const deviceId = pinApplies
- ? pinnedDeviceId
- : inheritedTarget === 'device'
+ const inheritedDeviceId =
+ inheritedTarget === 'device'
? agencyConfig?.boundDeviceId
: inheritedTarget === 'local'
? localDeviceId
: undefined;
+ const deviceId = pinApplies ? pinnedDeviceId : inheritedDeviceId;
// From the device list this hook already fetched, not the device store,
// which a task page may never populate.
@@ -263,6 +268,7 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
devicesFailed,
directoryKind,
effectiveTarget,
+ inheritedDeviceId,
inheritedDirectory,
inheritedLabel,
inheritedTarget,