🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): structured acceptance criteria, goal chat with context injection, liveness heartbeats and process-control polish (#19050)
Arvin Xuc3aaad989df9
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex ba5f04d9c34..b3fa7af506d 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -326,6 +326,26 @@ list items, table rows, fenced code, and literal transcript output, which are exthe places the break is the content. Never run a proseWrap formatter over files under`assets/`.+### L-E20 — Seeding an entity below its composing layer, then publishing its page as evidence++**Wrong approach:** build a goal/task fixture by calling the service or TRPC endpoint+directly with minimal fields, skipping the client-side composer the real creation flows+run (e.g. `buildGoalRequirement` folding acceptance criteria into the requirement+prose), then screenshot the entity page as feature evidence.++**Why it fails:** the page renders the under-composed data faithfully — a requirement+reduced to one bare sentence — and the reviewer reads that as a code regression in an+untouched block ("这块怎么被改了?canary 才是对的"). A whole feedback round gets spent+disproving a defect that only exists in the fixture. The diff shows nothing because+nothing changed.++**Correct approach:** drive fixtures through the same composition the product uses —+either the real creation surface, or the same shaping helpers the callers invoke — and+before publishing an entity page as evidence, compare its populated fields against a+canary-created sibling. When a service accepts decomposed inputs, prefer adding a+server-side guard that re-derives the composed field, so no API caller (fixtures+included) can create the under-composed shape at all.+## Product and interaction contracts### L-D1 — Rebuilding a canonical surface from visual impressiondiff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 0c529bb735c..11933238af5 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -252,6 +252,40 @@ completion whose `content` is parsed as the object. A text-only evidence check iAssert the round from three places together: the toast copy (a MutationObserver on`document.body`), the rows' `status`/`action`/`created_at`, and the card count.+#### Structured generation crashes on the deepseek provider path — stub via openai instead++**Situation:** driving a server-side `generateObject` scenario (e.g. `verify_plan_gen`)+through `llm-stub.mjs` when the resolved model config is `deepseek` (the OSS default).++**Doesn't work:** pointing the deepseek provider's keyVaults at the stub. The chat+turn streams fine, but `generateObject` fails with `TypeError: Cannot read properties+of undefined (reading '0')` (visible in `llm_generation_tracing.error_detail`), and+the caller silently falls back (verify plan gen → holistic single check), which reads+as "my feature didn't run".++**Works:** route the generation through the openai protocol path — e.g. point the+resolver's agent (for verify: `update agents set model='gpt-5.6-luna', provider='openai'+where slug='verify-agent'`) at the stubbed openai provider. The server-side openai+provider calls `/v1/responses`, which the stub answers correctly for `stream:false`+structured generation (`llm_generation_tracing.success=t` is the confirmation probe).++#### Forcing the goal frontier 失联 state needs >15 min, not the server's 5++**Situation:** A/B-forcing the goal page's 失联 (lost-heartbeat) banner by backdating+`goal_nodes.updated_at` / `agent_operations.updated_at` with SQL.++**Doesn't work:** backdating by ~10 minutes because the server reclaim default+(`resolveOperationLeaseTimeout`) is 5 minutes. The frontier still shows 运行中: the+client view model has its own `DEFAULT_LEASE_TIMEOUT_MS = 15 min` and only honors+`goal.config.recovery.operationLeaseTimeoutMs` when the goal sets one.++**Works:** backdate past the client's window (25 min is comfortable), or create the+goal with an explicit `--operation-lease-timeout-ms`. Liveness = the newer of the+node row and `runHeartbeats` (the running operation's `updated_at` served by+`goal.graph`), so the A/B is: node stale + op fresh → 运行中; both stale → 失联.+Restore the forced rows (node/task/task_topics/operation status + timestamps) after+capturing.+#### A CLI-created topic has no trigger/status and is filtered out of the Agent paged view**Situation:** building a topic fixture with `lh topic create`, writing fields such as@@ -1960,6 +1994,31 @@ domain and is unaffected, so this is purely a local verification-environment gatnot a product defect — do not report it as a bug, and do not work around it byswitching to inline base64, which would verify a path the product never takes.+#### Real web-search evidence needs local SearXNG — the on-disk search1api keys are dead++**Situation:** a check needs the product's real web-search pipeline (builtin+`lobe-web-browsing____search` executing an actual HTTP search and rendering result+cards), e.g. "ask the agent a weather question".++**Doesn't work:** `SEARCH_PROVIDERS=search1api` with any `SEARCH1API_SEARCH_API_KEY`+found in sibling repo `.env` files — they all return 401 (verify with a direct+`curl api.search1api.com/search` before blaming the product). Keyless fallbacks+don't exist: with no `SEARCH_PROVIDERS` the impl list is empty and every search+returns "all configured providers returned errors"; public SearXNG instances+rate-limit (429) or ship JSON-disabled (HTML back).++**Works:** run a local SearXNG:+`docker run -d -p 8888:8080 -v <dir>:/etc/searxng searxng/searxng` with a+`settings.yml` of `use_default_settings: true`, `server.limiter: false`, and+`search.formats: [html, json]`, then start the dev server with+`SEARCH_PROVIDERS=searxng SEARXNG_URL=http://localhost:8888`. It aggregates real+engines, so the whole product path (server search impl → result cards → tool+message persistence) is genuine. English queries return results more reliably+than Chinese ones. One trap when the model is a tool_call-emitting stub AND a+synthetic context injector is active (e.g. `getGoalContext`): "last message is a+tool result → answer" fires on the injected pair and skips the search — key the+stub's answer-mode off the NAME of the last `function_call` instead.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) — all historicaldiff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 865799f30da..6d0770af67e 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -123,6 +123,16 @@ export const goalRouter = router({.optional(),maxRounds: z.number().int().positive().optional(),maxTotalCost: z.number().positive().optional(),+/** Structured acceptance criteria — persisted rows that gate the terminal acceptance. */+ criteria: z+ .array(+ z.object({+ description: z.string().optional(),+ instruction: z.string().optional(),+ title: z.string().min(1),+ }),+ )+ .optional(),problemDescription: z.string().optional(),projectId: z.string().optional(),requirement: z.string().optional(),@@ -272,6 +282,18 @@ export const goalRouter = router({}}),+ /** Rebind which persisted verify criteria gate this goal's terminal acceptance. */+ setAcceptanceCriteria: goalWriteProcedure+ .input(idInput.extend({ criteriaIds: z.array(z.string()) }))+ .mutation(async ({ ctx, input }) => {+ try {+ await ctx.goalService.setAcceptanceCriteria(input.id, input.criteriaIds);+ return { success: true };+ } catch (error) {+ mapGoalError(error, 'setAcceptanceCriteria');+ }+ }),+setBudget: goalWriteProcedure.input(idInput.extend({diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex bfc3e17e5e2..d998e3f7c92 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -21,6 +21,7 @@ import {wsCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentOperationModel } from '@/database/models/agentOperation';+import { DocumentModel } from '@/database/models/document';import { LlmGenerationTracingModel } from '@/database/models/llmGenerationTracing';import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';import { VerifyCriterionModel } from '@/database/models/verifyCriterion';@@ -270,6 +271,7 @@ const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =return opts.next({ctx: {criterionModel: new VerifyCriterionModel(ctx.serverDB, ctx.userId, workspaceId),+ documentModel: new DocumentModel(ctx.serverDB, ctx.userId, workspaceId),evidenceModel: new VerifyEvidenceModel(ctx.serverDB, ctx.userId, workspaceId),executorService: new VerifyExecutorService(ctx.serverDB, ctx.userId, workspaceId),tracingModel: new LlmGenerationTracingModel(ctx.serverDB, ctx.userId, workspaceId),@@ -360,6 +362,36 @@ export const verifyRouter = router({.input(z.object({ ids: z.array(z.string()) })).mutation(async ({ ctx, input }) => ctx.criterionModel.forkRubricCriteria(input.ids)),+ /**+ * Resolve a specific criteria id list (e.g. the ones bound to a goal), in+ * input order. Each row carries `instruction` resolved from its linked+ * document — the judge rule must be inspectable and editable where the+ * criteria are shown, not an invisible value edits would silently replace.+ */+ getCriteria: verifyProcedure+ .input(z.object({ ids: z.array(z.string()) }))+ .query(async ({ ctx, input }) => {+ if (input.ids.length === 0) return [];+ const rows = await ctx.criterionModel.findByIds(input.ids);+ const documentIds = [+ ...new Set(rows.flatMap((row) => (row.documentId ? [row.documentId] : []))),+ ];+ const documents = await Promise.all(documentIds.map((id) => ctx.documentModel.findById(id)));+ const contentByDocId = new Map(+ documents.flatMap((doc) => (doc ? [[doc.id, doc.content ?? undefined] as const] : [])),+ );+ const byId = new Map(+ rows.map((row) => [+ row.id,+ {+ ...row,+ instruction: row.documentId ? contentByDocId.get(row.documentId) : undefined,+ },+ ]),+ );+ return input.ids.map((id) => byId.get(id)).filter(Boolean);+ }),+listCriteria: verifyProcedure.query(async ({ ctx }) => ctx.criterionModel.query()),updateCriterion: verifyWriteProcedurediff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 000e51d19bb..652c0e26120 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -8,7 +8,11 @@ import { buildExpertiseContextSnapshot, SkillEngine } from '@lobechat/context-enimport type { LobeChatDatabase } from '@lobechat/database';import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';import type { LobeAgentAgencyConfig, WorkingDirConfig, WorkspaceInitResult } from '@lobechat/types';-import { getActivePluginIds, getWorkingDirEffectivePath } from '@lobechat/types';+import {+ buildGoalOverviewContext,+ getActivePluginIds,+ getWorkingDirEffectivePath,+} from '@lobechat/types';import debug from 'debug';import type { AgentModel } from '@/database/models/agent';@@ -16,6 +20,7 @@ import { AgentSkillModel } from '@/database/models/agentSkill';import { AiModelModel } from '@/database/models/aiModel';import { DeviceModel } from '@/database/models/device';import { ExpertiseModel } from '@/database/models/expertise';+import { GoalGraphModel } from '@/database/models/goalGraph';import type { MessageModel } from '@/database/models/message';import type { TopicModel } from '@/database/models/topic';import { UserPersonaModel } from '@/database/models/userMemory/persona';@@ -720,6 +725,27 @@ export const prepareOperation = async (};}+ // Goal-page side conversation: mirror the client executor's injection so+ // server-run agents also answer progress questions from the live graph.+ if (appContext?.viewedGoal?.goalId) {+ try {+ const snapshot = await new GoalGraphModel(deps.db, deps.userId, deps.workspaceId).getGraph(+ appContext.viewedGoal.goalId,+ );+ if (snapshot) {+ initialContext = {+ ...initialContext,+ initialContext: {+ ...initialContext.initialContext,+ goalOverview: buildGoalOverviewContext(snapshot),+ },+ };+ }+ } catch (error) {+ log('execAgent: failed to build goal overview context: %O', error);+ }+ }+// Persist the @-mentioned agents into the runtime initialContext so the// context engine injects the delegation context on every step (survives the// queue-mode dispatch). `callLlm` bridges this into `agentManagementContext`diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex 51c3bc773b0..35853d4b647 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -4,9 +4,10 @@ import type {GoalTickBranch,GoalTickOutcome,} from '@lobechat/agent-tracing';+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';import type { GoalGraphNode, GoalGraphSnapshot, TaskItem } from '@lobechat/types';-export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';+export { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';/** Reason strings the recovery paths key off, written by the settle path. */export const LEASE_EXPIRED_ERROR = 'Goal Work operation lease expired.';@@ -106,7 +107,7 @@ export const frontierNeedsBudget = (});export interface GoalMoveInput {- /** Required only when {@link needsBudget} says the branch could dispatch. */+ /** Required only when {@link needsBudget} says the branch could dispatch or recover. */budget?: GoalBudgetState;/** How many of this goal's Tasks may be in flight at once. */concurrency: number;@@ -388,6 +389,18 @@ const decideForTask = (task.status === 'canceled' ||(task.status === 'paused' && task.error)) {+ if (+ budget?.deadlinePassed &&+ task.status === 'paused' &&+ (task.error === LEASE_EXPIRED_ERROR || task.error === VERIFICATION_FAILED_ERROR)+ ) {+ return {+ ...base,+ branch: 'budget_exhausted',+ message: `Deadline passed (${graph.goal.config?.schedule?.deadline ?? 'unknown'}); no new Work will be dispatched`,+ outcome: 'no_progress',+ };+ }if (task.status === 'paused' && task.error === LEASE_EXPIRED_ERROR) {if (!capacity) return 'needs-capacity';return {@@ -430,6 +443,15 @@ const decideForTask = (};}+ if (budget?.deadlinePassed) {+ return {+ ...base,+ branch: 'budget_exhausted',+ message: `Deadline passed (${graph.goal.config?.schedule?.deadline ?? 'unknown'}); no new Work will be dispatched`,+ outcome: 'no_progress',+ };+ }+if (budget?.roundLimitReached || budget?.costLimitReached) {return {...base,diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 75f6350972f..6982647d291 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -29,7 +29,9 @@ import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimport { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';+import { VerifyPlanGeneratorService } from '../verify/planGenerator';import { GoalCriteriaGeneratorService } from './criteriaGenerator';+import { LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR } from './decideNextMove';import { GoalService } from './index';import type { GoalTickObservation } from './traceObservation';@@ -59,6 +61,64 @@ afterEach(async () => {});describe('GoalService', () => {+ it('persists structured criteria on create and records their ids on the goal config', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ criteria: [+ { description: 'Runs end to end locally', title: 'Local run works' },+ { instruction: 'Check README covers install and run', title: 'Docs are complete' },+ ],+ title: 'Structured goal',+ work: ['Only work'],+ });++ const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];+ expect(criteriaIds).toHaveLength(2);++ const rows = await serverDB.query.verifyCriteria.findMany();+ const byId = new Map(rows.map((row) => [row.id, row]));+ expect(byId.get(criteriaIds[0])?.title).toBe('Local run works');+ expect(byId.get(criteriaIds[1])?.title).toBe('Docs are complete');+ // the how-to-judge instruction landed in a linked document+ expect(byId.get(criteriaIds[1])?.documentId).toBeTruthy();+ });++ it('rebinding criteria also updates the dispatched terminal acceptance task', async () => {+ // Editing the standard after the terminal Goal-acceptance Work exists must+ // not leave that Work's Acceptance gating on the stale id list.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ criteria: [{ title: 'Original criterion' }],+ requirement: 'Deliver with evidence',+ title: 'Rebind criteria goal',+ work: ['Only work'],+ });++ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id); // synthesize finding+ await service.tick(graph.goal.id); // create acceptance work+ const acceptanceTaskCreated = await service.tick(graph.goal.id); // dispatch it+ expect(acceptanceTaskCreated.taskId).toBeDefined();++ const [replacementId] = await new VerifyPlanGeneratorService(+ serverDB,+ userId,+ ).createCriteriaFromDrafts([+ { onFail: 'manual', required: true, title: 'Replacement criterion', verifierType: 'agent' },+ ]);+ await service.setAcceptanceCriteria(graph.goal.id, [replacementId]);++ const goal = (await service.graph(graph.goal.id)).goal;+ expect(goal.config?.acceptance?.criteriaIds).toEqual([replacementId]);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ acceptanceTaskCreated.taskId!,+ );+ expect(acceptance?.config?.verifyCriteriaIds).toEqual([replacementId]);+ });+it('creates only one responsible task when ticks race on the same work node', async () => {const service = new GoalService(serverDB, userId);const graph = await service.create({ title: 'Concurrent goal', work: ['Single owner work'] });@@ -116,6 +176,31 @@ describe('GoalService', () => {expect(runSpy).toHaveBeenCalledTimes(1);});+ it.each([LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR])(+ 'does not dispatch recovery for an overdue goal with %s',+ async (error) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },+ title: `Overdue recovery ${error}`,+ work: ['Do not retry'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error });+ runSpy.mockClear();++ const stopped = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ expect(stopped).toMatchObject({ outcome: 'no_progress' });+ expect(stopped.message).toContain('Deadline passed');+ },+ );+it('hands back a dispatch claim whose worker died before the run existed', async () => {// The claim is taken just before `runTask` creates the topic. If the worker// dies in that sliver the task is `running` with no operation to reclaim,diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 30fdcac9205..5a8fc1a3628 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -1,4 +1,5 @@import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';import type {GoalConfig,@@ -30,6 +31,7 @@ import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimport { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { AcceptanceService } from '../verify/acceptanceService';+import { VerifyPlanGeneratorService } from '../verify/planGenerator';import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from './criteriaGenerator';import {decideNextMove,@@ -70,6 +72,14 @@ export interface CreateGoalGraphInput {* on an agent's page sets that, but the author is still the person.*/createdByAgentId?: string;+ /**+ * Structured acceptance criteria. Persisted as `verify_criteria` rows and+ * recorded on `config.acceptance.criteriaIds`, so the goal page can show and+ * edit them and the terminal Goal-acceptance Work verifies against exactly+ * these checks. Callers still fold the same criteria into `requirement`+ * prose — that text remains what every Work's execution context reads.+ */+ criteria?: Array<{ description?: string; instruction?: string; title: string }>;maxRounds?: number;maxTotalCost?: number;/**@@ -159,13 +169,48 @@ export class GoalService {).findManageableById(input.projectId);if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });}+ // Persist the structured acceptance criteria first: their ids ride on the+ // goal config so the page can edit them and the terminal acceptance Work+ // is gated on exactly these checks (not an AI re-derivation of the prose).+ let config = input.config;+ let requirement = input.requirement;+ if (input.criteria?.length) {+ // The prose requirement must keep carrying the full standard (the goal+ // page's 什么算完成 block and every Work's execution context read it).+ // Callers normally compose it via `buildGoalRequirement`; guard API+ // callers that pass criteria with a bare requirement.+ const carriesCriteria = input.criteria.every((item) =>+ input.requirement?.includes(item.title),+ );+ if (!carriesCriteria) {+ requirement = buildGoalRequirement(input.title, input.criteria, input.requirement);+ }+ }+ if (input.criteria?.length) {+ const criteriaIds = await new VerifyPlanGeneratorService(+ this.db,+ this.userId,+ this.workspaceId,+ ).createCriteriaFromDrafts(+ input.criteria.map((item) => ({+ description: item.description,+ instruction: item.instruction,+ onFail: 'manual',+ required: true,+ title: item.title,+ verifierType: 'agent',+ })),+ );+ config = { ...config, acceptance: { criteriaIds } };+ }+const goal = await this.goalModel.create({agentId: input.agentId,- config: input.config,+ config,maxRounds: input.maxRounds,maxTotalCost: input.maxTotalCost,projectId: input.projectId,- requirement: input.requirement,+ requirement,subjectType: 'standalone',title: input.title,});@@ -202,7 +247,94 @@ export class GoalService {return (await this.graphModel.getGraph(goal.id))!;};- graph = async (goalId: string) => this.requireGraph(goalId);+ /**+ * Replace the goal's structured acceptance criteria id list (goal-page+ * editing). The criteria rows themselves are edited through the verify+ * criteria endpoints; this only rebinds which of them gate the goal.+ */+ setAcceptanceCriteria = async (goalId: string, criteriaIds: string[]) => {+ const goal = await this.goalModel.findById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ await this.goalModel.update(goalId, {+ config: { ...goal.config, acceptance: { criteriaIds } },+ });++ // A terminal Goal-acceptance Work may already be dispatched — its+ // Acceptance row snapshotted the previous id list. Rebind it too, or the+ // page would present the new criteria as gates while the verifier keeps+ // materializing plans from the stale list. A verify round already+ // materialized for an in-flight run stays as-is (rounds are immutable+ // snapshots); every later run instantiates from the updated config.+ const graph = await this.graphModel.getGraph(goalId);+ const terminalTaskId = graph?.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && node.taskId,+ )?.taskId;+ if (!terminalTaskId) return;++ const acceptance = await this.acceptanceService.acceptanceModel.findBySubject(+ 'task',+ terminalTaskId,+ );+ if (!acceptance || acceptance.status === 'accepted') return;+ await this.acceptanceService.acceptanceModel.update(acceptance.id, {+ config: {+ ...acceptance.config,+ ...(criteriaIds.length > 0+ ? { verifyCriteriaIds: criteriaIds }+ : { verifyCriteriaIds: undefined }),+ },+ });+ };++ graph = async (goalId: string) => {+ const graph = await this.requireGraph(goalId);+ return { ...graph, runHeartbeats: await this.collectRunHeartbeats(graph) };+ };++ /**+ * Live heartbeat per active task node: the `agent_operations.updatedAt` of+ * the run behind it. The runtime refreshes that lease every ~90s while+ * `goal_nodes.updatedAt` only moves on observations / status changes, so a+ * client judging liveness from the node row alone would cry "lost" over any+ * long quiet stretch (a big tool call, the verify stage) the reclaim path+ * considers perfectly healthy.+ */+ private collectRunHeartbeats = async (+ graph: GoalGraphSnapshot,+ ): Promise<Record<string, Date> | undefined> => {+ const activeTasks = graph.nodes.filter(+ (node): node is GoalGraphNode & { taskId: string } =>+ node.kind === 'task' && node.status === 'active' && !!node.taskId,+ );+ if (activeTasks.length === 0) return undefined;++ const nodeByTaskId = new Map(activeTasks.map((node) => [node.taskId, node.id]));+ const running = await this.taskTopicModel.findRunningByTaskIds(+ activeTasks.map((n) => n.taskId),+ );++ // One batched read: the graph polls every few seconds per open client, so+ // a per-topic operation lookup would scale queries with task concurrency.+ const operationIds = [+ ...new Set(running.flatMap((topic) => (topic.operationId ? [topic.operationId] : []))),+ ];+ const operations = await new AgentOperationModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findByIds(operationIds);+ const operationById = new Map(operations.map((operation) => [operation.id, operation]));++ const heartbeats: Record<string, Date> = {};+ for (const topic of running) {+ const nodeId = topic.taskId ? nodeByTaskId.get(topic.taskId) : undefined;+ if (!nodeId || !topic.operationId || heartbeats[nodeId]) continue;+ const updatedAt = operationById.get(topic.operationId)?.updatedAt;+ if (updatedAt) heartbeats[nodeId] = updatedAt;+ }++ return Object.keys(heartbeats).length > 0 ? heartbeats : undefined;+ };/** Current lifecycle status, without paying for the whole graph. */status = async (goalId: string): Promise<GoalStatus | undefined> =>@@ -308,6 +440,11 @@ export class GoalService {* Rounds are counted across every Work Task in the graph, not per Work — the* budget is the goal's, so `setBudget` has to read it exactly the way the* coordinator does or raising a budget would not reliably unstick a goal.+ *+ * The calendar-time budget (schedule.deadline) is evaluated in the same+ * shape: time is the long-horizon budget unit the attempt/round/dollar trio+ * cannot express, and a goal whose deadline passed must stop the same way a+ * goal out of money does.*/private evaluateBudget = async (goal: GoalItem, graph: GoalGraphSnapshot) => {const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));@@ -727,8 +864,19 @@ export class GoalService {name: frontier.title,projectId: graph.goal.projectId ?? undefined,});+ // The terminal Goal-acceptance Work is gated on the goal's structured+ // criteria when it has them: the verify plan materializes exactly those+ // rows (deterministic checklist) instead of AI-deriving checks from the+ // requirement prose. Ordinary Work keeps the prose-scoped contract.+ const goalCriteriaIds =+ frontier.title === GOAL_ACCEPTANCE_TASK_TITLE+ ? graph.goal.config?.acceptance?.criteriaIds+ : undefined;const acceptance = await this.acceptanceService.ensureForSubject('task', task.id, {- config: { enabled: true },+ config: {+ enabled: true,+ ...(goalCriteriaIds?.length ? { verifyCriteriaIds: goalCriteriaIds } : {}),+ },requirement: this.buildTaskAcceptanceRequirement(graph,frontier.title,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts b/apps/server/src/services/toolExecution/serverRuntimes/goal.tsindex 30efd1b3ffc..6d411269d51 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts@@ -54,6 +54,9 @@ export const goalRuntime: ServerRuntimeRegistration = {// `maxIterations` caps attempts on one Work; it is deliberately not// passed as `maxRounds`, which counts runs across every Work in the// graph and would strand later tasks that have not run at all.+ // Structured criteria persist alongside the prose requirement so the+ // goal page can edit them and the terminal acceptance runs exactly them.+ criteria: drafts,maxTotalCost: args.maxTotalCost ?? undefined,// No seed work: the coordinator plans the decomposition on first// advance, so a complex ask becomes several explorable directionsdiff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.tsindex 47be517e7f5..9fe87f71afb 100644--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ensureForOperation: vi.fn(),generateDraftPlan: vi.fn(),operationFindById: vi.fn(),+ resolveModelConfig: vi.fn(),runFindByOperation: vi.fn(),setMetadata: vi.fn(),setPlan: vi.fn(),@@ -38,6 +39,10 @@ vi.mock('../taskAcceptance', () => ({resolveTaskAcceptance: mocks.taskAcceptanceResolve,}));+vi.mock('../modelConfig', () => ({+ resolveVerifyModelConfig: mocks.resolveModelConfig,+}));+vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(() => ({findById: mocks.taskFindById,@@ -108,6 +113,60 @@ describe('Verify acceptance lifecycle', () => {expect(mocks.generateDraftPlan).not.toHaveBeenCalled();});+ it('AI-decomposes an undecomposed requirement into named criteria, holistic as fallback', async () => {+ mocks.taskAcceptanceResolve.mockResolvedValue({+ acceptance: { id: 'acceptance-1' },+ config: { enabled: true, verifierAgentId: 'verifier-1' },+ requirement: 'Deliver a runnable repro under ~/WikiSkill-Repro',+ });+ mocks.taskFindById.mockResolvedValue({ instruction: 'Build the repro', name: 'Repro' });+ mocks.resolveModelConfig.mockResolvedValue({ model: 'model-1', provider: 'provider-1' });+ mocks.runFindByOperation+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: 'run-1', plan });++ await instantiateVerifyPlanOnStart(db, 'user-1', {+ operationId: 'operation-1',+ taskId: 'task-1',+ });++ expect(mocks.resolveModelConfig).toHaveBeenCalledWith(+ db,+ 'user-1',+ { verifierAgentId: 'verifier-1' },+ undefined,+ );+ expect(mocks.generateDraftPlan).toHaveBeenCalledWith(+ expect.objectContaining({+ context: 'Deliver a runnable repro under ~/WikiSkill-Repro',+ enableAiGeneration: true,+ holisticFallback: true,+ modelConfig: { model: 'model-1', provider: 'provider-1' },+ }),+ );+ });++ it('does not spend an AI call when the task already picked its criteria', async () => {+ mocks.taskAcceptanceResolve.mockResolvedValue({+ acceptance: { id: 'acceptance-1' },+ config: { enabled: true, verifyRubricId: 'rubric-1' },+ });+ mocks.taskFindById.mockResolvedValue({ name: 'Repro' });+ mocks.runFindByOperation+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: 'run-1', plan });++ await instantiateVerifyPlanOnStart(db, 'user-1', {+ operationId: 'operation-1',+ taskId: 'task-1',+ });++ expect(mocks.resolveModelConfig).not.toHaveBeenCalled();+ expect(mocks.generateDraftPlan).toHaveBeenCalledWith(+ expect.objectContaining({ enableAiGeneration: false, holisticFallback: false }),+ );+ });+it('attaches an auto-repair verify run as the next round of the same acceptance', async () => {mocks.operationFindById.mockResolvedValue({ parentOperationId: null });mocks.agentExec.mockResolvedValue({ operationId: 'repair-operation' });diff --git a/apps/server/src/services/verify/planGenerator.ts b/apps/server/src/services/verify/planGenerator.tsindex 9bf5646379c..eff248aed00 100644--- a/apps/server/src/services/verify/planGenerator.ts+++ b/apps/server/src/services/verify/planGenerator.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { TRACING_SCENARIOS, VERIFY_INSTRUCTION_FILE_TYPE } from '@lobechat/const';-import { isProgrammaticTestCheck } from '@lobechat/const/verify';+import { HOLISTIC_CHECK_TITLE, isProgrammaticTestCheck } from '@lobechat/const/verify';import type { TracingOptions } from '@lobechat/llm-generation-tracing';import {chainVerifyPlan,@@ -89,7 +89,7 @@ const buildHolisticAgentItem = (requirement?: string, goal?: string): VerifyChec// rather than the operation-level auto-repair loop.onFail: 'manual',required: true,- title: 'Task delivery acceptance',+ title: HOLISTIC_CHECK_TITLE,verifierConfig: {},verifierType: 'agent',};diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.tsindex 9cc5ee705db..eb9426f8bb4 100644--- a/apps/server/src/services/verify/planInstantiation.ts+++ b/apps/server/src/services/verify/planInstantiation.ts@@ -5,6 +5,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';import { AcceptanceService } from './acceptanceService';+import { resolveVerifyModelConfig } from './modelConfig';import { VerifyPlanGeneratorService } from './planGenerator';import { resolveTaskAcceptance } from './taskAcceptance';@@ -21,9 +22,12 @@ export interface InstantiateVerifyPlanParams {** Without this, a task's Acceptance policy (rubric / criteria) is never turned* into a plan, so verify silently no-ops. We resolve the Task's Acceptance and- * materialize the rubric + ad-hoc criteria into a- * plan (no AI generation — the task already picked its criteria), and confirm it- * immediately (task scenario doesn't show a "confirm plan" step).+ * materialize the rubric + ad-hoc criteria into a plan (no AI generation there+ * — the task already picked its criteria), and confirm it immediately (task+ * scenario doesn't show a "confirm plan" step). Only the undecomposed path+ * spends an AI call: the acceptance requirement is split into named criteria so+ * the checklist shows distinguishable items, with the single holistic check as+ * the fallback when generation fails.** Fire-and-forget + idempotent: never throws (verify must not affect the run),* and skips when a plan already exists (recordStart can re-fire).@@ -63,12 +67,28 @@ export const instantiateVerifyPlanOnStart = async (const goal = task?.instruction ?? task?.name ?? '';const planGenerator = new VerifyPlanGeneratorService(db, userId, workspaceId);+ // Undecomposed acceptance (goal-dispatched Work, one-sentence requirement):+ // spend one generation call splitting the requirement into named criteria,+ // so the checklist reads as distinguishable items instead of one generic+ // "Task delivery acceptance" row.+ const modelConfig = holistic+ ? await resolveVerifyModelConfig(+ db,+ userId,+ { verifierAgentId: verifyConfig.verifierAgentId },+ workspaceId,+ )+ : undefined;await planGenerator.generateDraftPlan({- // No AI proposal — the task's configured rubric/criteria are the plan.- enableAiGeneration: false,+ // Ground the generated criteria in the acceptance text, not just the title.+ context: requirement,+ // Configured rubric/criteria ARE the plan — no AI proposal on that path.+ enableAiGeneration: holistic,goal,- // Fall back to a single agent-type holistic check when nothing decomposed.+ // Still fall back to the single agent-type holistic check when the+ // generation fails or returns nothing, so verify runs either way.holisticFallback: holistic,+ modelConfig,operationId: params.operationId,requirement,verifyCriteriaIds: verifyConfig.verifyCriteriaIds,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 345a7d8ad17..1ac4656aff6 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -387,6 +387,22 @@"globalApproval.subtitle": "Waiting for your approval","globalApproval.title": "Approval needed","globalApproval.userRequestLabel": "Request",+ "goalAcceptance.add": "Add criterion",+ "goalAcceptance.edit": "Edit",+ "goalAcceptance.empty": "No criteria yet — add the outcomes the final acceptance should check.",+ "goalAcceptance.form.descriptionPlaceholder": "What this criterion covers (optional)",+ "goalAcceptance.form.instructionPlaceholder": "How to judge — what evidence makes this pass or fail (optional)",+ "goalAcceptance.form.titlePlaceholder": "Criterion, stated as an outcome",+ "goalAcceptance.gateHint": "The final goal acceptance checks each of these",+ "goalAcceptance.judgePrefix": "How to judge: ",+ "goalAcceptance.remove": "Remove",+ "goalAcceptance.removeConfirm.content": "\"{{title}}\" will no longer gate this goal's final acceptance.",+ "goalAcceptance.removeConfirm.title": "Remove this criterion?",+ "goalAcceptance.title": "Acceptance standard",+ "goalChat.newTopic": "New conversation",+ "goalChat.noTopics": "No conversations yet",+ "goalChat.title": "Ask about progress",+ "goalChat.welcome": "Ask the agent about this goal — how it's going, what's blocking, or what happens next.","goalDetail.acceptance": "Acceptance checks","goalDetail.acceptanceError": "Could not load acceptance checks.","goalDetail.acceptanceProgress": "Acceptance progress",@@ -501,7 +517,6 @@"goalProcess.attempts.running": "Running","goalProcess.attempts.title": "Previous attempts","goalProcess.edge.contradicts": "contradicts",- "goalProcess.edge.dependsOn": "depends on","goalProcess.edge.investigates": "investigates","goalProcess.edge.leadsTo": "leads to","goalProcess.edge.produces": "produces",@@ -528,14 +543,21 @@"goalProcess.frontier.emptyTitle": "Nothing to advance right now","goalProcess.frontier.needsYou": "{{count}} need you","goalProcess.frontier.title": "Current tasks",- "goalProcess.gate.noteLabel": "Extra guidance (optional — goes into the next attempt)",- "goalProcess.gate.notePlaceholder": "e.g. reuse the existing checkpoint instead of retraining from scratch",+ "goalProcess.gate.decisionPointLabel": "What needs your decision",+ "goalProcess.gate.noteLabel": "Extra guidance",+ "goalProcess.gate.notePlaceholder": "Optional — goes into the next attempt instructions","goalProcess.gate.option.fail": "Fail goal","goalProcess.gate.option.retire": "Retire work","goalProcess.gate.option.retry": "Retry work",- "goalProcess.gate.options": "What each choice means",+ "goalProcess.gate.reason.attemptBudgetExhausted": "The attempt budget for this work is used up",+ "goalProcess.gate.reason.costBudgetExhausted": "The goal cost budget is used up",+ "goalProcess.gate.reason.goalAcceptanceFailed": "Goal-level acceptance did not pass",+ "goalProcess.gate.reason.recoveryFailed": "Automatic recovery could not start the next attempt",+ "goalProcess.gate.reason.verifyFailed": "Task {{id}} did not pass verification",+ "goalProcess.gate.reason.verifyInternalError": "Verification could not run (internal error); this delivery was not evaluated","goalProcess.gate.recommended": "recommended",- "goalProcess.gate.why": "Why it stopped",+ "goalProcess.gate.title.goalAcceptance": "Decide the goal acceptance outcome",+ "goalProcess.gate.title.recoverTask": "Decide what happens to the failed task","goalProcess.graph.exitFullscreen": "Exit fullscreen","goalProcess.graph.fullscreen": "Fullscreen","goalProcess.graph.title": "Exploration map",@@ -586,6 +608,7 @@"goalProcess.node.producedByTitle": "Produced by","goalProcess.node.producedFindings": "Produced findings","goalProcess.node.running": "Running",+ "goalProcess.node.terminalAcceptance": "Complete full goal acceptance","goalProcess.node.unanswered": "Unanswered","goalProcess.node.unassigned": "Not dispatched","goalProcess.node.verifierTooltip": "This task has its own acceptance contract — a verifier judges the delivery.",@@ -1590,6 +1613,8 @@"taskDetail.replyInThread": "Reply in this thread","taskDetail.replyPlaceholder": "Reply in this thread...","taskDetail.rerunTask": "Re-run task",+ "taskDetail.run.outputLabel": "Run output",+ "taskDetail.run.summaryLabel": "Run summary","taskDetail.runAll": "Run all","taskDetail.runAll.cancel": "Cancel","taskDetail.runAll.confirm": "Run {{count}} subtask(s)",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 383d301b1f7..f6a6072c110 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -1,6 +1,30 @@{"arguments.moreParams": "{{count}} params in total","arguments.title": "Arguments",+ "builtins.claude-code.apiName.Agent": "Run subagent",+ "builtins.claude-code.apiName.Bash": "Run command",+ "builtins.claude-code.apiName.Edit": "Edit file",+ "builtins.claude-code.apiName.EnterWorktree": "Enter worktree",+ "builtins.claude-code.apiName.ExitWorktree": "Leave worktree",+ "builtins.claude-code.apiName.Glob": "Find files",+ "builtins.claude-code.apiName.Grep": "Search content",+ "builtins.claude-code.apiName.Monitor": "Monitor command",+ "builtins.claude-code.apiName.Read": "Read file",+ "builtins.claude-code.apiName.ScheduleWakeup": "Schedule wakeup",+ "builtins.claude-code.apiName.SendMessage": "Send message",+ "builtins.claude-code.apiName.Skill": "Use skill",+ "builtins.claude-code.apiName.TaskCreate": "Create task",+ "builtins.claude-code.apiName.TaskGet": "View task",+ "builtins.claude-code.apiName.TaskList": "List tasks",+ "builtins.claude-code.apiName.TaskOutput": "Read task output",+ "builtins.claude-code.apiName.TaskStop": "Stop task",+ "builtins.claude-code.apiName.TaskUpdate": "Update task",+ "builtins.claude-code.apiName.TodoWrite": "Update tasks",+ "builtins.claude-code.apiName.ToolSearch": "Search tools",+ "builtins.claude-code.apiName.WebFetch": "Fetch web page",+ "builtins.claude-code.apiName.WebSearch": "Search the web",+ "builtins.claude-code.apiName.Write": "Write file",+ "builtins.claude-code.apiName.askUserQuestion": "Ask a question","builtins.codex.agentBrowser.click": "Clicked element","builtins.codex.agentBrowser.eval": "Evaluated page","builtins.codex.agentBrowser.fill": "Filled input",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex fbccd685043..7499f7d5ff0 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -65,6 +65,7 @@"acceptance.checks.emptyFilter.needsFix": "No checks marked for fixing","acceptance.checks.emptyFilter.pending": "No checks left to review","acceptance.checks.finalRoundHint": "The final result and evidence come from this round — click to locate it.",+ "acceptance.checks.holisticTitle": "Task delivery acceptance","acceptance.checks.introduced": "Added in round {{round}}","acceptance.checks.introducedHint": "This check first appeared in that round — click to locate it.","acceptance.checks.iterated": "Iterated {{count}}×",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fc99eb89235..07459f4e673 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -387,6 +387,22 @@"globalApproval.subtitle": "等待你的审批","globalApproval.title": "需要审批","globalApproval.userRequestLabel": "用户请求",+ "goalAcceptance.add": "添加标准",+ "goalAcceptance.edit": "编辑",+ "goalAcceptance.empty": "还没有验收标准——把最终验收要核对的结果逐条加进来。",+ "goalAcceptance.form.descriptionPlaceholder": "这条标准覆盖什么(可选)",+ "goalAcceptance.form.instructionPlaceholder": "如何判定——什么样的证据算通过或不通过(可选)",+ "goalAcceptance.form.titlePlaceholder": "以结果表述的验收标准",+ "goalAcceptance.gateHint": "目标最终验收会逐条核对这些标准",+ "goalAcceptance.judgePrefix": "怎么判定:",+ "goalAcceptance.remove": "移除",+ "goalAcceptance.removeConfirm.content": "「{{title}}」将不再作为该目标最终验收的门槛。",+ "goalAcceptance.removeConfirm.title": "移除这条标准?",+ "goalAcceptance.title": "验收标准",+ "goalChat.newTopic": "新对话",+ "goalChat.noTopics": "还没有对话",+ "goalChat.title": "问问进展",+ "goalChat.welcome": "向助理询问这个目标:进展如何、卡在哪里、接下来会做什么。","goalDetail.acceptance": "验收检查","goalDetail.acceptanceError": "无法加载验收检查。","goalDetail.acceptanceProgress": "验收进度",@@ -501,7 +517,6 @@"goalProcess.attempts.running": "进行中","goalProcess.attempts.title": "之前的尝试","goalProcess.edge.contradicts": "反驳",- "goalProcess.edge.dependsOn": "依赖","goalProcess.edge.investigates": "调查","goalProcess.edge.leadsTo": "导向","goalProcess.edge.produces": "产出",@@ -528,14 +543,21 @@"goalProcess.frontier.emptyTitle": "当前没有可推进的任务","goalProcess.frontier.needsYou": "{{count}} 项需要你","goalProcess.frontier.title": "当前任务",- "goalProcess.gate.noteLabel": "补充说明(可选,会写进下一次尝试的指令)",- "goalProcess.gate.notePlaceholder": "例如:不要重训,基于已有 checkpoint 继续",+ "goalProcess.gate.decisionPointLabel": "需要你决定什么",+ "goalProcess.gate.noteLabel": "补充说明",+ "goalProcess.gate.notePlaceholder": "可选,会写进下一次尝试的指令","goalProcess.gate.option.fail": "判定目标失败","goalProcess.gate.option.retire": "放弃这项任务","goalProcess.gate.option.retry": "重试这项任务",- "goalProcess.gate.options": "每个选择意味着什么",+ "goalProcess.gate.reason.attemptBudgetExhausted": "这项任务的尝试次数已用完",+ "goalProcess.gate.reason.costBudgetExhausted": "目标的成本预算已用完",+ "goalProcess.gate.reason.goalAcceptanceFailed": "目标整体验收未通过",+ "goalProcess.gate.reason.recoveryFailed": "自动恢复未能启动下一次尝试",+ "goalProcess.gate.reason.verifyFailed": "任务 {{id}} 未通过验证",+ "goalProcess.gate.reason.verifyInternalError": "验证未能运行(内部错误),这次交付没有被评估","goalProcess.gate.recommended": "推荐",- "goalProcess.gate.why": "为什么停下来",+ "goalProcess.gate.title.goalAcceptance": "决定目标验收的去向",+ "goalProcess.gate.title.recoverTask": "决定失败任务的去向","goalProcess.graph.exitFullscreen": "退出全屏","goalProcess.graph.fullscreen": "全屏","goalProcess.graph.title": "探索图",@@ -586,6 +608,7 @@"goalProcess.node.producedByTitle": "来自任务","goalProcess.node.producedFindings": "产出结论","goalProcess.node.running": "进行中",+ "goalProcess.node.terminalAcceptance": "完成目标整体验收","goalProcess.node.unanswered": "待回答","goalProcess.node.unassigned": "未派发","goalProcess.node.verifierTooltip": "这项任务有自己的验收合约,由 verifier 判定交付",@@ -1590,6 +1613,8 @@"taskDetail.replyInThread": "在此对话中回复","taskDetail.replyPlaceholder": "在此对话中回复…","taskDetail.rerunTask": "重新运行",+ "taskDetail.run.outputLabel": "运行输出",+ "taskDetail.run.summaryLabel": "运行摘要","taskDetail.runAll": "全部运行","taskDetail.runAll.cancel": "取消","taskDetail.runAll.confirm": "运行 {{count}} 个子任务",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 88cf73a2111..e245cc226b0 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -1,6 +1,30 @@{"arguments.moreParams": "等 {{count}} 个参数","arguments.title": "参数列表",+ "builtins.claude-code.apiName.Agent": "运行子代理",+ "builtins.claude-code.apiName.Bash": "执行命令",+ "builtins.claude-code.apiName.Edit": "编辑文件",+ "builtins.claude-code.apiName.EnterWorktree": "进入工作树",+ "builtins.claude-code.apiName.ExitWorktree": "离开工作树",+ "builtins.claude-code.apiName.Glob": "查找文件",+ "builtins.claude-code.apiName.Grep": "搜索内容",+ "builtins.claude-code.apiName.Monitor": "监控命令",+ "builtins.claude-code.apiName.Read": "读取文件",+ "builtins.claude-code.apiName.ScheduleWakeup": "定时唤醒",+ "builtins.claude-code.apiName.SendMessage": "发送消息",+ "builtins.claude-code.apiName.Skill": "使用技能",+ "builtins.claude-code.apiName.TaskCreate": "创建任务",+ "builtins.claude-code.apiName.TaskGet": "查看任务",+ "builtins.claude-code.apiName.TaskList": "查看任务列表",+ "builtins.claude-code.apiName.TaskOutput": "读取任务输出",+ "builtins.claude-code.apiName.TaskStop": "停止任务",+ "builtins.claude-code.apiName.TaskUpdate": "更新任务",+ "builtins.claude-code.apiName.TodoWrite": "更新任务清单",+ "builtins.claude-code.apiName.ToolSearch": "搜索工具",+ "builtins.claude-code.apiName.WebFetch": "抓取网页",+ "builtins.claude-code.apiName.WebSearch": "搜索网页",+ "builtins.claude-code.apiName.Write": "写入文件",+ "builtins.claude-code.apiName.askUserQuestion": "向你提问","builtins.codex.agentBrowser.click": "点击元素","builtins.codex.agentBrowser.eval": "检查页面状态","builtins.codex.agentBrowser.fill": "填写输入框",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex ab3f6e53a19..8661cc28e44 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -65,6 +65,7 @@"acceptance.checks.emptyFilter.needsFix": "没有待修复的检查项","acceptance.checks.emptyFilter.pending": "没有待验收的检查项","acceptance.checks.finalRoundHint": "最终结果与证据来自该轮,点击查看",+ "acceptance.checks.holisticTitle": "任务交付验收","acceptance.checks.introduced": "第 {{round}} 轮引入","acceptance.checks.introducedHint": "该检查在此轮首次出现,点击查看","acceptance.checks.iterated": "迭代 {{count}} 次",diff --git a/packages/builtin-tool-goal/src/client/executor/index.ts b/packages/builtin-tool-goal/src/client/executor/index.tsindex 9ffc77ebbd8..b03831e2903 100644--- a/packages/builtin-tool-goal/src/client/executor/index.ts+++ b/packages/builtin-tool-goal/src/client/executor/index.ts@@ -66,6 +66,9 @@ class GoalExecutor extends BaseExecutor<typeof GoalApiName> {// `maxIterations` caps attempts on one Work; it is deliberately not// passed as `maxRounds`, which counts runs across every Work in the// graph and would strand later tasks that have not run at all.+ // Structured criteria persist alongside the prose requirement so the+ // goal page can edit them and the terminal acceptance runs exactly them.+ criteria,maxTotalCost: params.maxTotalCost ?? undefined,// No seed work: the coordinator plans the decomposition on first// advance, turning a complex ask into several explorable directions.diff --git a/packages/builtin-tool-goal/src/createGoalInput.test.ts b/packages/builtin-tool-goal/src/createGoalInput.test.tsindex d650c77aeb7..a22053cc904 100644--- a/packages/builtin-tool-goal/src/createGoalInput.test.ts+++ b/packages/builtin-tool-goal/src/createGoalInput.test.ts@@ -1,6 +1,40 @@import { describe, expect, it } from 'vitest';-import { resolveGoalAttemptBudget, resolveGoalScheduleConfig } from './createGoalInput';+import {+ buildGoalRequirement,+ resolveGoalAttemptBudget,+ resolveGoalScheduleConfig,+} from './createGoalInput';++describe('buildGoalRequirement', () => {+ it('composes structured markdown the requirement document renders cleanly', () => {+ // The text is shown by the goal page's markdown editor, so blocks separate+ // with blank lines while the numbered criteria stay one tight list, each+ // how-to-judge note on its own sub-line instead of a run-on parenthetical.+ const text = buildGoalRequirement(+ 'Ship it',+ [+ { description: 'Runs locally', instruction: 'Run the demo script', title: 'Local run' },+ { title: 'Docs complete' },+ ],+ 'End-to-end reproduction',+ );++ expect(text).toBe(+ [+ '## Ship it',+ '',+ '**Scope:** End-to-end reproduction',+ '',+ '**Acceptance criteria** — every one must be satisfied with concrete evidence:',+ '',+ '1. **Local run** — Runs locally ',+ ' *How to judge:* Run the demo script',+ '2. **Docs complete**',+ ].join('\n'),+ );+ });+});describe('resolveGoalAttemptBudget', () => {it('leaves the budget unset when the user cleared the field', () => {diff --git a/packages/builtin-tool-goal/src/createGoalInput.ts b/packages/builtin-tool-goal/src/createGoalInput.tsindex 4683c58491c..934607884cd 100644--- a/packages/builtin-tool-goal/src/createGoalInput.ts+++ b/packages/builtin-tool-goal/src/createGoalInput.ts@@ -46,23 +46,33 @@ export const resolveGoalScheduleConfig = (* done" as one authoritative text, which the coordinator folds into every* Work's acceptance contract — so the drafted criteria are rendered into it* rather than persisted as separate verify criteria rows.+ *+ * The text doubles as the goal page's editable "what counts as done" document,+ * which renders markdown — so the composition is structured markdown, not bare+ * lines: criterion titles bold, the how-to-judge note on its own sub-line.*/export const buildGoalRequirement = (name: string,criteria: GoalCriterionInput[],instruction?: string,-): string =>- [- name,- instruction ? `Scope: ${instruction}` : undefined,- 'Acceptance criteria — every one must be satisfied with concrete evidence:',- ...criteria.map((item, index) =>+): string => {+ const list = criteria+ .map((item, index) =>[- `${index + 1}. ${item.title}`,+ `${index + 1}. **${item.title}**`,item.description ? ` — ${item.description}` : '',- item.instruction ? ` (how to judge: ${item.instruction})` : '',+ // Hard break (trailing two spaces) + indented continuation keeps the+ // judge note inside the SAME list item — a nested bullet would steal+ // the next ordinal from the editor's list numbering (1/3/5).+ item.instruction ? ` \n *How to judge:* ${item.instruction}` : '',].join(''),- ),+ )+ .join('\n');+ return [+ `## ${name}`,+ instruction ? `**Scope:** ${instruction}` : undefined,+ `**Acceptance criteria** — every one must be satisfied with concrete evidence:\n\n${list}`,].filter(Boolean)- .join('\n');+ .join('\n\n');+};diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 73fdbe862a5..d7233cbf729 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -42,3 +42,10 @@ export type GoalSubjectType = (typeof goalSubjectTypes)[number];* unanswerable — a stable id for the one non-human actor is what separates them.*/export const GOAL_COORDINATOR_ACTOR_ID = 'goal-coordinator';++/**+ * Fixed title of the terminal Goal-acceptance Work the coordinator creates+ * once every other Work is terminal. Stored in English as data; clients+ * recognize it and render the localized copy (`goalProcess.node.terminalAcceptance`).+ */+export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';diff --git a/packages/const/src/layoutTokens.ts b/packages/const/src/layoutTokens.tsindex eba35063b52..7593e84803a 100644--- a/packages/const/src/layoutTokens.ts+++ b/packages/const/src/layoutTokens.ts@@ -12,6 +12,8 @@ export const CONVERSATION_MIN_WIDTH = 960;export const CHAT_PORTAL_WIDTH = 400;export const CHAT_PORTAL_MAX_WIDTH = 1280;export const CHAT_PORTAL_TOOL_UI_WIDTH = 600;+/** Opening width for task / goal-node detail panes — one column of status + activity. */+export const CHAT_PORTAL_TASK_WIDTH = 640;/** For portal views that read as a document (acceptance report, evidence, screenshots) */export const CHAT_PORTAL_WIDE_WIDTH = 840;/**diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.tsindex bc5b1f27dbc..8303976db0b 100644--- a/packages/const/src/verify.ts+++ b/packages/const/src/verify.ts@@ -163,6 +163,14 @@ const PROGRAMMATIC_TEST_PATTERNS: RegExp[] = [/单元测试|单测|集成测试|回归测试|类型检查|类型校验|测试覆盖率|代码覆盖率|静态检查|测试用例全部通过/,];+/**+ * Stored title of the synthesized holistic fallback check (one broad agent+ * verify over the whole deliverable, used when a task opted into verify without+ * decomposing into criteria). The server persists this fixed English string;+ * clients match against it to render a localized display title instead.+ */+export const HOLISTIC_CHECK_TITLE = 'Task delivery acceptance';+/*** Whether a proposed acceptance check is really one of the repo's programmatic* test / static-analysis gates rather than a delivery outcome a person accepts.diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex d234a1343a9..427e0e16dd5 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -41,6 +41,7 @@ import {EvalContextSystemInjector,ExpertiseContextInjector,ForceFinishSummaryInjector,+ GoalContextSyntheticInjector,GroupAgentBuilderContextInjector,GroupContextInjector,HistorySummaryProvider,@@ -437,6 +438,13 @@ export class MessagesEngine {// Inject high-churn runtime guidance at the tail to preserve stable prefix caching// =============================================+ // Goal progress overview (goal detail page conversation) — a synthetic+ // getGoalContext tool pair after the last user message: environment+ // state arrives as machine-provided tool output, not as user words.+ new GoalContextSyntheticInjector({+ enabled: !!initialContext?.goalOverview,+ overview: initialContext?.goalOverview,+ }),// Onboarding synthetic state (fake getOnboardingState tool call pair to drive action loop)new OnboardingSyntheticStateInjector({enabled: !!onboardingContext?.phaseGuidance,diff --git a/packages/context-engine/src/providers/GoalContextSyntheticInjector.ts b/packages/context-engine/src/providers/GoalContextSyntheticInjector.tsnew file mode 100644index 00000000000..90f71063799--- /dev/null+++ b/packages/context-engine/src/providers/GoalContextSyntheticInjector.ts@@ -0,0 +1,95 @@+import { buildGoalOverviewPrompt } from '@lobechat/prompts';+import type { InitialGoalOverviewContext } from '@lobechat/types';+import debug from 'debug';++import { BaseProcessor } from '../base/BaseProcessor';+import type { Message, PipelineContext, ProcessorOptions } from '../types';++const log = debug('context-engine:provider:GoalContextSyntheticInjector');++const makeSyntheticToolCallId = () => `synthetic-getGoalContext-${Date.now()}`;++export interface GoalContextSyntheticInjectorConfig {+ enabled?: boolean;+ /**+ * Structured snapshot of the viewed goal — the injector owns rendering it+ * into the synthetic `getGoalContext` result body, so transports only ship+ * data and prompt wording stays in one place.+ */+ overview?: InitialGoalOverviewContext;+}++/**+ * Goal Context Synthetic Injector+ *+ * Injects a fake assistant(tool_call getGoalContext) + tool(result) pair after+ * the last user message, carrying the goal-page overview as environment+ * information (same topology as {@link OnboardingSyntheticStateInjector}).+ *+ * Why a tool pair rather than appending to the user message: environment state+ * the product injects is not something the user said. As a tool result it is+ * clearly machine-provided, survives user-message rendering untouched, and+ * keeps the action→feedback shape models already handle for tool output.+ */+export class GoalContextSyntheticInjector extends BaseProcessor {+ readonly name = 'GoalContextSyntheticInjector';++ constructor(+ private config: GoalContextSyntheticInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ if (!this.config.enabled || !this.config.overview) {+ log('Disabled or no overview, skipping');+ return this.markAsExecuted(context);+ }++ const clonedContext = this.cloneContext(context);++ let lastUserIdx = -1;+ for (let i = clonedContext.messages.length - 1; i >= 0; i--) {+ if (clonedContext.messages[i].role === 'user') {+ lastUserIdx = i;+ break;+ }+ }++ if (lastUserIdx === -1) {+ log('No user message found, skipping');+ return this.markAsExecuted(context);+ }++ const toolCallId = makeSyntheticToolCallId();++ const assistantMsg: Message = {+ content: '',+ id: `synthetic-assistant-goal-${Date.now()}`,+ role: 'assistant',+ tool_calls: [+ {+ function: {+ arguments: '{}',+ name: 'getGoalContext',+ },+ id: toolCallId,+ type: 'function',+ },+ ],+ };++ const toolMsg: Message = {+ content: buildGoalOverviewPrompt(this.config.overview),+ id: `synthetic-tool-goal-${Date.now()}`,+ role: 'tool',+ tool_call_id: toolCallId,+ };++ clonedContext.messages.splice(lastUserIdx + 1, 0, assistantMsg, toolMsg);++ log('Injected synthetic getGoalContext pair after user message %d', lastUserIdx);+ return this.markAsExecuted(clonedContext);+ }+}diff --git a/packages/context-engine/src/providers/__tests__/GoalContextSyntheticInjector.test.ts b/packages/context-engine/src/providers/__tests__/GoalContextSyntheticInjector.test.tsnew file mode 100644index 00000000000..5b7d2a9653a--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/GoalContextSyntheticInjector.test.ts@@ -0,0 +1,129 @@+import { buildGoalOverviewPrompt } from '@lobechat/prompts';+import type { InitialGoalOverviewContext } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { GoalContextSyntheticInjector } from '../GoalContextSyntheticInjector';++const createContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+});++const OVERVIEW: InitialGoalOverviewContext = {+ findings: [],+ goal: { status: 'running', title: 'Demo' },+ pendingDecisions: [],+ work: [{ seq: 1, status: 'active', title: 'Only work' }],+};+// The injector owns prompt composition — callers pass structured data only.+const OVERVIEW_PROMPT = buildGoalOverviewPrompt(OVERVIEW);++describe('GoalContextSyntheticInjector', () => {+ it('injects a getGoalContext tool pair right after the last user message', async () => {+ const provider = new GoalContextSyntheticInjector({ enabled: true, overview: OVERVIEW });+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: 'earlier question', role: 'user' },+ { content: 'earlier answer', role: 'assistant' },+ { content: '现在进展如何?', role: 'user' },+ ]),+ );++ expect(result.messages).toHaveLength(6);+ const [assistant, tool] = result.messages.slice(4);+ expect(assistant.role).toBe('assistant');+ expect(assistant.tool_calls?.[0]?.function?.name).toBe('getGoalContext');+ expect(tool.role).toBe('tool');+ expect(tool.tool_call_id).toBe(assistant.tool_calls?.[0]?.id);+ expect(tool.content).toBe(OVERVIEW_PROMPT);+ expect(tool.content).toContain('<goal_overview>');+ // the user message itself stays untouched+ expect(result.messages[3].content).toBe('现在进展如何?');+ });++ it('injects exactly one fresh pair per request across a multi-turn history', async () => {+ // The pair is injected per-request into the pipeline and never persisted,+ // so a long conversation still carries exactly one pair — after the LAST+ // user message — no matter how many earlier turns exist.+ const provider = new GoalContextSyntheticInjector({ enabled: true, overview: OVERVIEW });+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: '第一轮:进展如何?', role: 'user' },+ { content: '第一轮回答', role: 'assistant' },+ { content: '第二轮:卡在哪里?', role: 'user' },+ { content: '第二轮回答', role: 'assistant' },+ { content: '第三轮:接下来做什么?', role: 'user' },+ ]),+ );++ const pairs = result.messages.filter(+ (m: any) => m.tool_calls?.[0]?.function?.name === 'getGoalContext',+ );+ expect(pairs).toHaveLength(1);+ expect(result.messages).toHaveLength(8);+ // pair sits after the LAST user message, earlier turns untouched+ expect(result.messages[5].content).toBe('第三轮:接下来做什么?');+ expect(result.messages[6].tool_calls?.[0]?.function?.name).toBe('getGoalContext');+ expect(result.messages[7].role).toBe('tool');+ expect(result.messages[2].content).toBe('第一轮回答');+ });++ it('keeps a real tool chain intact when the current turn already ran tools', async () => {+ // Second model call of a turn that ran a real tool (e.g. web search):+ // [user][real assistant tool_call][real tool result]. The synthetic pair+ // lands right after the user message; both tool exchanges stay adjacent+ // and self-contained, so provider-side tool ordering remains valid.+ const provider = new GoalContextSyntheticInjector({ enabled: true, overview: OVERVIEW });+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: '搜一下再回答我进展', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ {+ function: { arguments: '{"query":"x"}', name: 'lobe-web-browsing____search' },+ id: 'call_real',+ type: 'function',+ },+ ],+ },+ { content: '[search results]', role: 'tool', tool_call_id: 'call_real' },+ ]),+ );++ expect(result.messages.map((m: any) => m.role)).toEqual([+ 'system',+ 'user',+ 'assistant',+ 'tool',+ 'assistant',+ 'tool',+ ]);+ // synthetic pair directly after the user message…+ expect(result.messages[2].tool_calls?.[0]?.function?.name).toBe('getGoalContext');+ expect(result.messages[3].tool_call_id).toBe(result.messages[2].tool_calls?.[0]?.id);+ // …and the real chain untouched and still adjacent+ expect(result.messages[4].tool_calls?.[0]?.id).toBe('call_real');+ expect(result.messages[5].tool_call_id).toBe('call_real');+ });++ it('does nothing when disabled, without overview, or with no user message', async () => {+ const messages = [{ content: 'sys', role: 'system' }];++ for (const provider of [+ new GoalContextSyntheticInjector({ enabled: false, overview: OVERVIEW }),+ new GoalContextSyntheticInjector({ enabled: true }),+ new GoalContextSyntheticInjector({ enabled: true, overview: OVERVIEW }),+ ]) {+ const result = await provider.process(createContext([...messages]));+ expect(result.messages).toHaveLength(1);+ }+ });+});diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 9f232dac2ba..913623893b4 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -19,6 +19,8 @@ export {ExpertiseContextInjector,} from './ExpertiseContextInjector';export { ForceFinishSummaryInjector } from './ForceFinishSummaryInjector';+export type { GoalContextSyntheticInjectorConfig } from './GoalContextSyntheticInjector';+export { GoalContextSyntheticInjector } from './GoalContextSyntheticInjector';export { GroupAgentBuilderContextInjector } from './GroupAgentBuilderContextInjector';export { GroupContextInjector } from './GroupContextInjector';export { HistorySummaryProvider } from './HistorySummary';diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 75d982af071..781e1a9624b 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -405,6 +405,15 @@ export class AgentOperationModel {return row ?? null;}+ /** Batch lookup for callers that would otherwise issue one query per id. */+ async findByIds(operationIds: string[]) {+ if (operationIds.length === 0) return [];+ return this.db+ .select()+ .from(agentOperations)+ .where(and(inArray(agentOperations.id, operationIds), this.ownership()));+ }+/*** Operations recorded for one topic, newest first — the lookup that turns a* topic id (what a user actually has on hand) into the operation ids theirdiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 229abd47b15..18c2cef594e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -662,6 +662,8 @@ export default {'input.warpWithKey': 'Press <key/> to insert a line break','inputQueue.delete': 'Delete','inputQueue.edit': 'Edit',+ 'inputQueue.enqueueRejected': 'Queue is full. Try again after the current run finishes.',+ 'inputQueue.queuedHint': 'Queued — will steer the next turn','inputQueue.sendNow': 'Send now (interrupts current run)','intentUnderstanding.title': 'Understanding your intent...','inviteMembers': 'Invite members',@@ -1633,6 +1635,8 @@ export default {'taskDetail.topicMenu.stopConfirm.content':'The current run will be canceled. Generated messages are kept and you can re-run the task later.','taskDetail.topicMenu.stopConfirm.title': 'Stop Run?',+ 'taskDetail.run.outputLabel': 'Run output',+ 'taskDetail.run.summaryLabel': 'Run summary','taskDetail.runTrigger.goal': 'Goal loop','taskDetail.runTrigger.heartbeat': 'Heartbeat','taskDetail.runTrigger.schedule': 'Scheduled',@@ -1796,6 +1800,25 @@ export default {'goalWork.status.waiting': 'Waiting','goalList.title': 'Goals','goalDetail.acceptance': 'Acceptance checks',+ 'goalAcceptance.add': 'Add criterion',+ 'goalAcceptance.edit': 'Edit',+ 'goalAcceptance.empty': 'No criteria yet — add the outcomes the final acceptance should check.',+ 'goalAcceptance.form.descriptionPlaceholder': 'What this criterion covers (optional)',+ 'goalAcceptance.form.instructionPlaceholder':+ 'How to judge — what evidence makes this pass or fail (optional)',+ 'goalAcceptance.form.titlePlaceholder': 'Criterion, stated as an outcome',+ 'goalAcceptance.judgePrefix': 'How to judge: ',+ 'goalAcceptance.gateHint': 'The final goal acceptance checks each of these',+ 'goalAcceptance.remove': 'Remove',+ 'goalAcceptance.removeConfirm.content':+ '"{{title}}" will no longer gate this goal’s final acceptance.',+ 'goalAcceptance.removeConfirm.title': 'Remove this criterion?',+ 'goalAcceptance.title': 'Acceptance standard',+ 'goalChat.newTopic': 'New conversation',+ 'goalChat.noTopics': 'No conversations yet',+ 'goalChat.title': 'Ask about progress',+ 'goalChat.welcome':+ "Ask the agent about this goal — how it's going, what's blocking, or what happens next.",'goalDetail.acceptanceError': 'Could not load acceptance checks.','goalDetail.acceptanceProgress': 'Acceptance progress','goalDetail.agentRun': 'Agent run',@@ -1857,12 +1880,19 @@ export default {'goalProcess.tag.lost': 'Lost','goalProcess.tag.done': 'Done','goalProcess.tag.retired': 'Retired',- 'goalProcess.gate.why': 'Why it stopped',- 'goalProcess.gate.options': 'What each choice means',+ 'goalProcess.gate.decisionPointLabel': 'What needs your decision',+ 'goalProcess.gate.title.recoverTask': 'Decide what happens to the failed task',+ 'goalProcess.gate.title.goalAcceptance': 'Decide the goal acceptance outcome',+ 'goalProcess.gate.reason.verifyInternalError':+ 'Verification could not run (internal error); this delivery was not evaluated',+ 'goalProcess.gate.reason.verifyFailed': 'Task {{id}} did not pass verification',+ 'goalProcess.gate.reason.goalAcceptanceFailed': 'Goal-level acceptance did not pass',+ 'goalProcess.gate.reason.attemptBudgetExhausted': 'The attempt budget for this work is used up',+ 'goalProcess.gate.reason.costBudgetExhausted': 'The goal cost budget is used up',+ 'goalProcess.gate.reason.recoveryFailed': 'Automatic recovery could not start the next attempt','goalProcess.gate.recommended': 'recommended',- 'goalProcess.gate.noteLabel': 'Extra guidance (optional — goes into the next attempt)',- 'goalProcess.gate.notePlaceholder':- 'e.g. reuse the existing checkpoint instead of retraining from scratch',+ 'goalProcess.gate.noteLabel': 'Extra guidance',+ 'goalProcess.gate.notePlaceholder': 'Optional — goes into the next attempt instructions','goalProcess.gate.option.retry': 'Retry work','goalProcess.gate.option.retire': 'Retire work','goalProcess.gate.option.fail': 'Fail goal',@@ -1880,7 +1910,6 @@ export default {'goalProcess.graph.view.all': 'Full map','goalProcess.graph.fullscreen': 'Fullscreen','goalProcess.graph.exitFullscreen': 'Exit fullscreen',- 'goalProcess.edge.dependsOn': 'depends on','goalProcess.edge.investigates': 'investigates','goalProcess.edge.produces': 'produces','goalProcess.edge.supports': 'supports',@@ -1893,6 +1922,7 @@ export default {'goalProcess.node.running': 'Running','goalProcess.node.done': 'Done','goalProcess.node.waiting': 'Waiting',+ 'goalProcess.node.terminalAcceptance': 'Complete full goal acceptance','goalProcess.node.unanswered': 'Unanswered','goalProcess.metrics.status': 'Status','goalProcess.actor.agent': 'Agent',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex a2ccfb656cb..d5124944cfe 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -100,6 +100,30 @@ export default {'builtins.lobe-claude-code.worktree.remove.failed': 'Failed to remove worktree','builtins.lobe-claude-code.worktree.remove.idle': 'Remove worktree','builtins.lobe-claude-code.worktree.remove.loading': 'Removing worktree',+ 'builtins.claude-code.apiName.Agent': 'Run subagent',+ 'builtins.claude-code.apiName.Bash': 'Run command',+ 'builtins.claude-code.apiName.Edit': 'Edit file',+ 'builtins.claude-code.apiName.EnterWorktree': 'Enter worktree',+ 'builtins.claude-code.apiName.ExitWorktree': 'Leave worktree',+ 'builtins.claude-code.apiName.Glob': 'Find files',+ 'builtins.claude-code.apiName.Grep': 'Search content',+ 'builtins.claude-code.apiName.Monitor': 'Monitor command',+ 'builtins.claude-code.apiName.Read': 'Read file',+ 'builtins.claude-code.apiName.ScheduleWakeup': 'Schedule wakeup',+ 'builtins.claude-code.apiName.SendMessage': 'Send message',+ 'builtins.claude-code.apiName.Skill': 'Use skill',+ 'builtins.claude-code.apiName.TaskCreate': 'Create task',+ 'builtins.claude-code.apiName.TaskGet': 'View task',+ 'builtins.claude-code.apiName.TaskList': 'List tasks',+ 'builtins.claude-code.apiName.TaskOutput': 'Read task output',+ 'builtins.claude-code.apiName.TaskStop': 'Stop task',+ 'builtins.claude-code.apiName.TaskUpdate': 'Update task',+ 'builtins.claude-code.apiName.TodoWrite': 'Update tasks',+ 'builtins.claude-code.apiName.ToolSearch': 'Search tools',+ 'builtins.claude-code.apiName.WebFetch': 'Fetch web page',+ 'builtins.claude-code.apiName.WebSearch': 'Search the web',+ 'builtins.claude-code.apiName.Write': 'Write file',+ 'builtins.claude-code.apiName.askUserQuestion': 'Ask a question','builtins.codex.apiName.collab_tool_call': 'Coordinate subagents','builtins.codex.apiName.command_execution': 'Run command','builtins.codex.apiName.file_change': 'Edit files',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 5135c93f0b9..b91ea76cc16 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -54,6 +54,7 @@ export default {'acceptance.checks.viewTrace': 'View verification run','acceptance.checks.finalRoundHint':'The final result and evidence come from this round — click to locate it.',+ 'acceptance.checks.holisticTitle': 'Task delivery acceptance','acceptance.checks.introduced': 'Added in round {{round}}','acceptance.checks.introducedHint':'This check first appeared in that round — click to locate it.',diff --git a/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.test.ts b/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.test.tsnew file mode 100644index 00000000000..bb2704d6e5b--- /dev/null+++ b/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { buildGoalOverviewPrompt } from './buildGoalOverviewPrompt';++describe('buildGoalOverviewPrompt', () => {+ it('renders goal, work items, findings and pending decisions', () => {+ const prompt = buildGoalOverviewPrompt({+ findings: ['Local run boots end to end'],+ goal: {+ requirement: 'Reproduce the paper locally',+ status: 'running',+ title: 'WikiSkill 本地完整复现',+ },+ pendingDecisions: [{ question: 'Use the small model for the ablation?' }],+ work: [+ { seq: 1, status: 'resolved', title: '项目骨架与本地运行基座' },+ { attempts: 2, seq: 2, status: 'active', title: '经验编译与技能演化闭环' },+ ],+ });++ expect(prompt).toContain('<goal_overview>');+ expect(prompt).toContain('Goal: WikiSkill 本地完整复现 [running]');+ expect(prompt).toContain('Requirement: Reproduce the paper locally');+ expect(prompt).toContain('#1 [resolved] 项目骨架与本地运行基座');+ expect(prompt).toContain('#2 [active] 经验编译与技能演化闭环 (attempt 2)');+ expect(prompt).toContain('- Local run boots end to end');+ expect(prompt).toContain('- Use the small model for the ablation?');+ expect(prompt).toContain('</goal_overview>');+ });++ it('omits empty sections', () => {+ const prompt = buildGoalOverviewPrompt({+ findings: [],+ goal: { status: 'pending', title: 'Goal' },+ pendingDecisions: [],+ work: [],+ });++ expect(prompt).not.toContain('Findings');+ expect(prompt).not.toContain('Pending decisions');+ expect(prompt).not.toContain('Requirement:');+ });+});diff --git a/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.ts b/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.tsnew file mode 100644index 00000000000..df86f29029a--- /dev/null+++ b/packages/prompts/src/prompts/goal/buildGoalOverviewPrompt.ts@@ -0,0 +1,48 @@+// ── Goal progress overview for the goal-page side conversation ──+//+// The goal detail page hosts a chat with the goal's responsible agent so a+// user can ask "how is this going?" in plain language. The page already holds+// the full Goal Graph snapshot, so the client distills it into this block and+// injects it into the last user message (same channel as the Task Manager+// context) — the agent answers from the on-screen state without tool calls.++import type { InitialGoalOverviewContext } from '@lobechat/types';++export type BuildGoalOverviewPromptInput = InitialGoalOverviewContext;++/**+ * Goal overview prompt for the goal-page conversational reference.+ */+export const buildGoalOverviewPrompt = (input: BuildGoalOverviewPromptInput): string => {+ const { findings, goal, pendingDecisions, work } = input;++ const lines: string[] = [+ '<goal_overview>',+ `<hint>The user is currently viewing this Goal's progress page and their questions are about it. Answer from this snapshot of the on-screen state — do not claim you cannot see the goal, and do not re-fetch it.</hint>`,+ `Goal: ${goal.title} [${goal.status}]`,+ ];++ if (goal.requirement?.trim()) lines.push(`Requirement: ${goal.requirement.trim()}`);++ if (work.length > 0) {+ lines.push('', `Work items (${work.length}):`);+ for (const item of work) {+ const seq = item.seq ? `#${item.seq} ` : '';+ const attempts = item.attempts && item.attempts > 1 ? ` (attempt ${item.attempts})` : '';+ lines.push(` ${seq}[${item.status}] ${item.title}${attempts}`);+ }+ }++ if (findings.length > 0) {+ lines.push('', `Findings (${findings.length}):`);+ for (const finding of findings) lines.push(` - ${finding}`);+ }++ if (pendingDecisions.length > 0) {+ lines.push('', `Pending decisions waiting on the user (${pendingDecisions.length}):`);+ for (const decision of pendingDecisions) lines.push(` - ${decision.question}`);+ }++ lines.push('</goal_overview>');+ return lines.join('\n');+};diff --git a/packages/prompts/src/prompts/goal/index.ts b/packages/prompts/src/prompts/goal/index.tsnew file mode 100644index 00000000000..b184f75383b--- /dev/null+++ b/packages/prompts/src/prompts/goal/index.ts@@ -0,0 +1 @@+export * from './buildGoalOverviewPrompt';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 1c786782e21..fba1bb8378c 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -10,6 +10,7 @@ export * from './compressContext';export * from './discordContext';export * from './files';export * from './fileSystem';+export * from './goal';export * from './groupChat';export * from './knowledgeBaseQA';export * from './messagesToText';diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 17b90952426..e15d2494d93 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -174,6 +174,12 @@ export interface ExecAgentAppContext {threadId?: string | null;/** Topic ID */topicId?: string | null;+ /**+ * Goal detail page the conversation is happening on. The server builds+ * `RuntimeInitialContext.goalOverview` from the goal graph so the agent can+ * answer progress questions without tool calls.+ */+ viewedGoal?: { goalId: string };}/**diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsindex b4a45735aab..23576efec5c 100644--- a/packages/types/src/conversation.ts+++ b/packages/types/src/conversation.ts@@ -239,6 +239,11 @@ export interface ConversationContext {* When present, allows unauthenticated access to topic messages*/topicShareId?: string;+ /**+ * Goal detail page the user is currently viewing. When set, streamingExecutor+ * builds `RuntimeInitialContext.goalOverview` from the goal store snapshot.+ */+ viewedGoal?: { goalId: string };/*** Task Manager page the user is currently viewing. When set, streamingExecutor* builds `RuntimeInitialContext.taskManager` from the task store.diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex cb667248be6..7d98985df87 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,3 +1,5 @@+import type { InitialGoalOverviewContext } from './stepContext';+// ============================================// Goal — independent target entity (`goals` table)// ============================================@@ -45,7 +47,18 @@ export interface GoalSchedulePolicy {deadline?: string | null;}+/**+ * The goal's structured acceptance standard. The drafted criteria persist as+ * `verify_criteria` rows (viewable and editable on the goal page); this block+ * records their ids so the terminal Goal-acceptance Work verifies against+ * exactly these checks instead of re-deriving them from the requirement prose.+ */+export interface GoalAcceptancePolicy {+ criteriaIds?: string[];+}+export interface GoalConfig {+ acceptance?: GoalAcceptancePolicy;/*** How many of a goal's Tasks may be in flight at once. Independent Tasks are* the common case — four bug fixes that share no code have no reason to run@@ -209,9 +222,42 @@ export interface GoalGraphSnapshot {events: GoalGraphEvent[];goal: GoalItem;nodes: GoalGraphNode[];+ /**+ * Live heartbeat per active task node id: the `agent_operations.updatedAt`+ * of the run behind it. The runtime refreshes that lease every ~90s, while+ * `goal_nodes.updatedAt` only moves on observations / status changes —+ * liveness judgements must use whichever of the two is newer.+ */+ runHeartbeats?: Record<string, Date>;workVersions: GoalGraphWorkVersionLink[];}+/**+ * Distill a graph snapshot into the structured goal overview that rides+ * `RuntimeInitialContext.goalOverview`. Shared by every transport (client+ * executor, gateway → server pipeline) so they ship identical data; the+ * context-engine injector owns rendering it into prompt text.+ */+export const buildGoalOverviewContext = (+ snapshot: GoalGraphSnapshot,+): InitialGoalOverviewContext => {+ let workSeq = 0;+ return {+ findings: snapshot.nodes.filter((node) => node.kind === 'finding').map((node) => node.title),+ goal: {+ requirement: snapshot.goal.requirement,+ status: snapshot.goal.status,+ title: snapshot.goal.title,+ },+ pendingDecisions: snapshot.decisions+ .filter((decision) => decision.status === 'pending')+ .map((decision) => ({ question: decision.question })),+ work: snapshot.nodes+ .filter((node) => node.kind === 'task')+ .map((node) => ({ seq: ++workSeq, status: node.status, title: node.title })),+ };+};+export type GoalTickOutcome ='advanced' | 'achieved' | 'waiting_human' | 'waiting_external' | 'no_progress' | 'failed';diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.tsindex d02725aaef1..418815c83d7 100644--- a/packages/types/src/stepContext.ts+++ b/packages/types/src/stepContext.ts@@ -231,6 +231,12 @@ export interface RuntimeInitialContext {* This lets the model continue document work without page-editor tools.*/activeTopicDocument?: RuntimeActiveTopicDocumentContext;+ /**+ * Goal progress overview, built from the goal detail page the user is+ * currently viewing. Injected into the last user message so the LLM can+ * answer progress questions about the goal without extra tool calls.+ */+ goalOverview?: InitialGoalOverviewContext;/*** Ad-hoc tool manifests injected by callers for the current request.* Merged into the tool resolution output without passing through ToolsEngine.@@ -270,3 +276,32 @@ export interface InitialTaskManagerContext {/** Prebuilt prompt describing the tasks shown on the page. */contextPrompt: string;}++export interface GoalOverviewWorkItem {+ /** 1-based attempt count so far, when known. */+ attempts?: number;+ /** 1-based Work number as shown in the UI (#1, #2 …). */+ seq?: number;+ status: string;+ title: string;+}++export interface GoalOverviewDecision {+ question: string;+}++/**+ * Structured snapshot of the goal the user is viewing. Producers (goal page /+ * server pipeline) pass the data; the context-engine injector owns turning it+ * into prompt text, so wording changes never touch the transports.+ */+export interface InitialGoalOverviewContext {+ findings: string[];+ goal: {+ requirement?: string | null;+ status: string;+ title: string;+ };+ pendingDecisions: GoalOverviewDecision[];+ work: GoalOverviewWorkItem[];+}diff --git a/src/features/Acceptance/Viewer/CheckList.tsx b/src/features/Acceptance/Viewer/CheckList.tsxindex 701c1be263d..144fa15ad1f 100644--- a/src/features/Acceptance/Viewer/CheckList.tsx+++ b/src/features/Acceptance/Viewer/CheckList.tsx@@ -51,6 +51,7 @@ import {} from '../Report/MarkdownEvidence';import { hasRenderableEvidence, readVisualizationManifest } from '../Report/visualization';import { VisualizationDeltaBadge, VisualizationRenderer } from '../Report/VisualizationRenderer';+import { checkDisplayTitle } from '../utils';import { AnnotatedImage } from './Annotation';import { AttachmentThumbs } from './attachments';import { openCheckRejectModal } from './CheckRejectModal';@@ -955,6 +956,7 @@ const CheckRow = memo<{// unreviewed check would push the evidence the reviewer came for below the fold.const [proposalOpen, setProposalOpen] = useState(false);const meta = STATE_META[check.state];+ const title = checkDisplayTitle(check.title, t('acceptance.checks.holisticTitle'));const counts = evidenceCounts(check.evidence);const visualization = readVisualizationManifest(check.result?.metadata);@@ -996,7 +998,7 @@ const CheckRow = memo<{const openReject = (fromProposal?: CheckProposal) =>openCheckRejectModal({checkDescription: check.planItem?.description,- checkTitle: `C${check.seq} · ${check.title}`,+ checkTitle: `C${check.seq} · ${title}`,draftKey: check.id,evidence: check.evidence.filter((item) => isAnnotatable(item))@@ -1152,7 +1154,7 @@ const CheckRow = memo<{className={expanded ? undefined : styles.titleEllipsis}style={{ fontSize: 13, minWidth: 0 }}>- {check.title}+ {title}</Text>{!check.required && (<Tooltip title={t('acceptance.checks.notRequiredHint')}>diff --git a/src/features/Acceptance/index.ts b/src/features/Acceptance/index.tsindex aa235d6fc06..7732bf07aef 100644--- a/src/features/Acceptance/index.ts+++ b/src/features/Acceptance/index.ts@@ -18,7 +18,7 @@ export {export { default as ReportViewer } from './Report/ReportViewer';export { default as CheckerDock } from './Run/CheckerDock';export { default as RunResult } from './Run/RunResult';-export { countResults, isDraftUnconfirmed, phaseFromStatus } from './utils';+export { checkDisplayTitle, countResults, isDraftUnconfirmed, phaseFromStatus } from './utils';export { default as AcceptanceViewer } from './Viewer';export type { AcceptanceCheck, CheckReviewInput } from './Viewer/CheckList';export {diff --git a/src/features/Acceptance/utils.ts b/src/features/Acceptance/utils.tsindex 1c821669c86..ae508438468 100644--- a/src/features/Acceptance/utils.ts+++ b/src/features/Acceptance/utils.ts@@ -1,4 +1,8 @@-import { normalizeVerifySurface, type VerifySurface } from '@lobechat/const/verify';+import {+ HOLISTIC_CHECK_TITLE,+ normalizeVerifySurface,+ type VerifySurface,+} from '@lobechat/const/verify';import type { VerifyCheckItem, VerifyCodingScope } from '@lobechat/types';import type { VerifyStatus } from '@/database/models/agentOperation';@@ -16,6 +20,14 @@ export type DockPhase =| 'repairing'| 'passed';+/**+ * The holistic fallback check is persisted with a fixed English title+ * ({@link HOLISTIC_CHECK_TITLE}) — swap in the localized copy at display time.+ * Author-provided titles are shown verbatim.+ */+export const checkDisplayTitle = (title: string, holisticLabel: string): string =>+ title === HOLISTIC_CHECK_TITLE ? holisticLabel : title;+/** Map the persisted rollup status to the dock's phase state machine. */export const phaseFromStatus = (status: VerifyStatus | null | undefined): DockPhase => {switch (status) {diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex aef96f838b3..b1784e719d0 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -378,6 +378,13 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {// `maxIterations` is the per-Work attempt budget above; it is not the// graph-wide round cap, which counts runs across every Work and would// strand the fourth task of a goal whose limit is three attempts.+ // Structured criteria persist alongside the prose requirement: the goal+ // page shows/edits them and the terminal acceptance is gated on them.+ criteria: reviewedCriteria.map(({ description, instruction: how, title: name }) => ({+ description,+ instruction: how,+ title: name,+ })),maxTotalCost: budget.maxTotalCost ?? undefined,// No seed work: the coordinator plans the decomposition on first// advance, turning a complex ask into several explorable directions.diff --git a/src/features/AgentGoals/GoalAcceptanceCriteria.tsx b/src/features/AgentGoals/GoalAcceptanceCriteria.tsxnew file mode 100644index 00000000000..e3fd2ac3c2b--- /dev/null+++ b/src/features/AgentGoals/GoalAcceptanceCriteria.tsx@@ -0,0 +1,260 @@+'use client';++import { Block, Flexbox, Icon, Input, TextArea } from '@lobehub/ui';+import { ActionIcon, Button, confirmModal, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { PencilIcon, PlusIcon, XIcon } from 'lucide-react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermission } from '@/hooks/usePermission';+import { useClientDataSWR } from '@/libs/swr';+import { goalService } from '@/services/goal';+import type { GoalCriterionWithInstruction } from '@/services/verify';+import { verifyService } from '@/services/verify';+import { useGoalStore } from '@/store/goal';++const styles = createStaticStyles(({ css }) => ({+ row: css`+ padding-block: 8px;++ &:not(:last-child) {+ border-block-end: 1px dashed ${cssVar.colorBorderSecondary};+ }+ `,+ seq: css`+ flex: none;+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextQuaternary};+ `,+}));++interface CriterionFormValue {+ description: string;+ instruction: string;+ title: string;+}++const emptyForm: CriterionFormValue = { description: '', instruction: '', title: '' };++/**+ * The goal's structured acceptance standard: the persisted verify criteria the+ * terminal Goal-acceptance Work is gated on. Rendered as its own section so the+ * standard is inspectable and editable instead of living only inside the+ * requirement prose.+ *+ * Editing note: the how-to-judge instruction lives in a linked document, so a+ * save that changes it persists a replacement criterion (new row + doc) and+ * rebinds the goal; title/description-only edits update the row in place.+ */+const GoalAcceptanceCriteria = memo<{ criteriaIds: string[]; goalId: string }>(+ ({ criteriaIds, goalId }) => {+ const { t } = useTranslation('chat');+ const { allowed: canEdit } = usePermission('create_content');+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);++ const { data: criteria, mutate } = useClientDataSWR(+ criteriaIds.length > 0 ? ['goal-acceptance-criteria', goalId, criteriaIds.join(',')] : null,+ () => verifyService.getCriteria(criteriaIds),+ );++ const [editingId, setEditingId] = useState<string | 'new' | null>(null);+ const [form, setForm] = useState<CriterionFormValue>(emptyForm);+ // The judge instruction the editor opened with — an unchanged instruction+ // means the row can update in place; a changed one persists a replacement+ // criterion (the rule body lives in an immutable linked document).+ const [initialInstruction, setInitialInstruction] = useState('');+ const [saving, setSaving] = useState(false);++ const openEdit = (item: GoalCriterionWithInstruction) => {+ const instruction = item.instruction ?? '';+ setForm({ description: item.description ?? '', instruction, title: item.title });+ setInitialInstruction(instruction);+ setEditingId(item.id);+ };++ const rebind = useCallback(+ async (nextIds: string[]) => {+ await goalService.setAcceptanceCriteria(goalId, nextIds);+ await refreshGoalGraph(goalId);+ await mutate();+ },+ [goalId, mutate, refreshGoalGraph],+ );++ const handleSave = useCallback(async () => {+ const title = form.title.trim();+ if (!title || saving) return;+ setSaving(true);+ try {+ const instruction = form.instruction.trim();+ if (editingId !== 'new' && editingId && instruction === initialInstruction.trim()) {+ await verifyService.updateCriterion(editingId, {+ description: form.description.trim() || null,+ title,+ });+ await mutate();+ } else {+ const [createdId] = await verifyService.createCriteria([+ {+ description: form.description.trim() || undefined,+ instruction: instruction || undefined,+ onFail: 'manual',+ required: true,+ title,+ verifierType: 'agent',+ },+ ]);+ if (createdId) {+ await rebind(+ editingId === 'new'+ ? [...criteriaIds, createdId]+ : criteriaIds.map((id) => (id === editingId ? createdId : id)),+ );+ }+ }+ setEditingId(null);+ setForm(emptyForm);+ } finally {+ setSaving(false);+ }+ }, [criteriaIds, editingId, form, initialInstruction, mutate, rebind, saving]);++ const handleRemove = (item: GoalCriterionWithInstruction) => {+ confirmModal({+ content: t('goalAcceptance.removeConfirm.content', { title: item.title }),+ okButtonProps: { danger: true },+ onOk: async () => {+ await rebind(criteriaIds.filter((id) => id !== item.id));+ },+ title: t('goalAcceptance.removeConfirm.title'),+ });+ };++ const editorForm = (+ <Flexbox gap={8} paddingBlock={8}>+ <Input+ placeholder={t('goalAcceptance.form.titlePlaceholder')}+ value={form.title}+ onChange={(event) => setForm((prev) => ({ ...prev, title: event.target.value }))}+ />+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ placeholder={t('goalAcceptance.form.descriptionPlaceholder')}+ value={form.description}+ onChange={(event) => setForm((prev) => ({ ...prev, description: event.target.value }))}+ />+ <TextArea+ autoSize={{ maxRows: 6, minRows: 2 }}+ placeholder={t('goalAcceptance.form.instructionPlaceholder')}+ value={form.instruction}+ onChange={(event) => setForm((prev) => ({ ...prev, instruction: event.target.value }))}+ />+ <Flexbox horizontal gap={8}>+ <Button+ disabled={!form.title.trim()}+ loading={saving}+ size={'small'}+ type={'primary'}+ onClick={handleSave}+ >+ {t('save', { ns: 'common' })}+ </Button>+ <Button+ size={'small'}+ onClick={() => {+ setEditingId(null);+ setForm(emptyForm);+ }}+ >+ {t('cancel', { ns: 'common' })}+ </Button>+ </Flexbox>+ </Flexbox>+ );++ // The section header (title + count + gate hint) belongs to the hosting+ // accordion row in ProcessControl — this renders the list body only.+ return (+ <Block paddingBlock={4} paddingInline={16} variant={'outlined'}>+ {criteriaIds.length === 0 && editingId !== 'new' && (+ <Flexbox className={styles.row}>+ <Text fontSize={13} type={'secondary'}>+ {t('goalAcceptance.empty')}+ </Text>+ </Flexbox>+ )}+ {(criteria ?? []).map((item, index) => (+ <Flexbox className={styles.row} gap={4} key={item.id}>+ {editingId === item.id ? (+ editorForm+ ) : (+ <>+ <Flexbox horizontal align={'center'} gap={10}>+ <span className={styles.seq}>C{index + 1}</span>+ <Text style={{ flex: 1, minWidth: 0 }} weight={500}>+ {item.title}+ </Text>+ {canEdit && (+ <Flexbox horizontal gap={2} style={{ flex: 'none' }}>+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('goalAcceptance.edit')}+ onClick={() => openEdit(item)}+ />+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('goalAcceptance.remove')}+ onClick={() => handleRemove(item)}+ />+ </Flexbox>+ )}+ </Flexbox>+ {item.description && (+ <Text fontSize={13} style={{ paddingInlineStart: 30 }} type={'secondary'}>+ {item.description}+ </Text>+ )}+ {item.instruction && (+ <Text+ fontSize={12}+ style={{ color: cssVar.colorTextTertiary, paddingInlineStart: 30 }}+ >+ {t('goalAcceptance.judgePrefix')}+ {item.instruction}+ </Text>+ )}+ </>+ )}+ </Flexbox>+ ))}+ {editingId === 'new' ? (+ <Flexbox className={styles.row}>{editorForm}</Flexbox>+ ) : (+ canEdit && (+ <Flexbox horizontal className={styles.row}>+ <Button+ icon={<Icon icon={PlusIcon} />}+ size={'small'}+ type={'text'}+ onClick={() => {+ setForm(emptyForm);+ setEditingId('new');+ }}+ >+ {t('goalAcceptance.add')}+ </Button>+ </Flexbox>+ )+ )}+ </Block>+ );+ },+);++GoalAcceptanceCriteria.displayName = 'GoalAcceptanceCriteria';++export default GoalAcceptanceCriteria;diff --git a/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsxnew file mode 100644index 00000000000..3316e785a9b--- /dev/null+++ b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx@@ -0,0 +1,72 @@+import type { ConversationContext } from '@lobechat/types';+import type { ReactNode } from 'react';+import { memo, useEffect, useMemo } from 'react';++import { ConversationProvider } from '@/features/Conversation';+import { useOperationState } from '@/hooks/useOperationState';+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++interface GoalChatProviderProps {+ /** The goal's responsible agent — the one the user asks about progress. */+ agentId: string;+ children: ReactNode;+ goalId: string;+}++/**+ * Scopes the goal-page side conversation to the goal's responsible agent.+ * The context carries `viewedGoal`, which makes the send path inject the goal+ * progress overview into the request (see streamingExecutor).+ */+export const GoalChatProvider = memo<GoalChatProviderProps>(({ agentId, children, goalId }) => {+ const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);+ const activeTopicId = useChatStore((s) => s.activeTopicId);++ useEffect(() => {+ if (!agentId) return;++ if (useAgentStore.getState().activeAgentId !== agentId) {+ setActiveAgentId(agentId);+ }++ const chatState = useChatStore.getState();+ if (chatState.activeAgentId === agentId) return;++ useChatStore.setState({ activeAgentId: agentId });+ // Entering the goal page mid-way through another agent's conversation:+ // start from a fresh topic rather than showing that unrelated thread.+ void chatState.switchTopic(null, { skipRefreshMessage: true });+ }, [agentId, setActiveAgentId]);++ const context = useMemo<ConversationContext>(+ () => ({+ agentId,+ topicId: activeTopicId,+ viewedGoal: { goalId },+ }),+ [activeTopicId, agentId, goalId],+ );++ const chatKey = useMemo(() => messageMapKey(context), [context]);+ const replaceMessages = useChatStore((s) => s.replaceMessages);+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);+ const operationState = useOperationState(context);++ return (+ <ConversationProvider+ context={context}+ hasInitMessages={!!messages}+ messages={messages}+ operationState={operationState}+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });+ }}+ >+ {children}+ </ConversationProvider>+ );+});++GoalChatProvider.displayName = 'GoalChatProvider';diff --git a/src/features/AgentGoals/GoalChat/Toolbar.tsx b/src/features/AgentGoals/GoalChat/Toolbar.tsxnew file mode 100644index 00000000000..97aaeb49693--- /dev/null+++ b/src/features/AgentGoals/GoalChat/Toolbar.tsx@@ -0,0 +1,119 @@+import { Flexbox, Popover } from '@lobehub/ui';+import { ActionIcon, Text } from '@lobehub/ui/base-ui';+import { Clock3Icon, PanelRightCloseIcon, PlusIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import { conversationSelectors, useConversationStore } from '@/features/Conversation';+import NavHeader from '@/features/NavHeader';+import TopicItem from '@/features/PageEditor/Copilot/TopicSelector/TopicItem';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';++interface ToolbarProps {+ onCollapse: () => void;+}++/** Topic title + new-conversation + history — the agent's conversation list. */+const Toolbar = memo<ToolbarProps>(({ onCollapse }) => {+ const { t } = useTranslation('chat');+ const [topicPopoverOpen, setTopicPopoverOpen] = useState(false);+ const agentId = useConversationStore(conversationSelectors.agentId);++ useChatStore((s) => s.useFetchTopics)(true, { agentId });++ const [activeTopicId, switchTopic, topics] = useChatStore((s) => [+ s.activeTopicId,+ s.switchTopic,+ topicSelectors.currentTopics(s),+ ]);+ const currentTopic = useChatStore(topicSelectors.currentActiveTopic);++ const isLoadingTopics = topics === undefined;+ const topicTitle = currentTopic?.title || t('goalChat.title');+ const hasTopics = !!topics && topics.length > 0;++ return (+ <NavHeader+ showTogglePanelButton={false}+ left={+ <Text+ style={{ fontSize: 13, fontWeight: 500, marginLeft: 8 }}+ type={'secondary'}+ ellipsis={{+ tooltipWhenOverflow: true,+ }}+ >+ {topicTitle}+ </Text>+ }+ right={+ <>+ <ActionIcon+ icon={PlusIcon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('goalChat.newTopic')}+ onClick={() => switchTopic(null)}+ />+ <Popover+ open={isLoadingTopics ? false : topicPopoverOpen}+ placement="bottomRight"+ trigger="click"+ content={+ hasTopics ? (+ <Flexbox+ gap={4}+ padding={8}+ style={{+ maxHeight: '50vh',+ overflowY: 'auto',+ width: '100%',+ }}+ >+ {topics!.map((topic) => (+ <TopicItem+ active={topic.id === activeTopicId}+ key={topic.id}+ topicId={topic.id}+ topicTitle={topic.title}+ onClose={() => setTopicPopoverOpen(false)}+ onTopicChange={(id) => switchTopic(id)}+ />+ ))}+ </Flexbox>+ ) : (+ <Flexbox padding={16}>+ <Text type={'secondary'}>{t('goalChat.noTopics')}</Text>+ </Flexbox>+ )+ }+ styles={{+ content: {+ padding: 0,+ width: 240,+ },+ }}+ onOpenChange={setTopicPopoverOpen}+ >+ <ActionIcon+ disabled={isLoadingTopics}+ icon={Clock3Icon}+ loading={isLoadingTopics}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ />+ </Popover>+ <ActionIcon+ icon={PanelRightCloseIcon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ onClick={onCollapse}+ />+ </>+ }+ />+ );+});++Toolbar.displayName = 'GoalChatToolbar';++export default Toolbar;diff --git a/src/features/AgentGoals/GoalChat/index.tsx b/src/features/AgentGoals/GoalChat/index.tsxnew file mode 100644index 00000000000..393b1754385--- /dev/null+++ b/src/features/AgentGoals/GoalChat/index.tsx@@ -0,0 +1,92 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';+import {+ COMPACT_ACTION_BAR_STYLE,+ COMPACT_SEND_BUTTON_PROPS,+} from '@/features/ChatInput/compactPreset';+import {+ ChatInput,+ ChatList,+ conversationSelectors,+ useConversationStore,+} from '@/features/Conversation';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++import { GoalChatProvider } from './GoalChatProvider';+import Toolbar from './Toolbar';++const EMPTY_LEFT_ACTIONS: [] = [];++const Welcome = memo(() => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox align={'center'} flex={1} justify={'center'} padding={24}>+ <Text style={{ fontSize: 14, textAlign: 'center' }} type={'secondary'}>+ {t('goalChat.welcome')}+ </Text>+ </Flexbox>+ );+});++Welcome.displayName = 'GoalChatWelcome';++const Conversation = memo<{ onCollapse: () => void }>(({ onCollapse }) => {+ const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);+ const currentAgentId = useConversationStore(conversationSelectors.agentId);++ useFetchAgentConfig(true, currentAgentId);++ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(currentAgentId)(s));+ const provider = useAgentStore((s) =>+ agentByIdSelectors.getAgentModelProviderById(currentAgentId)(s),+ );+ const { handleUploadFiles } = useUploadFiles({ agentId: currentAgentId, model, provider });++ return (+ <DragUploadZone style={{ flex: 1, height: '100%' }} onUploadFiles={handleUploadFiles}>+ <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>+ <Toolbar onCollapse={onCollapse} />+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>+ <ChatList welcome={<Welcome />} />+ </Flexbox>+ <ChatInput+ actionBarStyle={COMPACT_ACTION_BAR_STYLE}+ allowExpand={false}+ leftActions={EMPTY_LEFT_ACTIONS}+ sendButtonProps={COMPACT_SEND_BUTTON_PROPS}+ showControlBar={false}+ />+ </Flexbox>+ </DragUploadZone>+ );+});++Conversation.displayName = 'GoalChatConversation';++interface GoalChatProps {+ agentId: string;+ goalId: string;+ onCollapse: () => void;+}++/**+ * The goal page's side conversation with the goal's responsible agent. The+ * provider tags the context with `viewedGoal`, so every question is answered+ * with the current goal overview injected — "how is this going?" just works.+ */+const GoalChat = memo<GoalChatProps>(({ agentId, goalId, onCollapse }) => (+ <GoalChatProvider agentId={agentId} goalId={goalId}>+ <Conversation onCollapse={onCollapse} />+ </GoalChatProvider>+));++GoalChat.displayName = 'GoalChat';++export default GoalChat;diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsxindex f41d02a959a..3eb3d322f3e 100644--- a/src/features/AgentGoals/GoalDetailActions.tsx+++ b/src/features/AgentGoals/GoalDetailActions.tsx@@ -11,6 +11,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useAppOrigin } from '@/hooks/useAppOrigin';import { usePermission } from '@/hooks/usePermission';import { useGoalStore } from '@/store/goal';@@ -26,6 +27,13 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, projeconst navigate = useWorkspaceAwareNavigate();const { allowed: canEditTask } = usePermission('create_content');const deleteGoal = useGoalStore((s) => s.deleteGoal);+ // Not `window.location.href`: on desktop that is the `app://renderer` shell+ // origin (and the shell location does not track the active tab) — build the+ // shareable web URL from the app origin and the goal route explicitly.+ const appOrigin = useAppOrigin();+ const shareUrl = appOrigin+ ? `${appOrigin}${agentId ? `/agent/${agentId}/goal/${goalId}` : `/goal/${goalId}`}`+ : undefined;const items = useMemo<DropdownItem[]>(() => [@@ -39,11 +47,13 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje},},{+ disabled: !shareUrl,icon: <Icon icon={LinkIcon} />,key: 'copyLink',label: t('taskList.contextMenu.copyLink'),onClick: async () => {- await copyToClipboard(window.location.href);+ if (!shareUrl) return;+ await copyToClipboard(shareUrl);toast.success(t('taskList.contextMenu.copyLinkSuccess'));},},@@ -76,7 +86,7 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje},},],- [agentId, canEditTask, deleteGoal, goalId, navigate, projectId, t],+ [agentId, canEditTask, deleteGoal, goalId, navigate, projectId, shareUrl, t],);return (diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 7503f8f1d3c..d5b206de61f 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -4,7 +4,7 @@ import { Flexbox } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { PauseIcon, PlayIcon } from 'lucide-react';-import { memo, type ReactNode, useEffect, useMemo } from 'react';+import { memo, type ReactNode, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import NotFound from '@/components/404';@@ -13,6 +13,7 @@ import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';import AgentBreadcrumb from '@/features/AgentBreadcrumb';import NavHeader from '@/features/NavHeader';import { PortalContent } from '@/features/Portal/router';+import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';import RightPanel from '@/features/RightPanel';import WideScreenContainer from '@/features/WideScreenContainer';import { useActivityTime } from '@/hooks/useActivityTime';@@ -22,6 +23,7 @@ import { chatPortalSelectors } from '@/store/chat/selectors';import { type GoalMetricKind } from '@/store/chat/slices/portal/initialState';import { goalSelectors, useGoalStore } from '@/store/goal';+import GoalChat from './GoalChat';import GoalDetailActions from './GoalDetailActions';import { formatSpan, goalStatusKey } from './goalPresentation';import GoalRequirement from './GoalRequirement';@@ -110,9 +112,15 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const resumeGoal = useGoalStore((s) => s.resumeGoal);const showPortal = useChatStore(chatPortalSelectors.showPortal);+ const currentViewType = useChatStore(chatPortalSelectors.currentViewType);+ const [chatOpen, setChatOpen] = useState(true);const openGoalMetric = useChatStore((s) => s.openGoalMetric);const clearPortalStack = useChatStore((s) => s.clearPortalStack);+ // Same per-view width grammar as the conversation portal, but remembered+ // under the 'goal' scope: resizing here never affects the chat surface.+ const { maxWidth, minWidth, updateWidth, width } = usePortalPanelWidth(currentViewType, 'goal');+// The portal stack belongs to this goal's inspection session — leaving the// page (or switching goals) must not leak it into the conversation surface.useEffect(() => () => clearPortalStack(), [clearPortalStack, goalId]);@@ -273,17 +281,25 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {{/* Same Portal the conversation surface uses — the drill-down chain(metric / node → task detail → topic) rides its view stack, and the- header's back arrow and close come for free. */}+ header's back arrow and close come for free. When no drill-down is+ open, the panel hosts the conversation with the goal's responsible+ agent so a user can just ask about progress. */}<RightPanel- defaultWidth={440}- expand={showPortal}- maxWidth={720}- minWidth={360}+ expand={showPortal || (chatOpen && !!agentId)}+ maxWidth={maxWidth}+ minWidth={minWidth}+ width={width}+ onSizeChange={(size) => updateWidth(size?.width)}onExpandChange={(next) => {if (!next) clearPortalStack();+ setChatOpen(next);}}>- <PortalContent />+ {showPortal ? (+ <PortalContent />+ ) : agentId ? (+ <GoalChat agentId={agentId} goalId={goalId} onCollapse={() => setChatOpen(false)} />+ ) : null}</RightPanel></Flexbox>);diff --git a/src/features/AgentGoals/ProcessControl/Activity.tsx b/src/features/AgentGoals/ProcessControl/Activity.tsxindex b432cb2ea42..d8d894b5143 100644--- a/src/features/AgentGoals/ProcessControl/Activity.tsx+++ b/src/features/AgentGoals/ProcessControl/Activity.tsx@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';import { useActivityTime } from '@/hooks/useActivityTime';+import { coordinatorNodeTitleKey } from './coordinatorCopy';import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';import { KindDot } from './shared';import { useElapsed } from './useElapsed';@@ -125,6 +126,7 @@ const ActivityRow = memo<{ onSelect: (nodeId: string) => void; view: GoalNodeVieconst [open, setOpen] = useState(false);const { text, title } = useActivityTime(lastTouch(view));const hasDetail = view.attempts.length > 0 || view.findings.length > 0;+ const coordinatorTitleKey = coordinatorNodeTitleKey(view);return (<Flexbox gap={0}>@@ -143,7 +145,7 @@ const ActivityRow = memo<{ onSelect: (nodeId: string) => void; view: GoalNodeVie/><KindDot kind={view.node.kind} /><Text ellipsis style={{ flexShrink: 1, minWidth: 0 }} weight={500}>- {view.node.title}+ {coordinatorTitleKey ? t(coordinatorTitleKey as any) : view.node.title}</Text><Text ellipsis fontSize={14} style={{ flexShrink: 1, minWidth: 0 }} type={'secondary'}>{summarize(view)}diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsxindex c5f55e4f9d5..6ec44b35cb6 100644--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx@@ -14,6 +14,12 @@ import { openAddGoalTaskModal } from '@/features/AgentGoals/AddTaskModal';import RunningGlyph from '@/features/Home/components/RunningGlyph';import { useActivityTime } from '@/hooks/useActivityTime';+import {+ coordinatorGateReason,+ coordinatorNodeTitleKey,+ coordinatorReasonCopy,+ viewGateKind,+} from './coordinatorCopy';import type { FrontierItem, GoalGraphView, GoalNodeView } from './goalGraphViewModel';import { useElapsed } from './useElapsed';@@ -54,8 +60,9 @@ const styles = createStaticStyles(({ css }) => ({}`,body: css`- padding-block: 2px 14px;- padding-inline: 46px 12px;+ /* Aligned with the row title (glyph + gap), not floated on its own indent. */+ padding-block: 8px 14px;+ padding-inline: 26px 12px;`,deps: css`font-family: ${cssVar.fontFamilyCode};@@ -72,7 +79,6 @@ const styles = createStaticStyles(({ css }) => ({`,label: css`font-size: 12px;- font-weight: 600;color: ${cssVar.colorTextSecondary};`,list: css`@@ -181,6 +187,18 @@ const RowGlyph = memo<{ kind: FrontierItem['kind']; view: GoalNodeView }>(({ kinRowGlyph.displayName = 'GoalFrontierRowGlyph';+const AttemptReason = memo<{ reason?: string | null }>(({ reason }) => {+ const { t } = useTranslation('chat');+ const copy = coordinatorReasonCopy(reason);+ return (+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>+ {copy ? t(copy.key as any, copy.params) : (reason ?? '')}+ </Text>+ );+});++AttemptReason.displayName = 'GoalAttemptReason';+const AttemptLedger = memo<{ view: GoalNodeView }>(({ view }) => {const { t } = useTranslation('chat');if (view.attempts.length === 0) return null;@@ -217,9 +235,7 @@ const AttemptLedger = memo<{ view: GoalNodeView }>(({ view }) => {>{t(`goalProcess.attempts.${attempt.outcome}` as const)}</Text>- <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>- {attempt.reason ?? ''}- </Text>+ <AttemptReason reason={attempt.reason} /></Flexbox>))}</Flexbox>@@ -254,7 +270,7 @@ DoneTime.displayName = 'GoalDoneTime';const StaleBody = memo<{ view: GoalNodeView }>(({ view }) => {const { t } = useTranslation('chat');- const { text } = useActivityTime(view.node.updatedAt);+ const { text } = useActivityTime(view.heartbeatAt);return (<Text fontSize={13} type={'secondary'}>{t('goalProcess.stale.description', { duration: text })}@@ -280,20 +296,28 @@ const FrontierRow = memo<{const { node } = view;const deps = view.dependsOn.map((id) => numbers.get(id)).filter(Boolean);+ // Coordinator-authored gates carry English strings; recognized shapes render+ // in the user's language, arbitrary gates keep their stored copy.+ const coordinatorTitleKey = coordinatorNodeTitleKey(view);+ const gateKind = item.kind === 'gate' ? viewGateKind(view) : undefined;+ const rawGateReason = gateKind ? coordinatorGateReason(view.decision?.question) : undefined;+ const gateReasonCopy = coordinatorReasonCopy(rawGateReason);+ const gateReasonText = gateReasonCopy+ ? t(gateReasonCopy.key as any, gateReasonCopy.params)+ : rawGateReason;++ // Gate rows carry no tag: the expanded card with its action buttons already+ // says "this needs you", and a warning chip next to it is noise.const tag =- item.kind === 'gate'- ? { color: 'warning', text: t('goalProcess.tag.needsDecision') }- : item.kind === 'stale'- ? { color: 'error', text: t('goalProcess.tag.lost') }- : item.kind === 'done'- ? {- color: undefined,- text:- node.status === 'resolved'- ? t('goalProcess.tag.done')- : t('goalProcess.tag.retired'),- }- : null;+ item.kind === 'stale'+ ? { color: 'error', text: t('goalProcess.tag.lost') }+ : item.kind === 'done'+ ? {+ color: undefined,+ text:+ node.status === 'resolved' ? t('goalProcess.tag.done') : t('goalProcess.tag.retired'),+ }+ : null;const stop = (event: React.MouseEvent) => event.stopPropagation();@@ -309,7 +333,7 @@ const FrontierRow = memo<{{view.seq !== undefined && <span className={styles.num}>#{view.seq}</span>}<RowGlyph kind={item.kind} view={view} /><Text ellipsis style={{ flexShrink: 1, maxWidth: '60%', minWidth: 0 }} weight={500}>- {node.title}+ {coordinatorTitleKey ? t(coordinatorTitleKey as any) : node.title}</Text>{tag && (<Tag color={tag.color} size={'small'}>@@ -325,65 +349,51 @@ const FrontierRow = memo<{<Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>{item.kind === 'running' && <RunningClock startedAt={view.startedAt} />}{item.kind === 'done' && <DoneTime view={view} />}- {item.kind === 'gate' &&- canEdit &&- view.decision?.options?.map((option) => (- <Tooltip key={option.id} title={option.description}>- <Button- size={'small'}- type={option.id === view.decision?.recommendedOptionId ? 'primary' : 'default'}- onClick={(event) => {- stop(event);- actions.decide(view.decision!.id, option.id, note.trim() || undefined);- }}- >- {optionLabel(option)}- </Button>- </Tooltip>- ))}</Flexbox></Flexbox>{item.rank === 0 && (- <Flexbox className={styles.body} gap={12} onClick={stop}>+ <Flexbox className={styles.body} gap={14} onClick={stop}>{item.kind === 'gate' && view.decision && (- <>- <Flexbox gap={4}>- <span className={styles.label}>{t('goalProcess.gate.why')}</span>- <Text fontSize={13}>{view.decision.question}</Text>- </Flexbox>- {!!view.decision.options?.length && (- <Flexbox gap={6}>- <span className={styles.label}>{t('goalProcess.gate.options')}</span>- {view.decision.options.map((option) => (- <div className={styles.option} key={option.id}>- <Text fontSize={13} weight={500}>- {optionLabel(option)}- {option.id === view.decision?.recommendedOptionId- ? `(${t('goalProcess.gate.recommended')})`- : ''}- </Text>- <Text fontSize={13} type={'secondary'}>- {option.description ?? ''}- </Text>- </div>- ))}- </Flexbox>- )}- </>+ // State the problem itself, in the user's language when the+ // coordinator's vocabulary is recognized — the buttons below+ // already carry the choices, so no extra framing sentence.+ <Text fontSize={13} weight={500}>+ {gateReasonText ?? view.decision.question}+ </Text>)}{item.kind === 'stale' && <StaleBody view={view} />}<AttemptLedger view={subject ?? view} />{item.kind === 'gate' && canEdit && (- <Flexbox gap={4}>- <span className={styles.label}>{t('goalProcess.gate.noteLabel')}</span>- <TextArea- autoSize={{ maxRows: 3, minRows: 1 }}- placeholder={t('goalProcess.gate.notePlaceholder')}- value={note}- onChange={(event) => setNote(event.target.value)}- />- </Flexbox>+ <>+ <Flexbox gap={4}>+ <span className={styles.label}>{t('goalProcess.gate.noteLabel')}</span>+ <TextArea+ autoSize={{ maxRows: 3, minRows: 1 }}+ placeholder={t('goalProcess.gate.notePlaceholder')}+ value={note}+ onChange={(event) => setNote(event.target.value)}+ />+ </Flexbox>+ {/* Actions close the card: read the situation, add guidance, then decide. */}+ <Flexbox horizontal gap={8}>+ {view.decision?.options?.map((option) => (+ <Tooltip key={option.id} title={option.description}>+ <Button+ type={+ option.id === view.decision?.recommendedOptionId ? 'primary' : 'default'+ }+ onClick={(event) => {+ stop(event);+ actions.decide(view.decision!.id, option.id, note.trim() || undefined);+ }}+ >+ {optionLabel(option)}+ </Button>+ </Tooltip>+ ))}+ </Flexbox>+ </>)}</Flexbox>)}diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsxindex 40078d31465..87a15bc565f 100644--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx@@ -11,6 +11,7 @@ import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';import RunningGlyph from '@/features/Home/components/RunningGlyph';import { shinyTextStyles } from '@/styles';+import { coordinatorNodeTitleKey } from '../coordinatorCopy';import type { GoalNodeView } from '../goalGraphViewModel';import { KIND_COLOR, KIND_ICON } from '../shared';import { useElapsed } from '../useElapsed';@@ -259,6 +260,8 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {const palette = KIND_COLOR[node.kind];const isTask = node.kind === 'task';const attempts = view.attempts.length;+ // Coordinator-authored node titles are English; recognized ones localize.+ const coordinatorTitleKey = coordinatorNodeTitleKey(view);return (<div style={{ position: 'relative' }}>@@ -315,7 +318,9 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {<Icon icon={KIND_ICON[node.kind]} size={16} /></div><Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>- <span className={styles.title}>{node.title}</span>+ <span className={styles.title}>+ {coordinatorTitleKey ? t(coordinatorTitleKey as any) : node.title}+ </span>{subtitle && <span className={styles.subtitle}>{subtitle}</span>}</Flexbox></div>diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsxindex 4f882df7a98..296cb215d3f 100644--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx@@ -178,9 +178,9 @@ const useEdgeLabel = () => {case 'contradicts': {return t('goalProcess.edge.contradicts');}- case 'depends_on': {- return t('goalProcess.edge.dependsOn');- }+ // `depends_on` is drawn blocker → blocked as a dashed edge — the dash+ // already reads as "blocked on"; any word on it invites a backwards+ // reading, so it carries no label.case 'investigates': {return t('goalProcess.edge.investigates');}diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.tsnew file mode 100644index 00000000000..60bc72f829a--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest';++import {+ coordinatorGateKind,+ coordinatorGateReason,+ coordinatorReasonCopy,+} from './coordinatorCopy';++const decision = (ids: string[]) => ({ options: ids.map((id) => ({ id, label: id })) }) as any;++describe('coordinatorGateKind', () => {+ it('recognizes the two coordinator gate shapes and nothing else', () => {+ expect(coordinatorGateKind(decision(['retry', 'retire']))).toBe('recoverTask');+ expect(coordinatorGateKind(decision(['retry', 'fail']))).toBe('goalAcceptance');+ expect(coordinatorGateKind(decision(['approve', 'reject']))).toBeUndefined();+ expect(coordinatorGateKind(undefined)).toBeUndefined();+ });+});++describe('coordinatorNodeTitleKey', () => {+ it('maps the terminal acceptance work and coordinator gates to locale keys', async () => {+ const { coordinatorNodeTitleKey } = await import('./coordinatorCopy');+ const view = (node: any, dec?: any) => ({ decision: dec, humanTouches: [], node }) as any;++ expect(+ coordinatorNodeTitleKey(view({ kind: 'task', title: 'Complete full Goal acceptance' })),+ ).toBe('goalProcess.node.terminalAcceptance');+ expect(+ coordinatorNodeTitleKey(+ view({ kind: 'decision', title: 'x' }, decision(['retry', 'retire'])),+ ),+ ).toBe('goalProcess.gate.title.recoverTask');+ expect(coordinatorNodeTitleKey(view({ kind: 'task', title: '普通任务' }))).toBeUndefined();+ });+});++describe('coordinatorGateReason', () => {+ it('strips the question template down to the reason', () => {+ expect(+ coordinatorGateReason(+ 'Verification could not run (internal error); the delivery was not evaluated.. Retry or retire this task node?',+ ),+ ).toBe('Verification could not run (internal error); the delivery was not evaluated.');+ expect(+ coordinatorGateReason(+ 'Goal-level acceptance did not pass. Retry Goal acceptance or fail this Goal?',+ ),+ ).toBe('Goal-level acceptance did not pass');+ });++ it('returns non-template questions verbatim', () => {+ expect(coordinatorGateReason('Which dataset should the ablation use?')).toBe(+ 'Which dataset should the ablation use?',+ );+ });+});++describe('coordinatorReasonCopy', () => {+ it('maps every known coordinator reason to a locale ref', () => {+ expect(+ coordinatorReasonCopy(+ 'Verification could not run (internal error); the delivery was not evaluated.',+ ),+ ).toEqual({ key: 'goalProcess.gate.reason.verifyInternalError' });+ expect(coordinatorReasonCopy('Task T-932 did not pass verification')).toEqual({+ key: 'goalProcess.gate.reason.verifyFailed',+ params: { id: 'T-932' },+ });+ expect(coordinatorReasonCopy('Work attempt budget was exhausted')).toEqual({+ key: 'goalProcess.gate.reason.attemptBudgetExhausted',+ });+ expect(+ coordinatorReasonCopy('Goal cost budget was exhausted after an operation was abandoned'),+ ).toEqual({ key: 'goalProcess.gate.reason.costBudgetExhausted' });+ expect(coordinatorReasonCopy('Automatic recovery could not start the next attempt')).toEqual({+ key: 'goalProcess.gate.reason.recoveryFailed',+ });+ });++ it('passes unknown reasons through as undefined so the raw text renders', () => {+ expect(coordinatorReasonCopy('some future reason')).toBeUndefined();+ expect(coordinatorReasonCopy(undefined)).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.tsnew file mode 100644index 00000000000..2515c1ccdcc--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts@@ -0,0 +1,113 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalGraphDecision } from '@lobechat/types';++import type { GoalNodeView } from './goalGraphViewModel';++/**+ * The goal coordinator authors its gate/attempt strings in English on the+ * server (`GoalService.openFailureDecision` and the verify settle reasons).+ * The option ids and reason templates are a stable, finite vocabulary, so the+ * client recognizes them and swaps in the user's language; anything it does+ * not recognize renders verbatim.+ */++export type CoordinatorGateKind = 'goalAcceptance' | 'recoverTask';++export interface LocalizedCopyRef {+ key: string;+ params?: Record<string, string>;+}++const idsOf = (decision?: GoalGraphDecision | null): Set<string> =>+ new Set((decision?.options ?? []).map((option) => option.id));++export const coordinatorGateKind = (+ decision?: GoalGraphDecision | null,+): CoordinatorGateKind | undefined => {+ const ids = idsOf(decision);+ if (ids.has('retry') && ids.has('retire')) return 'recoverTask';+ if (ids.has('retry') && ids.has('fail')) return 'goalAcceptance';+ return undefined;+};++/** The gate a node view carries — pending first, else the last human-resolved one. */+export const viewGateKind = (view: GoalNodeView): CoordinatorGateKind | undefined =>+ coordinatorGateKind(view.decision ?? view.humanTouches.at(-1));++export const gateTitleKey = (kind: CoordinatorGateKind): string => `goalProcess.gate.title.${kind}`;++/**+ * Locale key for a coordinator-authored fixed node title (gate nodes and the+ * terminal Goal-acceptance Work), or undefined for user/agent-authored nodes.+ */+export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefined => {+ const { node } = view;+ if (node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE)+ return 'goalProcess.node.terminalAcceptance';+ if (node.kind === 'decision') {+ const kind = viewGateKind(view);+ if (kind) return gateTitleKey(kind);+ }+ return undefined;+};++/** Strip the coordinator question template down to its dynamic reason half. */+const QUESTION_TAILS = [+ /\.?\s*Retry or retire this task node\?$/,+ /\.?\s*Retry Goal acceptance or fail this Goal\?$/,+];++export const coordinatorGateReason = (question?: string | null): string | undefined => {+ if (!question) return undefined;+ for (const tail of QUESTION_TAILS) {+ if (tail.test(question)) {+ const reason = question.replace(tail, '').trim();+ return reason || undefined;+ }+ }+ return question;+};++/** Known coordinator reason templates → chat-ns locale refs. */+const REASON_PATTERNS: Array<{+ key: string;+ param?: string;+ pattern: RegExp;+}> = [+ {+ key: 'goalProcess.gate.reason.verifyInternalError',+ pattern: /^Verification could not run \(internal error\); the delivery was not evaluated\.?$/,+ },+ {+ key: 'goalProcess.gate.reason.verifyFailed',+ param: 'id',+ pattern: /^Task (\S+) did not pass verification$/,+ },+ {+ key: 'goalProcess.gate.reason.goalAcceptanceFailed',+ pattern: /^Goal-level acceptance did not pass$/,+ },+ {+ key: 'goalProcess.gate.reason.attemptBudgetExhausted',+ pattern: /^Work attempt budget was exhausted( after an operation was abandoned)?$/,+ },+ {+ key: 'goalProcess.gate.reason.costBudgetExhausted',+ pattern: /^Goal cost budget was exhausted( after an operation was abandoned)?$/,+ },+ {+ key: 'goalProcess.gate.reason.recoveryFailed',+ pattern:+ /^Automatic recovery could not (start the next attempt|restart an abandoned operation)$/,+ },+];++export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {+ if (!reason) return undefined;+ const trimmed = reason.trim();+ for (const { key, param, pattern } of REASON_PATTERNS) {+ const match = pattern.exec(trimmed);+ if (match) return { key, ...(param && match[1] ? { params: { [param]: match[1] } } : {}) };+ }+ return undefined;+};diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.tsindex e3d15270ee7..c343723abe8 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts@@ -170,6 +170,24 @@ describe('buildGoalGraphView', () => {expect(view.needsYou).toBe(1);});+ it('keeps a work running when the run operation heartbeat is fresh despite a quiet node row', () => {+ // The node row only moves on observations / status changes; a long tool+ // call or the verify stage keeps the operation lease fresh while the row+ // goes quiet. That must not read as "lost".+ const view = buildGoalGraphView(+ snapshot({+ events: [event('w1', 'activated', 30)],+ nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(30) })],+ runHeartbeats: { w1: at(119) },+ }),+ NOW,+ );++ expect(view.byId.w1.isStale).toBe(false);+ expect(view.byId.w1.heartbeatAt).toEqual(at(119));+ expect(view.frontier[0]).toMatchObject({ kind: 'running' });+ });+it('keeps a fresh active work running, with the current attempt start for the clock', () => {const view = buildGoalGraphView(snapshot({@@ -263,20 +281,22 @@ describe('buildGoalGraphView', () => {expect(view.byId.w1.findings.map((n) => n.id)).toEqual(['f1']);});- it('keeps only the most recent finished tasks, ahead of the live rows', () => {+ it('keeps only the most recent finished tasks, shown in work numbering ahead of live rows', () => {+ // w2 finished AFTER w3: recency picks which rows stay (w1 drops), but the+ // list still reads #2 then #3 — not "most recently finished first".const view = buildGoalGraphView(snapshot({nodes: [node('w1', { resolvedAt: at(10), status: 'resolved' }),- node('w2', { resolvedAt: at(20), status: 'resolved' }),- node('w3', { resolvedAt: at(30), status: 'resolved' }),+ node('w2', { resolvedAt: at(30), status: 'resolved' }),+ node('w3', { resolvedAt: at(20), status: 'resolved' }),node('w4'),],}),NOW,);- expect(view.frontier.map((item) => item.view.node.id)).toEqual(['w3', 'w2', 'w4']);+ expect(view.frontier.map((item) => item.view.node.id)).toEqual(['w2', 'w3', 'w4']);expect(view.advanceable).toBe(1);});diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.tsindex a20c2019ab6..2719987ad51 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts@@ -54,9 +54,11 @@ export interface GoalNodeView {findings: GoalGraphNode[];/** Decision only: the Work this gate was opened for — its ledger is the case. */gateSubjectId?: string;+ /** Latest liveness signal: node row update or the run operation's lease heartbeat. */+ heartbeatAt: Date;/** Decisions on this node a human already resolved. */humanTouches: GoalGraphDecision[];- /** Active for longer than the lease window with no update — the coordinator would reclaim it. */+ /** Active for longer than the lease window with no heartbeat — the coordinator would reclaim it. */isStale: boolean;node: GoalGraphNode;/** The Work that produced this finding. */@@ -179,7 +181,7 @@ export const buildGoalGraphView = (snapshot: GoalGraphSnapshot,now: number = Date.now(),): GoalGraphView => {- const { decisions, edges, events, goal, nodes, workVersions } = snapshot;+ const { decisions, edges, events, goal, nodes, runHeartbeats, workVersions } = snapshot;const nodeById = new Map(nodes.map((node) => [node.id, node]));const lease = leaseTimeoutMs(goal);@@ -222,6 +224,14 @@ export const buildGoalGraphView = (const attempts = buildAttempts(node, events);const open = attempts.at(-1);const isRunningAttempt = node.status === 'active' && open?.outcome === 'running';+ // Liveness = the newer of the node row (moves on observations / status+ // changes) and the run operation's lease heartbeat (refreshed ~90s while+ // the agent works). Judging from the node row alone flags any long quiet+ // stretch — a big tool call, the verify stage — as lost while the+ // coordinator's reclaim path still sees a healthy lease.+ const heartbeatAt = new Date(+ Math.max(node.updatedAt.getTime(), runHeartbeats?.[node.id]?.getTime() ?? 0),+ );return {answers: supportsByFinding.get(node.id) ?? [],artifactCount: artifactCounts.get(node.id) ?? 0,@@ -233,9 +243,10 @@ export const buildGoalGraphView = (dependsOn: dependsOn.get(node.id) ?? [],findings: producesByWork.get(node.id) ?? [],gateSubjectId: gateSubject.get(node.id),+ heartbeatAt,humanTouches: nodeDecisions.filter((d) => d.status === 'resolved' && !!d.resolvedByUserId),isStale:- node.kind === 'task' && node.status === 'active' && now - node.updatedAt.getTime() > lease,+ node.kind === 'task' && node.status === 'active' && now - heartbeatAt.getTime() > lease,node,producedBy: producedByFinding.get(node.id),seq: node.kind === 'task' ? ++seq : undefined,@@ -271,8 +282,16 @@ export const buildGoalGraphView = (const done = views.filter((view) => view.node.kind === 'task' && TERMINAL_NODE_STATUSES.has(view.node.status))+ // Recency picks WHICH finished rows stay visible….sort((a, b) => resolvedTime(b.node) - resolvedTime(a.node)).slice(0, RECENT_DONE)+ // …but the list displays them in the stable Work numbering (#1, #2, …) —+ // "most recently finished first" reads as the sequence having changed.+ .sort(+ (a, b) =>+ (a.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER) ||+ resolvedTime(a.node) - resolvedTime(b.node),+ ).map((view) => ({ key: `done:${view.node.id}`, kind: 'done' as const, rank: -1, view }));frontier.sort((a, b) => a.rank - b.rank || b.view.node.priority - a.view.node.priority);diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsxindex 65ea734e11b..b9d41050c1d 100644--- a/src/features/AgentGoals/ProcessControl/index.tsx+++ b/src/features/AgentGoals/ProcessControl/index.tsx@@ -11,6 +11,7 @@ import { goalService } from '@/services/goal';import { useChatStore } from '@/store/chat';import { goalSelectors, useGoalStore } from '@/store/goal';+import GoalAcceptanceCriteria from '../GoalAcceptanceCriteria';import Activity from './Activity';import Findings from './Findings';import Frontier, { type FrontierActions } from './Frontier';@@ -88,6 +89,11 @@ const ProcessControl = memo<ProcessControlProps>(({ goalId }) => {const planning =['planning', 'running'].includes(graph.goal.status) &&!graph.nodes.some((view) => view.node.kind === 'task');+ // Presence of the acceptance block (not a non-empty list) keeps the section+ // mounted: removing the last criterion must leave the add control reachable,+ // while legacy prose-only goals (no acceptance config at all) show nothing.+ const acceptanceConfig = graph.goal.config?.acceptance;+ const criteriaIds = acceptanceConfig?.criteriaIds ?? [];// A closed goal cannot move: the coordinator returns immediately for these,// and a Work added here would sit `proposed` forever. Stop offering actions// that cannot land. The goal otherwise advances entirely on its own — the@@ -110,6 +116,31 @@ const ProcessControl = memo<ProcessControlProps>(({ goalId }) => {<Graph graph={graph} planning={planning} selectedId={selectedId} onSelect={select} /><Accordion defaultExpandedKeys={['findings', 'activity']} gap={0}>+ {/* The structured acceptance standard the terminal goal acceptance is+ gated on. Collapsed by default — reference material, like the task+ detail's 交付验收 section. Prose-only legacy goals have none. */}+ {!!acceptanceConfig && (+ <AccordionItem+ itemKey={'acceptance'}+ paddingBlock={6}+ paddingInline={0}+ title={+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalAcceptance.title')}+ </Text>+ {criteriaIds.length > 0 && <Tag size={'small'}>{criteriaIds.length}</Tag>}+ <Text fontSize={12} type={'secondary'}>+ {t('goalAcceptance.gateHint')}+ </Text>+ </Flexbox>+ }+ >+ <Flexbox className={styles.section}>+ <GoalAcceptanceCriteria criteriaIds={criteriaIds} goalId={goalId} />+ </Flexbox>+ </AccordionItem>+ )}<AccordionItemitemKey={'findings'}paddingBlock={6}diff --git a/src/features/AgentGoals/routeMeta.ts b/src/features/AgentGoals/routeMeta.tsindex 85e3452b0c6..2a4e5be7fb4 100644--- a/src/features/AgentGoals/routeMeta.ts+++ b/src/features/AgentGoals/routeMeta.ts@@ -2,7 +2,10 @@ import { TargetIcon } from 'lucide-react';import GoalSkeleton from '@/components/Skeleton/Goal';import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';+import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';+import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';import { routeMeta } from '@/spa/router/routeMeta';+import { goalSelectors, useGoalStore } from '@/store/goal';export const goalsRouteMeta = routeMeta({icon: TargetIcon,@@ -10,7 +13,26 @@ export const goalsRouteMeta = routeMeta({titleKey: 'navigation.goals',});+const GoalDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {+ const goalId = params.goalId ?? '';+ const title = useGoalStore((s) => {+ const snapshot = goalSelectors.goalGraph(goalId)(s);+ if (snapshot?.goal.title) return snapshot.goal.title;+ // Before the detail page fetches the graph, the agent's goal list (already+ // loaded when the tab was opened from the goals rail) may know the title.+ if (!params.aid) return undefined;+ return goalSelectors+ .goalList(params.aid)(s)+ .find((item) => item.goal.id === goalId)?.goal.title;+ });++ usePublishDynamicRouteMeta({ title: title || undefined }, onResolve);++ return null;+};+export const goalDetailRouteMeta = routeMeta({+ DynamicMeta: GoalDynamicMeta,icon: TargetIcon,Skeleton: GoalDetailSkeleton,titleKey: 'navigation.goals',diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsxindex 2a66bc87c23..5529afb7b37 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx@@ -68,6 +68,7 @@ vi.mock('@/features/Acceptance', async () => ({CheckRow: ({ check }: { check: { title: string } }) => (<div data-testid="acceptance-check-detail">detail: {check.title}</div>),+ checkDisplayTitle: (title: string) => title,checkHeadMeta: () => ({ color: 'green', icon: () => null }),shouldGroupChecks: (checkCount: number) => checkCount > 10,groupChecks: (checks: Array<{ category: string }>) =>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsxindex 5df1aa9cb14..4fbe13126c0 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import {type AcceptanceCheck,+ checkDisplayTitle,checkHeadMeta,CriterionList,CriterionRow,@@ -86,6 +87,7 @@ interface CompactCheckRowProps {}const CompactCheckRow = memo<CompactCheckRowProps>(({ check, onOpen }) => {+ const { t } = useTranslation('verify');const meta = checkHeadMeta(check);return (@@ -93,7 +95,7 @@ const CompactCheckRow = memo<CompactCheckRowProps>(({ check, onOpen }) => {data-task-acceptance-check={check.id}icon={<Icon color={meta.color} icon={meta.icon} size={16} style={{ flex: 'none' }} />}seq={check.seq}- title={check.title}+ title={checkDisplayTitle(check.title, t('acceptance.checks.holisticTitle'))}onOpen={onOpen}/>);diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsxindex 1243b7e96be..92a4a38ddc4 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx@@ -360,15 +360,29 @@ const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true }) =>{hasBody && bodyExpanded && (<Flexbox gap={8} paddingInline={4}>+ {/* Both blocks carry a label naming what they are — an unlabeled blob+ of model output reads as page noise, not as the run's record. */}{activity.summary && (- <Text- fontSize={13}- style={{ color: cssVar.colorTextDescription, whiteSpace: 'pre-wrap' }}- >- {activity.summary}- </Text>+ <Flexbox gap={2}>+ <Text fontSize={12} style={{ color: cssVar.colorTextTertiary }}>+ {t('taskDetail.run.summaryLabel')}+ </Text>+ <Text+ fontSize={13}+ style={{ color: cssVar.colorTextDescription, whiteSpace: 'pre-wrap' }}+ >+ {activity.summary}+ </Text>+ </Flexbox>+ )}+ {activity.content && (+ <Flexbox gap={2}>+ <Text fontSize={12} style={{ color: cssVar.colorTextTertiary }}>+ {t('taskDetail.run.outputLabel')}+ </Text>+ <RunContent content={activity.content} />+ </Flexbox>)}- {activity.content && <RunContent content={activity.content} />}{/* The verdict's evidence, next to the delivery it judged — readingone should never require leaving for the acceptance page. */}{activity.verify && (diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsxindex b7f09d87e7d..ca492ffa0a4 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx@@ -1,4 +1,3 @@-import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';import { Icon } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -10,62 +9,35 @@ import { pluginHelpers, useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';import { shinyTextStyles } from '@/styles';+import { getToolDisplayName } from '../../toolDisplayNames';+import { extractToolKeyword } from './extractToolKeyword';+export const styles = createStaticStyles(({ css, cssVar }) => ({aborted: css`color: ${cssVar.colorTextQuaternary};`,- apiName: css`- font-family: ${cssVar.fontFamilyCode};- color: ${cssVar.colorTextSecondary};- `,- paramKey: css`+ keyword: css`+ overflow: hidden;+font-family: ${cssVar.fontFamilyCode};font-size: 12px;color: ${cssVar.colorTextTertiary};- `,- paramValue: css`- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;`,root: css`overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 1;+ display: flex;+ gap: 6px;+ align-items: center;+ min-width: 0;padding-block: 1px;color: ${cssVar.colorTextDescription};+ white-space: nowrap;`,}));-// Maximum number of parameters to display-const MAX_PARAMS = 1;-// Maximum length for parameter values before truncation-const MAX_VALUE_LENGTH = 50;--const truncateValue = (value: string, maxLength: number): string => {- if (value.length <= maxLength) return value;- return value.slice(0, maxLength) + '...';-};--const formatParamValue = (value: unknown): string => {- if (typeof value === 'string') {- return truncateValue(value, MAX_VALUE_LENGTH);- }- if (typeof value === 'number' || typeof value === 'boolean') {- return String(value);- }- if (Array.isArray(value)) {- return truncateValue(JSON.stringify(value), MAX_VALUE_LENGTH);- }- if (typeof value === 'object' && value !== null) {- return truncateValue(JSON.stringify(value), MAX_VALUE_LENGTH);- }- return String(value);-};-interface ToolTitleProps {apiName: string;args?: Record<string, unknown>;@@ -75,57 +47,42 @@ interface ToolTitleProps {partialArgs?: Record<string, unknown>;}+/**+ * Collapsed tool row title: a localized action phrase ("Run command",+ * "Edit file") plus at most one keyword of context (file basename, program,+ * query…). Full arguments stay in the expanded Detail view.+ */const ToolTitle = memo<ToolTitleProps>(({ identifier, apiName, args, partialArgs, isLoading, isAborted }) => {const { t } = useTranslation('plugin');const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);- const isBuiltinPlugin = builtinToolIdentifiers.includes(identifier);- const pluginTitle = pluginHelpers.getPluginTitle(pluginMeta) ?? identifier;-- const params = useMemo(() => {- const argsToUse = args || partialArgs || {};- return Object.entries(argsToUse).slice(0, MAX_PARAMS);- }, [args, partialArgs]);+ const pluginTitle = pluginHelpers.getPluginTitle(pluginMeta);- const remainingCount = useMemo(() => {- const argsToUse = args || partialArgs || {};- const total = Object.keys(argsToUse).length;- return total > MAX_PARAMS ? total - MAX_PARAMS : 0;- }, [args, partialArgs]);+ // Builtin (and hetero-agent) tools have per-API action labels under+ // `builtins.<identifier>.apiName.<apiName>`; everything else falls back to+ // the workflow-summary display name (MCP short labels / title-cased+ // apiName), prefixed with the plugin title when we actually know it.+ const actionLabel = t(`builtins.${identifier}.apiName.${apiName}`, { defaultValue: '' });- const moreParamsText = useMemo(() => {- if (remainingCount === 0) return '';- return ' ' + t('arguments.moreParams', { count: remainingCount + params.length });- }, [params.length, remainingCount, t]);+ const keyword = useMemo(() => extractToolKeyword(args ?? partialArgs), [args, partialArgs]);return (<div className={cx(styles.root, isAborted && styles.aborted)}><span className={cx(isLoading && shinyTextStyles.shinyText)}>- {isBuiltinPlugin- ? t(`builtins.${identifier}.title`, { defaultValue: identifier })- : pluginTitle}- </span>- <Icon icon={ChevronRight} style={{ marginInline: 4 }} />- <span className={styles.apiName}>- {isBuiltinPlugin- ? t(`builtins.${identifier}.apiName.${apiName}`, { defaultValue: apiName })- : apiName}+ {actionLabel || (+ <>+ {pluginTitle && (+ <>+ <span>{pluginTitle}</span>+ <Icon icon={ChevronRight} />+ </>+ )}+ <span>{getToolDisplayName(apiName)}</span>+ </>+ )}</span>- {params.length > 0 && (- <>- <span className={styles.paramKey}>{' ('}</span>- {params.map(([key, value], index) => (- <span key={key}>- <span className={styles.paramKey}>{key}:</span>- <span className={styles.paramValue}>{formatParamValue(value)}</span>- {index < params.length - 1 && <span className={styles.paramKey}>, </span>}- </span>- ))}- {moreParamsText && <span className={styles.paramKey}>{moreParamsText}</span>}- <span className={styles.paramKey}>{')'}</span>- </>- )}+ {keyword && <span className={styles.keyword}>{keyword}</span>}</div>);},diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.tsnew file mode 100644index 00000000000..a501cdd60c4--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import { extractToolKeyword } from './extractToolKeyword';++describe('extractToolKeyword', () => {+ it('returns undefined for missing or empty args', () => {+ expect(extractToolKeyword()).toBeUndefined();+ expect(extractToolKeyword({})).toBeUndefined();+ });++ describe('command args', () => {+ it('skips env setup and runners to find the script being run', () => {+ expect(+ extractToolKeyword({+ command:+ 'set -a && source .env && set +a && npx tsx scripts/gross-margin/monthly.ts 2>/dev/null',+ }),+ ).toBe('monthly.ts');+ });++ it('returns the program for a plain command', () => {+ expect(extractToolKeyword({ command: 'git status' })).toBe('git');+ });++ it('skips env assignments and sudo', () => {+ expect(extractToolKeyword({ command: 'FOO=1 sudo systemctl restart nginx' })).toBe(+ 'systemctl',+ );+ });++ it('prefers command over the model-written description', () => {+ expect(+ extractToolKeyword({ command: 'ls -la', description: 'List files in current directory' }),+ ).toBe('ls');+ });+ });++ describe('query and pattern args', () => {+ it('prefers pattern over path for grep-style calls', () => {+ expect(extractToolKeyword({ path: '/repo/src', pattern: 'TodoListRender' })).toBe(+ 'TodoListRender',+ );+ });++ it('truncates long queries', () => {+ const query = 'a'.repeat(50);+ const keyword = extractToolKeyword({ query });+ expect(keyword).toBe('a'.repeat(32) + '…');+ });+ });++ describe('path args', () => {+ it('returns the basename for file tools', () => {+ expect(extractToolKeyword({ file_path: '/repo/packages/database/src/message.ts' })).toBe(+ 'message.ts',+ );+ });++ it('handles windows separators', () => {+ expect(extractToolKeyword({ path: String.raw`C:\repo\src\index.tsx` })).toBe('index.tsx');+ });+ });++ describe('url args', () => {+ it('returns the hostname', () => {+ expect(extractToolKeyword({ url: 'https://lobehub.com/docs/changelog' })).toBe('lobehub.com');+ });++ it('takes the first entry of a url array', () => {+ expect(extractToolKeyword({ urls: ['https://example.com/a', 'https://other.dev/b'] })).toBe(+ 'example.com',+ );+ });+ });++ it('falls back to name-like args', () => {+ expect(extractToolKeyword({ skill: 'local-testing' })).toBe('local-testing');+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.tsnew file mode 100644index 00000000000..885d606eb21--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts@@ -0,0 +1,121 @@+const MAX_KEYWORD_LENGTH = 32;++// Arg keys checked in priority order. Query/pattern outranks path because+// Grep/Glob-style calls carry both, and the pattern is the informative half;+// pure file tools (Read/Edit/Write) only carry a path.+const COMMAND_KEYS = ['command', 'cmd', 'script'];+const QUERY_KEYS = ['query', 'q', 'pattern', 'keywords'];+const PATH_KEYS = ['file_path', 'filePath', 'path', 'filename', 'file'];+const URL_KEYS = ['url', 'urls'];+const NAME_KEYS = ['name', 'title', 'skill', 'description', 'prompt'];++// Shell tokens that never identify the program being run. The ones that take+// an argument (`source .env`, `cd dir`) consume the following token too.+const SHELL_NOISE = new Set(['env', 'exec', 'nice', 'nohup', 'set', 'sudo', 'time']);+const SHELL_NOISE_WITH_ARG = new Set(['.', 'cd', 'source']);+// Launchers whose next token (or a later path) is the real subject.+const SHELL_RUNNERS = new Set([+ 'bash',+ 'bun',+ 'bunx',+ 'deno',+ 'node',+ 'npm',+ 'npx',+ 'pnpm',+ 'python',+ 'python3',+ 'run',+ 'sh',+ 'ts-node',+ 'tsx',+ 'uv',+ 'uvx',+ 'yarn',+ 'zsh',+]);++const truncate = (value: string, maxLength = MAX_KEYWORD_LENGTH): string =>+ value.length > maxLength ? value.slice(0, maxLength) + '…' : value;++const basename = (path: string): string => {+ const trimmed = path.replace(/[/\\]+$/, '');+ return trimmed.split(/[/\\]/).pop() || trimmed;+};++const pickString = (args: Record<string, unknown>, keys: string[]): string | undefined => {+ for (const key of keys) {+ const value = args[key];+ if (typeof value === 'string' && value.trim()) return value.trim();+ // e.g. web-browsing `urls: string[]`+ if (Array.isArray(value) && typeof value[0] === 'string' && value[0].trim())+ return value[0].trim();+ }+ return undefined;+};++/**+ * Pull the program (or script file) actually being run out of a shell command,+ * skipping env assignments, flags, and wrapper launchers:+ * `set -a && source .env && npx tsx scripts/report/monthly.ts` → `monthly.ts`.+ */+const extractCommandKeyword = (command: string): string | undefined => {+ const tokens = command.split(/[\s;&|()]+/).filter(Boolean);++ let skipNext = false;+ for (const token of tokens) {+ if (skipNext) {+ skipNext = false;+ continue;+ }+ if (/^[A-Z_]\w*=/i.test(token)) continue; // env assignment+ if (/^[+-]/.test(token)) continue; // flag+ if (SHELL_NOISE_WITH_ARG.has(token)) {+ skipNext = true;+ continue;+ }+ if (SHELL_NOISE.has(token)) continue;+ if (SHELL_RUNNERS.has(token)) continue;++ return token.includes('/') ? basename(token) : token;+ }++ return tokens[0];+};++const extractUrlKeyword = (url: string): string => {+ try {+ return new URL(url).hostname;+ } catch {+ return url;+ }+};++/**+ * Distill tool-call args down to the single most informative token so the+ * collapsed inspector row can read as "<action> <keyword>" instead of dumping+ * raw arguments. Returns undefined when nothing identifiable is present.+ */+export const extractToolKeyword = (args?: Record<string, unknown>): string | undefined => {+ if (!args) return undefined;++ const command = pickString(args, COMMAND_KEYS);+ if (command) {+ const keyword = extractCommandKeyword(command);+ if (keyword) return truncate(keyword);+ }++ const query = pickString(args, QUERY_KEYS);+ if (query) return truncate(query);++ const path = pickString(args, PATH_KEYS);+ if (path) return truncate(basename(path));++ const url = pickString(args, URL_KEYS);+ if (url) return truncate(extractUrlKeyword(url));++ const name = pickString(args, NAME_KEYS);+ if (name) return truncate(name);++ return undefined;+};diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsxindex 2d13128318e..a1c5bbf70b8 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx@@ -22,6 +22,13 @@ interface InspectorProps {* Whether the tool arguments are currently streaming*/isArgumentsStreaming?: boolean;+ /**+ * Whether the tool detail is expanded. Collapsed rows show the plain+ * "<action> <keyword>" title; an expanded row restores the tool's own rich+ * inspector (full command, per-tool chips) since expanding means "show me+ * the details".+ */+ isExpanded?: boolean;/*** Whether the tool is currently executing (from operation state)*/@@ -39,6 +46,7 @@ const Inspectors = memo<InspectorProps>(result,intervention,isArgumentsStreaming,+ isExpanded,isToolCalling,toolCallId,toolCallStartTime,@@ -77,21 +85,24 @@ const Inspectors = memo<InspectorProps>(// — keep the question-mark glyph instead of the generic tick.const statusSuccessIcon = apiName === 'askUserQuestion' ? MessageCircleQuestion : undefined;- // Check for custom inspector renderer- const CustomInspector = getBuiltinInspector(identifier, apiName);+ const args = safeParseJSON(argsStr);+ const partialJson = safeParsePartialJSON(argsStr);- if (CustomInspector) {- const args = safeParseJSON(argsStr);- const partialJson = safeParsePartialJSON(argsStr);- return (- <Flexbox allowShrink horizontal align={'center'} gap={6}>- <StatusIndicator- intervention={intervention}- isToolExecuting={isToolCalling}- result={result}- successIcon={statusSuccessIcon}- successVariant={statusSuccessVariant}- />+ // Collapsed rows read as one plain sentence ("<action> <keyword>") so a+ // finished run scans as prose; expanding a row is an explicit ask for the+ // details, so it restores the tool's own rich inspector when one exists.+ const CustomInspector = isExpanded ? getBuiltinInspector(identifier, apiName) : undefined;++ return (+ <Flexbox allowShrink horizontal align={'center'} gap={6}>+ <StatusIndicator+ intervention={intervention}+ isToolExecuting={isToolCalling}+ result={result}+ successIcon={statusSuccessIcon}+ successVariant={statusSuccessVariant}+ />+ {CustomInspector ? (<SafeBoundary minHeight={22} resetKeys={[argsStr, result]}><CustomInspectorapiName={apiName}@@ -105,35 +116,16 @@ const Inspectors = memo<InspectorProps>(toolCallId={toolCallId}/></SafeBoundary>- <ExecutionTime- isExecuting={showExecutionTimer}- startTime={toolCallStartTime}- timerKey={toolCallId}+ ) : (+ <ToolTitle+ apiName={apiName}+ args={args || undefined}+ identifier={identifier}+ isAborted={isAborted}+ isLoading={isTitleLoading}+ partialArgs={partialJson || undefined}/>- </Flexbox>- );- }-- const args = safeParseJSON(argsStr);- const partialJson = safeParsePartialJSON(argsStr);-- return (- <Flexbox horizontal align={'center'} gap={6}>- <StatusIndicator- intervention={intervention}- isToolExecuting={isToolCalling}- result={result}- successIcon={statusSuccessIcon}- successVariant={statusSuccessVariant}- />- <ToolTitle- apiName={apiName}- args={args || undefined}- identifier={identifier}- isAborted={isAborted}- isLoading={isTitleLoading}- partialArgs={partialJson || undefined}- />+ )}<ExecutionTimeisExecuting={showExecutionTimer}startTime={toolCallStartTime}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex ca2c09457eb..cb488e5ec3e 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -155,6 +155,7 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =identifier={identifier}intervention={intervention}isArgumentsStreaming={isArgumentsStreaming}+ isExpanded={isToolDetailExpand}isToolCalling={isToolCalling}result={result}toolCallId={id}diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.tsindex dda89724f87..441dcbce7b9 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts@@ -160,11 +160,35 @@ describe('reasoning headline extraction', () => {expect(state).toEqual({explicitStep: 'Searched the web: Searching release notes',- fallbackTool: 'Searched the web: Node.js 24',+ fallbackTool: 'Searched the web Node.js 24',kind: 'tool',});});+ it('renders the running headline as action label + keyword, never the raw args', () => {+ const state = getWorkflowStreamingHeadlineState([+ blk({+ id: '0',+ tools: [+ {+ apiName: 'Bash',+ arguments: JSON.stringify({+ command: 'set -a && source .env && set +a && npx tsx scripts/gross-margin/monthly.ts',+ }),+ id: 't1',+ identifier: 'claude-code',+ } as any,+ ],+ }),+ ]);++ // the plugin i18n namespace is not registered in the test harness, so the+ // label falls back to the apiName; the shape under test is label + keyword.+ expect(state.kind).toBe('tool');+ expect((state as any).fallbackTool).toMatch(/ monthly\.ts$/);+ expect((state as any).fallbackTool).not.toContain('set -a');+ });+it('uses prose state when the trailing block is prose', () => {const state = getWorkflowStreamingHeadlineState([blk({@@ -210,7 +234,7 @@ describe('reasoning headline extraction', () => {expect(state).toEqual({explicitStep: 'Searched the web: Searching release notes',- fallbackTool: 'Searched the web: Node.js 24',+ fallbackTool: 'Searched the web Node.js 24',kind: 'tool',});});diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.tsindex 52209a7b7aa..d1d98384065 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts@@ -12,7 +12,6 @@ import {DURATION_SECONDS_PER_MINUTE,TIME_MS_PER_SECOND,TOOL_API_DISPLAY_NAMES,- TOOL_FIRST_DETAIL_MAX_CHARS,TOOL_HEADLINE_DETAIL_MAX_CHARS,TOOL_HEADLINE_DETAIL_TRUNCATE_LEN,TOOL_HEADLINE_TRUNCATION_SUFFIX,@@ -23,6 +22,7 @@ import {WORKFLOW_PROSE_SOURCE_MIN_CHARS,WORKFLOW_TRUNCATE_WORD_BOUNDARY_MIN_RATIO,} from './constants';+import { extractToolKeyword } from './Tool/Inspector/extractToolKeyword';export const areWorkflowToolsComplete = (tools: ChatToolPayloadWithResult[]): boolean => {const collapsible = tools.filter((t) => t.intervention?.status !== 'pending');@@ -95,21 +95,26 @@ export const getWorkflowCompletionStatus = (return 'partial';};-export const getToolFirstDetail = (tool: ChatToolPayloadWithResult): string => {+/**+ * Identifier-aware action label ("Run command" / 执行命令) — the same builtin+ * per-API copy the collapsed inspector rows use; workflow display name (or+ * title-cased apiName) otherwise.+ */+const getToolActionLabel = (tool: ChatToolPayloadWithResult): string => {+ const builtinLabel = tool.identifier+ ? t(`builtins.${tool.identifier}.apiName.${tool.apiName}`, { defaultValue: '', ns: 'plugin' })+ : '';+ return builtinLabel || getToolDisplayName(tool.apiName);+};++/** The single most informative token from the args — never the raw args dump. */+const getToolKeywordDetail = (tool: ChatToolPayloadWithResult): string => {try {- const args = JSON.parse(tool.arguments || '{}');- const values = Object.values(args);- for (const val of values) {- if (typeof val === 'string' && val.trim()) {- return val.length > TOOL_FIRST_DETAIL_MAX_CHARS- ? val.slice(0, TOOL_FIRST_DETAIL_MAX_CHARS) + TOOL_HEADLINE_TRUNCATION_SUFFIX- : val;- }- }+ return extractToolKeyword(JSON.parse(tool.arguments || '{}')) ?? '';} catch {// arguments still streaming or invalid+ return '';}- return '';};/** Optional progress line from tool-runtime state (pluginState → result.state) or metadata */@@ -130,7 +135,7 @@ const getResultStepMessage = (tool: ChatToolPayloadWithResult): string => {export const getExplicitStepHeadlineLine = (tool: ChatToolPayloadWithResult): string => {const step = getResultStepMessage(tool).trim();if (!step) return '';- const label = getToolDisplayName(tool.apiName);+ const label = getToolActionLabel(tool);const short =step.length > TOOL_HEADLINE_DETAIL_MAX_CHARS? step.slice(0, TOOL_HEADLINE_DETAIL_TRUNCATE_LEN) + TOOL_HEADLINE_TRUNCATION_SUFFIX@@ -138,18 +143,15 @@ export const getExplicitStepHeadlineLine = (tool: ChatToolPayloadWithResult): streturn `${label}: ${short}`;};-/** C — tool label + first string arg (no explicit step). */+/**+ * C — action label + one keyword (no explicit step). This is the shining line+ * of a RUNNING collapsed workflow, so it reads as a sentence ("执行命令+ * monthly.ts"), never as a raw args dump.+ */export const getToolFallbackHeadlineLine = (tool: ChatToolPayloadWithResult): string => {- const label = getToolDisplayName(tool.apiName);- const fromArgs = getToolFirstDetail(tool).trim();- if (fromArgs) {- const short =- fromArgs.length > TOOL_HEADLINE_DETAIL_MAX_CHARS- ? fromArgs.slice(0, TOOL_HEADLINE_DETAIL_TRUNCATE_LEN) + TOOL_HEADLINE_TRUNCATION_SUFFIX- : fromArgs;- return `${label}: ${short}`;- }- return label;+ const label = getToolActionLabel(tool);+ const keyword = getToolKeywordDetail(tool);+ return keyword ? `${label} ${keyword}` : label;};/**diff --git a/src/features/Portal/AcceptanceCheck/Title.tsx b/src/features/Portal/AcceptanceCheck/Title.tsxindex 5e239ae8153..81af76e0938 100644--- a/src/features/Portal/AcceptanceCheck/Title.tsx+++ b/src/features/Portal/AcceptanceCheck/Title.tsx@@ -1,7 +1,7 @@import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useAcceptanceBundle } from '@/features/Acceptance';+import { checkDisplayTitle, useAcceptanceBundle } from '@/features/Acceptance';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';@@ -11,14 +11,18 @@ import { chatPortalSelectors } from '@/store/chat/selectors';* with several panels open needs to tell them apart.*/const Title = memo(() => {- const { t } = useTranslation('chat');+ const { t } = useTranslation(['chat', 'verify']);const portal = useChatStore(chatPortalSelectors.acceptanceCheckPortal);const { data } = useAcceptanceBundle(portal?.acceptanceId ?? null);const check = data?.checks.find((item) => item.id === portal?.checkId);if (!check) return t('taskDetail.acceptance.detailTitle');- return check.seq ? `C${check.seq} · ${check.title}` : check.title;+ const title = checkDisplayTitle(+ check.title,+ t('acceptance.checks.holisticTitle', { ns: 'verify' }),+ );+ return check.seq ? `C${check.seq} · ${title}` : title;});Title.displayName = 'AcceptanceCheckPortalTitle';diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsxindex 73b16c18e04..0a053d1af9d 100644--- a/src/features/Portal/GoalNode/Body.tsx+++ b/src/features/Portal/GoalNode/Body.tsx@@ -6,6 +6,11 @@ import { SquareArrowOutUpRight } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import {+ coordinatorGateReason,+ coordinatorReasonCopy,+ viewGateKind,+} from '@/features/AgentGoals/ProcessControl/coordinatorCopy';import {buildGoalGraphView,type GoalNodeView,@@ -141,6 +146,14 @@ const Body = memo(() => {const { node } = nodeView;const isFinding = node.kind === 'finding';+ // Coordinator gates localize; arbitrary gates keep their stored copy.+ const gateKind = node.kind === 'decision' ? viewGateKind(nodeView) : undefined;+ const rawGateReason = gateKind ? coordinatorGateReason(nodeView.decision?.question) : undefined;+ const gateReasonCopy = coordinatorReasonCopy(rawGateReason);+ const gateReasonText = gateReasonCopy+ ? t(gateReasonCopy.key as any, gateReasonCopy.params)+ : rawGateReason;+return (<Flexbox flex={1} gap={16} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}><Flexbox horizontal align={'center'} gap={8}>@@ -173,8 +186,9 @@ const Body = memo(() => {))}{node.kind === 'decision' && nodeView.decision && (- <Section title={t('goalProcess.gate.why')}>- <Text fontSize={13}>{nodeView.decision.question}</Text>+ <Section title={t('goalProcess.gate.decisionPointLabel')}>+ {/* State the problem itself; the resolution options carry the choices. */}+ <Text fontSize={13}>{gateReasonText ?? nodeView.decision.question}</Text></Section>)}diff --git a/src/features/Portal/portalWidth.test.ts b/src/features/Portal/portalWidth.test.tsindex 71eeaa4e407..c47ae98f6f0 100644--- a/src/features/Portal/portalWidth.test.ts+++ b/src/features/Portal/portalWidth.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {CHAT_PORTAL_MAX_WIDTH,+ CHAT_PORTAL_TASK_WIDTH,CHAT_PORTAL_TOOL_UI_WIDTH,CHAT_PORTAL_WIDE_WIDTH,CHAT_PORTAL_WIDTH,@@ -23,6 +24,8 @@ describe('getPortalViewMinWidth', () => {PortalViewType.AcceptanceCheck,PortalViewType.AgentDetail,PortalViewType.Artifact,+ PortalViewType.GoalMetric,+ PortalViewType.GoalNode,PortalViewType.TaskDetail,PortalViewType.Thread,PortalViewType.ToolUI,@@ -39,6 +42,14 @@ describe('getPortalViewWidth', () => {).toBe(CHAT_PORTAL_WIDE_WIDTH);});+ it('opens task and goal-node detail at the task width even when the legacy width is narrow', () => {+ for (const viewType of [PortalViewType.TaskDetail, PortalViewType.GoalNode]) {+ expect(getPortalViewWidth({ legacyWidth: CHAT_PORTAL_WIDTH, viewType })).toBe(+ CHAT_PORTAL_TASK_WIDTH,+ );+ }+ });+it('remembers the width per view instead of sharing one value', () => {const widths = { [PortalViewType.Acceptance]: 1000, [PortalViewType.TaskDetail]: 620 };@@ -50,6 +61,23 @@ describe('getPortalViewWidth', () => {).toBe(480);});+ it('keeps scoped surfaces (goal page) separate from the chat widths', () => {+ const widths = { 'goal:taskDetail': 1000, [PortalViewType.TaskDetail]: 700 };++ expect(getPortalViewWidth({ viewType: PortalViewType.TaskDetail, widths })).toBe(700);+ expect(getPortalViewWidth({ scope: 'goal', viewType: PortalViewType.TaskDetail, widths })).toBe(+ 1000,+ );+ // a scoped surface with no memory of its own ignores the chat memory+ expect(+ getPortalViewWidth({+ scope: 'goal',+ viewType: PortalViewType.TaskDetail,+ widths: { [PortalViewType.TaskDetail]: 700 },+ }),+ ).toBe(CHAT_PORTAL_TASK_WIDTH);+ });+it('falls back to the legacy width for views without an explicit default', () => {expect(getPortalViewWidth({ legacyWidth: 520, viewType: PortalViewType.Home })).toBe(520);expect(getPortalViewWidth({ viewType: PortalViewType.Home })).toBe(CHAT_PORTAL_WIDTH);diff --git a/src/features/Portal/portalWidth.ts b/src/features/Portal/portalWidth.tsindex 64d7fdf1679..464ab376a13 100644--- a/src/features/Portal/portalWidth.ts+++ b/src/features/Portal/portalWidth.ts@@ -1,5 +1,6 @@import {CHAT_PORTAL_MAX_WIDTH,+ CHAT_PORTAL_TASK_WIDTH,CHAT_PORTAL_TOOL_UI_WIDTH,CHAT_PORTAL_WIDE_WIDTH,CHAT_PORTAL_WIDTH,@@ -22,6 +23,8 @@ const VIEW_MIN_WIDTH: PortalWidths = {[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.AgentDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.Artifact]: CHAT_PORTAL_TOOL_UI_WIDTH,+ [PortalViewType.GoalMetric]: CHAT_PORTAL_TOOL_UI_WIDTH,+ [PortalViewType.GoalNode]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.TaskDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.Thread]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.ToolUI]: CHAT_PORTAL_TOOL_UI_WIDTH,@@ -36,12 +39,27 @@ const VIEW_MIN_WIDTH: PortalWidths = {const VIEW_DEFAULT_WIDTH: PortalWidths = {[PortalViewType.Acceptance]: CHAT_PORTAL_WIDE_WIDTH,[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_WIDE_WIDTH,+ // Task / goal-node detail pack status, instruction, sub-tasks and the+ // activity feed into one column — wider than the reading column, but the+ // full document width crowds the page it sits next to.+ [PortalViewType.GoalNode]: CHAT_PORTAL_TASK_WIDTH,+ [PortalViewType.TaskDetail]: CHAT_PORTAL_TASK_WIDTH,};const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);const normalizeViewType = (viewType?: PortalViewType | null) => viewType ?? PortalViewType.Home;+/**+ * Surfaces that host the Portal remember widths independently: dragging the+ * task pane on the goal page must not resize the same pane in the chat+ * conversation. The chat surface (no scope) keeps the unprefixed legacy keys.+ */+export const portalWidthStorageKey = (viewType?: PortalViewType | null, scope?: string): string => {+ const key = normalizeViewType(viewType);+ return scope ? `${scope}:${key}` : key;+};+export const getPortalViewMinWidth = (viewType?: PortalViewType | null): number =>VIEW_MIN_WIDTH[normalizeViewType(viewType)] ?? CHAT_PORTAL_WIDTH;@@ -51,17 +69,24 @@ interface GetPortalViewWidthParams {* neither a remembered width nor an explicit default.*/legacyWidth?: number;+ /** Width-memory namespace (e.g. 'goal'); omitted for the chat surface. */+ scope?: string;viewType?: PortalViewType | null;- widths?: PortalWidths;+ widths?: Partial<Record<string, number>>;}export const getPortalViewWidth = ({legacyWidth,+ scope,viewType,widths,}: GetPortalViewWidthParams): number => {const key = normalizeViewType(viewType);const fallback = VIEW_DEFAULT_WIDTH[key] ?? legacyWidth ?? CHAT_PORTAL_WIDTH;- return clamp(widths?.[key] || fallback, getPortalViewMinWidth(key), CHAT_PORTAL_MAX_WIDTH);+ return clamp(+ widths?.[portalWidthStorageKey(key, scope)] || fallback,+ getPortalViewMinWidth(key),+ CHAT_PORTAL_MAX_WIDTH,+ );};diff --git a/src/features/Portal/usePortalPanelWidth.ts b/src/features/Portal/usePortalPanelWidth.tsnew file mode 100644index 00000000000..4d8898c65e6--- /dev/null+++ b/src/features/Portal/usePortalPanelWidth.ts@@ -0,0 +1,41 @@+import { CHAT_PORTAL_MAX_WIDTH } from '@/const/layoutTokens';+import type { PortalViewType } from '@/store/chat/slices/portal/initialState';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';++import { getPortalViewMinWidth, getPortalViewWidth, portalWidthStorageKey } from './portalWidth';++/**+ * Shared width state for every surface that hosts the Portal in a right-hand+ * panel: the same per-view min/default widths and drag persistence. Pass a+ * `scope` (e.g. 'goal') so the surface remembers its widths independently of+ * the chat conversation; scoped surfaces also ignore the chat legacy width.+ */+export const usePortalPanelWidth = (viewType?: PortalViewType | null, scope?: string) => {+ const [legacyWidth, portalWidths, updateSystemStatus] = useGlobalStore((s) => [+ systemStatusSelectors.portalWidth(s),+ systemStatusSelectors.portalWidths(s),+ s.updateSystemStatus,+ ]);++ const width = getPortalViewWidth({+ legacyWidth: scope ? undefined : legacyWidth,+ scope,+ viewType,+ widths: portalWidths,+ });++ const updateWidth = (next?: string | number) => {+ const parsed = typeof next === 'string' ? Number.parseInt(next) : next;+ if (!parsed || parsed === width) return;+ // updateSystemStatus deep-merges, so the other views keep their widths+ updateSystemStatus({ portalWidths: { [portalWidthStorageKey(viewType, scope)]: parsed } });+ };++ return {+ maxWidth: CHAT_PORTAL_MAX_WIDTH,+ minWidth: getPortalViewMinWidth(viewType),+ updateWidth,+ width,+ };+};diff --git a/src/routes/(main)/agent/features/Portal/features/Portal.tsx b/src/routes/(main)/agent/features/Portal/features/Portal.tsxindex 4594de41832..5bb2a3b412f 100644--- a/src/routes/(main)/agent/features/Portal/features/Portal.tsx+++ b/src/routes/(main)/agent/features/Portal/features/Portal.tsx@@ -3,17 +3,13 @@import { type DraggablePanelProps } from '@lobehub/ui';import { DraggablePanel } from '@lobehub/ui';import { createStaticStyles, useResponsive } from 'antd-style';-import isEqual from 'fast-deep-equal';import { type PropsWithChildren } from 'react';import { Activity, memo, useState } from 'react';-import { CHAT_PORTAL_MAX_WIDTH } from '@/const/layoutTokens';-import { getPortalViewMinWidth, getPortalViewWidth } from '@/features/Portal/portalWidth';+import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';import { useChatStore } from '@/store/chat';import { chatPortalSelectors, portalThreadSelectors } from '@/store/chat/selectors';import { PortalViewType } from '@/store/chat/slices/portal/initialState';-import { useGlobalStore } from '@/store/global';-import { systemStatusSelectors } from '@/store/global/selectors';const styles = createStaticStyles(({ css, cssVar }) => ({content: css`@@ -46,13 +42,7 @@ const PortalPanel = memo(({ children }: PropsWithChildren) => {// legacy threads live outside the view stack, so they surface as an empty stackconst viewType = currentViewType ?? (showThread ? PortalViewType.Thread : null);- const [legacyWidth, portalWidths, updateSystemStatus] = useGlobalStore((s) => [- systemStatusSelectors.portalWidth(s),- systemStatusSelectors.portalWidths(s),- s.updateSystemStatus,- ]);-- const portalWidth = getPortalViewWidth({ legacyWidth, viewType, widths: portalWidths });+ const { maxWidth, minWidth, updateWidth, width: portalWidth } = usePortalPanelWidth(viewType);const [tmpWidth, setWidth] = useState(portalWidth);if (tmpWidth !== portalWidth) setWidth(portalWidth);@@ -62,12 +52,10 @@ const PortalPanel = memo(({ children }: PropsWithChildren) => {const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {if (!size) return;const nextWidth = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;- if (!nextWidth) return;+ if (!nextWidth || nextWidth === portalWidth) return;- if (isEqual(nextWidth, portalWidth)) return;setWidth(nextWidth);- // updateSystemStatus deep-merges, so the other views keep their widths- updateSystemStatus({ portalWidths: { [viewType ?? PortalViewType.Home]: nextWidth } });+ updateWidth(nextWidth);};return (@@ -76,8 +64,8 @@ const PortalPanel = memo(({ children }: PropsWithChildren) => {defaultSize={{ width: tmpWidth }}expand={showPortal}expandable={false}- maxWidth={CHAT_PORTAL_MAX_WIDTH}- minWidth={getPortalViewMinWidth(viewType)}+ maxWidth={maxWidth}+ minWidth={minWidth}mode={lg ? 'fixed' : 'float'}placement={'right'}showHandleWhenCollapsed={false}diff --git a/src/services/goal.ts b/src/services/goal.tsindex 40303e69b17..e2053fcc666 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -25,6 +25,8 @@ class GoalService {config?: GoalConfig;/** Set by the `/goal` tool so the seeded graph is authored by the agent. */createdByAgentId?: string;+ /** Structured acceptance criteria — persisted rows that gate the terminal acceptance. */+ criteria?: Array<{ description?: string; instruction?: string; title: string }>;maxRounds?: number;maxTotalCost?: number;/** The user's ask in their own words — shown on the seeded problem node. */@@ -38,6 +40,10 @@ class GoalService {return data;};+ /** Rebind which persisted verify criteria gate this goal's terminal acceptance. */+ setAcceptanceCriteria = async (id: string, criteriaIds: string[]) =>+ lambdaClient.goal.setAcceptanceCriteria.mutate({ criteriaIds, id });+/** Delete a goal and its graph. The dispatched Work Tasks are left in place. */delete = async (id: string) => lambdaClient.goal.delete.mutate({ id });diff --git a/src/services/verify.ts b/src/services/verify.tsindex 652932dc95f..99fa279cf55 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -24,6 +24,9 @@ import type {} from '@/database/schemas/verify';import { lambdaClient } from '@/libs/trpc/client';+/** Criterion row plus the judge instruction resolved from its linked document. */+export type GoalCriterionWithInstruction = VerifyCriterionItem & { instruction?: string };+export type AcceptanceBundle = Awaited<ReturnType<typeof lambdaClient.acceptance.getBundle.query>>;export type AcceptanceBySubject = Awaited<ReturnType<typeof lambdaClient.acceptance.getBySubject.query>@@ -426,6 +429,10 @@ export class VerifyService {lambdaClient.verify.createCriteria.mutate({ drafts }) as Promise<string[]>;// ---- criteria / rubric management ----+ /** Resolve a specific criteria id list (e.g. a goal's acceptance standard), in order. */+ getCriteria = (ids: string[]): Promise<GoalCriterionWithInstruction[]> =>+ lambdaClient.verify.getCriteria.query({ ids }) as Promise<GoalCriterionWithInstruction[]>;+listCriteria = (): Promise<VerifyCriterionItem[]> =>lambdaClient.verify.listCriteria.query() as Promise<VerifyCriterionItem[]>;diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex c01310e83b5..57ef60c77eb 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -24,6 +24,7 @@ import {import { type ToolsEngine } from '@lobechat/context-engine';import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';import {+ buildGoalOverviewContext,type ConversationContext,type LobeAgentChatConfig,type MessageMetadata,@@ -56,6 +57,7 @@ import { type ChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { getElectronStoreState } from '@/store/electron';+import { getGoalStoreState } from '@/store/goal';import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';import { getTaskStoreState } from '@/store/task';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';@@ -446,6 +448,22 @@ export class StreamingExecutorActionImpl {}}+ const viewedGoal = operation?.context.viewedGoal;+ if (viewedGoal) {+ try {+ const snapshot = getGoalStoreState().goalGraphById[viewedGoal.goalId];+ if (snapshot) {+ runtimeInitialContext = {+ ...runtimeInitialContext,+ goalOverview: buildGoalOverviewContext(snapshot),+ };+ log('[internal_createAgentState] injected goal overview context (%s)', viewedGoal.goalId);+ }+ } catch (error) {+ log('[internal_createAgentState] Failed to build goal overview context: %o', error);+ }+ }+const mergedRuntimeInitialContext =runtimeInitialContext || initialContext?.initialContext? {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 8ece649e7b7..61fa4a201c4 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -706,6 +706,10 @@ export class GatewayActionImpl {taskId,threadId: executionContext.threadId,topicId: executionContext.topicId,+ // Goal-page side conversation: lets the server build the goal+ // overview injection for gateway-run agents (mirrors the client+ // streaming executor).+ viewedGoal: executionContext.viewedGoal,},...desktopDeviceHints,fileIds,diff --git a/src/store/goal/index.ts b/src/store/goal/index.tsindex e621984ca5f..59171211251 100644--- a/src/store/goal/index.ts+++ b/src/store/goal/index.ts@@ -19,4 +19,6 @@ export const useGoalStore = createWithEqualityFn<GoalStore>()(shallow,);+export const getGoalStoreState = () => useGoalStore.getState();+export { goalSelectors } from './selectors';