К основному содержанию
скилл CX Codex

understanding-streamlit-architecture — скилл для Claude Code

Скилл understanding-streamlit-architecture для Claude Code объясняет внутреннее устройство Streamlit. Помогает разбирать сквозные ошибки, модель перезапуска скрипта и обмен через WebSocket.

Apache-2.0 123 установок ★ 46 474 обновлён 2026-10-25

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add streamlit/streamlit --skill understanding-streamlit-architecture -a claude-code
Открыть на GitHub

Что делает understanding-streamlit-architecture

Скилл описывает внутреннюю архитектуру Streamlit: взаимодействие Python-бэкенда с фронтендом на React через двунаправленный протокол WebSocket и бинарные сообщения Protobuf (ForwardMsg и BackMsg). Внутри систематизированы понятия фреймворка, включая DeltaGenerator, дерево элементов BlockNode, управление состоянием в st.session_state и работу менеджера WidgetStateManager.

Текст разбирает модель выполнения пользовательского кода. Скрипт выполняется сверху вниз при каждом перезапуске, а колбэки on_change и on_click запускаются строго до основного тела страницы. Декораторы @st.fragment изолируют перезапуски внутри отдельных блоков UI. Команды управления потоком st.rerun(), st.stop() и st.switch_page() прерывают выполнение через вызов исключений.

Каждая вкладка браузера изолируется в собственный объект AppSession со своим состоянием. Общего состояния между сессиями нет.

Какие задачи решает

  • разобрать сквозные ошибки между бэкендом на Python и фронтендом на React
  • отследить путь сообщений ForwardMsg и BackMsg через WebSocket
  • понять логику частичных перезапусков внутри @st.fragment
  • спланировать доработки ядра DeltaGenerator и дерева элементов

Примеры запросов агенту

  • Объясни, как данные виджета передаются от React в SessionState через BackMsg
  • Почему вызов st.rerun прерывает выполнение пользовательского кода через исключение?
  • Как устроена изоляция сессий AppSession между разными вкладками браузера?

Как установить understanding-streamlit-architecture

1Через Skills CLI (Vercel)

npx skills add streamlit/streamlit --skill understanding-streamlit-architecture -a claude-code

2Вручную: положить файлы

~/.claude/skills/understanding-streamlit-architecture/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/understanding-streamlit-architecture/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об understanding-streamlit-architecture

Как установить understanding-streamlit-architecture в Claude Code?

Выполните команду npx skills add streamlit/streamlit --skill understanding-streamlit-architecture -a claude-code. Файл навыка будет сохранён в ~/.claude/skills/understanding-streamlit-architecture/SKILL.md.

Что объясняет скилл understanding-streamlit-architecture?

Он даёт карту внутреннего устройства Streamlit: сетевой протокол WebSocket, сериализацию Protobuf, модель повторных запусков скрипта и связку между DeltaGenerator и React-компонентами.

Что запускает повторное выполнение скрипта в Streamlit?

Перезапуск вызывают действия пользователя с виджетами, изменение исходного файла через файловый наблюдатель, вызов st.rerun() или таймер фрагмента @st.fragment(run_every=...).

Исходный текст

SKILL.md · Apache-2.0
---
name: understanding-streamlit-architecture
description: Explains Streamlit's internal architecture including backend runtime, frontend rendering, and WebSocket communication. Use when debugging cross-layer issues, understanding how features work end-to-end, planning architectural changes, or onboarding to the codebase. Covers ForwardMsg/BackMsg protocol, script rerun model, element tree, widget state management, and the delta-path rules shared by the frontend and the agent snapshot.
---

# Understanding Streamlit architecture

Streamlit is a client-server application with bidirectional WebSocket communication using Protocol Buffers.
Use this file as a quick mental model and navigation index; use `references/backend.md`, `references/frontend.md`, and `references/communication.md` for implementation details.

## Concepts glossary

