🤯 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(task): read the intent behind a task draft before creating it (#18859)
Arvin Xu5a5ddd35e634
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex 73f20773457..5acab78a77a 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -783,6 +783,30 @@ directly — strip `--> statement-breakpoint` and run it with `psql -v ON_ERROR_— and treat the collision as a local multi-worktree artifact, never as a defect ofthe branch or of canary (the numbers get rebased on merge).+**Same container, second shape — a sibling session truncates the data out from under+you.** The tables can be perfectly migrated and still hold none of your fixtures: a+worktree running the repo's DB test suites seeds and truncates `postgres` repeatedly,+so a seeded user is gone seconds after `seed-user` reports success. It surfaces as+web auth failing with `401` on `/api/auth/sign-in/email` while the seed command keeps+printing the same credentials — nothing points at the database. Confirm by listing+the table (`select id, email from users`) right after seeding and looking for rows+that are not yours (`test-user-id` and friends are another suite's fixtures).++Do NOT wait it out and do NOT reset the shared database — that destroys the other+session's run. Create your own database inside the same container and point the whole+run at it:++```bash+docker exec lobehub-agent-testing-postgres psql -U postgres -c "CREATE DATABASE <run>"+docker exec lobehub-agent-testing-postgres psql -U postgres -d "CREATE EXTENSION IF NOT EXISTS vector" < run > -c+export DATABASE_URL="postgresql://postgres:postgres@localhost:5433/<run>"+# migrate / seed-user / dev all inherit it; drop the database at teardown+```++`init-dev-env.sh` honours an inherited `DATABASE_URL` (PROJECT.md §2), so nothing else+about the run changes. Drop the database when finished and verify the shared one still+holds the other session's rows.+### L-S10 — Judging popover/menu behaviour from a Chrome MCP tab (it is hidden)**Wrong approach:** drive the debug-proxy page through the Chrome MCP tools, click a@@ -912,3 +936,88 @@ recording an unhealthy interval.timeouts, record timeout/`000` as an observation, and keep the monitor advancing.Prove recovery with a successful application request after restarting the ownedserver; neither a PID nor a listening socket is sufficient.++### L-S17 — Starting the dev server by a relative path, and getting the main checkout's SPA++**Wrong approach:** in a worktree under `.claude/worktrees/<name>/`, invoke+`.agents/acceptance/scripts/init-dev-env.sh dev` by its relative path and assume the+resulting dev server serves the worktree. Then, when the feature never fires, look for+the bug in the feature: check the lab flag, the store hydration, the click handler.++**Why it fails:** `REPO_ROOT` is derived from the invocation path+(`dirname "$0"/../../..`), and `cmd_dev` does `cd "$REPO_ROOT"` before `bun run dev`,+which spawns Vite with that inherited cwd. A worktree-isolated session's shell cwd can+silently reset to the main checkout between tool calls, so the very same relative+command starts the **main checkout's** stack instead. Nothing looks wrong: the port+answers, auth succeeds, `task.create` returns 200, the page renders the current+product. Only the code under test is absent, because the SPA is a different tree.+Fetching the module through the Next origin does not reveal it either — unknown `/src/*`+paths fall through to the SPA HTML shell, so a `grep` for your symbol "fails" against+`<!DOCTYPE html>` and reads as a stale bundle.++**Correct approach:** invoke the script by absolute path from the worktree, and before+capturing any evidence prove the SPA's identity rather than the server's liveness:+resolve the Vite pid from its port and read its cwd+(`lsof -a -p <pid> -d cwd -Fn`), then fetch the changed module **from the Vite origin+directly** (the port in the `Debug Proxy` line, not the Next port) and require a marker+unique to the change. A behavioural probe is equally decisive and cheaper: drive the+feature once and assert its server call appears in the log — an absent call with a+successful sibling call is this failure, not a client bug. Related but distinct:+\[\[L-S7]] is a stale bundle from the _right_ tree; this is a healthy bundle from the+_wrong_ tree.++### L-S18 — Calling a fix verified without reproducing the failure's precondition++**What happened.** A "draft stays in the composer after the task is created"+bug was declared fixed across four separate rounds (r5 / r7 / r8 / r9) and was+still fully present. Each verification ran against a task list that _already had+tasks in it_, and the bug only exists on the empty→non-empty transition — that+transition is what swaps the composer for a different component instance. Every+"fix" ran green on a page where the failure could not occur.++Two false root causes were shipped on the way: a stale editor handle (the handle+is `useMemo(..., [])`, it was never stale) and a Lexical update landing outside+the React event batch. Both were reasoned by analogy to other call sites rather+than measured.++**Rule.** Before verifying a fix, first reproduce the failure and write down the+precondition that makes it appear. Then verify with that precondition held. A+verification run that cannot fail proves nothing, and a green result on it is+worse than no result — it retires the bug from the todo list.++**Tell.** The bug reproduces "sometimes" or "only on the first try". That is not+flakiness; it is an unnamed precondition. Find it before touching the code.++**Tell.** The unit tests pass and the real app still breaks. Check what the test+mocks: here `cleanDocument` was `vi.fn()`, so the tests asserted the call was+made and could never observe that it landed on a dead instance. When the mocked+seam _is_ the suspect, drop the mock and drive the real thing — a 20-line probe+with the real editor kernel settled in one run what four rounds of analogy had+not.++### L-S19 — Putting your own work plan into `result.json` `plan[]`++**What happened.** A round's `plan[]` was filled with the agent's task list —+"find the root cause", "fix it and add a regression test", "record the flows" —+instead of acceptance criteria. `plan[]` is the *frozen check plan*: every item+is a check that must be executed by a case with the same `id`, and a planned+item with no case renders as **未执行** rather than vanishing. The three items+had no `id`, so the server numbered them `case-1..3` and three permanent+`not executed` gate checks appeared on the user's acceptance board — gates that+can never pass, on work that was in fact complete.++**Rule.** `plan[]` holds only what the *user* would accept or reject, each with+a stable `id` that a case in the same round fulfills. Your own steps —+investigate, fix, test, record — are not checks. If a round has one criterion,+`plan[]` has exactly one item.++**Rule.** Read the ingest summary line. `plan: N item(s) — N planned but not+executed — M unplanned case(s)` is not cosmetic: it says the plan and the+results do not line up, and the board is about to render rows nobody can clear.+A clean round prints `plan: N item(s)` with nothing after it.++**Repair.** Fold the bogus ids into the real check with+`supersedes: ['case-1', ...]` in the next round. Prefer this over+`lh acceptance run delete`: deleting the round to hide a bookkeeping error also+destroys the real results and evidence it carried, and rounds are immutable+snapshots.diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 46f1fd01808..b02e83c2b05 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -1825,6 +1825,10 @@ unrelated dirty files, while the intended worktree change stays uncommitted. Theonly tell is an unexpected diffstat / parent commit; `push <branch>` then reports"Everything up-to-date" because the worktree branch ref never moved.+The same reset has a second, harder-to-spot consequence: it also retargets+`init-dev-env.sh dev`, so the dev server and its Vite serve the MAIN checkout while+every health signal stays green — see `common-mistakes.md` L-S17.+**Works:** in any worktree session, prefix every git/check command with an explicit`cd <worktree> &&`, and read the commit output's diffstat + `git log -1` parentbefore pushing. Recovery for a mistaken main-repo commit: `git reset --mixed HEAD~1`@@ -1832,6 +1836,31 @@ restores the user's branch and leaves their working tree as it was (verify againthe session-start `gitStatus` snapshot); nothing needs force-pushing because thewrong-branch push was a no-op.+#### Proving which prompt version the running server holds++**Situation:** verifying a change to a prompt under `packages/prompts` — the assertion is+about the model's behaviour, so the run is only meaningful if the server is executing the+new prompt.++**Doesn't work:** trusting the Vite HMR line (`page reload packages/prompts/src/...`).+That is the client reloading; the Next server keeps the workspace package it started+with, so it answers with the old prompt indefinitely. Reading the model's output and+judging "this looks like the new behaviour" is circular — the whole point of the change+is that the output should differ, so any difference confirms the hypothesis either way.++**Works:** every traced generation records the version it ran. After one call, read it+back:++```bash+docker exec lobehub-agent-testing-postgres psql -U postgres -d postgres -tAc \+ "select prompt_version, model, created_at from llm_generation_tracing \+ where scenario='<scenario>' order by created_at desc limit 1"+```++A stale version means the server needs a real process restart (PROJECT.md §6), not a+reload. Gate the first evidence-bearing call on this row, not on the edit's timestamp —+otherwise the round publishes new-prompt claims backed by old-prompt output.+#### Server-side reads of local S3 evidence are blocked by SSRF protection — private IPs must be allowed explicitly**Situation:** verifying any capability where the **server** reads back an uploadeddiff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 60b23fb2fd3..4d21139ae8a 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1,4 +1,5 @@import { TASK_STATUSES } from '@lobechat/builtin-tool-task';+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import type { TaskListItem, TaskParticipant, TaskVerifyConfig } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -15,9 +16,11 @@ import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';import { EditLockService } from '@/server/services/editLock';import { publishResourceEvent } from '@/server/services/resourceEvents';import { TaskService } from '@/server/services/task';+import { TaskIntentService } from '@/server/services/task/intent';import { TaskLifecycleService } from '@/server/services/taskLifecycle';import { TaskRunnerService } from '@/server/services/taskRunner';import { AcceptanceService } from '@/server/services/verify/acceptanceService';@@ -37,6 +40,7 @@ const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>editLockService: new EditLockService(ctx.userId),taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId),taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),+ taskIntentService: new TaskIntentService(ctx.serverDB, ctx.userId, wsId),taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),taskTopicModel: new TaskTopicModel(ctx.serverDB, ctx.userId, wsId),topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),@@ -230,6 +234,72 @@ async function resolveSafeParentTaskId(}export const taskRouter = router({+ /**+ * Read a composer draft and report what it means — a name, the outcome as+ * understood, the questions that would change the deliverable, and whether+ * it is really a standing goal. Returns a reading only; nothing is created.+ */+ analyzeIntent: taskProcedureWrite+ .input(+ z.object({+ context: z.string().optional(),+ instruction: z.string().min(1).max(20_000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.taskIntentService.analyze(input);+ } catch (error) {+ const errorType = (error as { errorType?: unknown } | null)?.errorType;+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ const trpcError = new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ // Runtime errors are plain payloads, so tRPC normalizes them into an+ // Error cause; mark the cause the shared handler actually receives.+ markSilentTRPCErrorLog(trpcError.cause);+ throw trpcError;+ }++ throw error;+ }+ }),++ /**+ * Rewrite a confirmed draft into the brief that gets executed, folding in the+ * answers the user just gave. Returns a brief only; nothing is created.+ */+ synthesizeInstruction: taskProcedureWrite+ .input(+ z.object({+ answers: z+ .array(z.object({ answer: z.string().min(1), question: z.string().min(1) }))+ .max(3),+ context: z.string().optional(),+ instruction: z.string().min(1).max(20_000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.taskIntentService.synthesize(input);+ } catch (error) {+ const errorType = (error as { errorType?: unknown } | null)?.errorType;+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ const trpcError = new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ markSilentTRPCErrorLog(trpcError.cause);+ throw trpcError;+ }++ throw error;+ }+ }),+reorderSubtasks: taskProcedureWrite.input(z.object({diff --git a/apps/server/src/services/task/intent.test.ts b/apps/server/src/services/task/intent.test.tsnew file mode 100644index 00000000000..d52d8bf0db5--- /dev/null+++ b/apps/server/src/services/task/intent.test.ts@@ -0,0 +1,149 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { normalizeIntent, normalizeSynthesis, TaskIntentService } from './intent';++const { generateObject, resolveGoalModelConfig } = vi.hoisted(() => ({+ generateObject: vi.fn(),+ resolveGoalModelConfig: vi.fn(),+}));++vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: vi.fn(() => ({ generateObject })),+}));++vi.mock('@/server/services/goal/modelConfig', () => ({ resolveGoalModelConfig }));++const wellFormed = {+ clarifications: [],+ confidence: 'high',+ kind: 'task',+ kindReason: 'A single deliverable.',+ refinedInstruction: 'Fix the typo in the README title.',+ summary: 'You want the README typo fixed.',+ title: 'Fix README typo',+};++describe('TaskIntentService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolveGoalModelConfig.mockResolvedValue({ model: 'mini', provider: 'openai' });+ generateObject.mockResolvedValue(wellFormed);+ });++ it('reads the draft with the task-intent prompt, schema, and tracing scenario', async () => {+ const result = await new TaskIntentService({} as any, 'user-1', 'workspace-1').analyze({+ context: 'Assigned agent: Docs Bot',+ instruction: 'fix the readme typo',+ });++ expect(generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'mini',+ provider: 'openai',+ schema: expect.objectContaining({ name: 'task_intent' }),+ }),+ expect.objectContaining({+ tracing: {+ promptVersion: 'v1',+ scenario: 'task_intent',+ schemaName: 'task_intent',+ },+ }),+ );+ expect(result.title).toBe('Fix README typo');+ });++ it('rejects a malformed reading rather than returning a half-filled one', async () => {+ generateObject.mockResolvedValue({ title: 'Fix README typo' });++ await expect(+ new TaskIntentService({} as any, 'user-1').analyze({ instruction: 'fix the readme typo' }),+ ).rejects.toThrow('did not match the expected shape');+ });+});++describe('normalizeIntent', () => {+ it('drops a high-confidence claim that comes with a question', () => {+ const result = normalizeIntent(+ {+ ...wellFormed,+ clarifications: [{ question: 'Which repo?' }],+ confidence: 'high',+ } as any,+ 'fix the readme typo',+ );++ // Left as 'high', the composer's gate would create the task straight+ // through and silently discard the question the model just raised.+ expect(result.confidence).toBe('medium');+ expect(result.clarifications).toHaveLength(1);+ });++ it('keeps at most three questions and discards blank ones', () => {+ const result = normalizeIntent(+ {+ ...wellFormed,+ clarifications: [+ { question: ' Which repo? ', options: [' a ', '', 'b'] },+ { question: 'By when?' },+ { question: ' ' },+ { question: 'Who reviews?' },+ { question: 'Which branch?' },+ ],+ } as any,+ 'fix the readme typo',+ );++ expect(result.clarifications.map((item) => item.question)).toEqual([+ 'Which repo?',+ 'By when?',+ 'Who reviews?',+ ]);+ expect(result.clarifications[0].options).toEqual(['a', 'b']);+ });++ it('falls back to the user text when the model returns a blank brief', () => {+ const result = normalizeIntent(+ { ...wellFormed, refinedInstruction: ' ' } as any,+ 'fix the readme typo',+ );++ expect(result.refinedInstruction).toBe('fix the readme typo');+ });+});++describe('normalizeSynthesis', () => {+ it('keeps a rewrite that carried every literal through', () => {+ const result = normalizeSynthesis(+ {+ instruction:+ '把 https://example.com/spec 整理成 API 表格,交付格式为 PDF,覆盖全部 12 个接口。',+ title: '整理 API 表格',+ },+ '把 https://example.com/spec 整理成表格,一共 12 个接口',+ );++ expect(result.instruction).toContain('https://example.com/spec');+ expect(result.title).toBe('整理 API 表格');+ });++ it('rejects a rewrite that dropped a URL the draft carried', () => {+ // The executor would be left acting on a brief missing the only concrete+ // thing it was given, which is worse than not rewriting at all.+ expect(() =>+ normalizeSynthesis(+ { instruction: '把那篇文档整理成 API 表格。', title: '整理 API 表格' },+ '把 https://example.com/spec 整理成表格',+ ),+ ).toThrow(/dropped literals/);+ });++ it('rejects a rewrite that dropped a number the draft carried', () => {+ expect(() =>+ normalizeSynthesis(+ { instruction: '把接口整理成表格。', title: '整理表格' },+ '把 12 个接口整理成表格',+ ),+ ).toThrow(/dropped literals/);+ });+});diff --git a/apps/server/src/services/task/intent.ts b/apps/server/src/services/task/intent.tsnew file mode 100644index 00000000000..3fc39b6b0a4--- /dev/null+++ b/apps/server/src/services/task/intent.ts@@ -0,0 +1,209 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import {+ chainTaskInstruction,+ chainTaskIntent,+ TASK_INSTRUCTION_JSON_SCHEMA,+ TASK_INSTRUCTION_PROMPT_VERSION,+ TASK_INTENT_JSON_SCHEMA,+ TASK_INTENT_PROMPT_VERSION,+} from '@lobechat/prompts';+import type { TaskInstructionSynthesis, TaskIntentAnalysis } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';+import { resolveGoalModelConfig } from '@/server/services/goal/modelConfig';++const log = debug('lobe-server:task-intent');++const MAX_CLARIFICATIONS = 3;++const analysisSchema = z.object({+ clarifications: z+ .array(+ z.object({+ impact: z.string().optional(),+ options: z.array(z.string()).optional(),+ question: z.string().min(1),+ }),+ )+ .optional(),+ confidence: z.enum(['high', 'medium', 'low']).optional(),+ kind: z.enum(['task', 'goal']).optional(),+ kindReason: z.string().optional(),+ refinedInstruction: z.string().min(1),+ summary: z.string().min(1),+ title: z.string().min(1),+});++const synthesisSchema = z.object({+ instruction: z.string().min(1),+ title: z.string().min(1),+});++/**+ * Read the raw text typed into the task composer and report what it means.+ *+ * The surface used to derive a task name by truncating the first line at 30+ * characters and hand the text straight to an agent, so a request that was+ * missing the one detail that decides the deliverable only surfaced as a wrong+ * result an autonomous run later. This service is the step in between: it+ * names the task, restates the outcome for the user to check, flags the+ * questions whose answers change the work, and says whether the request is+ * really a standing goal rather than a single task.+ *+ * It answers only — the caller decides whether to create straight through or+ * stop for confirmation, and nothing here writes to the database.+ */+export class TaskIntentService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ async analyze(params: { context?: string; instruction: string }): Promise<TaskIntentAnalysis> {+ // Intent reading is the same "structure the user's request" model role as+ // goal criteria drafting, so it rides that assignment rather than adding a+ // configurable model slot for a feature still behind a lab toggle.+ const modelConfig = await resolveGoalModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);++ const raw = await ai.generateObject(+ {+ ...chainTaskIntent(params),+ ...modelConfig,+ schema: TASK_INTENT_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ {+ metadata: { trigger: 'task_intent' },+ tracing: {+ promptVersion: TASK_INTENT_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TaskIntent,+ schemaName: TASK_INTENT_JSON_SCHEMA.name,+ } satisfies TracingOptions,+ },+ );++ const parsed = analysisSchema.safeParse(raw);+ if (!parsed.success) {+ log('task intent did not match schema: %O', parsed.error.flatten());+ throw new Error('Task intent analysis did not match the expected shape.');+ }++ return normalizeIntent(parsed.data, params.instruction);+ }++ /**+ * Rewrite the confirmed draft into the brief that actually gets executed.+ *+ * `analyze` runs before the user answers, so its brief still names the+ * answered details as open. Appending the answers under it produces a+ * document that contradicts itself — the body calls a detail missing while+ * the appendix states it. This pass folds them in instead.+ */+ async synthesize(params: {+ answers: { answer: string; question: string }[];+ context?: string;+ instruction: string;+ }): Promise<TaskInstructionSynthesis> {+ const modelConfig = await resolveGoalModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);++ const raw = await ai.generateObject(+ {+ ...chainTaskInstruction(params),+ ...modelConfig,+ schema: TASK_INSTRUCTION_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ {+ metadata: { trigger: 'task_instruction' },+ tracing: {+ promptVersion: TASK_INSTRUCTION_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TaskInstruction,+ schemaName: TASK_INSTRUCTION_JSON_SCHEMA.name,+ } satisfies TracingOptions,+ },+ );++ const parsed = synthesisSchema.safeParse(raw);+ if (!parsed.success) {+ log('task instruction did not match schema: %O', parsed.error.flatten());+ throw new Error('Task instruction synthesis did not match the expected shape.');+ }++ return normalizeSynthesis(parsed.data, params.instruction);+ }+}++/**+ * Guard the one thing a rewrite must never do: lose what the user wrote.+ *+ * A brief that dropped a URL, a path or a number the draft carried is worse+ * than no rewrite at all — the executor would act on an instruction missing+ * the only concrete thing it was given. Exported for tests.+ */+export const normalizeSynthesis = (+ raw: z.infer<typeof synthesisSchema>,+ instruction: string,+): TaskInstructionSynthesis => {+ const written = raw.instruction.trim();+ const dropped = literalTokens(instruction).filter((token) => !written.includes(token));++ if (dropped.length > 0) {+ log('synthesis dropped literals from the draft: %O', dropped);+ // Keep the user's own text as the brief rather than shipping a lossy+ // rewrite; the caller's fallback path handles the rest.+ throw new Error('Task instruction synthesis dropped literals from the draft.');+ }++ return { instruction: written, title: raw.title.trim() };+};++/** URLs, paths and bare numbers — the parts a rewrite is not allowed to drop. */+const literalTokens = (text: string): string[] => [+ ...new Set([+ ...(text.match(/https?:\/\/\S+/g) ?? []),+ ...(text.match(/(?:^|\s)(\/[\w./-]+)/g) ?? []).map((token) => token.trim()),+ ...(text.match(/\b\d[\d.,]*\b/g) ?? []),+ ]),+];++type RawIntent = z.infer<typeof analysisSchema>;++/**+ * Bring a well-formed but over-eager answer back to something the composer can+ * act on. Exported for tests: the gate that decides whether the user is+ * interrupted reads `confidence` and `clarifications`, so the two must not be+ * allowed to contradict each other.+ */+export const normalizeIntent = (raw: RawIntent, instruction: string): TaskIntentAnalysis => {+ const clarifications = (raw.clarifications ?? [])+ .filter((item) => item.question.trim())+ .slice(0, MAX_CLARIFICATIONS)+ .map((item) => ({+ impact: item.impact?.trim() || undefined,+ options: item.options?.map((option) => option.trim()).filter(Boolean),+ question: item.question.trim(),+ }));++ // A model that asks a question has, by its own account, found something it+ // could not determine. Letting it also claim high confidence would send the+ // request straight through and drop the question on the floor.+ const claimed = raw.confidence ?? 'medium';+ const confidence = clarifications.length > 0 && claimed === 'high' ? 'medium' : claimed;++ return {+ clarifications,+ confidence,+ kind: raw.kind ?? 'task',+ kindReason: raw.kindReason?.trim() || undefined,+ refinedInstruction: raw.refinedInstruction.trim() || instruction,+ summary: raw.summary.trim(),+ title: raw.title.trim(),+ };+};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 2e725aaa1a3..9a14f5e3eae 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1652,6 +1652,20 @@"taskDetail.topicSource": "From {{identifier}}","taskDetail.untitled": "Untitled","taskDetail.updateFailed": "Failed to update task",+ "taskIntent.analyzing": "Reading…",+ "taskIntent.answerPlaceholder": "Answer, or leave blank to skip",+ "taskIntent.answersHeading": "Clarifications",+ "taskIntent.back": "Edit draft",+ "taskIntent.create": "Create",+ "taskIntent.createDirectly": "Create without reading the draft",+ "taskIntent.created": "Task created",+ "taskIntent.goalCallout.action": "Create a goal",+ "taskIntent.goalCallout.desc": "A goal keeps working against a standing acceptance bar across multiple rounds.",+ "taskIntent.goalCallout.title": "This reads like an ongoing goal",+ "taskIntent.moreCreateOptions": "More create options",+ "taskIntent.next": "Next",+ "taskIntent.openCreated": "Open",+ "taskIntent.reviewStep": "Confirm what I understood","taskList.activeTasks": "Active Tasks","taskList.all": "All tasks","taskList.assignTo": "Assign to",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex a06a4a9f80f..3ff193b9997 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1652,6 +1652,20 @@"taskDetail.topicSource": "来自 {{identifier}}","taskDetail.untitled": "无标题","taskDetail.updateFailed": "任务更新失败",+ "taskIntent.analyzing": "正在理解…",+ "taskIntent.answerPlaceholder": "回答,或留空跳过",+ "taskIntent.answersHeading": "补充说明",+ "taskIntent.back": "返回修改",+ "taskIntent.create": "创建",+ "taskIntent.createDirectly": "直接创建,跳过理解",+ "taskIntent.created": "任务已创建",+ "taskIntent.goalCallout.action": "改为创建目标",+ "taskIntent.goalCallout.desc": "目标会按既定的验收标准持续推进多轮。",+ "taskIntent.goalCallout.title": "这更像一个持续的目标",+ "taskIntent.moreCreateOptions": "更多创建方式",+ "taskIntent.next": "下一步",+ "taskIntent.openCreated": "打开",+ "taskIntent.reviewStep": "先确认一下我的理解","taskList.activeTasks": "进行中的任务","taskList.all": "全部任务","taskList.assignTo": "指派给",diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 3921fa26c10..be25ba4e542 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -28,6 +28,8 @@ export const TRACING_SCENARIOS = {TaskBrief: 'task_brief',TaskBriefJudge: 'task_brief_judge',TaskHandoff: 'task_handoff',+ TaskInstruction: 'task_instruction',+ TaskIntent: 'task_intent',TopicTitle: 'topic_title',TopicAutoSummary: 'topic_auto_summary',UnderstandingAnalysis: 'understanding_analysis',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 720fa252f26..9a3335272f0 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1709,6 +1709,21 @@ export default {'createTask.visibility.privateAgentLocked': 'Private agents can only run private tasks.','createTask.visibility.private': 'Private','createTask.visibility.workspace': 'Workspace',+ 'taskIntent.analyzing': 'Reading…',+ 'taskIntent.answerPlaceholder': 'Answer, or leave blank to skip',+ 'taskIntent.answersHeading': 'Clarifications',+ 'taskIntent.back': 'Edit draft',+ 'taskIntent.created': 'Task created',+ 'taskIntent.openCreated': 'Open',+ 'taskIntent.next': 'Next',+ 'taskIntent.createDirectly': 'Create without reading the draft',+ 'taskIntent.moreCreateOptions': 'More create options',+ 'taskIntent.create': 'Create',+ 'taskIntent.goalCallout.action': 'Create a goal',+ 'taskIntent.goalCallout.desc':+ 'A goal keeps working against a standing acceptance bar across multiple rounds.',+ 'taskIntent.goalCallout.title': 'This reads like an ongoing goal',+ 'taskIntent.reviewStep': 'Confirm what I understood','goalEmpty.create': 'Create your first goal','goalEmpty.examples.backlog.requirement':'Tag each item with a type and priority, dedupe into one table, and list the 10 most frequent issues.',diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex 32a6b6d0b68..82b486158d8 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -20,6 +20,8 @@ export * from './summaryGenerationTitle';export * from './summaryHistory';export * from './summaryTags';export * from './summaryTitle';+export * from './taskInstruction';+export * from './taskIntent';export * from './taskTopicHandoff';export * from './topicAutoSummary';export * from './translate';diff --git a/packages/prompts/src/chains/taskInstruction.test.ts b/packages/prompts/src/chains/taskInstruction.test.tsnew file mode 100644index 00000000000..2788b6af8b1--- /dev/null+++ b/packages/prompts/src/chains/taskInstruction.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';++import {+ chainTaskInstruction,+ TASK_INSTRUCTION_JSON_SCHEMA,+ TASK_INSTRUCTION_PROMPT_VERSION,+} from './taskInstruction';++describe('chainTaskInstruction', () => {+ it('owns a dedicated version and a schema that always answers both fields', () => {+ expect(TASK_INSTRUCTION_PROMPT_VERSION).toBe('v1');+ expect(TASK_INSTRUCTION_JSON_SCHEMA.name).toBe('task_instruction');+ expect(TASK_INSTRUCTION_JSON_SCHEMA.schema.required).toEqual(['instruction', 'title']);+ });++ it('forbids the appendix that made the first pass contradict itself', () => {+ const system = chainTaskInstruction({+ answers: [{ answer: 'PDF', question: 'Which format?' }],+ instruction: 'Compare last quarter by month',+ }).messages[0].content;++ expect(system).toContain('Fold every answer into the brief as a settled fact');+ expect(system).toContain('Never append a question-and-answer list');+ expect(system).toContain('missing, pending, or to be confirmed');+ });++ it('holds the rewrite to the request: nothing invented, nothing dropped', () => {+ const system = chainTaskInstruction({+ answers: [],+ instruction: 'Summarize https://example.com/spec',+ }).messages[0].content;++ expect(system).toContain('Preserve every URL, identifier, file path, number');+ expect(system).toContain('Completeness is about making the request fully actionable');+ expect(system).toContain('no invented deliverables, scope, quality bars, deadlines, or tools');+ // A skipped question is the user declining to narrow scope, not an+ // invitation to guess on their behalf.+ expect(system).toContain('A question the user skipped stays genuinely open');+ });++ it('asks for the whole working brief, not a one-line restatement', () => {+ // The executor reads this text and nothing else, so a single sentence+ // silently drops the inputs and constraints the answers established.+ const system = chainTaskInstruction({+ answers: [{ answer: 'Excel', question: 'Which format?' }],+ instruction: 'Compare last quarter by month',+ }).messages[0].content;++ expect(system).toContain('This brief is the whole handover');+ expect(system).toContain('not a one-line restatement of the request');+ expect(system).toContain('a complete brief in markdown');+ expect(system).toContain('an opening paragraph stating the outcome');+ // Completeness invites padding: an audience or business goal nobody stated+ // reads as a requirement to the executor.+ expect(system).toContain('Do not name an audience, a purpose or a business goal');+ expect(system).toContain('a requirements section under a markdown heading');+ // Open points are latitude, not a blocker that stalls the run.+ expect(system).toContain('in the wording of latitude rather than of a blocker');+ });++ it('passes the answers through as pairs, and omits the block when there are none', () => {+ const withAnswers = chainTaskInstruction({+ answers: [{ answer: 'PDF', question: 'Which format?' }],+ context: 'Assigned agent: Docs Bot',+ instruction: 'Compare last quarter by month',+ });+ expect(withAnswers.messages[1].content).toContain('- Which format? → PDF');+ expect(withAnswers.messages[1].content).toContain('## Context\nAssigned agent: Docs Bot');++ const none = chainTaskInstruction({ answers: [], instruction: 'Compare last quarter' });+ expect(none.messages[1].content).not.toContain('## Answers');+ });+});diff --git a/packages/prompts/src/chains/taskInstruction.ts b/packages/prompts/src/chains/taskInstruction.tsnew file mode 100644index 00000000000..8f30950da0f--- /dev/null+++ b/packages/prompts/src/chains/taskInstruction.ts@@ -0,0 +1,89 @@+import type { OpenAIChatMessage } from '@lobechat/types';++/** Bump when the confirmed-instruction synthesis prompt meaningfully changes. */+export const TASK_INSTRUCTION_PROMPT_VERSION = 'v1';++export const TASK_INSTRUCTION_JSON_SCHEMA = {+ name: 'task_instruction',+ schema: {+ additionalProperties: false,+ properties: {+ instruction: { minLength: 1, type: 'string' },+ title: { maxLength: 80, minLength: 1, type: 'string' },+ },+ required: ['instruction', 'title'],+ type: 'object' as const,+ },+ strict: true,+};++interface TaskInstructionInput {+ /** Question/answer pairs the user settled on the review step. */+ answers: { answer: string; question: string }[];+ /** Free-form surrounding context: the agent it is assigned to, the project. */+ context?: string;+ /** The draft exactly as the user typed it. */+ instruction: string;+}++/**+ * Rewrite a confirmed draft into the single brief an executor will actually run.+ *+ * The reading that produced the questions was written *before* the user+ * answered them, so it still names those gaps as open ("pending the delivery+ * format…"). Concatenating the answers underneath it leaves a brief that+ * contradicts itself — the body says a detail is missing while an appendix+ * below states it. This pass exists to resolve that: the answers are settled+ * facts now, and the brief has to read as though they always were.+ *+ * It is also the whole handover: the executor sees this text and nothing else,+ * so the brief has to carry the deliverable, the inputs, and every settled+ * constraint rather than restate the request in a sentence.+ *+ * It rewrites, so the hard limit is that it may not invent. Every URL,+ * identifier, path, number and named constraint has to survive verbatim, and+ * nothing the user did not ask for may appear — completeness means making the+ * request actionable, never adding to it.+ */+export const chainTaskInstruction = ({+ answers,+ context,+ instruction,+}: TaskInstructionInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ {+ content: [+ 'You write the final brief for an autonomous executor, from a task request and the answers the user just gave to your clarifying questions.',+ '',+ 'This brief is the whole handover. The executor never sees the request, the questions, or this conversation — it sees only what you write, so anything it needs that is missing here is simply lost. Write the full working brief, not a one-line restatement of the request.',+ '',+ 'Return:',+ '- instruction: a complete brief in markdown, structured as:',+ ' 1. an opening paragraph stating the outcome — what is being produced and from what. Do not name an audience, a purpose or a business goal the user did not state;',+ " 2. a requirements section under a markdown heading, its title written in the user's language, listing every settled requirement as its own bullet: the deliverable and its format, the sources or inputs to work from, the dimensions or metrics to cover, and every constraint the user stated or answered;",+ ' 3. a closing note naming what is deliberately left to the executor, phrased as latitude — only when the user actually left something open.',+ '- title: a short, specific task name in the imperative, consistent with the brief.',+ '',+ 'Rules:',+ '- Fold every answer into the brief as a settled fact. Never append a question-and-answer list, never restate a question, and never describe anything the user answered as missing, pending, or to be confirmed.',+ '- Preserve every URL, identifier, file path, number, threshold, and named constraint from the request exactly as written.',+ '- Completeness is about making the request fully actionable, never about adding to it. Every requirement you list must trace to something the user wrote or answered — no invented deliverables, scope, quality bars, deadlines, or tools.',+ '- A question the user skipped stays genuinely open: name it as the executor\'s call, in the wording of latitude rather than of a blocker — "decide this yourself based on what you find", never "pending X before starting". Never answer it on the user\'s behalf.',+ '- Write it in the language the user wrote in.',+ ].join('\n'),+ role: 'system',+ },+ {+ content: [+ `## Request\n${instruction}`,+ answers.length > 0+ ? `\n## Answers\n${answers.map(({ answer, question }) => `- ${question} → ${answer}`).join('\n')}`+ : '',+ context ? `\n## Context\n${context}` : '',+ ]+ .filter(Boolean)+ .join('\n'),+ role: 'user',+ },+ ],+});diff --git a/packages/prompts/src/chains/taskIntent.test.ts b/packages/prompts/src/chains/taskIntent.test.tsnew file mode 100644index 00000000000..514e4408fd2--- /dev/null+++ b/packages/prompts/src/chains/taskIntent.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';++import { chainTaskIntent, TASK_INTENT_JSON_SCHEMA, TASK_INTENT_PROMPT_VERSION } from './taskIntent';++describe('chainTaskIntent', () => {+ it('owns a dedicated version and a schema that always answers every field', () => {+ expect(TASK_INTENT_PROMPT_VERSION).toBe('v1');+ expect(TASK_INTENT_JSON_SCHEMA.name).toBe('task_intent');+ // `strict` output drops any field left out of `required`, and the composer+ // reads all of them to decide whether to interrupt the user.+ expect(TASK_INTENT_JSON_SCHEMA.schema.required).toEqual([+ 'title',+ 'summary',+ 'refinedInstruction',+ 'kind',+ 'kindReason',+ 'confidence',+ 'clarifications',+ ]);+ expect(TASK_INTENT_JSON_SCHEMA.schema.properties.clarifications.maxItems).toBe(3);+ });++ it('tells the model that asking nothing is the expected outcome', () => {+ const system = chainTaskIntent({ instruction: 'Fix the typo in the README' }).messages[0]+ .content;++ expect(system).toContain('Zero questions is the expected outcome');+ expect(system).toContain('confidence "high" must come with an empty list');+ expect(system).toContain('materially different deliverables');+ expect(system).toContain('Never add scope');+ expect(system).toContain('When in doubt, "task"');+ });++ it('blocks the failure modes a real batch exposed', () => {+ const system = chainTaskIntent({ instruction: '优化一下首页' }).messages[0].content;++ // Silence on a request that names an intent but no deliverable: an early+ // draft of this prompt rated "优化一下首页" high-confidence with zero+ // questions and sent it straight to an agent.+ expect(system).toContain('a vague request is NOT an actionable one');+ expect(system).toContain('name the deliverable you would hand back');+ // Asking the user to make the executor's own build decisions.+ expect(system).toContain('it picks the how, the user owns the what');+ // A German title for an English draft; kindReason in English for a Chinese one.+ expect(system).toContain('A single field in another language is a defect');+ });++ it('passes the request through verbatim and appends context only when given', () => {+ const withContext = chainTaskIntent({+ context: 'Assigned agent: Docs Bot',+ instruction: 'Summarize https://example.com/spec into a table',+ });+ expect(withContext.messages[1].content).toContain('Summarize https://example.com/spec');+ expect(withContext.messages[1].content).toContain('## Context\nAssigned agent: Docs Bot');++ const withoutContext = chainTaskIntent({ instruction: 'Summarize the spec' });+ expect(withoutContext.messages[1].content).not.toContain('## Context');+ });+});diff --git a/packages/prompts/src/chains/taskIntent.ts b/packages/prompts/src/chains/taskIntent.tsnew file mode 100644index 00000000000..b7acec7047b--- /dev/null+++ b/packages/prompts/src/chains/taskIntent.ts@@ -0,0 +1,109 @@+import type { OpenAIChatMessage } from '@lobechat/types';++/** Bump when the create-task intent recognition prompt meaningfully changes. */+export const TASK_INTENT_PROMPT_VERSION = 'v1';++/** How the user's request is best carried out. */+export const TASK_INTENT_KINDS = ['task', 'goal'] as const;++/** How sure the model is that it can hand the brief to an executor as-is. */+export const TASK_INTENT_CONFIDENCES = ['high', 'medium', 'low'] as const;++export const TASK_INTENT_JSON_SCHEMA = {+ name: 'task_intent',+ schema: {+ additionalProperties: false,+ properties: {+ clarifications: {+ items: {+ additionalProperties: false,+ properties: {+ /** Why the answer changes the work — shown under the question. */+ impact: { maxLength: 160, type: 'string' },+ /** Plausible answers offered as one-tap chips. May be empty. */+ options: { items: { maxLength: 60, type: 'string' }, maxItems: 4, type: 'array' },+ question: { maxLength: 120, minLength: 1, type: 'string' },+ },+ required: ['question', 'impact', 'options'],+ type: 'object',+ },+ maxItems: 3,+ type: 'array',+ },+ confidence: { enum: [...TASK_INTENT_CONFIDENCES], type: 'string' },+ kind: { enum: [...TASK_INTENT_KINDS], type: 'string' },+ kindReason: { maxLength: 160, type: 'string' },+ refinedInstruction: { minLength: 1, type: 'string' },+ summary: { maxLength: 200, minLength: 1, type: 'string' },+ title: { maxLength: 80, minLength: 1, type: 'string' },+ },+ required: [+ 'title',+ 'summary',+ 'refinedInstruction',+ 'kind',+ 'kindReason',+ 'confidence',+ 'clarifications',+ ],+ type: 'object' as const,+ },+ strict: true,+};++interface TaskIntentInput {+ /** Free-form surrounding context: the agent it is assigned to, the project. */+ context?: string;+ /** Raw text the user typed into the task composer. */+ instruction: string;+}++/**+ * Read what the user typed into the task composer and report what they meant.+ *+ * The caller decides what to do with the answer: a confident, unambiguous+ * reading is created straight through with a better title, and anything else+ * stops for the user to confirm. So the prompt's job is to be *honest* about+ * ambiguity rather than agreeable — an invented assumption costs a whole+ * wasted autonomous run, while an unnecessary question costs one click.+ */+export const chainTaskIntent = ({+ context,+ instruction,+}: TaskIntentInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ {+ content: [+ 'You read a task request a user just typed into a task composer and report what they actually want, before any agent starts working on it.',+ '',+ 'Return:',+ '- title: a short, specific task name in the imperative. Never a truncation of the request, never a restatement of the whole sentence.',+ '- summary: one sentence, addressed to the user, stating the outcome you understood they want. This is what they check before approving.',+ '- refinedInstruction: the request rewritten as a complete brief for an autonomous executor. Preserve every URL, identifier, file path, number, threshold, and named constraint from the original exactly. Never add scope, deliverables, or quality bars the user did not ask for.',+ '- kind: "goal" when the request is a standing outcome pursued over many autonomous rounds against a durable acceptance bar (keep something at a level, drive a metric, iterate until reviewed and accepted). "task" when a single execution can deliver it. When in doubt, "task" — a goal commits the user to a budget of autonomous rounds.',+ "- kindReason: one sentence justifying the kind, in the user's language.",+ '- confidence: "high" ONLY when the request already names a concrete deliverable AND a concrete target to act on. A short request that names an intent without a deliverable ("improve the homepage", "clean up the feedback", "make it faster") is never high — you cannot tell what would be handed back.',+ '- confidence: "medium" when the deliverable or the target is implied but recoverable from the wording; "low" when the request could reasonably produce materially different deliverables.',+ '- clarifications: the questions whose answers change what gets delivered.',+ '',+ 'Rules for clarifications:',+ '- Ask nothing when the request is already actionable. Zero questions is the expected outcome for a well-written request, and confidence "high" must come with an empty list.',+ '- But a vague request is NOT an actionable one. Before deciding to ask nothing, name the deliverable you would hand back and the exact thing you would act on. If you cannot name both from the request itself, you must ask — silence on a request like "improve the homepage" or "organize the feedback" sends an agent off to produce something the user never asked for.',+ '- At most 3, ordered by how much the answer changes the work.',+ '- Only ask when different answers lead to materially different deliverables. Never ask about implementation choices the executor should make ("which library", "which approach", "how should it be built"), about preferences that do not change the outcome, or about anything already stated in the request. The executor is a capable engineer: it picks the how, the user owns the what.',+ '- Never ask the user to restate their request or to "provide more detail" in general.',+ '- impact states what changes depending on the answer, concretely.',+ '- options lists plausible concrete answers when they are enumerable, so the user can answer with one tap. Use [] when the answer is open-ended.',+ '',+ 'Write EVERY human-facing field — title, summary, kindReason, and every question, impact, and option — in the language the user wrote in. A single field in another language is a defect.',+ ].join('\n'),+ role: 'system',+ },+ {+ content: [`## Request\n${instruction}`, context ? `\n## Context\n${context}` : '']+ .filter(Boolean)+ .join('\n'),+ role: 'user',+ },+ ],+});diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 6b1de7dd274..b2a139112d5 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -28,6 +28,47 @@ export type TaskAutomationMode = 'heartbeat' | 'schedule';*/export type TaskRunTrigger = 'manual' | 'schedule' | 'heartbeat' | 'goal';+/**+ * A clarifying question the intent reader wants answered before an agent+ * starts. Only raised when different answers change what gets delivered.+ */+export interface TaskIntentClarification {+ /** What concretely changes depending on the answer. */+ impact?: string;+ /** Enumerable candidate answers, offered as one-tap chips. */+ options?: string[];+ question: string;+}++/**+ * What the intent reader understood from the raw text typed into the task+ * composer. Purely advisory — nothing here is persisted until the user (or the+ * auto path, for an unambiguous request) confirms it.+ */+export interface TaskIntentAnalysis {+ clarifications: TaskIntentClarification[];+ /** How sure the reader is the brief can go to an executor as-is. */+ confidence: 'high' | 'medium' | 'low';+ /** Whether this is a single delivery or a standing goal. */+ kind: 'task' | 'goal';+ kindReason?: string;+ /** The request rewritten as a full brief, without added scope. */+ refinedInstruction: string;+ /** One sentence, addressed to the user: the outcome that was understood. */+ summary: string;+ title: string;+}++/**+ * The brief produced after the user answers, replacing the pre-answer reading.+ * A second pass is needed because the first one was written while those details+ * were still open, so it names them as gaps the answers have since closed.+ */+export interface TaskInstructionSynthesis {+ instruction: string;+ title: string;+}+// ── Config types ──export interface CheckpointConfig {diff --git a/src/components/GeneratingBorder/index.tsx b/src/components/GeneratingBorder/index.tsxnew file mode 100644index 00000000000..e5f97679489--- /dev/null+++ b/src/components/GeneratingBorder/index.tsx@@ -0,0 +1,114 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { createGlobalStyle, createStaticStyles, cssVar } from 'antd-style';+import { memo, type ReactNode } from 'react';++/**+ * `@property` is what makes the angle animatable — a plain custom property is+ * an unregistered token and jumps from 0deg to 360deg instead of sweeping.+ * Declared once here rather than per call site.+ */+const BorderAngleProperty = createGlobalStyle`+ @property --lobe-generating-border-angle {+ inherits: false;+ initial-value: 0deg;+ syntax: '<angle>';+ }+`;++const styles = createStaticStyles(({ css }) => ({+ shell: css`+ position: relative;+ border-radius: 8px;+ `,+ // `overflow: hidden` belongs to the generating state only: on the resting+ // shell it clips the wrapped input's own focus glow while the user types.+ shellGenerating: css`+ overflow: hidden;++ &::after {+ pointer-events: none;+ content: '';++ position: absolute;+ z-index: 1;+ inset: 0;++ padding: 2px;+ border-radius: inherit;++ background: conic-gradient(+ from var(--lobe-generating-border-angle),+ ${cssVar.colorBorderSecondary} 0deg 210deg,+ #ff3d8d 238deg,+ #8b5cf6 258deg,+ #00c8ff 278deg,+ #22e6a8 298deg,+ #ffd43b 318deg,+ #ff6b35 338deg,+ ${cssVar.colorBorderSecondary} 360deg+ );++ /* Masks the gradient down to the 2px padding ring, so only the edge lights up. */+ mask:+ linear-gradient(#fff 0 0) content-box,+ linear-gradient(#fff 0 0);++ animation: lobe-generating-border-flow 1.8s linear infinite;++ mask-composite: exclude;+ }++ @keyframes lobe-generating-border-flow {+ from {+ --lobe-generating-border-angle: 0deg;+ }++ to {+ --lobe-generating-border-angle: 360deg;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ &::after {+ animation: none;+ }+ }+ `,+}));++export interface GeneratingBorderProps {+ children?: ReactNode;+ className?: string;+ /** Lights the ring. Resting state renders the children untouched. */+ generating?: boolean;+ style?: React.CSSProperties;+}++/**+ * The flowing rainbow ring that marks "a model is writing this for you".+ *+ * It reads as one product gesture, so it is one component: every surface that+ * hands an input over to a generation — drafting a goal's acceptance contract,+ * naming a self-learning domain, reading a task draft — lights the same ring at+ * the same speed. Written per call site it drifts, and each copy also has to+ * remember the `@property` registration that makes the sweep animate at all.+ */+const GeneratingBorder = memo<GeneratingBorderProps>(+ ({ children, className, generating, style }) => (+ <>+ <BorderAngleProperty />+ <Flexbox+ style={style}+ className={[styles.shell, generating && styles.shellGenerating, className]+ .filter(Boolean)+ .join(' ')}+ >+ {children}+ </Flexbox>+ </>+ ),+);++export default GeneratingBorder;diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex ea75e01d7f7..aef96f838b3 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -7,7 +7,7 @@ import { useEditor } from '@lobehub/editor/react';import { Flexbox, Icon } from '@lobehub/ui';import { ActionIcon, Button, Text, toast, useModalContext } from '@lobehub/ui/base-ui';import { InputNumber } from 'antd';-import { createGlobalStyle, createStaticStyles, cssVar } from 'antd-style';+import { createStaticStyles, cssVar } from 'antd-style';import {ArrowLeft,Paperclip,@@ -21,6 +21,7 @@ import {import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import GeneratingBorder from '@/components/GeneratingBorder';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import {CriterionList,@@ -133,66 +134,10 @@ const styles = createStaticStyles(({ css }) => ({padding-inline: 16px;`,inputShell: css`- position: relative;-overflow: hidden;-min-height: 208px;- border-radius: 8px;-background: ${cssVar.colorBgElevated};`,- inputShellLoading: css`- background: ${cssVar.colorBgElevated};-- &::after {- pointer-events: none;- content: '';-- position: absolute;- z-index: 1;- inset: 0;-- padding: 2px;- border-radius: inherit;-- background: conic-gradient(- from var(--goal-border-angle),- ${cssVar.colorBorderSecondary} 0deg 210deg,- #ff3d8d 238deg,- #8b5cf6 258deg,- #00c8ff 278deg,- #22e6a8 298deg,- #ffd43b 318deg,- #ff6b35 338deg,- ${cssVar.colorBorderSecondary} 360deg- );-- mask:- linear-gradient(#fff 0 0) content-box,- linear-gradient(#fff 0 0);-- animation: goal-input-flow 1.8s linear infinite;-- mask-composite: exclude;- }-- @keyframes goal-input-flow {- from {- --goal-border-angle: 0deg;- }-- to {- --goal-border-angle: 360deg;- }- }-- @media (prefers-reduced-motion: reduce) {- &::after {- animation: none;- }- }- `,instructionEditor: css`min-height: 36px;padding-block: 0 4px;@@ -242,14 +187,6 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const GoalBorderFlowStyle = createGlobalStyle`- @property --goal-border-angle {- inherits: false;- initial-value: 0deg;- syntax: '<angle>';- }-`;-const GENERATION_ESTIMATE_SECONDS = 90;export const formatGoalGenerationRemainingTime = (seconds: number) => {@@ -489,7 +426,6 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {return (<Flexbox onKeyDown={handleKeyDown}>- <GoalBorderFlowStyle /><Flexbox horizontal className={styles.head}><Flexbox flex={1} gap={6}>{step === 'review' && (@@ -518,9 +454,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {)}{step !== 'review' && (<>- <div- className={`${styles.inputShell} ${step === 'preparing' ? styles.inputShellLoading : ''}`}- >+ <GeneratingBorder className={styles.inputShell} generating={step === 'preparing'}><EditorCanvasdisabled={!canCreate || step === 'preparing'}editor={editor}@@ -531,7 +465,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {style={{ fontSize: 14, minHeight: 206, padding: 16 }}onContentChange={handleContentChange}/>- </div>+ </GeneratingBorder>{step === 'preparing' ? (<Flexboxhorizontaldiff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsxindex 1dfc5db74d3..7883d8566d2 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx@@ -15,6 +15,12 @@ const focusMock = vi.hoisted(() => vi.fn());const createTaskMock = vi.hoisted(() => vi.fn());const insertNewlineMock = vi.hoisted(() => vi.fn());const editorMarkdownMock = vi.hoisted(() => ({ value: '' }));+const editorJsonMock = vi.hoisted(() => ({ value: {} as unknown }));+const analyzeIntentMock = vi.hoisted(() => vi.fn());+const synthesizeInstructionMock = vi.hoisted(() => vi.fn());+const navigateMock = vi.hoisted(() => vi.fn());+const toastSuccessMock = vi.hoisted(() => vi.fn());+const createGoalModalMock = vi.hoisted(() => vi.fn());const activeWorkspaceMock = vi.hoisted(() => ({id: 'workspace-1' as string | undefined,}));@@ -23,31 +29,103 @@ const workspaceMembersMock = vi.hoisted(() => ({members: [{ role: 'member', userId: 'user-1' }],}));-vi.mock('@lobehub/editor/react', () => ({- useEditor: () => ({- cleanDocument: vi.fn(),- focus: focusMock,- getDocument: (format: string) => (format === 'markdown' ? editorMarkdownMock.value : {}),- getLexicalEditor: () => undefined,- }),-}));+// `useEditor` is `useMemo(() => createEditor(), [])`, so each call site owns one+// stable instance. The composer and the review step each hold their own, and the+// review step's is seeded from `editorData` — a shared read-only stub would let+// the composer's text stand in for the confirmed instruction.+vi.mock('@lobehub/editor/react', async () => {+ const { useRef } = await import('react');+ return {+ useEditor: () => {+ const ref = useRef<Record<string, unknown> | null>(null);+ if (!ref.current) {+ const seeded: { json?: unknown; markdown?: string } = {};+ ref.current = {+ // Back to unseeded, not to empty: `editorMarkdownMock.value` stands+ // for what the user typed, and the composer clears itself on mount.+ cleanDocument: () => {+ seeded.markdown = undefined;+ seeded.json = undefined;+ },+ focus: focusMock,+ getDocument: (format: string) =>+ format === 'markdown'+ ? (seeded.markdown ?? editorMarkdownMock.value)+ : (seeded.json ?? editorJsonMock.value),+ getLexicalEditor: () => undefined,+ setDocument: (format: string, value: unknown) => {+ if (format !== 'markdown') {+ seeded.json = value;+ return;+ }+ // A real editor builds its own rich text from the markdown, so the+ // mirror it hands back afterwards carries the same content.+ seeded.markdown = String(value);+ seeded.json = {+ root: {+ children: String(value)+ .split('\n')+ .map((line) => ({ children: [{ text: line, type: 'text' }], type: 'paragraph' })),+ type: 'root',+ },+ };+ },+ };+ }+ return ref.current;+ },+ };+});vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({...(await importOriginal<object>()),- toast: { error: vi.fn(), success: vi.fn() },+ toast: { error: vi.fn(), success: toastSuccessMock },}));vi.mock('@/features/EditorCanvas', () => ({- EditorCanvas: ({ disabled, style }: { disabled?: boolean; style?: CSSProperties }) => (- <textarea- data-disabled={String(!!disabled)}- data-padding-bottom={String(style?.paddingBottom)}- data-testid="task-editor"- onKeyDown={(event) => {- if (event.key === 'Enter' && !event.defaultPrevented) insertNewlineMock();- }}- />- ),+ EditorCanvas: ({+ disabled,+ editor,+ editorData,+ style,+ }: {+ disabled?: boolean;+ editor?: { setDocument?: (format: string, value: unknown) => void };+ editorData?: { content?: string; editorData?: unknown };+ style?: CSSProperties;+ }) => {+ // Mirrors EditorDataMode: the rich-text mirror wins, and the markdown is+ // only read when there is no mirror to load.+ if (editorData && editor?.setDocument) {+ if (editorData.editorData) editor.setDocument('json', editorData.editorData);+ else if (editorData.content) editor.setDocument('markdown', editorData.content);+ }+ return (+ <textarea+ data-disabled={String(!!disabled)}+ data-padding-bottom={String(style?.paddingBottom)}+ data-testid="task-editor"+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !event.defaultPrevented) insertNewlineMock();+ }}+ />+ );+ },+}));++vi.mock('@/services/task', () => ({+ taskService: {+ analyzeIntent: analyzeIntentMock,+ synthesizeInstruction: synthesizeInstructionMock,+ },+}));++vi.mock('@/features/AgentGoals/CreateGoalModal', () => ({+ createGoalModal: createGoalModalMock,+}));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => navigateMock,}));vi.mock('@/hooks/usePermission', () => ({@@ -84,9 +162,13 @@ vi.mock('@/store/global', () => ({}),}));+const userStateMock = vi.hoisted(() => ({+ lab: {} as Record<string, boolean>,+}));+vi.mock('@/store/user', () => ({useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({ user: { id: 'self-user' } }),+ selector({ preference: { lab: userStateMock.lab }, user: { id: 'self-user' } }),}));vi.mock('../features/TaskPriorityTag', () => ({@@ -169,9 +251,35 @@ vi.mock('../shared/useAgentVisibility', () => ({useAgentVisibility: (agentId?: string) => (agentId === 'agent-private' ? 'private' : undefined),}));+/** Flips the Labs toggles the composer still reads. */+const setLabs = (lab: { enableTopicAcceptance?: boolean }) => {+ userStateMock.lab = lab as Record<string, boolean>;+};++const clearReading = {+ clarifications: [],+ confidence: 'high' as const,+ kind: 'task' as const,+ refinedInstruction: 'Write a project plan for Q3.',+ summary: 'You want a project plan.',+ title: 'Write the Q3 project plan',+};+describe('CreateTaskInlineEntry', () => {beforeEach(() => {permissionMock.allowed = true;+ setLabs({});+ analyzeIntentMock.mockReset();+ synthesizeInstructionMock.mockReset();+ // The second reading is the normal path: it rewrites the brief with the+ // answers folded in, so the confirmed task carries no Q&A appendix.+ synthesizeInstructionMock.mockResolvedValue({+ instruction: 'Write the Q3 plan for lobe-chat.',+ title: 'Write the Q3 project plan',+ });+ navigateMock.mockReset();+ toastSuccessMock.mockReset();+ createGoalModalMock.mockReset();activeWorkspaceMock.id = 'workspace-1';workspaceMembersMock.isLoading = false;workspaceMembersMock.members = [{ role: 'member', userId: 'user-1' }];@@ -179,6 +287,7 @@ describe('CreateTaskInlineEntry', () => {createTaskMock.mockReset();createTaskMock.mockResolvedValue({ identifier: 'task-1' });editorMarkdownMock.value = '';+ editorJsonMock.value = {};insertNewlineMock.mockReset();localStorage.clear();});@@ -229,6 +338,7 @@ describe('CreateTaskInlineEntry', () => {it('captures Cmd+Enter before the editor inserts a newline and submits the task', async () => {editorMarkdownMock.value = 'Write a project plan';+ analyzeIntentMock.mockResolvedValue(clearReading);render(<CreateTaskInlineEntry variant="hero" />);@@ -338,4 +448,336 @@ describe('CreateTaskInlineEntry', () => {expect(screen.getByTestId('member-selector')).toHaveAttribute('data-current-user-id', ''),);});+ it('confirms the task exists once it is created, and offers a way to open it', async () => {+ editorMarkdownMock.value = 'Write a project plan';+ analyzeIntentMock.mockResolvedValue(clearReading);+ createTaskMock.mockResolvedValue({ identifier: 'TASK-9', name: 'Write the Q3 project plan' });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ // Creating leaves the user on the list, so the spinner blinking out was the+ // only other signal — the flow ended with nothing saying the task existed.+ // (The visible name rides the i18n interpolation, which this suite's `t`+ // stub collapses to the key, so the assertion is on the action instead.)+ await waitFor(() => expect(toastSuccessMock).toHaveBeenCalledTimes(1));++ // Opening is an offer, not the next step. The toast's action slot is+ // right-aligned and shrink-wrapped by the component, so the link rides in+ // the description instead — same column as the task name.+ const { actions, description } = toastSuccessMock.mock.calls[0][0];+ expect(actions).toBeUndefined();++ render(description as ReactNode);+ fireEvent.click(screen.getByText('taskIntent.openCreated'));+ expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('TASK-9'));+ });++ it('confirms every creation path, not only the straight-through one', async () => {+ editorMarkdownMock.value = 'Write a project plan';+ createTaskMock.mockResolvedValue({ identifier: 'TASK-9', name: 'Write the Q3 project plan' });+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('taskIntent.create'));++ // The toast lives in the one place every path funnels through, so the+ // answered path confirms itself exactly like the unanswered one.+ await waitFor(() => expect(toastSuccessMock).toHaveBeenCalledTimes(1));+ });++ describe('intent recognition', () => {+ beforeEach(() => {+ setLabs({ enableTopicAcceptance: true });+ editorMarkdownMock.value = 'Write a project plan';+ });++ it('reads the draft on every submit — there is no setting to turn it on', async () => {+ analyzeIntentMock.mockResolvedValue(clearReading);++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await waitFor(() => expect(analyzeIntentMock).toHaveBeenCalledTimes(1));+ });++ it('creates an unambiguous draft straight through, named by the reading', async () => {+ analyzeIntentMock.mockResolvedValue(clearReading);++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ expect(createTaskMock).toHaveBeenCalledWith(+ expect.objectContaining({+ instruction: 'Write a project plan',+ name: 'Write the Q3 project plan',+ }),+ );+ expect(screen.queryByText('taskIntent.reviewStep')).toBeNull();+ });++ it('holds a draft with an open question and folds the answer into the brief', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ expect(createTaskMock).not.toHaveBeenCalled();++ // Answering the last question lands on the confirm step, and the primary+ // button says so — it reads "create task" on no step any more, which is+ // what left users unsure whether pressing it was the end of the flow.+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('taskIntent.create'));++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ // The answer reaches the task through the rewritten brief, not as a list+ // bolted underneath one written before the answer existed.+ expect(createTaskMock.mock.calls[0][0].instruction).toBe('Write the Q3 plan for lobe-chat.');+ expect(createTaskMock.mock.calls[0][0].instruction).not.toContain(+ 'taskIntent.answersHeading',+ );+ expect(createTaskMock.mock.calls[0][0].name).toBe('Write the Q3 project plan');+ });++ it('runs the second reading only once the answers are all in', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [+ { options: ['lobe-chat'], question: 'Which repo?' },+ { options: ['PDF'], question: 'Which format?' },+ ],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ // Answering is not what triggers the rewrite — there is no step between+ // the last answer and the task, so pressing generate is.+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('PDF'));+ expect(synthesizeInstructionMock).not.toHaveBeenCalled();++ fireEvent.click(await screen.findByText('taskIntent.create'));++ await waitFor(() => expect(synthesizeInstructionMock).toHaveBeenCalledTimes(1));+ expect(synthesizeInstructionMock.mock.calls[0][0].answers).toEqual([+ { answer: 'lobe-chat', question: 'Which repo?' },+ { answer: 'PDF', question: 'Which format?' },+ ]);+ // One press: the rewrite and the create, with no page in between.+ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ });++ it('names the last step "create", answered or not', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ // Whether or not the question gets an answer, pressing it ends with a+ // task — naming it for the machinery behind it described the product's+ // internals rather than what the user gets.+ await screen.findByText('taskIntent.reviewStep');+ expect(screen.getByText('taskIntent.create')).toBeDefined();++ fireEvent.click(screen.getByText('lobe-chat'));++ expect(screen.getByText('taskIntent.create')).toBeDefined();+ });++ it('has no confirmation step between the last answer and the task', async () => {+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));++ // No confirm tab, no answers recap, no second instruction editor: the+ // question the user is on is the last thing standing between them and+ // the task.+ expect(screen.queryByText('taskIntent.confirmStep')).toBeNull();+ expect(screen.queryByText('taskIntent.confirmHeading')).toBeNull();+ expect(screen.queryByText('taskIntent.instructionLabel')).toBeNull();+ expect(screen.getByText('taskIntent.create')).toBeDefined();+ });++ it('falls back to appending the answers when the second reading fails', async () => {+ // Same contract as the first reading: an assist, never a gate.+ synthesizeInstructionMock.mockRejectedValue(new Error('offline'));+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('taskIntent.create'));++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ expect(createTaskMock.mock.calls[0][0].instruction).toContain(+ '## taskIntent.answersHeading\n- Which repo? lobe-chat',+ );+ });++ it('sends no stale mirror alongside a rewritten brief', async () => {+ // The mirror wins over the markdown when a task is rendered, so shipping+ // the pre-answer draft's document next to a rewritten brief would show+ // the user something the agent never received. Freshly written prose has+ // no mirror to inherit: send none, and let the page rebuild from the+ // markdown that was actually run.+ editorJsonMock.value = {+ root: {+ children: [+ { children: [{ text: 'Write a project plan', type: 'text' }], type: 'paragraph' },+ ],+ type: 'root',+ },+ };+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('taskIntent.create'));++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ const { editorData, instruction } = createTaskMock.mock.calls[0][0];++ expect(instruction).toBe('Write the Q3 plan for lobe-chat.');+ expect(editorData).toBeUndefined();+ });++ it('falls back to appending the answers when the second reading fails', async () => {+ // Same contract as the first reading: an assist, never a gate.+ synthesizeInstructionMock.mockRejectedValue(new Error('offline'));+ analyzeIntentMock.mockResolvedValue({+ ...clearReading,+ clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],+ confidence: 'medium',+ });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await screen.findByText('taskIntent.reviewStep');+ fireEvent.click(screen.getByText('lobe-chat'));+ fireEvent.click(await screen.findByText('taskIntent.create'));++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ expect(createTaskMock.mock.calls[0][0].instruction).toContain(+ '## taskIntent.answersHeading\n- Which repo? lobe-chat',+ );+ });++ it('offers the goal handoff only for a request read as a standing goal', async () => {+ analyzeIntentMock.mockResolvedValue({ ...clearReading, kind: 'goal' });++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ fireEvent.click(await screen.findByText('taskIntent.goalCallout.action'));++ expect(createGoalModalMock).toHaveBeenCalledWith(+ expect.objectContaining({ initialTitle: 'Write the Q3 project plan' }),+ );+ expect(createTaskMock).not.toHaveBeenCalled();+ });++ it('still creates the task when the reading itself fails', async () => {+ analyzeIntentMock.mockRejectedValue(new Error('model unavailable'));++ render(<CreateTaskInlineEntry variant="hero" />);+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ expect(screen.queryByText('taskIntent.reviewStep')).toBeNull();+ });+ });++ describe('persisted draft across a create', () => {+ const DRAFT_KEY = 'lobehub:task-create-draft:workspace-1:all';++ beforeEach(() => {+ localStorage.clear();+ editorMarkdownMock.value = 'Write a project plan';+ analyzeIntentMock.mockResolvedValue(clearReading);+ });++ it('takes the draft off disk before the create resolves, not after', async () => {+ // Creating the first task flips the list from empty to non-empty, which+ // remounts the composer *during* this await. The new instance hydrates+ // from this key, so a draft still on disk here reappears on screen and+ // the success reset lands on the old, unmounted instance.+ let release: (value: { identifier: string }) => void = () => {};+ createTaskMock.mockReturnValue(+ new Promise<{ identifier: string }>((resolve) => {+ release = resolve;+ }),+ );++ render(<CreateTaskInlineEntry variant="hero" />);+ localStorage.setItem(DRAFT_KEY, JSON.stringify({ markdown: 'Write a project plan' }));++ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ expect(localStorage.getItem(DRAFT_KEY)).toBeNull();++ release({ identifier: 'task-1' });+ await waitFor(() => expect(localStorage.getItem(DRAFT_KEY)).toBeNull());+ });++ it('puts the draft back when the create fails', async () => {+ createTaskMock.mockRejectedValue(new Error('offline'));++ render(<CreateTaskInlineEntry variant="hero" />);+ localStorage.setItem(DRAFT_KEY, JSON.stringify({ markdown: 'Write a project plan' }));++ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });++ await waitFor(() => expect(createTaskMock).toHaveBeenCalledTimes(1));+ // Nothing was created, so the work is still the user's: it stays on disk+ // to match the text the composer is still showing.+ await waitFor(() =>+ expect(localStorage.getItem(DRAFT_KEY)).toContain('Write a project plan'),+ );+ });+ });});diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsxindex d9083445e28..ded2209413c 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx@@ -1,28 +1,34 @@'use client';import { canWorkspaceRoleBeTaskAssignee } from '@lobechat/const/rbac';+import type { TaskIntentAnalysis } from '@lobechat/types';import { useEditor } from '@lobehub/editor/react';-import { Block, Flexbox } from '@lobehub/ui';+import { Block, DropdownMenu, Flexbox } from '@lobehub/ui';import { ActionIcon, Button, Text, toast } from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';import { $getRoot } from 'lexical';-import { ChevronUp, Paperclip } from 'lucide-react';+import { ChevronDown, ChevronUp, Paperclip } from 'lucide-react';import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useFetchWorkspaceMembers } from '@/business/client/hooks/useFetchWorkspaceMembers';import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';+import GeneratingBorder from '@/components/GeneratingBorder';+import { createGoalModal } from '@/features/AgentGoals/CreateGoalModal';import { EditorCanvas } from '@/features/EditorCanvas';import {getAttachmentFileIdsFromEditor,pickAndInsertAttachments,} from '@/features/EditorCanvas/editorAttachments';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';+import { taskService } from '@/services/task';import { useGlobalStore } from '@/store/global';import { useTaskStore } from '@/store/task';import { useUserStore } from '@/store/user';-import { userProfileSelectors } from '@/store/user/selectors';+import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';+import { shinyTextStyles } from '@/styles';import AssigneeAgentSelector from '../features/AssigneeAgentSelector';import AssigneeAvatar from '../features/AssigneeAvatar';@@ -32,9 +38,18 @@ import TaskPriorityTag from '../features/TaskPriorityTag';import TaskVisibilityChipLabel from '../features/TaskVisibilityChipLabel';import TaskVisibilityTag from '../features/TaskVisibilityTag';import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';+import { taskDetailPath } from '../shared/taskDetailPath';import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';import { useAgentVisibility } from '../shared/useAgentVisibility';import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';+import {+ answeredClarifications,+ buildConfirmedDraft,+ buildGoalSeed,+ type ClarificationAnswers,+ shouldConfirmIntent,+} from './taskIntent';+import TaskIntentReview from './TaskIntentReview';interface CreateTaskInlineEntryProps {agentId?: string;@@ -96,6 +111,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {),[workspaceMembers],);+ const navigate = useWorkspaceAwareNavigate();const [priority, setPriority] = useState(0);const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);const [assigneeUserId, setAssigneeUserId] = useState<string | undefined>();@@ -105,6 +121,25 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {// In personal mode the chip is hidden and the value is never sent.const [visibility, setVisibility] = useState<'private' | 'public'>(defaultVisibility);+ // Reading the draft is what submit does now. It only stops for confirmation+ // when it found something the user alone can settle, so the escape hatch is+ // the dropdown's "create directly" rather than a setting nobody would find.+ const canCreateGoal = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const [analysis, setAnalysis] = useState<TaskIntentAnalysis | null>(null);+ const [intentTitle, setIntentTitle] = useState('');+ const [intentAnswers, setIntentAnswers] = useState<ClarificationAnswers>({});+ const [isAnalyzing, setIsAnalyzing] = useState(false);+ // The instruction the review step shows is a real editor, not a preview: it+ // is what gets created, so the user has to be able to read it and change it.+ // It is a second editor rather than the composer's own so that going back+ // returns to the untouched draft.+ // Set once the second reading has folded the answers into the instruction.+ // The appended Q&A block is then already redundant — leaving it on would put+ // the answers in the brief twice, once woven in and once as a list.+ const [isSynthesizing, setIsSynthesizing] = useState(false);++ // A private agent can only run a private task. Coerce + lock the+ // visibility chip when the selected agent is private.const assigneeVisibility = useAgentVisibility(assigneeAgentId);const isPrivateAgent = assigneeVisibility === 'private';const selfUserId = useUserStore(userProfileSelectors.userId);@@ -287,12 +322,30 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {pickAndInsertAttachments(editor);}, [editor]);- const handleSubmit = useCallback(async () => {- if (!canCreateTask) return;+ const resetComposer = useCallback(() => {+ setPriority(0);+ setAssigneeAgentId(agentId);+ setAssigneeUserId(undefined);+ setInstruction('');+ setVisibility(defaultVisibility);+ setAnalysis(null);+ setIntentAnswers({});+ editor?.cleanDocument?.();+ if (draftStorageKey) {+ try {+ localStorage.removeItem(draftStorageKey);+ } catch {+ /* ignore */+ }+ }+ }, [agentId, defaultVisibility, draftStorageKey, editor]);++ /** What the composer currently holds, or null when there is nothing to create. */+ const readDraft = useCallback(() => {const markdown = String(editor?.getDocument?.('markdown') ?? '').trim();const trimmedText = instruction.trim();const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;- if (!trimmedText && !markdown && !hasFiles) return;+ if (!trimmedText && !markdown && !hasFiles) return null;const firstLine =trimmedText@@ -304,71 +357,272 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {name = firstLine.length > 30 ? `${firstLine.slice(0, 30)}…` : firstLine;}- const editorJson = editor?.getDocument?.('json') as unknown;+ return {+ editorJson: editor?.getDocument?.('json') as unknown,+ instruction: markdown || trimmedText || name || '',+ name,+ };+ }, [editor, instruction]);++ const submitDraft = useCallback(+ async (draft: { editorJson: unknown; instruction: string; name?: string }) => {+ // Drop the persisted draft BEFORE the request, not in the success reset.+ // Creating the first task flips the list from empty to non-empty, which+ // swaps the hero composer for the one that sits above the list — a+ // different component instance, mounted while this await is still in+ // flight. That new instance hydrates itself from this key, so a draft+ // still on disk here comes straight back onto the screen and the reset+ // below lands on the old, dying instance. Kept in hand so a failed+ // create can put it back.+ let persistedDraft: string | null = null;+ if (draftStorageKey) {+ try {+ persistedDraft = localStorage.getItem(draftStorageKey);+ localStorage.removeItem(draftStorageKey);+ } catch {+ /* storage unavailable — persistence is best-effort */+ }+ }- // `createTask` keeps its rejecting contract (other callers rely on `catch`);- // handle the composer's own failure here so it isn't silent, keeping the- // draft intact (the reset only runs on success).- try {- const result = await createTask({- assigneeAgentId,- assigneeUserId,- editorData: editorJson,- instruction: markdown || trimmedText || name || '',- name,- parentTaskId,- priority: priority || undefined,- projectId,- // Only send visibility in workspace mode; personal mode lets the server- // fall through to the schema default ('public', inert in personal mode).- visibility: activeWorkspaceId ? visibility : undefined,- });+ // `createTask` keeps its rejecting contract (other callers rely on `catch`);+ // handle the composer's own failure here so it isn't silent, keeping the+ // draft intact (the reset only runs on success).+ try {+ const result = await createTask({+ assigneeAgentId,+ assigneeUserId,+ editorData: draft.editorJson,+ instruction: draft.instruction,+ name: draft.name,+ parentTaskId,+ priority: priority || undefined,+ projectId,+ // Only send visibility in workspace mode; personal mode lets the server+ // fall through to the schema default ('public', inert in personal mode).+ visibility: activeWorkspaceId ? visibility : undefined,+ });- if (result) {- setPriority(0);- setAssigneeAgentId(agentId);- setAssigneeUserId(undefined);- setInstruction('');- setVisibility(defaultVisibility);- editor?.cleanDocument?.();- if (draftStorageKey) {+ if (result) {+ resetComposer();+ // Creating from here leaves the user on the list, so without this the+ // whole flow ends in a spinner blinking out — nothing says the task+ // exists, what it ended up called, or where it went. The name matters+ // most after a reading, since that name is what the reading produced.+ toast.success({+ // The open affordance rides in the description rather than the+ // action slot: the toast's job is to say the task exists, and a+ // filled button pulled to the far right read as the thing to do+ // next. The action slot is right-aligned and shrink-wrapped by the+ // toast itself, so lining the link up under the task name means+ // putting it in the same column as the name.+ description: (+ <Flexbox align={'flex-start'} gap={2}>+ <Text>{result.name || draft.name}</Text>+ <Button+ size={'small'}+ style={{ paddingInline: 0 }}+ type={'text'}+ onClick={() =>+ navigate(taskDetailPath(result.identifier, result.assigneeAgentId ?? undefined))+ }+ >+ {t('taskIntent.openCreated')}+ </Button>+ </Flexbox>+ ),+ title: t('taskIntent.created'),+ });+ onCreated?.({+ agentId: result.assigneeAgentId ?? undefined,+ identifier: result.identifier,+ });+ }+ } catch {+ // Nothing was created, so the draft is still the user's work: put it+ // back on disk to match the text the composer is still showing.+ if (draftStorageKey && persistedDraft !== null) {try {- localStorage.removeItem(draftStorageKey);+ localStorage.setItem(draftStorageKey, persistedDraft);} catch {- /* ignore */+ /* storage unavailable — persistence is best-effort */}}- onCreated?.({- agentId: result.assigneeAgentId ?? undefined,- identifier: result.identifier,- });+ toast.error(t('createTask.createFailed'));}+ },+ [+ t,+ activeWorkspaceId,+ draftStorageKey,+ assigneeAgentId,+ assigneeUserId,+ createTask,+ navigate,+ onCreated,+ parentTaskId,+ priority,+ projectId,+ resetComposer,+ visibility,+ ],+ );++ const handleSubmit = useCallback(async () => {+ if (!canCreateTask) return;+ const draft = readDraft();+ if (!draft) return;++ setIsAnalyzing(true);+ try {+ const result = await taskService.analyzeIntent({+ context: assigneeMeta?.title ? `Assigned agent: ${assigneeMeta.title}` : undefined,+ instruction: draft.instruction,+ });++ // An unambiguous draft is never held up — it goes straight through, just+ // with a real name instead of the first thirty characters of line one.+ if (shouldConfirmIntent(result)) {+ setAnalysis(result);+ setIntentTitle(result.title);+ setIntentAnswers({});+ return;+ }++ await submitDraft({ ...draft, name: result.title || draft.name });} catch {- toast.error(t('createTask.createFailed'));+ // Reading the draft is an assist, never a gate: when the model call fails+ // the task is created exactly as it would have been without this step.+ await submitDraft(draft);+ } finally {+ setIsAnalyzing(false);}+ }, [assigneeMeta?.title, canCreateTask, readDraft, submitDraft]);++ /**+ * The escape hatch, one click away in the submit dropdown: create the task+ * with no reading at all. Same path the composer took before this feature —+ * first line truncated for the name, draft text handed straight over — so a+ * user who finds the reading slow or wrong is never stuck behind it.+ */+ const handleCreateDirectly = useCallback(async () => {+ if (!canCreateTask) return;+ const draft = readDraft();+ if (!draft) return;+ await submitDraft(draft);+ }, [canCreateTask, readDraft, submitDraft]);++ const handleAnswerChange = useCallback((index: number, value: string) => {+ setIntentAnswers((current) => ({ ...current, [index]: value }));+ }, []);++ /**+ * The review editor is the source of truth for what gets created, not the+ * composer draft it was seeded from — the user may have rewritten any of it.+ * Markdown and its rich-text mirror are read from the same editor and get the+ * answers appended together, so the task page cannot show one and the agent+ * read the other.+ */+ /**+ * Generate and create, in one press.+ *+ * The first reading ran before the user answered, so its brief still names+ * the answered details as open — creating from it, or from it with the+ * answers stapled underneath, hands the executor a document that contradicts+ * itself. So pressing generate writes the brief again with the answers folded+ * in as settled facts, and creates the task from that. There is no page in+ * between: the brief is on the task's own page the moment it exists.+ *+ * Like the first reading it is an assist, never a gate — a failed rewrite+ * falls back to the draft with the answers appended, which is what the flow+ * did before this step existed.+ */+ const handleConfirmIntent = useCallback(async () => {+ const draft = readDraft();+ if (!analysis || !draft) return;++ const pairs = answeredClarifications(analysis, intentAnswers);++ if (pairs.length > 0) {+ setIsSynthesizing(true);+ try {+ const written = await taskService.synthesizeInstruction({+ answers: pairs,+ context: assigneeMeta?.title ? `Assigned agent: ${assigneeMeta.title}` : undefined,+ instruction: draft.instruction,+ });++ await submitDraft({+ // Freshly written prose has no mirror to inherit. Sending the+ // pre-answer draft's document instead would win over this markdown+ // when the task renders, showing a brief the agent never received.+ editorJson: undefined,+ instruction: written.instruction,+ name: written.title.trim() || intentTitle.trim() || analysis.title,+ });+ return;+ } catch {+ // Fall through to the append path below.+ } finally {+ setIsSynthesizing(false);+ }+ }++ const confirmed = buildConfirmedDraft({+ analysis,+ answers: intentAnswers,+ editorJson: draft.editorJson,+ heading: t('taskIntent.answersHeading'),+ instruction: draft.instruction,+ });++ await submitDraft({+ editorJson: confirmed.editorData,+ instruction: confirmed.instruction,+ name: intentTitle.trim() || analysis.title,+ });+ }, [analysis, assigneeMeta?.title, intentAnswers, intentTitle, readDraft, submitDraft, t]);++ // Hands the draft (and any answers already given) to the goal modal, then+ // drops back to composing: the goal flow owns the outcome from here, and the+ // untouched draft is still in the editor if the user backs out of it.+ const handleSwitchToGoal = useCallback(() => {+ const draft = readDraft();+ if (!analysis || !draft) return;++ const seed = buildGoalSeed({+ analysis,+ answers: intentAnswers,+ heading: t('taskIntent.answersHeading'),+ instruction: draft.instruction,+ });++ createGoalModal({+ agentId: assigneeAgentId,+ initialRequirement: seed.requirement,+ initialTitle: intentTitle.trim() || seed.title,+ onCreated: resetComposer,+ projectId,+ });+ setAnalysis(null);}, [- t,- activeWorkspaceId,- agentId,+ analysis,assigneeAgentId,- assigneeUserId,- createTask,- defaultVisibility,- draftStorageKey,- editor,- instruction,- onCreated,- parentTaskId,- priority,+ intentAnswers,+ intentTitle,projectId,- canCreateTask,- visibility,+ readDraft,+ resetComposer,+ t,]);+ const isReviewing = Boolean(analysis);++ // Cmd+Enter means "the primary action of what is on screen": submit the+ // draft while composing, confirm the reading while reviewing.const handleSubmitRef = useRef(handleSubmit);useEffect(() => {- handleSubmitRef.current = handleSubmit;- }, [handleSubmit]);+ handleSubmitRef.current = isReviewing ? handleConfirmIntent : handleSubmit;+ }, [handleConfirmIntent, handleSubmit, isReviewing]);const handleKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {@@ -379,82 +633,76 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {}, []);return (- <Block- style={{ overflow: 'hidden', position: 'relative' }}- variant={'outlined'}- onKeyDownCapture={handleKeyDown}- >- {!isHero && (- <ActionIcon- icon={ChevronUp}- size={'small'}- style={{ position: 'absolute', right: 8, top: 8, zIndex: 1 }}- title={t('createTask.collapse')}- onClick={handleCollapse}- />- )}- <Flexbox- style={{- fontSize: isHero ? 16 : 14,- // Cap the editor so a long draft scrolls inside the box instead of- // growing the composer until it pushes the task list below the fold.- maxHeight: isHero ? 360 : 200,- overflowY: 'auto',- padding: isHero ? '12px 16px 0' : '8px 40px 0 16px',- }}+ // The ring belongs to the whole input surface — editor, controls and submit+ // are one thing being read, so lighting only the text area would draw a+ // second boundary the composer does not otherwise have.+ <GeneratingBorder generating={isAnalyzing || isSynthesizing}>+ <Block+ style={{ overflow: 'hidden', position: 'relative' }}+ variant={'outlined'}+ onKeyDownCapture={handleKeyDown}>- <EditorCanvas- disabled={!canCreateTask}- editor={editor}- floatingToolbar={false}- placeholder={placeholder ?? t('createTask.instructionPlaceholder')}+ {!isHero && !isReviewing && (+ <ActionIcon+ icon={ChevronUp}+ size={'small'}+ style={{ position: 'absolute', right: 8, top: 8, zIndex: 1 }}+ title={t('createTask.collapse')}+ onClick={handleCollapse}+ />+ )}+ {isReviewing && analysis && (+ <TaskIntentReview+ analysis={analysis}+ answers={intentAnswers}+ isCreating={isCreating || isSynthesizing}+ title={intentTitle}+ onAnswerChange={handleAnswerChange}+ onBack={() => setAnalysis(null)}+ onConfirm={handleConfirmIntent}+ onSwitchToGoal={canCreateGoal ? handleSwitchToGoal : undefined}+ onTitleChange={setIntentTitle}+ />+ )}+ {/* Kept mounted through the review step so going back restores the draft+ exactly as it was, attachments and all. */}+ <Flexboxstyle={{+ display: isReviewing ? 'none' : undefined,fontSize: isHero ? 16 : 14,- minHeight: isHero ? 80 : undefined,- paddingBottom: 12,+ // Cap the editor so a long draft scrolls inside the box instead of+ // growing the composer until it pushes the task list below the fold.+ maxHeight: isHero ? 360 : 200,+ overflowY: 'auto',+ padding: isHero ? '12px 16px 0' : '8px 40px 0 16px',}}- onContentChange={handleContentChange}- />- </Flexbox>- <Flexbox- horizontal- align={'center'}- justify={'space-between'}- style={{- borderTop: `1px solid ${cssVar.colorBorderSecondary}`,- paddingBlock: 8,- paddingInline: '8px 16px',- }}- >- <Flexbox horizontal align={'center'} gap={2} wrap={'wrap'}>- <TaskPriorityTag priority={priority} onChange={setPriority}>- <Block- clickable- horizontal- align="center"- gap={6}- height={24}- paddingBlock={3}- paddingInline={8}- variant={'borderless'}- >- <TaskPriorityTag disableDropdown priority={priority} size={14} />- <Text fontSize={12}>- {priority === 0- ? t('taskDetail.priority.none')- : t(- `taskDetail.priority.${(['', 'urgent', 'high', 'normal', 'low'] as const)[priority]}` as never,- )}- </Text>- </Block>- </TaskPriorityTag>-- {activeWorkspaceId && (- <AssigneeMemberSelector- currentUserId={assigneeUserId}- taskVisibility={visibility}- onChange={handleMemberChange}- >+ >+ <EditorCanvas+ disabled={!canCreateTask}+ editor={editor}+ floatingToolbar={false}+ placeholder={placeholder ?? t('createTask.instructionPlaceholder')}+ style={{+ fontSize: isHero ? 16 : 14,+ minHeight: isHero ? 80 : undefined,+ paddingBottom: 12,+ }}+ onContentChange={handleContentChange}+ />+ </Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ justify={'space-between'}+ style={{+ borderTop: `1px solid ${cssVar.colorBorderSecondary}`,+ display: isReviewing ? 'none' : undefined,+ paddingBlock: 8,+ paddingInline: '8px 16px',+ }}+ >+ <Flexbox horizontal align={'center'} gap={2} wrap={'wrap'}>+ <TaskPriorityTag priority={priority} onChange={setPriority}><Blockclickablehorizontal@@ -465,44 +713,52 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {paddingInline={8}variant={'borderless'}>- {assigneeUserId ? (- <>- <AssigneeUserAvatar size={18} userId={assigneeUserId} />- <Text fontSize={12}>{memberMeta?.title}</Text>- </>- ) : (- <>- <UnassignedAssigneeIcon kind={'human'} size={14} />- <Text color={cssVar.colorTextDescription} fontSize={12}>- {t('createTask.member')}- </Text>- </>- )}+ <TaskPriorityTag disableDropdown priority={priority} size={14} />+ <Text fontSize={12}>+ {priority === 0+ ? t('taskDetail.priority.none')+ : t(+ `taskDetail.priority.${(['', 'urgent', 'high', 'normal', 'low'] as const)[priority]}` as never,+ )}+ </Text></Block>- </AssigneeMemberSelector>- )}-- {lockAssignee ? (- <Block- horizontal- align="center"- gap={6}- height={24}- paddingBlock={3}- paddingInline={8}- variant={'borderless'}- >- <AssigneeAvatar agentId={assigneeAgentId} size={18} />- <Text fontSize={12}>{assigneeMeta?.title}</Text>- </Block>- ) : (- <AssigneeAgentSelector- currentAgentId={assigneeAgentId}- taskVisibility={isOtherMemberAssignee ? 'public' : undefined}- onChange={handleAgentChange}- >+ </TaskPriorityTag>++ {activeWorkspaceId && (+ <AssigneeMemberSelector+ currentUserId={assigneeUserId}+ taskVisibility={visibility}+ onChange={handleMemberChange}+ >+ <Block+ clickable+ horizontal+ align="center"+ gap={6}+ height={24}+ paddingBlock={3}+ paddingInline={8}+ variant={'borderless'}+ >+ {assigneeUserId ? (+ <>+ <AssigneeUserAvatar size={18} userId={assigneeUserId} />+ <Text fontSize={12}>{memberMeta?.title}</Text>+ </>+ ) : (+ <>+ <UnassignedAssigneeIcon kind={'human'} size={14} />+ <Text color={cssVar.colorTextDescription} fontSize={12}>+ {t('createTask.member')}+ </Text>+ </>+ )}+ </Block>+ </AssigneeMemberSelector>+ )}++ {lockAssignee ? (<Block- clickablehorizontalalign="center"gap={6}@@ -511,66 +767,130 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {paddingInline={8}variant={'borderless'}>- {assigneeAgentId ? (- <>- <AssigneeAvatar agentId={assigneeAgentId} size={18} />- <Text fontSize={12}>{assigneeMeta?.title}</Text>- </>- ) : (- <>- <UnassignedAssigneeIcon kind={'agent'} size={14} />- <Text color={cssVar.colorTextDescription} fontSize={12}>- {t('createTask.assignee')}- </Text>- </>- )}+ <AssigneeAvatar agentId={assigneeAgentId} size={18} />+ <Text fontSize={12}>{assigneeMeta?.title}</Text></Block>- </AssigneeAgentSelector>- )}-- <ActionIcon- icon={Paperclip}- size={'small'}- title={t('upload.action.tooltip')}- onClick={handleAttach}- />- </Flexbox>-- <Flexbox horizontal align={'center'} gap={4}>- {activeWorkspaceId && (- <TaskVisibilityTag- visibility={visibility}- lockedReason={- isPrivateAgent- ? t('createTask.visibility.privateAgentLocked', {- defaultValue: 'Private agents can only run private tasks.',- })- : isOtherMemberAssignee- ? t('createTask.visibility.memberAssigneeLocked', {- defaultValue: 'A task assigned to a member stays visible to the workspace.',+ ) : (+ <AssigneeAgentSelector+ currentAgentId={assigneeAgentId}+ taskVisibility={isOtherMemberAssignee ? 'public' : undefined}+ onChange={handleAgentChange}+ >+ <Block+ clickable+ horizontal+ align="center"+ gap={6}+ height={24}+ paddingBlock={3}+ paddingInline={8}+ variant={'borderless'}+ >+ {assigneeAgentId ? (+ <>+ <AssigneeAvatar agentId={assigneeAgentId} size={18} />+ <Text fontSize={12}>{assigneeMeta?.title}</Text>+ </>+ ) : (+ <>+ <UnassignedAssigneeIcon kind={'agent'} size={14} />+ <Text color={cssVar.colorTextDescription} fontSize={12}>+ {t('createTask.assignee')}+ </Text>+ </>+ )}+ </Block>+ </AssigneeAgentSelector>+ )}++ <ActionIcon+ icon={Paperclip}+ size={'small'}+ title={t('upload.action.tooltip')}+ onClick={handleAttach}+ />+ </Flexbox>++ <Flexbox horizontal align={'center'} gap={4}>+ {activeWorkspaceId && (+ <TaskVisibilityTag+ visibility={visibility}+ lockedReason={+ isPrivateAgent+ ? t('createTask.visibility.privateAgentLocked', {+ defaultValue: 'Private agents can only run private tasks.',})- : undefined- }- onChange={setVisibility}- >- <TaskVisibilityChipLabel height={24} paddingBlock={3} visibility={visibility} />- </TaskVisibilityTag>- )}-- <Button- disabled={!canCreateTask || isCreating || (!instruction.trim() && !hasAttachments)}- loading={isCreating}- shape={'round'}- size={'small'}- title={canCreateTask ? undefined : reason}- type={'primary'}- onClick={handleSubmit}- >- {t('createTask.submit')}- </Button>+ : isOtherMemberAssignee+ ? t('createTask.visibility.memberAssigneeLocked', {+ defaultValue:+ 'A task assigned to a member stays visible to the workspace.',+ })+ : undefined+ }+ onChange={setVisibility}+ >+ <TaskVisibilityChipLabel height={24} paddingBlock={3} visibility={visibility} />+ </TaskVisibilityTag>+ )}++ <Flexbox horizontal align={'center'} gap={2}>+ <Button+ loading={isCreating || isAnalyzing}+ shape={'round'}+ size={'small'}+ title={canCreateTask ? undefined : reason}+ // The shimmer is a text-clipped gradient in the foreground color, so+ // it only reads on a light surface. Dropping the filled style while+ // reading also matches what is happening: the button has handed the+ // draft off and is no longer the thing to press.+ type={isAnalyzing ? 'default' : 'primary'}+ disabled={+ !canCreateTask ||+ isCreating ||+ isAnalyzing ||+ (!instruction.trim() && !hasAttachments)+ }+ onClick={handleSubmit}+ >+ {isAnalyzing ? (+ // Same shimmer every other "a model is working on this" label in+ // the app uses, so the wait reads as the product thinking rather+ // than as the button having gone inert.+ <span className={shinyTextStyles.shinyText}>{t('taskIntent.analyzing')}</span>+ ) : (+ t('createTask.submit')+ )}+ </Button>+ {/* The escape hatch sits on the button it bypasses, so a user who+ does not want the reading finds it exactly where they already+ are — rather than in a setting they would have to know exists. */}+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ key: 'create-directly',+ label: t('taskIntent.createDirectly'),+ onClick: () => void handleCreateDirectly(),+ },+ ]}+ >+ <ActionIcon+ icon={ChevronDown}+ size={'small'}+ title={t('taskIntent.moreCreateOptions')}+ disabled={+ !canCreateTask ||+ isCreating ||+ isAnalyzing ||+ (!instruction.trim() && !hasAttachments)+ }+ />+ </DropdownMenu>+ </Flexbox>+ </Flexbox></Flexbox>- </Flexbox>- </Block>+ </Block>+ </GeneratingBorder>);});diff --git a/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx b/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsxnew file mode 100644index 00000000000..e0a0690ee70--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/TaskIntentReview.tsx@@ -0,0 +1,319 @@+'use client';++import { OptionCard } from '@lobechat/shared-tool-ui/components';+import type { TaskIntentAnalysis } from '@lobechat/types';+import { Flexbox, Icon, TextArea } from '@lobehub/ui';+import { Button, Tabs, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowLeft, Check, Sparkles, Target } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { ClarificationAnswers } from './taskIntent';++const styles = createStaticStyles(({ css }) => ({+ body: css`+ overflow-y: auto;++ /* Viewport-relative, because the footer holds the only way forward: a fixed+ cap sized for a tall window pushed "create" below the fold on a short one,+ leaving the panel's primary action unreachable without scrolling. The+ question list scrolls inside this box instead, and the footer stays put.+ (The absolute cap is the leftover from the confirm step's instruction+ editor, which no longer exists — the questions never needed it.) */+ max-height: min(420px, 42dvh);+ padding-block: 12px 16px;+ padding-inline: 16px;+ `,+ footer: css`+ padding-block: 8px;+ padding-inline: 8px 16px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ goalCallout: css`+ padding-block: 10px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ `,+ head: css`+ padding-block: 12px 0;+ padding-inline: 16px;+ `,+ // Mirrors OptionCard's own index chip so the free-text row reads as one more+ // numbered choice rather than a separate control below the list.+ customIndex: css`+ flex-shrink: 0;++ box-sizing: border-box;+ width: 22px;+ height: 22px;+ border-radius: 6px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-weight: 600;+ line-height: 22px;+ color: ${cssVar.colorTextSecondary};+ text-align: center;++ background: ${cssVar.colorFillTertiary};+ `,+ // Reuses OptionCard's row rhythm so the recap reads as the same list the+ // user just answered, not as a different kind of object.+ answerRow: css`+ cursor: pointer;++ padding-block: 8px;+ padding-inline: 12px;+ border-radius: 8px;++ transition: background 0.12s ease;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ customRow: css`+ margin-block-start: 2px;++ /* Align the chip under OptionCard's own index chips. */+ padding-inline: 12px;+ `,+ instruction: css`+ overflow-y: auto;+ max-height: 220px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ `,+ tabs: css`+ [role='tablist'] {+ width: 100%;+ }+ `,+ title: css`+ box-sizing: border-box;+ width: 100%;+ padding-block: 2px;+ border: none;++ font-family: inherit;+ font-size: 16px;+ font-weight: 600;+ line-height: 1.4;+ color: inherit;++ background: transparent;+ outline: none;+ `,+}));++export interface TaskIntentReviewProps {+ analysis: TaskIntentAnalysis;+ answers: ClarificationAnswers;+ /** True while the brief is being written and the task created. */+ isCreating?: boolean;+ onAnswerChange: (index: number, value: string) => void;+ onBack: () => void;+ onConfirm: () => void;+ /** Omitted when goals are unavailable — the exit is then simply not offered. */+ onSwitchToGoal?: () => void;+ onTitleChange: (title: string) => void;+ title: string;+}++/**+ * The confirmation step between typing a task and creating it.+ *+ * It only ever renders for a draft the reader could not settle on its own, so+ * everything here is something the user is the only one able to answer. The+ * questions stay optional: skipping them creates exactly the task the composer+ * would have created before, which keeps this a checkpoint rather than a form+ * to fill in. Answering the last one and pressing generate is the whole flow —+ * the brief is written from the answers and the task created in one step.+ */+const TaskIntentReview = memo<TaskIntentReviewProps>((props) => {+ const {+ analysis,+ answers,+ isCreating,+ onAnswerChange,+ onBack,+ onConfirm,+ onSwitchToGoal,+ onTitleChange,+ title,+ } = props;+ const { t } = useTranslation('chat');++ // One question at a time, exactly like AskUserQuestionView: stacking them all+ // in a scroll box hid both that a next question existed and how to reach it.+ const [activeIndex, setActiveIndex] = useState(0);+ const clarifications = analysis.clarifications;+ // A new reading is a new set of questions, so the cursor goes back to the top+ // rather than pointing past the end of a shorter list.+ useEffect(() => setActiveIndex(0), [clarifications]);++ const isAnswered = useCallback((index: number) => Boolean(answers[index]?.trim()), [answers]);++ // One past the last question: the step that says what answering produced.++ const pickOption = useCallback(+ (index: number, option: string) => {+ // Tapping the option that is already the answer clears it, so a mis-tap+ // doesn't force the user to select the text and delete it by hand.+ const cleared = answers[index] === option;+ onAnswerChange(index, cleared ? '' : option);+ if (cleared) return;++ // Sweep to the next still-unanswered question. When there is none left+ // the form stays put: the primary button already reads "generate", so+ // the step the user is on is also the last thing they have to press.+ const next = clarifications.findIndex((_, i) => i !== index && !answers[i]?.trim());+ if (next >= 0) setActiveIndex(next);+ },+ [answers, clarifications, onAnswerChange],+ );++ const showGoalExit = analysis.kind === 'goal' && Boolean(onSwitchToGoal);+ const active = clarifications[activeIndex];+ const onLastQuestion = activeIndex >= clarifications.length - 1;++ // The primary button names the step it is on: advancing through the+ // questions, then generating. There is no confirmation page between the last+ // answer and the task — pressing generate writes the brief from the answers+ // and creates it, and the brief is on the task's own page afterwards.+ // One label for the last step, whether or not anything was answered. Naming+ // it for the machinery behind it ("generate") described what the product does+ // rather than what the user gets: either way the press ends with a task.+ const primary = onLastQuestion+ ? { action: onConfirm, label: t('taskIntent.create') }+ : { action: () => setActiveIndex(activeIndex + 1), label: t('taskIntent.next') };++ return (+ <>+ <Flexbox className={styles.head} gap={6}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorTextDescription} icon={Sparkles} size={13} />+ <Text fontSize={12} type={'secondary'}>+ {t('taskIntent.reviewStep')}+ </Text>+ </Flexbox>+ <input+ className={styles.title}+ placeholder={t('createTask.titlePlaceholder')}+ value={title}+ onChange={(e) => onTitleChange(e.target.value)}+ />+ </Flexbox>++ <Flexbox className={styles.body} gap={16}>+ <Text fontSize={13} type={'secondary'}>+ {analysis.summary}+ </Text>++ {showGoalExit && (+ <Flexbox horizontal align={'center'} className={styles.goalCallout} gap={12}>+ <Icon color={cssVar.colorTextSecondary} icon={Target} size={16} />+ <Flexbox flex={1} gap={2}>+ <Text fontSize={13} weight={500}>+ {t('taskIntent.goalCallout.title')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {analysis.kindReason || t('taskIntent.goalCallout.desc')}+ </Text>+ </Flexbox>+ <Button size={'small'} type={'fill'} onClick={onSwitchToGoal}>+ {t('taskIntent.goalCallout.action')}+ </Button>+ </Flexbox>+ )}++ {clarifications.length > 0 && (+ <Tabs+ activeKey={String(activeIndex)}+ className={styles.tabs}+ variant={'square'}+ items={[+ ...clarifications.map((_, index) => ({+ key: String(index),+ label: (+ <Flexbox horizontal align={'center'} gap={6}>+ <Text>{`Q${index + 1}`}</Text>+ {isAnswered(index) && <Icon icon={Check} size={12} />}+ </Flexbox>+ ),+ })),+ ]}+ onChange={(key) => setActiveIndex(Number(key))}+ />+ )}++ {active &&+ (() => {+ const index = activeIndex;+ const options = active.options ?? [];+ // An answer that isn't one of the offered options is the user's own+ // wording, so it belongs in the free-text row rather than leaving+ // every card unselected with the text stranded elsewhere.+ const picked = options.includes(answers[index] ?? '') ? answers[index] : undefined;+ const custom = picked === undefined ? (answers[index] ?? '') : '';++ return (+ <Flexbox gap={10} key={active.question}>+ <Flexbox gap={2}>+ <Text strong>{active.question}</Text>+ {active.impact && (+ <Text fontSize={12} type={'secondary'}>+ {active.impact}+ </Text>+ )}+ </Flexbox>++ <Flexbox gap={4} role={'listbox'}>+ {options.map((option, optionIndex) => (+ <OptionCard+ index={optionIndex + 1}+ key={option}+ label={option}+ selected={picked === option}+ onToggle={() => pickOption(index, option)}+ />+ ))}+ <Flexbox horizontal align={'center'} className={styles.customRow} gap={12}>+ <span className={styles.customIndex}>{options.length + 1}</span>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ placeholder={t('taskIntent.answerPlaceholder')}+ style={{ flex: 1 }}+ value={custom}+ variant={'filled'}+ onChange={(e) => onAnswerChange(index, e.target.value)}+ />+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+ })()}+ </Flexbox>++ <Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>+ <Button icon={ArrowLeft} size={'small'} type={'text'} onClick={onBack}>+ {t('taskIntent.back')}+ </Button>+ <Button+ disabled={isCreating}+ loading={isCreating}+ shape={'round'}+ size={'small'}+ type={'primary'}+ onClick={primary.action}+ >+ {primary.label}+ </Button>+ </Flexbox>+ </>+ );+});++export default TaskIntentReview;diff --git a/src/features/AgentTasks/AgentTaskList/taskIntent.test.ts b/src/features/AgentTasks/AgentTaskList/taskIntent.test.tsnew file mode 100644index 00000000000..850a5963fe4--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/taskIntent.test.ts@@ -0,0 +1,155 @@+import type { TaskIntentAnalysis } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ appendParagraphsToEditorJson,+ buildConfirmedDraft,+ buildGoalSeed,+ preserveOriginalInstruction,+ shouldConfirmIntent,+} from './taskIntent';++const analysis = (patch: Partial<TaskIntentAnalysis> = {}): TaskIntentAnalysis => ({+ clarifications: [],+ confidence: 'high',+ kind: 'task',+ refinedInstruction: 'Fix the typo in the README title.',+ summary: 'Fix a typo.',+ title: 'Fix README typo',+ ...patch,+});++describe('shouldConfirmIntent', () => {+ it('lets an unambiguous single-delivery request through', () => {+ expect(shouldConfirmIntent(analysis())).toBe(false);+ });++ it('stops for a question, a goal, or a reading the model is unsure of', () => {+ expect(shouldConfirmIntent(analysis({ clarifications: [{ question: 'Which repo?' }] }))).toBe(+ true,+ );+ expect(shouldConfirmIntent(analysis({ kind: 'goal' }))).toBe(true);+ expect(shouldConfirmIntent(analysis({ confidence: 'medium' }))).toBe(true);+ });+});++describe('preserveOriginalInstruction', () => {+ it('keeps the user text when the brief expands on it', () => {+ expect(preserveOriginalInstruction('ship v1', 'Ship v1 of the CLI, tagged and released.')).toBe(+ 'ship v1\n\nShip v1 of the CLI, tagged and released.',+ );+ });++ it('does not duplicate text the brief already quotes', () => {+ expect(preserveOriginalInstruction('ship v1', 'Do this: ship v1 — tagged.')).toBe(+ 'Do this: ship v1 — tagged.',+ );+ });++ it('falls back to the original when the brief is empty or identical', () => {+ expect(preserveOriginalInstruction('ship v1', ' ')).toBe('ship v1');+ expect(preserveOriginalInstruction(' ship v1 ', 'ship v1')).toBe('ship v1');+ });+});++const lexicalDoc = (children: unknown[]) => ({ root: { children, type: 'root' } });++const paragraphOf = (text: string) => ({+ children: [{ text, type: 'text' }],+ type: 'paragraph',+});++const fileAttachmentDoc = lexicalDoc([+ paragraphOf('fix the readme typo'),+ { fileUrl: 'https://cdn/spec.pdf', status: 'uploaded', type: 'file' },+]);++const textOf = (json: unknown) =>+ ((json as any).root.children as any[]).flatMap((node) =>+ (node.children ?? []).map((child: any) => child.text),+ );++describe('appendParagraphsToEditorJson', () => {+ it('extends the document without touching what is already in it', () => {+ const result = appendParagraphsToEditorJson(fileAttachmentDoc, ['## Clarifications']);++ expect((result as any).root.children).toHaveLength(3);+ // The file node is exactly the thing a markdown round-trip would drop.+ expect((result as any).root.children[1]).toBe(fileAttachmentDoc.root.children[1]);+ expect(fileAttachmentDoc.root.children).toHaveLength(2);+ });++ it('reports no usable mirror rather than returning one missing the lines', () => {+ // editorData wins over the markdown when a task is rendered, so a stale+ // mirror would show the user a brief the agent never received.+ expect(appendParagraphsToEditorJson({}, ['line'])).toBeUndefined();+ expect(appendParagraphsToEditorJson(undefined, ['line'])).toBeUndefined();+ });++ it('passes the document straight through when there is nothing to add', () => {+ expect(appendParagraphsToEditorJson({}, [])).toEqual({});+ });+});++describe('buildConfirmedDraft', () => {+ const withQuestions = analysis({+ clarifications: [{ question: 'Which repo?' }, { question: 'By when?' }],+ });++ it('appends only the answered questions, to the markdown and the mirror alike', () => {+ const reviewed = lexicalDoc([paragraphOf('fix the readme typo')]);+ const result = buildConfirmedDraft({+ analysis: withQuestions,+ answers: { 0: 'lobehub/lobe-chat', 1: ' ' },+ editorJson: reviewed,+ heading: 'Clarifications',+ instruction: 'fix the readme typo',+ });++ expect(result.instruction).toBe(+ 'fix the readme typo\n\n## Clarifications\n- Which repo? lobehub/lobe-chat',+ );+ expect(result.instruction).not.toContain('By when?');+ expect(textOf(result.editorData)).toEqual([+ 'fix the readme typo',+ '## Clarifications',+ '- Which repo? lobehub/lobe-chat',+ ]);+ });++ it('creates exactly what the user reviewed when every question was skipped', () => {+ const reviewed = lexicalDoc([paragraphOf('fix the readme typo')]);+ const result = buildConfirmedDraft({+ analysis: withQuestions,+ answers: {},+ editorJson: reviewed,+ heading: 'Clarifications',+ instruction: 'edited by hand',+ });++ expect(result.instruction).toBe('edited by hand');+ expect(result.editorData).toBe(reviewed);+ });+});++describe('buildGoalSeed', () => {+ it('carries the answers already given into the goal handoff', () => {+ const seed = buildGoalSeed({+ analysis: analysis({+ clarifications: [{ question: 'Which metric?' }],+ kind: 'goal',+ refinedInstruction: 'Keep the p95 latency under the agreed bar.',+ title: 'Hold p95 latency',+ }),+ answers: { 0: 'p95 API latency' },+ heading: 'Clarifications',+ instruction: 'keep latency low',+ });++ expect(seed.title).toBe('Hold p95 latency');+ // The instruction handed over is the one the user reviewed, not the draft.+ expect(seed.requirement).toBe(+ 'keep latency low\n\n## Clarifications\n- Which metric? p95 API latency',+ );+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/taskIntent.ts b/src/features/AgentTasks/AgentTaskList/taskIntent.tsnew file mode 100644index 00000000000..9377838a147--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/taskIntent.ts@@ -0,0 +1,153 @@+import type { TaskIntentAnalysis } from '@lobechat/types';++/** Answers keyed by the index of the clarification they belong to. */+export type ClarificationAnswers = Record<number, string>;++/**+ * Whether the reading is worth stopping the user for.+ *+ * The composer runs the reader on every submit, so this gate is the whole+ * difference between a helpful confirmation and a tax on every task. It stops+ * only for something the user alone can settle: a question whose answer+ * changes the deliverable, a request that is really a standing goal, or a+ * reading the model itself is not sure of.+ */+export const shouldConfirmIntent = (analysis: TaskIntentAnalysis): boolean =>+ analysis.clarifications.length > 0 || analysis.kind === 'goal' || analysis.confidence !== 'high';++/**+ * The goal flow's rule, applied to tasks: a generated brief may expand on the+ * request but must never replace it, so the user's own words survive verbatim+ * into what the agent reads.+ */+export const preserveOriginalInstruction = (original: string, refined: string): string => {+ const source = original.trim();+ const generated = refined.trim();++ if (!generated || generated === source) return source;+ return generated.includes(source) ? generated : `${source}\n\n${generated}`;+};++/**+ * The questions the user actually answered. An unanswered question is the user+ * declining to narrow the scope, and writing "unanswered" into the brief would+ * read to the agent as a constraint they never stated.+ */+export const answeredClarifications = (+ analysis: TaskIntentAnalysis,+ answers: ClarificationAnswers,+) =>+ analysis.clarifications+ .map((clarification, index) => ({+ answer: answers[index]?.trim() ?? '',+ question: clarification.question,+ }))+ .filter((pair) => pair.answer);++interface LexicalRoot {+ children?: unknown[];+}++const lexicalParagraph = (text: string) => ({+ children: text+ ? [{ detail: 0, format: 0, mode: 'normal', style: '', text, type: 'text', version: 1 }]+ : [],+ direction: null,+ format: '',+ indent: 0,+ textFormat: 0,+ textStyle: '',+ type: 'paragraph',+ version: 1,+});++/**+ * Append plain paragraphs to a serialized Lexical document without touching+ * anything already in it — the only way to extend a draft that carries file or+ * image nodes, which a markdown round-trip would silently drop.+ *+ * Returns `undefined` when there is no document to extend. That is the signal+ * to send no `editorData` at all: the JSON mirror wins over the markdown when+ * a task is rendered, so a mirror that is missing the appended lines is worse+ * than no mirror, which just rebuilds from the markdown.+ */+export const appendParagraphsToEditorJson = (json: unknown, lines: string[]): unknown => {+ if (lines.length === 0) return json;++ const root = (json as { root?: LexicalRoot } | undefined)?.root;+ if (!root || !Array.isArray(root.children)) return undefined;++ return {+ ...(json as object),+ root: { ...root, children: [...root.children, ...lines.map(lexicalParagraph)] },+ };+};++const answersBlock = (pairs: { answer: string; question: string }[], heading: string): string[] => [+ `## ${heading}`,+ ...pairs.map(({ answer, question }) => `- ${question} ${answer}`),+];++/**+ * Fold the answered clarifications into the draft.+ *+ * Only reached when the rewrite could not run: the brief the user gets is then+ * their own text with their own answers under it, and no model prose they+ * never saw.+ *+ * Both fields are extended together: `instruction` is the markdown the agent+ * reads, `editorData` its rich-text mirror, and a mirror that is missing the+ * answers would be what the task page shows.+ *+ * @param heading localized heading for the appended answers block+ */+export const buildConfirmedDraft = ({+ analysis,+ answers,+ editorJson,+ heading,+ instruction,+}: {+ analysis: TaskIntentAnalysis;+ answers: ClarificationAnswers;+ editorJson: unknown;+ heading: string;+ instruction: string;+}): { editorData: unknown; instruction: string } => {+ const pairs = answeredClarifications(analysis, answers);+ if (pairs.length === 0) return { editorData: editorJson, instruction };++ const block = answersBlock(pairs, heading);+ return {+ editorData: appendParagraphsToEditorJson(editorJson, block),+ instruction: `${instruction}\n\n${block.join('\n')}`,+ };+};++/**+ * The requirement seed handed to the goal modal when the user takes the+ * "this is really a goal" exit. Keeps the answers already given so the+ * handoff doesn't ask for them a second time. Markdown only — the goal modal+ * seeds its own editor from text.+ */+export const buildGoalSeed = ({+ analysis,+ answers,+ heading,+ instruction,+}: {+ analysis: TaskIntentAnalysis;+ answers: ClarificationAnswers;+ heading: string;+ instruction: string;+}): { requirement: string; title: string } => {+ const pairs = answeredClarifications(analysis, answers);++ return {+ requirement:+ pairs.length === 0+ ? instruction+ : `${instruction}\n\n${answersBlock(pairs, heading).join('\n')}`,+ title: analysis.title,+ };+};diff --git a/src/features/SelfLearning/CreateDomainPage.tsx b/src/features/SelfLearning/CreateDomainPage.tsxindex 2f3b9786220..1eb479b8eaf 100644--- a/src/features/SelfLearning/CreateDomainPage.tsx+++ b/src/features/SelfLearning/CreateDomainPage.tsx@@ -3,7 +3,7 @@import { Flexbox, Icon, Input, TextArea } from '@lobehub/ui';import { ActionIcon, Button, Popover, Text, toast } from '@lobehub/ui/base-ui';import { Divider } from 'antd';-import { createGlobalStyle, createStaticStyles, cssVar } from 'antd-style';+import { createStaticStyles, cssVar } from 'antd-style';import {AnchorIcon,ArrowLeftIcon,@@ -18,6 +18,7 @@ import { useTranslation } from 'react-i18next';import { Link, useParams } from 'react-router';import urlJoin from 'url-join';+import GeneratingBorder from '@/components/GeneratingBorder';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import AgentBreadcrumb from '@/features/AgentBreadcrumb';import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';@@ -118,67 +119,6 @@ const styles = createStaticStyles(({ css }) => ({overflow: hidden;height: 22px;`,- // Wraps the brief textarea so the loading state can draw the same flowing- // border the goal creator uses — the shell owns the ring, not the input.- inputShell: css`- position: relative;- border-radius: 8px;- `,- // Only while generating: a conic-gradient ring rotated by the animated- // --domain-border-angle, masked to a 2px edge so the textarea reads as lit.- // `overflow: hidden` lives here, not on the resting shell, so the outlined- // textarea's focus glow isn't clipped when the user is typing.- inputShellLoading: css`- overflow: hidden;-- &::after {- pointer-events: none;- content: '';-- position: absolute;- z-index: 1;- inset: 0;-- padding: 2px;- border-radius: inherit;-- background: conic-gradient(- from var(--domain-border-angle),- ${cssVar.colorBorderSecondary} 0deg 210deg,- #ff3d8d 238deg,- #8b5cf6 258deg,- #00c8ff 278deg,- #22e6a8 298deg,- #ffd43b 318deg,- #ff6b35 338deg,- ${cssVar.colorBorderSecondary} 360deg- );-- mask:- linear-gradient(#fff 0 0) content-box,- linear-gradient(#fff 0 0);-- animation: domain-input-flow 1.8s linear infinite;-- mask-composite: exclude;- }-- @keyframes domain-input-flow {- from {- --domain-border-angle: 0deg;- }-- to {- --domain-border-angle: 360deg;- }- }-- @media (prefers-reduced-motion: reduce) {- &::after {- animation: none;- }- }- `,itemRow: css`display: grid;grid-template-columns: 32px minmax(0, 1fr) 28px;@@ -238,16 +178,6 @@ const styles = createStaticStyles(({ css }) => ({`,}));-// A registered custom property is what lets the conic gradient's angle animate-// at all — a plain `--domain-border-angle` is an un-typed string CSS can't tween.-const DomainBorderFlowStyle = createGlobalStyle`- @property --domain-border-angle {- inherits: false;- initial-value: 0deg;- syntax: '<angle>';- }-`;-export const formatRemainingTime = (seconds: number) => {const minutes = Math.floor(seconds / 60);const rest = seconds % 60;@@ -465,7 +395,6 @@ const CreateDomainPage = memo(() => {return (<Flexbox height={'100%'} width={'100%'}>- <DomainBorderFlowStyle /><NavHeaderstyles={{ left: { paddingInlineStart: 24 } }}left={@@ -511,9 +440,7 @@ const CreateDomainPage = memo(() => {<Text fontSize={12} type={'secondary'}>{t('create.briefHelp')}</Text>- <div- className={`${styles.inputShell} ${step === 'preparing' ? styles.inputShellLoading : ''}`}- >+ <GeneratingBorder generating={step === 'preparing'}><TextAreaautoFocusautoSize={{ maxRows: 10, minRows: 5 }}@@ -523,7 +450,7 @@ const CreateDomainPage = memo(() => {variant={step === 'preparing' ? 'borderless' : 'outlined'}onChange={(e) => setBrief(e.target.value)}/>- </div>+ </GeneratingBorder>{step === 'preparing' ? (<Flexboxhorizontaldiff --git a/src/services/task.ts b/src/services/task.tsindex fdbe71b9d8a..0848fd0ee9a 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -1,4 +1,10 @@-import type { CheckpointConfig, TaskAutomationMode, TaskStatus } from '@lobechat/types';+import type {+ CheckpointConfig,+ TaskAutomationMode,+ TaskInstructionSynthesis,+ TaskIntentAnalysis,+ TaskStatus,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -63,6 +69,27 @@ class TaskService {// ── Mutations ──+ /**+ * Read a composer draft and report what it means. A mutation on the wire+ * (it spends a model call), but it creates nothing — the caller decides+ * whether to act on the reading.+ */+ analyzeIntent = async (params: {+ context?: string;+ instruction: string;+ }): Promise<TaskIntentAnalysis> => lambdaClient.task.analyzeIntent.mutate(params);++ /**+ * Rewrite the confirmed draft into the brief that gets executed, with the+ * user's answers folded in. Also a mutation on the wire, and also creates+ * nothing.+ */+ synthesizeInstruction = async (params: {+ answers: { answer: string; question: string }[];+ context?: string;+ instruction: string;+ }): Promise<TaskInstructionSynthesis> => lambdaClient.task.synthesizeInstruction.mutate(params);+create = async (params: {assigneeAgentId?: string;assigneeUserId?: string;