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(desktop): enroll this machine into the workspace as a private device (#22826)

Rdmclin2b13c426a297e
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index 45f3f2970c5..5089e7fa56e 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "قم بتشغيل الوكلاء مع الوصول إلى جهاز الكمبيوتر الخاص بك",
"heteroAgent.executionTarget.downloadDesktopTitle": "احصل على تطبيق سطح المكتب",
"heteroAgent.executionTarget.fixedTip": "بيئة التنفيذ ثابتة في ملف تعريف الوكيل ولا يمكن تغييرها أثناء الدردشة.",
- "heteroAgent.executionTarget.gateway": "البوابة",
- "heteroAgent.executionTarget.gatewayDesc": "التشغيل عبر بوابة الجهاز بحيث يمكن للعملاء الآخرين متابعة التقدم",
"heteroAgent.executionTarget.infoTooltip": "اختر مكان تشغيل هذا الوكيل. يمكن للجهاز قراءة وكتابة الملفات أو تشغيل جهاز كمبيوتر؛ يعمل Cloud Sandbox في بيئة مؤقتة معزولة.",
"heteroAgent.executionTarget.loadFailed": "تعذر تحميل الأجهزة.",
"heteroAgent.executionTarget.loading": "جارٍ تحميل الأجهزة...",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 36ef5aaac33..ba74dac8fc6 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Führen Sie Agenten mit Zugriff auf Ihren Computer aus",
"heteroAgent.executionTarget.downloadDesktopTitle": "Desktop-App herunterladen",
"heteroAgent.executionTarget.fixedTip": "Die Ausführungsumgebung ist im Agentenprofil festgelegt und kann während des Chats nicht gewechselt werden.",
- "heteroAgent.executionTarget.gateway": "Gateway",
- "heteroAgent.executionTarget.gatewayDesc": "Über das Geräte-Gateway ausführen, damit andere Clients den Fortschritt verfolgen können",
"heteroAgent.executionTarget.infoTooltip": "Wählen Sie aus, wo dieser Agent ausgeführt wird. Ein Gerät kann Dateien lesen und schreiben oder einen Computer bedienen; Cloud Sandbox läuft in einer isolierten temporären Umgebung.",
"heteroAgent.executionTarget.loadFailed": "Geräte konnten nicht geladen werden.",
"heteroAgent.executionTarget.loading": "Geräte werden geladen…",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4b3b0a869ab..d50ab3985ec 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1521,8 +1521,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Run agents with access to your computer",
"heteroAgent.executionTarget.downloadDesktopTitle": "Get the desktop app",
"heteroAgent.executionTarget.fixedTip": "The execution environment is fixed in the Agent Profile and cannot be switched while chatting.",
- "heteroAgent.executionTarget.gateway": "Gateway",
- "heteroAgent.executionTarget.gatewayDesc": "Run through the device gateway so other clients can follow progress",
"heteroAgent.executionTarget.infoTooltip": "Choose where this Agent runs. A device can read and write files or operate a computer; Cloud Sandbox runs in an isolated temporary environment.",
"heteroAgent.executionTarget.loadFailed": "Couldn’t load devices.",
"heteroAgent.executionTarget.loading": "Loading devices…",
@@ -1555,6 +1553,7 @@
"heteroAgent.executionTarget.switchTopic.content": "This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.",
"heteroAgent.executionTarget.switchTopic.ok": "Switch",
"heteroAgent.executionTarget.switchTopic.title": "Move this topic to another environment?",
+ "heteroAgent.executionTarget.thisDevice": "This device",
"heteroAgent.executionTarget.title": "Execution Environment",
"heteroAgent.executionTarget.topicTag": "This topic",
"heteroAgent.executionTarget.unknownDevice": "Unknown device",
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 3834ec017eb..e2699c144ff 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -1,4 +1,5 @@
{
+ "gateway.autoEnroll.success": "This computer was added to this workspace as your private device. Only you can run agents on it.",
"gateway.enableConnection": "Connect to Gateway",
"gateway.error.authRejected": "Device Gateway rejected this sign-in. Retry or sign in again. If it persists, ask your server administrator to check the gateway configuration.",
"gateway.error.configUnavailable": "Couldn't load this server's configuration. Check your connection and retry.",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 27833acfb3b..ad474f950c9 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Ejecuta agentes con acceso a tu computadora",
"heteroAgent.executionTarget.downloadDesktopTitle": "Obtener la aplicación de escritorio",
"heteroAgent.executionTarget.fixedTip": "El entorno de ejecución está fijado en el Perfil del Agente y no se puede cambiar mientras se está conversando.",
- "heteroAgent.executionTarget.gateway": "Puerta de enlace",
- "heteroAgent.executionTarget.gatewayDesc": "Ejecutar a través de la puerta de enlace del dispositivo para que otros clientes puedan seguir el progreso",
"heteroAgent.executionTarget.infoTooltip": "Elige dónde se ejecuta este Agente. Un dispositivo puede leer y escribir archivos o operar una computadora; Cloud Sandbox se ejecuta en un entorno temporal aislado.",
"heteroAgent.executionTarget.loadFailed": "No se pudieron cargar los dispositivos.",
"heteroAgent.executionTarget.loading": "Cargando dispositivos…",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index a9d24ac8f56..1b081610bec 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "컴퓨터에 액세스할 수 있는 에이전트를 실행하세요",
"heteroAgent.executionTarget.downloadDesktopTitle": "데스크톱 앱 받기",
"heteroAgent.executionTarget.fixedTip": "실행 환경은 에이전트 프로필에서 고정되어 있으며 채팅 중에는 변경할 수 없습니다.",
- "heteroAgent.executionTarget.gateway": "게이트웨이",
- "heteroAgent.executionTarget.gatewayDesc": "장치 게이트웨이를 통해 실행하여 다른 클라이언트가 진행 상황을 따라갈 수 있도록 합니다",
"heteroAgent.executionTarget.infoTooltip": "이 에이전트가 실행되는 위치를 선택하세요. 장치는 파일을 읽고 쓰거나 컴퓨터를 작동시킬 수 있으며, 클라우드 샌드박스는 격리된 임시 환경에서 실행됩니다.",
"heteroAgent.executionTarget.loadFailed": "장치를 로드할 수 없습니다.",
"heteroAgent.executionTarget.loading": "장치 로드 중…",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 81165136d50..3e76aec424a 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Uruchamiaj agentów z dostępem do swojego komputera",
"heteroAgent.executionTarget.downloadDesktopTitle": "Pobierz aplikację na komputer",
"heteroAgent.executionTarget.fixedTip": "Środowisko wykonawcze jest ustalone w profilu agenta i nie można go zmienić podczas rozmowy.",
- "heteroAgent.executionTarget.gateway": "Brama",
- "heteroAgent.executionTarget.gatewayDesc": "Uruchom przez bramę urządzenia, aby inne klienty mogły śledzić postęp",
"heteroAgent.executionTarget.infoTooltip": "Wybierz, gdzie działa ten Agent. Urządzenie może odczytywać i zapisywać pliki lub obsługiwać komputer; Cloud Sandbox działa w izolowanym tymczasowym środowisku.",
"heteroAgent.executionTarget.loadFailed": "Nie udało się załadować urządzeń.",
"heteroAgent.executionTarget.loading": "Ładowanie urządzeń…",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index b12187de3fa..ad4d753bc80 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Execute agentes com acesso ao seu computador",
"heteroAgent.executionTarget.downloadDesktopTitle": "Obter o aplicativo para desktop",
"heteroAgent.executionTarget.fixedTip": "O ambiente de execução está fixado no Perfil do Agente e não pode ser alterado durante a conversa.",
- "heteroAgent.executionTarget.gateway": "Gateway",
- "heteroAgent.executionTarget.gatewayDesc": "Execute através do gateway do dispositivo para que outros clientes possam acompanhar o progresso",
"heteroAgent.executionTarget.infoTooltip": "Escolha onde este Agente será executado. Um dispositivo pode ler e escrever arquivos ou operar um computador; o Cloud Sandbox funciona em um ambiente temporário isolado.",
"heteroAgent.executionTarget.loadFailed": "Não foi possível carregar os dispositivos.",
"heteroAgent.executionTarget.loading": "Carregando dispositivos…",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 50f0b3f4739..1498795fd03 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Запускайте агентов с доступом к вашему компьютеру",
"heteroAgent.executionTarget.downloadDesktopTitle": "Скачать приложение для компьютера",
"heteroAgent.executionTarget.fixedTip": "Среда выполнения фиксирована в профиле агента и не может быть изменена во время общения.",
- "heteroAgent.executionTarget.gateway": "Шлюз",
- "heteroAgent.executionTarget.gatewayDesc": "Запуск через шлюз устройства, чтобы другие клиенты могли следить за прогрессом",
"heteroAgent.executionTarget.infoTooltip": "Выберите, где будет работать этот агент. Устройство может читать и записывать файлы или управлять компьютером; Cloud Sandbox работает в изолированной временной среде.",
"heteroAgent.executionTarget.loadFailed": "Не удалось загрузить устройства.",
"heteroAgent.executionTarget.loading": "Загрузка устройств…",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 4b50de8b016..17e97786721 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -1517,8 +1517,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "Chạy các tác nhân với quyền truy cập vào máy tính của bạn",
"heteroAgent.executionTarget.downloadDesktopTitle": "Tải ứng dụng máy tính",
"heteroAgent.executionTarget.fixedTip": "Môi trường thực thi đã được cố định trong Hồ sơ Đại lý và không thể thay đổi trong khi trò chuyện.",
- "heteroAgent.executionTarget.gateway": "Cổng",
- "heteroAgent.executionTarget.gatewayDesc": "Chạy qua cổng thiết bị để các khách hàng khác có thể theo dõi tiến trình",
"heteroAgent.executionTarget.infoTooltip": "Chọn nơi Agent này chạy. Một thiết bị có thể đọc và ghi tệp hoặc vận hành máy tính; Cloud Sandbox chạy trong môi trường tạm thời cách ly.",
"heteroAgent.executionTarget.loadFailed": "Không thể tải thiết bị.",
"heteroAgent.executionTarget.loading": "Đang tải thiết bị…",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 67dc0ccca32..a8e4b9ab3ec 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1521,8 +1521,6 @@
"heteroAgent.executionTarget.downloadDesktopDesc": "让 Agent 直接连接你的电脑",
"heteroAgent.executionTarget.downloadDesktopTitle": "下载桌面端",
"heteroAgent.executionTarget.fixedTip": "执行环境已在助理档案中固定,聊天时不可切换。",
- "heteroAgent.executionTarget.gateway": "网关",
- "heteroAgent.executionTarget.gatewayDesc": "经由设备网关运行,其他客户端可跟踪进度",
"heteroAgent.executionTarget.infoTooltip": "选择此代理运行的位置。设备可以读取和写入文件或操作计算机;云沙盒在隔离的临时环境中运行。",
"heteroAgent.executionTarget.loadFailed": "设备加载失败。",
"heteroAgent.executionTarget.loading": "正在加载设备…",
@@ -1555,6 +1553,7 @@
"heteroAgent.executionTarget.switchTopic.content": "本话题一直在「{{name}}」上运行,工作目录和会话都保存在那里。切换后,下一轮会在新环境中开启新会话;之后的新话题也会使用这个选择。",
"heteroAgent.executionTarget.switchTopic.ok": "切换",
"heteroAgent.executionTarget.switchTopic.title": "将本话题切换到其他执行环境?",
+ "heteroAgent.executionTarget.thisDevice": "本机",
"heteroAgent.executionTarget.title": "执行环境",
"heteroAgent.executionTarget.topicTag": "本话题",
"heteroAgent.executionTarget.unknownDevice": "未知设备",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index e097f4c4ade..44cbb95980d 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -1,4 +1,5 @@
{
+ "gateway.autoEnroll.success": "已将本机添加为当前工作区的私人设备,仅你可以在上面运行助理。",
"gateway.enableConnection": "连接到网关",
"gateway.error.authRejected": "设备网关拒绝了当前登录凭证。请重试或重新登录;若仍有问题,请联系服务器管理员检查网关配置。",
"gateway.error.configUnavailable": "无法读取当前服务器的配置。请检查网络后重试。",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 8d95214089e..c084bff06eb 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -915,9 +915,6 @@ export default {
'The execution environment is fixed in the Agent Profile and cannot be switched while chatting.',
'heteroAgent.executionTarget.infoTooltip':
'Choose where this Agent runs. A device can read and write files or operate a computer; Cloud Sandbox runs in an isolated temporary environment.',
- 'heteroAgent.executionTarget.gateway': 'Gateway',
- 'heteroAgent.executionTarget.gatewayDesc':
- 'Run through the device gateway so other clients can follow progress',
'heteroAgent.executionTarget.loadFailed': 'Couldn’t load devices.',
'heteroAgent.executionTarget.loading': 'Loading devices…',
'heteroAgent.executionTarget.local': 'Local device',
@@ -963,6 +960,7 @@ export default {
'This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.',
'heteroAgent.executionTarget.switchTopic.ok': 'Switch',
'heteroAgent.executionTarget.switchTopic.title': 'Move this topic to another environment?',
+ 'heteroAgent.executionTarget.thisDevice': 'This device',
'heteroAgent.executionTarget.unknownDevice': 'Unknown device',
'heteroAgent.executionTarget.wake': 'Wake now',
'heteroAgent.executionTarget.wakeFailed': 'Could not wake this cloud device. Try again.',
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 248a2ede4d0..b8c7d680929 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -123,6 +123,8 @@ export default {
'proxy.validation.serverRequired': 'Server address is required when proxy is enabled',
'proxy.validation.typeRequired': 'Proxy type is required when proxy is enabled',
'proxy.validation.usernameRequired': 'Username is required when authentication is enabled',
+ 'gateway.autoEnroll.success':
+ 'This computer was added to this workspace as your private device. Only you can run agents on it.',
'gateway.enableConnection': 'Connect to Gateway',
'gateway.error.authRejected':
'Device Gateway rejected this sign-in. Retry or sign in again. If it persists, ask your server administrator to check the gateway configuration.',
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
index ceef897db17..bf97bb7c122 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskExecutionConfig.tsx
@@ -7,6 +7,8 @@ import { memo, useCallback, useMemo } from 'react';
import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import TaskExecutionControls from '../features/TaskExecutionControls';
@@ -28,6 +30,8 @@ const TaskExecutionConfig = memo(() => {
const taskConfig = useTaskStore((s) => taskDetailSelectors.activeTaskDetail(s)?.config);
const updateTaskExecution = useTaskStore((s) => s.updateTaskExecution);
const { allowed: canEditTask } = usePermission('create_content');
+ const userId = useUserStore(userProfileSelectors.userId);
+ const createdByUserId = useTaskStore(taskDetailSelectors.activeTaskCreatedByUserId);
// 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
@@ -48,6 +52,7 @@ const TaskExecutionConfig = memo(() => {
return (
<TaskExecutionControls
assigneeAgentId={assigneeAgentId}
+ canPinPrivateDevices={!!userId && createdByUserId === userId}
disabled={!canEditTask}
key={taskId}
value={execution}
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index 0a907dc60b1..b1c7395a979 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -933,6 +933,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
)}
<TaskExecutionControls
+ canPinPrivateDevices
assigneeAgentId={assigneeAgentId}
disabled={!canCreateTask}
value={execution}
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index bd8c3970b50..e02236eca18 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -535,6 +535,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
)}
<TaskExecutionControls
+ canPinPrivateDevices
assigneeAgentId={assigneeAgentId}
disabled={!canCreateTask}
value={execution}
diff --git a/src/features/AgentTasks/features/TaskDeviceChip.tsx b/src/features/AgentTasks/features/TaskDeviceChip.tsx
index 38d16481db9..aa65a3aa8ea 100644
--- a/src/features/AgentTasks/features/TaskDeviceChip.tsx
+++ b/src/features/AgentTasks/features/TaskDeviceChip.tsx
@@ -16,6 +16,8 @@ import { deviceLabel, getTaskDeviceLockReason, useTaskRunTarget } from './useTas
interface TaskDeviceChipProps {
/** The assignee whose execution environment is inherited when nothing is pinned. */
agentId: string;
+ /** The caller is the task's creator (or is creating it); see `devicePoolForTask`. */
+ canPinPrivateDevices: boolean;
/**
* Row class for the trigger. Omitted → the composer's compact chip; the task
* detail's header row passes its own chip-sized class instead.
@@ -62,6 +64,7 @@ interface TaskDeviceChipProps {
const TaskDeviceChip = memo<TaskDeviceChipProps>(
({
agentId,
+ canPinPrivateDevices,
className,
disabled,
followDirectory,
@@ -84,7 +87,7 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
isPending,
pinnedDeviceId,
retryDevices,
- } = useTaskRunTarget(agentId, value);
+ } = useTaskRunTarget(agentId, value, { canPinPrivateDevices });
// 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
diff --git a/src/features/AgentTasks/features/TaskExecutionControls.tsx b/src/features/AgentTasks/features/TaskExecutionControls.tsx
index fd281ac260a..81ed30c885d 100644
--- a/src/features/AgentTasks/features/TaskExecutionControls.tsx
+++ b/src/features/AgentTasks/features/TaskExecutionControls.tsx
@@ -15,6 +15,12 @@ import { useTaskExecutionSelection } from './useTaskExecutionSelection';
interface TaskExecutionControlsProps {
/** The assignee whose execution environment a task inherits by default. */
assigneeAgentId?: string;
+ /**
+ * The caller is the task's creator, or is creating it. A task's scheduled
+ * runs execute as its creator, so only then may it pin the caller's own
+ * private workspace devices (see `devicePoolForTask`).
+ */
+ canPinPrivateDevices: boolean;
disabled?: boolean;
onChange: (execution?: TaskExecutionConfig) => void;
/** The task's current selection; empty means "inherit the agent". */
@@ -56,10 +62,15 @@ const TaskExecutionControls = memo<TaskExecutionControlsProps>((props) => {
const TaskExecutionControlsInner = memo<
Omit<TaskExecutionControlsProps, 'assigneeAgentId'> & { assigneeAgentId: string }
->(({ assigneeAgentId, disabled, onChange, value }) => {
+>(({ assigneeAgentId, canPinPrivateDevices, disabled, onChange, value }) => {
const canExecuteSomewhere = useTaskExecutionAvailability(assigneeAgentId);
const { changeDevice, changeDirectory, changeFollowing, changeRepos, following, target } =
- useTaskExecutionSelection({ agentId: assigneeAgentId, onChange, value });
+ useTaskExecutionSelection({
+ agentId: assigneeAgentId,
+ canPinPrivateDevices,
+ onChange,
+ value,
+ });
if (!canExecuteSomewhere) return null;
@@ -71,6 +82,7 @@ const TaskExecutionControlsInner = memo<
<>
<TaskDeviceChip
agentId={assigneeAgentId}
+ canPinPrivateDevices={canPinPrivateDevices}
disabled={disabled}
following={following}
value={value?.boundDeviceId}
diff --git a/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts b/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts
index 5fc1ca9374d..92020ef3b71 100644
--- a/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts
+++ b/src/features/AgentTasks/features/useTaskExecutionSelection.test.ts
@@ -35,7 +35,12 @@ const renderSelection = (value?: TaskExecutionConfig) => {
const onChange = vi.fn();
const hook = renderHook(
({ current }: { current?: TaskExecutionConfig }) =>
- useTaskExecutionSelection({ agentId: 'agent-1', onChange, value: current }),
+ useTaskExecutionSelection({
+ agentId: 'agent-1',
+ canPinPrivateDevices: true,
+ onChange,
+ value: current,
+ }),
{ initialProps: { current: value } },
);
return { onChange, ...hook };
diff --git a/src/features/AgentTasks/features/useTaskExecutionSelection.ts b/src/features/AgentTasks/features/useTaskExecutionSelection.ts
index 807e6dad355..d6048180497 100644
--- a/src/features/AgentTasks/features/useTaskExecutionSelection.ts
+++ b/src/features/AgentTasks/features/useTaskExecutionSelection.ts
@@ -18,9 +18,9 @@ import { type TaskRunTarget, useTaskRunTarget } from './useTaskRunTarget';
* 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.
+ * A machine outside the task's pool is left unpinned: a workspace task's runs
+ * cannot reach a member's personal device, and pinning it would point every run
+ * at a machine they never resolve.
*/
export const seedTaskExecutionSelection = (
target: Pick<TaskRunTarget, 'devices' | 'inheritedDeviceId' | 'inheritedDirectory'>,
@@ -36,6 +36,8 @@ export const seedTaskExecutionSelection = (
interface UseTaskExecutionSelectionParams {
agentId: string;
+ /** The caller is the task's creator (or is creating it); see `devicePoolForTask`. */
+ canPinPrivateDevices: boolean;
onChange: (execution?: TaskExecutionConfig) => void;
value?: TaskExecutionConfig;
}
@@ -51,10 +53,11 @@ interface UseTaskExecutionSelectionParams {
*/
export const useTaskExecutionSelection = ({
agentId,
+ canPinPrivateDevices,
onChange,
value,
}: UseTaskExecutionSelectionParams) => {
- const target = useTaskRunTarget(agentId, value?.boundDeviceId);
+ const target = useTaskRunTarget(agentId, value?.boundDeviceId, { canPinPrivateDevices });
const { deviceId, devices, inheritedDeviceId, inheritedDirectory } = target;
// "Not following" with nothing picked yet — a cloud agent before any repo, or
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.test.ts b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
index e5135c14397..d6a4f07c7b4 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.test.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
@@ -103,6 +103,8 @@ beforeEach(() => {
mocks.electron = { currentDeviceId: undefined, isDesktop: false };
});
+const AS_CREATOR = { canPinPrivateDevices: true };
+
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.
@@ -110,7 +112,9 @@ describe('useTaskRunTarget', () => {
mocks.devices = [PERSONAL_DEVICE];
mocks.devicesConfirmed = false;
- const { result, rerender } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result, rerender } = renderHook(() =>
+ useTaskRunTarget('agent-1', undefined, AS_CREATOR),
+ );
// A stored row may since have been deleted or unshared: no pin from it yet.
expect(result.current.isPending).toBe(true);
@@ -126,7 +130,7 @@ describe('useTaskRunTarget', () => {
mocks.devicesConfirmed = false;
mocks.devicesError = new Error('network down');
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
// Not stuck pending: the chip opens and says why, offering a retry.
expect(result.current.isPending).toBe(false);
@@ -142,7 +146,7 @@ describe('useTaskRunTarget', () => {
agencyConfig: { ...deviceBoundAgent, boundDeviceId: 'device-chat-topic' },
};
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
});
@@ -153,7 +157,7 @@ describe('useTaskRunTarget', () => {
// no way to pick a directory even though the runner supports one.
mocks.agency.agencyConfig = deviceBoundAgent;
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
expect(result.current.directoryKind).toBe('device');
@@ -169,7 +173,7 @@ describe('useTaskRunTarget', () => {
heterogeneousProvider: { type: 'claude-code' },
};
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.inheritedTarget).toBe('local');
expect(result.current.deviceId).toBe('device-this-desktop');
@@ -185,7 +189,7 @@ describe('useTaskRunTarget', () => {
heterogeneousProvider: { type: 'claude-code' },
};
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
expect(result.current.directoryKind).toBe('device');
@@ -202,7 +206,7 @@ describe('useTaskRunTarget', () => {
heterogeneousProvider: { type: 'claude-code' },
};
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.deviceId).toBeUndefined();
expect(result.current.directoryKind).not.toBe('device');
@@ -218,7 +222,7 @@ describe('useTaskRunTarget', () => {
};
mocks.agency.canSelectExecutionTarget = false;
- const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN, AS_CREATOR));
expect(result.current.pinnedDeviceId).toBeUndefined();
expect(result.current.isDeviceTarget).toBe(false);
@@ -230,7 +234,7 @@ describe('useTaskRunTarget', () => {
mocks.agency.agencyConfig = deviceBoundAgent;
mocks.agency.canSelectExecutionTarget = false;
- const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN, AS_CREATOR));
expect(result.current.pinnedDeviceId).toBeUndefined();
expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
@@ -242,7 +246,7 @@ describe('useTaskRunTarget', () => {
heterogeneousProvider: { type: 'claude-code' },
};
- const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', DEVICE_TASK_PIN, AS_CREATOR));
expect(result.current.pinnedDeviceId).toBe(DEVICE_TASK_PIN);
expect(result.current.isDeviceTarget).toBe(true);
@@ -260,7 +264,9 @@ describe('useTaskRunTarget', () => {
mocks.agentState.agentMap = { 'agent-1': { workspaceId: 'ws-1' } };
mocks.devices = [PERSONAL_DEVICE, WORKSPACE_DEVICE];
- const { result } = renderHook(() => useTaskRunTarget('agent-1', PERSONAL_DEVICE.deviceId));
+ const { result } = renderHook(() =>
+ useTaskRunTarget('agent-1', PERSONAL_DEVICE.deviceId, AS_CREATOR),
+ );
expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
WORKSPACE_DEVICE.deviceId,
@@ -268,18 +274,37 @@ describe('useTaskRunTarget', () => {
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.
+ it('offers a collaborator on someone else’s task only public workspace devices', () => {
+ // Scheduled runs execute as the task's creator, who cannot resolve a
+ // collaborator's private workspace device.
+ 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', undefined, { canPinPrivateDevices: false }),
+ );
+
+ expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
+ WORKSPACE_DEVICE.deviceId,
+ ]);
+ });
+
+ it('offers the task creator their own private devices with the public pool', () => {
+ // A device list only carries the caller's own private rows, and a Task's
+ // runs execute as its creator, who resolves the machine they enrolled.
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'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
expect(result.current.devices?.map((device) => device.deviceId)).toEqual([
+ 'device-private',
WORKSPACE_DEVICE.deviceId,
]);
});
@@ -287,7 +312,7 @@ describe('useTaskRunTarget', () => {
it('offers an agent outside a workspace only its own machines', () => {
mocks.devices = [PERSONAL_DEVICE, WORKSPACE_DEVICE];
- const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+ const { result } = renderHook(() => useTaskRunTarget('agent-1', undefined, AS_CREATOR));
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
index fc977b94246..08914dd5c9f 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts
@@ -125,7 +125,12 @@ export interface TaskRunTarget {
* 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 => {
+export const useTaskRunTarget = (
+ agentId: string,
+ pinnedDeviceId: string | undefined,
+ /** The caller is the task's creator, so their own private devices are pinnable. */
+ { canPinPrivateDevices }: { canPinPrivateDevices: boolean },
+): TaskRunTarget => {
const { t } = useTranslation('chat');
const {
data: devices,
@@ -154,11 +159,12 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
// 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`).
+ // The caller's own private rows only when they are the task's creator, whose
+ // identity the scheduled runs use (see `devicePoolForTask`).
const agentPool = devicePoolForAgent(devices, !!agentWorkspaceId);
- const pool = devicePoolForTask(devices, !!agentWorkspaceId);
+ const pool = devicePoolForTask(devices, !!agentWorkspaceId, {
+ includeOwnPrivate: canPinPrivateDevices,
+ });
const inheritedTarget = resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: isDesktop,
@@ -176,9 +182,9 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
const pinApplies = !!pinnedDeviceId && canSelectExecutionTarget;
const isDeviceTarget = pinApplies;
const effectiveTarget: DeviceExecutionTarget = pinApplies ? 'device' : inheritedTarget;
- // A workspace agent's `local` target is the member's own machine, which the
- // task's automation and collaborators cannot resolve unless it is in the task
- // pool (public workspace devices); offering it would pin an unreachable device.
+ // A workspace agent's `local` target is the member's own personal machine,
+ // which is never in a workspace task pool; offering it would pin a device the
+ // task's runs cannot resolve.
const localCandidate = agencyConfig?.boundDeviceId || currentDeviceId;
const localDeviceId =
localCandidate &&
diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
index c8878f3283c..0dc661ce643 100644
--- a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
@@ -22,8 +22,6 @@ const styles = stylex.create({
interface DeviceOptionRowProps {
active: boolean;
device: DeviceListItem;
- /** This app's own machine: described as the local process instead of by status. */
- isCurrentMachine: boolean;
onReconnect: () => void;
onSelect: () => void;
reconnecting: boolean;
@@ -37,7 +35,6 @@ interface DeviceOptionRowProps {
const DeviceOptionRow = ({
active,
device,
- isCurrentMachine,
onReconnect,
onSelect,
reconnecting,
@@ -65,19 +62,15 @@ const DeviceOptionRow = ({
tags={tags}
desc={
<>
- {isCurrentMachine ? (
- t('heteroAgent.executionTarget.gatewayDesc')
- ) : (
- <ExecutionTargetDeviceStatus
- offlineLabel={t(offlineLabelKey)}
- online={device.online}
- unknown={presenceUnknown}
- unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
- onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
- count: device.channels.length,
- })}
- />
- )}
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t(offlineLabelKey)}
+ online={device.online}
+ unknown={presenceUnknown}
+ unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
+ onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
+ count: device.channels.length,
+ })}
+ />
{showReconnect ? (
<Button
className={stylex.props(styles.reconnectButton).className}
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index a00a45534a4..7e7e0396f79 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -27,6 +27,8 @@ import DeviceLoadMeter, { useDeviceLoad } from '@/features/DeviceManager/DeviceL
import {
devicePoolForAgent,
ExecutionTargetIcon,
+ findOwnWorkspaceDevice,
+ getMachineDefaultTarget,
groupExecutionTargetDevices,
} from '@/features/ExecutionTargetPicker';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -37,6 +39,7 @@ import {
} from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
import { deviceService } from '@/services/device';
import { localFileService } from '@/services/electron/localFileService';
import { useAgentStore } from '@/store/agent';
@@ -245,6 +248,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
useElectronStore((s) => s.useFetchGatewayDeviceInfo)();
const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
+ // Both ids this machine holds — personal, and its row in the active
+ // workspace — so the workspace row reads as this machine too.
+ const localMachineDeviceIds = useLocalMachineDeviceIds();
const [reconnectingDeviceId, setReconnectingDeviceId] = useState<string>();
const handleReconnectDevice = useCallback(
@@ -257,7 +263,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// device list instead of making the user close and reopen the picker.
const outcome = await reconnectDevice(
device,
- { isCurrentMachine: isDesktop && device.deviceId === currentDeviceId },
+ { isCurrentMachine: isDesktop && localMachineDeviceIds.includes(device.deviceId) },
{
connectGateway: () => useElectronStore.getState().connectGateway(),
openDeepLink: (url) => {
@@ -282,13 +288,21 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
setReconnectingDeviceId(undefined);
}
},
- [currentDeviceId, refreshDevices, t],
+ [localMachineDeviceIds, refreshDevices, t],
);
// A member's explicit target override may resolve `local`; without one the
// raw shared fallback stays workspace-scoped so a legacy `local` value keeps
// routing to its bound workspace device rather than this member's desktop.
const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
+ // This machine's own row in a workspace agent's pool. Once it exists, "run on
+ // this machine" goes through the gateway on that row — which Tasks and other
+ // surfaces can resolve — rather than the in-app `local` path. Only when the
+ // agent routes through the gateway at all.
+ const ownWorkspaceDevice =
+ isDesktop && isWorkspaceAgent && isDeviceListConfirmed && deviceRoutingAvailable
+ ? findOwnWorkspaceDevice(devices, localMachineDeviceIds)
+ : undefined;
const executionTarget = resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: isDesktop,
deviceRoutingAvailable,
@@ -399,19 +413,39 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
if (!isDesktop) return;
if (!canShowExecutionTargetSelector) return;
if (isWorkspacePreferenceLoading) return;
- if (agencyConfig?.executionTarget !== undefined) return;
- if (agencyConfig?.boundDeviceId !== undefined) return;
if (!currentDeviceId) return;
+ // Whether this machine has a workspace row is only known once the server
+ // confirms the list; deciding earlier would write `local` and then move it.
+ // A failed list falls back to `local` rather than leaving no default.
+ if (isWorkspaceAgent && !isDeviceListConfirmed && !deviceListError) return;
+ // A workspace agent whose pool holds this machine runs on that row through
+ // the gateway. A plain `local` pick (not the sandboxed one, which only the
+ // in-app path can fence) moves over to it too.
+ const defaultTarget = getMachineDefaultTarget({
+ executionTarget: agencyConfig?.executionTarget,
+ boundDeviceId: agencyConfig?.boundDeviceId,
+ // Without an override of the member's own, a stored `local` is the
+ // agent's legacy shared value, not their pick: leave it alone.
+ isOwnPick: !workspaceScoped,
+ localSandboxEnabled,
+ ownWorkspaceDeviceId: ownWorkspaceDevice?.deviceId,
+ });
+ if (!defaultTarget) return;
// `silent`: this is a mount-time default, so a rejected write must not
// surface a save-failure toast on an agent the user only opened.
- void selectExecutionTarget('local', undefined, { silent: true });
+ void selectExecutionTarget(defaultTarget.target, defaultTarget.deviceId, { silent: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
agencyConfig?.executionTarget,
agencyConfig?.boundDeviceId,
currentDeviceId,
canShowExecutionTargetSelector,
+ deviceListError,
+ isDeviceListConfirmed,
isWorkspacePreferenceLoading,
+ workspaceScoped,
+ localSandboxEnabled,
+ ownWorkspaceDevice?.deviceId,
]);
const boundDevice =
@@ -529,17 +563,17 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
};
const renderDeviceRow = (d: NonNullable<typeof devices>[number]) => {
- const isCurrentMachine = d.deviceId === currentDeviceId;
+ const isCurrentMachine = localMachineDeviceIds.includes(d.deviceId);
return (
<DeviceOptionRow
active={isActive('device', d.deviceId)}
device={d}
- isCurrentMachine={isCurrentMachine}
key={d.deviceId}
reconnecting={reconnectingDeviceId === d.deviceId}
tags={tagsFor(
isActive('device', d.deviceId),
- isCurrentMachine ? [t('heteroAgent.executionTarget.gateway')] : [],
+ // Users pick a machine, not a transport: tag this one as "This device".
+ isCurrentMachine ? [t('heteroAgent.executionTarget.thisDevice')] : [],
)}
onReconnect={() => void handleReconnectDevice(d)}
onSelect={() => void handleSelect('device', d.deviceId)}
@@ -607,7 +641,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
`local` pick lands in `users.preference.agentDeviceOverrides` — my
per-user override — so it never binds the workspace-shared
`agencyConfig` or coerces any other member's dispatch. */}
- {isDesktop ? (
+ {/* Hidden once this machine has its own workspace row (listed below,
+ tagged as this machine), unless it is still the active pick. */}
+ {isDesktop && (!ownWorkspaceDevice || isActive('local')) ? (
<OptionRow
active={isActive('local')}
desc={t('heteroAgent.executionTarget.localDesc')}
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
index 0e7acae37f9..18cbe6362d7 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -31,6 +31,8 @@ const testState = vi.hoisted(() => ({
},
getDeviceInfo: vi.fn(),
isDesktop: false,
+ devices: [] as { deviceId: string; visibility?: 'private' | 'public' }[],
+ localMachineDeviceIds: [] as string[],
user: {
updateWorkspaceUserPreference: vi.fn(),
workspaceUserPreference: {} as {
@@ -62,6 +64,18 @@ vi.mock('@/services/electron/gatewayConnection', () => ({
},
}));
+vi.mock('@/store/device', () => ({
+ deviceSelectors: {
+ getDeviceById: (deviceId?: string) => () =>
+ testState.devices.find((device) => device.deviceId === deviceId),
+ },
+ getDeviceStoreState: () => ({}),
+}));
+
+vi.mock('@/hooks/useLocalMachineDeviceIds', () => ({
+ useLocalMachineDeviceIds: () => testState.localMachineDeviceIds,
+}));
+
vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({
useAgentManagementAccess: () => testState.access,
}));
@@ -88,6 +102,7 @@ vi.mock('@/store/user', () => ({
describe('useSelectExecutionTarget', () => {
beforeEach(() => {
+ vi.mocked(toast.error).mockClear();
testState.access.canManageAgent = true;
testState.access.isAccessLoading = false;
testState.agent.agencyConfig = undefined;
@@ -97,6 +112,8 @@ describe('useSelectExecutionTarget', () => {
testState.electron.gatewayDeviceInfo = undefined;
testState.getDeviceInfo = vi.fn();
testState.isDesktop = false;
+ testState.devices = [];
+ testState.localMachineDeviceIds = [];
testState.user.workspaceUserPreference = {};
testState.user.updateWorkspaceUserPreference = vi.fn();
});
@@ -455,6 +472,48 @@ describe('useSelectExecutionTarget', () => {
expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
});
+ // This machine's own workspace row is usually private: on the shared row
+ // it would point every other member at a device they cannot see.
+ it("routes a manager's pick of this machine's workspace row into the per-user override", async () => {
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.isDesktop = true;
+ testState.localMachineDeviceIds = ['this-machine', 'this-machine-ws'];
+ testState.devices = [{ deviceId: 'this-machine-ws', visibility: 'private' }];
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('device', 'this-machine-ws', { silent: true });
+
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentDeviceOverrides: {
+ 'agent-id': { boundDeviceId: 'this-machine-ws', executionTarget: 'device' },
+ },
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it("keeps a manager's pick of this machine's public workspace row a shared binding", async () => {
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.isDesktop = true;
+ testState.localMachineDeviceIds = ['this-machine', 'this-machine-ws'];
+ testState.devices = [{ deviceId: 'this-machine-ws', visibility: 'public' }];
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('device', 'this-machine-ws');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ { agencyConfig: { boundDeviceId: 'this-machine-ws', executionTarget: 'device' } },
+ { rethrow: true },
+ );
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+
it("routes a private Workspace agent owner's 'local' pick into the per-user override", async () => {
testState.agent.agentMap = {
'agent-id': { visibility: 'private', workspaceId: 'ws-1' },
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
index 051b5ffa385..a688e6d91e1 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -7,9 +7,11 @@ import { t } from 'i18next';
import { useCallback } from 'react';
import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';
+import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { deviceSelectors, getDeviceStoreState } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
@@ -100,6 +102,7 @@ export const useSelectExecutionTarget = (agentId: string) => {
// `local` selection to this device.
const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
+ const localMachineDeviceIds = useLocalMachineDeviceIds();
return useCallback(
async (
@@ -158,8 +161,18 @@ export const useSelectExecutionTarget = (agentId: string) => {
// A `local` pick on a workspace agent is always this caller's own
// machine — a personal device the workspace-shared row must never
// reference (the server rejects it) — so it routes to the per-user
- // override even for managers and private-agent owners.
- if (usesWorkspaceMemberSelection || (isWorkspaceAgent && target === 'local')) {
+ // override even for managers and private-agent owners. Picking this
+ // machine's own PRIVATE workspace row is the same choice made through
+ // the gateway: binding it on the shared row would point every other
+ // member at a device they cannot see. A row shared as public stays a
+ // shared pick, like any other workspace device.
+ const picksThisMachine =
+ target === 'local' ||
+ (target === 'device' &&
+ !!deviceId &&
+ localMachineDeviceIds.includes(deviceId) &&
+ deviceSelectors.getDeviceById(deviceId)(getDeviceStoreState())?.visibility === 'private');
+ if (usesWorkspaceMemberSelection || (isWorkspaceAgent && picksThisMachine)) {
const nextOverrides = {
...workspaceUserPreference.agentDeviceOverrides,
[agentId]: {
@@ -247,6 +260,7 @@ export const useSelectExecutionTarget = (agentId: string) => {
isHetero,
isAccessLoading,
isWorkspaceAgent,
+ localMachineDeviceIds,
updateAgentConfigById,
updateWorkspaceUserPreference,
usesWorkspaceMemberSelection,
diff --git a/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.test.ts b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.test.ts
new file mode 100644
index 00000000000..2fcb9374528
--- /dev/null
+++ b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.test.ts
@@ -0,0 +1,77 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { TRPCClientError } from '@trpc/client';
+import { describe, expect, it } from 'vitest';
+
+import {
+ type AutoEnrollInput,
+ autoEnrollStorageKey,
+ decideAutoEnroll,
+ isPermanentEnrollRefusal,
+} from './decide';
+
+const row = (deviceId: string) => ({ deviceId }) as DeviceListItem;
+
+const ready: AutoEnrollInput = {
+ confirmedDevices: [row('someone-else')],
+ handled: false,
+ isGatewayConnected: true,
+ isViewer: false,
+ personalDeviceId: 'personal',
+ workspaceDeviceId: 'ws-device',
+ workspaceId: 'ws-1',
+};
+
+const trpcError = (code: string) =>
+ Object.assign(new TRPCClientError('refused'), { data: { code } });
+
+describe('decideAutoEnroll', () => {
+ it('enrolls this machine when the workspace pool does not have it yet', () => {
+ expect(decideAutoEnroll(ready)).toBe('enroll');
+ });
+
+ it('only remembers a machine that is already in the pool', () => {
+ expect(decideAutoEnroll({ ...ready, confirmedDevices: [row('ws-device')] })).toBe(
+ 'markHandled',
+ );
+ });
+
+ // A handled machine whose row is gone was removed by the user.
+ it('never enrolls a machine again once handled for this workspace', () => {
+ expect(decideAutoEnroll({ ...ready, handled: true })).toBe('skip');
+ });
+
+ it('skips outside a workspace and for viewers', () => {
+ expect(decideAutoEnroll({ ...ready, workspaceId: null })).toBe('skip');
+ expect(decideAutoEnroll({ ...ready, isViewer: true })).toBe('skip');
+ });
+
+ it('waits for the gateway, both device ids and a server-confirmed list', () => {
+ expect(decideAutoEnroll({ ...ready, isGatewayConnected: false })).toBe('wait');
+ expect(decideAutoEnroll({ ...ready, personalDeviceId: undefined })).toBe('wait');
+ expect(decideAutoEnroll({ ...ready, workspaceDeviceId: undefined })).toBe('wait');
+ expect(decideAutoEnroll({ ...ready, confirmedDevices: undefined })).toBe('wait');
+ });
+});
+
+describe('isPermanentEnrollRefusal', () => {
+ it('treats a conflict (another member keeps it private, or a managed device) as final', () => {
+ expect(isPermanentEnrollRefusal(trpcError('CONFLICT'))).toBe(true);
+ });
+
+ it('lets an offline device, a role still loading or a network error retry later', () => {
+ expect(isPermanentEnrollRefusal(trpcError('PRECONDITION_FAILED'))).toBe(false);
+ expect(isPermanentEnrollRefusal(trpcError('FORBIDDEN'))).toBe(false);
+ expect(isPermanentEnrollRefusal(new Error('network'))).toBe(false);
+ });
+});
+
+describe('autoEnrollStorageKey', () => {
+ it('keeps a record per account-and-machine and per workspace', () => {
+ expect(autoEnrollStorageKey('personal', 'ws-1')).not.toBe(
+ autoEnrollStorageKey('personal', 'ws-2'),
+ );
+ expect(autoEnrollStorageKey('personal', 'ws-1')).not.toBe(
+ autoEnrollStorageKey('other-account', 'ws-1'),
+ );
+ });
+});
diff --git a/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.ts b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.ts
new file mode 100644
index 00000000000..79e7942a755
--- /dev/null
+++ b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/decide.ts
@@ -0,0 +1,91 @@
+import type { DeviceListItem } from '@lobechat/types';
+
+import { isTrpcErrorCode } from '@/utils/trpcError';
+
+export interface AutoEnrollInput {
+ /** The device list of the active workspace, only once the server confirmed it. */
+ confirmedDevices: DeviceListItem[] | undefined;
+ /** This machine has been handled for this workspace before (enrolled, found, or refused). */
+ handled: boolean;
+ isGatewayConnected: boolean;
+ isViewer: boolean;
+ personalDeviceId: string | undefined;
+ workspaceDeviceId: string | undefined;
+ workspaceId: string | null | undefined;
+}
+
+/**
+ * - `wait` — not enough is known yet; ask again when something changes.
+ * - `skip` — nothing to do for this workspace.
+ * - `markHandled` — the machine is already in the workspace (shared by hand
+ * or by `lh connect`): remember it, so removing it later is not undone.
+ * - `enroll` — share this machine into the workspace as a private device.
+ */
+export type AutoEnrollDecision = 'enroll' | 'markHandled' | 'skip' | 'wait';
+
+/**
+ * Whether the desktop should put itself into the active workspace as the
+ * member's private device.
+ *
+ * Only the workspace the user is in right now is enrolled — each enrollment is
+ * one more gateway connection. A machine handled once for a workspace is never
+ * enrolled again: if its row is gone, the user removed it.
+ */
+export const decideAutoEnroll = ({
+ confirmedDevices,
+ handled,
+ isGatewayConnected,
+ isViewer,
+ personalDeviceId,
+ workspaceDeviceId,
+ workspaceId,
+}: AutoEnrollInput): AutoEnrollDecision => {
+ if (!workspaceId) return 'skip';
+ // Enrolling writes the shared device pool, which viewers may not do.
+ if (isViewer) return 'skip';
+ if (handled) return 'skip';
+ // The share travels over the personal gateway connection.
+ if (!isGatewayConnected || !personalDeviceId || !workspaceDeviceId) return 'wait';
+ // A stored list may miss a row the server has; only the confirmed one decides.
+ if (!confirmedDevices) return 'wait';
+
+ return confirmedDevices.some((device) => device.deviceId === workspaceDeviceId)
+ ? 'markHandled'
+ : 'enroll';
+};
+
+/**
+ * A refusal that will not change on retry: another member keeps this machine
+ * private in the workspace, or the machine is a managed device (both CONFLICT).
+ * It is skipped silently and not tried again. Anything else — the device
+ * dropped offline, a network error, a role still loading — is retried in a
+ * later app session.
+ */
+export const isPermanentEnrollRefusal = (error: unknown): boolean =>
+ isTrpcErrorCode(error, 'CONFLICT');
+
+const STORAGE_PREFIX = 'LOBE_WORKSPACE_DEVICE_AUTO_ENROLLED';
+
+/**
+ * Keyed by the personal device id, which already encodes both the machine and
+ * the account, so a second account on the same computer keeps its own record.
+ */
+export const autoEnrollStorageKey = (personalDeviceId: string, workspaceId: string) =>
+ `${STORAGE_PREFIX}:${personalDeviceId}:${workspaceId}`;
+
+export const readAutoEnrollHandled = (key: string): boolean => {
+ try {
+ return localStorage.getItem(key) === '1';
+ } catch {
+ return false;
+ }
+};
+
+export const writeAutoEnrollHandled = (key: string) => {
+ try {
+ localStorage.setItem(key, '1');
+ } catch {
+ // Storage unavailable: the record is lost, so a removed machine may be
+ // enrolled again on a later switch. Nothing else depends on it.
+ }
+};
diff --git a/src/features/Electron/connection/AutoEnrollWorkspaceDevice/index.tsx b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/index.tsx
new file mode 100644
index 00000000000..3d7315bdd6f
--- /dev/null
+++ b/src/features/Electron/connection/AutoEnrollWorkspaceDevice/index.tsx
@@ -0,0 +1,102 @@
+'use client';
+
+import { toast } from '@lobehub/ui';
+import { memo, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';
+import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
+import { useSingleton } from '@/hooks/useSingleton';
+import { createWorkspaceLambdaClient } from '@/libs/trpc/client';
+import { useDeviceList } from '@/store/device';
+import { useElectronStore } from '@/store/electron';
+
+import {
+ autoEnrollStorageKey,
+ decideAutoEnroll,
+ isPermanentEnrollRefusal,
+ readAutoEnrollHandled,
+ writeAutoEnrollHandled,
+} from './decide';
+
+/**
+ * Puts this desktop into the active workspace as the member's private device,
+ * so a workspace agent or Task can run on it through the gateway instead of
+ * only through the in-app `local` path.
+ *
+ * Runs on each workspace switch, for that workspace only. Reuses the manual
+ * "share to workspace" flow (`device.shareDeviceToWorkspace`), so the server's
+ * conflict checks, rollback and the desktop's persisted reconnect all apply.
+ * Silent except for one toast on success; refusals are not reported.
+ */
+const AutoEnrollWorkspaceDevice = memo(() => {
+ const { t } = useTranslation('electron');
+ const workspaceId = useActiveWorkspaceId();
+ const isViewer = useIsWorkspaceViewer();
+ const isGatewayConnected = useElectronStore((s) => s.gatewayConnectionStatus === 'connected');
+ const [personalDeviceId, workspaceDeviceId] = useLocalMachineDeviceIds();
+ const { data: devices, isConfirmed, mutate: refreshDevices } = useDeviceList();
+ // One attempt per workspace per app session: a failure that may pass (the
+ // device dropped offline, a network error) is retried on the next launch,
+ // not on every device-list refresh.
+ const attempted = useSingleton(() => new Set<string>());
+
+ const storageKey =
+ personalDeviceId && workspaceId ? autoEnrollStorageKey(personalDeviceId, workspaceId) : '';
+
+ useEffect(() => {
+ if (!storageKey || attempted.has(storageKey)) return;
+
+ const decision = decideAutoEnroll({
+ confirmedDevices: isConfirmed ? devices : undefined,
+ handled: readAutoEnrollHandled(storageKey),
+ isGatewayConnected,
+ isViewer,
+ personalDeviceId,
+ workspaceDeviceId,
+ workspaceId,
+ });
+
+ if (decision === 'markHandled') writeAutoEnrollHandled(storageKey);
+ if (decision !== 'enroll') return;
+
+ attempted.add(storageKey);
+ void (async () => {
+ try {
+ const result = await createWorkspaceLambdaClient(
+ workspaceId!,
+ ).device.shareDeviceToWorkspace.mutate({
+ deviceId: personalDeviceId!,
+ visibility: 'private',
+ });
+ writeAutoEnrollHandled(storageKey);
+ // `alreadyEnrolled`: the row appeared after the list was read. Never
+ // overwrite it — its visibility is a choice someone already made.
+ if (result.success) toast.success(t('gateway.autoEnroll.success'));
+ await refreshDevices();
+ } catch (error) {
+ if (isPermanentEnrollRefusal(error)) writeAutoEnrollHandled(storageKey);
+ else console.warn('[AutoEnrollWorkspaceDevice] enroll failed:', error);
+ }
+ })();
+ }, [
+ attempted,
+ devices,
+ isConfirmed,
+ isGatewayConnected,
+ isViewer,
+ personalDeviceId,
+ refreshDevices,
+ storageKey,
+ t,
+ workspaceDeviceId,
+ workspaceId,
+ ]);
+
+ return null;
+});
+
+AutoEnrollWorkspaceDevice.displayName = 'AutoEnrollWorkspaceDevice';
+
+export default AutoEnrollWorkspaceDevice;
diff --git a/src/features/Electron/titlebar/TitleBar.tsx b/src/features/Electron/titlebar/TitleBar.tsx
index d6c685744a0..f4682a20cae 100644
--- a/src/features/Electron/titlebar/TitleBar.tsx
+++ b/src/features/Electron/titlebar/TitleBar.tsx
@@ -6,6 +6,7 @@ import { useDeferredMount } from '@/hooks/useDeferredMount';
import { electronStylish } from '@/styles/electron';
import { getPlatform } from '@/utils/platform';
+import AutoEnrollWorkspaceDevice from '../connection/AutoEnrollWorkspaceDevice';
import Connection from '../connection/Connection';
import DeviceGateway from '../connection/DeviceGateway';
import { useWatchThemeUpdate } from '../system/useWatchThemeUpdate';
@@ -40,6 +41,7 @@ const TitleBar = memo(() => {
<Flexbox horizontal className={electronStylish.nodrag} gap={8}>
<UpdateNotification />
<DeviceGateway />
+ <AutoEnrollWorkspaceDevice />
<Connection />
</Flexbox>
{showCustomWinControl && (
diff --git a/src/features/ExecutionTargetPicker/index.test.ts b/src/features/ExecutionTargetPicker/index.test.ts
index b71b9500d9d..1c3a49c0818 100644
--- a/src/features/ExecutionTargetPicker/index.test.ts
+++ b/src/features/ExecutionTargetPicker/index.test.ts
@@ -5,6 +5,8 @@ import {
devicePoolForAgent,
devicePoolForTask,
executionTargetValue,
+ findOwnWorkspaceDevice,
+ getMachineDefaultTarget,
groupExecutionTargetDevices,
isSharedExecutionTarget,
parseExecutionTargetValue,
@@ -146,9 +148,104 @@ describe('devicePoolForAgent', () => {
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([]);
+ it('lets the task creator pin their own private devices too', () => {
+ const asCreator = { includeOwnPrivate: true };
+ expect(devicePoolForTask(all, true, asCreator)).toEqual([privateWorkspace, publicWorkspace]);
+ expect(devicePoolForTask(all, false, asCreator)).toEqual([personal]);
+ expect(devicePoolForTask(undefined, true, asCreator)).toEqual([]);
+ });
+
+ // The creator's scheduled runs cannot resolve a collaborator's private row.
+ it('gives a collaborator on someone else’s task only the public workspace pool', () => {
+ const asCollaborator = { includeOwnPrivate: false };
+ expect(devicePoolForTask(all, true, asCollaborator)).toEqual([publicWorkspace]);
+ expect(devicePoolForTask(all, false, asCollaborator)).toEqual([personal]);
+ });
+});
+
+describe('findOwnWorkspaceDevice', () => {
+ const personal = device({ deviceId: 'personal-id' });
+ const own = device({ deviceId: 'ws-id', scope: 'workspace', visibility: 'private' });
+ const other = device({ deviceId: 'other', scope: 'workspace', visibility: 'public' });
+
+ it('ignores this machine’s row when it is shared as public', () => {
+ const ownPublic = device({ deviceId: 'ws-id', scope: 'workspace', visibility: 'public' });
+ expect(findOwnWorkspaceDevice([personal, ownPublic], ['personal-id', 'ws-id'])).toBeUndefined();
+ });
+
+ it('finds this machine’s workspace row, never its personal one', () => {
+ expect(findOwnWorkspaceDevice([personal, own, other], ['personal-id', 'ws-id'])).toBe(own);
+ expect(findOwnWorkspaceDevice([personal, other], ['personal-id', 'ws-id'])).toBeUndefined();
+ expect(findOwnWorkspaceDevice(undefined, ['personal-id'])).toBeUndefined();
+ });
+});
+
+describe('getMachineDefaultTarget', () => {
+ it('defaults an unset agent to this machine’s workspace row when it has one', () => {
+ expect(
+ getMachineDefaultTarget({
+ isOwnPick: true,
+ localSandboxEnabled: false,
+ ownWorkspaceDeviceId: 'ws-id',
+ }),
+ ).toEqual({ deviceId: 'ws-id', target: 'device' });
+ });
+
+ it('defaults an unset agent to local without a workspace row', () => {
+ expect(getMachineDefaultTarget({ isOwnPick: true, localSandboxEnabled: false })).toEqual({
+ target: 'local',
+ });
+ });
+
+ it('moves a plain local pick onto the workspace row', () => {
+ expect(
+ getMachineDefaultTarget({
+ boundDeviceId: 'personal-id',
+ executionTarget: 'local',
+ isOwnPick: true,
+ localSandboxEnabled: false,
+ ownWorkspaceDeviceId: 'ws-id',
+ }),
+ ).toEqual({ deviceId: 'ws-id', target: 'device' });
+ });
+
+ it('keeps a sandboxed local pick, and any other explicit pick', () => {
+ expect(
+ getMachineDefaultTarget({
+ executionTarget: 'local',
+ isOwnPick: true,
+ localSandboxEnabled: true,
+ ownWorkspaceDeviceId: 'ws-id',
+ }),
+ ).toBeUndefined();
+ expect(
+ getMachineDefaultTarget({
+ executionTarget: 'sandbox',
+ isOwnPick: true,
+ localSandboxEnabled: false,
+ ownWorkspaceDeviceId: 'ws-id',
+ }),
+ ).toBeUndefined();
+ expect(
+ getMachineDefaultTarget({
+ executionTarget: 'local',
+ isOwnPick: true,
+ localSandboxEnabled: false,
+ }),
+ ).toBeUndefined();
+ });
+
+ // A legacy shared `local` routes every member to its bound workspace device;
+ // a member who only inherits it must keep following the agent.
+ it('leaves an inherited shared local alone', () => {
+ expect(
+ getMachineDefaultTarget({
+ boundDeviceId: 'shared-ws-device',
+ executionTarget: 'local',
+ isOwnPick: false,
+ localSandboxEnabled: false,
+ ownWorkspaceDeviceId: 'ws-id',
+ }),
+ ).toBeUndefined();
});
});
diff --git a/src/features/ExecutionTargetPicker/index.tsx b/src/features/ExecutionTargetPicker/index.tsx
index 5adbd8ece11..a6d924c3946 100644
--- a/src/features/ExecutionTargetPicker/index.tsx
+++ b/src/features/ExecutionTargetPicker/index.tsx
@@ -212,21 +212,76 @@ export const devicePoolForAgent = (
/**
* 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.
+ * A Task's scheduled runs execute as its creator, and a private workspace
+ * device resolves only for the member who enrolled it
+ * (`DeviceModel.findWorkspaceDeviceById`). The private rows in a device list
+ * are only ever the caller's own, so they are pinnable exactly when the caller
+ * is the task's creator (`includeOwnPrivate`) — creating it, or editing their
+ * own task. A collaborator editing someone else's task gets the public pool
+ * only: their private machine is one the creator's runs can never reach.
*/
export const devicePoolForTask = (
devices: DeviceListItem[] | undefined,
workspaceAgent: boolean,
+ { includeOwnPrivate }: { includeOwnPrivate: boolean },
): DeviceListItem[] => {
- const { personal, publicWorkspace } = groupExecutionTargetDevices(devices);
+ if (!workspaceAgent || includeOwnPrivate) return devicePoolForAgent(devices, workspaceAgent);
- return workspaceAgent ? publicWorkspace : personal;
+ return groupExecutionTargetDevices(devices).publicWorkspace;
+};
+
+/**
+ * This machine's private row in the workspace pool, if it has one — the row
+ * auto-enrollment creates. `localMachineIds` are the ids this desktop holds
+ * (`useLocalMachineDeviceIds`); only the workspace one can match. A row shared
+ * as public is a team device: picking it is a shared binding, so it never
+ * stands in for "this machine".
+ */
+export const findOwnWorkspaceDevice = (
+ devices: DeviceListItem[] | undefined,
+ localMachineIds: string[],
+): DeviceListItem | undefined =>
+ devices?.find(
+ (device) =>
+ device.scope === 'workspace' &&
+ device.visibility === 'private' &&
+ localMachineIds.includes(device.deviceId),
+ );
+
+/**
+ * The target a desktop picker writes on its own, or `undefined` to leave the
+ * agent alone.
+ *
+ * - Nothing stored yet: this machine — its workspace row through the gateway
+ * when it has one, else the in-app `local` path.
+ * - The member's own plain `local` pick on a workspace agent whose machine now
+ * has a workspace row moves to that row, so runs go through the gateway. A
+ * sandboxed `local` stays: only the in-app path can fence commands. A shared
+ * `local` the member merely inherits (`isOwnPick: false`) is not theirs to move.
+ */
+export const getMachineDefaultTarget = ({
+ boundDeviceId,
+ executionTarget,
+ isOwnPick,
+ localSandboxEnabled,
+ ownWorkspaceDeviceId,
+}: {
+ boundDeviceId?: string;
+ executionTarget?: DeviceExecutionTarget;
+ isOwnPick: boolean;
+ localSandboxEnabled: boolean;
+ ownWorkspaceDeviceId?: string;
+}): ExecutionTargetSelection | undefined => {
+ if (executionTarget === undefined && boundDeviceId === undefined) {
+ return ownWorkspaceDeviceId
+ ? { deviceId: ownWorkspaceDeviceId, target: 'device' }
+ : { target: 'local' };
+ }
+
+ if (executionTarget === 'local' && isOwnPick && !localSandboxEnabled && ownWorkspaceDeviceId)
+ return { deviceId: ownWorkspaceDeviceId, target: 'device' };
+
+ return undefined;
};
interface ExecutionTargetIconProps {