🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): let admins make a group channel public for the workspace to join (#23110)
LiJiand8ef85bd6f34
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex 49145ebec68..ab9da083477 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -243,6 +243,16 @@ export const channelRouter = router({const access = await ctx.channelService.openPeer(input.userId);return { data: access.channel.id, success: true };}),+ /** Public Channels in the active workspace the caller can join. */+ listJoinable: channelProcedure+ .input(z.object({ search: z.string().max(100).optional() }).optional())+ .query(async ({ ctx, input }) => ({+ data: await ctx.channelService.repository.listJoinable(input?.search),+ })),+ join: channelProcedure.input(z.object({ channelId })).mutation(async ({ ctx, input }) => {+ const { channel } = await ctx.channelService.join(input.channelId);+ return { data: channel, success: true };+ }),list: channelProcedure.query(async ({ ctx }) => ({data: await ctx.channelService.repository.list(),success: true,@@ -263,6 +273,12 @@ export const channelRouter = router({data: await ctx.channelService.rename(input.channelId, input.title),success: true,})),+ updateVisibility: channelProcedure+ .input(z.object({ channelId, visibility: z.enum(['private', 'public']) }))+ .mutation(async ({ ctx, input }) => ({+ data: await ctx.channelService.updateVisibility(input.channelId, input.visibility),+ success: true,+ })),removeThread: channelProcedure.input(z.object({ channelId, threadId })).mutation(async ({ ctx, input }) => {diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex a36a2992708..9c0540ebbd9 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -1,6 +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 {agentDisplayName,CHANNEL_LIMITS,@@ -334,6 +335,19 @@ export class ChannelService {return member;};+ updateVisibility = async (channelId: string, visibility: ChannelVisibility) => {+ const channel = await this.repository.updateVisibility(channelId, visibility);+ await this.changed(channelId);+ return channel;+ };++ /** Members already in the Channel see the newcomer without waiting for their next poll. */+ join = async (channelId: string) => {+ const access = await this.repository.join(channelId);+ await this.changed(channelId);+ return access;+ };+changed = (channelId: string) => notifyChannel(this.db, channelId);detail = async (channelId: string, options: Parameters<ChannelRepository['detail']>[1]) => {diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 6d89d8d78f8..439f56e7c30 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -32,6 +32,13 @@"blocked.member_busy": "Waiting for the previous reply","blocked.unavailable": "Agent unavailable","blocked.workspace_changed": "Workspace changed",+ "browse.empty": "No public channels to join yet.",+ "browse.join": "Join",+ "browse.joinFailed": "Could not join the channel. Try again.",+ "browse.memberCount": "Members · {{count}}",+ "browse.noMatches": "No matching public channels",+ "browse.search": "Search public channels",+ "browse.title": "Browse channels","cancel": "Cancel","chooseDevice": "Choose a device","chooseDirectory": "Choose directory",@@ -220,6 +227,9 @@"settings.tab.members": "Members","settings.tab.reply": "Replies","settings.title": "Channel settings",+ "settings.visibility.privateHint": "Only invited members can see this channel. Turn it on to let everyone in the workspace find and join it.",+ "settings.visibility.publicHint": "Everyone in the workspace can find and join this channel.",+ "settings.visibility.title": "Public channel","sort.by": "Sort by","sort.by.createdAt": "Date created","sort.by.title": "Name",@@ -261,5 +271,7 @@"unarchiveThread": "Unarchive thread","unarchiveThreadSuccess": "Thread unarchived","unnamedAgent": "Unnamed Agent",- "unreadMentions": "Unread mentions: {{count}}"+ "unreadMentions": "Unread mentions: {{count}}",+ "visibilityFailed": "Could not change who can see the channel. Try again.",+ "visibilityForbidden": "Only the channel owner or an administrator can change who can see it."}diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 18660ef919a..00f4556caf6 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -32,6 +32,13 @@"blocked.member_busy": "等待上一条回复完成","blocked.unavailable": "Agent 暂不可用","blocked.workspace_changed": "工作空间已变更",+ "browse.empty": "暂时没有可加入的公开频道。",+ "browse.join": "加入",+ "browse.joinFailed": "加入频道失败,请重试。",+ "browse.memberCount": "{{count}} 位成员",+ "browse.noMatches": "没有匹配的公开频道",+ "browse.search": "搜索公开频道",+ "browse.title": "浏览频道","cancel": "取消","chooseDevice": "选择设备","chooseDirectory": "选择工作目录",@@ -220,6 +227,9 @@"settings.tab.members": "成员","settings.tab.reply": "回复策略","settings.title": "频道设置",+ "settings.visibility.privateHint": "只有被邀请的成员能看到这个频道。开启后,工作区里的所有人都可以找到并加入。",+ "settings.visibility.publicHint": "工作区里的所有人都可以找到并加入这个频道。",+ "settings.visibility.title": "公开频道","sort.by": "排序方式","sort.by.createdAt": "创建时间","sort.by.title": "名称",@@ -261,5 +271,7 @@"unarchiveThread": "取消归档线程","unarchiveThreadSuccess": "线程已取消归档","unnamedAgent": "未命名 Agent",- "unreadMentions": "{{count}} 条未读提及"+ "unreadMentions": "{{count}} 条未读提及",+ "visibilityFailed": "修改频道可见范围失败,请重试。",+ "visibilityForbidden": "只有频道所有者或管理员可以修改可见范围。"}diff --git a/packages/database/src/repositories/channel/__tests__/visibility.test.ts b/packages/database/src/repositories/channel/__tests__/visibility.test.tsnew file mode 100644index 00000000000..bfb93704a20--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/visibility.test.ts@@ -0,0 +1,126 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { channelAudit, channelMembers, channels, workspaceMembers } from '../../../schemas';+import { ChannelRepository } from '..';+import { createChannelFixture } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-visibility');+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 create = async (title = 'Announcements') => {+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await owner.create({ title });+ const outsider = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ return { channel, outsider, owner };+};++describe('Channel visibility', () => {+ it('starts private: workspace members outside it can neither find nor join it', async () => {+ const { channel, outsider } = await create();+ expect(channel.visibility).toBe('private');+ expect(await outsider.listJoinable()).toEqual([]);+ await expect(outsider.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(outsider.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('lets an admin publish it, then any workspace member find and join it as a member', async () => {+ const { channel, outsider, owner } = await create();+ expect(await owner.updateVisibility(channel.id, 'public')).toMatchObject({+ visibility: 'public',+ });+ await owner.send(channel.id, { content: 'Hello', requestKey: 'hello', routing: 'fallback' });++ expect(await outsider.listJoinable()).toEqual([+ expect.objectContaining({ id: channel.id, memberCount: 1, title: 'Announcements' }),+ ]);+ expect(await outsider.listJoinable('announ')).toHaveLength(1);+ expect(await outsider.listJoinable('nothing')).toEqual([]);+ // Joining still goes through membership: reading before it stays closed.+ await expect(outsider.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });++ const { member } = await outsider.join(channel.id);+ expect(member).toMatchObject({ role: 'member', status: 'active', userId: fixture.memberId });+ expect((await outsider.join(channel.id)).member.id).toBe(member.id);+ expect(await outsider.listJoinable()).toEqual([]);+ // The history is readable, and not counted as unread.+ expect((await outsider.detail(channel.id)).messages).toHaveLength(1);+ expect(await outsider.list()).toEqual([+ expect.objectContaining({ canDelete: false, id: channel.id, unreadCount: 0 }),+ ]);+ // A joiner is a plain member, so cannot change the visibility back.+ await expect(outsider.updateVisibility(channel.id, 'private')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ const events = await db+ .select({ event: channelAudit.event })+ .from(channelAudit)+ .where(eq(channelAudit.channelId, channel.id));+ expect(events.map(({ event }) => event)).toEqual(+ expect.arrayContaining(['visibility_changed', 'member_joined']),+ );+ });++ it('keeps members when it goes private again, and lets a former member rejoin while public', async () => {+ const { channel, outsider, owner } = await create();+ await owner.updateVisibility(channel.id, 'public');+ const { member } = await outsider.join(channel.id);+ await db.update(channelMembers).set({ status: 'left' }).where(eq(channelMembers.id, member.id));+ expect((await outsider.join(channel.id)).member).toMatchObject({+ id: member.id,+ status: 'active',+ });++ await owner.updateVisibility(channel.id, 'private');+ expect(await outsider.list()).toEqual([expect.objectContaining({ id: channel.id })]);+ await db.update(channelMembers).set({ status: 'left' }).where(eq(channelMembers.id, member.id));+ await expect(outsider.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('hides archived and trashed public channels, and rejects people outside the workspace', async () => {+ const { channel, outsider, owner } = await create();+ await owner.updateVisibility(channel.id, 'public');+ await owner.archive(channel.id);+ expect(await outsider.listJoinable()).toEqual([]);+ await expect(outsider.join(channel.id)).rejects.toMatchObject({ code: 'CONFLICT' });+ await owner.unarchive(channel.id);+ await owner.remove(channel.id);+ expect(await outsider.listJoinable()).toEqual([]);+ await expect(outsider.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });++ const other = await create('Other');+ await owner.updateVisibility(other.channel.id, 'public');+ await db+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(+ and(+ eq(workspaceMembers.workspaceId, fixture.workspaceId),+ eq(workspaceMembers.userId, fixture.memberId),+ ),+ );+ await expect(outsider.listJoinable()).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(outsider.join(other.channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('never makes a direct conversation or a personal channel public', async () => {+ const personal = new ChannelRepository(db, fixture.ownerId, null);+ const { channel } = await personal.create({ title: 'Mine' });+ await expect(personal.updateVisibility(channel.id, 'public')).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(await personal.listJoinable()).toEqual([]);+ const [stored] = await db.select().from(channels).where(eq(channels.id, channel.id));+ expect(stored.visibility).toBe('private');+ });+});diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 134f68e05ed..7744b56d694 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -6,7 +6,7 @@ import type {ChannelVisibility,} from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';-import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, isNull, notExists, or, sql } from 'drizzle-orm';import { TrashModel } from '../../models/trash';import type { ChannelItem, ChannelJobItem, ChannelMessageItem } from '../../schemas';@@ -20,6 +20,7 @@ import {channelThreads,} from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';+import { ilikeContains } from '../../utils/like';import { notTrashed, trashStamp } from '../../utils/softDelete';import { normalizeWorkspaceId } from '../../utils/workspace';import type { ChannelAddAgentInput } from './agent';@@ -33,7 +34,12 @@ import { channelAvatarMembers } from './avatars';import { findThread } from './delivery';import { ChannelError } from './error';import { lockPeerPair, peerOf, requireMutualContacts } from './peer';-import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';+import {+ addChannelUser,+ channelUserCandidates,+ newChannelUserCandidates,+ requireWorkspaceMember,+} from './people';import type { ChannelAgentPostInput } from './post';import { postAgentMessage } from './post';import { retryJob } from './retry';@@ -371,6 +377,133 @@ export class ChannelRepository {{ minRole: 'admin' },);+ /**+ * Who in the workspace can find a group Channel: `public` lists it for every workspace member+ * to join, `private` only for the people already in it. Members keep their access either way.+ */+ updateVisibility = async (channelId: string, visibility: ChannelVisibility) =>+ this.write(+ channelId,+ async (tx, { channel }) => {+ if (channel.agentId || channel.peerUserId || !channel.workspaceId)+ throw new ChannelError('BAD_REQUEST', 'Only a workspace group channel can be public');+ if (channel.visibility === visibility) return channel;+ const [updated] = await tx+ .update(channels)+ .set({ visibility })+ .where(eq(channels.id, channelId))+ .returning();+ await audit(tx, channelId, 'visibility_changed', channelId, { visibility });+ return updated;+ },+ { minRole: 'admin' },+ );++ /** Public group Channels in this workspace the caller has not joined, newest first. */+ listJoinable = async (search?: string) => {+ const { workspaceId } = this;+ if (!workspaceId) return [];+ const query = search?.trim();+ return this.db.transaction(async (tx) => {+ await requireWorkspaceMember(tx, workspaceId, this.userId);+ return tx+ .select({+ createdAt: channels.createdAt,+ id: channels.id,+ // Qualified by hand: a single-table select renders columns without their table.+ memberCount: sql<number>`(+ SELECT count(*)::int FROM channel_members m+ WHERE m.channel_id = "channels"."id" AND m.actor_type = 'user' AND m.status = 'active'+ )`,+ projectId: channels.projectId,+ title: channels.title,+ })+ .from(channels)+ .where(+ and(+ eq(channels.workspaceId, workspaceId),+ eq(channels.visibility, 'public'),+ eq(channels.status, 'active'),+ isNull(channels.agentId),+ isNull(channels.peerUserId),+ notTrashed(channels.isDeleted),+ query ? ilikeContains(channels.title, query) : undefined,+ notExists(+ tx+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channels.id),+ eq(channelMembers.userId, this.userId),+ eq(channelMembers.status, 'active'),+ ),+ ),+ ),+ ),+ )+ .orderBy(desc(channels.createdAt))+ .limit(100);+ });+ };++ /**+ * Joins a public group Channel of this workspace as a plain member. A person who left or was+ * removed can come back, the same as being added again.+ */+ join = async (channelId: string): Promise<ChannelAccess> => {+ const { workspaceId } = this;+ if (!workspaceId) throw new ChannelError('NOT_FOUND', 'Channel not found');+ return this.db.transaction(async (tx) => {+ await lockChannel(tx, channelId);+ const [channel] = await tx+ .select()+ .from(channels)+ .where(+ and(+ eq(channels.id, channelId),+ eq(channels.workspaceId, workspaceId),+ eq(channels.visibility, 'public'),+ isNull(channels.agentId),+ isNull(channels.peerUserId),+ notTrashed(channels.isDeleted),+ ),+ )+ .limit(1);+ // A private channel answers the same as a missing one, so its existence does not leak.+ if (!channel) throw new ChannelError('NOT_FOUND', 'Channel not found');+ if (channel.status === 'archived') throw new ChannelError('CONFLICT', 'Channel is archived');+ await requireWorkspaceMember(tx, workspaceId, this.userId);++ const [existing] = await tx+ .select()+ .from(channelMembers)+ .where(+ and(eq(channelMembers.channelId, channelId), eq(channelMembers.userId, this.userId)),+ );+ if (existing?.status === 'active') return { channel, member: existing };+ // History is there to read, but it is not unread: a joiner starts caught up.+ const [member] = existing+ ? await tx+ .update(channelMembers)+ .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })+ .where(eq(channelMembers.id, existing.id))+ .returning()+ : await tx+ .insert(channelMembers)+ .values({+ actorType: 'user',+ channelId,+ lastReadSequence: channel.sequence,+ role: 'member',+ userId: this.userId,+ })+ .returning();+ await audit(tx, channelId, 'member_joined', member.id, { userId: this.userId });+ return { channel, member };+ });+ };+addUser = async (channelId: string, userId: string) =>this.write(channelId, (tx, access) => addChannelUser(tx, access, userId), { minRole: 'admin' });diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.tsindex 6bb48c4fef0..96d766d1010 100644--- a/packages/database/src/repositories/channel/people.ts+++ b/packages/database/src/repositories/channel/people.ts@@ -8,7 +8,11 @@ import { ChannelError } from './error';import { audit } from './transaction';import type { ChannelAccess } from './types';-const requireWorkspaceMember = async (tx: Transaction, workspaceId: string, userId: string) => {+export const requireWorkspaceMember = async (+ tx: Transaction,+ workspaceId: string,+ userId: string,+) => {const [member] = await tx.select({ userId: workspaceMembers.userId }).from(workspaceMembers)diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex d4d30987fe4..b0511d9c121 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -295,4 +295,17 @@ export default {'settings.reply.instructionsHint':'Tell Agents who to answer and what to leave alone. It guides them and is not a hard rule.','settings.reply.instructionsContent': 'Instructions',+ 'browse.empty': 'No public channels to join yet.',+ 'browse.join': 'Join',+ 'browse.joinFailed': 'Could not join the channel. Try again.',+ 'browse.memberCount': 'Members · {{count}}',+ 'browse.noMatches': 'No matching public channels',+ 'browse.search': 'Search public channels',+ 'browse.title': 'Browse channels',+ 'settings.visibility.privateHint':+ 'Only invited members can see this channel. Turn it on to let everyone in the workspace find and join it.',+ 'settings.visibility.publicHint': 'Everyone in the workspace can find and join this channel.',+ 'settings.visibility.title': 'Public channel',+ 'visibilityFailed': 'Could not change who can see the channel. Try again.',+ 'visibilityForbidden': 'Only the channel owner or an administrator can change who can see it.',};diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex fafc7778b03..b2de7399115 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -439,6 +439,16 @@ export interface ChannelInputManifest {/** Flat audit payload: routing decisions, claims, stops, isolation reasons. */export type ChannelAuditDetails = Record<string, boolean | number | string | string[] | null>;+/** A public group Channel the caller has not joined yet, as the browse list shows it. */+export interface ChannelJoinableItem {+ createdAt: Date;+ id: string;+ /** Active people in it, Agents not counted. */+ memberCount: number;+ projectId: string | null;+ title: string;+}+/** A member pictured in a Channel's list avatar. */export interface ChannelAvatarMember {actorType: ChannelMemberActorType;@@ -500,6 +510,8 @@ export interface ChannelListItem {unreadCount?: number;/** Bumped by every new message, so it orders conversations by latest activity. */updatedAt?: Date;+ /** Ignored for a direct conversation, which is always private. */+ visibility: ChannelVisibility;workspaceId: string | null;}diff --git a/src/features/Channels/BrowseChannels.tsx b/src/features/Channels/BrowseChannels.tsxnew file mode 100644index 00000000000..0fada24001f--- /dev/null+++ b/src/features/Channels/BrowseChannels.tsx@@ -0,0 +1,126 @@+import type { ChannelJoinableItem } from '@lobechat/types';+import {+ Button,+ createModal,+ Flexbox,+ Icon,+ Input,+ Text,+ toast,+ useModalContext,+} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useDebounce } from 'ahooks';+import { t } from 'i18next';+import { Hash, Search } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';++const styles = stylex.create({+ list: {+ overflowY: 'auto',+ height: 400,+ maxHeight: '55vh',+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ paddingBlock: 8,+ paddingInline: 8,+ borderRadius: cssVar.borderRadius,+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ },+ note: { paddingBlock: 24, textAlign: 'center' },+});++interface BrowseChannelsProps {+ onJoined?: (channel: ChannelJoinableItem) => void;+}++/** Public Channels of the active workspace the user is not in yet; joining one opens it. */+function BrowseChannels({ onJoined }: BrowseChannelsProps) {+ const { t } = useTranslation('channel');+ const { close } = useModalContext();+ const [search, setSearch] = useState('');+ const [joining, setJoining] = useState<string>();+ const query = useDebounce(search.trim(), { wait: 200 });+ const sync = channelActions.useFetchJoinable(query);+ const data = useChannelStore(channelSelectors.joinable(query));++ const join = async (channel: ChannelJoinableItem) => {+ setJoining(channel.id);+ try {+ await channelActions.join(channel.id, query);+ close();+ onJoined?.(channel);+ } catch (cause) {+ console.error('Failed to join Channel', cause);+ toast.error(t('browse.joinFailed'));+ void sync.revalidate();+ } finally {+ setJoining(undefined);+ }+ };++ return (+ <Flexbox gap={12}>+ <Input+ allowClear+ aria-label={t('browse.search')}+ placeholder={t('browse.search')}+ prefix={<Icon icon={Search} />}+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ />+ <div {...stylex.props(styles.list)}>+ <AsyncBoundary+ data={data}+ error={sync.error}+ isEmpty={data?.length === 0}+ isLoading={!data && !sync.error}+ empty={+ <Text as="p" type="secondary" {...stylex.props(styles.note)}>+ {t(query ? 'browse.noMatches' : 'browse.empty')}+ </Text>+ }+ onRetry={() => void sync.revalidate()}+ >+ {data?.map((channel) => (+ <div key={channel.id} {...stylex.props(styles.row)}>+ <Icon icon={Hash} size={16} />+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {channel.title}+ </Text>+ <Text fontSize={12} type="secondary">+ {t('browse.memberCount', { count: channel.memberCount })}+ </Text>+ </Flexbox>+ <Button+ disabled={!!joining && joining !== channel.id}+ loading={joining === channel.id}+ size="small"+ onClick={() => void join(channel)}+ >+ {t('browse.join')}+ </Button>+ </div>+ ))}+ </AsyncBoundary>+ </div>+ </Flexbox>+ );+}++export const openBrowseChannels = (onJoined?: BrowseChannelsProps['onJoined']) =>+ createModal({+ content: <BrowseChannels onJoined={onJoined} />,+ footer: null,+ title: t('browse.title', { ns: 'channel' }),+ width: 'min(90vw, 560px)',+ });diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsxindex 6b21ea7b16e..76fd4247adc 100644--- a/src/features/Channels/ChannelList.tsx+++ b/src/features/Channels/ChannelList.tsx@@ -16,10 +16,11 @@ import {} from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { Archive, ArrowDownUp, Hash, MoreHorizontal, Plus } from 'lucide-react';+import { Archive, ArrowDownUp, Compass, Hash, MoreHorizontal, Plus } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import AsyncError from '@/components/AsyncError';import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';@@ -33,6 +34,7 @@ import { useGlobalStore } from '@/store/global';import type { ChannelListSort } from '@/store/global/initialState';import { systemStatusSelectors } from '@/store/global/selectors';+import { openBrowseChannels } from './BrowseChannels';import { channelsInScope } from './channelScope';import { openCreateChannel } from './CreateChannel';import { matchChannel, matchChannelThread } from './paths';@@ -217,6 +219,10 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecticonst activeChannelId = matchChannel(pathname);const create = () =>openCreateChannel((id) => navigate(CHANNEL_URL(id, null, projectId)), projectId);+ // Public Channels exist only in a workspace; a personal space has nobody else's to join.+ const workspaceId = useActiveWorkspaceId();+ const browse = () =>+ openBrowseChannels((channel) => navigate(CHANNEL_URL(channel.id, null, channel.projectId)));// Only a thread opened as the page is the current entry; one beside the Channel is not.const activeThreadId = matchChannelThread(pathname) ?? null;const menuItems = useChannelMenu();@@ -334,6 +340,18 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSectionClick={(event) => event.stopPropagation()}/></DropdownMenu>+ {workspaceId && (+ <ActionIcon+ aria-label={t('browse.title')}+ icon={Compass}+ size="small"+ title={t('browse.title')}+ onClick={(event) => {+ event.stopPropagation();+ browse();+ }}+ />+ )}<ActionIconaria-label={t('create')}icon={Plus}diff --git a/src/features/Channels/Settings/VisibilitySection.tsx b/src/features/Channels/Settings/VisibilitySection.tsxnew file mode 100644index 00000000000..551d5ab4904--- /dev/null+++ b/src/features/Channels/Settings/VisibilitySection.tsx@@ -0,0 +1,49 @@+import type { ChannelListItem, ChannelVisibility } from '@lobechat/types';+import { Switch, toast } from '@lobehub/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { channelActions } from '@/store/channel';+import { isTrpcErrorCode } from '@/utils/trpcError';++import { FormCard } from './FormCard';++/** Only a workspace group Channel can be public; a personal one has nobody else to show it to. */+export function VisibilitySection({ channel }: { channel: ChannelListItem }) {+ const { t } = useTranslation('channel');+ const [saving, setSaving] = useState(false);+ const isPublic = channel.visibility === 'public';++ const change = async (visibility: ChannelVisibility) => {+ setSaving(true);+ try {+ await channelActions.setVisibility(channel.id, visibility);+ toast.success(t('settings.saved'));+ } catch (error) {+ console.error('Failed to change the Channel visibility', error);+ toast.error(+ t(isTrpcErrorCode(error, 'FORBIDDEN') ? 'visibilityForbidden' : 'visibilityFailed'),+ );+ } finally {+ setSaving(false);+ }+ };++ return (+ <FormCard+ title={t('settings.visibility.title')}+ description={t(+ isPublic ? 'settings.visibility.publicHint' : 'settings.visibility.privateHint',+ )}+ headerAction={+ <Switch+ aria-label={t('settings.visibility.title')}+ checked={isPublic}+ disabled={channel.status === 'archived'}+ loading={saving}+ onChange={(checked) => void change(checked ? 'public' : 'private')}+ />+ }+ />+ );+}diff --git a/src/features/Channels/Settings/index.tsx b/src/features/Channels/Settings/index.tsxindex e3749f44112..904bcfbf5bd 100644--- a/src/features/Channels/Settings/index.tsx+++ b/src/features/Channels/Settings/index.tsx@@ -19,6 +19,7 @@ import { MembersSection } from './MembersSection';import { ReplySection } from './ReplySection';import { settingsStyles } from './styles';import { channelSettingsTabs, resolveChannelSettingsTab } from './tabs';+import { VisibilitySection } from './VisibilitySection';/** Everything an admin manages about a group Channel: its conversation stays uncluttered. */function EnabledChannelSettings() {@@ -89,6 +90,7 @@ function EnabledChannelSettings() {)}<div hidden={tab !== 'advanced'}><Flexbox gap={24}>+ {channel.workspaceId && <VisibilitySection channel={channel} />}<DangerSection channel={channel} /></Flexbox></div>diff --git a/src/features/Channels/useMentionInvites.test.ts b/src/features/Channels/useMentionInvites.test.tsindex 7209e894206..7f5fdebd512 100644--- a/src/features/Channels/useMentionInvites.test.ts+++ b/src/features/Channels/useMentionInvites.test.ts@@ -49,6 +49,7 @@ const channel: ChannelListItem = {sequence: 0,status: 'active',title: 'Team',+ visibility: 'private',workspaceId: 'ws_1',};diff --git a/src/features/Channels/useRemoveChannel.test.ts b/src/features/Channels/useRemoveChannel.test.tsindex 88b729d9954..e16c9310c83 100644--- a/src/features/Channels/useRemoveChannel.test.ts+++ b/src/features/Channels/useRemoveChannel.test.ts@@ -37,6 +37,7 @@ const channel: ChannelListItem = {sequence: 0,status: 'active',title: 'Important channel',+ visibility: 'private',workspaceId: null,};describe('Channel deletion confirmation', () => {diff --git a/src/features/Channels/useRemoveThread.test.ts b/src/features/Channels/useRemoveThread.test.tsindex 53bf90d4346..88c58bba5fb 100644--- a/src/features/Channels/useRemoveThread.test.ts+++ b/src/features/Channels/useRemoveThread.test.ts@@ -32,6 +32,7 @@ const channel: ChannelListItem = {sequence: 0,status: 'active',createdAt: new Date(),+ visibility: 'private',workspaceId: null,};diff --git a/src/services/channel.ts b/src/services/channel.tsindex 4e1816daafe..43ae506e976 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -1,4 +1,9 @@-import type { ChannelDetail, ChannelListItem } from '@lobechat/types';+import type {+ ChannelDetail,+ ChannelJoinableItem,+ ChannelListItem,+ ChannelVisibility,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -46,6 +51,12 @@ class ChannelService {lambdaClient.channel.updateWakeConfig.mutate({ channelId, wake });rename = (channelId: string, title: string) =>lambdaClient.channel.rename.mutate({ channelId, title });+ updateVisibility = (channelId: string, visibility: ChannelVisibility) =>+ lambdaClient.channel.updateVisibility.mutate({ channelId, visibility });+ /** Public Channels in the active workspace the caller has not joined. */+ listJoinable = async (search: string): Promise<ChannelJoinableItem[]> =>+ (await lambdaClient.channel.listJoinable.query({ search })).data;+ join = (channelId: string) => lambdaClient.channel.join.mutate({ channelId });addUser = (channelId: string, userId: string) =>lambdaClient.channel.addUser.mutate({ channelId, userId });/** Without a Channel, the people a new Channel in the active workspace can start with. */diff --git a/src/store/channel/action.archive.test.ts b/src/store/channel/action.archive.test.tsindex 05f685375de..55148c1d006 100644--- a/src/store/channel/action.archive.test.ts+++ b/src/store/channel/action.archive.test.ts@@ -26,6 +26,7 @@ const channel: ChannelListItem = {sequence: 1,status: 'active',title: 'Launch',+ visibility: 'private',workspaceId: null,};const thread: ChannelPublicThread = {diff --git a/src/store/channel/action.removeThread.test.ts b/src/store/channel/action.removeThread.test.tsindex 5aa5f4582fb..eff540ce89d 100644--- a/src/store/channel/action.removeThread.test.ts+++ b/src/store/channel/action.removeThread.test.ts@@ -25,6 +25,7 @@ const channel: ChannelListItem = {sequence: 0,status: 'active',createdAt: new Date(),+ visibility: 'private',workspaceId: null,};const removed: ChannelPublicThread = {diff --git a/src/store/channel/action.rename.test.ts b/src/store/channel/action.rename.test.tsindex 5819a870965..21f0ee3f2bf 100644--- a/src/store/channel/action.rename.test.ts+++ b/src/store/channel/action.rename.test.ts@@ -19,6 +19,7 @@ const channel: ChannelListItem = {sequence: 0,status: 'active',title: 'Old name',+ visibility: 'private',workspaceId: null,};const detail = (item: ChannelListItem): ChannelDetail => ({diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 8fbb48f7738..51fa362352c 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -1,4 +1,9 @@-import type { ChannelPublicThread, ChannelStatus, ChannelThreadStatus } from '@lobechat/types';+import type {+ ChannelPublicThread,+ ChannelStatus,+ ChannelThreadStatus,+ ChannelVisibility,+} from '@lobechat/types';import { cacheScope } from '@/libs/replica';import { mutate, useClientDataSWR } from '@/libs/swr';@@ -188,6 +193,22 @@ class ChannelActionImpl {() => channelService.rename(channelId, title),);};+ /** The settings switch shows the new visibility before the server confirms. */+ setVisibility = async (channelId: string, visibility: ChannelVisibility) => {+ await this.#private.entity.optimistic(+ channelId,+ (channel) => ({ ...channel, visibility }),+ () => channelService.updateVisibility(channelId, visibility),+ );+ };+ useFetchJoinable = (search: string) => this.#private.joinable.useSync({ search });+ /** Joins a public Channel; it enters the sidebar once the list refreshes. */+ join = async (channelId: string, search = '') => {+ await channelService.join(channelId);+ await this.#refreshAfterWrite(() =>+ Promise.all([this.refreshList(), this.#private.joinable.fetch({ search }, { fresh: true })]),+ );+ };useFetchAgentEnvironment = (channelId: string, memberId: string) =>useClientDataSWR(channelKeys.agentEnvironment(channelId, memberId), () =>channelService.agentEnvironment(channelId, memberId),diff --git a/src/store/channel/action.visibility.test.ts b/src/store/channel/action.visibility.test.tsnew file mode 100644index 00000000000..6e8980f8435--- /dev/null+++ b/src/store/channel/action.visibility.test.ts@@ -0,0 +1,110 @@+import type { ChannelDetail, ChannelJoinableItem, ChannelListItem } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { channelService } from '@/services/channel';++import { channelActions } from './action';+import { channelViewKey } from './projection';+import { channelSelectors } from './selectors';+import { useChannelStore } from './store';++vi.mock('@/services/channel', () => ({+ channelService: {+ detail: vi.fn(),+ join: vi.fn(),+ list: vi.fn(),+ listJoinable: vi.fn(),+ updateVisibility: vi.fn(),+ },+}));++const channel: ChannelListItem = {+ canDelete: true,+ createdAt: new Date(),+ id: 'chn_000000000001',+ projectId: null,+ sequence: 0,+ status: 'active',+ title: 'Announcements',+ visibility: 'private',+ workspaceId: 'ws_1',+};+const joinable: ChannelJoinableItem = {+ createdAt: new Date(),+ id: 'chn_000000000002',+ memberCount: 3,+ projectId: null,+ title: 'Launch',+};+const detail = (item: ChannelListItem): ChannelDetail => ({+ attachments: [],+ channel: item,+ hasMore: false,+ jobs: [],+ members: [],+ messages: [],+ rootMessage: null,+ threads: [],+});+const view = { channelId: channel.id };+const visibilities = () => ({+ detail: useChannelStore.getState().detailMap[channelViewKey(view)]?.channel.visibility,+ list: useChannelStore.getState().listMap.all?.map((item) => item.visibility),+});++describe('Channel visibility and joining', () => {+ beforeEach(async () => {+ const scope = crypto.randomUUID();+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);+ vi.mocked(channelService.list).mockResolvedValue([channel]);+ vi.mocked(channelService.detail).mockResolvedValue(detail(channel));+ channelActions.reset();+ await channelActions.refreshList();+ await channelActions.refreshDetail(view);+ });+ afterEach(() => {+ channelActions.reset();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('shows the new visibility before the server confirms', async () => {+ const request = Promise.withResolvers<never>();+ vi.mocked(channelService.updateVisibility).mockReturnValue(request.promise);++ const changing = channelActions.setVisibility(channel.id, 'public');+ expect(visibilities()).toEqual({ detail: 'public', list: ['public'] });++ request.resolve({ data: { ...channel, visibility: 'public' }, success: true } as never);+ await changing;+ expect(channelService.updateVisibility).toHaveBeenCalledWith(channel.id, 'public');+ expect(visibilities()).toEqual({ detail: 'public', list: ['public'] });+ });++ it('switches back when the server refuses', async () => {+ vi.mocked(channelService.updateVisibility).mockRejectedValue(new Error('Forbidden'));++ await expect(channelActions.setVisibility(channel.id, 'public')).rejects.toThrow('Forbidden');+ expect(visibilities()).toEqual({ detail: 'private', list: ['private'] });+ });++ it('moves a joined Channel from the browse list into the sidebar', async () => {+ vi.mocked(channelService.join).mockResolvedValue({ data: joinable, success: true } as never);+ const joined = { ...channel, id: joinable.id, title: joinable.title };+ vi.mocked(channelService.list).mockResolvedValue([channel, joined]);+ vi.mocked(channelService.listJoinable).mockResolvedValue([]);++ await channelActions.join(joinable.id, 'lau');++ expect(channelService.join).toHaveBeenLastCalledWith(joinable.id);+ expect(channelService.listJoinable).toHaveBeenLastCalledWith('lau');+ expect(channelSelectors.joinable('lau')(useChannelStore.getState())).toEqual([]);+ expect(channelSelectors.list(useChannelStore.getState())?.map((item) => item.id)).toEqual([+ channel.id,+ joinable.id,+ ]);+ });+});diff --git a/src/store/channel/privateAction.ts b/src/store/channel/privateAction.tsindex 3280f62c2b6..19af45e942f 100644--- a/src/store/channel/privateAction.ts+++ b/src/store/channel/privateAction.ts@@ -1,4 +1,4 @@-import type { ChannelDetail, ChannelListItem } from '@lobechat/types';+import type { ChannelDetail, ChannelJoinableItem, ChannelListItem } from '@lobechat/types';import {arrayEntity,@@ -14,6 +14,7 @@ import { settleOutbox } from './outbox';import {channelDetailEntity,channelDetailResource,+ channelJoinableResource,channelListResource,channelThreadEntityId,} from './projection';@@ -38,6 +39,7 @@ export class ChannelPrivateAction {};readonly detail;readonly entity;+ readonly joinable;readonly list;constructor(set: StoreSetter<ChannelState>, get: () => ChannelState) {this.list = createReplicaSlice(channelListResource, {@@ -48,6 +50,13 @@ export class ChannelPrivateAction {stateKey: 'listReplica',view: recordLens<ChannelState, ChannelListItem[]>('listMap'),});+ this.joinable = createReplicaSlice(channelJoinableResource, {+ actionPrefix: 'channel/joinable',+ get,+ set,+ stateKey: 'joinableReplica',+ view: recordLens<ChannelState, ChannelJoinableItem[]>('joinableMap'),+ });this.detail = createReplicaSlice(channelDetailResource, {actionPrefix: 'channel/detail',effects: {diff --git a/src/store/channel/projection.ts b/src/store/channel/projection.tsindex 90ccbc1eb00..22f38978fa0 100644--- a/src/store/channel/projection.ts+++ b/src/store/channel/projection.ts@@ -1,4 +1,4 @@-import type { ChannelDetail, ChannelListItem } from '@lobechat/types';+import type { ChannelDetail, ChannelJoinableItem, ChannelListItem } from '@lobechat/types';import { defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';import { channelService, type ChannelViewParams } from '@/services/channel';@@ -42,6 +42,19 @@ export const channelListResource = defineReplica<Record<string, never>, ChannelLversion: 1,});+export interface ChannelJoinableParams {+ search: string;+}++/** Public Channels the user can join, per search; only worth what the server says now. */+export const channelJoinableResource = defineReplica<ChannelJoinableParams, ChannelJoinableItem[]>({+ fetcher: ({ search }) => channelService.listJoinable(search),+ key: ({ search }) => search,+ name: 'channelJoinable',+ storage: 'memory',+ version: 1,+});+export const channelDetailResource = defineReplica<ChannelViewParams, ChannelDetail>({fetcher: channelService.detail,key: channelViewKey,diff --git a/src/store/channel/selectors.ts b/src/store/channel/selectors.tsindex 80ecc6d563e..14f6d04a149 100644--- a/src/store/channel/selectors.ts+++ b/src/store/channel/selectors.ts@@ -44,6 +44,8 @@ export const channelSelectors = {/** The caller's direct conversation with an Agent; a direct Channel never belongs to a project. */directByAgent: (agentId: string) => (state: ChannelState) =>state.listMap.all?.find((channel) => channel.agentId === agentId && !channel.projectId),+ /** Public Channels the user can join for a search; undefined while loading. */+ joinable: (search: string) => (state: ChannelState) => state.joinableMap[search],list: (state: ChannelState) => state.listMap.all,/** A listed conversation has a reply in progress, which its row shows until it settles. */listHasPendingWork: (state: ChannelState) =>diff --git a/src/store/channel/store.ts b/src/store/channel/store.tsindex 816cdebb321..bd4c806019e 100644--- a/src/store/channel/store.ts+++ b/src/store/channel/store.ts@@ -1,4 +1,4 @@-import type { ChannelDetail, ChannelListItem } from '@lobechat/types';+import type { ChannelDetail, ChannelJoinableItem, ChannelListItem } from '@lobechat/types';import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';@@ -10,6 +10,8 @@ import type { ChannelOutbox } from './outbox';export interface ChannelState {detailMap: Record<string, ChannelDetail>;detailReplica: ReplicaState<ChannelDetail>;+ joinableMap: Record<string, ChannelJoinableItem[]>;+ joinableReplica: ReplicaState<ChannelJoinableItem[]>;listMap: Record<string, ChannelListItem[]>;listReplica: ReplicaState<ChannelListItem[]>;/** Messages sent from this tab, by conversation, until a loaded page holds them. */@@ -19,6 +21,8 @@ export interface ChannelState {export const initialState: ChannelState = {detailMap: {},detailReplica: createReplicaState(),+ joinableMap: {},+ joinableReplica: createReplicaState(),listMap: {},listReplica: createReplicaState(),outbox: {},