🤯 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
✨ feat(channel): let device owners approve Channel Agents on their private devices (#23620)
Arvin Xu09a8dea486a1
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex ada5bcc402b..df3fc1a5ec6 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -119,6 +119,18 @@ export const channelRouter = router({),success: true,})),+ /** Requests to run Channel Agents on the caller's private devices, for them to decide. */+ deviceGrants: channelProcedure.query(async ({ ctx }) => ({+ data: await ctx.channelService.deviceGrants(),+ success: true,+ })),+ /** Only the device owner named on the grant may decide it. */+ decideDeviceGrant: channelProcedure+ .input(z.object({ decision: z.enum(['approve', 'reject', 'revoke']), grantId: z.uuid() }))+ .mutation(async ({ ctx, input }) => ({+ data: await ctx.channelService.decideDeviceGrant(input.grantId, input.decision),+ success: true,+ })),/** The channel's reply strategy and each Agent member's own, as stored; admins only. */wakeConfig: channelProcedure.input(z.object({ channelId })).query(async ({ ctx, input }) => ({data: await ctx.channelService.repository.wakeConfig(input.channelId),diff --git a/apps/server/src/services/channel/ChannelService.deviceGrant.test.ts b/apps/server/src/services/channel/ChannelService.deviceGrant.test.tsnew file mode 100644index 00000000000..2b0312683d5--- /dev/null+++ b/apps/server/src/services/channel/ChannelService.deviceGrant.test.ts@@ -0,0 +1,121 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ChannelService } from './ChannelService';++const { addAgent, decide, devicesByUser, findAccess, getAgent, notify, statPath, wake } =+ vi.hoisted(() => ({+ addAgent: vi.fn(),+ decide: vi.fn(),+ /** Workspace devices each user can see, by their user id. */+ devicesByUser: new Map<string, Record<string, unknown>[]>(),+ findAccess: vi.fn(),+ getAgent: vi.fn(),+ notify: vi.fn(),+ statPath: vi.fn(),+ wake: vi.fn(),+ }));+vi.mock('@/database/repositories/channel', async (original) => ({+ ...(await original<object>()),+ ChannelRepository: class {+ addAgent = addAgent;+ findAccess = findAccess;+ },+}));+vi.mock('@/database/repositories/channel/grants', () => ({+ decideDeviceGrant: decide,+ listDeviceGrants: vi.fn(),+}));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ constructor(+ _db: unknown,+ private readonly userId: string,+ ) {}+ findWorkspaceDeviceById = async (deviceId: string) =>+ devicesByUser.get(this.userId)?.find((device) => device.deviceId === deviceId);+ },+}));+vi.mock('@/server/services/agent', () => ({+ AgentService: class {+ getAgentConfigById = getAgent;+ },+}));+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { queryDeviceSystemInfo: vi.fn(), statPath },+}));+vi.mock('@/server/services/file', () => ({ FileService: class {} }));+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));+vi.mock('./notify', () => ({ notifyChannel: notify }));+vi.mock('./queue', () => ({ wakeChannel: wake }));++/** The Agent row lookup `workspaceChannelDevice` makes for the Agent's owner. */+const dbWithAgentOwner = (ownerId: string) =>+ ({+ select: () => ({+ from: () => ({ where: () => ({ limit: async () => [{ userId: ownerId }] }) }),+ }),+ }) as never;++const device = (deviceId: string, userId: string, visibility: 'private' | 'public') => ({+ deviceId,+ platform: 'darwin',+ userId,+ visibility,+});++describe('picking a workspace device for a Channel Agent', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ devicesByUser.clear();+ findAccess.mockResolvedValue({ channel: {}, member: { role: 'admin' } });+ getAgent.mockResolvedValue({ agencyConfig: { heterogeneousProvider: { type: 'codex' } } });+ statPath.mockResolvedValue({ canonicalPath: '/repo', isDirectory: true });+ addAgent.mockImplementation(async (_channelId, input) => input);+ });+ const add = (callerId: string, agentOwnerId: string, deviceId: string) =>+ new ChannelService(dbWithAgentOwner(agentOwnerId), callerId, 'ws').addAgent('chn_1', {+ agentId: 'agent-1',+ deviceId,+ workingDirectory: '/repo',+ });++ it('accepts a device shared with the workspace, owned by whoever enrolled it', async () => {+ devicesByUser.set('arvin', [device('shared', 'canis', 'public')]);+ await expect(add('arvin', 'canis', 'shared')).resolves.toMatchObject({+ config: { deviceId: 'shared', deviceOwnerId: 'canis', workingDirectory: '/repo' },+ });+ });++ it("accepts the caller's own private device", async () => {+ devicesByUser.set('canis', [device('mine', 'canis', 'private')]);+ await expect(add('canis', 'canis', 'mine')).resolves.toMatchObject({+ config: { deviceId: 'mine', deviceOwnerId: 'canis' },+ });+ });++ it("accepts the Agent owner's private device, for them to approve", async () => {+ devicesByUser.set('canis', [device('canis-mac', 'canis', 'private')]);+ await expect(add('arvin', 'canis', 'canis-mac')).resolves.toMatchObject({+ config: { deviceId: 'canis-mac', deviceOwnerId: 'canis' },+ });+ });++ it("refuses another member's private device the Agent does not belong to", async () => {+ devicesByUser.set('mia', [device('mia-mac', 'mia', 'private')]);+ await expect(add('arvin', 'canis', 'mia-mac')).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(addAgent).not.toHaveBeenCalled();+ });+});++describe('deciding a device grant', () => {+ beforeEach(() => vi.resetAllMocks());++ it('lets a reply waiting on the decision start right away', async () => {+ decide.mockResolvedValue({ channelId: 'chn_1', status: 'approved' });+ await new ChannelService({} as never, 'canis', 'ws').decideDeviceGrant('grant-1', 'approve');+ expect(decide).toHaveBeenCalledWith({}, 'canis', 'grant-1', 'approve');+ expect(wake).toHaveBeenCalledWith('chn_1');+ expect(notify).toHaveBeenCalledWith({}, 'chn_1');+ });+});diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 9d58a4088b6..84b2e392ea5 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -25,6 +25,8 @@ import type {ChannelStopScope,} from '@/database/repositories/channel';import { ChannelError, ChannelRepository } from '@/database/repositories/channel';+import type { ChannelDeviceGrantDecision } from '@/database/repositories/channel/grants';+import { decideDeviceGrant, listDeviceGrants } from '@/database/repositories/channel/grants';import { findProjectMainChannelId } from '@/database/repositories/channel/projectMainChannel';import {findShareVisitorTopic,@@ -32,7 +34,7 @@ import {listShareVisitorTopics,readShareVisitorChannel,} from '@/database/repositories/channel/shareVisitors';-import { users } from '@/database/schemas';+import { agents, users } from '@/database/schemas';import { AgentService } from '@/server/services/agent';import { deviceGateway } from '@/server/services/deviceGateway';import { FileService } from '@/server/services/file';@@ -99,9 +101,9 @@ export class ChannelService {throw new ChannelError('BAD_REQUEST', 'A remote Agent runs on its own host, not a device');if (input.deviceId) {const device = this.workspaceId- ? await this.deviceModel.findWorkspaceDeviceById(input.deviceId)+ ? await this.workspaceChannelDevice(input.agentId, input.deviceId): await this.deviceModel.findPersonalByDeviceId(input.deviceId);- if (!device || (this.workspaceId && device.visibility !== 'public'))+ if (!device)throw new ChannelError('FORBIDDEN','Choose an accessible device shared with this workspace',@@ -153,6 +155,29 @@ export class ChannelService {return { agentId: input.agentId, config, description: input.description, name: input.name };}+ /**+ * A workspace device an Agent member may be pointed at in a Channel: one shared with the+ * workspace, one of the caller's own private devices, or a private device of the Agent's own+ * owner. A private device runs there only once its owner approves the Channel grant (see+ * `syncMemberGrant`); picking their own device is that approval.+ */+ private async workspaceChannelDevice(agentId: string, deviceId: string) {+ const visible = await this.deviceModel.findWorkspaceDeviceById(deviceId);+ if (visible) return visible;+ const [owner] = await this.db+ .select({ userId: agents.userId })+ .from(agents)+ .where(eq(agents.id, agentId))+ .limit(1);+ if (!owner?.userId) return;+ const device = await new DeviceModel(+ this.db,+ owner.userId,+ this.workspaceId,+ ).findWorkspaceDeviceById(deviceId);+ return device?.userId === owner.userId ? device : undefined;+ }+/*** A project Channel seats only the project's own Agents. With `joinProject`, an Agent from* outside joins the project first, which takes the right to manage the project's members;@@ -412,6 +437,16 @@ export class ChannelService {return member;};+ /** Requests to run Agents on the caller's private devices in this workspace's Channels. */+ deviceGrants = () => listDeviceGrants(this.db, this.userId, this.workspaceId ?? null);++ /** The device owner approves, rejects or revokes; a reply waiting on it can start at once. */+ decideDeviceGrant = async (grantId: string, decision: ChannelDeviceGrantDecision) => {+ const grant = await decideDeviceGrant(this.db, this.userId, grantId, decision);+ await Promise.all([wakeChannel(grant.channelId), this.changed(grant.channelId)]);+ return grant;+ };+rename = async (channelId: string, title: string) => {const channel = await this.repository.rename(channelId, title);await this.changed(channelId);diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.mdindex 85cfb91b6d5..39612ea4d73 100644--- a/packages/database/src/repositories/channel/README.md+++ b/packages/database/src/repositories/channel/README.md@@ -64,6 +64,16 @@ nullable reference exists for deletion history, not for creating an unbound Agenmember's `config` contains only the Channel device, device owner and working directory. Its nameand description are Channel routing/execution labels; message author names come from the actual sender.+In a workspace Channel, an Agent member may run on a device that is not shared with the workspace+only under a `channel_member_grants` row for exactly its device, owner and directory+(`grants.ts`). Writing the environment (`addAgent`, `updateAgentEnvironment`) keeps the row in+step: the device owner picking their own device approves it at once; anyone else's pick (only the+Agent owner's private devices are offered to them) waits as `pending`. Saving the same environment+keeps the decision; any other environment replaces it. A claim that finds no row (the device was+made private after it was picked) files a pending request for the waiting requester. The device+owner lists requests with `listDeviceGrants` and approves, rejects or revokes with+`decideDeviceGrant`, which refuses a grant whose environment has since moved.+Every claim rechecks the actual requester's Agent access and reads the Agent's current settings.Configuration uses the same merge function as AgentService: system defaults, server defaults,personal defaults (personal scope only), then the Agent. Workers must supply trusteddiff --git a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts b/packages/database/src/repositories/channel/__tests__/claimGuards.test.tsindex adca2deaed6..84ff53ca489 100644--- a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts+++ b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts@@ -78,7 +78,7 @@ describe('claim guards', () => {});it('requires an approved grant that matches the device, directory and owner', async () => {- const { asOwner, channel, member } = await fixture.createTeamChannel();+ const { asOwner, channel } = await fixture.createTeamChannel();// A private device owned by the member, not shared with the workspace.await db.insert(devices)@@ -88,29 +88,28 @@ describe('claim guards', () => {'Coder',deviceConfig('/repo', 'device-2', fixture.memberId),);- const grant = {- channelId: channel.id,- deviceId: 'device-2',- deviceOwnerId: fixture.memberId,- memberId: agent.id,- requestedByMemberId: member.id,- status: 'approved' as const,- workingDirectory: '/elsewhere',- };const first = await request(asOwner, channel.id, agent.id, 'first');- // No grant at all fails closed.+ // Adding the Agent asked the device owner; until they approve, the reply waits.+ const [grant] = await db+ .select()+ .from(channelMemberGrants)+ .where(eq(channelMemberGrants.memberId, agent.id));+ expect(grant).toMatchObject({ deviceOwnerId: fixture.memberId, status: 'pending' });expect(await execution.claim(channel.id, first.job.id, lease)).toBeNull();expect(await jobById(first.job.id)).toMatchObject({ blockedCode: 'device_approval_pending' });// An approval for another directory does not count.- const [mismatched] = await db.insert(channelMemberGrants).values(grant).returning();+ await db+ .update(channelMemberGrants)+ .set({ status: 'approved', workingDirectory: '/elsewhere' })+ .where(eq(channelMemberGrants.id, grant.id));expect(await execution.claim(channel.id, first.job.id, lease)).toBeNull();await db.update(channelMemberGrants).set({ workingDirectory: '/repo' })- .where(eq(channelMemberGrants.id, mismatched.id));+ .where(eq(channelMemberGrants.id, grant.id));await answer(channel.id, first.job.id);// The grant goes with the owner's account; the device stays locked to this channel.diff --git a/packages/database/src/repositories/channel/__tests__/grants.test.ts b/packages/database/src/repositories/channel/__tests__/grants.test.tsnew file mode 100644index 00000000000..76671863800--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/grants.test.ts@@ -0,0 +1,237 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { channelJobs, channelMemberGrants, channelMembers, devices } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ChannelExecutionRepository, ChannelRepository } from '..';+import { decideDeviceGrant, listDeviceGrants } from '../grants';+import { createChannelFixture, deviceConfig, jobsOf, lease } from './testUtils';++const db: LobeChatDatabase = await getTestDB();+const fixture = createChannelFixture(db, 'channel-device-grants');+const execution = new ChannelExecutionRepository(db);++beforeEach(async () => {+ await fixture.setup();+ // The member's own workspace device, kept private.+ await db.insert(devices).values({+ deviceId: 'private-1',+ friendlyName: 'Mia MacBook',+ identitySource: 'fallback',+ userId: fixture.memberId,+ visibility: 'private',+ workspaceId: fixture.workspaceId,+ });+});+afterEach(fixture.cleanup);++const grantOf = async (memberId: string) => {+ const [grant] = await db+ .select()+ .from(channelMemberGrants)+ .where(eq(channelMemberGrants.memberId, memberId));+ return grant;+};++const request = async (+ model: ChannelRepository,+ channelId: string,+ agentId: string,+ key: string,+) => {+ const message = await model.send(channelId, {+ content: key,+ mentions: [agentId],+ requestKey: key,+ routing: 'decision',+ });+ const [job] = await jobsOf(db, message.id);+ return job;+};++const blockedCode = async (jobId: string) => {+ const [job] = await db.select().from(channelJobs).where(eq(channelJobs.id, jobId));+ return job.blockedCode;+};++describe('channel device grants', () => {+ it('asks the device owner, and runs once they approve', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(+ channel.id,+ 'Coder',+ deviceConfig('/repo', 'private-1', fixture.memberId),+ );+ const grant = await grantOf(agent.id);+ expect(grant).toMatchObject({ deviceOwnerId: fixture.memberId, status: 'pending' });++ // The owner sees the request, with who asked and where.+ expect(await listDeviceGrants(db, fixture.memberId, fixture.workspaceId)).toMatchObject([+ {+ agentName: 'Coder',+ channelTitle: 'Team',+ deviceName: 'Mia MacBook',+ id: grant.id,+ requesterName: 'Olivia Owner',+ status: 'pending',+ workingDirectory: '/repo',+ },+ ]);+ expect(await listDeviceGrants(db, fixture.ownerId, fixture.workspaceId)).toEqual([]);++ // Every member sees the Agent waits on the owner; the owner is offered the decision.+ const { members } = await asOwner.detail(channel.id);+ expect(members.find((m) => m.id === agent.id)?.environment?.grant).toEqual({+ deviceOwnerId: fixture.memberId,+ id: grant.id,+ status: 'pending',+ });++ const job = await request(asOwner, channel.id, agent.id, 'first');+ expect(await execution.claim(channel.id, job.id, lease)).toBeNull();+ expect(await blockedCode(job.id)).toBe('device_approval_pending');++ // Only the device owner may decide.+ await expect(decideDeviceGrant(db, fixture.ownerId, grant.id, 'approve')).rejects.toMatchObject(+ { code: 'NOT_FOUND' },+ );+ await decideDeviceGrant(db, fixture.memberId, grant.id, 'approve');+ expect(await execution.claim(channel.id, job.id, lease)).not.toBeNull();+ });++ it('blocks again once the owner revokes, and refuses a rejected request', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(+ channel.id,+ 'Coder',+ deviceConfig('/repo', 'private-1', fixture.memberId),+ );+ const grant = await grantOf(agent.id);++ await decideDeviceGrant(db, fixture.memberId, grant.id, 'reject');+ const rejected = await request(asOwner, channel.id, agent.id, 'rejected');+ expect(await execution.claim(channel.id, rejected.id, lease)).toBeNull();+ expect(await blockedCode(rejected.id)).toBe('unavailable');+ // A rejected request drops off the owner's list, and cannot be revoked.+ expect(await listDeviceGrants(db, fixture.memberId, fixture.workspaceId)).toEqual([]);+ await expect(decideDeviceGrant(db, fixture.memberId, grant.id, 'revoke')).rejects.toMatchObject(+ { code: 'CONFLICT' },+ );++ // The owner changes their mind, then takes it back.+ await decideDeviceGrant(db, fixture.memberId, grant.id, 'approve');+ const revoked = await decideDeviceGrant(db, fixture.memberId, grant.id, 'revoke');+ expect(revoked).toMatchObject({ revokeReason: 'revoked_by_owner', status: 'revoked' });+ });++ it('approves at once when the device owner picks their own device', async () => {+ const { channel, member } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(channel.id, 'Coder');+ // Environments are an admin's to change.+ await db.update(channelMembers).set({ role: 'admin' }).where(eq(channelMembers.id, member.id));+ const asDeviceOwner = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);++ await asDeviceOwner.updateAgentEnvironment(channel.id, agent.id, {+ deviceId: 'private-1',+ deviceOwnerId: fixture.memberId,+ workingDirectory: '/repo',+ });+ expect(await grantOf(agent.id)).toMatchObject({ status: 'approved' });+ });++ it('keeps a decision for the same environment and asks again for a new one', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(+ channel.id,+ 'Coder',+ deviceConfig('/repo', 'private-1', fixture.memberId),+ );+ const grant = await grantOf(agent.id);+ await decideDeviceGrant(db, fixture.memberId, grant.id, 'approve');++ const environment = {+ deviceId: 'private-1',+ deviceOwnerId: fixture.memberId,+ workingDirectory: '/repo',+ };+ await asOwner.updateAgentEnvironment(channel.id, agent.id, environment);+ expect(await grantOf(agent.id)).toMatchObject({ id: grant.id, status: 'approved' });++ await asOwner.updateAgentEnvironment(channel.id, agent.id, {+ ...environment,+ workingDirectory: '/other',+ });+ expect(await grantOf(agent.id)).toMatchObject({+ status: 'pending',+ workingDirectory: '/other',+ });++ // A stale grant cannot be approved into effect once the Agent moved off the device.+ const stale = await grantOf(agent.id);+ await asOwner.updateAgentEnvironment(channel.id, agent.id, {+ deviceId: 'device-1',+ workingDirectory: '/repo',+ });+ expect(await grantOf(agent.id)).toBeUndefined();+ await expect(+ decideDeviceGrant(db, fixture.memberId, stale.id, 'approve'),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('never lets the owner approve an environment that changed under the request', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(+ channel.id,+ 'Coder',+ deviceConfig('/repo', 'private-1', fixture.memberId),+ );+ const pending = await grantOf(agent.id);+ expect(pending).toMatchObject({ status: 'pending', workingDirectory: '/repo' });++ // An admin moves the member to another directory on the same device before the owner answers.+ await asOwner.updateAgentEnvironment(channel.id, agent.id, {+ deviceId: 'private-1',+ deviceOwnerId: fixture.memberId,+ workingDirectory: '/elsewhere',+ });++ const rotated = await grantOf(agent.id);+ expect(rotated).toMatchObject({ status: 'pending', workingDirectory: '/elsewhere' });+ expect(rotated.id).not.toBe(pending.id);++ // The request the owner was looking at cannot be approved into effect for the new directory.+ await expect(+ decideDeviceGrant(db, fixture.memberId, pending.id, 'approve'),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ // Only the environment they are shown now can be decided.+ expect((await decideDeviceGrant(db, fixture.memberId, rotated.id, 'approve')).status).toBe(+ 'approved',+ );+ });++ it('asks the owner when a device turns private after it was picked', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ await db.update(devices).set({ visibility: 'public' }).where(eq(devices.deviceId, 'private-1'));+ const agent = await fixture.addAgent(+ channel.id,+ 'Coder',+ deviceConfig('/repo', 'private-1', fixture.memberId),+ );+ expect(await grantOf(agent.id)).toBeUndefined();++ await db+ .update(devices)+ .set({ visibility: 'private' })+ .where(eq(devices.deviceId, 'private-1'));+ const job = await request(asOwner, channel.id, agent.id, 'after-private');+ expect(await execution.claim(channel.id, job.id, lease)).toBeNull();+ expect(await blockedCode(job.id)).toBe('device_approval_pending');+ expect(await grantOf(agent.id)).toMatchObject({+ deviceOwnerId: fixture.memberId,+ status: 'pending',+ });+ });+});diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.tsindex 74f334afafb..b84aa59b301 100644--- a/packages/database/src/repositories/channel/agent.ts+++ b/packages/database/src/repositories/channel/agent.ts@@ -21,6 +21,7 @@ import { agentShareAdmits } from '../../utils/agentShareAdmits';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';import { notTrashed } from '../../utils/softDelete';import { ChannelError } from './error';+import { syncMemberGrant } from './grants';/*** Whether a direct conversation is with an Agent reached through its share: someone else's Agent@@ -292,6 +293,7 @@ export const addAgentMember = async (name: input.name?.trim() || agentDisplayName(agent, 'Agent'),}).returning();+ await syncMemberGrant(tx, channel, member, inviter);return member;};diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex ee80009cee6..f2993cef184 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -16,6 +16,7 @@ import type { Transaction } from '../../type';import { createNanoId } from '../../utils/idGenerator';import { resolveExecutionConfig } from './agent';import { AWAITING_PRIMARY_REASON, findThread } from './delivery';+import { requestMissingGrant } from './grants';import { buildManifest } from './manifest';import type { ChannelTopicScope } from './topic';import { continuationTopic, resolveTopic } from './topic';@@ -123,6 +124,7 @@ const deviceBlock = async (tx: Transaction,channel: ChannelItem,member: ChannelMemberItem,+ job: Pick<ChannelJobItem, 'requesterMemberId'>,): Promise<Block | undefined> => {const { deviceId, deviceOwnerId, workingDirectory } = member.config ?? {};if (workingDirectory && !deviceId)@@ -152,6 +154,11 @@ const deviceBlock = async (.select().from(channelMemberGrants).where(eq(channelMemberGrants.memberId, member.id));+ // Picked while the device was public, then made private: ask its owner now.+ if (!grant) {+ await requestMissingGrant(tx, channel, member, job.requesterMemberId);+ return APPROVAL_PENDING;+ }if (!grant ||grant.deviceId !== deviceId ||@@ -417,7 +424,7 @@ export const claimJob = async (}const blocked =- (await deviceBlock(tx, channel, member)) ??+ (await deviceBlock(tx, channel, member, job)) ??(await directoryBlock(tx, member.config.deviceId, executionConfig.workingDirectory));if (blocked) {await block(tx, job, blocked.code, blocked.reason);diff --git a/packages/database/src/repositories/channel/grants.ts b/packages/database/src/repositories/channel/grants.tsnew file mode 100644index 00000000000..7275b640648--- /dev/null+++ b/packages/database/src/repositories/channel/grants.ts@@ -0,0 +1,256 @@+import type { ChannelMemberGrantStatus } from '@lobechat/types';+import { and, desc, eq, inArray, sql } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import type { ChannelItem, ChannelMemberItem } from '../../schemas';+import { channelMemberGrants, channelMembers, channels, devices, users } from '../../schemas';+import type { LobeChatDatabase, Transaction } from '../../type';+import { notTrashed } from '../../utils/softDelete';+import { ChannelError } from './error';+import { audit, lockChannel } from './transaction';++/**+ * Whether a member's Channel device needs its owner's approval, by the rule `deviceBlock` applies:+ * in a workspace Channel, any device not shared with the workspace. A personal Channel runs only+ * on its owner's own devices and has no grants.+ */+const needsGrant = async (+ tx: Transaction,+ channel: Pick<ChannelItem, 'workspaceId'>,+ deviceId: string,+) => {+ if (!channel.workspaceId) return false;+ const [shared] = await tx+ .select({ id: devices.id })+ .from(devices)+ .where(+ and(+ eq(devices.deviceId, deviceId),+ eq(devices.workspaceId, channel.workspaceId),+ eq(devices.visibility, 'public'),+ ),+ )+ .limit(1);+ return !shared;+};++/**+ * Keeps a member's grant in step with the environment just written to it, inside the same+ * channel lock. A private device gets a grant for exactly its device, owner and directory: approved+ * at once when the device owner picked it themselves, else pending until they decide. The same+ * environment saved again keeps its grant and decision; any other environment replaces it with a+ * fresh grant, so neither the approval nor the request ID carries over to somewhere else.+ */+export const syncMemberGrant = async (+ tx: Transaction,+ channel: Pick<ChannelItem, 'id' | 'workspaceId'>,+ member: Pick<ChannelMemberItem, 'config' | 'id'>,+ requester: Pick<ChannelMemberItem, 'id' | 'userId'>,+) => {+ const { deviceId, deviceOwnerId, workingDirectory } = member.config ?? {};+ const required = !!deviceId && (await needsGrant(tx, channel, deviceId));+ const [current] = await tx+ .select()+ .from(channelMemberGrants)+ .where(eq(channelMemberGrants.memberId, member.id));++ if (!required || !deviceId || !deviceOwnerId || !workingDirectory) {+ if (current) await tx.delete(channelMemberGrants).where(eq(channelMemberGrants.id, current.id));+ return;+ }+ if (+ current &&+ current.deviceId === deviceId &&+ current.deviceOwnerId === deviceOwnerId &&+ current.workingDirectory === workingDirectory+ )+ return current;++ // The grant is the device owner's answer to one environment, and the ID is what they answer+ // about. Replacing the row instead of updating it in place keeps that true: a request the owner+ // was looking at cannot be approved into effect for a directory or device that arrived after+ // they saw it, because the old ID no longer exists.+ if (current) await tx.delete(channelMemberGrants).where(eq(channelMemberGrants.id, current.id));++ const approved = requester.userId === deviceOwnerId;+ const now = new Date();+ const [grant] = await tx+ .insert(channelMemberGrants)+ .values({+ channelId: channel.id,+ decidedAt: approved ? now : null,+ deviceId,+ deviceOwnerId,+ memberId: member.id,+ requestedByMemberId: requester.id,+ revokeReason: null,+ revokedAt: null,+ status: (approved ? 'approved' : 'pending') as ChannelMemberGrantStatus,+ workingDirectory,+ })+ .returning();+ await audit(tx, channel.id, approved ? 'grant_approved' : 'grant_requested', grant.id);+ return grant;+};++/**+ * A pending request for a member whose device became private after it was picked: the claim found+ * no grant, so the device owner is asked on behalf of the person whose reply is waiting.+ */+export const requestMissingGrant = async (+ tx: Transaction,+ channel: Pick<ChannelItem, 'id'>,+ member: Pick<ChannelMemberItem, 'config' | 'id'>,+ requesterMemberId: string,+) => {+ const { deviceId, deviceOwnerId, workingDirectory } = member.config ?? {};+ if (!deviceId || !deviceOwnerId || !workingDirectory) return;+ // A deleted owner took their grants with them; nobody is left to ask.+ const [owner] = await tx+ .select({ id: users.id })+ .from(users)+ .where(eq(users.id, deviceOwnerId))+ .limit(1);+ if (!owner) return;+ const [grant] = await tx+ .insert(channelMemberGrants)+ .values({+ channelId: channel.id,+ deviceId,+ deviceOwnerId,+ memberId: member.id,+ requestedByMemberId: requesterMemberId,+ workingDirectory,+ })+ .onConflictDoNothing({ target: channelMemberGrants.memberId })+ .returning();+ if (grant) await audit(tx, channel.id, 'grant_requested', grant.id);+};++export type ChannelDeviceGrantDecision = 'approve' | 'reject' | 'revoke';++const NEXT_STATUS: Record<+ ChannelDeviceGrantDecision,+ { from: ChannelMemberGrantStatus[]; to: ChannelMemberGrantStatus }+> = {+ approve: { from: ['pending', 'rejected', 'revoked'], to: 'approved' },+ reject: { from: ['pending'], to: 'rejected' },+ revoke: { from: ['approved'], to: 'revoked' },+};++/**+ * The device owner's decision on one grant. Only the owner recorded on the grant may decide, and+ * only while the member still runs on exactly that device and directory: a grant for an+ * environment that has since moved is stale and cannot be approved into effect.+ */+export const decideDeviceGrant = async (+ db: LobeChatDatabase,+ userId: string,+ grantId: string,+ decision: ChannelDeviceGrantDecision,+) => {+ const [found] = await db+ .select({ channelId: channelMemberGrants.channelId })+ .from(channelMemberGrants)+ .where(eq(channelMemberGrants.id, grantId));+ if (!found) throw new ChannelError('NOT_FOUND', 'Device request not found');++ return db.transaction(async (tx) => {+ await lockChannel(tx, found.channelId);+ const [grant] = await tx+ .select()+ .from(channelMemberGrants)+ .where(eq(channelMemberGrants.id, grantId));+ if (!grant || grant.deviceOwnerId !== userId)+ throw new ChannelError('NOT_FOUND', 'Device request not found');++ const [member] = await tx+ .select({ config: channelMembers.config, status: channelMembers.status })+ .from(channelMembers)+ .where(eq(channelMembers.id, grant.memberId));+ const { deviceId, deviceOwnerId, workingDirectory } = member?.config ?? {};+ if (+ member?.status !== 'active' ||+ deviceId !== grant.deviceId ||+ deviceOwnerId !== grant.deviceOwnerId ||+ workingDirectory !== grant.workingDirectory+ )+ throw new ChannelError('CONFLICT', 'The Agent no longer runs on this device and directory');++ const { from, to } = NEXT_STATUS[decision];+ if (!from.includes(grant.status))+ throw new ChannelError('CONFLICT', `A ${grant.status} request cannot be changed that way`);++ const now = new Date();+ const [updated] = await tx+ .update(channelMemberGrants)+ .set({+ decidedAt: now,+ revokeReason: to === 'revoked' ? 'revoked_by_owner' : null,+ revokedAt: to === 'revoked' ? now : null,+ status: to,+ updatedAt: now,+ })+ .where(eq(channelMemberGrants.id, grantId))+ .returning();+ await audit(tx, grant.channelId, `grant_${to}`, grant.id);+ return updated;+ });+};++const requesters = alias(channelMembers, 'grant_requesters');+const requesterUsers = alias(users, 'grant_requester_users');++/**+ * Grants on the caller's devices in one scope, for the device owner to decide: pending requests+ * first, then what they have approved, newest first. Rejected and revoked ones drop off; asking+ * again (saving the environment anew) brings a request back.+ */+export const listDeviceGrants = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | null,+) => {+ if (!workspaceId) return [];+ const rows = await db+ .select({+ agentId: channelMembers.agentId,+ agentName: channelMembers.name,+ channelId: channelMemberGrants.channelId,+ channelTitle: channels.title,+ createdAt: channelMemberGrants.createdAt,+ decidedAt: channelMemberGrants.decidedAt,+ deviceId: channelMemberGrants.deviceId,+ deviceName: sql<+ string | null+ >`coalesce(nullif(${devices.friendlyName}, ''), ${devices.hostname})`,+ id: channelMemberGrants.id,+ memberId: channelMemberGrants.memberId,+ requesterName: sql<+ string | null+ >`coalesce(${requesterUsers.fullName}, ${requesterUsers.username})`,+ requesterUserId: requesters.userId,+ status: channelMemberGrants.status,+ workingDirectory: channelMemberGrants.workingDirectory,+ })+ .from(channelMemberGrants)+ .innerJoin(channels, eq(channels.id, channelMemberGrants.channelId))+ .innerJoin(channelMembers, eq(channelMembers.id, channelMemberGrants.memberId))+ .leftJoin(requesters, eq(requesters.id, channelMemberGrants.requestedByMemberId))+ .leftJoin(requesterUsers, eq(requesterUsers.id, requesters.userId))+ .leftJoin(+ devices,+ and(eq(devices.deviceId, channelMemberGrants.deviceId), eq(devices.workspaceId, workspaceId)),+ )+ .where(+ and(+ eq(channelMemberGrants.deviceOwnerId, userId),+ eq(channels.workspaceId, workspaceId),+ notTrashed(channels.isDeleted),+ eq(channelMembers.status, 'active'),+ inArray(channelMemberGrants.status, ['pending', 'approved']),+ ),+ )+ .orderBy(desc(channelMemberGrants.createdAt));+ return rows.sort((a, b) => Number(b.status === 'pending') - Number(a.status === 'pending'));+};diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 12ec364b33f..6f1e6aa43fb 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -43,6 +43,7 @@ import { deleteMessage } from './delete';import { findThread } from './delivery';import { editMessage } from './edit';import { ChannelError } from './error';+import { syncMemberGrant } from './grants';import { channelLastMessages } from './lastMessage';import { leaveChannel, removeChannelMember } from './membership';import { setMemberMuted } from './mute';@@ -290,7 +291,7 @@ export class ChannelRepository {) =>this.write(channelId,- async (tx) => {+ async (tx, access) => {const current = await requireAgentMember(tx, channelId, memberId);const [member] = await tx.update(channelMembers)@@ -305,6 +306,7 @@ export class ChannelRepository {.where(eq(channelMembers.id, memberId)).returning();await audit(tx, channelId, 'member_environment_changed', memberId);+ await syncMemberGrant(tx, access.channel, member, access.member);return member;},{ minRole: 'admin' },diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex ff594fc4380..8c0738a4909 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -32,6 +32,7 @@ import {agentOperations,agents,channelJobs,+ channelMemberGrants,channelMembers,channelMessages,channels,@@ -542,6 +543,11 @@ export const readChannelView = async (deviceId: sql<string | null>`${channelMembers.config}->>'deviceId'`,deviceOwnerId: sql<string | null>`${channelMembers.config}->>'deviceOwnerId'`,workingDirectory: sql<string | null>`${channelMembers.config}->>'workingDirectory'`,+ grantDeviceId: channelMemberGrants.deviceId,+ grantDeviceOwnerId: channelMemberGrants.deviceOwnerId,+ grantId: channelMemberGrants.id,+ grantStatus: channelMemberGrants.status,+ grantWorkingDirectory: channelMemberGrants.workingDirectory,agencyConfig: agents.agencyConfig,agentUserId: agents.userId,agentVisibility: agents.visibility,@@ -550,6 +556,7 @@ export const readChannelView = async (.from(channelMembers).leftJoin(users, eq(users.id, channelMembers.userId)).leftJoin(agents, eq(agents.id, channelMembers.agentId))+ .leftJoin(channelMemberGrants, eq(channelMemberGrants.memberId, channelMembers.id)).where(eq(channelMembers.channelId, channelId)).orderBy(asc(channelMembers.createdAt)),tx@@ -690,11 +697,27 @@ export const readChannelView = async (agentVisibility: _agentVisibility,agentWorkspaceId: _agentWorkspaceId,deviceId,- deviceOwnerId: _deviceOwnerId,+ deviceOwnerId,+ grantDeviceId,+ grantDeviceOwnerId,+ grantId,+ grantStatus,+ grantWorkingDirectory,inheritedConfig,workingDirectory: channelDirectory,...member} = row;+ // Only a grant for exactly the Channel's current pick speaks for it; a stale one is moot.+ const grant =+ grantId &&+ grantStatus &&+ grantDeviceOwnerId &&+ !inheritedConfig &&+ grantDeviceId === deviceId &&+ grantDeviceOwnerId === deviceOwnerId &&+ grantWorkingDirectory === channelDirectory+ ? { deviceOwnerId: grantDeviceOwnerId, id: grantId, status: grantStatus }+ : null;const device = deviceInfos.get(row);// An inherited device works in the Agent's own folder there, else the device's default.const workingDirectory =@@ -705,7 +728,12 @@ export const readChannelView = async (...member,environment:member.agentId && (deviceId || workingDirectory)- ? { deviceId, deviceName: device?.name ?? null, workingDirectory }+ ? {+ deviceId,+ deviceName: device?.name ?? null,+ ...(grant ? { grant } : {}),+ workingDirectory,+ }: null,};}),diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 8639246f908..8f36151657f 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -805,9 +805,40 @@ export interface ChannelMemberEnvironmentPreview {deviceId: string | null;/** The device's friendly name, else its hostname; null when the device row is gone. */deviceName: string | null;+ /**+ * The device owner's approval for a private workspace device picked in this Channel;+ * absent when the device needs none (public, personal, or the Agent's own setting).+ */+ grant?: ChannelMemberDeviceGrant;workingDirectory: string | null;}+/** One Agent member's grant on someone's private device, as members of the Channel see it. */+export interface ChannelMemberDeviceGrant {+ /** Who decides it; the client offers approve / reject / revoke to this person only. */+ deviceOwnerId: string;+ id: string;+ status: ChannelMemberGrantStatus;+}++/** A request on one of the caller's private devices, as the device owner reviews it. */+export interface ChannelDeviceGrantItem {+ agentId: string | null;+ agentName: string | null;+ channelId: string;+ channelTitle: string;+ createdAt: Date;+ decidedAt: Date | null;+ deviceId: string;+ deviceName: string | null;+ id: string;+ memberId: string;+ requesterName: string | null;+ requesterUserId: string | null;+ status: ChannelMemberGrantStatus;+ workingDirectory: string;+}+export interface ChannelPublicMember {actorType: ChannelMemberActorType;agentId: string | null;