Skip to content

Persist Dashboards

FlowDash stores dashboard configurations: which components are placed, how they are connected, and their grid layout. Dashboards and chats are both assets, one stored model (AssetModel) told apart by its kind, kept in an asset store. A store handles all CRUD operations. Three backends are provided: AssetStore (SQLite, the default), JSONFolderAssetStore (one JSON file per dashboard) and MemoryAssetStore (nothing persisted, for notebooks and tests). They all implement BaseAssetStore, so you can also bring your own.


Create a store

from panel_flowdash import AssetStore

store = AssetStore("path/to/assets.db")

The database file is created automatically with the required schema. WAL mode is enabled for concurrent read access. The store keeps one connection open per thread and closes the connections of threads that have exited; call store.close() to release the rest. A server that forks worker processes after building the store (flowdash serve --num-procs) is safe: each process opens its own connections and never closes the ones it inherited. A row that cannot be decoded is skipped and logged once instead of breaking the listing.

Stores from before the rename

Stores written before dashboards became assets open as they are and are migrated in place. AssetStore renames the dashboards and dashboard_history tables and their dashboard_id columns to assets, asset_history and asset_id in one transaction when it opens the database. JSONFolderAssetStore reads files with either dashboard_id or asset_id and writes asset_id the first time it writes a file, so a read-only folder is never changed. flowdash serve keeps using a project's dashboards.db when there is no assets.db. Stored model version 3 files, written by 0.1.0rc2 and earlier, still load.


Keep dashboards as JSON files

from panel_flowdash import JSONFolderAssetStore

store = JSONFolderAssetStore("path/to/dashboards")

Each dashboard is saved as <asset_id>.json in the folder. The files are indented, human-readable JSON, so you can review changes in a pull request, keep them in version control next to the project that serves them, or edit them by hand. The folder is scanned on every request, so files added or changed outside the application appear without a restart. Only files whose size, modification time or inode changed since the last listing are parsed again, so the models a listing returns are shared with that cache and should be treated as read-only; load_asset and load_for_access return a private copy.

Dashboards created through the store get an id derived from their title (Sales Overview becomes sales-overview, then sales-overview-2), which keeps file names and /asset/<id> URLs readable. Ids must be usable as file names: letters, digits, ., _ and -, starting with a letter or digit.

A file that cannot be parsed (invalid JSON or UTF-8, nesting too deep to decode, an id, owner or title that is not a string), or whose asset_id differs from its file name, is skipped and logged once, so one bad file does not take the others down.

To ship a fixed set of dashboards, open the folder read-only:

store = JSONFolderAssetStore("dashboards", read_only=True)

Writes then raise PermissionError (also an AssetStoreError, see below), and nobody can administer a dashboard, so the editor offers no way to modify, rename, share or delete one.

Files are written atomically. Several server processes can share one folder: creating a dashboard claims its id exclusively, so two users creating a dashboard with the same title at the same moment get sales and sales-2, and saving refuses (with an AssetStoreError) to replace a file that belongs to another user, which also covers ids that differ only in case on a case-insensitive file system. Saves, renames and permission changes hold an advisory lock on the folder (on Windows, on a .flowdash.lock file inside it) while they check the file they replace, so two saves of the same dashboard cannot both succeed; see Concurrent edits. The lock needs a file system that supports it; where it does not, as on some network shares, a warning is logged and only the writers within one process are serialized.

Each file stores the dashboard's revision. If you edit a file by hand while the server runs, increment its revision too, or a session that opened the old contents can still save over your edit. A file without a revision is treated as revision 0.

The files are written with sorted keys, and so are the history lines (see Undo, redo and the edit history), so a diff shows only what changed.

Combine several folders

Pass create=False for a folder the store must never create, for example one that another process provisions per user. While it is missing the store lists no dashboards and writes raise an AssetStoreError naming the folder.

To serve dashboards from several folders, say a read-only folder shared by a team and one per user, implement a store that delegates to one JSONFolderAssetStore per folder. store.scan() returns the usable files of a folder as (path, model) pairs, most recently updated first, from the same cache the store's own listings use (so treat the models as read-only), and store.load(asset_id) loads one dashboard by id whoever owns it. store.parse_file(path) parses a single file; it does not check that the path is inside the folder, so build paths from scan() rather than from ids. All three skip a file that cannot be used and log its path and the reason once, exactly as the store does.

from panel_flowdash import BaseAssetStore, JSONFolderAssetStore
from panel_flowdash.asset_store import DASHBOARD_KIND


