Skip to content

fix(cli): honor SIGINT/SIGTERM in browser and JS-runtime commands - #2879

Closed
DeryFerd wants to merge 3 commits into
morluto:mainfrom
DeryFerd:fix/cli-browser-javascript-cancellation
Closed

DeryFerd wants to merge 3 commits into
morluto:mainfrom
DeryFerd:fix/cli-browser-javascript-cancellation

Conversation

@DeryFerd

Copy link
Copy Markdown
Contributor

Summary

rea's passive browser commands and V8 Inspector commands do not honor SIGINT or SIGTERM. When you interrupt one of them, the process either dies without running any awaited cleanup or reports an ordinary operation failure instead of a cancellation, so a caller watching the process status cannot tell "I interrupted this" from "this broke". This PR wires the eight affected CLI commands through the same cancellation boundary the rest of the CLI already uses, so an interrupt aborts the in-flight observation, waits for cleanup, and exits with the conventional 130 (SIGINT) or 143 (SIGTERM) status while printing the typed cancelled result.

The MCP side already threads context.mcpReq.signal into these same services, and the services already accept an ExecutionOptions signal. Only the CLI adapter was missing the boundary, which makes this a one-layer fix rather than a contract change. The sibling web-runtime commands (observe-web-execution, inspect-web-event-listeners) already received this exact treatment for the same defect (issue #1126, commit 1d9b96a9c); this PR applies the established pattern to the browser and JavaScript-runtime commands that were left behind.

Problem and expected behavior

Smallest trigger: run any of these commands against a loopback endpoint that accepts the discovery connection but never answers, then send SIGINT or SIGTERM once the command has parked in discovery.

rea list-browser-targets http://127.0.0.1:<port> --json
rea inspect-web-page http://127.0.0.1:<port> <target-id> --json
rea analyze-web-bundle http://127.0.0.1:<port> <target-id> --json
rea observe-web-session http://127.0.0.1:<port> <target-id> --observation-ms 30000 --json
rea discover-webmcp-tools http://127.0.0.1:<port> <target-id> --json
rea capture-web-screenshot http://127.0.0.1:<port> <target-id> --json
rea list-javascript-runtime-targets http://127.0.0.1:<port> --json
rea observe-javascript-runtime http://127.0.0.1:<port> <target-id> --observation-ms 30000 --json

Violated invariant: a one-shot CLI command that receives an interrupt should abort its awaited work, run cleanup, and exit with the signal's conventional status and a typed cancellation result, matching every other cancellable command in the CLI. Before this change these eight commands registered their handlers directly, so the interrupt reached the process without any listener that aborts the observation. The command then either terminated abruptly or, once the stalled discovery finally failed on its own, reported a provider failure and exited 1.

Expected behavior after the change: the interrupt aborts the pending CDP/Inspector work, the command resolves a cancelled result with cleanup: "complete", and the process exits 130 for SIGINT and 143 for SIGTERM. Two of the browser commands, compare-web-captures and compare-web-screenshots, are pure comparisons with no provider or socket work, so they are correctly left unwrapped.

Change and scope

The change is narrow and follows an existing pattern instead of inventing a new one. Each affected handler is wrapped in withCommandCancellation((signal) => logCliCommand(...)) and passes { signal } into the service call it already makes. withCommandCancellation installs SIGINT/SIGTERM listeners that abort an AbortController, records 130/143, and removes the listeners in a finally block that also sets process.exitCode. The aborted signal travels through the existing ExecutionOptions plumbing into discoverCdpEndpoint and readCdpJson, which already translate an aborted signal into AnalysisCancelledError, and logCliCommand already projects that into the typed cancelled result. Nothing in the domain, application, or provider layers needed to change, because the only broken stage was the CLI adapter's missing boundary.

Files changed:

  • src/cli/browserCommands.ts wraps list-browser-targets, inspect-web-page, analyze-web-bundle, and observe-web-session.
  • src/cli/browserAdvancedCommands.ts wraps discover-webmcp-tools and capture-web-screenshot.
  • src/cliJavaScriptRuntimeCommands.ts wraps list-javascript-runtime-targets and observe-javascript-runtime.
  • tests/acceptance/passiveObservationCliCancellation.test.ts and tests/fixtures/passiveObservationCancellation.mjs add the regression coverage.

Intentionally not included: no change to withCommandCancellation itself, no change to the MCP adapters (they already pass context.mcpReq.signal), no change to service signatures (they already accept ExecutionOptions), and no change to the pure comparison commands. The change is additive at the adapter boundary and does not expand what any command reads, launches, injects, or mutates.

Follow the contribution scope. This is a routine bug fix inside existing boundaries, so no advance maintainer scope decision is required; the linked scope decision is "not applicable".

Contract and boundary impact

  • Semantic owner and earliest changed stage: The CLI command adapter owns interrupt handling. The earliest changed stage is the adapter boundary, where the handlers previously registered without a cancellation listener. Domain, application, and provider layers are unchanged.
  • Contribution scope fit and linked maintainer decision: Routine fix within existing boundaries; no new provider, target execution, injection, mutation, or protection recovery. Not applicable.
  • CLI and MCP/tool-catalog contract: No command name, argument, option, or JSON field changes. The only observable change is that an interrupted command now exits 130/143 and returns the existing cancelled result instead of exiting 1 with a provider failure. MCP is untouched and already cancels through context.mcpReq.signal. No generated tool catalog changes.
  • Provider, bridge, target-format, or platform compatibility: Applies to all platforms. POSIX delivers a real SIGINT/SIGTERM; Windows cannot deliver a catchable signal through child.kill(signal), so the test exercises the same handler through an in-process relay. No CDP, Inspector, or bridge protocol change.
  • Evidence, artifact, provenance, or reconstruction contract: Unchanged. Cancellation still produces the typed cancelled result with cleanup: "complete"; no artifact is published for a cancelled observation, and partial evidence semantics are unchanged.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): These commands only connect to a caller-supplied loopback CDP/Inspector endpoint and read page or runtime evidence. The change adds awaited cleanup on interrupt; it does not add target selection, launch, injection, or mutation authority.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): None. No contract, schema, catalog, package, or installation surface changes.

