Repository navigation
feat(compiler): require Strong effect cleanup to release platform resources - #1484
Conversation
…ters as Strong effect setup OCTANE_STRONG_EFFECT_STATE_UPDATE could be bypassed by deferring the update by zero delay or by returning the state tuple from a same-module custom hook. Callbacks that run before the next paint now count as synchronous effect setup: startTransition (imports, aliases, namespaces, optional calls), a useTransition start function, queueMicrotask, .then/.catch/.finally on Promise.resolve(value) or Promise.reject(), setTimeout without a positive delay, and code after awaiting a value that is not a pending promise. requestAnimationFrame, positive-delay timers, and external subscription callbacks remain event-driven. Synchronous calls to local functions now record what they return, so state tuples, updaters, callbacks, and transition starts returned by same-module custom hooks keep their provenance in the caller. Each call gets its own state identity so separate calls never read as one state in effect graphs. The classification lives in a new strong-effects.js policy module. Emitted code and compatibility modules are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…c state updates OCTANE_STRONG_EFFECT_DATA_FETCH only recognized fetch, and any returned cleanup satisfied it, so an imported client, axios, or an empty cleanup silenced the check. Any state update that runs after an await, or in a .then/.catch/.finally callback, of effect-owned work now needs proof that the returned cleanup cancels or ignores it: - the cleanup aborts an AbortController created in the effect whose signal reaches the request (directly, through aliases or destructuring, in an options object, or through a same-module helper parameter), or the update is guarded by that signal's aborted flag; or - the cleanup assigns a let flag declared in the effect, and the update is guarded by that flag after the last await (if tests, early returns, &&/||). Empty, opaque, and unconnected cleanups, component- or module-scoped flags, ref flags, and guards checked before a later await are errors. Async effect callbacks cannot return cleanup and get a message that says so. This replaces the fetch-only continuation tracking in strong-mode.js with guard, flow-segment, and source tracking in strong-effects.js. Deferred constructors and tagged templates in effect-owned work are now followed like calls. Emitted code and compatibility modules are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reading a state getter, a value ref's current, or a reassigned module variable in synchronous effect setup hides that input from dependency inference, so the effect does not re-run when it changes. The common previous-value and first-run ref guards rely on exactly this. Add OCTANE_STRONG_EFFECT_HIDDEN_DEPENDENCY for those reads in effect setup, including synchronous local helpers, zero-delay callbacks, compound updates, destructuring, and getters returned by same-module custom hooks. A value ref is a useRef whose identity is only used for property access, stable aliases, and explicit dependency lists; attaching it with ref=, passing it to a call, component, or hook, storing it in a container, or returning it keeps it readable. Reads in cleanup, deferred callbacks, and useEffectEvent callbacks remain valid. The message points to the render snapshot or useEffectEvent and notes that Octane never double-invokes effects. Emitted code and compatibility modules are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ources Octane has no StrictMode double-invoke to surface leaked listeners, timers, observers, or connections in development, and Strong accepted effects that acquired them without a release. Add OCTANE_STRONG_EFFECT_RESOURCE_LEAK for platform resources acquired in synchronous effect setup that the returned cleanup does not release: - addEventListener on window/document/globalThis, their properties and query results, matchMedia lists, elements held by refs attached to intrinsic elements, and connections created in the effect: released by removeEventListener with the same target, event type, handler identity, and capture flag, or by aborting the AbortController whose signal was passed in the options; - on<event> handler properties on those targets: released by reassigning the property or closing the connection; - setInterval and self-rescheduling setTimeout/requestAnimationFrame loops: released by clearing the stored ID; - Resize/Intersection/Mutation/PerformanceObserver: disconnect() or unobserve(); - WebSocket, EventSource, BroadcastChannel: close(); - geolocation.watchPosition: clearWatch(id). Only platform APIs count: store.subscribe and user objects' addEventListener stay legal, as do one-shot timers and animation frames. Emitted code and compatibility modules are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for all 3 issues found in the latest run.
- ✅ Fixed: Custom-hook shapes compared by identity
- Added shapesEqual to compare returned-array and returned-object shapes structurally by kind and element/property identity, so multi-path custom hooks that return the same bindings in different wrapper objects are correctly merged.
- ✅ Fixed: Helper targets skip leak detection
- Extended platformTarget to follow frameArgument for helper parameters and handle destructured property bindings (path.length > 0), so targets passed through helpers and destructured from platform globals are recognized.
- ✅ Fixed: Global listener methods not recognized
- Added bare addEventListener handling in acquire and bare removeEventListener handling in scan's cleanup detection, both using 'g:window' as the implicit target to match the existing timer global pattern.
Or push these changes by commenting:
@cursor push 5f8135232f
Preview (5f8135232f)
diff --git a/packages/octane/src/compiler/strong-effects.js b/packages/octane/src/compiler/strong-effects.js
--- a/packages/octane/src/compiler/strong-effects.js
+++ b/packages/octane/src/compiler/strong-effects.js
@@ -507,6 +507,13 @@
) {
const key = keyOf(node.arguments?.[0]);
if (key !== null) result.cleared.add(key);
+ } else if (name === 'removeEventListener') {
+ result.removed.push({
+ target: 'g:window',
+ type: eventType(node.arguments?.[0]),
+ handler: keyOf(node.arguments?.[1]),
+ capture: captureOf(node.arguments?.[2]),
+ });
} else if (callee?.type === 'MemberExpression') {
const method = memberName(callee);
const object = keyOf(callee.object);
@@ -638,8 +645,18 @@
if (node.type === 'Identifier') {
const binding = bindingOf(node);
if (binding === null) return EVENT_TARGET_GLOBALS.has(node.name);
+ const argument = frameArgument(binding);
+ if (argument !== null) return platformTarget(argument, depth + 1);
const init = stableInit(binding);
- return init !== null && platformTarget(init, depth + 1);
+ if (init !== null) return platformTarget(init, depth + 1);
+ if (!binding.reassigned) {
+ const info = declarator(binding);
+ if (info !== null && info.path.length !== 0) {
+ const base = unwrap(info.decl.init);
+ return base !== null && platformTarget(base, depth + 1);
+ }
+ }
+ return false;
}
if (node.type === 'MemberExpression') {
const object = unwrap(node.object);
@@ -675,6 +692,18 @@
}
return;
}
+ if (name === 'addEventListener') {
+ record.acquisitions.push({
+ kind: 'listener',
+ node,
+ target: 'g:window',
+ type: eventType(node.arguments?.[0]),
+ handler: keyOf(node.arguments?.[1]),
+ capture: captureOf(node.arguments?.[2]),
+ signal: listenerSignal(node.arguments?.[2]),
+ });
+ return;
+ }
if (callee?.type !== 'MemberExpression') return;
const method = memberName(callee);
if (method === 'addEventListener' && platformTarget(callee.object)) {
diff --git a/packages/octane/src/compiler/strong-mode.js b/packages/octane/src/compiler/strong-mode.js
--- a/packages/octane/src/compiler/strong-mode.js
+++ b/packages/octane/src/compiler/strong-mode.js
@@ -2727,9 +2727,28 @@
return shapeMember(node, scope);
}
+ function shapesEqual(a, b) {
+ if (a === b) return true;
+ if (a == null || b == null || a.kind !== b.kind) return false;
+ if (a.kind === 'returned-array') {
+ return (
+ a.elements.length === b.elements.length &&
+ a.elements.every((element, i) => element === b.elements[i])
+ );
+ }
+ if (a.kind === 'returned-object') {
+ if (a.properties.size !== b.properties.size) return false;
+ for (const [key, value] of a.properties) {
+ if (b.properties.get(key) !== value) return false;
+ }
+ return true;
+ }
+ return false;
+ }
+
function mergeShapes(shapes) {
const [first] = shapes;
- return first != null && shapes.every((shape) => shape === first) ? first : null;
+ return first != null && shapes.every((shape) => shapesEqual(shape, first)) ? first : null;
}
function bindReturnedShape(pattern, shape, bind) {You can send follow-ups to the cloud agent here.
…y awaits Two review findings on the Strong zero-delay and custom-hook checks: - mergeShapes required every return of a custom hook to yield the same shape object, but each `return [value, setValue]` or object literal builds a fresh shape, so a hook returning its tuple on two paths lost updater provenance. Array and object shapes now merge element by element, keeping each value that every path returns. - Zero-delay awaits only matched a direct Promise.resolve/reject call. Sequence, conditional, and logical forms now recurse, and an await result counts as a non-promise, so `await (await null)`, `await (0, Promise.resolve())`, and `await (flag ? Promise.resolve() : null)` stay in effect setup. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… path
Review finding: abort controllers found on one await stayed on the flow for
later awaits that carried no signal, and if/switch visits never restored the
flow, so an abort belonging to one request could count as cleanup for a
different update, including one on an exclusive branch.
Each yield now replaces the abort proof with its own request's controllers,
including a request whose result it reads (`(await fetch(url, { signal })).json()`).
Branches, logical operands, switch cases, try/catch, and loops join their
flows: only controllers shared by every path survive, and a join after any
yield starts a new segment. Loop bodies that yield start from a fresh
segment because a later iteration follows the previous iteration's yield.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies # Conflicts: # packages/octane/src/compiler/strong-effects.js
…ue-ref check Review finding: a ref listed in a parenthesized or cast dependency list (`([ref])`, `[ref] as const`, `[ref] satisfies unknown[]`) counted as an escape, so effect setup could read its current value without OCTANE_STRONG_EFFECT_HIDDEN_DEPENDENCY. The dependency-list check now climbs transparent wrappers to the hook call. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g-effect-resource-leaks # Conflicts: # packages/octane/src/compiler/strong-effects.js
…ts in Strong leak checks
Review findings on OCTANE_STRONG_EFFECT_RESOURCE_LEAK:
- platformTarget only followed const initializers, so a target passed to a
same-module helper (`listen(window, type, fn)`) or a destructured platform
property (`const { body } = document`) was never checked. Helper
parameters now resolve to the visited call's arguments, both when a
resource is acquired and when a cleanup helper releases it, and
destructured properties of platform objects count as platform targets.
- The global addEventListener/removeEventListener functions were ignored, so
a bare addEventListener leak was missed and window.addEventListener paired
with the global removeEventListener was reported. Both now name the
window, as do global on<event> handler properties such as `onresize`.
Ownership keys for timer handles are computed without call frames so they
stay stable across calls.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review finding: an await result counts as settled, so the outer await in `await (null ?? await load())` or `await (true ? await load() : null)` is zero-delay, and the yield belongs to the inner await. alwaysAwaits only inspected the left operand of a logical expression and required both branches of a conditional, so it missed that inner await and a later update was rejected as effect setup. A literal left operand or literal test now selects the operand that always runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies
…g-effect-resource-leaks
… loops normally Review findings on the flow joins added for Strong abort proofs: - A catch handler that always returns or throws no longer joins into the code after the try, so the try block's proof survives. - A switch case ending in continue leaves the enclosing loop and no longer joins the flow after the switch. - A loop test that always yields runs right before every iteration, so its proof is kept instead of starting the body from a fresh segment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies
…g-effect-resource-leaks
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Conditional awaits treated as zero-delay
- Added an AwaitExpression case to settled() that recurses on the argument instead of falling through to nonPromise(), and made ConditionalExpression/LogicalExpression use staticValue to skip unreachable branches, so nested awaits like
await (cond ? await load() : null)are correctly treated as real continuations.
- Added an AwaitExpression case to settled() that recurses on the argument instead of falling through to nonPromise(), and made ConditionalExpression/LogicalExpression use staticValue to skip unreachable branches, so nested awaits like
- ✅ Fixed: Helpers ignore listener type and capture
- Added frameArgument resolution to eventType() and captureOf() so helper parameters resolve to their call-site arguments instead of UNKNOWN, preventing mismatched event types or capture flags from being accepted as valid releases.
Or push these changes by commenting:
@cursor push e8dc4142df
Preview (e8dc4142df)
diff --git a/packages/octane/src/compiler/strong-effects.js b/packages/octane/src/compiler/strong-effects.js
--- a/packages/octane/src/compiler/strong-effects.js
+++ b/packages/octane/src/compiler/strong-effects.js
@@ -341,10 +341,23 @@
switch (node?.type) {
case 'SequenceExpression':
return settled(node.expressions?.at(-1), depth);
- case 'ConditionalExpression':
+ case 'ConditionalExpression': {
+ const test = staticValue(node.test);
+ if (test !== UNKNOWN) return settled(test ? node.consequent : node.alternate, depth);
return settled(node.consequent, depth) && settled(node.alternate, depth);
- case 'LogicalExpression':
- return settled(node.left, depth) && settled(node.right, depth);
+ }
+ case 'LogicalExpression': {
+ if (!settled(node.left, depth)) return false;
+ const left = staticValue(node.left);
+ if (left !== UNKNOWN) {
+ const rightReachable =
+ node.operator === '??' ? left == null : node.operator === '&&' ? Boolean(left) : !left;
+ return !rightReachable || settled(node.right, depth);
+ }
+ return settled(node.right, depth);
+ }
+ case 'AwaitExpression':
+ return settled(node.argument, depth);
case 'Identifier': {
const init = depth < 8 ? stableInitOf(node) : null;
if (init !== null) return settled(init, depth + 1);
@@ -697,14 +710,29 @@
// --- platform resources --------------------------------------------------
- function eventType(expression) {
+ function eventType(expression, depth = 0) {
+ const node = unwrap(expression);
+ if (node?.type === 'Identifier' && depth < 8) {
+ const binding = bindingOf(node);
+ if (binding) {
+ const argument = frameArgument(binding);
+ if (argument !== null) return eventType(argument, depth + 1);
+ }
+ }
const value = staticValue(expression);
return typeof value === 'string' ? value : UNKNOWN;
}
- function captureOf(expression) {
+ function captureOf(expression, depth = 0) {
const node = unwrap(expression);
if (node == null) return false;
+ if (node.type === 'Identifier' && depth < 8) {
+ const binding = bindingOf(node);
+ if (binding) {
+ const argument = frameArgument(binding);
+ if (argument !== null) return captureOf(argument, depth + 1);
+ }
+ }
if (node.type === 'ObjectExpression') {
let capture = false;
for (const property of node.properties ?? []) {You can send follow-ups to the cloud agent here.
… Strong abort proofs
Review findings on the Strong abort-proof flow:
- When a catch handler always exits, the code after the try keeps the try
block's proof, but the finally block also runs after the handler (or a
throw part way through either), so it now starts from the joined flow.
Code after the finally keeps the normal-completion proof unless finally
yields.
- Awaiting or chaining a conditional, sequence, or logical request, such as
`await (fast ? fetch(a, { signal }) : fetch(b, { signal }))`, now keeps
the controllers every possible request carries.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies
…g-effect-resource-leaks
… arguments Review finding: helper parameters resolved to the call's arguments for the listener target and handler, but the event type and capture flag still read the parameter itself, so they were unknown and matched anything. A helper removal with a different event or capture flag therefore counted as a release. Static values now follow helper parameters to the visited call's arguments too. Also pins that `await (flag ? await load() : null)` stays effect setup: when the flag is false only a settled value is awaited, so the update runs before the next paint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Continue treated as a loop exit
- Fixed by adding a continueExits flag to jump targets (false when the loop test always awaits) so continue flows are not recorded as exit edges, and by re-applying the test's continuation after the body to restore signed controllers that the body's unsigned awaits drop.
Or push these changes by commenting:
@cursor push fa4122d046
Preview (fa4122d046)
diff --git a/packages/octane/src/compiler/strong-mode.js b/packages/octane/src/compiler/strong-mode.js
--- a/packages/octane/src/compiler/strong-mode.js
+++ b/packages/octane/src/compiler/strong-mode.js
@@ -3927,9 +3927,9 @@
}
// Only paths that reach the next statement share its flow.
- function enterJumpTarget(loop) {
+ function enterJumpTarget(loop, continueExits = true) {
if (currentEffect === null) return null;
- jumpTargets = { loop, flows: [], next: jumpTargets };
+ jumpTargets = { loop, continueExits, flows: [], next: jumpTargets };
return jumpTargets;
}
@@ -3949,6 +3949,10 @@
const flow = effectPolicy.saveFlow();
for (let target = jumpTargets; target !== null; target = target.next) {
if (node.type === 'ContinueStatement' && !target.loop) continue;
+ if (node.type === 'ContinueStatement' && !target.continueExits) {
+ if (node.label == null) return;
+ continue;
+ }
target.flows.push(flow);
// A labeled jump may leave any enclosing target.
if (node.label == null) return;
@@ -5389,14 +5393,19 @@
}
const before = currentEffect === null ? undefined : effectPolicy.saveFlow();
// A test that always yields runs right before every iteration.
- if (before !== undefined && !alwaysAwaits(node.test)) {
+ const testAlwaysAwaits = before !== undefined && alwaysAwaits(node.test);
+ if (before !== undefined && !testAlwaysAwaits) {
effectPolicy.enterLoopBody([node.body, node.update]);
}
- const forTarget = enterJumpTarget(true);
+ const forTarget = enterJumpTarget(true, !testAlwaysAwaits);
visit(node.body, loop, executionPhase);
visit(node.update, loop, executionPhase);
// The body may not run.
if (before !== undefined) {
+ if (testAlwaysAwaits) {
+ const testNode = unwrap(node.test);
+ if (testNode?.type === 'AwaitExpression') effectPolicy.continuation(testNode.argument);
+ }
effectPolicy.restoreFlow(
exitJumpTarget(forTarget, effectPolicy.joinFlow(before, effectPolicy.saveFlow())),
);
@@ -5500,9 +5509,14 @@
: phase;
const before = currentEffect === null ? undefined : effectPolicy.saveFlow();
if (before !== undefined && !alwaysAwaits(node.test)) effectPolicy.enterLoopBody(node.body);
- const whileTarget = enterJumpTarget(true);
+ const testAlwaysAwaits = before !== undefined && alwaysAwaits(node.test);
+ const whileTarget = enterJumpTarget(true, !testAlwaysAwaits);
visit(node.body, scope, executionPhase);
if (before !== undefined) {
+ if (testAlwaysAwaits) {
+ const testNode = unwrap(node.test);
+ if (testNode?.type === 'AwaitExpression') effectPolicy.continuation(testNode.argument);
+ }
effectPolicy.restoreFlow(
exitJumpTarget(whileTarget, effectPolicy.joinFlow(before, effectPolicy.saveFlow())),
);
@@ -5511,7 +5525,7 @@
}
case 'DoWhileStatement': {
if (currentEffect !== null) effectPolicy.enterLoopBody([node.body, node.test]);
- const doTarget = enterJumpTarget(true);
+ const doTarget = enterJumpTarget(true, !alwaysAwaits(node.test));
visit(node.body, scope, phase);
const executionPhase =
currentFunctionIsAsync &&
diff --git a/packages/octane/tests/compiler/strong-effects.test.ts b/packages/octane/tests/compiler/strong-effects.test.ts
--- a/packages/octane/tests/compiler/strong-effects.test.ts
+++ b/packages/octane/tests/compiler/strong-effects.test.ts
@@ -299,6 +299,14 @@
],
['a for test', `for (; await fetch('/a', { signal }); ) { setData(1); }`],
[
+ 'a while test with continue after an unsigned request',
+ `while (await fetch('/a', { signal })) { await api.get(props.id); if (props.skip) continue; } setData(1);`,
+ ],
+ [
+ 'a for test with continue after an unsigned request',
+ `for (; await fetch('/a', { signal }); ) { await api.get(props.id); if (props.skip) continue; } setData(1);`,
+ ],
+ [
'a switch case that breaks inside a branch after a signed request',
`switch (props.mode) { case 'a': await fetch('/a', { signal }); if (props.fast) break; await fetch('/b', { signal }); break; default: await fetch('/c', { signal }); } setData(1);`,
],You can send follow-ups to the cloud agent here.
|
Bugbot Autofix prepared fixes for both issues found in the latest run.
Or push these changes by commenting: Preview (d31f7075e8)diff --git a/packages/octane/src/compiler/strong-effects.js b/packages/octane/src/compiler/strong-effects.js
--- a/packages/octane/src/compiler/strong-effects.js
+++ b/packages/octane/src/compiler/strong-effects.js
@@ -962,9 +962,17 @@
// A timer callback that schedules itself again is an interval.
function rescheduleKeys(node, name) {
const callback = functionOf(node.arguments?.[0]);
+ if (callback === null) return null;
const self = unwrap(node.arguments?.[0]);
- if (callback === null || self?.type !== 'Identifier') return null;
- const binding = bindingOf(self);
+ let binding;
+ if (self?.type === 'Identifier') {
+ binding = bindingOf(self);
+ } else if (FUNCTIONS.has(self?.type) && self.id?.type === 'Identifier') {
+ const fnScope = analysis.functionScopes.get(callback);
+ binding = fnScope ? lookup(fnScope, self.id.name) : null;
+ } else {
+ return null;
+ }
const keys = [];
const visit = (value) => {
if (value == null || typeof value !== 'object') return;
@@ -1059,6 +1067,18 @@
owners: new WeakMap(),
};
const { roots, aliases, declarations, owners } = references;
+ const setOwner = (expression, key) => {
+ const node = unwrap(expression);
+ if (node == null) return;
+ owners.set(node, key);
+ if (node.type === 'ConditionalExpression') {
+ setOwner(node.consequent, key);
+ setOwner(node.alternate, key);
+ } else if (node.type === 'LogicalExpression') {
+ setOwner(node.left, key);
+ setOwner(node.right, key);
+ }
+ };
const names = new Set();
for (const { decl, bindings } of declarators) {
const init = unwrap(decl.init);
@@ -1071,7 +1091,7 @@
}
}
if (decl.id?.type === 'Identifier' && binding && init != null) {
- owners.set(init, `b${binding.id}`);
+ setOwner(init, `b${binding.id}`);
}
}
// Stable aliases share their root's classification.
@@ -1109,7 +1129,7 @@
}
if (node.type === 'AssignmentExpression' && node.operator === '=') {
const key = keyOf(node.left);
- if (key !== null) owners.set(unwrap(node.right), key);
+ if (key !== null) setOwner(node.right, key);
}
if (node.type === 'Identifier' && names.has(node.name)) classify(node, parents);
parents.push(node);
diff --git a/packages/octane/tests/compiler/strong-effects.test.ts b/packages/octane/tests/compiler/strong-effects.test.ts
--- a/packages/octane/tests/compiler/strong-effects.test.ts
+++ b/packages/octane/tests/compiler/strong-effects.test.ts
@@ -1576,6 +1576,14 @@
`useEffect(() => { const tick = () => { setWidth((value) => value + 1); setTimeout(tick, 1000); }; setTimeout(tick, 1000); });`,
],
[
+ 'a named function expression timeout loop',
+ `useEffect(() => { setTimeout(function tick() { setWidth((value) => value + 1); setTimeout(tick, 1000); }, 1000); });`,
+ ],
+ [
+ 'a named function expression animation frame loop',
+ `useEffect(() => { requestAnimationFrame(function loop() { setWidth((value) => value + 1); requestAnimationFrame(loop); }); });`,
+ ],
+ [
'a timeout loop that loses its ID',
`useEffect(() => { let id = 0; const tick = () => { setWidth((value) => value + 1); setTimeout(tick, 1000); }; id = setTimeout(tick, 1000); return () => clearTimeout(id); });`,
],
@@ -1584,6 +1592,10 @@
`useEffect(() => { function loop() { setWidth((value) => value + 1); requestAnimationFrame(loop); } requestAnimationFrame(loop); });`,
],
[
+ 'a conditional interval without cleanup',
+ `useEffect(() => { const id = props.enabled ? setInterval(() => setWidth(1), 1000) : null; });`,
+ ],
+ [
'a chained ResizeObserver',
`useEffect(() => { new ResizeObserver(([entry]) => setWidth(entry.contentRect.height)).observe(element.current); });`,
],
@@ -1790,10 +1802,22 @@
`useEffect(() => { let id = 0; const tick = () => { setWidth((value) => value + 1); id = setTimeout(tick, 1000); }; id = setTimeout(tick, 1000); return () => clearTimeout(id); });`,
],
[
+ 'a cancelled named function expression timeout loop',
+ `useEffect(() => { let id = 0; id = setTimeout(function tick() { setWidth((value) => value + 1); id = setTimeout(tick, 1000); }, 1000); return () => clearTimeout(id); });`,
+ ],
+ [
'a cancelled animation loop',
`useEffect(() => { let frame = 0; function loop() { setWidth((value) => value + 1); frame = requestAnimationFrame(loop); } frame = requestAnimationFrame(loop); return () => cancelAnimationFrame(frame); });`,
],
[
+ 'a conditional interval with cleanup',
+ `useEffect(() => { const id = props.enabled ? setInterval(() => setWidth(1), 1000) : null; return () => clearInterval(id); });`,
+ ],
+ [
+ 'a logical interval with cleanup',
+ `useEffect(() => { const id = props.enabled && setInterval(() => setWidth(1), 1000); return () => clearInterval(id); });`,
+ ],
+ [
'a disconnected observer',
`useEffect(() => { const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.height)); observer.observe(element.current); return () => observer.disconnect(); });`,
],You can send follow-ups to the cloud agent here. |
`({ current } = ref);` reads the ref like `const { current } = ref`,
so it no longer counts as an escape and is reported in effect setup.
An assignment whose value is used still shares the ref.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g-effect-resource-leaks
- `setTimeout(function tick() { setTimeout(tick, ms); }, ms)` reschedules
through the function's own name, so it is checked like a stored loop.
- A timer stored through `?:`, `&&`/`||`, or a sequence keeps its
owner, so `clearInterval(id)` releases `enabled ? setInterval(…) : null`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A `continue` reaches the loop's update and test rather than leaving the loop, so its flow joins the exit only when the test (or a for update) does not await. A test that always awaits runs again before every normal exit, so the loop exits with that test's flow plus any breaks. Labeled jumps now go to the loop or switch they name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies
…g-effect-resource-leaks
A labeled `continue outer` or `break outer` skips the switches and loops
between it and its label, so it no longer joins the flow after them. A
labeled block is now a jump target too, so `break done` joins the flow
after `done: { … }`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ct-hidden-dependencies
…g-effect-resource-leaks
#1482 landed on main as a squash of the branch this one already contains, so every conflict resolves to this branch's side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
#1482 landed on main as a squash of the branch this one already contains, so every conflict resolves to this branch's side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Conditional platform targets skip leak check
- Added ConditionalExpression/LogicalExpression handling to platformTarget via someResult, so conditional platform targets like
enabled ? window : documentare now recognized and their addEventListener calls are tracked for cleanup.
- Added ConditionalExpression/LogicalExpression handling to platformTarget via someResult, so conditional platform targets like
- ✅ Fixed: Wrapped host refs miss leak check
- Added ConditionalExpression/LogicalExpression cases to classify for ref attributes and fixed the ArrayExpression case to walk through transparent TS wrappers to find JSXExpressionContainer, so
ref={enabled ? element : null}andref={[element] as const}correctly mark refs as host.
- Added ConditionalExpression/LogicalExpression cases to classify for ref attributes and fixed the ArrayExpression case to walk through transparent TS wrappers to find JSXExpressionContainer, so
Or push these changes by commenting:
@cursor push e6fbed9bd7
Preview (e6fbed9bd7)
diff --git a/packages/octane/src/compiler/strong-effects.js b/packages/octane/src/compiler/strong-effects.js
--- a/packages/octane/src/compiler/strong-effects.js
+++ b/packages/octane/src/compiler/strong-effects.js
@@ -895,6 +895,9 @@
const callee = unwrap(node.callee);
return callee?.type === 'MemberExpression' && platformTarget(callee.object, depth + 1);
}
+ if (node.type === 'ConditionalExpression' || node.type === 'LogicalExpression') {
+ return someResult(node, platformTarget, depth);
+ }
return platformConstructor(node) !== null;
}
@@ -1201,6 +1204,28 @@
case 'BreakStatement':
case 'ContinueStatement':
return;
+ case 'ConditionalExpression':
+ case 'LogicalExpression': {
+ let at = index - 1;
+ while (
+ at >= 0 &&
+ (TRANSPARENT.has(parents[at].type) ||
+ parents[at].type === 'ConditionalExpression' ||
+ parents[at].type === 'LogicalExpression')
+ )
+ at--;
+ if (parents[at]?.type === 'JSXExpressionContainer') {
+ const attribute = parents[at - 1];
+ const element = parents[at - 2];
+ if (attribute?.type === 'JSXAttribute' && attribute.name?.name === 'ref') {
+ const name = element?.type === 'JSXOpeningElement' ? element.name : null;
+ if (name?.type === 'JSXIdentifier' && /^[a-z]/.test(name.name)) {
+ references.host.add(root);
+ }
+ }
+ }
+ break;
+ }
case 'ArrayExpression': {
// A dependency list is not a use of the ref's identity, even when it
// is parenthesized or cast.
@@ -1216,9 +1241,14 @@
let attribute = parents[index - 1];
let element = parents[index - 2];
if (parent.type === 'ArrayExpression') {
- attribute = parents[index - 2];
- element = parents[index - 3];
- if (parents[index - 1]?.type !== 'JSXExpressionContainer') attribute = null;
+ let at = index - 1;
+ while (at >= 0 && TRANSPARENT.has(parents[at].type)) at--;
+ if (parents[at]?.type === 'JSXExpressionContainer') {
+ attribute = parents[at - 1];
+ element = parents[at - 2];
+ } else {
+ attribute = null;
+ }
}
if (attribute?.type === 'JSXAttribute' && attribute.name?.name === 'ref') {
const name = element?.type === 'JSXOpeningElement' ? element.name : null;
diff --git a/packages/octane/tests/compiler/strong-effects.test.ts b/packages/octane/tests/compiler/strong-effects.test.ts
--- a/packages/octane/tests/compiler/strong-effects.test.ts
+++ b/packages/octane/tests/compiler/strong-effects.test.ts
@@ -1477,6 +1477,21 @@
'<div ref={[element, props.forwarded]} />',
],
[
+ 'a conditional element ref',
+ `const element = useRef(null); useEffect(() => { props.log(element.current); });`,
+ '<div ref={props.enabled ? element : null} />',
+ ],
+ [
+ 'a logical element ref',
+ `const element = useRef(null); useEffect(() => { props.log(element.current); });`,
+ '<div ref={props.enabled && element} />',
+ ],
+ [
+ 'a TS-cast array element ref',
+ `const element = useRef(null); useEffect(() => { props.log(element.current); });`,
+ '<div ref={[element] as const} />',
+ ],
+ [
'a ref passed to a component',
`const element = useRef(null); useEffect(() => { props.log(element.current); });`,
'<props.Input inputRef={element} />',
@@ -1751,6 +1766,14 @@
`useEffect(() => { const id = props.enabled ? setInterval(() => setWidth(1), 1000) : null; });`,
],
[
+ 'a conditional platform target listener',
+ `useEffect(() => { const target = props.narrow ? document : window; target.addEventListener('resize', () => setWidth(1)); });`,
+ ],
+ [
+ 'a logical platform target listener',
+ `useEffect(() => { const target = props.target || document; target.addEventListener('resize', () => setWidth(1)); });`,
+ ],
+ [
'a stored helper remover for another handler',
`function subscribe(handler, other) { window.addEventListener('resize', handler); return () => window.removeEventListener('resize', other); } useEffect(() => { const first = () => setWidth(1); const second = () => setWidth(2); const stop = subscribe(first, second); return stop; });`,
],
@@ -1767,6 +1790,24 @@
});
it.each([
+ ['a conditional ref', `<div ref={props.enabled ? element : null} />`],
+ ['a logical ref', `<div ref={props.enabled && element} />`],
+ ['a TS-cast array ref', `<div ref={[element] as const} />`],
+ ])('rejects an element listener on %s without release', (_label, output) => {
+ rejects(
+ `
+import { useState, useEffect, useRef } from 'octane';
+export function App(props) @{
+ const [width, setWidth] = useState(0);
+ const element = useRef(null);
+ useEffect(() => { element.current.addEventListener('scroll', () => setWidth(1)); });
+ ${output}
+}`,
+ LEAK,
+ );
+ });
+
+ it.each([
[
'a removed listener',
`useEffect(() => { const onResize = () => setWidth(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); });`,
@@ -1949,6 +1990,10 @@
'a reset global handler property',
`useEffect(() => { onresize = () => setWidth(1); return () => { window.onresize = null; }; });`,
],
+ [
+ 'a removed conditional platform target listener',
+ `useEffect(() => { const target = props.narrow ? document : window; const onResize = () => setWidth(1); target.addEventListener('resize', onResize); return () => target.removeEventListener('resize', onResize); });`,
+ ],
])('accepts %s', (_label, setup) => {
accepts(app(setup));
});You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit cff777a. Configure here.
- A listener target that may be either of two values, as in `enabled ? window : document`, is a platform target when either is. - A ref given to an intrinsic element through `?:`, `&&`/`||`, an array, or a cast is an element ref, so its listeners need release. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dden-dependencies
…resource-leaks Both branches merged main's #1482 squash separately, so the merge had two bases. This branch already contains #1483's changes, so conflicts keep this side; the only new content is main's tiptap fix (#1502). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dden-dependencies
…g-effect-resource-leaks
Benchmark report🟢 No size increases and no timing regressions outside noise. Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)No changes across 45 measured values. Public-import reachability bundles (bytes)No changes across 105 measured values. |
#1484 landed on main as a squash of a branch that contained this one, so main already has these changes; every conflict resolves to main's side. Co-Authored-By: Claude Opus 5.5 <[email protected]>


