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(project): show device presence on agent topic groups (#21524)

Arvin Xu2b0f79ba65b0
diff --git a/apps/server/src/routers/lambda/__tests__/deviceBoundAgents.test.ts b/apps/server/src/routers/lambda/__tests__/deviceBoundAgents.test.ts
index d33faeb9900..7007f1d672a 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceBoundAgents.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceBoundAgents.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { DeviceBindingCandidate } from '@/database/models/agent';
-import { selectEffectivelyBoundAgents } from '../deviceBoundAgents';
+import { selectAgentDeviceBindings, selectEffectivelyBoundAgents } from '../deviceBoundAgents';
vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
vi.mock('@/database/models/workspaceUserSettings', () => ({ WorkspaceUserSettingsModel: vi.fn() }));
@@ -91,3 +91,51 @@ describe('selectEffectivelyBoundAgents', () => {
});
});
});
+
+describe('selectAgentDeviceBindings', () => {
+ const bind = (
+ candidates: DeviceBindingCandidate[],
+ overrides: Record<string, AgentDeviceOverride> = {},
+ canManage: string[] = [],
+ ) => selectAgentDeviceBindings(candidates, { canManage: new Set(canManage), overrides });
+
+ it('maps each agent to the device its stored config routes to', () => {
+ expect(
+ bind([
+ candidate('device-agent', onA),
+ candidate('local-agent', { boundDeviceId: 'device-b', executionTarget: 'local' }),
+ ]),
+ ).toEqual({ 'device-agent': 'device-a', 'local-agent': 'device-b' });
+ });
+
+ it('leaves out an agent whose stale binding the execution target does not use', () => {
+ // A binding lingers after switching to the sandbox / none; `auto` treats it as stale.
+ expect(
+ bind([
+ candidate('sandbox', { boundDeviceId: 'device-a', executionTarget: 'sandbox' }),
+ candidate('none', { boundDeviceId: 'device-a', executionTarget: 'none' }),
+ candidate('auto', { boundDeviceId: 'device-a', executionTarget: 'auto' }),
+ candidate('unbound', null),
+ ]),
+ ).toEqual({});
+ });
+
+ it("applies the caller's own override over the shared binding", () => {
+ const agents = [candidate('moved', onA), candidate('to-sandbox', onA)];
+
+ expect(
+ bind(agents, {
+ 'moved': { boundDeviceId: 'device-b', executionTarget: 'device' },
+ 'to-sandbox': { executionTarget: 'sandbox' },
+ }),
+ ).toEqual({ moved: 'device-b' });
+ });
+
+ it('ignores a member override on a fixed agent but honours the manager override', () => {
+ const fixed = candidate('fixed', { ...onA, executionTargetSelectionPolicy: 'fixed' });
+ const overrides = { fixed: { boundDeviceId: 'device-b', executionTarget: 'device' as const } };
+
+ expect(bind([fixed], overrides)).toEqual({ fixed: 'device-a' });
+ expect(bind([fixed], overrides, ['fixed'])).toEqual({ fixed: 'device-b' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.ts
index 23689f96318..87f92ddd317 100644
--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts
@@ -41,6 +41,7 @@ function expected(): Array<
['createTerminalSession', 'mutation', 12],
['createTunnel', 'mutation', 12],
['deleteGitBranch', 'mutation', 12],
+ ['getAgentDeviceBindings', 'query', 12],
['getAgentProfile', 'query', 12],
['getAppUpdateState', 'query', 12],
['getClaudeCodeQuota', 'query', 12],
diff --git a/apps/server/src/routers/lambda/device/registry.ts b/apps/server/src/routers/lambda/device/registry.ts
index 82d973618d2..9b393f0900a 100644
--- a/apps/server/src/routers/lambda/device/registry.ts
+++ b/apps/server/src/routers/lambda/device/registry.ts
@@ -17,7 +17,7 @@ import { router } from '@/libs/trpc/lambda';
import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGateway';
import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';
-import { loadDeviceBoundAgents } from '../deviceBoundAgents';
+import { loadAgentDeviceBindings, loadDeviceBoundAgents } from '../deviceBoundAgents';
import { preserveWorkspaceCache } from '../deviceWorkingDirs';
import { deviceProcedure } from './procedures';
@@ -95,6 +95,24 @@ export const registryRouter = router({
})),
};
}),
+ /**
+ * Where each agent runs for the caller, for a list of agents in one read β€”
+ * the sidebar decorates every agent group with its device's presence and must
+ * not fetch each agent's config separately. Resolved per caller like
+ * {@link getDeviceActivity}: the stored config merged with the caller's own
+ * device override, keeping only the `device` / `local` targets. Agents that
+ * route nowhere, or that the caller cannot see, are absent from the result.
+ */
+ getAgentDeviceBindings: deviceProcedure
+ .input(z.object({ agentIds: z.array(z.string()).max(200) }))
+ .query(async ({ ctx, input }): Promise<Record<string, string>> =>
+ loadAgentDeviceBindings({
+ agentIds: [...new Set(input.agentIds)],
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ ),
/**
* Per-device running-topic counts and the members behind them, for the
* device list cards. One read for the whole list instead of a request per
diff --git a/apps/server/src/routers/lambda/deviceBoundAgents.ts b/apps/server/src/routers/lambda/deviceBoundAgents.ts
index bdc314ef8d7..f4d5657a232 100644
--- a/apps/server/src/routers/lambda/deviceBoundAgents.ts
+++ b/apps/server/src/routers/lambda/deviceBoundAgents.ts
@@ -14,9 +14,18 @@ import { isResourceAuthorOrAdmin } from '@/server/services/resourcePermission';
/** Permission lookups are DB reads; a caller with many overrides must not open them all at once. */
const PERMISSION_LOOKUP_CONCURRENCY = 5;
+/**
+ * The device a config actually routes to. A stored `boundDeviceId` is only
+ * honoured by the `device` and `local` targets: it intentionally lingers after
+ * switching to the sandbox or `none`, and `auto` treats it as stale.
+ */
+const routedDeviceId = (config: LobeAgentAgencyConfig | undefined): string | undefined =>
+ config?.executionTarget === 'device' || config?.executionTarget === 'local'
+ ? config.boundDeviceId
+ : undefined;
+
const routesToDevice = (config: LobeAgentAgencyConfig | undefined, deviceId: string) =>
- config?.boundDeviceId === deviceId &&
- (config.executionTarget === 'device' || config.executionTarget === 'local');
+ routedDeviceId(config) === deviceId;
/**
* Keep the candidates whose EFFECTIVE execution target, for this caller, is
@@ -58,36 +67,22 @@ export const selectEffectivelyBoundAgents = (
}));
/**
- * Agents routed to `deviceId` for the caller: stored bindings plus the
- * caller's own workspace device overrides, resolved to the effective target.
+ * Agents of `candidates` the caller manages. Management access only changes the
+ * outcome when an override exists (it decides whether a `fixed` policy may
+ * ignore it), so look it up only then β€” with the same author-or-admin check
+ * the run path uses, failing closed.
*/
-export const loadDeviceBoundAgents = async ({
+const resolveManagedAgentIds = async ({
+ candidates,
db,
- deviceId,
+ overrides,
userId,
- workspaceId,
}: {
+ candidates: DeviceBindingCandidate[];
db: LobeChatDatabase;
- deviceId: string;
+ overrides: Record<string, AgentDeviceOverride>;
userId: string;
- workspaceId?: string;
-}): Promise<DeviceBoundAgentItem[]> => {
- // Overrides only exist per workspace; a personal agent's stored config is final.
- const overrides = workspaceId
- ? ((await new WorkspaceUserSettingsModel(db, userId, workspaceId).getPreference())
- .agentDeviceOverrides ?? {})
- : {};
-
- const candidates = await new AgentModel(db, userId, workspaceId).queryBoundToDevice(
- deviceId,
- Object.entries(overrides)
- .filter(([, override]) => override.boundDeviceId === deviceId)
- .map(([agentId]) => agentId),
- );
-
- // Management access only changes the outcome when an override exists (it
- // decides whether a `fixed` policy may ignore it), so look it up only then β€”
- // with the same author-or-admin check the run path uses, failing closed.
+}): Promise<Set<string>> => {
const canManage = new Set<string>();
await pMap(
candidates.filter((agent) => overrides[agent.id]),
@@ -117,5 +112,95 @@ export const loadDeviceBoundAgents = async ({
{ concurrency: PERMISSION_LOOKUP_CONCURRENCY },
);
+ return canManage;
+};
+
+/**
+ * Agents routed to `deviceId` for the caller: stored bindings plus the
+ * caller's own workspace device overrides, resolved to the effective target.
+ */
+export const loadDeviceBoundAgents = async ({
+ db,
+ deviceId,
+ userId,
+ workspaceId,
+}: {
+ db: LobeChatDatabase;
+ deviceId: string;
+ userId: string;
+ workspaceId?: string;
+}): Promise<DeviceBoundAgentItem[]> => {
+ // Overrides only exist per workspace; a personal agent's stored config is final.
+ const overrides = workspaceId
+ ? ((await new WorkspaceUserSettingsModel(db, userId, workspaceId).getPreference())
+ .agentDeviceOverrides ?? {})
+ : {};
+
+ const candidates = await new AgentModel(db, userId, workspaceId).queryBoundToDevice(
+ deviceId,
+ Object.entries(overrides)
+ .filter(([, override]) => override.boundDeviceId === deviceId)
+ .map(([agentId]) => agentId),
+ );
+
+ const canManage = await resolveManagedAgentIds({ candidates, db, overrides, userId });
+
return selectEffectivelyBoundAgents(candidates, { canManage, deviceId, overrides });
};
+
+/**
+ * Where each of `candidates` routes for this caller: the stored config merged
+ * with the caller's own override, exactly as a run resolves it. Agents that
+ * route nowhere (sandbox, none, auto, unbound) are absent.
+ */
+export const selectAgentDeviceBindings = (
+ candidates: DeviceBindingCandidate[],
+ {
+ canManage,
+ overrides,
+ }: {
+ canManage: ReadonlySet<string>;
+ overrides: Record<string, AgentDeviceOverride>;
+ },
+): Record<string, string> => {
+ const bindings: Record<string, string> = {};
+ for (const agent of candidates) {
+ const deviceId = routedDeviceId(
+ resolveAgentAgencyConfig(agent.agencyConfig, overrides[agent.id], {
+ canManage: canManage.has(agent.id),
+ visibility: agent.visibility,
+ workspaceId: agent.workspaceId,
+ }),
+ );
+ if (deviceId) bindings[agent.id] = deviceId;
+ }
+ return bindings;
+};
+
+/**
+ * The effective device of many agents for the caller in one pass β€” the batched
+ * counterpart of {@link loadDeviceBoundAgents}, for surfaces that decorate a
+ * list of agents and must not fetch each agent's config separately.
+ */
+export const loadAgentDeviceBindings = async ({
+ agentIds,
+ db,
+ userId,
+ workspaceId,
+}: {
+ agentIds: string[];
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}): Promise<Record<string, string>> => {
+ const overrides = workspaceId
+ ? ((await new WorkspaceUserSettingsModel(db, userId, workspaceId).getPreference())
+ .agentDeviceOverrides ?? {})
+ : {};
+ const candidates = await new AgentModel(db, userId, workspaceId).queryAgencyRoutingByIds(
+ agentIds,
+ );
+ const canManage = await resolveManagedAgentIds({ candidates, db, overrides, userId });
+
+ return selectAgentDeviceBindings(candidates, { canManage, overrides });
+};
diff --git a/packages/database/src/models/__tests__/agent.characterization.test.ts b/packages/database/src/models/__tests__/agent.characterization.test.ts
index 6d1834be45b..5ee57aac80f 100644
--- a/packages/database/src/models/__tests__/agent.characterization.test.ts
+++ b/packages/database/src/models/__tests__/agent.characterization.test.ts
@@ -86,6 +86,7 @@ const PUBLIC_METHODS = [
'lockTrashedForPurge',
'publishToWorkspace',
'purge',
+ 'queryAgencyRoutingByIds',
'queryAgents',
'queryBoundToDevice',
'rank',
diff --git a/packages/database/src/models/__tests__/agent.queryBoundToDevice.test.ts b/packages/database/src/models/__tests__/agent.queryBoundToDevice.test.ts
index c8dd78805ea..5c52cb030dd 100644
--- a/packages/database/src/models/__tests__/agent.queryBoundToDevice.test.ts
+++ b/packages/database/src/models/__tests__/agent.queryBoundToDevice.test.ts
@@ -105,3 +105,43 @@ describe('AgentModel.queryBoundToDevice', () => {
expect(rows.map((row) => row.id).sort()).toEqual(['ws-public', 'ws-shared-bound']);
});
});
+
+describe('AgentModel.queryAgencyRoutingByIds', () => {
+ it('returns the routing config of the requested agents in one read', async () => {
+ await insertAgent({
+ agencyConfig: { boundDeviceId: 'device-a', executionTarget: 'device' },
+ id: 'a-device',
+ userId: userA,
+ });
+ await insertAgent({ id: 'a-unbound', userId: userA });
+ await insertAgent({ id: 'a-not-requested', userId: userA });
+
+ const rows = await new AgentModel(serverDB, userA).queryAgencyRoutingByIds([
+ 'a-device',
+ 'a-unbound',
+ ]);
+
+ expect(rows.map((row) => row.id).sort()).toEqual(['a-device', 'a-unbound']);
+ expect(rows.find((row) => row.id === 'a-device')?.agencyConfig).toEqual({
+ boundDeviceId: 'device-a',
+ executionTarget: 'device',
+ });
+ });
+
+ it("drops an id the caller cannot see instead of leaking another member's private agent", async () => {
+ await insertAgent({ id: 'ws-public', userId: userA, workspaceId });
+ await insertAgent({ id: 'ws-private-a', userId: userA, visibility: 'private', workspaceId });
+
+ const rows = await new AgentModel(serverDB, userB, workspaceId).queryAgencyRoutingByIds([
+ 'ws-public',
+ 'ws-private-a',
+ 'does-not-exist',
+ ]);
+
+ expect(rows.map((row) => row.id)).toEqual(['ws-public']);
+ });
+
+ it('short-circuits an empty request', async () => {
+ expect(await new AgentModel(serverDB, userA).queryAgencyRoutingByIds([])).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.ts
index 5721f99507e..a56af816b7a 100644
--- a/packages/database/src/models/agent/index.ts
+++ b/packages/database/src/models/agent/index.ts
@@ -48,6 +48,7 @@ export class AgentModel {
// **************** List *************** //
rank = this.withContext(list.rank);
+ queryAgencyRoutingByIds = this.withContext(list.queryAgencyRoutingByIds);
queryBoundToDevice = this.withContext(list.queryBoundToDevice);
queryAgents = this.withContext(list.queryAgents);
countAgents = this.withContext(list.countAgents);
diff --git a/packages/database/src/models/agent/list.ts b/packages/database/src/models/agent/list.ts
index eeff6b39ee9..1a2a9b3d940 100644
--- a/packages/database/src/models/agent/list.ts
+++ b/packages/database/src/models/agent/list.ts
@@ -100,6 +100,44 @@ export const queryBoundToDevice = async (
return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
};
+/**
+ * The stored routing config of the given agents, for resolving where each runs
+ * for the caller in ONE read (a sidebar decorating many agents) instead of one
+ * config fetch per agent. Same visibility gate and row shape as
+ * {@link queryBoundToDevice}: an id the caller cannot see is dropped, never
+ * leaked.
+ */
+export const queryAgencyRoutingByIds = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+): Promise<DeviceBindingCandidate[]> => {
+ if (agentIds.length === 0) return [];
+
+ const rows = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ userId: agents.userId,
+ visibility: agents.visibility,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ and(
+ ctx.ownership(),
+ or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)),
+ inArray(agents.id, agentIds),
+ ),
+ );
+
+ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
+};
+
/**
* Build the where condition shared by queryAgents / countAgents: the current
* user's agents, with optional keyword filter.
diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.ts
index 9e60980e40c..b87f994d931 100644
--- a/packages/trpc/src/client/lambda.test.ts
+++ b/packages/trpc/src/client/lambda.test.ts
@@ -56,6 +56,15 @@ describe('lambdaClient large-input query transport', () => {
'topicIds',
1000,
],
+ [
+ 'device.getAgentDeviceBindings',
+ () =>
+ lambdaClient.device.getAgentDeviceBindings.query({
+ agentIds: Array.from({ length: 100 }, (_, i) => `agt_${String(i).padStart(12, '0')}`),
+ }),
+ 'agentIds',
+ 100,
+ ],
] as const)(
'sends %s with a large path/id array as a POST request',
async (path, call, arrayField, expectedLength) => {
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index a005dbf50bf..0e8deb05e7d 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -251,6 +251,10 @@ const LARGE_INPUT_QUERY_PROCEDURES = new Set([
// the batched GET's 2083-char budget, and a tool-heavy topic is exactly when
// it is called.
'message.getToolResultPayloads',
+ // The sidebar asks for every visible agent group's device binding at once;
+ // the supported 100-topic page can hold ~100 distinct agent ids, far past
+ // the batched GET's 2083-char budget.
+ 'device.getAgentDeviceBindings',
]);
/**
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.test.tsx
new file mode 100644
index 00000000000..26d2bb3a7b1
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.test.tsx
@@ -0,0 +1,116 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import DevicePresenceDot from './DevicePresenceDot';
+
+const mocks = vi.hoisted(() => ({
+ binding: undefined as string | null | undefined,
+ confirmed: true,
+ devices: undefined as Array<Record<string, unknown>> | undefined,
+ useAgentDeviceBinding: vi.fn(),
+}));
+
+vi.mock('./useAgentDeviceBinding', () => ({
+ useAgentDeviceBinding: (agentId: string) => {
+ mocks.useAgentDeviceBinding(agentId);
+ return { data: mocks.binding };
+ },
+}));
+
+vi.mock('@/store/device', () => ({
+ isDevicePresenceUnknown: (device: { onlineUnknown?: boolean }) => !!device.onlineUnknown,
+ useDeviceList: () => ({ data: mocks.devices, isConfirmed: mocks.confirmed }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+const dot = () => screen.queryByTestId('agent-device-presence');
+
+describe('DevicePresenceDot', () => {
+ beforeEach(() => {
+ mocks.useAgentDeviceBinding.mockClear();
+ mocks.binding = 'dev-1';
+ mocks.confirmed = true;
+ mocks.devices = [{ deviceId: 'dev-1', online: true }];
+ });
+
+ it('asks for the binding of the agent it decorates', () => {
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(mocks.useAgentDeviceBinding).toHaveBeenCalledWith('agt-1');
+ });
+
+ it('shows an online dot when the device the agent routes to is online', () => {
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()?.dataset.online).toBe('true');
+ });
+
+ it('shows an offline dot when the device the agent routes to is offline', () => {
+ mocks.devices = [{ deviceId: 'dev-1', online: false }];
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()?.dataset.online).toBe('false');
+ });
+
+ /** @example An agent moved from an offline device to the cloud sandbox is not gray. */
+ it('defaults an agent that routes to no device to online', () => {
+ // The server omits agents whose stored binding the execution target does not use.
+ mocks.binding = null;
+ mocks.devices = [{ deviceId: 'dev-1', online: false }];
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()?.dataset.online).toBe('true');
+ });
+
+ it('defaults to online when the routed device is absent from the caller-scoped list', () => {
+ mocks.devices = [{ deviceId: 'other', online: false }];
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()?.dataset.online).toBe('true');
+ });
+
+ it('renders nothing until the binding is known', () => {
+ mocks.binding = undefined;
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()).toBeNull();
+ });
+
+ it('renders nothing while the device list is only the persisted copy', () => {
+ mocks.confirmed = false;
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()).toBeNull();
+ });
+
+ it('renders nothing while the device list is missing', () => {
+ mocks.devices = undefined;
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()).toBeNull();
+ });
+
+ it('renders nothing when the routed device presence is still unknown', () => {
+ mocks.devices = [{ deviceId: 'dev-1', online: false, onlineUnknown: true }];
+
+ render(<DevicePresenceDot agentId="agt-1" />);
+
+ expect(dot()).toBeNull();
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.tsx
new file mode 100644
index 00000000000..6ab70a343d7
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/DevicePresenceDot.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isDevicePresenceUnknown, useDeviceList } from '@/store/device';
+
+import { useAgentDeviceBinding } from './useAgentDeviceBinding';
+
+const styles = stylex.create({
+ dot: {
+ borderColor: cssVar.colorBgLayout,
+ borderRadius: '50%',
+ borderStyle: 'solid',
+ borderWidth: 1.5,
+ height: 8,
+ insetBlockEnd: -2,
+ insetInlineEnd: -2,
+ position: 'absolute',
+ width: 8,
+ },
+ offline: { backgroundColor: cssVar.colorTextQuaternary },
+ online: { backgroundColor: cssVar.colorSuccess },
+});
+
+interface DevicePresenceDotProps {
+ agentId: string;
+}
+
+/**
+ * Presence of the machine an agent runs on. An agent routed to a device
+ * follows that device. Anything else β€” no binding, cloud / sandbox targets, or
+ * a binding absent from the caller-scoped device list (a shared/legacy binding
+ * can point at the author's personal device, so absence is not proof of
+ * offline, same rule as `useRemoteAgentDeviceGuard`) β€” defaults to online.
+ */
+export const resolveAgentPresence = (
+ boundDeviceId: string | null | undefined,
+ devices: DeviceListItem[],
+): { device?: DeviceListItem; online: boolean } => {
+ const device = boundDeviceId ? devices.find((d) => d.deviceId === boundDeviceId) : undefined;
+ return { device, online: device ? !!device.online : true };
+};
+
+/**
+ * Presence dot anchored to the bottom-right of the (relatively positioned)
+ * avatar it sits in: green when the agent's machine is online, gray when it is
+ * offline. Independent of the topic list β€” it only reads where the agent
+ * routes for the caller and the device list.
+ */
+const DevicePresenceDot = memo<DevicePresenceDotProps>(({ agentId }) => {
+ const { t } = useTranslation('setting');
+ // Where this agent routes for the caller, resolved server-side and fetched
+ // for every group in one batched read (see `useAgentDeviceBinding`).
+ const { data: boundDeviceId } = useAgentDeviceBinding(agentId);
+ const { data: devices, isConfirmed } = useDeviceList();
+
+ // Wait for every source: painting the "online" default first would flash
+ // green on an agent whose device is offline, and a reload paints the
+ // persisted device list first, whose `online: false` is a placeholder.
+ if (boundDeviceId === undefined || !devices || !isConfirmed) return null;
+
+ const { device, online } = resolveAgentPresence(boundDeviceId, devices);
+ if (device && isDevicePresenceUnknown(device)) return null;
+ const deviceName = device?.friendlyName || device?.hostname;
+ const status = t(online ? 'devices.status.online' : 'devices.status.offline');
+
+ return (
+ <Tooltip title={deviceName ? `${deviceName} Β· ${status}` : status}>
+ <span
+ data-online={online ? 'true' : 'false'}
+ data-testid="agent-device-presence"
+ {...stylex.props(styles.dot, online ? styles.online : styles.offline)}
+ />
+ </Tooltip>
+ );
+});
+
+DevicePresenceDot.displayName = 'AgentDevicePresenceDot';
+
+export default DevicePresenceDot;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
index ec22cb5c214..13bb3cd6f5b 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
@@ -108,6 +108,8 @@ vi.mock('@/store/chat/selectors', () => ({
},
}));
+vi.mock('./DevicePresenceDot', () => ({ default: () => null }));
+
vi.mock('@/components/RingLoading', () => ({ default: () => <span /> }));
// Capture what the group hands each row: by-agent buckets are named in the
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
index 70086c751a1..020b7000f9d 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
@@ -42,12 +42,14 @@ import { useProjectDirectories } from '@/store/projectWorkingDirectory';
import { useTopicListScope } from '../../TopicListScope';
import ProjectTopicList from '../ByProjectMode/ProjectTopicList';
import { type GroupItemComponentProps } from '../GroupedAccordion';
+import DevicePresenceDot from './DevicePresenceDot';
const AGENT_GROUP_PREFIX = 'agent:';
const SUB_GROUP_MODES: ProjectTopicSubGroupMode[] = ['none', 'byDevice', 'byTime', 'byStatus'];
const styles = createStaticStyles(({ css }) => ({
avatarWrap: css`
+ position: relative;
flex: none;
border-radius: 50%;
background: ${cssVar.colorFillTertiary};
@@ -161,6 +163,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
<Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>
<Center className={styles.avatarWrap} flex={'none'} height={18} width={18}>
<Avatar avatar={avatar} name={name} size={18} />
+ {agentId && <DevicePresenceDot agentId={agentId} />}
</Center>
<Text ellipsis fontSize={14} style={{ flex: 1 }}>
{name}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.test.tsx
new file mode 100644
index 00000000000..1be28214268
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.test.tsx
@@ -0,0 +1,23 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import ByAgentMode, { DEVICE_PRESENCE_POLL_MS } from './index';
+
+const mocks = vi.hoisted(() => ({ useDeviceList: vi.fn(() => ({})) }));
+
+vi.mock('@/store/device', () => ({ useDeviceList: mocks.useDeviceList }));
+vi.mock('../GroupedAccordion', () => ({ default: () => <div data-testid="accordion" /> }));
+vi.mock('./GroupItem', () => ({ default: () => null }));
+
+describe('ByAgentMode', () => {
+ /** @example A device that drops while the sidebar stays open must turn its dots gray. */
+ it('keeps the device list fresh while it is on screen, polling once for every dot', () => {
+ render(<ByAgentMode />);
+
+ expect(mocks.useDeviceList).toHaveBeenCalledTimes(1);
+ expect(mocks.useDeviceList).toHaveBeenCalledWith({ refreshInterval: DEVICE_PRESENCE_POLL_MS });
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx
index 4d9a978ed82..2bba646216e 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx
@@ -1,8 +1,20 @@
'use client';
+import { useDeviceList } from '@/store/device';
+
import GroupedAccordion from '../GroupedAccordion';
import GroupItem from './GroupItem';
-const ByAgentMode = () => <GroupedAccordion GroupItem={GroupItem} />;
+/** How often the device list is re-read while this list is on screen. */
+export const DEVICE_PRESENCE_POLL_MS = 30_000;
+
+const ByAgentMode = () => {
+ // The presence dots on the group headers read this same device list. One
+ // poller here keeps them live β€” a device that drops while the sidebar stays
+ // open turns gray without a refocus β€” instead of every dot polling on its own.
+ useDeviceList({ refreshInterval: DEVICE_PRESENCE_POLL_MS });
+
+ return <GroupedAccordion GroupItem={GroupItem} />;
+};
export default ByAgentMode;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.test.ts
new file mode 100644
index 00000000000..4696843314c
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.test.ts
@@ -0,0 +1,75 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { loadAgentDeviceBinding } from './useAgentDeviceBinding';
+
+const mocks = vi.hoisted(() => ({ getAgentDeviceBindings: vi.fn() }));
+
+vi.mock('@/services/device', () => ({
+ deviceService: { getAgentDeviceBindings: mocks.getAgentDeviceBindings },
+}));
+vi.mock('@/libs/swr', () => ({ useClientDataSWR: vi.fn() }));
+vi.mock('@/store/user', () => ({ useUserStore: vi.fn() }));
+vi.mock('@/store/user/selectors', () => ({ authSelectors: { isLogin: vi.fn() } }));
+
+describe('loadAgentDeviceBinding', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.getAgentDeviceBindings.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /** @example A sidebar mounting a hundred agent groups makes one read, not a hundred. */
+ it('coalesces agents asked for in the same tick into one server read', async () => {
+ mocks.getAgentDeviceBindings.mockResolvedValue({ a: 'dev-1', b: 'dev-2' });
+
+ const results = Promise.all([
+ loadAgentDeviceBinding('a'),
+ loadAgentDeviceBinding('b'),
+ loadAgentDeviceBinding('c'),
+ ]);
+ await vi.runAllTimersAsync();
+
+ expect(mocks.getAgentDeviceBindings).toHaveBeenCalledTimes(1);
+ expect(mocks.getAgentDeviceBindings).toHaveBeenCalledWith(['a', 'b', 'c']);
+ // An agent the server omits routes to no device.
+ expect(await results).toEqual(['dev-1', 'dev-2', null]);
+ });
+
+ it('asks once for an agent requested twice in the same tick and answers both callers', async () => {
+ mocks.getAgentDeviceBindings.mockResolvedValue({ a: 'dev-1' });
+
+ const results = Promise.all([loadAgentDeviceBinding('a'), loadAgentDeviceBinding('a')]);
+ await vi.runAllTimersAsync();
+
+ expect(mocks.getAgentDeviceBindings).toHaveBeenCalledWith(['a']);
+ expect(await results).toEqual(['dev-1', 'dev-1']);
+ });
+
+ it('starts a new read for agents asked for after the previous batch left', async () => {
+ mocks.getAgentDeviceBindings.mockResolvedValue({});
+
+ const first = loadAgentDeviceBinding('a');
+ await vi.runAllTimersAsync();
+ await first;
+ const second = loadAgentDeviceBinding('b');
+ await vi.runAllTimersAsync();
+ await second;
+
+ expect(mocks.getAgentDeviceBindings.mock.calls).toEqual([[['a']], [['b']]]);
+ });
+
+ it('rejects every waiter of a batch when the read fails', async () => {
+ mocks.getAgentDeviceBindings.mockRejectedValue(new Error('boom'));
+
+ const results = Promise.allSettled([loadAgentDeviceBinding('a'), loadAgentDeviceBinding('b')]);
+ await vi.runAllTimersAsync();
+
+ expect((await results).map((r) => r.status)).toEqual(['rejected', 'rejected']);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.ts
new file mode 100644
index 00000000000..fb0016c2a96
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/useAgentDeviceBinding.ts
@@ -0,0 +1,59 @@
+import { useClientDataSWR } from '@/libs/swr';
+import { deviceService } from '@/services/device';
+import { AGENT_DEVICE_BINDING_SWR_KEY } from '@/store/device/agentDeviceBinding';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+type Waiter = { reject: (error: unknown) => void; resolve: (deviceId: string | null) => void };
+
+let pending = new Map<string, Waiter[]>();
+
+const flush = async () => {
+ const batch = pending;
+ pending = new Map();
+
+ try {
+ const bindings = await deviceService.getAgentDeviceBindings([...batch.keys()]);
+ for (const [agentId, waiters] of batch) {
+ for (const waiter of waiters) waiter.resolve(bindings[agentId] ?? null);
+ }
+ } catch (error) {
+ for (const waiters of batch.values()) {
+ for (const waiter of waiters) waiter.reject(error);
+ }
+ }
+};
+
+/**
+ * Coalesce every agent asked for in the same tick into ONE server read. Each
+ * agent group asks for its own binding, but a sidebar can mount a hundred of
+ * them at once, and a request per agent would be a hundred logical reads.
+ */
+export const loadAgentDeviceBinding = (agentId: string): Promise<string | null> =>
+ new Promise((resolve, reject) => {
+ const waiters = pending.get(agentId);
+ if (waiters) waiters.push({ reject, resolve });
+ else {
+ const isFirst = pending.size === 0;
+ pending.set(agentId, [{ reject, resolve }]);
+ if (isFirst) setTimeout(() => void flush(), 0);
+ }
+ });
+
+/**
+ * The device an agent runs on for the caller: a device id, `null` when it runs
+ * on no device (sandbox, none, auto, unbound), `undefined` until known.
+ *
+ * Resolved server-side (stored config merged with the caller's own override,
+ * keeping only the `device` / `local` targets), so a lingering `boundDeviceId`
+ * of an agent moved to the sandbox never shows up, and a public workspace
+ * agent never reports the author's binding before the caller's override lands.
+ */
+export const useAgentDeviceBinding = (agentId: string | undefined) => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ return useClientDataSWR<string | null>(
+ isLogin && agentId ? [AGENT_DEVICE_BINDING_SWR_KEY, agentId] : null,
+ () => loadAgentDeviceBinding(agentId!),
+ );
+};
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
index 04c42b10fc8..21e182dc05f 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
@@ -90,15 +90,15 @@ describe('useTopicFilterDropdownMenu group modes', () => {
});
/** @example The project sidebar offers by agent and by device, and drops by project because it is already one project. */
- it('offers by agent and by device but not by project inside a project-scoped list', () => {
+ it('offers by agent first, then by device but not by project inside a project-scoped list', () => {
scopeMock.scope = { projectId: 'prj-1' };
const { result } = renderHook(() => useTopicFilterDropdownMenu());
expect(organizeLabels(result.current())).toEqual([
+ 'filter.groupMode.byAgent',
'filter.groupMode.byStatus',
'filter.groupMode.byTime',
- 'filter.groupMode.byAgent',
'filter.groupMode.byDevice',
'filter.groupMode.flat',
]);
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
index 46a0d865425..0b601e34076 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
@@ -28,11 +28,11 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {
return useCallback(() => {
// "by agent" and "by device" only exist where topics span multiple agents
- // and machines β€” the project-scoped list. A single agent's own sidebar
- // hides them. The project-scoped list already is one project, so it hides
+ // and machines β€” the project-scoped list, where "by agent" is the default
+ // and listed first. A single agent's own sidebar hides them. The project-scoped list already is one project, so it hides
// "by project" instead.
const groupModes: TopicGroupMode[] = scope
- ? ['byStatus', 'byTime', 'byAgent', 'byDevice', 'flat']
+ ? ['byAgent', 'byStatus', 'byTime', 'byDevice', 'flat']
: ['byStatus', 'byTime', 'byProject', 'flat'];
const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];
diff --git a/src/services/device.ts b/src/services/device.ts
index a6dbbea8d8e..4c88e3a41ba 100644
--- a/src/services/device.ts
+++ b/src/services/device.ts
@@ -92,6 +92,15 @@ class DeviceService {
return lambdaClient.device.getDeviceActivity.query(input) as any;
}
+ /**
+ * The device each agent runs on for the caller, resolved server-side in one
+ * read. Agents that route to no device (sandbox, none, auto, unbound) are
+ * absent from the result.
+ */
+ getAgentDeviceBindings(agentIds: string[]): Promise<Record<string, string>> {
+ return lambdaClient.device.getAgentDeviceBindings.query({ agentIds });
+ }
+
/** Running-topic count and the members behind it, for every device in the list. */
getRunningSummary(): Promise<DeviceRunningSummary[]> {
return lambdaClient.device.getRunningSummary.query();
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index 781de1f117e..be8ee1ca270 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -28,6 +28,7 @@ import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@
import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';
import { resolveAgentDocumentsContext } from '@/services/agentDocument';
import { aiAgentService } from '@/services/aiAgent';
+import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
// Projection module only (no store import), so this does not cycle through the home store.
@@ -478,6 +479,9 @@ export class AgentSliceActionImpl {
try {
await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal, options);
+ // An execution-target or device change moves where the agent routes for
+ // the caller, which the sidebar presence dots cache per agent.
+ if (config.agencyConfig) void refreshAgentDeviceBindings();
} finally {
if (this.#updateAgentConfigControllers.get(agentId) === controller) {
this.#updateAgentConfigControllers.delete(agentId);
diff --git a/src/store/agent/slices/agent/updateAgentConfigDeviceBinding.test.ts b/src/store/agent/slices/agent/updateAgentConfigDeviceBinding.test.ts
new file mode 100644
index 00000000000..93e94d3b101
--- /dev/null
+++ b/src/store/agent/slices/agent/updateAgentConfigDeviceBinding.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
+
+import { useAgentStore } from '../../store';
+
+vi.mock('@/services/agent', () => ({
+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
+ agentService: {
+ updateAgentConfig: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/device/agentDeviceBinding', () => ({ refreshAgentDeviceBindings: vi.fn() }));
+
+describe('updateAgentConfigById device binding cache', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({ success: true } as any);
+ useAgentStore.setState({ agentMap: { 'agent-1': { agencyConfig: {} } } });
+ });
+
+ /** @example Moving an agent from one device to the cloud sandbox must update its sidebar dot. */
+ it('refreshes the cached device bindings after an agency config write settles', async () => {
+ await useAgentStore
+ .getState()
+ .updateAgentConfigById('agent-1', { agencyConfig: { executionTarget: 'sandbox' } });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalled();
+ expect(refreshAgentDeviceBindings).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the cached device bindings alone for a write that does not touch routing', async () => {
+ await useAgentStore.getState().updateAgentConfigById('agent-1', { model: 'model-a' });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalled();
+ expect(refreshAgentDeviceBindings).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/device/agentDeviceBinding.test.ts b/src/store/device/agentDeviceBinding.test.ts
new file mode 100644
index 00000000000..51c7a7ed65e
--- /dev/null
+++ b/src/store/device/agentDeviceBinding.test.ts
@@ -0,0 +1,21 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AGENT_DEVICE_BINDING_SWR_KEY, refreshAgentDeviceBindings } from './agentDeviceBinding';
+
+const mocks = vi.hoisted(() => ({ mutate: vi.fn() }));
+
+vi.mock('@/libs/swr', () => ({ mutate: mocks.mutate }));
+
+describe('refreshAgentDeviceBindings', () => {
+ beforeEach(() => mocks.mutate.mockClear());
+
+ it('revalidates only the cached agent device bindings, in every workspace context', () => {
+ refreshAgentDeviceBindings();
+
+ const matcher = mocks.mutate.mock.calls[0][0] as (key: unknown) => boolean;
+ expect(matcher([AGENT_DEVICE_BINDING_SWR_KEY, 'agt_1', 'ws-1'])).toBe(true);
+ expect(matcher([AGENT_DEVICE_BINDING_SWR_KEY, 'agt_2'])).toBe(true);
+ expect(matcher(['device/listDevices'])).toBe(false);
+ expect(matcher(AGENT_DEVICE_BINDING_SWR_KEY)).toBe(false);
+ });
+});
diff --git a/src/store/device/agentDeviceBinding.ts b/src/store/device/agentDeviceBinding.ts
new file mode 100644
index 00000000000..2d003c9bcd7
--- /dev/null
+++ b/src/store/device/agentDeviceBinding.ts
@@ -0,0 +1,22 @@
+import { mutate } from '@/libs/swr';
+
+/**
+ * SWR cache key of one agent's resolved device binding (see
+ * `useAgentDeviceBinding`). `useClientDataSWR` appends the active workspace id,
+ * so the key stays an array and every workspace context matches on `[0]`.
+ *
+ * A leaf module on purpose: the agent and user stores call
+ * {@link refreshAgentDeviceBindings} after a routing write, and importing the
+ * hook (which imports those stores) from them would close a module cycle.
+ */
+export const AGENT_DEVICE_BINDING_SWR_KEY = 'agent-device-binding';
+
+/**
+ * Re-resolve every cached agent device binding. The binding the server
+ * resolves for the caller changes whenever an agent's execution target or
+ * device changes, or the caller's own per-agent device override does β€” call
+ * this after those writes settle so a mounted sidebar does not keep showing
+ * the previous device's status until the next focus or remount.
+ */
+export const refreshAgentDeviceBindings = () =>
+ mutate((key: unknown) => Array.isArray(key) && key[0] === AGENT_DEVICE_BINDING_SWR_KEY);
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index 6d9bb5135e3..8639a752f05 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -10,6 +10,7 @@ import {
} from '@/business/client/hooks/useActiveWorkspaceId';
import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
+import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
@@ -261,6 +262,10 @@ export class WorkspaceUserSettingsActionImpl {
() => workspaceUserSettingsService.updatePreference(patch),
{ revalidate: true },
);
+ // The caller's per-agent device override changes where an agent routes for
+ // them, which the sidebar presence dots cache per agent. (Personal mode
+ // has no overrides, so the early return above needs no refresh.)
+ if (patch.agentDeviceOverrides) void refreshAgentDeviceBindings();
};
}
diff --git a/src/store/user/slices/workspaceUserSettings/replica.test.ts b/src/store/user/slices/workspaceUserSettings/replica.test.ts
index 4cec6e7c393..84da8b70ba0 100644
--- a/src/store/user/slices/workspaceUserSettings/replica.test.ts
+++ b/src/store/user/slices/workspaceUserSettings/replica.test.ts
@@ -20,6 +20,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
+import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
import { useUserStore } from '@/store/user';
import { initialWorkspaceUserSettingsState } from './initialState';
@@ -34,6 +35,8 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => active.id,
}));
+vi.mock('@/store/device/agentDeviceBinding', () => ({ refreshAgentDeviceBindings: vi.fn() }));
+
vi.mock('@/services/workspaceUserSettings', () => ({
workspaceUserSettingsService: {
getPreference: vi.fn(),
@@ -238,6 +241,46 @@ describe('workspace user preference replica', () => {
});
});
+ describe('cached agent device bindings', () => {
+ beforeEach(() => {
+ vi.mocked(refreshAgentDeviceBindings).mockClear();
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue({});
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+ renderSync();
+ });
+
+ /** @example A member moving an agent to another device must update its sidebar dot. */
+ it('refreshes after a per-agent device override is written', async () => {
+ await act(() =>
+ state().updateWorkspaceUserPreference({
+ agentDeviceOverrides: { a1: { boundDeviceId: 'device-b', executionTarget: 'device' } },
+ }),
+ );
+
+ expect(refreshAgentDeviceBindings).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves them alone for a preference that does not move an agent', async () => {
+ await act(() => state().updateWorkspaceUserPreference({ agentModeOverrides: { a1: false } }));
+
+ expect(refreshAgentDeviceBindings).not.toHaveBeenCalled();
+ });
+
+ it('leaves them alone when the write fails', async () => {
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockRejectedValue(new Error('nope'));
+
+ await act(async () => {
+ await expect(
+ state().updateWorkspaceUserPreference({
+ agentDeviceOverrides: { a1: { executionTarget: 'sandbox' } },
+ }),
+ ).rejects.toThrow('nope');
+ });
+
+ expect(refreshAgentDeviceBindings).not.toHaveBeenCalled();
+ });
+ });
+
it('applies a write made before hydration onto the persisted bucket, not over it', async () => {
await resource.storage!.set(
{ queryKey: storageKey, scope },