🤯 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(workflow): cancel guarded runs by URL prefix (#16721)
Neko3572c2bc4694
diff --git a/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts b/src/server/workflows/runGuard/__tests__/qstashCancel.test.tsindex 2d95987ec22..5e377adabee 100644--- a/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts+++ b/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts@@ -9,32 +9,11 @@ describe('workflow run guard qstash cancel', () => {* appUrl: 'https://app.lobehub.com',* workflowPath: 'api/workflows/memory-user-memory',* })- * // cancels RUN_STARTED workflow ids whose URL starts with the workflow prefix+ * // cancels pending and active workflows whose URL starts with the workflow prefix*/- it('resolves matching run ids from logs and cancels by id', async () => {+ it('cancels workflows using the SDK url prefix API', async () => {const client = {- cancel: vi.fn().mockResolvedValue({ cancelled: 2 }),- logs: vi.fn().mockResolvedValue({- runs: [- {- workflowRunId: 'wfr_1',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',- },- {- workflowRunId: 'wfr_2',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',- },- {- workflowRunId: 'wfr_other',- workflowState: 'RUN_STARTED',- workflowUrl: 'https://app.lobehub.com/api/workflows/agent-eval-run/execute-test-case',- },- ],- }),+ cancel: vi.fn().mockResolvedValue({ cancelled: 12 }),};await expect(@@ -46,47 +25,26 @@ describe('workflow run guard qstash cancel', () => {},),).resolves.toEqual({- cancelled: 2,- matchedRunIds: ['wfr_1', 'wfr_2'],+ cancelled: 12,workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});- expect(client.logs).toHaveBeenCalledWith({ count: 100, state: 'RUN_STARTED' });- expect(client.cancel).toHaveBeenCalledWith({ ids: ['wfr_1', 'wfr_2'] });+ expect(client.cancel).toHaveBeenCalledWith({+ urlStartingWith: 'https://app.lobehub.com/api/workflows/memory-user-memory',+ });});/*** @example* cancelWorkflowRunsByGuardPolicy(client, {* appUrl: 'https://app.lobehub.com/',- * workflowPath: '/api/workflows/memory-user-memory/',+ * workflowPath: '/api/workflows/memory-user-memory/?cursor=1#hash',* })- * // deduplicates matching workflow run ids before cancellation+ * // normalizes the URL prefix before cancellation*/- it('normalizes the URL prefix and deduplicates matched run ids', async () => {+ it('normalizes the workflow URL prefix before cancellation', async () => {const client = {cancel: vi.fn().mockResolvedValue({ cancelled: 1 }),- logs: vi.fn().mockResolvedValue({- runs: [- {- workflowRunId: 'wfr_1',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',- },- {- workflowRunId: 'wfr_1',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',- },- {- workflowRunId: 'wfr_other',- workflowState: 'RUN_STARTED',- workflowUrl: 'https://app.lobehub.com/api/workflows/agent-eval-run/execute-test-case',- },- ],- }),};await expect(@@ -94,82 +52,16 @@ describe('workflow run guard qstash cancel', () => {client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],{appUrl: 'https://app.lobehub.com/',- workflowPath: '/api/workflows/memory-user-memory/',+ workflowPath: '/api/workflows/memory-user-memory/?cursor=1#hash',},),).resolves.toEqual({cancelled: 1,- matchedRunIds: ['wfr_1'],workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});- expect(client.cancel).toHaveBeenCalledWith({ ids: ['wfr_1'] });- });-- /**- * @example- * cancelWorkflowRunsByGuardPolicy(client, {- * appUrl: 'https://app.lobehub.com',- * workflowPath: 'api/workflows/memory-user-memory/pipelines/process-topic',- * })- * // does not cancel sibling routes with the same string prefix- */- it('matches workflow URL prefixes on path segment boundaries', async () => {- const client = {- cancel: vi.fn().mockResolvedValue({ cancelled: 2 }),- logs: vi.fn().mockResolvedValue({- runs: [- {- workflowRunId: 'wfr_exact',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic',- },- {- workflowRunId: 'wfr_child',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic/child',- },- {- workflowRunId: 'wfr_query',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic?cursor=1',- },- {- workflowRunId: 'wfr_sibling',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topics',- },- {- workflowRunId: 'wfr_v2',- workflowState: 'RUN_STARTED',- workflowUrl:- 'https://app.lobehub.com/api/workflows/memory-user-memory-v2/pipelines/process-topic',- },- ],- }),- };-- await expect(- cancelWorkflowRunsByGuardPolicy(- client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],- {- appUrl: 'https://app.lobehub.com',- workflowPath: 'api/workflows/memory-user-memory/pipelines/process-topic',- },- ),- ).resolves.toEqual({- cancelled: 2,- matchedRunIds: ['wfr_exact', 'wfr_child', 'wfr_query'],- workflowUrlPrefix:- 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic',- });-expect(client.cancel).toHaveBeenCalledWith({- ids: ['wfr_exact', 'wfr_child', 'wfr_query'],+ urlStartingWith: 'https://app.lobehub.com/api/workflows/memory-user-memory',});});@@ -179,12 +71,11 @@ describe('workflow run guard qstash cancel', () => {* appUrl: 'https://app.lobehub.com',* workflowPath: 'api/workflows/memory-user-memory',* })- * // returns zero and does not call cancel when logs have no matches+ * // returns the SDK cancellation count, including zero*/- it('returns zero when no started runs match', async () => {+ it('returns zero when QStash reports no cancelled workflows', async () => {const client = {- cancel: vi.fn(),- logs: vi.fn().mockResolvedValue({ runs: [] }),+ cancel: vi.fn().mockResolvedValue({ cancelled: 0 }),};await expect(@@ -197,10 +88,7 @@ describe('workflow run guard qstash cancel', () => {),).resolves.toEqual({cancelled: 0,- matchedRunIds: [],workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',});-- expect(client.cancel).not.toHaveBeenCalled();});});diff --git a/src/server/workflows/runGuard/qstashCancel.ts b/src/server/workflows/runGuard/qstashCancel.tsindex 8f9c3befdf1..edc2f816784 100644--- a/src/server/workflows/runGuard/qstashCancel.ts+++ b/src/server/workflows/runGuard/qstashCancel.ts@@ -18,7 +18,7 @@ export interface CancelWorkflowRunsByGuardPolicyParams {}/**- * Result returned after resolving and optionally cancelling QStash workflow runs.+ * Result returned after cancelling QStash workflow runs by URL prefix.*/export interface CancelWorkflowRunsByGuardPolicyResult {/**@@ -27,21 +27,16 @@ export interface CancelWorkflowRunsByGuardPolicyResult {cancelled: number;/**- * Deduplicated workflow run ids selected from active QStash logs.- */- matchedRunIds: string[];-- /**- * Absolute workflow URL prefix used for local log filtering.+ * Absolute workflow URL prefix passed to the QStash workflow cancellation API.*/workflowUrlPrefix: string;}/**- * Builds the absolute workflow URL prefix used for QStash log matching.+ * Builds the absolute workflow URL prefix used for QStash cancellation.** Use when:- * - Resolving workflow runs from QStash logs by workflow path.+ * - Cancelling workflow runs from QStash by workflow path.* - Matching child workflow endpoint prefixes under a route group.** Expects:@@ -57,51 +52,28 @@ export const buildWorkflowUrlPrefix = ({}: CancelWorkflowRunsByGuardPolicyParams): string =>new URL(`/${normalizeWorkflowRunGuardPath(workflowPath)}`, appUrl).toString().replace(/\/$/, '');-const matchesWorkflowUrlPrefix = (workflowUrl: string, workflowUrlPrefix: string): boolean => {- if (workflowUrl === workflowUrlPrefix) return true;- if (!workflowUrl.startsWith(workflowUrlPrefix)) return false;-- const boundary = workflowUrl.at(workflowUrlPrefix.length);- return boundary === '/' || boundary === '?' || boundary === '#';-};-/**- * Cancels active QStash workflow runs selected by a workflow run guard policy.+ * Cancels QStash workflow runs selected by a workflow run guard policy.** Use when:- * - A guard with QStash cancellation enabled should stop already-started workflow runs.- * - SDK `urlStartingWith` cancellation cannot be trusted and run ids must be resolved first.+ * - A guard with QStash cancellation enabled should stop pending and active workflow runs.+ * - QStash should resolve matching workflow runs by URL prefix.** Expects:- * - `client.logs` supports filtering with `{ count: 100, state: 'RUN_STARTED' }`.- * - QStash log entries include workflow URL, state, and run id fields.+ * - `client.cancel` supports `{ urlStartingWith }` for workflow URL prefix cancellation.** Returns:- * - The workflow URL prefix, matched run ids, and QStash cancellation count.+ * - The workflow URL prefix and QStash cancellation count.*/export const cancelWorkflowRunsByGuardPolicy = async (- client: Pick<WorkflowClient, 'cancel' | 'logs'>,+ client: Pick<WorkflowClient, 'cancel'>,params: CancelWorkflowRunsByGuardPolicyParams,): Promise<CancelWorkflowRunsByGuardPolicyResult> => {const workflowUrlPrefix = buildWorkflowUrlPrefix(params);- const logs = await client.logs({ count: 100, state: 'RUN_STARTED' });- const matchedRunIds = Array.from(- new Set(- logs.runs- .filter((run) => matchesWorkflowUrlPrefix(run.workflowUrl, workflowUrlPrefix))- .map((run) => run.workflowRunId),- ),- );-- if (matchedRunIds.length === 0) {- return { cancelled: 0, matchedRunIds, workflowUrlPrefix };- }-- const result = await client.cancel({ ids: matchedRunIds });+ const result = await client.cancel({ urlStartingWith: workflowUrlPrefix });return {cancelled: result.cancelled || 0,- matchedRunIds,workflowUrlPrefix,};};