Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(acceptance): keep flow zoom on node click and stop draft rounds from inflating (#19350)

Arvin Xuc17b9a938864
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 900c7a3024d..5c8ea90f2b6 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -714,8 +714,9 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
process.exit(1);
}
- // Every ingest is a new immutable verification snapshot. A repair or
- // re-verification is represented by another run on the same acceptance.
+ // Every ingest is an immutable verification snapshot. A repair or
+ // re-verification is another round on the same acceptance, unless the
+ // acceptance still holds a draft round: the server folds this run into it.
const run = await client.verify.createRun.mutate({
context,
goal,
@@ -726,13 +727,15 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
source: options.source as any,
title,
});
- const runId = run.id;
-
// 1c. Chain the session onto its subject's acceptance as the next round
// BEFORE the report lands, so the report-time status rollup already
- // sees the aggregate.
+ // sees the aggregate. Results and the report go to the round the server
+ // returns, which is the draft round when this run was folded into one.
const acceptanceId = acceptance.id;
- const attached = await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: runId });
+ const attached = await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: run.id });
+ const runId = attached?.id ?? run.id;
+ if (runId !== run.id)
+ console.log(pc.dim(`Folded into the acceptance's draft round ${attached.roundIndex ?? ''}`));
// The chained round's index — `?r=<roundIndex>` on the acceptance URL
// deep-links this round's report as the fixed snapshot view.
const roundIndex = attached?.roundIndex ?? null;
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
index 255765374b3..5dc4f5935e6 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
findPolicyById: vi.fn(),
findReportByRun: vi.fn(),
findRunById: vi.fn(),
+ foldIntoRound: vi.fn(),
ensureForSubject: vi.fn(),
listByAcceptance: vi.fn(),
setDecision: vi.fn(),
@@ -31,6 +32,7 @@ vi.mock('@/database/models/verifyRun', () => ({
VerifyRunModel: vi.fn(() => ({
attachToAcceptance: mocks.attachToAcceptance,
findById: mocks.findRunById,
+ foldIntoRound: mocks.foldIntoRound,
listByAcceptance: mocks.listByAcceptance,
setDecision: mocks.setDecision,
})),
@@ -156,6 +158,38 @@ describe('AcceptanceService decision gating', () => {
expect(mocks.attachToAcceptance).toHaveBeenCalledWith('run-2', 'acc-1', undefined);
});
+ it('folds a new run into the draft round instead of opening another', async () => {
+ mocks.findById.mockResolvedValue(acceptance('planned'));
+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2', plan: [] });
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', planConfirmedAt: null, roundIndex: 1, status: 'planned', userDecision: null },
+ ]);
+ mocks.foldIntoRound.mockResolvedValue({ acceptanceId: 'acc-1', id: 'run-1', roundIndex: 1 });
+
+ await expect(service().attachRun('run-2', 'acc-1')).resolves.toMatchObject({ id: 'run-1' });
+ expect(mocks.foldIntoRound).toHaveBeenCalledWith('run-2', 'run-1');
+ expect(mocks.attachToAcceptance).not.toHaveBeenCalled();
+ });
+
+ it('opens a new round when the newest one is no longer a draft', async () => {
+ mocks.findById.mockResolvedValue(acceptance('planned'));
+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-3', plan: [] });
+ // Ascending chain: an abandoned draft sits behind an executed newer round.
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', planConfirmedAt: null, roundIndex: 1, status: 'planned', userDecision: null },
+ { id: 'run-2', planConfirmedAt: new Date(), roundIndex: 2, status: null, userDecision: null },
+ ]);
+ mocks.attachToAcceptance.mockResolvedValue({
+ acceptanceId: 'acc-1',
+ id: 'run-3',
+ roundIndex: 3,
+ });
+
+ await expect(service().attachRun('run-3', 'acc-1')).resolves.toMatchObject({ id: 'run-3' });
+ expect(mocks.foldIntoRound).not.toHaveBeenCalled();
+ expect(mocks.attachToAcceptance).toHaveBeenCalledWith('run-3', 'acc-1', undefined);
+ });
+
it.each(['delivered', 'errored'])('accepts a settled (%s) delivery', async (status) => {
mocks.findById.mockResolvedValue(acceptance(status));
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 295bfb451e4..25870ebae03 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -1,4 +1,4 @@
-import { normalizeVerifySurface } from '@lobechat/const/verify';
+import { isDraftVerifyRun, normalizeVerifySurface } from '@lobechat/const/verify';
import type {
AcceptanceAttachment,
AcceptanceCheckGroup,
@@ -688,6 +688,24 @@ export class AcceptanceService {
await this.assertPlanLeavesAcceptedChecksAlone(existing, acceptanceId);
+ // A round that is still only planned has nothing to preserve: the incoming
+ // run folds into it instead of pushing the ledger to yet another number.
+ // Only the newest round counts — `listByAcceptance` is ascending, and an
+ // older draft the chain has moved past is an abandoned ledger position.
+ const latest = (await this.runModel.listByAcceptance(acceptanceId)).at(-1);
+ const draft = latest && isDraftVerifyRun(latest) ? latest : undefined;
+ if (draft) {
+ const folded = await this.runModel.foldIntoRound(runId, draft.id);
+ await this.recomputeStatus(acceptanceId);
+ log(
+ 'run %s folded into draft round %d of acceptance %s',
+ runId,
+ folded.roundIndex,
+ acceptanceId,
+ );
+ return folded;
+ }
+
// Rounds inherit the aggregate's visibility so a private acceptance's new
// round never leaks through its own report URL.
const run = await this.runModel.attachToAcceptance(runId, acceptanceId, acceptance.visibility);
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index dc8e787ade9..5f56fd4174a 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -503,7 +503,7 @@
"flow.noAttachments": "No additional evidence attached. See the observation above.",
"flow.nodeCount": "{{count}} nodes",
"flow.outlineView": "Steps",
- "flow.pendingPlan": "Pending verification plan",
+ "flow.pendingPlan": "Draft",
"flow.plan.actionError": "Unable to update the flow plan. Refresh and review the latest plan before retrying.",
"flow.plan.feedbackDescription": "Describe which journeys, branches or expected outcomes need to change.",
"flow.plan.label": "Acceptance flow plan",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 353cbbd9fdf..ebb5fba3c4b 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -503,7 +503,7 @@
"flow.noAttachments": "暂无附加证据,可先查看上方实际结果。",
"flow.nodeCount": "{{count}} 个节点",
"flow.outlineView": "步骤",
- "flow.pendingPlan": "待验证计划",
+ "flow.pendingPlan": "草稿",
"flow.plan.actionError": "流程计划更新失败,请刷新并检查最新计划后重试。",
"flow.plan.feedbackDescription": "说明哪些业务流程、分支或预期结果需要调整。",
"flow.plan.label": "验收流程计划",
diff --git a/packages/builtin-skills/src/acceptance/SKILL.md b/packages/builtin-skills/src/acceptance/SKILL.md
index 4f614120154..4f6e97eb13f 100644
--- a/packages/builtin-skills/src/acceptance/SKILL.md
+++ b/packages/builtin-skills/src/acceptance/SKILL.md
@@ -165,8 +165,10 @@ execution semantics.
current `expectedHash` in the file. `lh acceptance flow view <acceptanceId>`
reads definitions, snapshots and results. Publishing does not execute checks.
3. `lh acceptance flow plan <acceptanceId> --flow <flowId>` creates a draft round
- with a frozen graph and plan. Add `--run <verifyRunId>` to attach another flow
- to the same open round. Read `lh acceptance run get <verifyRunId> --json` for
+ with the graph and its plan. While the round is only planned it follows the
+ live graph: publishing an edit refreshes its snapshot and plan in place, and
+ running `flow plan` again refreshes the same draft instead of opening another
+ round. Add `--run <verifyRunId>` to attach another flow to the same draft. Read `lh acceptance run get <verifyRunId> --json` for
the actual plan IDs: each branch and subflow invocation has its own
`checkItemId`; never substitute the reusable asset ID.
4. Share the acceptance link so the user can inspect the proposed nodes, branches
@@ -174,8 +176,9 @@ execution semantics.
feedback. Preparing a plan neither executes checks nor approves delivery;
there is no separate flow-confirmation action. Continue within the user's
authorized scope, or pause if the user explicitly asked to review before work.
- For requested changes, publish the revised definition and prepare a new draft
- round in the same acceptance.
+ For requested changes, publish the revised definition with its `flowId` and
+ `expectedHash`; the draft round follows automatically. Never open another
+ round or another flow just to revise a plan that has not executed.
5. Implement the work and exercise the real product, then use
`lh acceptance flow record <acceptanceId> --file result.json`, containing
`verifyRunId`, `checkItemId`, `verdict` (`passed`, `failed`, `uncertain`, or
@@ -189,7 +192,10 @@ execution semantics.
To rerun the exact old graph, prepare a plan with `--from-run <sourceVerifyRunId>` and
omit `--run` for a fresh round. This preserves the old definition and starts
-without results. Each replay starts as an unexecuted draft. Accepted or closed
+without results. Each replay starts as an unexecuted draft. A round is frozen
+by its first recorded result; only then does it keep its number. An
+`lh acceptance run ingest` that reaches an acceptance whose latest round is
+still a draft folds into that draft rather than opening a new round. Accepted or closed
acceptances must be explicitly reopened
before starting. Edges describe business transitions; they do not automatically
schedule execution. Continue to read `lh acceptance feedback <acceptanceId> --actionable` before repairs and publish new rounds into the same acceptance.
diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.ts
index 8303976db0b..06b1ea1c8fc 100644
--- a/packages/const/src/verify.ts
+++ b/packages/const/src/verify.ts
@@ -71,6 +71,28 @@ export const verifyRunStatuses = [
] as const;
export type VerifyRunStatus = (typeof verifyRunStatuses)[number];
+/**
+ * A draft round only describes what will be verified: nothing has executed and
+ * nobody has decided. Drafts follow the live plan and are reused by the next
+ * plan or ingest instead of consuming another round number.
+ *
+ * A replay is excluded: it is pinned to the source round's frozen definition, so
+ * it must not follow later graph edits or absorb another flow. Only the newest
+ * round can be the open draft — an older one left behind by a replay is an
+ * abandoned ledger position, so callers check the latest round rather than
+ * searching the whole chain.
+ */
+export const isDraftVerifyRun = (run: {
+ metadata?: { replayOfRunId?: string } | null;
+ planConfirmedAt?: Date | string | null;
+ status?: string | null;
+ userDecision?: string | null;
+}): boolean =>
+ run.status === 'planned' &&
+ !run.planConfirmedAt &&
+ !run.userDecision &&
+ !run.metadata?.replayOfRunId;
+
/**
* What produced a verification session.
* - agent: verifying a real Agent Run (`verify_runs.operation_id` set)
diff --git a/packages/database/src/models/__tests__/acceptanceFlow.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
index ca0e6c342ab..9f9ee0d8a01 100644
--- a/packages/database/src/models/__tests__/acceptanceFlow.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
@@ -152,8 +152,11 @@ describe('check assets and round snapshots', () => {
});
const run = await model.start(acceptanceId, parent.flowId);
const round = await roundPlan(run.id);
+ // The child joins the same draft round; read its own occurrences back.
const childRun = await model.start(acceptanceId, child.flowId);
- const childPlan = (await roundPlan(childRun.id)).plan!;
+ const childPlan = (await roundPlan(childRun.id)).plan!.filter(
+ (item) => item.sourceFlowNode?.flowId === child.flowId,
+ );
const expectedIds = [`${a}/entry/`, `${b}/${forward}/`, `${a}/${back}/`].flatMap((prefix) =>
childPlan.map((item) => prefix + item.id),
);
@@ -206,6 +209,127 @@ describe('check assets and round snapshots', () => {
expect((await roundPlan(replay.id)).planConfirmedAt).toBeNull();
});
+ it('keeps a planned round on the live graph while the flow is edited before execution', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const run = await model.start(acceptanceId, flowId);
+ const third = randomUUID();
+ const revised: AcceptanceFlowDefinition = {
+ ...definition,
+ title: 'Send, retry and recover',
+ nodes: [
+ ...definition.nodes,
+ {
+ id: third,
+ check: {
+ id: randomUUID(),
+ title: 'Recovered',
+ definition: {
+ steps: [{ id: 'reconnect', instruction: 'Reconnect' }],
+ expected: 'Message delivered',
+ },
+ },
+ },
+ ],
+ edges: [
+ ...definition.edges,
+ {
+ id: randomUUID(),
+ sourceNodeId: definition.nodes[1].id,
+ targetNodeId: third,
+ trigger: 'Reconnect',
+ required: true,
+ },
+ ],
+ };
+ await model.publish(acceptanceId, revised, flowId, hash);
+ const round = await roundPlan(run.id);
+ expect(round.status).toBe('planned');
+ expect(round.flowSnapshots?.[0].title).toBe('Send, retry and recover');
+ expect(round.flowSnapshots?.[0].nodes.map((n) => n.id)).toContain(third);
+ expect(round.plan?.map((p) => p.sourceFlowNode?.nodeId)).toContain(third);
+ expect(round.plan?.map((p) => p.index)).toEqual(round.plan?.map((_, i) => i));
+ const [flow] = await model.list(acceptanceId);
+ expect(flow.versions).toHaveLength(1);
+ expect(flow.versions[0].runs[0]?.id).toBe(run.id);
+ expect(flow.versions[0].title).toBe('Send, retry and recover');
+ });
+
+ it('plans again into the same draft round instead of opening another', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const draft = await model.start(acceptanceId, flowId);
+ expect((await model.start(acceptanceId, flowId)).id).toBe(draft.id);
+ await model.publish(acceptanceId, { ...definition, title: 'Renamed draft' }, flowId, hash);
+ const again = await model.start(acceptanceId, flowId);
+ expect(again.id).toBe(draft.id);
+ const round = await roundPlan(draft.id);
+ expect(round.roundIndex).toBe(1);
+ expect(round.flowSnapshots?.[0].title).toBe('Renamed draft');
+ expect(
+ await db.select().from(verifyRuns).where(eq(verifyRuns.acceptanceId, acceptanceId)),
+ ).toHaveLength(1);
+ });
+
+ it('leaves an abandoned older draft alone once a newer round has taken over', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const stale = await model.start(acceptanceId, flowId);
+ const staleSnapshot = (await roundPlan(stale.id)).flowSnapshots;
+ // A replay opens its own round and pins the definition it replays.
+ const replay = await model.start(acceptanceId, flowId, undefined, stale.id);
+ expect(replay.id).not.toBe(stale.id);
+ await model.record(acceptanceId, {
+ verifyRunId: replay.id,
+ checkItemId: (await roundPlan(replay.id)).plan![0].id,
+ verdict: 'passed',
+ observation: 'Composer visible',
+ });
+
+ // The newest round is frozen now, so the stale draft must not be reused…
+ await model.publish(acceptanceId, { ...definition, title: 'Edited later' }, flowId, hash);
+ expect((await roundPlan(stale.id)).flowSnapshots).toEqual(staleSnapshot);
+ const fresh = await model.start(acceptanceId, flowId);
+ expect(fresh.id).not.toBe(stale.id);
+ expect((await roundPlan(fresh.id)).roundIndex).toBe(3);
+ });
+
+ it('keeps a replay pinned to the definition it replays while it is still unexecuted', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const first = await model.start(acceptanceId, flowId);
+ await model.record(acceptanceId, {
+ verifyRunId: first.id,
+ checkItemId: (await roundPlan(first.id)).plan![0].id,
+ verdict: 'passed',
+ observation: 'Composer visible',
+ });
+ const replay = await model.start(acceptanceId, flowId, undefined, first.id);
+ const pinned = await roundPlan(replay.id);
+
+ await model.publish(acceptanceId, { ...definition, title: 'Edited later' }, flowId, hash);
+
+ const after = await roundPlan(replay.id);
+ expect(after.flowSnapshots).toEqual(pinned.flowSnapshots);
+ expect(after.plan).toEqual(pinned.plan);
+ // The replay is a numbered round, so planning again opens the next one.
+ expect((await model.start(acceptanceId, flowId)).id).not.toBe(replay.id);
+ });
+
+ it('leaves an executed round frozen when the flow is edited afterwards', async () => {
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const run = await model.start(acceptanceId, flowId);
+ const before = await roundPlan(run.id);
+ await model.record(acceptanceId, {
+ verifyRunId: run.id,
+ checkItemId: before.plan![0].id,
+ verdict: 'passed',
+ observation: 'Composer visible',
+ });
+ await model.publish(acceptanceId, { ...definition, title: 'Renamed after run' }, flowId, hash);
+ const after = await roundPlan(run.id);
+ expect(after.flowSnapshots).toEqual(before.flowSnapshots);
+ expect(after.plan).toEqual(before.plan);
+ const [flow] = await model.list(acceptanceId);
+ expect(flow.versions.map((v) => v.title)).toEqual(['Renamed after run', 'Send and retry']);
+ });
+
it('creates assets before execution and instantiates each incoming branch in the canonical plan', async () => {
const published = await model.publish(acceptanceId, definition);
expect(
@@ -261,6 +385,13 @@ describe('check assets and round snapshots', () => {
const { flowId } = await model.publish(acceptanceId, definition);
const first = await model.start(acceptanceId, flowId);
const initial = await roundPlan(first.id);
+ // Executing freezes the round; only a frozen round keeps the old definition.
+ await model.record(acceptanceId, {
+ verifyRunId: first.id,
+ checkItemId: initial.plan![0].id,
+ verdict: 'passed',
+ observation: 'Composer visible',
+ });
const assetId = definition.nodes[0].check!.id;
await db
.update(verifyCriteria)
@@ -270,6 +401,7 @@ describe('check assets and round snapshots', () => {
const replay = await model.start(acceptanceId, flowId, undefined, first.id);
expect((await roundPlan(first.id)).plan).toEqual(initial.plan);
expect((await roundPlan(replay.id)).plan).toEqual(initial.plan);
+ expect(current.id).not.toBe(first.id);
expect(
(await roundPlan(current.id)).plan?.find((p) => p.sourceCriterionId === assetId)?.definition
?.expected,
diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.ts
index abfdb509e65..eefb9bbb07f 100644
--- a/packages/database/src/models/__tests__/verifyRun.test.ts
+++ b/packages/database/src/models/__tests__/verifyRun.test.ts
@@ -3,7 +3,7 @@ import { eq, sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { users, verifyRuns } from '../../schemas';
+import { acceptances, users, verifyRuns } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentOperationModel } from '../agentOperation';
import { VerifyRunModel } from '../verifyRun';
@@ -236,3 +236,70 @@ describe('VerifyRunModel.findStuckVerifying', () => {
expect(stuck.map((r) => r.id)).not.toContain(run.id);
});
});
+
+describe('VerifyRunModel.foldIntoRound', () => {
+ const model = () => new VerifyRunModel(serverDB, userId);
+ const item = (id: string) => ({
+ id,
+ index: 0,
+ onFail: 'manual' as const,
+ required: true,
+ title: id,
+ verifierConfig: {},
+ verifierType: 'agent' as const,
+ });
+ const draftRound = async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ userId, subjectType: 'standalone', subjectId: 'fold-subject' })
+ .returning();
+ const draft = await model().create({
+ acceptanceId: acceptance.id,
+ plan: [item('flow-1')],
+ roundIndex: 1,
+ status: 'planned',
+ title: 'draft',
+ });
+ return { acceptance, draft };
+ };
+
+ it('folds a detached harness run into the draft and removes the extra row', async () => {
+ const { acceptance, draft } = await draftRound();
+ const incoming = await model().create({
+ metadata: { interactionCost: { total: 1 } } as any,
+ plan: [item('case-1'), item('flow-1')],
+ source: 'agent-testing',
+ title: 'harness',
+ });
+
+ const folded = await model().foldIntoRound(incoming.id, draft.id);
+
+ expect(folded.id).toBe(draft.id);
+ expect(folded.roundIndex).toBe(1);
+ expect(folded.plan?.map((p) => [p.id, p.index])).toEqual([
+ ['flow-1', 0],
+ ['case-1', 1],
+ ]);
+ expect(folded.status).toBeNull();
+ expect(folded.planConfirmedAt).not.toBeNull();
+ expect(folded.source).toBe('agent-testing');
+ expect(folded.metadata).toMatchObject({ interactionCost: { total: 1 } });
+ expect(await model().findById(incoming.id)).toBeUndefined();
+ expect(await model().listByAcceptance(acceptance.id)).toHaveLength(1);
+ });
+
+ it('refuses to fold into a round that already executed or a run already chained', async () => {
+ const { acceptance, draft } = await draftRound();
+ await model().confirmPlan(draft.id);
+ const incoming = await model().create({ plan: [item('case-1')], title: 'harness' });
+ await expect(model().foldIntoRound(incoming.id, draft.id)).rejects.toThrow('draft round');
+
+ const chained = await model().create({
+ acceptanceId: acceptance.id,
+ plan: [item('case-2')],
+ roundIndex: 2,
+ title: 'chained',
+ });
+ await expect(model().foldIntoRound(chained.id, draft.id)).rejects.toThrow('detached');
+ });
+});
diff --git a/packages/database/src/models/acceptanceFlow.ts b/packages/database/src/models/acceptanceFlow.ts
index 8e36e587018..8f1fb2ef7c4 100644
--- a/packages/database/src/models/acceptanceFlow.ts
+++ b/packages/database/src/models/acceptanceFlow.ts
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
+import { isDraftVerifyRun } from '@lobechat/const/verify';
import type {
AcceptanceFlowDefinition,
AcceptanceFlowReview,
@@ -65,6 +66,36 @@ function fingerprint(value: unknown) {
.digest('hex');
}
+/** The newest round of a chain ordered by ascending `roundIndex`. */
+function latestRound<T extends { roundIndex: number | null }>(rounds: T[]) {
+ return rounds.findLast((round) => round.roundIndex != null);
+}
+
+/** Link each occurrence to the plan items earlier rounds recorded at the same graph position. */
+function withSupersedes(
+ plan: VerifyCheckItem[],
+ priorPlans: (VerifyCheckItem[] | null | undefined)[],
+ flowId: string,
+) {
+ return plan.map((item) => {
+ const supersedes = [
+ ...new Set(
+ priorPlans
+ .flatMap((p) => p ?? [])
+ .filter(
+ (p) =>
+ p.id !== item.id &&
+ p.sourceFlowNode?.flowId === flowId &&
+ p.sourceFlowNode.nodeId === item.sourceFlowNode?.nodeId &&
+ p.sourceFlowNode.incomingEdgeId === item.sourceFlowNode?.incomingEdgeId,
+ )
+ .map((p) => p.id),
+ ),
+ ];
+ return supersedes.length ? { ...item, supersedes } : item;
+ });
+}
+
export class AcceptanceFlowModel {
constructor(
private db: LobeChatDatabase,
@@ -187,10 +218,61 @@ export class AcceptanceFlowModel {
updatedAt: new Date(),
})
.where(eq(flows.id, flow.id));
+ await this.syncOpenRounds(acceptanceId, tx);
return { flowId: flow.id, hash: (await this.graph(flow.id, tx)).hash };
});
}
+ /**
+ * Editing a graph before any round executes must not fork a new version:
+ * refresh the snapshot and plan of the open draft, so the ledger keeps
+ * describing the graph the editor shows. Only the newest round qualifies —
+ * an older draft the ledger has moved past, and a replay pinned to a frozen
+ * definition, both keep what they already hold.
+ */
+ private async syncOpenRounds(acceptanceId: string, tx: Transaction) {
+ const rounds = await tx
+ .select()
+ .from(verifyRuns)
+ .where(eq(verifyRuns.acceptanceId, acceptanceId))
+ .orderBy(asc(verifyRuns.roundIndex))
+ .for('update');
+ const open = latestRound(rounds);
+ for (const round of open && isDraftVerifyRun(open) ? [open] : []) {
+ if (!round.flowSnapshots?.length) continue;
+ let plan = round.plan ?? [];
+ const snapshots: VerifyFlowSnapshot[] = [];
+ let changed = false;
+ for (const snapshot of round.flowSnapshots) {
+ const current = await this.graph(snapshot.flowId, tx);
+ const existing = plan.filter((p) => p.sourceFlowNode?.flowId === snapshot.flowId);
+ if (
+ fingerprint(current.snapshot) === fingerprint(snapshot) &&
+ fingerprint(existing.map((p) => p.id)) === fingerprint(current.plan.map((p) => p.id))
+ ) {
+ snapshots.push(snapshot);
+ continue;
+ }
+ changed = true;
+ snapshots.push(current.snapshot);
+ const priorPlans = rounds.filter((r) => r.id !== round.id).map((r) => r.plan);
+ const items = withSupersedes(current.plan, priorPlans, snapshot.flowId);
+ const at = plan.findIndex((p) => p.sourceFlowNode?.flowId === snapshot.flowId);
+ const rest = plan.filter((p) => p.sourceFlowNode?.flowId !== snapshot.flowId);
+ plan =
+ at === -1 ? [...rest, ...items] : [...rest.slice(0, at), ...items, ...rest.slice(at)];
+ }
+ if (!changed) continue;
+ await tx
+ .update(verifyRuns)
+ .set({
+ plan: plan.map((item, index) => ({ ...item, index })),
+ flowSnapshots: snapshots,
+ })
+ .where(eq(verifyRuns.id, round.id));
+ }
+ }
+
private async graph(
flowId: string,
database: LobeChatDatabase | Transaction = this.db,
@@ -437,23 +519,30 @@ export class AcceptanceFlowModel {
.select({ plan: verifyRuns.plan })
.from(verifyRuns)
.where(eq(verifyRuns.acceptanceId, acceptanceId));
- graph.plan = graph.plan.map((item) => {
- const supersedes = [
- ...new Set(
- priorRounds
- .flatMap((r) => r.plan ?? [])
- .filter(
- (p) =>
- p.id !== item.id &&
- p.sourceFlowNode?.flowId === flowId &&
- p.sourceFlowNode.nodeId === item.sourceFlowNode?.nodeId &&
- p.sourceFlowNode.incomingEdgeId === item.sourceFlowNode?.incomingEdgeId,
- )
- .map((p) => p.id),
- ),
- ];
- return supersedes.length ? { ...item, supersedes } : item;
- });
+ graph.plan = withSupersedes(
+ graph.plan,
+ priorRounds.map((r) => r.plan),
+ flowId,
+ );
+ }
+ if (!verifyRunId && !sourceRunId) {
+ // Planning again is a refresh of the open draft, never another round.
+ const latest = latestRound(
+ await tx
+ .select()
+ .from(verifyRuns)
+ .where(eq(verifyRuns.acceptanceId, acceptanceId))
+ .orderBy(asc(verifyRuns.roundIndex))
+ .for('update'),
+ );
+ const draft = latest && isDraftVerifyRun(latest) ? latest : undefined;
+ if (draft) {
+ verifyRunId = draft.id;
+ if (draft.flowSnapshots?.some((s) => s.flowId === flowId)) {
+ await this.syncOpenRounds(acceptanceId, tx);
+ return { id: draft.id, verifyRunId: draft.id, flowId };
+ }
+ }
}
if (!verifyRunId) {
const [last] = await tx
@@ -472,6 +561,9 @@ export class AcceptanceFlowModel {
roundIndex: (last?.roundIndex ?? 0) + 1,
title: flow.title,
status: 'planned',
+ // A replay is pinned to the definition it replays, so it stays out
+ // of the draft reuse and refresh paths.
+ ...(sourceRunId ? { metadata: { replayOfRunId: sourceRunId } } : {}),
})
.returning();
verifyRunId = created.id;
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index 1d6f0903f19..227d9d1da0d 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
-import type { VerifyVisibility } from '@lobechat/const/verify';
+import { isDraftVerifyRun, type VerifyVisibility } from '@lobechat/const/verify';
import type {
VerifyCheckItem,
VerifyRunDecisionDetail,
@@ -328,6 +328,58 @@ export class VerifyRunModel {
return run;
};
+ /**
+ * A harness run arriving while the acceptance still holds a draft round must
+ * not open another round: its plan folds into the draft, the draft becomes the
+ * ingest target (frozen now, since results are about to land) and the
+ * detached run row goes away. Returns the draft row the caller ingests into.
+ */
+ foldIntoRound = async (sourceRunId: string, targetRunId: string): Promise<VerifyRunItem> => {
+ return this.db.transaction(async (tx) => {
+ const rows = await tx
+ .select()
+ .from(verifyRuns)
+ .where(and(inArray(verifyRuns.id, [sourceRunId, targetRunId]), this.ownership()))
+ .for('update');
+ const source = rows.find((row) => row.id === sourceRunId);
+ const target = rows.find((row) => row.id === targetRunId);
+ if (!source || !target) throw new Error('Verify run not found in the current workspace');
+ if (source.acceptanceId) throw new Error('Only a detached run can fold into a draft round');
+ if (!isDraftVerifyRun(target)) throw new Error('Only a draft round can absorb another run');
+ const executed = await tx
+ .select({ id: verifyCheckResults.id })
+ .from(verifyCheckResults)
+ .where(inArray(verifyCheckResults.verifyRunId, [sourceRunId, targetRunId]))
+ .limit(1);
+ if (executed.length) throw new Error('A run with results cannot fold into a draft round');
+
+ const known = new Set((target.plan ?? []).map((item) => item.id));
+ const plan = [
+ ...(target.plan ?? []),
+ ...(source.plan ?? []).filter((item) => !known.has(item.id)),
+ ].map((item, index) => ({ ...item, index }));
+ // The source row goes first so its unique operation_id can move over.
+ await tx.delete(verifyRuns).where(eq(verifyRuns.id, sourceRunId));
+ const [folded] = await tx
+ .update(verifyRuns)
+ .set({
+ context: target.context ?? source.context,
+ goal: target.goal ?? source.goal,
+ metadata: { ...target.metadata, ...source.metadata },
+ operationId: target.operationId ?? source.operationId,
+ plan,
+ planConfirmedAt: new Date(),
+ scenario: target.scenario ?? source.scenario,
+ source: source.source ?? target.source,
+ // Ingested rounds carry no rollup status: the report settles them.
+ status: null,
+ })
+ .where(eq(verifyRuns.id, targetRunId))
+ .returning();
+ return folded;
+ });
+ };
+
/** Flip who can read this round's report page beyond its creator. */
setVisibility = async (runId: string, visibility: VerifyVisibility): Promise<void> => {
await this.db
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 0e301c9651d..49b696cbe13 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -88,7 +88,7 @@ export default {
'flow.running': 'Verification in progress',
'flow.planned': 'Plan published \u00B7 verification has not started',
- 'flow.pendingPlan': 'Pending verification plan',
+ 'flow.pendingPlan': 'Draft',
'flow.title': 'User flow',
'flow.empty': 'The agent will publish the verification flow here before running checks.',
'flow.run': 'Run {{number}}',
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index c1a50976cbf..1e4b865c9a1 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -589,6 +589,12 @@ export interface VerifyRunMetadata {
* run that *authored* the report — and is many-to-one.
*/
origin?: VerifyRunOrigin;
+ /**
+ * The round this one replays (`flow plan --from-run`). A replay is pinned to
+ * the source round's frozen definition, so it never follows later graph edits
+ * and never absorbs another flow, even while it holds no results yet.
+ */
+ replayOfRunId?: string;
}
export type VerifyVisualizationValue = boolean | null | number | string;
diff --git a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx
index 123b86c9e2f..876398860e1 100644
--- a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx
+++ b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx
@@ -1,5 +1,6 @@
'use client';
+import { isDraftVerifyRun } from '@lobechat/const/verify';
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, Select, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, useResponsive } from 'antd-style';
@@ -273,7 +274,9 @@ const AcceptanceCheckInventory = ({
options={[
{ label: t('acceptance.filter.roundAll'), value: 'all' },
...[...data.rounds].reverse().map((round) => ({
- label: t('acceptance.round', { round: round.run.roundIndex }),
+ label: isDraftVerifyRun(round.run)
+ ? t('flow.pendingPlan')
+ : t('acceptance.round', { round: round.run.roundIndex }),
value: String(round.run.roundIndex),
})),
]}
diff --git a/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx b/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx
index 6085ff03abd..895003ed4ea 100644
--- a/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx
+++ b/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx
@@ -12,11 +12,12 @@ import {
import { createStaticStyles, cssVar } from 'antd-style';
import { useEffect, useRef } from 'react';
-import { useFitViewOnResize } from '@/features/AgentGoals/ProcessControl/Graph/useFitViewOnResize';
+import { observeWidth } from '@/features/AgentGoals/ProcessControl/Graph/useFitViewOnResize';
import { useSingleton } from '@/hooks/useSingleton';
import { FlowEdge } from './FlowEdge';
import type { FlowGraphData } from './flowGraph';
+import { getSelectedFlowNodeId, revealSelectionAfterResize } from './flowViewport';
const edgeTypes = { transition: FlowEdge };
@@ -61,11 +62,29 @@ export function FlowCanvas({
viewKey: string;
}) {
const ref = useRef<HTMLDivElement>(null);
- const { fitView, getViewport, setViewport } = useReactFlow();
+ const { fitView, getNodesBounds, getViewport, setViewport } = useReactFlow();
const viewports = useSingleton(
() => new Map<string, { viewport: Viewport; width: number; height: number }>(),
);
- useFitViewOnResize(ref, fitView, fitOptions);
+ const selectedId = getSelectedFlowNodeId(nodes);
+ const selectedRef = useRef(selectedId);
+ useEffect(() => {
+ selectedRef.current = selectedId;
+ }, [selectedId]);
+ // The details panel opens beside the canvas when a node is picked. Refitting
+ // here would throw away the zoom the user just set, so only bring the picked
+ // node back into view when the narrower canvas hid it.
+ useEffect(() => {
+ const container = ref.current;
+ if (!container || typeof ResizeObserver === 'undefined') return;
+ return observeWidth(container, () =>
+ revealSelectionAfterResize(
+ { fitView, getNodesBounds, getViewport },
+ { height: container.clientHeight, width: container.clientWidth },
+ selectedRef.current,
+ ),
+ );
+ }, [fitView, getNodesBounds, getViewport]);
useEffect(() => {
const container = ref.current;
const frame = requestAnimationFrame(() => {
diff --git a/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts b/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts
index ece4c5141cb..a36f2a06353 100644
--- a/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts
+++ b/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts
@@ -84,3 +84,24 @@ it('falls back from draft and selected flows when the surface does not offer flo
expect(resolveAcceptanceTab('resources', 3, true, false)).toBe('resources');
expect(resolveAcceptanceTab('flow', 3, false, true)).toBe('flow');
});
+
+it('shows a draft round as the pending plan and hides the unsynced live copy', () => {
+ const flows = makeFlows();
+ const rounds = [
+ { run: { id: 'round-a', roundIndex: 4 } },
+ {
+ run: {
+ id: 'round-b',
+ planConfirmedAt: null,
+ roundIndex: 9,
+ status: 'planned',
+ userDecision: null,
+ },
+ },
+ ] as Parameters<typeof getFlowRoundViews>[1];
+ const views = getFlowRoundViews(flows, rounds);
+ expect(views.map(({ id, roundIndex }) => [id, roundIndex])).toEqual([
+ ['v1:visit-b', undefined],
+ ['v1:visit-a', 4],
+ ]);
+});
diff --git a/src/features/Acceptance/Viewer/Flow/flowNavigation.ts b/src/features/Acceptance/Viewer/Flow/flowNavigation.ts
index c00fe6d6f0e..0d10f9e0549 100644
--- a/src/features/Acceptance/Viewer/Flow/flowNavigation.ts
+++ b/src/features/Acceptance/Viewer/Flow/flowNavigation.ts
@@ -1,3 +1,5 @@
+import { isDraftVerifyRun } from '@lobechat/const/verify';
+
import type { verifyService } from '@/services/verify';
import type { AcceptanceTabKey } from '../Header/AcceptanceTabs';
@@ -21,9 +23,15 @@ export const resolveAcceptanceTab = (
return selected === 'flow' && (!flowAvailable || nodeCount === 0) ? 'checks' : selected;
};
-/** Round numbers come from the same acceptance ledger as the checklist. */
+/**
+ * Round numbers come from the same acceptance ledger as the checklist. A draft
+ * round has not executed, so it is the pending plan rather than a numbered
+ * round; its snapshot follows the live graph and stands in for it.
+ */
export const getFlowRoundViews = (flows: Bundle['flows'] = [], rounds: Bundle['rounds'] = []) => {
- const roundNumbers = new Map(rounds.map(({ run }) => [run.id, run.roundIndex]));
+ const ledger = new Map(
+ rounds.map(({ run }) => [run.id, { draft: isDraftVerifyRun(run), roundIndex: run.roundIndex }]),
+ );
const views: {
id: string;
roundIndex?: number;
@@ -32,14 +40,22 @@ export const getFlowRoundViews = (flows: Bundle['flows'] = [], rounds: Bundle['r
}[] = [];
for (const flow of flows) {
const versions = flow.versions.filter((version) => version.nodes.length > 0);
+ const hasDraft = versions.some((version) =>
+ version.runs.some((run) => ledger.get(run.verifyRunId)?.draft),
+ );
for (const version of versions) {
- if (version === versions[0] && version.runs.length === 0) {
+ if (version === versions[0] && version.runs.length === 0 && !hasDraft) {
views.push({ id: version.id, version });
}
for (const run of version.runs) {
- const roundIndex = roundNumbers.get(run.verifyRunId);
- if (roundIndex != null)
- views.push({ id: `${version.id}:${run.id}`, roundIndex, run, version });
+ const round = ledger.get(run.verifyRunId);
+ if (round?.roundIndex == null) continue;
+ views.push({
+ id: `${version.id}:${run.id}`,
+ roundIndex: round.draft ? undefined : round.roundIndex,
+ run,
+ version,
+ });
}
}
}
diff --git a/src/features/Acceptance/Viewer/Flow/flowViewport.test.ts b/src/features/Acceptance/Viewer/Flow/flowViewport.test.ts
new file mode 100644
index 00000000000..ea731c07b33
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Flow/flowViewport.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getSelectedFlowNodeId, isRectInView, revealSelectionAfterResize } from './flowViewport';
+
+const size = { height: 600, width: 1000 };
+
+describe('isRectInView', () => {
+ it('accepts a rect inside the canvas at the current zoom', () => {
+ expect(
+ isRectInView({ height: 100, width: 200, x: 100, y: 50 }, { x: 0, y: 0, zoom: 1 }, size),
+ ).toBe(true);
+ });
+
+ it('rejects a rect crossing the right edge after zooming in', () => {
+ expect(
+ isRectInView({ height: 100, width: 200, x: 500, y: 50 }, { x: -100, y: 0, zoom: 2 }, size),
+ ).toBe(false);
+ });
+});
+
+describe('revealSelectionAfterResize', () => {
+ const flow = (
+ viewport = { x: 0, y: 0, zoom: 1.4 },
+ bounds = { height: 80, width: 200, x: 100, y: 100 },
+ ) => ({
+ fitView: vi.fn().mockResolvedValue(true),
+ getNodesBounds: vi.fn().mockReturnValue(bounds),
+ getViewport: vi.fn().mockReturnValue(viewport),
+ });
+
+ it('keeps the zoomed viewport untouched when nothing is selected', () => {
+ const api = flow();
+ revealSelectionAfterResize(api, size, undefined);
+ expect(api.fitView).not.toHaveBeenCalled();
+ });
+
+ it('keeps the zoomed viewport untouched when the selected node is still visible', () => {
+ const api = flow();
+ revealSelectionAfterResize(api, size, 'node-1');
+ expect(api.fitView).not.toHaveBeenCalled();
+ });
+
+ it('pans at the same zoom when the panel pushes the selected node out of view', () => {
+ const api = flow({ x: 0, y: 0, zoom: 1.4 }, { height: 80, width: 200, x: 620, y: 100 });
+ revealSelectionAfterResize(api, size, 'node-1');
+ expect(api.fitView).toHaveBeenCalledWith(
+ expect.objectContaining({ maxZoom: 1.4, minZoom: 1.4, nodes: [{ id: 'node-1' }] }),
+ );
+ });
+
+ it('ignores a selection whose node is not laid out yet', () => {
+ const api = flow(undefined, { height: 0, width: 0, x: 0, y: 0 });
+ revealSelectionAfterResize(api, size, 'node-1');
+ expect(api.fitView).not.toHaveBeenCalled();
+ });
+});
+
+describe('getSelectedFlowNodeId', () => {
+ it('reads the picked node from graph data rather than the React Flow selected flag', () => {
+ expect(
+ getSelectedFlowNodeId([
+ { data: { selected: false }, id: 'a' },
+ { data: { selected: true }, id: 'b' },
+ { data: {}, id: 'c' },
+ ]),
+ ).toBe('b');
+ expect(getSelectedFlowNodeId([{ data: {}, id: 'a' }])).toBeUndefined();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Flow/flowViewport.ts b/src/features/Acceptance/Viewer/Flow/flowViewport.ts
new file mode 100644
index 00000000000..e3276dba8ba
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Flow/flowViewport.ts
@@ -0,0 +1,54 @@
+import type { FitViewOptions, Rect, Viewport } from '@xyflow/react';
+
+export interface CanvasSize {
+ height: number;
+ width: number;
+}
+
+/** Whether a flow-space rect sits fully inside the visible canvas. */
+export const isRectInView = (rect: Rect, viewport: Viewport, size: CanvasSize) => {
+ const left = rect.x * viewport.zoom + viewport.x;
+ const top = rect.y * viewport.zoom + viewport.y;
+ return (
+ left >= 0 &&
+ top >= 0 &&
+ left + rect.width * viewport.zoom <= size.width &&
+ top + rect.height * viewport.zoom <= size.height
+ );
+};
+
+/**
+ * `buildFlowGraph` marks the picked node inside `data`, not with React Flow's
+ * own `selected` flag, so the reveal logic must read it from there.
+ */
+export const getSelectedFlowNodeId = (nodes: { data: Record<string, unknown>; id: string }[]) =>
+ nodes.find((node) => Boolean(node.data.selected))?.id;
+
+export interface FlowViewportApi {
+ fitView: (options?: FitViewOptions) => Promise<boolean>;
+ getNodesBounds: (nodes: string[]) => Rect;
+ getViewport: () => Viewport;
+}
+
+/**
+ * A side panel opening or closing changes the canvas width around the graph.
+ * Keep the user's zoom and position untouched; only pan, at the same zoom,
+ * when the selected node would otherwise be pushed out of view.
+ */
+export const revealSelectionAfterResize = (
+ flow: FlowViewportApi,
+ size: CanvasSize,
+ selectedId: string | undefined,
+) => {
+ if (!selectedId) return;
+ const viewport = flow.getViewport();
+ const bounds = flow.getNodesBounds([selectedId]);
+ if (!bounds.width || !bounds.height) return;
+ if (isRectInView(bounds, viewport, size)) return;
+ void flow.fitView({
+ duration: 200,
+ maxZoom: viewport.zoom,
+ minZoom: viewport.zoom,
+ nodes: [{ id: selectedId }],
+ });
+};