Expected effects (check known effects; use documentation-only on its own). Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

The two checked items describe the commands' existing passive behavior: they read page and runtime evidence and connect to a caller-supplied loopback CDP/Inspector endpoint. This PR changes none of those effects; it only adds awaited cleanup when the caller interrupts.

Evidence and regression coverage

  • Tests added or updated: tests/acceptance/passiveObservationCliCancellation.test.ts drives all eight commands through a real rea process against a stalled loopback server, and asserts that the process exits 130/143, that it was not force-terminated, and that stdout carries the cancelled result with cleanup: "complete" and the matching operation. It runs 16 cases (eight commands across SIGINT and SIGTERM). tests/fixtures/passiveObservationCancellation.mjs is the relay hook that re-emits the signal in-process on Windows, where the OS cannot deliver a catchable signal to a child.
  • Base reproduction or other evidence: On the unmodified base revision the test fails 16 of 16 cases: the interrupt force-terminates the child (observed terminationSignal: "SIGINT" with a null exit code) or the stalled discovery eventually fails and the command exits 1 with a provider failure instead of the cancelled result. With the fix in place all 16 cases pass. The regression therefore fails on the affected base revision and passes after the change.
  • User-visible CLI/MCP output (if applicable): An interrupted command now resolves the typed cancellation instead of a provider failure. The asserted fields are:
{
  "code": "cancelled",
  "category": "cancelled",
  "details": { "cleanup": "complete", "operation": "list_browser_targets" }
}
  • Remaining proof gaps: The acceptance test uses a stalled loopback fixture rather than a real browser or Electron target, which is deliberate: the assertion is about the adapter's interrupt wiring and awaited cleanup, and a real target would add a racing window without changing what is proven. On this Windows host the OS-signal lane is skipped and the relay lane runs; the OS-signal lane is exercised on the Linux CI shard. No real-browser or real-Electron cancellation run was performed here.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

