🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): goalShare router for sharing a finished goal's report, graph and acceptance (#22752)
Lobehub Coderf0dd704c2211
diff --git a/apps/server/src/routers/lambda/__tests__/goalShare.router.test.ts b/apps/server/src/routers/lambda/__tests__/goalShare.router.test.tsnew file mode 100644index 00000000000..16c97060c6c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/goalShare.router.test.ts@@ -0,0 +1,335 @@+// @vitest-environment node+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { beforeEach, describe, expect, it, vi } from 'vitest';++// serverDatabase middleware calls getServerDB(); stub it (the model mocks+// ignore the db handle anyway).+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++const mockGoalFindById = vi.fn();+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(function () {+ return { findById: mockGoalFindById };+ }),+}));++const mockGraph = vi.fn();+vi.mock('@/server/services/goal', () => ({+ GoalService: vi.fn(function () {+ return { graph: mockGraph };+ }),+}));++const mockShareCreate = vi.fn();+const mockShareGetByGoalId = vi.fn();+const mockShareUpdateVisibility = vi.fn();+const mockShareDeleteByGoalId = vi.fn();+const mockFindWithAccessCheck = vi.fn();+const mockIncrementViewCount = vi.fn();+vi.mock('@/database/models/goalShare', () => ({+ GoalShareModel: Object.assign(+ vi.fn(function () {+ return {+ create: mockShareCreate,+ deleteByGoalId: mockShareDeleteByGoalId,+ getByGoalId: mockShareGetByGoalId,+ updateVisibility: mockShareUpdateVisibility,+ };+ }),+ {+ findByShareIdWithAccessCheck: (...args: unknown[]) => mockFindWithAccessCheck(...args),+ incrementViewCount: (...args: unknown[]) => mockIncrementViewCount(...args),+ },+ ),+}));++const mockLoadRounds = vi.fn();+vi.mock('@/server/services/verify', () => ({+ AcceptanceService: vi.fn(function () {+ return { loadRounds: mockLoadRounds };+ }),+ buildAcceptanceCheckUnion: (rounds: { results: any[] }[]) =>+ rounds.flatMap((round) =>+ round.results.map((result) => ({+ result,+ state: result.verdict,+ title: result.checkItemTitle,+ })),+ ),+}));++const { goalShareRouter } = await import('../goalShare');++const creatorId = 'user-creator';+const memberId = 'user-member';+const workspaceId = 'ws-1';+const goalId = 'goal-1';++const baseGraph = () => ({+ acceptances: { node_acc: { id: 'acc-1', status: 'accepted' } },+ assignees: { node_acc: 'agt_assignee' },+ decisions: [{ id: 'dec', question: 'internal question' }],+ edges: [],+ events: [{ id: 'evt', operationId: 'op_secret' }],+ goal: {+ config: { budget: 5 },+ id: goalId,+ requirement: 'Ship it',+ status: 'achieved',+ title: 'The goal',+ topicId: 'tpc_secret',+ userId: creatorId,+ },+ nodes: [+ {+ createdAt: new Date(0),+ id: 'node_acc',+ kind: 'task',+ status: 'resolved',+ taskId: 'task_secret',+ title: GOAL_ACCEPTANCE_TASK_TITLE,+ },+ ],+ report: {+ dispatch: { operationId: 'op_leak' },+ latest: {+ metadata: {+ chapters: [{ detours: [], findingIds: [], narrative: 'Story', nodeIds: [], title: 'One' }],+ graphCursor: 'cursor',+ headline: 'Done',+ nextSteps: [],+ },+ },+ status: 'completed',+ },+ runHeartbeats: {},+ spend: { totalCost: 4 },+ workVersions: [],+});++describe('goalShare router', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGoalFindById.mockResolvedValue({ id: goalId, userId: creatorId });+ mockGraph.mockResolvedValue(baseGraph());+ mockShareGetByGoalId.mockResolvedValue(null);+ mockShareCreate.mockResolvedValue({ goalId, id: 'share-1', visibility: 'private' });+ mockShareUpdateVisibility.mockResolvedValue({ goalId, id: 'share-1', visibility: 'link' });+ mockIncrementViewCount.mockResolvedValue(undefined);+ mockLoadRounds.mockResolvedValue({+ results: [+ {+ checkItemTitle: 'Report is readable',+ toulmin: { reasoning: 'Read end to end' },+ verdict: 'passed',+ verifyRunId: 'run-1',+ },+ ],+ runs: [{ id: 'run-1' }],+ });+ });++ describe('enable', () => {+ it('creates the share for the goal creator', async () => {+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ const result = await caller.enable({ goalId, visibility: 'link' });++ expect(mockShareCreate).toHaveBeenCalledWith(goalId, 'link');+ expect(mockShareUpdateVisibility).toHaveBeenCalledWith(goalId, 'link');+ expect(result.data).toMatchObject({ visibility: 'link' });+ });++ it('refuses with a clear error when the goal has no report.latest', async () => {+ mockGraph.mockResolvedValue({ ...baseGraph(), report: undefined });+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ await expect(caller.enable({ goalId })).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('no wrap-up report'),+ });+ expect(mockShareCreate).not.toHaveBeenCalled();+ });++ it('refuses while the report is still being written', async () => {+ mockGraph.mockResolvedValue({+ ...baseGraph(),+ report: { dispatch: {}, status: 'running' },+ });+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ await expect(caller.enable({ goalId })).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ });++ it('reads a goal outside the caller scope as NOT_FOUND', async () => {+ mockGoalFindById.mockResolvedValue(undefined);+ const caller = goalShareRouter.createCaller({ userId: memberId } as any);++ await expect(caller.enable({ goalId })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockShareCreate).not.toHaveBeenCalled();+ });++ it('rejects a workspace member who did not create the goal', async () => {+ const caller = goalShareRouter.createCaller({+ userId: memberId,+ workspaceId,+ workspaceRole: 'member',+ } as any);++ await expect(caller.enable({ goalId })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockShareCreate).not.toHaveBeenCalled();+ });++ it('allows a workspace owner to manage a goal someone else created', async () => {+ const caller = goalShareRouter.createCaller({+ userId: memberId,+ workspaceId,+ workspaceRole: 'owner',+ } as any);++ await caller.enable({ goalId });++ expect(mockShareCreate).toHaveBeenCalledWith(goalId, 'private');+ });+ });++ describe('setVisibility / disable / getInfo', () => {+ it('updates the visibility', async () => {+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ const result = await caller.setVisibility({ goalId, visibility: 'link' });++ expect(mockShareUpdateVisibility).toHaveBeenCalledWith(goalId, 'link');+ expect(result.data).toMatchObject({ visibility: 'link' });+ });++ it('reports NOT_FOUND when updating a goal that was never shared', async () => {+ mockShareUpdateVisibility.mockResolvedValue(null);+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ await expect(caller.setVisibility({ goalId, visibility: 'link' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it('deletes the share', async () => {+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ await caller.disable({ goalId });++ expect(mockShareDeleteByGoalId).toHaveBeenCalledWith(goalId);+ });++ it('rejects disabling by a non-creator workspace member', async () => {+ const caller = goalShareRouter.createCaller({ userId: memberId, workspaceId } as any);++ await expect(caller.disable({ goalId })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockShareDeleteByGoalId).not.toHaveBeenCalled();+ });++ it('returns the share record, or null when not shared', async () => {+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);+ expect((await caller.getInfo({ goalId })).data).toBeNull();++ mockShareGetByGoalId.mockResolvedValue({ goalId, id: 'share-1', visibility: 'link' });+ expect((await caller.getInfo({ goalId })).data).toMatchObject({ id: 'share-1' });+ });+ });++ describe('getSharedGoal', () => {+ const share = {+ goalId,+ ownerId: creatorId,+ shareId: 'share-1',+ visibility: 'link',+ workspaceId: null,+ };++ it('returns the redacted view to an anonymous visitor', async () => {+ mockFindWithAccessCheck.mockResolvedValue(share);+ const caller = goalShareRouter.createCaller({} as any);++ const { data } = await caller.getSharedGoal({ shareId: 'share-1' });++ expect(mockFindWithAccessCheck).toHaveBeenCalledWith(expect.anything(), 'share-1', undefined);+ expect(data.goal).toEqual({+ requirement: 'Ship it',+ status: 'achieved',+ title: 'The goal',+ });+ expect(data.report?.headline).toBe('Done');+ expect(data.acceptance).toEqual({+ checks: [+ {+ passed: true,+ state: 'passed',+ summary: 'Read end to end',+ title: 'Report is readable',+ },+ ],+ status: 'accepted',+ });+ expect(data.isOwner).toBe(false);+ expect(mockIncrementViewCount).toHaveBeenCalledWith(expect.anything(), 'share-1');++ const json = JSON.stringify(data);+ for (const leaked of [+ creatorId,+ 'tpc_secret',+ 'task_secret',+ 'op_leak',+ 'op_secret',+ 'agt_assignee',+ 'internal question',+ 'cursor',+ 'acc-1',+ ]) {+ expect(json, leaked).not.toContain(leaked);+ }+ for (const key of ['spend', 'config', 'events', 'decisions', 'assignees', 'runHeartbeats']) {+ expect(data, key).not.toHaveProperty(key);+ }+ });++ it('reads the goal as the share owner, not the visitor', async () => {+ mockFindWithAccessCheck.mockResolvedValue({ ...share, workspaceId });+ const { GoalService } = await import('@/server/services/goal');+ const { AcceptanceService } = await import('@/server/services/verify');+ const caller = goalShareRouter.createCaller({ userId: 'someone-else' } as any);++ await caller.getSharedGoal({ shareId: 'share-1' });++ expect(GoalService).toHaveBeenCalledWith(expect.anything(), creatorId, workspaceId);+ expect(AcceptanceService).toHaveBeenCalledWith(expect.anything(), creatorId, workspaceId);+ });++ it('does not count the owner viewing their own share', async () => {+ mockFindWithAccessCheck.mockResolvedValue(share);+ const caller = goalShareRouter.createCaller({ userId: creatorId } as any);++ const { data } = await caller.getSharedGoal({ shareId: 'share-1' });++ expect(data.isOwner).toBe(true);+ expect(mockIncrementViewCount).not.toHaveBeenCalled();+ });++ it('propagates the access check refusal for a private share', async () => {+ const { TRPCError } = await import('@trpc/server');+ mockFindWithAccessCheck.mockRejectedValue(+ new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' }),+ );+ const caller = goalShareRouter.createCaller({} as any);++ await expect(caller.getSharedGoal({ shareId: 'share-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockGraph).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/sharedGoalAcceptances.ts b/apps/server/src/routers/lambda/_helpers/sharedGoalAcceptances.tsnew file mode 100644index 00000000000..e5e624f57b8--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/sharedGoalAcceptances.ts@@ -0,0 +1,60 @@+import type { GoalNodeAcceptance } from '@lobechat/types';+import pMap from 'p-map';++import type { LobeChatDatabase } from '@/database/type';+import { AcceptanceService, buildAcceptanceCheckUnion } from '@/server/services/verify';++import type { SharedGoalAcceptanceInput } from './sharedGoalView';++/** Cap on concurrent acceptance reads while building one shared view. */+const ACCEPTANCE_READ_CONCURRENCY = 5;++/**+ * Read each node's Acceptance as criterion / verdict / summary rows.+ *+ * Runs AS the share owner: the visitor owns nothing, so the acceptance models'+ * ownership scope has to be the owner's. The access decision was already made+ * by `findByShareIdWithAccessCheck`.+ */+export const readSharedGoalAcceptances = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string },+ nodeAcceptances: Record<string, GoalNodeAcceptance> | undefined,+): Promise<{+ acceptances: Record<string, SharedGoalAcceptanceInput>;+ nodeAcceptanceIds: Record<string, string>;+}> => {+ const nodeAcceptanceIds: Record<string, string> = {};+ for (const [nodeId, acceptance] of Object.entries(nodeAcceptances ?? {})) {+ nodeAcceptanceIds[nodeId] = acceptance.id;+ }++ const service = new AcceptanceService(db, owner.userId, owner.workspaceId);+ const entries = await pMap(+ Object.values(nodeAcceptances ?? {}),+ async ({ id, status }): Promise<[string, SharedGoalAcceptanceInput]> => {+ const { results, runs } = await service.loadRounds(id);+ const checks = buildAcceptanceCheckUnion(+ runs.map((run) => ({+ results: results.filter((result) => result.verifyRunId === run.id),+ run,+ })),+ );+ return [+ id,+ {+ checks: checks.map((check) => ({+ passed: check.state === 'passed',+ state: check.state,+ summary: check.result?.toulmin?.reasoning ?? null,+ title: check.title,+ })),+ status,+ },+ ];+ },+ { concurrency: ACCEPTANCE_READ_CONCURRENCY },+ );++ return { acceptances: Object.fromEntries(entries), nodeAcceptanceIds };+};diff --git a/apps/server/src/routers/lambda/_helpers/sharedGoalView.test.ts b/apps/server/src/routers/lambda/_helpers/sharedGoalView.test.tsnew file mode 100644index 00000000000..52e05495e27--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/sharedGoalView.test.ts@@ -0,0 +1,246 @@+// @vitest-environment node+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { describe, expect, it } from 'vitest';++import { buildSharedGoalView, type SharedGoalAcceptanceInput } from './sharedGoalView';++const at = (minute: number) => new Date(Date.UTC(2026, 0, 1, 0, minute));++const node = (id: string, minute: number, extra: Record<string, unknown> = {}) => ({+ confidence: null,+ createdAt: at(minute),+ createdByAgentId: 'agt_secret',+ createdByUserId: 'user_secret',+ description: 'internal description',+ goalId: 'goal_1',+ id,+ kind: 'task',+ priority: 1,+ resolvedAt: null,+ status: 'resolved',+ taskId: `task_for_${id}`,+ title: `Step ${id.length}`,+ updatedAt: at(minute),+ ...extra,+});++const edge = (id: string, source: string, target: string, kind = 'depends_on') => ({+ createdAt: at(0),+ goalId: 'goal_1',+ id,+ kind,+ sourceNodeId: source,+ targetNodeId: target,+});++const accepted: SharedGoalAcceptanceInput = {+ checks: [+ { passed: true, state: 'passed', summary: 'Looks right', title: 'Report renders' },+ { passed: false, state: 'failed', summary: null, title: 'Graph is drawn' },+ ],+ status: 'accepted',+};++const buildGraph = () =>+ ({+ acceptances: { node_a: { id: 'acc_secret', status: 'accepted' } },+ assignees: { node_a: 'agt_assignee' },+ decisions: [{ id: 'dec_1', question: 'secret decision', requestedUserId: 'user_x' }],+ edges: [edge('edge_1', 'node_b', 'node_a'), edge('edge_2', 'node_a', 'node_zzz')],+ events: [{ id: 'evt_1', operationId: 'op_secret', taskId: 'task_x' }],+ goal: {+ config: { budget: { maxCost: 99 } },+ id: 'goal_1',+ requirement: 'Ship the thing',+ spendLimit: 12,+ status: 'achieved',+ title: 'My goal',+ topicId: 'tpc_secret',+ userId: 'user_owner',+ },+ nodes: [+ node('node_b', 2),+ node('node_a', 1),+ node('node_acc', 3, { title: GOAL_ACCEPTANCE_TASK_TITLE }),+ ],+ report: {+ dispatch: { acceptanceKey: 'k', dispatchedAt: 'x', nodeId: 'node_a', operationId: 'op_leak' },+ latest: {+ content: 'markdown body',+ createdAt: at(5),+ metadata: {+ chapters: [+ {+ detours: [+ {+ kind: 'dead_end',+ lesson: 'lesson',+ nodeIds: ['node_b', 'node_unknown'],+ reason: 'reason',+ title: 'detour',+ },+ ],+ findingIds: ['node_b'],+ narrative: 'It went well',+ nodeIds: ['node_a', 'node_unknown'],+ title: 'Chapter 1',+ workVersionIds: ['wv_secret'],+ },+ ],+ deliverableWorkId: 'work_1',+ graphCursor: 'evt_cursor_secret',+ headline: 'Done',+ mainline: { edgeIds: ['edge_1', 'edge_missing'], nodeIds: ['node_a', 'node_b'] },+ nextSteps: [{ nodeIds: ['node_b'], reason: 'because', title: 'Next' }],+ },+ pageDocumentId: 'docs_secret',+ version: 3,+ workId: 'work_internal',+ workVersionId: 'wv_internal',+ },+ status: 'completed',+ },+ runHeartbeats: { node_a: at(9) },+ spend: { byTask: [], runs: 4, totalCost: 3.5, totalTokens: 1000 },+ workVersions: [],+ }) as any;++describe('buildSharedGoalView', () => {+ const nodeAcceptanceIds = { node_a: 'acc_secret', node_acc: 'acc_goal' };+ const acceptances = { acc_goal: accepted, acc_secret: accepted };++ it('keeps title, requirement and status of the goal', () => {+ const view = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);++ expect(view.goal).toEqual({+ requirement: 'Ship the thing',+ status: 'achieved',+ title: 'My goal',+ });+ });++ it('never carries any forbidden field or internal id, at any depth', () => {+ const view = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);+ const json = JSON.stringify(view);++ for (const forbidden of [+ 'userId',+ 'createdByUserId',+ 'createdByAgentId',+ 'cost',+ 'Cost',+ 'budget',+ 'spend',+ 'config',+ 'events',+ 'decisions',+ 'assignees',+ 'runHeartbeats',+ 'taskId',+ 'topicId',+ 'operationId',+ 'graphCursor',+ 'workVersionId',+ 'pageDocumentId',+ 'description',+ ]) {+ expect(json, forbidden).not.toContain(`"${forbidden}"`);+ }+ for (const leaked of [+ 'user_owner',+ 'user_secret',+ 'agt_secret',+ 'agt_assignee',+ 'tpc_secret',+ 'op_leak',+ 'op_secret',+ 'task_for_',+ 'acc_secret',+ 'wv_secret',+ 'wv_internal',+ 'work_internal',+ 'docs_secret',+ 'evt_cursor_secret',+ 'secret decision',+ 'node_a',+ 'edge_1',+ ]) {+ expect(json, leaked).not.toContain(leaked);+ }+ });++ it('exposes only kind / title / status / dependencies on graph nodes', () => {+ const view = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);++ expect(view.nodes.map((n) => Object.keys(n).sort())).toEqual([+ ['acceptance', 'dependsOn', 'id', 'kind', 'status', 'title'],+ ['dependsOn', 'id', 'kind', 'status', 'title'],+ ['acceptance', 'dependsOn', 'id', 'kind', 'status', 'title'],+ ]);+ // node_b depends on node_a; ids are view-local, ordered by creation.+ expect(view.nodes.map((n) => [n.id, n.dependsOn])).toEqual([+ ['n1', []],+ ['n2', ['n1']],+ ['n3', []],+ ]);+ });++ it('drops edges that leave the shared graph and remaps the rest', () => {+ const view = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);++ expect(view.edges).toEqual([{ from: 'n2', id: 'e1', kind: 'depends_on', to: 'n1' }]);+ });++ it('keeps the report narrative with mainline references remapped', () => {+ const { report } = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);++ expect(report).toMatchObject({+ deliverableWorkId: 'work_1',+ headline: 'Done',+ mainline: { edgeIds: ['e1'], nodeIds: ['n1', 'n2'] },+ nextSteps: [{ nodeIds: ['n2'], reason: 'because', title: 'Next' }],+ });+ expect(report?.chapters[0]).toMatchObject({+ findingIds: ['n2'],+ narrative: 'It went well',+ nodeIds: ['n1'],+ title: 'Chapter 1',+ });+ expect(report?.chapters[0]?.detours[0]?.nodeIds).toEqual(['n2']);+ });++ it('returns per-node and Goal-level Acceptance with criterion, verdict and summary', () => {+ const view = buildSharedGoalView(buildGraph(), acceptances, nodeAcceptanceIds);++ expect(view.nodes[0]?.acceptance).toEqual(accepted);+ expect(view.nodes[1]?.acceptance).toBeUndefined();+ expect(view.acceptance).toEqual(accepted);+ });++ it('never copies fields the acceptance reader attached beyond the allow-list', () => {+ const leaky = {+ checks: [{ passed: true, resultId: 'res_secret', state: 'passed', summary: 's', title: 't' }],+ id: 'acc_secret',+ status: 'accepted',+ userId: 'user_owner',+ } as unknown as SharedGoalAcceptanceInput;+ const view = buildSharedGoalView(buildGraph(), { acc_goal: leaky }, nodeAcceptanceIds);+ const json = JSON.stringify(view);++ expect(json).not.toContain('res_secret');+ expect(json).not.toContain('user_owner');+ expect(view.acceptance).toEqual({+ checks: [{ passed: true, state: 'passed', summary: 's', title: 't' }],+ status: 'accepted',+ });+ });++ it('has no report or Goal acceptance when none exists', () => {+ const graph = buildGraph();+ graph.report = undefined;+ const view = buildSharedGoalView(graph, {}, {});++ expect(view.report).toBeNull();+ expect(view.acceptance).toBeNull();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/sharedGoalView.ts b/apps/server/src/routers/lambda/_helpers/sharedGoalView.tsnew file mode 100644index 00000000000..825d221c818--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/sharedGoalView.ts@@ -0,0 +1,198 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import type {+ GoalEdgeKind,+ GoalGraphSnapshot,+ GoalNodeKind,+ GoalNodeStatus,+ GoalReportDetourKind,+ GoalStatus,+} from '@lobechat/types';++/** One verified criterion of an Acceptance, as a visitor reads it. */+export interface SharedGoalCheck {+ /** `passed` when the criterion held; every other state reads as not (yet) passed. */+ passed: boolean;+ state: 'failed' | 'not_executed' | 'passed' | 'uncertain';+ /** The verifier's reasoning for the verdict, when it wrote one. */+ summary: string | null;+ /** The criterion text. */+ title: string;+}++export interface SharedGoalAcceptance {+ checks: SharedGoalCheck[];+ status: string;+}++/** What the server read for one Acceptance — the redaction's only input about it. */+export type SharedGoalAcceptanceInput = SharedGoalAcceptance;++export interface SharedGoalNode {+ acceptance?: SharedGoalAcceptance;+ /** Opaque, view-local ids of the nodes this one depends on. */+ dependsOn: string[];+ /** View-local id (`n1`, `n2`, …): the graph's real ids never leave the server. */+ id: string;+ kind: GoalNodeKind;+ status: GoalNodeStatus;+ title: string;+}++export interface SharedGoalEdge {+ from: string;+ id: string;+ kind: GoalEdgeKind;+ to: string;+}++export interface SharedGoalReport {+ chapters: {+ detours: {+ kind: GoalReportDetourKind;+ lesson: string;+ nodeIds: string[];+ reason: string;+ title: string;+ }[];+ findingIds: string[];+ narrative: string;+ nodeIds: string[];+ title: string;+ }[];+ deliverableWorkId?: string;+ headline: string;+ mainline?: { edgeIds: string[]; nodeIds: string[] };+ nextSteps: { nodeIds?: string[]; reason: string; title: string }[];+}++export interface SharedGoalView {+ /** The Goal-level acceptance (the node that closes the Goal), when it has been judged. */+ acceptance: SharedGoalAcceptance | null;+ edges: SharedGoalEdge[];+ goal: { requirement: string | null; status: GoalStatus; title: string };+ nodes: SharedGoalNode[];+ report: SharedGoalReport | null;+}++/**+ * The read-only view an anonymous visitor gets of a shared Goal.+ *+ * Built by copying an explicit allow-list of fields out of the graph rather+ * than deleting the sensitive ones, so a field added to the snapshot later is+ * private until someone decides otherwise. Everything that identifies an owner,+ * a run or money — user ids, cost and budget, config, events, decisions,+ * assignees, heartbeats, task / topic / operation ids — is never read. Node and+ * edge ids are replaced with view-local ones because the real ids are internal;+ * the report's references to nodes are remapped the same way and dropped when+ * they point outside the shared graph.+ */+export const buildSharedGoalView = (+ graph: Pick<GoalGraphSnapshot, 'edges' | 'goal' | 'nodes' | 'report'>,+ /** Acceptance read per real acceptance id; `nodeAcceptanceIds` maps node → acceptance. */+ acceptances: Record<string, SharedGoalAcceptanceInput>,+ nodeAcceptanceIds: Record<string, string>,+): SharedGoalView => {+ const ordered = [...graph.nodes].sort(+ (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),+ );+ const nodeIds = new Map(ordered.map((node, index) => [node.id, `n${index + 1}`]));+ const mapNodes = (ids: string[] | undefined) =>+ (ids ?? []).flatMap((id) => {+ const mapped = nodeIds.get(id);+ return mapped ? [mapped] : [];+ });++ const edges: SharedGoalEdge[] = [];+ const edgeIds = new Map<string, string>();+ for (const edge of graph.edges) {+ const from = nodeIds.get(edge.sourceNodeId);+ const to = nodeIds.get(edge.targetNodeId);+ if (!from || !to) continue;+ const id = `e${edgeIds.size + 1}`;+ edgeIds.set(edge.id, id);+ edges.push({ from, id, kind: edge.kind, to });+ }++ const acceptanceOf = (nodeId: string) => {+ const acceptanceId = nodeAcceptanceIds[nodeId];+ const found = acceptanceId ? acceptances[acceptanceId] : undefined;+ return found+ ? {+ checks: found.checks.map((check) => ({+ passed: check.passed,+ state: check.state,+ summary: check.summary,+ title: check.title,+ })),+ status: found.status,+ }+ : undefined;+ };++ const nodes: SharedGoalNode[] = ordered.map((node) => {+ const acceptance = acceptanceOf(node.id);+ return {+ ...(acceptance ? { acceptance } : {}),+ dependsOn: graph.edges+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === node.id)+ .flatMap((edge) => mapNodes([edge.targetNodeId])),+ id: nodeIds.get(node.id)!,+ kind: node.kind,+ status: node.status,+ title: node.title,+ };+ });++ const goalAcceptanceNode = graph.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,+ );++ const latest = graph.report?.latest?.metadata;+ const report: SharedGoalReport | null = latest+ ? {+ chapters: latest.chapters.map((chapter) => ({+ detours: chapter.detours.map((detour) => ({+ kind: detour.kind,+ lesson: detour.lesson,+ nodeIds: mapNodes(detour.nodeIds),+ reason: detour.reason,+ title: detour.title,+ })),+ findingIds: mapNodes(chapter.findingIds),+ narrative: chapter.narrative,+ nodeIds: mapNodes(chapter.nodeIds),+ title: chapter.title,+ })),+ ...(latest.deliverableWorkId ? { deliverableWorkId: latest.deliverableWorkId } : {}),+ headline: latest.headline,+ ...(latest.mainline+ ? {+ mainline: {+ edgeIds: (latest.mainline.edgeIds ?? []).flatMap((id) => {+ const mapped = edgeIds.get(id);+ return mapped ? [mapped] : [];+ }),+ nodeIds: mapNodes(latest.mainline.nodeIds),+ },+ }+ : {}),+ nextSteps: latest.nextSteps.map((step) => ({+ ...(step.nodeIds ? { nodeIds: mapNodes(step.nodeIds) } : {}),+ reason: step.reason,+ title: step.title,+ })),+ }+ : null;++ return {+ acceptance: goalAcceptanceNode ? (acceptanceOf(goalAcceptanceNode.id) ?? null) : null,+ edges,+ goal: {+ requirement: graph.goal.requirement,+ status: graph.goal.status,+ title: graph.goal.title,+ },+ nodes,+ report,+ };+};diff --git a/apps/server/src/routers/lambda/goalShare.ts b/apps/server/src/routers/lambda/goalShare.tsnew file mode 100644index 00000000000..b86552f5066--- /dev/null+++ b/apps/server/src/routers/lambda/goalShare.ts@@ -0,0 +1,175 @@+import { GOAL_GRAPH_CAPABILITY } from '@lobechat/const/goal';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { GoalShareModel } from '@/database/models/goalShare';+import { publicProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { GoalService } from '@/server/services/goal';+import { graphForClient } from '@/server/services/goal/graphCompat';++import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { readSharedGoalAcceptances } from './_helpers/sharedGoalAcceptances';+import { buildSharedGoalView } from './_helpers/sharedGoalView';+import { goalProcedure, mapGoalError } from './goalProcedures';++const visibilitySchema = z.enum(['private', 'link']);+const goalIdInput = z.object({ goalId: z.string().trim().min(1) });++/**+ * The goal the caller may manage a share for: its creator, or a workspace+ * owner. A goal the caller cannot see at all reads as NOT_FOUND.+ */+const requireManageableGoal = async (+ ctx: {+ goalModel: { findById: (id: string) => Promise<{ userId: string } | undefined> };+ userId: string;+ workspaceId?: string | null;+ workspaceRole?: string;+ },+ goalId: string,+) => {+ const goal = await ctx.goalModel.findById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal share');+ return goal;+};++const goalShareProcedure = goalProcedure.use(async (opts) =>+ opts.next({+ ctx: {+ goalShareModel: new GoalShareModel(+ opts.ctx.serverDB,+ opts.ctx.userId,+ opts.ctx.workspaceId ?? undefined,+ ),+ },+ }),+);++export const goalShareRouter = router({+ /** Remove the share link (deletes the share record). */+ disable: goalShareProcedure+ .use(withScopedPermission('agent:update'))+ .input(goalIdInput)+ .mutation(async ({ ctx, input }) => {+ try {+ await requireManageableGoal(ctx, input.goalId);+ await ctx.goalShareModel.deleteByGoalId(input.goalId);+ return { success: true };+ } catch (error) {+ mapGoalError(error, 'disable share for');+ }+ }),++ /**+ * Create (or reuse) the share of a finished goal. A goal with no wrap-up+ * report has nothing to show a visitor, so it is refused rather than+ * publishing an empty page.+ */+ enable: goalShareProcedure+ .use(withScopedPermission('agent:update'))+ .input(goalIdInput.extend({ visibility: visibilitySchema.default('private') }))+ .mutation(async ({ ctx, input }) => {+ try {+ await requireManageableGoal(ctx, input.goalId);++ const { report } = await ctx.goalService.graph(input.goalId);+ if (!report?.latest) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'This goal has no wrap-up report yet — there is nothing finished to share',+ });+ }++ const created = await ctx.goalShareModel.create(input.goalId, input.visibility);+ // `create` keeps an existing record as is; an explicit visibility on a+ // re-enable still has to win.+ const share =+ created && created.visibility !== input.visibility+ ? await ctx.goalShareModel.updateVisibility(input.goalId, input.visibility)+ : created;+ return { data: share, success: true };+ } catch (error) {+ mapGoalError(error, 'enable share for');+ }+ }),++ /** The share record of a goal, or null when it is not shared. */+ getInfo: goalShareProcedure.input(goalIdInput).query(async ({ ctx, input }) => {+ try {+ await requireManageableGoal(ctx, input.goalId);+ return { data: await ctx.goalShareModel.getByGoalId(input.goalId), success: true };+ } catch (error) {+ mapGoalError(error, 'read share for');+ }+ }),++ /**+ * The redacted public view of a shared goal. Anyone with the link reads a+ * `link` share; a `private` one is the owner's alone. The read runs as the+ * share owner, never as the visitor.+ */+ getSharedGoal: publicProcedure+ .use(serverDatabase)+ .input(+ z.object({+ /** Graph features the viewer renders (see `GOAL_GRAPH_CAPABILITY`). */+ capabilities: z.array(z.string()).max(20).optional(),+ shareId: z.string().trim().min(1),+ }),+ )+ .query(async ({ ctx, input }) => {+ const share = await GoalShareModel.findByShareIdWithAccessCheck(+ ctx.serverDB,+ input.shareId,+ ctx.userId ?? undefined,+ );+ const owner = { userId: share.ownerId, workspaceId: share.workspaceId ?? undefined };+ const isOwner = !!ctx.userId && share.ownerId === ctx.userId;++ try {+ const graph = graphForClient(+ await new GoalService(ctx.serverDB, owner.userId, owner.workspaceId).graph(share.goalId),+ input.capabilities ?? [GOAL_GRAPH_CAPABILITY.batch],+ );+ const { acceptances, nodeAcceptanceIds } = await readSharedGoalAcceptances(+ ctx.serverDB,+ owner,+ graph.acceptances,+ );++ if (!isOwner) {+ // A counter must never break the page it counts.+ await GoalShareModel.incrementViewCount(ctx.serverDB, share.shareId).catch(() => {});+ }++ return {+ data: {+ ...buildSharedGoalView(graph, acceptances, nodeAcceptanceIds),+ isOwner,+ visibility: share.visibility,+ },+ success: true,+ };+ } catch (error) {+ mapGoalError(error, 'read shared');+ }+ }),++ /** Change who can open the link. */+ setVisibility: goalShareProcedure+ .use(withScopedPermission('agent:update'))+ .input(goalIdInput.extend({ visibility: visibilitySchema }))+ .mutation(async ({ ctx, input }) => {+ try {+ await requireManageableGoal(ctx, input.goalId);+ const share = await ctx.goalShareModel.updateVisibility(input.goalId, input.visibility);+ if (!share) throw new TRPCError({ code: 'NOT_FOUND', message: 'This goal is not shared' });+ return { data: share, success: true };+ } catch (error) {+ mapGoalError(error, 'update share for');+ }+ }),+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex c44cce46b91..faa63dd9fd4 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -74,6 +74,7 @@ import { generationRouter } from './generation';import { generationBatchRouter } from './generationBatch';import { generationTopicRouter } from './generationTopic';import { goalRouter } from './goal';+import { goalShareRouter } from './goalShare';import { homeRouter } from './home';import { imageRouter } from './image';import { importerRouter } from './importer';@@ -180,6 +181,7 @@ export const lambdaRouter = router({generationBatch: generationBatchRouter,generationTopic: generationTopicRouter,goal: goalRouter,+ goalShare: goalShareRouter,group: agentGroupRouter,healthcheck: publicProcedure.query(() => "i'm live!"),home: homeRouter,diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 9b7a88a29b5..40a2095507a 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -263,6 +263,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRulegenerationBatch: { any: 'model:invoke' },generationTopic: { any: 'model:invoke' },goal: rw('agent:read', 'agent:write'),+ // a share link publishes the goal's wrap-up to anyone holding it; restricted+ // API keys must not flip it (full-access keys still can)+ goalShare: 'blocked',group: rw('agent:read', 'agent:write'),healthcheck: 'open',home: rw('chat:read', 'chat:write'),