| Concept | Description | Key files |
|---------|-------------|-----------|
| **Command** | Any function exposed in Streamlit's public API (`st.*` namespace). Commands can create elements/widgets, control execution flow, or configure app behavior. | `lib/streamlit/delta_generator.py`, `lib/streamlit/elements/`, `lib/streamlit/commands/` |
| **Element** | Umbrella term for all UI components in Streamlit: widgets, containers, and display elements. Represented in `Element.proto` as a `oneof` union of ~50+ types. | `proto/streamlit/proto/Element.proto`, `lib/streamlit/elements/` |
| **Widget** | Interactive element (button, slider, text_input) that typically triggers a rerun on user interaction. Value accessible via return value or `st.session_state`. Widgets that support `on_change="ignore"` update in the browser without rerunning until something else does. Some elements become widgets conditionally (e.g., dataframe/chart with `on_select`). | `lib/streamlit/elements/widgets/`, `frontend/lib/src/components/widgets/` |
| **Display Element** | Non-interactive element (text, markdown, image, chart) that renders content without triggering reruns by itself. | `lib/streamlit/elements/`, `frontend/lib/src/components/elements/` |
| **Container** | Layout block that groups elements spatially (sidebar, columns, expander, tabs, form). Represented as `BlockNode` in the element tree. | `lib/streamlit/elements/layouts.py`, `Block.proto` |
| **DeltaGenerator** | The `st` object; API entry point that queues UI deltas. Uses mixin pattern to compose all `st.*` commands. | `lib/streamlit/delta_generator.py` |
| **Session State** | Per-session dictionary (`st.session_state`) persisting data across reruns. Stores widget values and user variables. | `lib/streamlit/runtime/state/session_state.py` |
| **Rerun** | Re-execution of the user script for the current page. Triggered by widget interactions, `st.rerun()`, file changes, or fragment timers. Rebuilds the element tree while preserving session state. | `lib/streamlit/runtime/scriptrunner/script_runner.py`, `lib/streamlit/commands/execution_control.py` |
| **Form** | Container (`st.form`) that batches widget inputs, deferring reruns until form submission. | `lib/streamlit/elements/form.py`, `WidgetStateManager.ts` |
| **Fragment** | Decorator (`@st.fragment`) enabling partial reruns of specific UI sections without full script re-execution. | `lib/streamlit/runtime/fragment.py` |
| **Caching** | Decorators (`@st.cache_data`, `@st.cache_resource`) that memoize function results to avoid redundant computation. | `lib/streamlit/runtime/caching/` |
| **Pages** | Multipage app system using `st.navigation()` and `st.Page()` or auto-discovery from `pages/` directory. | `lib/streamlit/navigation/`, `lib/streamlit/runtime/pages_manager.py` |
| **Config** | App configuration via `.streamlit/config.toml` controlling server, client, and theme settings. | `lib/streamlit/config.py`, `lib/streamlit/config_option.py` |
| **Theming** | Customizable UI themes (Light/Dark/Custom) defined in config or via theme editor. | `lib/streamlit/runtime/theme_util.py`, `frontend/lib/src/theme/` |
| **Secrets** | Secure credential storage via `.streamlit/secrets.toml` (local) or platform settings (deployed). Accessed via `st.secrets`. | `lib/streamlit/runtime/secrets.py` |
| **Connection** | Database/service abstraction (`st.connection`) with built-in caching and secrets integration. | `lib/streamlit/connections/` |
| **Custom Components** | User-built extensions using React/iframe. **v1 (legacy)**: `declare_component()` API. **v2 (current)**: Bidirectional components with improved state management. | `frontend/component-lib/`, `frontend/component-v2-lib/`, `lib/streamlit/components/v1/`, `lib/streamlit/components/v2/` |
| **Static File Serving** | Files in `static/` directory served directly via `/app/static/*` (when static serving is enabled). | `lib/streamlit/web/server/server.py`, `lib/streamlit/web/server/starlette/starlette_routes.py` |
| **App Testing** | Testing framework (`AppTest`) for simulating user interactions and inspecting rendered output. | `lib/streamlit/testing/` |

## Core mental model

