agentleFS
deeleeramonedeeleeramone/PyWry/pywry/AGENTS.md

PyWry / pywry

AGENTS.md93 starsChanged 5 months agoApache-2.0View on GitHub

Purpose: This document provides AI coding agents with comprehensive context to understand, develop with, and contribute to the PyWry library. PyWry is a blazingly fast rendering library for generating and managing native desktop windows, iFrames, and Jupyter widgets — with full bidirectional Python ↔ JavaScript communication. Unlike dashboard libraries that only render output, PyWry provides a complete event system where Python can send events to JavaScript and JavaScript can invoke Python callbacks, enabling truly interactive applications. Built on PyTauri (which…

  • Installs packages
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

The file

We split this AGENTS.md into the rules it gives an agent

6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When a window has multiple charts or grids, use IDs to target specific ones:

    line 640
  2. Distinctive:

    All toolbar items share these properties:

    line 1092
  3. Very specific:

    When authenticated, window.__PYWRY_AUTH__ contains { user_id, roles, token_type }.

    line 1495
  4. Distinctive:

    All configuration uses Pydantic v2:

    line 1859
  5. Very specific:

    Every toolbar component has a component_id (default: {type}-{8-char-random}):

    line 1916
  6. Very specific:

    With callbacks (scripts): Use block() after setting up handlers:

    line 2044

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md - PyWry Library Guide for AI Coding Agents

Purpose: This document provides AI coding agents with comprehensive context to understand, develop with, and contribute to the PyWry library.


Quick Reference

AspectDetails
LanguagePython 3.10–3.14 (base); dev tooling requires 3.11+
Type Systemty type checker, Pydantic v2 models
StyleRuff (line length 100), NumPy docstrings
Testingpytest with fixtures, PYWRY_HEADLESS=1 for CI
ArchitectureSubprocess IPC (native) + FastAPI inline server (notebook / browser)
StateMemory (default), Redis, or SQLite + SQLCipher for multi-worker / at-rest encryption
ChatStreaming chat widget with OpenAI / Anthropic / Magentic / Callback / Stdio-ACP / Deepagent providers
MCPFastMCP server (pywry mcp) exposing widget, chart, grid, chat, tvchart, and auth tooling

Project Overview

PyWry is a blazingly fast rendering library for generating and managing native desktop windows, iFrames, and Jupyter widgets — with full bidirectional Python ↔ JavaScript communication.

Unlike dashboard libraries that only render output, PyWry provides a complete event system where Python can send events to JavaScript and JavaScript can invoke Python callbacks, enabling truly interactive applications.

Built on PyTauri (which uses Rust's Tauri framework), it leverages the OS webview instead of bundling a browser engine—resulting in binaries under 3MB compared to Electron's 150MB+ overhead.

Core Capabilities

  • Window Modes: NEW_WINDOW, SINGLE_WINDOW, MULTI_WINDOW, NOTEBOOK, BROWSER.
  • Notebook Support: Automatic inline rendering via anywidget or IFrame in Jupyter / VS Code / Colab.
  • Toolbar System: Declarative Pydantic components (Button, Select, MultiSelect, TextInput, SecretInput, SliderInput, RangeInput, Toggle, Checkbox, RadioGroup, TabGroup, Marquee, Modal, …) with top / bottom / left / right / header / footer / inside positions and automatic nested-flexbox layout.
  • Two-Way Events: Python ↔ JavaScript communication with pre-wired Plotly / AgGrid / TradingView / chat events plus utility events for DOM manipulation.
  • Theming & CSS: Light / dark / system modes, --pywry-* CSS variables, component-ID targeting, hot reload, and dynamic styling via events (pywry:set-style, pywry:inject-css).
  • Security: Scoped token auth enabled by default, CSP headers, internal API protection, SecuritySettings.strict() / .permissive() / .localhost() presets.
  • AgGrid Tables: Pandas → AgGrid conversion with pre-wired events, context menus, server-side mode, and persisted column/filter/sort state.
  • Plotly Charts: Plotly rendering with pre-wired plot events, layout / trace / figure updates, and state round-trips.
  • TradingView Charts: Extended Lightweight Charts integration — drawing surface (trendlines, fib tools, text, price notes, brushes), pluggable datafeed API, UDF adapter for external quote servers, streaming bar updates, compare overlays, compare-derivative indicators (Spread / Ratio / Sum / Product / Correlation), savable layouts, and a themeable settings panel.
  • Chat Widget: Streaming chat UI with threads, artifacts, slash commands, plan / todo updates, permission prompts, context sources, and pluggable providers (OpenAIProvider, AnthropicProvider, MagenticProvider, CallbackProvider, StdioProvider for ACP subprocesses, DeepagentProvider for LangChain Deep Agents).
  • MCP Server: pywry mcp --transport stdio | http exposes widget management, components, chart / grid / tvchart control, events, chat-agent driving, auth, and docs skills to any MCP client.
  • Toast Notifications: Built-in alert system (info, success, warning, error, confirm) with positioning and blocking overlay.
  • Marquee Ticker: Scrolling text/content with dynamic per-item updates.
  • Secrets Handling: SecretInput stores values server-side; HTML only carries opaque component IDs.
  • Hot Reload: CSS injection and JS refresh with scroll preservation.
  • Bundled Libraries: Plotly.js, AgGrid, and TradingView Lightweight Charts are bundled (offline capable) and served from pywry/frontend/assets/.
  • Native File Dialogs, Menus, Tray: Tauri-powered save/open dialogs and filesystem access; MenuProxy, TrayProxy, and WindowProxy wrap the Tauri runtime APIs.
  • Configuration System: TOML files, pyproject.toml [tool.pywry], environment variables (PYWRY_*).
  • CLI Tools: pywry config, pywry init, pywry mcp, pywry mcp install.
  • Deploy Mode: Horizontal scaling with Redis-backed state, or SQLite + SQLCipher for single-node at-rest encryption.
  • Authentication: OAuth2 (Google / GitHub / Microsoft / OIDC / custom) with PKCE, keyring-backed token storage, automatic refresh, and optional RBAC for deploy-mode routes.
  • Standalone Executables: pywry[freeze] ships a PyInstaller hook — no .spec edits or --hidden-import flags required.

Dependencies

Base package (always installed):

Python 3.10–3.14
pytauri >= 0.8.0
anyio >= 4.0.0
httpx >= 0.27.0
pydantic >= 2.0.0
pydantic-settings >= 2.0.0
redis >= 7.1.0            # client library; only used if state_backend != "memory"
fastapi >= 0.128.0
uvicorn >= 0.40.0
watchdog >= 3.0.0
setproctitle >= 1.3.0
websockets >= 16.0.0

Optional extras (see pyproject.toml for full lists):

ExtraPulls inPurpose
notebookanywidget, ipykernelJupyter / anywidget integration
authauthlib, keyringOAuth2 and keyring-backed token storage
mcpfastmcppywry mcp MCP server
acpagent-client-protocolStdioProvider (Agent Client Protocol subprocess)
sqlitesqlcipher3Encrypted SQLite state backend
openai / anthropic / magenticmatching SDKChat providers
deepagentdeepagents, langchain-mcp-adapters, fastmcp, agent-client-protocolDeepagentProvider (LangChain Deep Agents)
freezepyinstallerStandalone executable builds
allall of the aboveEverything (no freeze)

Also used at build time: cryptography (for token storage in deploy mode), plotly, pandas.


Architecture Overview

Rendering Paths

PyWry automatically selects the appropriate rendering path based on environment:

EnvironmentRendering PathModuleReturn Type
Desktop (script/terminal)Native Windowpywry.app.PyWryNativeWindowHandle
Jupyter/VS Code with anywidgetNotebook Widgetpywry.widgetPyWryWidget
Jupyter/VS Code without anywidgetInline IFramepywry.inlineInlineWidget
Headless / Server / SSHBrowser Modepywry.window_manager.modes.browserInlineWidget

Window Modes

ModeBehavior
NEW_WINDOWCreates new window for each show() call
SINGLE_WINDOWReuses one window, replaces content
MULTI_WINDOWMultiple labeled windows, update by label
NOTEBOOKInline rendering in Jupyter notebooks (auto-detected)
BROWSEROpens in system browser, uses FastAPI server (headless/SSH)

Key Architectural Points

  1. Desktop Mode: Python manages high-level API via PyWry class; PyTauri subprocess handles window creation and OS webview; JSON IPC over stdin/stdout; subprocess starts lazily on first show() call
  2. Notebook Mode: Auto-detected via notebook.py; FastAPI server starts on first render; IFrame displays content; bidirectional events via WebSocket
  3. anywidget Mode: Uses anywidget/traitlets for Jupyter widget protocol; bundles Plotly.js and AgGrid as ESM modules
  4. Browser Mode: Same FastAPI server as Notebook mode; opens URL in system default browser; ideal for headless/SSH/server environments

Directory Structure

pywry/
├── __init__.py          # Public API exports (see "Core API / Imports")
├── __main__.py          # PyTauri subprocess entry point (IPC loop + plugin loader)
├── _freeze.py           # PyInstaller-aware freeze support + runtime setup
├── _pyinstaller_hook/   # PyInstaller hook dir (pulled in by `pywry[freeze]`)
├── _vendor/             # Vendored pytauri_wheel bundle
├── app.py               # Main PyWry class — user entry point
├── runtime.py           # PyTauri subprocess management (stdin/stdout IPC)
├── window_dispatch.py   # Thread-safe dispatch into the PyTauri runtime
├── window_proxy.py      # WindowProxy wrapping Tauri WebviewWindow API
├── menu_proxy.py        # MenuProxy (native window / app menus)
├── tray_proxy.py        # TrayProxy (system tray icons)
├── modal.py             # Modal toolbar component + helpers
├── inline.py            # FastAPI-based inline rendering + InlineWidget class
├── notebook.py          # Notebook environment detection (NotebookEnvironment enum)
├── widget.py            # anywidget widgets (PyWryWidget, PyWry{Plotly,AgGrid,TVChart}Widget)
├── widget_protocol.py   # BaseWidget protocol and NativeWindowHandle class
├── config.py            # Layered configuration system (pydantic-settings)
├── models.py            # Core Pydantic models (WindowConfig, HtmlContent, ThemeMode, WindowMode)
├── types.py             # Shared enum / menu / tray / mouse-button TypedDicts & Pydantic models
├── exceptions.py        # PyWry exception hierarchy
├── templates.py         # HTML template builder (CSP, themes, scripts, toolbar)
├── scripts.py           # JavaScript bridge code injected into windows
├── callbacks.py         # Event callback registry (singleton)
├── assets.py            # Bundled asset loading (Plotly.js, AgGrid, TradingView CSS/JS)
├── asset_loader.py      # CSS/JS file loading with caching
├── grid.py              # AgGrid Pydantic models (ColDef, GridOptions, etc.)
├── plotly_config.py     # Plotly configuration models (PlotlyConfig, ModeBarButton, …)
├── toolbar.py           # Toolbar component models (Button, Select, Marquee, …)
├── state_mixins.py      # Widget state management mixins (Grid/Plotly/Toolbar/TVChart)
├── hot_reload.py        # Hot reload manager
├── watcher.py           # File system watcher (watchdog-based)
├── log.py               # Logging utilities
├── cli.py               # CLI commands (config, init, mcp …)
├── Tauri.toml           # Tauri configuration
├── capabilities/        # Tauri capability permissions
│   └── default.toml
├── commands/            # IPC command handlers
│   └── window_commands.py
├── frontend/            # Frontend HTML and bundled assets
│   ├── index.html
│   ├── assets/          # Compressed libraries (plotly, ag-grid, tvchart, icons, PyWry-{light,dark}.svg)
│   ├── src/             # JS modules (main.js, aggrid-defaults.js, plotly-defaults.js, tvchart/*.js, chat/*.js)
│   └── style/           # CSS files (pywry.css, chat.css, tvchart.css, …)
├── tvchart/             # TradingView Lightweight Charts integration
│   ├── __init__.py      # Public exports (TVChartConfig, DatafeedProvider, UDFAdapter, mixin, …)
│   ├── config.py        # TVChartConfig / SeriesConfig / layout / drawings models
│   ├── models.py        # TVChartBar, TVChartSymbolInfo, quote / search / mark payloads
│   ├── normalize.py     # OHLCV normalization (DataFrame → bars, indicator helpers)
│   ├── datafeed.py      # DatafeedProvider ABC + default async dispatcher
│   ├── udf.py           # UDFAdapter (HTTP UDF-compatible datafeed)
│   ├── mixin.py         # TVChartStateMixin (Python-side chart state surface)
│   └── toolbars.py      # build_tvchart_toolbars() factory
├── chat/                # Streaming chat widget
│   ├── __init__.py      # Public exports (ChatProvider, artifacts, html builder, get_provider)
│   ├── manager.py       # ChatManager, ChatContext, SettingsItem
│   ├── session.py       # ACP session lifecycle: capabilities, modes, config options, plans
│   ├── models.py        # ChatConfig, ChatMessage, ChatThread, ContentBlock, ACP payloads
│   ├── updates.py       # SessionUpdate union (agent / artifact / plan / mode / tool-call / …)
│   ├── artifacts.py     # Code / Html / Image / Json / Markdown / Plotly / Table / TradingView
│   ├── permissions.py   # Permission request / response plumbing
│   ├── html.py          # build_chat_html() — standalone chat UI bootstrap
│   └── providers/       # Pluggable ChatProvider backends
│       ├── __init__.py  # ChatProvider ABC + get_provider() factory
│       ├── openai.py    # OpenAIProvider (OpenAI SDK)
│       ├── anthropic.py # AnthropicProvider (Anthropic SDK)
│       ├── magentic.py  # MagenticProvider (any magentic-supported LLM)
│       ├── callback.py  # CallbackProvider (sync/async Python callback)
│       ├── stdio.py     # StdioProvider (Agent Client Protocol subprocess)
│       └── deepagent.py # DeepagentProvider (LangChain Deep Agents + MCP adapters + ACP)
├── mcp/                 # Model Context Protocol server
│   ├── __init__.py
│   ├── __main__.py      # `python -m pywry.mcp`
│   ├── server.py        # FastMCP server setup, transport wiring
│   ├── tools.py         # Low-level event dispatch + widget/component tools
│   ├── handlers.py      # Tool handlers
│   ├── builders.py      # HTML/component builders shared across tools
│   ├── resources.py     # MCP resources (bundled assets, component reference)
│   ├── prompts.py       # MCP prompts
│   ├── agentic.py       # Agent orchestration helpers
│   ├── state.py         # Per-session state for long-running tools
│   ├── docs.py          # Docs skill content
│   ├── install.py       # `pywry mcp install` — client config writer
│   └── skills/          # Skills (authentication, chat, chat_agent, component_reference,
│                        #   css_selectors, data_visualization, deploy, events,
│                        #   forms_and_inputs, iframe, interactive_buttons, jupyter,
│                        #   modals, native, styling, tvchart, autonomous_building)
├── state/               # Pluggable state management for deploy mode
│   ├── __init__.py      # Public exports (stores, factory functions, types)
│   ├── _factory.py      # Factory functions for store instantiation
│   ├── base.py          # WidgetStore / EventBus / ConnectionRouter / SessionStore ABCs
│   ├── memory.py        # In-memory backends (default)
│   ├── redis.py         # Redis-backed backends
│   ├── sqlite.py        # SQLite + SQLCipher backend (at-rest encryption)
│   ├── file.py          # File-backed backend (dev / single-process)
│   ├── server.py        # Deploy-mode FastAPI routes glue
│   ├── callbacks.py     # Cross-worker callback dispatch
│   ├── auth.py          # Authentication and RBAC utilities
│   ├── types.py         # Type definitions (StateBackend, WidgetData, OAuthTokenSet, …)
│   └── sync_helpers.py  # Sync↔async bridging (run_async, wait_for_event)
├── auth/                # OAuth2 authentication system
│   ├── __init__.py      # Public exports
│   ├── pkce.py          # PKCE challenge generation (RFC 7636)
│   ├── providers.py     # OAuthProvider ABC + Google, GitHub, Microsoft, OIDC implementations
│   ├── token_store.py   # TokenStore ABC + Memory, Keyring, Redis backends
│   ├── callback_server.py # Ephemeral localhost server for native auth redirects
│   ├── deploy_routes.py # FastAPI /auth/* routes for deploy mode
│   ├── login_page.py    # Rendered login page shipped with deploy-mode routes
│   ├── flow.py          # AuthFlowManager orchestrator
│   └── session.py       # SessionManager with automatic token refresh
├── utils/               # Utility helpers (async_helpers, …)
└── window_manager/      # Window mode implementations
    ├── controller.py
    ├── lifecycle.py
    └── modes/           # base.py, new_window.py, single_window.py, multi_window.py, browser.py

Core API

Imports

# Main class
from pywry import PyWry

# Enums
from pywry import WindowMode, ThemeMode

# Models
from pywry import HtmlContent, WindowConfig

# Toolbar components
from pywry import (
    Toolbar, Button, Select, MultiSelect, TextInput, TextArea, SearchInput,
    SecretInput, NumberInput, DateInput, SliderInput, RangeInput, Toggle,
    Checkbox, RadioGroup, TabGroup, Div, Marquee, TickerItem, Option, ToolbarItem,
    Modal,
)

# Plotly configuration (for customizing modebar, icons, buttons)
from pywry import PlotlyConfig, PlotlyIconName, ModeBarButton, ModeBarConfig, SvgIcon, StandardButton

# Grid models (for AgGrid customization)
from pywry import ColDef, ColGroupDef, DefaultColDef, RowSelection, GridOptions, build_grid_config, to_js_grid_config
# Or, with additional helpers:
from pywry.grid import GridConfig, GridData

# TradingView charts
from pywry import (
    TVChartConfig, TVChartData, TVChartBar, TVChartMark, TVChartTimescaleMark,
    TVChartExchange, TVChartSymbolInfo, TVChartSymbolInfoPriceSource,
    TVChartLibrarySubsessionInfo, TVChartSearchSymbolResultItem,
    TVChartStateMixin, QuoteData,
    # Datafeed surface
    DatafeedProvider, UDFAdapter, build_tvchart_toolbars,
    # Datafeed request/response payloads
    TVChartDatafeedConfigRequest, TVChartDatafeedConfigResponse, TVChartDatafeedConfiguration,
    TVChartDatafeedHistoryRequest, TVChartDatafeedHistoryResponse,
    TVChartDatafeedResolveRequest, TVChartDatafeedResolveResponse,
    TVChartDatafeedSearchRequest, TVChartDatafeedSearchResponse,
    TVChartDatafeedMarksRequest, TVChartDatafeedMarksResponse,
    TVChartDatafeedTimescaleMarksRequest, TVChartDatafeedTimescaleMarksResponse,
    TVChartDatafeedServerTimeRequest, TVChartDatafeedServerTimeResponse,
    TVChartDatafeedSubscribeRequest, TVChartDatafeedUnsubscribeRequest,
    TVChartDatafeedBarUpdate, TVChartDatafeedSymbolType,
)

# Chat widget (ChatProvider ABC, artifact models, HTML bootstrap, provider factory)
from pywry import (
    ChatProvider, get_provider, build_chat_html,
    ChatManager, ChatContext, SettingsItem,
    ChatConfig, ChatMessage, ChatThread, ContentBlock,
    CodeArtifact, HtmlArtifact, ImageArtifact, JsonArtifact,
    MarkdownArtifact, PlotlyArtifact, TableArtifact,
    TradingViewArtifact, TradingViewSeries,
    # Session / update types
    PlanEntry, SessionConfigOption, SessionMode,
    AgentMessageUpdate, ArtifactUpdate, CitationUpdate, CommandsUpdate,
    ConfigOptionUpdate, ModeUpdate, PlanUpdate, StatusUpdate,
    ThinkingUpdate, ToolCallUpdate,
    # ACP command payloads
    ACPCommand, ACPToolCall,
)
# Concrete providers are imported from their modules:
from pywry.chat.providers.openai import OpenAIProvider            # requires [openai]
from pywry.chat.providers.anthropic import AnthropicProvider      # requires [anthropic]
from pywry.chat.providers.magentic import MagenticProvider        # requires [magentic]
from pywry.chat.providers.callback import CallbackProvider
from pywry.chat.providers.stdio import StdioProvider              # requires [acp]
from pywry.chat.providers.deepagent import DeepagentProvider      # requires [deepagent]

# Native / Tauri proxies
from pywry import MenuProxy, TrayProxy
from pywry.window_proxy import WindowProxy
from pywry.types import (
    MenuConfig, MenuItemConfig, CheckMenuItemConfig, IconMenuItemConfig,
    PredefinedMenuItemConfig, PredefinedMenuItemKind, SubmenuConfig,
    TrayIconConfig, MouseButton, MouseButtonState,
)

# State mixins (for extending custom widgets)
from pywry import GridStateMixin, PlotlyStateMixin, ToolbarStateMixin

# Inline functions (for notebooks)
from pywry.inline import show_plotly, show_dataframe, show_tvchart, block, stop_server

# Notebook detection
from pywry import NotebookEnvironment, detect_notebook_environment, is_anywidget_available, should_use_inline_rendering

# Widget classes (anywidget)
from pywry import PyWryWidget, PyWryPlotlyWidget, PyWryAgGridWidget, PyWryTVChartWidget

# Widget protocol (for type checking and custom implementations)
from pywry.widget_protocol import BaseWidget, NativeWindowHandle, is_base_widget

# Window manager
from pywry import BrowserMode, get_lifecycle

# Settings (exported from pywry)
from pywry import PyWrySettings, SecuritySettings, WindowSettings, ThemeSettings, HotReloadSettings, TimeoutSettings, AssetSettings, LogSettings

# Settings (require full path import)
from pywry.config import ServerSettings, DeploySettings, OAuth2Settings, ChatSettings

# Asset loading
from pywry import AssetLoader, get_asset_loader

# Callback registry
from pywry import CallbackFunc, WidgetType, get_registry

# Runtime (for low-level PyTauri access in native mode)
# Note: runtime is importable from pywry but not in __all__
from pywry import runtime

# State management (for deploy mode / horizontal scaling / at-rest encryption)
from pywry.state import (
    get_widget_store,
    get_event_bus,
    get_connection_router,
    get_session_store,
    is_deploy_mode,
    get_worker_id,
    get_state_backend,
    WidgetData,
    EventMessage,
    ConnectionInfo,
    UserSession,
    StateBackend,
)

# OAuth2 authentication (public surface from pywry.auth)
from pywry.auth import (
    OAuthProvider, PKCEChallenge, TokenStore,
    AuthFlowManager, SessionManager, OAuthCallbackServer,
)

PyWry Class

PyWry(
    mode: WindowMode = WindowMode.NEW_WINDOW,
    theme: ThemeMode = ThemeMode.DARK,
    title: str = "PyWry",
    width: int = 800,
    height: int = 600,
    settings: PyWrySettings | None = None,
    hot_reload: bool = False,
)

Display Methods

# Show HTML content - returns NativeWindowHandle (native) or widget (notebook)
handle = app.show(
    content,                    # str or HtmlContent
    title=None,
    width=None,                 # int for pixels, str for CSS (e.g., "60%")
    height=None,
    callbacks=None,             # Dict of event handlers {"event:name": handler}
    include_plotly=False,
    include_aggrid=False,
    aggrid_theme="alpine",
    label=None,
    watch=None,                 # Enable hot reload file watching
    toolbars=None,              # List of Toolbar objects
)

# Show Plotly figure
handle = app.show_plotly(
    figure,                     # Plotly Figure or dict
    title=None,
    width=None,
    height=None,
    callbacks=None,
    label=None,
    inline_css=None,
    on_click=None,              # Click callback (notebook mode)
    on_hover=None,              # Hover callback (notebook mode)
    on_select=None,             # Selection callback (notebook mode)
    toolbars=None,
    config=None,                # PlotlyConfig or dict
)

# Show DataFrame as AgGrid
handle = app.show_dataframe(
    data,                       # pandas DataFrame or dict
    title=None,
    width=None,
    height=None,
    callbacks=None,
    label=None,
    column_defs=None,           # List of ColDef objects
    aggrid_theme="alpine",
    grid_options=None,
    toolbars=None,
    inline_css=None,
    on_cell_click=None,         # Cell click callback (notebook mode)
    on_row_selected=None,       # Row selection callback (notebook mode)
    server_side=False,          # Use server-side mode for large datasets
)

# Show TradingView Lightweight Chart
handle = app.show_tvchart(
    data,                       # OHLCV DataFrame, list of dicts, or dict of lists
    title=None,
    width=None,
    height=None,
    callbacks=None,
    chart_options=None,         # Chart-level options (layout, grid, etc.)
    series_options=None,        # Series-specific options (colors, etc.)
    symbol_col=None,            # Column name for multi-series grouping
    max_bars=10_000,
    toolbars=None,
    on_click=None,
    on_crosshair=None,
)

HtmlContent Model

Pass structured content with custom CSS/JS files and data:

from pywry import HtmlContent

content = HtmlContent(
    html="<div id='app'></div>",       # HTML content
    json_data={"items": [1, 2, 3]},    # Accessible as window.json_data in JS
    css_files=["style.css"],            # CSS files to include
    script_files=["app.js"],            # JS files to include
    inline_css="body { padding: 20px; }", # Inline CSS
    init_script="initApp()",            # JS to run after DOM ready
    watch=True,                         # Enable hot reload for these files
)
app.show(content, title="Custom App")
FieldTypeDescription
htmlstrHTML content
json_datadictData accessible as window.json_data
css_fileslist[str]CSS file paths to include
script_fileslist[str]JS file paths to include
inline_cssstrInline CSS styles
init_scriptstrJavaScript to run after DOM ready
watchboolEnable hot reload for included files

PlotlyConfig

Customize chart behavior and modebar:

from pywry import PlotlyConfig, ModeBarButton, SvgIcon

config = PlotlyConfig(
    responsive=True,
    display_mode_bar=True,             # True, False, or "hover"
    scroll_zoom=False,
    mode_bar_buttons_to_remove=["lasso2d", "select2d"],
    mode_bar_buttons_to_add=[
        ModeBarButton(
            name="custom",
            title="Custom Action",
            icon=SvgIcon(path="M10 10 L90 90", width=100, height=100),
            click="function(gd) { window.pywry.emit('app:custom', {}); }"
        )
    ],
)
app.show_plotly(fig, config=config)
ParameterTypeDescription
responsiveboolResize chart with container
display_mode_barbool | strShow modebar (True, False, "hover")
scroll_zoomboolEnable scroll to zoom
mode_bar_buttons_to_addlistCustom ModeBarButton objects
mode_bar_buttons_to_removelist[str]Remove default buttons by name

ColDef and GridOptions

Configure AgGrid columns and behavior:

from pywry.grid import ColDef, DefaultColDef, GridOptions, RowSelection

# Column definitions
col_defs = [
    ColDef(field="name", header_name="Name", pinned="left", width=150),
    ColDef(field="age", header_name="Age", filter="agNumberColumnFilter", sortable=True),
    ColDef(field="email", header_name="Email", editable=True),
]

# Default column settings
default_col_def = DefaultColDef(
    sortable=True,
    filter=True,
    resizable=True,
    flex=1,
)

# Grid options
grid_options = GridOptions(
    default_col_def=default_col_def,
    row_selection=RowSelection(mode="multiple", enable_click_selection=True),
    pagination=True,
    pagination_page_size=50,
)

app.show_dataframe(df, column_defs=col_defs, grid_options=grid_options)

ColDef Key Properties:

PropertyTypeDescription
fieldstrDataFrame column name
header_namestrDisplay header
pinnedstrPin column: "left", "right", None
widthintColumn width in pixels
flexintFlex grow factor
filterstr | boolFilter type or True for default
sortableboolEnable column sorting
editableboolEnable cell editing
value_formatterstrJS formatter function
cell_rendererstrJS renderer function

Server-Side AgGrid (Large Datasets)

For datasets >10K rows, use server-side mode with pagination callbacks:

import pandas as pd
from pywry import PyWry

app = PyWry()
df = pd.DataFrame(...)  # Large dataset

def on_page_request(data, event_type, label):
    """Handle pagination requests from AgGrid."""
    start = data["startRow"]
    end = data["endRow"]
    
    # Slice your data based on request
    page_data = df.iloc[start:end].to_dict("records")
    
    # Send page response
    app.emit("grid:page-response", {
        "gridId": data["gridId"],
        "rows": page_data,
        "totalRows": len(df),
        "isLastPage": end >= len(df),
    }, label)

app.show_dataframe(
    df.head(100),  # Initial data (first page)
    server_side=True,
    callbacks={"grid:request-page": on_page_request}
)

Hot Reload

Enable live updates during development:

# Method 1: Constructor
app = PyWry(hot_reload=True)

# Method 2: HtmlContent with watch
content = HtmlContent(html="<h1>Hi</h1>", css_files=["style.css"], watch=True)
app.show(content, watch=True)

# Method 3: Toggle at runtime
app.enable_hot_reload()
app.refresh_css(label)  # Manual CSS reload
app.disable_hot_reload()

Hot Reload Behavior:

File TypeBehavior
.cssInjected without refresh (styles update instantly)
.js, .htmlFull refresh with scroll position preservation

Multiple Charts/Grids (ID Targeting)

When a window has multiple charts or grids, use IDs to target specific ones:

# Target specific chart with chart_id
widget.update_layout({"title": "Updated"}, chart_id="sales-chart")
widget.reset_zoom(chart_id="revenue-chart")

# Target specific grid with grid_id
widget.update_data(new_rows, grid_id="users-grid")
widget.update_cell("row1", "status", "Active", grid_id="orders-grid")

# Register handlers for specific components (compound event ID)
app.on("plotly:click:sales-chart", handle_sales_click)
app.on("grid:row-selected:users-grid", handle_user_selection)

ID Hierarchy:

ID TypeScopeExample
labelWindow/Widget"pywry-abc123"
chartIdPlotly chart"sales-chart"
gridIdAgGrid table"users-grid"
componentIdToolbar item"export-btn"

Event Handler Signature

def handler(data: dict, event_type: str, label: str) -> None:
    """
    data: Event payload from JavaScript
    event_type: The event name (e.g., "app:click", "plotly:click")
    label: Window/widget label that triggered the event
    """
    pass

Sending Events to JavaScript

# All modes return a handle/widget with emit() method
handle = app.show("<h1>Hello</h1>")
handle.emit("app:response", {"key": "value"})

# Alternative: use app.emit() with window label
app.emit("app:response", {"key": "value"}, handle.label)

Low-level alternative: For direct access to PyTauri runtime in native mode, use from pywry import runtime then runtime.emit_event(handle.label, ...).

Widget Methods (Plotly/AgGrid)

Widgets returned by show_plotly() and show_dataframe() have convenience methods:

Plotly Widget Methods:

widget = app.show_plotly(fig)
widget.update_figure(new_fig, chart_id=None)        # Replace entire figure
widget.update_layout({"title": "New Title"})        # Update layout properties
widget.update_traces({"marker.color": "red"}, [0])  # Update specific traces
widget.reset_zoom(chart_id=None)                    # Reset zoom/pan
widget.request_plotly_state(chart_id=None)          # Request current state -> plotly:state-response

AgGrid Widget Methods:

widget = app.show_dataframe(df)
widget.update_data(rows, grid_id=None)              # Replace row data
widget.update_columns(col_defs, grid_id=None)       # Replace column definitions
widget.update_cell(row_id, col_id, value)           # Update single cell
widget.update_grid(data=None, columns=None)         # Combined update
widget.request_grid_state(grid_id=None)             # Request state -> grid:state-response
widget.restore_state(state, grid_id=None)           # Restore saved state
widget.reset_state(grid_id=None, hard=False)        # Reset to initial state

Other Methods

MethodDescription
emit(event_type, data, label=None)Send event to JavaScript in window(s)
alert(message, alert_type, ...)Show toast notification
on(event_type, handler, ...)Register event handler
on_grid(event_type, handler, ...)Register grid-specific event handler
on_chart(event_type, handler, ...)Register chart-specific event handler
on_toolbar(event_type, handler, ...)Register toolbar-specific event handler
on_html(event_type, handler, ...)Register HTML element event handler
on_window(event_type, handler, ...)Register window lifecycle event handler
eval_js(script, label=None)Execute JavaScript in window(s)
update_content(html, label=None)Update window HTML content
show_window(label)Show a hidden window
hide_window(label)Hide a window (keeps it alive)
close(label=None)Close specific or all windows
get_labels()Get list of all active window labels
is_open(label=None)Check if window(s) are open
refresh(label=None)Refresh window content
refresh_css(label=None)Hot-reload CSS without page refresh
enable_hot_reload()Enable hot reload
disable_hot_reload()Disable hot reload
block(label=None)Block until window(s) close
destroy()Close all windows and cleanup
get_lifecycle()Get WindowLifecycle manager

Event System

Namespace Pattern

Events follow the format namespace:event-name:

PartRulesExamples
namespaceStarts with letter, alphanumeric onlyapp, plotly, grid, myapp
event-nameStarts with letter, alphanumeric + hyphens + underscoresclick, row-select, update_data

Valid: app:save, plotly:click, grid:row-select

Reserved Namespaces

NamespacePurpose
pywry:*System events (initialization, results, theme, downloads, content updates)
plotly:*Plotly chart events
grid:*AgGrid table events
tvchart:*TradingView Lightweight Charts events (datafeed, drawings, layouts, settings)
chat:*Chat widget events (streaming updates, plans, permissions, modes, config)
toolbar:*Toolbar state (toolbar:request-state, toolbar:set-value, toolbar:state-response, …)
auth:*Authentication lifecycle (auth:login, auth:logout, auth:state-change)
tray:*System tray icon / menu events
menu:*Native window / app menu events
modal:*Modal open / close / submit events

Pre-Registered Events

Plotly Events (JS → Python):

EventTriggerKey Payload Fields
plotly:clickUser clicks a data pointchartId, points, widget_type: "chart"
plotly:hoverUser hovers over a pointchartId, points, widget_type
plotly:selectedUser selects with box/lassochartId, points, range, lassoPoints
plotly:relayoutUser zooms, pans, or resizeschartId, relayout_data, widget_type
plotly:state-responseResponse to state requestchartId, layout, data

Plotly Events (Python → JS):

EventDescriptionKey Payload Fields
plotly:update-figureReplace entire figurefigure, chartId?, config?
plotly:update-layoutUpdate layout propertieslayout, chartId?
plotly:update-tracesUpdate trace dataupdate, indices, chartId?
plotly:reset-zoomReset chart zoomchartId?
plotly:request-stateRequest current chart statechartId?
plotly:export-dataRequest trace data exportchartId?

Note: plotly:export-data triggers plotly:export-response (JS → Python) with payload { data: [{ traceIndex, name, x, y, type }, ...] }.

AgGrid Events (JS → Python):

EventTriggerKey Payload Fields
grid:row-selectedRow selection changesgridId, rows, widget_type: "grid"
grid:cell-clickUser clicks a cellgridId, rowIndex, colId, value, data
grid:cell-editUser edits a cellgridId, rowIndex, rowId, colId, oldValue, newValue, data
grid:filter-changedFilter appliedgridId, filterModel, widget_type
grid:data-truncatedClient-side dataset truncatedgridId, displayedRows, truncatedRows, message
grid:modeGrid mode info (server-side)gridId, mode, serverSide, totalRows, blockSize
grid:request-pageServer-side requests data blockgridId, startRow, endRow, sortModel, filterModel
grid:state-responseResponse to state requestgridId, columnState, filterModel, sortModel

AgGrid Events (Python → JS):

EventDescriptionKey Payload Fields
grid:page-responseRespond to page requestgridId, rows, totalRows, isLastPage
grid:update-dataUpdate row datadata, gridId?, strategy?
grid:update-columnsUpdate column definitionscolumnDefs, gridId?
grid:update-cellUpdate single cellrowId, colId, value, gridId?
grid:update-gridCombined update (data+columns+state)data?, columnDefs?, restoreState?, gridId?
grid:request-stateRequest grid stategridId?, context?
grid:restore-stateRestore saved statestate, gridId?
grid:reset-stateReset stategridId?, hard?
grid:update-themeChange grid themetheme, gridId?
grid:show-notificationShow grid notificationmessage, duration?, gridId?

System Events (JS → Python):

EventTriggerKey Payload Fields
pywry:readyWindow/widget initialized{}
pywry:resultData via window.pywry.result()any
pywry:content-requestRequest content (load/reload)widget_type, window_label, reason
pywry:theme-updateSystem theme changed (OS follow mode)theme: "light" | "dark"
pywry:disconnectWidget disconnected (inline mode){}

System Events (Python → JS):

EventDescriptionKey Payload Fields
pywry:update-themeUpdate themetheme
pywry:inject-cssInject CSScss, id?
pywry:remove-cssRemove injected CSSid
pywry:set-styleUpdate element stylesid?, selector?, styles
pywry:set-contentUpdate element contentid?, selector?, html?, text?
pywry:update-htmlReplace widget HTMLhtml
pywry:downloadTrigger file downloadcontent, filename, mimeType?
pywry:download-csvTrigger CSV download (widget mode)csv, filename
pywry:navigateNavigate to URLurl
pywry:alertShow toast notificationmessage, type?, title?, duration?
pywry:refreshRefresh window content{}

TradingView Events (JS → Python):

EventTriggerKey Payload Fields
tvchart:crosshairCrosshair movedchartId, time, price, seriesId?
tvchart:clickChart clickedchartId, time, price, seriesId?
tvchart:visible-range-changeUser panned / zoomedchartId, from, to
tvchart:data-settledAll series rendered (first frame settled)chartId, widget_type: "tvchart"
tvchart:datafeed-requestDrawing-surface / UDF datafeed callchartId, kind, payload
tvchart:datafeed-subscribeSubscribe to bar updateschartId, symbol, resolution, listenerGuid
tvchart:datafeed-unsubscribeUnsubscribe from bar updateschartId, listenerGuid
tvchart:drawing-changeUser added / edited / removed a drawingchartId, drawings
tvchart:layout-saveLayout savedchartId, name, layout
tvchart:settings-updateSettings panel changedchartId, settings

TradingView Events (Python → JS):

EventDescriptionKey Payload Fields
tvchart:update-dataReplace series datadata, chartId?, seriesId?
tvchart:append-barAppend or update the last barbar, chartId?, seriesId?
tvchart:datafeed-responseAnswer a datafeed requestchartId, kind, payload
tvchart:datafeed-bar-updatePush streaming bar to subscriberschartId, listenerGuid, bar
tvchart:apply-indicatorAdd / update an indicatorchartId, indicator, seriesId?
tvchart:set-visible-rangeProgrammatic range changechartId, from, to
tvchart:load-layoutRestore a saved layoutchartId, layout
tvchart:apply-settingsApply settings panel statechartId, settings

Chat Events (JS → Python):

EventTriggerKey Payload Fields
chat:user-messageUser sent a messagethreadId, message, content
chat:cancelUser cancelled a streaming responsethreadId
chat:new-threadUser requested a new thread{}
chat:switch-threadUser switched threadsthreadId
chat:permission-responseUser answered a permission promptrequestId, outcome
chat:config-setUser changed a settings itemoptionId, value
chat:mode-setUser switched agent modemodeId
chat:slash-commandUser ran a slash commandcommand, args
chat:context-requestUser opened a context sourcesourceId

Chat Events (Python → JS):

EventDescriptionKey Payload Fields
chat:agent-messageStreaming agent message deltathreadId, delta, messageId
chat:thinkingThinking / reasoning chunkthreadId, delta
chat:tool-callTool call start / update / completethreadId, toolCallId, status, input?, output?
chat:artifactAttach / update an artifactthreadId, artifact
chat:statusStatus string updatethreadId, status
chat:plan-updatePlan / todo list changethreadId, plan
chat:permission-requestPrompt the user to approve/denythreadId, requestId, prompt, options
chat:mode-updateAvailable modes / active modethreadId, modes, active
chat:config-updateAvailable config optionsthreadId, options
chat:commands-updateAvailable slash commandsthreadId, commands
chat:citationEmit a citationthreadId, citation

Note: Namespace events (auth:*, tray:*, menu:*, modal:*) follow the same pattern and are documented under their respective subsystems.

Toast Notifications (pywry:alert)

PyWry provides a unified toast notification system across all rendering paths.

Alert Types:

TypeBehaviorUse Case
infoAuto-dismiss 5sStatus updates
successAuto-dismiss 3sCompleted actions
warningPersist until clickedImportant notices
errorPersist until clickedErrors requiring acknowledgment
confirmBlocks UI until responseUser confirmation needed

AlertPayload Model:

class AlertPayload(BaseModel):
    message: str  # Required
    type: Literal["info", "success", "warning", "error", "confirm"] = "info"
    title: str | None = None
    duration: int | None = None  # Auto-dismiss ms
    callback_event: str | None = None  # Event on confirm/cancel
    position: Literal["top-right", "bottom-right", "bottom-left", "top-left"] = "top-right"

Usage:

# Convenience method
app.alert("Data loaded", alert_type="success", label=label)

# With emit
app.emit("pywry:alert", {"message": "Done", "type": "info"}, label)

# Confirm dialog with callback
app.alert("Delete item?", alert_type="confirm", callback_event="app:confirm-delete", label=label)

# Handle response
@app.on("app:confirm-delete")
def on_confirm(data, event_type, label):
    if data.get("confirmed"):
        # User clicked Confirm
        pass

Keyboard: Press Escape to dismiss all visible toasts.

JavaScript Bridge

// Send event to Python
window.pywry.emit("app:action", { key: "value" });

// Listen for Python events
window.pywry.on("app:update", function(data) {
    console.log("Received:", data);
});

// Access injected globals
window.__PYWRY_LABEL__        // Window label
window.json_data              // Data from HtmlContent.json_data
window.__PYWRY_PLOTLY_DIV__   // Plotly chart container
window.__PYWRY_GRID_API__     // AgGrid API

Native File Dialogs (Desktop Mode Only)

In native desktop windows, access Tauri's file system APIs:

// Save file dialog
const path = await window.__TAURI__.dialog.save({
    defaultPath: "export.csv",
    filters: [{ name: "CSV", extensions: ["csv"] }]
});
if (path) {
    await window.__TAURI__.fs.writeTextFile(path, csvContent);
}

// Open file dialog
const selected = await window.__TAURI__.dialog.open({
    multiple: false,
    filters: [{ name: "JSON", extensions: ["json"] }]
});
if (selected) {
    const content = await window.__TAURI__.fs.readTextFile(selected);
    window.pywry.emit("app:file-loaded", { path: selected, content });
}

// Confirmation dialog
const confirmed = await window.__TAURI__.dialog.confirm("Delete this item?", {
    title: "Confirm Delete",
    okLabel: "Delete",
    cancelLabel: "Cancel"
});

Note: File dialogs are only available in native desktop mode. For notebook/browser mode, use pywry:download event for downloads.


Toolbar System

Components

ComponentEmits
Button{ componentId, ...data }
Select{ value: str, componentId }
MultiSelect{ values: [str, ...], componentId }
TextInput{ value: str, componentId }
TextArea{ value: str, componentId }
SearchInput{ value: str, componentId }
SecretInput{ value, componentId, encoded } + {event}:reveal, {event}:copy
NumberInput{ value: number, componentId }
DateInput{ value: "YYYY-MM-DD", componentId }
SliderInput{ value: number, componentId }
RangeInput{ start: number, end: number, componentId }
Toggle{ value: bool, componentId }
Checkbox{ value: bool, componentId }
RadioGroup{ value: str, componentId }
TabGroup{ value: str, componentId }
DivContainer (no events)
Marquee{ value, componentId } when clickable
TickerItemHelper for Marquee (not a ToolbarItem)

Toolbar Positions

PyWry automatically creates nested flexbox wrappers based on which toolbars are present:

PositionDescription
"header"Full-width bar at very top (outermost)
"footer"Full-width bar at very bottom (outermost)
"left"Vertical bar on left, full height
"right"Vertical bar on right, full height
"top"Horizontal bar above content (inside left/right)
"bottom"Horizontal bar below content (inside left/right)
"inside"Floating overlay at top-right of content

Note: Layout wrappers (.pywry-wrapper-*) are created dynamically. If you only use top and bottom, no left/right wrappers are generated.

Example

from pywry import PyWry, Toolbar, Button, Select, Option

app = PyWry()
widget = None

def on_export(data, event_type, label):
    """Trigger a file download when export is clicked."""
    widget.emit("pywry:download", {
        "content": "name,score\nAlice,95\nBob,87",
        "filename": "export.csv",
        "mimeType": "text/csv"
    })

toolbar = Toolbar(
    position="top",
    items=[
        Button(label="Export", event="app:export", data={"format": "csv"}),
        Select(
            label="View:",
            event="view:change",
            options=[Option(label="Table", value="table"), Option(label="Chart", value="chart")],
            selected="table",
        ),
    ],
)

widget = app.show(
    '<h1 id="heading">Dashboard</h1>',
    toolbars=[toolbar],
    callbacks={"app:export": on_export}
)

Common Component Properties

All toolbar items share these properties:

PropertyTypeDefaultDescription
eventstr"toolbar:input"Event name in namespace:event-name format
component_idstrauto-generatedUnique ID (format: {type}-{uuid8})
labelstr""Label text displayed next to control
descriptionstr""Tooltip text on hover
disabledboolFalseWhether control is disabled
stylestr""Inline CSS styles

Component Parameters Quick Reference

Button:

Button(label="Save", event="app:save", data={"key": "val"}, variant="primary")
# Variants: primary|secondary|neutral|ghost|outline|danger|warning|icon

Select / MultiSelect:

Select(label="Theme:", event="theme:change", options=[Option(label="Dark", value="dark")], selected="dark")
MultiSelect(label="Cols:", event="cols:change", options=["A", "B", "C"], selected=["A"])
# Shorthand: strings auto-convert to Option(label=s, value=s)

TextInput / TextArea / SearchInput:

TextInput(label="Name:", event="form:name", placeholder="Enter name", debounce_ms=300)
TextArea(label="Notes:", event="form:notes", rows=4, resizable=True)
SearchInput(label="Search:", event="search:query", placeholder="Type to search...")

SecretInput:

SecretInput(label="API Key:", event="secret:key", placeholder="Enter key")
# Emits: {event} with {value, encoded}, plus {event}:reveal and {event}:copy

NumberInput:

NumberInput(label="Qty:", event="form:qty", min_value=0, max_value=100, step=1, value=10)

DateInput:

DateInput(label="Date:", event="form:date", value="2024-01-01", min_date="2020-01-01")

SliderInput / RangeInput:

SliderInput(label="Volume:", event="audio:volume", min_value=0, max_value=100, value=50, show_value=True)
RangeInput(label="Price:", event="filter:price", min_value=0, max_value=1000, start=100, end=500)

Toggle / Checkbox:

Toggle(label="Dark Mode:", event="theme:toggle", value=True)
Checkbox(label="Accept Terms", event="form:terms", value=False)

RadioGroup / TabGroup:

RadioGroup(label="Size:", event="form:size", options=["S", "M", "L"], selected="M", layout="horizontal")
TabGroup(event="view:tab", options=[Option(label="Chart", value="chart"), Option(label="Table", value="table")])

Div (Container):

Div(children=[Button(...), Select(...)], class_name="my-group", style="gap: 8px;")

Marquee / TickerItem:

Marquee(
    event="ticker:click",
    items=[
        TickerItem(ticker="AAPL", text="$150.25", styles={"color": "green"}),
        TickerItem(ticker="MSFT", text="$380.00"),
    ],
    speed=50,
    separator=" | ",
)
# Update dynamically via toolbar:marquee-set-item event

Toolbar Container Options

Toolbar(
    position="top",              # header|footer|left|right|top|bottom|inside
    items=[...],
    component_id="main-toolbar", # For state management
    collapsible=False,           # Allow collapse/expand
    collapsed=False,             # Initial collapsed state
    resizable=False,             # Allow drag-to-resize
    min_width=None,              # Min size for resizable
    max_width=None,              # Max size for resizable
)

Toolbar State Management

# Request current toolbar state
app.emit("toolbar:request-state", {"context": "save"}, label)

# Handle state response
def on_state(data, event_type, label):
    values = data["components"]  # {componentId: value, ...}
app.on("toolbar:state-response", on_state)

# Set single component value
app.emit("toolbar:set-value", {"componentId": "my-select", "value": "option2"}, label)

# Set value with attributes (label, disabled, etc.)
app.emit("toolbar:set-value", {
    "componentId": "submit-btn",
    "label": "Saving...",
    "disabled": True
}, label)

# Update dropdown options dynamically
app.emit("toolbar:set-value", {
    "componentId": "type-select",
    "value": "bar",
    "options": [{"label": "Bar", "value": "bar"}, {"label": "Line", "value": "line"}]
}, label)

# Or use widget method (recommended)
widget.set_toolbar_value("submit-btn", label="Saving...", disabled=True)
widget.set_toolbar_value("type-select", value="bar", options=[...])

# Set multiple values
app.emit("toolbar:set-values", {"values": {"select-1": "A", "toggle-1": True}}, label)

Configuration System

Priority Order (highest last)

  1. Built-in defaults
  2. pyproject.toml [tool.pywry] section
  3. ./pywry.toml
  4. User config (~/.config/pywry/config.toml)
  5. Environment variables (PYWRY_*)

Configuration Sections

SectionEnv PrefixDescription
windowPYWRY_WINDOW__Default window properties
themePYWRY_THEME__Custom CSS file path
serverPYWRY_SERVER__Inline server settings (host, port, SSL, CORS)
hot_reloadPYWRY_HOT_RELOAD__Hot reload behavior
cspPYWRY_CSP__Content Security Policy
logPYWRY_LOG__Logging configuration
timeoutPYWRY_TIMEOUT__Timeout values
assetPYWRY_ASSET__Library versions
deployPYWRY_DEPLOY__Deploy mode and state backend

Tauri Plugins

PyWry bundles the full Tauri plugin set via pytauri_wheel. By default, only dialog and fs are enabled. Developers can enable additional plugins through configuration — no Rust compilation required.

Enabling Plugins

# Via PyWrySettings constructor
from pywry import PyWry
from pywry.config import PyWrySettings

settings = PyWrySettings(tauri_plugins=["dialog", "fs", "notification", "http"])
app = PyWry(settings=settings)
# Via pywry.toml or pyproject.toml [tool.pywry]
tauri_plugins = ["dialog", "fs", "notification", "http"]
extra_capabilities = ["shell:allow-execute"]
# Via environment variables
export PYWRY_TAURI_PLUGINS="dialog,fs,notification,http"
export PYWRY_EXTRA_CAPABILITIES="shell:allow-execute"

Available Plugins

Plugin NameJS APIDescription
autostart-Launch app on system startup
clipboard_managerwindow.__TAURI__.clipboardManagerRead/write system clipboard
deep_link-Handle custom URL schemes
dialogwindow.__TAURI__.dialogNative file/message dialogs
fswindow.__TAURI__.fsFilesystem read/write
global_shortcutwindow.__TAURI__.globalShortcutSystem-wide keyboard shortcuts
httpwindow.__TAURI__.httpHTTP client from webview
notificationwindow.__TAURI__.notificationDesktop notifications
openerwindow.__TAURI__.openerOpen URLs/files with default app
oswindow.__TAURI__.osOS info (platform, arch, etc.)
persisted_scope-Persist filesystem scopes
positionerwindow.__TAURI__.positionerPosition windows on screen
processwindow.__TAURI__.processProcess management
shellwindow.__TAURI__.shellExecute system commands
single_instance-Prevent duplicate app instances
updaterwindow.__TAURI__.updaterAuto-update support
uploadwindow.__TAURI__.uploadFile upload with progress
websocketwindow.__TAURI__.websocketWebSocket client
window_state-Persist/restore window size and position

How It Works

  1. PyWrySettings.tauri_plugins holds the list of plugin names to activate
  2. The parent process passes this list to the subprocess via PYWRY_TAURI_PLUGINS env var
  3. In __main__.py, _load_plugins() dynamically imports each pytauri_plugins.<name> module and calls .init()
  4. The capabilities/default.toml pre-grants <plugin>:default permissions for every bundled plugin (unused permissions are harmless)
  5. For fine-grained permission control, use extra_capabilities to add specific permission strings (e.g., shell:allow-execute)

Each plugin has a PLUGIN_* compile-time feature flag in pytauri_plugins that is checked before initialization. If a plugin is not compiled into the bundled pytauri_wheel, a clear RuntimeError is raised.

Example pywry.toml

[window]
title = "My Application"
width = 1280
height = 720
devtools = false

[hot_reload]
enabled = true
debounce_ms = 100

[log]
level = "WARNING"

[deploy]
state_backend = "redis"
redis_url = "redis://localhost:6379/0"
redis_prefix = "pywry:"

Server Settings (for Notebook/Browser Mode)

SettingEnv VarDefaultDescription
hostPYWRY_SERVER__HOST127.0.0.1Server bind address
portPYWRY_SERVER__PORT8765Server port
ssl_certfilePYWRY_SERVER__SSL_CERTFILENoneSSL certificate path
ssl_keyfilePYWRY_SERVER__SSL_KEYFILENoneSSL key path
cors_originsPYWRY_SERVER__CORS_ORIGINS["*"]Allowed CORS origins
workersPYWRY_SERVER__WORKERS1Number of workers
reloadPYWRY_SERVER__RELOADFalseEnable auto-reload (dev)
# Example: Production server config
[server]
host = "0.0.0.0"
port = 443
ssl_certfile = "/path/to/cert.pem"
ssl_keyfile = "/path/to/key.pem"
cors_origins = ["https://myapp.com"]

Deploy Mode & Scaling

Deploy mode enables horizontal scaling for multi-worker deployments (e.g., behind a load balancer).

When to Use Deploy Mode

ScenarioDeploy ModeBackend
Single process (development, notebooks)Not neededMemory (default)
Multiple workers (gunicorn, uvicorn)RequiredRedis
Load-balanced deploymentRequiredRedis
Kubernetes / Docker SwarmRequiredRedis

State Stores

StorePurposeKey Methods
WidgetStoreWidget metadata persistenceget(), set(), delete(), list_widgets()
EventBusCross-worker event routingpublish(), subscribe()
ConnectionRouterWebSocket connection trackingregister(), unregister(), get_worker()
SessionStoreUser session managementget_session(), set_session(), delete_session()

Factory Functions

from pywry.state import (
    get_widget_store,      # Returns WidgetStore (memory or redis)
    get_event_bus,         # Returns EventBus (memory or redis)
    get_connection_router, # Returns ConnectionRouter
    get_session_store,     # Returns SessionStore
    is_deploy_mode,        # Returns True if state_backend != "memory"
    get_worker_id,         # Returns unique worker identifier
)

Environment Variables

# Enable Redis backend
PYWRY_DEPLOY__STATE_BACKEND=redis
PYWRY_DEPLOY__REDIS_URL=redis://localhost:6379/0
PYWRY_DEPLOY__REDIS_PREFIX=pywry:

# TTL settings
PYWRY_DEPLOY__WIDGET_TTL=86400      # 24 hours
PYWRY_DEPLOY__CONNECTION_TTL=300    # 5 minutes

# Authentication (optional)
PYWRY_DEPLOY__ENABLE_AUTH=true
PYWRY_DEPLOY__AUTH_SECRET=your-secret-key
PYWRY_DEPLOY__RBAC_ENABLED=true
PYWRY_DEPLOY__DEFAULT_ROLE=viewer

DeploySettings Reference

SettingTypeDefaultDescription
state_backendStateBackendmemory"memory" or "redis"
redis_urlstrredis://localhost:6379/0Redis connection URL
redis_prefixstrpywry:Key prefix for Redis keys
widget_ttlint86400Widget data TTL (seconds)
connection_ttlint300Connection registration TTL
auto_cleanupboolTrueAuto-cleanup expired entries
enable_authboolFalseEnable JWT authentication
auth_secretstr | NoneNoneJWT signing secret
rbac_enabledboolFalseEnable role-based access
default_rolestrviewerDefault user role

Authentication & OAuth2

PyWry includes a full OAuth2 authentication system that works in both native window mode and deploy mode.

Quick Start (Native Mode)

from pywry import PyWry

app = PyWry()

# Login with Google (configure via environment variables)
# PYWRY_OAUTH2__PROVIDER=google
# PYWRY_OAUTH2__CLIENT_ID=your-client-id
# PYWRY_OAUTH2__CLIENT_SECRET=your-secret
result = app.login()

if result.success:
    print(f"Logged in! Tokens: {result.tokens.token_type}")
    app.show("<h1>Welcome!</h1>")
    app.block()

Quick Start (Deploy Mode)

PYWRY_DEPLOY__AUTH_ENABLED=true
PYWRY_DEPLOY__STATE_BACKEND=redis
PYWRY_OAUTH2__PROVIDER=github
PYWRY_OAUTH2__CLIENT_ID=your-client-id
PYWRY_OAUTH2__CLIENT_SECRET=your-secret

Deploy mode automatically mounts /auth/login, /auth/callback, /auth/logout, /auth/status routes.

Architecture

ComponentFilePurpose
OAuthProviderauth/providers.pyABC for OAuth2 providers (Google, GitHub, Microsoft, OIDC, custom)
PKCEChallengeauth/pkce.pyPKCE code challenge generation (RFC 7636)
TokenStoreauth/token_store.pyABC for token persistence (Memory, Keyring, Redis)
OAuthCallbackServerauth/callback_server.pyEphemeral localhost HTTP server for native redirect capture
AuthFlowManagerauth/flow.pyOrchestrates the complete OAuth2 flow
SessionManagerauth/session.pyToken lifecycle with automatic background refresh
deploy_routesauth/deploy_routes.pyFastAPI /auth/* routes for production deployments

OAuth2Settings

SettingTypeDefaultDescription
providerstr"custom"google, github, microsoft, oidc, or custom
client_idstr""OAuth2 client ID
client_secretstr""Client secret (empty for PKCE public clients)
scopesstr"openid email profile"Space-separated scopes
use_pkceboolTrueEnable PKCE for public clients
token_store_backendstr"memory"memory, keyring, or redis
auth_timeout_secondsfloat120.0Max wait for OAuth callback
refresh_buffer_secondsint60Pre-expiry refresh margin

Frontend Integration

When authenticated, window.__PYWRY_AUTH__ contains { user_id, roles, token_type }. Use window.pywry.auth.isAuthenticated(), .getState(), .login(), .logout(), .onAuthStateChange(cb).


Chat Widget

PyWry ships a streaming chat widget with a pluggable provider interface modelled on the Agent Client Protocol (ACP) session lifecycle: initialize → new_session → prompt loop → cancel.

Providers

ProviderExtraDescription
OpenAIProviderpywry[openai]OpenAI Responses / Chat Completions SDK
AnthropicProviderpywry[anthropic]Anthropic Messages SDK (streaming)
MagenticProviderpywry[magentic]magentic — any magentic-supported LLM
CallbackProvider(base)Wraps a sync / async Python callback
StdioProviderpywry[acp]Runs any ACP agent as a subprocess
DeepagentProviderpywry[deepagent]LangChain Deep Agents with built-in MCP adapters and ACP bridging

Select a provider by name with the factory:

from pywry.chat import get_provider

provider = get_provider("anthropic", model="claude-opus-4-7", api_key="...")

ChatManager

from pywry import PyWry, ChatManager, build_chat_html

app = PyWry()
chat = ChatManager(provider=provider, app=app)
html = build_chat_html()          # chat UI bootstrap
handle = app.show(html, callbacks=chat.callbacks())
app.block()

ChatManager owns:

  • Threads — persisted via the configured state backend; switched with chat:switch-thread.
  • Artifacts — CodeArtifact, HtmlArtifact, ImageArtifact, JsonArtifact, MarkdownArtifact, PlotlyArtifact, TableArtifact, TradingViewArtifact. Emitted via chat:artifact.
  • Plan / todo updates — PlanEntry list streamed via chat:plan-update.
  • Permissions — chat:permission-request prompts the UI; the user answer comes back on chat:permission-response.
  • Modes / config / commands — chat:mode-update, chat:config-update, chat:commands-update surface whatever the underlying provider advertises.
  • Context sources — register file / URL / custom sources that the user can attach to a prompt.

SettingsItem

Settings appear in the chat settings panel and are round-tripped via chat:config-update / chat:config-set. They support text / select / toggle / secret inputs, validation, and per-option help.


TradingView Charts

pywry.tvchart wraps TradingView Lightweight Charts with a full drawing surface, pluggable datafeed API, UDF adapter, streaming bar updates, compare overlays, compare-derivative indicators, savable layouts, and a themeable settings panel.

Quick Start

import pandas as pd
from pywry import PyWry, TVChartConfig

app = PyWry()
df = pd.DataFrame(...)  # columns: time / open / high / low / close / volume
app.show_tvchart(df, title="AAPL — Daily")
app.block()

Datafeed API

Implement DatafeedProvider to drive the chart from a quote server or any async source:

from pywry.tvchart import (
    DatafeedProvider,
    TVChartDatafeedHistoryRequest,
    TVChartDatafeedHistoryResponse,
    TVChartDatafeedResolveRequest,
    TVChartDatafeedResolveResponse,
)

class MyDatafeed(DatafeedProvider):
    async def resolve_symbol(self, req: TVChartDatafeedResolveRequest) -> TVChartDatafeedResolveResponse:
        ...
    async def get_history(self, req: TVChartDatafeedHistoryRequest) -> TVChartDatafeedHistoryResponse:
        ...
    # search_symbols, get_marks, get_timescale_marks, get_server_time, subscribe_bars, unsubscribe_bars

app.show_tvchart(datafeed=MyDatafeed(), symbol="AAPL", resolution="1D")

UDFAdapter

Point the chart at any TradingView UDF-compatible HTTP endpoint:

from pywry.tvchart import UDFAdapter

adapter = UDFAdapter(base_url="https://demo_feed.tradingview.com")
app.show_tvchart(datafeed=adapter, symbol="AAPL", resolution="1D")

Indicators, Compare, Drawings

  • Indicators — overlay any Lightweight Charts indicator; compare-derivative indicators (Spread, Ratio, Sum, Product, Correlation) are computed across overlays.
  • Drawings — trendlines, fib tools, text annotations, price notes, and brushes. All round-trip through tvchart:drawing-change and are persisted with layouts.
  • Layouts — save the current chart (series, overlays, indicators, drawings, settings) with tvchart:layout-save; restore with tvchart:load-layout.

TVChartStateMixin

The Python-side chart state surface is exposed via TVChartStateMixin, which is mixed into PyWry, PyWryTVChartWidget, and any user-defined widget that wants chart control.


MCP Server

PyWry ships an MCP server that exposes widget management, chart / grid / tvchart control, events, chat driving, auth, and skills to any MCP client (Claude Desktop, Claude Code, Cursor, …).

Launching

pip install 'pywry[mcp]'

pywry mcp --transport stdio                   # default, for Claude Desktop / Claude Code
pywry mcp --transport http --host 0.0.0.0     # HTTP transport
pywry mcp install                             # write client config (interactive)

Skills

Each skill bundles tools + prompts + reference docs for a coherent area. Current skills:

  • authentication — OAuth2 flows and token management
  • autonomous_building — long-running "build this dashboard" loops
  • chat — low-level chat widget control
  • chat_agent — drive a running chat session (select mode, send a prompt, observe)
  • component_reference — Pydantic toolbar components with live previews
  • css_selectors — --pywry-* variables and selector crib sheet
  • data_visualization — Plotly / AgGrid / TradingView recipes
  • deploy — deploy-mode scaling and state backend choices
  • events — Python ↔ JS event catalogue
  • forms_and_inputs — toolbar-driven form recipes
  • iframe — notebook / browser / inline quirks
  • interactive_buttons — button-centric patterns
  • jupyter — anywidget + iframe behaviour in notebooks
  • modals — Modal toolbar component recipes
  • native — native-only features (menus, tray, dialogs, WindowProxy)
  • styling — CSS variables, theming, hot reload
  • tvchart — TradingView datafeed, UDF, drawings, indicators, layouts

Tools

Tools are grouped under widget_*, component_*, chart_*, grid_*, tvchart_*, chat_*, auth_*, events_*, and docs_*. The low-level send_event tool dispatches any namespaced event directly.


State Backends

PyWry's state layer powers deploy mode, notebook / browser mode, and any multi-window / multi-worker setup. The same WidgetStore / EventBus / ConnectionRouter / SessionStore ABCs are implemented by every backend.

BackendUse caseNotes
memory (default)Single-process, development, notebooksNo external deps
fileSingle-node persistence without a DBJSON on disk
sqliteSingle-node with at-rest encryptionpywry[sqlite] (SQLCipher); keyed by PYWRY_DEPLOY__SQLITE_KEY
redisMulti-worker / horizontally scaledredis >= 7.1.0 (client ships in base install)

Select a backend via PYWRY_DEPLOY__STATE_BACKEND, pywry.toml [deploy], or DeploySettings(state_backend=...).


Key Classes Reference

Core Classes

ClassFileResponsibility
PyWryapp.pyMain user-facing API
CallbackRegistrycallbacks.pySingleton managing event callbacks
HotReloadManagerhot_reload.pyFile watching and CSS injection
AssetLoaderasset_loader.pyCSS/JS file loading with caching

NativeWindowHandle (Desktop Mode)

In native desktop mode, show() returns a NativeWindowHandle that provides full window control:

Core Methods:

handle = app.show("<h1>Hello</h1>", title="My Window")

# Event communication
handle.emit("app:update", {"key": "value"})   # Send event to JS
handle.on("app:click", callback)              # Register event handler
handle.eval_js("console.log('Hello')")        # Execute JavaScript

# Content
handle.update("<h1>New Content</h1>")         # Replace HTML content

# Window visibility
handle.close()                                 # Close and destroy
handle.hide()                                  # Hide (keep alive)
handle.show_window()                          # Show hidden window

# Window properties (via proxy)
handle.set_title("New Title")
handle.set_size(1280, 720)
handle.set_min_size(400, 300)
handle.set_max_size(1920, 1080)
handle.set_always_on_top(True)
handle.set_decorations(False)                 # Remove title bar
handle.set_background_color(30, 30, 30)       # RGBA

# Window actions
handle.maximize()
handle.minimize()
handle.center()

# Developer tools
handle.open_devtools()
handle.close_devtools()
handle.set_zoom(1.5)                          # 150% zoom

Properties:

handle.label        # str: Window identifier
handle.resources    # WindowResources: Metadata (content, config, created_at, etc.)
handle.proxy        # WindowProxy: Full WebviewWindow API access

WindowProxy (Advanced):

proxy = handle.proxy

# State queries
proxy.is_maximized      # bool
proxy.is_minimized      # bool
proxy.is_fullscreen     # bool
proxy.is_focused        # bool
proxy.is_decorated      # bool
proxy.is_resizable      # bool
proxy.is_visible        # bool

# Position & Size
proxy.inner_size        # PhysicalSize(width, height)
proxy.outer_size        # PhysicalSize(width, height)
proxy.inner_position    # PhysicalPosition(x, y)
proxy.outer_position    # PhysicalPosition(x, y)
proxy.scale_factor      # float (e.g., 1.0, 1.5, 2.0 for HiDPI)

# Monitor info
proxy.current_monitor   # Monitor or None
proxy.primary_monitor   # Monitor or None
proxy.available_monitors  # list[Monitor]

# Actions
proxy.set_fullscreen(True)
proxy.set_resizable(False)
proxy.set_visible_on_all_workspaces(True)
proxy.navigate("https://example.com")
proxy.reload()

Widget Classes

ClassFileResponsibility
BaseWidgetwidget_protocol.pyProtocol defining unified widget API
NativeWindowHandlewidget_protocol.pyHandle for native windows implementing BaseWidget
InlineWidgetinline.pyIFrame-based widget (notebook fallback)
PyWryWidgetwidget.pyBase anywidget
PyWryPlotlyWidgetwidget.pyPlotly-specific anywidget
PyWryAgGridWidgetwidget.pyAgGrid anywidget

Window Modes

ClassFileBehavior
NewWindowModewindow_manager/modes/new_window.pyNew window per show()
SingleWindowModewindow_manager/modes/single_window.pyReuses one window
MultiWindowModewindow_manager/modes/multi_window.pyMultiple windows
BrowserModewindow_manager/modes/browser.pyOpens in browser

Configuration Classes

ClassFilePurpose
PyWrySettingsconfig.pyRoot settings
SecuritySettingsconfig.pyCSP configuration
ServerSettingsconfig.pyFastAPI server settings
WindowSettingsconfig.pyDefault window properties
DeploySettingsconfig.pyDeploy mode and state backend settings
WindowConfigmodels.pyWindow properties model
HtmlContentmodels.pyContent with files/scripts

State Classes (Deploy Mode)

ClassFilePurpose
WidgetStorestate/memory.py, state/redis.pyWidget metadata persistence
EventBusstate/memory.py, state/redis.pyCross-worker event routing
ConnectionRouterstate/memory.py, state/redis.pyWebSocket connection tracking
SessionStorestate/memory.py, state/redis.pyUser session management
WidgetDatastate/types.pyWidget metadata model
EventMessagestate/types.pyEvent payload model
ConnectionInfostate/types.pyConnection metadata model
UserSessionstate/types.pySession data model

Enums

EnumFileValues
ThemeModemodels.pyLIGHT, DARK, SYSTEM
WindowModemodels.pyNEW_WINDOW, SINGLE_WINDOW, MULTI_WINDOW, NOTEBOOK, BROWSER
NotebookEnvironmentnotebook.pyNONE, COLAB, KAGGLE, AZURE, VSCODE, JUPYTERLAB, etc.
StateBackendstate/types.pyMEMORY, REDIS

Design Patterns

Singleton Pattern

Used for global state managers:

class CallbackRegistry:
    _instance: CallbackRegistry | None = None

    @classmethod
    def get_instance(cls) -> "CallbackRegistry":
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

Singletons: CallbackRegistry, _ServerState (inline.py)

Strategy Pattern

Window modes implement WindowModeBase interface:

class WindowModeBase(ABC):
    @abstractmethod
    def show(self, content, config, callbacks) -> str: ...

Mixin Pattern

State management via composable mixins:

class PyWry(GridStateMixin, PlotlyStateMixin, ToolbarStateMixin):
    def emit(self, event_type, data, label=None): ...

class PyWryAgGridWidget(GridStateMixin, ToolbarStateMixin, PyWryWidget):
    def emit(self, event_type, data): ...

Pydantic Models

All configuration uses Pydantic v2:

from pydantic import BaseModel, Field

class WindowConfig(BaseModel):
    title: str = "PyWry"
    width: int = Field(default=1280, ge=200)
    height: int = Field(default=720, ge=150)

ID Hierarchy

PyWry uses hierarchical IDs for event routing:

ID LevelScopeFormat Example
labelWindow/Widget"pywry-abc123"
chartIdPlotly chart"chart_def456"
gridIdAgGrid"grid_ghi789"
componentIdToolbar item"button-xyz123"

Events include widget_type for identification:

  • Plotly events: widget_type: "chart"
  • Grid events: widget_type: "grid"

CSS Theming

PyWry is themed through --pywry-* CSS variables, with component-ID targeting for precise styling. The full variable reference lives in the CSS docs.

Theme Classes

SelectorDescription
html.dark / html.lightDocument root theme (native windows)
.pywry-theme-dark / .pywry-theme-lightWidget container theme (notebooks)
html.pywry-nativeAdded to <html> in native window mode

Dynamic Styling via Events

# Update element styles from Python
app.emit("pywry:set-style", {"id": "my-btn", "styles": {"backgroundColor": "green"}}, label)

# Inject CSS dynamically
app.emit("pywry:inject-css", {"css": "#title { color: blue; }", "id": "custom-styles"}, label)

# Remove injected CSS
app.emit("pywry:remove-css", {"id": "custom-styles"}, label)

Component ID Targeting

Every toolbar component has a component_id (default: {type}-{8-char-random}):

Button(label="Save", event="app:save", component_id="save-btn")  # Custom ID

Target in CSS: #save-btn { background: green; } or [data-event="app:save"] { ... }

Key CSS Variables

:root {
  --pywry-bg-primary: #212124;
  --pywry-bg-secondary: rgba(21, 21, 24, 1);
  --pywry-bg-tertiary: rgba(31, 30, 35, 1);
  --pywry-text-primary: #ebebed;
  --pywry-text-secondary: #a0a0a0;
  --pywry-accent: #0078d4;
  --pywry-border-color: #333;
  --pywry-radius: 4px;
}

Layout Classes

ClassPurpose
.pywry-widgetRoot widget container
.pywry-contentContent flex container
.pywry-toolbarToolbar container
.pywry-plotlyPlotly container
.pywry-gridAgGrid container

Toast Notification Classes

ClassPurpose
.pywry-toast-containerToast stack container (positioned absolutely)
.pywry-toast-container--top-rightTop-right position (default)
.pywry-toast-container--blockingElevated z-index for confirm
.pywry-toastBase toast styling
.pywry-toast--info/success/warning/error/confirmType variants
.pywry-toast__iconToast icon
.pywry-toast__titleToast title
.pywry-toast__messageToast message
.pywry-toast__closeClose button
.pywry-toast__buttonsConfirm dialog buttons
.pywry-toast__btn--cancel/--confirmButton variants
.pywry-toast-overlayBlocking overlay for confirm
.pywry-toast-overlay--visibleVisible overlay state

Toast CSS Variables:

.pywry-toast {
  --pywry-toast-bg: rgba(30, 30, 30, 0.95);
  --pywry-toast-color: #ffffff;
  --pywry-toast-accent: #0ea5e9;  /* Left border color */
}

Development

Setup

git clone https://github.com/deeleeramone/PyWry.git
cd PyWry/pywry
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
uv sync --all-extras --group dev

Testing

pytest tests/ -v
pytest tests/ --cov=pywry --cov-report=html

Linting

ruff check pywry/ tests/
ruff format pywry/ tests/
ty check pywry/

Environment Variables for Testing

PYWRY_HEADLESS=1  # Force InlineWidget, skip browser.open()
PYWRY_LOG__LEVEL=DEBUG  # Enable debug logging

Quick Examples

REPL vs Script Usage

In a REPL (IPython, Jupyter, Python shell): Windows stay open because the Python process keeps running. You can interact with handles directly.

# IPython / Python REPL
>>> from pywry import PyWry
>>> app = PyWry()
>>> handle = app.show("<h1>Hello</h1>")  # Window opens, stays open
>>> handle.set_title("Updated Title")    # Interact with window
>>> handle.emit("app:update", {"x": 1})  # Send events
>>> handle.close()                        # Close when done

In a script: The script exits immediately after show(), closing the window. Use app.block() to keep it open:

# my_script.py
from pywry import PyWry

app = PyWry()
handle = app.show("<h1>Hello</h1>")

# Without this, the script exits and window closes immediately
app.block()  # Blocks until user closes the window

With callbacks (scripts): Use block() after setting up handlers:

# interactive_script.py
from pywry import PyWry, Toolbar, Button

app = PyWry()

def on_click(data, event_type, label):
    print(f"Button clicked: {data}")
    app.close(label)  # Close window to unblock

handle = app.show(
    "<h1>Click the button</h1>",
    toolbars=[Toolbar(position="top", items=[Button(label="Click Me", event="app:click")])],
    callbacks={"app:click": on_click}
)

app.block()  # Wait for window to close
print("Window closed, script continues...")

Basic Window

from pywry import PyWry, WindowMode, ThemeMode

app = PyWry(mode=WindowMode.SINGLE_WINDOW, theme=ThemeMode.DARK)
app.show("<h1>Hello World</h1>")

Plotly Chart with Events

from pywry import PyWry
import plotly.express as px

app = PyWry()
widget = None

def on_click(data, event_type, label):
    """Update chart title to show clicked point coordinates."""
    point = data["points"][0]
    widget.emit("plotly:update-layout", {
        "layout": {"title": f"Clicked: ({point['x']}, {point['y']})"}
    })

fig = px.scatter(x=[1, 2, 3], y=[4, 5, 6])
widget = app.show_plotly(fig, title="Click a point", callbacks={"plotly:click": on_click})

DataFrame with Toolbar

import pandas as pd
from pywry import PyWry, Toolbar, Button

app = PyWry()
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
widget = None

def on_export(data, event_type, label):
    """Download the DataFrame as CSV."""
    widget.emit("pywry:download", {
        "content": df.to_csv(index=False),
        "filename": "data.csv",
        "mimeType": "text/csv"
    })

toolbar = Toolbar(position="top", items=[Button(label="Export", event="app:export")])
widget = app.show_dataframe(df, toolbars=[toolbar], callbacks={"app:export": on_export})

Browser Mode (Server)

from pywry import PyWry, WindowMode
from pywry.inline import block

app = PyWry(mode=WindowMode.BROWSER)
widget = app.show_plotly(fig)
print(f"Open: {widget.url}")
block()  # Keep server running

CLI Commands

# Show current configuration
pywry config --show

# Export as TOML
pywry config --toml

# Initialize pywry.toml
pywry init

Debugging

# Enable debug logging
import pywry.log
pywry.log.enable_debug()

# Or via environment
# PYWRY_LOG__LEVEL=DEBUG

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.