The middle item is left unchecked because a cancelled observation publishes no artifact, so artifact identity and provenance are not exercised by this change. The typed cancelled result keeps the interrupted outcome visible rather than collapsing it into a generic failure.

Validation performed

  • npm run test:focused -- tests/acceptance/passiveObservationCliCancellation.test.ts — 16 passed, 16 skipped (the OS-signal lane is skipped on Windows; the relay lane runs). On the reverted base revision the same file reports 16 failed, 16 skipped.
  • npm run check:fast — passed (cached typecheck and lint, plus the pre-push check).
  • git diff --stat upstream/main...HEAD — 5 files changed, 420 insertions, 165 deletions.

Compatibility, safety, and release

  • Breaking changes or migration steps: None. Exit status for an interrupted command changes from 1 to the conventional 130/143, which is the fix, not a break. Command names, arguments, options, and JSON fields are unchanged.
  • Real Hopper/Ghidra, browser, or OS coverage: No Hopper or Ghidra involvement. The regression drives the real rea binary against a stalled loopback CDP/Inspector endpoint. A real browser or Electron target was not exercised; see the remaining proof gap above.
  • Package or release metadata impact: None. No package, lockfile, version, or generated metadata change.
  • Security, privacy, process, or containment review: The change only adds a signal listener that aborts in-flight work and removes itself in finally. It does not add target selection, execution, injection, mutation, persistence, or new network behavior, and it does not weaken any existing boundary. No secrets or sensitive values are involved.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

On the issue link: no open issue tracks this exact gap. Issue #1126 covers the sibling web-runtime commands and was fixed by the same pattern, so this PR extends that fix to the browser and JavaScript-runtime commands rather than reopening a closed issue. If maintainers prefer, this can be filed as a follow-up issue first.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-13T15:19:10.178169Z 3736be5 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] The remaining test-only changes appear safe to merge.

Summary

The current diff adds cancellation tests and fixture support. The production fixes described by the PR are already present in the target commit.

  • CLI cancellation tests cover all eight passive commands.
  • Service tests cover cancellation during browser and runtime observations.

Reviews (9) · Last reviewed commit: "Merge origin/main into fix/cli-browser-j..." · Reviewed by Greptile

Comment thread src/cli/browserCommands.ts Resolved
Comment thread src/cli/browserCommands.ts Resolved
@DeryFerd
DeryFerd force-pushed the fix/cli-browser-javascript-cancellation branch from 52a462c to 168d12e Compare October 13, 2026 16:29
Comment thread src/cliJavaScriptRuntimeCommands.ts Resolved
@DeryFerd
DeryFerd force-pushed the fix/cli-browser-javascript-cancellation branch 2 times, most recently from ca8150d to 0e2831b Compare October 13, 2026 16:46
@morluto
morluto force-pushed the fix/cli-browser-javascript-cancellation branch from 0fa72c3 to e80bdb0 Compare October 13, 2026 18:09
@morluto
morluto force-pushed the fix/cli-browser-javascript-cancellation branch from e80bdb0 to e4b07b8 Compare October 13, 2026 18:27
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The fix works on Linux. An interrupted command now exits 130 or 143 and prints a cancelled result. Without the fix, the same interrupt kills the process and prints nothing.

Head 0fa72c3 did not move while I tested. It was then rebased onto newer main twice, most recently as e4b07b8. The 14 files this PR changes are the same, byte for byte, so these results still apply.

Results

Test file Node 22 Node 24 Node 26 Before
passiveObservationCliCancellation, 16 cases pass pass pass 16 fail
browserObservationServiceCancellation, 5 cases pass pass pass 5 fail
cdpBrowserProvider.lifecycle_failures, 12 cases pass pass pass 1 fail
JavaScriptRuntimeObservationService, 2 cases pass pass pass 1 fail