class TeamAndUserStore(BaseAssetStore):
    """The user's dashboards, then the team's; the user's win on the same id."""

    random_ids = False

    def __init__(self, team_folder, user_folder):
        self.team = JSONFolderAssetStore(team_folder, read_only=True, create=False)
        self.user = JSONFolderAssetStore(user_folder)
        self.stores = (self.user, self.team)

    def _all_assets(self):
        seen, models = set(), []
        for store in self.stores:
            for _, model in store.scan():
                if model.asset_id not in seen:
                    seen.add(model.asset_id)
                    models.append(model)
        return sorted(models, key=lambda m: m.updated_at, reverse=True)

    def _load_any(self, asset_id):
        for store in self.stores:
            if (model := store.load(asset_id)) is not None:
                return model
        return None

    def save_asset(self, dashboard):
        self.user.save_asset(dashboard)

    def create_asset(self, user_id, title, kind=DASHBOARD_KIND):
        return self.user.create_asset(user_id, title, kind)

    def delete_asset(self, user_id, asset_id):
        return self.user.delete_asset(user_id, asset_id)

    def rename_asset(self, user_id, asset_id, new_title):
        return self.user.rename_asset(user_id, asset_id, new_title)

    def set_permission(self, asset_id, permission):
        return self.user.set_permission(asset_id, permission)

    def set_owner(self, asset_id, owner):
        return self.user.set_owner(asset_id, owner)

    # The edit history (undo across sessions) lives next to the user's files.
    def load_history(self, asset_id):
        return self.user.load_history(asset_id)

    def append_history(self, asset_id, record):
        self.user.append_history(asset_id, record)

    def replace_history(self, asset_id, records):
        self.user.replace_history(asset_id, records)

    def rewrite_history(self, asset_id, rewrite):
        return self.user.rewrite_history(asset_id, rewrite)

    def delete_history(self, asset_id):
        self.user.delete_history(asset_id)

Delegate every write, including the edit history methods: the ones a store leaves out fall back to BaseAssetStore's defaults, which keep no history and so silently lose undo across sessions. Forward rewrite_history rather than relying on the default, so the read and write happen under the folder's lock. The history is only kept for dashboards in the user's folder, so edits to a team dashboard start their history once it is saved there.

A dashboard saved under a team dashboard's id lands in the user's folder and shadows the team's from then on. Renaming, sharing and changing the owner only apply to dashboards in the user's folder; for a team dashboard they return False until it has been saved into the user's folder.


Dashboard data model

A persisted dashboard consists of three parts:

AssetItem

Each placed component instance:

from panel_flowdash import AssetItem

item = AssetItem(
    instance_id="filter_1",
    component_id="Analytics/filter",
    x=100,      # ReactFlow canvas x position
    y=200,      # ReactFlow canvas y position
    config={},  # Instance-specific configuration
)

x and y store the node editor canvas position. Grid layout (widths, heights, visibility) is stored separately in tile_layout.

AssetEdge

Each connection between component ports:

from panel_flowdash import AssetEdge

edge = AssetEdge(
    source="filter_1",
    source_port="filtered",
    target="chart_1",
    target_port="data",
)

An edge that reshapes its value also carries a transform, the list of steps it applies. See Transform Edges.

AssetModel

The complete dashboard:

from panel_flowdash import AssetModel

model = AssetModel(
    asset_id="abc123",
    user_id="user@example.com",
    title="My Dashboard",
    items=[item],
    edges=[edge],
    tile_layout=[
        {"id": "filter_1", "w": 4, "h": 3, "x": 0, "y": 0},
        {"id": "chart_1", "w": 8, "h": 4, "x": 4, "y": 0},
    ],
)

The tile_layout list stores the grid positions and sizes for the rendered dashboard view (separate from the node editor canvas positions in items). reference_width, breakpoints and responsive_layouts store how that layout adapts to other screen sizes; see Layout & sizing.

settings is a dictionary of dashboard-wide values, such as {"refresh_period": 30}. Every store persists it, and a dashboard saved before settings existed loads with an empty dictionary. An existing SQLite database gains the column the first time it is opened. Settings that are not a dictionary with string keys are dropped with a warning, so the dashboard itself still loads. See Dashboard settings and refresh.

turns lists the requests to the assistant and the batches of manual edits that changed the dashboard, as AssetTurn objects, and each item's origin names the turn that created it. The editor records them as edits happen (see the dashboard YAML format). Every store persists them; dashboards saved before turns existed (model version 3 and older) load without turns, an existing SQLite database gains a turns_json column the first time it is opened, and malformed stored turns are dropped with a warning like malformed settings.

