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.

🐛 fix(channel): show share visitors the Works their reply created (#23642)

YuTengjingb2ee8d5761cc
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 4fba41671a9..ffd45870813 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -248,6 +248,11 @@ export const channelRouter = router({
z.object({
before: z.number().int().positive().optional(),
channelId,
+ /**
+ * The client renders the opt-in Work types (files, collections) on reply cards. Released
+ * desktop clients without them omit it and keep receiving only the types they know.
+ */
+ includeFileWorks: z.boolean().optional(),
limit: z.number().int().min(1).max(100).optional(),
threadId: threadId.nullish(),
}),
diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.ts
index 68e24e272ef..210167cbf7b 100644
--- a/packages/database/src/models/message/visitor.ts
+++ b/packages/database/src/models/message/visitor.ts
@@ -288,7 +288,7 @@ const sanitizeVisitorMetadata = (
* The identity keys are omitted rather than nulled (`userId` is non-nullable on
* `WorkItem`); no visitor-facing Work surface reads them.
*/
-const sanitizeVisitorWorks = (
+export const sanitizeVisitorWorks = (
works: WorkSummaryItem[] | undefined,
): WorkSummaryItem[] | undefined =>
works?.map((work) => {
diff --git a/packages/database/src/repositories/channel/__tests__/replyWorksShared.test.ts b/packages/database/src/repositories/channel/__tests__/replyWorksShared.test.ts
new file mode 100644
index 00000000000..6614ff13b3f
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/replyWorksShared.test.ts
@@ -0,0 +1,176 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, agentShares, userContacts, works, workVersions } from '../../../schemas';
+import type { Transaction } from '../../../type';
+import { ChannelExecutionRepository, ChannelRepository } from '..';
+import { readChannelView } from '../view';
+import { tableContacts } from './tableContacts';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-reply-works-shared', tableContacts);
+const execution = new ChannelExecutionRepository(db);
+
+// The fixture's member is the visitor; its owner shares an Agent.
+const visitorId = fixture.memberId;
+const ownerId = fixture.ownerId;
+const agentId = 'agt_channel_reply_works_shared';
+const visitor = new ChannelRepository(db, visitorId, undefined, tableContacts);
+
+let shareId: string;
+
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(agents).values({ id: agentId, title: 'Shared Helper', userId: ownerId });
+ const [share] = await db
+ .insert(agentShares)
+ .values({ agentId, shareConfig: { monthlySpendLimit: 1 }, visibility: 'link' })
+ .returning();
+ shareId = share.id;
+});
+
+afterEach(async () => {
+ await db.delete(userContacts);
+ await fixture.cleanup();
+});
+
+/** The visitor asks the shared Agent, whose run (as the owner) publishes a reply. */
+const sharedReply = async () => {
+ const { channel } = await visitor.create({ agentId, sharedAgent: true, title: 'Shared Helper' });
+ const message = await visitor.send(channel.id, {
+ content: 'Collect the images',
+ requestKey: 'collect',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+ await execution.accepted(channel.id, job.id);
+ await execution.saveDraft(channel.id, job.id, 'Collected them');
+ await execution.publish(channel.id, job.id);
+ await execution.releaseWriter(channel.id, job.id);
+ const replyOf = (view: Awaited<ReturnType<typeof visitor.detail>>) =>
+ view.messages.find((entry) => entry.routingStatus === 'reply')!;
+ return {
+ channelId: channel.id,
+ operationId: claim.job.operationId!,
+ replyOf,
+ topicId: claim.topic.id,
+ };
+};
+
+/** A Work the share run registered: owned by the Agent's owner, stamped with the visitor scope. */
+const addShareWork = async (params: {
+ operationId: string;
+ topicId: string;
+ type: 'collection' | 'document' | 'external';
+ visitorUserId?: string;
+}) => {
+ const collection = params.type === 'collection';
+ const [work] = await db
+ .insert(works)
+ .values({
+ metadata: {
+ agentEditable: true,
+ agentShare: {
+ shareId,
+ topicId: params.topicId,
+ visitorUserId: params.visitorUserId ?? visitorId,
+ },
+ } as typeof works.$inferInsert.metadata,
+ resourceId: `${params.type}:${Math.random()}`,
+ resourceType: (
+ { collection: 'collection', document: 'document', external: 'github_pull_request' } as const
+ )[params.type],
+ title: collection ? 'Sketches' : 'Show works in channels',
+ toolIdentifier: 'lobe-work',
+ toolName: 'createWork',
+ type: params.type,
+ url: collection ? '/f/file_cover' : 'https://github.com/lobehub/lobehub/pull/1',
+ userId: ownerId,
+ visibility: 'private',
+ })
+ .returning();
+ const [version] = await db
+ .insert(workVersions)
+ .values({
+ changeType: 'created',
+ cumulativeCost: 0.3,
+ metadata: collection
+ ? { collection: { items: [{ fileId: 'file_cover', url: '/f/file_cover' }] } }
+ : null,
+ rootOperationId: params.operationId,
+ toolIdentifier: 'lobe-work',
+ toolName: 'createWork',
+ version: 1,
+ workId: work.id,
+ })
+ .returning();
+ await db.update(works).set({ currentVersionId: version.id }).where(eq(works.id, work.id));
+ return work;
+};
+
+describe('Channel reply works of a shared Agent', () => {
+ it('shows the visitor the Works their run registered as the owner, without the owner', async () => {
+ const state = await sharedReply();
+ const collection = await addShareWork({ ...state, type: 'collection' });
+ await addShareWork({ ...state, type: 'external' });
+ // A document only opens through the owner's Work, so the reply draws no dead card for it.
+ await addShareWork({ ...state, type: 'document' });
+
+ const cards = state.replyOf(
+ await visitor.detail(state.channelId, { includeFileWorks: true }),
+ ).works!;
+
+ expect(cards.map((card) => card.type).sort()).toEqual(['collection', 'external']);
+ expect(cards.find((card) => card.type === 'collection')).toMatchObject({
+ event: {
+ cumulativeCost: null,
+ metadata: { collection: { items: [{ fileId: 'file_cover' }] } },
+ },
+ id: collection.id,
+ title: 'Sketches',
+ totalCost: null,
+ });
+ const payload = JSON.stringify(cards);
+ expect(payload).not.toContain(ownerId);
+ expect(payload).not.toContain('"userId"');
+ });
+
+ it('keeps opt-in types from clients that did not ask for them', async () => {
+ const state = await sharedReply();
+ await addShareWork({ ...state, type: 'collection' });
+ await addShareWork({ ...state, type: 'external' });
+
+ const cards = state.replyOf(await visitor.detail(state.channelId)).works!;
+ expect(cards.map((card) => card.type)).toEqual(['external']);
+ });
+
+ it('keeps Works of another visitor scope out', async () => {
+ const state = await sharedReply();
+ await addShareWork({ ...state, type: 'collection', visitorUserId: ownerId });
+
+ const reply = state.replyOf(await visitor.detail(state.channelId, { includeFileWorks: true }));
+ expect(reply.works).toEqual([]);
+ });
+
+ it('shows anyone else reading the conversation only the external Works, without their ids', async () => {
+ const state = await sharedReply();
+ await addShareWork({ ...state, type: 'collection' });
+ const external = await addShareWork({ ...state, type: 'external' });
+
+ const view = await readChannelView(
+ db as unknown as Transaction,
+ state.channelId,
+ { includeFileWorks: true },
+ ownerId,
+ );
+ const cards = view.messages.find((entry) => entry.routingStatus === 'reply')!.works;
+ expect(cards).toEqual([
+ expect.objectContaining({ id: 'https://github.com/lobehub/lobehub/pull/1', userId: '' }),
+ ]);
+ expect(JSON.stringify(cards)).not.toContain(external.id);
+ });
+});
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 93106ce41f1..7ed5ed3634d 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -52,7 +52,7 @@ import { fileIdsByMessage } from './attachments';
import { isAgentAuthored } from './author';
import { activeMembers } from './delivery';
import { ChannelError } from './error';
-import { externalWorksByMessage } from './works';
+import { replyWorksByMessage } from './works';
export const publicMessageColumns = {
...getTableColumns(channelMessages),
@@ -567,7 +567,13 @@ export const viewerJobs = (
export const readChannelView = async (
tx: Transaction,
channelId: string,
- options: { before?: number; limit?: number; threadId?: string | null } = {},
+ options: {
+ before?: number;
+ /** The client renders the opt-in Work types on reply cards; see `replyWorksByMessage`. */
+ includeFileWorks?: boolean;
+ limit?: number;
+ threadId?: string | null;
+ } = {},
viewerUserId?: string,
) => {
const limit = Math.max(1, Math.min(options.limit ?? 100, 100));
@@ -734,7 +740,10 @@ export const readChannelView = async (
);
const [sourceTopics, works, relayAvatars] = await Promise.all([
sourceTopicsByMessage(tx, channelId, replyIds, viewerUserId),
- externalWorksByMessage(tx, channelId, replyIds),
+ replyWorksByMessage(tx, channelId, replyIds, {
+ includeFileWorks: options.includeFileWorks,
+ userId: viewerUserId,
+ }),
relayAgentAvatars(tx, [...page, ...(rootMessage ? [rootMessage] : [])]),
]);
const ids = [...new Set([...files.values()].flat())];
diff --git a/packages/database/src/repositories/channel/works.ts b/packages/database/src/repositories/channel/works.ts
index 1f3d696bd66..6ce9ed1ed90 100644
--- a/packages/database/src/repositories/channel/works.ts
+++ b/packages/database/src/repositories/channel/works.ts
@@ -1,7 +1,13 @@
-import type { ExternalWorkSummaryItem, WorkSummaryItem } from '@lobechat/types';
-import { and, eq, inArray, isNotNull } from 'drizzle-orm';
+import type {
+ ChannelSharedAgentAccess,
+ ExternalWorkSummaryItem,
+ WorkSummaryItem,
+} from '@lobechat/types';
+import { agentShareWorkAccessScope } from '@lobechat/types';
+import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm';
import pMap from 'p-map';
+import { sanitizeVisitorWorks } from '../../models/message/visitor';
import { WorkModel } from '../../models/work';
import { channelJobs, channelMembers, channels } from '../../schemas';
import type { Transaction } from '../../type';
@@ -9,6 +15,14 @@ import type { Transaction } from '../../type';
const isLinkedExternalWork = (item: WorkSummaryItem): item is ExternalWorkSummaryItem =>
item.type === 'external' && !!item.url;
+/**
+ * The Works a Channel reply card can open for a shared Agent's visitor: a link, a file by its
+ * public `/f/:id` URL, and a collection from the images its summary carries. Documents, canvases
+ * and tasks only open through the owner's Work, so they stay out instead of drawing dead cards.
+ */
+const isVisitorOpenableWork = (item: WorkSummaryItem) =>
+ isLinkedExternalWork(item) || item.type === 'file' || item.type === 'collection';
+
/**
* A summary as other members see it: what the card draws, without the ids that tie it to the
* requester's Work, conversation and run. The URL keys the card in place of the Work id.
@@ -26,21 +40,35 @@ const publicSummary = (item: ExternalWorkSummaryItem): ExternalWorkSummaryItem =
workspaceId: null,
});
+export interface ReplyWorksViewer {
+ /** The client renders the opt-in Work types (`file`, `collection`, ...); see `OPT_IN_WORK_TYPES`. */
+ includeFileWorks?: boolean;
+ userId?: string;
+}
+
/**
- * The external Works (GitHub, Linear, ...) each published reply's run touched, as the work cards
- * the requester's own conversation shows under that run: the same
- * `WorkModel.listSummariesByRootOperations` read, as the requester, keyed by the job's operation.
+ * The Works each published reply's run touched, as the work cards the requester's own
+ * conversation shows under that run: the same `WorkModel.listSummariesByRootOperations` read,
+ * under the identity and scope the run registered them with, keyed by the job's operation.
+ *
+ * Every member sees the external Works (GitHub, Linear, ...): a reply already shows what it did,
+ * and these resources live outside LobeHub behind their own URL. Internal Works (documents,
+ * canvases, files, collections, tasks) stay off the card, as do the ids that link a card to the
+ * requester's Work, topic and run.
*
- * Every member sees them: a reply already shows what it did, and these resources live outside
- * LobeHub behind their own URL. Internal Works (documents, canvases, files, tasks) stay with the
- * requester, as do the ids that link a card to the requester's Work, topic and run.
+ * A shared Agent's run executes as the Agent's owner and stamps its Works with the visitor's share
+ * scope, so they are read as the owner under that scope. The visitor who asked also sees the files
+ * and collections, with the owner's identity and spend removed as on the share page; anyone else
+ * reading the conversation (its owner, through visitor-conversation access) gets the external
+ * ones only.
*/
-export const externalWorksByMessage = async (
+export const replyWorksByMessage = async (
tx: Transaction,
channelId: string,
messageIds: string[],
-): Promise<Map<string, ExternalWorkSummaryItem[]>> => {
- const result = new Map<string, ExternalWorkSummaryItem[]>();
+ viewer: ReplyWorksViewer = {},
+): Promise<Map<string, WorkSummaryItem[]>> => {
+ const result = new Map<string, WorkSummaryItem[]>();
if (!messageIds.length) return result;
const jobs = await tx
@@ -48,6 +76,8 @@ export const externalWorksByMessage = async (
messageId: channelJobs.publishedMessageId,
operationId: channelJobs.operationId,
requesterUserId: channelMembers.userId,
+ share: sql<ChannelSharedAgentAccess | null>`${channelJobs.executionConfig}->'share'`,
+ topicId: channelJobs.topicId,
workspaceId: channels.workspaceId,
})
.from(channelJobs)
@@ -69,24 +99,57 @@ export const externalWorksByMessage = async (
);
if (!jobs.length) return result;
- // The run is the requester's, so its Works are read the way their own conversation reads them.
- const byRequester = new Map<string, typeof jobs>();
- for (const job of jobs)
- byRequester.set(job.requesterUserId!, [...(byRequester.get(job.requesterUserId!) ?? []), job]);
+ // One read per identity and scope the runs registered their Works under.
+ const readers = new Map<
+ string,
+ { jobs: typeof jobs; model: WorkModel; visitorSeesOwn: boolean }
+ >();
+ for (const job of jobs) {
+ const requesterUserId = job.requesterUserId!;
+ const { share } = job;
+ // A share run's Works are fenced to its visitor topic; without one there is nothing to read.
+ if (share && !job.topicId) continue;
+ const key = share
+ ? `share:${share.shareId}:${job.topicId}:${requesterUserId}`
+ : `user:${requesterUserId}`;
+ const reader =
+ readers.get(key) ??
+ (share
+ ? {
+ jobs: [],
+ model: new WorkModel(
+ tx,
+ share.ownerId,
+ share.workspaceId ?? undefined,
+ agentShareWorkAccessScope({
+ shareId: share.shareId,
+ topicId: job.topicId!,
+ visitorUserId: requesterUserId,
+ }),
+ ),
+ visitorSeesOwn: viewer.userId === requesterUserId,
+ }
+ : {
+ jobs: [],
+ model: new WorkModel(tx, requesterUserId, job.workspaceId ?? undefined),
+ visitorSeesOwn: false,
+ });
+ reader.jobs.push(job);
+ readers.set(key, reader);
+ }
+
await pMap(
- [...byRequester],
- async ([userId, requesterJobs]) => {
- const summaries = await new WorkModel(
- tx,
- userId,
- requesterJobs[0].workspaceId ?? undefined,
- ).listSummariesByRootOperations({
- rootOperationIds: requesterJobs.map((job) => job.operationId!),
+ [...readers.values()],
+ async ({ jobs: readerJobs, model, visitorSeesOwn }) => {
+ const summaries = await model.listSummariesByRootOperations({
+ includeFileWorks: visitorSeesOwn && viewer.includeFileWorks,
+ rootOperationIds: readerJobs.map((job) => job.operationId!),
});
- for (const job of requesterJobs) {
- const cards = (summaries[job.operationId!] ?? [])
- .filter(isLinkedExternalWork)
- .map(publicSummary);
+ for (const job of readerJobs) {
+ const runWorks = summaries[job.operationId!] ?? [];
+ const cards = visitorSeesOwn
+ ? (sanitizeVisitorWorks(runWorks.filter(isVisitorOpenableWork)) ?? [])
+ : runWorks.filter(isLinkedExternalWork).map(publicSummary);
if (cards.length) result.set(job.messageId!, cards);
}
},
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 2e8c0b63c0d..8ccc6bd4817 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -6,7 +6,7 @@ import {
import type { ContactCard, ContactCardType, ContactUserProfile } from './contact';
import { getWorkingDirEffectivePath } from './device';
import type { BotWakeKind } from './signal';
-import type { ExternalWorkSummaryItem } from './work';
+import type { WorkSummaryItem } from './work';
/**
* Channel: a shared conversation where people and Agents talk together.
@@ -974,10 +974,12 @@ export interface ChannelPublicMessage {
/** The Agent that relayed this request (or answered it, on a receipt); null otherwise. */
via?: (ChannelMessageVia & { avatar: string | null }) | null;
/**
- * External Works a reply's run touched: the conversation's work summaries, for every member,
- * without the ids that link them to the requester's Work, topic and run. Empty on requests.
+ * Works a reply's run touched, as the conversation's work summaries. Every member gets the
+ * external ones, without the ids that link them to the requester's Work, topic and run. A shared
+ * Agent's visitor also gets the internal Works of their own runs (collections, files, ...), with
+ * the Agent owner's identity and spend removed. Empty on requests.
*/
- works?: ExternalWorkSummaryItem[];
+ works?: WorkSummaryItem[];
}
export interface ChannelPublicJob {
diff --git a/src/features/Channels/ReplyWorks.tsx b/src/features/Channels/ReplyWorks.tsx
index dd937651db8..bbe3157ad0a 100644
--- a/src/features/Channels/ReplyWorks.tsx
+++ b/src/features/Channels/ReplyWorks.tsx
@@ -1,14 +1,42 @@
import type { WorkSummaryItem } from '@lobechat/types';
+import { openCollectionModal } from '@/features/CollectionModal/loader';
import { MessageWorkList } from '@/features/Conversation/Messages/MessageWorks';
-import { isSafeExternalUrl } from '@/features/Work/descriptors';
+import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
-/** A channel has no Working Sidebar or chat portal: a card just opens its link. */
-const openLink = (item: WorkSummaryItem) => {
- if (isSafeExternalUrl(item.url)) window.open(item.url, '_blank', 'noopener,noreferrer');
+/**
+ * A channel has no Working Sidebar or chat portal, and a shared Agent's visitor cannot read the
+ * owner's Work: a link opens in a new tab, a file from its URL (`/f/:id` is public by id), and a
+ * collection in the image modal from the images its summary row carries. The server sends no other
+ * Work type to a Channel (`replyWorksByMessage`).
+ */
+export const openReplyWork = (item: WorkSummaryItem, appOrigin: string) => {
+ const target = getWorkTypeDescriptor(item).getOpenTarget(item);
+ switch (target?.kind) {
+ case 'external': {
+ if (isSafeExternalUrl(target.url)) window.open(target.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ case 'filePreview': {
+ const url = isSafeExternalUrl(target.url)
+ ? target.url
+ : `${appOrigin}/f/${encodeURIComponent(target.fileId)}`;
+ window.open(url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ case 'collection': {
+ if (target.items) void openCollectionModal({ items: target.items, title: target.title });
+ return;
+ }
+ default: {
+ return;
+ }
+ }
};
-/** The external Works an Agent reply's run touched, as the conversation shows them. */
-export const ReplyWorks = ({ works }: { works: WorkSummaryItem[] }) => (
- <MessageWorkList items={works} onOpen={openLink} />
-);
+/** The Works an Agent reply's run touched, as the conversation shows them. */
+export const ReplyWorks = ({ works }: { works: WorkSummaryItem[] }) => {
+ const appOrigin = useAppOrigin();
+ return <MessageWorkList items={works} onOpen={(item) => openReplyWork(item, appOrigin)} />;
+};
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 60b39adea70..f4f0721336c 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -99,7 +99,8 @@ class ChannelService {
shareVisitorTopic = async (topicId: string) =>
(await lambdaClient.channel.shareVisitorTopic.query({ topicId })).data;
detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>
- (await lambdaClient.channel.detail.query(params)).data;
+ // `ReplyWorks` renders the opt-in Work types (files, collections).
+ (await lambdaClient.channel.detail.query({ ...params, includeFileWorks: true })).data;
list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;
markRead = (channelId: string, sequence: number) =>
lambdaClient.channel.markRead.mutate({ channelId, sequence });