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(project): avatar and main agent choice when creating a project (#22091)

LiJian8374a8045ac0
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index ef5b7e66e48..99f7f6d591c 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -31,12 +31,20 @@
"acceptance.success.start": "Project started",
"acceptance.title": "Acceptance",
"create.action": "Create project",
+ "create.avatarHint": "Pick an emoji or upload an image. You can also drop an image here.",
+ "create.avatarInvalidType": "Use a JPG, PNG, GIF, or WEBP image.",
+ "create.avatarUploadFailed": "Couldn't upload the image. Try again.",
"create.identifierDescription": "Replaces the task number prefix for this project, for example ACE. Leave it empty to use the default prefix.",
"create.identifierInvalid": "Use 3–6 uppercase letters or numbers, starting with a letter.",
"create.identifierLabel": "Identifier (optional)",
"create.identifierPlaceholder": "ACE",
+ "create.mainAgentDedicatedDescription": "Creates an agent named after the project, with its avatar and the Project label. It stays in your agents list. Your choice is reused next time.",
+ "create.mainAgentDedicatedPlaceholder": "Named after the project",
+ "create.mainAgentDedicatedTag": "New",
"create.mainAgentDescription": "Manages this project’s conversations, tasks, and goals. Your choice is reused next time.",
"create.mainAgentLabel": "Main agent",
+ "create.mainAgentMode.dedicated": "Create a dedicated agent",
+ "create.mainAgentMode.existing": "Use an existing agent",
"create.mainAgentPlaceholder": "Select an agent",
"create.nameLabel": "Project name",
"create.namePlaceholder": "What are you working on?",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 1dd39a80c16..75501d7c85f 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -31,12 +31,20 @@
"acceptance.success.start": "项目已启动",
"acceptance.title": "验收",
"create.action": "创建项目",
+ "create.avatarHint": "选择表情或上传图片,也可以把图片拖到这里",
+ "create.avatarInvalidType": "请使用 JPG、PNG、GIF 或 WEBP 图片",
+ "create.avatarUploadFailed": "图片上传失败,请重试",
"create.identifierDescription": "填写后替换本项目任务编号的前缀,例如 ACE;不填则使用默认前缀。",
"create.identifierInvalid": "请输入 3–6 位大写字母或数字,并以字母开头。",
"create.identifierLabel": "项目标识(可选)",
"create.identifierPlaceholder": "ACE",
+ "create.mainAgentDedicatedDescription": "用项目名称和头像新建一个 Agent,并打上 Project 标签,之后可以在助理列表里找到它。下次新建项目时会沿用这次的选择。",
+ "create.mainAgentDedicatedPlaceholder": "以项目名称命名",
+ "create.mainAgentDedicatedTag": "新建",
"create.mainAgentDescription": "负责管理项目里的对话、任务和目标,下次新建项目时会沿用这次的选择。",
"create.mainAgentLabel": "主 Agent",
+ "create.mainAgentMode.dedicated": "新建专属 Agent",
+ "create.mainAgentMode.existing": "选择已有 Agent",
"create.mainAgentPlaceholder": "选择一个 Agent",
"create.nameLabel": "项目名称",
"create.namePlaceholder": "你正在推进什么事情?",
diff --git a/packages/builtin-agents/src/agents/project-coordinator/index.test.ts b/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
index 56c9e4b31df..68e2a175ac8 100644
--- a/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
+++ b/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
@@ -19,7 +19,7 @@ describe('createProjectCoordinatorAgentConfig', () => {
'The current project, its member agents, linked knowledge bases and open tasks are provided with each message; rely on them over anything you remember.',
'Help the user resume work, turn intent into concrete tasks and goals, use project resources, and coordinate project agents.',
].join('\n'),
- title: 'LobeHub Coordinator',
+ title: 'LobeHub Project Agent',
});
});
@@ -37,6 +37,6 @@ describe('createProjectCoordinatorAgentConfig', () => {
it('builds the config for a project without an identifier', () => {
const config = createProjectCoordinatorAgentConfig({ name: 'LobeHub' });
- expect(config.title).toBe('LobeHub Coordinator');
+ expect(config.title).toBe('LobeHub Project Agent');
});
});
diff --git a/packages/builtin-agents/src/agents/project-coordinator/index.ts b/packages/builtin-agents/src/agents/project-coordinator/index.ts
index c7bc1b2b1b5..22b4684d94e 100644
--- a/packages/builtin-agents/src/agents/project-coordinator/index.ts
+++ b/packages/builtin-agents/src/agents/project-coordinator/index.ts
@@ -6,9 +6,10 @@ export interface ProjectCoordinatorContext {
}
/**
- * Project coordinators are provisioned once per project, so they cannot use a
- * shared reserved builtin slug. Keep their default configuration here with the
- * other product-owned agents, then materialize it into each project's agent row.
+ * The main agent a project creates for itself is provisioned once per project,
+ * so it cannot use a shared reserved builtin slug. Keep its default
+ * configuration here with the other product-owned agents, then materialize it
+ * into the project's agent row.
*
* The systemRole only states the role. Everything about the project itself —
* name, members, linked knowledge, open tasks — is injected live on every turn
@@ -26,5 +27,5 @@ export const createProjectCoordinatorAgentConfig = ({
'The current project, its member agents, linked knowledge bases and open tasks are provided with each message; rely on them over anything you remember.',
'Help the user resume work, turn intent into concrete tasks and goals, use project resources, and coordinate project agents.',
].join('\n'),
- title: `${name} Coordinator`,
+ title: `${name} Project Agent`,
});
diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.ts
new file mode 100644
index 00000000000..9536acf1517
--- /dev/null
+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts
@@ -0,0 +1,151 @@
+import { and, eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agentLabelAssignments,
+ agentLabels,
+ agents,
+ resourcePermissions,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentModel } from '../agent';
+import { AgentLabelModel } from '../agentLabel';
+import type { CreateProjectInput } from '../project';
+import { ProjectModel } from '../project';
+import { PROJECT_AGENT_LABEL } from '../projectMainAgent';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'project-main-agent-user';
+const memberId = 'project-main-agent-member';
+const workspaceId = 'project-main-agent-workspace';
+let projectIdentifierSequence = 0;
+
+const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>
+ projectModel.create({
+ ...input,
+ identifier: `M${String(++projectIdentifierSequence).padStart(5, '0')}`,
+ });
+
+const labelsOf = async (agentId: string) =>
+ serverDB
+ .select({ id: agentLabels.id, name: agentLabels.name, workspaceId: agentLabels.workspaceId })
+ .from(agentLabelAssignments)
+ .innerJoin(agentLabels, eq(agentLabels.id, agentLabelAssignments.labelId))
+ .where(eq(agentLabelAssignments.agentId, agentId));
+
+describe('the main agent a project creates', () => {
+ const model = new ProjectModel(serverDB, userId);
+
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: memberId }]);
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await serverDB.delete(users);
+ });
+
+ it('is an ordinary agent named after the project, wearing its avatar and the Project label', async () => {
+ const project = await createProject(model, { avatar: '🚀', name: 'Apollo' });
+
+ const [agent] = await serverDB
+ .select()
+ .from(agents)
+ .where(eq(agents.id, project.coordinatorAgentId!));
+ expect(agent).toEqual(
+ expect.objectContaining({ avatar: '🚀', title: 'Apollo Project Agent', virtual: false }),
+ );
+ expect(await labelsOf(agent.id)).toEqual([
+ expect.objectContaining({ name: PROJECT_AGENT_LABEL, workspaceId: null }),
+ ]);
+ // The label shows up in the agents list with the agent counted under it.
+ expect(await new AgentLabelModel(serverDB, userId).query()).toEqual([
+ expect.objectContaining({ name: PROJECT_AGENT_LABEL, usageCount: 1 }),
+ ]);
+ });
+
+ it('shares one Project label across the projects of a scope', async () => {
+ const first = await createProject(model, { name: 'First' });
+ const second = await createProject(model, { name: 'Second' });
+
+ const [firstLabel] = await labelsOf(first.coordinatorAgentId!);
+ const [secondLabel] = await labelsOf(second.coordinatorAgentId!);
+ expect(secondLabel.id).toBe(firstLabel.id);
+ expect(
+ await serverDB.select().from(agentLabels).where(eq(agentLabels.userId, userId)),
+ ).toHaveLength(1);
+ });
+
+ it('reuses a Project label the user made themselves, but not an archived one', async () => {
+ const labels = new AgentLabelModel(serverDB, userId);
+ const archived = await labels.create({ name: PROJECT_AGENT_LABEL });
+ await labels.update(archived.id, { archived: true });
+
+ const first = await createProject(model, { name: 'First' });
+ const [label] = await labelsOf(first.coordinatorAgentId!);
+ expect(label.id).not.toBe(archived.id);
+
+ const second = await createProject(model, { name: 'Second' });
+ expect(await labelsOf(second.coordinatorAgentId!)).toEqual([
+ expect.objectContaining({ id: label.id }),
+ ]);
+ });
+
+ it('labels nothing when the project is led by a picked agent', async () => {
+ const picked = await new AgentModel(serverDB, userId).create({ title: 'Planner' });
+
+ await createProject(model, { coordinatorAgentId: picked.id, name: 'Picked' });
+
+ expect(await labelsOf(picked.id)).toEqual([]);
+ expect(
+ await serverDB.select().from(agentLabels).where(eq(agentLabels.userId, userId)),
+ ).toHaveLength(0);
+ });
+
+ it('shares the workspace label between members and opens a public agent to the workspace', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Main Agent Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const owner = new ProjectModel(serverDB, userId, workspaceId);
+ const member = new ProjectModel(serverDB, memberId, workspaceId);
+
+ const shared = await createProject(owner, { name: 'Shared', visibility: 'public' });
+ const own = await createProject(member, { name: 'Own', visibility: 'private' });
+
+ const [sharedLabel] = await labelsOf(shared.coordinatorAgentId!);
+ const [ownLabel] = await labelsOf(own.coordinatorAgentId!);
+ expect(sharedLabel).toEqual(
+ expect.objectContaining({ name: PROJECT_AGENT_LABEL, workspaceId }),
+ );
+ expect(ownLabel.id).toBe(sharedLabel.id);
+
+ const agentIds = [shared.coordinatorAgentId!, own.coordinatorAgentId!];
+ expect(
+ await serverDB
+ .select({ visibility: agents.visibility })
+ .from(agents)
+ .where(eq(agents.id, shared.coordinatorAgentId!)),
+ ).toEqual([{ visibility: 'public' }]);
+ expect(
+ await serverDB
+ .select({
+ accessLevel: resourcePermissions.accessLevel,
+ resourceId: resourcePermissions.resourceId,
+ })
+ .from(resourcePermissions)
+ .where(
+ and(
+ eq(resourcePermissions.resourceType, 'agent'),
+ inArray(resourcePermissions.resourceId, agentIds),
+ ),
+ ),
+ ).toEqual([{ accessLevel: 'edit', resourceId: shared.coordinatorAgentId }]);
+ });
+});
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index a19f2c8ba6b..55aa506e8a3 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -208,9 +208,24 @@ describe('ProjectModel', () => {
});
it('tells whether replacing a main agent retires it', async () => {
- const project = await createProject(model, { name: 'Disposition' });
+ // Earlier projects were led by a virtual coordinator created for them.
+ const legacy = await new AgentModel(serverDB, userId).create({
+ title: 'Disposition Coordinator',
+ virtual: true,
+ });
+ const project = await createProject(model, {
+ coordinatorAgentId: legacy.id,
+ name: 'Disposition',
+ });
const inbox = (await new AgentModel(serverDB, userId).getBuiltinAgent(INBOX_SESSION_ID))!;
const user = await new AgentModel(serverDB, userId).create({ title: 'Planner' });
+ // The agent a project creates now is the user's to keep.
+ const created = await createProject(model, { name: 'Created' });
+ expect(
+ await model.isDedicatedCoordinator(created.coordinatorAgentId, {
+ exceptProjectId: created.id,
+ }),
+ ).toBe(false);
// The project's own lead is ignored only when asked about handing it over.
expect(
@@ -286,8 +301,8 @@ describe('ProjectModel', () => {
expect(project.coordinatorAgentId).toBeTruthy();
expect(
await serverDB.select().from(agents).where(eq(agents.id, project.coordinatorAgentId)),
- ).toEqual([expect.objectContaining({ virtual: true })]);
- expect(await new AgentModel(serverDB, userId).queryAgents()).not.toContainEqual(
+ ).toEqual([expect.objectContaining({ title: 'Apollo Project Agent', virtual: false })]);
+ expect(await new AgentModel(serverDB, userId).queryAgents()).toContainEqual(
expect.objectContaining({ id: project.coordinatorAgentId }),
);
expect(await model.listAgents(project.id)).toEqual([
@@ -302,9 +317,10 @@ describe('ProjectModel', () => {
expect(updated?.name).toBe('Apollo 2');
expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
expect(await model.findById(project.id)).toBeNull();
+ // The main agent is an ordinary agent and stays with the user.
expect(
await serverDB.select().from(agents).where(eq(agents.id, project.coordinatorAgentId)),
- ).toHaveLength(0);
+ ).toHaveLength(1);
});
it('resolves a project by slug without escaping the current scope', async () => {
@@ -505,7 +521,7 @@ describe('ProjectModel', () => {
expect(await owner.findById(project.id)).toBeNull();
expect(
await serverDB.select().from(agents).where(eq(agents.id, project.coordinatorAgentId)),
- ).toHaveLength(0);
+ ).toHaveLength(1);
});
it('lists the main agent first whatever order the other members carry', async () => {
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 52209d0a024..32f13611993 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -1,4 +1,4 @@
-import { BUILTIN_AGENT_SLUGS, createProjectCoordinatorAgentConfig } from '@lobechat/builtin-agents';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { INBOX_SESSION_ID } from '@lobechat/const';
import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';
import { and, asc, desc, eq, inArray, isNull, max, ne, or, sql } from 'drizzle-orm';
@@ -26,11 +26,12 @@ import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { AgentModel } from './agent';
import { EnvironmentModel } from './environment';
+import { createProjectMainAgent } from './projectMainAgent';
import { topicHasGoal } from './topicGoal';
export interface CreateProjectInput {
avatar?: string;
- /** Lead the project with an existing agent instead of provisioning a dedicated one. */
+ /** Lead the project with an existing agent instead of creating one named after it. */
coordinatorAgentId?: string;
description?: string;
/** Task prefix for this project; omit to keep the scope's default prefix. */
@@ -155,16 +156,11 @@ export class ProjectModel {
return this.db.transaction(async (tx) => {
const coordinator = input.coordinatorAgentId
? await this.findAccessibleAgent(tx as LobeChatDatabase, input.coordinatorAgentId)
- : await new AgentModel(tx as LobeChatDatabase, this.userId, this.workspaceId).create({
- ...createProjectCoordinatorAgentConfig({
- avatar: input.avatar,
- description: input.description,
- identifier,
- name: input.name,
- }),
- visibility: input.visibility,
- virtual: true,
- });
+ : await createProjectMainAgent(
+ tx as LobeChatDatabase,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { avatar: input.avatar, name: input.name, visibility: input.visibility },
+ );
if (!coordinator) throw new Error('Agent not found');
if (input.coordinatorAgentId) {
this.assertSharedResource(
@@ -230,6 +226,8 @@ export class ProjectModel {
/**
* A coordinator provisioned for one project: a virtual, non-builtin agent no
* other project leads or counts as a member, and no group, session or Channel holds.
+ * Only projects created before main agents became ordinary agents have one;
+ * the agent a project creates now is a real agent the user keeps.
*/
async isDedicatedCoordinator(
agentId: string,
@@ -393,8 +391,9 @@ export class ProjectModel {
.orderBy(desc(projects.updatedAt))
.limit(limit)
.offset(offset);
- // Coordinators are virtual agents the client agent list never loads, so the
- // list carries their display meta for the owner column.
+ // A main agent may be a virtual coordinator from before main agents were
+ // ordinary agents, which the client agent list never loads, so the list
+ // carries its display meta for the owner column.
return rows.map(({ coordinatorAgent, project }) => ({ ...project, coordinatorAgent }));
}
diff --git a/packages/database/src/models/projectMainAgent.ts b/packages/database/src/models/projectMainAgent.ts
new file mode 100644
index 00000000000..73cb2e0476c
--- /dev/null
+++ b/packages/database/src/models/projectMainAgent.ts
@@ -0,0 +1,93 @@
+import { createProjectCoordinatorAgentConfig } from '@lobechat/builtin-agents';
+import type { ProjectVisibility } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import { agentLabelAssignments, agentLabels } from '../schemas/agentLabel';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '../schemas/resourcePermission';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import { AgentModel } from './agent';
+import { ResourcePermissionModel } from './resourcePermission';
+
+/**
+ * Every agent a project creates for itself carries this label, so they group
+ * together in the agents list. One label per scope, shared by all projects.
+ */
+export const PROJECT_AGENT_LABEL = 'Project';
+
+interface Scope {
+ userId: string;
+ workspaceId?: string;
+}
+
+const findOrCreateProjectLabel = async (db: LobeChatDatabase, scope: Scope) => {
+ const ownership = buildWorkspaceWhere(scope, {
+ userId: agentLabels.userId,
+ workspaceId: agentLabels.workspaceId,
+ });
+ const find = async () => {
+ const [label] = await db
+ .select({ id: agentLabels.id })
+ .from(agentLabels)
+ .where(
+ and(
+ eq(agentLabels.name, PROJECT_AGENT_LABEL),
+ // An archived label is retired and cannot take new agents.
+ eq(agentLabels.archived, false),
+ ownership,
+ ),
+ )
+ .limit(1);
+ return label?.id;
+ };
+
+ const existing = await find();
+ if (existing) return existing;
+
+ const [created] = await db
+ .insert(agentLabels)
+ .values(buildWorkspacePayload(scope, { name: PROJECT_AGENT_LABEL }))
+ // Another project created in the same scope may have just added it.
+ .onConflictDoNothing()
+ .returning({ id: agentLabels.id });
+
+ const id = created?.id ?? (await find());
+ if (!id) throw new Error('Failed to create the project agent label');
+ return id;
+};
+
+/**
+ * Create the agent that leads a new project when none was picked: an ordinary
+ * agent the user sees in the agents list, named after the project, wearing its
+ * avatar and the shared project label. Unlike the virtual coordinators earlier
+ * projects got, it outlives the project.
+ */
+export const createProjectMainAgent = async (
+ db: LobeChatDatabase,
+ scope: Scope,
+ input: { avatar?: string; name: string; visibility?: ProjectVisibility },
+) => {
+ const agent = await new AgentModel(db, scope.userId, scope.workspaceId).create({
+ ...createProjectCoordinatorAgentConfig({ avatar: input.avatar, name: input.name }),
+ visibility: input.visibility,
+ });
+
+ // Same as an agent created from the agents list: a shared workspace agent
+ // starts at the default access level.
+ if (scope.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(db, scope.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ scope.userId,
+ );
+ }
+
+ const labelId = await findOrCreateProjectLabel(db, scope);
+ await db
+ .insert(agentLabelAssignments)
+ .values(buildWorkspacePayload(scope, { agentId: agent.id, labelId }))
+ .onConflictDoNothing();
+
+ return agent;
+};
diff --git a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
index 5f772a1df3f..ae32b7f8037 100644
--- a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts
@@ -33,9 +33,18 @@ const repo = new ProjectCoordinatorRepository(serverDB, userId);
const otherRepo = new ProjectCoordinatorRepository(serverDB, otherUserId);
let identifierSequence = 0;
-const createProject = (input: { name: string }) =>
+const createProject = (input: { coordinatorAgentId?: string; name: string }) =>
model.create({ ...input, identifier: `C${String(++identifierSequence).padStart(5, '0')}` });
+/** Projects created before main agents were ordinary agents got a virtual coordinator. */
+const createLegacyProject = async (name: string) => {
+ const coordinator = await new AgentModel(serverDB, userId).create({
+ title: `${name} Coordinator`,
+ virtual: true,
+ });
+ return createProject({ coordinatorAgentId: coordinator.id, name });
+};
+
describe('ProjectCoordinatorRepository.replaceCoordinator', () => {
beforeEach(async () => {
await serverDB.delete(users);
@@ -47,7 +56,7 @@ describe('ProjectCoordinatorRepository.replaceCoordinator', () => {
});
it('hands a dedicated coordinator history to the new main agent, then deletes it', async () => {
- const project = await createProject({ name: 'Handover' });
+ const project = await createLegacyProject('Handover');
const coordinatorId = project.coordinatorAgentId;
const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });
const topic = await new TopicModel(serverDB, userId).create({
@@ -241,11 +250,15 @@ describe('ProjectCoordinatorRepository.replaceCoordinator', () => {
expect(updated?.coordinatorAgentId).toBe(second.id);
expect(await serverDB.select().from(agents).where(eq(agents.id, first.id))).toHaveLength(1);
+ // The agent the project created is the user's own agent, so it stays too.
expect(await model.listAgents(project.id)).toEqual([
expect.objectContaining({
agent: expect.objectContaining({ id: second.id }),
binding: expect.objectContaining({ enabled: true, role: 'Reviewer' }),
}),
+ expect.objectContaining({
+ agent: expect.objectContaining({ id: project.coordinatorAgentId }),
+ }),
expect.objectContaining({
agent: expect.objectContaining({ id: first.id }),
binding: expect.objectContaining({ role: null }),
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 649b01f428c..3c483ad6e2a 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -161,14 +161,23 @@ export default {
'acceptance.success.start': 'Project started',
'acceptance.title': 'Acceptance',
'create.action': 'Create project',
+ 'create.avatarHint': 'Pick an emoji or upload an image. You can also drop an image here.',
+ 'create.avatarInvalidType': 'Use a JPG, PNG, GIF, or WEBP image.',
+ 'create.avatarUploadFailed': "Couldn't upload the image. Try again.",
'create.identifierDescription':
'Replaces the task number prefix for this project, for example ACE. Leave it empty to use the default prefix.',
'create.identifierInvalid': 'Use 3–6 uppercase letters or numbers, starting with a letter.',
'create.identifierLabel': 'Identifier (optional)',
'create.identifierPlaceholder': 'ACE',
+ 'create.mainAgentDedicatedDescription':
+ 'Creates an agent named after the project, with its avatar and the Project label. It stays in your agents list. Your choice is reused next time.',
+ 'create.mainAgentDedicatedPlaceholder': 'Named after the project',
+ 'create.mainAgentDedicatedTag': 'New',
'create.mainAgentDescription':
'Manages this project’s conversations, tasks, and goals. Your choice is reused next time.',
'create.mainAgentLabel': 'Main agent',
+ 'create.mainAgentMode.dedicated': 'Create a dedicated agent',
+ 'create.mainAgentMode.existing': 'Use an existing agent',
'create.mainAgentPlaceholder': 'Select an agent',
'create.nameLabel': 'Project name',
'create.namePlaceholder': 'What are you working on?',
diff --git a/src/features/Projects/CreateProjectContent.tsx b/src/features/Projects/CreateProjectContent.tsx
index be40f2e6a3a..66ef3d495d3 100644
--- a/src/features/Projects/CreateProjectContent.tsx
+++ b/src/features/Projects/CreateProjectContent.tsx
@@ -20,17 +20,22 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import { type ProjectListItem, useProjectStore } from '@/store/project';
import {
+ buildCreateProjectRequest,
getCreateProjectInput,
getProjectFieldSuggestions,
isProjectIdentifierValid,
isProjectSlugValid,
} from './createProjectForm';
-import MainAgentField from './MainAgentField';
+import MainAgentSection from './MainAgentSection';
import {
+ DEDICATED_MAIN_AGENT,
+ type MainAgentMode,
readRememberedMainAgent,
resolveDefaultMainAgent,
+ resolveDefaultMainAgentMode,
writeRememberedMainAgent,
} from './mainAgentStorage';
+import ProjectAvatarField from './ProjectAvatarField';
export interface CreateProjectOptions {
/**
@@ -42,10 +47,15 @@ export interface CreateProjectOptions {
}
interface CreateProjectFormState {
+ /** Emoji or uploaded image URL; a dedicated main agent takes it over too. */
+ avatar?: string;
+ /** Creating now would save the project, and its agent, without the avatar on its way. */
+ avatarUploading: boolean;
identifier: string;
loading: boolean;
/** Explicit pick in this modal; otherwise the remembered agent or LobeAI. */
mainAgentId?: string;
+ mainAgentMode: MainAgentMode;
name: string;
slug: string;
slugEdited: boolean;
@@ -62,15 +72,17 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
const { close } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
const createProject = useProjectStore((s) => s.createProject);
- const [form, setForm] = useState<CreateProjectFormState>({
+ const [remembered] = useState(() => readRememberedMainAgent(getActiveWorkspaceId()));
+ const [form, setForm] = useState<CreateProjectFormState>(() => ({
+ avatarUploading: false,
identifier: '',
loading: false,
+ mainAgentMode: resolveDefaultMainAgentMode(remembered),
name: '',
slug: '',
slugEdited: false,
- });
+ }));
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const [remembered] = useState(() => readRememberedMainAgent(getActiveWorkspaceId()));
const defaultMainAgentId = useHomeStore((s) =>
resolveDefaultMainAgent({
// New projects are shared, so a private agent is not a valid default.
@@ -100,11 +112,24 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
};
const handleCreate = async () => {
- if (!createInput || form.loading) return;
+ if (!createInput || form.loading || form.avatarUploading) return;
updateForm({ loading: true });
try {
- const project = await createProject({ ...createInput, coordinatorAgentId: mainAgentId });
- if (mainAgentId) writeRememberedMainAgent(mainAgentId, getActiveWorkspaceId());
+ const project = await createProject(
+ buildCreateProjectRequest(createInput, {
+ avatar: form.avatar,
+ mainAgentId,
+ mainAgentMode: form.mainAgentMode,
+ }),
+ );
+ const rememberedChoice =
+ form.mainAgentMode === 'dedicated' ? DEDICATED_MAIN_AGENT : mainAgentId;
+ if (rememberedChoice) writeRememberedMainAgent(rememberedChoice, getActiveWorkspaceId());
+ if (form.mainAgentMode === 'dedicated') {
+ // The project created an agent and maybe the Project label; show both.
+ const { refreshAgentLabels, refreshAgentList } = useHomeStore.getState();
+ void Promise.all([refreshAgentList(), refreshAgentLabels()]);
+ }
close();
if (onCreated) onCreated(project);
else navigate(`/project/${project.slug ?? project.id}`);
@@ -123,14 +148,22 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
<Text fontSize={13} weight={500}>
{t('create.nameLabel')}
</Text>
- <Input
- autoFocus
- maxLength={255}
- placeholder={t('create.namePlaceholder')}
- value={form.name}
- onChange={(event) => updateName(event.target.value)}
- onPressEnter={handleCreate}
- />
+ <ProjectAvatarField
+ avatar={form.avatar}
+ disabled={form.loading}
+ name={form.name}
+ onChange={(avatar) => updateForm({ avatar })}
+ onUploadingChange={(avatarUploading) => updateForm({ avatarUploading })}
+ >
+ <Input
+ autoFocus
+ maxLength={255}
+ placeholder={t('create.namePlaceholder')}
+ value={form.name}
+ onChange={(event) => updateName(event.target.value)}
+ onPressEnter={handleCreate}
+ />
+ </ProjectAvatarField>
</Flexbox>
<Flexbox gap={6}>
<Text fontSize={13} weight={500}>
@@ -168,24 +201,20 @@ const CreateProjectContent = memo<CreateProjectOptions>(({ onCreated }) => {
{t(slugValid ? 'create.slugDescription' : 'create.slugInvalid')}
</Text>
</Flexbox>
- <Flexbox gap={6}>
- <Text fontSize={13} weight={500}>
- {t('create.mainAgentLabel')}
- </Text>
- <MainAgentField
- agentId={mainAgentId}
- disabled={form.loading}
- onChange={(id) => updateForm({ mainAgentId: id })}
- />
- <Text fontSize={12} type="secondary">
- {t('create.mainAgentDescription')}
- </Text>
- </Flexbox>
+ <MainAgentSection
+ agentId={mainAgentId}
+ disabled={form.loading}
+ mode={form.mainAgentMode}
+ projectAvatar={form.avatar}
+ projectName={form.name}
+ onAgentChange={(id) => updateForm({ mainAgentId: id })}
+ onModeChange={(mainAgentMode) => updateForm({ mainAgentMode })}
+ />
</Flexbox>
<ModalFooter>
<Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
<Button
- disabled={!createInput}
+ disabled={!createInput || form.avatarUploading}
loading={form.loading}
type="primary"
onClick={handleCreate}
diff --git a/src/features/Projects/MainAgentSection.tsx b/src/features/Projects/MainAgentSection.tsx
new file mode 100644
index 00000000000..3d974a1dd48
--- /dev/null
+++ b/src/features/Projects/MainAgentSection.tsx
@@ -0,0 +1,95 @@
+import { createProjectCoordinatorAgentConfig } from '@lobechat/builtin-agents';
+import { Flexbox, Segmented, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AgentAvatar from '@/components/AgentAvatar';
+
+import MainAgentField from './MainAgentField';
+import type { MainAgentMode } from './mainAgentStorage';
+
+const styles = stylex.create({
+ preview: {
+ display: 'flex',
+ gap: 8,
+ alignItems: 'center',
+ height: 36,
+ paddingInline: '8px',
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadius,
+ },
+});
+
+interface MainAgentSectionProps {
+ agentId?: string;
+ disabled?: boolean;
+ mode: MainAgentMode;
+ onAgentChange: (agentId: string) => void;
+ onModeChange: (mode: MainAgentMode) => void;
+ /** The project's avatar and name, which a dedicated agent takes over. */
+ projectAvatar?: string;
+ projectName: string;
+}
+
+/**
+ * Lead the project with an agent created for it, or pick one the workspace
+ * already has. The dedicated agent does not exist until the project is
+ * created, so its row previews the agent the server will create.
+ */
+const MainAgentSection = memo<MainAgentSectionProps>(
+ ({ agentId, disabled, mode, onAgentChange, onModeChange, projectAvatar, projectName }) => {
+ const { t } = useTranslation('project');
+ const name = projectName.trim();
+ const dedicatedTitle = name ? createProjectCoordinatorAgentConfig({ name }).title : undefined;
+
+ return (
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.mainAgentLabel')}
+ </Text>
+ <Segmented
+ block
+ disabled={disabled}
+ value={mode}
+ options={[
+ { label: t('create.mainAgentMode.dedicated'), value: 'dedicated' },
+ { label: t('create.mainAgentMode.existing'), value: 'existing' },
+ ]}
+ onChange={(value) => onModeChange(value as MainAgentMode)}
+ />
+ {mode === 'dedicated' ? (
+ <div {...stylex.props(styles.preview)}>
+ {/* Without a project avatar the agent draws a generated character. */}
+ <AgentAvatar
+ avatar={projectAvatar}
+ name={dedicatedTitle}
+ size={22}
+ title={dedicatedTitle}
+ />
+ <Text ellipsis style={{ flex: 1 }} type={dedicatedTitle ? undefined : 'secondary'}>
+ {dedicatedTitle ?? t('create.mainAgentDedicatedPlaceholder')}
+ </Text>
+ <Tag size={'small'}>{t('create.mainAgentDedicatedTag')}</Tag>
+ </div>
+ ) : (
+ <MainAgentField agentId={agentId} disabled={disabled} onChange={onAgentChange} />
+ )}
+ <Text fontSize={12} type="secondary">
+ {t(
+ mode === 'dedicated'
+ ? 'create.mainAgentDedicatedDescription'
+ : 'create.mainAgentDescription',
+ )}
+ </Text>
+ </Flexbox>
+ );
+ },
+);
+
+MainAgentSection.displayName = 'MainAgentSection';
+
+export default MainAgentSection;
diff --git a/src/features/Projects/ProjectAvatarField.tsx b/src/features/Projects/ProjectAvatarField.tsx
new file mode 100644
index 00000000000..450d5153dc4
--- /dev/null
+++ b/src/features/Projects/ProjectAvatarField.tsx
@@ -0,0 +1,131 @@
+import { Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ImagePlusIcon, LoaderCircleIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import EmojiPicker from '@/components/EmojiPicker';
+
+import { isLocalAvatarPreview } from './pickedAvatar';
+import ProjectAvatar from './ProjectAvatar';
+import { useAvatarFileDrop } from './useAvatarFileDrop';
+import { useProjectAvatarUpload } from './useProjectAvatarUpload';
+
+const TILE_SIZE = 32;
+
+const styles = stylex.create({
+ dragging: {
+ outlineWidth: 2,
+ outlineStyle: 'dashed',
+ outlineColor: cssVar.colorPrimary,
+ outlineOffset: 1,
+ },
+ overlay: {
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: cssVar.colorTextLightSolid,
+ background: cssVar.colorBgMask,
+ opacity: { 'default': 0, ':hover': 1 },
+ transitionProperty: 'opacity',
+ transitionDuration: cssVar.motionDurationMid,
+ },
+ overlayShown: {
+ opacity: 1,
+ },
+ tile: {
+ cursor: 'pointer',
+ position: 'relative',
+ overflow: 'hidden',
+ flex: 'none',
+ width: TILE_SIZE,
+ height: TILE_SIZE,
+ borderRadius: cssVar.borderRadius,
+ },
+});
+
+interface ProjectAvatarFieldProps {
+ avatar?: string;
+ /** 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. */
+ name: string;
+ onChange: (avatar?: string) => void;
+ /** An upload is in flight; the avatar it brings arrives through `onChange` later. */
+ onUploadingChange?: (uploading: boolean) => void;
+}
+
+/**
+ * The project's avatar beside its name: click to pick an emoji or upload an
+ * image, or drop an image anywhere on the row.
+ */
+const ProjectAvatarField = memo<ProjectAvatarFieldProps>(
+ ({ avatar, children, disabled, name, onChange, onUploadingChange }) => {
+ const { t } = useTranslation('project');
+ const { upload, uploading } = useProjectAvatarUpload({ onChange, onUploadingChange });
+
+ const { dragging, dropProps } = useAvatarFileDrop({
+ disabled: disabled || uploading,
+ onFile: (file) => void upload(file, { crop: true }),
+ onReject: () => toast.error(t('create.avatarInvalidType')),
+ });
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8} {...dropProps}>
+ <EmojiPicker
+ allowDelete={!!avatar}
+ allowUpload={{ enableEmoji: true }}
+ loading={uploading}
+ open={disabled ? false : undefined}
+ popupProps={{ placement: 'bottomLeft' }}
+ size={TILE_SIZE}
+ value={avatar}
+ customRender={(value) => (
+ <Tooltip title={t('create.avatarHint')}>
+ <div
+ aria-label={t('create.avatarHint')}
+ {...stylex.props(styles.tile, dragging && styles.dragging)}
+ 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. */}
+ <ProjectAvatar
+ avatar={value}
+ name={name.trim() || t('create.title')}
+ size={TILE_SIZE}
+ />
+ <div
+ {...stylex.props(styles.overlay, (dragging || uploading) && styles.overlayShown)}
+ >
+ <Icon
+ icon={uploading ? LoaderCircleIcon : ImagePlusIcon}
+ size={16}
+ spin={uploading}
+ />
+ </div>
+ </div>
+ </Tooltip>
+ )}
+ onDelete={() => onChange(undefined)}
+ onUpload={(file) => void upload(file, { crop: false })}
+ // Typed as a string, but delete reports `null`.
+ onChange={(next: string | null) => {
+ // The uploader reports a local preview first; keep only the stored URL.
+ if (!isLocalAvatarPreview(next)) onChange(next || undefined);
+ }}
+ />
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ {children}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ProjectAvatarField.displayName = 'ProjectAvatarField';
+
+export default ProjectAvatarField;
diff --git a/src/features/Projects/createProjectForm.test.ts b/src/features/Projects/createProjectForm.test.ts
index 778b3216452..4ba1d20d767 100644
--- a/src/features/Projects/createProjectForm.test.ts
+++ b/src/features/Projects/createProjectForm.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ buildCreateProjectRequest,
getCreateProjectInput,
getProjectFieldSuggestions,
isProjectIdentifierValid,
@@ -61,4 +62,22 @@ describe('createProjectForm', () => {
getCreateProjectInput({ identifier: 'LOBE', name: 'LobeHub Project', slug: '-invalid' }),
).toBeNull();
});
+
+ it('leaves the main agent out so the server creates a dedicated one', () => {
+ expect(
+ buildCreateProjectRequest(
+ { name: 'Launch' },
+ { avatar: '🚀', mainAgentId: 'inbox', mainAgentMode: 'dedicated' },
+ ),
+ ).toEqual({ avatar: '🚀', name: 'Launch' });
+ });
+
+ it('sends the picked agent when the project reuses an existing one', () => {
+ expect(
+ buildCreateProjectRequest(
+ { name: 'Launch', slug: 'launch' },
+ { mainAgentId: 'agt_1', mainAgentMode: 'existing' },
+ ),
+ ).toEqual({ coordinatorAgentId: 'agt_1', name: 'Launch', slug: 'launch' });
+ });
});
diff --git a/src/features/Projects/createProjectForm.ts b/src/features/Projects/createProjectForm.ts
index 67bdd7aeab9..636e1ffa584 100644
--- a/src/features/Projects/createProjectForm.ts
+++ b/src/features/Projects/createProjectForm.ts
@@ -48,3 +48,23 @@ export const getCreateProjectInput = (draft: CreateProjectDraft) => {
return { name, ...(identifier ? { identifier } : {}), ...(slug ? { slug } : {}) };
};
+
+export interface CreateProjectExtras {
+ avatar?: string;
+ /** The picked agent; only sent when the project reuses an existing agent. */
+ mainAgentId?: string;
+ mainAgentMode: 'dedicated' | 'existing';
+}
+
+/**
+ * Leaving `coordinatorAgentId` out is what makes the server create an agent
+ * for the project, named after it and wearing its avatar.
+ */
+export const buildCreateProjectRequest = (
+ input: NonNullable<ReturnType<typeof getCreateProjectInput>>,
+ { avatar, mainAgentId, mainAgentMode }: CreateProjectExtras,
+) => ({
+ ...input,
+ ...(avatar ? { avatar } : {}),
+ ...(mainAgentMode === 'existing' && mainAgentId ? { coordinatorAgentId: mainAgentId } : {}),
+});
diff --git a/src/features/Projects/mainAgentStorage.test.ts b/src/features/Projects/mainAgentStorage.test.ts
index d7a837df418..f7c475e0b12 100644
--- a/src/features/Projects/mainAgentStorage.test.ts
+++ b/src/features/Projects/mainAgentStorage.test.ts
@@ -1,8 +1,10 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
+ DEDICATED_MAIN_AGENT,
readRememberedMainAgent,
resolveDefaultMainAgent,
+ resolveDefaultMainAgentMode,
writeRememberedMainAgent,
} from './mainAgentStorage';
@@ -47,4 +49,23 @@ describe('mainAgentStorage', () => {
expect(resolveDefaultMainAgent({ ...input, listLoaded: false })).toBe('agt_deleted');
expect(resolveDefaultMainAgent({ ...input, listLoaded: true })).toBe('inbox');
});
+
+ it('reopens in the mode the last project was created with', () => {
+ expect(resolveDefaultMainAgentMode()).toBe('existing');
+ expect(resolveDefaultMainAgentMode('agt_1')).toBe('existing');
+ expect(resolveDefaultMainAgentMode(DEDICATED_MAIN_AGENT)).toBe('dedicated');
+ });
+
+ it('never treats the dedicated marker as an agent id', () => {
+ for (const listLoaded of [false, true]) {
+ expect(
+ resolveDefaultMainAgent({
+ agentExists: () => true,
+ inboxAgentId: 'inbox',
+ listLoaded,
+ remembered: DEDICATED_MAIN_AGENT,
+ }),
+ ).toBe('inbox');
+ }
+ });
});
diff --git a/src/features/Projects/mainAgentStorage.ts b/src/features/Projects/mainAgentStorage.ts
index 3b502b87449..4c2111805b5 100644
--- a/src/features/Projects/mainAgentStorage.ts
+++ b/src/features/Projects/mainAgentStorage.ts
@@ -1,5 +1,14 @@
const MAIN_AGENT_STORAGE_KEY = 'lobechat-project-main-agent';
+/**
+ * Remembered in place of an agent id when the last project got an agent of its
+ * own. Agent ids carry a prefix, so this never collides with one.
+ */
+export const DEDICATED_MAIN_AGENT = 'dedicated';
+
+/** Lead a new project with an agent created for it, or with an existing one. */
+export type MainAgentMode = 'dedicated' | 'existing';
+
// Agent ids belong to one workspace, so each workspace remembers its own pick.
const storageKey = (workspaceId?: string | null) =>
`${MAIN_AGENT_STORAGE_KEY}:${workspaceId ?? 'personal'}`;
@@ -20,6 +29,9 @@ export const writeRememberedMainAgent = (agentId: string, workspaceId?: string |
}
};
+export const resolveDefaultMainAgentMode = (remembered?: string): MainAgentMode =>
+ remembered === DEDICATED_MAIN_AGENT ? 'dedicated' : 'existing';
+
/**
* Reuse the remembered main agent while it still exists; otherwise LobeAI.
* Before the agent list loads the remembered id is trusted as-is.
@@ -35,6 +47,7 @@ export const resolveDefaultMainAgent = ({
listLoaded: boolean;
remembered?: string;
}): string | undefined => {
+ if (remembered === DEDICATED_MAIN_AGENT) return inboxAgentId;
if (remembered && (!listLoaded || remembered === inboxAgentId || agentExists(remembered))) {
return remembered;
}
diff --git a/src/features/Projects/pickedAvatar.test.ts b/src/features/Projects/pickedAvatar.test.ts
new file mode 100644
index 00000000000..7a26a3026e1
--- /dev/null
+++ b/src/features/Projects/pickedAvatar.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { isLocalAvatarPreview } from './pickedAvatar';
+
+describe('isLocalAvatarPreview', () => {
+ it('skips the upload preview but keeps stored values', () => {
+ expect(isLocalAvatarPreview('data:image/webp;base64,AAAA')).toBe(true);
+ expect(isLocalAvatarPreview('https://files.example.com/avatar.webp')).toBe(false);
+ expect(isLocalAvatarPreview('🚀')).toBe(false);
+ });
+
+ it('treats a deleted avatar as a change, not a preview', () => {
+ expect(isLocalAvatarPreview(null)).toBe(false);
+ });
+});
diff --git a/src/features/Projects/pickedAvatar.ts b/src/features/Projects/pickedAvatar.ts
new file mode 100644
index 00000000000..d2bd5c1d3d3
--- /dev/null
+++ b/src/features/Projects/pickedAvatar.ts
@@ -0,0 +1,5 @@
+/**
+ * The avatar picker reports a `data:` preview before an upload finishes, and
+ * `null` when the avatar is deleted.
+ */
+export const isLocalAvatarPreview = (value: string | null) => !!value?.startsWith('data:');
diff --git a/src/features/Projects/useAvatarFileDrop.test.ts b/src/features/Projects/useAvatarFileDrop.test.ts
new file mode 100644
index 00000000000..a845c6a4080
--- /dev/null
+++ b/src/features/Projects/useAvatarFileDrop.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { isFileDrag, pickAvatarFile } from './useAvatarFileDrop';
+
+const file = (name: string, type: string) => new File(['x'], name, { type });
+
+describe('useAvatarFileDrop', () => {
+ it('takes the first image among the dropped files', () => {
+ const png = file('logo.png', 'image/png');
+
+ expect(pickAvatarFile([file('notes.pdf', 'application/pdf'), png])).toBe(png);
+ });
+
+ it('rejects files the avatar uploader cannot use', () => {
+ expect(pickAvatarFile([file('logo.svg', 'image/svg+xml')])).toBeUndefined();
+ expect(pickAvatarFile(null)).toBeUndefined();
+ });
+
+ it('only reacts to drags that carry files', () => {
+ expect(isFileDrag({ types: ['Files'] } as unknown as DataTransfer)).toBe(true);
+ expect(isFileDrag({ types: ['text/plain'] } as unknown as DataTransfer)).toBe(false);
+ expect(isFileDrag(null)).toBe(false);
+ });
+});
diff --git a/src/features/Projects/useAvatarFileDrop.ts b/src/features/Projects/useAvatarFileDrop.ts
new file mode 100644
index 00000000000..0fbb8a095b5
--- /dev/null
+++ b/src/features/Projects/useAvatarFileDrop.ts
@@ -0,0 +1,61 @@
+import { type DragEvent, useRef, useState } from 'react';
+
+/** The image types the avatar picker's own uploader accepts. */
+const AVATAR_IMAGE_TYPES = new Set(['image/gif', 'image/jpeg', 'image/png', 'image/webp']);
+
+export const isFileDrag = (dataTransfer: DataTransfer | null) =>
+ !!dataTransfer && Array.from(dataTransfer.types).includes('Files');
+
+/** The first dropped file usable as an avatar, if any. */
+export const pickAvatarFile = (files: ArrayLike<File> | null | undefined) =>
+ Array.from(files ?? []).find((file) => AVATAR_IMAGE_TYPES.has(file.type));
+
+interface UseAvatarFileDropOptions {
+ disabled?: boolean;
+ onFile: (file: File) => void;
+ /** Files were dropped, but none of them is an image. */
+ onReject?: () => void;
+}
+
+/**
+ * Accept an image dropped anywhere on the element the returned props are spread
+ * on. Events keep bubbling: the app-wide drag overlay listens on `window` and
+ * must see the drop to close.
+ */
+export const useAvatarFileDrop = ({ disabled, onFile, onReject }: UseAvatarFileDropOptions) => {
+ const [dragging, setDragging] = useState(false);
+ // dragenter/dragleave fire for every child crossed, so count the nesting.
+ const depth = useRef(0);
+
+ const accepts = (event: DragEvent) => !disabled && isFileDrag(event.dataTransfer);
+
+ const dropProps = {
+ onDragEnter: (event: DragEvent) => {
+ if (!accepts(event)) return;
+ event.preventDefault();
+ depth.current += 1;
+ setDragging(true);
+ },
+ onDragLeave: (event: DragEvent) => {
+ if (!accepts(event)) return;
+ depth.current = Math.max(0, depth.current - 1);
+ if (depth.current === 0) setDragging(false);
+ },
+ onDragOver: (event: DragEvent) => {
+ if (!accepts(event)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'copy';
+ },
+ onDrop: (event: DragEvent) => {
+ if (!accepts(event)) return;
+ event.preventDefault();
+ depth.current = 0;
+ setDragging(false);
+ const file = pickAvatarFile(event.dataTransfer.files);
+ if (file) onFile(file);
+ else onReject?.();
+ },
+ };
+
+ return { dragging, dropProps };
+};
diff --git a/src/features/Projects/useProjectAvatarUpload.test.ts b/src/features/Projects/useProjectAvatarUpload.test.ts
new file mode 100644
index 00000000000..200c302d69f
--- /dev/null
+++ b/src/features/Projects/useProjectAvatarUpload.test.ts
@@ -0,0 +1,59 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useProjectAvatarUpload } from './useProjectAvatarUpload';
+
+const uploadWithProgress = vi.fn();
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (state: unknown) => unknown) => selector({ uploadWithProgress }),
+}));
+
+afterEach(() => {
+ uploadWithProgress.mockReset();
+});
+
+const pickedFile = () => new File(['x'], 'avatar.webp', { type: 'image/webp' });
+
+describe('useProjectAvatarUpload', () => {
+ it('reports an upload in flight so the form can wait for its avatar', async () => {
+ let finish!: (result: { url: string }) => void;
+ uploadWithProgress.mockReturnValue(new Promise((resolve) => (finish = resolve)));
+ const onChange = vi.fn();
+ const onUploadingChange = vi.fn();
+ const { result } = renderHook(() => useProjectAvatarUpload({ onChange, onUploadingChange }));
+
+ let pending!: Promise<void>;
+ act(() => {
+ pending = result.current.upload(pickedFile(), { crop: false });
+ });
+
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+ expect(result.current.uploading).toBe(true);
+ expect(onChange).not.toHaveBeenCalled();
+
+ await act(async () => {
+ finish({ url: 'https://files.example.com/avatar.webp' });
+ await pending;
+ });
+
+ expect(onChange).toHaveBeenCalledWith('https://files.example.com/avatar.webp');
+ expect(onUploadingChange).toHaveBeenLastCalledWith(false);
+ expect(result.current.uploading).toBe(false);
+ });
+
+ it('releases the form when the upload fails', async () => {
+ uploadWithProgress.mockRejectedValue(new Error('network'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onChange = vi.fn();
+ const onUploadingChange = vi.fn();
+ const { result } = renderHook(() => useProjectAvatarUpload({ onChange, onUploadingChange }));
+
+ await act(async () => {
+ await result.current.upload(pickedFile(), { crop: false });
+ });
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onUploadingChange.mock.calls).toEqual([[true], [false]]);
+ });
+});
diff --git a/src/features/Projects/useProjectAvatarUpload.ts b/src/features/Projects/useProjectAvatarUpload.ts
new file mode 100644
index 00000000000..295b2e746f7
--- /dev/null
+++ b/src/features/Projects/useProjectAvatarUpload.ts
@@ -0,0 +1,60 @@
+import { toast } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useFileStore } from '@/store/file';
+import { imageToBase64 } from '@/utils/imageToBase64';
+
+/** Matches the avatar picker's own uploader, so both paths store the same image. */
+const AVATAR_SIZE = 256;
+
+/** Center-crop a dropped image to the square the picker would have produced. */
+const toAvatarFile = async (file: File) => {
+ const url = URL.createObjectURL(file);
+ try {
+ const img = new Image();
+ img.src = url;
+ await img.decode();
+ const blob = await (await fetch(imageToBase64({ img, size: AVATAR_SIZE }))).blob();
+ return new File([blob], 'avatar.webp', { type: 'image/webp' });
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+};
+
+interface UseProjectAvatarUploadOptions {
+ onChange: (avatar: string) => void;
+ /** An upload is in flight; the avatar it brings arrives through `onChange` later. */
+ onUploadingChange?: (uploading: boolean) => void;
+}
+
+/** Upload a project avatar image and report the stored URL once it lands. */
+export const useProjectAvatarUpload = ({
+ onChange,
+ onUploadingChange,
+}: UseProjectAvatarUploadOptions) => {
+ const { t } = useTranslation('project');
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [uploading, setUploadingState] = useState(false);
+ const setUploading = (next: boolean) => {
+ setUploadingState(next);
+ onUploadingChange?.(next);
+ };
+
+ /** `crop` center-crops a raw image; the picker's uploader has already done it. */
+ const upload = async (file: File, { crop }: { crop: boolean }) => {
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file: crop ? await toAvatarFile(file) : file });
+ if (!result?.url) throw new Error('Upload returned no URL');
+ onChange(result.url);
+ } catch (error) {
+ console.error('Failed to upload project avatar', error);
+ toast.error(t('create.avatarUploadFailed'));
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ return { upload, uploading };
+};
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 35730e0640e..695f2b7783d 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -48,6 +48,7 @@ interface ProjectStore extends ProjectStoreState {
addProjectAgents: (projectId: string, agentIds: string[]) => Promise<void>;
addProjectKnowledgeBases: (projectId: string, knowledgeBaseIds: string[]) => Promise<void>;
createProject: (input: {
+ avatar?: string;
coordinatorAgentId?: string;
identifier?: string;
name: string;