🤯 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
// @vitest-environment node
import { createHash } from 'node:crypto';
import { type LobeChatDatabase } from '@lobechat/database';
import { getTestDB } from '@lobechat/database/test-utils';
import type { ArtboardOp } from '@lobechat/types';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { agents, projects, tasks, topics, users } from '@/database/schemas';
import { ArtboardServiceError } from '../errors';
import type { ArtboardBlobStore } from '../files';
import { ArtboardService } from '../index';
import type { ArtboardSourceResolver } from '../sources';
const userId = 'artboard-comments-user';
const agentId = 'agt_artboard_comments';
const projectId = 'prj_artboard_comments';
const topicId = 'tpc_artboard_comments';
const db: LobeChatDatabase = await getTestDB();
const sources: ArtboardSourceResolver = {
imageBytes: async () => undefined,
importPage: async () => undefined,
};
const blobs = new Map<string, Uint8Array>();
const fileStore: ArtboardBlobStore = {
delete: async (keys) => {
for (const key of keys) blobs.delete(key);
},
list: async (prefix) =>
[...blobs]
.filter(([key]) => key.startsWith(prefix))
.map(([key, bytes]) => ({
etag: createHash('md5').update(bytes).digest('hex'),
key,
size: bytes.byteLength,
})),
presignWrite: async (key) => ({ url: `memory://${key}` }),
read: async (key) => blobs.get(key) ?? new Uint8Array(),
write: async (key, bytes) => {
blobs.set(key, bytes);
},
};
const asUser = () =>
new ArtboardService(db, userId, undefined, { context: { agentId: null }, fileStore, sources });
const asAgent = () =>
new ArtboardService(db, userId, undefined, { context: { agentId }, fileStore, sources });
const ops = (): ArtboardOp[] => [
{ group: { kind: 'journey', title: '主流程' }, ref: 'j', type: 'addGroup' },
{
board: {
groupId: 'j',
source: { kind: 'file', path: 'pages/home.html' },
title: '首页',
x: 0,
y: 0,
},
type: 'addBoard',
},
{ ref: 'r', round: { title: '入口放哪' }, type: 'addRound' },
{ group: { kind: 'options', title: '方案' }, ref: 'o', type: 'addGroup' },
{
board: {
groupId: 'o',
recommended: true,
roundId: 'r',
source: { kind: 'file', path: 'pages/option-a.html' },
title: 'A',
x: 0,
y: 800,
},
type: 'addBoard',
},
];
const create = async () => {
const { artboard } = await asUser().create(
{
files: {
writes: [
{ content: '<h1>首页</h1>', path: 'pages/home.html' },
{ content: '<h1>A</h1>', path: 'pages/option-a.html' },
],
},
ops: ops(),
title: '画板',
},
{ topicId },
);
const journey = artboard.content.boards.find((b) => !b.roundId)!;
const option = artboard.content.boards.find((b) => b.roundId)!;
return { artboard, journey, option, round: artboard.content.rounds[0] };
};
const errorOf = async (promise: Promise<unknown>) => {
try {
await promise;
} catch (error) {
if (error instanceof ArtboardServiceError) return error;
throw error;
}
throw new Error('expected an ArtboardServiceError');
};
const threadOf = async (artboardId: string, id: string) =>
(await asUser().listComments(artboardId)).find((thread) => thread.id === id)!;
beforeEach(async () => {
await db.delete(users).where(eq(users.id, userId));
await db.insert(users).values({ id: userId });
await db.insert(agents).values({ id: agentId, userId });
await db.insert(projects).values({ id: projectId, name: 'Comments', userId });
await db.insert(topics).values({ id: topicId, projectId, title: '需求讨论', userId });
blobs.clear();
});
afterEach(async () => {
await db.delete(tasks).where(eq(tasks.createdByUserId, userId));
await db.delete(users).where(eq(users.id, userId));
});
describe('ArtboardService comment delivery', () => {
it('marks a thread unread until the agent takes it, and again on a new user reply', async () => {
const { artboard } = await create();
const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '太挤了' });
expect((await threadOf(artboard.id, thread.id)).unread).toBe(true);
await asAgent().takeUndeliveredComments(artboard.id);
expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);
await asAgent().replyComment(thread.id, { content: '已拉开' });
expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);
await asUser().replyComment(thread.id, { clientId: 'c2', content: '还是挤' });
expect((await threadOf(artboard.id, thread.id)).unread).toBe(true);
});
it('drops a thread the user resolved from the unread set and from the agent', async () => {
const { artboard } = await create();
const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '算了' });
await asUser().resolveComment(thread.id);
expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);
expect(await asAgent().takeUndeliveredComments(artboard.id)).toEqual([]);
});
it("still hands the agent the user's answer when the user resolves its question first", async () => {
const { artboard } = await create();
const question = await asAgent().askQuestion(artboard.id, { content: '入口放哪?' });
await asUser().replyComment(question.id, { clientId: 'c1', content: '标题旁' });
await asUser().resolveComment(question.id);
expect((await threadOf(artboard.id, question.id)).unread).toBe(true);
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);
const taken = await asAgent().takeUndeliveredComments(artboard.id);
expect(taken.map((thread) => thread.id)).toEqual([question.id]);
expect(taken[0].replies.map((reply) => reply.content)).toEqual(['标题旁']);
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);
});
it('keeps a question the user resolved without answering away from the agent', async () => {
const { artboard } = await create();
const question = await asAgent().askQuestion(artboard.id, { content: '入口放哪?' });
await asUser().resolveComment(question.id);
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);
expect(await asAgent().takeUndeliveredComments(artboard.id)).toEqual([]);
});
it('keeps comments on the options of an open round from the agent until it is submitted', async () => {
const { artboard, journey, option, round } = await create();
const quiet = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 0.5, y: 0.5 },
boardId: option.id,
clientId: 'c1',
content: 'A 的按钮太小',
});
const loud = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 0.1, y: 0.2 },
boardId: journey.id,
clientId: 'c2',
content: '首页缺标题',
});
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);
const first = await asAgent().takeUndeliveredComments(artboard.id);
expect(first.map((thread) => thread.id)).toEqual([loud.id]);
expect((await threadOf(artboard.id, quiet.id)).unread).toBe(true);
await asUser().submitRound(artboard.id, round.id);
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);
const second = await asAgent().takeUndeliveredComments(artboard.id);
expect(second.map((thread) => thread.id)).toContain(quiet.id);
expect((await threadOf(artboard.id, quiet.id)).unread).toBe(false);
});
it('tells the agent which of the threads it takes carry something new', async () => {
const { artboard } = await create();
const old = await asUser().addComment(artboard.id, { clientId: 'c1', content: '旧的' });
await asAgent().takeUndeliveredComments(artboard.id);
const fresh = await asUser().addComment(artboard.id, { clientId: 'c2', content: '新的' });
const taken = await asAgent().takeUndeliveredComments(artboard.id);
expect(Object.fromEntries(taken.map((thread) => [thread.id, thread.unread]))).toEqual({
[old.id]: false,
[fresh.id]: true,
});
expect((await threadOf(artboard.id, fresh.id)).unread).toBe(false);
});
it('refuses a submit when the open rounds are not the ones the user saw', async () => {
const { artboard, round } = await create();
const error = await errorOf(asUser().submitOpenRounds(artboard.id, ['rnd_gone']));
expect(error.code).toBe('conflict');
const { artboard: after } = await asUser().get(artboard.id);
expect(after.content.rounds[0].status).toBe('open');
expect((await asUser().submitOpenRounds(artboard.id, [round.id])).submitted).toBe(1);
});
it('counts threads, not messages', async () => {
const { artboard } = await create();
const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '一' });
await asUser().replyComment(thread.id, { clientId: 'c2', content: '二' });
await asUser().addComment(artboard.id, { clientId: 'c3', content: '三' });
expect(await asUser().countUndeliveredComments(artboard.id)).toBe(2);
});
});
describe('ArtboardService.unreadCommentNotices', () => {
it('lists the artboards of a conversation that have unread threads', async () => {
const { artboard } = await create();
expect(await asUser().unreadCommentNotices(projectId, topicId)).toEqual([]);
await asUser().addComment(artboard.id, { clientId: 'c1', content: '一' });
await asUser().addComment(artboard.id, { clientId: 'c2', content: '二' });
expect(await asUser().unreadCommentNotices(projectId, topicId)).toEqual([
{ id: artboard.id, threads: 2, title: '画板' },
]);
expect(await asUser().unreadCommentNotices(projectId, 'tpc_other')).toEqual([]);
});
});
describe('ArtboardService comment anchors', () => {
it('flags a board thread as stale once the board file it was written on changes', async () => {
const { artboard, journey } = await create();
const onBoard = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 0.5, y: 0.5 },
boardId: journey.id,
clientId: 'c1',
content: '按钮颜色',
});
const onCanvas = await asUser().addComment(artboard.id, { clientId: 'c2', content: '整体' });
expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(false);
await asUser().writeFiles(artboard.id, {
edits: [{ newText: '<h1>新首页</h1>', oldText: '<h1>首页</h1>', path: 'pages/home.html' }],
});
expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(true);
expect((await threadOf(artboard.id, onCanvas.id)).stale).toBe(false);
});
it('flags a board thread as stale once the board points at another file', async () => {
const { artboard, journey } = await create();
const onBoard = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 0.5, y: 0.5 },
boardId: journey.id,
clientId: 'c1',
content: '按钮颜色',
});
await asUser().update(
artboard.id,
artboard.revision,
[
{
id: journey.id,
patch: { source: { kind: 'file', path: 'pages/home-v2.html' } },
type: 'updateBoard',
},
],
{ writes: [{ content: '<h1>首页 v2</h1>', path: 'pages/home-v2.html' }] },
);
expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(true);
});
it('drops the anchor of a thread whose board was removed', async () => {
const { artboard, journey } = await create();
const thread = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 0.5, y: 0.25 },
boardId: journey.id,
clientId: 'c1',
content: '按钮颜色',
});
const free = await asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 900, y: 40 },
clientId: 'c2',
content: '空白处',
});
await asUser().update(artboard.id, artboard.revision, [
{ id: journey.id, type: 'removeBoard' },
]);
expect(await threadOf(artboard.id, thread.id)).toMatchObject({ anchor: null, boardId: null });
expect((await threadOf(artboard.id, free.id)).anchor).toEqual({
type: 'canvas',
x: 900,
y: 40,
});
});
it('refuses a board anchor outside the board', async () => {
const { artboard, journey } = await create();
const error = await errorOf(
asUser().addComment(artboard.id, {
anchor: { type: 'canvas', x: 320, y: 0.5 },
boardId: journey.id,
clientId: 'c1',
content: '外面',
}),
);
expect(error.code).toBe('invalid');
});
});