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(channel): ask the device owner in their conversation with the Agent (#23656)

Arvin Xub03764a3fe9a
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index 3a68317f3e4..ce37d4d6b4f 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -33,6 +33,7 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { reportAgentExchange } from './agentExchange';
import { resolveChannelAttachments } from './attachments';
import { ChannelRoutingService } from './ChannelRoutingService';
+import { announceDeviceGrants } from './deviceGrantCard';
import { notifyChannelMentions } from './mention';
import { notifyChannel } from './notify';
import { registerLocalChannelAdvance, wakeChannel } from './queue';
@@ -266,6 +267,8 @@ export class ChannelCoordinator {
} finally {
if (pending.length) await notifyChannel(this.db, channelId);
}
+ // A claim that found the device made private since it was picked files a request; ask now.
+ if (pending.length) await announceDeviceGrants(this.db, channelId);
};
/**
diff --git a/apps/server/src/services/channel/ChannelService.environment.test.ts b/apps/server/src/services/channel/ChannelService.environment.test.ts
index 52d2ac44a8f..58a4b59b326 100644
--- a/apps/server/src/services/channel/ChannelService.environment.test.ts
+++ b/apps/server/src/services/channel/ChannelService.environment.test.ts
@@ -48,6 +48,10 @@ vi.mock('@/server/services/deviceGateway', () => ({
vi.mock('@/server/services/file', () => ({ FileService: class {} }));
vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
vi.mock('./notify', () => ({ notifyChannel: notify }));
+vi.mock('./deviceGrantCard', () => ({
+ announceDeviceGrants: vi.fn(),
+ refreshDeviceGrantCard: vi.fn(),
+}));
vi.mock('./queue', () => ({ wakeChannel: wake }));
describe('changing an Agent member’s channel environment', () => {
@@ -163,6 +167,7 @@ describe('changing an Agent member’s channel environment', () => {
it('creates a member in the device home folder when the Agent has no directory there', async () => {
querySystemInfo.mockResolvedValue({ homePath: '/Users/me' });
statPath.mockResolvedValue({ canonicalPath: '/Users/me', isDirectory: true });
+ create.mockResolvedValue({ channel: { id: 'channel-1' } });
await service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' });
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 4c333abfeb4..8e3bf36c927 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -41,6 +41,7 @@ import { FileService } from '@/server/services/file';
import { ChannelCoordinator } from './ChannelCoordinator';
import { channelContacts } from './contacts';
+import { announceDeviceGrants, refreshDeviceGrantCard } from './deviceGrantCard';
import { notifyChannelDirectMessages } from './directMessage';
import { notifyChannelMentions } from './mention';
import { notifyChannel } from './notify';
@@ -237,6 +238,7 @@ export class ChannelService {
});
// Invited people see the new Channel without waiting for their next poll.
if (userIds.length) await this.changed(access.channel.id);
+ await announceDeviceGrants(this.db, access.channel.id);
return access;
};
@@ -274,6 +276,7 @@ export class ChannelService {
});
// Invitees see the new group without waiting for their next poll.
await this.changed(access.channel.id);
+ await announceDeviceGrants(this.db, access.channel.id);
return access;
};
@@ -419,7 +422,7 @@ export class ChannelService {
);
}
const member = await this.repository.addAgent(channelId, agent);
- await this.changed(channelId);
+ await Promise.all([this.changed(channelId), announceDeviceGrants(this.db, channelId)]);
return member;
};
@@ -433,7 +436,11 @@ export class ChannelService {
const { config = {} } = await this.resolveAgent({ ...input, agentId });
const member = await this.repository.updateAgentEnvironment(channelId, memberId, config);
// A job blocked on the previous device or directory may be claimable now.
- await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
+ await Promise.all([
+ wakeChannel(channelId),
+ this.changed(channelId),
+ announceDeviceGrants(this.db, channelId),
+ ]);
return member;
};
@@ -443,7 +450,11 @@ export class ChannelService {
/** 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)]);
+ await Promise.all([
+ wakeChannel(grant.channelId),
+ this.changed(grant.channelId),
+ refreshDeviceGrantCard(this.db, grant),
+ ]);
return grant;
};
diff --git a/apps/server/src/services/channel/deviceGrantCard.db.test.ts b/apps/server/src/services/channel/deviceGrantCard.db.test.ts
new file mode 100644
index 00000000000..99e01d632a5
--- /dev/null
+++ b/apps/server/src/services/channel/deviceGrantCard.db.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelRepository } from '@/database/repositories/channel';
+import {
+ createChannelFixture,
+ deviceConfig,
+} from '@/database/repositories/channel/__tests__/testUtils';
+import {
+ channelMemberGrants,
+ channelMessages,
+ channels,
+ devices,
+ workspaceMembers,
+} from '@/database/schemas';
+
+import { ChannelService } from './ChannelService';
+import { announceDeviceGrants } from './deviceGrantCard';
+import { notifyChannel } from './notify';
+
+vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./mention', () => ({ notifyChannelMentions: vi.fn() }));
+vi.mock('./routingConfig', () => ({ resolveChannelRoutingConfig: vi.fn() }));
+vi.mock('./featureGate', () => ({ assertChannelEnabled: vi.fn() }));
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-device-grant-card');
+beforeEach(async () => {
+ vi.mocked(notifyChannel).mockClear();
+ await fixture.setup();
+ await db.insert(workspaceMembers).values([
+ { role: 'owner', userId: fixture.ownerId, workspaceId: fixture.workspaceId },
+ { role: 'member', userId: fixture.memberId, workspaceId: fixture.workspaceId },
+ ]);
+ // 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 cardsIn = (channelId: string) =>
+ db.select().from(channelMessages).where(eq(channelMessages.channelId, channelId));
+
+/** The owner points the Agent at the member's private device; the member has a conversation with it. */
+const setup = async () => {
+ const { channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(
+ channel.id,
+ 'Coder',
+ deviceConfig('/repo', 'private-1', fixture.memberId),
+ );
+ const [grant] = await db
+ .select()
+ .from(channelMemberGrants)
+ .where(eq(channelMemberGrants.memberId, agent.id));
+ const asMember = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const direct = await asMember.create({
+ agentConfig: {},
+ agentId: agent.agentId!,
+ title: 'Coder',
+ });
+ return { agent, channel, direct: direct.channel, grant };
+};
+
+describe('device request cards', () => {
+ it('asks the device owner once, as the Agent, in their conversation with it', async () => {
+ const { agent, channel, direct, grant } = await setup();
+
+ await announceDeviceGrants(db, channel.id);
+ await announceDeviceGrants(db, channel.id);
+
+ const cards = await cardsIn(direct.id);
+ expect(cards).toEqual([
+ expect.objectContaining({
+ agentId: agent.agentId,
+ content:
+ '[Device request] Olivia Owner asks to run Coder in "Team" on Mia MacBook (/repo).',
+ metadata: {
+ deviceGrant: {
+ agentName: 'Coder',
+ channelId: channel.id,
+ channelTitle: 'Team',
+ deviceId: 'private-1',
+ deviceName: 'Mia MacBook',
+ grantId: grant.id,
+ requesterName: 'Olivia Owner',
+ requesterUserId: fixture.ownerId,
+ workingDirectory: '/repo',
+ },
+ },
+ userId: null,
+ }),
+ ]);
+ expect(vi.mocked(notifyChannel).mock.calls.filter(([, id]) => id === direct.id)).toHaveLength(
+ 1,
+ );
+
+ const { messages } = await new ChannelRepository(
+ db,
+ fixture.memberId,
+ fixture.workspaceId,
+ ).detail(direct.id);
+ expect(messages[0].deviceGrant).toMatchObject({ grantId: grant.id, status: 'pending' });
+ });
+
+ it('refreshes the card when the owner decides, and asks no one about a decided request', async () => {
+ const { channel, direct, grant } = await setup();
+ await announceDeviceGrants(db, channel.id);
+ vi.mocked(notifyChannel).mockClear();
+
+ await new ChannelService(db, fixture.memberId, fixture.workspaceId).decideDeviceGrant(
+ grant.id,
+ 'approve',
+ );
+ expect(vi.mocked(notifyChannel).mock.calls.map(([, id]) => id)).toContain(direct.id);
+
+ await db.delete(channelMessages).where(eq(channelMessages.channelId, direct.id));
+ await announceDeviceGrants(db, channel.id);
+ expect(await cardsIn(direct.id)).toEqual([]);
+ });
+
+ it('leaves it to the Channel and settings when the owner trashed the conversation', async () => {
+ const { channel, direct } = await setup();
+ await db.update(channels).set({ isDeleted: true }).where(eq(channels.id, direct.id));
+
+ await expect(announceDeviceGrants(db, channel.id)).resolves.toBeUndefined();
+ expect(await cardsIn(direct.id)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/channel/deviceGrantCard.ts b/apps/server/src/services/channel/deviceGrantCard.ts
new file mode 100644
index 00000000000..e482accd495
--- /dev/null
+++ b/apps/server/src/services/channel/deviceGrantCard.ts
@@ -0,0 +1,143 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ChannelDeviceGrantRequest } from '@lobechat/types';
+import { deviceGrantRequestText } from '@lobechat/types';
+import { and, eq, sql } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+import pMap from 'p-map';
+
+import { ChannelRepository } from '@/database/repositories/channel';
+import {
+ channelMemberGrants,
+ channelMembers,
+ channelMessages,
+ channels,
+ devices,
+ users,
+} from '@/database/schemas';
+
+import { ChannelService } from './ChannelService';
+import { notifyChannel } from './notify';
+
+/** Request key of a grant's card in its device owner's direct conversation. */
+export const deviceGrantCardKey = (grantId: string) => `device-grant:${grantId}`;
+
+const requesters = alias(channelMembers, 'card_requesters');
+const requesterUsers = alias(users, 'card_requester_users');
+
+/** Pending requests in one Channel, with what their cards are written from. */
+const pendingRequests = (db: LobeChatDatabase, channelId: string) =>
+ db
+ .select({
+ agentId: channelMembers.agentId,
+ agentName: channelMembers.name,
+ channelId: channelMemberGrants.channelId,
+ channelTitle: channels.title,
+ deviceId: channelMemberGrants.deviceId,
+ deviceName: sql<
+ string | null
+ >`coalesce(nullif(${devices.friendlyName}, ''), ${devices.hostname})`,
+ deviceOwnerId: channelMemberGrants.deviceOwnerId,
+ grantId: channelMemberGrants.id,
+ memberId: channelMemberGrants.memberId,
+ requesterName: sql<
+ string | null
+ >`coalesce(${requesterUsers.fullName}, ${requesterUsers.username})`,
+ requesterUserId: requesters.userId,
+ workingDirectory: channelMemberGrants.workingDirectory,
+ workspaceId: channels.workspaceId,
+ })
+ .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, channels.workspaceId),
+ ),
+ )
+ .where(
+ and(
+ // Filters on the member, whose Channel is indexed; the grant joins by its unique member.
+ eq(channelMembers.channelId, channelId),
+ eq(channelMemberGrants.status, 'pending'),
+ eq(channelMembers.status, 'active'),
+ ),
+ );
+
+type CardGrant = { deviceOwnerId: string; id: string; memberId: string };
+
+/** The device owner's direct conversations with the member's Agent that hold this grant's card. */
+const cardChannels = (db: LobeChatDatabase, grant: CardGrant) =>
+ db
+ .select({ channelId: channelMessages.channelId })
+ .from(channelMembers)
+ .innerJoin(
+ channels,
+ and(eq(channels.agentId, channelMembers.agentId), eq(channels.userId, grant.deviceOwnerId)),
+ )
+ .innerJoin(
+ channelMessages,
+ and(
+ eq(channelMessages.channelId, channels.id),
+ eq(channelMessages.requestKey, deviceGrantCardKey(grant.id)),
+ ),
+ )
+ .where(eq(channelMembers.id, grant.memberId));
+
+/**
+ * Asks each device owner with a pending request in this Channel, as the Agent that would run
+ * there: one card per request in the owner's direct conversation with that Agent, which they
+ * approve or reject in place. Idempotent per request, so callers run it after anything that may
+ * file one. Best-effort: an owner who cannot open a conversation with the Agent (no access, or
+ * moved it to the trash) still decides in the Channel or in device settings.
+ */
+export const announceDeviceGrants = async (db: LobeChatDatabase, channelId: string) => {
+ try {
+ const rows = await pendingRequests(db, channelId);
+ for (const { agentId, deviceOwnerId, memberId, workspaceId, ...request } of rows) {
+ if (!agentId) continue;
+ try {
+ const grant = { deviceOwnerId, id: request.grantId, memberId };
+ if ((await cardChannels(db, grant)).length) continue;
+ const scope = workspaceId ?? undefined;
+ const direct = await new ChannelService(db, deviceOwnerId, scope).openDirect(agentId);
+ if (!direct) continue;
+ const card: ChannelDeviceGrantRequest = request;
+ await new ChannelRepository(db, deviceOwnerId, scope).postAgentMessage(direct.channel.id, {
+ agentId,
+ content: deviceGrantRequestText(card),
+ metadata: { deviceGrant: card },
+ requestKey: deviceGrantCardKey(request.grantId),
+ });
+ await notifyChannel(db, direct.channel.id);
+ } catch (error) {
+ console.error('[channel] Failed to post a device request card', {
+ channelId,
+ error,
+ grantId: request.grantId,
+ });
+ }
+ }
+ } catch (error) {
+ console.error('[channel] Failed to read device requests', { channelId, error });
+ }
+};
+
+/**
+ * Refreshes the device owner's conversations holding this grant's card, so its status follows a
+ * decision made anywhere: on the card, in the Channel, or in device settings.
+ */
+export const refreshDeviceGrantCard = async (db: LobeChatDatabase, grant: CardGrant) => {
+ try {
+ const cards = await cardChannels(db, grant);
+ await pMap(cards, (card) => notifyChannel(db, card.channelId), { concurrency: 5 });
+ } catch (error) {
+ console.error('[channel] Failed to refresh a device request card', {
+ error,
+ grantId: grant.id,
+ });
+ }
+};
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index c32268a121d..da59429e86f 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -72,7 +72,10 @@ Agent owner's private devices are offered to them) waits as `pending`. Saving th
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.
+`decideDeviceGrant`, which refuses a grant whose environment has since moved. The server also asks
+them as the Agent (`announceDeviceGrants` in the channel services): a card in their direct
+conversation with it, `metadata.deviceGrant` under request key `device-grant:<grantId>`. The view
+adds the grant's live status for the device owner, `expired` once the grant is gone.
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,
diff --git a/packages/database/src/repositories/channel/__tests__/grants.test.ts b/packages/database/src/repositories/channel/__tests__/grants.test.ts
index 76671863800..8b4e8deb83b 100644
--- a/packages/database/src/repositories/channel/__tests__/grants.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/grants.test.ts
@@ -234,4 +234,54 @@ describe('channel device grants', () => {
status: 'pending',
});
});
+
+ it("shows a request card's current status to its device owner only", async () => {
+ const { asMember, 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);
+ const card = await asOwner.postAgentMessage(channel.id, {
+ agentId: agent.agentId!,
+ content: '[Device request]',
+ metadata: {
+ deviceGrant: {
+ agentName: 'Coder',
+ channelId: channel.id,
+ channelTitle: 'Team',
+ deviceId: 'private-1',
+ deviceName: 'Mia MacBook',
+ grantId: grant.id,
+ requesterName: 'Olivia Owner',
+ requesterUserId: fixture.ownerId,
+ workingDirectory: '/repo',
+ },
+ },
+ requestKey: `device-grant:${grant.id}`,
+ });
+ const cardFor = async (model: ChannelRepository) =>
+ (await model.detail(channel.id)).messages.find((message) => message.id === card.id)
+ ?.deviceGrant;
+
+ expect(await cardFor(asMember)).toMatchObject({
+ deviceName: 'Mia MacBook',
+ grantId: grant.id,
+ status: 'pending',
+ });
+ // Someone else's request is no card of theirs.
+ expect(await cardFor(asOwner)).toBeNull();
+
+ await decideDeviceGrant(db, fixture.memberId, grant.id, 'approve');
+ expect(await cardFor(asMember)).toMatchObject({ status: 'approved' });
+
+ // A new environment replaces the grant; the old card no longer decides anything.
+ await asOwner.updateAgentEnvironment(channel.id, agent.id, {
+ deviceId: 'private-1',
+ deviceOwnerId: fixture.memberId,
+ workingDirectory: '/other',
+ });
+ expect(await cardFor(asMember)).toMatchObject({ status: 'expired' });
+ });
});
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 635f74f4cb1..bffb64b2e47 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -1,6 +1,8 @@
import {
type AgentDeviceOverride,
+ type ChannelDeviceGrantCard,
channelMessageDeletedAt,
+ channelMessageDeviceGrant,
channelMessageEditedAt,
channelMessageReceipt,
channelMessageReplyError,
@@ -204,6 +206,44 @@ const withRelayAvatar = <
};
};
+/**
+ * The current status of the device requests an Agent's cards on this page carry, for the device
+ * owner reading them. A grant that is gone (its environment moved, or the member left) reads as
+ * `expired`; a card the viewer does not own reads as nothing.
+ */
+const deviceGrantCards = async (
+ tx: Transaction,
+ rows: MessageRow[],
+ viewerUserId: string | undefined,
+) => {
+ const requests = rows.flatMap((row) => {
+ const request = isAgentAuthored(row) && channelMessageDeviceGrant(row.metadata);
+ return request ? [[row.id, request] as const] : [];
+ });
+ const cards = new Map<string, ChannelDeviceGrantCard>();
+ if (!viewerUserId || !requests.length) return cards;
+ const found = await tx
+ .select({
+ deviceOwnerId: channelMemberGrants.deviceOwnerId,
+ id: channelMemberGrants.id,
+ status: channelMemberGrants.status,
+ })
+ .from(channelMemberGrants)
+ .where(
+ inArray(
+ channelMemberGrants.id,
+ requests.map(([, request]) => request.grantId),
+ ),
+ );
+ const grants = new Map(found.map((grant) => [grant.id, grant]));
+ for (const [messageId, request] of requests) {
+ const grant = grants.get(request.grantId);
+ if (grant && grant.deviceOwnerId !== viewerUserId) continue;
+ cards.set(messageId, { ...request, status: grant?.status ?? 'expired' });
+ }
+ return cards;
+};
+
/** Public projection only. Execution settings, drafts and internal messages never leave this boundary. */
/**
* The Agent topic behind each published reply, for replies the viewer ran: the topic belongs to
@@ -737,13 +777,14 @@ export const readChannelView = async (
const replyIds = [...page, ...(rootMessage ? [rootMessage] : [])].flatMap((message) =>
message.routingStatus === 'reply' ? [message.id] : [],
);
- const [sourceTopics, works, relayAvatars] = await Promise.all([
+ const [sourceTopics, works, relayAvatars, grantCards] = await Promise.all([
sourceTopicsByMessage(tx, channelId, replyIds, viewerUserId),
replyWorksByMessage(tx, channelId, replyIds, {
includeFileWorks: options.includeFileWorks,
userId: viewerUserId,
}),
relayAgentAvatars(tx, [...page, ...(rootMessage ? [rootMessage] : [])]),
+ deviceGrantCards(tx, [...page, ...(rootMessage ? [rootMessage] : [])], viewerUserId),
]);
const ids = [...new Set([...files.values()].flat())];
const attachments = await channelAttachments(tx, ids);
@@ -818,6 +859,7 @@ export const readChannelView = async (
}),
relayAvatars,
),
+ deviceGrant: grantCards.get(rootMessage.id) ?? null,
sourceTopicId: sourceTopics.get(rootMessage.id)?.id ?? null,
sourceTopicTitle: sourceTopics.get(rootMessage.id)?.title ?? null,
works: works.get(rootMessage.id) ?? [],
@@ -831,6 +873,7 @@ export const readChannelView = async (
}),
relayAvatars,
),
+ deviceGrant: grantCards.get(message.id) ?? null,
sourceTopicId: sourceTopics.get(message.id)?.id ?? null,
sourceTopicTitle: sourceTopics.get(message.id)?.title ?? null,
works: works.get(message.id) ?? [],
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index d61cc6e06d9..3dc69b3ff2f 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -919,6 +919,63 @@ export interface ChannelDeviceGrantItem {
workingDirectory: string;
}
+/**
+ * `metadata.deviceGrant` of the message an Agent posts in its direct conversation with a device
+ * owner when someone asks to run it on their private device in a Channel. Only `grantId` is
+ * authoritative; the rest is the server's snapshot at request time, so the card reads without
+ * the Channel.
+ */
+export interface ChannelDeviceGrantRequest {
+ agentName: string | null;
+ channelId: string;
+ channelTitle: string;
+ deviceId: string;
+ deviceName: string | null;
+ grantId: string;
+ requesterName: string | null;
+ requesterUserId: string | null;
+ workingDirectory: string;
+}
+
+/** A request card as its reader sees it: `expired` once the grant was replaced or removed. */
+export type ChannelDeviceGrantCard = ChannelDeviceGrantRequest & {
+ status: ChannelMemberGrantStatus | 'expired';
+};
+
+/** `metadata.deviceGrant` of a device request card, or undefined for anything else. */
+export const channelMessageDeviceGrant = (
+ metadata: ChannelMessageMetadata | null | undefined,
+): ChannelDeviceGrantRequest | undefined => {
+ const request = metadata?.deviceGrant as Partial<ChannelDeviceGrantRequest> | undefined;
+ return typeof request?.grantId === 'string' &&
+ typeof request.channelId === 'string' &&
+ typeof request.deviceId === 'string' &&
+ typeof request.workingDirectory === 'string'
+ ? {
+ agentName: request.agentName ?? null,
+ channelId: request.channelId,
+ channelTitle: request.channelTitle ?? '',
+ deviceId: request.deviceId,
+ deviceName: request.deviceName ?? null,
+ grantId: request.grantId,
+ requesterName: request.requesterName ?? null,
+ requesterUserId: request.requesterUserId ?? null,
+ workingDirectory: request.workingDirectory,
+ }
+ : undefined;
+};
+
+/**
+ * The stored text of a request card, for every reader that does not render the card: list
+ * previews, notifications and the Agent itself. Clients that render cards localize their own.
+ */
+export const deviceGrantRequestText = (request: ChannelDeviceGrantRequest) =>
+ `[Device request] ${request.requesterName || 'A member'} asks to run ${
+ request.agentName || 'this Agent'
+ } in "${request.channelTitle}" on ${request.deviceName || request.deviceId} (${
+ request.workingDirectory
+ }).`;
+
export interface ChannelPublicMember {
actorType: ChannelMemberActorType;
agentId: string | null;
@@ -958,6 +1015,8 @@ export interface ChannelPublicMessage {
* attachments, so Threads, replies and jobs that point at it still resolve.
*/
deletedAt?: Date | null;
+ /** An Agent's request card for the reader's private device, with the grant's current status. */
+ deviceGrant?: ChannelDeviceGrantCard | null;
/** Set once the author has edited the text; shown as "(edited)". */
editedAt?: Date | null;
fileIds: string[];