🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(channel): check a shared Agent's routed device as its owner (#23460)
YuTengjing3d6932ece7d2
diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.tsindex cc593ff52aa..08cde2178a3 100644--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts@@ -276,7 +276,7 @@ describe('Channel concurrent startup', () => {await new ChannelCoordinator({ select } as never).advance('channel');// Outside the channel lock, before the claim resolves the routed device.- expect(routedPresence.prefetch).toHaveBeenCalledWith('requester');+ expect(routedPresence.prefetch).toHaveBeenCalledWith('requester', 'workspace');expect(routedPresence.prefetch.mock.invocationCallOrder[0]).toBeLessThan(executions.claim.mock.invocationCallOrder[0],);diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex a533690322b..35d1c39e019 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -174,10 +174,11 @@ export class ChannelCoordinator {and(eq(channelMembers.channelId, channelId), inArray(channelMembers.id, requesterIds)),): [];- const routedPresence = createRoutedDevicePresence(this.db, channel.workspaceId);+ // A shared Agent's run executes as its owner; the claim reads that presence on demand.+ const routedPresence = createRoutedDevicePresence(this.db);await pMap(requesters.flatMap(({ userId }) => (userId ? [userId] : [])),- (userId) => routedPresence.prefetch(userId),+ (userId) => routedPresence.prefetch(userId, channel.workspaceId),{ concurrency: 5 },);const owners = [diff --git a/apps/server/src/services/channel/routedDevice.test.ts b/apps/server/src/services/channel/routedDevice.test.tsindex f0d426710ee..46a6afd75c9 100644--- a/apps/server/src/services/channel/routedDevice.test.ts+++ b/apps/server/src/services/channel/routedDevice.test.ts@@ -42,7 +42,7 @@ const pools = (workspace: unknown[], personal: unknown[] = []) =>getScopedOnlineDevices.mockImplementation(async (_db, _userId, scope?: string) =>scope ? workspace : personal,);-const presence = () => createRoutedDevicePresence({} as never, 'workspace');+const presence = () => createRoutedDevicePresence({} as never);const claudeOnDevice = {boundDeviceId: 'agent-device',executionTarget: 'device',@@ -146,6 +146,21 @@ describe('resolveChannelRoutedDevice', () => {expect(await resolveChannelRoutedDevice(db(), continued, presence())).toBeUndefined();});+ // A shared Agent runs as its owner in the owner's scope; the visitor's Channel may sit in a+ // workspace the owner's device was never in.+ it("checks a shared Agent's device in the owner's scope, not the visitor Channel's", async () => {+ getScopedOnlineDevices.mockImplementation(async (_db, userId: string, scope?: string) =>+ userId === 'owner' && !scope ? [online('agent-device')] : [],+ );+ expect(+ await resolveChannelRoutedDevice(+ db(),+ { ...run(claudeOnDevice), userId: 'owner', workspaceId: null },+ presence(),+ ),+ ).toEqual({ deviceId: 'agent-device', online: true });+ });+it('reports the routed device offline when neither pool has it', async () => {pools([online('device-1')], [online('other-laptop')]);expect(await resolveChannelRoutedDevice(db(), run(claudeOnDevice), presence())).toEqual({@@ -161,17 +176,17 @@ describe('createRoutedDevicePresence', () => {it('reads each pool once per requester and only asks about the routed device', async () => {pools([online('device-1')], [online('personal-laptop')]);const cache = presence();- await cache.prefetch('requester');- expect(await cache.isOnline('requester', 'personal-laptop')).toBe(true);- expect(await cache.isOnline('requester', 'device-1')).toBe(true);- expect(await cache.isOnline('requester', 'missing')).toBe(false);+ await cache.prefetch('requester', 'workspace');+ expect(await cache.isOnline('requester', 'personal-laptop', 'workspace')).toBe(true);+ expect(await cache.isOnline('requester', 'device-1', 'workspace')).toBe(true);+ expect(await cache.isOnline('requester', 'missing', 'workspace')).toBe(false);expect(getScopedOnlineDevices).toHaveBeenCalledTimes(2);});- it('uses only the personal pool for a personal Channel', async () => {+ it('uses only the personal pool for a personal run', async () => {pools([online('device-1')], [online('personal-laptop')]);- const cache = createRoutedDevicePresence({} as never, null);- expect(await cache.isOnline('requester', 'device-1')).toBe(false);- expect(await cache.isOnline('requester', 'personal-laptop')).toBe(true);+ const cache = presence();+ expect(await cache.isOnline('requester', 'device-1', null)).toBe(false);+ expect(await cache.isOnline('requester', 'personal-laptop', null)).toBe(true);});});diff --git a/apps/server/src/services/channel/routedDevice.ts b/apps/server/src/services/channel/routedDevice.tsindex 39ec368febb..0e3db1655ce 100644--- a/apps/server/src/services/channel/routedDevice.ts+++ b/apps/server/src/services/channel/routedDevice.ts@@ -18,23 +18,23 @@ import { findWakeableManagedDevices } from '@/server/services/deviceGateway/manaimport { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';export interface RoutedDevicePresence {- /** Whether `userId` can reach `deviceId` online in this Channel's scope. */- isOnline: (userId: string, deviceId: string) => Promise<boolean>;+ /** Whether `userId` can reach `deviceId` online in the run's `workspaceId` scope. */+ isOnline: (userId: string, deviceId: string, workspaceId: string | null) => Promise<boolean>;/** Reads the user's presence ahead of the claim, outside the channel lock. */- prefetch: (userId: string) => Promise<void>;+ prefetch: (userId: string, workspaceId: string | null) => Promise<void>;}/**- * Presence of requesters' routed devices for one advance pass, read once per requester. A- * workspace run reaches the Channel workspace's devices and, as `readDevicePool` allows, the- * requester's own personal device when the run routes exactly there: the gateway routes it by+ * Presence of routed devices for one advance pass, read once per execution identity and scope. A+ * workspace run reaches that workspace's devices and, as `readDevicePool` allows, the executing+ * user's own personal device when the run routes exactly there: the gateway routes it by* `(userId, deviceId)`. Only that device is asked about, so no other personal device can stand* in for a Channel-picked one.+ *+ * The scope is the run's, not the Channel's: a shared Agent runs as its owner in the owner's+ * scope, so its device is looked up there even when the visitor's Channel sits in a workspace.*/-export const createRoutedDevicePresence = (- db: LobeChatDatabase,- workspaceId: string | null,-): RoutedDevicePresence => {+export const createRoutedDevicePresence = (db: LobeChatDatabase): RoutedDevicePresence => {const pools = new Map<string, Promise<Set<string>>>();const pool = (userId: string, scope?: string) => {const key = `${userId}\0${scope ?? ''}`;@@ -47,15 +47,17 @@ export const createRoutedDevicePresence = (}return ids;};- const scopes = workspaceId ? [workspaceId, undefined] : [undefined];+ const scopes = (workspaceId: string | null) =>+ workspaceId ? [workspaceId, undefined] : [undefined];return {- isOnline: async (userId, deviceId) => {- for (const scope of scopes) if ((await pool(userId, scope)).has(deviceId)) return true;+ isOnline: async (userId, deviceId, workspaceId) => {+ for (const scope of scopes(workspaceId))+ if ((await pool(userId, scope)).has(deviceId)) return true;return false;},- // At most two reads: the Channel workspace's pool and, for a workspace Channel, the personal one.- prefetch: async (userId) => {- await Promise.all([pool(userId, workspaceId ?? undefined), workspaceId && pool(userId)]);+ // At most two reads: the workspace's pool and, for a workspace run, the personal one.+ prefetch: async (userId, workspaceId) => {+ await Promise.all(scopes(workspaceId).map((scope) => pool(userId, scope)));},};};@@ -130,7 +132,10 @@ export const resolveChannelRoutedDevice = async (]);if (pinnedDeviceId) {if (wakeable.length) return;- return { deviceId: pinnedDeviceId, online: await presence.isOnline(userId, pinnedDeviceId) };+ return {+ deviceId: pinnedDeviceId,+ online: await presence.isOnline(userId, pinnedDeviceId, workspaceId),+ };}const plan = resolveExecutionPlan({agencyConfig,@@ -141,5 +146,8 @@ export const resolveChannelRoutedDevice = async (});// No presence here: the plan trusts the binding (personal or not), as hetero dispatch does.if (plan.kind !== 'device') return;- return { deviceId: plan.deviceId, online: await presence.isOnline(userId, plan.deviceId) };+ return {+ deviceId: plan.deviceId,+ online: await presence.isOnline(userId, plan.deviceId, workspaceId),+ };};diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex fdab611358e..55be690f74f 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -837,9 +837,15 @@ describe('AgentShareModel', () => {});describe('lockUploadAdmission', () => {- const heldAdvisoryLocks = async (db: LobeChatDatabase) => {+ // Counts only this share's upload lock: other test files run in parallel against the same+ // database and hold advisory locks of their own, so a database-wide count is flaky. A bigint+ // advisory key is stored as its high (`classid`) and low (`objid`) 32 bits.+ const heldUploadLocks = async (db: LobeChatDatabase, shareId: string) => {const { rows } = await db.execute(- sql`SELECT count(*)::int AS held FROM pg_locks WHERE locktype = 'advisory'`,+ sql`SELECT count(*)::int AS held FROM pg_locks+ WHERE locktype = 'advisory' AND objsubid = 1+ AND ((classid::text::bigint << 32) | objid::text::bigint)+ = hashtext(${`agent_share_upload:${shareId}`})::bigint`,);return (rows[0] as { held: number }).held;};@@ -847,12 +853,12 @@ describe('AgentShareModel', () => {it('holds a transaction-scoped advisory lock that is released at commit', async () => {await serverDB.transaction(async (tx) => {await AgentShareModel.lockUploadAdmission(tx, 'share-lock-test');- await expect(heldAdvisoryLocks(tx)).resolves.toBe(1);+ await expect(heldUploadLocks(tx, 'share-lock-test')).resolves.toBe(1);// Re-entrant within the same transaction: a retry does not deadlock.await AgentShareModel.lockUploadAdmission(tx, 'share-lock-test');});- await expect(heldAdvisoryLocks(serverDB)).resolves.toBe(0);+ await expect(heldUploadLocks(serverDB, 'share-lock-test')).resolves.toBe(0);});});diff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.tsindex 143528a0212..250a66f9e99 100644--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';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 {@@ -162,6 +162,42 @@ describe('a contact’s shared Agent in a direct conversation', () => {}});+ // The run uses the owner's device, so its presence is the owner's: asking about the visitor+ // left every visitor waiting for a device that was online.+ it("checks the owner's routed device as the owner, in the owner's scope", async () => {+ await db+ .update(agents)+ .set({+ agencyConfig: {+ boundDeviceId: 'owner-device',+ executionTarget: 'device',+ heterogeneousProvider: { command: 'claude-code', type: 'claude-code' },+ },+ })+ .where(eq(agents.id, agentId));+ const { channel } = await new ChannelRepository(db, visitorId, fixture.workspaceId).create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const message = await new ChannelRepository(db, visitorId, fixture.workspaceId).send(+ channel.id,+ { content: 'Hello', requestKey: 'routed', routing: 'fallback' },+ );+ const [job] = await jobsOf(db, message.id);+ const routedDevice = vi.fn(async () => ({ deviceId: 'owner-device', online: true }));++ const claim = await execution.claim(channel.id, job.id, {+ ...lease,+ onlineDeviceIds: [],+ routedDevice,+ });+ expect(routedDevice).toHaveBeenCalledWith(+ expect.objectContaining({ agentId, userId: ownerId, workspaceId: null }),+ );+ expect(claim?.job).toMatchObject({ blockedCode: null });+ });+it('is blocked for a runtime its share page cannot run', async () => {await db.update(agents)diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex 0f2302982ef..ee80009cee6 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -31,10 +31,10 @@ export interface ChannelClaimOptions {onlineDeviceIds?: string[];/*** The device a run with no device picked in the Channel will route to, from the Agent's own- * settings as the requester's ordinary conversation would resolve them, and whether it is- * online for that requester; undefined when it needs none or would wake it. Lets an offline- * Agent-bound device wait like a Channel one. Its presence is the requester's, which may- * include their personal device, so it stays out of `onlineDeviceIds`. Only consulted with+ * settings as the execution identity's ordinary conversation would resolve them, and whether it+ * is online for that identity; undefined when it needs none or would wake it. Lets an offline+ * Agent-bound device wait like a Channel one. Its presence is that identity's, which may+ * include a personal device, so it stays out of `onlineDeviceIds`. Only consulted with* `onlineDeviceIds`.*/routedDevice?: (run: ChannelRoutedDeviceInput) => Promise<ChannelRoutedDevice | undefined>;@@ -55,8 +55,12 @@ export interface ChannelRoutedDeviceInput {*/continuation?: Pick<TopicItem, 'agentId' | 'groupId' | 'metadata' | 'projectWorkingDirectoryId'>;executionConfig: ChannelExecutionConfig;- /** The requester: the run executes as them, with their device preference for the Agent. */+ /**+ * The execution identity, with its device preference for the Agent: the requester, or a shared+ * Agent's owner, whose device the visitor's run uses.+ */userId: string;+ /** The run's scope: the Channel's, or a shared Agent's owner scope. */workspaceId: string | null;}@@ -444,8 +448,8 @@ export const claimJob = async (executionConfig,),executionConfig,- userId: requester.userId!,- workspaceId: channel.workspaceId,+ userId: scope.userId,+ workspaceId: scope.workspaceId,}): undefined;const offlineDeviceId = !options.onlineDeviceIds