🤯 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): wait for an offline Agent-bound device instead of failing the reply (#23060)
Arvin Xu82ef2fd658e8
diff --git a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.tsindex d17b58305ce..c20300f738d 100644--- a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts+++ b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts@@ -70,7 +70,7 @@ export interface ResolvedRunAgentConfig {resolvedAgentId: string;}-interface WorkspaceMemberOverrides {+export interface WorkspaceMemberOverrides {device?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;mode?: boolean;model?: AgentModelOverride;@@ -82,8 +82,8 @@ interface WorkspaceMemberOverrides {* never mutate the shared Agent config. Losing them is non-fatal: execution* falls back to the shared row.*/-const loadWorkspaceMemberOverrides = async (- deps: ResolveRunAgentConfigDeps,+export const loadWorkspaceMemberOverrides = async (+ deps: Pick<ResolveRunAgentConfigDeps, 'db' | 'userId' | 'workspaceId'>,agentId: string,): Promise<WorkspaceMemberOverrides> => {if (!deps.workspaceId) return {};@@ -112,9 +112,9 @@ const loadWorkspaceMemberOverrides = async (* fail-closed: applying member policy is safer than accidentally granting* shared-config semantics.*/-const resolveCanManage = async (- deps: ResolveRunAgentConfigDeps,- agentConfig: AgentConfigWithId,+export const resolveCanManage = async (+ deps: Pick<ResolveRunAgentConfigDeps, 'db' | 'userId'>,+ agentConfig: Pick<AgentConfigWithId, 'userId' | 'visibility'>,agentWorkspaceId: string | undefined,isPublicWorkspaceAgent: boolean,): Promise<boolean> => {diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.tsindex d37c858744b..3f354c83225 100644--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts@@ -10,6 +10,8 @@ const {getScopedOnlineDevices,notifyChannel,openChannelReply,+ resolveChannelRoutedDevice,+ routedPresence,} = vi.hoisted(() => ({createChannelWorktree: vi.fn(),executions: {@@ -30,6 +32,8 @@ const {getScopedOnlineDevices: vi.fn(),notifyChannel: vi.fn(),openChannelReply: vi.fn(),+ resolveChannelRoutedDevice: vi.fn(),+ routedPresence: { isOnline: vi.fn(), prefetch: vi.fn() },}));vi.mock('@/database/repositories/channel', () => ({ChannelExecutionRepository: class {@@ -56,6 +60,10 @@ vi.mock('./ChannelRoutingService', () => ({vi.mock('./notify', () => ({ notifyChannel }));vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));vi.mock('./replyOpening', () => ({ openChannelReply }));+vi.mock('./routedDevice', () => ({+ createRoutedDevicePresence: () => routedPresence,+ resolveChannelRoutedDevice,+}));vi.mock('./worktree', () => ({ createChannelWorktree }));const coordinator = (count = 3, recovering = false, members: unknown[] = []) => {@@ -239,6 +247,46 @@ describe('Channel concurrent startup', () => {expect(notifyChannel).toHaveBeenCalledWith(expect.anything(), 'channel');});+ it('reads requester presence before claiming an Agent with no device picked in the Channel', async () => {+ executions.candidates.mockResolvedValue({+ heads: [{ id: 'job-0', memberId: 'agent', requesterMemberId: 'person', status: 'queued' }],+ inFlight: [],+ });+ const query = (rows: unknown[]) => {+ const result = Object.assign(Promise.resolve(rows), { from: vi.fn(), where: vi.fn() });+ result.from.mockReturnValue(result);+ result.where.mockReturnValue(result);+ return result;+ };+ const select = vi+ .fn()+ .mockReturnValueOnce(query([{ id: 'channel', workspaceId: 'workspace' }]))+ .mockReturnValueOnce(query([{ config: {}, id: 'agent' }]))+ .mockReturnValueOnce(query([{ userId: 'requester' }]));+ getScopedOnlineDevices.mockResolvedValue([{ deviceId: 'agent-device', online: false }]);+ executions.claim.mockResolvedValue(null);++ 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.mock.invocationCallOrder[0]).toBeLessThan(+ executions.claim.mock.invocationCallOrder[0],+ );+ const [, , options] = executions.claim.mock.calls[0];+ // The requester's devices never join the pool a Channel-picked device is checked against.+ expect(getScopedOnlineDevices).not.toHaveBeenCalled();+ expect(options.onlineDeviceIds).toEqual([]);+ const run = {+ agentId: 'agt',+ executionConfig: {},+ userId: 'requester',+ workspaceId: 'workspace',+ };+ await options.routedDevice(run);+ expect(resolveChannelRoutedDevice).toHaveBeenCalledWith(expect.anything(), run, routedPresence);+ });+it('does not dispatch a blocked job or prevent other Agents from starting', async () => {executions.claim.mockResolvedValueOnce(null);await coordinator().advance('channel');diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex 86ec9c5e8f4..53ff6f9f113 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -3,7 +3,7 @@ import type { LobeChatDatabase } from '@lobechat/database';import { buildChannelPrompt, CHANNEL_INSTRUCTIONS } from '@lobechat/prompts';import type { ChannelExecutionConfig, ChannelSharedAgentAccess } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';-import { and, eq } from 'drizzle-orm';+import { and, eq, inArray } from 'drizzle-orm';import { groupBy } from 'es-toolkit';import pMap from 'p-map';@@ -33,6 +33,7 @@ import { notifyChannel } from './notify';import { registerLocalChannelAdvance, wakeChannel } from './queue';import { deliverRelayReceipt } from './relayReceipt';import { openChannelReply } from './replyOpening';+import { createRoutedDevicePresence, resolveChannelRoutedDevice } from './routedDevice';import { createChannelWorktree } from './worktree';const LEASE_MS = 60_000;@@ -102,10 +103,35 @@ export class ChannelCoordinator {const members = heads.length? await this.db- .select({ config: channelMembers.config })+ .select({ config: channelMembers.config, id: channelMembers.id }).from(channelMembers).where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.status, 'active'))): [];+ // A member with no device picked in the Channel runs where the Agent's own settings say, as+ // its requester: their presence decides whether that device is online. Read it here, outside+ // the channel lock; the claim only resolves which device it is.+ const unpicked = new Set(+ members.filter(({ config }) => !config?.deviceId).map((member) => member.id),+ );+ const requesterIds = [+ ...new Set(+ heads.filter((job) => unpicked.has(job.memberId)).map((job) => job.requesterMemberId),+ ),+ ];+ const requesters = requesterIds.length+ ? await this.db+ .select({ userId: channelMembers.userId })+ .from(channelMembers)+ .where(+ and(eq(channelMembers.channelId, channelId), inArray(channelMembers.id, requesterIds)),+ )+ : [];+ const routedPresence = createRoutedDevicePresence(this.db, channel.workspaceId);+ await pMap(+ requesters.flatMap(({ userId }) => (userId ? [userId] : [])),+ (userId) => routedPresence.prefetch(userId),+ { concurrency: 5 },+ );const owners = [...new Set(members.flatMap(({ config }) => (config?.deviceOwnerId ? [config.deviceOwnerId] : [])),@@ -138,6 +164,7 @@ export class ChannelCoordinator {leaseMs: LEASE_MS,leaseOwner: crypto.randomUUID(),onlineDeviceIds,+ routedDevice: (run) => resolveChannelRoutedDevice(this.db, run, routedPresence),serverDefaultAgentConfig: getServerDefaultAgentConfig(),});let claim = await claimNow();diff --git a/apps/server/src/services/channel/routedDevice.test.ts b/apps/server/src/services/channel/routedDevice.test.tsnew file mode 100644index 00000000000..f0d426710ee--- /dev/null+++ b/apps/server/src/services/channel/routedDevice.test.ts@@ -0,0 +1,177 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createRoutedDevicePresence, resolveChannelRoutedDevice } from './routedDevice';++const {+ findWakeableManagedDevices,+ getScopedOnlineDevices,+ loadWorkspaceMemberOverrides,+ resolveCanManage,+} = vi.hoisted(() => ({+ findWakeableManagedDevices: vi.fn(),+ getScopedOnlineDevices: vi.fn(),+ loadWorkspaceMemberOverrides: vi.fn(),+ resolveCanManage: vi.fn(),+}));+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({ getScopedOnlineDevices }));+vi.mock('@/server/services/aiAgent/pipeline/resolveRunAgentConfig', () => ({+ loadWorkspaceMemberOverrides,+ resolveCanManage,+}));+vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ findWakeableManagedDevices,+}));++const agentRow = { userId: 'author', visibility: 'public', workspaceId: 'workspace' };+const db = (rows: unknown[] = [agentRow]) => {+ const result = Object.assign(Promise.resolve(rows), { from: vi.fn(), where: vi.fn() });+ result.from.mockReturnValue(result);+ result.where.mockReturnValue(result);+ return { select: vi.fn(() => result) } as never;+};+const run = (agencyConfig: Record<string, unknown>) => ({+ agentId: 'agt',+ executionConfig: { agencyConfig } as never,+ userId: 'requester',+ workspaceId: 'workspace',+});+const online = (deviceId: string) => ({ deviceId, online: true });+/** Pools by scope: `workspace` for the Channel's workspace, `personal` without one. */+const pools = (workspace: unknown[], personal: unknown[] = []) =>+ getScopedOnlineDevices.mockImplementation(async (_db, _userId, scope?: string) =>+ scope ? workspace : personal,+ );+const presence = () => createRoutedDevicePresence({} as never, 'workspace');+const claudeOnDevice = {+ boundDeviceId: 'agent-device',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+};++describe('resolveChannelRoutedDevice', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ loadWorkspaceMemberOverrides.mockResolvedValue({});+ resolveCanManage.mockResolvedValue(false);+ findWakeableManagedDevices.mockResolvedValue([]);+ pools([]);+ });++ it('routes a local CLI Agent to the device bound in its own settings', async () => {+ expect(await resolveChannelRoutedDevice(db(), run(claudeOnDevice), presence())).toEqual({+ deviceId: 'agent-device',+ online: false,+ });+ expect(loadWorkspaceMemberOverrides).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'requester', workspaceId: 'workspace' }),+ 'agt',+ );+ });++ it("follows the requester's own device for the Agent", async () => {+ loadWorkspaceMemberOverrides.mockResolvedValue({+ device: { boundDeviceId: 'requester-device', executionTarget: 'device' },+ });+ expect(await resolveChannelRoutedDevice(db(), run(claudeOnDevice), presence())).toEqual({+ deviceId: 'requester-device',+ online: false,+ });+ });++ it('needs no device for a Native Agent, a sandbox run or a device dispatch would wake', async () => {+ expect(await resolveChannelRoutedDevice(db(), run({}), presence())).toBeUndefined();+ expect(+ await resolveChannelRoutedDevice(+ db(),+ run({ executionTarget: 'sandbox', heterogeneousProvider: { type: 'claude-code' } }),+ presence(),+ ),+ ).toBeUndefined();+ findWakeableManagedDevices.mockResolvedValue([{ deviceId: 'agent-device' }]);+ expect(await resolveChannelRoutedDevice(db(), run(claudeOnDevice), presence())).toBeUndefined();+ });++ it('needs no device when the Agent is gone', async () => {+ expect(+ await resolveChannelRoutedDevice(db([]), run(claudeOnDevice), presence()),+ ).toBeUndefined();+ });++ it("sees the requester's routed personal device online in a workspace Channel", async () => {+ pools([online('device-1')], [online('personal-laptop'), online('other-laptop')]);+ loadWorkspaceMemberOverrides.mockResolvedValue({+ device: { boundDeviceId: 'personal-laptop', executionTarget: 'device' },+ });+ expect(await resolveChannelRoutedDevice(db(), run(claudeOnDevice), presence())).toEqual({+ deviceId: 'personal-laptop',+ online: true,+ });+ });++ it("checks a continued conversation's device, not the binding it supersedes", async () => {+ // The requester moved their own binding to an offline device after a run on `device-1`.+ pools([online('device-1')]);+ loadWorkspaceMemberOverrides.mockResolvedValue({+ device: { boundDeviceId: 'offline-device', executionTarget: 'device' },+ });+ const continued = {+ ...run(claudeOnDevice),+ continuation: { agentId: 'agt', metadata: { boundDeviceId: 'device-1' } } as never,+ };+ expect(await resolveChannelRoutedDevice(db(), continued, presence())).toEqual({+ deviceId: 'device-1',+ online: true,+ });+ });++ it('keeps the binding when the workspace fixes the target or the pin was an auto pick', async () => {+ const pinned = { agentId: 'agt', metadata: { boundDeviceId: 'device-1' } } as never;+ const fixed = { ...claudeOnDevice, executionTargetSelectionPolicy: 'fixed' };+ expect(+ await resolveChannelRoutedDevice(db(), { ...run(fixed), continuation: pinned }, presence()),+ ).toEqual({ deviceId: 'agent-device', online: false });+ const auto = { ...claudeOnDevice, executionTarget: 'auto' };+ expect(+ (await resolveChannelRoutedDevice(db(), { ...run(auto), continuation: pinned }, presence()))+ ?.deviceId,+ ).not.toBe('device-1');+ });++ it('leaves a project-directory conversation to the run', async () => {+ const continued = {+ ...run(claudeOnDevice),+ continuation: { agentId: 'agt', metadata: {}, projectWorkingDirectoryId: 'dir' } as never,+ };+ expect(await resolveChannelRoutedDevice(db(), continued, presence())).toBeUndefined();+ });++ 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({+ deviceId: 'agent-device',+ online: false,+ });+ });+});++describe('createRoutedDevicePresence', () => {+ beforeEach(() => vi.resetAllMocks());++ 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);+ expect(getScopedOnlineDevices).toHaveBeenCalledTimes(2);+ });++ it('uses only the personal pool for a personal Channel', 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);+ });+});diff --git a/apps/server/src/services/channel/routedDevice.ts b/apps/server/src/services/channel/routedDevice.tsnew file mode 100644index 00000000000..39ec368febb--- /dev/null+++ b/apps/server/src/services/channel/routedDevice.ts@@ -0,0 +1,145 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import { resolveAgentAgencyConfig } from '@lobechat/types';+import { eq } from 'drizzle-orm';++import type {+ ChannelRoutedDevice,+ ChannelRoutedDeviceInput,+} from '@/database/repositories/channel';+import { agents } from '@/database/schemas';+import { defaultsToAuto, resolveExecutionPlan } from '@/helpers/executionTarget';+import { supportsCloudHeterogeneousSandbox } from '@/server/services/aiAgent/helpers/heteroErrors';+import {+ loadWorkspaceMemberOverrides,+ resolveCanManage,+} from '@/server/services/aiAgent/pipeline/resolveRunAgentConfig';+import { findWakeableManagedDevices } from '@/server/services/deviceGateway/managedDeviceWake';+import { 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>;+ /** Reads the user's presence ahead of the claim, outside the channel lock. */+ prefetch: (userId: string) => 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+ * `(userId, deviceId)`. Only that device is asked about, so no other personal device can stand+ * in for a Channel-picked one.+ */+export const createRoutedDevicePresence = (+ db: LobeChatDatabase,+ workspaceId: string | null,+): RoutedDevicePresence => {+ const pools = new Map<string, Promise<Set<string>>>();+ const pool = (userId: string, scope?: string) => {+ const key = `${userId}\0${scope ?? ''}`;+ let ids = pools.get(key);+ if (!ids) {+ ids = getScopedOnlineDevices(db, userId, scope)+ .then((devices) => new Set(devices.filter((d) => d.online).map((d) => d.deviceId)))+ .catch(() => new Set<string>());+ pools.set(key, ids);+ }+ return ids;+ };+ const scopes = workspaceId ? [workspaceId, undefined] : [undefined];+ return {+ isOnline: async (userId, deviceId) => {+ for (const scope of scopes) 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)]);+ },+ };+};++/**+ * The device a Channel run with no device picked in the Channel routes to, resolved from the+ * same inputs the run itself uses: the claimed Agent config, the requester's own device override+ * for the Agent (`snapshotFollowsCallerDevice`) and the local CLI execution plan of+ * `resolveHeteroRouting`. Undefined when the run needs no device to start: a Native run, a+ * remote (platform) Agent, a sandbox or unrouted plan, or a managed device dispatch would wake.+ *+ * A continued conversation is checked against the device it will actually run on: the topic's+ * pin wins over the Agent binding, except when the workspace fixes the target, or the target is+ * `auto` and the pin was only an earlier auto pick. A project-directory continuation routes to+ * its directory's device, which only the run resolves, so it is not gated here.+ */+export const resolveChannelRoutedDevice = async (+ db: LobeChatDatabase,+ { agentId, continuation, executionConfig, userId, workspaceId }: ChannelRoutedDeviceInput,+ presence: RoutedDevicePresence,+): Promise<ChannelRoutedDevice | undefined> => {+ const heteroType = executionConfig.agencyConfig?.heterogeneousProvider?.type;+ if (!heteroType || isRemoteHeterogeneousType(heteroType)) return;++ const [agent] = await db+ .select({+ userId: agents.userId,+ visibility: agents.visibility,+ workspaceId: agents.workspaceId,+ })+ .from(agents)+ .where(eq(agents.id, agentId));+ if (!agent) return;+ const scope = { db, userId, workspaceId: workspaceId ?? undefined };+ // As `resolveRunAgentConfig` decides it for the same caller and Agent.+ const agentWorkspaceId = agent.workspaceId ?? scope.workspaceId;+ const [{ device }, canManage] = await Promise.all([+ loadWorkspaceMemberOverrides(scope, agentId),+ resolveCanManage(+ scope,+ agent,+ agentWorkspaceId,+ !!agentWorkspaceId && agent.visibility !== 'private',+ ),+ ]);+ const agencyConfig = resolveAgentAgencyConfig(executionConfig.agencyConfig, device, {+ canManage,+ visibility: agent.visibility ?? undefined,+ workspaceId: agentWorkspaceId,+ });++ // A continued conversation stays on the device it ran on, as `turnSetup` routes it: the topic's+ // pin beats the Agent binding unless the workspace fixes the target, or the target is `auto`+ // and the pin was only an earlier auto pick. A project-directory topic routes to its+ // directory's device, which only the run resolves, so it is not gated here.+ if (continuation?.projectWorkingDirectoryId) return;+ const topicPinnedDeviceId =+ !continuation?.groupId || continuation.agentId === agentId+ ? continuation?.metadata?.boundDeviceId+ : undefined;+ const fixedSelection = !!workspaceId && agencyConfig?.executionTargetSelectionPolicy === 'fixed';+ const autoTarget = agencyConfig?.executionTarget === 'auto' || defaultsToAuto(agencyConfig, true);+ const pinnedDeviceId =+ topicPinnedDeviceId &&+ !fixedSelection &&+ (!autoTarget || continuation?.metadata?.deviceBindingPinned === true)+ ? topicPinnedDeviceId+ : undefined;++ const wakeable = await findWakeableManagedDevices(scope, [+ pinnedDeviceId ?? agencyConfig?.boundDeviceId,+ ]);+ if (pinnedDeviceId) {+ if (wakeable.length) return;+ return { deviceId: pinnedDeviceId, online: await presence.isOnline(userId, pinnedDeviceId) };+ }+ const plan = resolveExecutionPlan({+ agencyConfig,+ clientExecutionAvailable: false,+ isHetero: true,+ sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),+ wakeableDeviceIds: wakeable.map((target) => target.deviceId),+ });+ // 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) };+};diff --git a/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts b/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.tsindex e48ab796876..2738229250d 100644--- a/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts+++ b/packages/database/src/repositories/channel/__tests__/dispatchSafety.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { 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 { AgentOperationModel } from '../../../models/agentOperation';@@ -69,6 +69,124 @@ describe('Channel dispatch reservation', () => {expect(claimed?.job.operationId).toBeTruthy();expect(claimed?.job.blockedCode).toBeNull();});+ it('records the Channel device a job waits for', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Device agent', deviceConfig());+ const message = await asOwner.send(channel.id, {+ content: 'Wait for device',+ requestKey: 'offline-device-id',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ await executions.claim(channel.id, job.id, { ...lease, onlineDeviceIds: [] });+ expect(await jobById(db, job.id)).toMatchObject({+ blockedCode: 'device_offline',+ deviceId: 'device-1',+ });+ });++ it('keeps a job queued while the device the Agent itself routes to is offline', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ // No device picked in the Channel: the Agent's own settings route the run.+ const member = await fixture.addAgent(channel.id, 'Claude Code', {+ model: 'claude-code',+ provider: 'claude-code',+ runtime: 'claude-code',+ });+ const message = await asOwner.send(channel.id, {+ content: 'Run on the bound device',+ requestKey: 'agent-bound-offline',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ const routedDevice = vi.fn(async () => ({ deviceId: 'agent-device', online: false }));++ expect(+ await executions.claim(channel.id, job.id, { ...lease, onlineDeviceIds: [], routedDevice }),+ ).toBeNull();+ expect(routedDevice).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: member.agentId,+ userId: fixture.ownerId,+ workspaceId: fixture.workspaceId,+ }),+ );+ expect(await jobById(db, job.id)).toMatchObject({+ status: 'queued',+ operationId: null,+ blockedCode: 'device_offline',+ deviceId: 'agent-device',+ writerHeld: false,+ });++ routedDevice.mockResolvedValue({ deviceId: 'agent-device', online: true });+ const claimed = await executions.claim(channel.id, job.id, {+ ...lease,+ onlineDeviceIds: [],+ routedDevice,+ });+ expect(claimed?.job.operationId).toBeTruthy();+ // The wait marker does not become the claimed run's Channel device.+ expect(claimed?.job).toMatchObject({ blockedCode: null, deviceId: null });+ });++ it('asks for no routed device without a presence snapshot', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Claude Code', {+ model: 'claude-code',+ provider: 'claude-code',+ runtime: 'claude-code',+ });+ const message = await asOwner.send(channel.id, {+ content: 'Storage-only claim',+ requestKey: 'agent-bound-storage',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ const routedDevice = vi.fn(async () => ({ deviceId: 'agent-device', online: false }));+ expect(await executions.claim(channel.id, job.id, { ...lease, routedDevice })).not.toBeNull();+ expect(routedDevice).not.toHaveBeenCalled();+ });++ it("starts on the requester's own device outside the Channel's device pool", async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Claude Code', {+ model: 'claude-code',+ provider: 'claude-code',+ runtime: 'claude-code',+ });+ const message = await asOwner.send(channel.id, {+ content: 'Run on my laptop',+ requestKey: 'agent-bound-personal',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ // The workspace pool does not list a personal device; the requester reaches it anyway.+ const claimed = await executions.claim(channel.id, job.id, {+ ...lease,+ onlineDeviceIds: ['device-1'],+ routedDevice: async () => ({ deviceId: 'personal-laptop', online: true }),+ });+ expect(claimed?.job).toMatchObject({ blockedCode: null, status: 'running' });+ });++ it('never lets the routed device stand in for a Channel-picked one', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await fixture.addAgent(channel.id, 'Device agent', deviceConfig());+ const message = await asOwner.send(channel.id, {+ content: 'Channel device offline',+ requestKey: 'picked-offline',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ const routedDevice = vi.fn(async () => ({ deviceId: 'device-1', online: true }));+ expect(+ await executions.claim(channel.id, job.id, { ...lease, onlineDeviceIds: [], routedDevice }),+ ).toBeNull();+ expect(routedDevice).not.toHaveBeenCalled();+ expect(await jobById(db, job.id)).toMatchObject({ blockedCode: 'device_offline' });+ });+it('fences a dispatcher that resumes after its reservation was retired', async () => {const { channel, job, operationId, start } = await reserve();expect(await executions.retireReservation(channel.id, job.id)).toBe(true);diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex e712cf88287..5d1680dc795 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -1,4 +1,4 @@-import type { ChannelJobBlockCode, LobeAgentConfig } from '@lobechat/types';+import type { ChannelExecutionConfig, ChannelJobBlockCode, LobeAgentConfig } from '@lobechat/types';import { and, asc, eq, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';@@ -19,7 +19,8 @@ import { uniqueViolationConstraint } from '../../utils/uniqueViolation';import { resolveExecutionConfig } from './agent';import { AWAITING_PRIMARY_REASON, findThread } from './delivery';import { buildManifest } from './manifest';-import { resolveTopic } from './topic';+import type { ChannelTopicScope } from './topic';+import { continuationTopic, resolveTopic } from './topic';import { audit } from './transaction';import { assignedWorktree } from './worktree';@@ -30,10 +31,37 @@ export interface ChannelClaimOptions {leaseOwner: string;/** Trusted presence snapshot from the current Gateway scope; omitted by storage-only callers. */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+ * `onlineDeviceIds`.+ */+ routedDevice?: (run: ChannelRoutedDeviceInput) => Promise<ChannelRoutedDevice | undefined>;/** Trusted server defaults from getServerDefaultAgentConfig(); use {} when unconfigured. */serverDefaultAgentConfig: PartialDeep<LobeAgentConfig>;}+export interface ChannelRoutedDevice {+ deviceId: string;+ online: boolean;+}++export interface ChannelRoutedDeviceInput {+ agentId: string;+ /**+ * The topic this run will continue, if any. A conversation stays on the device it ran on, so+ * its pin can outrank the Agent's binding.+ */+ continuation?: Pick<TopicItem, 'agentId' | 'groupId' | 'metadata' | 'projectWorkingDirectoryId'>;+ executionConfig: ChannelExecutionConfig;+ /** The requester: the run executes as them, with their device preference for the Agent. */+ userId: string;+ workspaceId: string | null;+}+export interface ChannelClaim {/** The claimed job, with its reserved `operationId` and frozen `manifest`. */job: ChannelJobItem;@@ -44,20 +72,25 @@ export interface ChannelClaim {const DIRECTORY_LOCK = 'channel_jobs_active_directory_unique';-/** Records why a queued job cannot start; clients read the code, never the text. */+/**+ * Records why a queued job cannot start; clients read the code, never the text. A job waiting+ * for a device also records which one in `deviceId`, so it can be shown before any claim sets+ * it. Only a claim gives a job its writer, so a queued job's device holds no directory.+ */const block = async (tx: Transaction,job: ChannelJobItem,code: ChannelJobBlockCode,reason: string,+ deviceId: string | null = null,) => {- if (job.blockedCode === code && job.blockedReason === reason) return;+ if (job.blockedCode === code && job.blockedReason === reason && job.deviceId === deviceId) return;await tx.update(channelJobs)- .set({ blockedCode: code, blockedReason: reason })+ .set({ blockedCode: code, blockedReason: reason, deviceId }).where(eq(channelJobs.id, job.id));- await audit(tx, job.channelId, 'job_blocked', job.id, { code, reason });+ await audit(tx, job.channelId, 'job_blocked', job.id, { code, deviceId, reason });};/** Settles a job that must never run, e.g. its requester left or its branch was archived. */@@ -344,12 +377,51 @@ export const claimJob = async (return null;}- if (- member.config?.deviceId &&- options.onlineDeviceIds &&- !options.onlineDeviceIds.includes(member.config.deviceId)- ) {- await block(tx, job, 'device_offline', 'Waiting for the configured device to connect');+ // The execution identity the topic belongs to: a shared Agent's owner (with the requester as+ // `senderId`), else the requester. The routing pre-check below and the claim itself resolve+ // the same topic, so they have to agree on this scope.+ const { share } = executionConfig;+ const scope: ChannelTopicScope = share+ ? { senderId: requester.userId!, userId: share.ownerId, workspaceId: share.workspaceId }+ : { userId: requester.userId!, workspaceId: channel.workspaceId };++ // A device picked in the Channel, else the one the Agent's own settings route the run to.+ const channelDeviceId = member.config?.deviceId;+ const routed =+ options.onlineDeviceIds && !channelDeviceId+ ? await options.routedDevice?.({+ agentId: member.agentId!,+ continuation: await continuationTopic(+ tx,+ channel,+ job,+ member,+ scope,+ request.sequence,+ executionConfig,+ ),+ executionConfig,+ userId: requester.userId!,+ workspaceId: channel.workspaceId,+ })+ : undefined;+ const offlineDeviceId = !options.onlineDeviceIds+ ? undefined+ : channelDeviceId+ ? options.onlineDeviceIds.includes(channelDeviceId)+ ? undefined+ : channelDeviceId+ : routed && !routed.online+ ? routed.deviceId+ : undefined;+ if (offlineDeviceId) {+ await block(+ tx,+ job,+ 'device_offline',+ 'Waiting for the configured device to connect',+ offlineDeviceId,+ );return null;}@@ -359,10 +431,6 @@ export const claimJob = async (// A savepoint, so losing the directory race to another channel keeps this transaction// and leaves no topic or operation behind.claimed = await tx.transaction(async (savepoint) => {- const { share } = executionConfig;- const scope = share- ? { senderId: requester.userId!, userId: share.ownerId, workspaceId: share.workspaceId }- : { userId: requester.userId!, workspaceId: channel.workspaceId };const topic = await resolveTopic(savepoint,channel,@@ -399,7 +467,8 @@ export const claimJob = async (claimedAt: sql`clock_timestamp()`,blockedCode: null,blockedReason: null,- deviceId: member.config!.deviceId,+ // Only a device picked in the Channel; a wait marker from `block` must not linger.+ deviceId: member.config!.deviceId ?? null,executionConfig,leaseExpiresAt: new Date(now.getTime() + options.leaseMs),leaseOwner: options.leaseOwner,diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 4010f11d6c8..6fcac321db6 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -51,7 +51,12 @@ export {CHANNEL_ROUTING_LEASE_MS,ChannelRoutingRepository,} from './ChannelRoutingRepository';-export type { ChannelClaim, ChannelClaimOptions } from './claim';+export type {+ ChannelClaim,+ ChannelClaimOptions,+ ChannelRoutedDevice,+ ChannelRoutedDeviceInput,+} from './claim';export type { ChannelErrorCode } from './error';export { ChannelError } from './error';export { ChannelExecutionRepository } from './execution';diff --git a/packages/database/src/repositories/channel/topic.ts b/packages/database/src/repositories/channel/topic.tsindex e3ff1c5f5fc..ba57266792a 100644--- a/packages/database/src/repositories/channel/topic.ts+++ b/packages/database/src/repositories/channel/topic.ts@@ -32,7 +32,12 @@ export interface ChannelTopicScope {workspaceId: string | null;}-export const resolveTopic = async (+/**+ * The topic this job continues, when it may: the requester's latest settled run for this member+ * and branch, with an unchanged execution config and a fresh enough topic. Undefined starts a new+ * topic. Read-only, so a claim can ask before it commits to running.+ */+export const continuationTopic = async (tx: Transaction,channel: ChannelItem,job: ChannelJobItem,@@ -79,7 +84,29 @@ export const resolveTopic = async (!topic.isDeleted &&(job.threadId || Date.now() - topic.updatedAt.getTime() <= TOPIC_STALE_THRESHOLD) &&!(executionConfig.share && (await reachedShareTurnLimit(tx, member.agentId!, topic.id)))- ) {+ )+ return topic;+};++export const resolveTopic = async (+ tx: Transaction,+ channel: ChannelItem,+ job: ChannelJobItem,+ member: ChannelMemberItem,+ scope: ChannelTopicScope,+ requestSequence: number,+ executionConfig: ChannelExecutionConfig,+) => {+ const topic = await continuationTopic(+ tx,+ channel,+ job,+ member,+ scope,+ requestSequence,+ executionConfig,+ );+ if (topic) {// A Channel that belongs to a project runs inside it, so the topic it works in// must say which project it belongs to: that binding is what the run resolves// its project context from (project prompt, coordinator scope, task ownership).