Before means the head tree with six source files put back to their 93e29d2 (#2768) version. The PR's tests stay. The first file also skips 16 Windows-only cases.

By hand

I ran the compiled CLI against a loopback server that never answers. Then I sent one signal to the CLI's PID.

Command Signal Before Head
list-browser-targets SIGINT killed, no output exit 130, cancelled
list-browser-targets SIGTERM killed, no output exit 143, cancelled
list-javascript-runtime-targets SIGINT killed, no output exit 130, cancelled
list-javascript-runtime-targets SIGTERM killed, no output exit 143, cancelled

On head, stdout held the cancelled result and stderr stayed empty. The CLI exited about 30 ms after the signal. Its process group held only the CLI, and nothing was left after exit.

Notes

The description says no app or provider code changed. The later commits changed both. PR #2893 also edits src/browser/CdpBrowserProvider.ts. I did not compare the two diffs.

Not run

  • The Windows relay lane (the 16 skipped cases).
  • tests/boundary/browser/cdpCleanupCancellation.test.ts, which this PR also changes.
  • The Before tree on Node 22 and Node 26.
  • Interrupts after discovery, by hand. Only the new tests with fakes cover those.
  • The other six commands by hand. The acceptance test covers them.
  • A real browser or Electron target, typecheck, lint, the full suite and macOS.
  • A diff of this PR against fix(browser): report cancellation after cleanup and source-map abort #2893.

Thanks, DeryFerd, for the fix and for the quick follow-up commits.

Commands

Node 24 was first on PATH unless noted. HOME and TMPDIR pointed into the job folder.

npm ci --prefix /tmp/pr2879/head                  # exit 0
npm run build --prefix /tmp/pr2879/head           # exit 0
npm run test:prepare --prefix /tmp/pr2879/head    # exit 0
(same three on /tmp/pr2879/before)                # exit 0 each

# per Node, from the tree folder; four test files, one at a time
node scripts/run-development-tests.mjs focused tests/acceptance/passiveObservationCliCancellation.test.ts
node scripts/run-development-tests.mjs focused tests/boundary/browser/browserObservationServiceCancellation.test.ts
node scripts/run-development-tests.mjs focused tests/boundary/browser/cdpBrowserProvider.lifecycle_failures.test.ts
node scripts/run-development-tests.mjs focused src/application/javascript/JavaScriptRuntimeObservationService.test.ts
# head: Node 22, 24, 26 -> exit 0 on all twelve runs
# before: Node 24 -> exit 1 on all four runs

# by hand (driver script below)
node signal-driver.mjs /tmp/pr2879/head list-browser-targets SIGINT
node signal-driver.mjs /tmp/pr2879/head list-browser-targets SIGTERM
node signal-driver.mjs /tmp/pr2879/head list-javascript-runtime-targets SIGINT
node signal-driver.mjs /tmp/pr2879/head list-javascript-runtime-targets SIGTERM
(same four on /tmp/pr2879/before)
SIGNAL_GAP_MS=0 node signal-driver.mjs /tmp/pr2879/head list-browser-targets SIGINT,SIGTERM   # CLI exit 130
SIGNAL_GAP_MS=0 node signal-driver.mjs /tmp/pr2879/head list-browser-targets SIGTERM,SIGINT   # CLI exit 143

On head, I also sent two signals back to back. The first one set the exit code. SIGINT first gave 130, and SIGTERM first gave 143.

On the Before tree, the acceptance failures read expected 'SIGINT' to be null (and 'SIGTERM'), because the child died from the signal. The service tests got evidence where they wanted a cancelled result. The provider test got ProviderAdapterError where it wanted AnalysisCancelledError. The JS runtime test got evidence where it wanted a cancelled result.

Driver script
// Usage: node signal-driver.mjs <tree> <command> <signal[,signal2]> [extra CLI args...]
// Starts a loopback HTTP server that accepts and never answers, starts the compiled CLI
// from <tree>/scripts/rea.mjs in its own process group, waits until the CLI has contacted
// the server, sends the signal(s) to the recorded child PID, and prints one JSON report.
import { spawn, execFileSync } from "node:child_process";
import { once } from "node:events";
import { createServer } from "node:http";

const [tree, command, signalArg, ...extra] = process.argv.slice(2);
const signals = signalArg.split(",");
const sockets = new Set();
const server = createServer(() => undefined);
server.on("connection", (socket) => {
  sockets.add(socket);
  socket.once("close", () => sockets.delete(socket));
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const port = server.address().port;
const contacted = once(server, "request");

const groupMembers = (pgid) =>
  execFileSync("ps", ["-eo", "pid,ppid,pgid,stat,args", "--no-headers"], {
    encoding: "utf8",
  })
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line.length > 0)
    .map((line) => {
      const [pid, ppid, group, stat, ...args] = line.split(/\s+/);
      return { pid: Number(pid), ppid: Number(ppid), pgid: Number(group), stat, args: args.join(" ") };
    })
    .filter((row) => row.pgid === pgid);

const child = spawn(
  process.execPath,
  [tree + "/scripts/rea.mjs", command, "http://127.0.0.1:" + port, ...extra, "--json"],
  {
    cwd: "/tmp/pr2879/tmp",
    detached: true,
    stdio: ["ignore", "pipe", "pipe"],
    env: {
      ...process.env,
      HOPPER_LAUNCHER_PATH: "/rea-unconfigured-provider/hopper",
    },
  },
);
const pid = child.pid;
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => (stdout += chunk));
child.stderr.on("data", (chunk) => (stderr += chunk));
const closed = once(child, "close");

let hung = false;
const hardStop = setTimeout(() => {
  hung = true;
  try {
    process.kill(pid, "SIGKILL");
  } catch {}
}, 20000);

await Promise.race([
  contacted,
  new Promise((_, reject) =>
    setTimeout(() => reject(new Error("CLI did not contact the server")), 8000),
  ),
]);
const before = groupMembers(pid);
const sent = [];
const t0 = Date.now();
process.kill(pid, signals[0]);
sent.push(signals[0]);
if (signals[1] !== undefined) {
  const gapMs = Number(process.env.SIGNAL_GAP_MS ?? 30);
  if (gapMs > 0) await new Promise((resolve) => setTimeout(resolve, gapMs));
  try {
    process.kill(pid, signals[1]);
    sent.push(signals[1]);
  } catch (error) {
    sent.push(signals[1] + " (failed: " + error.code + ")");
  }
}
const [exitCode, signalCode] = await closed;
const elapsedMs = Date.now() - t0;
clearTimeout(hardStop);
await new Promise((resolve) => setTimeout(resolve, 300));
const after = groupMembers(pid);
let pidAlive = true;
try {
  process.kill(pid, 0);
} catch {
  pidAlive = false;
}
const serverSocketsOpen = sockets.size;
for (const socket of sockets) socket.destroy();
await new Promise((resolve) => server.close(() => resolve()));
console.log(
  JSON.stringify(
    {
      tree,
      command,
      extra,
      pid,
      sent,
      exitCode,
      signalCode,
      elapsedMs,
      hung,
      groupBeforeSignal: before.map((row) => ({ pid: row.pid, ppid: row.ppid, args: row.args.slice(0, 120) })),
      groupAfterExit: after.map((row) => ({ pid: row.pid, ppid: row.ppid, stat: row.stat, args: row.args.slice(0, 120) })),
      pidAliveAfterExit: pidAlive,
      serverSocketsStillOpenAtExit: serverSocketsOpen,
      stdout,
      stderr,
    },
    null,
    2,
  ),
);
Test setup

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

@greptile-apps

greptile-apps Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

DeryFerd and others added 2 commits October 14, 2026 02:51
… JS-runtime commands

The passive browser and V8 Inspector CLI command groups invoked their
services without an AbortSignal, so Ctrl-C did not cancel an in-flight
observation the way it does everywhere else in the CLI. Every other command
family either wraps its handler in withCommandCancellation or reaches
withProcessCancellation inside runDirectAnalysis; these two groups did
neither. Wrap each network-touching handler in
withCommandCancellation((signal) => logCliCommand(...)) and thread { signal }
into the service call. The service layer already accepts options:
ExecutionOptions and the providers already forward options.signal into CDP
discovery, so this is adapter parity with the MCP side, which already passes
context.mcpReq.signal. The pure compare-web-captures / compare-web-screenshots
commands stay unwrapped because they touch no provider.

Once the signal reaches the provider, three more windows could still misreport
an interrupt. `fetchWebSourceMaps` throws the caller's abort reason, which is
not an `AnalysisError`, so `providerError` wrapped it in `ProviderAdapterError`
and `analyze-web-bundle --fetch-source-maps` printed `execution_failure` even
though the command exited 130/143. `providerError` now receives the caller
signal and classifies a non-analysis cause raised under an aborted signal as
`AnalysisCancelledError`; deadline aborts still map to
`SourceMapDeadlineError` and are not misreported as cancellation. An interrupt
that lands while the provider awaits `closeCdpTargetSession` arrives after the
capture has already succeeded: the provider owns its transport and
legitimately reports the completed capture, but the application boundary was
still publishing it as evidence. `BrowserObservationService` now rechecks the
caller signal before publishing and returns `AnalysisCancelledError` for the
operation, matching the existing `WebRuntimeService.evidence()` pattern. The
same gap existed for `list-javascript-runtime-targets`, whose sibling
`observeJavaScriptRuntime` already rechecked the signal while
`listJavaScriptRuntimeTargets` did not; it now rechecks before creating
evidence, since `V8InspectorProvider.listTargets` awaits file authorization
without consulting the signal.

Adds tests/acceptance/passiveObservationCliCancellation.test.ts, which spawns
the real CLI against a stalled loopback socket and interrupts it. On POSIX it
delivers a real OS signal; on Windows it relays an in-process SIGINT/SIGTERM
through a --import hook, because child.kill(signal) force-terminates on
Windows instead of running the handler. All eight commands x {SIGINT, SIGTERM}
now assert terminationSignal === null, exit 130/143, and a
{ code: "cancelled", details: { cleanup: "complete", operation } } envelope.
Adds a `hangOnSourceMap` fixture seam, provider coverage for an interrupted
source-map download, application-boundary coverage for all five browser
commands whose cleanup can outlast an interrupt, and a service test for a
listing abort that lands during file authorization.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@morluto
morluto force-pushed the fix/cli-browser-javascript-cancellation branch from e4b07b8 to b23dd48 Compare October 13, 2026 18:51
@morluto morluto added area: runtime Process capture and runtime observation bug Something isn't working labels Oct 14, 2026
morluto added a commit that referenced this pull request Oct 14, 2026
Own service-worker CDP registrations and retry failed teardown. Admit redaction and network metadata against remaining capture capacity, retain explicit omission reasons, and preserve source URL, redirect ancestry, caller-selected content, and historical capture values. Forward CLI cancellation through provider cleanup.

Reviewed fixes: #2263, #2637, #2767, #2845, #2859, #2863, #2872, #2874, #2876, #2879, #2955, #2957, #2961, #3033.

Validation: 25 current event/network source tests passed; earlier focused browser lanes passed 201 source tests and 176 boundary tests with two skips, plus 35 Python tests. Real browser/Windows lanes were not rerun. Playwright allocation before admission remains unbounded by these retention limits.
@kaoru0822-kitauji kaoru0822-kitauji added the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
Main (f690571) already reports caller cancellation after a provider
returns in BrowserObservationService and JavaScriptRuntimeObservationService,
and forwards CLI signals. Keep main's versions of those services and of
CdpBrowserProvider: the service layer owns the post-result cancellation
check, while a provider-level throw from `finally` would replace genuine
provider failures with cancellation. Keep this PR's CLI/service cancellation
coverage, including the file-check abort case for runtime targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

CI-fix track: the shard 4 and Portable failure (productCatalog build-generated facts) came from main at the time, not this PR. I merged current main and resolved the conflicts (a6ecfe9). Main already has the core of this change in f690571: BrowserObservationService and JavaScriptRuntimeObservationService return AnalysisCancelledError when the caller aborts after the provider returns, and the CLI forwards signals. I kept main's services and dropped the extra throw new AnalysisCancelledError(operation) in withTargetSession's finally. The service layer already owns that check, and throwing from finally would also replace a genuine provider failure with cancellation. For the same reason cdpCleanupCancellation keeps main's provider-level expectation. This PR's coverage stays: the CLI SIGINT/SIGTERM acceptance test, service cancellation, provider lifecycle failures, and the runtime-target file-check abort case. Locally: 440 related tests passed (16 skipped) and check:fast is clean.

@kaoru0822-kitauji kaoru0822-kitauji removed the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
@DeryFerd

Copy link
Copy Markdown
Contributor Author

Thanks — the robustness point is worth pinning, and I checked the current state. At this head the provider does not throw after cleanup: merging main reverted the post-cleanup throw that an earlier commit on the branch had added, so CdpBrowserProvider returns the completed result and these five cases do exercise the result.ok && signal.aborted rechecks — disabling those rechecks in BrowserObservationService fails all five. The underlying concern is right for the merged result, though: current main now carries the post-cleanup cancellation throw in CdpBrowserProvider, so once this branch lands the provider will fail first and these five would pass even without the service rechecks. A service case with a recording provider that aborts and returns ok would keep the rechecks pinned independently, while the transport cases stay as-is for the cleanup window. Happy to add it if that's wanted; noting it as P2 since the production fix is already in main and the branch diff is test-only.

@CassieFox23

Copy link
Copy Markdown
Contributor

Heads up: main covers this in its own way in f690571. The code is in src/cli/browserCommands.ts. The test does not publish targets when cancellation arrives during provider cleanup shows it. Only the tests are left. It is listed on tracker #3582. If this PR still adds something main doesn't have, please say so here and I'll take it off the list. Thanks for the fix!

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

@DeryFerd

Copy link
Copy Markdown
Contributor Author

@CassieFox23 Thanks for the roundup, and for confirming main carries it. To your question: there is still a little here that main doesn't have, and it is all test-side.

The one piece worth keeping is the stub-based service case in src/application/javascript/JavaScriptRuntimeObservationService.test.ts ("reports cancellation instead of targets when the caller aborts during file checks"). It aborts inside listTargets and returns ok, so it pins the listJavaScriptRuntimeTargets recheck on its own instead of relying on the provider to fail first. Main's copy of that file has only the two earlier cases.

tests/fixtures/passiveObservationCancellation.mjs is the other unique piece: it re-emits SIGINT/SIGTERM from inside the CLI so the acceptance test can exercise the guard on Windows, where child.kill(signal) terminates the child instead of running its handler.

The rest overlaps main and can go if you want a smaller diff. tests/acceptance/passiveObservationCliCancellation.test.ts covers the same eight passive commands that webRuntimeCli.test.ts already covers with real signals, exit 130/143 and cancelled with cleanup: complete — main's list is a superset. Main also already has a source-map cancellation test in cdpBrowserProvider.lifecycle_failures.test.ts, and its fetchMock version additionally asserts the abort reason is preserved, which the hangOnSourceMap fixture version here does not. For the five cases in browserObservationServiceCancellation.test.ts, main's provider now throws after cleanup, so once this branch lands they exercise the operation wiring for those five commands rather than the service rechecks themselves — useful, but not the independent pin the stub case above gives.

I left all of it in place because the merge kept it, but I'm happy to trim this down to the two unique pieces, or to close it and hand the stub case to main separately, whichever is easier for you.

@DeryFerd DeryFerd closed this Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants