🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): carry task deliverables on the Goal Graph as Work (#19131)
Arvin Xud896947d0c5d
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex b3026c823ab..656337b1f86 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -544,6 +544,29 @@ value in the running app (`getComputedStyle` on the element, or resolvethe tint and x9–x10 for the line, verified in both themes: the scale flips indark mode, so a step that is a tint in light is a deep fill in dark.+### L-D14 — Linking to an agent document with the Work's binding id++**Wrong approach:** build an in-app document link out of the identifier a+document Work carries in `work_versions.metadata.agentDocumentId`, on the+reading that it names the agent's document.++**Why it fails:** `agentDocumentId` is the `agent_documents` binding ROW id — it+establishes that a binding exists and is not addressable. The document route+resolves the DOCUMENT id (`src/routes/(main)/agent/docs/[docId]` runs+`getIdFromIdentifier(docId, 'docs')`), which lives on `works.resource_id`+(`docs_xxx`). Document Works also carry no `url`, so there is nothing to fall+back to: the mis-addressed link degrades silently to the documents index+instead of erroring, and both the click and the navigation look successful.+Unit tests that assert the field was carried through cannot see it, because the+failure is in what the id means, not whether it arrived.++**Correct approach:** address an agent document by `works.resourceId`; use+`metadata.agentDocumentId` only as the gate proving the document is bound to an+agent. When verifying any Work-to-resource link, open it in the running app and+read `location.pathname` plus `document.title` — a link that lands on a list+page is the tell, and the id shape (`docs_xxx` vs a bare uuid) says which id was+used.+## Environment safety### L-S0 — Concluding a dependency moved from the root manifest alonediff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex dbaf5306588..ef0960ae620 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -11,6 +11,7 @@ import { GoalGraphModel } from '@/database/models/goalGraph';import { MetricModel } from '@/database/models/metric';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { WorkModel } from '@/database/models/work';import {acceptances,agentOperations,@@ -348,6 +349,79 @@ describe('GoalService', () => {});});+ it('links what the task delivered to its node, and skips the task Work itself', async () => {+ // The deliverable used to survive only as a URL inside the finding's prose:+ // the graph recorded that a task finished but not what came out of it.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const workModel = new WorkModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Deliver me'], title: 'Harvest deliverables' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ handoff: { summary: 'Delivered', title: 'Delivered title' },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await workModel.registerExternal({+ changeType: 'created',+ identifier: 'ENG-7',+ resourceId: 'lobehub/lobehub#7',+ resourceType: 'github_issue',+ rootOperationId: 'op-delivered',+ title: 'The delivered issue',+ toolIdentifier: 'lobe-github',+ toolName: 'createIssue',+ });+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);++ const snapshot = await service.graph(graph.goal.id);+ const linked = snapshot.workVersions.filter((link) => link.nodeId === created.nodeId);+ expect(linked.some((link) => link.work?.title === 'The delivered issue')).toBe(true);+ // The responsible task's own Work is still linked — it is the execution+ // container, and the client is what filters it out of the deliverable list.+ expect(linked.some((link) => link.work?.type === 'task')).toBe(true);+ });++ it('re-settling a task does not duplicate its deliverable links', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const workModel = new WorkModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Deliver me'], title: 'Idempotent harvest' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ handoff: { summary: 'Delivered', title: 'Delivered title' },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await workModel.registerExternal({+ changeType: 'created',+ resourceId: 'lobehub/lobehub#8',+ resourceType: 'github_issue',+ rootOperationId: 'op-delivered',+ title: 'Delivered once',+ toolIdentifier: 'lobe-github',+ toolName: 'createIssue',+ });+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);++ const snapshot = await service.graph(graph.goal.id);+ const delivered = snapshot.workVersions.filter(+ (link) => link.nodeId === created.nodeId && link.work?.title === 'Delivered once',+ );+ expect(delivered).toHaveLength(1);+ });+it('leaves a fresh dispatch claim alone', async () => {// The same shape a moment after the claim is just a run about to start.vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(new Error('worker died'));diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 288229ddb0f..9c52baff55e 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -16,6 +16,7 @@ import type {MetricKind,TaskItem,TaskTopicHandoff,+ WorkVersionEventItem,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { sql } from 'drizzle-orm';@@ -117,6 +118,14 @@ export interface CreateGoalNodeInput {}/** Application service shared by CLI today and Graph UI/schedulers later. */+/**+ * Version events read per task run when harvesting deliverables. Generous+ * because the cap applies to events rather than to Works: the newest N events+ * of a run must still contain every Work it produced, even one revised many+ * times over.+ */+const DELIVERABLE_EVENTS_PER_RUN = 200;+export class GoalService {private readonly acceptanceService: AcceptanceService;private readonly goalModel: GoalModel;@@ -1508,6 +1517,11 @@ export class GoalService {'The complete requirements for this Task are included here. Do not inspect unrelated agent documents to recover requirements. This Task carries its own Acceptance: run it inside this Task — drive the real product surface, capture the evidence, and submit it against your own criteria while you work. Submit evidence only; an independent verifier judges whether this Task is complete.','Create implementation-level subtasks when useful. Finish the operation once the Current Task deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.','Make the final delivery self-contained for an independent verifier that may not have workspace access. Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands; file paths and claims that checks passed are not sufficient evidence by themselves.',+ // A path on the machine that happened to run the task is not a+ // deliverable: the goal page cannot open it, the reviewer cannot read it,+ // and /tmp does not survive the week. Only artifacts that reach the+ // product are harvested onto the Goal Graph (see attachTaskDeliverables).+ 'Persist every deliverable inside the product, not only on the local disk. Write reports and analyses as agent documents, and produce generated files (pptx / xlsx / docx / pdf, …) in the operation workspace so they are uploaded and registered. A local path such as /tmp or a repository directory is a working location, not a delivery — anything left only there is unreviewable and is not attached to the Goal.','Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',].filter(Boolean)@@ -1638,6 +1652,69 @@ export class GoalService {.join('\n\n');};+ /**+ * Link what a task actually delivered to the node that ordered it.+ *+ * The task Work attached alongside is the execution container; these are its+ * outputs — the documents and external resources the run registered. Without+ * them the graph records that a task finished but not what it produced, and+ * the deliverable survives only as a URL buried in the finding's prose.+ *+ * Harvested across every run of the task, not just the delivering one: a task+ * that wrote its document in an earlier round and only revised it in the last+ * still delivered that document. Works are deduplicated by identity and+ * linked at their newest version, so a document refined across rounds is one+ * deliverable with a history rather than several deliverables.+ *+ * `task` Works are deliberately excluded: the responsible task's own Work is+ * the execution container and the caller already links it. `file` Works are+ * opt-in at the registry (conversation lists do not want every exported+ * file), but a goal's deliverables are exactly where a produced deck or PDF+ * belongs, so they are requested explicitly here.+ */+ private attachTaskDeliverables = async (+ goalId: string,+ nodeId: string,+ operationIds: string[],+ effects: GoalAdvanceEffect[],+ ) => {+ if (operationIds.length === 0) return;++ // The per-operation cap is applied to version EVENTS before this dedupes by+ // Work identity, so the default of 20 lets a document revised twenty times+ // push every other deliverable out of its own task's list.+ const byOperation = await this.workModel.listByRootOperations({+ includeFileWorks: true,+ limit: DELIVERABLE_EVENTS_PER_RUN,+ rootOperationIds: operationIds,+ });++ const newestByWork = new Map<string, WorkVersionEventItem>();+ for (const item of Object.values(byOperation).flat()) {+ if (item.type === 'task') continue;+ const seen = newestByWork.get(item.id);+ if (!seen || seen.version.createdAt < item.version.createdAt) newestByWork.set(item.id, item);+ }++ for (const item of newestByWork.values()) {+ const link = await this.coordinatorGraph.attachWorkVersion(+ goalId,+ nodeId,+ item.version.id,+ 'produced',+ );+ // `attachWorkVersion` is idempotent, so a re-settled task re-links the+ // same versions silently; only a genuinely new link is worth an effect.+ if (link)+ effects.push({+ detail: item.type,+ nodeId,+ targetId: item.id,+ type: 'attached_work_version',+ });+ }+ };+private consumeCompletedTask = async (graph: GoalGraphSnapshot,nodeId: string,@@ -1680,6 +1757,16 @@ export class GoalService {'produced',);}+ // Every run of the task, not the ten `findWithHandoff` reads for the+ // finding: an attempt budget above ten would otherwise strand a deliverable+ // produced early and merely referenced later.+ const allRuns = await this.taskTopicModel.findByTaskId(taskId);+ await this.attachTaskDeliverables(+ graph.goal.id,+ nodeId,+ allRuns.flatMap((topic) => (topic.operationId ? [topic.operationId] : [])),+ effects,+ );if (!existingFinding) {const handoff = latest?.handoff as TaskTopicHandoff | null;const finding = await this.coordinatorGraph.createNode(graph.goal.id, {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e0f0aeac16f..c5b3326710f 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -524,6 +524,10 @@"goalProcess.attempts.retired": "Retired","goalProcess.attempts.running": "Running","goalProcess.attempts.title": "Previous attempts",+ "goalProcess.deliverables.empty": "Nothing delivered yet. Documents, generated files and linked resources a task persists show up here — anything left only on a local path does not.",+ "goalProcess.deliverables.from": "From “{{title}}”",+ "goalProcess.deliverables.title": "Deliverables",+ "goalProcess.deliverables.untitled": "Untitled","goalProcess.edge.contradicts": "contradicts","goalProcess.edge.investigates": "investigates","goalProcess.edge.leadsTo": "leads to",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex a9dd1fdbec5..b58f941e512 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -524,6 +524,10 @@"goalProcess.attempts.retired": "已放弃","goalProcess.attempts.running": "进行中","goalProcess.attempts.title": "之前的尝试",+ "goalProcess.deliverables.empty": "还没有交付物。任务写入产品的文档、生成的文件和关联资源会出现在这里——只留在本地路径上的产物不会。",+ "goalProcess.deliverables.from": "来自「{{title}}」",+ "goalProcess.deliverables.title": "交付物",+ "goalProcess.deliverables.untitled": "未命名","goalProcess.edge.contradicts": "反驳","goalProcess.edge.investigates": "调查","goalProcess.edge.leadsTo": "导向",diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex 78087f7f733..31fadd4176f 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -4,7 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, goalNodes, users } from '../../schemas';+import { agents, goalNodes, goals, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { GoalModel } from '../goal';import { GoalGraphModel } from '../goalGraph';@@ -223,7 +223,50 @@ describe('GoalGraphModel', () => {);expect(link).toMatchObject({ nodeId: node!.id, relation: 'produced' });- expect((await graphModel.getGraph(goal.id))?.workVersions).toHaveLength(1);+ const links = (await graphModel.getGraph(goal.id))?.workVersions;+ expect(links).toHaveLength(1);+ // Personal mode: the Work ownership predicate the workspace case needs must+ // not hide the owner's own deliverable from their own goal.+ expect(links?.[0].work).toMatchObject({ type: 'task', workId: work!.id });+ });++ it('hydrates a linked Work only for a viewer allowed to see it', async () => {+ // A workspace goal is readable by every member (`goals` has no visibility+ // column), but a Work is owner-scoped. Hydrating the link without the Work+ // ownership predicate handed another member the owner's private title,+ // status, url and document binding.+ const workspaceId = 'goal-graph-workspace';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Goal graph workspace',+ primaryOwnerId: userId,+ slug: 'goal-graph-workspace',+ });+ const ownerGoals = new GoalModel(serverDB, userId, workspaceId);+ const ownerGraph = new GoalGraphModel(serverDB, userId, workspaceId);+ const goal = await ownerGoals.create({ subjectType: 'standalone', title: 'Shared goal' });+ await serverDB.update(goals).set({ workspaceId }).where(eq(goals.id, goal.id));+ const node = await ownerGraph.createNode(goal.id, { kind: 'task', title: 'Produce evidence' });++ const work = await new WorkModel(serverDB, userId, workspaceId).registerExternal({+ changeType: 'created',+ resourceId: 'lobehub/lobehub#1',+ resourceType: 'github_issue',+ title: 'Private follow-up issue',+ toolIdentifier: 'goal-test',+ toolName: 'createIssue',+ url: 'https://github.com/lobehub/lobehub/issues/1',+ });+ await ownerGraph.attachWorkVersion(goal.id, node!.id, work!.currentVersionId!, 'produced');++ const asOwner = await ownerGraph.getGraph(goal.id);+ expect(asOwner?.workVersions[0].work).toMatchObject({ title: 'Private follow-up issue' });++ // The other member reaches the same goal and the same link…+ const asMember = await new GoalGraphModel(serverDB, otherUserId, workspaceId).getGraph(goal.id);+ expect(asMember?.workVersions).toHaveLength(1);+ // …but the Work behind it stays unresolved rather than naming itself.+ expect(asMember?.workVersions[0].work).toBeUndefined();});it('does not expose or mutate another user graph', async () => {diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 705ba4c2d7c..80ab5e5c21c 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -7,6 +7,7 @@ import type {GoalEventEntityType,GoalEventType,GoalGraphSnapshot,+ GoalGraphWorkVersionDisplay,GoalNodeKind,GoalNodeStatus,GoalNodeWorkVersionRelation,@@ -134,16 +135,85 @@ export class GoalGraphModel {.orderBy(asc(goalNodeWorkVersions.createdAt)),]);+ const linkDisplays = await this.hydrateWorkVersions(+ linkedWorkVersions.map(({ link }) => link.workVersionId),+ );+return {decisions: decisions.map(({ goal_node_decisions }) => goal_node_decisions),edges,events,goal,nodes,- workVersions: linkedWorkVersions.map(({ link }) => link),+ workVersions: linkedWorkVersions.map(({ link }) => ({+ ...link,+ // A link nothing came back for still counts; it just cannot be named.+ work: linkDisplays.get(link.workVersionId),+ })),};};+ /**+ * Display snapshots for linked Work versions, keyed by version id.+ *+ * Read separately from the link rows, and gated by `workOwnership`: `goals`+ * has no visibility column, so every member of a team workspace can read a+ * workspace goal, while a Work is owner-scoped (external Works are always+ * private, document/file Works follow their backing resource). Hydrating+ * without the predicate handed another member the owner's private title,+ * status, url and document binding.+ *+ * A second small query rather than a join on the graph read: `workOwnership`+ * carries correlated EXISTS guards, and evaluating those inside the graph+ * join cost that read ~2.5x — which the detail page pays every few seconds+ * while it polls. Here they run once over a handful of linked versions, and a+ * goal with no links skips the query entirely.+ */+ private hydrateWorkVersions = async (versionIds: string[]) => {+ const display = new Map<string, GoalGraphWorkVersionDisplay>();+ const ids = [...new Set(versionIds)];+ if (ids.length === 0) return display;++ const rows = await this.db+ .select({+ identifier: workVersions.identifier,+ // Document and file Works keep their open target in the version+ // metadata rather than the `url` column.+ metadata: workVersions.metadata,+ resourceId: works.resourceId,+ status: workVersions.status,+ title: workVersions.title,+ type: works.type,+ url: workVersions.url,+ versionId: workVersions.id,+ workId: works.id,+ })+ .from(workVersions)+ .innerJoin(+ works,+ and(+ eq(workVersions.workId, works.id),+ workOwnership({ db: this.db, userId: this.userId, workspaceId: this.workspaceId }),+ ),+ )+ .where(inArray(workVersions.id, ids));++ for (const row of rows) {+ display.set(row.versionId, {+ identifier: row.identifier,+ resourceId: row.resourceId,+ status: row.status,+ title: row.title,+ type: row.type,+ url: row.url,+ workId: row.workId,+ ...(row.metadata?.agentDocumentId ? { agentDocumentId: row.metadata.agentDocumentId } : {}),+ ...(row.metadata?.fileUrl ? { fileUrl: row.metadata.fileUrl } : {}),+ });+ }+ return display;+ };+/*** How many events one graph read carries.*diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 283c0c71982..4798f6ec967 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1993,6 +1993,11 @@ export default {'goalProcess.node.artifactsTooltip':'{{count}} work versions registered. Opening them needs a server read that does not exist yet.','goalProcess.node.humanTouched': 'You took part in this task',+ 'goalProcess.deliverables.title': 'Deliverables',+ 'goalProcess.deliverables.empty':+ 'Nothing delivered yet. Documents, generated files and linked resources a task persists show up here — anything left only on a local path does not.',+ 'goalProcess.deliverables.from': 'From “{{title}}”',+ 'goalProcess.deliverables.untitled': 'Untitled','goalProcess.findings.title': 'Findings','goalProcess.findings.empty': 'No findings yet.','goalProcess.findings.answers': 'Answers “{{title}}”',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 9395f2e5c84..bb1d9a9a3b7 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,4 +1,5 @@import type { InitialGoalOverviewContext } from './stepContext';+import type { WorkType } from './work';// ============================================// Goal — independent target entity (`goals` table)@@ -260,9 +261,41 @@ export interface GoalGraphWorkVersionLink {id: string;nodeId: string;relation: GoalNodeWorkVersionRelation;+ /**+ * Display snapshot of the linked Work version, joined at read time so the+ * graph can name a deliverable instead of counting it. Absent only when the+ * version row is gone — the link is kept so the count stays honest.+ */+ work?: GoalGraphWorkVersionDisplay;workVersionId: string;}+/**+ * What a linked Work version shows without a second round-trip. Taken from the+ * immutable version row rather than the live Work: the graph records what the+ * task delivered at that moment, and a title edited later does not rewrite the+ * goal's history.+ */+export interface GoalGraphWorkVersionDisplay {+ /**+ * Proof that a `document` Work is bound to an agent, and therefore openable+ * in-app. It is the binding row's id, NOT a route parameter — the document+ * route resolves {@link resourceId}.+ */+ agentDocumentId?: string;+ /** Durable download target of a `file` Work, which keeps it out of `url`. */+ fileUrl?: string;+ identifier: string | null;+ /** Canonical resource identity — the document id an in-app link addresses. */+ resourceId: string | null;+ status: string | null;+ title: string | null;+ type: WorkType;+ /** Canonical http(s) open target, for Works that live outside the app. */+ url: string | null;+ workId: string;+}+export interface GoalGraphSnapshot {decisions: GoalGraphDecision[];edges: GoalGraphEdge[];diff --git a/src/features/AgentGoals/ProcessControl/Deliverables.test.ts b/src/features/AgentGoals/ProcessControl/Deliverables.test.tsnew file mode 100644index 00000000000..ed6e322682b--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Deliverables.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { openTargetOf } from './Deliverables';+import type { GoalArtifactView } from './goalGraphViewModel';++const artifact = (over: Partial<GoalArtifactView>): GoalArtifactView => ({+ createdAt: new Date(),+ identifier: null,+ nodeId: 'w1',+ resourceId: null,+ title: 'x',+ type: 'external',+ url: null,+ workId: 'wk1',+ workVersionId: 'v1',+ ...over,+});++describe('openTargetOf', () => {+ it('opens a bound document in-app, addressed by its document id', () => {+ expect(+ openTargetOf(artifact({ agentDocumentId: 'a-1', resourceId: 'docs_1', type: 'document' })),+ ).toEqual({ kind: 'document' });+ });++ it('opens a file and an external resource at their canonical url', () => {+ expect(openTargetOf(artifact({ type: 'file', url: 'https://cdn.example.com/a.pdf' }))).toEqual({+ kind: 'external',+ url: 'https://cdn.example.com/a.pdf',+ });+ expect(openTargetOf(artifact({ url: 'http://example.com/1' }))).toEqual({+ kind: 'external',+ url: 'http://example.com/1',+ });+ });++ it.each(['javascript:alert(1)', 'data:text/html,<script>', 'file:///etc/passwd', 'notaurl'])(+ 'refuses %s as a destination',+ (url) => {+ // On desktop `window.open` hands straight to `shell.openExternal`, so a+ // stored non-http(s) value must never become a clickable row.+ expect(openTargetOf(artifact({ url }))).toBeUndefined();+ },+ );++ it('has no destination when the artifact resolves to nothing', () => {+ // These rows must not render a pointer cursor, hover or a focusable button.+ expect(openTargetOf(artifact({ type: 'external', url: null }))).toBeUndefined();+ expect(openTargetOf(artifact({ type: 'file', url: null }))).toBeUndefined();+ expect(openTargetOf(artifact({ resourceId: null, type: 'document' }))).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/Deliverables.tsx b/src/features/AgentGoals/ProcessControl/Deliverables.tsxnew file mode 100644index 00000000000..7b6c30e3082--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Deliverables.tsx@@ -0,0 +1,188 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ExternalLink, FileDown, FileText, Link2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { isSafeExternalUrl } from '@/features/Work/descriptors';+import { useActivityTime } from '@/hooks/useActivityTime';+import { useChatStore } from '@/store/chat';++import type { GoalArtifactView, GoalGraphView } from './goalGraphViewModel';+import { KindDot } from './shared';++/**+ * What the goal produced, as things you can open.+ *+ * Findings say what the goal now believes; this says what came out of it. They+ * are deliberately separate rows: a finding is the synthesized prose, the+ * deliverable is the artifact that prose is about, and until now the artifact+ * survived only as a URL buried inside that prose.+ *+ * Only artifacts the run persisted into the product appear. Anything a task+ * left on a local path is invisible here by construction — which is what the+ * empty state says, and what the dispatched task contract asks for up front.+ *+ * Goal-level rather than per-task, because "show me the report" is a question+ * about the goal — no single task node can answer it.+ *+ * Opening one keeps you on the goal: the surrounding page already drills into a+ * node or a task run through the side Portal, and a deliverable is the same+ * kind of look. Navigating away would cost the reader the goal they were+ * reading. Only a resource that genuinely lives outside the product leaves.+ */++const styles = createStaticStyles(({ css }) => ({+ producer: css`+ flex: none;+ justify-content: flex-end;+ max-width: 40%;+ `,+ /**+ * A fixed slot for the timestamp. Without it the attribution column ends+ * wherever the relative time happens to start, so a list mixing "几秒前" with+ * "8 小时前" loses the very alignment this row is built for.+ */+ time: css`+ flex: none;+ min-width: 60px;+ text-align: end;+ `,+ row: css`+ width: 100%;+ padding-block: 8px;+ padding-inline: 8px;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ text-align: start;++ background: none;+ `,+ rowOpenable: css`+ cursor: pointer;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+}));++/**+ * Where a row actually goes, or `undefined` when it goes nowhere: an external+ * Work registered without a url, a file version missing its `fileUrl`, a+ * document whose binding never resolved. Such a row must not look clickable,+ * and a url is only a destination once it is proven http(s) — a stored value+ * can carry `javascript:` / `data:` / a custom scheme, and on desktop+ * `window.open` hands straight to `shell.openExternal`.+ */+export const openTargetOf = (artifact: GoalArtifactView) => {+ if (artifact.type === 'document' && artifact.resourceId) return { kind: 'document' } as const;+ if (isSafeExternalUrl(artifact.url)) return { kind: 'external', url: artifact.url } as const;+ return undefined;+};++const DeliverableRow = memo<{+ artifact: GoalArtifactView;+ onOpen: (artifact: GoalArtifactView) => void;+ producerTitle?: string;+}>(({ artifact, onOpen, producerTitle }) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(artifact.createdAt);+ // A document opens inside the app; a generated file downloads; an external+ // resource leaves for its own site.+ const icon =+ artifact.type === 'document' ? FileText : artifact.type === 'file' ? FileDown : ExternalLink;++ const openable = !!openTargetOf(artifact);++ return (+ <Flexbox+ horizontal+ align={'center'}+ as={openable ? 'button' : 'div'}+ className={cx(styles.row, openable && styles.rowOpenable)}+ gap={8}+ // A real button carries focus, Enter/Space and the right semantics for+ // free; a row with nowhere to go stays inert rather than faking an+ // affordance it cannot honour.+ {...(openable ? { onClick: () => onOpen(artifact), type: 'button' as const } : {})}+ >+ <Icon color={cssVar.colorTextQuaternary} icon={icon} size={14} />+ {/* The title takes the slack so the attribution and the timestamp form+ right-aligned columns; letting the title size itself left every row's+ attribution starting at a different x. */}+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>+ {artifact.title || artifact.identifier || t('goalProcess.deliverables.untitled')}+ </Text>+ {!!producerTitle && (+ <Flexbox horizontal align={'center'} className={styles.producer} gap={6}>+ <KindDot kind={'task'} />+ <Text ellipsis fontSize={12} type={'secondary'}>+ {t('goalProcess.deliverables.from', { title: producerTitle })}+ </Text>+ </Flexbox>+ )}+ <Text className={styles.time} fontSize={12} title={title} type={'secondary'}>+ {text}+ </Text>+ </Flexbox>+ );+});++DeliverableRow.displayName = 'GoalDeliverableRow';++const Deliverables = memo<{ graph: GoalGraphView }>(({ graph }) => {+ const { t } = useTranslation('chat');+ const openDocument = useChatStore((s) => s.openDocument);++ const open = (artifact: GoalArtifactView) => {+ const target = openTargetOf(artifact);+ if (!target) return;+ // `openDocument` takes the DOCUMENT id, not the agent-document binding id:+ // `agentDocumentId` only establishes that a binding exists.+ if (target.kind === 'document') {+ openDocument(artifact.resourceId!, artifact.agentDocumentId);+ return;+ }+ // A generated file and an external resource both leave for their canonical+ // target. The file-preview Portal is not a substitute: it resolves a+ // knowledge-base item, so an ordinary exported file loads forever in it.+ window.open(target.url, '_blank', 'noopener,noreferrer');+ };++ if (graph.artifacts.length === 0)+ return (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorTextQuaternary} icon={Link2} size={14} />+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.deliverables.empty')}+ </Text>+ </Flexbox>+ );++ return (+ <Flexbox gap={0}>+ {graph.artifacts.map((artifact) => (+ <DeliverableRow+ artifact={artifact}+ key={artifact.workVersionId}+ producerTitle={graph.byId[artifact.nodeId]?.node.title}+ onOpen={open}+ />+ ))}+ </Flexbox>+ );+});++Deliverables.displayName = 'GoalDeliverables';++export default Deliverables;diff --git a/src/features/AgentGoals/ProcessControl/Findings.tsx b/src/features/AgentGoals/ProcessControl/Findings.tsxindex ef787aeea33..67b4616a509 100644--- a/src/features/AgentGoals/ProcessControl/Findings.tsx+++ b/src/features/AgentGoals/ProcessControl/Findings.tsx@@ -31,6 +31,17 @@ const styles = createStaticStyles(({ css }) => ({padding-block: 0 10px;padding-inline: 30px 8px;`,+ source: css`+ flex: none;+ max-width: 40%;+ text-align: end;+ `,+ /** Matches the deliverables list, so both sections share one column edge. */+ time: css`+ flex: none;+ min-width: 60px;+ text-align: end;+ `,row: css`cursor: pointer;padding-block: 8px;@@ -65,22 +76,21 @@ const FindingRow = memo<{ onSelect: (nodeId: string) => void; view: GoalNodeViewsize={14}/><KindDot kind={'finding'} />- <Text ellipsis style={{ flexShrink: 1, minWidth: 0 }} weight={500}>+ {/* The title takes the slack so the attribution and the timestamp+ line up as columns, matching the deliverables list directly+ above — otherwise the two adjacent sections read as different+ layouts of the same row. */}+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>{view.node.title}</Text>- <Text ellipsis fontSize={12} style={{ flexShrink: 1, minWidth: 0 }} type={'secondary'}>+ <Text ellipsis className={styles.source} fontSize={12} type={'secondary'}>{answered? t('goalProcess.findings.answers', { title: answered.title }): view.producedBy? t('goalProcess.findings.from', { title: view.producedBy.title }): ''}</Text>- <Text- fontSize={12}- style={{ flex: 'none', marginInlineStart: 'auto' }}- title={title}- type={'secondary'}- >+ <Text className={styles.time} fontSize={12} title={title} type={'secondary'}>{text}</Text></Flexbox>diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsxindex 0d779f17c6b..030f1866245 100644--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx@@ -332,13 +332,13 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {{attempts}</span></Tooltip>- {view.artifactCount > 0 && (+ {view.artifacts.length > 0 && (<Tooltip- title={t('goalProcess.node.artifactsTooltip', { count: view.artifactCount })}+ title={t('goalProcess.node.artifactsTooltip', { count: view.artifacts.length })}><span className={styles.metric}><Icon icon={FileBox} size={13} />- {view.artifactCount}+ {view.artifacts.length}</span></Tooltip>)}diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.tsindex 05e865430d4..9aafc331b9d 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts@@ -300,18 +300,156 @@ describe('buildGoalGraphView', () => {expect(view.advanceable).toBe(1);});- it('counts registered work versions per node', () => {+ it("names a node's deliverables newest first, and rolls them up for the goal", () => {const view = buildGoalGraphView(snapshot({nodes: [node('w1')],workVersions: [- { createdAt: at(5), id: 'l1', nodeId: 'w1', relation: 'produced', workVersionId: 'v1' },+ {+ createdAt: at(5),+ id: 'l1',+ nodeId: 'w1',+ relation: 'produced',+ work: {+ agentDocumentId: 'docs_1',+ identifier: null,+ resourceId: null,+ status: null,+ title: 'Report',+ type: 'document',+ url: null,+ workId: 'wk1',+ },+ workVersionId: 'v1',+ },+ {+ createdAt: at(9),+ id: 'l2',+ nodeId: 'w1',+ relation: 'produced',+ work: {+ identifier: 'ENG-1',+ resourceId: 'lobehub/lobehub#1',+ status: 'open',+ title: 'Issue',+ type: 'external',+ url: 'https://example.com/1',+ workId: 'wk2',+ },+ workVersionId: 'v2',+ },+ ],+ }),+ NOW,+ );++ expect(view.byId.w1.artifacts.map((a) => a.title)).toEqual(['Issue', 'Report']);+ expect(view.artifacts.map((a) => a.workId)).toEqual(['wk2', 'wk1']);+ });++ it('addresses a document deliverable by its document id, not the binding id', () => {+ // The document route resolves the DOCUMENT id. Carrying only+ // `agentDocumentId` — the agent-document binding row — sent the user to the+ // documents index instead of the document they asked for.+ const view = buildGoalGraphView(+ snapshot({+ nodes: [node('w1')],+ workVersions: [+ {+ createdAt: at(5),+ id: 'l1',+ nodeId: 'w1',+ relation: 'produced',+ work: {+ agentDocumentId: 'a719df25-40c8-4b1c-a24d-6d38cedef82b',+ identifier: null,+ resourceId: 'docs_NRoMGzwytmhHCLSt',+ status: null,+ title: 'Issue pain-point analysis report',+ type: 'document',+ url: null,+ workId: 'wk1',+ },+ workVersionId: 'v1',+ },+ ],+ }),+ NOW,+ );++ expect(view.artifacts[0]).toMatchObject({+ agentDocumentId: 'a719df25-40c8-4b1c-a24d-6d38cedef82b',+ resourceId: 'docs_NRoMGzwytmhHCLSt',+ });+ });++ it('opens a generated file at the url its version metadata carries', () => {+ const view = buildGoalGraphView(+ snapshot({+ nodes: [node('w1')],+ workVersions: [+ {+ createdAt: at(5),+ id: 'l1',+ nodeId: 'w1',+ relation: 'produced',+ // A file Work keeps its target in the version metadata, so the+ // `url` column is null and the row would otherwise not open.+ work: {+ fileUrl: 'https://cdn.example.com/deck.pptx',+ identifier: null,+ resourceId: null,+ status: null,+ title: 'deck.pptx',+ type: 'file',+ url: null,+ workId: 'wk1',+ },+ workVersionId: 'v1',+ },+ ],+ }),+ NOW,+ );++ expect(view.artifacts).toMatchObject([+ { title: 'deck.pptx', type: 'file', url: 'https://cdn.example.com/deck.pptx' },+ ]);+ });++ it('leaves the responsible task Work and unresolvable links out of the deliverables', () => {+ const view = buildGoalGraphView(+ snapshot({+ nodes: [node('w1')],+ workVersions: [+ {+ createdAt: at(5),+ id: 'l1',+ nodeId: 'w1',+ relation: 'produced',+ // The execution container the coordinator links on dispatch — it+ // would otherwise head every task's list with the task itself.+ work: {+ identifier: 'T-1',+ resourceId: 'task_1',+ status: 'completed',+ title: 'Build the thing',+ type: 'task',+ url: null,+ workId: 'wk1',+ },+ workVersionId: 'v1',+ },+ // Nothing to name the link with — the version row is gone, or the+ // Work belongs to another member and the read-time ownership guard+ // refused to hydrate it. Either way the link still counts.{ createdAt: at(9), id: 'l2', nodeId: 'w1', relation: 'produced', workVersionId: 'v2' },],}),NOW,);- expect(view.byId.w1.artifactCount).toBe(2);+ expect(view.byId.w1.artifacts).toEqual([]);+ expect(view.artifacts).toEqual([]);});});diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.tsindex 670fef1a403..0d0451b6a25 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts@@ -5,14 +5,15 @@ import type {GoalGraphNode,GoalGraphSnapshot,GoalItem,+ WorkType,} from '@lobechat/types';/*** Read model for the Goal process-control surface.** Everything here is derived from one `goal.graph` snapshot — the server has no- * frontier projection, no per-node attempt/cost roll-up and no artifact- * hydration, so the client reproduces the coordinator's own selection rule+ * frontier projection and no per-node attempt/cost roll-up, so the client+ * reproduces the coordinator's own selection rule* (`GoalService.tick`) and reads the append-only `goal_events` trail for the* per-node attempt ledger. Anything that cannot be derived honestly is left* `undefined` and the UI omits it rather than inventing a value.@@ -39,11 +40,35 @@ export interface GoalAttempt {taskId?: string;}+/**+ * One deliverable a task produced, named rather than counted. `link` keeps the+ * relation so a future `input` / `supports` link can render differently without+ * another shape.+ */+export interface GoalArtifactView {+ /**+ * Set when a document deliverable is bound to an agent, which is what makes+ * it openable in-app. The link itself addresses {@link resourceId}.+ */+ agentDocumentId?: string;+ createdAt: Date;+ identifier: string | null;+ /** The task node that produced it — the goal-level list has no other owner. */+ nodeId: string;+ /** Canonical resource identity; the document id an in-app link addresses. */+ resourceId: string | null;+ title: string | null;+ type: WorkType;+ url: string | null;+ workId: string;+ workVersionId: string;+}+export interface GoalNodeView {/** Problems this finding was linked to with a `supports` edge. */answers: GoalGraphNode[];- /** Registered work versions. Names/urls need a server join that does not exist yet. */- artifactCount: number;+ /** Deliverables this node produced, newest first. */+ artifacts: GoalArtifactView[];attempts: GoalAttempt[];/** Unresolved `depends_on` targets — why this node cannot start. */blockers: GoalGraphNode[];@@ -82,6 +107,11 @@ export interface FrontierItem {export interface GoalGraphView {/** Every node the frontier can move now, excluding the fading done rows. */advanceable: number;+ /**+ * Every deliverable the goal has produced, newest first — the goal-level+ * answer to "what came out of this", which no single node can give.+ */+ artifacts: GoalArtifactView[];blocked: GoalNodeView[];byId: Record<string, GoalNodeView>;decisions: GoalGraphDecision[];@@ -207,9 +237,29 @@ export const buildGoalGraphView = (supportsByFinding.set(source.id, [...(supportsByFinding.get(source.id) ?? []), target]);}- const artifactCounts = new Map<string, number>();- for (const link of workVersions)- artifactCounts.set(link.nodeId, (artifactCounts.get(link.nodeId) ?? 0) + 1);+ // Only Works that were named by the read-time join can be shown, and the+ // responsible task's own `task` Work is execution bookkeeping rather than a+ // deliverable — it would otherwise head every task's list with itself.+ const artifactsByNode = new Map<string, GoalArtifactView[]>();+ for (const link of workVersions) {+ if (!link.work || link.work.type === 'task') continue;+ const artifact: GoalArtifactView = {+ createdAt: link.createdAt,+ identifier: link.work.identifier,+ nodeId: link.nodeId,+ resourceId: link.work.resourceId,+ title: link.work.title,+ type: link.work.type,+ // A file Work carries its target in the version metadata, not `url`.+ url: link.work.url ?? link.work.fileUrl ?? null,+ workId: link.work.workId,+ workVersionId: link.workVersionId,+ ...(link.work.agentDocumentId ? { agentDocumentId: link.work.agentDocumentId } : {}),+ };+ artifactsByNode.set(link.nodeId, [...(artifactsByNode.get(link.nodeId) ?? []), artifact]);+ }+ for (const list of artifactsByNode.values())+ list.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());const decisionsByNode = new Map<string, GoalGraphDecision[]>();for (const decision of decisions)@@ -234,7 +284,7 @@ export const buildGoalGraphView = ();return {answers: supportsByFinding.get(node.id) ?? [],- artifactCount: artifactCounts.get(node.id) ?? 0,+ artifacts: artifactsByNode.get(node.id) ?? [],attempts,blockers: (dependsOn.get(node.id) ?? []).map((id) => nodeById.get(id))@@ -298,6 +348,9 @@ export const buildGoalGraphView = (return {advanceable: frontier.length,+ artifacts: [...artifactsByNode.values()]+ .flat()+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()),blocked,byId,decisions,diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsxindex cd1afaac2f2..ff2d3d9b2d9 100644--- a/src/features/AgentGoals/ProcessControl/index.tsx+++ b/src/features/AgentGoals/ProcessControl/index.tsx@@ -13,6 +13,7 @@ import { goalSelectors, useGoalStore } from '@/store/goal';import GoalAcceptanceCriteria from '../GoalAcceptanceCriteria';import Activity from './Activity';+import Deliverables from './Deliverables';import Findings from './Findings';import Frontier, { type FrontierActions } from './Frontier';import { buildGoalGraphView } from './goalGraphViewModel';@@ -126,7 +127,7 @@ const ProcessControl = memo<ProcessControlProps>(onSelect={select}/>- <Accordion defaultExpandedKeys={['findings', 'activity']} gap={0}>+ <Accordion defaultExpandedKeys={['deliverables', 'findings', 'activity']} gap={0}>{/* The structured acceptance standard the terminal goal acceptance isgated on. Collapsed by default — reference material, like the taskdetail's 交付验收 section. Prose-only legacy goals have none. */}@@ -152,6 +153,26 @@ const ProcessControl = memo<ProcessControlProps>(</Flexbox></AccordionItem>)}+ {/* Between the standard and the conclusions on purpose: 验收标准 says+ what counts as done, 交付物 what was produced, 结论 what the goal now+ believes about it. Findings routinely cite these artifacts. */}+ <AccordionItem+ itemKey={'deliverables'}+ paddingBlock={6}+ paddingInline={0}+ title={+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalProcess.deliverables.title')}+ </Text>+ {graph.artifacts.length > 0 && <Tag size={'small'}>{graph.artifacts.length}</Tag>}+ </Flexbox>+ }+ >+ <Flexbox className={styles.section}>+ <Deliverables graph={graph} />+ </Flexbox>+ </AccordionItem><AccordionItemitemKey={'findings'}paddingBlock={6}