Heuristic:AFK surf Open agent Keep Effect Idempotent
| Knowledge Sources | |
|---|---|
| Domains | Extensions, Initialization |
| Last Updated | 2026-10-25 00:00 GMT |
Overview
Keep the view provider effect() hook idempotent — it runs only once per provider class but may be invoked across multiple manager instances, so it must be safe to re-run.
Description
In the ext-loader system, `ViewExtensionProvider.effect()` is the one-time initialization hook (registering Lit custom elements, setting up global state/listeners). The README explicitly notes the method "will only run once per provider class" but that class can be registered on multiple managers (e.g., different editor scopes). Re-running `effect()` must not double-register elements or duplicate global listeners.
Usage
Apply this heuristic when authoring a ViewExtensionProvider with an `effect()` override. Ensure element registration and global setup are guarded against duplicates.
The Insight (Rule of Thumb)
- Action: Make `effect()` safe to call more than once — guard element registration (`customElements.get` check) and dedupe global listeners.
- Value: Use `if (!customElements.get('my-element')) customElements.define(...)` patterns.
- Trade-off: A tiny guard check on each call — but you avoid duplicate-registration errors when the provider class is shared.
- Compatibility: Applies to all `ViewExtensionProvider` subclasses; store providers have no `effect()` hook.
Reasoning
The ext-loader runs `effect()` once per provider class, not per manager instance — but a single class can be reused across managers (page, edgeless, preview). If `effect()` unconditionally registers a Lit element or adds a window listener, the second manager that triggers the same class path would throw (`customElements.define` errors on redefinition) or leak listeners. Idempotency guarantees the one-time guarantee holds even when the class is shared.
Code Evidence
The one-time-per-class guarantee from `blocksuite/affine/ext-loader/README.md:100-117`:
// Override effect to run one-time initialization logic
override effect() {
// This will only run once per provider class
console.log('Initializing MyViewProvider');
// Register lit elements
this.registerLitElements();
}
Scope branching in setup from `blocksuite/affine/ext-loader/README.md:72-80`:
if (context.scope === 'page') {
context.register([PageExt]);
} else if (context.scope === 'edgeless') {
context.register([EdgelessExt]);
}