updated_at is when the store last wrote the dashboard, as a timezone-aware UTC datetime. Stores fill it in when they load a dashboard (the SQLite store from its updated_at column, the JSON folder store from the file's modification time) and the launcher shows it as "Edited 12 minutes ago". It is not part of the dashboard's contents, so it is not saved, exported or compared. A custom store that leaves it None still works; its launcher cards then name only the owner.

Chats

A chat is an AssetModel with kind="chat"; every other dashboard has kind="dashboard", the default. store.create_asset(user_id, title, kind="chat") creates one. Chats are private to their owner: no permission, sharing rule or default_allow lets anyone else open them, admins included, who see them only in Admin > Dashboards. The launcher, the command palette, the assistant's dashboard listing and a homepage dashboard looked up by title leave them out, and FlowDashApp(chats=True) lists a person's chats under Chats in the rail and at /chats (see Sidebar sections). With FlowDashApp(home="explore") asking on the homepage starts a chat, which keeps the data chips picked there in settings["data_scope"] (see Ask on the homepage). A chat also keeps the dashboard its answers were last added to in settings["add_target"] and the dashboards made from it in settings["made_dashboards"] (see From a chat to dashboards). Its answers are its items, edges and turns, with an empty tile_layout: only the chat's Explore view loads them, and saving the chat from the editor keeps them as stored.

Every built-in store persists kind: the SQLite store gains a kind column the first time it opens an older database, and the JSON stores and dashboard YAML write the key only for chats, so existing data reads as dashboards. A custom store must save and load kind too. As a fallback a new chat starts with a permission allowing only its owner, so a store that drops kind still keeps the chat to its owner, though it then lists it as one of their dashboards.

Reports

A standalone report is an AssetModel with kind="report": its own graph of nodes and its report document (report), with no tile layout. It opens on the report editor, whose Layout tab edits the document and whose Dataflow tab edits the graph. store.create_asset(user_id, title, kind="report") creates one with an empty document. Reports are shared like dashboards, are listed in the rail's Reports section and on Browse, and are left out of dashboard listings unless you pass kind="report" or kind=None.

A dashboard can still carry a report of its own, which shares the dashboard's graph. Make a standalone report, in the overflow menu while a dashboard's report is shown, turns it into a report asset: the new report holds copies of only the nodes the report uses (its node, group and turn blocks and the nodes its text placeholders read) and every node upstream of them, keeping their instance ids, so the document needs no rewriting. From then on it is independent of the dashboard, which its source attribute names; the report's overflow menu offers From to open it again, for anyone who may open that dashboard. A duplicated or imported report does not keep source. The same clone is available as panel_flowdash.standalone_report.standalone_report(source, blocks, asset_id=..., user_id=..., title=...).

Every built-in store persists source: the SQLite store gains a source_json column the first time it opens an older database, and the JSON stores write the key only when it is set.


CRUD operations

Create

dashboard = store.create_asset(user_id="user1", title="Sales Overview")

Generates a dashboard ID and persists an empty dashboard. Pass kind="chat" to create a chat or kind="report" for a report instead.

Load

dashboard = store.load_asset(user_id="user1", asset_id="abc123")

Returns None if not found.

List

dashboards = store.list_assets(user_id="user1")
chats = store.list_assets(user_id="user1", kind="chat")

Returns a user's dashboards, ordered by most recently updated. Chats are left out unless you pass kind="chat" (only chats) or kind=None (both), see Chats.

everything = store.all_assets()
dashboards_only = store.all_assets(kind="dashboard")

Returns every stored dashboard regardless of owner, ordered by most recently updated, without any access check; kind keeps only one kind, and by default both are returned. Use store.list_accessible(identity) for the dashboards a user may open, which also leaves chats out unless given kind. Some stores return shared, cached models, so load a dashboard with load_asset before changing it. A custom store implements _all_assets(), which all_assets() and the other listings call.

Save

dashboard.items.append(new_item)
dashboard.edges.append(new_edge)
store.save_asset(dashboard)

Inserts the dashboard or replaces the stored one with the same id. If the dashboard was changed since it was loaded, the save raises AssetConflictError instead; see Concurrent edits.

Rename

store.rename_asset("user1", "abc123", "New Title")

Delete

store.delete_asset("user1", "abc123")

Returns True if a dashboard was deleted, False if not found.


Concurrent edits

Every stored dashboard has a revision, a number the store increments on each save. A model loaded from a store carries the revision it was loaded at, and save_asset only writes it if that is still the stored revision. Otherwise another session saved the dashboard in the meantime, and the store raises AssetConflictError (an AssetStoreError) without writing anything. The check and the write are one atomic step in every built-in store, also when several server processes share a SQLite database or a JSON folder. On success the store sets dashboard.revision to the new revision, so the same model can be saved again.

from panel_flowdash import AssetConflictError

first = store.load_asset("user1", "abc123")
second = store.load_asset("user1", "abc123")
store.save_asset(first)
try:
    store.save_asset(second)
except AssetConflictError as exc:
    print(exc.expected, exc.current)  # 1 2

A model whose revision is None, such as one you build yourself, is saved unconditionally. Renaming a dashboard or changing who it is shared with does not change its revision, because a save keeps the stored title and sharing rules anyway. An existing SQLite database gains the revision column the first time it is opened, with every dashboard at revision 0.

In the editor, a rejected save leaves the canvas as it was and opens a dialog explaining that someone else saved the dashboard. Reload discards the local changes and loads the latest version. Save as copy saves the canvas as a new dashboard owned by the current user, titled after the original with (copy) appended, and switches to it; in a FlowDashApp the URL and dashboard menu follow. Keep editing closes the dialog. The same applies to saving dashboard settings, which are part of the saved dashboard. From Python, FlowDash.save() raises AssetConflictError and FlowDash.save_as(title) saves a copy.

A store of your own can support this too: compare dashboard.revision with the stored revision under the same lock or transaction as the write, raise AssetConflictError on a mismatch, and set dashboard.revision to the stored value afterwards. The helper panel_flowdash.asset_store.check_revision does the comparison and returns the next revision. A store that ignores revision keeps working, with saves resolving last-writer-wins.


Decide who administers and edits a dashboard

store.can_administer(identity, asset_id, admin_groups) decides whether a user may rename, share or delete a dashboard, and store.can_edit(identity, asset_id, admin_groups) whether they may edit and save its contents and settings. Listings already hold the models, so the app calls store.can_administer_model(identity, model, admin_groups) and store.can_edit_model(...) for them instead of loading every dashboard again, and the id-based methods delegate to these. To change a rule in a custom store, override the _model method. The default can_edit_model allows everyone can_administer_model allows, plus the editors named on the dashboard's permission.


Refuse an operation from a custom store

A store of your own can turn down a request, for example a duplicate title, a name the backend cannot hold or a user without write access, by raising AssetStoreError from create_asset, save_asset, rename_asset, delete_asset or set_permission:

from panel_flowdash import AssetStoreError, MemoryAssetStore


class UniqueTitleStore(MemoryAssetStore):
    def create_asset(self, user_id, title):
        if any(m.title == title for m in self.all_assets()):
            raise AssetStoreError(f'A dashboard called "{title}" already exists.')
        return super().create_asset(user_id, title)

The app shows the message to the user as written, logs it at INFO and leaves the open dashboard, canvas and menu as they were, so phrase it for an end user. The create and rename dialogs stay open with the message under the name field. Returning False from rename_asset, delete_asset or set_permission is reported as a generic failure. Any other exception is treated as a bug or an infrastructure fault: it is logged with its traceback and the user sees a generic message such as "Could not save the dashboard. The error has been logged.", never the exception text.


Items that cannot be restored

A saved dashboard can outlive the code it was built with. When a dashboard is loaded or imported, an item whose component is no longer offered, or whose component raises while it is built, is shown as a placeholder node on the wiring canvas and a placeholder tile on the dashboard, in the slot it had. An edge whose port no longer exists, whose types no longer fit, or which touches a placeholder is listed under the wiring canvas instead of being drawn.

Nothing is dropped: placeholders and broken edges are saved back exactly as they were stored, so the dashboard is whole again as soon as the component returns. Remove a placeholder node to drop the item and its edges, or click Discard under the listing to drop the broken edges. Someone who can save the dashboard is told once, when it is opened for editing, how many items and connections could not be restored.

To keep dashboards loading after you rename a component or a port, declare the former names, see Renaming components and ports.

Export and import dashboard files

In edit mode, Download in the side panel saves the canvas as a JSON file named after the dashboard, and Download as YAML saves it in the readable YAML format. Dropping either file onto the wiring canvas recreates its components, connections and tile layout. If the canvas already has components, the editor asks before replacing them. Components the editor doesn't offer are kept as placeholders, see Items that cannot be restored.

The file holds the dashboard contents but not its asset_id, user_id, permission or revision. An imported file takes the identity of the dashboard currently loaded, so saving writes the imported contents to that dashboard and cannot overwrite another one or change who it is shared with. It also keeps the revision the dashboard was loaded at, so importing a file does not hide a save made by another session since then.

The launcher offers the same files for any dashboard you can open: Download as file and Download as YAML in the card's menu save the stored dashboard without opening it, and Import file creates a new dashboard of yours from a downloaded JSON or YAML file (titled after the file's dashboard, numbered if you already have one with that title) and opens it. Duplicate copies a dashboard the same way, titled "Sales copy" for a dashboard called "Sales", owned by you and not shared with anyone. A copy is yours to edit and inspect, so when the app has inspect_outputs on and a dashboard keeps Viewers can inspect outputs off, only its editors and administrators get Duplicate and Download as file; viewers would otherwise get around the restriction by copying it. The same goes for Download as YAML.

