Skip to content

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

✨ feat(acceptance): let an author delete a flow the delivery no longer follows (#19388)

Arvin Xud26542b423fb
diff --git a/apps/cli/src/commands/acceptanceFlow.test.ts b/apps/cli/src/commands/acceptanceFlow.test.ts
index 1ed0c0f6094..8e5a86b6e23 100644
--- a/apps/cli/src/commands/acceptanceFlow.test.ts
+++ b/apps/cli/src/commands/acceptanceFlow.test.ts
@@ -3,17 +3,19 @@ import { expect, it, vi } from 'vitest';
import { attachAcceptanceFlowCommands } from './acceptanceFlow';
-const { startFlow, outputJson } = vi.hoisted(() => ({
+const { startFlow, deleteFlow, confirm, outputJson } = vi.hoisted(() => ({
startFlow: vi.fn().mockResolvedValue({ id: 'flow-run' }),
+ deleteFlow: vi.fn().mockResolvedValue({ flowId: 'flow-id', title: 'First attempt' }),
+ confirm: vi.fn().mockResolvedValue(false),
outputJson: vi.fn(),
}));
vi.mock('../api/client', () => ({
getTrpcClient: async () => ({
- acceptance: { startFlow: { mutate: startFlow } },
+ acceptance: { startFlow: { mutate: startFlow }, deleteFlow: { mutate: deleteFlow } },
}),
}));
-vi.mock('../utils/format', () => ({ outputJson }));
+vi.mock('../utils/format', () => ({ confirm, outputJson }));
it('starts the requested flow version without triggering the root CLI version option', async () => {
const program = new Command().version('0.0.52').exitOverride();
@@ -82,3 +84,27 @@ it('prepares a flow for review through the plan command', async () => {
verifyRunId: undefined,
});
});
+
+it('asks before deleting a flow and passes the confirmed request through', async () => {
+ const deleteArgs = [
+ 'node',
+ 'lh',
+ 'acceptance',
+ 'flow',
+ 'delete',
+ 'acceptance-id',
+ '--flow',
+ 'flow-id',
+ ];
+ const program = new Command().exitOverride();
+ attachAcceptanceFlowCommands(program.command('acceptance'));
+ await program.parseAsync(deleteArgs);
+ expect(confirm).toHaveBeenCalled();
+ expect(deleteFlow).not.toHaveBeenCalled();
+
+ const confirmed = new Command().exitOverride();
+ attachAcceptanceFlowCommands(confirmed.command('acceptance'));
+ await confirmed.parseAsync([...deleteArgs, '--yes']);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ expect(deleteFlow).toHaveBeenCalledWith({ id: 'acceptance-id', flowId: 'flow-id' });
+});
diff --git a/apps/cli/src/commands/acceptanceFlow.ts b/apps/cli/src/commands/acceptanceFlow.ts
index f009dc1e176..84832201b56 100644
--- a/apps/cli/src/commands/acceptanceFlow.ts
+++ b/apps/cli/src/commands/acceptanceFlow.ts
@@ -1,9 +1,10 @@
import { readFile } from 'node:fs/promises';
import type { Command } from 'commander';
+import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
-import { outputJson } from '../utils/format';
+import { confirm, outputJson } from '../utils/format';
/** Agent entry point: author a graph before exercising the product, then append real visits. */
export function attachAcceptanceFlowCommands(acceptance: Command) {
@@ -22,6 +23,29 @@ export function attachAcceptanceFlowCommands(acceptance: Command) {
const client = await getTrpcClient();
outputJson((await client.acceptance.getBundle.query({ id })).flows);
});
+ flow
+ .command('delete <acceptanceId>')
+ .description('Delete a graph that has never been verified')
+ .requiredOption('--flow <id>')
+ .option('-y, --yes', 'Skip the confirmation prompt')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (id: string, options: { flow: string; json?: boolean | string; yes?: boolean }) => {
+ const client = await getTrpcClient();
+ if (!options.yes) {
+ const ok = await confirm(
+ `Delete flow ${pc.bold(options.flow)} and drop it from any planned round? This cannot be undone.`,
+ );
+ if (!ok) return void console.log('Aborted.');
+ }
+ const result = await client.acceptance.deleteFlow.mutate({ id, flowId: options.flow });
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Deleted flow ${pc.bold(result.title)}`);
+ },
+ );
flow
.command('plan <acceptanceId>')
.alias('start')
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
index b07c82b356a..867942f0256 100644
--- a/apps/server/src/routers/lambda/acceptance.ts
+++ b/apps/server/src/routers/lambda/acceptance.ts
@@ -240,6 +240,17 @@ export const acceptanceRouter = router({
input.expectedHash,
);
}),
+ deleteFlow: acceptanceWriteProcedure
+ .input(z.object({ id: z.string().uuid(), flowId: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);
+ const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).delete(
+ input.id,
+ input.flowId,
+ );
+ await service.recomputeStatus(input.id);
+ return result;
+ }),
startFlow: acceptanceWriteProcedure
.input(
z.object({
diff --git a/packages/builtin-skills/src/acceptance/SKILL.md b/packages/builtin-skills/src/acceptance/SKILL.md
index 4f6e97eb13f..3f118c521d3 100644
--- a/packages/builtin-skills/src/acceptance/SKILL.md
+++ b/packages/builtin-skills/src/acceptance/SKILL.md
@@ -164,6 +164,12 @@ execution semantics.
definition and returns `flowId`. To edit it, include that `flowId` and the
current `expectedHash` in the file. `lh acceptance flow view <acceptanceId>`
reads definitions, snapshots and results. Publishing does not execute checks.
+ Revise a graph in place rather than publishing a second one; a superseded
+ graph left behind still renders as its own journey with its own unexecuted
+ checks. `lh acceptance flow delete <acceptanceId> --flow <flowId>` removes
+ one that never should have existed, and only while it has no verified
+ history: it is refused once a settled round has run it, or while another
+ flow invokes it as a subflow.
3. `lh acceptance flow plan <acceptanceId> --flow <flowId>` creates a draft round
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
diff --git a/packages/database/src/models/__tests__/acceptanceFlow.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
index 9f9ee0d8a01..ccb2aed1033 100644
--- a/packages/database/src/models/__tests__/acceptanceFlow.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceFlow.test.ts
@@ -25,10 +25,15 @@ beforeEach(async () => {
.values({ userId: owner, subjectType: 'standalone', subjectId: randomUUID() })
.returning();
acceptanceId = acceptance.id;
+ definition = journeyDefinition('Send and retry');
+});
+
+/** The same two-state journey with fresh ids, so one acceptance can hold several. */
+function journeyDefinition(title: string): AcceptanceFlowDefinition {
const first = randomUUID();
const second = randomUUID();
- definition = {
- title: 'Send and retry',
+ return {
+ title,
entryNodeId: first,
nodes: [
{
@@ -71,7 +76,7 @@ beforeEach(async () => {
},
],
};
-});
+}
afterEach(async () => {
await db.delete(users).where(eq(users.id, owner));
await db.delete(users).where(eq(users.id, other));
@@ -564,6 +569,50 @@ describe('check assets and round snapshots', () => {
);
});
+ it('deletes an abandoned graph and unplans it from the open draft', async () => {
+ const abandoned = await model.publish(acceptanceId, definition);
+ const kept = await model.publish(acceptanceId, journeyDefinition('Second attempt'));
+ const draft = await model.start(acceptanceId, abandoned.flowId);
+ await model.start(acceptanceId, kept.flowId, draft.id);
+ expect((await roundPlan(draft.id)).flowSnapshots).toHaveLength(2);
+
+ const removed = await model.delete(acceptanceId, abandoned.flowId);
+ expect(removed.title).toBe('Send and retry');
+ expect((await model.list(acceptanceId)).map((flow) => flow.id)).toEqual([kept.flowId]);
+ const round = await roundPlan(draft.id);
+ expect(round.flowSnapshots?.map((snapshot) => snapshot.flowId)).toEqual([kept.flowId]);
+ expect(round.plan?.every((item) => item.sourceFlowNode?.flowId === kept.flowId)).toBe(true);
+ expect(round.plan?.map((item) => item.index)).toEqual(round.plan?.map((_, index) => index));
+ });
+
+ it('refuses to delete a graph a round has already verified', async () => {
+ const { flowId } = await model.publish(acceptanceId, definition);
+ const run = await model.start(acceptanceId, flowId);
+ await model.record(acceptanceId, {
+ verifyRunId: run.id,
+ checkItemId: (await roundPlan(run.id)).plan![0].id,
+ verdict: 'passed',
+ observation: 'Composer visible',
+ });
+ await expect(model.delete(acceptanceId, flowId)).rejects.toThrow('verified this flow');
+ expect(await model.list(acceptanceId)).toHaveLength(1);
+ });
+
+ it('refuses to delete a graph another flow invokes as a subflow', async () => {
+ const child = await model.publish(acceptanceId, definition);
+ const occurrence = randomUUID();
+ const parent = await model.publish(acceptanceId, {
+ title: 'End to end',
+ entryNodeId: occurrence,
+ nodes: [{ id: occurrence, subFlowId: child.flowId }],
+ edges: [],
+ });
+ await expect(model.delete(acceptanceId, child.flowId)).rejects.toThrow('invokes this flow');
+ await model.delete(acceptanceId, parent.flowId);
+ await model.delete(acceptanceId, child.flowId);
+ expect(await model.list(acceptanceId)).toHaveLength(0);
+ });
+
it('rejects unreachable nodes and missing entry points', () => {
expect(() => validateFlow({ ...definition, entryNodeId: randomUUID() })).toThrow('Entry node');
expect(() => validateFlow({ ...definition, edges: [] })).toThrow('Unreachable');
diff --git a/packages/database/src/models/acceptanceFlow.ts b/packages/database/src/models/acceptanceFlow.ts
index 8f1fb2ef7c4..b363b152057 100644
--- a/packages/database/src/models/acceptanceFlow.ts
+++ b/packages/database/src/models/acceptanceFlow.ts
@@ -273,6 +273,89 @@ export class AcceptanceFlowModel {
}
}
+ /**
+ * Drop a graph the acceptance no longer describes.
+ *
+ * Authoring a journey takes several tries, and until now every try stayed on
+ * the page forever: an abandoned first draft still renders as its own root
+ * with its own unexecuted checks, so the reader cannot tell which graph the
+ * delivery is actually being verified against.
+ *
+ * Only a graph without verified history can go. A settled round renders from
+ * the snapshot it froze, so its results would outlive the map that explains
+ * them. A draft has nothing to preserve: the flow's snapshot and plan items
+ * are stripped from it, leaving the ledger as if the flow had never been
+ * planned. Check assets the nodes pointed at are reusable on their own and
+ * stay put.
+ */
+ async delete(acceptanceId: string, flowId: string) {
+ await this.owned(acceptanceId);
+ return this.db.transaction(async (tx) => {
+ const [locked] = await tx
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptanceId))
+ .for('update');
+ if (['accepted', 'closed'].includes(locked.status))
+ throw new Error('Reopen acceptance before deleting a flow');
+ const [flow] = await tx
+ .select()
+ .from(flows)
+ .where(and(eq(flows.id, flowId), eq(flows.acceptanceId, acceptanceId)))
+ .for('update');
+ if (!flow) throw new Error('Flow not found');
+
+ const [invoked] = await tx
+ .select({ title: flows.title })
+ .from(nodes)
+ .innerJoin(flows, eq(nodes.flowId, flows.id))
+ .where(eq(nodes.subFlowId, flowId));
+ if (invoked)
+ throw new Error(`"${invoked.title}" invokes this flow — remove that subflow node first`);
+
+ const rounds = await tx
+ .select()
+ .from(verifyRuns)
+ .where(eq(verifyRuns.acceptanceId, acceptanceId))
+ .orderBy(asc(verifyRuns.roundIndex))
+ .for('update');
+ const carrying = rounds.filter((round) =>
+ round.flowSnapshots?.some((snapshot) => snapshot.flowId === flowId),
+ );
+ const settled = carrying.find((round) => !isDraftVerifyRun(round));
+ if (settled)
+ throw new Error(
+ `Round ${settled.roundIndex} verified this flow — delete that round first, or leave the graph in place`,
+ );
+ const planned = carrying.flatMap((round) =>
+ (round.plan ?? [])
+ .filter((item) => item.sourceFlowNode?.flowId === flowId)
+ .map((item) => item.id),
+ );
+ const [recorded] = planned.length
+ ? await tx
+ .select({ id: verifyCheckResults.id })
+ .from(verifyCheckResults)
+ .where(inArray(verifyCheckResults.checkItemId, planned))
+ .limit(1)
+ : [];
+ if (recorded) throw new Error('This flow already has recorded results');
+
+ for (const round of carrying)
+ await tx
+ .update(verifyRuns)
+ .set({
+ plan: (round.plan ?? [])
+ .filter((item) => item.sourceFlowNode?.flowId !== flowId)
+ .map((item, index) => ({ ...item, index })),
+ flowSnapshots: round.flowSnapshots!.filter((snapshot) => snapshot.flowId !== flowId),
+ })
+ .where(eq(verifyRuns.id, round.id));
+ await tx.delete(flows).where(eq(flows.id, flowId));
+ return { flowId, title: flow.title, unplannedRounds: carrying.map((round) => round.id) };
+ });
+ }
+
private async graph(
flowId: string,
database: LobeChatDatabase | Transaction = this.db,