数据审查
- 作者仓库星标 15
- 许可证 BSD-3-Clause (see repo LICENSE)
- 作者更新于 实时读取
- 作者仓库 agilab
- 领域
- 通用
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 94 / 100 · 已通过审计
- 作者 / 版本 / 许可
- @ThalesGroup · BSD-3-Clause (see repo LICENSE)
- Token 消耗评级
- 中等消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- macOS · Linux · Windows
- 底层运行要求
- Node.js · Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 读取环境变量
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: agilab-streamlit-pages
description: Streamlit page authoring patterns for AGILAB (session_state safety, keys, rerun, UX). Use this s…
category: 通用
runtime: Node.js / Python
---
# agilab-streamlit-pages 输出预览
## PART A: 任务判断
- 适用问题:通用任务拆解、检查和交付。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Apps-Pages Versus Apps Boundary / App Args Forms And Sidebar Controls / Session State Rules (Avoid Common Crashes)”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于通用任务拆解、检查和交付,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Apps-Pages Versus Apps Boundary / App Args Forms And Sidebar Controls / Session State Rules (Avoid Common Crashes)”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、读取环境变量、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令、读取环境变量。
先用一个小任务确认它会围绕“Apps-Pages Versus Apps Boundary / App Args Forms And Sidebar Controls / Session State Rules (Avoid Common Crashes)”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: agilab-streamlit-pages
description: Streamlit page authoring patterns for AGILAB (session_state safety, keys, rerun, UX). Use this s…
category: 通用
source: ThalesGroup/agilab
---
# agilab-streamlit-pages
## 什么时候使用
- agilab-streamlit-pages 是一个通用扩展技能,按 SKILL 适合处理通用任务拆解、检查、交付和复盘,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继…
- 面向通用任务拆解、检查和交付,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Apps-Pages Versus Apps Boundary / App Args Forms And Sidebar Controls / Session State Rules (Avoid Common Crashes)」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "agilab-streamlit-pages" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Apps-Pages Versus Apps Boundary / App Args Forms And Sidebar Controls / Session State Rules (Avoid Common Crashes)
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Node.js / Python | 读取文件、写入/修改文件、执行终端命令、读取环境变量 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Streamlit Pages Skill (AGILAB)
Use this skill when editing:
src/agilab/main_page.pysrc/agilab/pages/*.pysrc/agilab/apps-pages/*/src/*/*.py- custom
app_args_form.pyviews in AGILAB-managed app repos
Apps-Pages Versus Apps Boundary
- Treat
apps-pagesas app-agnostic analysis sidecars by default. A page should inspect artifacts, manifests, metrics, or settings from the selected active app; it should not own the domain workflow. - Before promoting a Streamlit surface as an apps-page, check whether it generates its own dataset, trains a model, runs an optimizer, owns evidence generation, or encodes project-specific semantics. If yes, it is probably an app project with a companion analysis page, not a generic page bundle.
- If a self-contained teaching surface must stay under
apps-pagesfor packaging or launch reasons, document it as an explicit opt-in playground or exception. Do not describe it as a generic app-agnostic view. - Prefer the split architecture when the surface has both execution and review concerns: the app owns reproducible execution and artifact/evidence export; the page reads those artifacts and renders the analysis.
- AGILAB app projects do not always need workers. Use a workerless app template for local/UI prototypes, notebook-derived tools, explainers, and reports that can write artifacts from the manager process. Use a worker template only when the app needs AGILAB Install/Execute worker deployment, Dask, worker-specific dependencies, or a distributed task plan.
App Args Forms And Sidebar Controls
- Custom
app_args_form.pyviews are app UI, not apps-pages. Use them when an app needs persisted execution fields in ORCHESTRATE. - For compact app-specific controls, use
agi_env.streamlit_args.render_formwith an explicit container such asst.sidebar:render_form(defaults_model, container=st.sidebar). - Keep the capability generic in
agi_env.streamlit_args; do not hard-code a project name or page bundle just because one app wants sidebar controls. - If a Streamlit surface owns training, optimization, generated data, or evidence export, make it an app project first. Keep any app-owned standalone Streamlit surface under that app project unless a separate generic analysis page reads only exported artifacts.
- For an app-owned Streamlit surface that should appear as the app's primary
ANALYSIS experience, declare
[app_surface]in the app'sapp_settings.tomlwith a project-local entrypoint such aspytorch_playground/app_surface.py. Use[pages] restrict_to_view_module = truefor app-surface-first projects; an empty or missingpages.view_modulemay be migrated to the virtualview_app_uilauncher so the app surface is selected and visible in the ANALYSIS sidebar. Do not create a genericapps-pages/view_<app>bridge for this. - Treat
view_app_uias an internal route key, not a user-facing label. Sidebar links for app surfaces should use[app_surface].title, route through the app surface renderer, and avoid exposing duplicateview_app_uibridge links. - Keep the standard ANALYSIS view multiselect usable for app-surface projects:
view_app_uimay be the default selected sidebar launcher, but users must still be able to add other installed analysis views through the same existing selector instead of a custom "additional views" control. - Render an ANALYSIS sidebar launcher from one place per page route. If the main page persists selected views after rendering controls, do not also render the same project label or app-surface link before the main-page body; add a regression assertion that the compact project caption and app-surface link appear exactly once.
Session State Rules (Avoid Common Crashes)
Never assign
st.session_state["k"] = …after a widget withkey="k"was created.- Prefer
st.session_state.setdefault("k", default)before the widget. - Or use widget return values and compute derived state separately.
- Prefer
Do not both pre-seed
st.session_state[key]and pass a widget default/value/index for the same keyed widget. Pick one source of initialization:- use the widget default and leave
st.session_stateuntouched before creation, or - pre-seed
st.session_statebefore creation and omit the widget default. This avoids Streamlit warnings such as "created with a default value but also had its value set via the Session State API". Shared widget wrappers should drop their default argument when the key already exists in session state.
- use the widget default and leave
If you need to “reset” a widget value:
- Use a different key (versioned key pattern), or
- Gate the reset behind a rerun and only mutate state before widget creation.
When Streamlit raises a duplicate-widget ID error, check whether the page or app surface is being rendered twice before only adding widget keys. Add stable keys for repeated controls, but fix duplicate entrypoint execution at the source.
Recommended Pattern
- Initialize defaults with
setdefaultat the top of the page. - Render widgets.
- Read values from widgets, compute derived state, store under different keys.
Project-Scoped State Models
- If a page can switch between projects/apps in one Streamlit session, any persisted widget state that belongs to a specific project must use project-scoped keys.
- Prefer patterns like
f"cluster_pool__{app_name}", not"cluster_pool". - Apply the same rule to toggles, text inputs, password/auth fields, scheduler/worker fields, and similar per-project controls.
- Prefer patterns like
- Keep one clear source of truth for persisted settings.
- File-backed or workspace-backed
app_settingsshould hydrate widget keys on page init and after project switches. - Do not let a stale widget key silently override freshly loaded settings just because it already exists in
st.session_state.
- File-backed or workspace-backed
- On project change:
- compute any preservation/override decision before popping tracking keys from
st.session_state - then clear the old project's widget keys explicitly
- then rehydrate the new project's widget state from persisted settings
- compute any preservation/override decision before popping tracking keys from
- Treat
app_settings["cluster"],app_settings["args"], or equivalent persisted payloads as the serializable config contract.- Widget keys are UI transport, not a second config layer.
Page Bootstrap And Path Drift
- At page start, resolve the active app and apps root from the current launch context first: explicit CLI args, current source checkout, and packaged runtime location. Only then consult persisted user settings.
- Do not let stale persisted state override the current launch root:
~/.agilab/.env~/.local/share/agilab/.agilab-path- a previous
st.session_state["env"] - a previous
active_apporAPPS_PATH
- If the launch context says the page is running from source, UI readiness cards such as
ORCHESTRATE
Manager envmust point at the source app path, not$HOME/agi-space. - When the resolved app root changes, rebuild or realign the session
envobject before rendering headers, buttons, or action state. Rendering first and repairing later leaves stale paths visible to users and can make action buttons operate on the wrong project. - Add regressions for both cold sessions and warm sessions with stale
st.session_statewhen touching page bootstrap, sidebar project selection, or ORCHESTRATE header state.
Derived Preview Metrics
- Treat previews as read-only explanations, not as another persisted config source.
- Compute any preview metric from the same backend helper used by the runtime or exported summary artifact.
- If a preview depends on existing generated files, label it explicitly as a previous-run value (for example,
Last generated ...) rather than implying it reflects the current unsaved inputs. - When both are available, show the distinction clearly:
- current preview from present inputs
- last generated metric from persisted output
- Do not write preview-only values back into
app_settings.tomlunless they are real app args.
Cross-Page UX and KPI Headers
- Keep sidebar text short and action-oriented. Remove labels that only restate the active project/page or explain obvious scope such as "actions below apply to this project".
- Keep shared page chrome minimal. Do not add global active-project labels, chips, or badges above page controls; the selected project belongs in the selector, the sidebar, or an explicitly opened context expander.
- Before reusing or renaming a visible action label, compare its meaning across
PROJECT, ORCHESTRATE, WORKFLOW, ANALYSIS, SETTINGS, sidebars, and robot click
labels. Avoid same-label/different-contract collisions; scope labels by
object and layer, for example
Install agi-appfor package/catalog install andDeploy workersfor manager/worker environment deployment. - Preserve stable lower-level API names when product copy changes. In
ORCHESTRATE,
Deploy workerscan correctly callAGI.install: the API prepares manager and worker runtime environments and reuses an already-ready local manager environment rather than forcing a reinstall. - For visible-label cleanup, search every render path before closing the task:
page files,
main_page.py,page_bootstrap.py,workflow_ui.py,page_project_selector.py, lazy-import wrappers, CSS class names, and tests. Add or update a negative regression assertion for removed text so tests do not encode newly introduced clutter as expected behavior. - Prefer page headers with a few read-only KPI cards over status banners that say
ready,not set, ormissingwithout useful context. - Use the same visual semantics across pages:
- green only for verified positive values
- amber for incomplete, missing, or no-evidence-yet values
- neutral for identity or purely informational values
- Do not color a value green just because it is present when the value means "no run", "not configured", or "no artifact discovered".
- Use product-facing labels instead of internal implementation terms:
Workflow graphinstead ofDAG shapeStagesanddependenciesfor project workflow instead of graph-only jargon such as nodes and edgesPlan,steps,outputs,Creates, andUsesfor multi-app workplans before technical DAG, artifact, node, or edge wording- hide generated graphs behind an explicit
Show graphcontrol when the graph can be too small to read Project namewhen the widget selects a project
- Derived header values must be computed locally from existing evidence when possible.
For example, count ORCHESTRATE runs from
run_*.logfiles under the app run environment instead of adding another persisted setting. - When a page references a machine-readable evidence file such as
run_manifest.json,evidence_graph.json,workflow_run_manifest.json,notebook_export_manifest.json, or a dry-run report, do not stop at showing the file path. Render a compact human inspection surface for the contents: status, counts, schema, key rows, validation issues, and artifact links. Keep the raw path visible for audit/replay. - When a generic page has no app-specific semantic data, show an honest fallback such as execution stages, output files, or discovered dataframes rather than inventing a domain-specific metric.
- Keep one navigation surface per action. If a page already exposes compact sidebar
launch links, do not duplicate the same action as in-page sidecar cards, repeated
Openbuttons, or another selector unless the second surface adds a distinct workflow stage. - For lightweight page routing, prefer compact Markdown/HTML links with encoded
query parameters such as
current_pageover a selectbox plusOpenbutton when the user only needs to jump to a target. Add a tiny helper to construct and test the encoded URL instead of inlining query-string formatting in the render block. - Treat legacy “default view” UI as configuration debt when a project already has a
selected view list. Persist the selected list in
pages.view_module; remove staledefault_view/default_viewsvalues only when that behavior is intentionally replaced by the new launcher model. - With
st.navigation,st.switch_pagetargets must be the main app file or an exact file underpages/relative to the Streamlit entrypoint. Do not hard-code stale numeric filenames such aspages/3_WORKFLOW.py; route through central page constants and add a focused test when a wizard button or deep link opens another page. - For wizard/deep-link actions that need the destination page to open a drawer, selector, upload area, or run action, set a non-widget intent key before navigation and consume it once on the destination page. Clear the intent before rerunning so the link cannot recursively navigate or keep the app in a loading loop.
- Update focused page tests when changing visible labels, header cards, or sidebar structure. Grep old wording before closing the task so stale copy does not survive in tests, docs, or screenshots.
- When replacing a single-item action with a batch action, keep button labels compact
unless the extra word is needed to prevent misuse. Put selection semantics in the
selector label/help text and assert the exact end-user button labels in focused page
tests so stale wording such as
Update selectedorRemove selectedcannot survive after a product copy decision.
First-Proof Onboarding UX
- Treat the first-proof panel as a new-user wizard, not as an expert shortcut list. Every visible action must state whether it runs the built-in demo, imports AGILAB's included notebook, or uploads the user's own notebook.
- Do not hide packaged sample assets behind vague labels such as
example notebookwhen the user cannot know where that file is. Prefer explicit copy such asCreate from built-in notebook, say that no file needs to be found or uploaded, and show the project that will be created. - Keep first-proof alternatives simple: the built-in demo lane should expose install, run, and analysis actions; the notebook lane should expose the included sample. Keep local notebook upload in PROJECT Create instead of adding another direct uploader to the ABOUT wizard.
- When changing first-proof labels, update ABOUT tests, PROJECT notebook-import tests, newcomer docs, and stale-wording greps in the same change.
App-Specific Page Defaults
- Prefer app-declared defaults in
app_settings.tomlover page-level hardcoded paths. - For apps-pages, use
pages.<page_name>for app-specific defaults that should be portable across apps and machines. - Remember that versioned app seeds and workspace settings are different:
src/.../app_settings.tomlis only the seed.- mutable user/HF settings can live under
~/.agilab/apps/<app>/app_settings.toml. - if a bug is caused by a stale default already persisted in the workspace, changing only the seed will not fix existing deployments.
- When changing app analysis defaults, add a narrow migration for the stale workspace value when needed.
- Scope migrations to the affected app and legacy value.
- Preserve custom user defaults when the legacy value is absent.
- Write the migrated config before widgets/options are built.
- For app/page visibility, prefer explicit exclusions over global restrictions when the app should still see generic pages.
- Example: for
flight_project, excludeview_maps_networkwhile keeping generic views such asview_maps,view_maps_3d, andview_barycentricavailable. - Avoid setting a broad
restrict_to_view_moduleunless hiding every undeclared generic view is the intended product behavior.
- Example: for
- For
view_maps_network, supported defaults now include:dataset_base_choicedataset_custom_basedataset_subpathdefault_traj_globsdefault_allocation_globsdefault_baseline_globscloudmap_sat_pathcloudmap_ivdl_path
- Keep persisted
view_maps_networkstate for user choices, but put repo/app conventions underpages.view_maps_network.
DAG And Worker-Type UI
- For generic ORCHESTRATE/WORKFLOW page behavior that depends on whether an app is
DAG-based, use
AgiEnv.base_worker_clsfirst.AgiEnvalready populates this from worker source inspection, so page code should not import app worker classes just to decide which controls to show. - Treat
DagWorker, known DAG-derived workers such asSb3TrainerWorker, and custom*Dag*Workerbase names as DAG-capable for UI decisions. - Keep name-token fallbacks narrow and explicit for planning-only or synthetic apps that intentionally have no DAG worker base yet, such as multi-app DAG draft/demo projects.
- Reuse one helper for DAG detection across sidebars, execute controls, and
distribution/workplan rendering. Do not leave page-local string checks such as
endswith("dag-worker"); they drift from theAgiEnvcontract and silently fail for real base names likeDagWorker. - DAG-only planning projects should expose run/workflow actions, not dataframe load/export/delete controls, unless the app has an explicit dataframe artifact contract.
Rerun API
- Do not use
st.experimental_rerun(); usest.rerun().
Diagnostics Rendering
- Render long diagnostics and tracebacks as code blocks, not message-box text:
st.error("Short actionable summary.")st.caption("Full diagnostic")st.code(diagnostic_text, language="text")
- Do not embed Markdown code fences inside
st.error()orst.code(). - Do not pass
traceback.format_exc()directly tost.error(); Streamlit message boxes collapse readability and can flatten newlines. - If a diagnostic arrives as a single long line, format a display-only copy with
line breaks or wrapping before passing it to
st.code; keep the original exception/message unchanged for logs and assertions that depend on exact text. - Add a focused helper test for display formatting and keep the repository scan
guard in
test/test_streamlit_diagnostic_rendering.pygreen when touching diagnostic rendering paths.
Action Results and Runtime Logs
- Do not classify a page action as failed only because stderr is non-empty. AGILAB runtime helpers, package managers, and subprocess wrappers may write normal progress or warnings to stderr.
- Treat action success/failure as a typed result contract first:
- subprocess return code or raised exception
ActionResult.status- explicit fatal markers in logs such as tracebacks, non-zero exit status, missing imports, or worker/build failure phrases
- Keep log classifiers narrow. Avoid broad predicates such as
"failed" in lineunless the surrounding phrase is part of a known fatal contract; benign warnings can contain words likefailed. - Apply the same action-result semantics to sibling workflow actions. If INSTALL
and RUN already use typed results or fatal-log heuristics, do not leave CHECK,
DISTRIBUTE, LOAD, EXPORT, or service actions on older
stderr == failurerules. - Add a regression with a realistic noisy stderr log for any action whose runtime can emit progress on stderr. The regression should prove benign stderr stays successful and a concrete fatal marker still fails.
WORKFLOW Assistant UX
- Default generated dataframe work to a safe-action mode: the model returns a versioned JSON action contract, AGILAB validates it, and the UI displays the deterministic pandas code derived from that contract.
- Keep raw Python generation as an explicit advanced choice with clear wording. Do not imply a container or VM is required for the normal safe-action path.
- Persist the generation mode and action contract beside the saved stage so a
reopened
lab_stages.tomlexplains whether code came from safe actions or raw Python. - When generation fails validation, keep the existing stage code intact and show the contract error; do not silently replace it with partial or arbitrary code.
Long-Running Action Timers
- For long async actions such as ORCHESTRATE install/run/serve, render a live elapsed-time placeholder before awaiting the subprocess or background task.
- Prefer
asyncio.create_task(...), yield once withawait asyncio.sleep(0), then poll at a short fixed interval and update the placeholder until the task is done. Do not depend only on log callbacks; quiet processes still need a visible timer. - Keep the final duration visible after completion and record it in action history when that history is user-facing evidence.
- Store timer values under non-widget session-state keys such as
last_run_elapsed_secondsandlast_run_elapsed_label; never mutate a key already owned by a rendered widget. - Add focused tests for both the formatting helper and the action path that records the elapsed label, without requiring a real long-running process.
Key Hygiene
- Every widget must have a stable, unique key.
- Prefer namespaced keys:
f\"{page_id}:df_files\", not"df_files".
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核