```mermaid
flowchart TB
    subgraph Backend["Backend (Python)"]
        Script[User Script]
        DG[DeltaGenerator]
        Runtime[Runtime/AppSession]
    end

    subgraph Protocol["WebSocket + Protobuf"]
        FM[ForwardMsg]
        BM[BackMsg]
    end

    subgraph Frontend["Frontend (React)"]
        App[App.tsx]
        Tree[AppRoot Tree]
        Renderer[ElementNodeRenderer]
        WSM[WidgetStateManager]
    end

    Script --> DG
    DG --> FM
    FM --> App
    App --> Tree
    Tree --> Renderer
    Renderer --> WSM
    WSM -->|User interaction| BM
    BM --> Runtime
    Runtime -->|Rerun| Script
```

**Key insight**: Script execution is rerun-driven: most widget interactions trigger reruns (full app or fragment-scoped). State persists via `st.session_state` and caching decorators.

## Execution model

Streamlit's execution model differs from traditional web frameworks:

**Rerun triggers**:
1. **Widget interaction**: User clicks button, moves slider, etc. (widgets with `on_change="ignore"` update without a rerun)
2. **Source code change**: File watcher detects script modification
3. **`st.rerun()`**: Explicit programmatic rerun
4. **Fragment timer**: `@st.fragment(run_every=...)` periodic reruns

**Execution order nuances**:
- Scripts execute **top-to-bottom** on every rerun
- **Callbacks first**: `on_change`/`on_click` handlers run *before* the main script body
- **Fragments typically isolate reruns**: Widget interactions inside `@st.fragment` usually rerun only that fragment
- **Keyed fragment reruns**: `st.rerun("<key>")` from a widget callback reruns only the named `@st.fragment(key=...)` fragment(s)
- **Control flow exceptions**: `st.stop()`, `st.rerun()`, `st.switch_page()` raise exceptions to halt/redirect execution

**Session isolation**:
- Each browser tab = separate `AppSession` with its own `SessionState`
- Refreshing the page creates a new session (unless reconnecting within TTL)
- No shared state between sessions (use external storage for multi-user state)

**What persists across reruns** (within a session):
- `st.session_state` values
- Cached function results (`@st.cache_data`, `@st.cache_resource`)
- Uploaded files
- Fragment registrations

**What resets on each rerun**:
- Local variables in script
- Widget return values (re-read from `SessionState`)
- Element tree (rebuilt from scratch, then diffed)

## Architecture layers

### Backend (Python)

| Component | File | Purpose |
|-----------|------|---------|
| Runtime | `lib/streamlit/runtime/runtime.py` | Singleton managing app lifecycle and sessions |
| AppSession | `lib/streamlit/runtime/app_session.py` | Per browser tab or agent API session: ScriptRunner + SessionState + ForwardMsgQueue |
| ScriptRunner | `lib/streamlit/runtime/scriptrunner/script_runner.py` | Executes user scripts in separate thread |
| DeltaGenerator | `lib/streamlit/delta_generator.py` | API entry point using mixin pattern |
| SessionState | `lib/streamlit/runtime/state/session_state.py` | Widget values and user variables |
| Elements | `lib/streamlit/elements/` | Backend implementation of `st.*` commands |

**For backend deep dive**: See [references/backend.md](references/backend.md)

### Frontend (TypeScript/React)

| Component | File | Purpose |
|-----------|------|---------|
| App | `frontend/app/src/App.tsx` | Central orchestrator |
| AppRoot | `frontend/lib/src/render-tree/AppRoot.ts` | Immutable element tree with 4 containers |
| ElementNodeRenderer | `frontend/lib/src/components/core/Block/ElementNodeRenderer.tsx` | Maps protos to React components |
| WidgetStateManager | `frontend/lib/src/WidgetStateManager.ts` | Widget state, forms, query params |
| ConnectionManager | `frontend/connection/src/ConnectionManager.ts` | WebSocket state machine |

**For frontend deep dive**: See [references/frontend.md](references/frontend.md)

### Communication (Protobuf)

