🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): rename goals by hand or with smart rename, and stop titling new goals with the whole instruction (#21970)
Lobehub Coderac0b3a3780c7
diff --git a/apps/server/src/routers/lambda/goal/configuration.test.ts b/apps/server/src/routers/lambda/goal/configuration.test.tsnew file mode 100644index 00000000000..51826254e67--- /dev/null+++ b/apps/server/src/routers/lambda/goal/configuration.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { GOAL_TITLE_MAX_LENGTH } from '@lobechat/const/goal';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };+});++const mockFindById = vi.fn();+const mockUpdateTitle = vi.fn();+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(function () {+ return { findById: mockFindById };+ }),+}));+vi.mock('@/server/services/goal', () => ({+ GoalService: vi.fn(function () {+ return { updateTitle: mockUpdateTitle };+ }),+}));+vi.mock('@/server/services/goal/subscriptions', () => ({ GoalSubscriptionService: vi.fn() }));+vi.mock('@/server/services/goal/scheduler', () => ({ scheduleGoalAdvance: vi.fn() }));++const { configurationRouter } = await import('./configuration');++describe('goal configurationRouter.updateTitle', () => {+ const caller = (ctx: { workspaceId?: string | null; workspaceRole?: string } = {}) =>+ configurationRouter.createCaller({ serverDB: {}, userId: 'user-1', ...ctx } as any);++ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'user-1' });+ mockUpdateTitle.mockImplementation(async (id: string, title: string) => ({ id, title }));+ });++ it('saves the trimmed title', async () => {+ const result = await caller().updateTitle({ id: 'goal_1', title: ' Desk pet TTS ' });++ expect(mockUpdateTitle).toHaveBeenCalledWith('goal_1', 'Desk pet TTS');+ expect(result).toEqual({ data: { id: 'goal_1', title: 'Desk pet TTS' }, success: true });+ });++ it('rejects a blank title', async () => {+ await expect(caller().updateTitle({ id: 'goal_1', title: ' ' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockUpdateTitle).not.toHaveBeenCalled();+ });++ it('rejects a title over the length cap', async () => {+ await expect(+ caller().updateTitle({ id: 'goal_1', title: 'a'.repeat(GOAL_TITLE_MAX_LENGTH + 1) }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateTitle).not.toHaveBeenCalled();+ });++ it('reports a goal outside the caller scope as not found', async () => {+ mockFindById.mockResolvedValue(undefined);++ await expect(caller().updateTitle({ id: 'goal_x', title: 'New' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockUpdateTitle).not.toHaveBeenCalled();+ });++ it('lets only the creator or an owner rename a workspace goal', async () => {+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'user-2' });++ await expect(+ caller({ workspaceId: 'ws-1', workspaceRole: 'member' }).updateTitle({+ id: 'goal_1',+ title: 'New',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockUpdateTitle).not.toHaveBeenCalled();++ await caller({ workspaceId: 'ws-1', workspaceRole: 'owner' }).updateTitle({+ id: 'goal_1',+ title: 'New',+ });+ expect(mockUpdateTitle).toHaveBeenCalledWith('goal_1', 'New');+ });+});diff --git a/apps/server/src/routers/lambda/goal/configuration.ts b/apps/server/src/routers/lambda/goal/configuration.tsindex 467ea50eb56..906aafc9cc5 100644--- a/apps/server/src/routers/lambda/goal/configuration.ts+++ b/apps/server/src/routers/lambda/goal/configuration.ts@@ -1,3 +1,4 @@+import { GOAL_TITLE_MAX_LENGTH } from '@lobechat/const/goal';import { MAX_GOAL_METRIC_CRITERIA } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -259,4 +260,18 @@ export const configurationRouter = router({mapGoalError(error, 'updateRequirement');}}),++ /** Rename the goal; like a topic, a workspace goal is renamed by its creator or an owner. */+ updateTitle: goalWriteProcedure+ .input(idInput.extend({ title: z.string().trim().min(1).max(GOAL_TITLE_MAX_LENGTH) }))+ .mutation(async ({ ctx, input: { id, title } }) => {+ try {+ const goal = await ctx.goalModel.findById(id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');+ return { data: await ctx.goalService.updateTitle(id, title), success: true };+ } catch (error) {+ mapGoalError(error, 'updateTitle');+ }+ }),});diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.tsindex 7a2bdb0f4df..31bd0d9b7ad 100644--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts@@ -77,6 +77,7 @@ function expected(): Array<['tick', 'mutation', 13],['updateRequirement', 'mutation', 13],['updateSubscription', 'mutation', 13],+ ['updateTitle', 'mutation', 13],['wake', 'mutation', 13],];}diff --git a/apps/server/src/services/goal/GoalService/__tests__/editing.test.ts b/apps/server/src/services/goal/GoalService/__tests__/editing.test.tsindex 1ae109bf253..12be6a8be07 100644--- a/apps/server/src/services/goal/GoalService/__tests__/editing.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/editing.test.ts@@ -6,7 +6,7 @@ import { getTestDB } from '@/database/core/getTestDB';import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { agents, goals, taskTopics, topics } from '@/database/schemas';+import { agents, goalNodes, goals, taskTopics, topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { TaskService } from '../../../task';@@ -202,6 +202,74 @@ describe('GoalService', () => {await expect(service.updateRequirement('goal_missing', 'x')).rejects.toThrow();});+ it('renames the goal without touching its requirement', async () => {+ const service = new GoalService(serverDB, userId);+ const longAsk = '继续并完成桌宠项目,在现有基础上完善 TTS 语音系统'.repeat(4);+ const graph = await service.create({ requirement: longAsk, title: longAsk });++ const updated = await service.updateTitle(graph.goal.id, '桌宠 TTS 语音系统');++ expect(updated.title).toBe('桌宠 TTS 语音系统');+ const read = (await service.graph(graph.goal.id)).goal;+ expect(read.title).toBe('桌宠 TTS 语音系统');+ expect(read.requirement).toBe(longAsk);+ await expect(service.updateTitle('goal_missing', 'x')).rejects.toThrow();+ });++ it('renames the root question and the management topic with the goal', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Old name' });+ await serverDB+ .insert(topics)+ .values({ id: 'tpc_rename_manager', title: 'Goal management: Old name', userId });+ await serverDB+ .update(goals)+ .set({ config: { managerState: { consumed: true, topicId: 'tpc_rename_manager' } } as never })+ .where(eq(goals.id, graph.goal.id));++ await service.updateTitle(graph.goal.id, 'New name');++ const read = await service.graph(graph.goal.id);+ expect(read.nodes.find((node) => node.kind === 'problem')?.title).toBe('New name');+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'tpc_rename_manager'));+ expect(topic.title).toBe('Goal management: New name');+ });++ it('keeps the goal and its root question in step when two renames race', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Old name' });++ await Promise.all([+ service.updateTitle(graph.goal.id, 'Name A'),+ service.updateTitle(graph.goal.id, 'Name B'),+ ]);++ const read = await service.graph(graph.goal.id);+ expect(read.nodes.find((node) => node.kind === 'problem')?.title).toBe(read.goal.title);+ });++ it('leaves a root question and a topic someone already renamed', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Old name' });+ const problem = graph.nodes.find((node) => node.kind === 'problem')!;+ await serverDB+ .update(goalNodes)+ .set({ title: 'My question' })+ .where(eq(goalNodes.id, problem.id));+ await serverDB.insert(topics).values({ id: 'tpc_rename_kept', title: 'My topic', userId });+ await serverDB+ .update(goals)+ .set({ config: { managerState: { consumed: true, topicId: 'tpc_rename_kept' } } as never })+ .where(eq(goals.id, graph.goal.id));++ await service.updateTitle(graph.goal.id, 'New name');++ const read = await service.graph(graph.goal.id);+ expect(read.nodes.find((node) => node.kind === 'problem')?.title).toBe('My question');+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'tpc_rename_kept'));+ expect(topic.title).toBe('My topic');+ });+it('names the agent each dispatched task node is assigned to', async () => {await serverDB.insert(agents).values([{ id: 'agt_exec', slug: 'agt-exec', userId }]);const service = new GoalService(serverDB, userId);diff --git a/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.ts b/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.tsindex 2e998c5b46f..43b2681607a 100644--- a/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.ts@@ -56,6 +56,36 @@ describe('GoalService', () => {expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);});+ it('keeps the plan when the goal is renamed while the planner runs', async () => {+ // Creating a goal without a drafted title names it in the background, right+ // as its first plan is being made; that rename must not throw the plan away.+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockImplementation(async () => {+ await gate;+ return {+ problemStatement: '改名不影响规划',+ tasks: [{ dependsOn: [], instruction: '收集', title: '方向A' }],+ };+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ problemDescription: '原话', title: 'Stopgap' });++ const tick = service.tick(graph.goal.id);+ await vi.waitFor(() => expect(planner).toHaveBeenCalled());+ await service.updateTitle(graph.goal.id, 'Named');+ release();+ await tick;++ const after = await service.graph(graph.goal.id);+ expect(after.goal.title).toBe('Named');+ expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);+ });+it('waits for an unfenced legacy planner instead of generating a second graph', async () => {const service = new GoalService(serverDB, userId);const graph = await service.create({ title: 'Legacy in-flight planning' });diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.tsindex daa9c117972..33c6ae460b2 100644--- a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts@@ -117,6 +117,7 @@ const METHODS = ['tickOnce','transitionStatus','updateRequirement',+ 'updateTitle','waitForDevice','waitForQuotaReset',];diff --git a/apps/server/src/services/goal/GoalService/editing.ts b/apps/server/src/services/goal/GoalService/editing.tsindex e0b7cc510d7..74efce60c57 100644--- a/apps/server/src/services/goal/GoalService/editing.ts+++ b/apps/server/src/services/goal/GoalService/editing.ts@@ -1,9 +1,11 @@import type { GoalEdgeKind, GoalItem } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { TopicModel } from '@/database/models/topic';import { TaskService } from '../../task';import { GoalAssignmentService } from '../assignment';@@ -62,6 +64,38 @@ export const updateRequirement = async (return goal;};+/**+ * Rename the goal. Only the label changes: the requirement and the Tasks already+ * dispatched keep their own text. The map's root question and the management+ * topic were named after the goal, so they follow unless someone renamed them.+ */+export const updateTitle = async (ctx: GoalServiceContext, goalId: string, title: string) => {+ // The goal row is locked so concurrent renames apply to all three in the same order.+ return ctx.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const previous = await goalModel.findByIdForUpdate(goalId);+ if (!previous) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const goal = await goalModel.update(goalId, { title });+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ if (previous.title === title) return goal;++ await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId).renameProblemNode(+ goalId,+ previous.title,+ title,+ );++ const topicId = goal.config?.managerState?.topicId;+ if (topicId) {+ const topicModel = new TopicModel(tx, ctx.userId, ctx.workspaceId);+ const topic = await topicModel.findById(topicId);+ if (topic?.title === `Goal management: ${previous.title}`)+ await topicModel.update(topicId, { title: `Goal management: ${title}` });+ }+ return goal;+ });+};+/*** Who works on a goal and with which model lives in `GoalAssignmentService`:* handoffs, the Task executor and both model slots share its lockeddiff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.tsindex 8231dc7f6eb..0fa256f0bd0 100644--- a/apps/server/src/services/goal/GoalService/index.ts+++ b/apps/server/src/services/goal/GoalService/index.ts@@ -50,6 +50,7 @@ import {setTaskModel,stopFencedTasks,updateRequirement,+ updateTitle,} from './editing';import {close,@@ -290,6 +291,7 @@ export class GoalService {tickOnce: (...args) => self.tickOnce(...args),transitionStatus: (...args) => self.transitionStatus(...args),updateRequirement: (...args) => self.updateRequirement(...args),+ updateTitle: (...args) => self.updateTitle(...args),get userId() {return self.userId;},@@ -386,6 +388,8 @@ export class GoalService {updateRequirement = (...args: MethodArgs<typeof updateRequirement>) =>updateRequirement(this.context, ...args);+ updateTitle = (...args: MethodArgs<typeof updateTitle>) => updateTitle(this.context, ...args);+setAgent = (...args: MethodArgs<typeof setAgent>) => setAgent(this.context, ...args);private followGoalAgent = (...args: MethodArgs<typeof followGoalAgent>) =>diff --git a/apps/server/src/services/goal/GoalService/planning.ts b/apps/server/src/services/goal/GoalService/planning.tsindex ac142845245..cd9e141f61e 100644--- a/apps/server/src/services/goal/GoalService/planning.ts+++ b/apps/server/src/services/goal/GoalService/planning.ts@@ -186,8 +186,8 @@ export const planDecomposition = async (if (!fresh || fresh.nodes.some((node) => node.kind === 'task')) return undefined;const currentProblem = fresh.nodes.find((node) => node.kind === 'problem');if (+ // Not the title: it is a label, so renaming a goal mid-plan keeps the plan.fresh.goal.requirement !== graph.goal.requirement ||- fresh.goal.title !== graph.goal.title ||currentProblem?.description !== problem?.description)return undefined;diff --git a/apps/server/src/services/goal/GoalService/types.ts b/apps/server/src/services/goal/GoalService/types.tsindex 3aac99d9c35..377aca6dd42 100644--- a/apps/server/src/services/goal/GoalService/types.ts+++ b/apps/server/src/services/goal/GoalService/types.ts@@ -51,6 +51,7 @@ import type {setTaskModel,stopFencedTasks,updateRequirement,+ updateTitle,} from './editing';import type {close,@@ -271,6 +272,7 @@ export interface GoalServiceContext {tickOnce: Bound<typeof tickOnce>;transitionStatus: Bound<typeof transitionStatus>;updateRequirement: Bound<typeof updateRequirement>;+ updateTitle: Bound<typeof updateTitle>;readonly userId: string;waitForDevice: Bound<typeof waitForDevice>;waitForQuotaReset: Bound<typeof waitForQuotaReset>;diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 0cb12e8ddf6..1ca9186cc75 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -21,6 +21,12 @@ export const goalStatuses = [export type GoalStatus = (typeof goalStatuses)[number];+/**+ * Longest title a person may give a goal. A title is a one-line label for the+ * list, the sidebar and the page header; the full ask lives in `requirement`.+ */+export const GOAL_TITLE_MAX_LENGTH = 255;+/*** The execution carrier a goal is optionally bound to. Kept polymorphic so a* goal does not depend on any single execution model:diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 92fa47c4a7d..42d0c79c1cb 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -802,6 +802,32 @@ export class GoalGraphModel {/** Rewrite a node's description — e.g. the planner replacing the seeded requirement blob with its own problem statement. *//** `confidence` travels with the description when the planner re-reads the problem. */+ /** Follow a goal rename on the root question, while it still carries the goal's old title. */+ renameProblemNode = async (goalId: string, from: string, to: string) =>+ this.db.transaction(async (tx) => {+ if (!(await this.ownedGoal(goalId, tx))) return undefined;+ const [node] = await tx+ .update(goalNodes)+ .set({ title: to, updatedAt: new Date() })+ .where(+ and(+ eq(goalNodes.goalId, goalId),+ eq(goalNodes.kind, 'problem'),+ eq(goalNodes.title, from),+ ),+ )+ .returning();+ if (!node) return undefined;+ await this.appendEvent(tx, goalId, {+ entityId: node.id,+ entityType: 'node',+ eventType: 'updated',+ reason: 'Goal renamed',+ taskId: node.taskId ?? undefined,+ });+ return node;+ });+updateNodeDescription = async (goalId: string,nodeId: string,diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex 4c4f1acf793..ecc9c4440bf 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -2,6 +2,7 @@import { resolveGoalAttemptBudget } from '@lobechat/builtin-tool-goal';import type { CreateGoalParams, GoalCriterionDraft } from '@lobechat/builtin-tool-task';+import { GOAL_TITLE_MAX_LENGTH } from '@lobechat/const/goal';import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';import { useEditor } from '@lobehub/editor/react';import {@@ -24,6 +25,7 @@ import {Pencil,PencilLine,Plus,+ RotateCw,ShieldCheck,Trash2,X,@@ -43,12 +45,18 @@ import { EditorCanvas } from '@/features/EditorCanvas';import { pickAndInsertAttachments } from '@/features/EditorCanvas/editorAttachments';import { usePermission } from '@/hooks/usePermission';import { goalService } from '@/services/goal';+import { useGoalStore } from '@/store/goal';import { shinyTextStyles } from '@/styles';import GoalAgentPill from '../GoalAgentPill';import { buildGoalAgents, buildGoalCreateInput, buildReviewedGoalContent } from './goalConfig';import { createFallbackGoalCriterion, generateGoalCriteria } from './goalCriteria';-import { deriveGoalTitle } from './goalTitle';+import {+ deriveGoalTitle,+ resolveDraftedTitle,+ resolveFallbackTitle,+ resolveSubmittedGoalTitle,+} from './goalTitle';import { hasUnsavedGoalDraft } from './hasUnsavedGoalDraft';const styles = createStaticStyles(({ css }) => ({@@ -239,11 +247,16 @@ export interface CreateGoalContentProps {const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const { agentId, initialRequirement, initialRoundBudget, initialTitle, onCreated, projectId } =props;- const { t } = useTranslation('chat');+ const { t } = useTranslation(['chat', 'common']);const { close } = useModalContext();const { allowed: canCreate, reason } = usePermission('create_content');const [isCreating, setIsCreating] = useState(false);+ // Drafting failed, so the review step offers to draft again.+ const [generateFailed, setGenerateFailed] = useState(false);+ // The stopgap title a failed draft leaves behind; still unedited at submit,+ // it is replaced by a generated one once the goal exists.+ const fallbackTitleRef = useRef<string>(undefined);const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');const [plan, setPlan] = useState<CreateGoalParams>({@@ -285,13 +298,15 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const handleNext = useCallback(async () => {const instruction = instructionRef.current.trim() || plan.instruction.trim();if (!canCreate || !instruction) return;- const name = plan.name.trim() || deriveGoalTitle(instruction);+ const typed = plan.name.trim();+ const name = typed || deriveGoalTitle(instruction);setPlan((current) => ({...current,instruction,name,}));instructionRef.current = instruction;+ setGenerateFailed(false);setStep('preparing');try {const generated = await generateGoalCriteria({@@ -299,25 +314,40 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {goal: instruction,});instructionRef.current = generated.instruction;+ const draftedTitle = resolveDraftedTitle({+ generated: generated.title,+ previousFallback: fallbackTitleRef.current,+ retrying: generateFailed,+ typed,+ });+ fallbackTitleRef.current = undefined;setPlan((current) => ({...current,criteria: generated.criteria,instruction: generated.instruction,- name: generated.title,+ name: draftedTitle,}));setStep('review');} catch (error) {console.error('[CreateGoalContent] generate failed:', error);+ // Never the instruction itself: a pasted prompt as the title is what+ // took over the goal page. The instruction stays the goal's body.+ fallbackTitleRef.current = resolveFallbackTitle({+ name,+ previousFallback: fallbackTitleRef.current,+ typed,+ });setPlan((current) => ({...current,criteria: [createFallbackGoalCriterion(instruction)],instruction,- name: instruction,+ name,}));+ setGenerateFailed(true);setStep('review');toast.warning(t('createGoal.generateFailed'));}- }, [canCreate, plan.instruction, plan.name, t]);+ }, [canCreate, generateFailed, plan.instruction, plan.name, t]);const handleCreateBlank = useCallback(() => {if (!canCreate) return;@@ -378,7 +408,11 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const reviewedCriteria = plan.criteria.filter((criterion) => criterion.title.trim());if (!instruction || reviewedCriteria.length === 0) return;- const title = plan.name.trim() || instruction;+ const { needsGeneratedTitle, title } = resolveSubmittedGoalTitle({+ fallbackTitle: fallbackTitleRef.current,+ instruction,+ name: plan.name,+ });const budget = buildGoalCreateInput({costBudget: plan.maxTotalCost,instruction,@@ -416,6 +450,13 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {// durable fallback — fired and forgotten so the modal still closes// immediately; the server dedupes a raced decomposition.void goalService.advance(graph.goal.id).catch(() => {});+ // A stopgap title is named from the instruction once the goal exists;+ // failing that, it keeps the stopgap rather than blocking the create.+ if (needsGeneratedTitle)+ void useGoalStore+ .getState()+ .autoRenameGoalTitle(graph.goal.id)+ .catch(() => {});close();onCreated?.({ agentId: graph.goal.agentId ?? undefined, goalId: graph.goal.id });} catch (error) {@@ -490,13 +531,32 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {</Flexbox>)}{step === 'review' ? (- <input- className={styles.title}- disabled={!canCreate}- placeholder={t('createGoal.titlePlaceholder')}- value={plan.name}- onChange={(e) => setPlan((current) => ({ ...current, name: e.target.value }))}- />+ <>+ <input+ className={styles.title}+ disabled={!canCreate}+ maxLength={GOAL_TITLE_MAX_LENGTH}+ placeholder={t('createGoal.titlePlaceholder')}+ value={plan.name}+ onChange={(e) => setPlan((current) => ({ ...current, name: e.target.value }))}+ />+ {generateFailed && (+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={12} type={'warning'}>+ {t('createGoal.generateFailed')}+ </Text>+ <Button+ disabled={!canCreate}+ icon={RotateCw}+ size={'small'}+ type={'text'}+ onClick={() => void handleNext()}+ >+ {t('regenerate', { ns: 'common' })}+ </Button>+ </Flexbox>+ )}+ </>) : (<div className={styles.titleStatic}>{t('createGoal.describeTitle')}</div>)}diff --git a/src/features/AgentGoals/CreateGoalModal/goalTitle.test.ts b/src/features/AgentGoals/CreateGoalModal/goalTitle.test.tsindex f84d1903e45..c6e01595d88 100644--- a/src/features/AgentGoals/CreateGoalModal/goalTitle.test.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalTitle.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { deriveGoalTitle } from './goalTitle';+import {+ deriveGoalTitle,+ resolveDraftedTitle,+ resolveFallbackTitle,+ resolveSubmittedGoalTitle,+} from './goalTitle';describe('deriveGoalTitle', () => {it('uses the first semantic clause instead of the entire instruction', () => {@@ -15,3 +20,90 @@ describe('deriveGoalTitle', () => {expect(deriveGoalTitle('a'.repeat(80))).toHaveLength(48);});});++describe('resolveSubmittedGoalTitle', () => {+ const instruction =+ '继续并完成桌宠项目 https://github.com/example/desk-pet,在现有基础上完善 TTS 语音系统,补齐唤醒词与打断';++ it('never submits the instruction as the title when the field is blank', () => {+ const { needsGeneratedTitle, title } = resolveSubmittedGoalTitle({ instruction, name: '' });++ expect(title).not.toBe(instruction);+ expect(title).toBe(deriveGoalTitle(instruction));+ expect(needsGeneratedTitle).toBe(true);+ });++ it('names the goal later when the stopgap from a failed draft is left untouched', () => {+ const fallbackTitle = deriveGoalTitle(instruction);++ expect(resolveSubmittedGoalTitle({ fallbackTitle, instruction, name: fallbackTitle })).toEqual({+ needsGeneratedTitle: true,+ title: fallbackTitle,+ });+ });++ it('keeps a title the user wrote', () => {+ expect(+ resolveSubmittedGoalTitle({+ fallbackTitle: deriveGoalTitle(instruction),+ instruction,+ name: ' 桌宠 TTS ',+ }),+ ).toEqual({ needsGeneratedTitle: false, title: '桌宠 TTS' });+ });+});++describe('resolveFallbackTitle', () => {+ const stopgap = '桌宠 TTS';++ it('records the derived title when the field was blank', () => {+ expect(resolveFallbackTitle({ name: stopgap, typed: '' })).toBe(stopgap);+ });++ it('keeps an untouched stopgap across a failed retry', () => {+ expect(resolveFallbackTitle({ name: stopgap, previousFallback: stopgap, typed: stopgap })).toBe(+ stopgap,+ );+ });++ it('does not treat a title edited before a failed retry as a stopgap', () => {+ expect(+ resolveFallbackTitle({ name: '我的标题', previousFallback: stopgap, typed: '我的标题' }),+ ).toBeUndefined();+ });++ it('does not treat a title typed before the first draft as a stopgap', () => {+ expect(resolveFallbackTitle({ name: '我的标题', typed: '我的标题' })).toBeUndefined();+ });+});++describe('resolveDraftedTitle', () => {+ const generated = 'Generated';++ it('uses the generated title on a first draft', () => {+ expect(resolveDraftedTitle({ generated, retrying: false, typed: 'Typed' })).toBe(generated);+ });++ it('keeps a title edited before drafting again', () => {+ expect(+ resolveDraftedTitle({+ generated,+ previousFallback: 'Stopgap',+ retrying: true,+ typed: 'Mine',+ }),+ ).toBe('Mine');+ });++ it('replaces an untouched stopgap or a blank field when drafting again', () => {+ expect(+ resolveDraftedTitle({+ generated,+ previousFallback: 'Stopgap',+ retrying: true,+ typed: 'Stopgap',+ }),+ ).toBe(generated);+ expect(resolveDraftedTitle({ generated, retrying: true, typed: '' })).toBe(generated);+ });+});diff --git a/src/features/AgentGoals/CreateGoalModal/goalTitle.ts b/src/features/AgentGoals/CreateGoalModal/goalTitle.tsindex 2e1641228cf..b210667fa63 100644--- a/src/features/AgentGoals/CreateGoalModal/goalTitle.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalTitle.ts@@ -4,3 +4,60 @@ export const deriveGoalTitle = (instruction: string) => {return (firstSentence || normalized).slice(0, 48);};++/**+ * The title a goal is created with. Never the instruction: a pasted prompt as+ * the title took over the goal page. A title the user did not write — left+ * blank, or the stopgap a failed draft put there — is named by the model once+ * the goal exists.+ */+export const resolveSubmittedGoalTitle = ({+ fallbackTitle,+ instruction,+ name,+}: {+ /** The stopgap title a failed draft left in the field, if any. */+ fallbackTitle?: string;+ instruction: string;+ name: string;+}) => {+ const typed = name.trim();+ const title = typed || deriveGoalTitle(instruction);+ return { needsGeneratedTitle: !typed || typed === fallbackTitle, title };+};++/**+ * The title after a successful draft. Drafting again from the review step keeps+ * a title the user edited there; otherwise the generated one is used.+ */+export const resolveDraftedTitle = ({+ generated,+ previousFallback,+ retrying,+ typed,+}: {+ generated: string;+ /** The stopgap title the failed draft left in the field, if any. */+ previousFallback?: string;+ /** Drafting again from the review step, rather than for the first time. */+ retrying: boolean;+ /** What was in the field before the draft, trimmed. */+ typed: string;+}) => (retrying && typed && typed !== previousFallback ? typed : generated);++/**+ * The stopgap title to remember when a criteria draft fails. Only a title the+ * user did not write stays a stopgap: one they typed or edited before this+ * draft is theirs, even when the draft fails again.+ */+export const resolveFallbackTitle = ({+ name,+ previousFallback,+ typed,+}: {+ /** The title the field holds after the failed draft. */+ name: string;+ previousFallback?: string;+ /** What was in the field before the draft, trimmed. */+ typed: string;+}) => (!typed || typed === previousFallback ? name : undefined);diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsxindex 0b92f8911e3..c2961652b66 100644--- a/src/features/AgentGoals/GoalDetailActions.tsx+++ b/src/features/AgentGoals/GoalDetailActions.tsx@@ -11,21 +11,34 @@ interface GoalDetailActionsProps {/** Absent for a goal with no responsible agent — e.g. one created from a project. */agentId?: string;goalId: string;+ /** Moves to the in-place title editor instead of opening the rename dialog. */+ onRename?: () => void;projectId?: string | null;}-const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, projectId }) => {- const { t } = useTranslation('chat');- const status = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.status);- const creatorUserId = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.userId);- const items = useGoalMenuItems({ agentId, creatorUserId, goalId, projectId, status });+const GoalDetailActions = memo<GoalDetailActionsProps>(+ ({ agentId, goalId, onRename, projectId }) => {+ const { t } = useTranslation('chat');+ const status = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.status);+ const creatorUserId = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.userId);+ const title = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.title);+ const items = useGoalMenuItems({+ agentId,+ creatorUserId,+ goalId,+ onRename,+ projectId,+ status,+ title,+ });- return (- <DropdownMenu items={items} placement={'bottomRight'}>- <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('goalDetail.moreActions')} />- </DropdownMenu>- );-});+ return (+ <DropdownMenu items={items} placement={'bottomRight'}>+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('goalDetail.moreActions')} />+ </DropdownMenu>+ );+ },+);GoalDetailActions.displayName = 'GoalDetailActions';diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex fa84bce7ec8..ead6105cbc9 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -153,6 +153,7 @@ vi.mock('./GoalChat', () => ({),}));vi.mock('./GoalDetailActions', () => ({ default: () => null }));+vi.mock('./GoalDetailTitle', () => ({ default: () => null }));vi.mock('./GoalHeaderMetrics', () => ({ default: () => null }));vi.mock('./GoalRequirement', () => ({ default: () => <div data-testid="goal-requirement" /> }));vi.mock('./NorthStarMetrics', () => ({ default: () => <div data-testid="goal-north-star" /> }));diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex a75e7fb9a10..942871d4e61 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -32,6 +32,7 @@ import GoalAgentModelConfig from './GoalAgentModelConfig';import GoalChat from './GoalChat';import { GoalConversationContext } from './goalConversation';import GoalDetailActions from './GoalDetailActions';+import GoalDetailTitle from './GoalDetailTitle';import GoalHeaderMetrics from './GoalHeaderMetrics';import { goalManagerConversation } from './goalPresentation';import GoalRequirement from './GoalRequirement';@@ -124,6 +125,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const showLeftPanel = useGlobalStore(systemStatusSelectors.showLeftPanel);const toggleLeftPanel = useGlobalStore((s) => s.toggleLeftPanel);const collapsedRailRef = useRef(false);+ const titleInputRef = useRef<HTMLTextAreaElement>(null);useEffect(() => {if (showPortal) {@@ -232,6 +234,22 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {else openPanel();};+ // Deferred past the menu closing, which hands focus back to its trigger.+ const focusTitleEditor = () => {+ requestAnimationFrame(() => {+ titleInputRef.current?.focus();+ titleInputRef.current?.select();+ });+ };++ // Clipped like the workspace crumb, so a long title cannot push the header's+ // actions off the bar.+ const goalCrumb = (+ <Text ellipsis color={'inherit'} style={{ maxWidth: 'min(320px, 45vw)' }} weight={500}>+ {goal.title}+ </Text>+ );+const paused = goal.status === 'paused';// Pace control exists only while the coordinator loop is actually moving (or// explicitly paused). A goal in review awaits the human, and a closed goal@@ -251,7 +269,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {{agentId ? (<AgentBreadcrumbagentId={agentId}- extraItems={[goal.title]}+ extraItems={[goalCrumb]}// The goal title owns the last crumb, so this one is a way back// to the agent's goal list rather than a label for this page.title={<Link to={buildAgentPath('goals')}>{t('goalList.title')}</Link>}@@ -267,7 +285,12 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {/>{/* Not nested under the breadcrumb: an agent-less goal still has tobe deletable, and this menu is the only place that can do it. */}- <GoalDetailActions agentId={agentId} goalId={goal.id} projectId={goal.projectId} />+ <GoalDetailActions+ agentId={agentId}+ goalId={goal.id}+ projectId={goal.projectId}+ onRename={focusTitleEditor}+ /></Flexbox>}right={@@ -291,9 +314,12 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {<Flexbox flex={1} style={{ overflowY: 'auto' }}><WideScreenContainer gap={20} paddingBlock={16}><Flexbox className={styles.header} gap={8}>- <Text as={'h1'} fontSize={22} weight={600}>- {goal.title}- </Text>+ <GoalDetailTitle+ creatorUserId={goal.userId}+ goalId={goal.id}+ inputRef={titleInputRef}+ title={goal.title}+ /><GoalHeaderMetrics goalId={goalId} />{/* Pause/resume above the requirement document — its reviewedhome. The status glyph keeps the "running" animation; thisdiff --git a/src/features/AgentGoals/GoalDetailTitle.test.tsx b/src/features/AgentGoals/GoalDetailTitle.test.tsxnew file mode 100644index 00000000000..b8d7f04e51d--- /dev/null+++ b/src/features/AgentGoals/GoalDetailTitle.test.tsx@@ -0,0 +1,23 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import GoalDetailTitle from './GoalDetailTitle';++vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));+vi.mock('@/hooks/useResourceManageable', () => ({ useResourceManageable: () => true }));+vi.mock('@/store/goal', () => ({+ goalSelectors: { isGoalTitleRenaming: () => () => false },+ useGoalStore: (selector: (s: unknown) => unknown) => selector({}),+}));+vi.mock('./useGoalActions', () => ({ useGoalRename: () => ({ rename: vi.fn() }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++describe('GoalDetailTitle', () => {+ it('stays the page heading and names its editor for screen readers', () => {+ render(<GoalDetailTitle goalId={'goal_1'} title={'Desk pet'} />);++ const editor = screen.getByRole('textbox', { name: 'rename' });+ expect(editor).toHaveValue('Desk pet');+ expect(screen.getByRole('heading', { level: 1 })).toContainElement(editor);+ });+});diff --git a/src/features/AgentGoals/GoalDetailTitle.tsx b/src/features/AgentGoals/GoalDetailTitle.tsxnew file mode 100644index 00000000000..18aab888a22--- /dev/null+++ b/src/features/AgentGoals/GoalDetailTitle.tsx@@ -0,0 +1,64 @@+import { GOAL_TITLE_MAX_LENGTH } from '@lobechat/const/goal';+import { TextArea } from '@lobehub/ui';+import { memo, type Ref } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermission } from '@/hooks/usePermission';+import { useResourceManageable } from '@/hooks/useResourceManageable';+import { goalSelectors, useGoalStore } from '@/store/goal';+import { shinyTextStyles } from '@/styles';++import { useGoalRename } from './useGoalActions';+import { useGoalTitleEditor } from './useGoalTitleEditor';++/** Past this many lines the header scrolls the title instead of pushing the page down. */+const MAX_TITLE_ROWS = 3;++interface GoalDetailTitleProps {+ creatorUserId?: string | null;+ goalId: string;+ /** Lets the header's menu move focus here for its Rename entry. */+ inputRef?: Ref<HTMLTextAreaElement>;+ title: string;+}++/**+ * The goal page's title, edited in place (see `useGoalTitleEditor`). Wraps+ * instead of truncating, up to `MAX_TITLE_ROWS`, so a goal still titled with a+ * whole pasted prompt cannot take over the page before it is renamed.+ */+const GoalDetailTitle = memo<GoalDetailTitleProps>(({ creatorUserId, goalId, inputRef, title }) => {+ const { t } = useTranslation('common');+ const { allowed: canEdit } = usePermission('create_content');+ // Same rule the server applies to a workspace goal: its creator or an owner.+ const canManage = useResourceManageable(creatorUserId);+ const renaming = useGoalStore(goalSelectors.isGoalTitleRenaming(goalId));+ const { rename } = useGoalRename(goalId);+ const { onBlur, onKeyDown, setValue, value } = useGoalTitleEditor(title, rename);++ return (+ <h1 style={{ margin: 0 }}>+ <TextArea+ aria-label={t('rename')}+ autoSize={{ maxRows: MAX_TITLE_ROWS, minRows: 1 }}+ className={renaming ? shinyTextStyles.shinyText : undefined}+ maxLength={GOAL_TITLE_MAX_LENGTH}+ readOnly={!canEdit || !canManage || renaming}+ ref={inputRef}+ style={{ padding: 0 }}+ value={value}+ variant={'borderless'}+ styles={{+ input: { fontSize: 22, fontWeight: 600, lineHeight: 1.5, minHeight: 'auto' },+ }}+ onBlur={onBlur}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={onKeyDown}+ />+ </h1>+ );+});++GoalDetailTitle.displayName = 'GoalDetailTitle';++export default GoalDetailTitle;diff --git a/src/features/AgentGoals/useGoalActions.ts b/src/features/AgentGoals/useGoalActions.tsindex f57d66d3a43..c9fb519d356 100644--- a/src/features/AgentGoals/useGoalActions.ts+++ b/src/features/AgentGoals/useGoalActions.ts@@ -1,12 +1,15 @@-import { confirmModal } from '@lobehub/ui';+import { GOAL_TITLE_MAX_LENGTH } from '@lobechat/const/goal';+import { confirmModal, toast } from '@lobehub/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { openRenameModal } from '@/components/RenameModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useAppOrigin } from '@/hooks/useAppOrigin';import { useGoalStore } from '@/store/goal';+import { isForbiddenError } from '@/utils/forbiddenError';interface GoalRef {/** Absent for a goal with no responsible agent — e.g. one created from a project. */@@ -70,3 +73,60 @@ export const useConfirmDeleteGoal = ({});}, [agentId, deleteGoal, goalId, navigate, onDeleted, projectId, t]);};++/**+ * Rename a goal by hand or let the topic naming model do it — the same two+ * actions, copy and error handling as a topic's menu. Each settles on its own+ * and reports a failure itself, so a caller only wires up the click.+ */+export const useGoalRename = (goalId: string) => {+ const { t } = useTranslation(['topic', 'common']);+ const updateGoalTitle = useGoalStore((s) => s.updateGoalTitle);+ const autoRenameGoalTitle = useGoalStore((s) => s.autoRenameGoalTitle);++ const reportFailure = useCallback(+ (error: unknown) => {+ toast.error(+ isForbiddenError(error)+ ? t('manageOnlyCreator', { ns: 'common' })+ : t('operationFailed', { ns: 'common' }),+ );+ },+ [t],+ );++ /** Saves `title`; rejects after reporting, so an editor can keep the typed text. */+ const rename = useCallback(+ async (title: string) => {+ try {+ await updateGoalTitle(goalId, title);+ } catch (error) {+ console.error('[useGoalRename] rename failed:', error);+ reportFailure(error);+ throw error;+ }+ },+ [goalId, reportFailure, updateGoalTitle],+ );++ const openRename = useCallback(+ (title: string) =>+ openRenameModal({+ defaultValue: title,+ maxLength: GOAL_TITLE_MAX_LENGTH,+ onSave: rename,+ }),+ [rename],+ );++ const autoRename = useCallback(async () => {+ try {+ await autoRenameGoalTitle(goalId);+ } catch (error) {+ console.error('[useGoalRename] auto rename failed:', error);+ reportFailure(error);+ }+ }, [autoRenameGoalTitle, goalId, reportFailure]);++ return { autoRename, openRename, rename };+};diff --git a/src/features/AgentGoals/useGoalMenuItems.test.ts b/src/features/AgentGoals/useGoalMenuItems.test.tsindex b4d00502d07..ed76e131f35 100644--- a/src/features/AgentGoals/useGoalMenuItems.test.ts+++ b/src/features/AgentGoals/useGoalMenuItems.test.ts@@ -2,12 +2,15 @@ import type { DropdownItem } from '@lobehub/ui';import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { useGoalItemMenu } from './useGoalMenuItems';+import { useGoalItemMenu, useGoalMenuItems } from './useGoalMenuItems';const mocks = vi.hoisted(() => ({+ autoRename: vi.fn(),confirmDelete: vi.fn(),deleteOptions: undefined as { onDeleted?: () => void } | undefined,navigate: vi.fn(),+ openRename: vi.fn(),+ renameGoalId: undefined as string | undefined,store: {closeGoal: vi.fn(),pauseGoal: vi.fn(),@@ -31,11 +34,21 @@ vi.mock('./useGoalActions', () => ({mocks.deleteOptions = options;return mocks.confirmDelete;},+ useGoalRename: (goalId: string) => {+ mocks.renameGoalId = goalId;+ return { autoRename: mocks.autoRename, openRename: mocks.openRename, rename: vi.fn() };+ },useGoalShareUrl: () => 'https://app.lobehub.com/goal/goal_1',}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));-const goal = { agentId: 'agt_1', id: 'goal_1', status: 'running', userId: 'user_1' };+const goal = {+ agentId: 'agt_1',+ id: 'goal_1',+ status: 'running',+ title: 'Desk pet',+ userId: 'user_1',+};const pickStatus = (items: DropdownItem[], next: string) => {const status = items.find((item) => item && 'key' in item && item.key === 'status') as any;@@ -95,4 +108,37 @@ describe('useGoalItemMenu', () => {const keys = result.current.map((item) => (item && 'key' in item ? item.key : item?.type));expect(keys.slice(-4)).toEqual(['copyLink', 'copy-goal', 'divider', 'delete']);});++ // Same pair, copy and order as a topic's menu.+ it('leads with smart rename and rename, like a topic', () => {+ const { result } = renderHook(() => useGoalItemMenu({ agentId: 'agt_1', goal }));+ const keys = result.current.map((item) => (item && 'key' in item ? item.key : item?.type));++ expect(keys.slice(0, 3)).toEqual(['autoRename', 'rename', 'divider']);+ expect(result.current[0]).toMatchObject({ label: 'actions.autoRename' });+ expect(result.current[1]).toMatchObject({ label: 'rename' });+ });++ it('renames the row it was opened on, prefilled with its title', () => {+ const { result } = renderHook(() => useGoalItemMenu({ agentId: 'agt_1', goal }));++ (result.current[0] as any).onClick();+ (result.current[1] as any).onClick();++ expect(mocks.renameGoalId).toBe('goal_1');+ expect(mocks.autoRename).toHaveBeenCalled();+ expect(mocks.openRename).toHaveBeenCalledWith('Desk pet');+ });++ it('hands Rename to a host that edits the title in place, without the dialog', () => {+ const onRename = vi.fn();+ const { result } = renderHook(() =>+ useGoalMenuItems({ goalId: 'goal_1', onRename, title: 'Desk pet' }),+ );++ (result.current[1] as any).onClick();++ expect(onRename).toHaveBeenCalled();+ expect(mocks.openRename).not.toHaveBeenCalled();+ });});diff --git a/src/features/AgentGoals/useGoalMenuItems.tsx b/src/features/AgentGoals/useGoalMenuItems.tsxindex d4d71148628..01abf1bb5e8 100644--- a/src/features/AgentGoals/useGoalMenuItems.tsx+++ b/src/features/AgentGoals/useGoalMenuItems.tsx@@ -1,5 +1,12 @@import { confirmModal, copyToClipboard, type DropdownItem, Icon, toast } from '@lobehub/ui';-import { CircleDashedIcon, CopyIcon, LinkIcon, TrashIcon } from 'lucide-react';+import {+ CircleDashedIcon,+ CopyIcon,+ LinkIcon,+ PencilLineIcon,+ TrashIcon,+ Wand2Icon,+} from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -17,7 +24,7 @@ import {type ManualGoalStatus,toManualStatus,} from './goalStatusMenu';-import { useConfirmDeleteGoal, useGoalShareUrl } from './useGoalActions';+import { useConfirmDeleteGoal, useGoalRename, useGoalShareUrl } from './useGoalActions';interface UseGoalMenuItemsOptions {/** Absent for a goal with no responsible agent — e.g. one created from a project. */@@ -26,10 +33,14 @@ interface UseGoalMenuItemsOptions {goalId: string;/** Replaces the default redirect to the goal list after a delete. */onDeleted?: () => void;+ /** Replaces the rename dialog, for a host that already edits the title in place. */+ onRename?: () => void;/** Runs after a status change lands, for hosts that render the status from another read. */onStatusChanged?: () => void;projectId?: string | null;status?: string;+ /** The current title, prefilled by the rename dialog. */+ title?: string;}/** The goal's action menu, shared by the detail header's "more" button and the list rows. */@@ -38,11 +49,13 @@ export const useGoalMenuItems = ({creatorUserId,goalId,onDeleted,+ onRename,onStatusChanged,projectId,status,+ title,}: UseGoalMenuItemsOptions): DropdownItem[] => {- const { t } = useTranslation(['chat', 'common']);+ const { t } = useTranslation(['chat', 'common', 'topic']);const { allowed: canEditTask } = usePermission('create_content');const shareUrl = useGoalShareUrl({ agentId, goalId });const confirmDelete = useConfirmDeleteGoal({ agentId, goalId, onDeleted, projectId });@@ -54,6 +67,9 @@ export const useGoalMenuItems = ({const startGoal = useGoalStore((s) => s.startGoal);const closeGoal = useGoalStore((s) => s.closeGoal);const transferItems = useGoalTransferMenuItem(goalId) as DropdownItem[] | null;+ const { autoRename, openRename } = useGoalRename(goalId);+ // The server lets a workspace goal be renamed only by its creator or an owner.+ const canRename = canEditTask && canClose;const current = toManualStatus(status);@@ -81,6 +97,25 @@ export const useGoalMenuItems = ({return useMemo<DropdownItem[]>(() => [+ // The topic menu's pair, in the topic menu's order.+ {+ disabled: !canRename,+ icon: <Icon icon={Wand2Icon} />,+ key: 'autoRename',+ label: t('actions.autoRename', { ns: 'topic' }),+ onClick: autoRename,+ },+ {+ disabled: !canRename || title === undefined,+ icon: <Icon icon={PencilLineIcon} />,+ key: 'rename',+ label: t('rename', { ns: 'common' }),+ onClick: () => {+ if (onRename) onRename();+ else if (title !== undefined) openRename(title);+ },+ },+ { type: 'divider' },// Same shape as a task's status submenu: status-colored glyphs, a check on the current one.{children: MANUAL_STATUSES.map((next) => {@@ -132,15 +167,20 @@ export const useGoalMenuItems = ({},],[+ autoRename,canClose,canEditTask,+ canRename,changeStatus,confirmDelete,current,goalId,+ onRename,+ openRename,shareUrl,status,t,+ title,transferItems,],);@@ -151,7 +191,13 @@ interface UseGoalItemMenuOptions {agentId?: string | null;/** The cross-agent list rendering the row, refreshed in place of an agent's or project's. */globalScopeId?: string;- goal: { agentId?: string | null; id: string; status: string; userId?: string | null };+ goal: {+ agentId?: string | null;+ id: string;+ status: string;+ title?: string;+ userId?: string | null;+ };/** The project whose goal page renders the row; absent on an agent's page. */projectId?: string;/** The route's agent, which keys the list scope on an agent's page. */@@ -183,6 +229,7 @@ export const useGoalItemMenu = ({onStatusChanged: handleStatusChanged,projectId,status: goal.status,+ title: goal.title,});};diff --git a/src/features/AgentGoals/useGoalTitleEditor.test.ts b/src/features/AgentGoals/useGoalTitleEditor.test.tsnew file mode 100644index 00000000000..381b3372738--- /dev/null+++ b/src/features/AgentGoals/useGoalTitleEditor.test.ts@@ -0,0 +1,126 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGoalTitleEditor } from './useGoalTitleEditor';++const save = vi.fn();++const keyEvent = (key: string) => {+ const blur = vi.fn();+ return {+ blur,+ event: {+ currentTarget: { blur },+ key,+ nativeEvent: { isComposing: false },+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ } as never,+ };+};++const renderEditor = (title = 'Old title') =>+ renderHook(({ current }) => useGoalTitleEditor(current, save), {+ initialProps: { current: title },+ });++describe('useGoalTitleEditor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ save.mockResolvedValue(undefined);+ });++ it('saves the trimmed title when the field loses focus', async () => {+ const { result } = renderEditor();++ act(() => result.current.setValue(' New title '));+ await act(async () => result.current.onBlur());++ expect(save).toHaveBeenCalledWith('New title');+ });++ it('keeps a newer edit when an older save fails', async () => {+ let rejectFirst!: (error: Error) => void;+ save.mockReturnValueOnce(new Promise((_, reject) => (rejectFirst = reject)));+ const { rerender, result } = renderEditor();++ act(() => result.current.setValue('First'));+ await act(async () => result.current.onBlur());+ rerender({ current: 'First' });+ act(() => result.current.setValue('Second'));+ await act(async () => result.current.onBlur());+ rerender({ current: 'Second' });++ await act(async () => rejectFirst(new Error('network')));++ expect(result.current.value).toBe('Second');+ });++ it('leaves the field on Enter, which saves through the blur', () => {+ const { result } = renderEditor();+ const { blur, event } = keyEvent('Enter');++ act(() => result.current.onKeyDown(event));++ expect(blur).toHaveBeenCalled();+ });++ it('puts the saved title back on Escape and skips the save its blur triggers', async () => {+ const { result } = renderEditor();+ const { blur, event } = keyEvent('Escape');++ act(() => result.current.setValue('Draft'));+ act(() => result.current.onKeyDown(event));+ await act(async () => result.current.onBlur());++ expect(blur).toHaveBeenCalled();+ expect(save).not.toHaveBeenCalled();+ expect(result.current.value).toBe('Old title');++ // Only that one blur is skipped; the next edit saves again.+ act(() => result.current.setValue('Later'));+ await act(async () => result.current.onBlur());+ expect(save).toHaveBeenCalledWith('Later');+ });++ it('ignores Enter while an IME is composing', () => {+ const { result } = renderEditor();+ const { blur, event } = keyEvent('Enter');+ (event as { nativeEvent: { isComposing: boolean } }).nativeEvent.isComposing = true;++ act(() => result.current.onKeyDown(event));++ expect(blur).not.toHaveBeenCalled();+ });++ it('saves nothing for a blank or unchanged title', async () => {+ const { result } = renderEditor();++ act(() => result.current.setValue(' '));+ await act(async () => result.current.onBlur());+ expect(result.current.value).toBe('Old title');++ act(() => result.current.setValue('Old title'));+ await act(async () => result.current.onBlur());++ expect(save).not.toHaveBeenCalled();+ });++ it('shows the saved title again when the save is rejected', async () => {+ save.mockRejectedValue(new Error('forbidden'));+ const { result } = renderEditor();++ act(() => result.current.setValue('Nope'));+ await act(async () => result.current.onBlur());++ await waitFor(() => expect(result.current.value).toBe('Old title'));+ });++ it('follows a rename that lands from elsewhere', () => {+ const { rerender, result } = renderEditor();++ rerender({ current: 'Smart title' });++ expect(result.current.value).toBe('Smart title');+ });+});diff --git a/src/features/AgentGoals/useGoalTitleEditor.ts b/src/features/AgentGoals/useGoalTitleEditor.tsnew file mode 100644index 00000000000..1a71c46f217--- /dev/null+++ b/src/features/AgentGoals/useGoalTitleEditor.ts@@ -0,0 +1,59 @@+import { type KeyboardEvent, useEffect, useRef, useState } from 'react';++/**+ * In-place title editing: Enter or leaving the field saves, Escape puts the+ * saved title back. A blank or unchanged value saves nothing, and a rejected+ * save shows the saved title again (`save` reports its own failure).+ */+export const useGoalTitleEditor = (title: string, save: (title: string) => Promise<void>) => {+ const [value, setValue] = useState(title);+ // Escape blurs the field too; the save that blur would run must not fire.+ const skipBlurSaveRef = useRef(false);+ // Only the latest save may restore the field: an older one failing must not+ // put its stale title over a newer edit, which a later blur would then save.+ const latestSaveRef = useRef(0);++ useEffect(() => {+ setValue(title);+ }, [title]);++ const commit = async () => {+ const next = value.trim();+ if (!next || next === title) {+ setValue(title);+ return;+ }+ const saveId = ++latestSaveRef.current;+ try {+ await save(next);+ } catch {+ if (saveId === latestSaveRef.current) setValue(title);+ }+ };++ const onBlur = () => {+ if (skipBlurSaveRef.current) {+ skipBlurSaveRef.current = false;+ return;+ }+ void commit();+ };++ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.nativeEvent.isComposing) return;+ if (event.key === 'Enter') {+ event.preventDefault();+ event.currentTarget.blur();+ return;+ }+ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ skipBlurSaveRef.current = true;+ setValue(title);+ event.currentTarget.blur();+ }+ };++ return { onBlur, onKeyDown, setValue, value };+};diff --git a/src/services/goal.ts b/src/services/goal.tsindex 21be33c25e6..7fe0eefb6be 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -232,6 +232,9 @@ class GoalService {updateRequirement = async (id: string, requirement: string) =>lambdaClient.goal.updateRequirement.mutate({ id, requirement });++ updateTitle = async (id: string, title: string) =>+ lambdaClient.goal.updateTitle.mutate({ id, title });}export const goalService = new GoalService();diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 67fcc119478..b41cfa080af 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -3,6 +3,7 @@ import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { mutate, useClientDataSWR } from '@/libs/swr';+import { aiChatService } from '@/services/aiChat';import { goalService } from '@/services/goal';import { useGoalStore } from './index';@@ -26,9 +27,18 @@ vi.mock('@/services/goal', () => ({getGraph: vi.fn(),list: vi.fn(),tick: vi.fn(),+ updateTitle: vi.fn(),},}));+vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => ({ refreshTopicDetail: vi.fn() }) },+}));++vi.mock('@/services/aiChat', () => ({+ aiChatService: { generateJSON: vi.fn() },+}));+const SCOPE = 'user-1:personal';/** The replica sync call of one resource — the hydrate read shares the hook. */@@ -404,4 +414,170 @@ describe('GoalAction', () => {expect(goalService.advance).toHaveBeenCalledWith('goal-1', 'ollama');expect(goalService.tick).toHaveBeenCalledWith('goal-1', 'ollama');});++ describe('goal title', () => {+ const LONG_ASK = '继续并完成桌宠项目,在现有基础上完善 TTS 语音系统,补齐唤醒词与打断';++ const seedEverywhere = () =>+ useGoalStore.setState({+ goalGraphById: {+ 'goal-1': graphWith('paused', {+ goal: { id: 'goal-1', requirement: LONG_ASK, status: 'paused', title: LONG_ASK },+ nodes: [+ { id: 'n1', kind: 'task', status: 'active', title: 'Wire up the TTS engine' },+ { id: 'n2', kind: 'finding', status: 'resolved', title: 'Edge TTS has low latency' },+ ],+ }),+ },+ goalListByAgentId: {+ 'agent-1': { goals: [{ goal: { id: 'goal-1', title: LONG_ASK } }] as never, total: 1 },+ },+ homeGoalsByScope: {+ [SCOPE]: { goals: [{ goal: { id: 'goal-1', title: LONG_ASK } }] as never, total: 1 },+ },+ });++ const titlesShown = () => {+ const state = useGoalStore.getState();+ return [+ state.goalGraphById['goal-1']?.goal.title,+ state.goalListByAgentId['agent-1']?.goals[0]?.goal.title,+ state.homeGoalsByScope[SCOPE]?.goals[0]?.goal.title,+ ];+ };++ it('renames the goal on the page and in every list holding it', async () => {+ seedEverywhere();+ vi.mocked(goalService.updateTitle).mockResolvedValue({} as never);++ await useGoalStore.getState().updateGoalTitle('goal-1', ' 桌宠 TTS ');++ expect(goalService.updateTitle).toHaveBeenCalledWith('goal-1', '桌宠 TTS');+ expect(titlesShown()).toEqual(['桌宠 TTS', '桌宠 TTS', '桌宠 TTS']);+ });++ it('ignores a blank title', async () => {+ seedEverywhere();++ await useGoalStore.getState().updateGoalTitle('goal-1', ' ');++ expect(goalService.updateTitle).not.toHaveBeenCalled();+ expect(titlesShown()).toEqual([LONG_ASK, LONG_ASK, LONG_ASK]);+ });++ it('re-reads from the server and rethrows when the rename is rejected', async () => {+ seedEverywhere();+ const error = new Error('forbidden');+ vi.mocked(goalService.updateTitle).mockRejectedValue(error);++ await expect(useGoalStore.getState().updateGoalTitle('goal-1', 'New')).rejects.toBe(error);++ expect(mutate).toHaveBeenCalled();+ });++ it('sends title writes one at a time, so the latest edit is the last the server sees', async () => {+ seedEverywhere();+ const finish: Array<() => void> = [];+ vi.mocked(goalService.updateTitle).mockImplementation(+ () => new Promise((resolve) => finish.push(() => resolve({} as never))),+ );++ const first = useGoalStore.getState().updateGoalTitle('goal-1', 'First');+ const second = useGoalStore.getState().updateGoalTitle('goal-1', 'Second');+ await vi.waitFor(() => expect(goalService.updateTitle).toHaveBeenCalledTimes(1));+ expect(goalService.updateTitle).toHaveBeenLastCalledWith('goal-1', 'First');++ finish[0]();+ await first;+ await vi.waitFor(() => expect(goalService.updateTitle).toHaveBeenCalledTimes(2));+ expect(goalService.updateTitle).toHaveBeenLastCalledWith('goal-1', 'Second');++ finish[1]();+ await second;+ expect(titlesShown()).toEqual(['Second', 'Second', 'Second']);+ });++ it('keeps the newer edit on screen when an older write fails', async () => {+ seedEverywhere();+ const error = new Error('network');+ vi.mocked(goalService.updateTitle)+ .mockRejectedValueOnce(error)+ .mockResolvedValueOnce({} as never);+ mutate.mockClear();++ const first = useGoalStore.getState().updateGoalTitle('goal-1', 'First');+ const second = useGoalStore.getState().updateGoalTitle('goal-1', 'Second');++ await expect(first).rejects.toBe(error);+ await second;++ expect(goalService.updateTitle).toHaveBeenLastCalledWith('goal-1', 'Second');+ expect(mutate).not.toHaveBeenCalled();+ expect(titlesShown()).toEqual(['Second', 'Second', 'Second']);+ });++ it('keeps a title saved by hand while the model was generating', async () => {+ seedEverywhere();+ vi.mocked(goalService.updateTitle).mockResolvedValue({} as never);+ vi.mocked(aiChatService.generateJSON).mockImplementation(async () => {+ await useGoalStore.getState().updateGoalTitle('goal-1', 'By hand');+ return { data: { title: 'Generated' } } as never;+ });++ await useGoalStore.getState().autoRenameGoalTitle('goal-1');++ expect(goalService.updateTitle).toHaveBeenCalledTimes(1);+ expect(titlesShown()).toEqual(['By hand', 'By hand', 'By hand']);+ });++ it('names the goal from its ask and progress with the topic title chain', async () => {+ seedEverywhere();+ vi.mocked(aiChatService.generateJSON).mockResolvedValue({+ data: { title: '桌宠 TTS 语音系统' },+ } as never);+ vi.mocked(goalService.updateTitle).mockResolvedValue({} as never);++ await useGoalStore.getState().autoRenameGoalTitle('goal-1');++ const [params] = vi.mocked(aiChatService.generateJSON).mock.calls[0];+ const prompt = (params as { messages: Array<{ content: string }> }).messages+ .map((message) => message.content)+ .join('\n');+ expect(prompt).toContain(LONG_ASK);+ expect(prompt).toContain('Wire up the TTS engine');+ expect(prompt).toContain('Edge TTS has low latency');+ expect(params).toMatchObject({ schema: { name: expect.any(String) } });+ expect(goalService.updateTitle).toHaveBeenCalledWith('goal-1', '桌宠 TTS 语音系统');+ expect(titlesShown()).toEqual([+ '桌宠 TTS 语音系统',+ '桌宠 TTS 语音系统',+ '桌宠 TTS 语音系统',+ ]);+ expect(useGoalStore.getState().goalTitleRenamingIds).toEqual([]);+ });++ it('keeps the title and reports the failure when no title comes back', async () => {+ seedEverywhere();+ vi.mocked(aiChatService.generateJSON).mockResolvedValue({ data: { title: ' ' } } as never);++ await expect(useGoalStore.getState().autoRenameGoalTitle('goal-1')).rejects.toThrow();++ expect(goalService.updateTitle).not.toHaveBeenCalled();+ expect(titlesShown()).toEqual([LONG_ASK, LONG_ASK, LONG_ASK]);+ expect(useGoalStore.getState().goalTitleRenamingIds).toEqual([]);+ });++ it('reads the graph first when the goal is only known from a list', async () => {+ vi.mocked(goalService.getGraph).mockResolvedValue(+ graphWith('running', { goal: { id: 'goal-1', requirement: LONG_ASK, title: 'x' } }),+ );+ vi.mocked(aiChatService.generateJSON).mockResolvedValue({ data: { title: 'TTS' } } as never);+ vi.mocked(goalService.updateTitle).mockResolvedValue({} as never);++ await useGoalStore.getState().autoRenameGoalTitle('goal-1');++ expect(goalService.getGraph).toHaveBeenCalledWith('goal-1');+ expect(goalService.updateTitle).toHaveBeenCalledWith('goal-1', 'TTS');+ });+ });});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex e3fbb46f6f6..a5640423271 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -1,5 +1,20 @@-import { GOAL_ACCEPTANCE_TASK_TITLE, type GoalStatus } from '@lobechat/const/goal';-import type { GoalGraphSnapshot, GoalMetricCriterion, GoalTickResult } from '@lobechat/types';+import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_TITLE_MAX_LENGTH,+ type GoalStatus,+} from '@lobechat/const/goal';+import {+ chainSummaryTitle,+ TOPIC_TITLE_JSON_SCHEMA,+ TOPIC_TITLE_PROMPT_VERSION,+} from '@lobechat/prompts';+import {+ type GoalGraphSnapshot,+ type GoalMetricCriterion,+ type GoalTickResult,+ RequestTrigger,+} from '@lobechat/types';import {createReplicaSlice,@@ -9,12 +24,16 @@ import {} from '@/libs/replica';import { mutate, useClientDataSWR } from '@/libs/swr';import { goalKeys } from '@/libs/swr/keys';+import { aiChatService } from '@/services/aiChat';import { type GoalListItem, goalService } from '@/services/goal';import { type MetricSeriesWithPoints, metricService } from '@/services/metric';import type { StoreSetter } from '@/store/types';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';import { isTrpcErrorCode } from '@/utils/trpcError';import { goalStatusesForFilter } from './goalListFilter';+import { buildGoalTitleMessages } from './goalTitle';import { useGoalStore } from './index';import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';import {@@ -397,6 +416,134 @@ export class GoalActionImpl {await this.refreshGoalGraph(goalId);};+ /** Each goal's latest title write, so writes reach the server in the order they were made. */+ #titleWrites = new Map<string, Promise<unknown>>();++ /**+ * Rename a goal everywhere it is shown — the page header, every list tab,+ * the home rail and the conversation that created it — before the server+ * answers. A rejected rename re-reads them all from the server and rethrows,+ * so the caller can say why. Writes run one at a time per goal, so the latest+ * edit is the one the server keeps, whichever request would have finished first.+ */+ updateGoalTitle = async (goalId: string, title: string): Promise<void> => {+ const next = title.trim().slice(0, GOAL_TITLE_MAX_LENGTH);+ if (!next) return;++ this.#goalGraph.update(+ goalId,+ (graph) =>+ graph && {+ ...graph,+ goal: { ...graph.goal, title: next },+ // The server moves the root question along while it still has the old title.+ nodes: graph.nodes.map((node) =>+ node.kind === 'problem' && node.title === graph.goal.title+ ? { ...node, title: next }+ : node,+ ),+ },+ );+ this.#goalListRows.update(goalId, (item) => ({ ...item, goal: { ...item.goal, title: next } }));++ const write = (this.#titleWrites.get(goalId) ?? Promise.resolve())+ .catch(() => {})+ .then(() => goalService.updateTitle(goalId, next));+ this.#titleWrites.set(goalId, write);++ try {+ await write;+ // The goal's management topic was renamed with it.+ const topicId = this.#get().goalGraphById[goalId]?.goal.config?.managerState?.topicId;+ // Loaded on demand: a static import puts the whole chat store on the first screen.+ if (topicId)+ void import('@/store/chat')+ .then(({ useChatStore }) => useChatStore.getState().refreshTopicDetail(topicId, true))+ .catch(() => {});+ } catch (error) {+ // A newer edit is still on its way: re-reading now would show this one's old title over it.+ if (this.#titleWrites.get(goalId) === write) {+ await Promise.allSettled([+ this.refreshGoalGraph(goalId),+ revalidateReplica(goalListResource),+ revalidateReplica(homeGoalListResource),+ revalidateReplica(topicGoalListResource),+ ]);+ }+ throw error;+ } finally {+ if (this.#titleWrites.get(goalId) === write) this.#titleWrites.delete(goalId);+ }+ };++ /**+ * Name the goal from what it asks and what it has produced so far, with the+ * chain and model topics are named with (`summaryTopicTitle`). An empty answer+ * leaves the title alone. Failures reach the caller: the menu reports them,+ * the background rename after creation ignores them.+ */+ autoRenameGoalTitle = async (goalId: string): Promise<void> => {+ if (this.#get().goalTitleRenamingIds.includes(goalId)) return;+ this.#setGoalTitleRenaming(goalId, true);++ try {+ const graph = this.#get().goalGraphById[goalId] ?? (await goalService.getGraph(goalId));+ // A title saved by hand while the model was working is the newer choice.+ const titleWhenAsked = this.#titleShown(goalId) ?? graph.goal.title;+ const { model, provider } = systemAgentSelectors.topic(useUserStore.getState());+ const { data } = await aiChatService.generateJSON(+ {+ ...chainSummaryTitle(+ buildGoalTitleMessages(graph),+ userGeneralSettingsSelectors.currentResponseLanguage(useUserStore.getState()),+ ),+ metadata: { trigger: RequestTrigger.Goal },+ model,+ provider,+ schema: TOPIC_TITLE_JSON_SCHEMA,+ tracing: {+ promptVersion: TOPIC_TITLE_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicTitle,+ schemaName: TOPIC_TITLE_JSON_SCHEMA.name,+ },+ },+ new AbortController(),+ );++ const title = (data as { title?: string } | undefined)?.title?.trim();+ if (!title) throw new Error('No goal title was generated.');++ if ((this.#titleShown(goalId) ?? titleWhenAsked) !== titleWhenAsked) return;++ await this.updateGoalTitle(goalId, title);+ } finally {+ this.#setGoalTitleRenaming(goalId, false);+ }+ };++ /** What the page or a list row shows now; a list row may be all that is loaded. */+ #titleShown = (goalId: string): string | undefined => {+ const state = this.#get();+ const inList = (lists: Record<string, { goals: GoalListItem[] } | undefined>) =>+ Object.values(lists)+ .flatMap((list) => list?.goals ?? [])+ .find((item) => item.goal.id === goalId)?.goal.title;+ return (+ state.goalGraphById[goalId]?.goal.title ??+ inList(state.goalListByAgentId) ??+ inList(state.homeGoalsByScope)+ );+ };++ #setGoalTitleRenaming = (goalId: string, renaming: boolean) => {+ const ids = this.#get().goalTitleRenamingIds.filter((id) => id !== goalId);+ this.#set(+ { goalTitleRenamingIds: renaming ? [...ids, goalId] : ids },+ false,+ 'setGoalTitleRenaming',+ );+ };+/*** Ask the server to run the coordinator now. The goal keeps advancing on its* own afterwards as its Work Tasks settle, so this is a nudge rather than thediff --git a/src/store/goal/goalTitle.test.ts b/src/store/goal/goalTitle.test.tsnew file mode 100644index 00000000000..4d1a0c5d3ff--- /dev/null+++ b/src/store/goal/goalTitle.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { buildGoalTitleMessages } from './goalTitle';++const snapshot = (goal: Record<string, unknown>, nodes: unknown[] = []) =>+ ({ goal: { id: 'goal-1', status: 'paused', ...goal }, nodes }) as never;++describe('buildGoalTitleMessages', () => {+ it('asks with the requirement, not a title that is the whole prompt', () => {+ const messages = buildGoalTitleMessages(+ snapshot({ requirement: 'Finish the desk pet TTS system', title: 'old title' }),+ );++ expect(messages).toEqual([{ content: 'Finish the desk pet TTS system', role: 'user' }]);+ });++ it('falls back to the title when the goal has no requirement', () => {+ expect(buildGoalTitleMessages(snapshot({ requirement: null, title: 'Ship v2' }))).toEqual([+ { content: 'Ship v2', role: 'user' },+ ]);+ });++ it('adds the tasks and findings produced so far as the reply', () => {+ const messages = buildGoalTitleMessages(+ snapshot({ requirement: 'Ask', title: 'Ask' }, [+ { kind: 'problem', title: 'Root' },+ { kind: 'task', title: 'Wire TTS' },+ { kind: 'finding', title: 'Edge TTS is fast' },+ ]),+ );++ expect(messages[1]).toEqual({+ content: '- Task: Wire TTS\n- Finding: Edge TTS is fast',+ role: 'assistant',+ });+ });++ it('caps how many nodes reach the prompt', () => {+ const nodes = Array.from({ length: 50 }, (_, index) => ({ kind: 'task', title: `T${index}` }));+ const [, reply] = buildGoalTitleMessages(snapshot({ requirement: 'Ask' }, nodes));++ expect(reply.content.split('\n')).toHaveLength(20);+ });++ it('caps Tasks and findings together, Tasks first', () => {+ const nodes = [+ ...Array.from({ length: 15 }, (_, index) => ({ kind: 'task', title: `T${index}` })),+ ...Array.from({ length: 15 }, (_, index) => ({ kind: 'finding', title: `F${index}` })),+ ];+ const [, reply] = buildGoalTitleMessages(snapshot({ requirement: 'Ask' }, nodes));+ const lines = reply.content.split('\n');++ expect(lines).toHaveLength(20);+ expect(lines.filter((line) => line.startsWith('- Task:'))).toHaveLength(15);+ });+});diff --git a/src/store/goal/goalTitle.ts b/src/store/goal/goalTitle.tsnew file mode 100644index 00000000000..fdd6e51a511--- /dev/null+++ b/src/store/goal/goalTitle.ts@@ -0,0 +1,28 @@+import type { GoalGraphSnapshot, GoalNodeKind } from '@lobechat/types';++/** Enough of the graph to say what the goal is about without flooding the title prompt. */+const MAX_TITLE_CONTEXT_ITEMS = 20;++/**+ * The goal as a conversation for `chainSummaryTitle`, so goals are named by the+ * same chain and model as topics. The ask is the requirement, not the title: a+ * goal whose title is the whole pasted prompt is exactly the one being renamed.+ * Its Tasks and findings read as the reply, which is what the goal turned into.+ */+export const buildGoalTitleMessages = ({+ goal,+ nodes = [],+}: GoalGraphSnapshot): Array<{ content: string; role: 'assistant' | 'user' }> => {+ const ofKind = (kind: GoalNodeKind) => nodes.filter((node) => node.kind === kind);++ const ask = goal.requirement?.trim() || goal.title;+ // One cap across both kinds, Tasks first.+ const progress = [...ofKind('task'), ...ofKind('finding')]+ .slice(0, MAX_TITLE_CONTEXT_ITEMS)+ .map((node) => `- ${node.kind === 'task' ? 'Task' : 'Finding'}: ${node.title}`);++ return [+ { content: ask, role: 'user' },+ ...(progress.length > 0 ? [{ content: progress.join('\n'), role: 'assistant' as const }] : []),+ ];+};diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsindex 497b6f8874f..001686277d4 100644--- a/src/store/goal/initialState.ts+++ b/src/store/goal/initialState.ts@@ -49,6 +49,8 @@ export interface GoalState {goalMetricSeriesById: Record<string, MetricSeriesWithPoints[]>;/** Local-first bookkeeping for `goalMetricSeriesById`. */goalMetricSeriesReplica: ReplicaState<MetricSeriesWithPoints[]>;+ /** Goals whose title is being generated right now, for the header's loading state. */+ goalTitleRenamingIds: string[];goalViewMode: GoalViewMode;/*** Every agent's goals, for the home rail's cross-agent roll-up — keyed by@@ -74,6 +76,7 @@ export const initialState: GoalState = {goalListVisibleLimit: 10,goalMetricSeriesById: {},goalMetricSeriesReplica: createReplicaState(),+ goalTitleRenamingIds: [],goalViewMode: 'list',homeGoalsByScope: {},homeGoalsReplica: createReplicaState(),diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.tsindex 48d49bd9ac9..8f7fbe4356d 100644--- a/src/store/goal/selectors.ts+++ b/src/store/goal/selectors.ts@@ -10,6 +10,9 @@ const goalGraph = (goalId?: string | null) => (s: GoalStore) =>const goalMetricSeries = (goalId?: string | null) => (s: GoalStore) =>goalId ? s.goalMetricSeriesById[goalId] : undefined;+const isGoalTitleRenaming = (goalId?: string | null) => (s: GoalStore) =>+ !!goalId && s.goalTitleRenamingIds.includes(goalId);+/** One list entry by its replica key — the scope itself for `all`, a tab's own key otherwise. */const goalListView = (entryKey: string) => (s: GoalStore) => s.goalListByAgentId[entryKey];@@ -37,6 +40,7 @@ export const goalSelectors = {goalListView,goalMetricSeries,homeGoals,+ isGoalTitleRenaming,topicGoals,topicGoalsConfirmed,};