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): readable batch plan skill names and a legible gate detail panel (#22737)

Arvin Xu12578658a78a
diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.ts
index dd7ab2bef9b..6b078c6ede4 100644
--- a/apps/cli/src/commands/goal/index.ts
+++ b/apps/cli/src/commands/goal/index.ts
@@ -497,9 +497,9 @@ export function registerGoalCommand(program: Command) {
'When the work applies one recipe to many units (migrate N stores to one mechanism, give N resources',
'the same caching, update N callers), declare a batch instead of listing every unit: add "rollout" with',
'"recipe" (the procedure every unit follows), "units" (every unit beyond the probes, as a title or',
- '{"title","description"}) and optional "variants" ([{"axis","values"}]); "tasks" then hold 2-5',
- 'representative probes. The probes run first; once they ran through without a person the owner approves',
- 'the first wave, and each later wave is handed to this agent to release or escalate; a rejected',
+ '{"title","description"}), optional "skillName" (kebab-case, what the recipe does) and "variants"',
+ '([{"axis","values"}]); "tasks" then hold 2-5 representative probes. The probes run first; once they',
+ 'ran through without a person the owner approves the first wave, and each later wave is handed to this agent to release or escalate; a rejected',
'release comes back to this agent to rewrite the plan for review. Units that differ',
'only in names, files or details are still one mould; work whose steps differ per task is not.',
].join('\n'),
diff --git a/apps/server/src/routers/lambda/goal/lifecycle.ts b/apps/server/src/routers/lambda/goal/lifecycle.ts
index 6cbab5e7fad..547f16b098a 100644
--- a/apps/server/src/routers/lambda/goal/lifecycle.ts
+++ b/apps/server/src/routers/lambda/goal/lifecycle.ts
@@ -26,6 +26,7 @@ const startRolloutInput = z
.object({
probeNodeIds: z.array(z.string().min(1)).min(2).max(10),
recipe: z.string().trim().min(1).max(8000),
+ skillName: z.string().trim().max(80).optional(),
trigger: z.enum(['canary', 'full']).optional(),
unitNodeIds: z.array(z.string().min(1)).max(60).optional(),
variants: z
diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
index 4545f8692e6..3957c2efbe7 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts
@@ -95,8 +95,9 @@ describe('GoalService', () => {
// The plan lives as a skill in the user's library: v1 at decomposition,
// v2 when the break revised it — each version kept whole.
+ // Named after the goal ("Migrate stores"), not the batch id.
const planSkill = next.planSkill!;
- expect(planSkill.name).toMatch(/^goal-plan-/);
+ expect(planSkill.name).toBe('migrate-stores-plan');
const skills = new UserSkillService(serverDB, userId);
const skill = await skills.getSkill(planSkill.id);
expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);
diff --git a/apps/server/src/services/goal/batchPlanSkill.test.ts b/apps/server/src/services/goal/batchPlanSkill.test.ts
index 67d7f2dcfd1..a6c231147e0 100644
--- a/apps/server/src/services/goal/batchPlanSkill.test.ts
+++ b/apps/server/src/services/goal/batchPlanSkill.test.ts
@@ -3,9 +3,36 @@ import { describe, expect, it } from 'vitest';
import { learnedRulesClause, planSkillName, planUnitBrief } from './batchPlanSkill';
describe('planSkillName', () => {
- it('turns a node id into a short, valid skill name', () => {
- expect(planSkillName('13b47c2a-5b56-4e8d-b53a-41e2b418d58a')).toBe('goal-plan-13b47c2a');
- expect(planSkillName('gnd_AbC123xyz')).toBe('goal-plan-gndabc12');
+ const batchNodeId = '2e351018-5b56-4e8d-b53a-41e2b418d58a';
+
+ it("uses the planner's name, slugged into a valid skill name", () => {
+ expect(planSkillName({ batchNodeId, name: 'Migrate store reads to Replica' })).toBe(
+ 'migrate-store-reads-to-replica',
+ );
+ });
+
+ /**
+ * Regression: the plan skill was named after the batch id
+ * (`goal-plan-2e351018`), which says nothing in the library or in a unit's
+ * brief about what the plan does.
+ */
+ it('falls back to the words of the goal title rather than the batch id', () => {
+ expect(
+ planSkillName({ batchNodeId, goalTitle: '客户端读取全量迁移到 replica(STAMP v2)' }),
+ ).toBe('replica-stamp-v2-plan');
+ });
+
+ it('cuts a long name at a word', () => {
+ const name = planSkillName({ batchNodeId, name: 'word '.repeat(20) });
+ expect(name.length).toBeLessThanOrEqual(48);
+ expect(name).toMatch(/^word(-word)*$/);
+ });
+
+ it('keeps the batch id only when nothing reads as words', () => {
+ expect(planSkillName({ batchNodeId, goalTitle: '首页迁移', name: 'v2' })).toBe(
+ 'goal-plan-2e351018',
+ );
+ expect(planSkillName({ batchNodeId: 'gnd_AbC123xyz' })).toBe('goal-plan-gndabc12');
});
});
diff --git a/apps/server/src/services/goal/batchPlanSkill.ts b/apps/server/src/services/goal/batchPlanSkill.ts
index a1ae1bcae89..7d07dae460f 100644
--- a/apps/server/src/services/goal/batchPlanSkill.ts
+++ b/apps/server/src/services/goal/batchPlanSkill.ts
@@ -28,15 +28,47 @@ const oneLine = (text: string, max: number) => {
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
};
+/** Longest a plan skill name runs before it is cut at a word. */
+const MAX_NAME = 48;
+
+/** Lowercase ASCII words of `text` as a slug, cut at a word within `MAX_NAME`. */
+const slugWords = (text: string) => {
+ let slug = '';
+ for (const word of text
+ .normalize('NFKD')
+ .toLowerCase()
+ .split(/[^\da-z]+/)) {
+ if (!word) continue;
+ const next = slug ? `${slug}-${word}` : word;
+ if (next.length > MAX_NAME) break;
+ slug = next;
+ }
+ return slug;
+};
+
+/** A slug carries meaning when it holds a word, not only a version or an id. */
+const isReadable = (slug: string) => /[a-z]{3}/.test(slug);
+
/**
- * A short skill name for a batch: `goal-plan-` and the first characters of its
- * id. The library keeps names unique, suffixing a clash.
+ * The batch's skill name, read in the user's library and in every unit's brief,
+ * so it says what the plan does: the name the planner gave it, else the ASCII
+ * words of the goal title, and only when neither reads as words the batch id.
+ * The library keeps names unique, suffixing a clash.
*/
-export const planSkillName = (batchNodeId: string) =>
- `goal-plan-${batchNodeId
+export const planSkillName = (params: {
+ batchNodeId: string;
+ goalTitle?: string;
+ name?: string;
+}) => {
+ const named = slugWords(params.name ?? '');
+ if (isReadable(named)) return named;
+ const fromTitle = slugWords(params.goalTitle ?? '');
+ if (isReadable(fromTitle)) return `${fromTitle}-plan`;
+ return `goal-plan-${params.batchNodeId
.toLowerCase()
.replaceAll(/[^\da-z]+/g, '')
.slice(0, 8)}`;
+};
export const planSkillIdentifier = (skill: GoalRolloutPlanSkill) =>
buildUserSkillIdentifier(skill.name);
@@ -96,6 +128,8 @@ export class BatchPlanSkillService {
batchNodeId: string;
goalId: string;
goalTitle: string;
+ /** The planner's slug for the plan; see {@link planSkillName}. */
+ name?: string;
plan: string;
}): Promise<GoalRolloutPlanSkill> => {
const skill = await new UserSkillService(this.db, this.userId, this.workspaceId).createSkill({
@@ -104,7 +138,7 @@ export class BatchPlanSkillService {
`How each unit of "${params.goalTitle}" is done. Revised whenever the batch's release gate sends it back.`,
MAX_DESCRIPTION,
),
- name: planSkillName(params.batchNodeId),
+ name: planSkillName(params),
origin: { batchNodeId: params.batchNodeId, goalId: params.goalId, revision: 1 },
title: oneLine(params.goalTitle, MAX_TITLE),
});
diff --git a/apps/server/src/services/goal/manager/planSchema.ts b/apps/server/src/services/goal/manager/planSchema.ts
index 6e9606533b6..f9213bde361 100644
--- a/apps/server/src/services/goal/manager/planSchema.ts
+++ b/apps/server/src/services/goal/manager/planSchema.ts
@@ -63,6 +63,8 @@ export const planRolloutSchema = z
.object({
/** The one reusable recipe every unit follows; the batch's Template, revised on every break. */
recipe: reason,
+ /** A short kebab-case name for the plan skill saying what the recipe does (e.g. "migrate-store-to-replica"). */
+ skillName: z.string().trim().max(80).optional(),
/** Every unit after the probes in `tasks`, in delivery order; a unit may carry its own notes. */
units: z
.array(
diff --git a/apps/server/src/services/goal/manager/submit.ts b/apps/server/src/services/goal/manager/submit.ts
index bcf62e8f331..6ce81957ab0 100644
--- a/apps/server/src/services/goal/manager/submit.ts
+++ b/apps/server/src/services/goal/manager/submit.ts
@@ -90,6 +90,7 @@ const declareBatch = async (
planSkillOwner: {
db,
goalTitle: goal.title,
+ skillName: plan.rollout.skillName,
userId: ctx.userId,
workspaceId: ctx.workspaceId,
},
diff --git a/apps/server/src/services/goal/releaseGate.test.ts b/apps/server/src/services/goal/releaseGate.test.ts
new file mode 100644
index 00000000000..f9e8e062d1c
--- /dev/null
+++ b/apps/server/src/services/goal/releaseGate.test.ts
@@ -0,0 +1,130 @@
+import type { GoalGraphSnapshot } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { planUnitBrief } from './batchPlanSkill';
+import { buildReleaseGateDossier, withUnitWorks } from './releaseGate';
+
+const { listSummariesByIds } = vi.hoisted(() => ({ listSummariesByIds: vi.fn() }));
+vi.mock('@/database/models/work', () => ({
+ WorkModel: class {
+ listSummariesByIds = listSummariesByIds;
+ },
+}));
+
+const plan = {
+ outline: '# Recipe\n\nMove each read to the replica.',
+ skill: { id: 'skill_1', name: 'migrate-reads-to-replica' },
+};
+
+const graphWith = (
+ nodes: { description: string; id: string; title: string }[],
+ workVersions: unknown[] = [],
+) =>
+ ({
+ goal: {
+ config: {
+ rollout: { spec: { recipeOutline: plan.outline } },
+ rolloutState: {
+ batchNodeId: 'batch',
+ phase: 'probe',
+ probeNodeIds: nodes.map((node) => node.id),
+ waveIndex: 0,
+ },
+ },
+ title: 'Migrate reads',
+ },
+ nodes: nodes.map((node) => ({ ...node, status: 'resolved' })),
+ workVersions,
+ }) as unknown as GoalGraphSnapshot;
+
+describe('buildReleaseGateDossier', () => {
+ /**
+ * Regression: a unit's brief was its whole task description, so the review
+ * panel showed the plan-skill instruction and a second copy of the plan
+ * instead of what this unit itself had to do.
+ */
+ it("reports a unit's own brief, not the plan instruction every unit carries", () => {
+ const dossier = buildReleaseGateDossier(
+ graphWith([
+ { description: planUnitBrief('Home inbox', plan), id: 'n1', title: 'Home inbox' },
+ {
+ description: 'Migrate `useInbox`; cold start must render cached.',
+ id: 'n2',
+ title: 'Brief',
+ },
+ ]),
+ { kind: 'probes', waveSize: 5 },
+ );
+
+ expect(dossier?.units.find((unit) => unit.nodeId === 'n1')?.brief).toBeUndefined();
+ expect(dossier?.units.find((unit) => unit.nodeId === 'n2')?.brief).toBe(
+ 'Migrate `useInbox`; cold start must render cached.',
+ );
+ });
+
+ /**
+ * Regression: a unit's pull request reached the review as a bare title link,
+ * with no number or state, so the owner could not tell what to merge.
+ */
+ it("carries each output's reference and state", () => {
+ const dossier = buildReleaseGateDossier(
+ graphWith(
+ [{ description: 'Migrate inbox reads.', id: 'n1', title: 'Home inbox' }],
+ [
+ {
+ nodeId: 'n1',
+ work: {
+ identifier: '#22737',
+ resourceId: 'lobehub/lobehub#22737',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ title: 'Move inbox reads to replica',
+ type: 'external',
+ url: 'https://github.com/lobehub/lobehub/pull/22737',
+ workId: 'work_1',
+ },
+ },
+ ],
+ ),
+ { kind: 'probes', waveSize: 5 },
+ );
+
+ expect(dossier?.units[0].artifacts).toEqual([
+ {
+ identifier: '#22737',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ title: 'Move inbox reads to replica',
+ type: 'external',
+ url: 'https://github.com/lobehub/lobehub/pull/22737',
+ workId: 'work_1',
+ },
+ ]);
+ });
+});
+
+describe('withUnitWorks', () => {
+ const dossier = {
+ units: [
+ { artifacts: [{ title: 'PR', type: 'external', workId: 'work_1' }], nodeId: 'n1' },
+ { artifacts: [], nodeId: 'n2' },
+ ],
+ } as any;
+
+ /**
+ * Regression: the review drew its own output rows instead of the Work cards
+ * the conversation shows, because the dossier carried no Work summaries.
+ */
+ it("freezes each unit's outputs as Work summary cards", async () => {
+ listSummariesByIds.mockResolvedValueOnce([{ id: 'work_1', title: 'PR' }]);
+ const frozen = await withUnitWorks({} as any, { userId: 'u' }, dossier);
+ expect(listSummariesByIds).toHaveBeenCalledWith(['work_1']);
+ expect(frozen.units[0].works).toEqual([{ id: 'work_1', title: 'PR' }]);
+ expect(frozen.units[1].works).toBeUndefined();
+ });
+
+ it('keeps the plain artifact list when the read fails', async () => {
+ listSummariesByIds.mockRejectedValueOnce(new Error('db down'));
+ expect(await withUnitWorks({} as any, { userId: 'u' }, dossier)).toBe(dossier);
+ });
+});
diff --git a/apps/server/src/services/goal/releaseGate.ts b/apps/server/src/services/goal/releaseGate.ts
index 3ec8a132476..08e14169c70 100644
--- a/apps/server/src/services/goal/releaseGate.ts
+++ b/apps/server/src/services/goal/releaseGate.ts
@@ -10,9 +10,11 @@ import debug from 'debug';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyReportModel } from '@/database/models/verifyReport';
import { VerifyRunModel } from '@/database/models/verifyRun';
+import { WorkModel } from '@/database/models/work';
import type { LobeChatDatabase } from '@/database/type';
import { AcceptanceService } from '../verify/acceptanceService';
+import { carriedUnitBrief } from './rolloutBatch';
import type { RolloutGateResult } from './rolloutGate';
const log = debug('lobe-server:goal-release-gate');
@@ -63,6 +65,7 @@ export const buildReleaseGateDossier = (
if (!node) return [];
const spend = node.taskId ? spendByTask.get(node.taskId) : undefined;
const acceptance = graph.acceptances?.[nodeId];
+ const brief = carriedUnitBrief(node);
return [
{
...(acceptance && {
@@ -82,11 +85,17 @@ export const buildReleaseGateDossier = (
.map((link) => ({
...(link.work!.type === 'document' &&
link.work!.resourceId && { documentId: link.work!.resourceId }),
+ ...(link.work!.identifier && { identifier: link.work!.identifier }),
+ ...(link.work!.resourceType && { resourceType: link.work!.resourceType }),
+ ...(link.work!.status && { status: link.work!.status }),
title: link.work!.title ?? link.work!.identifier ?? '',
type: link.work!.type,
...(link.work!.url && { url: link.work!.url }),
+ workId: link.work!.workId,
})),
- ...(node.description && { brief: node.description }),
+ // The unit's own note, not the plan-skill instruction every unit
+ // carries: the plan itself is the dossier's first section.
+ ...(brief && { brief }),
nodeId,
runs: spend?.runs ?? 0,
status: node.status,
@@ -150,6 +159,42 @@ const gatePlan = (dossier: GoalReleaseGateDossier): VerifyCheckItem[] => {
];
};
+/**
+ * Freezes each unit's outputs the way the conversation's Work cards show them,
+ * so the review lists them with the same cards. Best-effort: a failed read
+ * leaves the dossier with its plain artifact list.
+ */
+export const withUnitWorks = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string },
+ dossier: GoalReleaseGateDossier,
+): Promise<GoalReleaseGateDossier> => {
+ const ids = dossier.units.flatMap((unit) =>
+ unit.artifacts.flatMap((artifact) => (artifact.workId ? [artifact.workId] : [])),
+ );
+ if (ids.length === 0) return dossier;
+ try {
+ const summaries = await new WorkModel(db, scope.userId, scope.workspaceId).listSummariesByIds(
+ ids,
+ );
+ const byId = new Map(summaries.map((summary) => [summary.id, summary]));
+ return {
+ ...dossier,
+ units: dossier.units.map((unit) => {
+ const workIds = new Set(unit.artifacts.map((artifact) => artifact.workId));
+ const works = [...workIds].flatMap((id) => {
+ const work = id && byId.get(id);
+ return work ? [work] : [];
+ });
+ return works.length ? { ...unit, works } : unit;
+ }),
+ };
+ } catch (error) {
+ log('release gate: unit works not read: %O', error);
+ return dossier;
+ }
+};
+
/**
* Open the acceptance a held release is reviewed on: one aggregate per gate
* node, one round carrying the frozen dossier, settled at once so the owner
@@ -180,7 +225,7 @@ export const openReleaseGateAcceptance = async (
const plan = gatePlan(dossier);
const run = await new VerifyRunModel(db, scope.userId, scope.workspaceId).create({
goal: requirement,
- metadata: { releaseGate: dossier },
+ metadata: { releaseGate: await withUnitWorks(db, scope, dossier) },
plan,
scenario: 'generic',
source: 'agent',
diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.ts
index f9282a5db55..675c3c71c03 100644
--- a/apps/server/src/services/goal/rolloutBatch.ts
+++ b/apps/server/src/services/goal/rolloutBatch.ts
@@ -265,6 +265,8 @@ export interface MaterializeRolloutBatchInput {
planSkillOwner?: {
db: LobeChatDatabase;
goalTitle: string;
+ /** The planner's short slug for the plan; derived from the goal title when absent. */
+ skillName?: string;
userId: string;
workspaceId?: string;
};
@@ -343,6 +345,7 @@ export const materializeRolloutBatch = async ({
batchNodeId: batch.id,
goalId,
goalTitle: planSkillOwner.goalTitle,
+ name: planSkillOwner.skillName,
plan: outline,
}),
);
diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.ts
index 35c3640d6b3..514f538d83f 100644
--- a/apps/server/src/services/goal/start.ts
+++ b/apps/server/src/services/goal/start.ts
@@ -20,6 +20,8 @@ export interface StartGoalRolloutInput {
probeNodeIds: string[];
/** The one procedure every unit follows; the batch's Template. */
recipe: string;
+ /** A short kebab-case name for the plan skill, saying what the recipe does. */
+ skillName?: string;
/** Overrides the goal's own `config.rollout.trigger`; `off` is not a way to start a batch. */
trigger?: 'canary' | 'full';
/** Seeds that become roster units; every other seed when omitted. Seeds left out stay ordinary tasks. */
@@ -298,6 +300,7 @@ export class GoalStartService {
planSkillOwner: {
db,
goalTitle: goal.title,
+ skillName: rollout.skillName,
userId: this.userId,
workspaceId: this.workspaceId,
},
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index ec13149a29e..1f882f263aa 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -283,6 +283,8 @@
"acceptance.gate.titleWave": "Release wave {{wave}}?",
"acceptance.gate.unitAcceptance": "Acceptance {{passed}}/{{total}}",
"acceptance.gate.unitAcceptanceOpen": "Open acceptance",
+ "acceptance.gate.unitArtifacts": "Outputs",
+ "acceptance.gate.unitArtifactsEmpty": "No outputs registered for this unit.",
"acceptance.gate.unitBrief": "What this unit does",
"acceptance.gate.unitCount": "{{count}} units",
"acceptance.gate.unitMeta": "{{runs}} run(s) · {{tokens}} tokens",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 8554d0d3434..99c5fd64dbe 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -283,6 +283,8 @@
"acceptance.gate.titleWave": "是否继续放出第 {{wave}} 批?",
"acceptance.gate.unitAcceptance": "验收 {{passed}}/{{total}}",
"acceptance.gate.unitAcceptanceOpen": "打开验收",
+ "acceptance.gate.unitArtifacts": "产出",
+ "acceptance.gate.unitArtifactsEmpty": "这一项没有登记产出。",
"acceptance.gate.unitBrief": "这一项要做什么",
"acceptance.gate.unitCount": "{{count}} 项",
"acceptance.gate.unitMeta": "{{runs}} 轮 · {{tokens}} token",
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index fcc86bb13e6..a181916c91d 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -305,6 +305,7 @@ export class GoalGraphModel {
// metadata rather than the `url` column.
metadata: workVersions.metadata,
resourceId: works.resourceId,
+ resourceType: works.resourceType,
status: workVersions.status,
title: workVersions.title,
type: works.type,
@@ -326,6 +327,7 @@ export class GoalGraphModel {
display.set(row.versionId, {
identifier: row.identifier,
resourceId: row.resourceId,
+ resourceType: row.resourceType,
status: row.status,
title: row.title,
type: row.type,
diff --git a/packages/database/src/models/work/__tests__/work.coverage.test.ts b/packages/database/src/models/work/__tests__/work.coverage.test.ts
index 161238dad07..89be7a83e78 100644
--- a/packages/database/src/models/work/__tests__/work.coverage.test.ts
+++ b/packages/database/src/models/work/__tests__/work.coverage.test.ts
@@ -250,6 +250,20 @@ describe('WorkModel coverage · facade', () => {
});
describe('WorkModel coverage · queries', () => {
+ it('lists summary cards by Work id, dropping ids the caller cannot see', async () => {
+ const mine = await model().registerExternal(
+ externalParams({ resourceId: 'LOB-ids-1', toolCallId: 'ids-1' }),
+ );
+ const theirs = await new WorkModel(serverDB, otherUserId).registerExternal(
+ externalParams({ resourceId: 'LOB-ids-2', toolCallId: 'ids-2' }),
+ );
+
+ const summaries = await model().listSummariesByIds([mine!.id, mine!.id, theirs!.id, '']);
+ expect(summaries.map((summary) => summary.id)).toEqual([mine!.id]);
+ expect(summaries[0]).toMatchObject({ resourceId: 'LOB-ids-1', type: 'external' });
+ expect(await model().listSummariesByIds([])).toEqual([]);
+ });
+
it('caps each root operation’s version events at the limit', async () => {
await model().registerExternal(
externalParams({ resourceId: 'LOB-cap-1', rootOperationId: 'op-cap', toolCallId: 'c1' }),
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index c9a129f21ce..b2e30dcb06d 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -201,6 +201,9 @@ export class WorkModel {
rootOperationIds?: string[] | null;
}) => queries.listByRootOperations(this.ctx, params);
+ /** See {@link queries.listSummariesByIds}. */
+ listSummariesByIds = (workIds: string[]) => queries.listSummariesByIds(this.ctx, workIds);
+
listSummariesByRootOperations = (params: {
includeFileWorks?: boolean;
limit?: number;
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index 0da9de0bec3..9dc40daddb8 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -120,6 +120,50 @@ export const listByRootOperations = async (
return result;
};
+/** Summary cards of these Works, newest first; Works the caller cannot see drop out. */
+const summariesOf = async (ctx: WorkContext, workIds: string[]): Promise<WorkSummaryItem[]> => {
+ const rows = await ctx.db
+ .select({
+ event: currentVersionEventSelection,
+ ...currentTaskSummaryFields,
+ resourceDeleted: resourceDeletedField,
+ version: {
+ createdAt: currentVersions.createdAt,
+ id: currentVersions.id,
+ version: currentVersions.version,
+ },
+ work: currentWorkListFields,
+ })
+ .from(works)
+ .innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
+ .leftJoin(tasks, taskSummaryJoin(ctx))
+ // LEFT JOIN, like the tasks one: an orphaned document Work (backing row
+ // hard-deleted outside the tool path) must still surface, so the UI can
+ // render it as "document deleted" and offer removal instead of showing a
+ // live-looking card that 404s on click.
+ .leftJoin(documents, documentSummaryJoin)
+ .where(and(workOwnership(ctx), inArray(works.id, workIds)))
+ .orderBy(desc(works.updatedAt), desc(works.id));
+
+ const costByWorkId = await getTotalCostByWorkIds(
+ ctx,
+ rows.map((row) => row.work.id),
+ );
+
+ return rows.map((row) =>
+ WORK_TYPE_ADAPTERS[row.work.type].mapCurrentRow(row, costByWorkId.get(row.work.id) ?? null),
+ );
+};
+
+/** Summary cards of the given Works, as the conversation shows them; unknown or hidden ids drop out. */
+export const listSummariesByIds = async (
+ ctx: WorkContext,
+ workIds: string[],
+): Promise<WorkSummaryItem[]> => {
+ const ids = [...new Set(workIds.filter(Boolean))];
+ return ids.length ? summariesOf(ctx, ids) : [];
+};
+
export const listSummariesByRootOperations = async (
ctx: WorkContext,
params: {
@@ -171,37 +215,7 @@ export const listSummariesByRootOperations = async (
}
if (anchorByWorkId.size === 0) return result;
- const rows = await ctx.db
- .select({
- event: currentVersionEventSelection,
- ...currentTaskSummaryFields,
- resourceDeleted: resourceDeletedField,
- version: {
- createdAt: currentVersions.createdAt,
- id: currentVersions.id,
- version: currentVersions.version,
- },
- work: currentWorkListFields,
- })
- .from(works)
- .innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
- .leftJoin(tasks, taskSummaryJoin(ctx))
- // LEFT JOIN, like the tasks one: an orphaned document Work (backing row
- // hard-deleted outside the tool path) must still surface, so the UI can
- // render it as "document deleted" and offer removal instead of showing a
- // live-looking card that 404s on click.
- .leftJoin(documents, documentSummaryJoin)
- .where(and(workOwnership(ctx), inArray(works.id, Array.from(anchorByWorkId.keys()))))
- .orderBy(desc(works.updatedAt), desc(works.id));
-
- const costByWorkId = await getTotalCostByWorkIds(
- ctx,
- rows.map((row) => row.work.id),
- );
-
- const summaries = rows.map((row) =>
- WORK_TYPE_ADAPTERS[row.work.type].mapCurrentRow(row, costByWorkId.get(row.work.id) ?? null),
- );
+ const summaries = await summariesOf(ctx, Array.from(anchorByWorkId.keys()));
for (const summary of summaries) {
const rootOperationId = anchorByWorkId.get(summary.id);
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index e2423af9ebc..dc6d0c302a0 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -586,6 +586,8 @@ export default {
'acceptance.gate.planFiles': '{{count}} files',
'acceptance.gate.planTitle': 'Execution plan',
'acceptance.gate.agentSays': 'Main Agent: {{reason}}',
+ 'acceptance.gate.unitArtifacts': 'Outputs',
+ 'acceptance.gate.unitArtifactsEmpty': 'No outputs registered for this unit.',
'acceptance.gate.unitBrief': 'What this unit does',
'acceptance.gate.unitWaitingHint': 'Not started yet. It runs the plan above once you approve.',
'acceptance.gate.unitWaiting': 'Starts on approval',
diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.ts
index 1fb28e8ca33..b17b13b6199 100644
--- a/packages/prompts/src/chains/goalManager.test.ts
+++ b/packages/prompts/src/chains/goalManager.test.ts
@@ -85,6 +85,7 @@ describe('buildGoalManagerPrompt', () => {
.map((line) => JSON.parse(line));
expect(tasksSchemas.find((schema) => schema.rollout)?.rollout).toMatchObject({
recipe: expect.any(String),
+ skillName: expect.any(String),
units: expect.any(Array),
});
});
diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.ts
index 682c4641a4d..3b7d60a52ca 100644
--- a/packages/prompts/src/chains/goalManager.ts
+++ b/packages/prompts/src/chains/goalManager.ts
@@ -186,7 +186,7 @@ export const GOAL_BATCH_DISTILL_RULE =
* server only checks the declaration is well formed.
*/
export const GOAL_BATCH_PLANNING_RULE =
- 'Batch (one repeated mould): when the remaining work applies one recipe to many units — migrate N stores to one mechanism, give N resources the same caching, update N callers — and the first units will likely need a person (unsettled conventions, review, acceptance), do not plan every unit as a task. Add "rollout" to the tasks plan instead: "tasks" become 2-5 probes, the most representative units covering every variant, each with a full brief; "rollout.recipe" is the one procedure every unit follows; "rollout.units" lists every other unit in delivery order, as a title or as {"title","description"} when the unit has its own pointers; "rollout.variants" names the axes the units differ along, and the gate holds until the probes cover each value. The probes run first; once they settle you rewrite the plan from what they ran into, and once every probe ran through without a person, the owner approves the first wave, each later wave is handed to you to release or escalate, and a rejected release comes back to you to rewrite the plan for the owner to review again. Units that differ only in names, files or details are still one mould; work whose steps differ from task to task is not, so plan it as ordinary tasks. Never declare a batch on a Goal whose rollout is off. While a batch is in flight no planning turn starts; the next one comes after its roster is delivered.';
+ 'Batch (one repeated mould): when the remaining work applies one recipe to many units — migrate N stores to one mechanism, give N resources the same caching, update N callers — and the first units will likely need a person (unsettled conventions, review, acceptance), do not plan every unit as a task. Add "rollout" to the tasks plan instead: "tasks" become 2-5 probes, the most representative units covering every variant, each with a full brief; "rollout.recipe" is the one procedure every unit follows; "rollout.skillName" names that procedure in a few English kebab-case words (e.g. "migrate-store-to-replica"), since the recipe is saved as a reusable skill under that name; "rollout.units" lists every other unit in delivery order, as a title or as {"title","description"} when the unit has its own pointers; "rollout.variants" names the axes the units differ along, and the gate holds until the probes cover each value. The probes run first; once they settle you rewrite the plan from what they ran into, and once every probe ran through without a person, the owner approves the first wave, each later wave is handed to you to release or escalate, and a rejected release comes back to you to rewrite the plan for the owner to review again. Units that differ only in names, files or details are still one mould; work whose steps differ from task to task is not, so plan it as ordinary tasks. Never declare a batch on a Goal whose rollout is off. While a batch is in flight no planning turn starts; the next one comes after its roster is delivered.';
const contract = (input: GoalManagerPromptInput) =>
[
@@ -215,7 +215,7 @@ const contract = (input: GoalManagerPromptInput) =>
'Measured acceptance clauses gate on recorded observations only; the "metrics" field of lh goal show lists each clause with the latest value the gate reads. Task conclusions and decision answers are not observations. When the evidence already meets a clause nobody recorded, escalate asking the owner to record the value on the Goal page (or with lh goal metric record) instead of submitting verify again; once metrics shows every clause met, submit verify.',
'Choose exactly one schema:',
'{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance","dependsOn":["task node ID from an earlier round", 0]}]}',
- '{"action":"tasks","reason":"why these units are one mould","tasks":[{"title":"probe unit","description":"full brief for this unit"}],"rollout":{"recipe":"the procedure every unit follows","units":["unit title",{"title":"unit title","description":"this unit\'s own pointers"}],"variants":[{"axis":"what the units differ in","values":["value a","value b"]}]}}',
+ '{"action":"tasks","reason":"why these units are one mould","tasks":[{"title":"probe unit","description":"full brief for this unit"}],"rollout":{"recipe":"the procedure every unit follows","skillName":"short-kebab-case-english-name-of-what-the-recipe-does","units":["unit title",{"title":"unit title","description":"this unit\'s own pointers"}],"variants":[{"axis":"what the units differ in","values":["value a","value b"]}]}}',
'{"action":"wait","reason":"why evidence must arrive later","until":"future UTC ISO instant","event":{"type":"external.result","key":"correlated job ID"}}',
'{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}',
'{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 85192602758..ac633f2029c 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -2,7 +2,7 @@ import type { GoalReportDispatch, GoalReportState } from './goalReport';
import type { GoalRolloutPolicy, GoalRolloutState } from './goalRollout';
import type { InitialGoalOverviewContext } from './stepContext';
import type { AcceptanceStatus, VerifyCheckTally } from './verify';
-import type { WorkType } from './work';
+import type { WorkResourceType, WorkType } from './work';
// ============================================
// Goal — independent target entity (`goals` table)
@@ -759,6 +759,8 @@ export interface GoalGraphWorkVersionDisplay {
mimeType?: string;
/** Canonical resource identity — the document id an in-app link addresses. */
resourceId: string | null;
+ /** What the Work is beyond its type, e.g. `github_pull_request`; draws its state glyph. */
+ resourceType?: WorkResourceType;
status: string | null;
title: string | null;
type: WorkType;
diff --git a/packages/types/src/goalRollout.ts b/packages/types/src/goalRollout.ts
index b6c86cdf569..d0a7d96a785 100644
--- a/packages/types/src/goalRollout.ts
+++ b/packages/types/src/goalRollout.ts
@@ -1,5 +1,6 @@
import type { GoalNodeStatus } from './goal';
import type { GoalRolloutRetro, GoalRolloutVerifier } from './goalRetro';
+import type { WorkSummaryItem } from './work';
/**
* Batch rollout trigger. `off`/absent keeps the ordinary decomposition: a goal
@@ -201,7 +202,19 @@ export interface GoalReleaseGateUnit {
/** The unit's own acceptance, when it was verified. */
acceptance?: { checks?: { failed: number; passed: number; total: number }; id: string };
/** Deliverables it produced: pull requests, reports, documents. */
- artifacts: { documentId?: string; title: string; type: string; url?: string }[];
+ artifacts: {
+ documentId?: string;
+ /** Short reference, e.g. a pull request's `#123`. */
+ identifier?: string;
+ /** e.g. `github_pull_request`; with `status`, what the review shows its state by. */
+ resourceType?: string;
+ /** The resource's state when the gate opened, e.g. `open` / `merged`. */
+ status?: string;
+ title: string;
+ type: string;
+ url?: string;
+ workId?: string;
+ }[];
/** The unit's own brief: what it was asked to do. */
brief?: string;
nodeId: string;
@@ -211,6 +224,11 @@ export interface GoalReleaseGateUnit {
taskId?: string;
title: string;
tokens: number;
+ /**
+ * The same outputs as the conversation's Work cards show them, frozen when
+ * the gate opened. Absent from dossiers frozen by an older server.
+ */
+ works?: WorkSummaryItem[];
}
/**
diff --git a/src/features/Acceptance/Viewer/Gate/GateReview.tsx b/src/features/Acceptance/Viewer/Gate/GateReview.tsx
index 58031c7484c..225e94e0142 100644
--- a/src/features/Acceptance/Viewer/Gate/GateReview.tsx
+++ b/src/features/Acceptance/Viewer/Gate/GateReview.tsx
@@ -7,6 +7,7 @@ import {
createStaticStyles,
cssVar,
cx,
+ DraggablePanel,
Flexbox,
Icon,
Markdown,
@@ -36,8 +37,9 @@ import { useAcceptanceComments } from '../Comments/hooks';
import { acceptanceOverviewPath } from '../routes';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import { canReviewAcceptance, isReadOnlyAcceptanceDecider } from '../visibility';
-import { latestRound, unitArtifacts } from './dossier';
+import { latestRound } from './dossier';
import SkillDirectory from './SkillDirectory';
+import UnitArtifacts from './UnitArtifacts';
import { usePlanFiles } from './usePlanFiles';
const styles = createStaticStyles(({ css }) => ({
@@ -97,12 +99,9 @@ const styles = createStaticStyles(({ css }) => ({
`,
panel: css`
overflow: hidden auto;
- flex: none;
-
- width: 340px;
- padding-block: 20px;
- padding-inline: 20px;
- border-inline-start: 1px solid ${cssVar.colorBorder};
+ height: 100%;
+ padding-block: 16px;
+ padding-inline: 16px;
`,
plan: css`
padding-block: 4px;
@@ -160,6 +159,9 @@ const formatTokens = (tokens: number) =>
/** A unit the owner has to look at: it was reworked, or did not settle cleanly. */
const isException = (unit: GoalReleaseGateUnit) => unit.runs > 1 || unit.status !== 'resolved';
+/** The detail panel opens at this width; its edge drags it between the bounds. */
+const PANEL_WIDTH = { default: 360, max: 720, min: 280 };
+
/** What the side panel shows: a unit that ran, or one the next wave would start. */
type Selection =
{ kind: 'result'; unit: GoalReleaseGateUnit } | { brief?: string; kind: 'next'; title: string };
@@ -282,69 +284,63 @@ const DetailPanel = memo<{ onClose: () => void; selection: Selection }>(
const title = selection.kind === 'result' ? selection.unit.title : selection.title;
const brief = selection.kind === 'result' ? selection.unit.brief : selection.brief;
return (
- <Flexbox className={styles.panel} gap={16}>
- <Flexbox horizontal align={'flex-start'} gap={8}>
- <Text strong style={{ flex: 1, minWidth: 0 }}>
- {title}
- </Text>
- <ActionIcon icon={X} size={'small'} onClick={onClose} />
- </Flexbox>
- {selection.kind === 'result' ? (
- <Flexbox gap={8}>
- <span className={styles.meta}>
- {t('acceptance.gate.unitMeta', {
- runs: selection.unit.runs,
- tokens: formatTokens(selection.unit.tokens),
- })}
- </span>
- {selection.unit.acceptance && (
- <a
- className={styles.link}
- rel="noreferrer"
- target="_blank"
- href={buildWorkspaceAwarePath(
- acceptanceOverviewPath(selection.unit.acceptance.id),
- workspaceSlug,
- )}
- >
- {selection.unit.acceptance.checks
- ? t('acceptance.gate.unitAcceptance', {
- passed: selection.unit.acceptance.checks.passed,
- total: selection.unit.acceptance.checks.total,
- })
- : t('acceptance.gate.unitAcceptanceOpen')}
- </a>
- )}
- {unitArtifacts(selection.unit).map((artifact) =>
- artifact.url ? (
+ <DraggablePanel
+ backgroundColor={'transparent'}
+ classNames={{ content: styles.panel }}
+ defaultSize={{ height: '100%', width: PANEL_WIDTH.default }}
+ expandable={false}
+ maxWidth={PANEL_WIDTH.max}
+ minWidth={PANEL_WIDTH.min}
+ placement={'right'}
+ >
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'flex-start'} gap={8}>
+ <Text strong style={{ flex: 1, minWidth: 0 }}>
+ {title}
+ </Text>
+ <ActionIcon icon={X} size={'small'} onClick={onClose} />
+ </Flexbox>
+ {selection.kind === 'result' ? (
+ <Flexbox gap={8}>
+ <span className={styles.meta}>
+ {t('acceptance.gate.unitMeta', {
+ runs: selection.unit.runs,
+ tokens: formatTokens(selection.unit.tokens),
+ })}
+ </span>
+ {selection.unit.acceptance && (
<a
className={styles.link}
- href={artifact.url}
- key={artifact.url}
rel="noreferrer"
target="_blank"
+ href={buildWorkspaceAwarePath(
+ acceptanceOverviewPath(selection.unit.acceptance.id),
+ workspaceSlug,
+ )}
>
- {artifact.title}
+ {selection.unit.acceptance.checks
+ ? t('acceptance.gate.unitAcceptance', {
+ passed: selection.unit.acceptance.checks.passed,
+ total: selection.unit.acceptance.checks.total,
+ })
+ : t('acceptance.gate.unitAcceptanceOpen')}
</a>
- ) : (
- <span className={styles.meta} key={artifact.title}>
- {artifact.title}
- </span>
- ),
- )}
- </Flexbox>
- ) : (
- <span className={styles.meta}>{t('acceptance.gate.unitWaitingHint')}</span>
- )}
- {brief && (
- <Flexbox gap={6}>
- <span className={styles.meta}>{t('acceptance.gate.unitBrief')}</span>
- <Text className={styles.body} type={'secondary'}>
- {brief.replace(/^\[origin=\w+\]\s*/, '')}
- </Text>
- </Flexbox>
- )}
- </Flexbox>
+ )}
+ </Flexbox>
+ ) : (
+ <span className={styles.meta}>{t('acceptance.gate.unitWaitingHint')}</span>
+ )}
+ {brief && (
+ <Flexbox gap={4}>
+ <span className={styles.meta}>{t('acceptance.gate.unitBrief')}</span>
+ <Markdown fontSize={13} variant={'chat'}>
+ {brief.replace(/^\[origin=\w+\]\s*/, '')}
+ </Markdown>
+ </Flexbox>
+ )}
+ {selection.kind === 'result' && <UnitArtifacts unit={selection.unit} />}
+ </Flexbox>
+ </DraggablePanel>
);
},
);
diff --git a/src/features/Acceptance/Viewer/Gate/UnitArtifacts.test.tsx b/src/features/Acceptance/Viewer/Gate/UnitArtifacts.test.tsx
new file mode 100644
index 00000000000..b603c509e73
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Gate/UnitArtifacts.test.tsx
@@ -0,0 +1,132 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import UnitArtifacts from './UnitArtifacts';
+
+/**
+ * Regression: the panel opened outputs through the Work gallery's opener,
+ * which reaches the canvas modal; the share app serves this review without the
+ * canvas runtime, so its build failed to resolve `virtual:canvas-runtime`.
+ */
+it('does not reach the canvas modal', async () => {
+ const source = await import('./UnitArtifacts?raw');
+ expect(source.default).not.toMatch(/WorkGallery\/useOpenWork|CanvasModal/);
+});
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const navigate = vi.fn();
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigate,
+}));
+vi.mock('@/features/Work/WorkSummaryCard', () => ({
+ default: ({
+ item,
+ onOpen,
+ variant,
+ }: {
+ item: { title: string };
+ onOpen: (item: unknown) => void;
+ variant?: string;
+ }) => (
+ <button type="button" onClick={() => onOpen(item)}>
+ work-card:{variant}:{item.title}
+ </button>
+ ),
+}));
+
+const unit = (patch: Record<string, unknown>) =>
+ ({ nodeId: 'n1', runs: 1, status: 'resolved', title: 'Unit', tokens: 0, ...patch }) as any;
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('UnitArtifacts', () => {
+ /**
+ * Regression: the review drew its own output rows instead of the Work cards
+ * the conversation lists under a reply, so the same PR looked different in
+ * the two places.
+ */
+ it("lists a unit's outputs with the conversation's Work cards and opens them", () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ const work = {
+ id: 'work_1',
+ resourceType: 'github_pull_request',
+ title: 'Move inbox reads to replica',
+ type: 'external',
+ url: 'https://github.com/lobehub/lobehub/pull/22737',
+ };
+ render(
+ <UnitArtifacts
+ unit={unit({
+ artifacts: [
+ { title: work.title, type: 'external', url: 'https://example.com', workId: 'work_1' },
+ ],
+ works: [work],
+ })}
+ />,
+ );
+ // The compact flat row of the conversation's working sidebar, not the tall card.
+ fireEvent.click(screen.getByText('work-card:inline:Move inbox reads to replica'));
+ expect(open).toHaveBeenCalledWith(
+ 'https://github.com/lobehub/lobehub/pull/22737',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ });
+
+ /**
+ * Regression: the gate's unit panel showed a unit's outputs as small gray
+ * title links, without a pull request's number or state, so the owner could
+ * not see what was ready to merge.
+ */
+ it('lists a pull request with its number and state, and opens it', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(
+ <UnitArtifacts
+ unit={unit({
+ artifacts: [
+ {
+ identifier: '#22737',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ title: 'Move inbox reads to replica',
+ type: 'external',
+ url: 'https://github.com/lobehub/lobehub/pull/22737',
+ },
+ ],
+ })}
+ />,
+ );
+
+ expect(screen.getByText('acceptance.gate.unitArtifacts')).toBeInTheDocument();
+ expect(screen.getByText('#22737 · metaCard.pr.open')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Move inbox reads to replica'));
+ expect(open).toHaveBeenCalledWith(
+ 'https://github.com/lobehub/lobehub/pull/22737',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ });
+
+ it('does not offer to open an output with an unsafe url', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(
+ <UnitArtifacts
+ unit={unit({
+ artifacts: [{ title: 'Notes', type: 'external', url: 'javascript:alert(1)' }],
+ })}
+ />,
+ );
+ fireEvent.click(screen.getByText('Notes'));
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it('says so when the unit registered no outputs', () => {
+ render(<UnitArtifacts unit={unit({ artifacts: [] })} />);
+ expect(screen.getByText('acceptance.gate.unitArtifactsEmpty')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Gate/UnitArtifacts.tsx b/src/features/Acceptance/Viewer/Gate/UnitArtifacts.tsx
new file mode 100644
index 00000000000..af994a04d9e
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Gate/UnitArtifacts.tsx
@@ -0,0 +1,142 @@
+'use client';
+
+import type { GoalReleaseGateUnit, WorkSummaryItem } from '@lobechat/types';
+import { Block, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { ExternalLink, FileDown, FileText } from 'lucide-react';
+import { createElement, memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { openDocumentModal } from '@/features/DocumentModal/loader';
+import {
+ getWorkTypeDescriptor,
+ isSafeExternalUrl,
+ WORK_TYPE_DESCRIPTORS,
+ type WorkIcon,
+} from '@/features/Work/descriptors';
+import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+import { unitArtifacts } from './dossier';
+
+type Artifact = GoalReleaseGateUnit['artifacts'][number];
+type ExternalItem = Parameters<(typeof WORK_TYPE_DESCRIPTORS)['external']['getIcon']>[0];
+
+/** A pull request or issue draws its state (open / merged / …) the way the Work cards do. */
+const externalItem = (artifact: Artifact) =>
+ ({ resourceType: artifact.resourceType, status: artifact.status ?? null }) as ExternalItem;
+
+const iconOf = (artifact: Artifact): WorkIcon =>
+ artifact.type === 'external'
+ ? WORK_TYPE_DESCRIPTORS.external.getIcon(externalItem(artifact))
+ : artifact.type === 'document'
+ ? FileText
+ : artifact.type === 'file'
+ ? FileDown
+ : ExternalLink;
+
+/**
+ * Opens a unit's output where it lives. Not the Work gallery's `useOpenWork`:
+ * that one reaches the canvas modal, whose runtime the share app (which also
+ * serves this review) does not bundle. A canvas output stays where it is.
+ */
+const useOpenUnitWork = () => {
+ const navigate = useWorkspaceAwareNavigate();
+ return useCallback(
+ (item: WorkSummaryItem) => {
+ const target = getWorkTypeDescriptor(item).getOpenTarget(item);
+ switch (target?.kind) {
+ case 'document': {
+ void openDocumentModal(target.documentId);
+ return;
+ }
+ case 'external':
+ case 'filePreview': {
+ if (isSafeExternalUrl(target.url))
+ window.open(target.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ case 'task': {
+ navigate(taskDetailPath(target.identifier ?? target.taskId, undefined, target.name));
+ }
+ }
+ },
+ [navigate],
+ );
+};
+
+const ArtifactRow = memo<{ artifact: Artifact }>(({ artifact }) => {
+ const { t } = useTranslation('topic');
+ const url = isSafeExternalUrl(artifact.url) ? artifact.url : undefined;
+ const stateKey =
+ artifact.type === 'external'
+ ? WORK_TYPE_DESCRIPTORS.external.getStateLabelKey?.(externalItem(artifact))
+ : undefined;
+ return (
+ <Block
+ horizontal
+ align={'center'}
+ clickable={!!url}
+ gap={8}
+ padding={8}
+ title={url}
+ variant={'outlined'}
+ onClick={url ? () => window.open(url, '_blank', 'noopener,noreferrer') : undefined}
+ >
+ {/* Icons are module-level components; picking one per row creates none. */}
+ {createElement(iconOf(artifact), { size: 16 })}
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {artifact.title || artifact.identifier}
+ </Text>
+ {(artifact.identifier || stateKey) && (
+ <Text fontSize={12} type={'secondary'}>
+ {[artifact.identifier, stateKey && t(stateKey)].filter(Boolean).join(' · ')}
+ </Text>
+ )}
+ </Flexbox>
+ {url && <Icon color={cssVar.colorTextQuaternary} icon={ExternalLink} size={14} />}
+ </Block>
+ );
+});
+
+ArtifactRow.displayName = 'GateUnitArtifactRow';
+
+/**
+ * What a unit's run delivered — its PRs, documents, files — as the same Work
+ * cards the conversation lists under a reply, each opened where it lives. A
+ * dossier frozen before the cards were carried falls back to plain rows.
+ */
+const UnitArtifacts = memo<{ unit: GoalReleaseGateUnit }>(({ unit }) => {
+ const { t } = useTranslation('verify');
+ const openWork = useOpenUnitWork();
+ const artifacts = unitArtifacts(unit);
+ return (
+ <Flexbox gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.gate.unitArtifacts')}
+ </Text>
+ {unit.works?.length ? (
+ // The flat rows of the conversation's working sidebar: the panel is
+ // narrow, and the rows' own inset lines their icons up with the label.
+ <Flexbox style={{ marginInline: -8 }}>
+ {unit.works.map((work) => (
+ <WorkSummaryCard item={work} key={work.id} variant={'inline'} onOpen={openWork} />
+ ))}
+ </Flexbox>
+ ) : artifacts.length > 0 ? (
+ artifacts.map((artifact, index) => (
+ <ArtifactRow artifact={artifact} key={artifact.url ?? `${artifact.title}-${index}`} />
+ ))
+ ) : (
+ <Text fontSize={13} type={'secondary'}>
+ {t('acceptance.gate.unitArtifactsEmpty')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+UnitArtifacts.displayName = 'GateUnitArtifacts';
+
+export default UnitArtifacts;