Repository navigation
feat: enforce Strong template locality for hooks and events - #963
Conversation
trueadm
left a comment
There was a problem hiding this comment.
Reviewed at head 6034c9129. I read the pass end to end, ran the new suite locally (687/687 pass), and pushed roughly 80 additional programs through compile() and compileToVolarMappings() to probe shapes the suite does not cover. The scope modelling is careful and the tests are broad, but I do not think this should land in its current form. Details are inline; the summary is here.
1. The rule infers lifetime from syntax, and the fix it prescribes changes behaviour
Every arm except a nested @{} block has its own hook lifetime: state in an @if arm resets when the arm unmounts, state in a keyed @for row is per row, and an effect moved into an arm stops running while the arm is hidden. "Every use is inside one arm" is not evidence that the author wants that lifetime. It is usually the opposite, and following the diagnostic on ordinary code breaks it:
// flagged: "Move useState into the @for row at line 6"
const [selected, setSelected] = useState(null);
<ul>@for (const item of items; key item.id) {
<li class={item.id === selected ? 'on' : ''} onClick={() => setSelected(item.id)}>{item.name as string}</li>
}</ul>Moved into the row as instructed, each row owns its own selected. I mounted both forms and clicked row a then row b: the parent form renders on off off then off on off; the row form renders on off off then on on off. The PR's own headline example has the same problem: Search with query moved into @if (open) loses the draft on close and reopen. Other confirmed instances: a setInterval effect whose display is behind @if, a retry counter read only in @catch (reset tears the catch scope down, so it is always 0), a useRef(new Map()) roving-focus registry read only in rows, a hoisted useMemo(() => new Intl.NumberFormat(...)) used by N rows becoming N formatters, and a list-level useReducer filter read only in rows.
There is no opt-out. The documented remedy ("keep a parent template consumer") means adding a dummy read; void selected; silences the error with no code change, and wrapping the hook in a local custom hook bypasses it entirely. A rule that valid code has to route around is exactly the app-workaround pattern the repo rules say not to ship.
The nested @{} case is different: same lifetime, narrower update scope, so there the check is a sound "move it closer" hint. My recommendation is to keep the hard error for nested @{} blocks only, and either drop the lifetime-changing arms (@if, @for, @switch, @try and their secondary arms) or emit a warning that states the lifetime consequence. The handler rule has no runtime effect at all, so I would make it a warning or an editor suggestion.
2. Confirmed defects in the analysis (repros inline)
@else,@empty,@pendingand@catchdiagnostics report the@if/@for/@tryline rather than the arm's line;@else ifarms are labelled@if arm; the@finallybranch is unreachable.- Any closure whose body is JSX (
items.map((x) => <li>{count}</li>), render props,useMemo(() => <jsx/>)) becomes a parentless "component" region, so uses inside it are dropped. Block-bodied helpers that return JSX throughif/ternary are treated the opposite way and flagged "and its helper renderItem". BecauseownsTemplatereadsbody.typewithoutunwrap, a Prettier-parenthesised arrow body errors in Volar but passes the build. import.metaandnew.targetare walked as identifier uses of bindings namedmeta/target;AccessorProperty(build parser) andPropertyDefinition{accessor}(Volar parser) disagree the same way.predeclareNestedVarsdoes not stop atJSXCodeBlock, so avarinside a nested@{}shadows the enclosing arm even though the block compiles to its own function.useEffectinside a local custom-hook closure is registered as a component-level effect; the diagnostic points inside the closure and fires even when the hook is called from the arm.- Two silent bypasses of the rule's own model:
onClick={() => f()}is never flagged whereonClick={f}is, and an effect that reads state through a helper (useEffect(() => observe(read()), [read])) never becomes a dependency. useMemo(() => count * 2)in root with the memo used in an arm produces a two-round cascade: "Move useMemo", then after moving, "Move useState".useFormState(the exported alias ofuseActionState) is missing from the hook set; TSenum/namespaceinitializers are skipped so a read there is invisible; closures declared inside a handler are listed as separate helpers to move; two dependencies in sibling arms block the effect instead of climbing to their common ancestor.
3. Compile cost
The pass forces the lazy collectReassignedBindings full scope build for almost every strong module (resolve() on every function name, isReassigned on every const f = () =>), which the existing pass avoided. This runs on every Volar keystroke.
| module | before | after |
|---|---|---|
| small counter, one handler | 0.004 ms | 0.015 ms |
| 33 KB, 200 useState x 50 arms | 0.37 ms | 1.87 ms (1.19 ms is the forced build) |
| 300 chained effects | 0.4 ms | 9.5 ms (301 iterations, 90k useRegions calls) |
| 600 chained effects | 0.6 ms | 34 ms |
The fixpoint recomputes every owner on every iteration while carrying one effect per iteration, so it is quadratic in effect chains. The +4.5% in the PR body was measured on an earlier tree; there is no number for this head.
4. Docs, changeset, CI
docs/tsrx-basics.mdsays the placement checks apply only to opted-in modules, butstrong: truein the Vite plugin applies them to every application module. That is an app-wide breaking change under apatchchangeset that does not say previously valid modules now fail; the changeset's "Allow named handlers..." describes a relaxation relative to this PR's first commit, not to anything released.- The "Label" example (and the test that pins it) uses a bare
{label};useState('ready')is not a string proof, so it lowers throughchildTextHoleUpdateinstead of the text path. The authoring rule asks for{label as string}. - The Strong-mode code lists in
website/src/content/docs/build-tools.mdxandwebsite/public/llms.txtstill enumerate eight codes. - The apt change is unrelated to this feature and belongs in its own PR. The second
sedalso rewrites every mirror host toarchive.ubuntu.com(contrary to the script's comment) and turnsports.ubuntu.com/ubuntu-portsinto a nonexistent path. The failed run was a Canonical port-80 outage that HTTPS to the same hosts would not have fixed. - The branch is behind
mainby six commits, two of which touchcompile.jsemission. It needs a merge,pnpm sync, and a fresh green run before it is ready.
Suggested path
- Scope the hard error to nested
@{}blocks; decide separately whether arm placement is a warning at all. - Fix the region node,
ownsTemplate,MetaProperty,JSXCodeBlockvar, and effect-via-helper issues, and add the repros above as tests. - Stop forcing
collectReassignedBindings(scope.bindings.getfor the function-name lookup, drop theconstreassignment check) and make the fixpoint incremental. - Split the CI change out, fix the docs/changeset/website lists, rebase, and re-measure on the final head.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Bugbot Autofix is ON, but it could not run because the branch was deleted or merged before autofix could start.
Reviewed by Cursor Bugbot for commit c9e12b1. Configure here.
trueadm
left a comment
There was a problem hiding this comment.
Re-reviewed at head 9dae2a1fb. Every point from my earlier review is addressed, and I re-verified the fixes on this head rather than taking the replies on trust.
Design. canMoveInto now only climbs through same-lifetime regions, so a hook can be asked to move only into a nested @{} block, never into an @if/@switch/@try arm or a keyed @for row. I re-ran the cases that were wrong before: list-level selection state read only in rows, the timer effect behind @if, the draft that must survive @if (open) closing, the @catch retry counter, a subscription hook shown conditionally, and a hoisted memo used by rows. All compile clean now. The nested-block cases that should still error do (the docs Counter example, a hook declared in an arm and used only in a block inside that arm), and a root hook used only in a block inside an @if arm is correctly left alone.
Bugs. Confirmed fixed by probe, in both compile() (client and server) and compileToVolarMappings(): .map callbacks and parenthesised arrow bodies inside a block now count as uses and the editor agrees with the build; import.meta and accessor fields no longer count as identifier uses; a var in a nested block no longer shadows the parent; state read by an effect through a helper is a dependency; onClick={() => f()} is diagnosed like onClick={f}; useMemo reading state reports both hooks in one round; useFormState is recognised; TS enum initializers are visited; effects inside a local custom-hook closure are attributed through the helper; the dead @finally branch is gone.
Cost. The pass is gated on the main visitor actually meeting a nested JSXCodeBlock (component @{} bodies go through visitFunction, so ordinary modules skip it), isReassigned is only consulted for candidate function moves, and the fixpoint is replaced by one connected-components traversal.
Process. The apt script and the five workflow steps are gone and ci.yml matches main; the Label example uses {label as string}; the website and llms.txt code lists include both new codes; the changeset now describes the additive errors and the strong: true scope; the branch is current with main and CI is green on this head. The new suite passes locally (714).
One note, not a blocker: the nested-block rule is still a hard error, and it will convert a render-only @{ … } block that was written as transparent grouping into a real child scope once the author complies. The docs now say so, and the lifetime is unchanged, so that is a reasonable call. Approving.

Summary
@{…}block owns their use.<button {onClick} />.Why
@{…}lets component setup live beside the JSX that consumes it. Strong mode can identify a sole nested block without rewriting valid output. An@ifarm, keyed@forrow,@switchcase, or@tryarm has a different lifetime, so this rule does not force a parent hook into one of those scopes.Examples
Each snippet is a complete
.tsrxmodule."use strong"opts in per file;compiler: { strong: true }inoctane.config.tsapplies to application modules. The failing examples report compiler and editor diagnostics; the passing examples compile for client and server output.State and effect used by one nested block
Fails:
OCTANE_STRONG_HOOK_LOCALITYpoints to both hook calls and names the nested@{…}block.Passes: keep the hooks and the named handler beside their button.
Named handler used by a nested event
Fails:
OCTANE_STRONG_EVENT_HANDLER_LOCALITYpoints toonClickand names the block containing its sole event.Passes: declare the handler immediately before that button. An inline
onClick={() => save()}also passes.Handler moves while shared state stays in its parent
Fails: the callback belongs next to its event, while
countis also consumed by the parent output and remains there.Passes: move only the handler into the nested block.
Direct JSX and conditional JSX already pass
The direct JSX form needs no extra block. The cast marks
labelas text in.tsrx:State owned by the parent also stays there when an
@ifarm is hidden and shown again:Changes
@{…}block in a Strong-mode module.mainand remove the unrelated CI apt-mirror edits from this PR.Validation
pnpm syncpassed; the eight PR examples produced the stated client, server, and editor results.main: on the final source, 300 chained effects added 3.6% to full compile and 6.2% to editor analysis; nested and ordinary controls varied by at most 1.2% in full compile/editor time. A prior 600-effect run added about 4–5%. The emitted JavaScript for valid cases was byte-identical.9dae2a1fb: all 26 jobs succeeded, including Node 24 test shards, browser integration, lint, typecheck, and package/provenance checks. All 28 PR checks are successful;[code]smithis skipped.Risk
These are new hard errors for previously valid Strong-mode application code, including applications enabled with
strong: true. The change is scoped to provable local bindings with one nested block owner; custom hook implementations and unknown callback flows remain opaque. Moving a hook into a nested block gives it that block's lifetime. Parent state in conditional arms and keyed rows retains its current lifetime.Provenance
agent-authored)Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Adds new compile-time failures for Strong-mode application code (including app-wide
strong: true), though checks are opt-in, bounded, and do not rewrite or change output for already-valid modules.Overview
Strong mode now rejects mis-placed setup in opted-in modules (
"use strong"orcompiler: { strong: true }) with two new diagnostics:OCTANE_STRONG_HOOK_LOCALITYfor built-in hook values (and effects that depend on them) declared outside the sole nested@{…}block that consumes them, andOCTANE_STRONG_EVENT_HANDLER_LOCALITYfor named callbacks used on nativeonXattributes outside the deeper block that owns that event.The compiler adds a separate
strongLocalityDiagnosticspass instrong-mode.js(gated on an actual nested@{…}in the module) that walks template regions—including@if, keyed@for,@switch, and@tryarms—groups hook/helper/effect ownership, and reports authored locations with a suggested target block line. Parent-scope hooks for conditional arms, shared state across sibling blocks, inline handlers, shorthand{onClick}, and imported/forwarded callbacks stay valid; valid modules still emit unchanged code.Documentation and
llms.txtdescribe the rules and examples; a largestrong-mode.test.tssuite covers diagnostics, edge cases, and client/server/Volar parity.Reviewed by Cursor Bugbot for commit 9dae2a1. Bugbot is set up for automated code reviews on this repo. Configure here.