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): name a project's default Channel after its project on the server (#23647)

Arvin Xua417193f33d5
diff --git a/apps/server/src/services/channel/ChannelService.default.test.ts b/apps/server/src/services/channel/ChannelService.default.test.ts
index cbf2995a848..e51339c1cc9 100644
--- a/apps/server/src/services/channel/ChannelService.default.test.ts
+++ b/apps/server/src/services/channel/ChannelService.default.test.ts
@@ -47,11 +47,25 @@ describe('the default Channel of a new workspace or project', () => {
expect(getBuiltinAgent).not.toHaveBeenCalled();
expect(create).toHaveBeenCalledWith({
agents: [{ agentId: 'agt_main' }],
+ metadata: { projectDefault: true },
projectId: 'pro_1',
title: 'General',
});
});
+ it("marks no workspace's default Channel as a project's", async () => {
+ getAgent.mockResolvedValue({ model: 'gpt-5' });
+ await new ChannelService({} as never, 'owner', 'workspace').createDefault({
+ agentId: 'agt_main',
+ title: 'General',
+ });
+ expect(create).toHaveBeenCalledWith({
+ agents: [{ agentId: 'agt_main' }],
+ projectId: undefined,
+ title: 'General',
+ });
+ });
+
it.each([
['an external main Agent, which needs a device', { model: 'claude-code' }],
[
@@ -65,6 +79,7 @@ describe('the default Channel of a new workspace or project', () => {
expect(getBuiltinAgent).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.inbox);
expect(create).toHaveBeenCalledWith({
agents: [{ agentId: 'agt_lobeai' }],
+ metadata: { projectDefault: true },
projectId: 'pro_1',
title: 'General',
});
diff --git a/apps/server/src/services/channel/ChannelService.environment.test.ts b/apps/server/src/services/channel/ChannelService.environment.test.ts
index 58a4b59b326..62fb3781410 100644
--- a/apps/server/src/services/channel/ChannelService.environment.test.ts
+++ b/apps/server/src/services/channel/ChannelService.environment.test.ts
@@ -167,7 +167,9 @@ describe('changing an Agent member’s channel environment', () => {
it('creates a member in the device home folder when the Agent has no directory there', async () => {
querySystemInfo.mockResolvedValue({ homePath: '/Users/me' });
statPath.mockResolvedValue({ canonicalPath: '/Users/me', isDirectory: true });
- create.mockResolvedValue({ channel: { id: 'channel-1' } });
+ create.mockResolvedValue({
+ channel: { id: 'chn_1', metadata: null, projectId: null, title: 'c' },
+ });
await service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' });
diff --git a/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts b/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts
index 7eba0e41139..bd44d0adf30 100644
--- a/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts
+++ b/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts
@@ -36,9 +36,14 @@ describe('reading a visitor’s conversation with a shared Agent', () => {
it('opens it read-only for the creator when the caller is not a member', async () => {
detail.mockRejectedValue(notFound);
- readShareVisitorChannel.mockResolvedValue({ attachments: [], readOnly: true });
+ readShareVisitorChannel.mockResolvedValue({
+ attachments: [],
+ channel: { id: 'chn_visitor', metadata: {}, projectId: null, title: 'Visitor' },
+ readOnly: true,
+ });
await expect(service().detail('chn_visitor', undefined)).resolves.toMatchObject({
+ channel: { displayTitle: 'Visitor' },
readOnly: true,
});
expect(readShareVisitorChannel).toHaveBeenCalledWith(
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 8e3bf36c927..20094d8a3e5 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -1,7 +1,7 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
-import type { ChannelVisibility } from '@lobechat/types';
+import type { ChannelMetadata, ChannelVisibility } from '@lobechat/types';
import {
agentDisplayName,
CHANNEL_LIMITS,
@@ -25,6 +25,10 @@ import type {
ChannelStopScope,
} from '@/database/repositories/channel';
import { ChannelError, ChannelRepository } from '@/database/repositories/channel';
+import {
+ projectDefaultChannelMetadata,
+ withDisplayTitle,
+} from '@/database/repositories/channel/displayTitle';
import type { ChannelDeviceGrantDecision } from '@/database/repositories/channel/grants';
import { decideDeviceGrant, listDeviceGrants } from '@/database/repositories/channel/grants';
import { findProjectMainChannelId } from '@/database/repositories/channel/projectMainChannel';
@@ -239,17 +243,19 @@ export class ChannelService {
// Invited people see the new Channel without waiting for their next poll.
if (userIds.length) await this.changed(access.channel.id);
await announceDeviceGrants(this.db, access.channel.id);
- return access;
+ return this.withDisplayTitle(access);
};
/**
* 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.
+ * in this scope, so its readability is not checked again. A project's is marked so clients show
+ * it under the project's name (`displayTitle`); a workspace's carries no mark.
*/
createDefault = async (input: { agentId: string; projectId?: string; title: string }) => {
const agentId = await this.defaultChannelAgent(input.agentId);
return this.repository.create({
agents: [{ agentId }],
+ ...(input.projectId && { metadata: projectDefaultChannelMetadata() }),
projectId: input.projectId,
title: input.title,
});
@@ -277,7 +283,7 @@ export class ChannelService {
// Invitees see the new group without waiting for their next poll.
await this.changed(access.channel.id);
await announceDeviceGrants(this.db, access.channel.id);
- return access;
+ return this.withDisplayTitle(access);
};
/**
@@ -458,10 +464,11 @@ export class ChannelService {
return grant;
};
+ /** Edits `title` only: a project's default Channel keeps its mark and its project's name. */
rename = async (channelId: string, title: string) => {
const channel = await this.repository.rename(channelId, title);
await this.changed(channelId);
- return channel;
+ return withDisplayTitle(this.db, channel);
};
editMessage = async (channelId: string, messageId: string, content: string) => {
@@ -486,7 +493,7 @@ export class ChannelService {
updateVisibility = async (channelId: string, visibility: ChannelVisibility) => {
const channel = await this.repository.updateVisibility(channelId, visibility);
await this.changed(channelId);
- return channel;
+ return withDisplayTitle(this.db, channel);
};
/** The coordinator physically stops a removed Agent's runs. */
@@ -509,7 +516,7 @@ export class ChannelService {
join = async (channelId: string) => {
const access = await this.repository.join(channelId);
await this.changed(channelId);
- return access;
+ return this.withDisplayTitle(access);
};
/**
@@ -527,6 +534,18 @@ export class ChannelService {
changed = (channelId: string) => notifyChannel(this.db, channelId);
+ /** Adds `displayTitle` to a Channel handed back to a client; see `withDisplayTitle`. */
+ private withDisplayTitle = async <
+ T extends {
+ channel: { metadata: ChannelMetadata | null; projectId: string | null; title: string };
+ },
+ >(
+ access: T,
+ ) => ({
+ ...access,
+ channel: await withDisplayTitle(this.db, access.channel),
+ });
+
/** A personal list write that joins an open Channel first; members hear only about a join. */
private writeMayJoin = async <T>(
channelId: string,
@@ -596,10 +615,12 @@ export class ChannelService {
detail = async (channelId: string, options: Parameters<ChannelRepository['detail']>[1]) => {
const view = await this.readView(channelId, options);
const files = new FileService(this.db, this.userId, this.workspaceId);
+ const channel = await withDisplayTitle(this.db, view.channel);
// The public message's attachment relation grants this read after membership authorization.
// Do not return private storage keys or route through an unrelated ordinary-chat ACL.
return {
...view,
+ channel,
attachments: await pMap(
view.attachments,
async (file) => ({ ...file, url: await files.getFullFileUrl(file.url, 300) }),
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index da59429e86f..771c96fc048 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -37,6 +37,11 @@ which then follows the Thread. Deleting a bound Agent cascades its direct conver
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`).
+A project's default Channel (`createDefaultChannel`, titled `General`) carries
+`metadata.projectDefault`. Every Channel the router hands a client gets `displayTitle`
+(`withDisplayTitles`): the project's name for that marked Channel while the project is live and
+named, else `title`. It is read each time, so a project rename shows at once, and renaming the
+Channel edits only `title`, keeping the mark.
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 people. `userCandidates` lists those people from a direct
diff --git a/packages/database/src/repositories/channel/__tests__/displayTitle.test.ts b/packages/database/src/repositories/channel/__tests__/displayTitle.test.ts
new file mode 100644
index 00000000000..f864e209409
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/displayTitle.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channels, projects, workspaceMembers } from '../../../schemas';
+import { trashStamp } from '../../../utils/softDelete';
+import { ChannelRepository, projectDefaultChannelMetadata, withDisplayTitle } from '..';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-display-title');
+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(async () => {
+ await db.delete(projects).where(eq(projects.workspaceId, fixture.workspaceId));
+ await fixture.cleanup();
+});
+
+const owner = () => new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+
+/** Project "Lobot" with its default Channel, and another Channel named General in it. */
+const lobot = async () => {
+ const [project] = await db
+ .insert(projects)
+ .values({ name: 'Lobot', userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const { channel: main } = await owner().create({
+ metadata: projectDefaultChannelMetadata(),
+ projectId: project.id,
+ title: 'General',
+ });
+ const { channel: other } = await owner().create({ projectId: project.id, title: 'General' });
+ return { main, other, project };
+};
+
+const displayTitleOf = async (channelId: string) =>
+ (await owner().list()).find(({ id }) => id === channelId)?.displayTitle;
+
+describe('Channel display titles', () => {
+ it("shows a project's default Channel under the project's name, others under their title", async () => {
+ const { main, other } = await lobot();
+ const { channel: workspace } = await owner().create({ title: 'General' });
+
+ const list = await owner().list();
+
+ expect(Object.fromEntries(list.map(({ displayTitle, id }) => [id, displayTitle]))).toEqual({
+ [main.id]: 'Lobot',
+ [other.id]: 'General',
+ [workspace.id]: 'General',
+ });
+ expect(list.find(({ id }) => id === main.id)?.title).toBe('General');
+ });
+
+ it('follows a project rename without touching the Channel', async () => {
+ const { main, project } = await lobot();
+
+ await db.update(projects).set({ name: 'Lobot 2' }).where(eq(projects.id, project.id));
+
+ expect(await displayTitleOf(main.id)).toBe('Lobot 2');
+ });
+
+ it('keeps the mark and the project name when the Channel is renamed', async () => {
+ const { main } = await lobot();
+
+ await owner().rename(main.id, 'Lobby');
+
+ expect(await displayTitleOf(main.id)).toBe('Lobot');
+ const [row] = await db.select().from(channels).where(eq(channels.id, main.id));
+ expect(row).toMatchObject({ metadata: { projectDefault: true }, title: 'Lobby' });
+ });
+
+ it('falls back to the title once the project is trashed or has no name', async () => {
+ const { main, project } = await lobot();
+
+ await db.update(projects).set({ name: ' ' }).where(eq(projects.id, project.id));
+ expect(await displayTitleOf(main.id)).toBe('General');
+
+ await db
+ .update(projects)
+ .set({ name: 'Lobot', ...trashStamp(new Date()) })
+ .where(eq(projects.id, project.id));
+ expect(await displayTitleOf(main.id)).toBe('General');
+ });
+
+ it('falls back to the title for a marked Channel whose project is gone', async () => {
+ const marked = { metadata: projectDefaultChannelMetadata(), title: 'General' };
+
+ expect(await withDisplayTitle(db, { ...marked, projectId: 'pro_missing' })).toMatchObject({
+ displayTitle: 'General',
+ });
+ expect(await withDisplayTitle(db, { ...marked, projectId: null })).toMatchObject({
+ displayTitle: 'General',
+ });
+ });
+
+ it('names a joinable public default Channel after its project', async () => {
+ const [project] = await db
+ .insert(projects)
+ .values({ name: 'Lobot', userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const { channel } = await owner().create({
+ metadata: projectDefaultChannelMetadata(),
+ projectId: project.id,
+ title: 'General',
+ visibility: 'public',
+ });
+ const teammate = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+
+ const joinable = await teammate.listJoinable();
+
+ expect(joinable).toEqual([
+ expect.objectContaining({ displayTitle: 'Lobot', id: channel.id, title: 'General' }),
+ ]);
+ expect(joinable[0]).not.toHaveProperty('metadata');
+ });
+});
diff --git a/packages/database/src/repositories/channel/displayTitle.ts b/packages/database/src/repositories/channel/displayTitle.ts
new file mode 100644
index 00000000000..1445c90308f
--- /dev/null
+++ b/packages/database/src/repositories/channel/displayTitle.ts
@@ -0,0 +1,50 @@
+import type { ChannelMetadata } from '@lobechat/types';
+import { and, inArray } from 'drizzle-orm';
+
+import { projects } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
+
+interface TitledChannel {
+ metadata: ChannelMetadata | null;
+ projectId: string | null;
+ title: string;
+}
+
+/** The marked Channel a project starts with; see `ChannelMetadata.projectDefault`. */
+export const isProjectDefaultChannel = (channel: Pick<TitledChannel, 'metadata' | 'projectId'>) =>
+ !!channel.projectId && channel.metadata?.projectDefault === true;
+
+/** The metadata a project's default Channel is created with. */
+export const projectDefaultChannelMetadata = (): ChannelMetadata => ({ projectDefault: true });
+
+/**
+ * Adds `displayTitle`: the project's name for a project's default Channel while that project is
+ * live and named, otherwise the Channel's own `title`. Read every time, so a project rename shows
+ * at once; one query for every marked row, none when no row is marked.
+ */
+export const withDisplayTitles = async <T extends TitledChannel>(
+ db: LobeChatDatabase | Transaction,
+ rows: T[],
+): Promise<Array<T & { displayTitle: string }>> => {
+ const projectIds = [
+ ...new Set(rows.filter(isProjectDefaultChannel).map(({ projectId }) => projectId!)),
+ ];
+ const nameOf = new Map<string, string>();
+ if (projectIds.length) {
+ const found = await db
+ .select({ id: projects.id, name: projects.name })
+ .from(projects)
+ .where(and(inArray(projects.id, projectIds), notTrashed(projects.isDeleted)));
+ for (const { id, name } of found) if (name?.trim()) nameOf.set(id, name.trim());
+ }
+ return rows.map((row) => ({
+ ...row,
+ displayTitle: (isProjectDefaultChannel(row) && nameOf.get(row.projectId!)) || row.title,
+ }));
+};
+
+export const withDisplayTitle = async <T extends TitledChannel>(
+ db: LobeChatDatabase | Transaction,
+ row: T,
+): Promise<T & { displayTitle: string }> => (await withDisplayTitles(db, [row]))[0];
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 661067d621c..da0d5d110b7 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -41,6 +41,7 @@ import type { ChannelContacts } from './contacts';
import { noChannelContacts } from './contacts';
import { deleteMessage } from './delete';
import { findThread } from './delivery';
+import { withDisplayTitles } from './displayTitle';
import { editMessage } from './edit';
import { ChannelError } from './error';
import { syncMemberGrant } from './grants';
@@ -95,6 +96,7 @@ export type {
} from './claim';
export type { ChannelContacts } from './contacts';
export { noChannelContacts } from './contacts';
+export * from './displayTitle';
export type { ChannelErrorCode } from './error';
export { ChannelError } from './error';
export { ChannelExecutionRepository } from './execution';
@@ -156,6 +158,7 @@ export class ChannelRepository {
/** The direct conversation's Agent environment; the caller resolved and checked it. */
agentConfig?: ChannelMemberConfig;
agents?: ChannelAddAgentInput[];
+ metadata?: ChannelItem['metadata'];
/** Callers check that the project is readable in this scope. */
projectId?: string;
title: string;
@@ -189,6 +192,7 @@ export class ChannelRepository {
}
const insert = tx.insert(channels).values({
agentId,
+ metadata: params.metadata,
projectId: params.projectId,
userId: this.userId,
title: params.title,
@@ -580,6 +584,7 @@ export class ChannelRepository {
sharedAgentHandle: string | null;
threadMentions: ChannelThreadMention[];
unreadCount: number;
+ displayTitle: string;
}
>
> => {
@@ -726,7 +731,7 @@ export class ChannelRepository {
};
},
);
- return [
+ const items = [
...joined,
// Not joined: nothing is unread or pending for the caller yet.
...open.map((channel) => ({
@@ -750,6 +755,7 @@ export class ChannelRepository {
unreadCount: 0,
})),
].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+ return withDisplayTitles(this.db, items);
};
/**
diff --git a/packages/database/src/repositories/channel/publicAccess.ts b/packages/database/src/repositories/channel/publicAccess.ts
index 45df394fd98..7c871c8f39e 100644
--- a/packages/database/src/repositories/channel/publicAccess.ts
+++ b/packages/database/src/repositories/channel/publicAccess.ts
@@ -4,6 +4,7 @@ import { channelMembers, channels } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ilikeContains } from '../../utils/like';
import { notTrashed } from '../../utils/softDelete';
+import { withDisplayTitles } from './displayTitle';
import { ChannelError } from './error';
import { memberInviterMetadata, requireWorkspaceMember } from './people';
import { audit, lockChannel } from './transaction';
@@ -18,7 +19,7 @@ export const listJoinableChannels = async (
) => {
if (!workspaceId) return [];
const query = search?.trim();
- return db.transaction(async (tx) => {
+ const rows = await db.transaction(async (tx) => {
await requireWorkspaceMember(tx, workspaceId, userId);
return tx
.select({
@@ -29,6 +30,7 @@ export const listJoinableChannels = async (
SELECT count(*)::int FROM channel_members m
WHERE m.channel_id = "channels"."id" AND m.actor_type = 'user' AND m.status = 'active'
)`,
+ metadata: channels.metadata,
projectId: channels.projectId,
title: channels.title,
})
@@ -59,6 +61,8 @@ export const listJoinableChannels = async (
.orderBy(desc(channels.createdAt))
.limit(100);
});
+ // The metadata only marks a project's default Channel; it is not part of the browse item.
+ return (await withDisplayTitles(db, rows)).map(({ metadata: _metadata, ...item }) => item);
};
/**
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 3dc69b3ff2f..0c0d57b03cf 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -159,7 +159,13 @@ export type ChannelMemberMetadata = Record<string, unknown> & {
};
/** Free-form channel state that does not need its own column. */
-export type ChannelMetadata = Record<string, unknown>;
+export type ChannelMetadata = Record<string, unknown> & {
+ /**
+ * The Channel a project starts with. Clients show it under the project's name (see
+ * `ChannelListItem.displayTitle`) while its own `title` stays as stored; renaming keeps the mark.
+ */
+ projectDefault?: boolean;
+};
/** Free-form grant state that does not need its own column. */
export type ChannelMemberGrantMetadata = Record<string, unknown>;
@@ -744,6 +750,8 @@ export type ChannelAuditDetails = Record<string, boolean | number | string | str
/** A public group Channel the caller has not joined yet, as the browse list shows it. */
export interface ChannelJoinableItem {
createdAt: Date;
+ /** What clients show as its name; see `ChannelListItem.displayTitle`. */
+ displayTitle: string;
id: string;
/** Active people in it, Agents not counted. */
memberCount: number;
@@ -799,6 +807,12 @@ export interface ChannelListItem {
/** Server-computed for the current member. */
canDelete: boolean;
createdAt: Date;
+ /**
+ * What clients show as the Channel's name, computed by the server on every read: the project's
+ * name for a project's default Channel (`metadata.projectDefault`) while that project is live
+ * and named, otherwise `title`. Clients only read it; renaming still edits `title`.
+ */
+ displayTitle: string;
/**
* The caller hid the conversation from their list; new activity brings it back. Set by the
* Channel list. Personal: other members never see it.