| Proto | Purpose |
|-------|---------|
| `ForwardMsg.proto` | Server to client: deltas, session events, navigation |
| `BackMsg.proto` | Client to server: rerun requests with widget states |
| `Element.proto` | ~50+ element types in `oneof type` union |
| `WidgetStates.proto` | Widget values: `trigger_value`, `string_value`, `bool_value`, etc. |

**Location**: `proto/streamlit/proto/`

**For protocol deep dive**: See [references/communication.md](references/communication.md)

## Essential concepts (quick map)

- **Layout system**: Width/height parameters for elements, flexbox containers, and responsive sizing.
  - Deep dive: [references/layout.md](references/layout.md)
- **Script rerun model**: Widget interaction -> `BackMsg` (`ClientState`) -> backend updates `SessionState` -> script rerun -> `ForwardMsg` deltas.
  - Deep dive: `references/communication.md#widget-interaction-to-script-rerun`
- **Delta path system**: Elements are addressed by delta paths (for example `[0, 2, 3]`) to support efficient tree updates. The frontend and the agent snapshot apply the same placement rules.
  - Deep dive: `references/communication.md#delta-ui-changes`
- **`active_script_hash` semantics**: `ForwardMsg.metadata.active_script_hash` scopes node ownership across multipage and fragment reruns.
  - Deep dive: `references/communication.md#forwardmsg-metadata-active_script_hash`
- **Agent element descriptions**: A command can attach JSON on `ForwardMsg.metadata.agent_props`.
  - Deep dive: `references/communication.md#agent-command-descriptions`
- **Element tree structure**: Frontend `AppRoot` maintains `main`, `sidebar`, `event`, and `bottom` containers with `BlockNode`/`ElementNode`.
  - Deep dive: `references/frontend.md#element-tree-frontendlibsrcrender-tree`
- **Element identity semantics**: Delta paths decide where a node lives; element IDs decide whether stateful elements can reconnect to prior state after remounts.
  - Deep dive: `references/element-identity.md`
