Skip to content

feat: enforce Strong template locality for hooks and events - #963

Merged
trueadm merged 15 commits into
octanejs:mainfrom
openai-oss-forks:feat/strong-mode-local-hooks
Sep 5, 2026
Merged

trueadm merged 15 commits into
octanejs:mainfrom
openai-oss-forks:feat/strong-mode-local-hooks

Conversation

@domgan-oai

@domgan-oai domgan-oai commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Enforce local placement for built-in hook values, their dependent effects, and named native event handlers in Strong-mode modules when one deeper nested @{…} block owns their use.
  • Keep parent hooks in their parent scope when they serve a conditional arm, keyed row, or more than one nested block. A named handler may sit beside the JSX event in its own block, including shorthand <button {onClick} />.
  • Report the declaration's source location and the owning block's line with a concrete move suggestion in client, server, and editor diagnostics.

Why

@{…} lets component setup live beside the JSX that consumes it. Strong mode can identify a sole nested block without rewriting valid output. An @if arm, keyed @for row, @switch case, or @try arm has a different lifetime, so this rule does not force a parent hook into one of those scopes.

Examples

Each snippet is a complete .tsrx module. "use strong" opts in per file; compiler: { strong: true } in octane.config.ts applies 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_LOCALITY points to both hook calls and names the nested @{…} block.

"use strong";

import { useEffect, useState } from 'octane';

export function Counter({ observe }) @{
	const [count, setCount] = useState(0);
	useEffect(() => observe(count), [count]);
	<div>@{
		const onClick = () => setCount(count + 1);
		<button {onClick}>{count as string}</button>
	}</div>
}

Passes: keep the hooks and the named handler beside their button.

"use strong";

import { useEffect, useState } from 'octane';

export function Counter({ observe }) @{
	<div>@{
		const [count, setCount] = useState(0);
		useEffect(() => observe(count), [count]);
		const onClick = () => setCount(count + 1);
		<button {onClick}>{count as string}</button>
	}</div>
}

Named handler used by a nested event

Fails: OCTANE_STRONG_EVENT_HANDLER_LOCALITY points to onClick and names the block containing its sole event.

"use strong";

export function Save({ save }) @{
	const onClick = () => save();
	<div>@{ <button {onClick}>Save</button> }</div>
}

Passes: declare the handler immediately before that button. An inline onClick={() => save()} also passes.

"use strong";

export function Save({ save }) @{
	<div>@{
		const onClick = () => save();
		<button {onClick}>Save</button>
	}</div>
}

Handler moves while shared state stays in its parent

Fails: the callback belongs next to its event, while count is also consumed by the parent output and remains there.

"use strong";

import { useState } from 'octane';

export function Count() @{
	const [count, setCount] = useState(0);
	const onClick = () => setCount(count + 1);
	<div><output>{count as string}</output>@{ <button {onClick}>+</button> }</div>
}

Passes: move only the handler into the nested block.

"use strong";

import { useState } from 'octane';

export function Count() @{
	const [count, setCount] = useState(0);
	<div><output>{count as string}</output>@{
		const onClick = () => setCount(count + 1);
		<button {onClick}>+</button>
	}</div>
}

Direct JSX and conditional JSX already pass

The direct JSX form needs no extra block. The cast marks label as text in .tsrx:

"use strong";

import { useState } from 'octane';

export function Label() @{
	const [label] = useState('ready');
	<div><span>{label as string}</span></div>
}

State owned by the parent also stays there when an @if arm is hidden and shown again:

"use strong";

import { useState } from 'octane';

export function Search({ open }) @{
	const [query, setQuery] = useState('');
	<section>@if (open) {
		<input value={query} onInput={(event) => setQuery(event.currentTarget.value)} />
	}</section>
}

Changes

  • Analyze authored scopes, live helper captures, derived hook values, effect dependencies, and direct or inline native event references. Dead helpers no longer mask separate hook owners; errors name the target block and explain when a stale helper must be removed.
  • Respect nested component boundaries, lexical shadowing, JSX-returning helper closures, parsed AST immutability, and the client/server/editor parser variants. Keep the analysis gated on an actual nested @{…} block in a Strong-mode module.
  • Add targeted tests for the review reproductions, diagnostic offsets and messages, valid parent ownership, helper chains, and documentation examples. Update the Strong-mode docs, website inventory, and patch changeset.
  • Bring the branch up to current main and remove the unrelated CI apt-mirror edits from this PR.

