textual-async-data-loading

A pattern for loading data in a Textual terminal interface (a text-based app) without freezing the screen. It covers background work, loading indicators, safe screen updates, and avoiding duplicate requests.

In plain words
What is it for?
Use it when a Textual app fetches data, runs subprocesses, or responds to frequent changes such as moving through a list.
Why use it?
Blocking tasks such as running commands or making HTTP requests can make the interface unresponsive or show outdated results.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/st1page/agent-knowledge-framework/textual-async-data-loading
Any agent
npx skills add st1page/agent-knowledge-framework --skill textual-async-data-loading
Clone the repo
git clone --depth 1 https://github.com/st1page/agent-knowledge-framework

Made for: Claude Code, Codex.

Per session 56 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 941 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 2 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00056 $0.00941
Opus 5 $0.00028 $0.00470
Sonnet 5 $0.00011 $0.00188
Haiku 4.5 $0.00006 $0.00094

Measured 3d ago against content hash b934e60ebc06, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

textual-async-data-loading scanned grade A with 2 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

result = fetch(run_id)

Runs shell commandslowCapability

Expected in a hook, worth knowing in a rule or an instructions file.

result = subprocess.run(...) # 在后台线程执行
roles/cli-tool-dev/skills/textual-async-data-loading/SKILL.md · 114 lines

How it starts

The opening of the file, as written. The whole thing — 114 lines — stays where its author put it; the contents beside it link to each section on GitHub.

textual TUI 异步数据加载模式

目标:在 textual TUI 中执行阻塞 IO(subprocess、HTTP)时,保持 UI 响应,同时避免竞态和重复请求。

核心三件套

1. @work(thread=True) — 阻塞 IO 移出 UI 线程

from textual import work  # 注意:不是 from textual.work import work

@work(thread=True)
def _fetch_data(self) -> None:
    result = subprocess.run(...)  # 在后台线程执行
    self.app.call_from_thread(self._render, result)  # 回主线程更新 UI

陷阱from textual.work import workModuleNotFoundError

2. LoadingIndicator — 加载过渡

compose 时同时 yield 数据 widget 和 loading indicator,用 display 属性互斥切换:

def compose(self) -> ComposeResult:
    yield LoadingIndicator(id="loading")
    yield DataTable(id="table", cursor_type="row")

def on_mount(self) -> None:
    self.query_one("#table").display = False  # 初始隐藏数据

def _render(self, data) -> None:
    self.query_one("#loading").display = False
    self.query_one("#table").display = True
    # ... 填充数据

3. call_from_thread — worker 回调回主线程

worker 线程中不能直接操作 UI widget。必须通过 self.app.call_from_thread(callback, *args) 调度回主线程。

增强模式

4. exclusive worker group — 高频触发防抖

光标快速移动时,每次触发数据请求。用 exclusive=True + group 自动取消旧请求:

@work(thread=True, exclusive=True, group="jobs")
def _fetch_jobs(self, run_id: int) -> None:
    ...

效果:连续触发只执行最后一个请求。

5. dict 缓存 + stale check

简单 dict 缓存已请求过的数据;异步回调时检查数据是否仍然是当前需要的:

_cache: dict[int, Data] = {}

@work(thread=True, exclusive=True, group="jobs")
def _fetch_jobs(self, run_id: int) -> None:
    if run_id in self._cache:
        self.app.call_from_thread(self._render_jobs, run_id, self._cache[run_id])
        return
    result = fetch(run_id)
    self._cache[run_id] = result
    # stale check:渲染前确认用户没有切走
    if self._selected_run_id == run_id:
        self.app.call_from_thread(self._render_jobs, run_id, result)

刷新时清空整个 cache(CLI 工具生命周期短,不需要 TTL)。

headless 测试中等待 worker

pilot.pause() 只处理事件队列,不等 worker 线程。必须轮询:

async def wait_workers(app, pilot, timeout=15):
    import asyncio
    for _ in range(int(timeout / 0.1)):
        await pilot.pause()
        if all(w.is_finished for w in app.workers):
            return
        await asyncio.sleep(0.1)
    raise TimeoutError("workers not finished")

Read the full file on GitHub · 114 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 114 lines · 56 tokens per session scan A b934e60ebc06

Subscribe to this mod's changes

textual-async-data-loading is a skill published in the GitHub repository st1page/agent-knowledge-framework (41 stars, last pushed 5mo ago), licensed Apache-2.0. It adds 56 tokens to every session and 941 once invoked, about $0.0003 per session on Opus 5. A static security scan graded it A with 2 findings (makes network calls, runs shell commands). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes.

obra/superpowers · 21 tokens

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.

obra/superpowers · 37 tokens

auto-perf-optimize

Run agent-driven VS Code performance or memory investigations. Use when asked to launch Code OSS, automate a VS Code scenario, run the Chat memory smoke runner, capture renderer heap snapshots, take workflow screenshots, compare run summaries, or drive a repeatable scenario before heap-snapshot analysis.

microsoft/vscode · 62 tokens

chat-perf

Run chat perf benchmarks and memory leak checks against the local dev build or any published VS Code version. Use when investigating chat rendering regressions, validating perf-sensitive changes to chat UI, or checking for memory leaks in the chat response pipeline.

microsoft/vscode · 51 tokens

chat-pet-sprite-creation

Use when creating or changing VS Code chat pet sprite art, sprite sheets, state animations, eye treatments, Stable/Insiders variants, or pet transitions under src/vs/workbench/contrib/chat/browser/widget/media/chatPet.

microsoft/vscode · 53 tokens

cpu-profile-analysis

Analyze V8/Chrome CPU profiles (.cpuprofile) and DevTools trace files (Trace-.json). Use when: profiling performance, investigating slow functions, comparing code paths, finding bottlenecks, analyzing timeToRequest, understanding call trees from sampling profiler data, analyzing layout/paint/rendering, investigating…

microsoft/vscode · 71 tokens