🤯 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(agent): add goal views and acceptance progress (#17995)
Arvin Xu10dbe1a16ca3
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 796062d251b..19283392339 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -58,6 +58,7 @@ const createSchema = z.object({// 'schedule', `schedulePattern` (cron) is required for the central// schedule-dispatch sweep to pick the task up.automationMode: z.enum(['heartbeat', 'schedule']).optional(),+ config: z.record(z.string(), z.unknown()).optional(),createdByAgentId: z.string().optional(),description: z.string().optional(),editorData: z.unknown().optional(),@@ -104,6 +105,7 @@ const updateSchema = z.object({const listSchema = z.object({assigneeAgentId: z.string().optional(),+ hasGoal: z.boolean().optional(),limit: z.number().min(1).max(100).default(50),offset: z.number().min(0).default(0),parentIdentifier: z.string().optional(),@@ -129,6 +131,7 @@ const groupListSchema = z.object({).min(1).max(10),+ hasGoal: z.boolean().optional(),parentTaskId: z.string().nullish(),visibility: z.enum(['private', 'public']).optional(),});@@ -455,6 +458,27 @@ export const taskRouter = router({}}),+ deleteGoal: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ const model = ctx.taskModel;+ const task = await resolveOrThrow(model, input.id);+ if (!(task.config as { goal?: unknown } | null)?.goal) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task is not a goal root' });+ }+ assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');+ const count = await model.deleteSubtree(task.id);+ return { count, data: task, message: 'Goal deleted', success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:deleteGoal]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to delete goal',+ });+ }+ }),+detail: taskProcedure.input(idInput).query(async ({ input, ctx }) => {try {const detail = await ctx.taskService.getTaskDetail(input.id);diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex 3021679dbac..144bcacba9c 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -930,7 +930,7 @@ describe('TaskService', () => {});});- it('should propagate topic completedAt to the topic activity', async () => {+ it('should propagate topic completedAt and cost to the topic activity', async () => {const task = {assigneeAgentId: null,assigneeUserId: null,@@ -957,6 +957,7 @@ describe('TaskService', () => {handoff: null,seq: 1,status: 'completed',+ totalCost: '0.0425',topicId: 'topic-done',},{@@ -965,6 +966,7 @@ describe('TaskService', () => {handoff: null,seq: 2,status: 'running',+ totalCost: null,topicId: 'topic-running',},];@@ -987,7 +989,9 @@ describe('TaskService', () => {const done = topicActivities.find((a) => a.id === 'topic-done');const running = topicActivities.find((a) => a.id === 'topic-running');expect(done?.completedAt).toBe('2024-01-03T00:01:30.000Z');+ expect(done?.cost).toBe(0.0425);expect(running?.completedAt).toBeUndefined();+ expect(running?.cost).toBeNull();});it('should not include topicCount when no topics exist', async () => {diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex cad5deba395..a9adbba8f70 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -53,6 +53,7 @@ export interface CreateTaskInput {assigneeAgentId?: string;assigneeUserId?: string;automationMode?: 'heartbeat' | 'schedule';+ config?: Record<string, unknown>;// Runtime-state pockets stored on the task row (tasks.context JSONB). Used at// creation to record `context.origin` — the creator conversation pointer.context?: TaskContext;@@ -152,7 +153,7 @@ export class TaskService {if (input.assigneeAgentId) {const agentInfo = await this.agentModel.getAgentSnapshotForTaskCreate(input.assigneeAgentId);if (agentInfo) {- if (agentInfo.snapshot) createData.config = agentInfo.snapshot;+ if (agentInfo.snapshot) createData.config = { ...agentInfo.snapshot, ...createData.config };agentVisibility = agentInfo.visibility;}}@@ -723,6 +724,7 @@ export class TaskService {? { schedule: { pattern: s.schedulePattern, timezone: s.scheduleTimezone } }: {}),status: s.status,+ updatedAt: s.updatedAt ? new Date(s.updatedAt).toISOString() : undefined,};});};@@ -822,6 +824,7 @@ export class TaskService {return {author: topicAgentId ? authorMap.get(topicAgentId) : undefined,completedAt: toISO(t.completedAt),+ cost: t.totalCost == null ? null : Number(t.totalCost),// Raw last assistant message of the run, shown alongside// the synthesized summary on the run card.content: handoff?.content,@@ -931,6 +934,7 @@ export class TaskService {subtasks,activities: activities.length > 0 ? activities : undefined,topicCount: topics.length > 0 ? topics.length : undefined,+ updatedAt: task.updatedAt ? new Date(task.updatedAt).toISOString() : undefined,workspace: workspaceFolders.length > 0 ? workspaceFolders : undefined,workspaceId: task.workspaceId ?? null,};diff --git a/docs/development/agent-goals-design.md b/docs/development/agent-goals-design.mdnew file mode 100644index 00000000000..6f12b5eb50c--- /dev/null+++ b/docs/development/agent-goals-design.md@@ -0,0 +1,341 @@+# Agent Goals: a durable goal loop on top of Tasks++## Summary++An agent goal should not be another kind of chat session or a process that stays alive forever.+It should be a durable control loop whose execution plan is represented by the existing task tree.++The proposed relationship is:++```text+Agent+ -> Goal (intent, success contract, policy, budget, lifecycle)+ -> root Task (current plan)+ -> subtasks + dependencies (execution graph)+ -> Task Topics (individual attempts)+ -> Agent Operations (runtime/cost/trace)+```++The agent is the owner and executor. The goal is the long-lived outcome contract. Tasks are the+mutable execution plan. Topics are finite execution attempts. No worker or LLM call is kept alive+between attempts.++This reuses the strongest parts of the task system without making every task a permanent agent+goal.++## Why a first-class Goal is still needed++The current task system already provides:++- assignee agents;+- unbounded task trees and dependency edges;+- heartbeat and cron automation;+- topic-per-run history and handoff summaries;+- operation linkage, cost data, documents, comments, and briefs;+- human checkpoints and pause/resume states;+- verify-backed acceptance for task delivery.++A task can therefore be the execution substrate of a goal. It should not be the goal aggregate+itself, because a durable goal has semantics that do not belong to an individual plan node:++- an invariant objective that survives replanning;+- an explicit, machine-evaluable success contract;+- a controller lifecycle separate from task execution status;+- wake-up policies from time and external events;+- global cost, time, iteration, and concurrency budgets;+- a record of why the controller continued, waited, replanned, or stopped;+- ownership at the agent level, including which goals are currently active.++If these are stored only in `tasks.config`, the root task becomes overloaded, goal discovery by+agent is weak, status transitions become ambiguous, and future replanning cannot replace the root+plan cleanly.++## Domain model++### `agent_goals`++Recommended columns:++| Field | Purpose |+| -------------------------------------- | ----------------------------------------------------------------------------------- |+| `id` | Stable goal identity |+| `agentId` | Agent that owns and pursues the goal |+| `userId`, `workspaceId`, `visibility` | Existing ownership and workspace rules |+| `rootTaskId` | Current root task / plan entry point |+| `title`, `objective` | Human-readable outcome; objective is immutable while a run is active |+| `successCriteria` | Structured verify criteria and evaluator configuration |+| `status` | `draft`, `active`, `waiting`, `paused`, `achieved`, `blocked`, `canceled`, `failed` |+| `policy` | Replan cadence, retry/fuse, allowed triggers, concurrency |+| `budget` | Max USD, active runtime, rounds, operations, and optional deadline |+| `progress` | Cached summary, score, last decision, and counters for cheap UI reads |+| `nextWakeAt` | Durable time-based wake-up hint |+| `leaseOwner`, `leaseExpiresAt` | Single-controller execution lease |+| `startedAt`, `completedAt`, timestamps | Lifecycle audit |++Keep `rootTaskId` nullable during draft creation. Do not put `goalId` only inside task JSONB: add a+nullable indexed `tasks.goalId` foreign key so every plan node and operation can be queried cheaply.+The root task is the node whose `id === goal.rootTaskId`.++An agent may own multiple goals, but MVP should default to one active goal per agent. Supporting+multiple active goals later is a scheduling-policy decision, not a schema rewrite.++### `agent_goal_runs`++Each controller decision is an append-only run, distinct from a task topic:++| Field | Purpose |+| -------------------------- | ------------------------------------------------------------------------------- |+| `goalId`, `seq` | Ordered controller history and idempotency boundary |+| `triggerType`, `triggerId` | `created`, `timer`, `signal`, `task_completed`, `verify_settled`, `manual` |+| `status` | `queued`, `running`, `waiting`, `completed`, `failed`, `canceled` |+| `decision` | `execute`, `decompose`, `replan`, `verify`, `wait`, `achieve`, `pause`, `block` |+| `reason` | Human-readable controller rationale |+| `inputSnapshot`, `output` | Reproducible state and selected actions |+| `operationId` | Agent operation used for planning, when an LLM was needed |+| timestamps | Latency and audit |++Use a uniqueness constraint over the durable trigger identity, for example+`(goalId, triggerType, triggerId)`, so at-least-once queue delivery cannot create two rounds.++### Optional `agent_goal_events`++Do not add this in the first migration unless product needs a user-facing activity stream that+cannot be reconstructed. Agent Signal traces plus `agent_goal_runs` cover the initial audit need.++## Runtime architecture++### Finite controller turns, not a permanent process++“7x24 running” means that the goal can always resume from durable state. It must not mean an open+HTTP response, an endless LLM loop, or an in-memory timer.++Every controller turn is finite:++```text+wake event+ -> acquire goal lease+ -> load goal + task graph + latest handoffs + verify state + budgets+ -> choose exactly one bounded decision+ -> persist decision and enqueue/execute bounded actions+ -> set nextWakeAt or wait for an event+ -> release lease+```++Production execution should use a durable queue/workflow. Local mode may use in-process scheduling+for developer ergonomics, but must be documented as non-durable across restarts.++### Goal controller decisions++The controller is not another general chat agent. Give it a narrow output schema:++```ts+type GoalDecision =+ | { type: 'execute'; taskIds: string[] }+ | { type: 'decompose'; parentTaskId: string; tasks: ProposedTask[] }+ | { type: 'replan'; mutations: TaskGraphMutation[]; reason: string }+ | { type: 'verify'; subjectTaskId: string }+ | { type: 'wait'; reason: string; wakeAt?: string }+ | { type: 'achieve'; evidence: EvidenceRef[] }+ | { type: 'pause'; reason: string }+ | { type: 'block'; reason: string; requestedInput?: string };+```++One turn may start a bounded set of ready tasks in parallel, subject to the goal concurrency policy.+It must not recursively call itself. Completion events enqueue the next controller turn.++### Wake-up sources++Use Agent Signal as the event interpretation and routing layer:++```text+task topic completed / verify settled / document changed / connector event / timer+ -> source event+ -> signal.goal.wake-requested+ -> action.goal.enqueue-turn+ -> durable goal workflow+```++Agent Signal should decide whether an event matters and dedupe it. The goal controller should own+goal state transitions and task-plan mutation. This avoids coupling every connector or task hook to+goal orchestration.++Time wake-ups can reuse the task scheduler conceptually, but should expose a generic durable+`scheduleGoalWake` API rather than pretending every wake is a heartbeat task topic. A delayed+message is one-shot; after handling it, the controller chooses whether another wake is needed.++### Task execution and feedback++The existing `TaskRunnerService` remains the only path that starts task work. A goal controller+selects ready tasks; it does not execute tools itself.++When a topic completes:++1. Task lifecycle persists status, handoff, brief, and verify linkage as today.+2. A source event records the durable fact.+3. Goal policy maps it to a wake request if the task has `goalId`.+4. The controller reloads authoritative DB state and decides what is next.++This keeps lifecycle hooks observational and makes retries safe.++## Success, replanning, and stopping++### Success is verified, not self-declared++The controller may propose `achieve`, but the goal only reaches `achieved` after its structured+success criteria pass. Reuse Verify as the acceptance plane. Evidence must reference durable+artifacts, task outputs, connector objects, or checks rather than only an LLM narrative.++Use two nested loops:++```text+inner loop: one task attempt -> verify/repair that delivery+outer loop: goal progress review -> execute more tasks or replan the task graph+```++The existing `feat/goal-loop-server` exploration already demonstrates the useful inner primitive:+a failed verify result can spawn a fresh topic, carry handoffs and failed checks forward, and stop on+round/cost budgets. The agent-level goal controller should generalize the outer loop rather than+duplicating that logic inside every task.++### Waiting, blocked, and paused are different++- `waiting`: healthy; awaiting a known event or future time. May auto-resume.+- `blocked`: the agent cannot make meaningful progress without new authority/input. Never+ auto-resume unless the blocking condition changes.+- `paused`: explicitly stopped by a user, policy, fuse, or budget. Requires an explicit resume or+ policy change.+- `failed`: unrecoverable controller/system failure after the retry policy is exhausted.++A goal should not become blocked after one weak attempt. Persist a repeated-condition fingerprint;+only block once the same condition survives the configured number of controller turns.++### Budgets and safety++Every active goal needs hard server-enforced limits:++- total cost and per-day cost;+- max controller turns and max task attempts;+- max concurrent task topics;+- optional deadline and active-hours window;+- consecutive runtime failure fuse;+- allowed tool/plugin policy and human-approval policy.++Budget checks happen both before enqueue and immediately before execution. The database is the+authority because queued work may be stale.++Never promise literal uninterrupted execution. Billing failure, revoked credentials, connector+outages, approval requirements, and infrastructure incidents must transition to a visible state and+brief rather than spin indefinitely.++## Lease and idempotency rules++At-least-once delivery is assumed.++1. Acquire a short DB/Redis lease keyed by `goalId` before creating a run.+2. Insert the run using its unique trigger key.+3. Re-read goal status and budgets after acquiring the lease.+4. Use stable action idempotency keys such as `goal:{goalId}:run:{seq}:task:{taskId}:execute`.+5. Task execution still relies on its existing in-flight topic conflict guard.+6. Persist `nextWakeAt` before publishing the delayed wake; save the returned queue message id when+ cancellation is supported.+7. A stale wake is harmless: the handler exits when status, generation, or `nextWakeAt` no longer+ matches.++Add a `generation` integer to the goal if edits/resume should invalidate all queued work cheaply.++## MVP rollout++### Phase 0: align the existing task goal loop++Before adding the aggregate, finish or reuse the existing `feat/goal-loop-server` work:++- `TaskGoalConfig` under `tasks.config.goal`;+- verify-failure continuation into a fresh task topic;+- round and USD budgets;+- failed-check and handoff carry-over;+- goal tool-card state projection.++Treat this as a task-level execution primitive, not the final agent-goal model.++### Phase 1: first-class aggregate and manual controller++- Add `agent_goals`, `agent_goal_runs`, and indexed `tasks.goalId`.+- Add Goal model/service and CRUD/status transitions.+- Create a goal and its root task atomically.+- Implement a manually invoked controller turn with pure decision validation.+- Support one active goal per agent and a small concurrency cap.+- Reuse TaskRunner and Verify; do not add event-driven wakes yet.++This phase proves the semantics and UI without claiming 7x24 durability.++### Phase 2: durable time and lifecycle wakes++- Add durable goal workflow and lease/idempotency.+- Emit task-completion and verify-settled source events.+- Add Agent Signal goal wake policy and one-shot timer wakes.+- Add restart recovery scan for active goals whose `nextWakeAt` is overdue and have no valid lease.+- Add observability: queue delay, controller latency, decision counts, budget use, stuck goals.++At this point the system can honestly claim unattended continuous pursuit in queue mode.++### Phase 3: external signals and replanning++- Allow connector/domain events to wake selected goals.+- Add constrained task-graph mutation operations.+- Add evidence-aware progress evaluation and replanning prompts.+- Support multiple goals per agent with explicit priority/fairness policy.++## Suggested code boundaries++```text+packages/database/src/schemas/agentGoal.ts+packages/database/src/models/agentGoal.ts+packages/database/src/models/agentGoalRun.ts+packages/types/src/agentGoal/++apps/server/src/services/agentGoal/+ AgentGoalService.ts # CRUD and lifecycle invariants+ GoalController.ts # bounded decide/apply turn+ GoalContextBuilder.ts # goal + task graph + evidence snapshot+ GoalBudgetService.ts+ GoalLeaseService.ts+ decisions.ts # schema and validation++apps/server/src/workflows/agentGoal/+apps/server/src/services/agentSignal/policies/goalWake/+apps/server/src/routers/lambda/agentGoal.ts+```++Avoid placing the controller inside `TaskLifecycleService`; lifecycle completion must remain+bounded and resilient. It should emit/enqueue and return.++## MVP acceptance criteria++The first durable release is complete when all of these are true:++1. Creating a goal atomically creates an agent-owned goal and root task.+2. A controller turn can decompose the root into task dependencies and start only ready tasks.+3. Duplicate wake delivery cannot create duplicate runs or task topics.+4. A server restart does not lose an active goal's future wake in queue mode.+5. Task/verify completion wakes the goal without a foreground client connection.+6. Verified success is the only automatic path to `achieved`.+7. Cost, attempt, concurrency, pause, and cancellation limits are enforced server-side.+8. Waiting, blocked, budget-paused, runtime-failed, and achieved states are distinguishable in DB+ and UI.+9. Every controller decision is inspectable with its trigger, reason, task mutations, operation, and+ cost.+10. Local mode clearly reports that timers are development-only and non-durable.++## Product shape++The primary agent surface should show a single “Current goal” card with:++- objective and verified progress;+- current plan (the existing task tree);+- current state and the next expected wake-up;+- spend/round/deadline budget;+- latest controller reason;+- pause, resume, edit budget, and cancel controls.++The user should not need to understand controller turns. They should see what the agent is pursuing,+what it is doing now, what it is waiting for, and what proof will count as done.diff --git a/docs/development/agent-goals-product-ux-audit.md b/docs/development/agent-goals-product-ux-audit.mdnew file mode 100644index 00000000000..c3ba0aaffa1--- /dev/null+++ b/docs/development/agent-goals-product-ux-audit.md@@ -0,0 +1,105 @@+# Agent Goals product and UX audit++## Scope++Audited the complete implemented journey:++```text+Topic Goal lab gate+ → Agent navigation+ → Goal list+ → Goal detail+ → Acceptance checks and latest result+ → Task execution plan+ → Agent runs / operations+```++Evidence sources: task and acceptance domain types, Task lifecycle/store behavior,+Goal list/detail routes, Agent navigation, Acceptance bundle hooks, and browser+verification against representative local data.++## Product model++| Concept | Business role | Terminal fact |+| -------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |+| Goal | Stable result the Agent keeps pursuing | The user-visible objective remains stable while its plan and runs change |+| Acceptance | Decision contract and evidence for whether the result is good enough | Human acceptance closes the delivery lifecycle; verifier output is supporting evidence |+| Task | Current executable plan for pursuing the Goal | Task status describes execution, not Goal success |+| Task execution | One scheduled/manual/heartbeat attempt represented by a task topic | Produces an execution outcome and may trigger verification or another round |+| Agent run | Gateway operation actually executed by an Agent | Supplies execution provenance; it does not by itself mean the Goal succeeded |++The UI therefore treats Goal as the lookup object, Acceptance as attached proof,+and Task/Agent Run as drill-down execution evidence.++## User view model++When a user opens Goals, the first scan must answer:++1. What outcomes is this Agent pursuing?+2. Which goals need attention and how close are they to acceptance?+3. On a Goal, what exactly is the target?+4. How much execution has happened (Task executions and Agent runs)?+5. What is the latest acceptance result, and what evidence supports it?++Chronology, task configuration, individual topics and operations are secondary+audit dimensions. They remain accessible through the execution-plan drill-down.++## Implemented corrections++- Goal list defaults to a dense list for scanning and supports explicit List/Card switching.+- Goal detail begins with the complete Goal definition.+- The first screen then shows Acceptance progress, Task execution count, Agent run+ count, round budget, and the latest acceptance result.+- Acceptance checks are displayed as the proof attached to the Goal, not as an+ unrelated report.+- Current execution plan is secondary and links to the existing Task Detail.+- Loading, transient error, not-found and lab-gated deep-link states are distinct.++## End-to-end audit++| Stage | Expected behavior | Result |+| ----------- | ------------------------------------------------------------------------- | ------- |+| Gate | Disabled lab hides navigation and redirects Goal deep links | Covered |+| Entry | Goal is an Agent-level destination | Covered |+| Browse | Default list supports fast comparison; Card view remains available | Covered |+| Inspect | Goal definition and progress lead; execution internals are secondary | Covered |+| Judge | Acceptance checks and latest result are visible | Covered |+| Investigate | User can open the underlying Task execution plan | Covered |+| Recover | Fetch errors offer retry; missing Goal is not reported as a network error | Covered |++## Honest remaining boundaries++### Direct Goal creation — not modeled as a management-page event++Goals are currently created through the `/goal` conversation flow, which creates+the goal-marked root Task and Acceptance contract. The Goal page has no standalone+create event or form contract. Adding a decorative Create button would promise a+business event that does not yet exist. A future slice should first define whether+creation starts a conversation draft, creates a durable Goal immediately, or opens+a structured contract editor.++### At-scale browsing — data capability required++The current Goal query is capped at 100 records and has no cursor/search contract.+The view is suitable for the current Agent-level collection, but a 10k Goal manager+requires server-side pagination, search, sort and status facets so counts and empty+results remain truthful across the full set.++### Dedicated Goal lifecycle actions — intentionally delegated++Pause/resume/run controls currently belong to the underlying Task execution model.+Before adding Goal-level controls, the controller must define their business event:+whether they pause scheduling only, suspend all external wakes, or terminate the+Goal contract. Until then, Goal Detail links to Task Detail rather than presenting+ambiguous controls.++## Coverage signal++- High confidence: navigation, gate, list/detail information architecture,+ Acceptance projection, Task drill-down, local loading/error behavior.+- Medium confidence: Agent run count is derived from persisted/running operation+ provenance in task activities; the future dedicated Goal model should expose an+ explicit aggregate rather than relying on projection.+- Not covered by the current model: controller wake history, cost budget, deadline,+ lease ownership and Goal-level pause/terminate semantics described in the broader+ architecture proposal.diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 839b82d160c..2f190f71643 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -308,6 +308,75 @@"globalApproval.subtitle": "Waiting for your approval","globalApproval.title": "Approval needed","globalApproval.userRequestLabel": "Request",+ "goalDetail.acceptance": "Acceptance checks",+ "goalDetail.acceptanceError": "Could not load acceptance checks.",+ "goalDetail.acceptanceProgress": "Acceptance progress",+ "goalDetail.agentRun": "Agent run",+ "goalDetail.definition": "Goal definition",+ "goalDetail.deleteConfirm.content": "This goal and its task plan will be permanently deleted. Conversation history is retained.",+ "goalDetail.deleteConfirm.ok": "Delete goal",+ "goalDetail.deleteConfirm.title": "Delete this goal?",+ "goalDetail.executionOverview": "Execution overview",+ "goalDetail.executionOverviewDescription": "The complete task tree and latest runs for this goal.",+ "goalDetail.executionPlan": "Current execution plan",+ "goalDetail.instruction": "Goal instruction",+ "goalDetail.latestRuns": "Recent executions",+ "goalDetail.metrics.agentRuns": "Agent runs",+ "goalDetail.metrics.latestAcceptance": "Latest acceptance",+ "goalDetail.metrics.planItems": "Plan items",+ "goalDetail.metrics.progress": "Progress",+ "goalDetail.metrics.roundBudget": "Round budget",+ "goalDetail.metrics.rounds": "Rounds run",+ "goalDetail.metrics.taskExecutions": "Task executions",+ "goalDetail.metrics.totalCost": "Total cost",+ "goalDetail.metrics.totalDuration": "Total runtime",+ "goalDetail.moreActions": "More goal actions",+ "goalDetail.noChecks": "No acceptance checks yet",+ "goalDetail.noDefinition": "No goal definition yet.",+ "goalDetail.noRuns": "No Agent runs yet",+ "goalDetail.notFoundDescription": "This goal may have been deleted or is no longer accessible.",+ "goalDetail.notFoundTitle": "Goal not found",+ "goalDetail.openExecution": "Open execution task",+ "goalDetail.subtasks": "Subtasks",+ "goalDetail.taskStatus": "Execution status",+ "goalDetail.unnamedRun": "Untitled run",+ "goalDetail.viewPlan": "View execution plan",+ "goalList.acceptanceProgress": "{{passed}}/{{total}} passed",+ "goalList.agentRuns": "{{count}} runs",+ "goalList.empty": "No goals yet",+ "goalList.loadError": "Could not load goals.",+ "goalList.retry": "Retry",+ "goalList.roundProgress": "Round {{current}}/{{total}}",+ "goalList.status.achieved": "Achieved",+ "goalList.status.canceled": "Canceled",+ "goalList.status.error": "Needs attention",+ "goalList.status.paused": "Paused",+ "goalList.status.planning": "Planning",+ "goalList.status.review": "Pending acceptance",+ "goalList.status.running": "Pursuing",+ "goalList.status.verifying": "Verifying",+ "goalList.status.waiting": "Waiting",+ "goalList.title": "Goals",+ "goalPage.activeGoals": "Open goals",+ "goalPage.allGoals": "All goals",+ "goalPage.create": "Create goal",+ "goalPage.description": "Track what this agent is pursuing and how close each goal is to acceptance.",+ "goalPage.emptyDescription": "Goals created for this agent will appear here with their progress.",+ "goalPage.emptyTitle": "No goals yet",+ "goalPage.filter.active": "In progress",+ "goalPage.filter.all": "All",+ "goalPage.filter.open": "Open goals",+ "goalPage.filteredEmptyDescription": "Switch to All to review completed or canceled goals.",+ "goalPage.filteredEmptyTitle": "No open goals",+ "goalPage.listTitle": "Goal list",+ "goalPage.loadMore": "Load more",+ "goalPage.loadingProgress": "Loading acceptance progress…",+ "goalPage.metrics.delivered": "Delivered",+ "goalPage.metrics.pursuing": "Open",+ "goalPage.metrics.total": "Total goals",+ "goalPage.title": "Overview",+ "goalPage.view.card": "Cards",+ "goalPage.view.list": "List","group.desc": "Move a task forward with multiple Agents in one shared space.","group.memberTooltip": "There are {{count}} members in the group","group.orchestratorThinking": "Orchestrator is thinking...",diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex 7aa05426519..06dadf883a0 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -18,6 +18,7 @@"navigation.discoverProviders": "Discover Providers","navigation.document": "Document","navigation.downloads": "Downloads",+ "navigation.goals": "Goals","navigation.group": "Group","navigation.groupChat": "Group Chat","navigation.groupProfile": "Group Profile",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7e997a08584..439d7cf1732 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -308,6 +308,75 @@"globalApproval.subtitle": "等待你的审批","globalApproval.title": "需要审批","globalApproval.userRequestLabel": "用户请求",+ "goalDetail.acceptance": "验收检查",+ "goalDetail.acceptanceError": "无法加载验收检查。",+ "goalDetail.acceptanceProgress": "验收进度",+ "goalDetail.agentRun": "Agent 运行",+ "goalDetail.definition": "目标定义",+ "goalDetail.deleteConfirm.content": "该目标及其任务计划将被永久删除;对话历史会保留。",+ "goalDetail.deleteConfirm.ok": "删除目标",+ "goalDetail.deleteConfirm.title": "删除这个目标?",+ "goalDetail.executionOverview": "执行总览",+ "goalDetail.executionOverviewDescription": "这个目标的完整 Task 树和最近运行过程。",+ "goalDetail.executionPlan": "当前执行计划",+ "goalDetail.instruction": "目标说明",+ "goalDetail.latestRuns": "最近执行",+ "goalDetail.metrics.agentRuns": "Agent 运行次数",+ "goalDetail.metrics.latestAcceptance": "最后验收结果",+ "goalDetail.metrics.planItems": "计划项",+ "goalDetail.metrics.progress": "进度",+ "goalDetail.metrics.roundBudget": "轮次预算",+ "goalDetail.metrics.rounds": "已运行轮次",+ "goalDetail.metrics.taskExecutions": "Task 执行次数",+ "goalDetail.metrics.totalCost": "累计消耗成本",+ "goalDetail.metrics.totalDuration": "累计运行时间",+ "goalDetail.moreActions": "更多目标操作",+ "goalDetail.noChecks": "暂时没有验收检查",+ "goalDetail.noDefinition": "暂时没有目标定义。",+ "goalDetail.noRuns": "还没有 Agent 运行",+ "goalDetail.notFoundDescription": "该目标可能已被删除或你已无法访问。",+ "goalDetail.notFoundTitle": "找不到目标",+ "goalDetail.openExecution": "打开执行任务",+ "goalDetail.subtasks": "子任务",+ "goalDetail.taskStatus": "执行状态",+ "goalDetail.unnamedRun": "未命名运行",+ "goalDetail.viewPlan": "查看执行计划",+ "goalList.acceptanceProgress": "已通过 {{passed}}/{{total}}",+ "goalList.agentRuns": "{{count}} 次运行",+ "goalList.empty": "暂无目标",+ "goalList.loadError": "无法加载目标。",+ "goalList.retry": "重试",+ "goalList.roundProgress": "第 {{current}}/{{total}} 轮",+ "goalList.status.achieved": "已达成",+ "goalList.status.canceled": "已取消",+ "goalList.status.error": "需要处理",+ "goalList.status.paused": "已暂停",+ "goalList.status.planning": "规划中",+ "goalList.status.review": "待验收",+ "goalList.status.running": "追逐中",+ "goalList.status.verifying": "验证中",+ "goalList.status.waiting": "等待中",+ "goalList.title": "目标",+ "goalPage.activeGoals": "待处理目标",+ "goalPage.allGoals": "全部目标",+ "goalPage.create": "创建目标",+ "goalPage.description": "掌握 Agent 正在追逐什么,以及每个目标距离验收还有多远。",+ "goalPage.emptyDescription": "为这个 Agent 创建目标后,目标及其进度会显示在这里。",+ "goalPage.emptyTitle": "还没有目标",+ "goalPage.filter.active": "进行中",+ "goalPage.filter.all": "全部",+ "goalPage.filter.open": "待处理目标",+ "goalPage.filteredEmptyDescription": "切换到“全部”可查看已完成或已取消的目标。",+ "goalPage.filteredEmptyTitle": "没有待处理目标",+ "goalPage.listTitle": "目标列表",+ "goalPage.loadMore": "加载更多",+ "goalPage.loadingProgress": "正在加载验收进度…",+ "goalPage.metrics.delivered": "已交付",+ "goalPage.metrics.pursuing": "待处理",+ "goalPage.metrics.total": "目标总数",+ "goalPage.title": "概览",+ "goalPage.view.card": "卡片",+ "goalPage.view.list": "列表","group.desc": "在同一对话空间,让多个助理一起推进任务","group.memberTooltip": "群组内有 {{count}} 名成员","group.orchestratorThinking": "主持人思考中…",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex 78c44570cda..834d85a9b51 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -18,6 +18,7 @@"navigation.discoverProviders": "发现模型服务商","navigation.document": "文档","navigation.downloads": "下载",+ "navigation.goals": "目标","navigation.group": "群组","navigation.groupChat": "群组对话","navigation.groupProfile": "群组档案",diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 0225c370253..bda552673a2 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -3,7 +3,16 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, briefs, documents, tasks, topics, users, workspaces } from '../../schemas';+import {+ acceptances,+ agents,+ briefs,+ documents,+ tasks,+ topics,+ users,+ workspaces,+} from '../../schemas';import { taskTopics } from '../../schemas/task';import { works } from '../../schemas/work';import type { LobeChatDatabase } from '../../type';@@ -450,6 +459,113 @@ describe('TaskModel', () => {expect(result[0].total).toBe(1);expect(result[0].tasks).toHaveLength(1);});++ it('should filter tasks by the goal marker', async () => {+ const model = new TaskModel(serverDB, userId);++ const goal = await model.create({ instruction: 'Persistent objective' });+ await model.update(goal.id, { config: { goal: { maxIterations: 5 } } });+ await model.create({ instruction: 'Ordinary task' });++ const goals = await model.groupList({+ groups: [{ key: 'goals', statuses: ['backlog'] }],+ hasGoal: true,+ });+ const ordinary = await model.groupList({+ groups: [{ key: 'tasks', statuses: ['backlog'] }],+ hasGoal: false,+ });++ expect(goals[0].tasks.map((task) => task.id)).toEqual([goal.id]);+ expect(ordinary[0].tasks).toHaveLength(1);+ expect(ordinary[0].tasks[0].instruction).toBe('Ordinary task');+ });++ it('should aggregate run cost and duration for the returned task batch', async () => {+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({ instruction: 'Measured goal' });+ const startedAt = new Date('2026-08-06T10:00:00.000Z');++ await serverDB.insert(topics).values([+ {+ completedAt: new Date('2026-08-06T10:01:00.000Z'),+ id: 'group-list-run-1',+ totalCost: 0.015,+ userId,+ },+ {+ completedAt: new Date('2026-08-06T10:03:00.000Z'),+ id: 'group-list-run-2',+ totalCost: 0.025,+ userId,+ },+ ]);+ await serverDB.insert(taskTopics).values([+ { createdAt: startedAt, seq: 1, taskId: task.id, topicId: 'group-list-run-1', userId },+ { createdAt: startedAt, seq: 2, taskId: task.id, topicId: 'group-list-run-2', userId },+ ]);++ const [group] = await model.groupList({+ groups: [{ key: 'goals', statuses: ['backlog'] }],+ });+ const measuredTask = group.tasks.find(({ id }) => id === task.id);++ expect(measuredTask?.totalRunCost).toBeCloseTo(0.04);+ expect(measuredTask?.totalRunDuration).toBe(240_000);+ });++ it('should aggregate descendant run metrics into the root goal', async () => {+ const model = new TaskModel(serverDB, userId);+ const root = await model.create({ instruction: 'Root goal' });+ const child = await model.create({ instruction: 'Delegated work', parentTaskId: root.id });+ const startedAt = new Date('2026-08-06T10:00:00.000Z');++ await serverDB.insert(topics).values({+ completedAt: new Date('2026-08-06T10:02:00.000Z'),+ id: 'descendant-goal-run',+ totalCost: 0.05,+ userId,+ });+ await serverDB.insert(taskTopics).values({+ createdAt: startedAt,+ seq: 1,+ taskId: child.id,+ topicId: 'descendant-goal-run',+ userId,+ });++ const [group] = await model.groupList({+ groups: [{ key: 'goals', statuses: ['backlog'] }],+ parentTaskId: null,+ });+ const measuredRoot = group.tasks.find(({ id }) => id === root.id);++ expect(measuredRoot?.totalRunCost).toBeCloseTo(0.05);+ expect(measuredRoot?.totalRunDuration).toBe(120_000);+ });+ });++ describe('deleteSubtree', () => {+ it('should delete the root and all descendants without leaving orphan tasks', async () => {+ const model = new TaskModel(serverDB, userId);+ const root = await model.create({ instruction: 'Root goal' });+ const child = await model.create({ instruction: 'Child', parentTaskId: root.id });+ const grandchild = await model.create({ instruction: 'Grandchild', parentTaskId: child.id });+ await serverDB.insert(acceptances).values({+ subjectId: grandchild.id,+ subjectType: 'task',+ userId,+ });++ await expect(model.deleteSubtree(root.id)).resolves.toBe(3);+ await expect(model.findAllDescendants(root.id)).resolves.toEqual([]);+ await expect(model.findById(root.id)).resolves.toBeNull();+ const remainingAcceptances = await serverDB+ .select()+ .from(acceptances)+ .where(eq(acceptances.subjectId, grandchild.id));+ expect(remainingAcceptances).toEqual([]);+ });});describe('findSubtasks', () => {diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.tsindex a96a3b4c673..35201d73c55 100644--- a/packages/database/src/models/__tests__/taskTopic.test.ts+++ b/packages/database/src/models/__tests__/taskTopic.test.ts@@ -320,7 +320,7 @@ describe('TaskTopicModel', () => {});describe('findWithHandoff', () => {- it('should return completedAt joined from topics', async () => {+ it('should return completedAt and totalCost joined from topics', async () => {const taskModel = new TaskModel(serverDB, userId);const topicModel = new TaskTopicModel(serverDB, userId);const task = await taskModel.create({ instruction: 'Test' });@@ -330,12 +330,15 @@ describe('TaskTopicModel', () => {await topicModel.add(task.id, 'tpc_h1', { seq: 1 });await topicModel.add(task.id, 'tpc_h2', { seq: 2 });await topicModel.updateStatus(task.id, 'tpc_h1', 'completed');+ await serverDB.update(topics).set({ totalCost: 0.0123 }).where(eq(topics.id, 'tpc_h1'));const rows = await topicModel.findWithHandoff(task.id, 10);const h1 = rows.find((r) => r.topicId === 'tpc_h1');const h2 = rows.find((r) => r.topicId === 'tpc_h2');expect(h1?.completedAt).toBeInstanceOf(Date);+ expect(Number(h1?.totalCost)).toBeCloseTo(0.0123);expect(h2?.completedAt).toBeNull();+ expect(h2?.totalCost).toBeNull();});it('should return source task metadata when querying multiple task ids', async () => {diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 661e7e5582e..2c342fa506a 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -29,6 +29,8 @@ import { merge } from '@/utils/merge';import { documents } from '../schemas/file';import type { NewTaskComment, TaskCommentItem } from '../schemas/task';import { taskComments, taskDependencies, taskDocuments, tasks, taskTopics } from '../schemas/task';+import { topics } from '../schemas/topic';+import { acceptances } from '../schemas/verify';import { works } from '../schemas/work';import type { LobeChatDatabase } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';@@ -433,6 +435,33 @@ export class TaskModel {return result.length;}+ /** Delete a task and every descendant in one transaction. */+ async deleteSubtree(rootTaskId: string): Promise<number> {+ const descendants = await this.findAllDescendants(rootTaskId);+ const taskIds = [rootTaskId, ...descendants.map(({ id }) => id)];++ return this.db.transaction(async (tx) => {+ await tx+ .delete(acceptances)+ .where(+ and(+ eq(acceptances.subjectType, 'task'),+ inArray(acceptances.subjectId, taskIds),+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },+ ),+ ),+ );+ const result = await tx+ .delete(tasks)+ .where(and(inArray(tasks.id, taskIds), this.ownership()))+ .returning({ id: tasks.id });++ return result.length;+ });+ }+// ========== Query ==========async groupList(options: {@@ -444,6 +473,8 @@ export class TaskModel {statuses: string[];}>;parentTaskId?: string | null;+ /** Only return tasks carrying the goal-controller marker in `config.goal`. */+ hasGoal?: boolean;/** Same semantics as `list({ visibility })` — UI narrowing on top of the* already ownership-filtered set. */visibility?: 'private' | 'public';@@ -457,10 +488,12 @@ export class TaskModel {total: number;}>> {- const { groups, assigneeAgentId, parentTaskId, visibility } = options;+ const { groups, assigneeAgentId, hasGoal, parentTaskId, visibility } = options;const baseConditions = [this.ownership()];if (assigneeAgentId) baseConditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));+ if (hasGoal === true) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);+ if (hasGoal === false) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);if (visibility) baseConditions.push(eq(tasks.visibility, visibility));if (parentTaskId === null) {baseConditions.push(isNull(tasks.parentTaskId));@@ -508,11 +541,65 @@ export class TaskModel {}),);- return results;+ const taskIds = Array.from(+ new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))),+ );+ const runStats =+ taskIds.length === 0+ ? []+ : (+ await this.db.execute<{+ root_id: string;+ total_run_cost: number;+ total_run_duration: number;+ }>(sql`+ WITH RECURSIVE goal_tree AS (+ SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id+ FROM ${tasks}+ WHERE ${inArray(tasks.id, taskIds)} AND ${this.ownership()}+ UNION ALL+ SELECT goal_tree.root_id, child.id+ FROM ${tasks} child+ JOIN goal_tree ON child.parent_task_id = goal_tree.task_id+ WHERE ${this.ownershipSql('child')}+ )+ SELECT+ goal_tree.root_id,+ coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,+ coalesce(+ sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)+ filter (where ${topics.completedAt} is not null),+ 0+ ) AS total_run_duration+ FROM goal_tree+ LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id+ LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}+ GROUP BY goal_tree.root_id+ `)+ ).rows;+ const runStatsByTaskId = new Map(+ runStats.map((stats) => [+ stats.root_id,+ {+ totalRunCost: Number(stats.total_run_cost),+ totalRunDuration: Number(stats.total_run_duration),+ },+ ]),+ );++ return results.map((group) => ({+ ...group,+ tasks: group.tasks.map((task) => ({+ ...task,+ totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,+ totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,+ })),+ }));}async list(options?: {assigneeAgentId?: string;+ hasGoal?: boolean;limit?: number;offset?: number;parentTaskId?: string | null;@@ -530,6 +617,7 @@ export class TaskModel {priorities,parentTaskId,assigneeAgentId,+ hasGoal,visibility,limit = 50,offset = 0,@@ -540,6 +628,8 @@ export class TaskModel {if (statuses?.length) conditions.push(inArray(tasks.status, statuses));if (priorities?.length) conditions.push(inArray(tasks.priority, priorities));if (assigneeAgentId) conditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));+ if (hasGoal === true) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);+ if (hasGoal === false) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);if (visibility) conditions.push(eq(tasks.visibility, visibility));if (parentTaskId === null) {diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 3dad00b4197..c6e18dc5f4d 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -296,6 +296,7 @@ export class TaskTopicModel {// assignee (which changes when the task is reassigned).agentId: topics.agentId,completedAt: topics.completedAt,+ totalCost: topics.totalCost,createdAt: taskTopics.createdAt,handoff: taskTopics.handoff,metadata: topics.metadata,@@ -323,6 +324,7 @@ export class TaskTopicModel {// assignee (which changes when the task is reassigned).agentId: topics.agentId,completedAt: topics.completedAt,+ totalCost: topics.totalCost,createdAt: taskTopics.createdAt,handoff: taskTopics.handoff,metadata: topics.metadata,diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex bbf74257c41..5707e401c3a 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1427,6 +1427,78 @@ export default {'createTask.visibility.privateAgentLocked': 'Private agents can only run private tasks.','createTask.visibility.private': 'Private','createTask.visibility.workspace': 'Workspace',+ 'goalList.acceptanceProgress': '{{passed}}/{{total}} passed',+ 'goalList.agentRuns': '{{count}} runs',+ 'goalList.empty': 'No goals yet',+ 'goalList.loadError': 'Could not load goals.',+ 'goalList.retry': 'Retry',+ 'goalList.roundProgress': 'Round {{current}}/{{total}}',+ 'goalList.status.achieved': 'Achieved',+ 'goalList.status.canceled': 'Canceled',+ 'goalList.status.error': 'Needs attention',+ 'goalList.status.paused': 'Paused',+ 'goalList.status.planning': 'Planning',+ 'goalList.status.review': 'Pending acceptance',+ 'goalList.status.running': 'Pursuing',+ 'goalList.status.verifying': 'Verifying',+ 'goalList.status.waiting': 'Waiting',+ 'goalList.title': 'Goals',+ 'goalDetail.acceptance': 'Acceptance checks',+ 'goalDetail.acceptanceError': 'Could not load acceptance checks.',+ 'goalDetail.acceptanceProgress': 'Acceptance progress',+ 'goalDetail.agentRun': 'Agent run',+ 'goalDetail.definition': 'Goal definition',+ 'goalDetail.executionPlan': 'Current execution plan',+ 'goalDetail.executionOverview': 'Execution overview',+ 'goalDetail.executionOverviewDescription':+ 'The complete task tree and latest runs for this goal.',+ 'goalDetail.instruction': 'Goal instruction',+ 'goalDetail.latestRuns': 'Recent executions',+ 'goalDetail.deleteConfirm.content':+ 'This goal and its task plan will be permanently deleted. Conversation history is retained.',+ 'goalDetail.deleteConfirm.ok': 'Delete goal',+ 'goalDetail.deleteConfirm.title': 'Delete this goal?',+ 'goalDetail.moreActions': 'More goal actions',+ 'goalDetail.metrics.planItems': 'Plan items',+ 'goalDetail.metrics.progress': 'Progress',+ 'goalDetail.metrics.agentRuns': 'Agent runs',+ 'goalDetail.metrics.latestAcceptance': 'Latest acceptance',+ 'goalDetail.metrics.roundBudget': 'Round budget',+ 'goalDetail.metrics.rounds': 'Rounds run',+ 'goalDetail.metrics.taskExecutions': 'Task executions',+ 'goalDetail.metrics.totalCost': 'Total cost',+ 'goalDetail.metrics.totalDuration': 'Total runtime',+ 'goalDetail.noChecks': 'No acceptance checks yet',+ 'goalDetail.noDefinition': 'No goal definition yet.',+ 'goalDetail.noRuns': 'No Agent runs yet',+ 'goalDetail.notFoundDescription': 'This goal may have been deleted or is no longer accessible.',+ 'goalDetail.notFoundTitle': 'Goal not found',+ 'goalDetail.openExecution': 'Open execution task',+ 'goalDetail.subtasks': 'Subtasks',+ 'goalDetail.taskStatus': 'Execution status',+ 'goalDetail.unnamedRun': 'Untitled run',+ 'goalDetail.viewPlan': 'View execution plan',+ 'goalPage.allGoals': 'All goals',+ 'goalPage.activeGoals': 'Open goals',+ 'goalPage.description':+ 'Track what this agent is pursuing and how close each goal is to acceptance.',+ 'goalPage.create': 'Create goal',+ 'goalPage.emptyDescription': 'Goals created for this agent will appear here with their progress.',+ 'goalPage.emptyTitle': 'No goals yet',+ 'goalPage.filteredEmptyDescription': 'Switch to All to review completed or canceled goals.',+ 'goalPage.filteredEmptyTitle': 'No open goals',+ 'goalPage.filter.active': 'In progress',+ 'goalPage.filter.all': 'All',+ 'goalPage.filter.open': 'Open goals',+ 'goalPage.loadingProgress': 'Loading acceptance progress…',+ 'goalPage.listTitle': 'Goal list',+ 'goalPage.loadMore': 'Load more',+ 'goalPage.metrics.delivered': 'Delivered',+ 'goalPage.metrics.pursuing': 'Open',+ 'goalPage.metrics.total': 'Total goals',+ 'goalPage.title': 'Overview',+ 'goalPage.view.card': 'Cards',+ 'goalPage.view.list': 'List','taskList.activeTasks': 'Active Tasks','taskList.all': 'All tasks','taskList.visibility.all': 'All',diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex 60c221a5a4b..cc720200606 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -37,6 +37,7 @@ export default {'navigation.stats': 'Statistics','navigation.task': 'Task','navigation.tasks': 'Tasks',+ 'navigation.goals': 'Goals','navigation.topics': 'Topics','navigation.unpin': 'Unpin','navigation.verifyReports': 'Verification Reports',diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 7a85450c352..d824ae39ef2 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -271,6 +271,8 @@ export interface TaskItem {sortOrder: number | null;startedAt: Date | null;status: string;+ totalRunCost?: number | null;+ totalRunDuration?: number | null;totalTopics: number | null;updatedAt: Date;// 'private' tasks are only visible to their creator in workspace mode.@@ -348,6 +350,7 @@ export interface TaskDetailSubtask {runningTopic?: TaskDetailSubtaskRunningTopic | null;schedule?: { pattern?: string | null; timezone?: string | null };status: string;+ updatedAt?: string;}export interface TaskDetailWorkspaceNode {@@ -397,6 +400,8 @@ export interface TaskDetailActivity {*/completedAt?: string;content?: string;+ /** Topic-only: denormalized total run cost in USD. */+ cost?: number | null;createdAt?: string;cronJobId?: string | null;/** Comment-only: rich Lexical JSON state. When present, supersedes `content` for rendering. */@@ -504,6 +509,7 @@ export interface TaskDetailData {status: string;subtasks?: TaskDetailSubtask[];topicCount?: number;+ updatedAt?: string;userId?: string | null;/** Task-level verify (delivery-acceptance) gate config; `tasks.config.verify`. */verify?: TaskVerifyConfig | null;diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxnew file mode 100644index 00000000000..6c69eaa3ba4--- /dev/null+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -0,0 +1,269 @@+'use client';++import { ActionIcon, Block, Empty, Flexbox, Text } from '@lobehub/ui';+import { Button, Segmented } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { LayoutGridIcon, ListIcon, PlusIcon, RefreshCwIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import AgentBreadcrumb from '@/features/AgentBreadcrumb';+import { createTaskModal } from '@/features/AgentTasks/CreateTaskModal';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { goalSelectors, useGoalStore } from '@/store/goal';+import { useVerifyStore } from '@/store/verify';++import { GoalCardItem } from './GoalCardItem';+import { GoalListItem } from './GoalListItem';+import { getGoalPresentation } from './goalPresentation';+import { shouldShowGoal } from './goalViewModel';++const styles = createStaticStyles(({ css }) => ({+ countBadge: css`+ padding-block: 1px;+ padding-inline: 7px;+ border-radius: 99px;++ font-size: 12px;+ font-variant-numeric: tabular-nums;+ line-height: 18px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ overview: css`+ padding-block: 6px 18px;+ `,+ list: css`+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px;++ @media (width <= 900px) {+ grid-template-columns: minmax(0, 1fr);+ }+ `,+ listRows: css`+ display: flex;+ flex-direction: column;+ border-block: 1px solid ${cssVar.colorBorderSecondary};+ `,+ metric: css`+ min-width: 88px;+ padding-inline-start: 16px;+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};++ &:first-child {+ padding-inline-start: 0;+ border-inline-start: 0;+ }+ `,+}));++interface AgentGoalsPageProps {+ agentId: string;+}++const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId }) => {+ const { t } = useTranslation('chat');+ const useFetchGoals = useGoalStore((s) => s.useFetchGoals);+ const refreshGoals = useGoalStore((s) => s.refreshGoals);+ const goals = useGoalStore(goalSelectors.goalList(agentId));+ const isInitialized = useGoalStore(goalSelectors.isGoalListInitialized(agentId));+ const filter = useGoalStore((s) => s.goalListFilter);+ const viewMode = useGoalStore((s) => s.goalViewMode);+ const visibleLimit = useGoalStore((s) => s.goalListVisibleLimit);+ const setFilter = useGoalStore((s) => s.setGoalListFilter);+ const setViewMode = useGoalStore((s) => s.setGoalViewMode);+ const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);+ const acceptanceBySubjectMap = useVerifyStore((s) => s.acceptanceBySubjectMap);+ const acceptanceBundleMap = useVerifyStore((s) => s.acceptanceBundleMap);+ const { error, isLoading } = useFetchGoals(agentId);+ const summary = useMemo(() => {+ const delivered = goals.filter((goal) => goal.status === 'completed').length;++ return { delivered, pursuing: goals.length - delivered, total: goals.length };+ }, [goals]);+ const filteredGoals = useMemo(() => {+ if (filter === 'all') return goals;++ return goals.filter((goal) => {+ const acceptance = acceptanceBySubjectMap[`task:${goal.id}`];+ const bundle = acceptance ? acceptanceBundleMap[acceptance.id] : undefined;+ const config = goal.config as { goal?: { maxIterations?: number | null } } | null;+ const presentation = getGoalPresentation({+ acceptanceStatus: bundle?.acceptance.status,+ checks: bundle?.checks,+ maxRounds: config?.goal?.maxIterations,+ rounds: goal.totalTopics ?? 0,+ taskStatus: goal.status,+ });++ return shouldShowGoal(presentation.statusKey, 'active');+ });+ }, [acceptanceBundleMap, acceptanceBySubjectMap, filter, goals]);+ const visibleGoalCount = filteredGoals.length;+ const GoalItem = viewMode === 'list' ? GoalListItem : GoalCardItem;+ const openCreateGoal = () => {+ createTaskModal({+ agentId,+ goal: true,+ lockAssignee: true,+ showInlineToggle: false,+ onCreated: () => void refreshGoals(agentId),+ });+ };++ return (+ <Flexbox flex={1} height={'100%'}>+ <NavHeader+ left={<AgentBreadcrumb agentId={agentId} title={t('goalList.title')} />}+ right={+ <Button icon={PlusIcon} size={'small'} onClick={openCreateGoal}>+ {t('goalPage.create')}+ </Button>+ }+ />+ <WideScreenContainer+ flex={1}+ gap={16}+ paddingBlock={16}+ wrapperStyle={{ flex: 1, overflowY: 'auto' }}+ >+ {isLoading && !isInitialized ? (+ <Flexbox align={'center'} flex={1} justify={'center'}>+ <NeuralNetworkLoading />+ </Flexbox>+ ) : error ? (+ <Flexbox align={'center'} flex={1} gap={12} justify={'center'}>+ <Text type={'secondary'}>{t('goalList.loadError')}</Text>+ <ActionIcon+ icon={RefreshCwIcon}+ title={t('goalList.retry')}+ onClick={() => void refreshGoals(agentId)}+ />+ </Flexbox>+ ) : goals.length === 0 ? (+ <Block padding={32} variant={'outlined'}>+ <Empty description={t('goalPage.emptyDescription')} title={t('goalPage.emptyTitle')}>+ <Button icon={PlusIcon} onClick={openCreateGoal}>+ {t('goalPage.create')}+ </Button>+ </Empty>+ </Block>+ ) : (+ <>+ <Flexbox className={styles.overview}>+ <Flexbox horizontal align={'center'} gap={20} justify={'space-between'} wrap={'wrap'}>+ <Flexbox gap={3}>+ <Text fontSize={20} weight={600}>+ {t('goalPage.title')}+ </Text>+ <Text type={'secondary'}>{t('goalPage.description')}</Text>+ </Flexbox>+ <Flexbox horizontal gap={20}>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={20} weight={600}>+ {summary.total}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalPage.metrics.total')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={20} weight={600}>+ {summary.pursuing}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalPage.metrics.pursuing')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={20} weight={600}>+ {summary.delivered}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalPage.metrics.delivered')}+ </Text>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ <Flexbox gap={10}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={16} weight={600}>+ {t('goalPage.listTitle')}+ </Text>+ <span className={styles.countBadge}>{visibleGoalCount}</span>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8}>+ <Segmented+ size={'small'}+ value={filter}+ options={[+ {+ label: t('goalPage.filter.open'),+ value: 'active',+ },+ {+ label: t('goalPage.filter.all'),+ value: 'all',+ },+ ]}+ onChange={(value) => setFilter(value as 'active' | 'all')}+ />+ <ActionIcon+ icon={ListIcon}+ size={'small'}+ style={{ alignSelf: 'center' }}+ title={t('goalPage.view.list')}+ variant={viewMode === 'list' ? 'filled' : 'borderless'}+ onClick={() => setViewMode('list')}+ />+ <ActionIcon+ icon={LayoutGridIcon}+ size={'small'}+ style={{ alignSelf: 'center' }}+ title={t('goalPage.view.card')}+ variant={viewMode === 'card' ? 'filled' : 'borderless'}+ onClick={() => setViewMode('card')}+ />+ </Flexbox>+ </Flexbox>+ <div className={viewMode === 'card' ? styles.list : styles.listRows}>+ {filteredGoals.length === 0 ? (+ <Block padding={32} variant={'outlined'}>+ <Empty+ description={t('goalPage.filteredEmptyDescription')}+ title={t('goalPage.filteredEmptyTitle')}+ />+ </Block>+ ) : (+ filteredGoals+ .slice(0, visibleLimit)+ .map((goal) => (+ <GoalItem hideAchieved={filter === 'active'} key={goal.id} task={goal} />+ ))+ )}+ </div>+ {visibleLimit < filteredGoals.length && (+ <Flexbox align={'center'} paddingBlock={8}>+ <Button size={'small'} onClick={loadMoreGoals}>+ {t('goalPage.loadMore')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ </>+ )}+ </WideScreenContainer>+ </Flexbox>+ );+});++AgentGoalsPage.displayName = 'AgentGoalsPage';++export default AgentGoalsPage;diff --git a/src/features/AgentGoals/GoalAcceptance.tsx b/src/features/AgentGoals/GoalAcceptance.tsxnew file mode 100644index 00000000000..819a16c7259--- /dev/null+++ b/src/features/AgentGoals/GoalAcceptance.tsx@@ -0,0 +1,40 @@+'use client';++import type { ReactNode } from 'react';+import { memo } from 'react';++import type { AcceptanceBundle } from '@/services/verify';+import { useVerifyStore, verifySelectors } from '@/store/verify';++interface GoalAcceptanceRenderState {+ bundle?: AcceptanceBundle;+ error?: unknown;+ isLoading: boolean;+ retry: () => void;+}++interface GoalAcceptanceProps {+ children: (state: GoalAcceptanceRenderState) => ReactNode;+ taskId: string;+}++export const GoalAcceptance = memo<GoalAcceptanceProps>(({ children, taskId }) => {+ const useFetchAcceptanceBySubject = useVerifyStore((s) => s.useFetchAcceptanceBySubject);+ const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);+ const acceptance = useVerifyStore(verifySelectors.acceptanceBySubject('task', taskId));+ const bundle = useVerifyStore(verifySelectors.acceptanceBundle(acceptance?.id));+ const acceptanceQuery = useFetchAcceptanceBySubject('task', taskId);+ const bundleQuery = useFetchAcceptanceBundle(acceptance?.id);++ return children({+ bundle,+ error: acceptanceQuery.error || bundleQuery.error,+ isLoading: acceptanceQuery.isLoading || (!!acceptance?.id && bundleQuery.isLoading),+ retry: () => {+ void acceptanceQuery.mutate();+ if (acceptance?.id) void bundleQuery.mutate();+ },+ });+});++GoalAcceptance.displayName = 'GoalAcceptance';diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsxnew file mode 100644index 00000000000..735a3506cdb--- /dev/null+++ b/src/features/AgentGoals/GoalCardItem.tsx@@ -0,0 +1,135 @@+'use client';++import type { TaskStatus } from '@lobechat/types';+import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';+import type { KeyboardEvent } from 'react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';++import { GoalAcceptance } from './GoalAcceptance';+import { getGoalPresentation } from './goalPresentation';+import { GoalProgress } from './GoalProgress';+import { getGoalDescription, goalStatusToTaskStatus, shouldShowGoal } from './goalViewModel';+import type { GoalItemProps } from './types';++const styles = createStaticStyles(({ css }) => ({+ card: css`+ min-width: 0;+ transition:+ border-color 0.2s ${cssVar.motionEaseOut},+ background 0.2s ${cssVar.motionEaseOut},+ transform 0.2s ${cssVar.motionEaseOut};++ &:hover {+ transform: translateY(-1px);+ border-color: ${cssVar.colorPrimaryBorder};+ background: ${cssVar.colorFillQuaternary};+ }+ `,+}));++export const GoalCardItem = memo<GoalItemProps>((props) => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ const { aid } = useActiveRouteParams<{ aid?: string }>();+ const { hideAchieved = false, task } = props;+ const config = task.config as { goal?: { maxIterations?: number | null } } | null;+ const title = task.name?.trim() || task.instruction.trim() || task.identifier;+ const description = getGoalDescription(task);+ const handleClick = () => {+ if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);+ };+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ handleClick();+ };++ return (+ <GoalAcceptance taskId={task.id}>+ {({ bundle, error, isLoading, retry }) => {+ const presentation = getGoalPresentation({+ acceptanceStatus: bundle?.acceptance.status,+ checks: bundle?.checks,+ maxRounds: config?.goal?.maxIterations,+ rounds: task.totalTopics ?? 0,+ taskStatus: task.status,+ });+ if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))+ return null;+ const visual =+ TASK_STATUS_VISUALS[goalStatusToTaskStatus(presentation.statusKey) as TaskStatus] ??+ TASK_STATUS_VISUALS.backlog;++ return (+ <Block+ clickable+ className={styles.card}+ gap={14}+ padding={16}+ role={'link'}+ tabIndex={0}+ variant={'outlined'}+ onClick={handleClick}+ onKeyDown={handleKeyDown}+ >+ <Flexbox+ horizontal+ align={'flex-start'}+ gap={12}+ justify={'space-between'}+ style={{ minWidth: 0 }}+ >+ <Flexbox gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={7}>+ <Icon+ color={visual.color}+ icon={visual.icon}+ size={13}+ style={{ flexShrink: 0 }}+ />+ <Text ellipsis fontSize={15} weight={600}>+ {title}+ </Text>+ </Flexbox>+ {description && description !== title && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {description}+ </Text>+ )}+ </Flexbox>+ {error ? (+ <ActionIcon+ icon={RefreshCwIcon}+ size={'small'}+ title={t('goalList.retry')}+ onClick={(event) => {+ event.stopPropagation();+ retry();+ }}+ />+ ) : (+ <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />+ )}+ </Flexbox>+ <GoalProgress+ isLoading={isLoading}+ presentation={presentation}+ totalRunCost={props.task.totalRunCost}+ totalRunDuration={props.task.totalRunDuration}+ totalRuns={props.task.totalTopics}+ />+ </Block>+ );+ }}+ </GoalAcceptance>+ );+});++GoalCardItem.displayName = 'GoalCardItem';diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsxnew file mode 100644index 00000000000..d6b07796378--- /dev/null+++ b/src/features/AgentGoals/GoalDetailActions.tsx@@ -0,0 +1,75 @@+import { ActionIcon, copyToClipboard, Icon } from '@lobehub/ui';+import { confirmModal, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';+import { CopyIcon, LinkIcon, MoreHorizontalIcon, TrashIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { useGoalStore } from '@/store/goal';++interface GoalDetailActionsProps {+ agentId: string;+ goalId: string;+}++const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId }) => {+ const { t } = useTranslation(['chat', 'common']);+ const navigate = useWorkspaceAwareNavigate();+ const { allowed: canEditTask } = usePermission('create_content');+ const deleteGoal = useGoalStore((s) => s.deleteGoal);++ const items = useMemo<DropdownItem[]>(+ () => [+ {+ icon: <Icon icon={CopyIcon} />,+ key: 'copyId',+ label: t('taskList.contextMenu.copyId'),+ onClick: async () => {+ await copyToClipboard(goalId);+ toast.success(t('taskList.contextMenu.copyIdSuccess'));+ },+ },+ {+ icon: <Icon icon={LinkIcon} />,+ key: 'copyLink',+ label: t('taskList.contextMenu.copyLink'),+ onClick: async () => {+ await copyToClipboard(window.location.href);+ toast.success(t('taskList.contextMenu.copyLinkSuccess'));+ },+ },+ { type: 'divider' },+ {+ danger: true,+ disabled: !canEditTask,+ icon: <Icon icon={TrashIcon} />,+ key: 'delete',+ label: t('delete', { ns: 'common' }),+ onClick: () => {+ confirmModal({+ content: t('goalDetail.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('goalDetail.deleteConfirm.ok'),+ onOk: async () => {+ await deleteGoal(agentId, goalId);+ navigate(`/agent/${agentId}/goals`);+ },+ title: t('goalDetail.deleteConfirm.title'),+ });+ },+ },+ ],+ [agentId, canEditTask, deleteGoal, goalId, navigate, t],+ );++ return (+ <DropdownMenu items={items} placement={'bottomRight'}>+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('goalDetail.moreActions')} />+ </DropdownMenu>+ );+});++GoalDetailActions.displayName = 'GoalDetailActions';++export default GoalDetailActions;diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxnew file mode 100644index 00000000000..1aaf70dfa93--- /dev/null+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -0,0 +1,414 @@+'use client';++import type { TaskDetailSubtask, TaskStatus } from '@lobechat/types';+import { Accordion, AccordionItem, Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { Progress } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { BadgeCheckIcon, BotIcon, CircleDashedIcon, RotateCcwIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import NotFound from '@/components/404';+import AsyncError from '@/components/AsyncError';+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';+import Loading from '@/components/Loading/BrandTextLoading';+import AgentBreadcrumb from '@/features/AgentBreadcrumb';+import { useActiveTaskDetail } from '@/features/AgentTasks/AgentTaskDetail';+import TaskDetailTitleInput from '@/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput';+import TaskInstruction from '@/features/AgentTasks/AgentTaskDetail/TaskInstruction';+import TopicCard from '@/features/AgentTasks/AgentTaskDetail/TopicCard';+import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';+import { useNavigateToTaskDetail } from '@/features/AgentTasks/shared/taskDetailPath';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { useActivityTime } from '@/hooks/useActivityTime';+import { useTaskStore } from '@/store/task';+import { taskDetailSelectors } from '@/store/task/selectors';+import { useVerifyStore, verifySelectors } from '@/store/verify';++import GoalDetailActions from './GoalDetailActions';+import { getGoalPresentation } from './goalPresentation';+import {+ formatGoalCost,+ formatGoalDuration,+ getGoalRunMetrics,+ getGoalRuns,+ getRecentGoalRuns,+ goalStatusToTaskStatus,+} from './goalViewModel';++const styles = createStaticStyles(({ css }) => ({+ acceptanceList: css`+ overflow: hidden;+ padding: 0;+ `,+ acceptanceRow: css`+ padding-block: 11px;+ padding-inline: 12px;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ executionSection: css`+ padding-block: 18px;+ `,+ header: css`+ padding-block: 8px 4px;+ `,+ metric: css`+ min-width: 112px;++ & + & {+ padding-inline-start: 18px;+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ title: css`+ .ant-input {+ flex: none;+ }+ `,+ treeChildren: css`+ margin-inline-start: 13px;+ padding-inline-start: 20px;+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ treeRow: css`+ position: relative;+ min-height: 40px;+ padding-block: 8px;++ &::before {+ content: '';++ position: absolute;+ inset-block-start: 20px;+ inset-inline-start: -20px;++ width: 12px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+}));++interface GoalDetailPageProps {+ agentId: string;+ goalId: string;+}++const statusVisual = (status: string) =>+ TASK_STATUS_VISUALS[status as TaskStatus] ?? TASK_STATUS_VISUALS.backlog;++const TaskTreeItem = memo<{ task: TaskDetailSubtask }>(({ task }) => {+ const navigateToTaskDetail = useNavigateToTaskDetail();+ const visual = statusVisual(task.status);+ const { text: updatedAt, title: updatedAtTitle } = useActivityTime(task.updatedAt);++ return (+ <Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.treeRow}+ gap={8}+ style={{ cursor: 'pointer' }}+ onClick={() => navigateToTaskDetail(task.identifier)}+ >+ <Icon color={visual.color} icon={visual.icon} size={14} />+ <Text fontSize={12} type={'secondary'}>+ {task.identifier}+ </Text>+ <Text ellipsis style={{ flex: 1, minWidth: 0 }}>+ {task.name || task.identifier}+ </Text>+ <AssigneeAvatar agentId={task.assignee?.id} size={18} />+ <Text fontSize={12} title={updatedAtTitle} type={'secondary'}>+ {updatedAt || '—'}+ </Text>+ </Flexbox>+ {task.children && task.children.length > 0 && (+ <Flexbox className={styles.treeChildren}>+ <TaskTreeRows tasks={task.children} />+ </Flexbox>+ )}+ </Flexbox>+ );+});++TaskTreeItem.displayName = 'GoalTaskTreeItem';++const TaskTreeRows = memo<{ depth?: number; tasks: TaskDetailSubtask[] }>(({ tasks }) => {+ return tasks.map((item) => <TaskTreeItem key={item.identifier} task={item} />);+});++TaskTreeRows.displayName = 'GoalTaskTreeRows';++const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {+ const { t } = useTranslation('chat');+ const navigateToTaskDetail = useNavigateToTaskDetail();+ const { error, isInitialLoading, isNotFound, onRetry } = useActiveTaskDetail(goalId);+ const task = useTaskStore(taskDetailSelectors.taskDetailById(goalId));+ const useFetchAcceptanceBySubject = useVerifyStore((s) => s.useFetchAcceptanceBySubject);+ const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);+ const acceptance = useVerifyStore(verifySelectors.acceptanceBySubject('task', task?.id));+ const bundle = useVerifyStore(verifySelectors.acceptanceBundle(acceptance?.id));+ const acceptanceQuery = useFetchAcceptanceBySubject('task', task?.id);+ const bundleQuery = useFetchAcceptanceBundle(acceptance?.id);+ const config = task?.config as { goal?: { maxIterations?: number | null } } | undefined;+ const runs = useMemo(() => getGoalRuns(task?.activities), [task?.activities]);+ const recentRuns = useMemo(() => getRecentGoalRuns(task?.activities), [task?.activities]);+ const runMetrics = useMemo(() => getGoalRunMetrics(task?.activities), [task?.activities]);+ const { text: rootUpdatedAt, title: rootUpdatedAtTitle } = useActivityTime(task?.updatedAt);+ const presentation = getGoalPresentation({+ acceptanceStatus: bundle?.acceptance.status,+ checks: bundle?.checks,+ maxRounds: config?.goal?.maxIterations,+ rounds: task?.topicCount ?? 0,+ taskStatus: task?.status ?? 'backlog',+ });+ const visual = statusVisual(goalStatusToTaskStatus(presentation.statusKey));+ const title = task?.name?.trim() || task?.instruction.trim() || goalId;++ if (error) return <AsyncError error={error} variant={'page'} onRetry={onRetry} />;+ if (isNotFound)+ return (+ <NotFound desc={t('goalDetail.notFoundDescription')} title={t('goalDetail.notFoundTitle')} />+ );++ return (+ <Flexbox flex={1} height={'100%'}>+ <NavHeader+ left={+ <Flexbox horizontal align={'center'} gap={4}>+ <AgentBreadcrumb agentId={agentId} extraItems={[title]} title={t('goalList.title')} />+ <GoalDetailActions agentId={agentId} goalId={goalId} />+ </Flexbox>+ }+ />+ <Flexbox flex={1} style={{ overflowY: 'auto' }}>+ <WideScreenContainer gap={20} paddingBlock={16}>+ {isInitialLoading || !task ? (+ <Loading debugId={'GoalDetail'} />+ ) : (+ <>+ <Flexbox className={styles.header} gap={8}>+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Flexbox className={styles.title} gap={5} style={{ flex: 1, minWidth: 0 }}>+ <TaskDetailTitleInput />+ {task.description && (+ <Text fontSize={15} style={{ lineHeight: 1.65, whiteSpace: 'pre-wrap' }}>+ {task.description}+ </Text>+ )}+ </Flexbox>+ </Flexbox>++ <Flexbox horizontal gap={18} wrap={'wrap'}>+ <Flexbox className={styles.metric} gap={2}>+ <Flexbox horizontal align={'center'} gap={7}>+ <Progress+ percent={presentation.progress}+ showInfo={false}+ size={24}+ strokeColor={cssVar.colorSuccess}+ type={'circle'}+ />+ <Text fontSize={18} weight={600}>+ {presentation.total > 0+ ? `${presentation.passed}/${presentation.total}`+ : '—'}+ </Text>+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {t('goalDetail.metrics.progress')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={18} weight={600}>+ {task.topicCount ?? 0}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalDetail.metrics.taskExecutions')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={18} weight={600}>+ {runs.length}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalDetail.metrics.agentRuns')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={18} weight={600}>+ {formatGoalDuration(runMetrics.duration)}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalDetail.metrics.totalDuration')}+ </Text>+ </Flexbox>+ <Flexbox className={styles.metric} gap={2}>+ <Text fontSize={18} weight={600}>+ {formatGoalCost(runMetrics.cost)}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalDetail.metrics.totalCost')}+ </Text>+ </Flexbox>+ </Flexbox>+ <Flexbox gap={4} paddingBlock={'8px 0'}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('goalDetail.instruction')}+ </Text>+ <TaskInstruction />+ </Flexbox>+ </Flexbox>++ <Flexbox gap={4}>+ <Accordion defaultExpandedKeys={['acceptance']} gap={0}>+ <AccordionItem+ itemKey={'acceptance'}+ paddingBlock={6}+ paddingInline={0}+ title={+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalDetail.acceptance')}+ </Text>+ {presentation.total > 0 && <Tag size={'small'}>{presentation.total}</Tag>}+ </Flexbox>+ }+ >+ <Flexbox paddingBlock={8}>+ {acceptanceQuery.error || bundleQuery.error ? (+ <AsyncError+ error={acceptanceQuery.error || bundleQuery.error}+ variant={'inline'}+ onRetry={() => {+ void acceptanceQuery.mutate();+ if (acceptance?.id) void bundleQuery.mutate();+ }}+ />+ ) : acceptanceQuery.isLoading || bundleQuery.isLoading ? (+ <Text type={'secondary'}>{t('goalPage.loadingProgress')}</Text>+ ) : presentation.total === 0 ? (+ <Text type={'secondary'}>{t('goalDetail.noChecks')}</Text>+ ) : (+ <Block className={styles.acceptanceList} variant={'outlined'}>+ {bundle?.checks.map((check, index) => {+ const passed = check.state === 'passed';+ const failed = check.state === 'failed';+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.acceptanceRow}+ gap={10}+ key={check.id}+ >+ <Icon+ size={16}+ color={+ passed+ ? cssVar.colorSuccess+ : failed+ ? cssVar.colorError+ : cssVar.colorTextQuaternary+ }+ icon={+ passed+ ? BadgeCheckIcon+ : failed+ ? RotateCcwIcon+ : CircleDashedIcon+ }+ />+ <Text fontSize={12} type={'secondary'}>+ C{index + 1}+ </Text>+ <Text style={{ flex: 1 }}>{check.title}</Text>+ </Flexbox>+ );+ })}+ </Block>+ )}+ </Flexbox>+ </AccordionItem>+ </Accordion>++ <Flexbox className={styles.executionSection} gap={12}>+ <Flexbox gap={5}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalDetail.executionOverview')}+ </Text>+ <Button+ size={'small'}+ type={'text'}+ onClick={() => navigateToTaskDetail(task.identifier, agentId)}+ >+ {t('goalDetail.viewPlan')}+ </Button>+ </Flexbox>+ </Flexbox>+ <Flexbox gap={4}>+ <Flexbox horizontal align={'center'} className={styles.treeRow} gap={8}>+ <Icon color={visual.color} icon={visual.icon} size={14} />+ <Text fontSize={12} type={'secondary'}>+ {task.identifier}+ </Text>+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={600}>+ {task.name || task.identifier}+ </Text>+ <AssigneeAvatar agentId={task.agentId} size={18} />+ <Text fontSize={12} title={rootUpdatedAtTitle} type={'secondary'}>+ {rootUpdatedAt || '—'}+ </Text>+ </Flexbox>+ {task.subtasks && task.subtasks.length > 0 && (+ <Flexbox className={styles.treeChildren}>+ <TaskTreeRows tasks={task.subtasks} />+ </Flexbox>+ )}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8} paddingBlock={'12px 0'}>+ <Text fontSize={13} weight={600}>+ {t('goalDetail.latestRuns')}+ </Text>+ </Flexbox>+ {runs.length > 0 ? (+ <Flexbox gap={12} paddingBlock={8}>+ {recentRuns.map((activity, index) => (+ <TopicCard+ activity={activity}+ key={activity.id || activity.topicId || index}+ />+ ))}+ </Flexbox>+ ) : (+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ paddingBlock={10}+ paddingInline={12}+ >+ <Icon color={cssVar.colorTextQuaternary} icon={BotIcon} size={15} />+ <Text type={'secondary'}>{t('goalDetail.noRuns')}</Text>+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>+ </>+ )}+ </WideScreenContainer>+ </Flexbox>+ </Flexbox>+ );+});++GoalDetailPage.displayName = 'GoalDetailPage';++export default GoalDetailPage;diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsxnew file mode 100644index 00000000000..11086b6d4ff--- /dev/null+++ b/src/features/AgentGoals/GoalListItem.tsx@@ -0,0 +1,139 @@+'use client';++import type { TaskStatus } from '@lobechat/types';+import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';+import type { KeyboardEvent } from 'react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';++import { GoalAcceptance } from './GoalAcceptance';+import { getGoalPresentation } from './goalPresentation';+import { GoalProgress } from './GoalProgress';+import { getGoalDescription, goalStatusToTaskStatus, shouldShowGoal } from './goalViewModel';+import type { GoalItemProps } from './types';++const styles = createStaticStyles(({ css }) => ({+ row: css`+ min-width: 0;+ border-radius: 0;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+}));++export const GoalListItem = memo<GoalItemProps>((props) => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ const { aid } = useActiveRouteParams<{ aid?: string }>();+ const { hideAchieved = false, task } = props;+ const config = task.config as { goal?: { maxIterations?: number | null } } | null;+ const title = task.name?.trim() || task.instruction.trim() || task.identifier;+ const description = getGoalDescription(task);+ const handleClick = () => {+ if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);+ };+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ handleClick();+ };++ return (+ <GoalAcceptance taskId={task.id}>+ {({ bundle, error, isLoading, retry }) => {+ const presentation = getGoalPresentation({+ acceptanceStatus: bundle?.acceptance.status,+ checks: bundle?.checks,+ maxRounds: config?.goal?.maxIterations,+ rounds: task.totalTopics ?? 0,+ taskStatus: task.status,+ });+ if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))+ return null;+ const visual =+ TASK_STATUS_VISUALS[goalStatusToTaskStatus(presentation.statusKey) as TaskStatus] ??+ TASK_STATUS_VISUALS.backlog;++ return (+ <Block+ clickable+ horizontal+ align={'center'}+ className={styles.row}+ gap={12}+ justify={'space-between'}+ paddingBlock={10}+ paddingInline={0}+ role={'link'}+ tabIndex={0}+ variant={'borderless'}+ onClick={handleClick}+ onKeyDown={handleKeyDown}+ >+ <Flexbox+ horizontal+ align={'center'}+ flex={1}+ gap={12}+ justify={'space-between'}+ style={{ minWidth: 0 }}+ >+ <Flexbox gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={7}>+ <Icon+ color={visual.color}+ icon={visual.icon}+ size={13}+ style={{ flexShrink: 0 }}+ />+ <Text ellipsis fontSize={15} weight={600}>+ {title}+ </Text>+ </Flexbox>+ {description && description !== title && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {description}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ <GoalProgress+ isLoading={isLoading}+ presentation={presentation}+ totalRunCost={props.task.totalRunCost}+ totalRunDuration={props.task.totalRunDuration}+ totalRuns={props.task.totalTopics}+ />+ {error ? (+ <ActionIcon+ icon={RefreshCwIcon}+ size={'small'}+ title={t('goalList.retry')}+ onClick={(event) => {+ event.stopPropagation();+ retry();+ }}+ />+ ) : (+ <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />+ )}+ </Block>+ );+ }}+ </GoalAcceptance>+ );+});++GoalListItem.displayName = 'GoalListItem';diff --git a/src/features/AgentGoals/GoalProgress.tsx b/src/features/AgentGoals/GoalProgress.tsxnew file mode 100644index 00000000000..3d2bcc27113--- /dev/null+++ b/src/features/AgentGoals/GoalProgress.tsx@@ -0,0 +1,103 @@+import { Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { getGoalPresentation } from './goalPresentation';+import { formatGoalCost, formatGoalDuration } from './goalViewModel';++const styles = createStaticStyles(({ css }) => ({+ acceptance: css`+ min-width: 0;+ `,+ loading: css`+ grid-column: 1 / -1;+ `,+ metric: css`+ justify-self: end;+ white-space: nowrap;+ `,+ metrics: css`+ display: grid;+ grid-template-columns: minmax(178px, 1fr) 64px 48px 64px;+ column-gap: 12px;+ align-items: center;++ width: min(100%, 390px);+ min-width: 390px;+ `,+ progress: css`+ overflow: hidden;++ width: 64px;+ height: 4px;+ border-radius: ${cssVar.borderRadiusXS};++ background: ${cssVar.colorFillSecondary};+ `,+ progressValue: css`+ height: 100%;+ border-radius: inherit;+ background: ${cssVar.colorSuccess};+ transition: width 0.2s ${cssVar.motionEaseOut};+ `,+}));++interface GoalProgressProps {+ isLoading: boolean;+ presentation: ReturnType<typeof getGoalPresentation>;+ totalRunCost?: number | null;+ totalRunDuration?: number | null;+ totalRuns?: number | null;+}++export const GoalProgress = memo<GoalProgressProps>(+ ({ isLoading, presentation, totalRunCost = 0, totalRunDuration = 0, totalRuns = 0 }) => {+ const { t } = useTranslation('chat');++ if (isLoading)+ return (+ <div className={styles.metrics}>+ <Text className={styles.loading} fontSize={12} type={'secondary'}>+ {t('goalPage.loadingProgress')}+ </Text>+ </div>+ );++ return (+ <div className={styles.metrics}>+ {presentation.total > 0 ? (+ <Flexbox horizontal align={'center'} className={styles.acceptance} gap={6}>+ <div aria-hidden className={styles.progress}>+ <div+ className={styles.progressValue}+ style={{ width: `${presentation.progress}%` }}+ />+ </div>+ <Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>+ {t('goalList.acceptanceProgress', presentation)}+ </Text>+ </Flexbox>+ ) : (+ <Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>+ {t('goalList.roundProgress', {+ current: presentation.rounds,+ total: typeof presentation.maxRounds === 'number' ? presentation.maxRounds : '∞',+ })}+ </Text>+ )}+ <Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>+ {t('goalList.agentRuns', { count: totalRuns })}+ </Text>+ <Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>+ {formatGoalDuration(totalRunDuration ?? 0)}+ </Text>+ <Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>+ {formatGoalCost(totalRunCost ?? 0)}+ </Text>+ </div>+ );+ },+);++GoalProgress.displayName = 'GoalProgress';diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.tsnew file mode 100644index 00000000000..07194cf92a1--- /dev/null+++ b/src/features/AgentGoals/goalPresentation.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { getGoalPresentation } from './goalPresentation';++describe('getGoalPresentation', () => {+ it('uses Acceptance as the authoritative lifecycle and progress source', () => {+ expect(+ getGoalPresentation({+ acceptanceStatus: 'verifying',+ checks: [{ state: 'passed' }, { state: 'failed' }, { state: 'passed' }],+ rounds: 2,+ taskStatus: 'running',+ }),+ ).toMatchObject({+ passed: 2,+ progress: 67,+ statusKey: 'goalList.status.verifying',+ total: 3,+ });+ });++ it('shows achieved only after Acceptance is accepted', () => {+ expect(+ getGoalPresentation({+ acceptanceStatus: 'accepted',+ checks: [{ state: 'passed' }],+ rounds: 3,+ taskStatus: 'completed',+ }).statusKey,+ ).toBe('goalList.status.achieved');+ });++ it('falls back to task execution and round state before Acceptance exists', () => {+ expect(getGoalPresentation({ maxRounds: 5, rounds: 2, taskStatus: 'scheduled' })).toMatchObject(+ {+ maxRounds: 5,+ passed: 0,+ progress: 0,+ rounds: 2,+ statusKey: 'goalList.status.waiting',+ total: 0,+ },+ );+ });+});diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.tsnew file mode 100644index 00000000000..947a455207c--- /dev/null+++ b/src/features/AgentGoals/goalPresentation.ts@@ -0,0 +1,74 @@+export interface GoalPresentationInput {+ acceptanceStatus?: string;+ checks?: Array<{ state: string }>;+ maxRounds?: number | null;+ rounds: number;+ taskStatus: string;+}++const acceptanceStatusKey = (status?: string) => {+ switch (status) {+ case 'accepted': {+ return 'goalList.status.achieved';+ }+ case 'closed':+ case 'rejected': {+ return 'goalList.status.paused';+ }+ case 'delivered': {+ return 'goalList.status.review';+ }+ case 'errored': {+ return 'goalList.status.error';+ }+ case 'planned':+ case 'repairing':+ case 'verifying': {+ return 'goalList.status.verifying';+ }+ default: {+ return undefined;+ }+ }+};++const taskStatusKey = (status: string) => {+ switch (status) {+ case 'backlog': {+ return 'goalList.status.planning';+ }+ case 'completed': {+ return 'goalList.status.review';+ }+ case 'failed': {+ return 'goalList.status.error';+ }+ case 'paused': {+ return 'goalList.status.paused';+ }+ case 'canceled': {+ return 'goalList.status.canceled';+ }+ case 'scheduled': {+ return 'goalList.status.waiting';+ }+ default: {+ return 'goalList.status.running';+ }+ }+};++export const getGoalPresentation = (input: GoalPresentationInput) => {+ const checks = input.checks ?? [];+ const passed = checks.filter((check) => check.state === 'passed').length;+ const total = checks.length;++ return {+ maxRounds: input.maxRounds,+ passed,+ progress: total > 0 ? Math.round((passed / total) * 100) : 0,+ rounds: input.rounds,+ statusKey: acceptanceStatusKey(input.acceptanceStatus) ?? taskStatusKey(input.taskStatus),+ total,+ };+};diff --git a/src/features/AgentGoals/goalViewModel.test.ts b/src/features/AgentGoals/goalViewModel.test.tsnew file mode 100644index 00000000000..c7bdafeebe8--- /dev/null+++ b/src/features/AgentGoals/goalViewModel.test.ts@@ -0,0 +1,99 @@+import type { TaskDetailActivity } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ formatGoalCost,+ formatGoalDuration,+ getGoalDescription,+ getGoalRunMetrics,+ getGoalRuns,+ getRecentGoalRuns,+ goalStatusToTaskStatus,+ shouldShowGoal,+} from './goalViewModel';++describe('goalViewModel', () => {+ it('formats compact run duration and cost metrics', () => {+ expect(formatGoalDuration(7500)).toBe('1m');+ expect(formatGoalDuration(3_900_000)).toBe('1h 5m');+ expect(formatGoalCost(0.0042)).toBe('$0.0042');+ expect(formatGoalCost(0)).toBe('—');+ });+ it('uses the persisted goal description before the execution instruction', () => {+ expect(+ getGoalDescription({+ description: 'Increase successful releases',+ instruction: 'Run the release checklist',+ }),+ ).toBe('Increase successful releases');+ });++ it('falls back to the instruction when no description exists', () => {+ expect(+ getGoalDescription({ description: null, instruction: 'Run the release checklist' }),+ ).toBe('Run the release checklist');+ });++ it('returns only Agent runs with the newest run first', () => {+ const activities = [+ { id: 'created', type: 'created' },+ { id: 'run-1', type: 'topic' },+ { id: 'comment', type: 'comment' },+ { id: 'run-2', type: 'topic' },+ ] as TaskDetailActivity[];++ expect(getGoalRuns(activities).map((activity) => activity.id)).toEqual(['run-2', 'run-1']);+ });++ it('limits the recent execution list to the latest 10 runs', () => {+ const activities = Array.from({ length: 12 }, (_, index) => ({+ id: `run-${index + 1}`,+ type: 'topic',+ })) as TaskDetailActivity[];++ expect(getRecentGoalRuns(activities).map((activity) => activity.id)).toEqual([+ 'run-12',+ 'run-11',+ 'run-10',+ 'run-9',+ 'run-8',+ 'run-7',+ 'run-6',+ 'run-5',+ 'run-4',+ 'run-3',+ ]);+ });++ it('hides achieved goals from the default active filter without hiding pending acceptance', () => {+ expect(shouldShowGoal('goalList.status.achieved', 'active')).toBe(false);+ expect(shouldShowGoal('goalList.status.review', 'active')).toBe(true);+ expect(shouldShowGoal('goalList.status.achieved', 'all')).toBe(true);+ });++ it('uses the Goal acceptance state for its status icon', () => {+ expect(goalStatusToTaskStatus('goalList.status.review')).toBe('paused');+ expect(goalStatusToTaskStatus('goalList.status.achieved')).toBe('completed');+ expect(goalStatusToTaskStatus('goalList.status.verifying')).toBe('running');+ });++ it('aggregates duration and cost from every topic run', () => {+ expect(+ getGoalRunMetrics([+ {+ completedAt: '2026-08-06T00:00:03.000Z',+ cost: 0.012,+ time: '2026-08-06T00:00:01.000Z',+ type: 'topic',+ },+ { content: 'comment', type: 'comment' },+ {+ completedAt: '2026-08-06T00:00:08.500Z',+ cost: 0.008,+ time: '2026-08-06T00:00:03.000Z',+ type: 'topic',+ },+ ]),+ ).toEqual({ cost: 0.02, duration: 7500 });+ });+});diff --git a/src/features/AgentGoals/goalViewModel.ts b/src/features/AgentGoals/goalViewModel.tsnew file mode 100644index 00000000000..ba65f0f1c13--- /dev/null+++ b/src/features/AgentGoals/goalViewModel.ts@@ -0,0 +1,74 @@+import type { TaskDetailActivity } from '@lobechat/types';++interface GoalDescriptionSource {+ description?: string | null;+ instruction: string;+}++export const getGoalDescription = ({ description, instruction }: GoalDescriptionSource) =>+ description?.trim() || instruction.trim();++export const getGoalRuns = (activities?: TaskDetailActivity[]) =>+ activities?.filter((activity) => activity.type === 'topic').toReversed() ?? [];++export const getRecentGoalRuns = (activities?: TaskDetailActivity[], limit = 10) =>+ getGoalRuns(activities).slice(0, limit);++export const formatGoalDuration = (milliseconds: number) => {+ if (milliseconds <= 0) return '—';+ const totalMinutes = Math.max(1, Math.round(milliseconds / 60_000));+ if (totalMinutes < 60) return `${totalMinutes}m`;+ const hours = Math.floor(totalMinutes / 60);+ const minutes = totalMinutes % 60;+ return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;+};++export const formatGoalCost = (cost: number) =>+ cost > 0 ? `$${cost < 0.01 ? cost.toFixed(4) : cost.toFixed(2)}` : '—';++export const getGoalRunMetrics = (activities?: TaskDetailActivity[]) =>+ getGoalRuns(activities).reduce(+ (metrics, activity) => {+ const startedAt = activity.time ? new Date(activity.time).getTime() : Number.NaN;+ const completedAt = activity.completedAt+ ? new Date(activity.completedAt).getTime()+ : Number.NaN;+ const duration = completedAt - startedAt;++ return {+ cost: metrics.cost + (activity.cost ?? 0),+ duration: metrics.duration + (Number.isFinite(duration) && duration > 0 ? duration : 0),+ };+ },+ { cost: 0, duration: 0 },+ );++export const shouldShowGoal = (statusKey: string, filter: 'active' | 'all') =>+ filter === 'all' || statusKey !== 'goalList.status.achieved';++export const goalStatusToTaskStatus = (statusKey: string) => {+ switch (statusKey) {+ case 'goalList.status.achieved': {+ return 'completed';+ }+ case 'goalList.status.error': {+ return 'failed';+ }+ case 'goalList.status.canceled': {+ return 'canceled';+ }+ case 'goalList.status.paused':+ case 'goalList.status.review': {+ return 'paused';+ }+ case 'goalList.status.planning': {+ return 'backlog';+ }+ case 'goalList.status.waiting': {+ return 'scheduled';+ }+ default: {+ return 'running';+ }+ }+};diff --git a/src/features/AgentGoals/index.ts b/src/features/AgentGoals/index.tsnew file mode 100644index 00000000000..515badd2884--- /dev/null+++ b/src/features/AgentGoals/index.ts@@ -0,0 +1,2 @@+export { default as AgentGoalsPage } from './AgentGoalsPage';+export { default as GoalDetailPage } from './GoalDetailPage';diff --git a/src/features/AgentGoals/routeMeta.ts b/src/features/AgentGoals/routeMeta.tsnew file mode 100644index 00000000000..acbe9fea227--- /dev/null+++ b/src/features/AgentGoals/routeMeta.ts@@ -0,0 +1,8 @@+import { TargetIcon } from 'lucide-react';++import { routeMeta } from '@/spa/router/routeMeta';++export const goalsRouteMeta = routeMeta({+ icon: TargetIcon,+ titleKey: 'navigation.goals',+});diff --git a/src/features/AgentGoals/types.ts b/src/features/AgentGoals/types.tsnew file mode 100644index 00000000000..e89ad7abea6--- /dev/null+++ b/src/features/AgentGoals/types.ts@@ -0,0 +1,6 @@+import type { GoalListItem } from '@/store/goal/initialState';++export interface GoalItemProps {+ hideAchieved?: boolean;+ task: GoalListItem;+}diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsxindex e39d6918925..c1b75803595 100644--- a/src/features/AgentSidebar/Header/Nav.test.tsx+++ b/src/features/AgentSidebar/Header/Nav.test.tsx@@ -41,6 +41,7 @@ vi.mock('lucide-react', () => ({MessagesSquareIcon: () => null,RadioTowerIcon: () => null,SearchIcon: () => null,+ TargetIcon: () => null,}));vi.mock('react-i18next', () => ({@@ -137,6 +138,18 @@ vi.mock('@/store/serverConfig', () => ({) => selector({ featureFlags: { isAgentEditable: true } }),}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: unknown) => unknown) =>+ selector({ preference: { lab: { enableTopicAcceptance: true } } }),+}));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: {+ enableTopicAcceptance: (state: { preference: { lab?: { enableTopicAcceptance?: boolean } } }) =>+ state.preference.lab?.enableTopicAcceptance ?? false,+ },+}));+describe('Agent sidebar header nav', () => {beforeEach(() => {mutateMock.mockReset();@@ -194,6 +207,7 @@ describe('Agent sidebar header nav', () => {it('shows message channels for Codex agents', () => {agentMock.heterogeneousProviderType = 'codex';+usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');render(<Nav />);@@ -209,4 +223,24 @@ describe('Agent sidebar header nav', () => {expect(screen.queryByRole('button', { name: 'tab.integration' })).not.toBeInTheDocument();});++ it('navigates to the agent goals page', () => {+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');++ render(<Nav />);+ fireEvent.click(screen.getByRole('button', { name: 'goalList.title' }));++ expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });+ expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u/goals');+ });++ it('places topics above profile and goals in the agent navigation', () => {+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');++ render(<Nav />);++ const labels = screen.getAllByRole('button').map((button) => button.textContent);+ expect(labels.indexOf('management.sidebarEntry')).toBeLessThan(labels.indexOf('tab.profile'));+ expect(labels.indexOf('tab.profile')).toBeLessThan(labels.indexOf('goalList.title'));+ });});diff --git a/src/features/AgentSidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsxindex 3ec8ee75105..8f3d8da7e13 100644--- a/src/features/AgentSidebar/Header/Nav.tsx+++ b/src/features/AgentSidebar/Header/Nav.tsx@@ -7,6 +7,7 @@ import {MessagesSquareIcon,RadioTowerIcon,SearchIcon,+ TargetIcon,} from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -26,6 +27,8 @@ import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useGlobalStore } from '@/store/global';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';const Nav = memo(() => {const { t } = useTranslation('chat');@@ -34,6 +37,7 @@ const Nav = memo(() => {const agentId = params.aid;const { pathname } = useActiveLocation();const isProfileActive = pathname.includes('/profile');+ const isGoalsActive = pathname.endsWith('/goals');const isChannelActive = pathname.includes('/channel');// Topic IDs are prefixed `topics_`, so /agent/:aid/topics_abc would also match// pathname.includes('/topics') — anchor to end to avoid that false positive.@@ -56,6 +60,7 @@ const Nav = memo(() => {const switchTopic = useChatStore((s) => s.switchTopic);const [openNewTopicOrSaveTopic] = useChatStore((s) => [s.openNewTopicOrSaveTopic]);const isNewTopicSendInFlight = useChatStore(topicSelectors.isNewTopicSendInFlight);+ const enableTopicAcceptance = useUserStore(labPreferSelectors.enableTopicAcceptance);const { mutate } = useActionSWR(topicActionKeys.openNewOrSave(), openNewTopicOrSaveTopic);const handleNewTopic = () => {@@ -84,6 +89,15 @@ const Nav = memo(() => {toggleCommandMenu(true);}}/>+ <NavItem+ active={isTopicsActive}+ icon={MessagesSquareIcon}+ title={tTopic('management.sidebarEntry')}+ onClick={() => {+ switchTopic(null, { skipRefreshMessage: true });+ router.push(urlJoin('/agent', agentId!, 'topics'));+ }}+ />{!hideProfile && (<NavItemactive={isProfileActive}@@ -95,15 +109,17 @@ const Nav = memo(() => {}}/>)}- <NavItem- active={isTopicsActive}- icon={MessagesSquareIcon}- title={tTopic('management.sidebarEntry')}- onClick={() => {- switchTopic(null, { skipRefreshMessage: true });- router.push(urlJoin('/agent', agentId!, 'topics'));- }}- />+ {enableTopicAcceptance && (+ <NavItem+ active={isGoalsActive}+ icon={TargetIcon}+ title={t('goalList.title')}+ onClick={() => {+ switchTopic(null, { skipRefreshMessage: true });+ router.push(urlJoin('/agent', agentId!, 'goals'));+ }}+ />+ )}{!hideChannel && (<NavItemactive={isChannelActive}diff --git a/src/features/AgentSidebar/Task/index.tsx b/src/features/AgentSidebar/Task/index.tsxindex 652d9f5b38a..ea713e48a7f 100644--- a/src/features/AgentSidebar/Task/index.tsx+++ b/src/features/AgentSidebar/Task/index.tsx@@ -35,13 +35,13 @@ const TaskList = memo<TaskListProps>(({ itemKey }) => {const { data, isLoading } = useClientDataSWR<{ data: TaskGroupItem[]; success: boolean }>(enabled ? taskKeys.sidebarGroups(agentId) : null,async ([, id]: [string, string]) =>- taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS }),+ taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS, hasGoal: false }),{fallbackData: { data: [], success: true },revalidateOnFocus: false,},);- const taskGroups = data?.data ?? [];+ const taskGroups = useMemo(() => data?.data ?? [], [data?.data]);const orderedGroups = useMemo(() => {const map = new Map(taskGroups.map((g) => [g.key, g]));diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsxindex 9776719cdb7..be0476f05f6 100644--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx@@ -28,6 +28,8 @@ import { useAgentVisibility } from '../shared/useAgentVisibility';export interface CreateTaskContentProps {agentId?: string;+ /** Create a persistent goal root backed by the existing task + verify config. */+ goal?: boolean;/*** Locks the assignee to `agentId` and hides the agent picker. Used on the* agent-scoped task list where every task belongs to that agent.@@ -42,7 +44,7 @@ export interface CreateTaskContentProps {}const CreateTaskContent = memo<CreateTaskContentProps>(- ({ agentId, lockAssignee, onCreated, showInlineToggle = true }) => {+ ({ agentId, goal = false, lockAssignee, onCreated, showInlineToggle = true }) => {const { t } = useTranslation('chat');const { close } = useModalContext();const { allowed: canCreateTask, reason } = usePermission('create_content');@@ -102,6 +104,16 @@ const CreateTaskContent = memo<CreateTaskContentProps>(try {const result = await createTask({assigneeAgentId,+ config: goal+ ? {+ goal: { maxIterations: 10 },+ verify: {+ enabled: true,+ maxIterations: 10,+ requirement: instruction || title.trim(),+ },+ }+ : undefined,editorData: editorJson,instruction: instruction || title.trim(),name: title.trim() || undefined,@@ -127,6 +139,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(close,createTask,editor,+ goal,onCreated,priority,t,diff --git a/src/routes/(main)/agent/goal/[goalId]/index.tsx b/src/routes/(main)/agent/goal/[goalId]/index.tsxnew file mode 100644index 00000000000..449e5bba94c--- /dev/null+++ b/src/routes/(main)/agent/goal/[goalId]/index.tsx@@ -0,0 +1,26 @@+'use client';++import { memo, useEffect } from 'react';+import { useParams } from 'react-router';++import { GoalDetailPage } from '@/features/AgentGoals';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++const GoalDetailRoute = memo(() => {+ const { aid, goalId } = useParams<{ aid?: string; goalId?: string }>();+ const navigate = useWorkspaceAwareNavigate();+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);++ useEffect(() => {+ if (aid && !enabled) navigate(`/agent/${aid}`, { replace: true });+ }, [aid, enabled, navigate]);++ if (!aid || !goalId) return null;+ if (!enabled) return null;++ return <GoalDetailPage agentId={aid} goalId={goalId} />;+});++export default GoalDetailRoute;diff --git a/src/routes/(main)/agent/goals/index.tsx b/src/routes/(main)/agent/goals/index.tsxnew file mode 100644index 00000000000..636917400fd--- /dev/null+++ b/src/routes/(main)/agent/goals/index.tsx@@ -0,0 +1,26 @@+'use client';++import { memo, useEffect } from 'react';+import { useParams } from 'react-router';++import { AgentGoalsPage } from '@/features/AgentGoals';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++const AgentGoalsRoute = memo(() => {+ const { aid } = useParams<{ aid?: string }>();+ const navigate = useWorkspaceAwareNavigate();+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);++ useEffect(() => {+ if (aid && !enabled) navigate(`/agent/${aid}`, { replace: true });+ }, [aid, enabled, navigate]);++ if (!aid) return null;+ if (!enabled) return null;++ return <AgentGoalsPage agentId={aid} />;+});++export default AgentGoalsRoute;diff --git a/src/services/__tests__/task.test.ts b/src/services/__tests__/task.test.tsindex 155f261d146..cea0c41680a 100644--- a/src/services/__tests__/task.test.ts+++ b/src/services/__tests__/task.test.ts@@ -17,6 +17,7 @@ vi.mock('@/libs/trpc/client', () => ({clearAll: { mutate: vi.fn() },create: { mutate: vi.fn() },delete: { mutate: vi.fn() },+ deleteGoal: { mutate: vi.fn() },deleteComment: { mutate: vi.fn() },deleteTopic: { mutate: vi.fn() },detail: { query: vi.fn() },@@ -102,6 +103,11 @@ describe('TaskService', () => {expect(lambdaClient.task.delete.mutate).toHaveBeenCalledWith({ id: 'T-1' });});+ it('deleteGoal should call the subtree deletion endpoint', async () => {+ await taskService.deleteGoal('GOAL-1');+ expect(lambdaClient.task.deleteGoal.mutate).toHaveBeenCalledWith({ id: 'GOAL-1' });+ });+it('updateStatus should pass status directly', async () => {await taskService.updateStatus('T-1', 'running');expect(lambdaClient.task.updateStatus.mutate).toHaveBeenCalledWith({diff --git a/src/services/task.ts b/src/services/task.tsindex 017d4792a68..5e4d9e78daa 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -11,6 +11,7 @@ class TaskService {list = async (params: {assigneeAgentId?: string;+ hasGoal?: boolean;limit?: number;offset?: number;parentIdentifier?: string;@@ -28,6 +29,7 @@ class TaskService {offset?: number;statuses: string[];}>;+ hasGoal?: boolean;parentTaskId?: string | null;visibility?: 'private' | 'public';}) => lambdaClient.task.groupList.query(params);@@ -54,6 +56,7 @@ class TaskService {assigneeAgentId?: string;assigneeUserId?: string;automationMode?: TaskAutomationMode;+ config?: Record<string, unknown>;createdByAgentId?: string;description?: string;editorData?: unknown;@@ -98,6 +101,8 @@ class TaskService {delete = async (id: string) => lambdaClient.task.delete.mutate({ id });+ deleteGoal = async (id: string) => lambdaClient.task.deleteGoal.mutate({ id });+clearAll = async () => lambdaClient.task.clearAll.mutate();updateStatus = async (id: string, status: TaskStatus, error?: string) =>diff --git a/src/services/verify.ts b/src/services/verify.tsindex 52acabe9466..fd6c86e9054 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -22,6 +22,9 @@ import type {import { lambdaClient } from '@/libs/trpc/client';export type AcceptanceBundle = Awaited<ReturnType<typeof lambdaClient.acceptance.getBundle.query>>;+export type AcceptanceBySubject = Awaited<+ ReturnType<typeof lambdaClient.acceptance.getBySubject.query>+>;export type AcceptanceListItem = Awaited<ReturnType<typeof lambdaClient.acceptance.list.query>>[number];diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 0ce3c944b04..8fe6fc77aa7 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -20,6 +20,7 @@ import {} from '@/business/client/BusinessDesktopRoutes';import ContentLoading from '@/components/Loading/ContentLoading';import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';+import { goalsRouteMeta } from '@/features/AgentGoals/routeMeta';import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';@@ -120,6 +121,22 @@ export const sharedMainAreaChildren: RouteObject[] = [),path: 'docs',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/goals'),+ 'Desktop > Chat > Goals',+ ),+ handle: { meta: goalsRouteMeta },+ path: 'goals',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/goal/[goalId]'),+ 'Desktop > Chat > Goal Detail',+ ),+ handle: { meta: goalsRouteMeta },+ path: 'goal/:goalId',+ },{element: dynamicElement(() => import('@/routes/(main)/agent/profile'),diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsnew file mode 100644index 00000000000..7378280457e--- /dev/null+++ b/src/store/goal/action.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskService } from '@/services/task';++import { useGoalStore } from './index';++vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));+vi.mock('@/services/task', () => ({ taskService: { deleteGoal: vi.fn(), groupList: vi.fn() } }));++beforeEach(() => {+ vi.clearAllMocks();+ useGoalStore.setState({+ goalListByAgentId: {},+ goalListFilter: 'active',+ goalListInitializedAgentIds: [],+ goalListVisibleLimit: 10,+ goalViewMode: 'list',+ });+});++describe('GoalAction', () => {+ it('stores goal lists independently for each agent', () => {+ useGoalStore.getState().useFetchGoals('agent-1');+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {+ onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;+ };++ options.onSuccess({ data: [{ tasks: [{ id: 'goal-1' }] }] });++ expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'goal-1' }]);+ expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');+ });++ it('refreshes only the requested agent goal cache', async () => {+ await useGoalStore.getState().refreshGoals('agent-1');++ expect(mutate).toHaveBeenCalledWith(['task:sidebarGroups', 'agent-1:goals-page']);+ });++ it('owns list display state', () => {+ useGoalStore.getState().setGoalListFilter('all');+ useGoalStore.getState().setGoalViewMode('card');+ useGoalStore.getState().loadMoreGoals();++ expect(useGoalStore.getState()).toMatchObject({+ goalListFilter: 'all',+ goalListVisibleLimit: 20,+ goalViewMode: 'card',+ });+ });++ it('deletes a goal subtree through the goal endpoint and removes it from local state', async () => {+ useGoalStore.getState().useFetchGoals('agent-1');+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {+ onSuccess: (value: {+ data: Array<{ tasks: Array<{ id: string; identifier: string }> }>;+ }) => void;+ };+ options.onSuccess({+ data: [+ {+ tasks: [+ { id: 'goal-1', identifier: 'GOAL-1' },+ { id: 'goal-2', identifier: 'GOAL-2' },+ ],+ },+ ],+ });++ await useGoalStore.getState().deleteGoal('agent-1', 'GOAL-1');++ expect(taskService.deleteGoal).toHaveBeenCalledWith('GOAL-1');+ expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([+ { id: 'goal-2', identifier: 'GOAL-2' },+ ]);+ });+});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsnew file mode 100644index 00000000000..3191f726297--- /dev/null+++ b/src/store/goal/action.ts@@ -0,0 +1,98 @@+import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskKeys } from '@/libs/swr/keys';+import { taskService } from '@/services/task';+import type { StoreSetter } from '@/store/types';++import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';++const GOAL_STATUSES = [+ 'backlog',+ 'running',+ 'scheduled',+ 'paused',+ 'completed',+ 'failed',+ 'canceled',+];++export type GoalStore = GoalState & GoalAction;+type Setter = StoreSetter<GoalStore>;++export class GoalActionImpl {+ readonly #get: () => GoalStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => GoalStore, _api?: unknown) {+ void _api;+ this.#get = get;+ this.#set = set;+ }++ deleteGoal = async (agentId: string, goalId: string): Promise<void> => {+ await taskService.deleteGoal(goalId);+ const current = this.#get().goalListByAgentId[agentId] ?? [];+ this.#set(+ ({ goalListByAgentId }) => ({+ goalListByAgentId: {+ ...goalListByAgentId,+ [agentId]: current.filter(({ id, identifier }) => id !== goalId && identifier !== goalId),+ },+ }),+ false,+ 'deleteGoal/success',+ );+ await this.refreshGoals(agentId);+ };++ loadMoreGoals = (): void => {+ this.#set(+ ({ goalListVisibleLimit }) => ({ goalListVisibleLimit: goalListVisibleLimit + 10 }),+ false,+ 'loadMoreGoals',+ );+ };++ refreshGoals = async (agentId: string): Promise<void> => {+ await mutate(taskKeys.sidebarGroups(`${agentId}:goals-page`));+ };++ setGoalListFilter = (filter: GoalListFilter): void => {+ this.#set({ goalListFilter: filter, goalListVisibleLimit: 10 }, false, 'setGoalListFilter');+ };++ setGoalViewMode = (mode: GoalViewMode): void => {+ this.#set({ goalViewMode: mode }, false, 'setGoalViewMode');+ };++ useFetchGoals = (agentId?: string) =>+ useClientDataSWR(+ agentId ? taskKeys.sidebarGroups(`${agentId}:goals-page`) : null,+ () =>+ taskService.groupList({+ assigneeAgentId: agentId,+ groups: [{ key: 'goals', limit: 100, statuses: GOAL_STATUSES }],+ hasGoal: true,+ parentTaskId: null,+ }),+ {+ onSuccess: ({ data }) => {+ this.#set(+ ({ goalListByAgentId, goalListInitializedAgentIds }) => ({+ goalListByAgentId: {+ ...goalListByAgentId,+ [agentId!]: data[0]?.tasks ?? [],+ },+ goalListInitializedAgentIds: goalListInitializedAgentIds.includes(agentId!)+ ? goalListInitializedAgentIds+ : [...goalListInitializedAgentIds, agentId!],+ }),+ false,+ 'useFetchGoals/success',+ );+ },+ revalidateOnFocus: true,+ },+ );+}++export type GoalAction = Pick<GoalActionImpl, keyof GoalActionImpl>;diff --git a/src/store/goal/index.ts b/src/store/goal/index.tsnew file mode 100644index 00000000000..e621984ca5f--- /dev/null+++ b/src/store/goal/index.ts@@ -0,0 +1,22 @@+'use client';++import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '@/store/middleware/createDevtools';+import { flattenActions } from '@/store/utils/flattenActions';++import { type GoalAction, GoalActionImpl, type GoalStore } from './action';+import { initialState } from './initialState';++const devtools = createDevtools('goal');++export const useGoalStore = createWithEqualityFn<GoalStore>()(+ devtools((...parameters) => ({+ ...initialState,+ ...flattenActions<GoalAction>([new GoalActionImpl(...parameters)]),+ })),+ shallow,+);++export { goalSelectors } from './selectors';diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsnew file mode 100644index 00000000000..9db955e7fd5--- /dev/null+++ b/src/store/goal/initialState.ts@@ -0,0 +1,21 @@+import type { TaskGroupItem } from '@/store/task/slices/list/initialState';++export type GoalListItem = TaskGroupItem['tasks'][number];+export type GoalListFilter = 'active' | 'all';+export type GoalViewMode = 'card' | 'list';++export interface GoalState {+ goalListByAgentId: Record<string, GoalListItem[]>;+ goalListFilter: GoalListFilter;+ goalListInitializedAgentIds: string[];+ goalListVisibleLimit: number;+ goalViewMode: GoalViewMode;+}++export const initialState: GoalState = {+ goalListByAgentId: {},+ goalListFilter: 'active',+ goalListInitializedAgentIds: [],+ goalListVisibleLimit: 10,+ goalViewMode: 'list',+};diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.tsnew file mode 100644index 00000000000..0b4f225bfdc--- /dev/null+++ b/src/store/goal/selectors.ts@@ -0,0 +1,13 @@+import type { GoalStore } from './action';++const EMPTY_GOALS: GoalStore['goalListByAgentId'][string] = [];++const goalList = (agentId: string) => (s: GoalStore) => s.goalListByAgentId[agentId] ?? EMPTY_GOALS;++const isGoalListInitialized = (agentId: string) => (s: GoalStore) =>+ s.goalListInitializedAgentIds.includes(agentId);++export const goalSelectors = {+ goalList,+ isGoalListInitialized,+};diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 2b1effc12f7..035e86ce0fa 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -183,6 +183,7 @@ export class TaskDetailSliceActionImpl {createTask = async (params: {assigneeAgentId?: string;automationMode?: 'heartbeat' | 'schedule';+ config?: Record<string, unknown>;createdByAgentId?: string;description?: string;editorData?: unknown;diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex ee514b8367d..285f6532865 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -137,6 +137,7 @@ export class TaskListSliceActionImpl {return taskService.groupList({assigneeAgentId: allAgents ? undefined : agentId,groups: DEFAULT_KANBAN_GROUPS,+ hasGoal: false,visibility: filterToServerVisibility(listVisibility),});},@@ -187,6 +188,7 @@ export class TaskListSliceActionImpl {async ([, id]: [string, string]) => {return this.fetchTaskList({...(allAgents ? {} : { assigneeAgentId: id }),+ hasGoal: false,visibility: filterToServerVisibility(listVisibility),});},diff --git a/src/store/verify/acceptance.test.ts b/src/store/verify/acceptance.test.tsnew file mode 100644index 00000000000..fba59ad3bd2--- /dev/null+++ b/src/store/verify/acceptance.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useClientDataSWR } from '@/libs/swr';++import { useVerifyStore } from './index';++vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));++beforeEach(() => {+ vi.clearAllMocks();+ useVerifyStore.setState({ acceptanceBundleMap: {}, acceptanceBySubjectMap: {} });+});++describe('Acceptance store', () => {+ it('normalizes acceptances by subject', () => {+ useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-1');+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {+ onSuccess: (value: { id: string }) => void;+ };++ options.onSuccess({ id: 'acceptance-1' });++ expect(useVerifyStore.getState().acceptanceBySubjectMap['task:task-1']).toEqual({+ id: 'acceptance-1',+ });+ });++ it('does not poll indefinitely when a subject has no acceptance', () => {+ useVerifyStore.getState().useFetchAcceptanceBySubject('task', 'task-without-acceptance');+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2];++ expect(options).not.toHaveProperty('refreshInterval');+ });++ it('caches bundles by acceptance id', () => {+ useVerifyStore.getState().useFetchAcceptanceBundle('acceptance-1');+ const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {+ onSuccess: (value: { acceptance: { id: string }; checks: never[] }) => void;+ };++ options.onSuccess({ acceptance: { id: 'acceptance-1' }, checks: [] });++ expect(useVerifyStore.getState().acceptanceBundleMap['acceptance-1']).toMatchObject({+ acceptance: { id: 'acceptance-1' },+ checks: [],+ });+ });+});diff --git a/src/store/verify/action.ts b/src/store/verify/action.tsindex 541488942ab..a4c844b113d 100644--- a/src/store/verify/action.ts+++ b/src/store/verify/action.ts@@ -1,8 +1,10 @@-import type { VerifyRubricConfig } from '@lobechat/types';+import type { AcceptanceSubjectType, VerifyRubricConfig } from '@lobechat/types';import { debounce } from 'es-toolkit/compat';import { type StateCreator } from 'zustand';import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';import { documentService } from '@/services/document';import { verifyService } from '@/services/verify';import { type StoreSetter } from '@/store/types';@@ -43,6 +45,58 @@ export class ActionImpl {});}+ refreshAcceptanceBundle = async (acceptanceId: string): Promise<void> => {+ await mutate(verifyKeys.acceptanceBundle(acceptanceId));+ };++ refreshAcceptanceBySubject = async (+ subjectType: AcceptanceSubjectType,+ subjectId: string,+ ): Promise<void> => {+ await mutate(verifyKeys.acceptanceBySubject(subjectType, subjectId));+ };++ useFetchAcceptanceBundle = (acceptanceId?: string | null) =>+ useClientDataSWR(+ acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,+ () => verifyService.getAcceptanceBundle(acceptanceId!),+ {+ onSuccess: (data) => {+ this.#set(+ ({ acceptanceBundleMap }) => ({+ acceptanceBundleMap: { ...acceptanceBundleMap, [acceptanceId!]: data },+ }),+ false,+ 'useFetchAcceptanceBundle/success',+ );+ },+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ },+ );++ useFetchAcceptanceBySubject = (subjectType: AcceptanceSubjectType, subjectId?: string | null) =>+ useClientDataSWR(+ subjectId ? verifyKeys.acceptanceBySubject(subjectType, subjectId) : null,+ () => verifyService.getAcceptanceBySubject(subjectType, subjectId!),+ {+ onSuccess: (data) => {+ const key = `${subjectType}:${subjectId}`;+ const { acceptanceBySubjectMap } = this.#get();+ if (Object.hasOwn(acceptanceBySubjectMap, key) && acceptanceBySubjectMap[key] === data)+ return;++ this.#set(+ { acceptanceBySubjectMap: { ...acceptanceBySubjectMap, [key]: data } },+ false,+ 'useFetchAcceptanceBySubject/success',+ );+ },+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ },+ );+#persist = async (): Promise<void> => {const criteria = [...this.#pendingCriteria.entries()];const instructions = [...this.#pendingInstructions.entries()];diff --git a/src/store/verify/initialState.ts b/src/store/verify/initialState.tsindex 32aaf5c73d3..658d41daf5a 100644--- a/src/store/verify/initialState.ts+++ b/src/store/verify/initialState.ts@@ -1,5 +1,7 @@import type { VerifierType, VerifyOnFailStrategy, VerifyRubricConfig } from '@lobechat/types';+import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';+/** The criterion fields the portal can edit. */export interface VerifyCriterionEdit {description?: string;@@ -10,6 +12,8 @@ export interface VerifyCriterionEdit {}export interface State {+ acceptanceBundleMap: Record<string, AcceptanceBundle>;+ acceptanceBySubjectMap: Record<string, AcceptanceBySubject>;/*** Per-criterion edit overlay, keyed by `verify_criteria.id`. Holds the* user's in-flight edits so the UI reflects them immediately while they are@@ -34,6 +38,8 @@ export interface State {}export const initialState: State = {+ acceptanceBundleMap: {},+ acceptanceBySubjectMap: {},criterionEdits: {},instructionEdits: {},rubricConfigEdits: {},diff --git a/src/store/verify/selectors.ts b/src/store/verify/selectors.tsindex ee21833ebfc..a5de33ee5cd 100644--- a/src/store/verify/selectors.ts+++ b/src/store/verify/selectors.ts@@ -6,6 +6,12 @@ import { type VerifyCriterionEdit } from './initialState';const EMPTY_EDIT: VerifyCriterionEdit = {};const EMPTY_RUBRIC_CONFIG: VerifyRubricConfig = {};+const acceptanceBundle = (acceptanceId?: string | null) => (s: Store) =>+ acceptanceId ? s.acceptanceBundleMap[acceptanceId] : undefined;++const acceptanceBySubject = (subjectType: string, subjectId?: string | null) => (s: Store) =>+ subjectId ? s.acceptanceBySubjectMap[`${subjectType}:${subjectId}`] : undefined;+const criterionEdit = (criterionId?: string) => (s: Store) =>(criterionId ? s.criterionEdits[criterionId] : undefined) ?? EMPTY_EDIT;@@ -19,6 +25,8 @@ const rubricTitleEdit = (rubricId?: string) => (s: Store) =>rubricId ? s.rubricTitleEdits[rubricId] : undefined;export const verifySelectors = {+ acceptanceBundle,+ acceptanceBySubject,criterionEdit,instructionEdit,rubricConfigEdit,