The same round trip is available from Python:

data = editor.export_dashboard()  # a JSON-serializable dict
other_editor.import_dashboard(data)  # also accepts the JSON string

import_dashboard raises ValueError for anything that isn't a dashboard export and marks the canvas dirty.

Undo, redo and the edit history

The canvas keeps an edit history: adding, removing and reconfiguring nodes, wiring and transforms, moving nodes, the tile layout, settings, clearing, importing a file and the assistant's edits all become versions of it, batched so the history reads naturally. Each request to the assistant is one version, made when the request ends, however many edits it took; if the person edits or saves while the assistant works, the assistant's edits so far become a version there, the person's edits their own, and its later edits another version of the same request. A person's edits are batched by burst: edits with no pause longer than FlowDash.history_coalesce seconds (3 by default) between them, such as a drag, typing into a config field or adding and wiring a node, become one version, and an edit of the assistant, a save, undo or redo ends the batch. history_coalesce=0 records each of the person's edits on its own. The defaults live in panel_flowdash.history (BURST_SECONDS).

In edit mode, Undo and Redo in the command palette, or Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z (Ctrl+Y on Windows), step through it. From Python:

editor.undo()      # True if something was undone
editor.redo()      # redoes everything the last undo undid
editor.can_undo, editor.can_redo

Undo steps back one version at a time, so it undoes a request to the assistant as a whole, back to the dashboard as it was before the request. When the person edited while the request ran, undo steps back through the request's versions and the person's one at a time instead, so nothing the person did is lost; editor.undo(whole_runs=False) always steps back one version. Redo lasts until the next edit. Undoing does not delete anything: it applies an earlier version and records that it did, so a later redo, or the history in the assistant's drawer, can get back to any version. Restoring a version changes only what differs from the canvas, so nodes that stay keep running.

