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.

πŸ› fix(project): keep generated project and agent avatars stable while creating (#22871)

AmAzing-a76600b4990f
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 d7bf2d00257..815ced543b9 100644
--- a/apps/server/src/routers/lambda/__tests__/project.create.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/project.create.test.ts
@@ -206,3 +206,37 @@ describe('project.create from a client that still sends a type or a site', () =>
expect(result).not.toHaveProperty('siteError');
});
});
+
+describe('project.create with ids the create form reserved', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.create.mockResolvedValue({
+ coordinatorAgentId: 'agt_reservedAgnt',
+ id: 'prj_reservedProj',
+ name: 'Launch',
+ });
+ mocks.resolveCoordinatorAgents.mockImplementation(async (projects) => projects);
+ });
+
+ it('passes the reserved project and agent ids on to the repository', async () => {
+ await caller('ws-1').create({
+ dedicatedAgentId: 'agt_reservedAgnt',
+ id: 'prj_reservedProj',
+ name: 'Launch',
+ });
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ dedicatedAgentId: 'agt_reservedAgnt', id: 'prj_reservedProj' }),
+ );
+ });
+
+ it.each([
+ { id: 'agt_reservedProj', name: 'Launch' },
+ { id: 'prj_short', name: 'Launch' },
+ { dedicatedAgentId: 'prj_reservedAgnt', name: 'Launch' },
+ { dedicatedAgentId: 'agt_reserved-gnt', name: 'Launch' },
+ ])('rejects an id outside the generated shape: %o', async (input) => {
+ await expect(caller('ws-1').create(input)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index 7a04c0a01b3..3935fd44ef4 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -1,5 +1,7 @@
import {
+ PROJECT_AGENT_ID_REGEX,
PROJECT_DUPLICATE_IDENTIFIER,
+ PROJECT_ID_REGEX,
PROJECT_IDENTIFIER_REGEX,
PROJECT_STATUSES,
PROJECT_VISIBILITIES,
@@ -196,7 +198,15 @@ export const projectRouter = router({
z.object({
avatar: z.string().optional(),
coordinatorAgentId: z.string().optional(),
+ /**
+ * Id reserved for the dedicated main agent, so the avatar the form
+ * previewed is the one it keeps. Ignored when `coordinatorAgentId`
+ * picks an existing agent.
+ */
+ dedicatedAgentId: z.string().regex(PROJECT_AGENT_ID_REGEX).optional(),
description: z.string().optional(),
+ /** Id reserved by the create form; its generated avatar is seeded by it. */
+ id: z.string().regex(PROJECT_ID_REGEX).optional(),
identifier: projectIdentifierInput.optional(),
name: z.string().min(1).max(255),
repository: z
diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.ts
index 6926da27f9e..d3be9082d6e 100644
--- a/packages/database/src/models/__tests__/project.mainAgent.test.ts
+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts
@@ -71,6 +71,34 @@ describe('the main agent a project creates', () => {
]);
});
+ it('takes the ids the create form reserved, so its generated avatars match the preview', async () => {
+ const project = await createProject(repo, {
+ dedicatedAgentId: 'agt_reservedAgnt',
+ id: 'prj_reservedProj',
+ name: 'Reserved',
+ });
+
+ expect(project.id).toBe('prj_reservedProj');
+ expect(project.coordinatorAgentId).toBe('agt_reservedAgnt');
+ // The reserved agent id is not a column of the project.
+ expect(project).not.toHaveProperty('dedicatedAgentId');
+ });
+
+ it('ignores a reserved agent id when the project reuses an existing agent', async () => {
+ const existing = await new AgentModel(serverDB, userId).create({ title: 'Existing' });
+
+ const project = await createProject(repo, {
+ coordinatorAgentId: existing.id,
+ dedicatedAgentId: 'agt_unusedAgent',
+ name: 'Reuse',
+ });
+
+ expect(project.coordinatorAgentId).toBe(existing.id);
+ expect(await serverDB.select().from(agents).where(eq(agents.id, 'agt_unusedAgent'))).toEqual(
+ [],
+ );
+ });
+
it('shares one Project label across the projects of a scope', async () => {
const first = await createProject(repo, { name: 'First' });
const second = await createProject(repo, { name: 'Second' });
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index b97adb98832..f184d9e954b 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -44,7 +44,11 @@ export interface CreateProjectInput {
avatar?: string;
/** Lead the project with an existing agent instead of creating one named after it. */
coordinatorAgentId?: string;
+ /** Id for the agent created to lead the project; ignored with `coordinatorAgentId`. */
+ dedicatedAgentId?: string;
description?: string;
+ /** Id reserved by the caller; generated when omitted. */
+ id?: string;
/** Task prefix for this project; omit to keep the scope's default prefix. */
identifier?: string | null;
name: string;
@@ -59,7 +63,10 @@ export interface CreateProjectInput {
* aggregate, so `ProjectRepository.create` resolves or creates it first and only
* its id reaches this model.
*/
-export interface InsertProjectInput extends Omit<CreateProjectInput, 'repository'> {
+export interface InsertProjectInput extends Omit<
+ CreateProjectInput,
+ 'dedicatedAgentId' | 'repository'
+> {
coordinatorAgentId: string;
}
diff --git a/packages/database/src/models/projectMainAgent.ts b/packages/database/src/models/projectMainAgent.ts
index f209853ecd0..610682593b7 100644
--- a/packages/database/src/models/projectMainAgent.ts
+++ b/packages/database/src/models/projectMainAgent.ts
@@ -65,10 +65,17 @@ const findOrCreateProjectLabel = async (db: LobeChatDatabase, scope: Scope) => {
export const createProjectMainAgent = async (
db: LobeChatDatabase,
scope: Scope,
- input: { avatar?: string; name: string; visibility?: ProjectVisibility },
+ input: {
+ avatar?: string;
+ /** Reserved by the create form so its generated avatar matches the preview. */
+ id?: string;
+ name: string;
+ visibility?: ProjectVisibility;
+ },
) => {
const agent = await new AgentModel(db, scope.userId, scope.workspaceId).create({
...createProjectCoordinatorAgentConfig({ avatar: input.avatar, name: input.name }),
+ ...(input.id && { id: input.id }),
// A project's work outlives a conversation and needs no machine of the
// member's to be online: the cloud sandbox keeps the project's checkout on
// its drive. Left unset, a web client would resolve the agent to no
diff --git a/packages/database/src/repositories/project/index.ts b/packages/database/src/repositories/project/index.ts
index 31f6f5b7bf5..9505cf48661 100644
--- a/packages/database/src/repositories/project/index.ts
+++ b/packages/database/src/repositories/project/index.ts
@@ -24,7 +24,7 @@ export class ProjectRepository {
private readonly workspaceId?: string,
) {}
- async create({ repository, ...input }: CreateProjectInput) {
+ async create({ dedicatedAgentId, repository, ...input }: CreateProjectInput) {
const identifier = normalizeProjectIdentifier(input.identifier);
return this.db.transaction(async (tx) => {
@@ -43,7 +43,12 @@ export class ProjectRepository {
: await createProjectMainAgent(
db,
{ userId: this.userId, workspaceId: this.workspaceId },
- { avatar: input.avatar, name: input.name, visibility: input.visibility },
+ {
+ avatar: input.avatar,
+ id: dedicatedAgentId,
+ name: input.name,
+ visibility: input.visibility,
+ },
);
if (!mainAgent) throw new Error('Agent not found');
diff --git a/packages/types/src/project/index.ts b/packages/types/src/project/index.ts
index 19d853e7b1b..917f954f953 100644
--- a/packages/types/src/project/index.ts
+++ b/packages/types/src/project/index.ts
@@ -1,5 +1,15 @@
export const PROJECT_IDENTIFIER_REGEX = /^[A-Z][A-Z0-9]{2,5}$/;
+/**
+ * Ids the create form reserves for a new project and its dedicated main agent,
+ * in the shape the server would generate them (`idGenerator`). Their generated
+ * avatars are seeded by id, so reserving the ids up front lets the form show
+ * the exact avatars the project and its agent keep after creation.
+ */
+export const PROJECT_ID_REGEX = /^prj_[\dA-Za-z]{12}$/;
+
+export const PROJECT_AGENT_ID_REGEX = /^agt_[\dA-Za-z]{12}$/;
+
/**
* `CONFLICT` messages for a taken project slug or identifier.
*
diff --git a/src/features/AgentHome/StagedProjectHint.tsx b/src/features/AgentHome/StagedProjectHint.tsx
index da42ffc9183..f6292865e4a 100644
--- a/src/features/AgentHome/StagedProjectHint.tsx
+++ b/src/features/AgentHome/StagedProjectHint.tsx
@@ -54,7 +54,12 @@ const StagedProjectHint = memo(() => {
return (
<Flexbox horizontal align={'center'} className={styles.card} gap={12}>
- <ProjectAvatar avatar={directory.projectAvatar} name={directory.projectName} size={32} />
+ <ProjectAvatar
+ avatar={directory.projectAvatar}
+ id={directory.projectId}
+ name={directory.projectName}
+ size={32}
+ />
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
<Text fontSize={14}>
<Trans
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 7252f60c4ac..ed8306b1e7d 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -350,6 +350,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
{project ? (
<ProjectAvatar
avatar={project.projectAvatar}
+ id={project.projectId}
name={project.projectName}
size={18}
/>
diff --git a/src/features/AgentTasks/features/ProjectSelector.tsx b/src/features/AgentTasks/features/ProjectSelector.tsx
index 1db20416495..4d05e7f7c7b 100644
--- a/src/features/AgentTasks/features/ProjectSelector.tsx
+++ b/src/features/AgentTasks/features/ProjectSelector.tsx
@@ -170,7 +170,12 @@ const ProjectSelector = memo<ProjectSelectorProps>(
}
icon={
option.kind === 'project' ? (
- <ProjectAvatar avatar={option.project.avatar} name={option.project.name} size={18} />
+ <ProjectAvatar
+ avatar={option.project.avatar}
+ id={option.project.id}
+ name={option.project.name}
+ size={18}
+ />
) : (
<Icon color={cssVar.colorTextDescription} icon={FolderXIcon} size={16} />
)
diff --git a/src/features/AgentTasks/features/TaskProjectChip.tsx b/src/features/AgentTasks/features/TaskProjectChip.tsx
index 5f260bc09f0..781595e5c0a 100644
--- a/src/features/AgentTasks/features/TaskProjectChip.tsx
+++ b/src/features/AgentTasks/features/TaskProjectChip.tsx
@@ -51,7 +51,7 @@ const TaskProjectChip = ({ projectId }: TaskProjectChipProps) => {
return (
<span data-testid={'task-project-chip'} title={project.name} {...stylex.props(styles.chip)}>
- <ProjectAvatar avatar={project.avatar} name={project.name} size={14} />
+ <ProjectAvatar avatar={project.avatar} id={project.id} name={project.name} size={14} />
{/* `type="secondary"` resolves to the tertiary text colour, under AA at 12px. */}
<Text ellipsis color={cssVar.colorTextSecondary} fontSize={12}>
{project.name}
diff --git a/src/features/AgentTasks/features/TaskProjectValue.tsx b/src/features/AgentTasks/features/TaskProjectValue.tsx
index 37c8df326de..3c95e15ceca 100644
--- a/src/features/AgentTasks/features/TaskProjectValue.tsx
+++ b/src/features/AgentTasks/features/TaskProjectValue.tsx
@@ -31,6 +31,7 @@ const TaskProjectValue = memo<TaskProjectValueProps>(
<>
<ProjectAvatar
avatar={display.project.avatar}
+ id={display.project.id}
name={display.project.name}
size={iconSize}
/>
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index 5df5cbaf3b5..5757c73ee17 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -287,7 +287,7 @@ const TabItem = memo<TabItemProps>(
size={16}
/>
) : meta.avatarSeed ? (
- <ProjectAvatar avatar={meta.avatar} name={meta.avatarSeed} size={16} />
+ <ProjectAvatar avatar={meta.avatar} id={meta.avatarSeed} name={meta.title} size={16} />
) : meta.avatarKind === 'workspace' ? (
<WorkspaceAvatar avatar={meta.avatar} name={meta.title} size={16} />
) : meta.avatar ? (
diff --git a/src/features/MessageList/ChannelConversation.tsx b/src/features/MessageList/ChannelConversation.tsx
index b0afcf5dc15..f08c11fcbdb 100644
--- a/src/features/MessageList/ChannelConversation.tsx
+++ b/src/features/MessageList/ChannelConversation.tsx
@@ -39,7 +39,12 @@ const ChannelConversation = memo<ChannelConversationProps>(({ active, activeAt,
url={CHANNEL_URL(channel.id)}
avatar={
project ? (
- <ProjectAvatar avatar={project.avatar} name={project.name} size={AVATAR_SIZE} />
+ <ProjectAvatar
+ avatar={project.avatar}
+ id={project.id}
+ name={project.name}
+ size={AVATAR_SIZE}
+ />
) : (
<Avatar
avatar={<Icon color={cssVar.colorTextSecondary} icon={HashIcon} size={16} />}
diff --git a/src/features/Projects/CreateFromGithub/Content.tsx b/src/features/Projects/CreateFromGithub/Content.tsx
index 2ea5ae9a18d..d30a5dd336c 100644
--- a/src/features/Projects/CreateFromGithub/Content.tsx
+++ b/src/features/Projects/CreateFromGithub/Content.tsx
@@ -25,6 +25,7 @@ import {
getProjectFieldSuggestions,
isProjectIdentifierValid,
type MainAgentMode,
+ reserveProjectIds,
} from '../createProjectForm';
import MainAgentSection from '../MainAgentSection';
import { useDefaultMainAgent } from '../useDefaultMainAgent';
@@ -66,6 +67,9 @@ const CreateFromGithubContent = () => {
url: '',
});
+ // Taken once per open dialog: the dedicated agent's previewed character is seeded by it.
+ const [reservedIds] = useState(reserveProjectIds);
+
const repository = parseGithubRepository(form.url);
const urlInvalid = Boolean(form.url.trim()) && !repository;
const defaultMainAgentId = useDefaultMainAgent();
@@ -109,6 +113,7 @@ const CreateFromGithubContent = () => {
try {
const project = await createProject({
...buildCreateProjectRequest(createInput, {
+ ids: reservedIds,
mainAgentId,
mainAgentMode: form.mainAgentMode,
}),
@@ -222,6 +227,7 @@ const CreateFromGithubContent = () => {
{repository && (
<MainAgentSection
agentId={mainAgentId}
+ dedicatedAgentId={reservedIds.agentId}
disabled={form.loading}
mode={form.mainAgentMode}
projectName={form.name}
diff --git a/src/features/Projects/CreateProjectContent.tsx b/src/features/Projects/CreateProjectContent.tsx
index 3631c984ac7..05518538211 100644
--- a/src/features/Projects/CreateProjectContent.tsx
+++ b/src/features/Projects/CreateProjectContent.tsx
@@ -19,6 +19,7 @@ import {
isProjectIdentifierValid,
isProjectSlugValid,
type MainAgentMode,
+ reserveProjectIds,
} from './createProjectForm';
import CreateProjectMoreFields from './CreateProjectMoreFields';
import MainAgentSection from './MainAgentSection';
@@ -75,6 +76,8 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
slugConflict: false,
slugEdited: false,
});
+ // Taken once per open modal: both generated avatars are seeded by these ids.
+ const [reservedIds] = useState(reserveProjectIds);
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const mainAgentId = form.mainAgentId ?? inboxAgentId;
const createInput = getCreateProjectInput(form);
@@ -117,6 +120,7 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
const project = await createProject(
buildCreateProjectRequest(createInput, {
avatar: form.avatar,
+ ids: reservedIds,
mainAgentId,
mainAgentMode: form.mainAgentMode,
}),
@@ -169,6 +173,7 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
<ProjectAvatarField
avatar={form.avatar}
disabled={form.loading}
+ id={reservedIds.projectId}
name={form.name}
onChange={(avatar) => updateForm({ avatar })}
onUploadingChange={(avatarUploading) => updateForm({ avatarUploading })}
@@ -185,6 +190,7 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
</Flexbox>
<MainAgentSection
agentId={mainAgentId}
+ dedicatedAgentId={reservedIds.agentId}
disabled={form.loading}
mode={form.mainAgentMode}
projectAvatar={form.avatar}
diff --git a/src/features/Projects/MainAgentSection.tsx b/src/features/Projects/MainAgentSection.tsx
index eaafa3f257e..2b6fb2575e4 100644
--- a/src/features/Projects/MainAgentSection.tsx
+++ b/src/features/Projects/MainAgentSection.tsx
@@ -26,6 +26,8 @@ const styles = stylex.create({
interface MainAgentSectionProps {
agentId?: string;
+ /** Id reserved for the dedicated agent: seeds the character it keeps after creation. */
+ dedicatedAgentId: string;
disabled?: boolean;
mode: MainAgentMode;
onAgentChange: (agentId: string) => void;
@@ -41,7 +43,16 @@ interface MainAgentSectionProps {
* created, so its row previews the agent the server will create.
*/
const MainAgentSection = memo<MainAgentSectionProps>(
- ({ agentId, disabled, mode, onAgentChange, onModeChange, projectAvatar, projectName }) => {
+ ({
+ agentId,
+ dedicatedAgentId,
+ disabled,
+ mode,
+ onAgentChange,
+ onModeChange,
+ projectAvatar,
+ projectName,
+ }) => {
const { t } = useTranslation('project');
const name = projectName.trim();
const dedicatedTitle = name ? createProjectCoordinatorAgentConfig({ name }).title : undefined;
@@ -63,8 +74,10 @@ const MainAgentSection = memo<MainAgentSectionProps>(
/>
{mode === 'dedicated' ? (
<div {...stylex.props(styles.preview)}>
- {/* Without a project avatar the agent draws a generated character. */}
+ {/* Without a project avatar the agent draws the generated character
+ its reserved id seeds, the one it keeps after creation. */}
<AgentAvatar
+ agentId={dedicatedAgentId}
avatar={projectAvatar}
name={dedicatedTitle}
size={22}
diff --git a/src/features/Projects/ProjectAvatar/index.tsx b/src/features/Projects/ProjectAvatar/index.tsx
index e8521187e97..0469117d96f 100644
--- a/src/features/Projects/ProjectAvatar/index.tsx
+++ b/src/features/Projects/ProjectAvatar/index.tsx
@@ -1,25 +1,18 @@
import { Avatar } from '@lobehub/ui';
import { memo } from 'react';
-export interface ProjectAvatarProps {
- /** The project's logo: an emoji or image URL. */
- avatar?: string | null;
- name: string;
+import { type ProjectAvatarSource, toProjectAvatarProps } from './seed';
+
+export interface ProjectAvatarProps extends ProjectAvatarSource {
size?: number;
}
/**
- * A project's logo, or the generated avatar `@lobehub/ui` seeds from its name
- * when it has none β€” the same one the project switcher shows.
+ * A project's logo, or the gradient `@lobehub/ui` generates from its id when it
+ * has none β€” the same one the project switcher shows.
*/
-const ProjectAvatar = memo<ProjectAvatarProps>(({ avatar, name, size = 20 }) => (
- <Avatar
- avatar={avatar || undefined}
- shape={'square'}
- size={size}
- style={{ flex: 'none' }}
- title={name}
- />
+const ProjectAvatar = memo<ProjectAvatarProps>(({ size = 20, ...source }) => (
+ <Avatar {...toProjectAvatarProps(source)} shape={'square'} size={size} style={{ flex: 'none' }} />
));
ProjectAvatar.displayName = 'ProjectAvatar';
@@ -28,6 +21,6 @@ export default ProjectAvatar;
// `avatar` is an emoji or image URL, not a component: `Icon` would pass it to
// createElement as a tag name and crash the whole page.
-export const projectIcon = (project: { avatar?: string | null; name: string }) => (
- <ProjectAvatar avatar={project.avatar} name={project.name} size={18} />
+export const projectIcon = (project: { avatar?: string | null; id: string; name: string }) => (
+ <ProjectAvatar avatar={project.avatar} id={project.id} name={project.name} size={18} />
);
diff --git a/src/features/Projects/ProjectAvatar/seed.test.ts b/src/features/Projects/ProjectAvatar/seed.test.ts
new file mode 100644
index 00000000000..501d47e3307
--- /dev/null
+++ b/src/features/Projects/ProjectAvatar/seed.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { toProjectAvatarProps } from './seed';
+
+describe('toProjectAvatarProps', () => {
+ it('seeds the generated avatar from the project id, so typing or renaming keeps it', () => {
+ const typing = toProjectAvatarProps({ id: 'prj_1', name: 'A' });
+ const typed = toProjectAvatarProps({ id: 'prj_1', name: 'Apollo' });
+
+ expect(typed.title).toBe(typing.title);
+ expect(typed).toEqual({ alt: 'Apollo', avatar: undefined, title: 'prj_1' });
+ });
+
+ it("passes the project's own logo through", () => {
+ expect(toProjectAvatarProps({ avatar: 'πŸš€', id: 'prj_1', name: 'Apollo' }).avatar).toBe('πŸš€');
+ });
+});
diff --git a/src/features/Projects/ProjectAvatar/seed.ts b/src/features/Projects/ProjectAvatar/seed.ts
new file mode 100644
index 00000000000..f56b4630886
--- /dev/null
+++ b/src/features/Projects/ProjectAvatar/seed.ts
@@ -0,0 +1,20 @@
+export interface ProjectAvatarSource {
+ /** The project's logo: an emoji or image URL. */
+ avatar?: string | null;
+ /**
+ * Seed of the generated avatar: the project id, so renaming a project keeps
+ * its avatar. The create modal passes the id it reserved for the project.
+ */
+ id: string;
+ name: string;
+}
+
+/**
+ * `@lobehub/ui`'s Avatar seeds its generated gradient from `title`, so the id
+ * goes there and the name only labels the avatar through `alt`.
+ */
+export const toProjectAvatarProps = ({ avatar, id, name }: ProjectAvatarSource) => ({
+ alt: name,
+ avatar: avatar || undefined,
+ title: id,
+});
diff --git a/src/features/Projects/ProjectAvatarField.tsx b/src/features/Projects/ProjectAvatarField.tsx
index 450d5153dc4..c020b821391 100644
--- a/src/features/Projects/ProjectAvatarField.tsx
+++ b/src/features/Projects/ProjectAvatarField.tsx
@@ -52,7 +52,9 @@ interface ProjectAvatarFieldProps {
/** The rest of the row; an image dropped on it lands here as well. */
children: ReactNode;
disabled?: boolean;
- /** Seeds the generated avatar shown until the user picks one. */
+ /** The project's reserved id: seeds the generated avatar shown until one is picked. */
+ id: string;
+ /** Labels the avatar. */
name: string;
onChange: (avatar?: string) => void;
/** An upload is in flight; the avatar it brings arrives through `onChange` later. */
@@ -64,7 +66,7 @@ interface ProjectAvatarFieldProps {
* image, or drop an image anywhere on the row.
*/
const ProjectAvatarField = memo<ProjectAvatarFieldProps>(
- ({ avatar, children, disabled, name, onChange, onUploadingChange }) => {
+ ({ avatar, children, disabled, id, name, onChange, onUploadingChange }) => {
const { t } = useTranslation('project');
const { upload, uploading } = useProjectAvatarUpload({ onChange, onUploadingChange });
@@ -92,9 +94,11 @@ const ProjectAvatarField = memo<ProjectAvatarFieldProps>(
role={'button'}
>
{/* Until one is picked, the project's own generated avatar: the one
- it keeps after creation, seeded by the name as it is typed. */}
+ it keeps after creation, seeded by its reserved id so typing the
+ name does not reshuffle it. */}
<ProjectAvatar
avatar={value}
+ id={id}
name={name.trim() || t('create.title')}
size={TILE_SIZE}
/>
diff --git a/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx b/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx
index 27e6af6b1e0..c1494291673 100644
--- a/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx
+++ b/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx
@@ -108,7 +108,7 @@ function AssociateTopicContent({ topicId, agentId }: { topicId: string; agentId?
value: p.id,
label: (
<Flexbox horizontal align="center" gap={8}>
- <ProjectAvatar avatar={p.avatar} name={p.name} />
+ <ProjectAvatar avatar={p.avatar} id={p.id} name={p.name} />
{p.name}
</Flexbox>
),
diff --git a/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx
index 143b8db0f65..b4199b9fe6a 100644
--- a/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx
+++ b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx
@@ -85,7 +85,7 @@ function BindDirectoryContent(options: BindDirectoryOptions) {
...projects.map((project) => ({
label: (
<Flexbox horizontal align="center" gap={8}>
- <ProjectAvatar avatar={project.avatar} name={project.name} />
+ <ProjectAvatar avatar={project.avatar} id={project.id} name={project.name} />
{project.name}
</Flexbox>
),
diff --git a/src/features/Projects/createProjectForm.test.ts b/src/features/Projects/createProjectForm.test.ts
index ad263bc416e..10b6a3a9e1e 100644
--- a/src/features/Projects/createProjectForm.test.ts
+++ b/src/features/Projects/createProjectForm.test.ts
@@ -1,3 +1,4 @@
+import { PROJECT_AGENT_ID_REGEX, PROJECT_ID_REGEX } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
@@ -11,6 +12,7 @@ import {
isProjectIdentifierValid,
isProjectSlugValid,
PROJECT_SLUG_MAX_LENGTH,
+ reserveProjectIds,
} from './createProjectForm';
describe('createProjectForm', () => {
@@ -132,40 +134,66 @@ describe('createProjectForm', () => {
).toBeNull();
});
- it('leaves the main agent out so the server creates a dedicated one', () => {
+ const ids = { agentId: 'agt_AAAAAAAAAAAA', projectId: 'prj_BBBBBBBBBBBB' };
+
+ it('sends the reserved ids, so the server creates a dedicated agent with them', () => {
expect(
buildCreateProjectRequest(
{ name: 'Launch' },
- { avatar: 'πŸš€', mainAgentId: 'inbox', mainAgentMode: 'dedicated' },
+ { avatar: 'πŸš€', ids, mainAgentId: 'inbox', mainAgentMode: 'dedicated' },
),
- ).toEqual({ avatar: 'πŸš€', name: 'Launch' });
+ ).toEqual({
+ avatar: 'πŸš€',
+ dedicatedAgentId: 'agt_AAAAAAAAAAAA',
+ id: 'prj_BBBBBBBBBBBB',
+ name: 'Launch',
+ });
});
it('creates a dedicated main agent by default', () => {
expect(
buildCreateProjectRequest(
{ name: 'Launch' },
- { mainAgentId: 'inbox', mainAgentMode: DEFAULT_MAIN_AGENT_MODE },
+ { ids, mainAgentId: 'inbox', mainAgentMode: DEFAULT_MAIN_AGENT_MODE },
),
- ).toEqual({ name: 'Launch' });
+ ).toEqual({ dedicatedAgentId: 'agt_AAAAAAAAAAAA', id: 'prj_BBBBBBBBBBBB', name: 'Launch' });
});
- it('sends the picked agent when the project reuses an existing one', () => {
+ it('sends the picked agent, and no dedicated id, when the project reuses an existing one', () => {
expect(
buildCreateProjectRequest(
{ name: 'Launch', slug: 'launch' },
- { mainAgentId: 'agt_1', mainAgentMode: 'existing' },
+ { ids, mainAgentId: 'agt_1', mainAgentMode: 'existing' },
),
- ).toEqual({ coordinatorAgentId: 'agt_1', name: 'Launch', slug: 'launch' });
+ ).toEqual({
+ coordinatorAgentId: 'agt_1',
+ id: 'prj_BBBBBBBBBBBB',
+ name: 'Launch',
+ slug: 'launch',
+ });
});
it('sends neither a project type nor a site, whatever the caller passes', () => {
expect(
buildCreateProjectRequest({ name: 'Launch' }, {
+ ids,
mainAgentMode: 'dedicated',
siteOrigin: 'https://launch.dev',
type: 'web',
} as never),
- ).toEqual({ name: 'Launch' });
+ ).toEqual({ dedicatedAgentId: 'agt_AAAAAAAAAAAA', id: 'prj_BBBBBBBBBBBB', name: 'Launch' });
+ });
+});
+
+describe('reserveProjectIds', () => {
+ it('reserves ids in the shape the create router accepts', () => {
+ const reserved = reserveProjectIds();
+
+ expect(reserved.projectId).toMatch(PROJECT_ID_REGEX);
+ expect(reserved.agentId).toMatch(PROJECT_AGENT_ID_REGEX);
+ });
+
+ it('reserves fresh ids each time a form opens', () => {
+ expect(reserveProjectIds()).not.toEqual(reserveProjectIds());
});
});
diff --git a/src/features/Projects/createProjectForm.ts b/src/features/Projects/createProjectForm.ts
index 721f9caf41f..c78d0b89ff0 100644
--- a/src/features/Projects/createProjectForm.ts
+++ b/src/features/Projects/createProjectForm.ts
@@ -4,6 +4,7 @@ import {
PROJECT_IDENTIFIER_REGEX,
type ProjectDuplicateField,
} from '@lobechat/types';
+import { createNanoId } from '@lobechat/utils';
import { kebabCase } from 'es-toolkit';
import { pinyin } from 'pinyin-pro';
@@ -120,8 +121,28 @@ export type MainAgentMode = 'dedicated' | 'existing';
*/
export const DEFAULT_MAIN_AGENT_MODE: MainAgentMode = 'dedicated';
+export interface ReservedProjectIds {
+ /** Id of the dedicated main agent, used only when the project creates one. */
+ agentId: string;
+ projectId: string;
+}
+
+const reserveIdSuffix = createNanoId(12);
+
+/**
+ * Ids for the project and its dedicated agent, taken once when the create form
+ * opens. Generated avatars are seeded by id, so the form previews the very
+ * avatars both keep after creation, and typing the name no longer reshuffles
+ * them. Same shape as the server's `idGenerator` (`PROJECT_ID_REGEX`).
+ */
+export const reserveProjectIds = (): ReservedProjectIds => ({
+ agentId: `agt_${reserveIdSuffix()}`,
+ projectId: `prj_${reserveIdSuffix()}`,
+});
+
export interface CreateProjectExtras {
avatar?: string;
+ ids: ReservedProjectIds;
/** The picked agent; only sent when the project reuses an existing agent. */
mainAgentId?: string;
mainAgentMode: MainAgentMode;
@@ -133,9 +154,12 @@ export interface CreateProjectExtras {
*/
export const buildCreateProjectRequest = (
input: NonNullable<ReturnType<typeof getCreateProjectInput>>,
- { avatar, mainAgentId, mainAgentMode }: CreateProjectExtras,
+ { avatar, ids, mainAgentId, mainAgentMode }: CreateProjectExtras,
) => ({
...input,
+ id: ids.projectId,
...(avatar ? { avatar } : {}),
- ...(mainAgentMode === 'existing' && mainAgentId ? { coordinatorAgentId: mainAgentId } : {}),
+ ...(mainAgentMode === 'existing' && mainAgentId
+ ? { coordinatorAgentId: mainAgentId }
+ : { dedicatedAgentId: ids.agentId }),
});
diff --git a/src/features/RouteMeta/ProjectDynamicMeta.test.ts b/src/features/RouteMeta/ProjectDynamicMeta.test.ts
index 3f4c4ddf5b6..39b26cf90d7 100644
--- a/src/features/RouteMeta/ProjectDynamicMeta.test.ts
+++ b/src/features/RouteMeta/ProjectDynamicMeta.test.ts
@@ -67,13 +67,13 @@ describe('useProjectTabAvatar', () => {
useProjectStore.setState({ projectDetailMap: {} });
});
- it('seeds the generated avatar from the project name when there is no logo', () => {
+ it('seeds the generated avatar from the project id, so a rename keeps it', () => {
seedStores();
const { result } = renderHook(() => useProjectTabAvatar({ projectId: 'prj_1' }));
// `null`, not `undefined`: the project has loaded, so a cached logo is stale.
- expect(result.current).toEqual({ avatar: null, avatarSeed: 'Alpha' });
+ expect(result.current).toEqual({ avatar: null, avatarSeed: 'prj_1' });
});
it("passes the project's own logo through", () => {
@@ -87,7 +87,7 @@ describe('useProjectTabAvatar', () => {
const { result } = renderHook(() => useProjectTabAvatar({ projectId: 'prj_1' }));
- expect(result.current).toEqual({ avatar: 'πŸš€', avatarSeed: 'Alpha' });
+ expect(result.current).toEqual({ avatar: 'πŸš€', avatarSeed: 'prj_1' });
});
it('publishes no avatar before the project detail lands', () => {
@@ -110,7 +110,7 @@ describe('ProjectSectionDynamicMeta', () => {
expect(onResolve).toHaveBeenLastCalledWith({
avatar: null,
- avatarSeed: 'Alpha',
+ avatarSeed: 'prj_1',
backgroundColor: undefined,
title: undefined,
});
diff --git a/src/features/RouteMeta/ProjectDynamicMeta.tsx b/src/features/RouteMeta/ProjectDynamicMeta.tsx
index 798c49db956..857948aa51f 100644
--- a/src/features/RouteMeta/ProjectDynamicMeta.tsx
+++ b/src/features/RouteMeta/ProjectDynamicMeta.tsx
@@ -11,6 +11,7 @@ import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';
interface ProjectIdentity {
/** `null` once the project has loaded without a logo. */
avatar?: string | null;
+ id?: string;
name?: string;
}
@@ -24,7 +25,7 @@ const useProjectIdentity = (params: RouteMetaParams): ProjectIdentity => {
if (!project) return {};
- return { avatar: project.avatar || null, name: project.name || undefined };
+ return { avatar: project.avatar || null, id: project.id, name: project.name || undefined };
};
export const useProjectConversationTitle = (params: RouteMetaParams): string | undefined => {
@@ -37,13 +38,13 @@ export const useProjectConversationTitle = (params: RouteMetaParams): string | u
};
/**
- * The project's own avatar, seeded from its name like every other project
+ * The project's own avatar, seeded from its id like every other project
* avatar, so its tabs match the project switcher.
*/
export const useProjectTabAvatar = (params: RouteMetaParams) => {
- const { avatar, name } = useProjectIdentity(params);
+ const { avatar, id } = useProjectIdentity(params);
- return { avatar, avatarSeed: name };
+ return { avatar, avatarSeed: id };
};
const ProjectConversationDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
diff --git a/src/services/project.ts b/src/services/project.ts
index 4a358eb2900..02e7dd324f5 100644
--- a/src/services/project.ts
+++ b/src/services/project.ts
@@ -58,7 +58,9 @@ class ProjectService {
params: {
avatar?: string;
coordinatorAgentId?: string;
+ dedicatedAgentId?: string;
description?: string;
+ id?: string;
identifier?: string;
name: string;
repository?: { defaultBranch?: string; name: string; url: string };
diff --git a/src/spa/router/routeMeta.ts b/src/spa/router/routeMeta.ts
index 3590794344c..de8b49e87e6 100644
--- a/src/spa/router/routeMeta.ts
+++ b/src/spa/router/routeMeta.ts
@@ -23,7 +23,7 @@ export interface DynamicRouteMeta {
*/
avatarKind?: RouteAvatarKind;
/**
- * Name a generated avatar is seeded from, for an entity that draws one when it
+ * Id a generated avatar is seeded from, for an entity that draws one when it
* has no image of its own (a project). Unset keeps the initials fallback.
*/
avatarSeed?: string;
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index aa800cdf24c..21bc4b06d86 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -50,6 +50,10 @@ interface ProjectStore extends ProjectStoreState {
createProject: (input: {
avatar?: string;
coordinatorAgentId?: string;
+ /** Reserved id of the dedicated main agent; see `reserveProjectIds`. */
+ dedicatedAgentId?: string;
+ /** Reserved project id; see `reserveProjectIds`. */
+ id?: string;
identifier?: string;
name: string;
/** GitHub repository to attach as the project's environment, in the same write. */