-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(cli): auto-cancel dev runs on CLI exit via detached watchdog #3191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ericallam
merged 6 commits into
main
from
feature/tri-7779-we-need-to-cancel-runs-when-the-cli-exists-again-to-prevent
Mar 9, 2026
+564
−31
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
562e88a
feat(cli): auto-cancel dev runs on CLI exit via detached watchdog
ericallam 0721012
fix: address CodeRabbit review feedback
ericallam e94add9
fix(cli): check response.ok and retry disconnect with exponential bac…
ericallam cb1cc61
fix(cli): use engineUrl for watchdog disconnect, exit on SIGINT
ericallam 09ac03a
fix(cli): unify shutdown sequence, guard PID-file fallback against reuse
ericallam 245c6ad
fix: restrict dev disconnect endpoint to DEVELOPMENT environments
ericallam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| "trigger.dev": patch | ||
| "@trigger.dev/core": patch | ||
| --- | ||
|
|
||
| Auto-cancel in-flight dev runs when the CLI exits, using a detached watchdog process that survives pnpm SIGKILL |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| area: webapp | ||
| type: feature | ||
| --- | ||
|
|
||
| Added `/engine/v1/dev/disconnect` endpoint to auto-cancel runs when the CLI disconnects. Maximum of 500 runs can be cancelled. Uses the bulk action system when there are more than 25 runs to cancel. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| import { json } from "@remix-run/server-runtime"; | ||
| import { Ratelimit } from "@upstash/ratelimit"; | ||
| import { tryCatch } from "@trigger.dev/core"; | ||
| import { DevDisconnectRequestBody } from "@trigger.dev/core/v3"; | ||
| import { BulkActionId, RunId } from "@trigger.dev/core/v3/isomorphic"; | ||
| import { BulkActionNotificationType, BulkActionType } from "@trigger.dev/database"; | ||
| import { prisma } from "~/db.server"; | ||
| import { logger } from "~/services/logger.server"; | ||
| import { RateLimiter } from "~/services/rateLimiter.server"; | ||
| import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server"; | ||
| import { CancelTaskRunService } from "~/v3/services/cancelTaskRun.server"; | ||
| import { commonWorker } from "~/v3/commonWorker.server"; | ||
| import pMap from "p-map"; | ||
|
|
||
| const CANCEL_REASON = "Dev session ended (CLI exited)"; | ||
|
|
||
| // Below this threshold, cancel runs inline with pMap. | ||
| // Above it, create a bulk action and process asynchronously. | ||
| const BULK_ACTION_THRESHOLD = 25; | ||
|
|
||
| // Maximum number of runs that can be cancelled in a single disconnect call. | ||
| const MAX_RUNS = 500; | ||
|
|
||
| // Rate limit: 5 calls per minute per environment | ||
| const disconnectRateLimiter = new RateLimiter({ | ||
| keyPrefix: "dev-disconnect", | ||
| limiter: Ratelimit.fixedWindow(5, "1 m"), | ||
| logFailure: true, | ||
| }); | ||
|
|
||
| const { action } = createActionApiRoute( | ||
| { | ||
| body: DevDisconnectRequestBody, | ||
| maxContentLength: 1024 * 256, // 256KB | ||
| method: "POST", | ||
| }, | ||
| async ({ authentication, body }) => { | ||
| // Only allow dev environments — this endpoint uses finalizeRun which | ||
| // skips PENDING_CANCEL and immediately finalizes executing runs. | ||
| if (authentication.environment.type !== "DEVELOPMENT") { | ||
| return json({ error: "This endpoint is only available for dev environments" }, { status: 403 }); | ||
| } | ||
|
|
||
| const environmentId = authentication.environment.id; | ||
|
|
||
| // Rate limit per environment | ||
| const rateLimitResult = await disconnectRateLimiter.limit(environmentId); | ||
| if (!rateLimitResult.success) { | ||
| return json( | ||
| { error: "Rate limit exceeded", retryAfter: Math.ceil((rateLimitResult.reset - Date.now()) / 1000) }, | ||
| { status: 429 } | ||
| ); | ||
| } | ||
|
|
||
| if (body.runFriendlyIds.length > MAX_RUNS) { | ||
| return json( | ||
| { error: `A maximum of ${MAX_RUNS} runs can be cancelled per request` }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const { runFriendlyIds } = body; | ||
|
|
||
| if (runFriendlyIds.length === 0) { | ||
| return json({ cancelled: 0 }, { status: 200 }); | ||
| } | ||
|
|
||
| logger.info("Dev disconnect: cancelling runs", { | ||
| environmentId, | ||
| runCount: runFriendlyIds.length, | ||
| }); | ||
|
|
||
| // For small numbers of runs, cancel inline | ||
| if (runFriendlyIds.length <= BULK_ACTION_THRESHOLD) { | ||
| const cancelled = await cancelRunsInline(runFriendlyIds, environmentId); | ||
| return json({ cancelled }, { status: 200 }); | ||
| } | ||
|
|
||
| // For large numbers, create a bulk action to process asynchronously | ||
| const bulkActionId = await createBulkCancelAction( | ||
| runFriendlyIds, | ||
| authentication.environment.project.id, | ||
| environmentId | ||
| ); | ||
|
|
||
| logger.info("Dev disconnect: created bulk action for large run set", { | ||
| environmentId, | ||
| bulkActionId, | ||
| runCount: runFriendlyIds.length, | ||
| }); | ||
|
|
||
| return json({ cancelled: 0, bulkActionId }, { status: 200 }); | ||
| } | ||
| ); | ||
devin-ai-integration[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| async function cancelRunsInline( | ||
| runFriendlyIds: string[], | ||
| environmentId: string | ||
| ): Promise<number> { | ||
| const runIds = runFriendlyIds.map((fid) => RunId.toId(fid)); | ||
|
|
||
| const runs = await prisma.taskRun.findMany({ | ||
| where: { | ||
| id: { in: runIds }, | ||
| runtimeEnvironmentId: environmentId, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| engine: true, | ||
| friendlyId: true, | ||
| status: true, | ||
| createdAt: true, | ||
| completedAt: true, | ||
| taskEventStore: true, | ||
| }, | ||
| }); | ||
|
|
||
| let cancelled = 0; | ||
| const cancelService = new CancelTaskRunService(prisma); | ||
|
|
||
| await pMap( | ||
| runs, | ||
| async (run) => { | ||
| const [error, result] = await tryCatch( | ||
| cancelService.call(run, { reason: CANCEL_REASON, finalizeRun: true }) | ||
| ); | ||
|
|
||
| if (error) { | ||
| logger.error("Dev disconnect: failed to cancel run", { | ||
| runId: run.id, | ||
| error, | ||
| }); | ||
| } else if (result && !result.alreadyFinished) { | ||
| cancelled++; | ||
| } | ||
| }, | ||
| { concurrency: 10 } | ||
| ); | ||
|
|
||
| logger.info("Dev disconnect: completed inline cancellation", { | ||
| environmentId, | ||
| cancelled, | ||
| total: runFriendlyIds.length, | ||
| }); | ||
|
|
||
| return cancelled; | ||
| } | ||
|
|
||
| async function createBulkCancelAction( | ||
| runFriendlyIds: string[], | ||
| projectId: string, | ||
| environmentId: string | ||
| ): Promise<string> { | ||
| const { id, friendlyId } = BulkActionId.generate(); | ||
|
|
||
| await prisma.bulkActionGroup.create({ | ||
| data: { | ||
| id, | ||
| friendlyId, | ||
| projectId, | ||
| environmentId, | ||
| name: "Dev session disconnect", | ||
| type: BulkActionType.CANCEL, | ||
| params: { runId: runFriendlyIds, finalizeRun: true }, | ||
| queryName: "bulk_action_v1", | ||
| totalCount: runFriendlyIds.length, | ||
| completionNotification: BulkActionNotificationType.NONE, | ||
| }, | ||
| }); | ||
|
|
||
| await commonWorker.enqueue({ | ||
| id: `processBulkAction-${id}`, | ||
| job: "processBulkAction", | ||
| payload: { bulkActionId: id }, | ||
| }); | ||
|
|
||
| return friendlyId; | ||
| } | ||
|
|
||
| export { action }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.