- **Fragments (`@st.fragment`)**: Fragment interactions usually trigger fragment-scoped reruns and update only affected regions. A widget callback can also target named fragments with `st.rerun("<key>")` when the fragment was declared with `@st.fragment(key=...)`.
  - Deep dive: [references/backend.md](references/backend.md#fragment-system-stfragment)

## Shared delta-path semantics

The browser and the agent interaction API both place nodes by applying `ForwardMsg` deltas in order. The frontend does this in `AppRoot` (`frontend/lib/src/render-tree/`). The interaction API does it in `merge_deltas` (`lib/streamlit/runtime/agent/tree.py`) when it builds a snapshot.

They follow the same placement rules. A delta path addresses a node. A block of the same type keeps its children, and a different block type or dialog identity replaces them. When those rules change, update both sides.

The two trees are not the same structure. The frontend merges deltas as they arrive, and it also filters by script hash, uses the message cache, and keeps transient nodes such as spinners. The snapshot merges the messages that remain after the run and its fragments settle, then drops nodes and props with no semantic value, such as `st.empty`, `st.space`, skeletons, spinners, width, and height. Leave the implementations separate. Do not require the JSON tree to match the render tree node for node.

## Element identity

- **Delta path** controls where a node is placed in the render tree.
- **Element ID** controls whether a stateful element can reconnect to prior state after remounts.
- **Widgets** use the ID to connect frontend `WidgetStateManager` state, `BackMsg.WidgetStates`, backend `SessionState`, callbacks, and `st.session_state`.
- **Some non-widgets** also use IDs for frontend-only reconstruction (for example chart view state or media autoplay guards).
- **Delta-path changes can remount elements**, but a stable `element.id` can still let React preserve a leaf when it remains under the same rendered parent list.

Deep dive: `references/element-identity.md`

## Key implementation patterns

- **Backend mixin composition**: `DeltaGenerator` composes `st.*` API via mixins.
  - Deep dive: `references/backend.md#deltagenerator-libstreamlitdelta_generatorpy`
- **Frontend visitor pattern**: Render-tree updates/staleness cleanup use visitors.
  - Deep dive: `references/frontend.md#visitor-pattern`
- **Message deduplication**: `ForwardMsg.hash` + `ref_hash` with frontend `ForwardMsgCache` reduces bandwidth.
  - Deep dive: `references/communication.md#message-caching`

## Quick reference: adding features

1. **Proto definition**: `proto/streamlit/proto/<Element>.proto`
2. **Register in Element.proto**: Add to `oneof type`
3. **Backend mixin**: `lib/streamlit/elements/<element>.py`
4. **Frontend component**: `frontend/lib/src/components/elements/<Element>/` or `frontend/lib/src/components/widgets/<Element>/` (depending on element vs widget)
5. **Register in ElementNodeRenderer**: Add case to switch statement
6. **Compile protos**: `make protobuf`

See `wiki/new-feature-guide.md` for a detailed implementation guide.

## Maintaining this documentation

When making changes that impact any of the concepts documented here (Runtime, AppSession, DeltaGenerator, element tree, communication protocol, element identity, etc.), update the relevant sections in this skill's files (`SKILL.md`, `references/backend.md`, `references/frontend.md`, `references/communication.md`, `references/element-identity.md`) to keep them accurate.

© streamlit · Apache-2.0 · streamlit/streamlit

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
harvard-artifacts-etl-streamlit-analytics reason-machines Скилл harvard-artifacts-etl-streamlit-analytics помогает агенту собрать ETL-пайплайн и аналитический дашборд на данных Harvard Art Museums API: Python, SQL и Streamlit. CX Codex +1 1 900установок harvard-artifacts-data-engineering-streamlit reason-machines Скилл harvard-artifacts-data-engineering-streamlit собирает данные из API Гарвардских художественных музеев, грузит их в MySQL и запускает дашборд на Streamlit. CX Codex +1 971установок writing-streamlit-apps PostHog Скилл writing-streamlit-apps для Claude Code помогает писать и отлаживать Python-код Streamlit-приложений, читающих данные PostHog в sandbox. Код используют для экранов с таблицами, метриками и графиками. CX Codex +1 177установок streamlit sanjeed5 Задаёт, как писать приложения на Streamlit: кэшировать тяжёлые операции, держать UI отдельно от логики и разбивать проект на модули. CX Codex +1 ★ 3 589звёзд репо streamlit-to-marimo marimo-team Скилл streamlit-to-marimo переводит приложение на Streamlit в ноутбук marimo: разбирает виджеты, состояние и кэш, собирает новый файл и проверяет его. CX Codex +1 2 400установок managing-streamlit-apps PostHog Скилл managing-streamlit-apps управляет жизненным циклом приложений Streamlit в PostHog через MCP-инструменты: от создания песочницы до правок кода и мониторинга. CX Codex +1 179установок

Из того же набора6

debugging-streamlit Скилл debugging-streamlit запускает отладку приложений и компонентов Streamlit через команду make debug с горячей перезагрузкой, сбором логов и скриншотами через Playwright. CX Codex +1 502установок checking-changes Скилл checking-changes для Claude Code запускает проверки кода после серии изменений, перед коммитом или завершением рабочей сессии. Он охватывает Python-бэкенд и TypeScript-фронтенд. CX Codex +1 122установок addressing-pr-review-comments Скилл addressing-pr-review-comments собирает комментарии ревьюеров к PR текущей ветки в streamlit/streamlit и вносит те правки, которые вы выберете из списка. CX Codex +1 108установок discovering-make-commands Скилл discovering-make-commands показывает ИИ-агенту доступные цели Makefile для сборки, линтинга и тестов в репозитории Streamlit. CX Codex +1 ★ 46 474звёзд репо fixing-streamlit-ci Скилл fixing-streamlit-ci разбирает упавшие проверки GitHub Actions для текущей ветки или PR и помогает исправить ошибку, затем проверить изменения локально. CX Codex +1 ★ 46 474звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой