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.

✨ feat(goal): write the wrap-up report as an HTML page (#21240)

Arvin Xud0ba7338e1d7
diff --git a/apps/cli/src/commands/goal/index.test.ts b/apps/cli/src/commands/goal/index.test.ts
index 099c3454b0e..7a53b3737ad 100644
--- a/apps/cli/src/commands/goal/index.test.ts
+++ b/apps/cli/src/commands/goal/index.test.ts
@@ -123,55 +123,6 @@ describe('goal plan authentication', () => {
);
});
-describe('goal report authentication', () => {
- afterEach(() => {
- vi.unstubAllEnvs();
- vi.mocked(console.log).mockRestore();
- });
-
- it.each(['hetero-operation', undefined])(
- 'routes %s credentials to the appropriate report endpoint',
- async (purpose) => {
- vi.clearAllMocks();
- vi.stubEnv(
- 'LOBEHUB_JWT',
- purpose
- ? `header.${Buffer.from(JSON.stringify({ purpose })).toString('base64url')}.signature`
- : undefined,
- );
- vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-wrapup');
- vi.spyOn(console, 'log').mockImplementation(() => {});
- mockClient.goal.submitReport.mutate.mockResolvedValue({ data: {} });
- mockClient.goal.submitOperationReport.mutate.mockResolvedValue({ data: {} });
- await createProgram().parseAsync([
- 'node',
- 'test',
- 'goal',
- 'report',
- 'goal-1',
- '--metadata-file',
- 'report.json',
- '--content-file',
- 'report.md',
- ]);
- const [selected, other] =
- purpose === 'hetero-operation'
- ? [mockClient.goal.submitOperationReport, mockClient.goal.submitReport]
- : [mockClient.goal.submitReport, mockClient.goal.submitOperationReport];
- // The mocked readFile returns the same text for both files.
- expect(selected.mutate).toHaveBeenCalledWith({
- id: 'goal-1',
- operationId: 'op-wrapup',
- report: {
- content: JSON.stringify({ action: 'verify', reason: 'Ready' }),
- metadata: { action: 'verify', reason: 'Ready' },
- },
- });
- expect(other.mutate).not.toHaveBeenCalled();
- },
- );
-});
-
describe('goal resume', () => {
it('asks the server to settle the stuck planning turn only with --confirm-exit', async () => {
vi.clearAllMocks();
diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.ts
index 8e97e07f7ec..897293e21d4 100644
--- a/apps/cli/src/commands/goal/index.ts
+++ b/apps/cli/src/commands/goal/index.ts
@@ -27,6 +27,7 @@ import {
registerGoalMetricCommands,
} from './metric';
import { goalReads, hasOperationToken } from './reads';
+import { registerGoalReportCommand } from './report';
import { missingSeedDependencies, parseTaskFile } from './seedTasks';
// Typed rather than inferred: an `as const` map is indexable by a widened
@@ -539,39 +540,7 @@ export function registerGoalCommand(program: Command) {
},
);
- goal
- .command('report <id>')
- .description("Submit this Goal's wrap-up report from its wrap-up run")
- .requiredOption(
- '--metadata-file <path>',
- 'JSON: headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor',
- )
- .requiredOption('--content-file <path>', 'The full written report in markdown')
- .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')
- .option('--json', 'Output JSON')
- .action(
- async (
- id: string,
- options: { contentFile: string; json?: boolean; metadataFile: string; operation?: string },
- ) => {
- const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;
- if (!operationId) throw new Error('Current wrap-up operation ID required');
- const client = await getTrpcClient();
- const endpoint = hasOperationToken()
- ? client.goal.submitOperationReport
- : client.goal.submitReport;
- const result = await endpoint.mutate({
- id,
- operationId,
- report: {
- content: await readFile(options.contentFile, 'utf8'),
- metadata: JSON.parse(await readFile(options.metadataFile, 'utf8')),
- },
- });
- if (options.json) outputJson(result.data);
- else console.log('Goal report recorded.');
- },
- );
+ registerGoalReportCommand(goal);
goal
.command('create <title>')
diff --git a/apps/cli/src/commands/goal/report.test.ts b/apps/cli/src/commands/goal/report.test.ts
new file mode 100644
index 00000000000..461e51014ae
--- /dev/null
+++ b/apps/cli/src/commands/goal/report.test.ts
@@ -0,0 +1,87 @@
+import { Buffer } from 'node:buffer';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerGoalReportCommand } from './report';
+
+const { mockClient } = vi.hoisted(() => ({
+ mockClient: {
+ goal: {
+ submitOperationReport: { mutate: vi.fn() },
+ submitReport: { mutate: vi.fn() },
+ },
+ },
+}));
+
+const files: Record<string, string> = {
+ 'report.html': '<!doctype html><html><body><h1>Report</h1></body></html>',
+ 'report.json': JSON.stringify({ headline: 'Done' }),
+ 'report.md': '# Report',
+};
+
+vi.mock('node:fs/promises', () => ({ readFile: async (path: string) => files[path] }));
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));
+
+const run = (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerGoalReportCommand(program.command('goal'));
+ return program.parseAsync(['node', 'test', 'goal', 'report', 'goal-1', ...args]);
+};
+
+const fileArgs = ['--metadata-file', 'report.json', '--content-file', 'report.md'];
+
+describe('goal report', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-wrapup');
+ mockClient.goal.submitReport.mutate.mockResolvedValue({ data: {} });
+ mockClient.goal.submitOperationReport.mutate.mockResolvedValue({ data: {} });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.mocked(console.log).mockRestore();
+ });
+
+ it.each(['hetero-operation', undefined])(
+ 'routes %s credentials to the appropriate report endpoint',
+ async (purpose) => {
+ vi.stubEnv(
+ 'LOBEHUB_JWT',
+ purpose
+ ? `header.${Buffer.from(JSON.stringify({ purpose })).toString('base64url')}.signature`
+ : undefined,
+ );
+
+ await run(...fileArgs);
+
+ const [selected, other] =
+ purpose === 'hetero-operation'
+ ? [mockClient.goal.submitOperationReport, mockClient.goal.submitReport]
+ : [mockClient.goal.submitReport, mockClient.goal.submitOperationReport];
+ expect(selected.mutate).toHaveBeenCalledWith({
+ id: 'goal-1',
+ operationId: 'op-wrapup',
+ report: { content: '# Report', metadata: { headline: 'Done' } },
+ });
+ expect(other.mutate).not.toHaveBeenCalled();
+ },
+ );
+
+ it('submits the HTML page alongside the markdown report', async () => {
+ await run(...fileArgs, '--html-file', 'report.html');
+
+ expect(mockClient.goal.submitReport.mutate).toHaveBeenCalledWith({
+ id: 'goal-1',
+ operationId: 'op-wrapup',
+ report: {
+ content: '# Report',
+ html: files['report.html'],
+ metadata: { headline: 'Done' },
+ },
+ });
+ });
+});
diff --git a/apps/cli/src/commands/goal/report.ts b/apps/cli/src/commands/goal/report.ts
new file mode 100644
index 00000000000..935d7fe89bb
--- /dev/null
+++ b/apps/cli/src/commands/goal/report.ts
@@ -0,0 +1,55 @@
+import { readFile } from 'node:fs/promises';
+
+import type { Command } from 'commander';
+
+import { getTrpcClient } from '../../api/client';
+import { outputJson } from '../../utils/format';
+import { hasOperationToken } from './reads';
+
+/** `lh goal report`: the wrap-up run submits the Goal report it wrote. */
+export function registerGoalReportCommand(goal: Command) {
+ goal
+ .command('report <id>')
+ .description("Submit this Goal's wrap-up report from its wrap-up run")
+ .requiredOption(
+ '--metadata-file <path>',
+ 'JSON: headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor',
+ )
+ .requiredOption('--content-file <path>', 'The full written report in markdown')
+ .option(
+ '--html-file <path>',
+ 'The same report as one self-contained HTML page (inline CSS/JS), shown as the report',
+ )
+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')
+ .option('--json', 'Output JSON')
+ .action(
+ async (
+ id: string,
+ options: {
+ contentFile: string;
+ htmlFile?: string;
+ json?: boolean;
+ metadataFile: string;
+ operation?: string;
+ },
+ ) => {
+ const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;
+ if (!operationId) throw new Error('Current wrap-up operation ID required');
+ const client = await getTrpcClient();
+ const endpoint = hasOperationToken()
+ ? client.goal.submitOperationReport
+ : client.goal.submitReport;
+ const result = await endpoint.mutate({
+ id,
+ operationId,
+ report: {
+ content: await readFile(options.contentFile, 'utf8'),
+ ...(options.htmlFile ? { html: await readFile(options.htmlFile, 'utf8') } : {}),
+ metadata: JSON.parse(await readFile(options.metadataFile, 'utf8')),
+ },
+ });
+ if (options.json) outputJson(result.data);
+ else console.log('Goal report recorded.');
+ },
+ );
+}
diff --git a/apps/server/src/routers/lambda/goal/planning.ts b/apps/server/src/routers/lambda/goal/planning.ts
index f0ae9272cb5..4d7a06a4dd9 100644
--- a/apps/server/src/routers/lambda/goal/planning.ts
+++ b/apps/server/src/routers/lambda/goal/planning.ts
@@ -23,6 +23,8 @@ const reportInput = idInput.extend({
operationId: z.string().min(1),
report: z.object({
content: z.string(),
+ /** The same report as one self-contained HTML page. */
+ html: z.string().optional(),
metadata: z.record(z.string(), z.unknown()),
}),
});
diff --git a/apps/server/src/services/goal/report.test.ts b/apps/server/src/services/goal/report.test.ts
index 8a2f4f9f87d..aa70f80cd4c 100644
--- a/apps/server/src/services/goal/report.test.ts
+++ b/apps/server/src/services/goal/report.test.ts
@@ -445,6 +445,22 @@ describe('buildGoalReportSkeleton', () => {
expect(text).not.toContain('submitGoalReport');
});
+ it('asks for the report as one self-contained HTML page and submits it with the markdown', () => {
+ const tool = buildGoalReportInstruction(snapshot, 'accepted', {
+ kind: 'tool',
+ toolName: 'lobe-goal-report.submitGoalReport',
+ });
+ expect(tool).toContain('ONE HTML page');
+ expect(tool).toContain('The page MUST be self-contained');
+ expect(tool).toContain('all CSS in <style> and all JS in <script>');
+ expect(tool).toContain('every diagram (the path, a timeline, a chart) drawn as inline <svg>');
+ expect(tool).toContain('html: that HTML page');
+
+ const cli = buildGoalReportInstruction(snapshot, 'accepted', { kind: 'cli' });
+ expect(cli).toContain('The page MUST be self-contained');
+ expect(cli).toContain('--html-file <html>');
+ });
+
describe('validateGoalReport', () => {
const valid: GoalReportMetadata = {
chapters: [
diff --git a/apps/server/src/services/goal/report.ts b/apps/server/src/services/goal/report.ts
index 57c7d61ab2d..62d392c2202 100644
--- a/apps/server/src/services/goal/report.ts
+++ b/apps/server/src/services/goal/report.ts
@@ -456,9 +456,16 @@ export const buildGoalReportInstruction = (
'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.',
+ [
+ '8. Also write the report as ONE HTML page — this is what readers see first. Lay out the headline, the chapters, the detours with their lessons and the next steps as a clear, well-designed report. The page MUST be self-contained; it is rendered in a sandboxed frame with no network access to your files:',
+ ' - all CSS in <style> and all JS in <script> inside the page; no <link rel="stylesheet">, no <script src>, no web fonts, no CDN libraries, no local file paths;',
+ ' - every diagram (the path, a timeline, a chart) drawn as inline <svg> in the page, never an external image or a chart library;',
+ ' - only images given as data URIs or public https URLs;',
+ ' - legible on a light background and at narrow widths.',
+ ].join('\n'),
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.`
- : `8. Call ${submission.toolName} once with goalId, the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor) and content: the full written report in markdown, built from that same metadata. If it rejects a reference, fix it and call again.`,
+ ? `9. Write the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor) as JSON to a file, the full written report in markdown, built from that same metadata, to another file, and the HTML page to a third. Submit them once with \`lh goal report ${graph.goal.id} --metadata-file <json> --content-file <md> --html-file <html>\`. If it rejects a reference, fix the file and submit again.`
+ : `9. Call ${submission.toolName} once with goalId, the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor), content: the full written report in markdown, built from that same metadata, and html: that HTML page. If it rejects a reference, fix it and call again.`,
].join('\n'),
]
.filter(Boolean)
diff --git a/apps/server/src/services/goal/reportPage.ts b/apps/server/src/services/goal/reportPage.ts
new file mode 100644
index 00000000000..4abfea495c4
--- /dev/null
+++ b/apps/server/src/services/goal/reportPage.ts
@@ -0,0 +1,65 @@
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+
+import { DocumentModel } from '@/database/models/document';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { DocumentService } from '../document';
+
+interface ReportPageOwner {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+interface WriteReportPageParams {
+ html: string;
+ /** The page an earlier report version wrote; reused so a Goal keeps one report page. */
+ previousPageId?: string;
+ title: string;
+}
+
+/**
+ * Store a report version as an HTML page (a `custom/html` document, rendered in
+ * a sandboxed frame). A Goal keeps one report page: a later version rewrites the
+ * page an earlier one created, unless that page is gone, no longer HTML, or
+ * cannot be written (e.g. a member holds its edit lock) — then a new page is
+ * created. Workspace pages are shared like the report itself.
+ */
+export const writeGoalReportPage = async (
+ { db, userId, workspaceId }: ReportPageOwner,
+ { html, previousPageId, title }: WriteReportPageParams,
+): Promise<string> => {
+ const documentService = new DocumentService(db, userId, workspaceId);
+
+ if (previousPageId) {
+ const previous = await new DocumentModel(db, userId, workspaceId).findById(previousPageId);
+ if (previous?.fileType === HTML_DOCUMENT_FILE_TYPE) {
+ const updated = await documentService
+ .updateDocument(previousPageId, { content: html, saveSource: 'llm_call', title })
+ .then(() => true)
+ .catch((error) => {
+ console.warn('[GoalReportPage] could not rewrite the previous page:', error);
+ return false;
+ });
+ if (updated) return previousPageId;
+ }
+ }
+
+ const page = await documentService.createDocument({
+ content: html,
+ fileType: HTML_DOCUMENT_FILE_TYPE,
+ title,
+ ...(workspaceId ? { visibility: 'public' as const } : {}),
+ });
+ if (workspaceId && page.visibility !== 'private') {
+ await new ResourcePermissionModel(db, workspaceId).setAccessLevel(
+ 'document',
+ page.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ userId,
+ );
+ }
+ return page.id;
+};
diff --git a/apps/server/src/services/goal/reportService.test.ts b/apps/server/src/services/goal/reportService.test.ts
index 6ffdf612c4b..a539ebcdfb0 100644
--- a/apps/server/src/services/goal/reportService.test.ts
+++ b/apps/server/src/services/goal/reportService.test.ts
@@ -14,6 +14,7 @@ import {
acceptances,
agentOperations,
agents,
+ documents,
goalEdges,
goalEvents,
goalNodeDecisions,
@@ -571,6 +572,42 @@ describe('GoalReportStore.submit', () => {
});
});
+ it('stores the report as one HTML page per Goal, rewritten by later versions', async () => {
+ const { goalId, metadata, service, topicId } = await setup();
+ const reports = new GoalReportStore(serverDB, userId);
+ const page = (n: number) => `<!doctype html><html><body><h1>Report v${n}</h1></body></html>`;
+
+ await reports.submit(goalId, { content: '# Report v1', html: page(1), metadata }, { topicId });
+ const first = (await service.graph(goalId)).report?.latest;
+ expect(first?.pageDocumentId).toBeDefined();
+
+ await reports.submit(goalId, { content: '# Report v2', html: page(2), metadata }, { topicId });
+ const second = (await service.graph(goalId)).report?.latest;
+ // The same page, now holding the newer report; the markdown stays the fallback.
+ expect(second).toMatchObject({ content: '# Report v2', pageDocumentId: first?.pageDocumentId });
+
+ const [stored] = await serverDB
+ .select()
+ .from(documents)
+ .where(eq(documents.id, first!.pageDocumentId!));
+ expect(stored).toMatchObject({ content: page(2), editorData: null, fileType: 'custom/html' });
+ });
+
+ it('writes no page for a report without HTML', async () => {
+ const { goalId, metadata, service, topicId } = await setup();
+
+ await new GoalReportStore(serverDB, userId).submit(
+ goalId,
+ { content: '# Report', metadata },
+ { topicId },
+ );
+
+ expect((await service.graph(goalId)).report?.latest?.pageDocumentId).toBeUndefined();
+ expect(
+ await serverDB.select().from(documents).where(eq(documents.fileType, 'custom/html')),
+ ).toHaveLength(0);
+ });
+
/**
* 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…"
diff --git a/apps/server/src/services/goal/reportStore.ts b/apps/server/src/services/goal/reportStore.ts
index bd2c06dd369..040ea3b5e19 100644
--- a/apps/server/src/services/goal/reportStore.ts
+++ b/apps/server/src/services/goal/reportStore.ts
@@ -19,6 +19,7 @@ import { goalEvents } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { reconcileGoalReport, validateGoalReport } from './report';
+import { writeGoalReportPage } from './reportPage';
/**
* How long a wrap-up run may go without submitting before the page stops
@@ -28,6 +29,8 @@ export const GOAL_REPORT_TIMEOUT_MS = 60 * 60 * 1000;
export interface SubmitGoalReportInput {
content: string;
+ /** The same report as one self-contained HTML page, stored as a `custom/html` document. */
+ html?: string;
metadata: Omit<GoalReportMetadata, 'graphCursor'> & { graphCursor?: string };
}
@@ -53,8 +56,8 @@ export class GoalReportStore {
constructor(
private readonly db: LobeChatDatabase,
- userId: string,
- workspaceId?: string,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
) {
this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {
id: GOAL_COORDINATOR_ACTOR_ID,
@@ -181,11 +184,27 @@ export class GoalReportStore {
message: `Invalid report references:\n${errors.join('\n')}`,
});
+ // The page is written only once the report itself is valid, and reused
+ // across versions so a Goal keeps one report page.
+ const html = typeof input.html === 'string' ? input.html.trim() : '';
+ const pageDocumentId = html
+ ? await writeGoalReportPage(
+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },
+ {
+ html,
+ previousPageId: (await this.workModel.findLatestGoalReport(goalId))?.metadata
+ ?.goalReportPageId,
+ title: `${graph.goal.title} · Report`,
+ },
+ )
+ : undefined;
+
const work = await this.workModel.registerGoalReport({
agentId: caller?.agentId,
content,
goalId,
metadata,
+ pageDocumentId,
rootOperationId: caller?.operationId,
title: `Goal report: ${graph.goal.title}`,
toolCallId: caller?.toolCallId,
@@ -230,6 +249,7 @@ export class GoalReportStore {
content: latestRow.content,
createdAt: latestRow.createdAt,
metadata: parsed.data,
+ pageDocumentId: latestRow.metadata?.goalReportPageId,
version: latestRow.version,
workId: latestRow.workId,
workVersionId: latestRow.workVersionId,
diff --git a/apps/server/src/services/goal/reportTools.ts b/apps/server/src/services/goal/reportTools.ts
index b102a47d42c..9adb758cf53 100644
--- a/apps/server/src/services/goal/reportTools.ts
+++ b/apps/server/src/services/goal/reportTools.ts
@@ -78,13 +78,13 @@ export class GoalReportTools {
};
});
- submitGoalReport = ({ content, goalId, ...metadata }: SubmitGoalReportParams) =>
+ submitGoalReport = ({ content, goalId, html, ...metadata }: SubmitGoalReportParams) =>
this.run(async () => {
const { agentId, operationId, serverDB, toolCallId, topicId, userId, workspaceId } =
this.context;
return new GoalReportStore(serverDB!, userId!, workspaceId).submit(
goalId,
- { content, metadata },
+ { content, html, metadata },
{ agentId, operationId, toolCallId, topicId: topicId ?? null },
);
});
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 5f9656c8aba..7ea227ca4ae 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1117,6 +1117,8 @@
"goalProcess.result.nav.document": "Final document",
"goalProcess.result.nav.label": "Jump to section",
"goalProcess.result.nav.overview": "Overview",
+ "goalProcess.result.nav.report": "Report",
+ "goalProcess.result.report.expand": "View full screen",
"goalProcess.result.requirement": "Original requirement",
"goalProcess.result.scale.cost": "Spent {{cost}}",
"goalProcess.result.scale.criteria": "{{met}}/{{total}} criteria met",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index f02f8e2e7df..7d6cf1ef3f7 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1117,6 +1117,8 @@
"goalProcess.result.nav.document": "交付文档",
"goalProcess.result.nav.label": "页面导航",
"goalProcess.result.nav.overview": "概览",
+ "goalProcess.result.nav.report": "报告",
+ "goalProcess.result.report.expand": "全屏查看",
"goalProcess.result.requirement": "原始要求",
"goalProcess.result.scale.cost": "花费 {{cost}}",
"goalProcess.result.scale.criteria": "标准达成 {{met}}/{{total}}",
diff --git a/packages/builtin-tool-goal/src/report.ts b/packages/builtin-tool-goal/src/report.ts
index f1b135e2f8b..6a31f0b7a50 100644
--- a/packages/builtin-tool-goal/src/report.ts
+++ b/packages/builtin-tool-goal/src/report.ts
@@ -16,6 +16,8 @@ export interface SubmitGoalReportParams extends Omit<GoalReportMetadata, 'graphC
goalId: string;
/** The graph cursor from the skeleton; the newest Goal event when omitted. */
graphCursor?: string;
+ /** The same report as one self-contained HTML page, shown as the report's page. */
+ html?: string;
}
const ids = { items: { type: 'string' }, type: 'array' };
@@ -80,6 +82,11 @@ export const GoalReportManifest: BuiltinToolManifest = {
type: 'string',
},
goalId: { type: 'string' },
+ html: {
+ description:
+ 'The same report as ONE self-contained HTML page, built from the metadata above. It MUST inline all CSS (<style>) and JS (<script>) and draw every diagram as inline <svg>; no external stylesheets, scripts, fonts, chart libraries or local files; images only as data URIs or public URLs. It is what readers see as the report; content stays its plain-text fallback.',
+ type: 'string',
+ },
graphCursor: {
description: 'The graph cursor given in the instruction.',
type: 'string',
diff --git a/packages/database/src/models/work/goalReport.ts b/packages/database/src/models/work/goalReport.ts
index dd6b90fefd5..485b0763535 100644
--- a/packages/database/src/models/work/goalReport.ts
+++ b/packages/database/src/models/work/goalReport.ts
@@ -11,6 +11,8 @@ export interface RegisterGoalReportWorkParams extends Omit<WorkVersionEventParam
content: string;
goalId: string;
metadata: GoalReportMetadata;
+ /** The `custom/html` document holding this version as an HTML page. */
+ pageDocumentId?: string;
title: string;
}
@@ -23,7 +25,7 @@ export const registerGoalReportWork = (
ctx: WorkContext,
params: RegisterGoalReportWorkParams,
): Promise<WorkItem> => {
- const { content, goalId, metadata, title, ...event } = params;
+ const { content, goalId, metadata, pageDocumentId, title, ...event } = params;
return registerWorkVersion(
ctx,
{
@@ -45,7 +47,10 @@ export const registerGoalReportWork = (
title,
url: null,
},
- metadata: { goalReport: metadata },
+ metadata: {
+ goalReport: metadata,
+ ...(pageDocumentId && { goalReportPageId: pageDocumentId }),
+ },
}),
);
};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d301addec18..455f259ed05 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2676,6 +2676,7 @@ export default {
'goalProcess.result.nav.document': 'Final document',
'goalProcess.result.nav.label': 'Jump to section',
'goalProcess.result.nav.overview': 'Overview',
+ 'goalProcess.result.nav.report': 'Report',
'goalProcess.result.requirement': 'Original requirement',
'goalProcess.result.scale.cost': 'Spent {{cost}}',
'goalProcess.result.scale.criteria': '{{met}}/{{total}} criteria met',
@@ -2711,6 +2712,7 @@ export default {
'goalProcess.result.unfinished.nextSteps': 'Suggested next steps',
'goalProcess.result.unfinished.title': 'Not done / next steps',
'goalProcess.result.unfinished.unmetCriteria': 'Unmet criteria',
+ 'goalProcess.result.report.expand': 'View full screen',
'goalProcess.result.story.chapterMissing':
'This chapter is no longer in the report — it may have been rewritten.',
'goalProcess.result.story.detourKind.dead_end': 'Dead end',
diff --git a/packages/types/src/goalReport.ts b/packages/types/src/goalReport.ts
index b391040bcb0..264125304c7 100644
--- a/packages/types/src/goalReport.ts
+++ b/packages/types/src/goalReport.ts
@@ -147,6 +147,8 @@ export interface GoalReportVersion {
content: string | null;
createdAt: Date;
metadata: GoalReportMetadata;
+ /** The report as a self-contained HTML page (a `custom/html` document), when one was written. */
+ pageDocumentId?: string;
version: number;
workId: string;
workVersionId: string;
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index 7f19f530085..585584965fc 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -86,6 +86,8 @@ export interface WorkVersionMetadata {
fileUrl?: string;
/** `goal_report` Work — the structured storyline; the full report is the version's `content`. */
goalReport?: GoalReportMetadata;
+ /** `goal_report` Work — the report as an HTML page: a `custom/html` document id. */
+ goalReportPageId?: string;
/** `file` Work — lines added by this version's edit (0 when the source tool reports none). */
linesAdded?: number;
/** `file` Work — lines deleted by this version's edit (0 when the source tool reports none). */
diff --git a/src/business/client/features/HtmlPageShareButton.tsx b/src/business/client/features/HtmlPageShareButton.tsx
new file mode 100644
index 00000000000..45fa617079c
--- /dev/null
+++ b/src/business/client/features/HtmlPageShareButton.tsx
@@ -0,0 +1,11 @@
+export interface HtmlPageShareButtonProps {
+ /** The `custom/html` document being shared. */
+ documentId: string;
+ html: string;
+ title: string;
+}
+
+/** Shares an HTML page as a public site (lobe.page). Cloud only. */
+export default function HtmlPageShareButton(_props: HtmlPageShareButtonProps) {
+ return null;
+}
diff --git a/src/features/AgentGoals/ProcessControl/GoalReportFullscreen.tsx b/src/features/AgentGoals/ProcessControl/GoalReportFullscreen.tsx
new file mode 100644
index 00000000000..780a6d6111a
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/GoalReportFullscreen.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
+import {
+ ActionIcon,
+ copyToClipboard,
+ Drawer,
+ DropdownMenu,
+ Flexbox,
+ HtmlPreview,
+ Icon,
+ Text,
+ toast,
+} from '@lobehub/ui';
+import { Download, Link2, MoreHorizontal } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import HtmlPageShareButton from '@/business/client/features/HtmlPageShareButton';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { isDesktop } from '@/const/version';
+import { buildDocumentModalUrl } from '@/features/DocumentModal/url';
+import { useHtmlExport } from '@/features/Portal/Document/useHtmlExport';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+
+const hideHtmlPreviewActions = () => null;
+
+interface GoalReportFullscreenProps {
+ content: string;
+ documentId: string;
+ onClose: () => void;
+ open: boolean;
+ title: string;
+}
+
+/**
+ * The report page full screen, to read it whole. Link and download sit in the
+ * menu beside the title; sharing it as a public page is the header's action.
+ */
+const GoalReportFullscreen = memo<GoalReportFullscreenProps>(
+ ({ content, documentId, onClose, open, title }) => {
+ const { t } = useTranslation(['file', 'common', 'components']);
+ const appOrigin = useAppOrigin();
+ const workspaceSlug = useActiveWorkspaceSlug();
+ const exportHtml = useHtmlExport(documentId);
+
+ const menu = [
+ {
+ icon: <Icon icon={Link2} />,
+ key: 'copy-link',
+ label: t('pageEditor.menu.copyLink'),
+ onClick: async () => {
+ await copyToClipboard(buildDocumentModalUrl(appOrigin, documentId, workspaceSlug));
+ toast.success(t('pageEditor.linkCopied'));
+ },
+ },
+ {
+ disabled: !exportHtml,
+ icon: <Icon icon={Download} />,
+ key: 'download',
+ label: t('HtmlPreview.actions.download', { ns: 'components' }),
+ onClick: () => exportHtml?.(),
+ },
+ ];
+
+ return (
+ <Drawer
+ containerMaxWidth={'100%'}
+ extra={<HtmlPageShareButton documentId={documentId} html={content} title={title} />}
+ height={isDesktop ? `calc(100vh - ${TITLE_BAR_HEIGHT}px)` : '100vh'}
+ open={open}
+ placement={'bottom'}
+ styles={{
+ bodyContent: { height: '100%', padding: 0 },
+ header: { paddingBlock: 8, paddingInline: 12 },
+ }}
+ title={
+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {title}
+ </Text>
+ <DropdownMenu items={menu}>
+ <ActionIcon
+ icon={MoreHorizontal}
+ size={'small'}
+ title={t('more', { ns: 'common' })}
+ />
+ </DropdownMenu>
+ </Flexbox>
+ }
+ onClose={onClose}
+ >
+ <HtmlPreview
+ actionsRender={hideHtmlPreviewActions}
+ copyable={false}
+ downloadable={false}
+ style={{ height: '100%' }}
+ styles={{ iframe: { height: '100%' } }}
+ title={title}
+ variant={'borderless'}
+ >
+ {content}
+ </HtmlPreview>
+ </Drawer>
+ );
+ },
+);
+
+GoalReportFullscreen.displayName = 'GoalReportFullscreen';
+
+export default GoalReportFullscreen;
diff --git a/src/features/AgentGoals/ProcessControl/GoalReportPage.tsx b/src/features/AgentGoals/ProcessControl/GoalReportPage.tsx
new file mode 100644
index 00000000000..69e1d6a515b
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/GoalReportPage.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+import { Button, createStaticStyles, cssVar, Skeleton } from '@lobehub/ui';
+import { Maximize2 } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { HtmlDocumentFrame } from '@/components/HtmlPreview';
+import { useDocumentStore } from '@/store/document';
+
+import GoalReportFullscreen from './GoalReportFullscreen';
+
+/** How much of the report the result page shows before the reader expands it. */
+const PREVIEW_MAX_HEIGHT = 480;
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ position: relative;
+
+ overflow: hidden;
+
+ max-height: ${PREVIEW_MAX_HEIGHT}px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+ // A shadow rising from the clipped edge says there is more below; the
+ // expand button sits on it.
+ expand: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 2;
+ inset-block-end: 0;
+ inset-inline: 0;
+
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+
+ height: 140px;
+ padding-block-end: 20px;
+
+ background: linear-gradient(to bottom, transparent, ${cssVar.colorBgMask});
+
+ > * {
+ pointer-events: auto;
+ }
+ `,
+ // The sandboxed frame swallows clicks; this layer turns the clipped preview
+ // into one target that opens the full report.
+ hit: css`
+ cursor: zoom-in;
+ position: absolute;
+ z-index: 1;
+ inset: 0;
+ `,
+}));
+
+/**
+ * The HTML page the wrap-up agent wrote, as the first screen of the result:
+ * clipped to a fixed height under a rising shadow, and opened full screen on
+ * click, where it runs interactively. Renders nothing when the page is gone or no longer HTML —
+ * the deliverable document below then leads the page as before.
+ */
+const GoalReportPage = memo<{ documentId: string }>(({ documentId }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: page, isLoading } = useFetchDocumentDetail(documentId);
+
+ if (isLoading) return <Skeleton height={PREVIEW_MAX_HEIGHT} radius={8} />;
+ if (page?.fileType !== HTML_DOCUMENT_FILE_TYPE || !page.content) return null;
+
+ const title = page.title || t('goalProcess.result.story.reportTitle');
+ const expand = () => setOpen(true);
+
+ return (
+ <>
+ <div className={styles.card}>
+ <HtmlDocumentFrame content={page.content} title={title} />
+ <div
+ aria-label={t('goalProcess.result.report.expand')}
+ className={styles.hit}
+ role={'button'}
+ tabIndex={0}
+ onClick={expand}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') expand();
+ }}
+ />
+ <div className={styles.expand}>
+ <Button icon={<Maximize2 size={14} />} shape={'round'} onClick={expand}>
+ {t('goalProcess.result.report.expand')}
+ </Button>
+ </div>
+ </div>
+ <GoalReportFullscreen
+ content={page.content}
+ documentId={documentId}
+ open={open}
+ title={title}
+ onClose={() => setOpen(false)}
+ />
+ </>
+ );
+});
+
+GoalReportPage.displayName = 'GoalReportPage';
+
+export default GoalReportPage;
diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
index 23669913f86..4eda2af11db 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResult.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
@@ -12,9 +12,10 @@ import { pickFinalDeliverable } from './goalAcceptanceReport';
import { buildAcceptanceTree } from './goalAcceptanceTree';
import GoalCriteriaResults from './GoalCriteriaResults';
import type { GoalGraphView } from './goalGraphViewModel';
+import GoalReportPage from './GoalReportPage';
import { GoalDecisionsMade, GoalUnfinished, useContinueFromResult } from './GoalResultFollowUps';
import GoalResultHeader from './GoalResultHeader';
-import { findFinalAcceptanceView } from './goalResultState';
+import { findFinalAcceptanceView, goalReportPageId } from './goalResultState';
import ResultAnchorRail from './ResultAnchorRail';
import { anchorProps } from './resultAnchors';
import ResultDeliverables from './ResultDeliverables';
@@ -25,7 +26,8 @@ import { useGoalResultData } from './useGoalResultData';
* 结果交付 — what a finished Goal hands over, on its own tab.
*
* Layered for a reviewer who reads top-down: the first screen is the Goal's own
- * headline, the document the work wrote leads the page as the delivery itself,
+ * headline and the HTML report the wrap-up wrote (clipped, full screen on
+ * click); the document the work wrote follows as the delivery itself,
* and the deliverables plus each acceptance criterion (against what the latest
* acceptance round found) follow as the evidence behind it. Under them the trail
* of how that result was reached. What the owner shaped along the way and what is
@@ -73,6 +75,7 @@ const GoalResult = ({ graph, onSelect }: GoalResultProps) => {
const data = useGoalResultData(graph);
const continueFromResult = useContinueFromResult(graph, data.outcomes);
const acceptanceTree = useMemo(() => buildAcceptanceTree(graph), [graph]);
+ const reportPageId = goalReportPageId(graph);
return (
<div ref={rootRef}>
@@ -81,6 +84,14 @@ const GoalResult = ({ graph, onSelect }: GoalResultProps) => {
<div {...anchorProps('overview', t('goalProcess.result.nav.overview'))}>
<GoalResultHeader data={data} graph={graph} />
</div>
+ {reportPageId && (
+ <div
+ {...anchorProps('report', t('goalProcess.result.nav.report'))}
+ style={{ paddingBlockStart: 16 }}
+ >
+ <GoalReportPage documentId={reportPageId} />
+ </div>
+ )}
{deliverable && (
<div
{...anchorProps('document', t('goalProcess.result.nav.document'))}
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
index 6f9f8935dca..b1a3ea5928b 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
@@ -16,6 +16,7 @@ import {
findFinalAcceptanceView,
findGoalAcceptanceGate,
findOpenChangeRequest,
+ goalReportPageId,
goalResultHeadline,
hasGoalResult,
isGoalReportOrganizing,
@@ -742,6 +743,15 @@ describe('resultTrailSource', () => {
const broken = { ...latest, metadata: { headline: 'x' } as any };
expect(resultTrailSource(report({ latest: broken, status: 'completed' })).kind).toBe('derived');
});
+
+ it('leads the result with the report HTML page, kept while a newer report is written', () => {
+ const withPage = { ...latest, pageDocumentId: 'docs-report' };
+ expect(goalReportPageId(report({ latest: withPage, status: 'completed' }))).toBe('docs-report');
+ expect(goalReportPageId(report({ latest: withPage, status: 'running' }))).toBe('docs-report');
+ // A markdown-only report, or none yet, has no page to lead with.
+ expect(goalReportPageId(report({ latest, status: 'completed' }))).toBeUndefined();
+ expect(goalReportPageId({})).toBeUndefined();
+ });
});
describe('buildStoryChapters', () => {
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.ts b/src/features/AgentGoals/ProcessControl/goalResultState.ts
index 07c30042dbb..e2b4a1a4620 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.ts
@@ -501,6 +501,13 @@ export const resultTrailSource = (graph: Pick<GoalGraphView, 'report'>): ResultT
return { kind: 'story', metadata: parsed.data, report: report.latest };
};
+/**
+ * The HTML page the latest report wrote, which leads the result page. A newer
+ * wrap-up still writing keeps the previous page on screen until it lands.
+ */
+export const goalReportPageId = (graph: Pick<GoalGraphView, 'report'>): string | undefined =>
+ graph.report?.latest?.pageDocumentId || undefined;
+
/** 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';