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 General channel with each new project (#21996)

AmAzing-69e2a6756063
diff --git a/apps/server/src/routers/lambda/__tests__/project.create.test.ts b/apps/server/src/routers/lambda/__tests__/project.create.test.ts
index 76d5ba14d18..860eac0649e 100644
--- a/apps/server/src/routers/lambda/__tests__/project.create.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/project.create.test.ts
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
assertCanPerformResourceAction: vi.fn(),
create: vi.fn(),
+ createDefaultChannel: vi.fn(),
resolveCoordinatorAgents: vi.fn(),
}));
@@ -32,6 +33,10 @@ vi.mock('@/database/repositories/projectCoordinator', () => ({
}),
}));
+vi.mock('@/server/services/channel/defaultChannel', () => ({
+ createDefaultChannel: mocks.createDefaultChannel,
+}));
+
vi.mock('@/server/services/resourcePermission', () => ({
assertCanPerformResourceAction: mocks.assertCanPerformResourceAction,
}));
@@ -44,7 +49,11 @@ const caller = (workspaceId?: string) =>
describe('project.create with a picked main agent', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.create.mockResolvedValue({ coordinatorAgentId: 'agent-1', id: 'project-1' });
+ mocks.create.mockResolvedValue({
+ coordinatorAgentId: 'agent-1',
+ id: 'project-1',
+ name: 'Launch',
+ });
mocks.resolveCoordinatorAgents.mockImplementation(async (projects) => projects);
});
@@ -81,3 +90,34 @@ describe('project.create with a picked main agent', () => {
expect(mocks.assertCanPerformResourceAction).not.toHaveBeenCalled();
});
});
+
+describe('project.create default Channel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.create.mockResolvedValue({ coordinatorAgentId: null, id: 'project-1', name: 'Launch' });
+ mocks.resolveCoordinatorAgents.mockImplementation(async (projects) =>
+ projects.map((project: object) => ({ ...project, coordinatorAgentId: 'inbox' })),
+ );
+ });
+
+ it('opens the project Channel with its resolved main agent in the caller scope', async () => {
+ const result = await caller('ws-1').create({ name: 'Launch' });
+
+ expect(mocks.createDefaultChannel).toHaveBeenCalledWith({
+ agentId: 'inbox',
+ db: {},
+ projectId: 'project-1',
+ userId: 'member',
+ workspaceId: 'ws-1',
+ });
+ expect(result.data).toMatchObject({ coordinatorAgentId: 'inbox', id: 'project-1' });
+ });
+
+ it('opens a personal project Channel outside any workspace', async () => {
+ await caller().create({ name: 'Launch' });
+
+ expect(mocks.createDefaultChannel).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'project-1', workspaceId: undefined }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index e299cc13cd1..7f5b8a6d7f5 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -12,6 +12,7 @@ import { ProjectCoordinatorRepository } from '@/database/repositories/projectCoo
import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createDefaultChannel } from '@/server/services/channel/defaultChannel';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
/**
@@ -187,11 +188,15 @@ export const projectRouter = router({
if (input.coordinatorAgentId) {
await assertResourceUsable(ctx, 'agent', input.coordinatorAgentId);
}
- return {
- data: await withMainAgent(ctx.projectModel, await ctx.projectModel.create(input)),
- message: 'Project created',
- success: true,
- };
+ const project = await withMainAgent(ctx.projectModel, await ctx.projectModel.create(input));
+ await createDefaultChannel({
+ agentId: project.coordinatorAgentId,
+ db: ctx.serverDB,
+ projectId: project.id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data: project, message: 'Project created', success: true };
} catch (error) {
mapProjectError(error, 'create');
}
diff --git a/apps/server/src/services/channel/ChannelService.default.test.ts b/apps/server/src/services/channel/ChannelService.default.test.ts
new file mode 100644
index 00000000000..cbf2995a848
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelService.default.test.ts
@@ -0,0 +1,79 @@
+// @vitest-environment node
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelService } from './ChannelService';
+
+const { create, getAgent, getBuiltinAgent } = vi.hoisted(() => ({
+ create: vi.fn(),
+ getAgent: vi.fn(),
+ getBuiltinAgent: vi.fn(),
+}));
+vi.mock('@/database/repositories/channel', async (original) => ({
+ ...(await original<object>()),
+ ChannelRepository: class {
+ create = create;
+ },
+}));
+vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));
+vi.mock('@/server/services/agent', () => ({
+ AgentService: class {
+ getAgentConfigById = getAgent;
+ getBuiltinAgent = getBuiltinAgent;
+ },
+}));
+vi.mock('@/server/services/file', () => ({ FileService: class {} }));
+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));
+
+describe('the default Channel of a new workspace or project', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ create.mockResolvedValue({ channel: { id: 'chn_1' } });
+ getBuiltinAgent.mockResolvedValue({ id: 'agt_lobeai', model: 'gpt-5' });
+ });
+ const createDefault = () =>
+ new ChannelService({} as never, 'owner', 'workspace').createDefault({
+ agentId: 'agt_main',
+ projectId: 'pro_1',
+ title: 'General',
+ });
+
+ it('seats a native main Agent next to its creator', async () => {
+ getAgent.mockResolvedValue({ model: 'gpt-5' });
+ await createDefault();
+ expect(getBuiltinAgent).not.toHaveBeenCalled();
+ expect(create).toHaveBeenCalledWith({
+ agents: [{ agentId: 'agt_main' }],
+ projectId: 'pro_1',
+ title: 'General',
+ });
+ });
+
+ it.each([
+ ['an external main Agent, which needs a device', { model: 'claude-code' }],
+ [
+ 'an Agent with a heterogeneous provider',
+ { agencyConfig: { heterogeneousProvider: { type: 'codex' } }, model: 'gpt-5' },
+ ],
+ ['a main Agent the creator cannot reach', undefined],
+ ])('lets the scope LobeAI answer instead of %s', async (_, agent) => {
+ getAgent.mockResolvedValue(agent);
+ await createDefault();
+ expect(getBuiltinAgent).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.inbox);
+ expect(create).toHaveBeenCalledWith({
+ agents: [{ agentId: 'agt_lobeai' }],
+ projectId: 'pro_1',
+ title: 'General',
+ });
+ });
+
+ it('opens no Channel that nobody could answer in', async () => {
+ getAgent.mockResolvedValue({ model: 'claude-code' });
+ getBuiltinAgent.mockResolvedValue(null);
+ await expect(createDefault()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(create).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index ee705c1c4fa..38cfd9c6ad5 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -1,3 +1,4 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import { isChannelRuntime } from '@lobechat/types';
@@ -29,6 +30,13 @@ export interface ChannelAgentSelection {
workingDirectory?: string;
}
+type ChannelAgentConfig = NonNullable<Awaited<ReturnType<AgentService['getAgentConfigById']>>>;
+
+/** An Agent's own runtime: external when it names a heterogeneous provider or model. */
+const agentRuntime = (agent: Pick<ChannelAgentConfig, 'agencyConfig' | 'model'>) =>
+ agent.agencyConfig?.heterogeneousProvider?.type ??
+ (isHeterogeneousAgentModelId(agent.model) ? agent.model : 'native');
+
export class ChannelService {
readonly repository: ChannelRepository;
private readonly agentService: AgentService;
@@ -49,9 +57,7 @@ export class ChannelService {
private async resolveAgent(input: ChannelAgentSelection): Promise<ChannelAddAgentInput> {
const agent = await this.agentService.getAgentConfigById(input.agentId);
if (!agent) throw new ChannelError('NOT_FOUND', 'Agent not found');
- const runtime =
- agent.agencyConfig?.heterogeneousProvider?.type ??
- (isHeterogeneousAgentModelId(agent.model) ? agent.model : 'native');
+ const runtime = agentRuntime(agent);
if (!isChannelRuntime(runtime))
throw new ChannelError('BAD_REQUEST', 'Unsupported Channel runtime');
const config: NonNullable<ChannelAddAgentInput['config']> = {};
@@ -123,6 +129,32 @@ export class ChannelService {
return this.repository.create({ agents, projectId: input.projectId, title: input.title });
};
+ /**
+ * The Channel a new workspace or project starts with. Callers pass a project they just created
+ * in this scope, so its readability is not checked again.
+ */
+ createDefault = async (input: { agentId: string; projectId?: string; title: string }) => {
+ const agentId = await this.defaultChannelAgent(input.agentId);
+ return this.repository.create({
+ agents: [{ agentId }],
+ projectId: input.projectId,
+ title: input.title,
+ });
+ };
+
+ /**
+ * 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.
+ */
+ private async defaultChannelAgent(agentId: string) {
+ const agent = await this.agentService.getAgentConfigById(agentId);
+ if (agent && agentRuntime(agent) === 'native') return agentId;
+ const inbox = await this.agentService.getBuiltinAgent(BUILTIN_AGENT_SLUGS.inbox);
+ if (!inbox?.id || agentRuntime(inbox) !== 'native')
+ throw new ChannelError('NOT_FOUND', 'No Agent can answer in the default Channel');
+ return inbox.id;
+ }
+
addAgent = async (channelId: string, input: ChannelAgentSelection) => {
// Check membership before probing a device; the write rechecks the current admin role.
if (!(await this.repository.findAccess(channelId)))
diff --git a/apps/server/src/services/channel/defaultChannel.test.ts b/apps/server/src/services/channel/defaultChannel.test.ts
new file mode 100644
index 00000000000..ea63ea1e3df
--- /dev/null
+++ b/apps/server/src/services/channel/defaultChannel.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createDefaultChannel, DEFAULT_CHANNEL_TITLE } from './defaultChannel';
+
+const { ChannelServiceCtor, createDefault, getFlags } = vi.hoisted(() => ({
+ ChannelServiceCtor: vi.fn(),
+ createDefault: vi.fn(),
+ getFlags: vi.fn(),
+}));
+vi.mock('@/server/featureFlags', () => ({ getServerFeatureFlagsStateFromRuntimeConfig: getFlags }));
+vi.mock('./ChannelService', () => ({
+ ChannelService: vi.fn(function (...args: unknown[]) {
+ ChannelServiceCtor(...args);
+ return { createDefault };
+ }),
+}));
+
+const db = {} as never;
+const params = { agentId: 'agt_main', db, userId: 'owner' };
+
+describe('createDefaultChannel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getFlags.mockResolvedValue({ enableChannels: true });
+ createDefault.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 createDefaultChannel({ ...params, projectId: 'pro_1', workspaceId: 'ws_1' });
+ expect(getFlags).toHaveBeenCalledWith('owner');
+ expect(createDefault).not.toHaveBeenCalled();
+ },
+ );
+
+ it('opens a General workspace Channel with the creator and the main Agent', async () => {
+ await createDefaultChannel({ ...params, workspaceId: 'ws_1' });
+ expect(ChannelServiceCtor).toHaveBeenCalledWith(db, 'owner', 'ws_1');
+ expect(createDefault).toHaveBeenCalledWith({
+ agentId: 'agt_main',
+ projectId: undefined,
+ title: 'General',
+ });
+ });
+
+ it('groups a project Channel under the project in its own scope', async () => {
+ await createDefaultChannel({ ...params, projectId: 'pro_1' });
+ expect(ChannelServiceCtor).toHaveBeenCalledWith(db, 'owner', undefined);
+ expect(createDefault).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'pro_1', title: DEFAULT_CHANNEL_TITLE }),
+ );
+ });
+
+ it('never fails the creation it follows', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ createDefault.mockRejectedValue(new Error('connection reset'));
+ await expect(createDefaultChannel(params)).resolves.toBeUndefined();
+ getFlags.mockRejectedValue(new Error('config unavailable'));
+ await expect(createDefaultChannel(params)).resolves.toBeUndefined();
+ expect(error).toHaveBeenCalledTimes(2);
+ 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
new file mode 100644
index 00000000000..31433e95d6f
--- /dev/null
+++ b/apps/server/src/services/channel/defaultChannel.ts
@@ -0,0 +1,46 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { ChannelService } from './ChannelService';
+import { isChannelEnabled } from './featureGate';
+
+/** Title of the Channel a new workspace or project starts with; members can rename it. */
+export const DEFAULT_CHANNEL_TITLE = 'General';
+
+export interface DefaultChannelParams {
+ /** The scope's main Agent: a workspace's LobeAI, or a project's main agent. */
+ agentId: string;
+ db: LobeChatDatabase;
+ projectId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * 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.
+ */
+export const createDefaultChannel = async ({
+ agentId,
+ db,
+ projectId,
+ userId,
+ workspaceId,
+}: DefaultChannelParams) => {
+ try {
+ if (!(await isChannelEnabled(userId))) return;
+ await new ChannelService(db, userId, workspaceId).createDefault({
+ agentId,
+ projectId,
+ title: DEFAULT_CHANNEL_TITLE,
+ });
+ } catch (error) {
+ console.error('[channel] Failed to create the default channel', {
+ agentId,
+ error,
+ projectId,
+ userId,
+ workspaceId,
+ });
+ }
+};
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index a70e9eafd94..52209d0a024 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -4,6 +4,7 @@ import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';
import { and, asc, desc, eq, inArray, isNull, max, ne, or, sql } from 'drizzle-orm';
import { agents } from '../schemas/agent';
+import { channelMembers } from '../schemas/channel';
import { chatGroupsAgents } from '../schemas/chatGroup';
import { environments } from '../schemas/environment';
import { knowledgeBases } from '../schemas/file';
@@ -228,7 +229,7 @@ export class ProjectModel {
/**
* A coordinator provisioned for one project: a virtual, non-builtin agent no
- * other project leads or counts as a member, and no group or session holds.
+ * other project leads or counts as a member, and no group, session or Channel holds.
*/
async isDedicatedCoordinator(
agentId: string,
@@ -266,8 +267,9 @@ export class ProjectModel {
if (stillUsed) return false;
// A group's own members are virtual and slugless as well; they belong to the group.
- // A session link would take the agent's conversations with it on delete, and a
- // member of another project would drop out of it.
+ // A session link would take the agent's conversations with it on delete, a member of
+ // another project would drop out of it, and a Channel (such as the project's default
+ // General, which outlives the project) would be left with no Agent to answer.
const [linked] = await db
.select({ agentId: chatGroupsAgents.agentId })
.from(chatGroupsAgents)
@@ -278,6 +280,13 @@ export class ProjectModel {
.from(agentsToSessions)
.where(eq(agentsToSessions.agentId, agentId)),
)
+ .union(
+ db
+ // Nullable column, but the filter below pins it to this agent.
+ .select({ agentId: sql<string>`${channelMembers.agentId}` })
+ .from(channelMembers)
+ .where(and(eq(channelMembers.agentId, agentId), eq(channelMembers.status, 'active'))),
+ )
.union(
db
.select({ agentId: projectAgents.agentId })
diff --git a/packages/database/src/repositories/channel/__tests__/agentMember.test.ts b/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
index c70700096ae..f4f831c6eae 100644
--- a/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';
import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -64,6 +65,16 @@ describe('adding an Agent to a Channel', () => {
expect(added).toMatchObject({ agentId: agent.id, config: {}, name: 'Current Agent name' });
});
+ it('labels LobeAI by its product name, not the generic fallback', async () => {
+ const team = await fixture.createTeamChannel();
+ const [inbox] = await db
+ .insert(agents)
+ .values({ slug: INBOX_SESSION_ID, userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const added = await team.asOwner.addAgent(team.channel.id, { agentId: inbox.id });
+ expect(added.name).toBe(DEFAULT_INBOX_TITLE);
+ });
+
// Retrying a batch that partly succeeded resubmits the members that already joined.
it('returns the existing member when the same Agent is added again', async () => {
const team = await fixture.createTeamChannel();
diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.ts
index 1948619de3c..50076456358 100644
--- a/packages/database/src/repositories/channel/agent.ts
+++ b/packages/database/src/repositories/channel/agent.ts
@@ -11,6 +11,7 @@ import { agents, channelMembers, userSettings } from '../../schemas';
import type { Transaction } from '../../type';
import { agentUsableByWhere } from '../../utils/agent-access';
import { mergeAgentDefaultConfig } from '../../utils/agentConfig';
+import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';
import { ChannelError } from './error';
/** Explicitly select environment fields so legacy or untyped copies cannot override an Agent. */
@@ -37,12 +38,13 @@ export const requireChannelAgent = async (
agentId: string,
) => {
const [agent] = await tx
- .select({ name: agents.name, title: agents.title })
+ .select({ name: agents.name, slug: agents.slug, title: agents.title })
.from(agents)
.where(agentUsableByWhere(agentId, { userId, workspaceId: workspaceId ?? undefined }))
.for('share');
if (!agent) throw new ChannelError('NOT_FOUND', 'Agent not found');
- return agent;
+ // LobeAI rows are stored without a title; label it the way the rest of the product does.
+ return { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) };
};
/** Called under the Channel lock after the caller's admin role has been checked. */
diff --git a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
index 3ee58a55938..5f772a1df3f 100644
--- a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
@@ -1,4 +1,4 @@
-import { eq } from 'drizzle-orm';
+import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
@@ -10,6 +10,7 @@ import {
agentDocuments,
agents,
briefs,
+ channelMembers,
chatGroups,
chatGroupsAgents,
dashboards,
@@ -21,6 +22,7 @@ import {
users,
widgets,
} from '../../../schemas';
+import { ChannelRepository } from '../../channel';
import { ProjectCoordinatorRepository } from '../index';
const serverDB = await getTestDB();
@@ -202,6 +204,31 @@ describe('ProjectCoordinatorRepository.replaceCoordinator', () => {
);
});
+ it('keeps a coordinator that answers in a Channel when it is replaced', async () => {
+ const project = await createProject({ name: 'Default channel' });
+ const coordinatorId = project.coordinatorAgentId;
+ const { channel } = await new ChannelRepository(serverDB, userId).create({
+ agents: [{ agentId: coordinatorId }],
+ projectId: project.id,
+ title: 'General',
+ });
+ const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });
+
+ await repo.replaceCoordinator(project.id, lead.id);
+
+ expect(await serverDB.select().from(agents).where(eq(agents.id, coordinatorId))).toHaveLength(
+ 1,
+ );
+ expect(
+ await serverDB
+ .select({ agentId: channelMembers.agentId })
+ .from(channelMembers)
+ .where(
+ and(eq(channelMembers.channelId, channel.id), eq(channelMembers.actorType, 'agent')),
+ ),
+ ).toEqual([{ agentId: coordinatorId }]);
+ });
+
it('keeps a reusable main agent as a member when it is replaced', async () => {
const project = await createProject({ name: 'Rotation' });
const agentModel = new AgentModel(serverDB, userId);
diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.ts
index e0bbdc89634..471fe6310b8 100644
--- a/src/store/project/store.test.ts
+++ b/src/store/project/store.test.ts
@@ -28,10 +28,21 @@ import {
const mocks = vi.hoisted(() => ({
activeWorkspaceId: null as string | null,
+ enableChannels: false,
+ refreshChannelList: vi.fn(),
refreshProjectTopics: vi.fn(),
syncFavoriteSnapshot: vi.fn(),
}));
+vi.mock('@/store/serverConfig', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getServerConfigStoreState: () => ({ featureFlags: { enableChannels: mocks.enableChannels } }),
+}));
+
+vi.mock('@/store/channel', () => ({
+ channelActions: { refreshList: mocks.refreshChannelList },
+}));
+
vi.mock('@/store/projectWorkingDirectory', () => ({
useProjectDirectoryStore: {
getState: () => ({ refreshProjectTopics: mocks.refreshProjectTopics }),
@@ -99,6 +110,7 @@ describe('project store replicas', () => {
beforeEach(() => {
mocks.activeWorkspaceId = null;
+ mocks.enableChannels = false;
useScope(`project-user-${randomUUID()}:personal`);
act(() => useProjectStore.setState(initialProjectState));
});
@@ -464,6 +476,20 @@ describe('project store replicas', () => {
);
expect(useProjectStore.getState().projectListMap.all[0].id).toBe('p3');
});
+ it("refetches Channels for the new project's default Channel only while they are on", async () => {
+ seed();
+ await waitSeeded();
+ vi.mocked(projectService.create).mockResolvedValue(ok(project('p3', 'Launch')) as any);
+ vi.mocked(projectService.listAll).mockImplementation(pending);
+ mocks.refreshChannelList.mockResolvedValue(undefined);
+
+ await act(() => useProjectStore.getState().createProject({ name: 'Launch' }));
+ expect(mocks.refreshChannelList).not.toHaveBeenCalled();
+
+ mocks.enableChannels = true;
+ await act(() => useProjectStore.getState().createProject({ name: 'Launch' }));
+ await waitFor(() => expect(mocks.refreshChannelList).toHaveBeenCalledTimes(1));
+ });
it('refreshes a favorited project when its name or logo changes', async () => {
seed();
await waitSeeded();
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 5969320ec8a..446c9943ce2 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -20,6 +20,7 @@ import {
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,
@@ -113,6 +114,18 @@ 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, {
@@ -193,6 +206,7 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(
items && !items.some((item) => item.id === project.id) ? [project, ...items] : items,
);
void refreshList();
+ refreshChannels();
return project;
},
deleteProject: async (id) => {