Summary
Last of four stacked Strong effect PRs (tracking issue #1027). #1481 and #1482 have landed on main (as #1482); this branch also contains #1483, so merge that first. The change for this PR is the top commit, "require Strong effect cleanup to release platform resources".
Octane has no StrictMode double-invoke to surface leaks in development. Effects that add a
windowlistener, start asetInterval, or observe with a chainednew ResizeObserver(cb).observe(el)compiled under Strong with no release.What changed. A new code,
OCTANE_STRONG_EFFECT_RESOURCE_LEAK, reports platform resources acquired in synchronous effect setup that the returned cleanup does not release:addEventListeneronwindow/document/globalThis, their properties and query results,matchMedialists, elements held by refs attached to intrinsic elements, and connections created in the effectremoveEventListenerwith the same target, event type, handler identity, and capture flag, orabort()of theAbortControllerwhosesignalwas passed in the optionson<event>handler properties on those targetsnull, or closing the connectionsetInterval, andsetTimeout/requestAnimationFramecallbacks that reschedule themselvesclearInterval/clearTimeout/cancelAnimationFramewith the stored ID; each reschedule must store to the same IDResizeObserver,IntersectionObserver,MutationObserver,PerformanceObserverdisconnect()orunobserve()WebSocket,EventSource,BroadcastChannelclose()navigator.geolocation.watchPositionnavigator.geolocation.clearWatch(id)store.subscribeandaddEventListeneron user objects stay legal, as do one-shot timers and animation frames.const el = ref.currentnamesref.current, andwindow.xnames the globalx.The two extra rows beyond the task's table (handler properties and self-rescheduling timers) are the most likely rewrites once
addEventListenerandsetIntervalare rejected.Validation
pnpm format:check: repo-wide, run on this exact content (the complete stack).pnpm typecheck: full run on the complete stack.pnpm typecheck:fileson the changed tests shows only the TS7016 errorsmainalready has.pnpm test: run on the complete stack through the four CI shards. All passed except the knownhmr.test.tsload timeout, which passes in isolation (details in fix(compiler): count zero-delay effect callbacks and custom-hook updaters as Strong effect setup #1481).{ once: true }, handler properties, a lost timer ID, chained observers, async callbacks, and zero-delay callbacks..tsx, plain.tshooks, and per-resource messages.pnpm syncproduced no changes.Risk / follow-ups
await, or in timer or subscription callbacks are not checked.useLayoutEffectwithout DOM access) was dropped by decision. Opaque calls such asonLayout(),editor.focus(), or an importedmeasure()legitimately do layout work, so the check cannot be precise.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Static analysis only, but it newly rejects or requires cleanup for common effect patterns; bounded proofs may miss releases in imported helpers or post-await work while still blocking valid-looking code elsewhere.
Overview
Adds two Strong-mode effect diagnostics (patch releases for
octaneand@octanejs/mcp-server), with no change to emitted code for compatibility modules.OCTANE_STRONG_EFFECT_HIDDEN_DEPENDENCYflags synchronous effect setup that reads values dependency inference cannot track: state getters,currenton “value” refs (refs only used for property access, not attached viaref=or passed onward), and reassigned modulelet/var. Attached DOM refs, cleanup/deferred/useEffectEventreads, and render snapshots stay allowed.OCTANE_STRONG_EFFECT_RESOURCE_LEAKrecords platform resources acquired during synchronous setup—listeners on browser targets/matchMedia/attached elements,on*handler properties, intervals and self-rescheduling timers, observers,WebSocket/EventSource/BroadcastChannel, geolocation watches—and requires a matching release in the returned cleanup (removeEventListenerwith matched identity/capture, abortedAbortControllersignals, clears,disconnect/close/clearWatch). Usersubscribe/addEventListeneron custom objects and one-shot timers are exempt.Implementation lives mainly in
strong-effects.js(ref classification walk, acquisition tracking, richer cleanup scanning through same-module helpers) andstrong-mode.jswiring during effect visits. Docs, MCP skills, and large compiler test suites document and lock behavior.Reviewed by Cursor Bugbot for commit 92ec717. Bugbot is set up for automated code reviews on this repo. Configure here.