🤯 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
🐛 fix(goal): show a sent-back plan's hand-off and re-run its experiments in place (#21163)
Arvin Xu9d448c0fa05e
diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.tsindex a9bd8434b1d..3f797de1c37 100644--- a/apps/cli/src/commands/goal/index.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -529,7 +529,7 @@ export function registerGoalCommand(program: Command) {).requiredOption('--file <path>',- 'JSON plan: action tasks/wait/verify/retry/escalate/release/revise_plan, reason and action fields; a tasks plan may add "rollout" to run its units as a batch; release answers a batch release handed to this turn; revise_plan answers a plan the owner sent back, with "recipe" the full revised plan',+ 'JSON plan: action tasks/wait/verify/retry/escalate/release/revise_plan, reason and action fields; a tasks plan may add "rollout" to run its units as a batch; release answers a batch release handed to this turn; revise_plan answers a plan the owner sent back, with "recipe" the full revised plan and optional "rerun" the experiment unit ids to run again on it (omitted: all)',).requiredOption('--token <token>', 'Current server-issued planning turn token').option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')diff --git a/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.test.ts b/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.test.tsindex eb7f46867ea..1af70156a66 100644--- a/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.test.ts+++ b/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.test.ts@@ -7,6 +7,7 @@ const findByNode = vi.hoisted(() => vi.fn());const answerReleaseGate = vi.hoisted(() => vi.fn());const scheduleGoalAdvance = vi.hoisted(() => vi.fn());const listByAcceptance = vi.hoisted(() => vi.fn());+const advanceGoal = vi.hoisted(() => vi.fn());vi.mock('@/database/models/goal', () => ({GoalModel: class {@@ -24,6 +25,7 @@ vi.mock('@/server/services/goal', () => ({},}));vi.mock('@/server/services/goal/scheduler', () => ({ scheduleGoalAdvance }));+vi.mock('@/server/services/goal/advanceGoal', () => ({ advanceGoal }));const db = {} as never;const gate = (id = 'acc_gate') =>@@ -43,6 +45,7 @@ beforeEach(() => {answerReleaseGate.mockReset();scheduleGoalAdvance.mockReset();listByAcceptance.mockReset();+ advanceGoal.mockReset();});describe('assertNotHoldingRelease', () => {@@ -98,10 +101,44 @@ describe('withGoalGateAnswer', () => {return 'written';});+ await expect(withGoalGateAnswer(db, service(true), gate(), 'release', {}, write)).resolves.toBe(+ 'written',+ );+ expect(answerReleaseGate).toHaveBeenCalledWith('node_release', 'release', undefined);+ expect(scheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1', trigger: 'decide' }),+ );+ expect(advanceGoal).not.toHaveBeenCalled();+ });++ // The owner's panel opens on the main Agent's hand-off as the request+ // returns, so a send-back hands it over in the request, not on the queue.+ it('hands a sent-back plan to the main Agent before answering', async () => {+ answerReleaseGate.mockResolvedValue('goal_1');+ advanceGoal.mockResolvedValue({ goalId: 'goal_1', ticks: 2 });+ const write = vi.fn(async () => {+ expect(advanceGoal).not.toHaveBeenCalled();+ return 'written';+ });+await expect(withGoalGateAnswer(db, service(true), gate(), 'revise', { comment: '补上播种' }, write),).resolves.toBe('written');expect(answerReleaseGate).toHaveBeenCalledWith('node_release', 'revise', '补上播种');+ expect(advanceGoal).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1', trigger: 'decide' }),+ );+ expect(scheduleGoalAdvance).not.toHaveBeenCalled();+ });++ it('queues the hand-off when the inline advance fails', async () => {+ answerReleaseGate.mockResolvedValue('goal_1');+ advanceGoal.mockRejectedValue(new Error('db busy'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(+ withGoalGateAnswer(db, service(true), gate(), 'revise', { comment: '补上播种' }, vi.fn()),+ ).resolves.toBeUndefined();expect(scheduleGoalAdvance).toHaveBeenCalledWith(expect.objectContaining({ goalId: 'goal_1', trigger: 'decide' }),);diff --git a/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.ts b/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.tsindex 64dd54a57db..87839efbf42 100644--- a/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.ts+++ b/apps/server/src/routers/lambda/_helpers/goalGateAcceptance.ts@@ -6,6 +6,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';import type { AcceptanceItem } from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';import { GoalService } from '@/server/services/goal';+import { advanceGoal } from '@/server/services/goal/advanceGoal';import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import { requireDecidableAcceptance } from '@/server/services/verify/acceptanceDecision';import type { AcceptanceService } from '@/server/services/verify/acceptanceService';@@ -81,13 +82,22 @@ export const withGoalGateAnswer = async <T>(): Promise<T> => {const goalId = await answerGoalGate(db, service, acceptance, optionId, answer);const written = await write();- if (goalId)- await scheduleGoalAdvance({- goalId,- trigger: 'decide',- userId: acceptance.userId,- workspaceId: acceptance.workspaceId ?? undefined,+ if (!goalId) return written;+ const advance = {+ goalId,+ trigger: 'decide' as const,+ userId: acceptance.userId,+ workspaceId: acceptance.workspaceId ?? undefined,+ };+ // A plan sent back is handed to the main Agent within this request, so the+ // owner's panel opens on that hand-off rather than on an empty conversation+ // while the queued advance catches up. Should it fail, the queue takes it.+ if (optionId === 'revise')+ await advanceGoal(advance).catch(async (error) => {+ console.error('[goalGateAcceptance] inline advance failed, queueing it:', error);+ await scheduleGoalAdvance(advance);});+ else await scheduleGoalAdvance(advance);return written;};diff --git a/apps/server/src/services/goal/batchPlanSkill.ts b/apps/server/src/services/goal/batchPlanSkill.tsindex 7bc6b3c2dca..a1ae1bcae89 100644--- a/apps/server/src/services/goal/batchPlanSkill.ts+++ b/apps/server/src/services/goal/batchPlanSkill.ts@@ -41,6 +41,9 @@ export const planSkillName = (batchNodeId: string) =>export const planSkillIdentifier = (skill: GoalRolloutPlanSkill) =>buildUserSkillIdentifier(skill.name);+/** Opens the instruction a plan-skill brief writes under its `Unit:` line. */+export const PLAN_SKILL_BRIEF_LEAD = "Do this unit by the batch's execution plan";+/*** A unit's brief. With a plan skill the brief names the skill — the run loads* its latest version — and still carries the plan as it stood at dispatch, so a@@ -54,7 +57,7 @@ export const planUnitBrief = (plan.skill? [`Unit: ${title}`,- `Do this unit by the batch's execution plan, the skill \`${planSkillIdentifier(plan.skill)}\` loaded for this run. Follow its latest version.`,+ `${PLAN_SKILL_BRIEF_LEAD}, the skill \`${planSkillIdentifier(plan.skill)}\` loaded for this run. Follow its latest version.`,plan.outline &&`If that skill is not loaded in this run, follow the plan as it stood at dispatch:\n\n${plan.outline}`,]diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex d9a4be1efad..ed4bf967e16 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -2084,7 +2084,7 @@ describe('a batch the main Agent declares', () => {return { op: op!, state };};- it('sends a plan the owner sent back to the main Agent, and reviews its rewrite in the same round', async () => {+ it('sends a plan the owner sent back to the main Agent, and re-runs the experiments on its rewrite in the same round', async () => {const { id } = await probesPassed();const pending = await pendingRelease(id);@@ -2112,19 +2112,18 @@ describe('a batch the main Agent declares', () => {await service().tick(id);const after = (await model().findById(id))!.config!;- // A rewrite revises the plan, not the experiments: still round 1, no new probes.- expect(after.rolloutState).toMatchObject({- phase: 'release_review',- probeNodeIds: held.config!.rolloutState!.probeNodeIds,- templateRevision: 1,- });+ // The experiments the correction judged run again on the rewrite, in round 1.+ const reruns = after.rolloutState!.probeNodeIds;+ expect(after.rolloutState).toMatchObject({ phase: 'probe', templateRevision: 1 });+ expect(reruns).toHaveLength(held.config!.rolloutState!.probeNodeIds.length);+ expect(reruns.some((n) => held.config!.rolloutState!.probeNodeIds.includes(n))).toBe(false);expect(after.rolloutState!.pendingRevision).toBeUndefined();// The rewrite replaces the plan; the correction is not pasted under it.expect(after.rollout!.spec!.recipeOutline).toBe(recipe);- // The rewritten plan goes back to the owner for the same release.- const again = await pendingRelease(id);- expect(again).toBeDefined();- expect(again!.nodeId).not.toBe(pending!.nodeId);+ // Their results, not the old ones, go back to the owner for the release.+ await settle(reruns);+ await service().tick(id);+ expect((await pendingRelease(id))!.nodeId).not.toBe(pending!.nodeId);});it('takes only a rewrite on a revise turn, and hands the revision over again when none came', async () => {diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 231d8efb8a9..df1707b330a 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -57,6 +57,8 @@ import { recoveryEligibility } from './supervisor/policy';import { goalWaitSchema, GoalWaitService } from './wait';const reason = z.string().trim().min(1).max(8000);+/** Node ids or titles of the reviewed units a revised plan runs again; omitted, all of them. */+const rerun = z.array(z.string().trim().min(1)).max(60).optional();/*** The question an escalation puts to the owner. A bare reason left the gate* asking "retry or retire?" while the decision that actually blocked the goal —@@ -189,11 +191,8 @@ export const goalPlanSchema = z.discriminatedUnion('action', [z.object({ action: z.literal('escalate'), reason, ask: goalAskSchema.optional() }).strict(),/** Answers a batch release handed over by the coordinator: the next wave goes out. */z.object({ action: z.literal('release'), reason }).strict(),- /**- * Answers a plan the owner sent back: the whole revised recipe the next probe- * round follows, rewritten from the owner's correction.- */- z.object({ action: z.literal('revise_plan'), reason, recipe: reason }).strict(),+ /** Answers a plan sent back: the full revised recipe, and the reviewed units to re-run. */+ z.object({ action: z.literal('revise_plan'), reason, recipe: reason, rerun }).strict(),]);type GoalPlan = z.infer<typeof goalPlanSchema>;const activeStatuses = new Set(['planning', 'running']);@@ -1975,8 +1974,7 @@ export class GoalManagerService {},});} else if (plan.action === 'revise_plan') {- // The rewrite lands with the plan; the coordinator opens the new probe- // round from it on its next advance.+ // The rewrite lands with the plan; the next advance re-runs the units it names.const rollout = goal.config?.rolloutState;if (rollout?.phase !== 'plan_revision' || !rollout.pendingRevision)throw new TRPCError({@@ -1987,6 +1985,7 @@ export class GoalManagerService {...rollout,pendingRevision: {...rollout.pendingRevision,+ ...(plan.rerun && { rerun: plan.rerun }),revisedReason: plan.reason,revisedRecipe: plan.recipe,},diff --git a/apps/server/src/services/goal/releaseGate.ts b/apps/server/src/services/goal/releaseGate.tsindex 3fa9ab4528e..3ec8a132476 100644--- a/apps/server/src/services/goal/releaseGate.ts+++ b/apps/server/src/services/goal/releaseGate.ts@@ -2,6 +2,7 @@ import type {GoalGraphSnapshot,GoalReleaseGateDossier,GoalReleaseGateUnit,+ GoalRolloutState,VerifyCheckItem,} from '@lobechat/types';import debug from 'debug';@@ -24,6 +25,16 @@ const NEXT_WAVE_ITEM_ID = 'next-wave';const GATE_CHECKS_ITEM_ID = 'gate-checks';const unitItemId = (nodeId: string) => `unit:${nodeId}`;+/**+ * The units a release review reports on: the probes while the round is on its+ * canary, the last released wave after that.+ */+export const reviewedUnitIds = (state: GoalRolloutState, waveSize: number): string[] => {+ if (state.waveIndex === 0) return state.probeNodeIds;+ const lastRelease = state.gateLog?.findLast((entry) => entry.outcome === 'released');+ return (state.massNodeIds ?? []).slice(-(lastRelease?.releasedCount ?? waveSize));+};+/*** Build the dossier a release gate is decided on, from the fetched graph.*@@ -44,11 +55,7 @@ export const buildReleaseGateDossier = (const state = graph.goal.config?.rolloutState;if (!policy || !state) return;- const lastRelease = state.gateLog?.findLast((entry) => entry.outcome === 'released');- const unitIds =- state.waveIndex === 0- ? state.probeNodeIds- : (state.massNodeIds ?? []).slice(-(lastRelease?.releasedCount ?? input.waveSize));+ const unitIds = reviewedUnitIds(state, input.waveSize);const spendByTask = new Map((graph.spend?.byTask ?? []).map((row) => [row.taskId, row]));const units: GoalReleaseGateUnit[] = unitIds.flatMap((nodeId) => {diff --git a/apps/server/src/services/goal/releaseReview.test.ts b/apps/server/src/services/goal/releaseReview.test.tsindex a24606ccca9..49bc42d6b7d 100644--- a/apps/server/src/services/goal/releaseReview.test.ts+++ b/apps/server/src/services/goal/releaseReview.test.ts@@ -195,7 +195,12 @@ describe('approving a batch release', () => {// is gone, so no new version can be written.await goalModel.updateRolloutState(goalId, {...state,- pendingRevision: { ...state.pendingRevision!, revisedRecipe: '先播种,再换 replica' },+ // Nothing to re-run: the rewrite goes straight back to the review.+ pendingRevision: {+ ...state.pendingRevision!,+ rerun: [],+ revisedRecipe: '先播种,再换 replica',+ },planSkill: { id: 'doc_deleted_plan', name: 'migrate-stores-plan' },});@@ -208,6 +213,209 @@ describe('approving a batch release', () => {expect(after.rolloutState!.phase).toBe('release_review');});+ /** Send the plan back from the report and land the main Agent's rewrite of it. */+ const sendBackAndRewrite = async (service: GoalService, goalId: string, rerun?: string[]) => {+ const pending = await pendingRelease(service, goalId);+ await service.answerReleaseGate(pending!.nodeId, 'revise', '每个 PR 都要过 codex review 和 CI');+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(goalId)).goal.config!.rolloutState!;+ await goalModel.updateRolloutState(goalId, {+ ...state,+ pendingRevision: {+ ...state.pendingRevision!,+ ...(rerun && { rerun }),+ revisedRecipe: '换 replica,并让 PR 过 codex review 和 CI',+ },+ });+ return service.tick(goalId);+ };+ const derivedFrom = async (goalId: string, nodeId: string) =>+ (await serverDB.query.goalEdges.findMany({ where: eq(goalEdges.goalId, goalId) })).find(+ (edge) => edge.kind === 'derived_from' && edge.sourceNodeId === nodeId,+ )?.targetNodeId;++ it('re-runs the reviewed experiments on a sent-back plan before the owner reviews again', async () => {+ const { goalId, graphModel, probeIds, service } = await passedProbes();+ await service.tick(goalId);+ const before = (await service.graph(goalId)).goal.config!.rolloutState!;++ const result = await sendBackAndRewrite(service, goalId);++ expect(result.outcome).toBe('advanced');+ const graph = await service.graph(goalId);+ const state = graph.goal.config!.rolloutState!;+ // The experiments run again in their own round, under the same gate: the+ // owner is not asked about results the correction was about.+ expect(await pendingRelease(service, goalId)).toBeUndefined();+ expect(state).toMatchObject({+ assayNodeId: before.assayNodeId,+ phase: 'probe',+ releaseGateAcceptanceId: before.releaseGateAcceptanceId,+ templateNodeId: before.templateNodeId,+ templateRevision: before.templateRevision,+ waveIndex: 0,+ });+ expect(graph.goal.config!.rollout!.spec?.recipeOutline).toBe(+ '换 replica,并让 PR 过 codex review 和 CI',+ );+ // Each experiment runs again as a new task that continues its earlier run.+ expect(state.probeNodeIds).toHaveLength(probeIds.length);+ expect(state.probeNodeIds.some((id) => probeIds.includes(id))).toBe(false);+ const reruns = state.probeNodeIds.map((id) => graph.nodes.find((node) => node.id === id)!);+ expect(reruns.map((node) => node.status)).not.toContain('resolved');+ expect(reruns[0].description).toContain('每个 PR 都要过 codex review 和 CI');+ expect(await Promise.all(state.probeNodeIds.map((id) => derivedFrom(goalId, id)))).toEqual(+ probeIds,+ );+ const gated = graph.edges+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === before.assayNodeId)+ .map((edge) => edge.targetNodeId);+ expect(gated).toEqual(expect.arrayContaining(state.probeNodeIds));+ // Units already delivered keep their delivery.+ for (const id of probeIds)+ expect(graph.nodes.find((node) => node.id === id)!.status).toBe('resolved');++ // Once the re-runs settle, the owner reviews their results on the same report,+ // named by the plan they ran on rather than the round number.+ for (const id of state.probeNodeIds) await graphModel.updateNodeStatus(goalId, id, 'resolved');+ await service.tick(goalId);+ const revised = (await service.graph(goalId)).goal.config!.rolloutState!;+ const planVersion = revised.planVersions?.[String(revised.templateRevision)];+ expect(planVersion).toBeGreaterThan(revised.templateRevision);+ expect((await pendingRelease(service, goalId))!.question).toContain(+ `Experiments of v${planVersion} finished`,+ );+ const rounds = await new VerifyRunModel(serverDB, userId).listByAcceptance(+ before.releaseGateAcceptanceId!,+ );+ expect(rounds.at(-1)!.metadata!.releaseGate!.units.map((unit) => unit.nodeId)).toEqual(+ state.probeNodeIds,+ );+ });++ // A probe that built on another runs after it again: the re-runs keep the+ // order, so the dependent one never starts on its prerequisite's old output.+ it('keeps the order between probes that depended on each other', async () => {+ const { goalId, graphModel, probeIds, service } = await passedProbes();+ await graphModel.createEdge(goalId, probeIds[1], probeIds[0], 'depends_on');+ await service.tick(goalId);++ await sendBackAndRewrite(service, goalId);++ const graph = await service.graph(goalId);+ const [first, second] = graph.goal.config!.rolloutState!.probeNodeIds;+ expect(+ graph.edges.some(+ (edge) =>+ edge.kind === 'depends_on' && edge.sourceNodeId === second && edge.targetNodeId === first,+ ),+ ).toBe(true);+ });++ it('re-runs only the units the main Agent names', async () => {+ const { goalId, probeIds, service } = await passedProbes();+ await service.tick(goalId);++ await sendBackAndRewrite(service, goalId, [probeIds[0], 'Unit 2']);++ const state = (await service.graph(goalId)).goal.config!.rolloutState!;+ // The named units are replaced in place by their re-runs; the rest stand.+ expect(state.probeNodeIds).toHaveLength(probeIds.length);+ expect(+ await Promise.all(state.probeNodeIds.slice(0, 2).map((id) => derivedFrom(goalId, id))),+ ).toEqual(probeIds.slice(0, 2));+ expect(state.probeNodeIds.slice(2)).toEqual(probeIds.slice(2));+ expect(state.releasedCount).toBe(probeIds.length);+ });++ it('returns a rewrite that re-runs nothing straight to the review', async () => {+ const { goalId, probeIds, service } = await passedProbes();+ await service.tick(goalId);+ const before = (await service.graph(goalId)).goal.config!.rolloutState!;++ await sendBackAndRewrite(service, goalId, []);++ const state = (await service.graph(goalId)).goal.config!.rolloutState!;+ expect(state).toMatchObject({+ phase: 'release_review',+ probeNodeIds: probeIds,+ templateRevision: before.templateRevision,+ });+ expect(await pendingRelease(service, goalId)).toBeDefined();+ });++ it('re-runs a later wave sent back in place, and returns its results to the owner', async () => {+ const { goalId, graphModel, service } = await firstWaveDelivered();+ // The owner reviews the later wave (escalated by the main Agent in practice).+ await service.tick(goalId);+ const before = (await service.graph(goalId)).goal.config!.rolloutState!;+ const reviewed = before.massNodeIds!;++ await sendBackAndRewrite(service, goalId);++ const state = (await service.graph(goalId)).goal.config!.rolloutState!;+ expect(state).toMatchObject({ phase: 'mass', waveIndex: before.waveIndex });+ expect(await Promise.all(state.massNodeIds!.map((id) => derivedFrom(goalId, id)))).toEqual(+ reviewed,+ );++ // The re-run wave passes its gate. A main Agent that could release later+ // waves on its own is not asked: the owner sent this one back.+ const agentId = 'goal-release-agent';+ await serverDB.insert(agents).values({ id: agentId, userId });+ const config = (await service.graph(goalId)).goal.config!;+ await serverDB+ .update(goals)+ .set({ agentId, config: { ...config, manager: { maxTurns: 4 } } })+ .where(eq(goals.id, goalId));+ const execAgent = vi.spyOn(AiAgentService.prototype, 'execAgent').mockResolvedValue({+ operationId: 'op-release-turn',+ } as Awaited<ReturnType<AiAgentService['execAgent']>>);+ for (const id of state.massNodeIds!) await graphModel.updateNodeStatus(goalId, id, 'resolved');+ await service.tick(goalId);++ expect(execAgent).not.toHaveBeenCalled();+ expect((await pendingRelease(service, goalId))!.question).toContain('re-run on plan');+ });++ // The review report may fail to open; the owner then sends the wave back on+ // the goal page. The re-run still returns to the owner, not the main Agent.+ it('returns a later wave sent back on the goal page to the owner', async () => {+ const { goalId, graphModel, service } = await firstWaveDelivered();+ await service.tick(goalId);+ const held = (await service.graph(goalId)).goal.config!.rolloutState!;+ const goalModel = new GoalModel(serverDB, userId);+ await goalModel.updateRolloutState(goalId, { ...held, releaseGateAcceptanceId: undefined });+ const pending = await pendingRelease(service, goalId);+ await service.decide(goalId, pending!.id, 'revise', '每个 PR 都要过 codex review 和 CI');+ const revising = (await service.graph(goalId)).goal.config!.rolloutState!;+ await goalModel.updateRolloutState(goalId, {+ ...revising,+ pendingRevision: {+ ...revising.pendingRevision!,+ revisedRecipe: '换 replica,过 review 和 CI',+ },+ });+ await service.tick(goalId);++ const agentId = 'goal-release-fallback-agent';+ await serverDB.insert(agents).values({ id: agentId, userId });+ const config = (await service.graph(goalId)).goal.config!;+ await serverDB+ .update(goals)+ .set({ agentId, config: { ...config, manager: { maxTurns: 4 } } })+ .where(eq(goals.id, goalId));+ const execAgent = vi.spyOn(AiAgentService.prototype, 'execAgent').mockResolvedValue({+ operationId: 'op-release-turn',+ } as Awaited<ReturnType<AiAgentService['execAgent']>>);+ const rerun = (await service.graph(goalId)).goal.config!.rolloutState!;+ for (const id of rerun.massNodeIds!) await graphModel.updateNodeStatus(goalId, id, 'resolved');+ await service.tick(goalId);++ expect(execAgent).not.toHaveBeenCalled();+ expect((await pendingRelease(service, goalId))!.question).toContain('re-run on plan');+ });+it('takes a retry of the answer it recorded, and refuses a different one', async () => {const { goalId, service } = await passedProbes();await service.tick(goalId);diff --git a/apps/server/src/services/goal/releaseReview.ts b/apps/server/src/services/goal/releaseReview.tsindex c4b87766e01..a163e9dc453 100644--- a/apps/server/src/services/goal/releaseReview.ts+++ b/apps/server/src/services/goal/releaseReview.ts@@ -27,8 +27,8 @@ import { BatchPlanSkillService } from './batchPlanSkill';import type { GoalBriefService } from './goalBriefs';import type { GoalService } from './index';import { answeredProblem, GoalManagerService, problemKey } from './manager';-import { buildReleaseGateDossier, openReleaseGateAcceptance } from './releaseGate';-import { createRecipeUnitTask } from './rolloutBatch';+import { buildReleaseGateDossier, openReleaseGateAcceptance, reviewedUnitIds } from './releaseGate';+import { carriedUnitBrief, createRecipeUnitTask, rerunUnitNote } from './rolloutBatch';import { describeGateChecks, type RolloutGateResult, withGateVerdict } from './rolloutGate';const log = debug('lobe-server:goal-rollout');@@ -48,6 +48,44 @@ export interface ReleaseReviewHost {transitionStatus: (goal: GoalItem, to: GoalStatus, reason?: string) => Promise<unknown>;}+/**+ * The plan version a round runs on. A plan sent back is rewritten inside its+ * round, so the round number alone would name the version the owner rejected.+ */+const planVersionOf = (state: GoalRolloutState) =>+ state.planVersions?.[String(state.templateRevision)] ?? state.templateRevision;++/**+ * The reviewed units a sent-back plan runs again, with the brief each keeps and+ * what it delivered. `names` are the node ids or titles the main Agent chose;+ * absent — or naming none of them, which is a slip rather than a choice —+ * every reviewed unit runs again, and an empty list runs none.+ */+const rerunUnits = (+ graph: GoalGraphSnapshot,+ state: GoalRolloutState,+ waveSize: number,+ names: string[] | undefined,+) => {+ const units = reviewedUnitIds(state, waveSize).flatMap((id) => {+ const node = graph.nodes.find((candidate) => candidate.id === id);+ if (!node || node.kind !== 'task') return [];+ const delivered = graph.workVersions+ .filter((link) => link.nodeId === id && link.work && link.work.type !== 'task')+ .map((link) => {+ const title = link.work!.title ?? link.work!.identifier ?? '';+ return link.work!.url ? `${title} ${link.work!.url}`.trim() : title;+ })+ .filter(Boolean);+ return [+ { brief: carriedUnitBrief(node), delivered: [...new Set(delivered)], id, title: node.title },+ ];+ });+ if (!names) return units;+ const chosen = units.filter((unit) => names.includes(unit.id) || names.includes(unit.title));+ return names.length && !chosen.length ? units : chosen;+};+/*** The batch's release gate as a decision a person (or the main Agent) makes.*@@ -55,7 +93,8 @@ export interface ReleaseReviewHost {* here: on the owner for a round's first wave, on the main Agent for the rest.* The owner decides on a review report; sending the plan back hands the* correction to the main Agent, whose rewrite becomes the plan skill's next- * version in the same round and comes back to the same review.+ * version in the same round. The units the correction covers run again on+ * it in place, and their results come back to the same review.*/export class GoalReleaseReview {constructor(@@ -100,10 +139,22 @@ export class GoalReleaseReview {return this.releaseRolloutWave(graph, effects, gate);const wave = `wave ${state.waveIndex + 1} (${waveCount} unit${waveCount === 1 ? '' : 's'})`;+ // A release review the owner has not approved means they sent this wave's+ // plan back and its units ran again: their results go back to the owner,+ // not to the main Agent to release on its own. The review's decision node+ // is the marker — it outlives a send-back and only an approval clears it —+ // so a send-back answered on the goal page, without a report, counts too.+ if (state.waveIndex > 0 && (state.releaseReviewNodeId || state.releaseGateAcceptanceId))+ return this.openReleaseReview(+ graph,+ `Units re-run on plan v${planVersionOf(state)} passed the gate; approve releasing ${wave}`,+ effects,+ { gate, kind: 'escalated' },+ );if (state.waveIndex === 0)return this.openReleaseReview(graph,- `Experiments of v${state.templateRevision} finished; start batch execution with ${wave}`,+ `Experiments of v${planVersionOf(state)} finished; start batch execution with ${wave}`,effects,{ gate, kind: 'probes' },);@@ -112,7 +163,7 @@ export class GoalReleaseReview {// read as the answer for the next.const problem = {kind: 'rollout_release' as const,- reason: `Batch gate passed for v${state.templateRevision} after wave ${state.waveIndex}: ${describeGateChecks(gate)}. Decide whether ${wave} goes out — release it, or escalate it for the owner to approve.`,+ reason: `Batch gate passed for v${planVersionOf(state)} after wave ${state.waveIndex}: ${describeGateChecks(gate)}. Decide whether ${wave} goes out — release it, or escalate it for the owner to approve.`,};const answered = answeredProblem(graph.goal.config?.managerState);// A `release` answer recorded its approval when it was submitted, so reaching@@ -143,8 +194,8 @@ export class GoalReleaseReview {* Parks the goal like a pattern break, but on a decision node of its own: a* node carries one decision, and the Assay keeps its for a break later in the* round. `release` sends the wave out on the proven recipe; `revise` takes a- * correction for the main Agent, whose rewritten plan comes back to this- * review — the probes already ran and are not run again.+ * correction for the main Agent, whose rewritten plan re-runs the units the+ * correction covers and comes back to this review with their new results.*/private openReleaseReview = async (graph: GoalGraphSnapshot,@@ -430,7 +481,7 @@ export class GoalReleaseReview {const problem = {kind: 'rollout_revise' as const,- reason: `The owner reviewed the experiments of plan v${state.templateRevision} and sent the plan back with this correction:\n${pending.correction}\nRewrite the plan so every remaining unit follows it, and answer revise_plan with the full revised plan.`,+ reason: `The owner reviewed the experiments of plan v${planVersionOf(state)} and sent the plan back with this correction:\n${pending.correction}\nRewrite the plan so every remaining unit follows it, and answer revise_plan with the full revised plan.`,};const takeover = await new GoalManagerService(this.db, this.userId, this.workspaceId).takeOver(graph,@@ -444,11 +495,13 @@ export class GoalReleaseReview {};/**- * Land the main Agent's rewrite in the round it was asked for. Sending a plan- * back revises the plan skill — a new version of the same round — not the- * experiments: they already ran, and the owner judged them. The rewritten- * plan then returns to the owner on the same release review, as its next- * round, so the decision is made on the plan the batch will actually copy.+ * Land the main Agent's rewrite in the round it was asked for: the plan+ * skill's next version, not a new round. The owner sent the plan back after+ * judging this round's experiments, so the units the rewrite names — every+ * one unless it said otherwise — run again on it in place, under the same+ * gate: each re-run is `derived_from` its earlier run, continues that+ * delivery, and takes its place in the round. Their results come back to the+ * same review. A rewrite that re-runs nothing returns to the review at once.*/private applyPlanRevision = async (graph: GoalGraphSnapshot): Promise<GoalTickResult> => {const goalId = graph.goal.id;@@ -457,6 +510,8 @@ export class GoalReleaseReview {const pending = state.pendingRevision!;const recipe = pending.revisedRecipe!.trim();const round = String(state.templateRevision);+ const waveSize = Math.max(1, policy?.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT);+ const rerun = rerunUnits(graph, state, waveSize, pending.rerun);const version = state.planSkill? await new BatchPlanSkillService(this.db, this.userId, this.workspaceId).revise(state.planSkill, {@@ -470,6 +525,10 @@ export class GoalReleaseReview {return undefined;}): undefined;+ // A revision that did not land leaves the skill on the plan the owner sent+ // back: units drop it and copy the revised plan instead.+ const planSkill = version === undefined ? undefined : state.planSkill;+ const reopened: string[] = [];const applied = await this.db.transaction(async (tx) => {const goalModel = new GoalModel(tx, this.userId, this.workspaceId);const current = (await goalModel.lockById(goalId))?.config?.rolloutState;@@ -484,31 +543,73 @@ export class GoalReleaseReview {repeatable: policy.spec?.repeatable ?? true,},});+ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });if (current.templateNodeId)- await new GoalGraphModel(tx, this.userId, this.workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- }).updateNodeDescription(goalId, current.templateNodeId, recipe);+ await writer.updateNodeDescription(goalId, current.templateNodeId, recipe);++ // Each re-run replaces its earlier run in the round, so the gate judges+ // the re-runs and the review reports them.+ const replaced = new Map<string, string>();+ for (const unit of rerun) {+ const nodeId = await createRecipeUnitTask(+ writer,+ goalId,+ current.batchNodeId,+ unit.title,+ { outline: recipe, skill: planSkill },+ unit.brief,+ rerunUnitNote(pending.correction, unit.delivered),+ );+ if (!nodeId) continue;+ replaced.set(unit.id, nodeId);+ reopened.push(unit.title);+ await writer.createEdge(goalId, nodeId, unit.id, 'derived_from');+ if (current.waveIndex === 0 && current.assayNodeId)+ await writer.createEdge(goalId, current.assayNodeId, nodeId, 'depends_on');+ }+ // A unit that waited on another keeps waiting on it: the order the units+ // ran in carries over to their re-runs, so a re-run never starts on the+ // output its prerequisite is still redoing.+ for (const edge of graph.edges) {+ const source = edge.kind === 'depends_on' && replaced.get(edge.sourceNodeId);+ if (!source) continue;+ await writer.createEdge(+ goalId,+ source,+ replaced.get(edge.targetNodeId) ?? edge.targetNodeId,+ 'depends_on',+ );+ }+ const swap = (ids: string[]) => ids.map((id) => replaced.get(id) ?? id);await goalModel.updateRolloutState(goalId, {...current,+ ...(current.massNodeIds && { massNodeIds: swap(current.massNodeIds) }),pendingRevision: undefined,phase: current.waveIndex === 0 ? 'probe' : 'mass',- // A revision that did not land leaves the skill on the plan the owner- // sent back: units drop it and copy the revised plan instead.- planSkill: version === undefined ? undefined : current.planSkill,+ planSkill,planVersions: version? { ...current.planVersions, [round]: version }: current.planVersions,+ probeNodeIds: swap(current.probeNodeIds),});return true;});if (!applied)return { goalId, message: 'The plan revision was already applied', outcome: 'no_progress' };+ if (reopened.length)+ return {+ goalId,+ message: `The main Agent revised the plan to v${version ?? state.templateRevision} from your correction; re-running ${reopened.length} unit${reopened.length === 1 ? '' : 's'} on it before you review again`,+ outcome: 'advanced',+ };+const fresh = await this.host.requireGraph(goalId);const freshState = fresh.goal.config!.rolloutState!;const released = freshState.releasedCount ?? freshState.probeNodeIds.length;- const waveSize = Math.max(1, policy?.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT);const count = (freshState.unitTitles ?? []).slice(released, released + waveSize).length;const wave = `wave ${freshState.waveIndex + 1} (${count} unit${count === 1 ? '' : 's'})`;return this.openReleaseReview(diff --git a/apps/server/src/services/goal/rolloutBatch.test.ts b/apps/server/src/services/goal/rolloutBatch.test.tsindex 1af30623087..276978623c9 100644--- a/apps/server/src/services/goal/rolloutBatch.test.ts+++ b/apps/server/src/services/goal/rolloutBatch.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { normalizeRolloutRoster } from './rolloutBatch';+import { carriedUnitBrief, normalizeRolloutRoster, rerunUnitNote } from './rolloutBatch';describe('normalizeRolloutRoster', () => {const probes = (...titles: string[]) => titles.map((title) => ({ title }));@@ -41,3 +41,60 @@ describe('normalizeRolloutRoster', () => {]);});});++describe('carriedUnitBrief', () => {+ const brief = (...sections: string[]) => ({ description: sections.join('\n\n'), title: 'A1' });++ it('keeps the unit brief but not the note of the re-run it was carried into', () => {+ // A unit re-run once, now re-opened again: its own brief travels on, the+ // earlier re-run's note does not pile up under the next one.+ const node = brief(+ 'Follow the plan skill.\n\nUnit: A1',+ 'Unit brief (from its first run):\n[origin=rework] PR #20858',+ `Re-run on the revised plan:\n${rerunUnitNote('过 codex review', ['PR #20858 https://github.com/lobehub/lobehub/pull/20858'])}`,+ );++ expect(carriedUnitBrief(node)).toBe('[origin=rework] PR #20858');+ });++ it('carries nothing for a unit briefed only from the plan skill', () => {+ // The plan text in such a brief is the version it ran on — carrying it+ // would hand a re-run the very plan the owner sent back.+ const node = brief(+ 'Unit: A1',+ "Do this unit by the batch's execution plan, the skill `plan` loaded for this run.",+ 'If that skill is not loaded in this run, follow the plan as it stood at dispatch:\n\nv1 plan',+ );++ expect(carriedUnitBrief(node)).toBeUndefined();+ });++ // A planner may write its own probe instruction under the same `Unit:` line;+ // only the generated plan-skill brief is boilerplate.+ it('keeps a planner instruction that opens with the unit line', () => {+ const node = brief('Unit: A1\nVariant: desktop\nCover the Electron window only.');++ expect(carriedUnitBrief(node)).toBe(+ 'Unit: A1\nVariant: desktop\nCover the Electron window only.',+ );+ });++ it('carries nothing for a re-run briefed only from the shared plan', () => {+ const node = brief(+ 'Follow the plan skill.\n\nUnit: A1',+ `Re-run on the revised plan:\n${rerunUnitNote('过 codex review', [])}`,+ );++ expect(carriedUnitBrief(node)).toBeUndefined();+ });+});++describe('rerunUnitNote', () => {+ it('points the re-run at its earlier delivery so it continues rather than duplicates it', () => {+ const note = rerunUnitNote('过 codex review', ['PR #1 https://example.com/pull/1']);++ expect(note).toContain('过 codex review');+ expect(note).toContain('- PR #1 https://example.com/pull/1');+ expect(note).toContain('do not open a second one');+ });+});diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.tsindex 9e0d05e4905..c44599c7097 100644--- a/apps/server/src/services/goal/rolloutBatch.ts+++ b/apps/server/src/services/goal/rolloutBatch.ts@@ -16,7 +16,7 @@ import debug from 'debug';import type { GoalModel } from '@/database/models/goal';import type { GoalGraphModel } from '@/database/models/goalGraph';-import { BatchPlanSkillService, planUnitBrief } from './batchPlanSkill';+import { BatchPlanSkillService, PLAN_SKILL_BRIEF_LEAD, planUnitBrief } from './batchPlanSkill';import { unitsNamedByProbes } from './spec';const log = debug('lobe-server:goal-rollout');@@ -67,6 +67,8 @@ export const normalizeRolloutRoster = (/** Heads the brief a unit carries over from its first run when it is re-opened. */const UNIT_BRIEF_HEADING = 'Unit brief (from its first run):';+/** Heads why a delivered unit runs again, and what it delivered before. */+const RERUN_HEADING = 'Re-run on the revised plan:';/*** The per-unit brief a re-opened unit must keep: the first-hand probe brief@@ -78,8 +80,18 @@ export const carriedUnitBrief = (node: { description?: string | null; title: strconst description = node.description?.trim();if (!description) return undefined;const carried = description.indexOf(UNIT_BRIEF_HEADING);- if (carried >= 0) return description.slice(carried + UNIT_BRIEF_HEADING.length).trim();- return description.endsWith(`Unit: ${node.title}`) ? undefined : description;+ // A re-run's note belongs to that run; the next re-open writes its own.+ const brief = carried >= 0 ? description.slice(carried + UNIT_BRIEF_HEADING.length) : description;+ const note = brief.indexOf(RERUN_HEADING);+ const own = (note >= 0 ? brief.slice(0, note) : brief).trim();+ if (carried >= 0) return own || undefined;+ // Briefed from the shared plan alone — the outline, or the plan skill — the+ // unit has nothing of its own, and the plan it ran on is not to be carried.+ // Only the generated skill brief is skipped: a planner's own instruction may+ // open with the same `Unit:` line and still carry the unit's constraints.+ const unit = `Unit: ${node.title}`;+ const skillBrief = own.startsWith(`${unit}\n\n${PLAN_SKILL_BRIEF_LEAD}`);+ return !own || own.endsWith(unit) || skillBrief ? undefined : own;};/**@@ -97,9 +109,15 @@ export const createRecipeUnitTask = async (title: string,plan: { outline?: string; skill?: GoalRolloutPlanSkill },unitBrief?: string,+ /** Why a delivered unit runs again; see {@link rerunUnitNote}. */+ rerunNote?: string,): Promise<string | undefined> => {const node = await writer.createNode(goalId, {- description: [planUnitBrief(title, plan), unitBrief && `${UNIT_BRIEF_HEADING}\n${unitBrief}`]+ description: [+ planUnitBrief(title, plan),+ unitBrief && `${UNIT_BRIEF_HEADING}\n${unitBrief}`,+ rerunNote && `${RERUN_HEADING}\n${rerunNote}`,+ ].filter(Boolean).join('\n\n'),kind: 'task',@@ -109,6 +127,19 @@ export const createRecipeUnitTask = async (return node?.id;};+/**+ * Why a unit the owner already saw delivered runs again: the correction its+ * plan was rewritten from, and what it delivered, so the run brings that+ * delivery up to the revised plan instead of starting a second one beside it.+ */+export const rerunUnitNote = (correction: string, delivered: string[]) =>+ [+ `The owner reviewed this unit's earlier delivery and sent the plan back with this correction:\n${correction}`,+ delivered.length+ ? `Earlier delivery:\n${delivered.map((item) => `- ${item}`).join('\n')}\nContinue on it (same branch / PR) until it meets the revised plan; do not open a second one.`+ : 'Redo the unit so it meets the revised plan.',+ ].join('\n\n');+export interface RolloutBatchProbe {/** 0-based indices of earlier probes this one builds on. */dependsOn?: number[];diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 1ded2590306..921b0b6cb0e 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -511,6 +511,9 @@"goalBatch.planPanel.latest": "v{{revision}} · latest","goalBatch.planPanel.same": "Same as v{{base}}","goalBatch.planPanel.unfoldFiles": "Show files",+ "goalBatch.probes.attemptNext": "Next run",+ "goalBatch.probes.attemptOf": "Run {{current}} / {{total}}",+ "goalBatch.probes.attemptPrevious": "Previous run","goalBatch.probes.cell.backlog": "Not started","goalBatch.probes.cell.done": "Done","goalBatch.probes.cell.human": "Needs you",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 1330b0f7ea8..457f4fc2161 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -191,7 +191,7 @@"acceptance.gate.cancel": "Cancel","acceptance.gate.checks": "Gate checks {{passed}}/{{total}} passed. They show the experiments finished, not that the plan carries over.","acceptance.gate.decidedRelease": "Started. Wave {{wave}} is running.",- "acceptance.gate.decidedRevise": "Sent back. The main Agent is rewriting the plan from your correction; the new version comes back here for your review.",+ "acceptance.gate.decidedRevise": "Sent back. The main Agent is rewriting the plan from your correction and re-running the affected units on it; their new results come back here for your review.","acceptance.gate.decisionHint": "Start runs the plan on the next wave. Revise has the main Agent rewrite the plan, then it comes back to you.","acceptance.gate.hideFiles": "Hide files","acceptance.gate.lead.escalated": "The main Agent reviewed wave {{wave}} and brought this release back to you instead of releasing it.",@@ -199,13 +199,14 @@"acceptance.gate.leadProbes": "{{count}} experiments are done. Once you start, the remaining {{remaining}} units follow this plan in batches.","acceptance.gate.leadRework": "Reworked: {{codes}}.","acceptance.gate.nextWaveTitle": "Wave {{wave}}",+ "acceptance.gate.planFiles": "{{count}} files","acceptance.gate.planTitle": "Execution plan","acceptance.gate.releaseWave": "Approve and release wave {{wave}} ({{count}})","acceptance.gate.remaining": "{{count}} more after that, each wave reviewed by the main Agent. About {{estimate}} tokens in total, estimated from the experiments.","acceptance.gate.resultsProbes": "Experiment results","acceptance.gate.resultsWave": "Last wave","acceptance.gate.revise": "Revise plan",- "acceptance.gate.reviseHint": "Your correction goes to the main Agent, which writes a new version of the plan skill. The results above stand; you review the new version before anything is released.",+ "acceptance.gate.reviseHint": "Your correction goes to the main Agent, which writes a new version of the plan skill and re-runs the units it covers on that version. You review their new results before anything is released.","acceptance.gate.revisePlaceholder": "Write the correction. The main Agent writes it into a new version of the plan.","acceptance.gate.reviseSubmit": "Send back to revise","acceptance.gate.showFiles": "Show the skill files",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ef329cc6f00..1c287853c06 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -511,6 +511,9 @@"goalBatch.planPanel.latest": "v{{revision}} · 最新","goalBatch.planPanel.same": "与 v{{base}} 相同","goalBatch.planPanel.unfoldFiles": "展开文件",+ "goalBatch.probes.attemptNext": "下一次",+ "goalBatch.probes.attemptOf": "第 {{current}} / {{total}} 次",+ "goalBatch.probes.attemptPrevious": "上一次","goalBatch.probes.cell.backlog": "未开始","goalBatch.probes.cell.done": "已完成","goalBatch.probes.cell.human": "需要介入",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 7fc28958b9a..d5bf84c5078 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -191,7 +191,7 @@"acceptance.gate.cancel": "取消","acceptance.gate.checks": "闸门检查 {{passed}}/{{total}} 通过(只说明实验跑完了,不代表方案可以复制)","acceptance.gate.decidedRelease": "已开启,第 {{wave}} 批正在执行。",- "acceptance.gate.decidedRevise": "已打回,主 Agent 正在按你的修正改写方案;新版本会回到这里等你审核。",+ "acceptance.gate.decidedRevise": "已打回,主 Agent 正在按你的修正改写方案,并在新方案上重跑受影响的单元;新结果会回到这里等你审核。","acceptance.gate.decisionHint": "开启后下一批照这份方案执行;修订会让主 Agent 改写方案,改完再回来给你审。","acceptance.gate.hideFiles": "收起文件","acceptance.gate.lead.escalated": "主 Agent 审完第 {{wave}} 批后没有自己放行,交回给你决定。",@@ -199,13 +199,14 @@"acceptance.gate.leadProbes": "{{count}} 个试点已经完成。开启后,剩下 {{remaining}} 项会照这份方案分批执行。","acceptance.gate.leadRework": "其中 {{codes}} 有返工。","acceptance.gate.nextWaveTitle": "第 {{wave}} 批",+ "acceptance.gate.planFiles": "共 {{count}} 个文件","acceptance.gate.planTitle": "执行方案","acceptance.gate.releaseWave": "通过并放出第 {{wave}} 批({{count}} 项)","acceptance.gate.remaining": "之后还有 {{count}} 项,由主 Agent 逐批审核放行。按实验平均估算,总共约 {{estimate}} token。","acceptance.gate.resultsProbes": "实验结果","acceptance.gate.resultsWave": "上一批结果","acceptance.gate.revise": "修订方案",- "acceptance.gate.reviseHint": "你的修正会发给主 Agent,由它把方案 skill 改出新版本。上面的结果仍然有效,新版本回到这里经你审核后才会放行。",+ "acceptance.gate.reviseHint": "你的修正会发给主 Agent,由它把方案 skill 改出新版本,并在新版本上重跑修正涉及的单元。重跑结果回到这里经你审核后才会放行。","acceptance.gate.revisePlaceholder": "写下对方案的修正,主 Agent 会把它改进方案的新版本。","acceptance.gate.reviseSubmit": "打回修订","acceptance.gate.showFiles": "展开技能文件",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 184b9c0f271..8ebad92f086 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -50,6 +50,9 @@ export default {'goalBatch.planPanel.latest': 'v{{revision}} · latest','goalBatch.planPanel.same': 'Same as v{{base}}','goalBatch.planPanel.unfoldFiles': 'Show files',+ 'goalBatch.probes.attemptNext': 'Next run',+ 'goalBatch.probes.attemptOf': 'Run {{current}} / {{total}}',+ 'goalBatch.probes.attemptPrevious': 'Previous run','goalBatch.probes.cell.backlog': 'Not started','goalBatch.probes.cell.done': 'Done','goalBatch.probes.cell.human': 'Needs you',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex af28068c492..4958d54d0a9 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -493,12 +493,12 @@ export default {'acceptance.status.closed': 'Acceptance closed','acceptance.status.delivered': 'Ready for your decision','acceptance.gate.decidedRevise':- 'Sent back. The main Agent is rewriting the plan from your correction; the new version comes back here for your review.',+ 'Sent back. The main Agent is rewriting the plan from your correction and re-running the affected units on it; their new results come back here for your review.','acceptance.gate.decidedRelease': 'Started. Wave {{wave}} is running.','acceptance.gate.cancel': 'Cancel','acceptance.gate.reviseSubmit': 'Send back to revise','acceptance.gate.reviseHint':- 'Your correction goes to the main Agent, which writes a new version of the plan skill. The results above stand; you review the new version before anything is released.',+ 'Your correction goes to the main Agent, which writes a new version of the plan skill and re-runs the units it covers on that version. You review their new results before anything is released.','acceptance.gate.revisePlaceholder':'Write the correction. The main Agent writes it into a new version of the plan.','acceptance.gate.revise': 'Revise plan',@@ -522,6 +522,7 @@ export default {'acceptance.gate.resultsProbes': 'Experiment results','acceptance.gate.hideFiles': 'Hide files','acceptance.gate.showFiles': 'Show the skill files',+ 'acceptance.gate.planFiles': '{{count}} files','acceptance.gate.planTitle': 'Execution plan','acceptance.gate.agentSays': 'Main Agent: {{reason}}','acceptance.gate.unitBrief': 'What this unit does',diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.tsindex 0a2ad8e5773..95cbcacc32e 100644--- a/packages/prompts/src/chains/goalManager.ts+++ b/packages/prompts/src/chains/goalManager.ts@@ -164,7 +164,7 @@ export const GOAL_BATCH_RELEASE_RULE =/** A takeover whose problem is a plan the owner sent back: rewrite it, or fall back. */export const GOAL_BATCH_REVISE_RULE =- 'Plan revision: the owner reviewed the batch\'s experiments and sent the plan back with the correction in <problem>. Read the current plan skill and the experiment results with lh goal show, then rewrite the whole plan so every remaining unit follows the correction — fold it into the steps it changes instead of appending a note. Answer {"action":"revise_plan","reason":"what changed and why it answers the correction","recipe":"the full revised plan, in the language of the Goal requirement"}; the next round of experiments runs on it. Where the correction conflicts with the plan, resolve it in the rewrite and say how in reason. No other action is accepted on this turn.';+ 'Plan revision: the owner reviewed the batch\'s experiments and sent the plan back with the correction in <problem>. Read the current plan skill and the experiment results with lh goal show, then rewrite the whole plan so every remaining unit follows the correction — fold it into the steps it changes instead of appending a note. Then decide which delivered experiment units the correction covers: those run again on the revised plan, continuing their earlier delivery (same branch / PR), and the owner reviews the new round\'s results — not the old ones. A correction about how the units were delivered (review, CI, quality, a missed step) covers all of them; one that only changes units still owed covers none. Answer {"action":"revise_plan","reason":"what changed and why it answers the correction","recipe":"the full revised plan, in the language of the Goal requirement","rerun":["node ids of the experiment units to run again"]} — omit "rerun" to run every experiment unit again, or pass [] when none needs it. Where the correction conflicts with the plan, resolve it in the rewrite and say how in reason. No other action is accepted on this turn.';/*** When to declare a batch, and how. The judgement is the planning agent's; thediff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 26e7c526434..ce1d2c9e81c 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -700,10 +700,21 @@ export interface GoalRolloutState {massNodeIds?: string[];/*** The owner's correction a sent-back release waits on, while the phase is- * `plan_revision`. The main Agent rewrites the plan from it (`revisedRecipe`);- * once it lands the rewrite returns to the owner's release review.+ * `plan_revision`. The main Agent rewrites the plan from it (`revisedRecipe`)+ * and names the delivered units the correction covers (`rerun`). Those units+ * run again on the rewrite as a new round of experiments before the owner+ * reviews it; with none to re-run, the rewrite returns to the review at once.*/- pendingRevision?: { correction: string; revisedReason?: string; revisedRecipe?: string };+ pendingRevision?: {+ correction: string;+ /**+ * Node ids (or titles) of the reviewed round's units to run again on the+ * rewrite. Absent re-runs every one of them; empty re-runs none.+ */+ rerun?: string[];+ revisedReason?: string;+ revisedRecipe?: string;+ };/** Phase the rollout is in; the coordinator reads this to pick its move. */phase: GoalRolloutPhase;/** The execution plan as a user skill; each Template revision is one of its versions. */diff --git a/src/features/Acceptance/Viewer/Gate/GateReview.tsx b/src/features/Acceptance/Viewer/Gate/GateReview.tsxindex 53378ed70f2..182e69ae454 100644--- a/src/features/Acceptance/Viewer/Gate/GateReview.tsx+++ b/src/features/Acceptance/Viewer/Gate/GateReview.tsx@@ -36,6 +36,7 @@ import { useAcceptanceBundle } from '../useAcceptanceBundle';import { canReviewAcceptance } from '../visibility';import { latestRound, unitArtifacts } from './dossier';import SkillDirectory from './SkillDirectory';+import { usePlanFiles } from './usePlanFiles';const styles = createStaticStyles(({ css }) => ({body: css`@@ -342,10 +343,13 @@ const DetailPanel = memo<{ onClose: () => void; selection: Selection }>(},);+/** How the owner settled the gate: let the next wave run, or send the plan back. */+export type GateDecisionKind = 'release' | 'revise';+const GateDecision = memo<{dossier: GoalReleaseGateDossier;inModal?: boolean;- onDecided?: () => void;+ onDecided?: (decision: GateDecisionKind) => void;}>(({ dossier, inModal, onDecided }) => {const { t } = useTranslation('verify');const { acceptanceId } = useAcceptanceScope();@@ -367,13 +371,13 @@ const GateDecision = memo<{</Flexbox>);- const run = async (action: () => Promise<unknown>) => {+ const run = async (decision: GateDecisionKind, action: () => Promise<unknown>) => {setPending(true);try {await action();await mutate();void globalMutate(isAcceptanceListKey);- onDecided?.();+ onDecided?.(decision);} catch (cause) {toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));} finally {@@ -415,7 +419,7 @@ const GateDecision = memo<{disabled={!correction.trim()}loading={pending}onClick={() =>- run(() =>+ run('revise', () =>verifyService.rejectDelivery(data.acceptance.id, correction.trim(), {dispatch: false,roundId,@@ -435,7 +439,9 @@ const GateDecision = memo<{loading={pending}type={'primary'}onClick={() =>- run(() => verifyService.acceptDelivery(data.acceptance.id, undefined, { roundId }))+ run('release', () =>+ verifyService.acceptDelivery(data.acceptance.id, undefined, { roundId }),+ )}>{releaseLabel}@@ -452,7 +458,7 @@ interface GateReviewProps {/** Rendered as the review dialog (with its own frame) rather than on the acceptance page. */inModal?: boolean;onClose?: () => void;- onDecided?: () => void;+ onDecided?: (decision: GateDecisionKind) => void;}/**@@ -463,8 +469,7 @@ interface GateReviewProps {const GateReview = memo<GateReviewProps>(({ dossier, inModal, onClose, onDecided }) => {const { t } = useTranslation('verify');const [selected, setSelected] = useState<Selection>();- // The plan reads as a document first; its other files are a click away.- const [filesOpen, setFilesOpen] = useState(false);+ const { extraFiles, filesOpen, toggleFiles } = usePlanFiles(dossier.plan.skillId);const average =dossier.units.reduce((sum, unit) => sum + unit.tokens, 0) / Math.max(1, dossier.units.length);const probes = dossier.kind === 'probes';@@ -510,6 +515,7 @@ const GateReview = memo<GateReviewProps>(({ dossier, inModal, onClose, onDecideddossier.plan.skillName && (<span className={styles.meta}>{dossier.plan.skillName} · v{dossier.plan.revision}+ {extraFiles > 0 && ` · ${t('acceptance.gate.planFiles', { count: extraFiles + 1 })}`}</span>)}@@ -519,7 +525,7 @@ const GateReview = memo<GateReviewProps>(({ dossier, inModal, onClose, onDecidedicon={filesOpen ? PanelLeftCloseIcon : PanelLeftOpenIcon}size={'small'}title={t(filesOpen ? 'acceptance.gate.hideFiles' : 'acceptance.gate.showFiles')}- onClick={() => setFilesOpen((open) => !open)}+ onClick={toggleFiles}/>)}diff --git a/src/features/Acceptance/Viewer/Gate/index.tsx b/src/features/Acceptance/Viewer/Gate/index.tsxindex c9429ba948a..adba22774f9 100644--- a/src/features/Acceptance/Viewer/Gate/index.tsx+++ b/src/features/Acceptance/Viewer/Gate/index.tsx@@ -5,14 +5,16 @@ import { createModal, useModalContext } from '@lobehub/ui';import { AcceptanceBundleGate, AcceptanceScope } from '../AcceptanceScope';import { useAcceptanceBundle } from '../useAcceptanceBundle';import { latestRound } from './dossier';-import GateReview from './GateReview';+import GateReview, { type GateDecisionKind } from './GateReview';++export type { GateDecisionKind } from './GateReview';const GateReportContent = ({acceptanceId,onDecided,}: {acceptanceId: string;- onDecided?: () => void;+ onDecided?: (decision: GateDecisionKind) => void;}) => {const { data } = useAcceptanceBundle(acceptanceId);const { close } = useModalContext();@@ -23,9 +25,9 @@ const GateReportContent = ({inModaldossier={dossier}onClose={close}- onDecided={() => {+ onDecided={(decision) => {close();- onDecided?.();+ onDecided?.(decision);}}/>);@@ -41,7 +43,7 @@ export const openGateReportModal = ({onDecided,}: {acceptanceId: string;- onDecided?: () => void;+ onDecided?: (decision: GateDecisionKind) => void;}) =>createModal({content: (diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.tsnew file mode 100644index 00000000000..30e1ca321cd--- /dev/null+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts@@ -0,0 +1,51 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { usePlanFiles } from './usePlanFiles';++const skill = vi.hoisted(() => ({ current: undefined as { files: unknown[] } | undefined }));++vi.mock('@/libs/swr', () => ({+ useClientDataSWR: (key: unknown) => ({ data: key ? skill.current : undefined }),+}));+vi.mock('@/services/userSkill', () => ({ userSkillService: { get: vi.fn() } }));++const file = (path: string) => ({ content: '', path });++describe('usePlanFiles', () => {+ beforeEach(() => {+ skill.current = undefined;+ });++ // The owner asked whether the plan carries scripts or more documents: a plan+ // that does opens on its directory, with every file listed.+ it('opens the directory of a plan that ships more than SKILL.md', () => {+ skill.current = { files: [file('scripts/check.sh'), file('references/review.md')] };++ const { result } = renderHook(() => usePlanFiles('skill-1'));++ expect(result.current).toMatchObject({ extraFiles: 2, filesOpen: true });+ });++ it('reads a lone SKILL.md as a document until the owner opens the tree', () => {+ skill.current = { files: [] };+ const { result } = renderHook(() => usePlanFiles('skill-1'));+ expect(result.current).toMatchObject({ extraFiles: 0, filesOpen: false });++ act(() => result.current.toggleFiles());++ expect(result.current.filesOpen).toBe(true);+ });++ it('lets the owner fold a directory that opened on its own', () => {+ skill.current = { files: [file('scripts/check.sh')] };+ const { result } = renderHook(() => usePlanFiles('skill-1'));++ act(() => result.current.toggleFiles());++ expect(result.current.filesOpen).toBe(false);+ });+});diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.tsnew file mode 100644index 00000000000..cd7d66393ba--- /dev/null+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts@@ -0,0 +1,25 @@+import { useState } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { userSkillService } from '@/services/userSkill';++/**+ * The plan skill's directory under review. A plan that ships scripts or+ * references opens on its whole directory, so the owner sees every file it+ * carries; a lone `SKILL.md` reads as a document until they open the tree.+ * Shares the directory's request, so it costs no second fetch.+ */+export const usePlanFiles = (skillId?: string) => {+ const { data: skill } = useClientDataSWR(skillId ? ['goal-gate-plan-skill', skillId] : null, () =>+ userSkillService.get(skillId!),+ );+ // `files` holds what sits beside `SKILL.md`, not `SKILL.md` itself.+ const extraFiles = skill?.files?.length ?? 0;+ const [toggled, setToggled] = useState<boolean>();+ const filesOpen = toggled ?? extraFiles > 0;+ return {+ extraFiles,+ filesOpen,+ toggleFiles: () => setToggled(!filesOpen),+ };+};diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex e099cee9c15..dc8685585af 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -8,6 +8,7 @@ import { Link } from 'react-router';import NotFound from '@/components/404';import AsyncError from '@/components/AsyncError';+import ConversationSkeleton from '@/components/Skeleton/Conversation/List';import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';import AgentBreadcrumb from '@/features/AgentBreadcrumb';import { useAgentRoutePath } from '@/features/AgentBreadcrumb/useAgentRoutePath';@@ -26,6 +27,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { goalSelectors, useGoalStore } from '@/store/goal';import GoalChat from './GoalChat';+import { GoalConversationContext } from './goalConversation';import GoalDetailActions from './GoalDetailActions';import GoalHeaderMetrics from './GoalHeaderMetrics';import { goalManagerConversation } from './goalPresentation';@@ -58,6 +60,9 @@ interface GoalDetailPageProps {goalId: string;}+/** How long the panel waits for a send-back's supervision record before giving up on it. */+const AWAIT_RECORD_TIMEOUT = 10_000;+const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const { t } = useTranslation('chat');const { allowed: canEdit } = usePermission('create_content');@@ -77,7 +82,11 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {// On the agent-less `/goal/:goalId` route an ancestor layout already owns the// side panel; mounting ours as well would give the surface two portal hosts.const hasWorkspaceSidePanel = useWorkspaceSidePanel();- const chat = useGoalChatPanel(goalId, agentId);+ const chat = useGoalChatPanel(+ goalId,+ agentId,+ snapshot ? goalManagerConversation(snapshot.goal) : undefined,+ );const clearPortalStack = useChatStore((s) => s.clearPortalStack);// While the exploration map runs fullscreen its overlay carries the portal@@ -133,6 +142,15 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {[],);+ // A send-back's hand-off normally lands with the request; when the main Agent+ // cannot take it up, the panel stops waiting and stays where it opened.+ const { awaitingRecord, stopAwaitingRecord } = chat;+ useEffect(() => {+ if (!awaitingRecord) return;+ const timer = setTimeout(stopAwaitingRecord, AWAIT_RECORD_TIMEOUT);+ return () => clearTimeout(timer);+ }, [awaitingRecord, stopAwaitingRecord]);+// The portal stack belongs to this goal's inspection session — leaving the// page (or switching goals) must not leak it into the conversation surface.useEffect(() => () => clearPortalStack(), [clearPortalStack, goalId]);@@ -181,6 +199,18 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {chat.setOpen(true);};+ // A decision that just messaged the agent (sending a plan back) shows that+ // message landing, so the reply is never invisible behind a drill-down. A+ // managed goal whose main Agent has no supervision record yet gets one from+ // this very turn: the panel opens now and moves there once it exists.+ const revealConversation = () => {+ setGraphFullscreen(false);+ clearPortalStack();+ if (goal.config?.manager && !managerConversation && supervisingAgentId)+ chat.openAwaitingRecord({ agentId: supervisingAgentId });+ else openPanel();+ };+const paused = goal.status === 'paused';// Pace control exists only while the coordinator loop is actually moving (or// explicitly paused). A goal in review awaits the human, and a closed goal@@ -191,130 +221,133 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {['paused', 'planning', 'running', 'verifying'].includes(goal.status);return (- <Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }}>- <Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>- <NavHeader- left={- <Flexbox horizontal align={'center'} gap={4}>- {agentId ? (- <AgentBreadcrumb- agentId={agentId}- extraItems={[goal.title]}- // The goal title owns the last crumb, so this one is a way back- // to the agent's goal list rather than a label for this page.- title={<Link to={buildAgentPath('goals')}>{t('goalList.title')}</Link>}- />- ) : (- <Text fontSize={14} weight={500}>+ <GoalConversationContext value={panelTarget ? revealConversation : undefined}>+ <Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }}>+ <Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>+ <NavHeader+ left={+ <Flexbox horizontal align={'center'} gap={4}>+ {agentId ? (+ <AgentBreadcrumb+ agentId={agentId}+ extraItems={[goal.title]}+ // The goal title owns the last crumb, so this one is a way back+ // to the agent's goal list rather than a label for this page.+ title={<Link to={buildAgentPath('goals')}>{t('goalList.title')}</Link>}+ />+ ) : (+ <Text fontSize={14} weight={500}>+ {goal.title}+ </Text>+ )}+ {/* Not nested under the breadcrumb: an agent-less goal still has to+ be deletable, and this menu is the only place that can do it. */}+ <GoalDetailActions agentId={agentId} goalId={goal.id} projectId={goal.projectId} />+ </Flexbox>+ }+ right={+ graphFullscreen+ ? undefined+ : supervisingAgentId && (+ <GoalSupervisorToggle+ hideWhenExpanded+ agentId={supervisingAgentId}+ expand={showPortal || chatVisible}+ label={+ managerConversation+ ? t('goalProcess.manager.viewTrace')+ : t('goalChat.title')+ }+ onToggle={openPanel}+ />+ )+ }+ />+ <Flexbox flex={1} style={{ overflowY: 'auto' }}>+ <WideScreenContainer gap={20} paddingBlock={16}>+ <Flexbox className={styles.header} gap={8}>+ <Text as={'h1'} fontSize={22} weight={600}>{goal.title}</Text>- )}- {/* Not nested under the breadcrumb: an agent-less goal still has to- be deletable, and this menu is the only place that can do it. */}- <GoalDetailActions agentId={agentId} goalId={goal.id} projectId={goal.projectId} />- </Flexbox>- }- right={- graphFullscreen- ? undefined- : supervisingAgentId && (- <GoalSupervisorToggle- hideWhenExpanded- agentId={supervisingAgentId}- expand={showPortal || chatVisible}- label={- managerConversation ? t('goalProcess.manager.viewTrace') : t('goalChat.title')- }- onToggle={openPanel}- />- )- }- />- <Flexbox flex={1} style={{ overflowY: 'auto' }}>- <WideScreenContainer gap={20} paddingBlock={16}>- <Flexbox className={styles.header} gap={8}>- <Text as={'h1'} fontSize={22} weight={600}>- {goal.title}- </Text>- <GoalHeaderMetrics goalId={goalId} />- {/* Pause/resume above the requirement document — its reviewed+ <GoalHeaderMetrics goalId={goalId} />+ {/* Pause/resume above the requirement document — its reviewedhome. The status glyph keeps the "running" animation; thisbutton is only the control. */}- {/* A draft is still being arranged: nothing has been dispatched,+ {/* A draft is still being arranged: nothing has been dispatched,and starting it is the one explicit move into running. */}- {goal.status === 'draft' && (- <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>- {canEdit && canStart && (+ {goal.status === 'draft' && (+ <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>+ {canEdit && canStart && (+ <Button+ icon={PlayIcon}+ loading={starting}+ type={'primary'}+ onClick={async () => {+ setStarting(true);+ try {+ await startGoal(goal.id);+ } catch (error) {+ toast.error((error as Error).message);+ } finally {+ setStarting(false);+ }+ }}+ >+ {t('goalProcess.start')}+ </Button>+ )}+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.draft')}+ </Text>+ </Flexbox>+ )}+ {canPause && (+ <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}><Button- icon={PlayIcon}- loading={starting}- type={'primary'}- onClick={async () => {- setStarting(true);- try {- await startGoal(goal.id);- } catch (error) {- toast.error((error as Error).message);- } finally {- setStarting(false);- }- }}+ icon={paused ? PlayIcon : PauseIcon}+ type={paused ? 'primary' : 'default'}+ onClick={() => void (paused ? resumeGoal(goal.id) : pauseGoal(goal.id))}>- {t('goalProcess.start')}+ {paused ? t('goalProcess.resume') : t('goalProcess.pause')}</Button>- )}- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.draft')}- </Text>- </Flexbox>- )}- {canPause && (- <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>- <Button- icon={paused ? PlayIcon : PauseIcon}- type={paused ? 'primary' : 'default'}- onClick={() => void (paused ? resumeGoal(goal.id) : pauseGoal(goal.id))}- >- {paused ? t('goalProcess.resume') : t('goalProcess.pause')}- </Button>- {paused && (- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.paused')}- </Text>- )}- </Flexbox>- )}- {goal.requirement && (- <GoalRequirement goalId={goal.id} requirement={goal.requirement} />- )}- {/* North-star strip follows the requirement it measures: the+ {paused && (+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.paused')}+ </Text>+ )}+ </Flexbox>+ )}+ {goal.requirement && (+ <GoalRequirement goalId={goal.id} requirement={goal.requirement} />+ )}+ {/* North-star strip follows the requirement it measures: thenumbers are what executing that requirement has observed sofar, so they read as its outcome, below it. */}- <NorthStarMetrics canEdit={canEdit} goalId={goalId} />- </Flexbox>+ <NorthStarMetrics canEdit={canEdit} goalId={goalId} />+ </Flexbox>- <ProcessControl- goalId={goal.id}- graphFullscreen={graphFullscreen}- onGraphFullscreenChange={setGraphFullscreen}- onFollowUp={- // Viewers can read the result but not talk to its agent; the- // backend would reject the turn, so they get no composer.- canEdit && panelTarget- ? (message) => {- // Same destination as the header entry — the supervision record- // when there is one — and it replaces any open drill-down.- clearPortalStack();- chat.openConversation({ ...panelTarget, initialMessage: message });- }- : undefined- }- />- </WideScreenContainer>+ <ProcessControl+ goalId={goal.id}+ graphFullscreen={graphFullscreen}+ onGraphFullscreenChange={setGraphFullscreen}+ onFollowUp={+ // Viewers can read the result but not talk to its agent; the+ // backend would reject the turn, so they get no composer.+ canEdit && panelTarget+ ? (message) => {+ // Same destination as the header entry — the supervision record+ // when there is one — and it replaces any open drill-down.+ clearPortalStack();+ chat.openConversation({ ...panelTarget, initialMessage: message });+ }+ : undefined+ }+ />+ </WideScreenContainer>+ </Flexbox></Flexbox>- </Flexbox>- {/* Same Portal the conversation surface uses — the drill-down chain+ {/* Same Portal the conversation surface uses — the drill-down chain(metric / node → task detail → topic) rides its view stack, and theheader's back arrow and close come for free. When no drill-down isopen, the panel hosts the goal agent's supervision record, or its side@@ -325,46 +358,53 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {way: a second host would render the same detail twice while squeezingthe goal column to nothing beside it. The goal conversation and thesupervision trace have no other home, so those still mount here. */}- <RightPanel- expand={(showPortal ? !hasWorkspaceSidePanel : chatVisible) && !graphFullscreen}- maxWidth={maxWidth}- minWidth={minWidth}- width={width}- onSizeChange={(size) => updateWidth(size?.width)}- onExpandChange={(next) => {- if (!next) clearPortalStack();- chat.setOpen(next);- }}- >- {graphFullscreen ? null : showPortal ? (- hasWorkspaceSidePanel ? null : (- <PortalContent />- )- ) : supervisingAgentId && chat.topicId ? (- <GoalSupervision- agentId={supervisingAgentId}- goalId={goalId}- initialMessage={chat.initialMessage}- key={`${goalId}:${supervisingAgentId}:${chat.request}`}- topicId={chat.topicId}- onCollapse={() => chat.setOpen(false)}- onInitialMessageConsumed={chat.consumeInitialMessage}- // A question that should not land in the manager's own record.- onOpenChat={() => chat.openConversation({ agentId: supervisingAgentId })}- />- ) : supervisingAgentId ? (- <GoalChat- agentId={supervisingAgentId}- goalId={goalId}- initialMessage={chat.initialMessage}- initialTopicId={chat.topicId}- key={`${goalId}:${supervisingAgentId}:${chat.request}`}- onCollapse={() => chat.setOpen(false)}- onInitialMessageConsumed={chat.consumeInitialMessage}- />- ) : null}- </RightPanel>- </Flexbox>+ <RightPanel+ expand={(showPortal ? !hasWorkspaceSidePanel : chatVisible) && !graphFullscreen}+ maxWidth={maxWidth}+ minWidth={minWidth}+ width={width}+ onSizeChange={(size) => updateWidth(size?.width)}+ onExpandChange={(next) => {+ if (!next) clearPortalStack();+ chat.setOpen(next);+ }}+ >+ {graphFullscreen ? null : showPortal ? (+ hasWorkspaceSidePanel ? null : (+ <PortalContent />+ )+ ) : supervisingAgentId && chat.topicId ? (+ <GoalSupervision+ agentId={supervisingAgentId}+ goalId={goalId}+ initialMessage={chat.initialMessage}+ key={`${goalId}:${supervisingAgentId}:${chat.request}`}+ topicId={chat.topicId}+ onCollapse={() => chat.setOpen(false)}+ onInitialMessageConsumed={chat.consumeInitialMessage}+ // A question that should not land in the manager's own record.+ onOpenChat={() => chat.openConversation({ agentId: supervisingAgentId })}+ />+ ) : chat.awaitingRecord ? (+ // The supervision record is on its way: show it loading, not the+ // side conversation's empty welcome.+ <Flexbox flex={1} padding={16}>+ <ConversationSkeleton />+ </Flexbox>+ ) : supervisingAgentId ? (+ <GoalChat+ agentId={supervisingAgentId}+ goalId={goalId}+ initialMessage={chat.initialMessage}+ initialTopicId={chat.topicId}+ key={`${goalId}:${supervisingAgentId}:${chat.request}`}+ onCollapse={() => chat.setOpen(false)}+ onInitialMessageConsumed={chat.consumeInitialMessage}+ />+ ) : null}+ </RightPanel>+ </Flexbox>+ </GoalConversationContext>);});diff --git a/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsxindex 0067457fa59..a2b2bfa218c 100644--- a/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx@@ -1,8 +1,19 @@'use client';-import { Button, createStaticStyles, cssVar, cx, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import {+ ActionIcon,+ Button,+ createStaticStyles,+ cssVar,+ cx,+ Flexbox,+ Icon,+ Tooltip,+} from '@lobehub/ui';import { Handle, type NodeProps, Position } from '@xyflow/react';import {+ ChevronLeft,+ ChevronRight,CircleCheck,CircleDashed,CircleDot,@@ -13,7 +24,7 @@ import {TestTubeDiagonal,Waves,} from 'lucide-react';-import { memo, type ReactNode } from 'react';+import { memo, type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';@@ -343,7 +354,9 @@ const GroupShell = memo<{onEnter?: () => void;status: GroupStatus;title: string;-}>(({ children, foot, hint, icon, iconColor, onEnter, status, title }) => {+ /** A control that belongs in the head, before the enter button. */+ toolbar?: ReactNode;+}>(({ children, foot, hint, icon, iconColor, onEnter, status, title, toolbar }) => {const { t } = useTranslation('chat');return (<div className={styles.group}>@@ -360,18 +373,21 @@ const GroupShell = memo<{</Tooltip>)}</Flexbox>- {onEnter && (- <Button- className={'nodrag'}- size={'small'}- onClick={(event) => {- event.stopPropagation();- onEnter();- }}- >- {t('goalBatch.enter')}- </Button>- )}+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>+ {toolbar}+ {onEnter && (+ <Button+ className={'nodrag'}+ size={'small'}+ onClick={(event) => {+ event.stopPropagation();+ onEnter();+ }}+ >+ {t('goalBatch.enter')}+ </Button>+ )}+ </Flexbox></div>{children}<div className={styles.foot}>@@ -472,11 +488,26 @@ export interface BatchExperimentProbeData extends Record<string, unknown> {views: Record<string, GoalNodeView>;}+/** Heads the unit's own brief in a re-run's description, after the shared plan. */+const CARRIED_BRIEF_HEADING = 'Unit brief (from its first run):';++/**+ * A probe's one-line subtitle: its own brief. A re-run's description opens with+ * the shared plan, so its subtitle is the brief it carried over from its first run.+ */+const probeSubtitle = (description?: string | null) => {+ if (!description) return '';+ const carried = description.indexOf(CARRIED_BRIEF_HEADING);+ const own =+ carried >= 0 ? description.slice(carried + CARRIED_BRIEF_HEADING.length) : description;+ return own.trim().split('\n')[0] ?? '';+};+const ProbeCell = memo<{ onSelect: (id: string) => void; probe: BatchProbe; view?: GoalNodeView }>(({ onSelect, probe, view }) => {const { t } = useTranslation('chat');const visual = CELL_VISUAL[probe.state];- const subtitle = view?.node.description?.split('\n')[0] ?? '';+ const subtitle = probeSubtitle(view?.node.description);return (<div className={styles.probeCell} data-probe={probe.nodeId} data-state={probe.state}><StatusText@@ -528,8 +559,20 @@ const ProbeCell = memo<{ onSelect: (id: string) => void; probe: BatchProbe; viewProbeCell.displayName = 'GoalBatchProbeCell';export const BatchExperimentProbeGroup = memo<NodeProps>(({ data }) => {- const { onEnter, onSelect, probes, started, views } = data as BatchExperimentProbeData;+ const { onEnter, onSelect, probes: latest, started, views } = data as BatchExperimentProbeData;const { t } = useTranslation('chat');+ // Trials sent back and run again in the round: one switch in the head picks+ // which run the cards show, the latest unless the reader goes back.+ const attempts = Math.max(1, ...latest.map((probe) => probe.attempt ?? 1));+ const [picked, setPicked] = useState<number>();+ const attempt = picked && picked <= attempts ? picked : attempts;+ const probes =+ attempt === attempts+ ? latest+ : latest.map((probe) => {+ const run = probe.runs?.[attempt - 1];+ return run ? { ...probe, ...run } : probe;+ });const status = useUnitsStatus()(probes,{@@ -546,6 +589,39 @@ export const BatchExperimentProbeGroup = memo<NodeProps>(({ data }) => {iconColor={KIND_COLOR.batch.line}status={status}title={t('goalBatch.probes.title')}+ toolbar={+ attempts > 1 && (+ // A plan can be sent back many times before it passes: step through+ // the runs one at a time rather than listing every one of them.+ <Flexbox horizontal align={'center'} className={'nodrag'} gap={2}>+ <ActionIcon+ aria-label={t('goalBatch.probes.attemptPrevious')}+ disabled={attempt <= 1}+ icon={ChevronLeft}+ size={'small'}+ title={t('goalBatch.probes.attemptPrevious')}+ onClick={(event) => {+ event.stopPropagation();+ setPicked(attempt - 1);+ }}+ />+ <span className={styles.muted} style={{ fontVariantNumeric: 'tabular-nums' }}>+ {t('goalBatch.probes.attemptOf', { current: attempt, total: attempts })}+ </span>+ <ActionIcon+ aria-label={t('goalBatch.probes.attemptNext')}+ disabled={attempt >= attempts}+ icon={ChevronRight}+ size={'small'}+ title={t('goalBatch.probes.attemptNext')}+ onClick={(event) => {+ event.stopPropagation();+ setPicked(attempt + 1);+ }}+ />+ </Flexbox>+ )+ }onEnter={onEnter}><div className={styles.probeGrid}>diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.tsindex 24ea0c815d9..64b333c9b36 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts@@ -228,6 +228,38 @@ describe('buildBatchModel', () => {expect(model.rounds[0].gate).toBe('rejected');});+ // Sending the plan back re-runs the trials inside their round, under the+ // same gate: the trials stage shows each unit once, as its latest run, in+ // its original place — not a superseded square next to a second round.+ it('keeps a trial re-run inside its round as one numbered unit', () => {+ const graph = buildGoalGraphView(+ batchSnapshot({+ decisions: [humanAnswer('r0')],+ extraEdges: [edge('p1r', 'p1', 'derived_from'), edge('a1', 'p1r', 'depends_on')],+ extraNodes: [+ node('r0', 'decision', 10, { status: 'resolved', title: GOAL_BATCH_RELEASE_TITLE }),+ node('p1r', 'task', 20, { status: 'active', title: 'U1', updatedAt: at(59) }),+ ],+ state: { planVersions: { '1': 2 }, probeNodeIds: ['p1r', 'p2'] },+ }),+ NOW,+ );+ const model = buildBatchModel(graph, 'batch');++ expect(model.rounds).toHaveLength(1);+ expect(model.rounds[0]).toMatchObject({ planVersion: 2, revision: 1 });+ expect(model.rounds[0].probes).toEqual([+ expect.objectContaining({ attempt: 2, nodeId: 'p1r', state: 'running', title: 'U1' }),+ expect.objectContaining({ nodeId: 'p2', state: 'done', title: 'U2' }),+ ]);+ expect(model.rounds[0].probes[1].attempt).toBeUndefined();+ // Its first run stays readable, as it ended — for the switch back to run 1.+ expect(model.rounds[0].probes[0].runs).toEqual([+ { nodeId: 'p1', state: 'done' },+ { nodeId: 'p1r', state: 'running' },+ ]);+ });+it('keeps the gate locked until every probe settled', () => {const snapshot = batchSnapshot({ state: {} });snapshot.nodes = snapshot.nodes.map((n) =>diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.tsindex 431998bac6d..aac1b622098 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts@@ -52,8 +52,12 @@ export type BatchUnitOrigin =| { index: number; kind: 'wave'; wave: number };export interface BatchProbe {+ /** Which run of the unit this is, when it was sent back and run again in the round (2, 3…). */+ attempt?: number;from?: BatchUnitOrigin;nodeId: string;+ /** Every run of a unit sent back inside its round, first to latest — this one last. */+ runs?: { nodeId: string; state: BatchCellState }[];state: BatchCellState;title: string;}@@ -310,16 +314,62 @@ export const buildBatchModel = (graph: GoalGraphView, batchId: string): BatchMod});const rounds: BatchRound[] = probeIdsByRound.map((ids, r) => {+ // A unit sent back and run again inside its round keeps one place there:+ // its latest run, numbered, instead of a superseded square beside it.+ const inRound = new Set(ids);+ const rerunOf = new Map(+ graph.edges+ .filter(+ (edge) =>+ edge.kind === 'derived_from' &&+ inRound.has(edge.sourceNodeId) &&+ inRound.has(edge.targetNodeId),+ )+ .map((edge) => [edge.sourceNodeId, edge.targetNodeId]),+ );+ const rerun = new Set(rerunOf.values());+ const attemptOf = (id: string): number => {+ const earlier = rerunOf.get(id);+ return earlier ? attemptOf(earlier) + 1 : 1;+ };+ // Where the unit first ran, so a re-run keeps its place among the trials.+ const firstRunOf = (id: string): string => {+ const earlier = rerunOf.get(id);+ return earlier ? firstRunOf(earlier) : id;+ };+ // The unit's runs in this round, first to latest.+ const runsOf = (id: string): string[] => {+ const earlier = rerunOf.get(id);+ return earlier ? [...runsOf(earlier), id] : [id];+ };const probes = ids+ .filter((id) => !rerun.has(id)).map((id) => graph.byId[id]).filter((view): view is GoalNodeView => !!view)- .sort(byCreatedAt)- .map((view) => ({- from: r > 0 ? originOf(view) : undefined,- nodeId: view.node.id,- state: cellOf(view.node.id),- title: view.node.title,- }));+ .sort(+ (a, b) =>+ byCreatedAt(+ graph.byId[firstRunOf(a.node.id)] ?? a,+ graph.byId[firstRunOf(b.node.id)] ?? b,+ ) || byCreatedAt(a, b),+ )+ .map((view) => {+ const attempt = attemptOf(view.node.id);+ return {+ ...(attempt > 1 && {+ attempt,+ // A superseded run is history here, read as it ended, not as superseded.+ runs: runsOf(view.node.id).map((id) => ({+ nodeId: id,+ state: batchCellState(graph.byId[id], waitingOn),+ })),+ }),+ from: r > 0 ? originOf(view) : undefined,+ nodeId: view.node.id,+ state: cellOf(view.node.id),+ title: view.node.title,+ };+ });const template = templates[r];const assay = assays[r];const previousTemplate = templates[r - 1];diff --git a/src/features/AgentGoals/ProcessControl/ReleaseGateEntry.tsx b/src/features/AgentGoals/ProcessControl/ReleaseGateEntry.tsxindex 72f62ba7310..addfb9b0ce5 100644--- a/src/features/AgentGoals/ProcessControl/ReleaseGateEntry.tsx+++ b/src/features/AgentGoals/ProcessControl/ReleaseGateEntry.tsx@@ -6,9 +6,9 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { openGateReportModal } from '@/features/Acceptance/Viewer/Gate';-import { useGoalStore } from '@/store/goal';import { coordinatorGateReason, localizedCoordinatorReason } from './coordinatorCopy';+import { useReleaseGateDecided } from './useReleaseGateDecided';/*** A held batch release, as an entry rather than an answer: the release is a@@ -21,7 +21,7 @@ const ReleaseGateEntry = memo<{goalId: string;}>(({ acceptanceId, decision, goalId }) => {const { t } = useTranslation('chat');- const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);+ const onDecided = useReleaseGateDecided(goalId);return (<Flexbox gap={12}><Text strong>{t('goalProcess.gate.title.batchRelease')}</Text>@@ -29,12 +29,7 @@ const ReleaseGateEntry = memo<{{localizedCoordinatorReason(coordinatorGateReason(decision.question), t as any)}</Text><Flexbox horizontal justify={'flex-end'}>- <Button- type={'primary'}- onClick={() =>- openGateReportModal({ acceptanceId, onDecided: () => refreshGoalGraph(goalId) })- }- >+ <Button type={'primary'} onClick={() => openGateReportModal({ acceptanceId, onDecided })}>{t('goalProcess.gate.openReview')}</Button></Flexbox>diff --git a/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.test.ts b/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.test.tsnew file mode 100644index 00000000000..385f39cb5d5--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.test.ts@@ -0,0 +1,69 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GoalConversationContext } from '../goalConversation';+import { useReleaseGateDecided } from './useReleaseGateDecided';++const refreshGoalGraph = vi.hoisted(() => vi.fn(async () => {}));++vi.mock('@/store/goal', () => ({+ useGoalStore: (selector: (state: { refreshGoalGraph: () => void }) => unknown) =>+ selector({ refreshGoalGraph }),+}));++/** The hook as the goal page mounts it: with the page's conversation opener in context. */+const onGoalPage = (openConversation = vi.fn()) => {+ const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(GoalConversationContext, { value: openConversation }, children);+ const { result } = renderHook(() => useReleaseGateDecided('goal-1'), { wrapper });+ return { decide: result.current, openConversation };+};++describe('useReleaseGateDecided', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('opens the goal conversation after the plan is sent back, so the owner sees the correction land', async () => {+ let refreshed = false;+ refreshGoalGraph.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) =>+ setTimeout(() => {+ refreshed = true;+ resolve();+ }, 0),+ ),+ );+ const openConversation = vi.fn(() => {+ // Opened on the goal as the send-back left it, not before.+ expect(refreshed).toBe(true);+ });+ const { decide } = onGoalPage(openConversation);++ await decide('revise');++ expect(refreshGoalGraph).toHaveBeenCalledWith('goal-1');+ expect(openConversation).toHaveBeenCalledTimes(1);+ });++ it('leaves the panel alone when the next wave is released', async () => {+ const { decide, openConversation } = onGoalPage();++ await decide('release');++ expect(refreshGoalGraph).toHaveBeenCalledWith('goal-1');+ expect(openConversation).not.toHaveBeenCalled();+ });++ it('still refreshes the goal where no page hosts its conversation', async () => {+ const { result } = renderHook(() => useReleaseGateDecided('goal-1'));++ await expect(result.current('revise')).resolves.toBeUndefined();+ expect(refreshGoalGraph).toHaveBeenCalledWith('goal-1');+ });+});diff --git a/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.ts b/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.tsnew file mode 100644index 00000000000..5ced97e3af9--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useReleaseGateDecided.ts@@ -0,0 +1,23 @@+import type { GateDecisionKind } from '@/features/Acceptance/Viewer/Gate';+import { useGoalStore } from '@/store/goal';++import { useOpenGoalConversation } from '../goalConversation';++/**+ * What the goal page does once its release gate is decided: the graph moves on+ * either way, and a plan sent back opens the goal's conversation — the+ * correction goes to the main Agent as a message, so the owner sees it sent+ * and the agent take it up instead of the gate going quiet.+ */+export const useReleaseGateDecided = (goalId: string) => {+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);+ const openGoalConversation = useOpenGoalConversation();+ return async (outcome: GateDecisionKind) => {+ const refreshed = refreshGoalGraph(goalId);+ if (outcome !== 'revise') return void refreshed;+ // The send-back handed the correction over within its request: read the+ // goal with that hand-off first, so the panel opens on it straight away.+ await refreshed.catch(() => {});+ openGoalConversation?.();+ };+};diff --git a/src/features/AgentGoals/goalConversation.ts b/src/features/AgentGoals/goalConversation.tsnew file mode 100644index 00000000000..6dbc1cf6f66--- /dev/null+++ b/src/features/AgentGoals/goalConversation.ts@@ -0,0 +1,13 @@+'use client';++import { createContext, use } from 'react';++/**+ * Bring the goal's conversation into the right panel, replacing any open+ * drill-down. Provided by the goal detail page so actions deep in the process+ * view — or in the portal it hosts — can show the owner what the agent was+ * just sent. Absent where no page owns that panel.+ */+export const GoalConversationContext = createContext<(() => void) | undefined>(undefined);++export const useOpenGoalConversation = () => use(GoalConversationContext);diff --git a/src/features/AgentGoals/useGoalChatPanel.test.ts b/src/features/AgentGoals/useGoalChatPanel.test.tsindex e240cff851b..1a7e3fd2851 100644--- a/src/features/AgentGoals/useGoalChatPanel.test.ts+++ b/src/features/AgentGoals/useGoalChatPanel.test.ts@@ -79,4 +79,52 @@ describe('useGoalChatPanel', () => {act(() => result.current.setOpen(true));expect(result.current).toMatchObject({ open: true, agentId: 'worker-b' });});++ // Sending a plan back hands the correction to the main Agent, whose turn may+ // be the one that opens the supervision record; the panel must end up there,+ // not on the side conversation it opened while the record did not exist.+ it('moves to the supervision record once the awaited record exists', () => {+ const { rerender, result } = renderHook(+ ({ record }: { record?: typeof manager }) => useGoalChatPanel('goal-a', 'creator', record),+ { initialProps: {} as { record?: typeof manager } },+ );++ act(() => result.current.openAwaitingRecord({ agentId: 'creator' }));+ expect(result.current).toMatchObject({ agentId: 'creator', awaitingRecord: true, open: true });+ expect(result.current.topicId).toBeUndefined();+ const fallbackRequest = result.current.request;++ rerender({ record: manager });+ expect(result.current).toMatchObject({ awaitingRecord: false, open: true, ...manager });+ expect(result.current.request).not.toBe(fallbackRequest);++ // Followed once: closing the panel later does not get it reopened.+ act(() => result.current.setOpen(false));+ rerender({ record: manager });+ expect(result.current.open).toBe(false);+ });++ it('does not move to a record nobody is waiting for', () => {+ const { rerender, result } = renderHook(+ ({ record }: { record?: typeof manager }) => useGoalChatPanel('goal-a', 'creator', record),+ { initialProps: {} as { record?: typeof manager } },+ );++ act(() => result.current.openConversation({ agentId: 'creator' }));+ rerender({ record: manager });++ expect(result.current.topicId).toBeUndefined();+ });++ // The main Agent may never take the correction up (no turn left, goal paused):+ // waiting gives way to the conversation the panel opened on.+ it('stays on the opened conversation once it stops waiting', () => {+ const { result } = renderHook(() => useGoalChatPanel('goal-a', 'creator'));++ act(() => result.current.openAwaitingRecord({ agentId: 'creator' }));+ act(() => result.current.stopAwaitingRecord());++ expect(result.current).toMatchObject({ agentId: 'creator', awaitingRecord: false, open: true });+ expect(result.current.topicId).toBeUndefined();+ });});diff --git a/src/features/AgentGoals/useGoalChatPanel.ts b/src/features/AgentGoals/useGoalChatPanel.tsindex 29f75cf12c2..1a2b08b81e5 100644--- a/src/features/AgentGoals/useGoalChatPanel.ts+++ b/src/features/AgentGoals/useGoalChatPanel.ts@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useCallback, useState } from 'react';interface ConversationTarget {agentId: string;@@ -9,6 +9,11 @@ interface ConversationTarget {}interface PanelState {+ /**+ * The panel waits for the goal's supervision record: a correction went to+ * the main Agent, whose turn opens the record a moment later.+ */+ awaitingRecord?: boolean;goalId: string;open: boolean;request: number;@@ -16,14 +21,34 @@ interface PanelState {}/** Keep the selected conversation within this goal's inspection session. */-export const useGoalChatPanel = (goalId: string, responsibleAgentId?: string) => {+export const useGoalChatPanel = (+ goalId: string,+ responsibleAgentId?: string,+ /** The goal's supervision record, once its main Agent has one. */+ record?: ConversationTarget,+) => {const [state, setState] = useState<PanelState>({ goalId, open: false, request: 0 });- const current: PanelState = state.goalId === goalId ? state : { goalId, open: false, request: 0 };+ let current: PanelState = state.goalId === goalId ? state : { goalId, open: false, request: 0 };- if (state.goalId !== goalId) setState(current);+ // The awaited record landed: the panel follows it, unless it is already there.+ if (current.awaitingRecord && record) {+ current =+ current.target?.topicId === record.topicId+ ? { ...current, awaitingRecord: false }+ : { goalId, open: true, request: current.request + 1, target: record };+ }+ if (current !== state) setState(current);++ // Stable, so a timer keyed on it is not restarted by every render.+ const stopAwaitingRecord = useCallback(+ () => setState((prev) => (prev.awaitingRecord ? { ...prev, awaitingRecord: false } : prev)),+ [],+ );return {agentId: current.target?.agentId ?? responsibleAgentId,+ /** Opened for a supervision record that does not exist yet; see `openAwaitingRecord`. */+ awaitingRecord: !!current.awaitingRecord,initialMessage: current.target?.initialMessage,/*** Acknowledge the handed-off message once the panel has sent or filled it in. The panel@@ -43,7 +68,23 @@ export const useGoalChatPanel = (goalId: string, responsibleAgentId?: string) =>openConversation: (target: ConversationTarget) => {setState({ goalId, open: true, request: current.request + 1, target });},+ /**+ * Open the panel on `fallback` now and move it to the supervision record as+ * soon as one exists — for a correction the main Agent takes up in a record+ * its turn has yet to open.+ */+ openAwaitingRecord: (fallback: ConversationTarget) => {+ setState({+ awaitingRecord: true,+ goalId,+ open: true,+ request: current.request + 1,+ target: fallback,+ });+ },request: current.request,+ /** Stop waiting for the record: the panel stays on the conversation it opened on. */+ stopAwaitingRecord,// A pending message survives folding the panel; only `consumeInitialMessage`// drops it, once the panel has actually handed it off.setOpen: (open: boolean) => setState({ ...current, open }),