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): show a reply's canvas on its card to those who can open it (#23662)

Arvin Xu68994288e770
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index ffd45870813..8cd55eafbe1 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 opens a reply's canvas beside the Channel. Released clients without a canvas
+ * view omit it and keep canvases off the cards.
+ */
+ includeCanvasWorks: z.boolean().optional(),
/**
* 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.
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index 1e503265214..8e933c9ec59 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -19,6 +19,7 @@ import {
type WorkAccessScope,
type WorkItem,
type WorkSkillProvider,
+ type WorkType,
type WorkVisibility,
} from '@lobechat/types';
import debug from 'debug';
@@ -336,6 +337,8 @@ export class WorkModel {
includeFileWorks?: boolean;
limit?: number;
rootOperationIds?: string[] | null;
+ /** See {@link queries.listSummariesByRootOperations}: narrows the types the caller draws. */
+ types?: WorkType[];
}) => queries.listSummariesByRootOperations(this.ctx, params);
listByConversation = (params: {
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index 5bf5c220cce..25fff9b3310 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -175,6 +175,15 @@ export const listSummariesByRootOperations = async (
includeFileWorks?: boolean;
limit?: number;
rootOperationIds?: string[] | null;
+ /**
+ * Narrows the type set to the ones the caller actually draws, on top of the
+ * opt-in gates. A caller that drops a type from the result afterwards (a
+ * Channel card keeps `external` + `canvas`) would otherwise have that type
+ * take a summary slot: opting into canvases also enables `file` and
+ * `collection`, and 20 files saved after the link would push it past `limit`
+ * before the caller filters them out.
+ */
+ types?: WorkType[];
},
): Promise<WorkSummaryMap> => {
const rootOperationIds = Array.from(
@@ -185,6 +194,13 @@ export const listSummariesByRootOperations = async (
);
if (rootOperationIds.length === 0) return result;
+ // Intersect the caller's own types with the opt-in gates: an un-opted-in
+ // request cannot widen its read set by naming a gated type.
+ const allowedTypes = resolveAllowedWorkTypes(params).filter(
+ (type) => !params.types || params.types.includes(type),
+ );
+ if (allowedTypes.length === 0) return result;
+
const limit = params.limit ?? 20;
const rowLimit = Math.min(rootOperationIds.length * limit, MAX_SUMMARY_ROW_LIMIT);
@@ -205,7 +221,7 @@ export const listSummariesByRootOperations = async (
.where(
and(
inArray(workVersions.rootOperationId, rootOperationIds),
- inArray(works.type, resolveAllowedWorkTypes(params)),
+ inArray(works.type, allowedTypes),
),
)
.orderBy(desc(workVersions.createdAt))
diff --git a/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts b/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts
index 0887d96446c..f786ef6b188 100644
--- a/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { WorkModel } from '../../../models/work';
-import { works, workVersions } from '../../../schemas';
+import { works, workspaceMembers, workVersions } from '../../../schemas';
import { ChannelExecutionRepository } from '..';
import { createChannelFixture, jobById, jobsOf, lease } from './testUtils';
@@ -50,8 +50,9 @@ interface WorkFixture {
share?: boolean;
tokens?: number;
trashed?: boolean;
- type?: 'document' | 'external';
+ type?: 'canvas' | 'collection' | 'document' | 'external' | 'file';
url?: string | null;
+ visibility?: 'private' | 'public';
}
const addWork = async ({
@@ -66,6 +67,7 @@ const addWork = async ({
tokens,
type = 'external',
url = 'https://github.com/lobehub/lobehub/pull/1',
+ visibility = 'private',
}: WorkFixture) => {
const [work] = await db
.insert(works)
@@ -88,7 +90,7 @@ const addWork = async ({
type,
url,
userId: ownerId,
- visibility: 'private',
+ visibility,
workspaceId: fixture.workspaceId,
})
.returning();
@@ -228,4 +230,93 @@ describe('Channel reply works', () => {
expect.objectContaining({ url: 'https://github.com/lobehub/lobehub/pull/1' }),
]);
});
+
+ describe('canvases', () => {
+ const addCanvas = (rootOperationId: string, visibility: 'private' | 'public' = 'private') =>
+ addWork({
+ resourceType: 'canvas',
+ rootOperationId,
+ type: 'canvas',
+ url: null,
+ visibility,
+ });
+ const joinWorkspace = (userId: string) =>
+ db
+ .insert(workspaceMembers)
+ .values({ role: 'member', userId, workspaceId: fixture.workspaceId });
+ const cardsOf = async (
+ state: Awaited<ReturnType<typeof publishedReply>>,
+ repo: typeof state.asOwner,
+ includeCanvasWorks = true,
+ ) => {
+ const view = await repo.detail(state.channel.id, { includeCanvasWorks });
+ return view.messages.find((message) => message.routingStatus === 'reply')!.works!;
+ };
+
+ it('shows the requester the canvas their run saved, with what opens it', async () => {
+ const state = await publishedReply();
+ const canvas = await addCanvas(state.operationId);
+
+ expect(await cardsOf(state, state.asMember)).toEqual([
+ expect.objectContaining({ id: canvas.id, resourceId: canvas.resourceId, type: 'canvas' }),
+ ]);
+ });
+
+ it('keeps canvases off the cards of clients that cannot open them', async () => {
+ const state = await publishedReply();
+ await addCanvas(state.operationId, 'public');
+
+ expect(await cardsOf(state, state.asMember, false)).toEqual([]);
+ });
+
+ it('shows workspace members a public canvas, never a private one', async () => {
+ const state = await publishedReply();
+ await addCanvas(state.operationId);
+ expect(await cardsOf(state, state.asOwner)).toEqual([]);
+
+ const shared = await addCanvas(state.operationId, 'public');
+ // Outside the workspace (an external contact) the canvas API cannot read it either.
+ expect(await cardsOf(state, state.asOwner)).toEqual([]);
+
+ await joinWorkspace(fixture.ownerId);
+ expect(await cardsOf(state, state.asOwner)).toEqual([
+ expect.objectContaining({ id: shared.id, type: 'canvas' }),
+ ]);
+ });
+
+ it('keeps the link and the canvas when the run saved many newer files', async () => {
+ const state = await publishedReply();
+ const link = await addWork({
+ at: new Date('2026-11-12T09:00:00Z'),
+ rootOperationId: state.operationId,
+ });
+ const canvas = await addWork({
+ at: new Date('2026-11-12T09:10:00Z'),
+ resourceType: 'canvas',
+ rootOperationId: state.operationId,
+ type: 'canvas',
+ url: null,
+ });
+ // Opting into canvases also enables `file` and `collection`: 25 newer files must not spend
+ // the card's summary slots, or the older link and canvas are dropped before the card is built.
+ for (let index = 0; index < 25; index++) {
+ await addWork({
+ at: new Date(Date.parse('2026-11-12T10:00:00Z') + index * 1000),
+ resourceType: 'file',
+ rootOperationId: state.operationId,
+ type: 'file',
+ url: null,
+ });
+ }
+
+ const cards = await cardsOf(state, state.asMember);
+ expect(cards.map((card) => card.type).sort()).toEqual(['canvas', 'external']);
+ expect(cards).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: canvas.id, type: 'canvas' }),
+ expect.objectContaining({ id: link.url, type: 'external' }),
+ ]),
+ );
+ });
+ });
});
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index bffb64b2e47..ebf44e315ad 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -608,6 +608,8 @@ export const readChannelView = async (
channelId: string,
options: {
before?: number;
+ /** The client opens canvases from reply cards; see `replyWorksByMessage`. */
+ includeCanvasWorks?: boolean;
/** The client renders the opt-in Work types on reply cards; see `replyWorksByMessage`. */
includeFileWorks?: boolean;
limit?: number;
@@ -780,6 +782,7 @@ export const readChannelView = async (
const [sourceTopics, works, relayAvatars, grantCards] = await Promise.all([
sourceTopicsByMessage(tx, channelId, replyIds, viewerUserId),
replyWorksByMessage(tx, channelId, replyIds, {
+ includeCanvasWorks: options.includeCanvasWorks,
includeFileWorks: options.includeFileWorks,
userId: viewerUserId,
}),
diff --git a/packages/database/src/repositories/channel/works.ts b/packages/database/src/repositories/channel/works.ts
index 6ce9ed1ed90..b3356eac7d2 100644
--- a/packages/database/src/repositories/channel/works.ts
+++ b/packages/database/src/repositories/channel/works.ts
@@ -1,28 +1,43 @@
import type {
+ CanvasWorkSummaryItem,
ChannelSharedAgentAccess,
ExternalWorkSummaryItem,
WorkSummaryItem,
+ WorkType,
} from '@lobechat/types';
import { agentShareWorkAccessScope } from '@lobechat/types';
-import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm';
+import { and, eq, inArray, isNotNull, isNull, 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 { channelJobs, channelMembers, channels, workspaceMembers } from '../../schemas';
import type { Transaction } from '../../type';
const isLinkedExternalWork = (item: WorkSummaryItem): item is ExternalWorkSummaryItem =>
item.type === 'external' && !!item.url;
+const isCanvasWork = (item: WorkSummaryItem): item is CanvasWorkSummaryItem =>
+ item.type === 'canvas' && !!item.resourceId;
+
/**
- * The Works a Channel reply card can open for a shared Agent's visitor: a link, a file by its
+ * The Works a 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';
+/**
+ * The Work types each card actually draws, handed to the summary read so a type that the card
+ * then drops cannot spend one of its `limit` slots. Opting into canvases also enables `file` and
+ * `collection` (see `OPT_IN_WORK_TYPES`), and a run that saved 20 newer files after its link would
+ * otherwise fill the bucket before the cards are filtered, losing the link and the canvas.
+ */
+const MEMBER_CARD_WORK_TYPES: WorkType[] = ['external', 'canvas'];
+const VISITOR_CARD_WORK_TYPES: WorkType[] = ['external', 'file', 'collection'];
+const EXTERNAL_ONLY_CARD_WORK_TYPES: WorkType[] = ['external'];
+
/**
* 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.
@@ -41,6 +56,8 @@ const publicSummary = (item: ExternalWorkSummaryItem): ExternalWorkSummaryItem =
});
export interface ReplyWorksViewer {
+ /** The client opens a canvas beside the Channel; older clients would draw a dead card. */
+ includeCanvasWorks?: boolean;
/** The client renders the opt-in Work types (`file`, `collection`, ...); see `OPT_IN_WORK_TYPES`. */
includeFileWorks?: boolean;
userId?: string;
@@ -52,9 +69,10 @@ export interface ReplyWorksViewer {
* 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.
+ * and these resources live outside LobeHub behind their own URL. A canvas is shown to whoever
+ * can read it through their own canvas API: the requester, and in a workspace the members when
+ * the canvas is not private. Other internal Works (documents, files, collections, tasks) stay
+ * off the card, as do the ids that link an external 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
@@ -99,10 +117,33 @@ export const replyWorksByMessage = async (
);
if (!jobs.length) return result;
+ // A workspace member reads the workspace's public canvases; an external contact does not.
+ const workspaceId = jobs[0].workspaceId;
+ const viewerInWorkspace =
+ !!viewer.includeCanvasWorks &&
+ !!viewer.userId &&
+ !!workspaceId &&
+ (
+ await tx
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, workspaceId),
+ eq(workspaceMembers.userId, viewer.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ .limit(1)
+ ).length > 0;
+ const canOpenCanvas = (item: CanvasWorkSummaryItem, requesterUserId: string) =>
+ !!viewer.includeCanvasWorks &&
+ (viewer.userId === requesterUserId || (viewerInWorkspace && item.visibility !== 'private'));
+
// One read per identity and scope the runs registered their Works under.
const readers = new Map<
string,
- { jobs: typeof jobs; model: WorkModel; visitorSeesOwn: boolean }
+ { jobs: typeof jobs; model: WorkModel; share: boolean; visitorSeesOwn: boolean }
>();
for (const job of jobs) {
const requesterUserId = job.requesterUserId!;
@@ -127,11 +168,13 @@ export const replyWorksByMessage = async (
visitorUserId: requesterUserId,
}),
),
+ share: true,
visitorSeesOwn: viewer.userId === requesterUserId,
}
: {
jobs: [],
model: new WorkModel(tx, requesterUserId, job.workspaceId ?? undefined),
+ share: false,
visitorSeesOwn: false,
});
reader.jobs.push(job);
@@ -140,16 +183,30 @@ export const replyWorksByMessage = async (
await pMap(
[...readers.values()],
- async ({ jobs: readerJobs, model, visitorSeesOwn }) => {
+ async ({ jobs: readerJobs, model, share, visitorSeesOwn }) => {
const summaries = await model.listSummariesByRootOperations({
- includeFileWorks: visitorSeesOwn && viewer.includeFileWorks,
+ // Canvases are an opt-in type; a share run's canvas stays fenced to its visitor topic.
+ includeFileWorks: share
+ ? visitorSeesOwn && viewer.includeFileWorks
+ : viewer.includeCanvasWorks,
rootOperationIds: readerJobs.map((job) => job.operationId!),
+ // Read only what this card can draw, so the types it drops never take a slot.
+ types: share
+ ? visitorSeesOwn
+ ? VISITOR_CARD_WORK_TYPES
+ : EXTERNAL_ONLY_CARD_WORK_TYPES
+ : MEMBER_CARD_WORK_TYPES,
});
for (const job of readerJobs) {
const runWorks = summaries[job.operationId!] ?? [];
- const cards = visitorSeesOwn
+ const cards: WorkSummaryItem[] = visitorSeesOwn
? (sanitizeVisitorWorks(runWorks.filter(isVisitorOpenableWork)) ?? [])
- : runWorks.filter(isLinkedExternalWork).map(publicSummary);
+ : runWorks.flatMap<WorkSummaryItem>((item): WorkSummaryItem[] => {
+ if (isLinkedExternalWork(item)) return [publicSummary(item)];
+ if (!share && isCanvasWork(item) && canOpenCanvas(item, job.requesterUserId!))
+ return [item];
+ return [];
+ });
if (cards.length) result.set(job.messageId!, cards);
}
},