Undo restores the dashboard's turns and node origins as they were at that version, so it never credits a node to someone who did not create it. It also never brings back what you may not use. A node whose component you are not authorized for, or that the app does not offer, keeps its config and connections as the canvas holds them, or as they were when you opened the dashboard if you removed it, so you can undo removing it. A version that holds such a node you never had on the canvas is out of reach: can_undo is False and undo raises PermissionError (the palette shows the message), and nothing changes. People who may only view a dashboard record no history and cannot undo.

The store keeps the history of each dashboard, so undo reaches edits of earlier sessions. When a dashboard is opened, undo steps back along the edits that made it as saved, never into edits that were undone or that a session made but did not save, also after an upgrade that changes how the dashboard's YAML reads. Undo waits while the assistant is working on a request. The history holds the dashboard YAML as its author saw it; when another person loads it, nodes they may not use are shown as restricted stand-ins, as in the YAML they download. Opening the assistant's drawer loads the stored history, so its History view lists the versions of earlier sessions right after a reload; when the dashboard reads differently from the latest stored version, e.g. because it was changed outside the editor, the dashboard as opened becomes a version then. Retention drops the oldest versions past FlowDash.history_limit (500 by default), those older than FlowDash.history_max_days (90 by default) and the oldest ones past about FlowDash.history_max_bytes of YAML (16 MB by default, always keeping the latest) when the history is first used after opening a dashboard, and a long session keeps the content of only about as many versions in memory; deleting a dashboard deletes its history. history=False turns it all off. In a FlowDashApp, set these through editor_options.

AssetStore keeps the history in an asset_history table, which it adds to existing databases on open; JSONFolderAssetStore keeps one JSON Lines file per dashboard in a .history folder inside the dashboards folder, which you may want to leave out of version control; MemoryAssetStore keeps it in memory. The stored history starts with a {"flowdash_history": 1} record naming its format version, followed by panel-agents events (ARTIFACT_PUBLISHED per version, with the full YAML, and the runs around them) and a FLOWDASH_SAVED record per save; a release that finds a newer format version neither shows nor extends that history. A custom store keeps it by implementing load_history, append_history, replace_history and delete_history, overriding rewrite_history to read and write in one transaction when several sessions share it, and dropping the history in delete_asset; without them undo still works within a session. editor.edit_history.state is the panel-agents RunState holding the versions, for showing them in an ArtifactView or sharing with your own AgentRunner.