Files
shockbot/utils/payload.ts
T
David Blass 8c6cd2bda2 cancel + restart workflow run when @pullfrog mention is edited (#612)
* cancel + restart workflow run when @pullfrog mention is edited

- add `WorkflowRun.triggeringCommentId` (BigInt?, indexed) so the webhook
  handler can find the run that was fired by a given comment
- thread `triggeringCommentId` through `reserveRun` / `triggerWorkflow`
- factor `dispatchMentionRun` out of `issue_comment_created` so the same
  shape is reused on edit
- replace the `issue_comment_edited` stub: re-evaluates the trigger gate,
  cancels prior runs (`octokit.rest.actions.cancelWorkflowRun` + DB
  status='cancelled'), then re-dispatches with a `previousRunsNote`
  appended to `eventInstructions` so the agent acknowledges the prior
  run/PR/artifacts in its summary
- if the edit removes `@pullfrog`, cancel only (no restart)

Co-authored-by: Cursor <cursoragent@cursor.com>

* thread previousRunsNote via dedicated payload field

user prompt has precedence over eventInstructions, so stuffing the
prior-runs note into eventInstructions made it vanish whenever the
trigger comment contained an @pullfrog mention (which is always for the
edit path). pass it as its own payload field and render it alongside the
user's task so the agent actually sees it.

* delete cancelled run's progress comment on edit-restart

so the issue thread doesn't accumulate "This run was cancelled" stubs
on every edit. only deletes for runs we actively cancel; runs that were
already terminal (e.g. completed before the edit) keep their summary
comment in the thread, and `previousRunsNote` links to it so the new
agent can reference prior work.

post-cleanup is race-safe: the action's `validateStuckProgressComment`
swallows the 404 from the deleted comment and exits cleanly, so the
old run's post step cannot clobber the new run's leaping comment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* also cancel + delete progress comment when triggering comment is deleted

mirrors the edit-removes-@pullfrog path: when an @pullfrog comment that
fired a run is hard-deleted, look up any prior runs by triggeringCommentId,
GH-cancel running ones, and delete their leaping progress comments.

skips trigger-gate re-eval (we're tearing down a run, not firing one) and
performs no restart. reuses the existing cancelRunsForTriggeringComment
helper; the returned previousRunsNote is discarded since no dispatch
follows.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: move cancellation before trigger gate in issue_comment_edited

cancelRunsForTriggeringComment now runs before the triggerEnabled check,
so edits that remove @pullfrog still cancel in-flight runs even when the
repo mention trigger is currently disabled (e.g. for non-collaborators).

* anneal: scope cancel updates per-row + simplify edit gate

- replace blanket updateMany on (triggeringCommentId, repoId) with per-row, status-guarded updates so a parallel handler's freshly-reserved run cannot be clobbered into cancelled by a racing edit delivery.
- drop wasMention/isMention early-break in issue_comment_edited; always run cancelRunsForTriggeringComment (DB is the canonical "did this comment ever trigger a run" source). closes the missing-changes.body.from edge and lets us tear down a still-running prior run even if the admin disabled the mention trigger mid-flight.
- buildPreviousRunsNote returns undefined (not "") when no link lines materialize.
- doc cleanups + wiki/modes.md addendum noting issue_comment_edited / _deleted now drive cancel + restart.

Co-authored-by: Cursor <cursoragent@cursor.com>

* address review feedback on cancel/restart semantics

- guard workflow_run.completed update against status='cancelled' so a
  successful-but-uncancellable GH Actions job can't resurrect a cancelled
  row (and re-bill it) via the completed webhook.
- bucket only status='completed' runs into `preserved` in
  cancelRunsForTriggeringComment; cancelled/failed prior runs have stubs
  as their progress comment, not summaries worth referencing.
- emit previousRunsNote for the runId-null cancel case so the restarted
  agent always knows when it's superseding a prior dispatch.
- drop the agent-forbidden `gh pr list` hint and soften 'was cancelled'
  to 'was signalled to cancel' in the note body.
- post a fallback comment when the edit-path dispatch fails (prior run
  already torn down and progress comment already deleted).
- symmetrize the delete-handler's pullfrog guard with the edit handler
  (key off hook.comment.user, not hook.sender).
- trim misleading comments on the per-row DB update guard.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-05-11 23:20:44 +00:00

178 lines
6.5 KiB
TypeScript

import { isAbsolute, resolve } from "node:path";
import * as core from "@actions/core";
import { type } from "arktype";
import type { AuthorPermission, PayloadEvent } from "../external.ts";
import packageJson from "../package.json" with { type: "json" };
import type { RepoSettings } from "./runContext.ts";
import { validateCompatibility } from "./versioning.ts";
// tool permission enum types for inputs
const ShellPermissionInput = type.enumerated("disabled", "restricted", "enabled");
const PushPermissionInput = type.enumerated("disabled", "restricted", "enabled");
// schema for JSON payload passed via prompt (internal dispatch invocation)
// note: permissions are intentionally NOT included here to prevent injection attacks
// permissions are derived from event.authorPermission instead
export const JsonPayload = type({
"~pullfrog": "true",
version: "string",
"model?": "string | undefined",
prompt: "string",
"triggerer?": "string | undefined",
"eventInstructions?": "string",
"previousRunsNote?": "string",
"event?": "object",
"timeout?": "string | undefined",
"progressComment?": type({
id: "string",
type: "'issue' | 'review'",
}).or("undefined"),
"generateSummary?": "boolean | undefined",
});
// permission levels that indicate collaborator status (have push access)
const COLLABORATOR_PERMISSIONS: AuthorPermission[] = ["admin", "maintain", "write"];
// check if the event author has collaborator-level permissions
function isCollaborator(event: PayloadEvent): boolean {
const perm = event.authorPermission;
return perm !== undefined && COLLABORATOR_PERMISSIONS.includes(perm);
}
// inputs schema - action inputs from core.getInput()
// note: tool permissions use .or("undefined") because getInput() || undefined
// explicitly sets the property to undefined when empty, which is different from
// the property being absent. arktype's "prop?" means "optional to include" but
// if included, must match the type - so we need to explicitly allow undefined.
export const Inputs = type({
prompt: "string",
"model?": type.string.or("undefined"),
"timeout?": type.string.or("undefined"),
"push?": PushPermissionInput.or("undefined"),
"shell?": ShellPermissionInput.or("undefined"),
"cwd?": type.string.or("undefined"),
"output_schema?": type.string.or("undefined"),
});
export type Inputs = typeof Inputs.infer;
function isPayloadEvent(value: unknown): value is PayloadEvent {
return typeof value === "object" && value !== null && "trigger" in value;
}
function resolveCwd(cwd: string | undefined): string | undefined {
const workspace = process.env.GITHUB_WORKSPACE;
if (!cwd) return workspace;
if (isAbsolute(cwd)) return cwd;
return workspace ? resolve(workspace, cwd) : cwd;
}
export type ResolvedPromptInput = string | typeof JsonPayload.infer;
export function resolvePromptInput(): ResolvedPromptInput {
const prompt = core.getInput("prompt", { required: true });
let parsed: unknown;
try {
parsed = JSON.parse(prompt);
} catch {
// JSON parse error is fine (plain text prompt)
return prompt;
}
if (!parsed || typeof parsed !== "object" || !("~pullfrog" in parsed)) {
// if it doesn't look like a pullfrog payload, return the plain text prompt
return prompt;
}
// validation errors should propagate
const jsonPayload = JsonPayload.assert(parsed);
validateCompatibility(jsonPayload.version, packageJson.version);
return jsonPayload;
}
function resolveNonPromptInputs() {
return Inputs.omit("prompt").assert({
model: core.getInput("model") || undefined,
timeout: core.getInput("timeout") || undefined,
cwd: core.getInput("cwd") || undefined,
push: core.getInput("push") || undefined,
shell: core.getInput("shell") || undefined,
});
}
const isPullfrog = (actor: string | null | undefined): boolean => {
actor = actor?.replace("[bot]", "");
return !!actor && (actor === "pullfrog" || actor === "pullfrogdev");
};
export function resolvePayload(
resolvedPromptInput: ResolvedPromptInput,
repoSettings: RepoSettings
) {
const [prompt, jsonPayload] =
typeof resolvedPromptInput !== "string"
? [resolvedPromptInput.prompt, resolvedPromptInput]
: [resolvedPromptInput, undefined];
const inputs = resolveNonPromptInputs();
// resolve event - use type guard for jsonPayload.event, fallback to unknown trigger
const rawEvent = jsonPayload?.event;
const event: PayloadEvent = isPayloadEvent(rawEvent) ? rawEvent : { trigger: "unknown" };
const model = jsonPayload?.model ?? inputs.model ?? repoSettings.model ?? undefined;
// determine shell permission - strictest setting wins
// precedence: disabled > restricted > enabled
// non-collaborators always get at least "restricted"
const isNonCollaborator = !isCollaborator(event);
const repoShell = repoSettings.shell ?? "restricted";
const inputShell = inputs.shell;
// resolve shell: start with repo setting, then apply restrictions
let resolvedShell = repoShell;
// input can only make it stricter (disabled > restricted > enabled)
if (inputShell === "disabled") {
resolvedShell = "disabled";
} else if (inputShell === "restricted" && resolvedShell === "enabled") {
resolvedShell = "restricted";
}
// non-collaborators get at least "restricted" (can't have "enabled")
if (isNonCollaborator && resolvedShell === "enabled") {
resolvedShell = "restricted";
}
// build payload - precedence: inputs > repoSettings > fallbacks
// note: modes are NOT in payload - they come from repoSettings in main()
return {
"~pullfrog": true as const,
version: jsonPayload?.version ?? packageJson.version,
model,
prompt,
triggerer:
jsonPayload?.triggerer ??
// it's not a common use case but GITHUB_ACTOR can be a user when the workflow is manually triggered by a user through GitHub Actions UI
(!isPullfrog(process.env.GITHUB_ACTOR) ? process.env.GITHUB_ACTOR : undefined),
eventInstructions: jsonPayload?.eventInstructions,
previousRunsNote: jsonPayload?.previousRunsNote,
event,
timeout: inputs.timeout ?? jsonPayload?.timeout,
cwd: resolveCwd(inputs.cwd),
progressComment: jsonPayload?.progressComment,
generateSummary: jsonPayload?.generateSummary,
// permissions: inputs > repoSettings > fallbacks
push: inputs.push ?? repoSettings.push ?? "restricted",
shell: resolvedShell,
// set by proxy logic in main.ts when routing through OpenRouter
proxyModel: undefined as string | undefined,
};
}
export type ResolvedPayload = ReturnType<typeof resolvePayload>;