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): onAgentCreated slot for seeding a new channel Agent's documents (#23420)

Arvin Xu9cab3b1a5afb
diff --git a/apps/server/src/services/channel/defaultChannel.test.ts b/apps/server/src/services/channel/defaultChannel.test.ts
index 558e161d3a1..b7a598d9a38 100644
--- a/apps/server/src/services/channel/defaultChannel.test.ts
+++ b/apps/server/src/services/channel/defaultChannel.test.ts
@@ -7,12 +7,16 @@ import {
DEFAULT_CHANNEL_TITLE,
} from './defaultChannel';
-const { ChannelServiceCtor, createDefault, createDirect, getFlags } = vi.hoisted(() => ({
- ChannelServiceCtor: vi.fn(),
- createDefault: vi.fn(),
- createDirect: vi.fn(),
- getFlags: vi.fn(),
-}));
+const { ChannelServiceCtor, createDefault, createDirect, getFlags, onAgentCreated } = vi.hoisted(
+ () => ({
+ ChannelServiceCtor: vi.fn(),
+ createDefault: vi.fn(),
+ createDirect: vi.fn(),
+ getFlags: vi.fn(),
+ onAgentCreated: vi.fn(),
+ }),
+);
+vi.mock('@/business/server/channel/onAgentCreated', () => ({ onAgentCreated }));
vi.mock('@/server/featureFlags', () => ({ getServerFeatureFlagsStateFromRuntimeConfig: getFlags }));
vi.mock('./ChannelService', () => ({
ChannelService: vi.fn(function (...args: unknown[]) {
@@ -78,6 +82,7 @@ describe('createAgentDirectChannel', () => {
vi.clearAllMocks();
getFlags.mockResolvedValue({ enableChannels: true });
createDirect.mockResolvedValue({ channel: { id: 'chn_1' } });
+ onAgentCreated.mockResolvedValue(undefined);
});
it.each([false, undefined])(
@@ -88,6 +93,7 @@ describe('createAgentDirectChannel', () => {
expect(getFlags).toHaveBeenCalledWith('owner');
expect(ChannelServiceCtor).not.toHaveBeenCalled();
expect(createDirect).not.toHaveBeenCalled();
+ expect(onAgentCreated).not.toHaveBeenCalled();
},
);
@@ -115,4 +121,35 @@ describe('createAgentDirectChannel', () => {
);
error.mockRestore();
});
+
+ it('hands the new Agent to the onAgentCreated slot after its direct Channel', async () => {
+ await createAgentDirectChannel({ ...params, workspaceId: 'ws_1' });
+ expect(onAgentCreated).toHaveBeenCalledWith({
+ agentId: 'agt_main',
+ db,
+ userId: 'owner',
+ workspaceId: 'ws_1',
+ });
+ expect(createDirect.mock.invocationCallOrder[0]).toBeLessThan(
+ onAgentCreated.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('still runs the slot when the direct Channel fails, and reports each failure', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ createDirect.mockRejectedValue(new Error('connection reset'));
+ onAgentCreated.mockRejectedValue(new Error('seed failed'));
+ await expect(createAgentDirectChannel(params)).resolves.toBeUndefined();
+ expect(onAgentCreated).toHaveBeenCalledTimes(1);
+ expect(error).toHaveBeenCalledTimes(2);
+ error.mockRestore();
+ });
+
+ it('skips the slot when the flag cannot be read', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ getFlags.mockRejectedValue(new Error('config unavailable'));
+ await expect(createAgentDirectChannel(params)).resolves.toBeUndefined();
+ expect(onAgentCreated).not.toHaveBeenCalled();
+ error.mockRestore();
+ });
});
diff --git a/apps/server/src/services/channel/defaultChannel.ts b/apps/server/src/services/channel/defaultChannel.ts
index c0d5a0153b7..cd1405bc801 100644
--- a/apps/server/src/services/channel/defaultChannel.ts
+++ b/apps/server/src/services/channel/defaultChannel.ts
@@ -1,5 +1,7 @@
import type { LobeChatDatabase } from '@lobechat/database';
+import { onAgentCreated } from '@/business/server/channel/onAgentCreated';
+
import { ChannelService } from './ChannelService';
import { isChannelEnabled } from './featureGate';
@@ -55,10 +57,20 @@ export interface AgentDirectChannelParams {
/**
* Opens the direct conversation between a person and the Agent they just created, named after the
- * Agent and bound to no device; see `ChannelService.createDirect`.
+ * Agent and bound to no device; see `ChannelService.createDirect`. Then hands the Agent to the
+ * `onAgentCreated` slot, which may seed its documents. Both run only while Channels are on for the
+ * creator, and each failure is reported on its own.
*/
-export const createAgentDirectChannel = async ({ db, ...context }: AgentDirectChannelParams) =>
- openForCreator('the direct channel of a new agent', context, async () => {
- if (!(await isChannelEnabled(context.userId))) return;
+export const createAgentDirectChannel = async ({ db, ...context }: AgentDirectChannelParams) => {
+ let enabled = false;
+ await openForCreator('the direct channel of a new agent', context, async () => {
+ enabled = await isChannelEnabled(context.userId);
+ if (!enabled) return;
await new ChannelService(db, context.userId, context.workspaceId).createDirect(context.agentId);
});
+ if (!enabled) return;
+
+ await openForCreator('the setup of a new channel agent', context, () =>
+ onAgentCreated({ db, ...context }),
+ );
+};
diff --git a/packages/business-server/src/channel/onAgentCreated.ts b/packages/business-server/src/channel/onAgentCreated.ts
new file mode 100644
index 00000000000..e240a7320df
--- /dev/null
+++ b/packages/business-server/src/channel/onAgentCreated.ts
@@ -0,0 +1,18 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+export interface OnAgentCreatedParams {
+ /** The Agent its creator just made. */
+ agentId: string;
+ db: LobeChatDatabase;
+ /** The person who created the Agent. */
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Follow-up for an Agent created while Channels are on, called after its direct Channel has been
+ * opened. An implementation can seed the Agent's own documents, such as a bootstrap document that
+ * the Agent removes once it has configured itself; whatever it writes belongs to the Agent, not to
+ * the user's memory. A failure is logged and never fails the creation. The default does nothing.
+ */
+export async function onAgentCreated(_params: OnAgentCreatedParams): Promise<void> {}