🤯 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
import { agentDisplayName, CHANNEL_LIMITS } from '@lobechat/types';
import { Button, createModal, Flexbox, Icon, Input, Text, useModalContext } from '@lobehub/ui';
import { t } from 'i18next';
import { Hash } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import type { ChannelPersonOption } from '@/services/channel';
import { channelActions } from '@/store/channel';
import type { ChannelAgentDraft } from './agentEnvironment';
import { canSubmitChannelMembers, 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;
/** The project a project Channel belongs to: it seats only that project's Agents. */
projectId: string | null;
}
interface CreateChannelProps {
/** Set when inviting members into a Channel that already exists. */
existing?: ExistingChannel;
onCreated?: (id: string) => void;
/** A new Channel created from a project's sidebar is grouped under that project. */
projectId?: string;
}
const openMemberDialog = (props: CreateChannelProps) =>
createModal({
content: <CreateChannel {...props} />,
footer: null,
title: t(props.existing ? 'invite.title' : 'create', { ns: 'channel' }),
width: 'min(90vw, 800px)',
});
export const openCreateChannel = (onCreated?: (id: string) => void, projectId?: string) =>
openMemberDialog({ onCreated, projectId });
/** The single entry for adding people and Agents to an existing Channel. */
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
* members' names; the sidebar renames it later. Inviting into an existing Channel uses the
* same picker without a name. It also lists the people who can join: workspace members in a
* workspace, mutual contacts in the personal space.
*/
function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
const { t } = useTranslation('channel');
const { close, setCanDismissByClickOutside } = useModalContext();
const [title, setTitle] = useState('');
const [agents, setAgents] = useState<ChannelAgentDraft[]>([]);
const [people, setPeople] = useState<ChannelPersonOption[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>();
const options = useChannelAgentOptions((existing ? existing.projectId : projectId) ?? undefined);
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.
useEffect(() => {
setCanDismissByClickOutside(!dirty && !busy);
}, [busy, dirty, setCanDismissByClickOutside]);
const agentNames = agents.map(({ agentId }) =>
agentDisplayName(
options.agents?.find((agent) => agent.id === agentId),
t('unnamedAgent'),
),
);
// A Channel with no one else in it yet still needs a name the sidebar can show.
const autoTitle =
defaultChannelTitle(
direct
? [existing?.directAgentName || t('unnamedAgent'), ...agentNames, ...people.map(nameOf)]
: [...agentNames, ...people.map(nameOf)],
{
more: (names, count, total) => t('autoTitle.more', { count, names, total }),
separator: t('autoTitle.separator'),
},
CHANNEL_LIMITS.titleLength,
) || t('autoTitle.empty');
// Agents from outside the project join it first; say so before anyone submits.
const joiningProject = options.project
? agentNames.filter((_, index) => !options.project!.memberIds.includes(agents[index].agentId))
: [];
const canSubmit = canSubmitChannelMembers(agents, {
creating: !existing,
people: people.length,
});
const submit = async () => {
if (busy || !canSubmit) return;
setBusy(true);
setError(undefined);
try {
const selections = agents.map(toChannelAgentSelection);
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),
});
close();
} else {
const id = await channelActions.create({
agents: selections,
// The notice above the buttons names who joins the project.
joinProject: true,
projectId,
title: title.trim() || autoTitle,
userIds: people.map((person) => person.userId),
});
close();
onCreated?.(id);
}
} catch (cause) {
console.error('Failed to save Channel members', cause);
setError(cause);
} finally {
setBusy(false);
}
};
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
emptyHint={existing ? undefined : t('create.onlyYou')}
exclude={existing?.agentIds}
options={options}
people={{ channelId: existing?.id, onChange: setPeople, value: people }}
value={agents}
onChange={setAgents}
/>
</Flexbox>
{(!existing || direct) && (
<Flexbox gap={6} inert={busy}>
<label htmlFor="channel-title" style={{ fontWeight: 500 }}>
{t('nameOptional')}
</label>
<Input
id="channel-title"
maxLength={CHANNEL_LIMITS.titleLength}
placeholder={autoTitle}
prefix={<Icon icon={Hash} size={14} />}
value={title}
onChange={(event) => setTitle(event.target.value)}
onPressEnter={() => void submit()}
/>
</Flexbox>
)}
{joiningProject.length > 0 && (
<Text fontSize={12} type="secondary">
{options.project?.name
? t('invite.joinProjectNotice', {
names: joiningProject.join(t('autoTitle.separator')),
project: options.project.name,
})
: t('invite.joinProjectNoticeUnnamed', {
names: joiningProject.join(t('autoTitle.separator')),
})}
</Text>
)}
{error !== undefined && (
<AsyncError error={error} title={t(getChannelSaveErrorKey(error))} variant="inline" />
)}
<Flexbox horizontal align="center" gap={8} justify="flex-end">
{agents.length > 0 && !canSubmit && (
<Text fontSize={12} type="secondary">
{t('environment.resolveRequired')}
</Text>
)}
<Button disabled={busy} onClick={close}>
{t('cancel')}
</Button>
<Button disabled={!canSubmit} loading={busy} type="primary" onClick={() => void submit()}>
{t(existing && !direct ? 'invite.submit' : 'submit')}
</Button>
</Flexbox>
</Flexbox>
);
}