Skip to content

🤯 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.

🐛 fix(goal): produce detour notes reliably under the default wrap-up config (when the skeleton has candidate detours) (#20300)

Arvin Xu526b91d82840
diff --git a/apps/server/src/services/goal/report.test.ts b/apps/server/src/services/goal/report.test.ts
index 8b6560eba5d..8a2f4f9f87d 100644
--- a/apps/server/src/services/goal/report.test.ts
+++ b/apps/server/src/services/goal/report.test.ts
@@ -7,13 +7,17 @@ import type {
GoalReportMetadata,
TaskItem,
} from '@lobechat/types';
+import { GoalReportMetadataSchema } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { decideNextMove, selectFrontier } from './decideNextMove';
import {
+ alignGoalReportStoryline,
+ backfillGoalReportDetours,
buildGoalReportInstruction,
buildGoalReportSkeleton,
decideGoalReport,
+ reconcileGoalReport,
validateGoalReport,
} from './report';
@@ -390,6 +394,43 @@ describe('buildGoalReportSkeleton', () => {
expect(text).toContain('headline, deliverableWorkId, chapters, mainline, nextSteps');
});
+ /**
+ * Regression: with the default wrap-up model the stored report carried zero
+ * detours even though the skeleton listed two. The instruction read as an
+ * invitation ("decide which detours are worth telling"), so a weak model
+ * dropped them all and the promised detour chapter never appeared. When the
+ * skeleton found candidate detours, the contract must make one mandatory.
+ */
+ it('requires at least one detour when the skeleton offers candidate detours', () => {
+ const text = buildGoalReportInstruction(snapshot, 'accepted', {
+ kind: 'tool',
+ toolName: 'lobe-goal-report.submitGoalReport',
+ });
+ expect(text).toContain('2 candidate detour');
+ expect(text).toContain('at least one MUST appear in your report');
+ expect(text).toContain('at least ONE of these must be told as a detour');
+ });
+
+ it('does not demand a detour when the skeleton found none', () => {
+ const noDetours = withReportDispatched(
+ graph({
+ edges: [edge('t1', 'depends_on', 'problem'), edge('acc', 'depends_on', 't1')],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { status: 'resolved' }),
+ acceptance({ status: 'resolved' }),
+ node('report', { title: GOAL_REPORT_TASK_TITLE }),
+ ],
+ }),
+ );
+ const text = buildGoalReportInstruction(noDetours, 'accepted', {
+ kind: 'tool',
+ toolName: 'lobe-goal-report.submitGoalReport',
+ });
+ expect(text).not.toContain('MUST appear in your report');
+ expect(text).toContain('- none');
+ });
+
/**
* Regression: a heterogeneous wrap-up agent (Claude Code, Codex) never
* receives server tools, so an instruction that only named the report tool
@@ -443,6 +484,63 @@ describe('buildGoalReportSkeleton', () => {
).toEqual([]);
});
+ /**
+ * Regression: the default wrap-up model submitted charts-only metadata with
+ * `detours: []` for a Goal whose skeleton offered dead ends, and the store
+ * accepted it — the report on the results page had no detour chapter. The
+ * contract must reject a report that drops every candidate detour, so the
+ * agent fixes it instead of the user losing the promised detours.
+ */
+ it('rejects a report that drops every candidate detour the skeleton offered', () => {
+ const dropped = {
+ ...valid,
+ chapters: valid.chapters.map((chapter) => ({ ...chapter, detours: [] })),
+ };
+ expect(validateGoalReport(snapshot, dropped)).toEqual([
+ 'chapters: the skeleton offers 2 candidate detour(s) (t1b, t0); the report must tell at least one detour, with its reason and lesson',
+ ]);
+
+ // Telling even one candidate detour satisfies the contract.
+ expect(
+ validateGoalReport(snapshot, {
+ ...valid,
+ chapters: [
+ { ...valid.chapters[0], detours: [valid.chapters[0].detours[0]] },
+ valid.chapters[1],
+ ],
+ }),
+ ).toEqual([]);
+ });
+
+ it('does not require a detour when the skeleton offered none', () => {
+ const noDetours = graph({
+ edges: [edge('t1', 'depends_on', 'problem'), edge('acc', 'depends_on', 't1')],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { status: 'resolved' }),
+ acceptance({ status: 'resolved' }),
+ ],
+ });
+ expect(
+ validateGoalReport(noDetours, {
+ chapters: [
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'N',
+ nodeIds: ['t1', 'acc'],
+ title: 'C1',
+ workVersionIds: [],
+ },
+ ],
+ graphCursor: 'evt_any',
+ headline: 'H',
+ mainline: { edgeIds: [], nodeIds: ['t1', 'acc'] },
+ nextSteps: [],
+ }),
+ ).toEqual([]);
+ });
+
it('rejects foreign ids, unresolved main-path nodes and fake detours', () => {
const errors = validateGoalReport(
snapshot,
@@ -549,4 +647,278 @@ describe('buildGoalReportSkeleton', () => {
});
});
});
+
+ describe('backfillGoalReportDetours', () => {
+ const detourless: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [],
+ findingIds: ['f1', 'f2'],
+ narrative: 'N',
+ nodeIds: ['t1', 't2'],
+ title: 'C1',
+ workVersionIds: ['wv_doc'],
+ },
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'N',
+ nodeIds: ['acc'],
+ title: 'C2',
+ workVersionIds: [],
+ },
+ ],
+ deliverableWorkId: 'work_doc',
+ graphCursor: 'evt_new',
+ headline: 'H',
+ mainline: {
+ edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
+ nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
+ },
+ nextSteps: [{ nodeIds: ['t2'], reason: 'R', title: 'Next' }],
+ };
+
+ /**
+ * Regression: the default model narrated the whole path and submitted every
+ * chapter with an empty detours array — the original bug. Rejecting the
+ * whole report for that would leave the user with no storyline at all, so
+ * the store fills the detours from the candidates the skeleton found.
+ */
+ it('fills the candidates the skeleton found when the report tells none', () => {
+ const filled = backfillGoalReportDetours(snapshot, detourless);
+ expect(filled.chapters.flatMap((c) => c.detours.flatMap((d) => d.nodeIds))).toEqual([
+ 't1b',
+ 't0',
+ ]);
+ expect(filled.chapters[0].detours.map((detour) => detour.kind)).toEqual([
+ 'superseded',
+ 'dead_end',
+ ]);
+ // The narrative the agent wrote (chapter nodeIds) is untouched.
+ expect(filled.chapters.map((c) => c.nodeIds)).toEqual(
+ detourless.chapters.map((c) => c.nodeIds),
+ );
+ // The filled report is now a valid submission.
+ expect(validateGoalReport(snapshot, filled)).toEqual([]);
+ });
+
+ /**
+ * Regression: `chapters[].detours` is capped by `GoalReportChapterSchema`.
+ * A Goal with more dead ends than one chapter may hold used to overflow that
+ * cap, and the stored version then failed the schema the next time it was
+ * read back — the report was persisted but never rendered, so the storyline
+ * disappeared even though the detours had been recovered.
+ */
+ it('keeps every chapter within the schema cap when the skeleton found more candidates', () => {
+ const deadEnds = Array.from({ length: 25 }, (_, index) => `dead_${index}`);
+ // Every dead end forks from t1, so they all prefer the chapter that
+ // narrates t1 — far more than that one chapter is allowed to tell.
+ const crowded = withReportDispatched(
+ graph({
+ edges: [
+ edge('t2', 'depends_on', 't1'),
+ edge('acc', 'depends_on', 't2'),
+ ...deadEnds.map((id) => edge(id, 'depends_on', 't1')),
+ ],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { createdAt: new Date(1), status: 'resolved' }),
+ node('t2', { createdAt: new Date(4), status: 'resolved' }),
+ acceptance({ createdAt: new Date(5), status: 'resolved' }),
+ node('report', { title: GOAL_REPORT_TASK_TITLE }),
+ ...deadEnds.map((id, index) =>
+ node(id, { createdAt: new Date(10 + index), status: 'retired' }),
+ ),
+ ],
+ }),
+ );
+
+ const filled = reconcileGoalReport(crowded, detourless);
+ const perChapter = filled.chapters.map((chapter) => chapter.detours.length);
+
+ // Every recovered detour is told, and no chapter spills past the cap.
+ expect(perChapter.reduce((total, count) => total + count, 0)).toBe(25);
+ expect(Math.max(...perChapter)).toBeLessThanOrEqual(20);
+ // The version the store would persist is one it can read back.
+ expect(GoalReportMetadataSchema.safeParse(filled).success).toBe(true);
+ });
+
+ /**
+ * Regression: a retired node's description may run to 8,000 characters (and
+ * a seeded title past 200), but a detour's reason / lesson / title are capped
+ * by `GoalReportDetourSchema`. Copying them verbatim made the store's second
+ * parse reject the whole otherwise-valid report, so the recovery produced no
+ * storyline at all.
+ */
+ it('clamps graph-derived detour text to the report schema limits', () => {
+ const verbose = withReportDispatched(
+ graph({
+ edges: [
+ edge('t2', 'depends_on', 't1'),
+ edge('acc', 'depends_on', 't2'),
+ edge('dead', 'depends_on', 't1'),
+ ],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { createdAt: new Date(1), status: 'resolved' }),
+ node('t2', { createdAt: new Date(4), status: 'resolved' }),
+ acceptance({ createdAt: new Date(5), status: 'resolved' }),
+ node('report', { title: GOAL_REPORT_TASK_TITLE }),
+ node('dead', {
+ createdAt: new Date(10),
+ description: 'why it failed. '.repeat(600),
+ status: 'retired',
+ title: 'A very long dead-end title '.repeat(20),
+ }),
+ ],
+ }),
+ );
+
+ const filled = reconcileGoalReport(verbose, detourless);
+ const [detour] = filled.chapters.flatMap((chapter) => chapter.detours);
+
+ expect(detour.nodeIds).toEqual(['dead']);
+ expect(detour.reason.length).toBeLessThanOrEqual(2000);
+ expect(detour.lesson.length).toBeLessThanOrEqual(2000);
+ expect(detour.title.length).toBeLessThanOrEqual(200);
+ expect(detour.reason.endsWith('…')).toBe(true);
+ // The version the store would persist is one it can read back.
+ expect(GoalReportMetadataSchema.safeParse(filled).success).toBe(true);
+ });
+
+ it('leaves a report that already tells a detour untouched', () => {
+ const told: GoalReportMetadata = {
+ ...detourless,
+ chapters: [
+ {
+ ...detourless.chapters[0],
+ detours: [{ kind: 'dead_end', lesson: 'L', nodeIds: ['t0'], reason: 'R', title: 'T' }],
+ },
+ detourless.chapters[1],
+ ],
+ };
+ expect(backfillGoalReportDetours(snapshot, told)).toBe(told);
+ });
+
+ it('does nothing when the skeleton found no detour', () => {
+ const noDetours = graph({
+ edges: [edge('t1', 'depends_on', 'problem'), edge('acc', 'depends_on', 't1')],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { status: 'resolved' }),
+ acceptance({ status: 'resolved' }),
+ ],
+ });
+ expect(backfillGoalReportDetours(noDetours, detourless)).toBe(detourless);
+ });
+
+ /**
+ * Regression: the default model opened a chapter for a detour and marked the
+ * acceptance node on the mainline without narrating it, so validation
+ * rejected the whole report. The storyline is reconciled with the graph, and
+ * the promised detours are still filled.
+ */
+ it('aligns a detour chapter back to a detour and drops a mainline node no chapter tells', () => {
+ const messy: GoalReportMetadata = {
+ ...detourless,
+ chapters: [
+ detourless.chapters[0],
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'A detour told as its own chapter.',
+ nodeIds: ['t0'],
+ title: 'Detour chapter',
+ workVersionIds: [],
+ },
+ ],
+ mainline: {
+ edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
+ nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
+ },
+ };
+
+ const aligned = alignGoalReportStoryline(snapshot, messy);
+ expect(aligned.chapters.map((c) => c.nodeIds)).toEqual([['t1', 't2'], []]);
+ expect(aligned.mainline!.nodeIds).toEqual(['problem', 't1', 't2', 'f2']);
+ expect(aligned.mainline!.edgeIds).toEqual(['t2-depends_on-t1', 't2-produces-f2']);
+
+ const reconciled = reconcileGoalReport(snapshot, messy);
+ expect(
+ reconciled.chapters.flatMap((c) => c.detours.flatMap((d) => d.nodeIds)).sort(),
+ ).toEqual(['t0', 't1b']);
+ expect(validateGoalReport(snapshot, reconciled)).toEqual([]);
+ });
+
+ it('leaves a fully consistent report unchanged', () => {
+ const detached: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [
+ { kind: 'superseded', lesson: 'L', nodeIds: ['t1b'], reason: 'R', title: 'Old' },
+ ],
+ findingIds: ['f1', 'f2'],
+ narrative: 'N',
+ nodeIds: ['t1', 't2'],
+ title: 'C1',
+ workVersionIds: ['wv_doc'],
+ },
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'N',
+ nodeIds: ['acc'],
+ title: 'C2',
+ workVersionIds: [],
+ },
+ ],
+ deliverableWorkId: 'work_doc',
+ graphCursor: 'evt_new',
+ headline: 'H',
+ mainline: {
+ edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],
+ nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],
+ },
+ nextSteps: [],
+ };
+ expect(alignGoalReportStoryline(snapshot, detached)).toEqual(detached);
+ expect(validateGoalReport(snapshot, detached)).toEqual([]);
+ });
+
+ /**
+ * Regression: reconciliation must never empty the mainline.
+ * `GoalReportMetadataSchema` requires at least one mainline node, while the
+ * filter that keeps the mainline to the path the chapters tell drops every
+ * resolved task a chapter never names. A weak model that marks a mainline
+ * but gives no chapter a nodeId therefore produced `mainline.nodeIds: []`,
+ * which was persisted and then failed the schema on the next read — the
+ * recovered storyline disappeared instead of surfacing an actionable error.
+ */
+ it('never empties the mainline when no chapter tells a node', () => {
+ const unreconciled: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [
+ { kind: 'dead_end', lesson: 'L', nodeIds: ['t0'], reason: 'R', title: 'Dead' },
+ ],
+ findingIds: [],
+ narrative: 'The whole path, told with no chapter nodeIds.',
+ nodeIds: [],
+ title: 'C1',
+ workVersionIds: [],
+ },
+ ],
+ graphCursor: 'evt_new',
+ headline: 'H',
+ mainline: { edgeIds: ['t2-depends_on-t1'], nodeIds: ['t1', 't2'] },
+ nextSteps: [],
+ };
+ expect(GoalReportMetadataSchema.safeParse(unreconciled).success).toBe(true);
+
+ const reconciled = reconcileGoalReport(snapshot, unreconciled);
+
+ expect(reconciled.mainline!.nodeIds.length).toBeGreaterThan(0);
+ expect(GoalReportMetadataSchema.safeParse(reconciled).success).toBe(true);
+ });
+ });
});
diff --git a/apps/server/src/services/goal/report.ts b/apps/server/src/services/goal/report.ts
index f05cc3b6ca7..57c7d61ab2d 100644
--- a/apps/server/src/services/goal/report.ts
+++ b/apps/server/src/services/goal/report.ts
@@ -6,6 +6,11 @@ import type {
GoalReportMetadata,
GoalReportTrigger,
} from '@lobechat/types';
+import {
+ GOAL_REPORT_MAX_DETOUR_TEXT_LENGTH,
+ GOAL_REPORT_MAX_DETOUR_TITLE_LENGTH,
+ GOAL_REPORT_MAX_DETOURS_PER_CHAPTER,
+} from '@lobechat/types';
/**
* The wrap-up branch of the Goal coordinator: once the Goal-level acceptance
@@ -412,7 +417,7 @@ export const buildGoalReportInstruction = (
.join('\n'),
skeleton.deliverable
? `Final deliverable: Work ${skeleton.deliverable.workId} (${skeleton.deliverable.type}) "${skeleton.deliverable.title ?? ''}", version ${skeleton.deliverable.workVersionId}`
- : 'Final deliverable: none linked to the graph.',
+ : 'Final deliverable: none linked to the graph — when reporting, omit deliverableWorkId entirely.',
[
'Candidate main path (traced back from the final deliverable along produces / depends_on / derived_from, oldest first):',
...skeleton.mainPath.map(
@@ -421,7 +426,9 @@ export const buildGoalReportInstruction = (
),
].join('\n'),
[
- 'Candidate detours (rejected / retired / superseded), under the fork they left from:',
+ skeleton.detours.length
+ ? `Candidate detours (rejected / retired / superseded), under the fork they left from — at least ONE of these must be told as a detour:`
+ : 'Candidate detours (rejected / retired / superseded), under the fork they left from:',
...(skeleton.detours.length
? skeleton.detours.map(
(node) => `- ${line(node)} · ${node.signal} · fork: ${node.forkNodeId ?? 'unknown'}`,
@@ -441,11 +448,13 @@ export const buildGoalReportInstruction = (
submission.kind === 'cli'
? `1. Inspect the Goal, its findings and deliverables as needed (\`lh goal show ${graph.goal.id} --json\`). The skeleton is a starting point, not the answer.`
: '1. Inspect the Goal, its findings and deliverables as needed. The skeleton is a starting point, not the answer.',
- '2. Split the main path into a few chapters. Give each a title and a narrative of what was tried, what was learned and what it produced; reference its nodeIds (resolved main-path nodes only), findingIds and workVersionIds.',
- '3. Decide which detours are worth telling. For each one attach it to the chapter it forked from, with kind (dead_end | superseded | retry), the reason it was abandoned and the lesson it taught. Leave out detours that teach nothing.',
+ '2. Split the main path into a few chapters. Give each a title and a narrative of what was tried, what was learned and what it produced; list in its nodeIds the mainline nodes it tells (resolved main-path nodes only), plus findingIds and workVersionIds. Every mainline task or experiment node, including the acceptance node when it is on the mainline, must be told by some chapter.',
+ skeleton.detours.length
+ ? `3. Tell the detours. The skeleton lists ${skeleton.detours.length} candidate detour(s), and at least one MUST appear in your report. Put each detour you tell in the \`detours\` array of the chapter it forked from — a detour entry has title, nodeIds, kind (dead_end | superseded | retry), the reason it was abandoned and the lesson it taught. Add the others that teach something and leave out only those that teach nothing. A report with no detour is incomplete and will be rejected.`
+ : '3. Decide which detours are worth telling. For each one attach it to the chapter it forked from, with kind (dead_end | superseded | retry), the reason it was abandoned and the lesson it taught. Leave out detours that teach nothing.',
'4. Write nextSteps: what remains or should come next, each with a reason.',
- '5. Write a one-sentence headline, and set deliverableWorkId when there is a final deliverable.',
- '6. Mark the mainline: the path that actually led to the result. mainline.nodeIds are the resolved tasks on the correct path (plus, when useful, the resolved root problem and the findings that carried the answer forward); mainline.edgeIds are the edges of this Goal that connect two of those nodes. Detour nodes are never on the mainline. The chapters must tell exactly this path: every chapter nodeId is a mainline node, and every mainline task appears in a chapter.',
+ '5. Write a one-sentence headline. When the Goal produced a final deliverable, set deliverableWorkId to that Work\'s id; when there is no final deliverable, omit deliverableWorkId entirely — do not send an empty string or a placeholder such as "none".',
+ "6. Mark the mainline: the path that actually led to the result. mainline.nodeIds are the resolved tasks on the correct path (plus, when useful, the resolved root problem and the findings that carried the answer forward); mainline.edgeIds are the ids of this Goal's edges that connect two of those nodes — copy the ids from the Candidate mainline list, never the edge kind. Detour nodes are never on the mainline. The chapters must tell exactly this path: every chapter nodeId is a mainline node, and every mainline task or experiment node — including the acceptance node when it is listed — appears in some chapter.",
'7. Do NOT restate acceptance verdicts or user decisions as data; the page reads those from their own records. Narrate around them.',
submission.kind === 'cli'
? `8. Write the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor) as JSON to a file, and the full written report in markdown, built from that same metadata, to another file. Submit both once with \`lh goal report ${graph.goal.id} --metadata-file <json> --content-file <md>\`. If it rejects a reference, fix the file and submit again.`
@@ -456,6 +465,168 @@ export const buildGoalReportInstruction = (
.join('\n\n');
};
+/**
+ * Fit graph-derived text into a report field. Node titles and descriptions are
+ * bounded looser than `GoalReportDetourSchema`, and the store re-parses the
+ * reconciled report: one over-long description copied verbatim would reject the
+ * whole otherwise-valid storyline. Cuts on a code point boundary and marks the
+ * cut with an ellipsis.
+ */
+const clampReportText = (text: string, max: number): string => {
+ const trimmed = text.trim();
+ if (trimmed.length <= max) return trimmed;
+ let cut = trimmed.slice(0, max - 1);
+ // Never leave half of a surrogate pair at the end.
+ if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1);
+ return `${cut.trimEnd()}…`;
+};
+
+/**
+ * The requirement promises the storyline explains the exploration, detours
+ * included, and the skeleton hands the wrap-up agent the dead ends it found.
+ * A weak default model can narrate the whole path and still submit an empty
+ * `detours` array; rejecting the whole report for that leaves the user with no
+ * storyline at all — worse than the bug. So the store fills a report that tells
+ * no detour from the candidates the skeleton already found — the graph's own
+ * record of each dead end — attaching each to the chapter that narrates the
+ * node it forked from.
+ *
+ * Authored detours are never touched: a report that tells any detour is
+ * returned unchanged, and the narrative stays exactly what the agent wrote. The
+ * fill respects the schema's per-chapter cap, so what it recovers is always a
+ * version the store can read back.
+ */
+export const backfillGoalReportDetours = (
+ source: GoalGraphSnapshot,
+ metadata: GoalReportMetadata,
+): GoalReportMetadata => {
+ const candidates = buildGoalReportSkeleton(source).detours;
+ if (candidates.length === 0 || metadata.chapters.length === 0) return metadata;
+
+ const told = new Set(
+ metadata.chapters.flatMap((chapter) => chapter.detours.flatMap((detour) => detour.nodeIds)),
+ );
+ if (candidates.some((candidate) => told.has(candidate.id))) return metadata;
+
+ const nodes = new Map(withoutGoalReport(source).nodes.map((node) => [node.id, node]));
+ const chapterIndexes = metadata.chapters.map((_, index) => index);
+ // The chapter that narrates the node a detour forked from, else the first
+ // chapter that narrates anything. A detour with no home of its own still
+ // belongs to this one report.
+ const preferredChapter = (forkNodeId?: string) => {
+ const exact = forkNodeId
+ ? metadata.chapters.findIndex((chapter) => chapter.nodeIds.includes(forkNodeId))
+ : -1;
+ if (exact >= 0) return exact;
+ const narrated = metadata.chapters.findIndex((chapter) => chapter.nodeIds.length > 0);
+ return narrated >= 0 ? narrated : 0;
+ };
+
+ // `GoalReportChapterSchema` caps a chapter's detours, and the store reads the
+ // persisted version back through that schema: spilling past the cap would
+ // store a version that can never be parsed again, hiding the very storyline
+ // this recovers. So each chapter takes at most its remaining room, and the
+ // overflow moves on to the next chapter that still has some.
+ const room = metadata.chapters.map(
+ (chapter) => GOAL_REPORT_MAX_DETOURS_PER_CHAPTER - chapter.detours.length,
+ );
+ const additions = metadata.chapters.map<GoalReportMetadata['chapters'][number]['detours']>(
+ () => [],
+ );
+
+ for (const candidate of candidates) {
+ const target = [preferredChapter(candidate.forkNodeId), ...chapterIndexes].find(
+ (index) => room[index] > 0,
+ );
+ // Every chapter is at the cap: the storyline keeps what it already tells
+ // rather than growing an unreadable chapter.
+ if (target === undefined) break;
+ room[target] -= 1;
+ // The graph only carries the node's own description; it holds both why the
+ // path was abandoned and what it taught, so it seeds both fields.
+ const detail = clampReportText(
+ nodes.get(candidate.id)?.description?.trim() || candidate.signal,
+ GOAL_REPORT_MAX_DETOUR_TEXT_LENGTH,
+ );
+ additions[target].push({
+ kind: candidate.signal.startsWith('superseded') ? 'superseded' : 'dead_end',
+ lesson: detail,
+ nodeIds: [candidate.id],
+ reason: detail,
+ title: clampReportText(candidate.title, GOAL_REPORT_MAX_DETOUR_TITLE_LENGTH),
+ });
+ }
+ if (additions.every((extra) => extra.length === 0)) return metadata;
+
+ return {
+ ...metadata,
+ chapters: metadata.chapters.map((chapter, index) =>
+ additions[index].length > 0
+ ? { ...chapter, detours: [...chapter.detours, ...additions[index]] }
+ : chapter,
+ ),
+ };
+};
+
+/**
+ * Keep a submitted storyline self-consistent, so a near-miss from the default
+ * model still yields the report the requirement promises instead of nothing:
+ *
+ * - A detour is never a main-path node: a candidate detour the agent listed in
+ * a chapter's own `nodeIds` is pulled out (it belongs in that chapter's
+ * `detours`).
+ * - The highlighted mainline must be the path the chapters tell: a mainline
+ * task/experiment no chapter narrates is dropped, and edges left dangling are
+ * pruned. Findings and the root problem may ride along without a chapter.
+ * - When the agent tells no detour at all but the skeleton found candidates, they
+ * are attached from the graph's own record.
+ *
+ * A fully consistent report is returned unchanged.
+ */
+export const alignGoalReportStoryline = (
+ source: GoalGraphSnapshot,
+ metadata: GoalReportMetadata,
+): GoalReportMetadata => {
+ const graph = withoutGoalReport(source);
+ const byId = new Map(graph.nodes.map((node) => [node.id, node]));
+ const detourIds = new Set(buildGoalReportSkeleton(source).detours.map((detour) => detour.id));
+
+ const chapters = metadata.chapters.map((chapter) => {
+ const nodeIds = chapter.nodeIds.filter((id) => !detourIds.has(id));
+ return nodeIds.length === chapter.nodeIds.length ? chapter : { ...chapter, nodeIds };
+ });
+
+ // A missing mainline is the validator's to report, not ours to invent.
+ if (!metadata.mainline) return { ...metadata, chapters };
+
+ const chaptered = new Set(chapters.flatMap((chapter) => chapter.nodeIds));
+ const narrated = metadata.mainline.nodeIds.filter((id) => {
+ const node = byId.get(id);
+ if (!node || node.status !== 'resolved' || !CHAPTERED_KINDS.has(node.kind)) return true;
+ return chaptered.has(id);
+ });
+ // Never empty the mainline: `GoalReportMetadataSchema` requires at least one node, and an
+ // emptied mainline is persisted, fails the schema on the next read, and takes the whole
+ // recovered storyline down with it. Keeping the agent's own nodes lets the validator ask
+ // for the missing chapters instead of losing the report.
+ const nodeIds = narrated.length > 0 ? narrated : metadata.mainline.nodeIds;
+ const onMainline = new Set(nodeIds);
+ const edgeById = new Map(source.edges.map((edge) => [edge.id, edge]));
+ const edgeIds = metadata.mainline.edgeIds.filter((id) => {
+ const edge = edgeById.get(id);
+ return !edge || (onMainline.has(edge.sourceNodeId) && onMainline.has(edge.targetNodeId));
+ });
+
+ return { ...metadata, chapters, mainline: { ...metadata.mainline, edgeIds, nodeIds } };
+};
+
+/** Reconcile a submitted report with the graph before it is validated. */
+export const reconcileGoalReport = (
+ source: GoalGraphSnapshot,
+ metadata: GoalReportMetadata,
+): GoalReportMetadata =>
+ backfillGoalReportDetours(source, alignGoalReportStoryline(source, metadata));
+
// ---------------------------------------------------------------------------
// Validation of a submitted report
// ---------------------------------------------------------------------------
@@ -478,6 +649,7 @@ export const validateGoalReport = (
graph.workVersions.flatMap((link) => (link.work ? [link.work.workId] : [])),
);
const superseded = supersededBy(graph);
+ const candidateDetours = buildGoalReportSkeleton(source).detours;
const errors: string[] = [];
metadata.chapters.forEach((chapter, index) => {
@@ -511,6 +683,22 @@ export const validateGoalReport = (
});
});
+ // The requirement promises the storyline explains the exploration, detours
+ // included. A weak default model silently drops every detour the skeleton
+ // offered, which the user only notices as a missing chapter — so the contract
+ // makes them observable: when the skeleton found candidate detours, a report
+ // that tells none is incomplete and must be fixed, never stored.
+ const toldDetours = metadata.chapters.reduce(
+ (total, chapter) => total + chapter.detours.length,
+ 0,
+ );
+ if (candidateDetours.length > 0 && toldDetours === 0)
+ errors.push(
+ `chapters: the skeleton offers ${candidateDetours.length} candidate detour(s) (${candidateDetours
+ .map((detour) => detour.id)
+ .join(', ')}); the report must tell at least one detour, with its reason and lesson`,
+ );
+
metadata.nextSteps.forEach((step, index) => {
for (const id of step.nodeIds ?? []) {
if (!byId.has(id))
diff --git a/apps/server/src/services/goal/reportService.test.ts b/apps/server/src/services/goal/reportService.test.ts
index f73b1c3eeba..6ffdf612c4b 100644
--- a/apps/server/src/services/goal/reportService.test.ts
+++ b/apps/server/src/services/goal/reportService.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment node
import { GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';
import type { GoalReportMetadata } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -473,6 +474,48 @@ describe('GoalReportStore.submit', () => {
expect(stored.version).toBe(1);
});
+ /**
+ * Regression: the default model narrated the whole path and submitted every
+ * chapter with an empty detours array, so the report stored no detour the
+ * requirement promises. The store now fills the candidates the skeleton found
+ * from the graph instead of losing them.
+ */
+ it('fills a detour the skeleton found when the agent tells none, and stores it', async () => {
+ const { goalId, metadata, topicId } = await setup();
+ const detourNodeId = 'dddddddd-1111-4000-8000-0000000000aa';
+ await serverDB.insert(goalNodes).values({
+ description: 'Tried a long-lived connection and abandoned it.',
+ goalId,
+ id: detourNodeId,
+ kind: 'task',
+ status: 'rejected',
+ title: 'Abandoned branch',
+ });
+
+ const reports = new GoalReportStore(serverDB, userId);
+ const stored = await reports.submit(
+ goalId,
+ { content: '# Report', metadata },
+ { operationId: 'op_report_1', topicId },
+ );
+ expect(stored.version).toBe(1);
+
+ const [row] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, stored.workId));
+ const detours =
+ (row.metadata as any)?.goalReport?.chapters?.flatMap((c: any) => c.detours) ?? [];
+ expect(detours).toHaveLength(1);
+ expect(detours[0]).toMatchObject({
+ kind: 'dead_end',
+ lesson: 'Tried a long-lived connection and abandoned it.',
+ nodeIds: [detourNodeId],
+ reason: 'Tried a long-lived connection and abandoned it.',
+ title: 'Abandoned branch',
+ });
+ });
+
it('stores metadata and content separately, appending a version per submission', async () => {
const { goalId, metadata, reportNode, service, topicId } = await setup();
const reports = new GoalReportStore(serverDB, userId);
@@ -527,4 +570,68 @@ describe('GoalReportStore.submit', () => {
items: expect.not.arrayContaining([expect.objectContaining({ type: 'goal_report' })]),
});
});
+
+ /**
+ * Regression: a Goal whose graph has no deliverable Work could not store its
+ * wrap-up report. The agent copies the skeleton's "Final deliverable: none…"
+ * into `deliverableWorkId` as `""` or `"none"`, which the schema (`min(1)`) and
+ * the reference check rejected, so the whole wrap-up finished with no report.
+ * Both placeholders must read as "no deliverable".
+ */
+ it('accepts a report for a Goal with no deliverable, reading placeholders as absent', async () => {
+ const { goalId, metadata, service, topicId } = await setup();
+ const reports = new GoalReportStore(serverDB, userId);
+
+ const first = await reports.submit(
+ goalId,
+ {
+ content: '# Report\n\nNo deliverable was produced.',
+ metadata: { ...metadata, deliverableWorkId: '' },
+ },
+ { operationId: 'op_report_1', topicId },
+ );
+ const second = await reports.submit(
+ goalId,
+ { content: '# Report v2', metadata: { ...metadata, deliverableWorkId: 'none' } },
+ { operationId: 'op_report_1', topicId },
+ );
+
+ expect(first.version).toBe(1);
+ expect(second.version).toBe(2);
+
+ const rows = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, first.workId))
+ .orderBy(workVersions.version);
+ expect(rows[0].metadata?.goalReport?.deliverableWorkId).toBeUndefined();
+ expect(rows[1].metadata?.goalReport?.deliverableWorkId).toBeUndefined();
+ expect((await service.graph(goalId)).report?.status).toBe('completed');
+ });
+
+ /**
+ * Regression: a submission with no `content` hit `input.content.trim()` on
+ * `undefined` and threw a raw TypeError, so the caller saw an unhandled crash
+ * instead of a validation error naming the missing field.
+ */
+ it('rejects a report whose content is missing with a structured validation error', async () => {
+ const { goalId, metadata, topicId } = await setup();
+ const reports = new GoalReportStore(serverDB, userId);
+
+ const missing = await reports
+ .submit(goalId, { content: undefined as unknown as string, metadata }, { topicId })
+ .catch((error: unknown) => error);
+ expect(missing).toBeInstanceOf(TRPCError);
+ expect(missing).toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('content'),
+ });
+ expect((missing as Error).message).not.toMatch(/Cannot read propert/);
+
+ await expect(
+ reports.submit(goalId, { content: null as unknown as string, metadata }, { topicId }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('content') });
+
+ expect(await new WorkModel(serverDB, userId).findLatestGoalReport(goalId)).toBeUndefined();
+ });
});
diff --git a/apps/server/src/services/goal/reportStore.ts b/apps/server/src/services/goal/reportStore.ts
index d4acf56d3fb..bd2c06dd369 100644
--- a/apps/server/src/services/goal/reportStore.ts
+++ b/apps/server/src/services/goal/reportStore.ts
@@ -18,7 +18,7 @@ import { WorkModel } from '@/database/models/work';
import { goalEvents } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
-import { validateGoalReport } from './report';
+import { reconcileGoalReport, validateGoalReport } from './report';
/**
* How long a wrap-up run may go without submitting before the page stops
@@ -148,11 +148,33 @@ export class GoalReportStore {
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
.join('; ')}`,
});
- const content = input.content.trim();
+ const content = typeof input.content === 'string' ? input.content.trim() : '';
if (!content)
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid report: content is empty' });
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Invalid report: content: required — the full markdown report is missing or empty',
+ });
- const errors = validateGoalReport(graph, parsed.data, { eventIds });
+ // Reconcile the storyline with the graph before judging it: a weak default
+ // model can narrate the whole path and still drop every detour, hang a
+ // detour off a chapter's own nodeIds, or mark a mainline node it never
+ // narrates. Those are recovered deterministically (see reconcileGoalReport);
+ // any remaining invalid reference is still the agent's to fix.
+ //
+ // Reconciliation appends to `chapters[].detours`, so its result is parsed
+ // again rather than trusted: a version that no longer satisfies the schema
+ // is one `GoalReportStore.state` could never read back, and storing it would
+ // hide the whole storyline behind a report that silently never loads.
+ const reconciled = GoalReportMetadataSchema.safeParse(reconcileGoalReport(graph, parsed.data));
+ if (!reconciled.success)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Invalid report after reconciliation: ${reconciled.error.issues
+ .map((issue) => `${issue.path.join('.')}: ${issue.message}`)
+ .join('; ')}`,
+ });
+ const metadata = reconciled.data;
+ const errors = validateGoalReport(graph, metadata, { eventIds });
if (errors.length > 0)
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -163,7 +185,7 @@ export class GoalReportStore {
agentId: caller?.agentId,
content,
goalId,
- metadata: parsed.data,
+ metadata,
rootOperationId: caller?.operationId,
title: `Goal report: ${graph.goal.title}`,
toolCallId: caller?.toolCallId,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 3eaa9fe5417..b77001a5cdc 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -878,9 +878,11 @@
"goalProcess.result.gate.error": "Could not save the decision. Try again.",
"goalProcess.result.gate.prompt": "Check which criteria were not met below, then retry or end the Goal.",
"goalProcess.result.gate.revising": "You chose to retry. The Agent is revising the result; it will be accepted again when done.",
+ "goalProcess.result.headline.pending": "Organizing this result…",
"goalProcess.result.nav.document": "Final document",
"goalProcess.result.nav.label": "Jump to section",
"goalProcess.result.nav.overview": "Overview",
+ "goalProcess.result.requirement": "Original requirement",
"goalProcess.result.scale.cost": "Spent {{cost}}",
"goalProcess.result.scale.criteria": "{{met}}/{{total}} criteria met",
"goalProcess.result.scale.duration": "Took {{duration}}",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4159fb642bb..73a0351b4e7 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -878,9 +878,11 @@
"goalProcess.result.gate.error": "决定没有保存成功,请重试。",
"goalProcess.result.gate.prompt": "先看下方哪些标准没有达成,再决定重试还是结束目标。",
"goalProcess.result.gate.revising": "你选择了重试,Agent 正在修改,改完后会重新验收。",
+ "goalProcess.result.headline.pending": "正在整理本次结果…",
"goalProcess.result.nav.document": "交付文档",
"goalProcess.result.nav.label": "页面导航",
"goalProcess.result.nav.overview": "概览",
+ "goalProcess.result.requirement": "原始要求",
"goalProcess.result.scale.cost": "花费 {{cost}}",
"goalProcess.result.scale.criteria": "标准达成 {{met}}/{{total}}",
"goalProcess.result.scale.duration": "用时 {{duration}}",
diff --git a/packages/builtin-tool-goal/src/report.ts b/packages/builtin-tool-goal/src/report.ts
index 3db708daba7..f1b135e2f8b 100644
--- a/packages/builtin-tool-goal/src/report.ts
+++ b/packages/builtin-tool-goal/src/report.ts
@@ -35,7 +35,7 @@ export const GoalReportManifest: BuiltinToolManifest = {
},
{
description:
- 'Submit the Goal wrap-up report. The storyline (headline, chapters with their main-path nodes, findings and Work versions, detours with reason and lesson, next steps) is stored as structured metadata and `content` as the full markdown report; each call appends a new report version. The mainline marks the nodes and edges of the path that led to the result; chapters tell exactly that path. Every id must belong to this Goal: chapter and mainline nodeIds must be resolved, mainline edges must join two mainline nodes, detour nodeIds must be rejected, retired or superseded (revises / contradicts). A rejected call lists every invalid reference — fix them and call again.',
+ 'Submit the Goal wrap-up report. The storyline (headline, chapters with their main-path nodes, findings and Work versions, detours with reason and lesson, next steps) is stored as structured metadata and `content` as the full markdown report; each call appends a new report version. The mainline marks the nodes and edges of the path that led to the result; chapters tell exactly that path. Every id must belong to this Goal: chapter and mainline nodeIds must be resolved, mainline edges must join two mainline nodes, detour nodeIds must be rejected, retired or superseded (revises / contradicts). When the instruction lists candidate detours, the report must tell at least one of them — a report that tells none is rejected. A rejected call lists every invalid reference — fix them and call again.',
name: GoalReportApiName.submitGoalReport,
parameters: {
additionalProperties: false,
@@ -74,7 +74,11 @@ export const GoalReportManifest: BuiltinToolManifest = {
description: 'The full written report in markdown, built from the metadata above.',
type: 'string',
},
- deliverableWorkId: { type: 'string' },
+ deliverableWorkId: {
+ description:
+ 'Work id of the Goal\'s final deliverable. Omit this field entirely when the Goal produced no deliverable; do not send an empty string or a placeholder such as "none".',
+ type: 'string',
+ },
goalId: { type: 'string' },
graphCursor: {
description: 'The graph cursor given in the instruction.',
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index e00c696e6a8..8264d43bd9f 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2239,9 +2239,11 @@ export default {
'Check which criteria were not met below, then retry or end the Goal.',
'goalProcess.result.gate.revising':
'You chose to retry. The Agent is revising the result; it will be accepted again when done.',
+ 'goalProcess.result.headline.pending': 'Organizing this result…',
'goalProcess.result.nav.document': 'Final document',
'goalProcess.result.nav.label': 'Jump to section',
'goalProcess.result.nav.overview': 'Overview',
+ 'goalProcess.result.requirement': 'Original requirement',
'goalProcess.result.scale.cost': 'Spent {{cost}}',
'goalProcess.result.scale.criteria': '{{met}}/{{total}} criteria met',
'goalProcess.result.scale.duration': 'Took {{duration}}',
diff --git a/packages/types/src/goalReport.ts b/packages/types/src/goalReport.ts
index 677da1552fb..b391040bcb0 100644
--- a/packages/types/src/goalReport.ts
+++ b/packages/types/src/goalReport.ts
@@ -10,23 +10,62 @@ import { z } from 'zod';
*/
const idList = z.array(z.string().trim().min(1)).max(200);
+/**
+ * The shapes a client uses to say "this id is not set". A wrap-up agent reads
+ * "Final deliverable: none linked to the graph." and copies a placeholder into
+ * `deliverableWorkId` instead of omitting the field, so a Goal that produced no
+ * deliverable could never submit its report. All of these mean the same as
+ * leaving the field out.
+ */
+const NO_VALUE_TOKENS = new Set(['', '-', '—', 'n/a', 'na', 'nil', 'none', 'null', 'undefined']);
+
+/**
+ * An optional id that folds the "no value" shapes into absence: `null`, an
+ * empty or blank string, and a placeholder such as `"none"` all parse as
+ * `undefined`, exactly as if the field were omitted. Anything else must still be
+ * a real, non-empty id — a wrong id is rejected downstream, not silently
+ * dropped.
+ */
+const optionalId = z.preprocess((value) => {
+ if (value === null || value === undefined) return undefined;
+ if (typeof value !== 'string') return value;
+ const trimmed = value.trim();
+ if (trimmed === '' || NO_VALUE_TOKENS.has(trimmed.toLowerCase())) return undefined;
+ return trimmed;
+}, z.string().trim().min(1).optional());
+
export const goalReportDetourKinds = ['dead_end', 'superseded', 'retry'] as const;
export type GoalReportDetourKind = (typeof goalReportDetourKinds)[number];
+/**
+ * Length caps of a detour's text fields. Exported so the server-side backfill,
+ * which copies graph-derived text (node titles and descriptions are bounded
+ * looser than this), can clamp to exactly what the schema reads back.
+ */
+export const GOAL_REPORT_MAX_DETOUR_TITLE_LENGTH = 200;
+export const GOAL_REPORT_MAX_DETOUR_TEXT_LENGTH = 2000;
+
export const GoalReportDetourSchema = z
.object({
kind: z.enum(goalReportDetourKinds),
- lesson: z.string().trim().min(1).max(2000),
+ lesson: z.string().trim().min(1).max(GOAL_REPORT_MAX_DETOUR_TEXT_LENGTH),
nodeIds: idList.min(1),
- reason: z.string().trim().min(1).max(2000),
- title: z.string().trim().min(1).max(200),
+ reason: z.string().trim().min(1).max(GOAL_REPORT_MAX_DETOUR_TEXT_LENGTH),
+ title: z.string().trim().min(1).max(GOAL_REPORT_MAX_DETOUR_TITLE_LENGTH),
})
.strict();
export type GoalReportDetour = z.infer<typeof GoalReportDetourSchema>;
+/**
+ * How many detours one chapter may tell. The cap is enforced by the schema and
+ * respected by the server-side backfill, so a recovered storyline can never
+ * exceed what the stored version can be read back as.
+ */
+export const GOAL_REPORT_MAX_DETOURS_PER_CHAPTER = 20;
+
export const GoalReportChapterSchema = z
.object({
- detours: z.array(GoalReportDetourSchema).max(20).default([]),
+ detours: z.array(GoalReportDetourSchema).max(GOAL_REPORT_MAX_DETOURS_PER_CHAPTER).default([]),
findingIds: idList.default([]),
narrative: z.string().trim().min(1).max(8000),
nodeIds: idList.default([]),
@@ -62,7 +101,12 @@ export type GoalReportMainline = z.infer<typeof GoalReportMainlineSchema>;
export const GoalReportMetadataSchema = z
.object({
chapters: z.array(GoalReportChapterSchema).min(1).max(30),
- deliverableWorkId: z.string().trim().min(1).optional(),
+ /**
+ * The Goal's final deliverable, when it produced one. A placeholder such as
+ * `""` or `"none"` is read as "no deliverable" rather than rejected, so a
+ * Goal without one can still report.
+ */
+ deliverableWorkId: optionalId,
/** The newest `goal_events.id` the report was written against. */
graphCursor: z.string().trim().min(1),
headline: z.string().trim().min(1).max(500),
diff --git a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
index 0c1d0206ed2..fd6d0349e2b 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
@@ -2,13 +2,14 @@
import type { GoalGraphDecision } from '@lobechat/types';
import { Flexbox, Tooltip } from '@lobehub/ui';
-import { Button, Text, TextArea, toast } from '@lobehub/ui/base-ui';
+import { Button, Spin, Text, TextArea, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { useGoalStore } from '@/store/goal';
+import { shinyTextStyles } from '@/styles';
import { coordinatorGateReason, coordinatorReasonCopy } from './coordinatorCopy';
import { useGateOptionLabel } from './Frontier';
@@ -17,6 +18,8 @@ import {
deriveGoalResultStatus,
findGoalAcceptanceGate,
findOpenChangeRequest,
+ goalResultHeadline,
+ isGoalReportOrganizing,
} from './goalResultState';
import type { GoalResultData } from './useGoalResultData';
@@ -117,6 +120,7 @@ interface GoalResultHeaderProps {
}
const GoalResultHeader = ({ data, graph }: GoalResultHeaderProps) => {
+ const { t } = useTranslation('chat');
const { goal } = graph;
const { outcomes } = data;
const gate = findGoalAcceptanceGate(graph);
@@ -128,14 +132,34 @@ const GoalResultHeader = ({ data, graph }: GoalResultHeaderProps) => {
goalStatus: goal.status,
unmetCriteria: outcomes.filter((outcome) => outcome.state === 'failed').length,
});
- const headline = graph.report?.latest?.metadata.headline;
+ const organizing = isGoalReportOrganizing(graph);
+ const headline = goalResultHeadline(graph);
return (
<Flexbox data-goal-result-status={status} gap={14}>
- {headline && (
- <Text fontSize={20} style={{ lineHeight: 1.4 }} weight={600}>
- {headline}
- </Text>
+ {organizing ? (
+ // The next wrap-up is writing this result's title. `report.latest` is
+ // still the previous version, so naming it here put the old result on
+ // top of the rework. Say that this one is being organized instead, with
+ // the same pending animation the storyline section uses; the title
+ // swaps in by itself when the run completes.
+ <Flexbox horizontal align={'center'} gap={8} role={'status'}>
+ <Spin size={'small'} variant={'network'} />
+ <Text
+ className={shinyTextStyles.shinyText}
+ fontSize={20}
+ style={{ lineHeight: 1.4 }}
+ weight={600}
+ >
+ {t('goalProcess.result.headline.pending')}
+ </Text>
+ </Flexbox>
+ ) : (
+ headline && (
+ <Text fontSize={20} style={{ lineHeight: 1.4 }} weight={600}>
+ {headline}
+ </Text>
+ )
)}
{status === 'awaitingDecision' && gate?.kind === 'pending' && (
<DecisionStrip
diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
index fb89ff76d7c..c6f7060fa17 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
@@ -174,10 +174,12 @@ const styles = createStaticStyles(({ css }) => ({
font-variant-numeric: tabular-nums;
color: ${cssVar.colorTextTertiary};
`,
- /* A ring, not a fill: the kind tint and the state chip must stay readable. */
+ /* A ring, not a fill: the kind tint and the state chip must stay readable.
+ Blue, not `colorPrimary` — the primary is near-black here, so the ring read
+ as a heavier version of the plain card border and told nothing apart. */
mainline: css`
- border-color: ${cssVar.colorPrimary};
- box-shadow: 0 0 0 1px ${cssVar.colorPrimary};
+ border-color: ${cssVar.colorInfo};
+ box-shadow: 0 0 0 1px ${cssVar.colorInfo};
`,
selected: css`
border-color: ${cssVar.colorPrimaryBorder};
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index 035146a337a..e439d024eaa 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -28,6 +28,7 @@ import { useTranslation } from 'react-i18next';
import { PortalContent } from '@/features/Portal/router';
import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
import RightPanel from '@/features/RightPanel';
+import { useIsDark } from '@/hooks/useIsDark';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -45,7 +46,16 @@ import ExplorationEdge from './ExplorationEdge';
import { explorationMap } from './explorationMap';
import GraphNodeView, { GhostNodeView, type GraphNodeData } from './GraphNode';
import { type GraphBridge, hideKinds, layoutGraph, NODE_WIDTH } from './layout';
-import { type EdgeTone, edgeTone, isNodeDimmed, nodeEmphasis, resolveMainline } from './mainline';
+import {
+ edgeMarkerColor,
+ type EdgeTone,
+ edgeTone,
+ isNodeDimmed,
+ MUTED_EDGE_OPACITY,
+ MUTED_EDGE_OPACITY_DARK,
+ nodeEmphasis,
+ resolveMainline,
+} from './mainline';
import { type MeasuredSizes, mergeMeasuredSizes } from './measuredSizes';
import { revealCenter } from './revealNode';
import { useExplorationNavigation } from './useExplorationNavigation';
@@ -102,7 +112,7 @@ const styles = createStaticStyles(({ css }) => ({
}
.react-flow__edge.goal-muted:not(.goal-hot) {
- opacity: 0.3;
+ opacity: ${MUTED_EDGE_OPACITY};
}
.react-flow__edge.goal-hot .react-flow__edge-path {
@@ -114,6 +124,20 @@ const styles = createStaticStyles(({ css }) => ({
stroke-width: 2.5;
}
+ /* Off-mainline lines keep their step-back on the light canvas. On the dark
+ one that same border token at a third opacity turns into background, so
+ the line is lifted just enough to read; the mainline stays the boldest
+ line on the map either way, so the hierarchy is not flattened. These
+ dark-theme overrides carry higher specificity, so they sit last to keep
+ the cascade ascending. */
+ html[data-theme='dark'] & .react-flow__edge.goal-muted:not(.goal-hot) {
+ opacity: ${MUTED_EDGE_OPACITY_DARK};
+ }
+
+ html[data-theme='dark'] & .react-flow__edge.goal-muted:not(.goal-hot) .react-flow__edge-path {
+ stroke: ${cssVar.colorTextQuaternary};
+ }
+
.react-flow__edge-textbg {
fill: ${cssVar.colorBgLayout};
}
@@ -159,7 +183,7 @@ const styles = createStaticStyles(({ css }) => ({
width: 14px;
height: 3px;
border-radius: 2px;
- background: ${cssVar.colorPrimary};
+ background: ${cssVar.colorInfo};
`,
legendOff: css`
opacity: 0.35;
@@ -388,6 +412,7 @@ const Canvas = memo<
const containerRef = useRef<HTMLDivElement>(null);
const subtitleOf = useSubtitle();
const edgeLabel = useEdgeLabel();
+ const isDarkMode = useIsDark();
const hasExperiments = graph.nodes.some((item) => item.node.kind === 'experiment');
const map = useMemo(
@@ -577,13 +602,13 @@ const Canvas = memo<
const flowEdges: FlowEdge[] = useMemo(() => {
const marker = {
- color: cssVar.colorBorder,
+ color: edgeMarkerColor(undefined, isDarkMode),
height: 12,
type: MarkerType.ArrowClosed,
width: 12,
};
- const mainlineMarker = { ...marker, color: cssVar.colorPrimary };
- const detourMarker = { ...marker, color: cssVar.colorWarning };
+ const mainlineMarker = { ...marker, color: edgeMarkerColor('mainline', isDarkMode) };
+ const detourMarker = { ...marker, color: edgeMarkerColor('detour', isDarkMode) };
const isMainlineCard = (id: string) => emphasisById.get(id) === 'mainline';
const toneOf = (edge: Parameters<typeof edgeTone>[1]) =>
edgeTone(mainline, edge, isMainlineCard, highlightedIds);
@@ -656,6 +681,7 @@ const Canvas = memo<
mainline,
emphasisById,
highlightedIds,
+ isDarkMode,
]);
const ghostFlowEdges: FlowEdge[] = useMemo(
@@ -901,7 +927,9 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,
{!fullscreen && toggle}
</>
);
- const hasMainline = !!resolveMainline(props.graph);
+ // Read against the map actually drawn — a scoped drill-down judges its own
+ // cards, so the legend never promises a mainline the view decided to drop.
+ const hasMainline = !!resolveMainline(scopedGraph);
const legend = (
<Flexbox horizontal align={'center'} className={styles.legend} gap={10}>
{hasMainline && (
diff --git a/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts b/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts
index 908bf67e9f5..419d6c5b184 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts
@@ -1,22 +1,36 @@
import type { GoalReportState } from '@lobechat/types';
+import { cssVar } from 'antd-style';
import { describe, expect, it } from 'vitest';
import type { GoalGraphView } from '../goalGraphViewModel';
-import { edgeEmphasis, isNodeDimmed, nodeEmphasis, resolveMainline } from './mainline';
+import {
+ edgeEmphasis,
+ edgeMarkerColor,
+ isNodeDimmed,
+ MUTED_EDGE_OPACITY,
+ MUTED_EDGE_OPACITY_DARK,
+ nodeEmphasis,
+ resolveMainline,
+} from './mainline';
const graphWith = (
mainline: { edgeIds: string[]; nodeIds: string[] } | undefined,
nodeIds = ['p', 't1', 't2', 't3', 'x1'],
-) =>
- ({
- byId: Object.fromEntries(nodeIds.map((id) => [id, { node: { id } }])),
+ kinds: Record<string, string> = {},
+) => {
+ const nodes = nodeIds.map((id) => ({ node: { id, kind: kinds[id] } }));
+ return {
+ byId: Object.fromEntries(nodes.map((view) => [view.node.id, view])),
+ edges: [],
+ nodes,
report: {
latest: {
metadata: { chapters: [], graphCursor: 'e', headline: 'H', mainline, nextSteps: [] },
},
status: 'completed',
} as unknown as GoalReportState,
- }) as unknown as Pick<GoalGraphView, 'byId' | 'report'>;
+ } as unknown as Pick<GoalGraphView, 'byId' | 'edges' | 'nodes' | 'report'>;
+};
describe('resolveMainline', () => {
it('reads the mark from the newest report version', () => {
@@ -36,6 +50,53 @@ describe('resolveMainline', () => {
]).toEqual(['t1']);
expect(resolveMainline(graphWith({ edgeIds: [], nodeIds: ['gone'] }))).toBeUndefined();
});
+
+ it('drops a mark that reaches every card, so the map is never all mainline', () => {
+ // The wrap-up model marks every node when it cannot tell the path apart;
+ // ringing the whole map says nothing, so the plain map is drawn instead.
+ const all = graphWith({ edgeIds: [], nodeIds: ['p', 't1', 't2', 't3', 'x1'] }, undefined, {
+ p: 'problem',
+ });
+ expect(resolveMainline(all)).toBeUndefined();
+ });
+
+ it('keeps the mark while any card stands off it, the root question aside', () => {
+ const root = graphWith({ edgeIds: [], nodeIds: ['t1', 't2', 't3', 'x1'] }, undefined, {
+ p: 'problem',
+ });
+ expect(resolveMainline(root)).toBeUndefined();
+ const oneOff = graphWith({ edgeIds: [], nodeIds: ['t1', 't2', 't3'] }, undefined, {
+ p: 'problem',
+ });
+ expect(resolveMainline(oneOff)).toBeDefined();
+ });
+
+ it('treats a collapsed experiment as on the mainline when its members are', () => {
+ const nodes = [
+ { node: { id: 'p', kind: 'problem' } },
+ { node: { id: 'e1', kind: 'experiment' } },
+ { node: { id: 't1', kind: 'task' } },
+ ];
+ expect(
+ resolveMainline({
+ byId: Object.fromEntries(nodes.map((view) => [view.node.id, view])),
+ edges: [{ id: 'c1', kind: 'contains', sourceNodeId: 'e1', targetNodeId: 't1' }],
+ nodes,
+ report: {
+ latest: {
+ metadata: {
+ chapters: [],
+ graphCursor: 'e',
+ headline: 'H',
+ mainline: { edgeIds: [], nodeIds: ['t1'] },
+ nextSteps: [],
+ },
+ },
+ status: 'completed',
+ },
+ } as unknown as Pick<GoalGraphView, 'byId' | 'edges' | 'nodes' | 'report'>),
+ ).toBeUndefined();
+ });
});
describe('nodeEmphasis', () => {
@@ -112,3 +173,26 @@ describe('isNodeDimmed', () => {
expect(isNodeDimmed({ blocked: false, emphasis: 'muted', highlighted: true })).toBe(false);
});
});
+
+describe('off-mainline legibility', () => {
+ /**
+ * Regression: the dark canvas turned the border token at a third opacity into
+ * background, so an off-mainline line and the arrow ending it were barely
+ * there. Only the off-mainline tone is lifted; the mainline keeps its own
+ * primary line, so the hierarchy is not flattened.
+ */
+ it('lifts only the off-mainline arrow on the dark canvas', () => {
+ expect(edgeMarkerColor('mainline', true)).toBe(cssVar.colorPrimary);
+ expect(edgeMarkerColor('detour', true)).toBe(cssVar.colorWarning);
+ // Light mode is unchanged — the same border token as before.
+ expect(edgeMarkerColor(undefined, false)).toBe(cssVar.colorBorder);
+ expect(edgeMarkerColor('muted', false)).toBe(cssVar.colorBorder);
+ expect(edgeMarkerColor(undefined, true)).toBe(cssVar.colorTextQuaternary);
+ expect(edgeMarkerColor('muted', true)).toBe(cssVar.colorTextQuaternary);
+ });
+
+ it('is more legible on the dark canvas while still stepping back', () => {
+ expect(MUTED_EDGE_OPACITY_DARK).toBeGreaterThan(MUTED_EDGE_OPACITY);
+ expect(MUTED_EDGE_OPACITY_DARK).toBeLessThan(1);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/mainline.ts b/src/features/AgentGoals/ProcessControl/Graph/mainline.ts
index ed8865cd3f3..abbbf2e4a7d 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/mainline.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/mainline.ts
@@ -1,4 +1,6 @@
import type { GoalGraphNode } from '@lobechat/types';
+import { experimentMembers } from '@lobechat/utils/goalGraph';
+import { cssVar } from 'antd-style';
import type { GoalGraphView } from '../goalGraphViewModel';
@@ -16,14 +18,18 @@ export interface Mainline {
export type MainlineEmphasis = 'mainline' | 'muted' | undefined;
export const resolveMainline = (
- graph: Pick<GoalGraphView, 'byId' | 'report'>,
+ graph: Pick<GoalGraphView, 'byId' | 'edges' | 'nodes' | 'report'>,
): Mainline | undefined => {
const mark = graph.report?.latest?.metadata.mainline;
if (!mark) return undefined;
// A node deleted since the report was written must not leave the whole map muted.
const nodeIds = new Set(mark.nodeIds.filter((id) => graph.byId[id]));
if (nodeIds.size === 0) return undefined;
- return { edgeIds: new Set(mark.edgeIds), nodeIds };
+ const mainline: Mainline = { edgeIds: new Set(mark.edgeIds), nodeIds };
+ // A mark that reaches every card rings the whole map and says nothing. The
+ // wrap-up model does exactly that when it cannot tell the path apart, so the
+ // host draws the plain map instead of a mainline nothing stands against.
+ return mainlineContrasts(mainline, graph) ? mainline : undefined;
};
/**
@@ -43,6 +49,24 @@ export const nodeEmphasis = (
return 'muted';
};
+/**
+ * Whether any card the map draws stands off the mark. A collapsed experiment
+ * stands in for its members, so it counts as on the mainline when they are —
+ * the rule {@link nodeEmphasis} applies when the card is painted.
+ */
+const mainlineContrasts = (
+ mainline: Mainline,
+ graph: Pick<GoalGraphView, 'edges' | 'nodes'>,
+): boolean => {
+ const snapshot = { edges: graph.edges, nodes: graph.nodes.map((view) => view.node) };
+ for (const view of graph.nodes) {
+ const members =
+ view.node.kind === 'experiment' ? experimentMembers(snapshot, view.node.id, false) : [];
+ if (nodeEmphasis(mainline, view.node, members) === 'muted') return true;
+ }
+ return false;
+};
+
/**
* Whether a card steps back on the map: still blocked before it started, or
* off a marked mainline — unless the host is calling it out on purpose (a
@@ -96,3 +120,26 @@ export const edgeTone = (
return 'detour';
return emphasis;
};
+
+/**
+ * How far an off-mainline line steps back.
+ *
+ * On the light canvas the border token at a third opacity reads as intended —
+ * clearly behind the mainline, still present. On the dark canvas that same
+ * combination sinks into the background, so the line is lifted just enough to
+ * stay legible. The mainline keeps its own bold primary line either way, so the
+ * hierarchy is never flattened.
+ */
+export const MUTED_EDGE_OPACITY = 0.3;
+export const MUTED_EDGE_OPACITY_DARK = 0.5;
+
+/**
+ * The arrowhead that ends a line, in the same tone as the line itself. An
+ * off-mainline marker uses the border token on the light canvas; on the dark one
+ * that token is nearly invisible, so it borrows the lighter text token.
+ */
+export const edgeMarkerColor = (tone: EdgeTone, isDarkMode: boolean): string => {
+ if (tone === 'mainline') return cssVar.colorPrimary;
+ if (tone === 'detour') return cssVar.colorWarning;
+ return isDarkMode ? cssVar.colorTextQuaternary : cssVar.colorBorder;
+};
diff --git a/src/features/AgentGoals/ProcessControl/ResultTrail.tsx b/src/features/AgentGoals/ProcessControl/ResultTrail.tsx
index 5a3efed3190..389183d056b 100644
--- a/src/features/AgentGoals/ProcessControl/ResultTrail.tsx
+++ b/src/features/AgentGoals/ProcessControl/ResultTrail.tsx
@@ -9,7 +9,6 @@ import {
ExternalLink,
FileDown,
FileText,
- GitBranch,
type LucideIcon,
} from 'lucide-react';
import { type ReactNode } from 'react';
@@ -138,26 +137,29 @@ const styles = createStaticStyles(({ css }) => ({
stepMuted: css`
opacity: 0.55;
`,
+ /**
+ * Review: the count is a note about the chapter, not a badge — plain gray
+ * text, with no tinted fill or pill around it, so it never competes with the
+ * chapter title it sits beside.
+ */
detour: css`
cursor: pointer;
display: inline-flex;
flex: none;
- gap: 4px;
align-items: center;
- padding-block: 2px;
- padding-inline: 8px;
- border: 1px dashed ${cssVar.colorWarningBorder};
- border-radius: 999px;
+ /* Reset the native button chrome — the hint is text, not a control. */
+ padding: 0;
+ border: none;
font-size: 12px;
- color: ${cssVar.colorWarningText};
+ color: ${cssVar.colorTextSecondary};
- background: ${cssVar.colorWarningBg};
+ background: none;
&:hover {
- border-style: solid;
+ color: ${cssVar.colorText};
}
&:focus-visible {
@@ -448,7 +450,6 @@ const DetourHint = ({
}
>
<button className={styles.detour} type={'button'} onClick={onOpen}>
- <Icon icon={GitBranch} size={12} />
{t('goalProcess.result.story.detours', { count })}
</button>
</Tooltip>
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
index ad7a91bc4fa..6f9f8935dca 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
@@ -16,7 +16,9 @@ import {
findFinalAcceptanceView,
findGoalAcceptanceGate,
findOpenChangeRequest,
+ goalResultHeadline,
hasGoalResult,
+ isGoalReportOrganizing,
latestRoundRunId,
resultTrailSource,
} from './goalResultState';
@@ -549,8 +551,11 @@ describe('buildUserDecisions', () => {
describe('buildAbandonedNodes', () => {
it('lists rejected and retired tasks with the reason that ended them', () => {
- const task = (id: string, status: string, attempts: unknown[] = []) =>
- ({ attempts, node: { id, kind: 'task', status, title: id } }) as unknown as GoalNodeView;
+ const task = (id: string, status: string, attempts: unknown[] = [], description?: string) =>
+ ({
+ attempts,
+ node: { description, id, kind: 'task', status, title: id },
+ }) as unknown as GoalNodeView;
const abandoned = buildAbandonedNodes({
nodes: [
@@ -559,9 +564,12 @@ describe('buildAbandonedNodes', () => {
{ outcome: 'failed', reason: 'First try' },
{ outcome: 'retired', reason: 'Source site is down' },
]),
- task('rejected', 'rejected'),
+ // No closing note and no attempt: the node's description is what says why.
+ task('rejected', 'rejected', [], 'Page scraping broke on every restyle'),
+ // Nothing recorded anywhere — still omitted rather than invented.
+ task('bare', 'rejected'),
{
- ...task('closed-early', 'retired'),
+ ...task('closed-early', 'retired', [], 'A plan that never ran'),
closedReason: 'Goal canceled before it started',
} as GoalNodeView,
],
@@ -569,7 +577,8 @@ describe('buildAbandonedNodes', () => {
expect(abandoned.map((a) => [a.view.node.id, a.reason])).toEqual([
['retired', 'Source site is down'],
- ['rejected', undefined],
+ ['rejected', 'Page scraping broke on every restyle'],
+ ['bare', undefined],
['closed-early', 'Goal canceled before it started'],
]);
});
@@ -794,3 +803,27 @@ describe('buildStoryChapters', () => {
expect(chapters[1].detourNodeIds).toEqual([]);
});
});
+
+describe('goalResultHeadline', () => {
+ const reportAt = (status: string, headline?: string) =>
+ ({
+ report: { latest: headline ? { metadata: { headline } } : undefined, status },
+ }) as unknown as Pick<GoalGraphView, 'report'>;
+
+ /**
+ * Regression: a new result's wrap-up runs while `report.latest` is still the
+ * version written for the previous one, so the header named the old result on
+ * top of the rework. The headline of this result only exists once its own run
+ * has landed; until then the caller shows the organizing state.
+ */
+ it('names this result, but never the previous one while the next is being written', () => {
+ expect(goalResultHeadline(reportAt('completed', 'Shipped the brief'))).toBe(
+ 'Shipped the brief',
+ );
+ expect(goalResultHeadline(reportAt('running', 'Old headline'))).toBeUndefined();
+ expect(isGoalReportOrganizing(reportAt('running', 'Old headline'))).toBe(true);
+
+ expect(goalResultHeadline(reportAt('completed'))).toBeUndefined();
+ expect(isGoalReportOrganizing(reportAt('completed', 'Shipped the brief'))).toBe(false);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.ts b/src/features/AgentGoals/ProcessControl/goalResultState.ts
index f6a53235756..07c30042dbb 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.ts
@@ -361,7 +361,9 @@ export interface AbandonedNodeView {
/**
* Task nodes the Goal gave up on — rejected or retired — with the reason
- * recorded when it closed them, falling back to the attempt that ended it.
+ * recorded when it closed them, falling back to the attempt that ended it and
+ * then to the node's own description, so a dropped task still says why it was
+ * dropped even when no closing note was recorded.
*/
export const buildAbandonedNodes = (graph: Pick<GoalGraphView, 'nodes'>): AbandonedNodeView[] =>
graph.nodes
@@ -374,7 +376,8 @@ export const buildAbandonedNodes = (graph: Pick<GoalGraphView, 'nodes'>): Abando
const reason = firstLine(
view.closedReason ??
view.attempts.findLast((attempt) => attempt.outcome !== 'running' && attempt.reason)
- ?.reason,
+ ?.reason ??
+ view.node.description,
);
return { ...(reason ? { reason } : {}), view };
});
@@ -498,6 +501,22 @@ export const resultTrailSource = (graph: Pick<GoalGraphView, 'report'>): ResultT
return { kind: 'story', metadata: parsed.data, report: report.latest };
};
+/** Whether the wrap-up agent is writing this result's storyline right now. */
+export const isGoalReportOrganizing = (graph: Pick<GoalGraphView, 'report'>): boolean =>
+ graph.report?.status === 'running';
+
+/**
+ * The one-line headline of the result.
+ *
+ * `report.latest` is the *previous* version until a new wrap-up lands, so while
+ * one is running (`report.status === 'running'`) there is no headline for this
+ * result yet. Returning the last version's here is what put the old result's
+ * title on top of a rework that had not produced its own; the caller shows the
+ * organizing state instead and the title swaps in when the run completes.
+ */
+export const goalResultHeadline = (graph: Pick<GoalGraphView, 'report'>): string | undefined =>
+ isGoalReportOrganizing(graph) ? undefined : graph.report?.latest?.metadata.headline;
+
export interface StoryChapterView {
artifacts: GoalArtifactView[];
chapter: GoalReportChapter;
diff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts
index d41446ed1b8..4a6414ef0f0 100644
--- a/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts
+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts
@@ -30,9 +30,13 @@ const wrapper = ({ children }: { children: ReactNode }) =>
);
/** A Goal whose final acceptance Task carries acceptance `acc-1`. */
-const graphWith = (acceptanceStatus: string, nodeStatus: string) =>
+const graphWith = (acceptanceStatus: string, nodeStatus: string, goalStatus = 'achieved') =>
({
- goal: { config: { acceptance: { criteriaIds: ['crit-1'] } }, id: 'goal-1' },
+ goal: {
+ config: { acceptance: { criteriaIds: ['crit-1'] } },
+ id: 'goal-1',
+ status: goalStatus,
+ },
nodes: [
{
acceptance: { id: 'acc-1', status: acceptanceStatus },
@@ -80,6 +84,90 @@ describe('useGoalResultData', () => {
expect(mocks.getAcceptanceBundle).toHaveBeenCalledTimes(2);
});
+ /**
+ * Regression: a rework ends by putting the Goal back on `achieved` — exactly
+ * when the graph poll stops. The snapshot it stops on can still carry the
+ * acceptance node's pre-rework status, so keyed on the acceptance alone the
+ * bundle stayed on the rejected round: the sign-off strip kept reading 修改中
+ * with no accept button, and the criteria count froze at the rework's starting
+ * point (2/3) until the page was reloaded. The Goal moving on is its own
+ * reason to re-read the latest round.
+ */
+ it('re-reads the latest round when the Goal returns to achieved after a rework', async () => {
+ const criteriaIds = ['crit-1', 'crit-2', 'crit-3'];
+ mocks.getCriteria.mockResolvedValue(criteriaIds.map((id) => ({ id, title: id })));
+
+ const reworkGraph = (goalStatus: string) =>
+ ({
+ goal: { config: { acceptance: { criteriaIds } }, id: 'goal-1', status: goalStatus },
+ nodes: [
+ {
+ // The graph the poll stops on: the Goal has moved back on, the
+ // acceptance node still reads the rejected round from the rework.
+ acceptance: { id: 'acc-1', status: 'rejected' },
+ node: {
+ id: 'node-acceptance',
+ kind: 'task',
+ status: 'active',
+ title: GOAL_ACCEPTANCE_TASK_TITLE,
+ },
+ },
+ ],
+ }) as unknown as GoalGraphView;
+
+ const round = (id: string, roundIndex: number) => ({ run: { id, roundIndex } });
+ const check = (criterionId: string, roundId: string, verdict: string) => ({
+ evidence: [],
+ id: criterionId,
+ result: {
+ id: `res-${criterionId}-${roundId}`,
+ sourceCriterionId: criterionId,
+ status: verdict,
+ verdict,
+ verifyRunId: roundId,
+ },
+ });
+
+ mocks.getAcceptanceBundle.mockResolvedValueOnce({
+ acceptance: { status: 'rejected' },
+ canReview: true,
+ checks: [
+ check('crit-1', 'run-1', 'passed'),
+ check('crit-2', 'run-1', 'passed'),
+ check('crit-3', 'run-1', 'failed'),
+ ],
+ rounds: [round('run-1', 1)],
+ });
+
+ const { rerender, result } = renderHook(({ graph }) => useGoalResultData(graph), {
+ initialProps: { graph: reworkGraph('running') },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.acceptanceStatus).toBe('rejected'));
+ expect(result.current.outcomes.filter((outcome) => outcome.state === 'passed')).toHaveLength(2);
+
+ // 返工完成:Goal 回到「已达成」,新一轮验收 3/3 落地。
+ mocks.getAcceptanceBundle.mockResolvedValueOnce({
+ acceptance: { status: 'delivered' },
+ canReview: true,
+ checks: [
+ check('crit-1', 'run-2', 'passed'),
+ check('crit-2', 'run-2', 'passed'),
+ check('crit-3', 'run-2', 'passed'),
+ ],
+ rounds: [round('run-1', 1), round('run-2', 2)],
+ });
+ rerender({ graph: reworkGraph('achieved') });
+
+ await waitFor(() => expect(result.current.acceptanceStatus).toBe('delivered'));
+ await waitFor(() =>
+ expect(result.current.outcomes.filter((outcome) => outcome.state === 'passed')).toHaveLength(
+ 3,
+ ),
+ );
+ expect(mocks.getAcceptanceBundle).toHaveBeenCalledTimes(2);
+ });
+
/**
* Regression: a failed read fell back to empty data, so criteria rendered as
* unjudged and the sign-off vanished with no error and no way to retry.
diff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.ts
index 0e37477b4e8..645ab065bba 100644
--- a/src/features/AgentGoals/ProcessControl/useGoalResultData.ts
+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.ts
@@ -15,6 +15,13 @@ import {
* the same acceptance id, so an id-only key held the rejected round until a
* reload; the polled graph moving the acceptance (or its Task node) on is what
* re-reads the bundle.
+ *
+ * The Goal's own status is part of that state too. A rework ends by putting the
+ * Goal back on `achieved` — the moment the graph poll stops — and the snapshot
+ * taken then can still carry the acceptance node's pre-rework status. Keyed on
+ * the acceptance alone, the bundle stayed on the rejected round and the
+ * sign-off strip kept reading 修改中 until the page was reloaded; the Goal
+ * moving on is its own reason to re-read the latest round.
*/
export const goalResultAcceptanceKey = (acceptanceId: string, graphState: string) =>
['goal-result-acceptance', acceptanceId, graphState] as const;
@@ -31,7 +38,7 @@ export const useGoalResultData = (graph: GoalGraphView) => {
const acceptanceId = acceptanceView?.acceptance?.id;
const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];
- const graphState = `${acceptanceView?.acceptance?.status}:${acceptanceView?.node.status}`;
+ const graphState = `${graph.goal.status}:${acceptanceView?.acceptance?.status}:${acceptanceView?.node.status}`;
const bundle = useClientDataSWR(
acceptanceId ? goalResultAcceptanceKey(acceptanceId, graphState) : null,
() => verifyService.getAcceptanceBundle(acceptanceId!),
diff --git a/src/features/Portal/GoalReport/Body.tsx b/src/features/Portal/GoalReport/Body.tsx
index 77a9afb623e..271834c470a 100644
--- a/src/features/Portal/GoalReport/Body.tsx
+++ b/src/features/Portal/GoalReport/Body.tsx
@@ -20,13 +20,15 @@ import { useReportChapter, useReportGraph } from './useReportGraph';
*/
const styles = createStaticStyles(({ css }) => ({
+ /**
+ * Review: an outline is enough — no tinted fill, so the detour reads as a
+ * callout beside the map rather than a filled warning block.
+ */
detour: css`
padding-block: 10px;
padding-inline: 12px;
border: 1px dashed ${cssVar.colorWarningBorder};
border-radius: ${cssVar.borderRadius};
-
- background: ${cssVar.colorWarningBg};
`,
scroll: css`
overflow-y: auto;
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 2077fb4ef5c..942dad5e3bb 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -1,3 +1,4 @@
+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
@@ -80,6 +81,48 @@ describe('GoalAction', () => {
expect(options.refreshInterval(undefined)).toBe(0);
});
+
+ /**
+ * Regression: a rework ends by putting the Goal back on `achieved`, but its
+ * own acceptance verdict is a later write. The poll stopped on that
+ * half-written snapshot, so an open result page stayed on the rework's
+ * starting state — sign-off strip still reading 修改中, criteria count
+ * frozen — until the page was reloaded.
+ */
+ it('keeps polling a terminal Goal whose own acceptance has not settled', () => {
+ useGoalStore.getState().useFetchGoalGraph('goal-1');
+ const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {
+ refreshInterval: (graph: unknown) => number;
+ };
+ const withAcceptance = (status: string, title = GOAL_ACCEPTANCE_TASK_TITLE) => ({
+ acceptances: { 'node-a': { id: 'acc-1', status } },
+ goal: { status: 'achieved' },
+ nodes: [{ id: 'node-a', kind: 'task', status: 'active', taskId: 't-1', title }],
+ });
+
+ expect(options.refreshInterval(withAcceptance('repairing'))).toBeGreaterThan(0);
+ expect(options.refreshInterval(withAcceptance('verifying'))).toBeGreaterThan(0);
+
+ // Settled: the page can rest on this snapshot.
+ expect(options.refreshInterval(withAcceptance('delivered'))).toBe(0);
+ expect(options.refreshInterval(withAcceptance('accepted'))).toBe(0);
+
+ /**
+ * Regression: rejecting a Goal's delivery with `dispatch: false` only
+ * records the decision, so the acceptance stays sticky on `rejected` while
+ * the Goal stays `achieved`. Nothing else is coming, and polling that state
+ * hammered the graph endpoint every five seconds for as long as the page
+ * stayed open.
+ */
+ expect(options.refreshInterval(withAcceptance('rejected'))).toBe(0);
+ // A rejection that reopens the Goal keeps polling: the Goal is running again.
+ expect(
+ options.refreshInterval({ ...withAcceptance('rejected'), goal: { status: 'running' } }),
+ ).toBeGreaterThan(0);
+
+ // Another task's rejection never keeps a terminal Goal polling.
+ expect(options.refreshInterval(withAcceptance('rejected', 'Ordinary work'))).toBe(0);
+ });
});
describe('useFetchTopicGoals', () => {
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 1dee20920f0..f76480cb60a 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -1,4 +1,4 @@
-import type { GoalStatus } from '@lobechat/const/goal';
+import { GOAL_ACCEPTANCE_TASK_TITLE, type GoalStatus } from '@lobechat/const/goal';
import type { GoalMetricCriterion, GoalTickResult } from '@lobechat/types';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
@@ -54,6 +54,48 @@ const SERVER_ADVANCING_STATUSES = new Set<GoalStatus>(['planning', 'running', 'v
const GOAL_GRAPH_POLL_INTERVAL = 5000;
const PENDING_CLARIFICATIONS_POLL_INTERVAL = 30_000;
+/**
+ * Acceptance states in which the Goal's own delivery has nothing left in
+ * flight. `pending`, `planned`, `repairing` and `verifying` are writes still on
+ * their way from the coordinator or from the verify run it dispatched.
+ *
+ * `rejected` is terminal for this poll as well. Rejecting a Goal's delivery
+ * either reopens the Goal — `reopenForChanges` makes it `running`, which the
+ * advancing-status branch above already covers — or only records the decision
+ * (`acceptance.reject` with `dispatch: false`), after which nothing else is
+ * coming for that acceptance. Leaving it out polls that sticky state every five
+ * seconds for as long as the page stays open.
+ */
+const SETTLED_ACCEPTANCE_STATUSES = new Set([
+ 'accepted',
+ 'closed',
+ 'delivered',
+ 'errored',
+ 'rejected',
+]);
+
+/**
+ * Whether the Goal's own acceptance has a write still coming.
+ *
+ * A terminal Goal whose own acceptance has not settled is **mid-transition**:
+ * the verdict is not written yet. Stopping the poll on that half-written
+ * snapshot is what froze an open result page after a rework — the Goal already
+ * read 已达成 while the sign-off strip still showed the rejected round and the
+ * criteria count stayed at the rework's starting point, until the page was
+ * reloaded. Keep reading until the acceptance settles; the settled snapshot is
+ * the one the page can rest on.
+ */
+const goalAcceptanceUnsettled = (graph: {
+ acceptances?: Record<string, { status: string }>;
+ nodes?: { id: string; kind: string; title: string }[];
+}): boolean => {
+ const terminal = graph.nodes?.find(
+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,
+ );
+ const acceptance = terminal ? graph.acceptances?.[terminal.id] : undefined;
+ return !!acceptance && !SETTLED_ACCEPTANCE_STATUSES.has(acceptance.status);
+};
+
/** A conversation rarely plans more than one goal; this only bounds a runaway topic. */
const TOPIC_GOAL_FETCH_LIMIT = 20;
@@ -208,9 +250,13 @@ export class GoalActionImpl {
},
// The wrap-up report is written after the Goal settles, so a finished
// Goal keeps polling until its report run ends and the storyline lands.
+ // A Goal that already reads terminal while its own acceptance has not
+ // settled is mid-transition too — the verdict is still coming.
refreshInterval: (graph) =>
graph &&
- (SERVER_ADVANCING_STATUSES.has(graph.goal.status) || graph.report?.status === 'running')
+ (SERVER_ADVANCING_STATUSES.has(graph.goal.status) ||
+ graph.report?.status === 'running' ||
+ (graph.goal.status === 'achieved' && goalAcceptanceUnsettled(graph)))
? GOAL_GRAPH_POLL_INTERVAL
: 0,
revalidateOnFocus: true,