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): open a direct channel with each new agent (#22018)

AmAzing-0a21f1f26df4
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts
new file mode 100644
index 00000000000..e7d380cdf38
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lifecycleRouter } from './lifecycle';
+
+const mocks = vi.hoisted(() => ({
+ createAgent: vi.fn(),
+ createAgentDirectChannel: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),
+}));
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
+vi.mock('@/server/services/editLock', () => ({ EditLockService: vi.fn() }));
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn(function () {
+ return { createAgent: mocks.createAgent };
+ }),
+}));
+vi.mock('@/server/services/channel/defaultChannel', () => ({
+ createAgentDirectChannel: mocks.createAgentDirectChannel,
+}));
+
+const caller = (workspaceId?: string) =>
+ lifecycleRouter.createCaller({ userId: 'owner', workspaceId } as never);
+
+describe('agent.createAgent direct Channel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createAgent.mockResolvedValue({ agentId: 'agt_new' });
+ });
+
+ it.each([undefined, 'ws-1'])(
+ "opens the creator's direct Channel to the new Agent in scope %s",
+ async (workspaceId) => {
+ const config = { name: '小满', title: 'Health Assistant' };
+ await expect(
+ caller(workspaceId).createAgent({ config, localDeviceId: 'desktop' }),
+ ).resolves.toEqual({ agentId: 'agt_new' });
+
+ // The device hint is for the Channel only; the Agent itself is created without it.
+ expect(mocks.createAgent).toHaveBeenCalledWith({ config });
+ expect(mocks.createAgentDirectChannel).toHaveBeenCalledWith({
+ agentId: 'agt_new',
+ db: {},
+ localDeviceId: 'desktop',
+ userId: 'owner',
+ workspaceId,
+ });
+ },
+ );
+
+ it('opens nothing when the Agent was not created', async () => {
+ mocks.createAgent.mockRejectedValue(new Error('A private agent cannot be created here'));
+
+ await expect(caller('ws-1').createAgent({})).rejects.toThrow();
+ expect(mocks.createAgentDirectChannel).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
index 34aeaf10400..488151df5b7 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -9,6 +9,7 @@ import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
+import { createAgentDirectChannel } from '@/server/services/channel/defaultChannel';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { TrashService } from '@/server/services/trash';
import { TransferErrorCode } from '@/types/transferError';
@@ -50,7 +51,8 @@ export const lifecycleRouter = router({
return ctx.agentModel.countAgents(input);
}),
/**
- * Create a standalone agent. Returns the created agent ID.
+ * Create a standalone agent, with the creator's direct Channel to it while Channels are on.
+ * Returns the created agent ID.
*/
createAgent: agentProcedure
.use(withScopedPermission('agent:create'))
@@ -58,11 +60,22 @@ export const lifecycleRouter = router({
z.object({
config: CreateAgentSchema.optional(),
groupId: z.string().optional(),
+ /** The caller's own desktop, where a direct Channel to a local Agent runs. */
+ localDeviceId: z.string().min(1).optional(),
visibility: z.enum(['private', 'public']).optional(),
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.agentService.createAgent(input);
+ const { localDeviceId, ...params } = input;
+ const result = await ctx.agentService.createAgent(params);
+ await createAgentDirectChannel({
+ agentId: result.agentId,
+ db: ctx.serverDB,
+ localDeviceId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return result;
}),
/**
* Create an agent without session.
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 9d591a5a507..2d398b7890b 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -102,6 +102,19 @@ export const channelRouter = router({
data: await ctx.channelService.create(input),
success: true,
})),
+ createGroupFromDirect: channelProcedure
+ .input(
+ z.object({
+ agents: z.array(agentSelection).max(20).default([]),
+ channelId,
+ title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength),
+ userIds: z.array(z.string().min(1)).max(100).default([]),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.createGroupFromDirect(input.channelId, input),
+ success: true,
+ })),
detail: channelProcedure
.input(
z.object({
diff --git a/apps/server/src/routers/lambda/session.createSession.test.ts b/apps/server/src/routers/lambda/session.createSession.test.ts
new file mode 100644
index 00000000000..8eadcd125b8
--- /dev/null
+++ b/apps/server/src/routers/lambda/session.createSession.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { sessionRouter } from './session';
+
+const mocks = vi.hoisted(() => ({
+ createAgent: vi.fn(),
+ createAgentDirectChannel: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),
+}));
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn(function () {
+ return { createAgent: mocks.createAgent };
+ }),
+}));
+vi.mock('@/server/services/channel/defaultChannel', () => ({
+ createAgentDirectChannel: mocks.createAgentDirectChannel,
+}));
+
+const caller = (workspaceId?: string) =>
+ sessionRouter.createCaller({ userId: 'owner', workspaceId } as never);
+
+const input = {
+ config: { title: 'Health Assistant' },
+ session: {},
+ type: 'agent' as const,
+};
+
+describe('session.createSession direct Channel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createAgent.mockResolvedValue({ agentId: 'agt_new' });
+ });
+
+ it("opens the creator's direct Channel to the Agent it creates", async () => {
+ await expect(caller('ws-1').createSession(input)).resolves.toBe('agt_new');
+
+ expect(mocks.createAgentDirectChannel).toHaveBeenCalledWith({
+ agentId: 'agt_new',
+ db: {},
+ userId: 'owner',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('opens nothing for a refused group session', async () => {
+ await expect(caller().createSession({ ...input, type: 'group' })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(mocks.createAgent).not.toHaveBeenCalled();
+ expect(mocks.createAgentDirectChannel).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 34956fa12d7..73be7e92a53 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -9,6 +9,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentService } from '@/server/services/agent';
import { resolveAgentReference } from '@/server/services/agent/resolveReference';
+import { createAgentDirectChannel } from '@/server/services/channel/defaultChannel';
import { assertCanUseConversationTargets } from './_helpers/conversationResourceGuard';
@@ -60,6 +61,12 @@ export const sessionRouter = router({
groupId: groupId && groupId !== 'default' ? groupId : undefined,
visibility: config.visibility,
});
+ await createAgentDirectChannel({
+ agentId,
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
return agentId;
}),
diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.ts
new file mode 100644
index 00000000000..421ea2a8398
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts
@@ -0,0 +1,209 @@
+// @vitest-environment node
+import { CHANNEL_LIMITS } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelError } from '@/database/repositories/channel';
+
+import { ChannelService } from './ChannelService';
+
+const {
+ create,
+ createGroupFromDirect,
+ findAccess,
+ findDevice,
+ getAgent,
+ notify,
+ querySystemInfo,
+ statPath,
+} = vi.hoisted(() => ({
+ create: vi.fn(),
+ createGroupFromDirect: vi.fn(),
+ findAccess: vi.fn(),
+ findDevice: vi.fn(),
+ getAgent: vi.fn(),
+ notify: vi.fn(),
+ querySystemInfo: vi.fn(),
+ statPath: vi.fn(),
+}));
+vi.mock('@/database/repositories/channel', async (original) => ({
+ ...(await original<object>()),
+ ChannelRepository: class {
+ create = create;
+ createGroupFromDirect = createGroupFromDirect;
+ findAccess = findAccess;
+ },
+}));
+vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: class {
+ findPersonalByDeviceId = findDevice;
+ },
+}));
+vi.mock('@/server/services/agent', () => ({
+ AgentService: class {
+ getAgentConfigById = getAgent;
+ },
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { queryDeviceSystemInfo: querySystemInfo, statPath },
+}));
+vi.mock('@/server/services/file', () => ({ FileService: class {} }));
+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
+vi.mock('./notify', () => ({ notifyChannel: notify }));
+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));
+
+const claudeCode = { heterogeneousProvider: { type: 'claude-code' } };
+
+describe('the direct Channel of a new Agent', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ create.mockResolvedValue({ channel: { id: 'chn_1' } });
+ findDevice.mockImplementation(async (deviceId: string) => ({
+ defaultCwd: null,
+ deviceId,
+ platform: 'darwin',
+ userId: 'owner',
+ }));
+ statPath.mockImplementation(async ({ path }: { path: string }) => ({
+ canonicalPath: `/real${path}`,
+ isDirectory: true,
+ }));
+ querySystemInfo.mockResolvedValue({ homePath: '/Users/owner' });
+ });
+ const createDirect = (localDeviceId?: string) =>
+ new ChannelService({} as never, 'owner').createDirect('agt_new', { localDeviceId });
+
+ it.each([
+ ['its personal name', { name: ' 小满 ', title: 'Health Assistant' }, '小满'],
+ ['its role when it has no name', { name: '', title: 'Health Assistant' }, 'Health Assistant'],
+ ['a generic label when it has neither', { name: null, title: ' ' }, 'Agent'],
+ [
+ 'a name cut to the Channel title limit',
+ { name: 'x'.repeat(CHANNEL_LIMITS.titleLength + 20) },
+ 'x'.repeat(CHANNEL_LIMITS.titleLength),
+ ],
+ ])('binds a native Agent and titles the Channel with %s', async (_, identity, title) => {
+ getAgent.mockResolvedValue({ model: 'gpt-5', ...identity });
+ await expect(createDirect('desktop')).resolves.toEqual({ channel: { id: 'chn_1' } });
+ expect(getAgent).toHaveBeenCalledTimes(1);
+ // A native Agent with no device of its own answers without one, even from a desktop.
+ expect(findDevice).not.toHaveBeenCalled();
+ expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_new', title });
+ });
+
+ it.each([
+ [
+ 'its own directory on that device',
+ { workingDirByDevice: { mac: { path: '/repo' } } },
+ null,
+ '/real/repo',
+ ],
+ ["the device's default directory", {}, '/projects', '/real/projects'],
+ ["the device's home folder", {}, null, '/real/Users/owner'],
+ ])(
+ 'seats an external Agent on its bound device in %s',
+ async (_, directories, defaultCwd, workingDirectory) => {
+ getAgent.mockResolvedValue({
+ agencyConfig: { ...claudeCode, ...directories, boundDeviceId: 'mac' },
+ name: 'Claude',
+ });
+ findDevice.mockResolvedValue({
+ defaultCwd,
+ deviceId: 'mac',
+ platform: 'darwin',
+ userId: 'owner',
+ });
+
+ await createDirect('desktop');
+
+ expect(findDevice).toHaveBeenCalledWith('mac');
+ expect(create).toHaveBeenCalledWith({
+ agentConfig: { deviceId: 'mac', deviceOwnerId: 'owner', workingDirectory },
+ agentId: 'agt_new',
+ title: 'Claude',
+ });
+ },
+ );
+
+ it("seats a local external Agent on its creator's desktop", async () => {
+ getAgent.mockResolvedValue({ agencyConfig: claudeCode, name: 'Claude' });
+ await createDirect('desktop');
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentConfig: {
+ deviceId: 'desktop',
+ deviceOwnerId: 'owner',
+ workingDirectory: '/real/Users/owner',
+ },
+ }),
+ );
+ });
+
+ it.each([
+ ['a local external Agent created away from a desktop', claudeCode, undefined],
+ [
+ 'an external Agent that runs in a sandbox',
+ { ...claudeCode, executionTarget: 'sandbox' },
+ 'desktop',
+ ],
+ [
+ 'a runtime Channels do not support',
+ { heterogeneousProvider: { type: 'openclaw' } },
+ 'desktop',
+ ],
+ ])('opens nothing for %s', async (_, agencyConfig, localDeviceId) => {
+ getAgent.mockResolvedValue({ agencyConfig, name: 'Agent' });
+ await expect(createDirect(localDeviceId)).resolves.toBeUndefined();
+ expect(findDevice).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('opens nothing for an Agent the creator cannot reach', async () => {
+ getAgent.mockResolvedValue(null);
+ await expect(createDirect('desktop')).resolves.toBeUndefined();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a device that is not the creator’s', () => findDevice.mockResolvedValue(undefined)],
+ ['a device that cannot be reached', () => statPath.mockResolvedValue(undefined)],
+ ])('refuses %s rather than seat the Agent where it cannot run', async (_, arrange) => {
+ getAgent.mockResolvedValue({ agencyConfig: claudeCode, name: 'Claude' });
+ arrange();
+ await expect(createDirect('desktop')).rejects.toBeInstanceOf(ChannelError);
+ expect(create).not.toHaveBeenCalled();
+ });
+});
+
+describe('inviting from a direct conversation', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ findAccess.mockResolvedValue({ channel: { agentId: 'agt_ada', id: 'chn_direct' } });
+ createGroupFromDirect.mockResolvedValue({ channel: { id: 'chn_group' } });
+ getAgent.mockResolvedValue({ model: 'gpt-5' });
+ });
+ const invite = () =>
+ new ChannelService({} as never, 'owner', 'workspace').createGroupFromDirect('chn_direct', {
+ agents: [{ agentId: 'agt_bo' }],
+ title: 'Ada, Bo, Mia',
+ userIds: ['user-mia'],
+ });
+
+ it('starts the group with the invited Agents resolved, then tells its members', async () => {
+ await expect(invite()).resolves.toEqual({ channel: { id: 'chn_group' } });
+ expect(getAgent).toHaveBeenCalledWith('agt_bo');
+ expect(createGroupFromDirect).toHaveBeenCalledWith('chn_direct', {
+ agents: [{ agentId: 'agt_bo', config: {}, description: undefined, name: undefined }],
+ title: 'Ada, Bo, Mia',
+ userIds: ['user-mia'],
+ });
+ expect(notify).toHaveBeenCalledWith({}, 'chn_group');
+ });
+
+ it('probes nothing for a conversation the caller cannot reach', async () => {
+ findAccess.mockResolvedValue(undefined);
+ await expect(invite()).rejects.toBeInstanceOf(ChannelError);
+ expect(getAgent).not.toHaveBeenCalled();
+ expect(createGroupFromDirect).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 38cfd9c6ad5..cccd7124ce4 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -1,7 +1,13 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
-import { isChannelRuntime } from '@lobechat/types';
+import {
+ agentDisplayName,
+ CHANNEL_LIMITS,
+ defaultChannelAgentDevice,
+ defaultChannelAgentDirectory,
+ isChannelRuntime,
+} from '@lobechat/types';
import pMap from 'p-map';
import { DeviceModel } from '@/database/models/device';
@@ -54,8 +60,12 @@ export class ChannelService {
this.projectModel = new ProjectModel(db, userId, workspaceId);
}
- private async resolveAgent(input: ChannelAgentSelection): Promise<ChannelAddAgentInput> {
- const agent = await this.agentService.getAgentConfigById(input.agentId);
+ private async resolveAgent(
+ input: ChannelAgentSelection,
+ /** The Agent's config when the caller already loaded it. */
+ loaded?: ChannelAgentConfig,
+ ): Promise<ChannelAddAgentInput> {
+ const agent = loaded ?? (await this.agentService.getAgentConfigById(input.agentId));
if (!agent) throw new ChannelError('NOT_FOUND', 'Agent not found');
const runtime = agentRuntime(agent);
if (!isChannelRuntime(runtime))
@@ -76,10 +86,11 @@ export class ChannelService {
'BAD_REQUEST',
'Native Channel execution is not supported on Windows devices yet',
);
- // An Agent without its own directory on this device runs in the device's home folder,
- // the same fallback an ordinary conversation uses.
+ // An unpicked directory follows the Agent's own choice on this device, then the device's
+ // default, then its home folder: the fallbacks an ordinary conversation uses.
const workingDirectory =
input.workingDirectory?.trim() ||
+ defaultChannelAgentDirectory(agent.agencyConfig, device.deviceId, device.defaultCwd) ||
(await deviceGateway.queryDeviceSystemInfo(this.userId, input.deviceId, this.workspaceId))
?.homePath;
if (!workingDirectory)
@@ -142,6 +153,55 @@ export class ChannelService {
});
};
+ /**
+ * Inviting into a direct conversation starts a group with its Agent and the invitees; the
+ * direct conversation stays one person and one Agent.
+ */
+ createGroupFromDirect = async (
+ channelId: string,
+ input: { agents: ChannelAgentSelection[]; title: string; userIds: string[] },
+ ) => {
+ // Check membership before probing a device; the write rechecks the current admin role.
+ if (!(await this.repository.findAccess(channelId)))
+ throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const agents = await pMap(input.agents, (agent) => this.resolveAgent(agent), {
+ concurrency: 5,
+ });
+ const access = await this.repository.createGroupFromDirect(channelId, {
+ agents,
+ title: input.title,
+ userIds: input.userIds,
+ });
+ // Invitees see the new group without waiting for their next poll.
+ await this.changed(access.channel.id);
+ return access;
+ };
+
+ /**
+ * The direct conversation a person starts with an Agent they just created, titled with the
+ * Agent's name. The Agent keeps the device and directory a new Channel would give it, checked
+ * the same way; an external Agent with no device to run on gets none, as it could not join a
+ * group either.
+ */
+ createDirect = async (agentId: string, { localDeviceId }: { localDeviceId?: string } = {}) => {
+ const agent = await this.agentService.getAgentConfigById(agentId);
+ if (!agent) return;
+ const runtime = agentRuntime(agent);
+ if (!isChannelRuntime(runtime)) return;
+ const deviceId = defaultChannelAgentDevice({
+ agencyConfig: agent.agencyConfig,
+ localDeviceId,
+ runtime,
+ });
+ if (!deviceId && runtime !== 'native') return;
+ const { config } = await this.resolveAgent({ agentId, deviceId }, agent);
+ return this.repository.create({
+ agentConfig: config,
+ agentId,
+ title: agentDisplayName(agent, 'Agent').slice(0, CHANNEL_LIMITS.titleLength),
+ });
+ };
+
/**
* The main Agent when it runs natively. An external Agent needs a device and directory that a
* member picks when adding it, so the scope's LobeAI answers in the meantime.
diff --git a/apps/server/src/services/channel/defaultChannel.test.ts b/apps/server/src/services/channel/defaultChannel.test.ts
index ea63ea1e3df..372ab25f226 100644
--- a/apps/server/src/services/channel/defaultChannel.test.ts
+++ b/apps/server/src/services/channel/defaultChannel.test.ts
@@ -1,18 +1,23 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createDefaultChannel, DEFAULT_CHANNEL_TITLE } from './defaultChannel';
+import {
+ createAgentDirectChannel,
+ createDefaultChannel,
+ DEFAULT_CHANNEL_TITLE,
+} from './defaultChannel';
-const { ChannelServiceCtor, createDefault, getFlags } = vi.hoisted(() => ({
+const { ChannelServiceCtor, createDefault, createDirect, getFlags } = vi.hoisted(() => ({
ChannelServiceCtor: vi.fn(),
createDefault: vi.fn(),
+ createDirect: vi.fn(),
getFlags: vi.fn(),
}));
vi.mock('@/server/featureFlags', () => ({ getServerFeatureFlagsStateFromRuntimeConfig: getFlags }));
vi.mock('./ChannelService', () => ({
ChannelService: vi.fn(function (...args: unknown[]) {
ChannelServiceCtor(...args);
- return { createDefault };
+ return { createDefault, createDirect };
}),
}));
@@ -68,3 +73,43 @@ describe('createDefaultChannel', () => {
error.mockRestore();
});
});
+
+describe('createAgentDirectChannel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getFlags.mockResolvedValue({ enableChannels: true });
+ createDirect.mockResolvedValue({ channel: { id: 'chn_1' } });
+ });
+
+ it.each([false, undefined])(
+ 'creates nothing while `channel` is %s for the creator',
+ async (flag) => {
+ getFlags.mockResolvedValue({ enableChannels: flag });
+ await createAgentDirectChannel({ ...params, workspaceId: 'ws_1' });
+ expect(getFlags).toHaveBeenCalledWith('owner');
+ expect(ChannelServiceCtor).not.toHaveBeenCalled();
+ expect(createDirect).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([undefined, 'ws_1'])(
+ "opens the creator's direct Channel to the new Agent in scope %s",
+ async (workspaceId) => {
+ await createAgentDirectChannel({ ...params, localDeviceId: 'desktop', workspaceId });
+ expect(ChannelServiceCtor).toHaveBeenCalledWith(db, 'owner', workspaceId);
+ expect(createDirect).toHaveBeenCalledWith('agt_main', { localDeviceId: 'desktop' });
+ expect(createDefault).not.toHaveBeenCalled();
+ },
+ );
+
+ it('never fails the Agent creation it follows', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ createDirect.mockRejectedValue(new Error('connection reset'));
+ await expect(createAgentDirectChannel(params)).resolves.toBeUndefined();
+ expect(error).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ agentId: 'agt_main', userId: 'owner' }),
+ );
+ error.mockRestore();
+ });
+});
diff --git a/apps/server/src/services/channel/defaultChannel.ts b/apps/server/src/services/channel/defaultChannel.ts
index 31433e95d6f..eea2d072cc5 100644
--- a/apps/server/src/services/channel/defaultChannel.ts
+++ b/apps/server/src/services/channel/defaultChannel.ts
@@ -16,31 +16,57 @@ export interface DefaultChannelParams {
}
/**
- * Opens the Channel a new workspace or project starts with: its creator and its main Agent (the
- * scope's LobeAI when that Agent needs a device). Only while Channels are on for the creator.
- * Best-effort: the workspace or project already exists, so a failure must not fail its creation.
+ * Runs `open` only while Channels are on for the creator. Best-effort: what it follows already
+ * exists, so a failure must not fail its creation.
*/
-export const createDefaultChannel = async ({
- agentId,
- db,
- projectId,
- userId,
- workspaceId,
-}: DefaultChannelParams) => {
+const openForCreator = async (
+ what: string,
+ context: Omit<DefaultChannelParams, 'db'>,
+ open: () => Promise<unknown>,
+) => {
try {
- if (!(await isChannelEnabled(userId))) return;
- await new ChannelService(db, userId, workspaceId).createDefault({
- agentId,
- projectId,
- title: DEFAULT_CHANNEL_TITLE,
- });
+ if (!(await isChannelEnabled(context.userId))) return;
+ await open();
} catch (error) {
- console.error('[channel] Failed to create the default channel', {
- agentId,
- error,
- projectId,
- userId,
- workspaceId,
- });
+ console.error(`[channel] Failed to create ${what}`, { ...context, error });
}
};
+
+/**
+ * Opens the Channel a new workspace or project starts with: its creator and its main Agent (the
+ * scope's LobeAI when that Agent needs a device).
+ */
+export const createDefaultChannel = async ({ db, ...context }: DefaultChannelParams) =>
+ openForCreator('the default channel', context, () =>
+ new ChannelService(db, context.userId, context.workspaceId).createDefault({
+ agentId: context.agentId,
+ projectId: context.projectId,
+ title: DEFAULT_CHANNEL_TITLE,
+ }),
+ );
+
+export interface AgentDirectChannelParams {
+ /** The Agent its creator just made. */
+ agentId: string;
+ db: LobeChatDatabase;
+ /** The creator's own desktop, where an Agent that runs locally answers; checked before use. */
+ localDeviceId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Opens the direct conversation between a person and the Agent they just created, named after the
+ * Agent and on the device and directory a new Channel would give it; see
+ * `ChannelService.createDirect`.
+ */
+export const createAgentDirectChannel = async ({
+ db,
+ localDeviceId,
+ ...context
+}: AgentDirectChannelParams) =>
+ openForCreator('the direct channel of a new agent', context, () =>
+ new ChannelService(db, context.userId, context.workspaceId).createDirect(context.agentId, {
+ localDeviceId,
+ }),
+ );
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 7695659678c..feae4a8dce8 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -88,6 +88,7 @@
"failure.messageLabel": "Reply failed: {{names}}",
"failure.title": "Failed replies · {{count}}",
"followers": "Replies from: {{names}}",
+ "invite.directHint": "Inviting here starts a new channel with {{name}} and the members you choose. This conversation with {{name}} stays as it is.",
"invite.noAgentMatches": "No matching Agents",
"invite.noAgents": "All available Agents have joined",
"invite.noSelected": "No one selected yet",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 3e8300dc876..23503a22f6e 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -88,6 +88,7 @@
"failure.messageLabel": "回复失败:{{names}}",
"failure.title": "回复失败 · {{count}}",
"followers": "参与回复:{{names}}",
+ "invite.directHint": "邀请后会新建一个频道,包含 {{name}} 和你选择的成员;你和 {{name}} 的这个对话保持不变。",
"invite.noAgentMatches": "没有匹配的 Agent",
"invite.noAgents": "可用的 Agent 都已加入",
"invite.noSelected": "还没有选择成员",
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index 407c585030d..4a8757b46fd 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -34,6 +34,13 @@ messages directly to the bound Agent. Group channels leave `agentId` NULL, inclu
only one Agent. A group whose only active members are one person and one Agent also skips routing:
every message that mentions no Agent, in the main timeline or any Thread, goes to that Agent,
which then follows the Thread. Deleting a bound Agent cascades its direct conversations and their public history.
+While Channels are on, creating an Agent opens its creator's conversation, titled with the Agent's
+name, with the Agent on the device and directory a new Channel would give it
+(`createAgentDirectChannel`).
+Inviting from a direct conversation leaves it as it is and starts a group instead
+(`createGroupFromDirect`): its person and Agent, the Agent in the same channel-local environment,
+plus the invited Agents and, in a workspace, people. `userCandidates` lists those people from a
+workspace direct conversation; `addUser` still refuses it.
Group history survives deletion of an author or Agent. Message sender references use `SET NULL`;
new writes require exactly one actual sender. Human requests have `userId`, Agent replies have
diff --git a/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts
new file mode 100644
index 00000000000..75b13acc228
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts
@@ -0,0 +1,119 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, channelMembers, channels, workspaceMembers } from '../../../schemas';
+import { ChannelRepository } from '..';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-group-from-direct');
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(workspaceMembers).values([
+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },
+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },
+ ]);
+});
+afterEach(fixture.cleanup);
+
+const environment = () => ({
+ deviceId: 'device-1',
+ deviceOwnerId: fixture.ownerId,
+ workingDirectory: '/repo',
+});
+
+const createAgent = async (name: string, workspaceId: string | null) => {
+ const [agent] = await db
+ .insert(agents)
+ .values({ name, userId: fixture.ownerId, workspaceId })
+ .returning();
+ return agent;
+};
+
+const createDirect = async (workspaceId: string | null = fixture.workspaceId) => {
+ const agent = await createAgent('Ada', workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, workspaceId);
+ const { channel } = await owner.create({
+ agentConfig: environment(),
+ agentId: agent.id,
+ title: 'Ada',
+ });
+ return { agent, direct: channel, owner };
+};
+
+const membersOf = (channelId: string) =>
+ db.select().from(channelMembers).where(eq(channelMembers.channelId, channelId));
+
+describe('inviting from a direct conversation', () => {
+ it('starts a group with its Agent, in the same environment, and the invitees', async () => {
+ const { agent, direct, owner } = await createDirect();
+ const helper = await createAgent('Bo', fixture.workspaceId);
+ expect(await owner.userCandidates(direct.id)).toEqual([
+ expect.objectContaining({ userId: fixture.memberId }),
+ ]);
+
+ const { channel, member } = await owner.createGroupFromDirect(direct.id, {
+ agents: [{ agentId: helper.id }],
+ title: 'Ada, Bo, mia',
+ userIds: [fixture.memberId],
+ });
+
+ expect(channel).toMatchObject({
+ agentId: null,
+ title: 'Ada, Bo, mia',
+ userId: fixture.ownerId,
+ visibility: 'private',
+ workspaceId: fixture.workspaceId,
+ });
+ expect(member).toMatchObject({ role: 'owner', userId: fixture.ownerId });
+ const members = await membersOf(channel.id);
+ expect(members).toHaveLength(4);
+ expect(members).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ agentId: agent.id, config: environment(), name: 'Ada' }),
+ expect.objectContaining({ actorType: 'agent', agentId: helper.id }),
+ expect.objectContaining({ role: 'member', status: 'active', userId: fixture.memberId }),
+ ]),
+ );
+ // The direct conversation stays one person and one Agent, and the invitee only sees the group.
+ expect(await membersOf(direct.id)).toHaveLength(2);
+ const invitee = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ expect((await invitee.list()).map(({ id }) => id)).toEqual([channel.id]);
+ });
+
+ it('starts a personal group with more Agents', async () => {
+ const { agent, direct, owner } = await createDirect(null);
+ const helper = await createAgent('Bo', null);
+ const { channel } = await owner.createGroupFromDirect(direct.id, {
+ agents: [{ agentId: helper.id }],
+ title: 'Ada, Bo',
+ });
+ expect(channel.workspaceId).toBeNull();
+ expect((await membersOf(channel.id)).map(({ agentId }) => agentId)).toEqual(
+ expect.arrayContaining([agent.id, helper.id]),
+ );
+ });
+
+ it.each([
+ ['people into a personal group', null, { userIds: [fixture.memberId] }],
+ ['an empty invitation', 'workspace', {}],
+ ])('refuses %s without creating anything', async (_, scope, invitees) => {
+ const workspaceId = scope ? fixture.workspaceId : null;
+ const { direct, owner } = await createDirect(workspaceId);
+ await expect(
+ owner.createGroupFromDirect(direct.id, { title: 'Group', ...invitees }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(await db.select().from(channels).where(eq(channels.userId, fixture.ownerId))).toEqual([
+ expect.objectContaining({ id: direct.id }),
+ ]);
+ });
+
+ it('only starts groups from a direct conversation', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await expect(
+ asOwner.createGroupFromDirect(channel.id, { title: 'Group', userIds: [fixture.memberId] }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/identity.test.ts b/packages/database/src/repositories/channel/__tests__/identity.test.ts
index ff9df6dada2..46e0898dc59 100644
--- a/packages/database/src/repositories/channel/__tests__/identity.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/identity.test.ts
@@ -113,6 +113,25 @@ describe('direct Channel identity', () => {
expect(personal.channel.workspaceId).toBeNull();
});
+ it('seats the bound Agent in the environment its caller resolved', async () => {
+ const agent = await createAgent(null);
+ const environment = {
+ deviceId: 'device-1',
+ deviceOwnerId: fixture.ownerId,
+ workingDirectory: '/repo',
+ };
+ const { channel } = await new ChannelRepository(db, fixture.ownerId).create({
+ agentConfig: environment,
+ agentId: agent.id,
+ title: 'Direct',
+ });
+ const [member] = await db
+ .select()
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channel.id), eq(channelMembers.actorType, 'agent')));
+ expect(member).toMatchObject({ agentId: agent.id, config: environment });
+ });
+
it('keeps a group unbound even when it contains a single Agent', async () => {
const team = await fixture.createTeamChannel();
await fixture.addAgent(team.channel.id, 'Only Agent');
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 652e68482cc..8f94827739f 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -77,6 +77,8 @@ export class ChannelRepository {
/** Opens the unique direct conversation, or creates a group with its initial members. */
create = async (params: {
agentId?: string;
+ /** The direct conversation's Agent environment; the caller resolved and checked it. */
+ agentConfig?: ChannelMemberConfig;
agents?: ChannelAddAgentInput[];
/** Callers check that the project is readable in this scope. */
projectId?: string;
@@ -115,24 +117,65 @@ export class ChannelRepository {
if (existing) return existing;
throw new ChannelError('CONFLICT', 'The direct conversation is unavailable');
}
- const [member] = await tx
- .insert(channelMembers)
- .values({
- actorType: 'user',
- channelId: channel.id,
- lastReadSequence: 0,
- role: 'owner',
- userId: this.userId,
- })
- .returning();
-
- if (agentId) await addAgentMember(tx, channel, this.userId, { agentId });
+ const member = await this.addOwner(tx, channel.id);
+
+ if (agentId)
+ await addAgentMember(tx, channel, this.userId, { agentId, config: params.agentConfig });
for (const agent of params.agents ?? [])
await addAgentMember(tx, channel, this.userId, agent);
return { channel, member } satisfies ChannelAccess;
});
+ /**
+ * Inviting into a direct conversation starts a group instead, and the direct conversation stays
+ * as it is. The group holds its person and Agent, the Agent keeping its channel-local
+ * environment, joined by the invited Agents and workspace people.
+ */
+ createGroupFromDirect = async (
+ channelId: string,
+ params: { agents?: ChannelAddAgentInput[]; title: string; userIds?: string[] },
+ ) =>
+ this.write(
+ channelId,
+ async (tx, { channel: direct }) => {
+ if (!direct.agentId)
+ throw new ChannelError('BAD_REQUEST', 'Only a direct conversation starts a group');
+ if (!params.agents?.length && !params.userIds?.length)
+ throw new ChannelError('BAD_REQUEST', 'Invite at least one person or Agent');
+ const [bound] = await tx
+ .select()
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, direct.id),
+ eq(channelMembers.agentId, direct.agentId),
+ eq(channelMembers.status, 'active'),
+ ),
+ )
+ .limit(1);
+ if (!bound) throw new ChannelError('NOT_FOUND', 'Agent member not found');
+
+ const [channel] = await tx
+ .insert(channels)
+ .values({ title: params.title, userId: this.userId, workspaceId: this.workspaceId })
+ .returning();
+ const member = await this.addOwner(tx, channel.id);
+ const access = { channel, member } satisfies ChannelAccess;
+ await addAgentMember(tx, channel, this.userId, {
+ agentId: direct.agentId,
+ config: bound.config ?? undefined,
+ description: bound.description,
+ name: bound.name ?? undefined,
+ });
+ for (const agent of params.agents ?? [])
+ await addAgentMember(tx, channel, this.userId, agent);
+ for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);
+ return access;
+ },
+ { minRole: 'admin' },
+ );
+
/** Adds a usable Agent reference; a missing reference is allowed only for retained history. */
addAgent = async (channelId: string, input: ChannelAddAgentInput) =>
this.write(channelId, (tx, { channel }) => addAgentMember(tx, channel, this.userId, input), {
@@ -487,6 +530,20 @@ export class ChannelRepository {
return retryRouting(tx, channelId, messageId);
});
+ private addOwner = async (tx: Transaction, channelId: string) => {
+ const [member] = await tx
+ .insert(channelMembers)
+ .values({
+ actorType: 'user',
+ channelId,
+ lastReadSequence: 0,
+ role: 'owner',
+ userId: this.userId,
+ })
+ .returning();
+ return member;
+ };
+
private findDirect = async (
tx: Transaction,
agentId: string,
diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.ts
index ce26b602374..a0b4a4b3d92 100644
--- a/packages/database/src/repositories/channel/people.ts
+++ b/packages/database/src/repositories/channel/people.ts
@@ -22,20 +22,29 @@ const requireWorkspaceMember = async (tx: Transaction, workspaceId: string, user
if (!member) throw new ChannelError('NOT_FOUND', 'Workspace member not found');
};
-const requireGroupWorkspace = async (tx: Transaction, { channel, member }: ChannelAccess) => {
- if (!channel.workspaceId || channel.agentId)
+const requireWorkspace = async (tx: Transaction, { channel, member }: ChannelAccess) => {
+ if (!channel.workspaceId)
throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');
await requireWorkspaceMember(tx, channel.workspaceId, member.userId!);
return channel.workspaceId;
};
-/** Only active people in this workspace; search the full directory, not a client-side page. */
+const requireGroupWorkspace = async (tx: Transaction, access: ChannelAccess) => {
+ if (access.channel.agentId)
+ throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');
+ return requireWorkspace(tx, access);
+};
+
+/**
+ * Only active people in this workspace; search the full directory, not a client-side page. A
+ * direct conversation lists them for the group that inviting from it starts.
+ */
export const channelUserCandidates = async (
tx: Transaction,
access: ChannelAccess,
search = '',
) => {
- const workspaceId = await requireGroupWorkspace(tx, access);
+ const workspaceId = await requireWorkspace(tx, access);
const query = search.trim();
return tx
.select({
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index b44ad0ad336..25066d38beb 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -154,6 +154,8 @@ export default {
'rename': 'Rename channel',
'renameFailed': 'Could not rename the channel. Try again.',
'renameForbidden': 'Only the channel owner or an administrator can rename this channel.',
+ 'invite.directHint':
+ 'Inviting here starts a new channel with {{name}} and the members you choose. This conversation with {{name}} stays as it is.',
'invite.noAgentMatches': 'No matching Agents',
'invite.noAgents': 'All available Agents have joined',
'invite.noSelected': 'No one selected yet',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 5bc0d82239a..27f7614af4c 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -1,4 +1,5 @@
-import type { LobeAgentConfig } from './agent';
+import type { LobeAgentAgencyConfig, LobeAgentConfig } from './agent';
+import { getWorkingDirEffectivePath } from './device';
/**
* Channel: a shared conversation where people and Agents talk together.
@@ -20,6 +21,41 @@ export type ChannelRuntime = (typeof CHANNEL_RUNTIMES)[number];
export const isChannelRuntime = (runtime: string): runtime is ChannelRuntime =>
(CHANNEL_RUNTIMES as readonly string[]).includes(runtime);
+/**
+ * The device a Channel seats an Agent on until someone picks another: the one the Agent is bound
+ * to, else this person's own desktop for an Agent that runs on its user's machine (`local`, or an
+ * external runtime with no target). Never another available or online device.
+ */
+export const defaultChannelAgentDevice = ({
+ agencyConfig,
+ localDeviceId,
+ runtime,
+ workspaceScoped,
+}: {
+ agencyConfig?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null;
+ /** This person's own desktop, when they act from one. */
+ localDeviceId?: string;
+ runtime: string;
+ /** The Agent runs on workspace devices only, never a personal desktop. */
+ workspaceScoped?: boolean;
+}): string | undefined => {
+ const target = agencyConfig?.executionTarget;
+ if (target === 'none' || target === 'sandbox' || target === 'auto') return;
+ const localDefault =
+ !workspaceScoped && (target === 'local' || (target === undefined && runtime !== 'native'));
+ return agencyConfig?.boundDeviceId || (localDefault ? localDeviceId : undefined);
+};
+
+/** The directory on that device: the Agent's own choice there, else the device's default. */
+export const defaultChannelAgentDirectory = (
+ agencyConfig: Pick<LobeAgentAgencyConfig, 'workingDirByDevice'> | null | undefined,
+ deviceId: string,
+ deviceDefaultCwd?: string | null,
+): string | undefined =>
+ getWorkingDirEffectivePath(agencyConfig?.workingDirByDevice?.[deviceId]) ||
+ deviceDefaultCwd ||
+ undefined;
+
export const CHANNEL_LIMITS = {
/** Files attached to one message. */
attachments: 20,
@@ -212,6 +248,8 @@ export type ChannelAuditDetails = Record<string, boolean | number | string | str
/** Public client projection. No execution configuration, private topic or draft fields. */
export interface ChannelListItem {
+ /** The bound Agent of a direct conversation; null for a group. */
+ agentId: string | null;
/** Server-computed for the current member. */
canDelete: boolean;
createdAt: Date;
diff --git a/src/features/Channels/CreateChannel/PeopleOptions.tsx b/src/features/Channels/CreateChannel/PeopleOptions.tsx
index c4e08107ab8..96b4445ded8 100644
--- a/src/features/Channels/CreateChannel/PeopleOptions.tsx
+++ b/src/features/Channels/CreateChannel/PeopleOptions.tsx
@@ -22,7 +22,7 @@ export interface PeopleSelection {
value: ChannelPersonOption[];
}
-const usePersonName = () => {
+export const usePersonName = () => {
const { t } = useTranslation('channel');
return (person: ChannelPersonOption) => person.fullName || person.username || t('person');
};
diff --git a/src/features/Channels/CreateChannel/agentEnvironment.ts b/src/features/Channels/CreateChannel/agentEnvironment.ts
index e5268f6121a..67d6eca74f5 100644
--- a/src/features/Channels/CreateChannel/agentEnvironment.ts
+++ b/src/features/Channels/CreateChannel/agentEnvironment.ts
@@ -1,6 +1,10 @@
import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { DeviceListItem, LobeAgentAgencyConfig } from '@lobechat/types';
-import { getWorkingDirEffectivePath, isChannelRuntime } from '@lobechat/types';
+import {
+ defaultChannelAgentDevice,
+ defaultChannelAgentDirectory,
+ isChannelRuntime,
+} from '@lobechat/types';
import type { ChannelAgentSelection } from '@/services/channel';
@@ -38,12 +42,12 @@ const getRuntime = ({ agencyConfig, model }: ChannelAgentEnvironment) =>
const getDeviceDirectory = (deviceId: string | undefined, environment: ChannelAgentEnvironment) => {
if (!deviceId) return;
- const configured = environment.agencyConfig?.workingDirByDevice?.[deviceId];
- return (
- getWorkingDirEffectivePath(configured) ||
- (environment.devicesConfirmed
- ? environment.devices?.find((device) => device.deviceId === deviceId)?.defaultCwd || undefined
- : undefined)
+ return defaultChannelAgentDirectory(
+ environment.agencyConfig,
+ deviceId,
+ environment.devicesConfirmed
+ ? environment.devices?.find((device) => device.deviceId === deviceId)?.defaultCwd
+ : undefined,
);
};
@@ -53,13 +57,12 @@ export const createChannelAgentSelection = (
environment: ChannelAgentEnvironment,
): ChannelAgentSelection => {
const { agencyConfig, currentDeviceId, isDesktop, workspaceScoped } = environment;
- const target = agencyConfig?.executionTarget;
- if (target === 'none' || target === 'sandbox' || target === 'auto') return { agentId };
- const localDefault =
- isDesktop &&
- !workspaceScoped &&
- (target === 'local' || (target === undefined && getRuntime(environment) !== 'native'));
- const deviceId = agencyConfig?.boundDeviceId || (localDefault ? currentDeviceId : undefined);
+ const deviceId = defaultChannelAgentDevice({
+ agencyConfig,
+ localDeviceId: isDesktop ? currentDeviceId : undefined,
+ runtime: getRuntime(environment),
+ workspaceScoped,
+ });
if (!deviceId) return { agentId };
return { agentId, deviceId, workingDirectory: getDeviceDirectory(deviceId, environment) };
};
diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsx
index fc2b9c77286..5800b63ad0d 100644
--- a/src/features/Channels/CreateChannel/index.tsx
+++ b/src/features/Channels/CreateChannel/index.tsx
@@ -13,12 +13,18 @@ import type { ChannelAgentDraft } from './agentEnvironment';
import { canSubmitChannelAgents, toChannelAgentSelection } from './agentEnvironment';
import { defaultChannelTitle } from './channelTitle';
import { MemberSelection } from './MemberSelection';
+import { usePersonName } from './PeopleOptions';
import { getChannelSaveErrorKey } from './saveError';
import { useChannelAgentOptions } from './useChannelAgentOptions';
interface ExistingChannel {
/** Agents already in the Channel. */
agentIds: string[];
+ /**
+ * Set for a direct conversation, which stays one person and one Agent: inviting starts a new
+ * group with that Agent instead.
+ */
+ directAgentName?: string;
id: string;
/** People can be invited only into workspace Channels. */
workspaceId: string | null;
@@ -44,7 +50,8 @@ export const openCreateChannel = (onCreated?: (id: string) => void, projectId?:
openMemberDialog({ onCreated, projectId });
/** The single entry for adding people and Agents to an existing Channel. */
-export const openInviteMembers = (existing: ExistingChannel) => openMemberDialog({ existing });
+export const openInviteMembers = (existing: ExistingChannel, onCreated?: (id: string) => void) =>
+ openMemberDialog({ existing, onCreated });
/**
* Like starting a group chat: choose members first. The name is optional and defaults to the
@@ -60,6 +67,8 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>();
const options = useChannelAgentOptions(existing ? undefined : projectId);
+ const direct = existing?.directAgentName !== undefined;
+ const nameOf = usePersonName();
const dirty = !!title.trim() || agents.length > 0 || people.length > 0;
// A mask click must not drop what the user typed or picked; ✕ and Esc still close.
@@ -67,13 +76,16 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
setCanDismissByClickOutside(!dirty && !busy);
}, [busy, dirty, setCanDismissByClickOutside]);
- const autoTitle = defaultChannelTitle(
- agents.map(({ agentId }) =>
- agentDisplayName(
- options.agents?.find((agent) => agent.id === agentId),
- t('unnamedAgent'),
- ),
+ const agentNames = agents.map(({ agentId }) =>
+ agentDisplayName(
+ options.agents?.find((agent) => agent.id === agentId),
+ t('unnamedAgent'),
),
+ );
+ const autoTitle = defaultChannelTitle(
+ direct
+ ? [existing?.directAgentName || t('unnamedAgent'), ...agentNames, ...people.map(nameOf)]
+ : agentNames,
{
more: (names, count, total) => t('autoTitle.more', { count, names, total }),
separator: t('autoTitle.separator'),
@@ -88,7 +100,16 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
setError(undefined);
try {
const selections = agents.map(toChannelAgentSelection);
- if (existing) {
+ if (existing && direct) {
+ const id = await channelActions.createGroupFromDirect({
+ agents: selections,
+ channelId: existing.id,
+ title: title.trim() || autoTitle,
+ userIds: people.map((person) => person.userId),
+ });
+ close();
+ onCreated?.(id);
+ } else if (existing) {
await channelActions.addMembers(existing.id, {
agents: selections,
userIds: people.map((person) => person.userId),
@@ -113,6 +134,11 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
return (
<Flexbox gap={16}>
+ {direct && (
+ <Text fontSize={12} type="secondary">
+ {t('invite.directHint', { name: existing?.directAgentName || t('unnamedAgent') })}
+ </Text>
+ )}
<Flexbox gap={8} inert={busy}>
<MemberSelection
exclude={existing?.agentIds}
@@ -126,7 +152,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
onChange={setAgents}
/>
</Flexbox>
- {!existing && (
+ {(!existing || direct) && (
<Flexbox gap={6} inert={busy}>
<label htmlFor="channel-title" style={{ fontWeight: 500 }}>
{t('nameOptional')}
@@ -155,7 +181,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
{t('cancel')}
</Button>
<Button disabled={!canSubmit} loading={busy} type="primary" onClick={() => void submit()}>
- {t(existing ? 'invite.submit' : 'submit')}
+ {t(existing && !direct ? 'invite.submit' : 'submit')}
</Button>
</Flexbox>
</Flexbox>
diff --git a/src/features/Channels/MemberStatus.tsx b/src/features/Channels/MemberStatus.tsx
index 9393ae2005c..5fd63095426 100644
--- a/src/features/Channels/MemberStatus.tsx
+++ b/src/features/Channels/MemberStatus.tsx
@@ -5,11 +5,14 @@ import { UserPlus, Users } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCloseOnNavigate } from '@/hooks/useCloseOnNavigate';
+import { canInviteMembers } from './channelAccess';
import { openInviteMembers } from './CreateChannel';
import { FailureIndicator } from './FailureIndicator';
import { MemberList, StatusAvatar, useMemberEntries } from './MemberList';
+import { channelPath } from './paths';
import { statusStyles, styles } from './styles';
/** Header avatars before the rest fold into a count; the list shows everyone. */
@@ -29,10 +32,12 @@ export function MemberStatus({
const { t } = useTranslation('channel');
const [open, setOpen] = useState(false);
const popoverKey = useCloseOnNavigate(open, () => setOpen(false));
+ const navigate = useWorkspaceAwareNavigate();
const { channel, members: allMembers = [] } = detail;
- // An archived channel is read-only: no new members or environment changes until reopened.
- const manageable = channel.canDelete && channel.status !== 'archived';
const entries = useMemberEntries(detail);
+ const directAgent = channel.agentId
+ ? entries.find((entry) => entry.member.agentId === channel.agentId)
+ : undefined;
const overflow = entries.length - MAX_VISIBLE;
const title = t('membersCount', { count: entries.length });
@@ -78,20 +83,25 @@ export function MemberStatus({
</Button>
</Popover>
)}
- {manageable && (
+ {canInviteMembers(channel) && (
<ActionIcon
aria-label={t('invite.title')}
icon={UserPlus}
size="small"
title={t('invite.title')}
onClick={() =>
- openInviteMembers({
- agentIds: allMembers.flatMap((member) =>
- member.status === 'active' && member.agentId ? [member.agentId] : [],
- ),
- id: channel.id,
- workspaceId: channel.workspaceId,
- })
+ openInviteMembers(
+ {
+ agentIds: allMembers.flatMap((member) =>
+ member.status === 'active' && member.agentId ? [member.agentId] : [],
+ ),
+ directAgentName: channel.agentId ? (directAgent?.name ?? '') : undefined,
+ id: channel.id,
+ workspaceId: channel.workspaceId,
+ },
+ // Inviting from a direct conversation opens the group it starts.
+ (id) => navigate(channelPath(id)),
+ )
}
/>
)}
diff --git a/src/features/Channels/channelAccess.test.ts b/src/features/Channels/channelAccess.test.ts
index 29c515a101d..bf1711e64ab 100644
--- a/src/features/Channels/channelAccess.test.ts
+++ b/src/features/Channels/channelAccess.test.ts
@@ -1,7 +1,7 @@
import type { ChannelDetail } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { visibleChannelDetail } from './channelAccess';
+import { canInviteMembers, visibleChannelDetail } from './channelAccess';
describe('Channel access after revalidation', () => {
const cached = { channel: { title: 'Previously accessible' } } as ChannelDetail;
@@ -13,3 +13,16 @@ describe('Channel access after revalidation', () => {
expect(visibleChannelDetail(cached, undefined)).toBe(cached);
});
});
+
+describe('inviting members', () => {
+ const open = { canDelete: true, status: 'active' } as const;
+ it('lets an admin invite from an open Channel', () => {
+ expect(canInviteMembers(open)).toBe(true);
+ });
+ it.each([
+ ['a plain member', { canDelete: false }],
+ ['an archived Channel', { status: 'archived' as const }],
+ ])('offers no invite to %s', (_, override) => {
+ expect(canInviteMembers({ ...open, ...override })).toBe(false);
+ });
+});
diff --git a/src/features/Channels/channelAccess.ts b/src/features/Channels/channelAccess.ts
index 09598136cad..58ea4b63de3 100644
--- a/src/features/Channels/channelAccess.ts
+++ b/src/features/Channels/channelAccess.ts
@@ -1,4 +1,4 @@
-import type { ChannelDetail } from '@lobechat/types';
+import type { ChannelDetail, ChannelListItem } from '@lobechat/types';
import { isTrpcErrorCode } from '@/utils/trpcError';
@@ -9,3 +9,10 @@ export const visibleChannelDetail = (cached: ChannelDetail | undefined, error: u
isTrpcErrorCode(error, 'UNAUTHORIZED')
? undefined
: cached;
+
+/**
+ * Inviting needs an admin of an open Channel; archived Channels take no new members until
+ * reopened. Inviting from a direct conversation starts a new group instead of joining it.
+ */
+export const canInviteMembers = (channel: Pick<ChannelListItem, 'canDelete' | 'status'>) =>
+ channel.canDelete && channel.status !== 'archived';
diff --git a/src/services/agent.ts b/src/services/agent.ts
index b031f345ed5..88e7dcf92b7 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -75,6 +75,8 @@ const normalizeMarketAgentModel = (config?: PartialDeep<AgentItem>): PartialDeep
export interface CreateAgentParams {
config?: PartialDeep<AgentItem>;
groupId?: string;
+ /** This desktop's gateway device, where the creator's direct Channel to a local Agent runs. */
+ localDeviceId?: string;
/**
* `private` keeps the agent visible only to its creator within the active
* workspace; `public` (default) makes it visible to every member. The
@@ -143,6 +145,7 @@ class AgentService {
return lambdaClient.agent.createAgent.mutate({
config: normalizedConfig as any,
groupId: params.groupId,
+ localDeviceId: params.localDeviceId,
visibility: params.visibility,
});
};
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 461cf38ec3b..d04740742b4 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -40,6 +40,12 @@ class ChannelService {
lambdaClient.channel.addAgent.mutate({ agent, channelId });
create = (input: { agents: ChannelAgentSelection[]; projectId?: string; title: string }) =>
lambdaClient.channel.create.mutate(input);
+ createGroupFromDirect = (input: {
+ agents: ChannelAgentSelection[];
+ channelId: string;
+ title: string;
+ userIds: string[];
+ }) => lambdaClient.channel.createGroupFromDirect.mutate(input);
detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>
(await lambdaClient.channel.detail.query(params)).data;
list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;
diff --git a/src/store/agent/slices/agent/action.createAgentChannel.test.ts b/src/store/agent/slices/agent/action.createAgentChannel.test.ts
new file mode 100644
index 00000000000..f1dd3e51036
--- /dev/null
+++ b/src/store/agent/slices/agent/action.createAgentChannel.test.ts
@@ -0,0 +1,89 @@
+import type * as ConstModule from '@lobechat/const';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { refreshChannelListIfEnabled } from '@/store/channel/refreshIfEnabled';
+
+import { useAgentStore } from '../../store';
+
+const mocks = vi.hoisted(() => ({ isDesktop: false, resolveGatewayDeviceId: vi.fn() }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof ConstModule>()),
+ get isDesktop() {
+ return mocks.isDesktop;
+ },
+}));
+
+vi.mock('@/services/agent', () => ({
+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
+ agentService: { createAgent: vi.fn() },
+}));
+
+vi.mock('@/store/channel/refreshIfEnabled', () => ({ refreshChannelListIfEnabled: vi.fn() }));
+
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ resolveGatewayDeviceId: mocks.resolveGatewayDeviceId }),
+}));
+
+const params = { config: { name: 'Ada', title: 'Math Tutor' } };
+
+describe('createAgent direct Channel', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ mocks.isDesktop = false;
+ });
+
+ it("refetches Channels once the server created the Agent and its creator's direct Channel", async () => {
+ vi.mocked(agentService.createAgent).mockImplementation(async () => {
+ expect(refreshChannelListIfEnabled).not.toHaveBeenCalled();
+ return { agentId: 'agent-new' };
+ });
+ const { result } = renderHook(() => useAgentStore());
+
+ await act(async () => {
+ await result.current.createAgent(params);
+ });
+
+ expect(refreshChannelListIfEnabled).toHaveBeenCalledTimes(1);
+ });
+
+ it('names this desktop so a local Agent can answer in its direct Channel here', async () => {
+ mocks.isDesktop = true;
+ mocks.resolveGatewayDeviceId.mockResolvedValue('desktop-device');
+ vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-new' });
+ const { result } = renderHook(() => useAgentStore());
+
+ await act(async () => {
+ await result.current.createAgent(params);
+ });
+
+ expect(vi.mocked(agentService.createAgent).mock.calls[0][0].localDeviceId).toBe(
+ 'desktop-device',
+ );
+ });
+
+ it('sends no device from the web', async () => {
+ vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-new' });
+ const { result } = renderHook(() => useAgentStore());
+
+ await act(async () => {
+ await result.current.createAgent(params);
+ });
+
+ expect(mocks.resolveGatewayDeviceId).not.toHaveBeenCalled();
+ expect(vi.mocked(agentService.createAgent).mock.calls[0][0].localDeviceId).toBeUndefined();
+ });
+
+ it('refetches nothing when the Agent was not created', async () => {
+ vi.mocked(agentService.createAgent).mockRejectedValue(new Error('forbidden'));
+ const { result } = renderHook(() => useAgentStore());
+
+ await act(async () => {
+ await expect(result.current.createAgent(params)).rejects.toThrow('forbidden');
+ });
+
+ expect(refreshChannelListIfEnabled).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index be8ee1ca270..bb4acce1ff8 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -28,7 +28,9 @@ import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@
import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';
import { resolveAgentDocumentsContext } from '@/services/agentDocument';
import { aiAgentService } from '@/services/aiAgent';
+import { refreshChannelListIfEnabled } from '@/store/channel/refreshIfEnabled';
import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
+import { getElectronStoreState } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
// Projection module only (no store import), so this does not cycle through the home store.
@@ -328,8 +330,14 @@ export class AgentSliceActionImpl {
: randomAgentName(locale, await getSidebarAgentNames())),
};
- const result = await agentService.createAgent({ ...params, config });
+ // On desktop, name this machine so a direct Channel to a local Agent can run here.
+ const localDeviceId = isDesktop
+ ? await getElectronStoreState().resolveGatewayDeviceId()
+ : undefined;
+ const result = await agentService.createAgent({ ...params, config, localDeviceId });
this.#get().invalidateAvailableAgents();
+ // The server opened the creator's direct Channel to the new Agent alongside it.
+ refreshChannelListIfEnabled();
const userId = userProfileSelectors.userId(getUserStoreState());
diff --git a/src/store/channel/action.test.ts b/src/store/channel/action.test.ts
index aa27acaea80..8c7c63d2350 100644
--- a/src/store/channel/action.test.ts
+++ b/src/store/channel/action.test.ts
@@ -7,6 +7,7 @@ vi.mock('@/services/channel', () => ({
addAgent: vi.fn(),
addUser: vi.fn(),
create: vi.fn(),
+ createGroupFromDirect: vi.fn(),
detail: vi.fn(),
list: vi.fn(),
send: vi.fn(),
@@ -35,6 +36,23 @@ describe('channelActions after a committed write', () => {
expect(channelService.create).toHaveBeenCalledTimes(1);
});
+ it('opens the group started from a direct conversation even when the list refresh fails', async () => {
+ vi.mocked(channelService.createGroupFromDirect).mockResolvedValue({
+ data: { channel: { id: 'chn_000000000002' } },
+ } as never);
+ vi.mocked(channelService.list).mockRejectedValue(new Error('offline'));
+ const input = {
+ agents: [],
+ channelId: 'chn_000000000001',
+ title: 'Ada, Mia',
+ userIds: ['user-mia'],
+ };
+
+ await expect(channelActions.createGroupFromDirect(input)).resolves.toBe('chn_000000000002');
+ expect(channelService.createGroupFromDirect).toHaveBeenCalledExactlyOnceWith(input);
+ expect(channelService.list).toHaveBeenCalled();
+ });
+
it('settles added members even when the detail refresh fails', async () => {
vi.mocked(channelService.addAgent).mockResolvedValue({} as never);
vi.mocked(channelService.detail).mockRejectedValue(new Error('offline'));
diff --git a/src/store/channel/action.ts b/src/store/channel/action.ts
index 5e5cc040534..2190e1d12cb 100644
--- a/src/store/channel/action.ts
+++ b/src/store/channel/action.ts
@@ -55,6 +55,14 @@ class ChannelActionImpl {
await this.#refreshAfterWrite(this.refreshList);
return result.data.channel.id;
};
+ /** Inviting into a direct conversation starts a new group; the conversation stays as it is. */
+ createGroupFromDirect = async (
+ input: Parameters<typeof channelService.createGroupFromDirect>[0],
+ ) => {
+ const result = await channelService.createGroupFromDirect(input);
+ await this.#refreshAfterWrite(this.refreshList);
+ return result.data.channel.id;
+ };
remove = async (channelId: string) => {
const scope = cacheScope.get();
// Optimistically hide the row; failure restores it. Keep the open conversation
diff --git a/src/store/channel/refreshIfEnabled.test.ts b/src/store/channel/refreshIfEnabled.test.ts
new file mode 100644
index 00000000000..3230fc0dc4f
--- /dev/null
+++ b/src/store/channel/refreshIfEnabled.test.ts
@@ -0,0 +1,49 @@
+import { waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { refreshChannelListIfEnabled } from './refreshIfEnabled';
+
+const mocks = vi.hoisted(() => ({
+ enableChannels: false as boolean | undefined,
+ refreshList: vi.fn(),
+}));
+
+vi.mock('@/store/serverConfig', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getServerConfigStoreState: () => ({ featureFlags: { enableChannels: mocks.enableChannels } }),
+}));
+
+vi.mock('@/store/channel', () => ({ channelActions: { refreshList: mocks.refreshList } }));
+
+describe('refreshChannelListIfEnabled', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.enableChannels = false;
+ });
+
+ it.each([false, undefined])(
+ 'leaves the Channel list alone while Channels are %s',
+ async (flag) => {
+ mocks.enableChannels = flag;
+ refreshChannelListIfEnabled();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mocks.refreshList).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refetches the Channel list while Channels are on', async () => {
+ mocks.enableChannels = true;
+ mocks.refreshList.mockResolvedValue(undefined);
+ refreshChannelListIfEnabled();
+ await waitFor(() => expect(mocks.refreshList).toHaveBeenCalledTimes(1));
+ });
+
+ it('logs a failed refetch instead of throwing into the caller', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.enableChannels = true;
+ mocks.refreshList.mockRejectedValue(new Error('offline'));
+ expect(() => refreshChannelListIfEnabled()).not.toThrow();
+ await waitFor(() => expect(error).toHaveBeenCalledWith(expect.any(String), expect.any(Error)));
+ error.mockRestore();
+ });
+});
diff --git a/src/store/channel/refreshIfEnabled.ts b/src/store/channel/refreshIfEnabled.ts
new file mode 100644
index 00000000000..14475828cbb
--- /dev/null
+++ b/src/store/channel/refreshIfEnabled.ts
@@ -0,0 +1,14 @@
+import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
+
+/**
+ * With Channels on, the server opens a Channel alongside some creations (a new project's default
+ * Channel, a new Agent's direct conversation); refetch the Channel list instead of waiting for its
+ * idle poll. The Channel store loads on demand, so callers outside Channels do not pull it in.
+ */
+export const refreshChannelListIfEnabled = (): void => {
+ const serverConfig = getServerConfigStoreState();
+ if (!serverConfig || !serverConfigSelectors.enableChannels(serverConfig)) return;
+ void import('@/store/channel')
+ .then(({ channelActions }) => channelActions.refreshList())
+ .catch((error) => console.error('[channel] failed to refresh the Channel list', error));
+};
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 446c9943ce2..35730e0640e 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -17,10 +17,10 @@ import {
type ProjectKnowledgeBaseBindingPatch,
projectService,
} from '@/services/project';
+import { refreshChannelListIfEnabled } from '@/store/channel/refreshIfEnabled';
import { createDevtools } from '@/store/middleware/createDevtools';
import { expose } from '@/store/middleware/expose';
import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
-import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import {
PROJECT_LIST_KEY,
@@ -114,18 +114,6 @@ const syncProjectFavorite = (project: Pick<ProjectListItem, 'avatar' | 'id' | 'n
.catch((error) => console.error('[project] failed to sync the favorite snapshot', error));
};
-/**
- * With Channels on, the server opens a new project's default Channel alongside it; refetch the
- * Channel list instead of waiting for its idle poll. Loaded on demand, like the favorite sync.
- */
-const refreshChannels = (): void => {
- const serverConfig = getServerConfigStoreState();
- if (!serverConfig || !serverConfigSelectors.enableChannels(serverConfig)) return;
- void import('@/store/channel')
- .then(({ channelActions }) => channelActions.refreshList())
- .catch((error) => console.error('[project] failed to refresh Channels', error));
-};
-
export const useProjectStore = createWithEqualityFn<ProjectStore>()(
devtools((set, get) => {
const list = createReplicaSlice(projectListResource, {
@@ -206,7 +194,7 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(
items && !items.some((item) => item.id === project.id) ? [project, ...items] : items,
);
void refreshList();
- refreshChannels();
+ refreshChannelListIfEnabled();
return project;
},
deleteProject: async (id) => {