# Plugin state (/vela-pro/persistence/stores/plugin-state)



Custom side panels, widget actions, and domain modules can store layout-level state directly inside the workspace state document by calling `registerStatePersistence` from `@luxalgo/vela/plugin` (part of Vela's open-source core). Registered state is saved automatically when `persist` is enabled, included in `workspace.getState()`, restored by `workspace.applyState()`, and carried along with named or shared layouts without requiring a dedicated storage endpoint.

Each persistence handler owns one namespaced key inside one of the state document's two `ext` maps. Using `scope: 'global'` stores a single entry at the document root (`ext[key]`), while `scope: 'cell'` stores an entry per chart cell (`charts[i].ext[key]`) that stays bound to that specific chart.

## Document-scoped state [#document-scoped-state]

Use `scope: 'global'` for workspace-wide preferences, such as side panel settings or filter states:

```ts
import { registerSidePanel, registerStatePersistence } from '@luxalgo/vela/plugin';

interface NewsPrefs {
    compact: boolean;
    sources: string[];
}

let prefs: NewsPrefs = { compact: false, sources: ['wire'] };

registerStatePersistence({
    key: 'acme.news', // flat vendor-namespaced key: 'vendor.feature'
    scope: 'global',
    serialize: () => prefs,
    restore(payload) {
        // Treat persisted payloads as untrusted and validate every field.
        if (!payload || typeof payload !== 'object') return;
        const saved = payload as Partial<Record<keyof NewsPrefs, unknown>>;
        prefs = {
            compact: typeof saved.compact === 'boolean' ? saved.compact : prefs.compact,
            sources: Array.isArray(saved.sources) ? saved.sources.filter((s): s is string => typeof s === 'string') : prefs.sources,
        };
    },
});

registerSidePanel({
    id: 'acme.news',
    title: 'News',
    icon: 'list',
    mount: (ctx, body) => {
        const toggle = document.createElement('button');
        toggle.textContent = 'Compact rows';
        toggle.addEventListener('click', () => {
            prefs = { ...prefs, compact: !prefs.compact };
            ctx.stateChanged(); // notify the workspace to schedule a save
        });
        body.append(toggle);
        return {};
    },
});
```

Call `ctx.stateChanged()` whenever external state mutates. While the workspace automatically observes built-in mutations (such as symbol switches, drawings, and indicator edits), it cannot detect changes to external variables unless notified. Calling `ctx.stateChanged()` coalesces with built-in changes into a single debounced `state:changed` event and storage write.

Vela Pro's built-in modules use this exact mechanism for layout preferences, storing order book column settings under `velapro.orderbook` and calendar filters under `velapro.calendar` with `scope: 'global'`.

## Chart-scoped state [#chart-scoped-state]

Scripts added programmatically via `ctx.addIndicator()` participate in the chart's undo history for the active session, but the workspace does not serialize them automatically. Registering a `scope: 'cell'` handler persists those indicators per chart cell and restores them under deterministic IDs:

```ts
import { inputDeltas, registerStatePersistence, registerWidgetAction, type InputValue } from '@luxalgo/vela/plugin';

const PREFIX = 'acme:';
const SCRIPTS: Record<string, { name: string; script: string }> = {
    trend: { name: 'Acme Trend', script: '//@version=5\nindicator("Acme Trend", overlay = true)\nplot(ta.ema(close, 50))' },
};

registerStatePersistence({
    key: 'acme.scripts',
    scope: 'cell',
    serialize(ctx) {
        const mine = ctx.chart.indicators().filter((h) => h.id.startsWith(PREFIX));
        if (mine.length === 0) return undefined; // omit key when no matching scripts exist on this chart
        return mine.map((h) => ({ slug: h.id.slice(PREFIX.length), inputs: inputDeltas(h.inputs, h.inputValues()), hidden: !h.visible }));
    },
    restore(payload, ctx) {
        if (!Array.isArray(payload)) return;
        for (const item of payload as unknown[]) {
            if (!item || typeof item !== 'object') continue;
            const { slug, inputs, hidden } = item as { slug?: unknown; inputs?: unknown; hidden?: unknown };
            const known = typeof slug === 'string' ? SCRIPTS[slug] : undefined;
            if (!known) continue;
            const values = inputs && typeof inputs === 'object' ? (inputs as Record<string, InputValue>) : undefined;
            ctx.addIndicator({ ...known, id: `${PREFIX}${slug}`, language: 'pine', inputs: values, hidden: hidden === true });
        }
    },
});

registerWidgetAction({
    id: 'acme.add-trend',
    target: 'topbar',
    label: 'Acme Trend',
    run: (ctx) => ctx.addIndicator({ ...SCRIPTS.trend!, id: `${PREFIX}trend`, language: 'pine' }),
});
```

Note three design details in the cell handler above:

* **Store script identifiers instead of source code** for application-owned scripts so state documents stay compact and bug fixes in `SCRIPTS` propagate to saved layouts automatically. Store raw source code only when persisting user-authored scripts.
* **Persist input deltas** using `inputDeltas` from the core so untouched inputs continue to inherit updated script defaults in future releases.
* **Restore via the handler's `ctx.addIndicator()`** rather than an outer workspace reference. The `ctx` passed to `restore` targets the specific chart cell being restored (even when it is not the active cell) and mounts the indicator without adding a step to the undo/redo stack.

## Registration rules [#registration-rules]

`registerStatePersistence` enforces five lifecycle rules:

1. **Register before constructing workspaces.** `VelaWorkspace` reads the state persistence registry at construction time, following the same initialization order as `enableVelaPro()`. Registering an existing `key` a second time replaces the previous handler.
2. **Keep `serialize` synchronous and lightweight.** `serialize` executes on every `getState()` call and every debounced `persist` write. Return a JSON-serializable value, or `undefined` to omit your key from `ext`. Call `ctx.stateChanged()` whenever your state changes outside built-in chart events.
3. **`restore` runs only when your key exists in the document.** During initial persistence load and `applyState()`, `restore` executes after charts, scripting engines, and built-in/manifest indicators have mounted. Applying a document that omits your key skips `restore` rather than resetting your state.
4. **Validate all `restore` payloads.** The workspace treats `ext` entries as opaque JSON without schema validation and preserves unrecognized `ext` keys across sessions where the owning handler is not registered. Always type-check fields inside `restore`.
5. **Select the matching `scope`.** Use `cell` scope for state bound to an individual chart's content and `global` scope for workspace-wide preferences.

Exceptions thrown inside `serialize` or `restore` are caught and logged by the workspace so failures in one handler cannot break other extensions. For the complete SDK specification, see [State persistence in the core plugin SDK](/vela/contributing/plugin-sdk#state-persistence--registerstatepersistence).

## Choosing between `ext` and a separate store [#choosing-between-ext-and-a-separate-store]

Persisting state inside the workspace state document fits layout-coupled configuration, whereas a standalone storage adapter or port is preferable when:

* **Data outlives individual layouts.** User records such as watchlists, journal entries, and alert rules should remain consistent when switching between saved layouts and should not be bundled when sharing a layout link.
* **Payloads are large or mutate rapidly.** Every state change serializes and writes the entire workspace state document as a single payload.
* **State is consumed outside a workspace.** Standalone widgets mounted on non-chart pages and server-side background jobs have no workspace state document.

For layout-independent data, follow the same adapter pattern used by Vela Pro's built-in features: define a focused `load` / `save` interface with a `localStorage` fallback and accept a custom adapter during initialization. Standalone widgets mounted outside a workspace emit setting changes through props callbacks so your host page can store them directly; see [Standalone widgets](/vela-pro/modules/widgets).

## Related [#related]

* [Overview](/vela-pro/persistence/overview)
* [Layouts and chart state](/vela-pro/persistence/layouts)
* [Custom modules](/vela-pro/modules/extending/custom-modules)
* [Custom panels and widgets](/vela-pro/modules/extending/custom-widgets)
