Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent): let a private workspace Agent's owner switch to their private device while fixed (#23230)

Rdmclin2afc096bed552
diff --git a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
index 09db613bdac..30c3d8a93b0 100644
--- a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
+++ b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
@@ -1,11 +1,12 @@
// @vitest-environment node
import { eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import { agents, devices, type NewAgent, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentModel } from '../agent';
+import type { AgentModelContext } from '../agent/context';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -33,6 +34,7 @@ beforeEach(async () => {
});
afterEach(async () => {
+ vi.restoreAllMocks();
await serverDB.delete(users);
});
@@ -138,6 +140,30 @@ describe('AgentModel workspace device binding', () => {
}),
).rejects.toThrow(/requires a public device/);
});
+
+ it('allows a private agent to save a fixed private-device target until it is published', async () => {
+ const privateDeviceId = 'workspace-private-device';
+ await serverDB.insert(devices).values({
+ deviceId: privateDeviceId,
+ identitySource: 'machine-id',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+
+ const agent = await wsModel.create({
+ agencyConfig: {
+ boundDeviceId: privateDeviceId,
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ title: 'Private fixed WS agent',
+ visibility: 'private',
+ });
+
+ expect(agent.agencyConfig?.boundDeviceId).toBe(privateDeviceId);
+ });
});
describe('updateConfig', () => {
@@ -223,6 +249,138 @@ describe('AgentModel workspace device binding', () => {
});
});
+ describe('private fixed agent (T-14315)', () => {
+ const privateDeviceId = 'workspace-private-device';
+
+ const createPrivateFixedSandboxAgent = async () => {
+ await serverDB.insert(devices).values({
+ deviceId: privateDeviceId,
+ identitySource: 'machine-id',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const agent = await wsModel.create({
+ agencyConfig: { executionTarget: 'sandbox', executionTargetSelectionPolicy: 'fixed' },
+ title: 'Private fixed sandbox agent',
+ visibility: 'private',
+ });
+ return { agent, wsModel };
+ };
+
+ it('lets the owner switch a private fixed agent to their private workspace device', async () => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+
+ await wsModel.updateConfig(agent.id, {
+ agencyConfig: {
+ boundDeviceId: privateDeviceId,
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ });
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.agencyConfig?.executionTarget).toBe('device');
+ expect(stored?.agencyConfig?.boundDeviceId).toBe(privateDeviceId);
+ });
+
+ it('still rejects publishing it while bound to the private device', async () => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+ await wsModel.updateConfig(agent.id, {
+ agencyConfig: { boundDeviceId: privateDeviceId, executionTarget: 'device' },
+ });
+
+ await expect(wsModel.publishToWorkspace(agent.id)).rejects.toThrow(
+ /requires a public device/,
+ );
+ await expect(wsModel.setVisibility(agent.id, 'public')).rejects.toThrow(
+ /requires a public device/,
+ );
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.visibility).toBe('private');
+ });
+
+ it('still rejects a private workspace device on a public fixed agent', async () => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+ await serverDB.update(agents).set({ visibility: 'public' }).where(eq(agents.id, agent.id));
+
+ await expect(
+ wsModel.updateConfig(agent.id, {
+ agencyConfig: { boundDeviceId: privateDeviceId, executionTarget: 'device' },
+ }),
+ ).rejects.toThrow(/requires a public device/);
+ });
+
+ // Race: each side validated a row the other side changed before writing.
+ const interleaveAfterCheck = (wsModel: AgentModel, interleave: () => Promise<unknown>) => {
+ const ctx = (wsModel as unknown as { ctx: AgentModelContext }).ctx;
+ const original = ctx.assertFixedExecutionTarget;
+ let fired = false;
+ vi.spyOn(ctx, 'assertFixedExecutionTarget').mockImplementation(async (...args) => {
+ await original(...args);
+ if (fired) return;
+ fired = true;
+ await interleave();
+ });
+ };
+
+ it('does not save a private device onto an agent published after the check', async () => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+ interleaveAfterCheck(wsModel, () =>
+ serverDB.update(agents).set({ visibility: 'public' }).where(eq(agents.id, agent.id)),
+ );
+
+ await expect(
+ wsModel.updateConfig(agent.id, {
+ agencyConfig: { boundDeviceId: privateDeviceId, executionTarget: 'device' },
+ }),
+ ).rejects.toThrow(/concurrently/);
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.visibility).toBe('public');
+ expect(stored?.agencyConfig?.executionTarget).toBe('sandbox');
+ expect(stored?.agencyConfig?.boundDeviceId).toBeUndefined();
+ });
+
+ it.each(['publishToWorkspace', 'setVisibility'] as const)(
+ 'does not %s an agent whose config changed to a private device after the check',
+ async (method) => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+ interleaveAfterCheck(wsModel, () =>
+ serverDB
+ .update(agents)
+ .set({
+ agencyConfig: {
+ boundDeviceId: privateDeviceId,
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ })
+ .where(eq(agents.id, agent.id)),
+ );
+
+ await expect(
+ method === 'publishToWorkspace'
+ ? wsModel.publishToWorkspace(agent.id)
+ : wsModel.setVisibility(agent.id, 'public'),
+ ).rejects.toThrow(/concurrently|already published/);
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.visibility).toBe('private');
+ },
+ );
+
+ it('publishes once the check and the write see the same config', async () => {
+ const { agent, wsModel } = await createPrivateFixedSandboxAgent();
+
+ await expect(wsModel.publishToWorkspace(agent.id)).resolves.toMatchObject({
+ visibility: 'public',
+ });
+ });
+ });
+
describe('publishToWorkspace', () => {
const createPrivateFixedAgent = async () => {
const wsModel = new AgentModel(serverDB, userId, wsId);
diff --git a/packages/database/src/models/agent/context.ts b/packages/database/src/models/agent/context.ts
index a6d3af3fb43..8c31dfc893b 100644
--- a/packages/database/src/models/agent/context.ts
+++ b/packages/database/src/models/agent/context.ts
@@ -5,6 +5,7 @@ import type { SQL } from 'drizzle-orm';
import { and, eq, inArray } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
+import type { AGENT_VISIBILITY } from '../../schemas';
import {
agents,
agentsFiles,
@@ -21,6 +22,8 @@ import {
} from '../../utils/agencyConfigDevices';
import { buildWorkspaceWhere } from '../../utils/workspace';
+type AgentVisibility = (typeof AGENT_VISIBILITY)[number];
+
/**
* The state and scope predicates every `AgentModel` operation shares. Built once
* per model instance; the operation modules receive it as their first argument.
@@ -32,6 +35,7 @@ export interface AgentModelContext {
assertFixedExecutionTarget: (
agentWorkspaceId: string | null,
agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ visibility?: AgentVisibility | null,
) => Promise<void>;
assertWorkspaceDeviceBinding: (
agentWorkspaceId: string | null,
@@ -204,12 +208,23 @@ export const createAgentModelContext = ({
* public in the same workspace. Use one generic device error for
* missing/private/cross-workspace rows so the write path never reveals a
* device the caller cannot otherwise see.
+ *
+ * A private Agent has a single runner β€” its owner β€” so the member-selection
+ * policy is dormant until publication (the client already treats it that
+ * way: `resolveAgentAgencyConfig` drops the policy for the owner and the
+ * picker writes the shared row directly). Config writes on a private Agent
+ * therefore skip this check; the publication boundary
+ * (`publishToWorkspace` / `setVisibility('public')`) omits `visibility` and
+ * re-checks the stored config, so a private device can never reach a
+ * published fixed Agent.
*/
assertFixedExecutionTarget: async (
agentWorkspaceId: string | null,
agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ visibility?: AgentVisibility | null,
): Promise<void> => {
if (!agentWorkspaceId || agencyConfig?.executionTargetSelectionPolicy !== 'fixed') return;
+ if (visibility === 'private') return;
if (
!agencyConfig.executionTarget ||
diff --git a/packages/database/src/models/agent/create.ts b/packages/database/src/models/agent/create.ts
index db5260174d9..3ffbbe86fab 100644
--- a/packages/database/src/models/agent/create.ts
+++ b/packages/database/src/models/agent/create.ts
@@ -30,7 +30,7 @@ export const create = async (
);
await ctx.assertWorkspaceDeviceBinding(ctx.workspaceId ?? null, agencyConfig);
- await ctx.assertFixedExecutionTarget(ctx.workspaceId ?? null, agencyConfig);
+ await ctx.assertFixedExecutionTarget(ctx.workspaceId ?? null, agencyConfig, config.visibility);
const [result] = await ctx.db
.insert(agents)
@@ -73,7 +73,11 @@ export const batchCreate = async (
(config) =>
Promise.all([
ctx.assertWorkspaceDeviceBinding(ctx.workspaceId ?? null, config.agencyConfig),
- ctx.assertFixedExecutionTarget(ctx.workspaceId ?? null, config.agencyConfig),
+ ctx.assertFixedExecutionTarget(
+ ctx.workspaceId ?? null,
+ config.agencyConfig,
+ config.visibility,
+ ),
]),
{ concurrency: 5 },
);
diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.ts
index a56af816b7a..a7765d429c7 100644
--- a/packages/database/src/models/agent/index.ts
+++ b/packages/database/src/models/agent/index.ts
@@ -309,10 +309,13 @@ export class AgentModel {
this.ctx.ownership(),
eq(agents.userId, this.ctx.userId),
eq(agents.visibility, 'private'),
+ update.sameAgencyConfig(agent.agencyConfig),
),
)
.returning();
+ // Also misses when a concurrent publication or config write changed the
+ // row between the read above and this write.
if (!result) {
throw new Error('Agent not found, already published, or access denied');
}
diff --git a/packages/database/src/models/agent/update.ts b/packages/database/src/models/agent/update.ts
index ddb816d743c..a6b40c5bda1 100644
--- a/packages/database/src/models/agent/update.ts
+++ b/packages/database/src/models/agent/update.ts
@@ -3,7 +3,7 @@ import { INBOX_SESSION_ID, isHeterogeneousAgentModelId } from '@lobechat/const';
import { applyWorkingDirByDevicePatch } from '@lobechat/types';
import { toRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, isNull, type SQL } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
@@ -11,6 +11,7 @@ import { merge } from '@/utils/merge';
import { writeAgent } from '../../repositories/channel/agentRename';
import type { AgentItem } from '../../schemas';
import { agents, sessionGroups } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
import { sanitizeAgentApiConfig } from '../../utils/sanitizeAgentApiConfig';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { RESERVED_AGENT_SLUGS } from './constants';
@@ -200,6 +201,7 @@ export const setVisibility = async (
const groupVisibility = current?.groupVisibility as 'private' | 'public' | null | undefined;
const clearGroup = groupVisibility != null && groupVisibility !== visibility;
+ const pinConfig = visibility === 'public' && current;
const [updated] = await ctx.db
.update(agents)
.set({
@@ -207,8 +209,15 @@ export const setVisibility = async (
visibility,
...(clearGroup ? { sessionGroupId: null } : {}),
})
- .where(and(eq(agents.id, agentId), ctx.ownership()))
+ .where(
+ and(
+ eq(agents.id, agentId),
+ ctx.ownership(),
+ pinConfig ? sameAgencyConfig(current.agencyConfig) : undefined,
+ ),
+ )
.returning();
+ if (!updated && pinConfig) throw agentPublishedConcurrentlyError();
return updated ?? null;
};
@@ -362,7 +371,19 @@ export const updateConfig = async (
replaceWorkingDirDeviceIds,
);
- await ctx.assertFixedExecutionTarget(agent.workspaceId, mergedValue.agencyConfig);
+ await ctx.assertFixedExecutionTarget(
+ agent.workspaceId,
+ mergedValue.agencyConfig,
+ agent.visibility,
+ );
+ // The check above trusted `agent.visibility` as read; publication may land
+ // between that read and the write below. Pin the write to the still-private
+ // row so a fixed target that skipped the public-device check cannot reach a
+ // published Agent (publication pins its write to the config it validated).
+ const pinPrivate =
+ !!agent.workspaceId &&
+ agent.visibility === 'private' &&
+ mergedValue.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
// Timestamp fields are left to Drizzle's $onUpdate.
touchedColumns.delete('updatedAt');
@@ -374,9 +395,41 @@ export const updateConfig = async (
) as Partial<typeof mergedValue>;
if (!Object.values(updateData).some((value) => value !== undefined)) return;
- return writeAgent(ctx.db, and(eq(agents.id, agentId), ctx.ownership()), agentId, updateData);
+ const where = and(eq(agents.id, agentId), ctx.ownership());
+ if (!pinPrivate) return writeAgent(ctx.db, where, agentId, updateData);
+
+ return ctx.db.transaction(async (tx) => {
+ const [locked] = await tx
+ .select({ visibility: agents.visibility })
+ .from(agents)
+ .where(where)
+ .for('update');
+ if (!locked) return;
+ if (locked.visibility !== 'private') throw agentPublishedConcurrentlyError();
+ return writeAgent(tx as unknown as LobeChatDatabase, where, agentId, updateData);
+ });
};
+/**
+ * A fixed-target config write and a publication raced: the other side changed
+ * the row this side validated, so neither may land unchecked. The caller
+ * retries against the current row.
+ */
+export const agentPublishedConcurrentlyError = () =>
+ new TRPCError({
+ cause: { data: { code: 'AgentVisibilityChangedConcurrently' } },
+ code: 'CONFLICT',
+ message: 'The agent was published or edited concurrently. Reload and try again.',
+ });
+
+/**
+ * Pin a publication write to the `agencyConfig` it validated with
+ * `assertFixedExecutionTarget`, so a concurrent config write cannot slip an
+ * unchecked target in between the check and the visibility flip.
+ */
+export const sameAgencyConfig = (agencyConfig: AgentItem['agencyConfig'] | null): SQL =>
+ agencyConfig == null ? isNull(agents.agencyConfig) : eq(agents.agencyConfig, agencyConfig);
+
/**
* Update the sessionGroupId for an agent
*/
diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
index 2b9c3e7c796..1ab849265ca 100644
--- a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
@@ -21,6 +21,12 @@ const styles = stylex.create({
interface DeviceOptionRowProps {
active: boolean;
+ /**
+ * Why this device cannot be picked for the current agent. The row is
+ * disabled and the reason replaces its status line, so the user learns why
+ * before trying instead of meeting a generic save error after.
+ */
+ blockedReason?: string;
device: DeviceListItem;
/** Replaces the machine name, e.g. "This computer" for this desktop's own row. */
label?: string;
@@ -36,6 +42,7 @@ interface DeviceOptionRowProps {
*/
const DeviceOptionRow = ({
active,
+ blockedReason,
device,
label,
onReconnect,
@@ -48,7 +55,7 @@ const DeviceOptionRow = ({
const presenceUnknown = isDevicePresenceUnknown(device);
const { offlineLabelKey, reconnectLabelKey, selectable, showReconnect } = getDeviceOptionState(
device,
- { presenceUnknown },
+ { blocked: !!blockedReason, presenceUnknown },
);
return (
@@ -64,32 +71,34 @@ const DeviceOptionRow = ({
label={label ?? (device.friendlyName || device.hostname || device.deviceId)}
tags={tags}
desc={
- <>
- <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}
- icon={<Icon icon={RefreshCwIcon} size={10} />}
- loading={reconnecting}
- size={'small'}
- type={'text'}
- onClick={(event) => {
- event.stopPropagation();
- onReconnect();
- }}
- >
- {t(reconnectLabelKey)}
- </Button>
- ) : null}
- </>
+ blockedReason || (
+ <>
+ <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}
+ icon={<Icon icon={RefreshCwIcon} size={10} />}
+ loading={reconnecting}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ onReconnect();
+ }}
+ >
+ {t(reconnectLabelKey)}
+ </Button>
+ ) : null}
+ </>
+ )
}
onClick={onSelect}
/>
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index e154f7a30eb..79f0acf16ef 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -33,6 +33,8 @@ import {
getMachineDefaultTarget,
groupExecutionTargetDevices,
} from '@/features/ExecutionTargetPicker';
+import { getPrivateDeviceBlock } from '@/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection';
+import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
isHeterogeneousSandboxExecutionAvailable,
@@ -197,7 +199,7 @@ interface HeteroDeviceSwitcherProps {
}
const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
- const { t } = useTranslation('chat');
+ const { t } = useTranslation(['chat', 'setting']);
const [open, setOpen] = useState(false);
const navigate = useWorkspaceAwareNavigate();
const { canUseResource } = useChatInputResourceAccess();
@@ -207,6 +209,13 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const topicId = useTopicId();
const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
const isWorkspaceAgent = Boolean(agentWorkspaceId);
+ const agentVisibility = useAgentStore((s) => s.agentMap[agentId]?.visibility);
+ // The stored (shared) policy, not the effective one: the effective config
+ // drops the policy for a private Agent's owner, for whom it is dormant.
+ const sharedSelectionPolicy = useAgentStore(
+ (s) => s.agentMap[agentId]?.agencyConfig?.executionTargetSelectionPolicy,
+ );
+ const { canManageAgent } = useAgentManagementAccess(agentId);
// Shared config merged with the caller's per-agent override β€”
// the hook eagerly fetches the `workspaceUserSettings` bucket on mount so
@@ -516,6 +525,20 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
);
const { personal, privateWorkspace, workspace } = groupExecutionTargetDevices(otherDevices);
const privateDevices = isWorkspaceAgent ? privateWorkspace : [];
+ // A manager's pick on a published fixed Agent writes the shared contract,
+ // which the server only accepts with a public device
+ // (`FixedAgentRequiresPublicWorkspaceDevice`): say so on the rows rather
+ // than after a failed save. A private Agent's owner may pick any of them β€”
+ // its policy is dormant until publication.
+ const privateDeviceBlockedReason =
+ getPrivateDeviceBlock({
+ canManageAgent,
+ isWorkspaceAgent,
+ selectionPolicy: sharedSelectionPolicy,
+ visibility: agentVisibility,
+ }) === 'fixed'
+ ? t('setting:settingAgent.devicePolicy.privateDeviceFixed')
+ : undefined;
const workspaceDevices = isWorkspaceAgent ? workspace : [];
const personalOnlyDevices = isWorkspaceAgent ? [] : personal;
// Workspace agents always render the Private / Workspace group split (even
@@ -638,9 +661,16 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const hasDeviceSection =
privateDevices.length + workspaceDevices.length + personalOnlyDevices.length > 0;
const showSectionLabels = isDesktop || hasDeviceSection;
- const renderDeviceRow = (d: DeviceListItem, { thisComputer = false } = {}) => (
+ const renderDeviceRow = (
+ d: DeviceListItem,
+ {
+ blockedReason,
+ thisComputer = false,
+ }: { blockedReason?: string; thisComputer?: boolean } = {},
+ ) => (
<DeviceOptionRow
active={isActive('device', d.deviceId)}
+ blockedReason={blockedReason}
device={d}
key={d.deviceId}
// Users pick a machine, not a transport: this one is "This computer".
@@ -858,7 +888,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
devices={privateDevices}
kind={'private'}
label={t('heteroAgent.executionTarget.personalGroup')}
- renderDevice={renderDeviceRow}
+ renderDevice={(d) => renderDeviceRow(d, { blockedReason: privateDeviceBlockedReason })}
/>
) : null}
{showDeviceGroups && workspaceDevices.length > 0 ? (
diff --git a/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts b/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts
index 56f95083bf0..4614a27bc9a 100644
--- a/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts
+++ b/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts
@@ -61,4 +61,16 @@ describe('getDeviceOptionState', () => {
false,
);
});
+
+ // T-14315: a private device on a published fixed Agent would be rejected by
+ // the server, so the row says why and cannot be picked even while online.
+ it('keeps a blocked device unselectable even while it is online', () => {
+ const online = { identitySource: 'machine-id', online: true };
+
+ expect(getDeviceOptionState(online, known).selectable).toBe(true);
+ expect(getDeviceOptionState(online, { ...known, blocked: true }).selectable).toBe(false);
+ expect(getDeviceOptionState(sleepingManaged, { ...known, blocked: true }).selectable).toBe(
+ false,
+ );
+ });
});
diff --git a/src/features/ChatInput/ControlBar/deviceOptionState.ts b/src/features/ChatInput/ControlBar/deviceOptionState.ts
index 30922faf911..9a7121261c6 100644
--- a/src/features/ChatInput/ControlBar/deviceOptionState.ts
+++ b/src/features/ChatInput/ControlBar/deviceOptionState.ts
@@ -23,11 +23,15 @@ export interface DeviceOptionState {
* it through the desktop app.
* - A managed device that cannot be woken (failed, deleting) has no control:
* the desktop app cannot reach it.
+ * - A device the current agent cannot bind (`blocked`, e.g. a private device on
+ * a published fixed Agent) is not selectable, whatever its presence: the
+ * save would be rejected. Its reconnect control stays, as reconnecting is
+ * still useful elsewhere.
*/
export const getDeviceOptionState = (
// Structural, so a `managedPhase` on the list row narrows it when present.
device: Parameters<typeof isWakeableManagedDevice>[0],
- { presenceUnknown }: { presenceUnknown: boolean },
+ { blocked = false, presenceUnknown }: { blocked?: boolean; presenceUnknown: boolean },
): DeviceOptionState => {
const wakeable = isWakeableManagedDevice(device);
@@ -38,7 +42,7 @@ export const getDeviceOptionState = (
reconnectLabelKey: wakeable
? 'heteroAgent.executionTarget.wake'
: 'heteroAgent.executionTarget.reconnect',
- selectable: device.online || wakeable,
+ selectable: !blocked && (device.online || wakeable),
showReconnect:
!device.online && !presenceUnknown && (wakeable || !isManagedCloudDevice(device)),
};
diff --git a/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.test.ts b/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.test.ts
index d4a636290f1..7d1e195c3b4 100644
--- a/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.test.ts
+++ b/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.test.ts
@@ -17,17 +17,28 @@ describe('getPrivateDeviceBlock', () => {
).toBe('publicAgent');
});
- it('blocks a private device once a private agent is fixed', () => {
+ it('blocks a private device on a public fixed agent, which the server rejects', () => {
expect(
getPrivateDeviceBlock({
canManageAgent: true,
isWorkspaceAgent: true,
selectionPolicy: 'fixed',
- visibility: 'private',
+ visibility: 'public',
}),
).toBe('fixed');
});
+ it("allows the owner's private device on a private fixed agent until it is published", () => {
+ expect(
+ getPrivateDeviceBlock({
+ canManageAgent: true,
+ isWorkspaceAgent: true,
+ selectionPolicy: 'fixed',
+ visibility: 'private',
+ }),
+ ).toBeUndefined();
+ });
+
it("allows the owner's private device on a private agent", () => {
expect(
getPrivateDeviceBlock({
diff --git a/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.ts b/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.ts
index 53ddbcc1ef6..0bf13a264ee 100644
--- a/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.ts
+++ b/src/features/HeterogeneousAgent/ExecutionEnvironment/heteroTargetSelection.ts
@@ -5,13 +5,18 @@ import { executionTargetValue } from '@/features/ExecutionTargetPicker';
export type PrivateDeviceBlock = 'fixed' | 'publicAgent';
/**
- * Why the profile picker cannot bind a private workspace device, if it cannot.
+ * Why a manager's picker cannot bind a private workspace device, if it cannot.
*
* A manager's pick replaces the shared default that every member resolves, and
* a private device resolves only for the member who enrolled it β€” so the
- * shared row may name one only on a private Agent that is not fixed. A
- * member's pick stays in their own override, where their private device is
- * fine. Personal agents have no private workspace devices at all.
+ * shared row of a published Agent should not name one (`publicAgent`), and a
+ * published fixed Agent cannot: the server rejects it (`fixed`,
+ * `FixedAgentRequiresPublicWorkspaceDevice`). A private Agent has a single
+ * runner, its owner, and its selection policy is dormant until publication
+ * (publishing re-checks the fixed target), so any of the owner's private
+ * devices is fine there. A member's pick stays in their own override, where
+ * their private device is fine. Personal agents have no private workspace
+ * devices at all.
*/
export const getPrivateDeviceBlock = ({
canManageAgent,
@@ -25,8 +30,8 @@ export const getPrivateDeviceBlock = ({
visibility?: 'private' | 'public';
}): PrivateDeviceBlock | undefined => {
if (!isWorkspaceAgent || !canManageAgent) return;
- if (visibility !== 'private') return 'publicAgent';
- if (selectionPolicy === 'fixed') return 'fixed';
+ if (visibility === 'private') return;
+ return selectionPolicy === 'fixed' ? 'fixed' : 'publicAgent';
};
/** The picker value for a resolved target; undefined leaves the placeholder. */
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
index 286f7eb875f..953ba9977ed 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
@@ -217,7 +217,10 @@ describe('WorkspaceAgentDevicePolicy with a private workspace device', () => {
);
});
- it('keeps private devices unselectable once the environment is fixed', () => {
+ // T-14315: the selection policy is dormant until the Agent is published
+ // (publishing re-checks a fixed target), so the owner may bind any of their
+ // private devices to a private fixed Agent.
+ it('lets the owner bind a private device to a private fixed agent', () => {
testState.agent.agentMap['agent-1'].visibility = 'private';
testState.agent.agentMap['agent-1'].agencyConfig = {
executionTarget: 'auto',
@@ -226,6 +229,28 @@ describe('WorkspaceAgentDevicePolicy with a private workspace device', () => {
render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+ const option = deviceOption();
+ expect(option?.disabled).toBeFalsy();
+ expect(privateGroupOptions().map((option) => option.value)).not.toContain(
+ 'status:privateUnavailable',
+ );
+
+ const { onChange } = selectPropsSpy.mock.lastCall?.[0] as { onChange: (v: string) => void };
+ onChange(option!.value);
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
+ agencyConfig: { boundDeviceId: 'private-device', executionTarget: 'device' },
+ });
+ });
+
+ it('keeps private devices unselectable on a public fixed agent', () => {
+ testState.agent.agentMap['agent-1'].visibility = 'public';
+ testState.agent.agentMap['agent-1'].agencyConfig = {
+ executionTarget: 'auto',
+ executionTargetSelectionPolicy: 'fixed',
+ };
+
+ render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+
expect(deviceOption()?.disabled).toBe(true);
expect(privateGroupOptions().map((option) => option.value)).toContain(
'status:privateUnavailable',
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
index 8de111cba06..7832c24194b 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
@@ -44,14 +44,13 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
const agencyConfig = config?.agencyConfig;
// This card writes the shared config, so a private device (resolvable only
// by the member who enrolled it) may be bound only when that member is the
- // sole runner: a private Agent. A fixed target must stay public β€” the
- // server rejects anything else (`assertFixedExecutionTarget`).
+ // sole runner: a private Agent β€” fixed or not, as the policy is dormant
+ // until publication, and publishing re-checks a fixed target
+ // (`assertFixedExecutionTarget`).
const privateDeviceBlockedReason =
config?.visibility !== 'private'
? t('settingAgent.devicePolicy.privateDevicePublicAgent')
- : agencyConfig?.executionTargetSelectionPolicy === 'fixed'
- ? t('settingAgent.devicePolicy.privateDeviceFixed')
- : undefined;
+ : undefined;
const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;
const isHeterogeneous = !!heterogeneousType;
const supportsSandbox = isHeterogeneousSandboxExecutionAvailable(heterogeneousType);