Validation

  • Focused compiler, AST immutability, and compile-error suites: 751 passed. Scoped typecheck, formatting, and pnpm sync passed; the eight PR examples produced the stated client, server, and editor results.
  • Website docs-search suite: 23 passed, including the Strong-mode guide deep link.
  • Paired Strong-mode performance check against upstream 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.
  • Dense event-helper follow-up: 1,601 handlers with nested events took 49.9 ms before the bounded traversal and 9.9 ms after it in isolated analysis; independent handlers stayed at 0.291 versus 0.289 ms for 40, and 200 randomized helper graphs produced identical diagnostics.
  • Current-head GitHub CI run 33985766149 on 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]smith is 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

  • An agent produced this diff (agent-authored)

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with 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" or compiler: { strong: true }) with two new diagnostics: OCTANE_STRONG_HOOK_LOCALITY for built-in hook values (and effects that depend on them) declared outside the sole nested @{…} block that consumes them, and OCTANE_STRONG_EVENT_HANDLER_LOCALITY for named callbacks used on native onX attributes outside the deeper block that owns that event.

The compiler adds a separate strongLocalityDiagnostics pass in strong-mode.js (gated on an actual nested @{…} in the module) that walks template regions—including @if, keyed @for, @switch, and @try arms—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.txt describe the rules and examples; a large strong-mode.test.ts suite 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.

@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent feat PR: new feature or capability labels Sep 5, 2026
@domgan-oai
domgan-oai marked this pull request as ready for review September 5, 2026 01:17

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@trueadm trueadm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, @pending and @catch diagnostics report the @if/@for/@try line rather than the arm's line; @else if arms are labelled @if arm; the @finally branch 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 through if/ternary are treated the opposite way and flagged "and its helper renderItem". Because ownsTemplate reads body.type without unwrap, a Prettier-parenthesised arrow body errors in Volar but passes the build.
  • import.meta and new.target are walked as identifier uses of bindings named meta/target; AccessorProperty (build parser) and PropertyDefinition{accessor} (Volar parser) disagree the same way.
  • predeclareNestedVars does not stop at JSXCodeBlock, so a var inside a nested @{} shadows the enclosing arm even though the block compiles to its own function.
  • useEffect inside 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 where onClick={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 of useActionState) is missing from the hook set; TS enum/namespace initializers 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.md says the placement checks apply only to opted-in modules, but strong: true in the Vite plugin applies them to every application module. That is an app-wide breaking change under a patch changeset 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 through childTextHoleUpdate instead of the text path. The authoring rule asks for {label as string}.
  • The Strong-mode code lists in website/src/content/docs/build-tools.mdx and website/public/llms.txt still enumerate eight codes.
  • The apt change is unrelated to this feature and belongs in its own PR. The second sed also rewrites every mirror host to archive.ubuntu.com (contrary to the script's comment) and turns ports.ubuntu.com/ubuntu-ports into 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 main by six commits, two of which touch compile.js emission. It needs a merge, pnpm sync, and a fresh green run before it is ready.

Suggested path

  1. Scope the hard error to nested @{} blocks; decide separately whether arm placement is a warning at all.
  2. Fix the region node, ownsTemplate, MetaProperty, JSXCodeBlock var, and effect-via-helper issues, and add the repros above as tests.
  3. Stop forcing collectReassignedBindings (scope.bindings.get for the function-name lookup, drop the const reassignment check) and make the fixpoint incremental.
  4. Split the CI change out, fix the docs/changeset/website lists, rebase, and re-measure on the final head.

Comment thread docs/tsrx-basics.md Resolved
Comment thread docs/tsrx-basics.md Resolved
Comment thread docs/differences-from-react.md Resolved
Comment thread .changeset/strong-template-locality.md Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

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 trueadm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@trueadm
trueadm merged commit c6516c0 into octanejs:main Sep 5, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent feat PR: new feature or capability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants