Skip to content

Terminal UI

Purpose

The Terminal UI (virtufin-tui) is a Textual-based Python operator dashboard for the Virtufin control plane. It is a pure consumer of the existing virtufin-api gRPC surface — it runs no service-side code, adds no proto messages, and requires no service changes. It fills the operator role that kubectl plays for Kubernetes: interactive worker / connection / state / event management over a remote virtufin-api endpoint, with live CloudEvent streaming, multi-context switching, and an AI assistant.

Related specs: - Cross-cutting — API-mediated pub/sub rule (the TUI talks only to virtufin-api, never Dapr directly). - Pub/Sub Topics — the CloudEvent envelope and topic taxonomy the TUI's event log renders. - Scenarios — the scenario registry triplet the TUI's scenario page edits. - Worker Management — worker lifecycle, tags, and creation-time config the TUI drives. - WebSocket Feed — the WebSocketFeed worker (one connection per worker), its commands and status, which the TUI drives for connections and worlds.

Requirements

Requirement: Multi-Context Configuration

The TUI SHALL implement the operator-clients Contexts; this requirement is its terminal binding.

The TUI SHALL read its endpoint configuration from a TOML file under the XDG config directory (~/.config/virtufin/api/contexts.toml on Linux/macOS, %APPDATA%\virtufin\api\contexts.toml on Windows). The file SHALL contain a [[contexts]] array; each entry MUST have name, api_host, api_port fields and MAY have tls (bool), api_key, default_worker_topic, worker_api_host, worker_api_port, description, event_topics (default ["sys.api.state.saved", "sys.api.state.deleted"]) and protected (bool). An entry missing a required field, or a file that does not parse, SHALL NOT stop the TUI: the entry SHALL be skipped and the problem shown at startup.

The active context is state, not config: it SHALL be persisted separately at ~/.local/state/virtufin/api/state.toml (mode 0600). The TUI SHALL keep the catalog-of-contexts vs. active-selection split for every user setting it persists (contexts, LLM providers, themes, event topics). Active-context resolution order SHALL be: CLI --context flag → $VIRTUFIN_TUI_CONTEXT env var → persisted state file → first entry in the file.

Environment variables VIRTUFIN_TUI_API_HOST and VIRTUFIN_TUI_API_PORT SHALL override the active context's host/port in memory when set (the active context as resolved above, the --context flag and $VIRTUFIN_TUI_CONTEXT included).

Every tab SHALL show the active context's name and its connection dot in a row under the tab bar (the Trading tab adds World and Scenario).

Scenario: First-run with no config file

  • WHEN the user runs virtufin-tui and no contexts.toml exists
  • THEN the TUI SHALL seed shipped default configs into ~/.config/virtufin/
  • AND SHALL NOT overwrite existing files (seeded files are mode 0600)

Scenario: Env var override

  • WHEN VIRTUFIN_TUI_API_HOST=staging.virtufin.com and VIRTUFIN_TUI_API_PORT=5002 are exported
  • THEN the TUI SHALL use those values for the active context, regardless of what is in contexts.toml

Scenario: Switch context mid-session

  • WHEN the user selects a different context from the config page
  • THEN the TUI SHALL tear down the existing gRPC channel, DataPump tasks, and event subscription
  • AND SHALL rebuild the client and restart its subscriptions against the new context
  • AND SHALL prepare it as at startup: bootstrap LIVE when missing, then run the init_scripts

Scenario: The config page's tables

  • WHEN the user presses Enter on the config page
  • THEN it SHALL switch context only in the contexts table; on an available pane it SHALL add the pane, in the tabs-and-panes table it SHALL do nothing
  • AND a context going up or down SHALL NOT move the highlight off the context the user picked
  • AND the page SHALL scroll as a whole, so its footer stays on screen

Scenario: A protected context

  • WHEN the active context has protected = true
  • THEN its context row SHALL be red on every tab and say so
  • AND every write the TUI sends to it (worker create/delete/start/stop/tags, worker commands other than status, state saves and deletes, trigger schedule/delete) SHALL wait for the user's yes in a dialog naming it, from pages, dialogs and the AI tab alike; a no SHALL send nothing
  • AND after a yes, the writes of the next 5 s SHALL go through without asking, so one action of several calls asks once

Scenario: A setting changed in the TUI

  • WHEN the user changes the active World or Scenario, the theme, the event topics, the LLM provider or a display toggle (Events' wall/message time) in the TUI
  • THEN the TUI SHALL save it to the state file and SHALL NOT rewrite the user's config file
  • AND for the theme and the display toggles, the config file's value SHALL be the default and the state's the current value

Scenario: A context entry without a port

  • WHEN a contexts.toml entry has no api_port
  • THEN the TUI SHALL start with the other contexts and show that the entry was skipped and why

Scenario: No active context

  • WHEN no context resolves (no contexts.toml, or the persisted name is not among its contexts)
  • THEN the TUI SHALL start on the config page with every context shown not connected, and watch no endpoint
  • AND every pane that needs a context (all but Home and Config; a custom pane opts out with WORKS_UNBOUND = True) SHALL say so instead of opening, and no pane SHALL stop the TUI
  • AND once a context is picked, the pane shown SHALL open for it
  • AND leaving the config page while its switch still connects SHALL NOT fail the switch

Requirement: Client Access via gRPC Reflection

This is the TUI's binding of operator-clients Backend Access through the Gateway: the descriptor path.

The TUI SHALL invoke control-plane RPCs without vendored proto stubs, using the API gateway's reflection RPCs (get_file_descriptor_protos_async) to load message descriptors at runtime. Each backend service SHALL get its own DescriptorPool (pools SHALL NOT be shared — backend protos all declare package virtufin and MAY declare identically-named messages). Control-plane RPCs (ListWorkers, etc.) SHALL be invoked via the raw reflection path (invoke_raw_async) with typed protobuf messages built from the loaded descriptors.

Scenario: List workers via reflection

  • WHEN the TUI reads the workers table
  • THEN it SHALL call WorkManager.ListWorkers through the reflection pipeline (invoke_raw_async), decoding the response from the dynamically-loaded message class

Scenario: One descriptor pool per service

  • WHEN the TUI loads descriptors for more than one backend service
  • THEN it SHALL build a separate DescriptorPool per service
  • AND SHALL NOT share pools between services with colliding package virtufin symbols

Requirement: Worker Operations Surface

The TUI SHALL implement the operator-clients Worker Operations; this requirement is its terminal binding.

The TUI SHALL expose worker CRUD, tagging, and lifecycle operations through the keyboard. List/detail/create/tag/start/stop/delete SHALL be backed by the WorkManager RPCs (ListWorkers, GetTags, GetWorkerHistory, CreateWorker, SetTag, StartWorker, StopWorker, DeleteWorker). Destructive actions (delete) SHALL require a confirmation modal. Tag changes SHALL be undoable for 10 seconds after the change. Start, stop and delete SHALL also apply to many workers at once: the marked ones, or with none marked every worker the filter shows; the TUI SHALL list them before acting, ask once more before deleting, carry on past a worker that fails, and report each worker's result. The Connections page SHALL do the same for stopping publishing and disconnecting.

A worker made from a versioned package of the worker registry SHALL be upgradable in place: the TUI SHALL find the registry entry and the version from the worker's code URL (the entry's templated source_url), offer the entry's versions (the newest first and preselected, an older one to roll back), say what an upgrade keeps and restarts, and load the picked one with LoadCode (the worker keeps its id, topics, config, secrets and tags; a running one restarts with the new code). It SHALL say how many workers have a newer version, and the bulk action SHALL offer upgrading to the latest.

Scenario: Stop everything a filter shows

  • WHEN the user filters the workers by tag:world=act, opens the bulk action with nothing marked and picks Stop
  • THEN the TUI SHALL stop every worker the filter shows, at a bounded number at a time, and report each one's result, the failed ones first
  • AND on a protected context that one choice SHALL be the confirmation for every stop of the run

Scenario: Upgrade a worker in place

  • WHEN a worker runs version 0.1.4 of a registry package whose newest version is 0.1.10 and the user upgrades it
  • THEN the TUI SHALL call LoadCode with the 0.1.10 URL and the entry's source credential, and the worker SHALL keep its id, topics, config and tags
  • AND a worker whose code is no registry package (inline code, another URL) SHALL say there is nothing to load

Scenario: Create a worker

  • WHEN the user invokes the new-worker flow and submits a worker with MIME type, topic, code source, and tags
  • THEN the TUI SHALL call CreateWorker and the new worker SHALL appear in the workers table when its registered lifecycle event arrives

Scenario: Set a tag with undo

  • WHEN the user sets a tag on a worker
  • THEN the TUI SHALL call SetTag, display an undo hint for 2 seconds, and undoing SHALL restore the prior value via SetTag

Scenario: Delete with confirmation

  • WHEN the user invokes the delete action on a worker
  • THEN the TUI SHALL show a confirmation modal; on confirm it SHALL call DeleteWorker; on cancel no action is taken

Scenario: Worker detail

  • WHEN the user opens a worker's detail popover
  • THEN the TUI SHALL aggregate GetTags + GetWorkerHistory + the creation-time config from the latest ListWorkers pass (config is immutable after creation; there is no dedicated get-config RPC)
  • AND it SHALL show the worker's lifecycle events received since the TUI connected (newest first, a bounded number per worker, repeats counted) and its last load-failed or failed with error_type and error_message, since the WorkManager keeps no history of them

Scenario: Workers sorted and filtered

  • WHEN the user presses o on the Workers or Connections table, or clicks a column header
  • THEN the rows SHALL be sorted by the picked column ([/], else the first), again reversed, numbers as numbers, text without case, empty cells last, and the selection SHALL stay on the same worker
  • AND / SHALL filter the Connections pane too, with the value-presentation Worker Filter over each feed (source its URL, topic its publish topic)

Requirement: WebSocket Connection Operations Surface

The TUI SHALL expose WebSocket connection management through the keyboard. A connection SHALL be a WebSocketFeed worker (WebSocket Feed), managed with the WorkManager RPCs: ListWorkers (the workers of type websocketfeed, with their reported status), the WorkManager tag RPCs (GetTags, SetTag), CreateWorker + StartWorker to connect, InvokeWorkerCommand (serve, send, publish, unpublish, status), StopWorker to disconnect and DeleteWorker to remove. Destructive actions (delete) SHALL require a confirmation modal. Tag changes SHALL be undoable for 10 seconds. The connections table SHALL show each feed's latency behind the venue from its metrics (latencyp50ms, latencyp90ms): a sparkline of p50 over the recent intervals and the latest p50/p90, or that the feed reports none. With the feed's venue clock offset (clockoffsetms, clockrttms) it SHALL show the bound (half the round trip), and SHALL mark the latency as carrying clock skew, with the reason in the connection's detail, when p50 is below zero, more than 5 % of the messages were stamped in the future, or the offset exceeds its bound.

Scenario: Connect to a new WebSocket URL

  • WHEN the user invokes the connect action with a URL and auto-reconnect preference
  • THEN the TUI SHALL create a WebSocketFeed worker (url, autoreconnect, autoreload=false) and start it, and the new connection SHALL appear in the connections table when its registered lifecycle event arrives
  • AND the TUI SHALL wait for the feed to connect from its lifecycle status events (subscribed before one status command that covers what happened earlier), never by asking its status repeatedly

Scenario: Send a raw message

  • WHEN the user sends a message to a connection
  • THEN the TUI SHALL call InvokeWorkerCommand(worker_id, "send", payload) with the message as the payload

Scenario: Start and stop publishing

  • WHEN the user starts or stops publishing on a connection
  • THEN the TUI SHALL call InvokeWorkerCommand with publish ({topic}) or unpublish
  • AND the feed's status answer (publishtopic) is the authoritative publishing signal

Scenario: Disconnect is not delete

  • WHEN the user disconnects a connection (after confirmation)
  • THEN the TUI SHALL call StopWorker and then DeleteWorker: the feed closes its socket, nothing reconnects, and the worker is deleted with its tags and saved session, so nothing is left behind
  • AND removing a connection from a world SHALL only clear its world tag, leaving the feed connected

Requirement: Pushed Data, Not Polling

The TUI SHALL implement the operator-clients Pushed Data, Not Polling; this requirement is its terminal binding and the TUI's lists beyond the workers.

The TUI SHALL keep its lists and statuses current from events (gRPC server streaming, Pubsub.Subscribe), not by calling the backend on a timer. Each list SHALL be read once when its subscription is live (and on r), then again only when an event says it changed, with a burst of changes read once. While a subscription is down the TUI SHALL fall back to reading the lists it carries every 2 seconds, so no pane freezes.

Scenario: Workers and connections

  • WHEN the worker lifecycle subscription (sys.workmanager.worker.lifecycle) is live
  • THEN ListWorkers SHALL be read once, and again only after a listing change (registered, deleted, updated, loaded, load-failed, online, stopped, failed)
  • AND a feed's counters and message rate SHALL come from its metrics events (wrk.websocketfeed.metrics), its connection state from its lifecycle status events

Scenario: Triggers

  • WHEN the subscription to sys.api.trigger.scheduled / sys.api.trigger.deleted is live
  • THEN ListTriggers SHALL be read once, and again only after such an event

Scenario: Registries

  • WHEN the TUI saves or deletes a cfg.world, cfg.scenario or cfg.strategy entry
  • THEN it SHALL announce the change (publish_change), and the World, Scenario and Strategy panes SHALL reload on those state-change events instead of on a timer

Scenario: EventStores

  • WHEN the EventStores pane is open
  • THEN each store's counts SHALL come from wrk.eventstore.metrics and its health from its lifecycle status reports; its status command SHALL be asked once per activation, when its metrics show a new failure, and when its code or config changes (updated)

Scenario: New books and indicators

  • WHEN a topic new to the gateway appears (sys.api.topic.catalog.added)
  • THEN the Order Book and Indicators selectors SHALL add the books and indicators among those topics, keeping the selection, and the Instruments pane SHALL add the instruments among them

Scenario: Instruments

  • WHEN the Instruments pane is open
  • THEN it SHALL list every instrument whose instrument.snapshot topic the gateway has seen, any venue and world, with its tick and lot size read once from the instrument state key its order-book worker saves, then from each snapshot event
  • AND an instrument with no saved state and no snapshot since SHALL show its sizes as unknown, not as zero

Scenario: Context liveness

  • WHEN contexts are configured and one is active
  • THEN each context's reachability SHALL come from one grpc.health.v1.Health/Watch stream on its own channel with HTTP/2 keepalive, not from a periodic probe
  • AND each time a context comes up, one keyed call SHALL check its API key (health checks need none)

Scenario: States

  • WHEN the States pane is shown
  • THEN the TUI MAY query state every 2 seconds, and SHALL NOT while it is not shown (state-change events are opt-in per write)
  • AND each value read that differs from its key's newest SHALL be appended to that key's stream (value-presentation, Value Streams)

Requirement: Error Reporting

The TUI SHALL implement the operator-clients Error Reporting: its error notice is a notification, the details go to its log, and a page's stale note is in its status line.

The TUI SHALL report a failed action one way: one error notification naming the action and a readable reason (a gRPC status in words, a refused call as STATUS: message), with the details in its log. When reading data a page shows fails, the page SHALL keep what it shows and say in its status line that it is stale, since when and why, until a read succeeds; it SHALL NOT act on the failed read as if there were no data.

Scenario: Failed action

  • WHEN an action (create, delete, tag, publish, compose, ...) fails
  • THEN the TUI SHALL show <Action> failed: <reason> once

Scenario: Failed read

  • WHEN reading a page's data fails
  • THEN the page SHALL keep its rows and show stale since <time>: <reason> until the next good read
  • AND a failed read SHALL NOT prune saved state (e.g. the World page's world sources)

Requirement: Live CloudEvent Streaming

The TUI SHALL subscribe to Pubsub.Subscribe (the sole subscribe RPC) and append incoming CloudEvents to the events log. The subscription SHALL be parameterized by the context's event_topics (user-editable, persisted to TUI state). On subscription failure the TUI SHALL retry with exponential backoff (1s → 30s cap) and SHALL NOT replay missed events on reconnect. The event log SHALL be a bounded append-only buffer (500 events) with a running total counter.

Scenario: Events flow into the log

  • WHEN the TUI is connected and a CloudEvent is received on a subscribed topic
  • THEN the event SHALL appear once at the bottom of the events log, pretty-printed (type/source/id/topic/time + decoded payload), unless the filter or a picked topic node keeps it out

Scenario: Change subscribed topics

  • WHEN the user adds or removes topics via the events page
  • THEN the TUI SHALL restart the subscription immediately with the new topic set
  • AND SHALL persist the new topic set to TUI state

Scenario: Reconnect on gRPC failure

  • WHEN the subscription drops
  • THEN the TUI SHALL retry with exponential backoff (1s → 30s cap) and surface a backoff status; the event log SHALL be preserved across reconnects

Requirement: World Management

The TUI SHALL manage market-data "worlds" as named abstractions over WebSocket connections. An atomic world SHALL be a WebSocketFeed worker tagged world=<name>; a composite world SHALL be a cfg.world.<NAME> entry (names are uppercase identifiers, listed at cfg.world.index) listing component worlds (with DFS cycle detection before saving). World definitions SHALL be loadable from per-file TOML configs under ~/.config/virtufin/tui/worlds/*.toml, each of type "websocket" (with a venue preset of market-data-devkit and/or ws_url, the topics it serves (topics, or pairs x families, times intervals for interval families, named by the naming library for the world's world), optional [feed] keys, handshake login steps, secrets, reconnect) or "script" (with script, execution_trigger, execution_function, return_type).

The canonical world-open sequence SHALL be: resolve the world's topics with market-data-devkit's resolver (feeds.resolve, owner = the world's name, the world's preset) and refuse, naming them, topics its preset does not serve, topics over a venue's limits or needing more than the world's one connection → create the feed worker with the world's preset config rendered for its world, its topics, overridden by its URL, [feed] keys, login steps (handshake), fixed frames (subscribe), the publish topic of unrouted frames and the tags world/universe/world_source → start it → wait for the status connected → tag publishing → persist.

Scenario: Connect a world

  • WHEN the user connects a world config
  • THEN the TUI SHALL run the canonical open sequence and tag the feed worker with world, universe, and world_source

Scenario: Compose worlds

  • WHEN the user composes two or more worlds into a composite
  • THEN the TUI SHALL persist cfg.world.<NAME> with its component list
  • AND SHALL reject a composition that would create a cycle

Scenario: Replay handshake on reconnect

  • WHEN a world's feed reconnects or moves to another Runtime pod
  • THEN the feed SHALL run the world's login and subscriptions again itself, and the TUI SHALL send nothing

Requirement: Strategy Management

The TUI SHALL manage strategies as named abstractions. An atomic strategy SHALL be a worker tagged type=<name> (derived — no state entry); a composite strategy SHALL be a cfg.strategy.<NAME> entry (names are uppercase identifiers, listed at cfg.strategy.index) listing component strategies (with DFS cycle detection before saving). Creating an atomic strategy SHALL create a worker and tag it with type and source.

Scenario: Create an atomic strategy

  • WHEN the user creates an atomic strategy
  • THEN the TUI SHALL create a worker and tag it with the strategy type and source

Scenario: Compose strategies

  • WHEN the user composes strategies
  • THEN the TUI SHALL persist cfg.strategy.<NAME> with its component list and reject cycles

Requirement: Scenario Management

The TUI SHALL edit the scenario registry (per the Scenarios spec) via the state store at cfg.scenario.<SCENARIO_ID> with the cfg.scenario.index list. LIVE SHALL be reserved (bootstrapped once per connected context, at app startup and on a switch, non-fatal on failure) and rejected as a user-supplied ID. Scenario IDs SHALL match ^[A-Z0-9_]{1,32}$. Deletion SHALL require a double confirmation and SHALL mark deleted, drop the index entry, purge the scenario's sc.<SCENARIO_ID>.* state, and delete the registry entry.

Scenario: Add a scenario

  • WHEN the user adds a scenario with market/portfolio/strategy legs
  • THEN the TUI SHALL persist the triplet to cfg.scenario.<id> and add the ID to cfg.scenario.index
  • AND SHALL reject LIVE and IDs not matching ^[A-Z0-9_]{1,32}$

Scenario: Set the active scenario

  • WHEN the user activates a scenario
  • THEN the TUI SHALL set it active and refresh the trade status bar (which highlights when the active scenario is LIVE)

Scenario: Delete a scenario

  • WHEN the user deletes a scenario
  • THEN the TUI SHALL require a double confirmation, then mark the entry deleted, remove it from cfg.scenario.index, purge its sc.<id>.* state (Scenarios spec, Delete scenario), and delete the registry entry

Requirement: State and Service Browser

The TUI SHALL provide a service browser that enumerates registered services and methods via the gateway reflection RPCs (ListServices, ListMethods), renders a JSON input form, and dispatches invocation through the gateway's dynamic method dispatch. The browser SHALL expose raw JSON invocation only — it SHALL NOT attempt schema-driven form generation for arbitrary methods.

Scenario: Browse services and methods

  • WHEN the user opens the service browser
  • THEN the TUI SHALL list services, then list a selected service's methods, and invoke a method by JSON payload

Requirement: Worker Registry and Schema-Driven Creation

The TUI SHALL support creating workers from a declarative registry at ~/.config/virtufin/tui/workers.toml. Each entry SHALL declare name, mime_type, source_url (templated with {version} or {ref}), config_schema (JSON Schema draft 2020-12), versions, and authentication. The new-worker flow SHALL render a form from config_schema (strings, integers, numbers, booleans, and enums; nested objects skipped with a warning). Source authentication SHALL resolve a SourceCredential (scheme basic/bearer) — "virtufin" SHALL resolve the org's server-resolved shared credential (VIRTUFIN_REGISTRY_CREDENTIAL_NAME), otherwise a named personal credential from credentials.toml.

Scenario: Create a worker from the registry

  • WHEN the user picks a registered worker type
  • THEN the TUI SHALL render a form from config_schema, resolve the source credential, create the worker, and tag it type + source

Scenario: Inline or versioned source

  • WHEN the user supplies inline code, a relative file, a version dropdown, or a fixed URL as the code source
  • THEN the TUI SHALL build the code_source accordingly (inline content base64-encoded) and pass it to CreateWorker

Requirement: Trigger Management

The TUI SHALL list, schedule, and delete cron/point-in-time triggers via the TriggerService stubs (ListTriggers, ScheduleTrigger, DeleteTrigger). The schedule modal SHALL support both cron and point-in-time modes with name, target topic, schedule/due-time, repeat count, and TTL.

Scenario: Schedule a trigger

  • WHEN the user schedules a trigger
  • THEN the TUI SHALL call ScheduleTrigger with the chosen cron or point-in-time parameters

Requirement: AI Assistant

The TUI SHALL ship an AI chat tab that translates natural-language requests into control-plane operations via OpenAI-compatible tool calling. The agent logic SHALL be Textual-free (unit-testable) and SHALL have no privileged path — every tool SHALL map 1:1 to an existing TuiClient/DataPump call. The tool catalog SHALL include create/delete trigger, set event topics, create/start/stop worker, add/connect/remove world. The agent SHALL run a bounded loop (max 5 iterations) and SHALL never raise from tool execution (errors returned as {"ok": false, "error": ...} for the model). A tool that deletes or stops (delete_trigger, stop_worker, remove_world) SHALL run only after the user confirms it in a dialog naming its target; a declined call SHALL be returned to the model as not confirmed.

Scenario: A destructive tool asks first

  • WHEN the model calls stop_worker for worker w1
  • THEN the TUI SHALL ask "Stop worker w1?" and SHALL call StopWorker only on yes

Scenario: Provider resolution

  • WHEN the AI tab resolves a provider
  • THEN it SHALL check VIRTUFIN_TUI_AI_PROVIDER env → persisted default → first ready provider → none
  • AND SHALL show a configure state (disabled input) when no provider resolves

Scenario: Tool execution never raises

  • WHEN a tool call fails
  • THEN the TUI SHALL surface the error to the model as a structured result rather than raising

Requirement: Custom Pane Extension

The TUI SHALL support user-defined panes dropped into ~/.config/virtufin/tui/panes/. Two kinds SHALL be supported: a script + form pair (<name>.py + sibling <name>.form.json, run as a subprocess on submit) and a live widget pane (<name>.py defining a module-level Pane class with a (stores, client, **kwargs) constructor, mounted as a persistent page). Files matching neither pattern SHALL be skipped with a warning.

Scenario: Discover panes

  • WHEN the TUI resolves pane tabs
  • THEN it SHALL scan ~/.config/virtufin/tui/panes/ and map script+form pairs and live-widget classes to pages

Requirement: Kill Switch

The TUI SHALL stop a context's trading with one key (K, on every tab), after listing what it will do and asking twice: it SHALL halt every registered scenario that is not archived or deleted (the trading halt, sc.<S>.trading.halt) and then send cancel-all to every running executor, an executor being a worker serving a sc.<S>.trading.order.submitted topic. It SHALL report per scenario and per executor what was done and what failed. Nothing SHALL resume by itself: the Scenario page halts or resumes one scenario (h, with a confirmation) and shows each scenario's halt. While any scenario is halted the context row SHALL say so on every tab. The AI tab SHALL have no kill switch tool.

Scenario: Kill switch

  • WHEN the user presses K and confirms twice
  • THEN every active or paused scenario SHALL be halted before any executor is asked to cancel, and the report SHALL list the halted scenarios and each executor's canceled orders and failures
  • AND a no at either question SHALL change nothing

Requirement: Alerts Pane

The TUI SHALL collect alerts as the Alerts spec says and show them in an alerts pane (Infra, before events; it works without an active context): one row per alert with when it last came, its severity (an error red, a warning yellow), context, source, subject, text, count and when it first came. d SHALL dismiss the selected alert and c clear the list. The context row SHALL say on every tab how many alerts are unread; showing the pane SHALL read them, and an alert that comes in while it is shown is read. Failed actions SHALL still show their error notice too.

Scenario: A breach while on another tab

  • WHEN the P&L worker publishes a limit breach while the user is on the Trading tab
  • THEN the context row SHALL count one new alert, and the Alerts pane SHALL list it at the top

Requirement: Change Log

The TUI SHALL record every write it sends to a context (a worker created, started, stopped, deleted or tagged, a worker command other than status, a state entry saved or deleted, a trigger scheduled or deleted) with its time, context and outcome: done, failed with the reason, or declined (a no on a protected context). The record SHALL outlive a restart: appended to changes.jsonl in the TUI's state directory, one JSON object per line, bounded in size with one previous file kept. A changes pane (Infra, after alerts; it works without an active context) SHALL list it newest first, a failed write in red. Scripts, which run with their own client, are not recorded.

Scenario: A write on a protected context declined

  • WHEN the user says no to a write on a protected context
  • THEN nothing SHALL be sent, and the change log SHALL list the write as declined

Scenario: After a restart

  • WHEN the TUI starts again
  • THEN the Changes pane SHALL list the writes of earlier sessions

Requirement: Dashboard and Pane Layout

This is the TUI's binding of operator-clients Navigation.

The TUI SHALL render a two-level tab layout (top-level tabs, per-tab sub-tabs) driven by an ordered pane spec. Built-in panes SHALL include home, world, instruments, orderbook, indicators, portfolio, pnl, risk, strategy, scenario, workers, connections, scripts, triggers, states, eventstores, alerts, changes, events, config, and ai. The layout SHALL be user-customizable and SHALL migrate newly-introduced default panes into existing user layouts, and drop default panes taken out of the defaults, without clobbering user edits (a pane_order_version stamp drives a one-time migration). Pages SHALL be Widget subclasses (not Screens) mounted into a shared page body. A page SHALL be built on its first visit and then kept (hidden, still following its data) while another is shown, so it keeps its filter, picked book or account, pause, tree view, cursor and log across tab switches; a context switch SHALL drop the pages of the previous context.

Scenario: Default pane order

  • WHEN the TUI starts with no pane customization
  • THEN the default order SHALL group trading panes (world, instruments, orderbook, indicators, portfolio, pnl, risk, strategy, scenario, ai, config) under a trading tab and infra panes (workers, connections, scripts, triggers, states, eventstores, alerts, changes, events, ai, config) under an infra tab
  • AND each of portfolio, pnl and risk SHALL be inserted into a saved layout once, when its data ships, like instruments (tui#23)

Scenario: Placeholders hidden until they have data

  • WHEN a saved layout from before the placeholders were hidden is loaded
  • THEN the migration SHALL drop instruments, portfolio, pnl and risk from the default tabs once
  • AND a placeholder the user adds back afterwards SHALL stay, and a custom tab SHALL keep its panes
  • AND a pane that has data since (instruments tui#23, portfolio tui#24, pnl tui#25, risk tui#26: all four) SHALL be inserted at its default position once, like a newly-introduced default pane

Scenario: Pane migration preserves user edits

  • WHEN a new default pane is introduced in a later release
  • THEN the migration SHALL insert it at its default position only if the user's pane_order_version is behind the new version
  • AND SHALL NOT re-add a pane the user previously removed: an upgrade SHALL add only the panes added since the saved version (each version records the panes it adds), not every default pane missing from the layout

Requirement: Command Palette

ctrl+p SHALL open a command palette that finds, as the user types, every command of where it was opened: each key of the current page it implements (named with that key), going to any pane of the layout, the kill switch, the keys overview, and switching to any other configured context (the same switch as the Config page's, only once the context's api answers), next to Textual's own commands.

Scenario: Run a page action from the palette

  • WHEN the user is on the Workers page, opens the palette and picks Bulk (b)
  • THEN the TUI SHALL do what b does there, and the palette SHALL NOT offer keys the page does not implement

Requirement: Keyboard Dispatch

The TUI SHALL expose per-page actions via a single dashboard binding table, with first-match-wins dispatch and footer visibility gated on whether the current page implements the action. Navigation SHALL support right/left to cycle top-level tabs (priority bindings; a press while a switch runs SHALL count), 1–9 and 0 (the tenth) to switch sub-tabs, and </> to step through them, so a pane past the tenth is reachable. ? SHALL show the help overlay, in a dialog too; q SHALL quit after asking. Every page's keys SHALL go through the dashboard table, so the footer shows them.

Scenario: One meaning per key

  • WHEN a page offers to add, delete, act on or open its rows
  • THEN a SHALL add, d SHALL delete, m SHALL open the row's actions, and Enter SHALL open the row (labelled Open) or make it the one in use (labelled Use: a world, scenario or context), on every page
  • AND no key SHALL be labelled with two of these meanings on different pages

Scenario: Live changes ask first

  • WHEN a single key would stop something live: stopping a world's feed, pausing a scenario, quitting
  • THEN the TUI SHALL ask before doing it; resuming or starting SHALL NOT ask
  • AND q pressed again in the quit question SHALL quit

Scenario: Undo a tag change

  • WHEN the user sets or clears a tag
  • THEN Ctrl+Z SHALL undo it for 10 seconds, as long as the toast saying so is shown

Scenario: Page-conditional bindings

  • WHEN the user presses a bound key on a page that does not implement the action
  • THEN the key SHALL be hidden from the footer help for that page
  • AND SHALL dispatch to the first matching action when present

Scenario: No refresh key

  • WHEN anything a page shows changes on the platform
  • THEN the page SHALL update by itself from events, so the TUI SHALL have no refresh key (r runs a script on Scripts only)

Scenario: An empty list

  • WHEN a page's list is empty
  • THEN its status line SHALL say how to add the first entry (the key, or the page where it is added)

Scenario: Focus on a page's table

  • WHEN a page is opened that has a table
  • THEN the table SHALL have focus, not a filter or selector above it, so Enter and space reach the page's actions
  • AND a page without a table SHALL focus its first shown widget, never a hidden one (the closed filter line)

Requirement: Filtering

This is the TUI's binding of the filtering of operator-clients Tables.

The States and Events panes SHALL share one filter on /, evaluating the value-presentation Filter Expressions on their Values, with the kinds of the shipped representations.json and of the user's ~/.config/virtufin/tui/representations.json when it exists. The Workers pane SHALL have the same filter line on /, evaluating the value-presentation Worker Filter on its workers, its status line showing the expression and the shown and listed counts.

The table panes (World, Instruments, Indicators, Portfolio, P&L, Risk, Strategy, Scenario, Triggers, EventStores, Alerts, Changes) SHALL have the same filter line on / over their rows: a word SHALL match any cell, a field SHALL name a column (its header lower-cased, other characters as _) and match that column's cell, -term SHALL exclude, with the value-presentation Filter Expressions rules for case, patterns and quoting. A pane SHALL show the expression and the shown and total row counts. The Order Book, a price ladder, SHALL have no filter.

Scenario: Open, type, keep, clear

  • WHEN the user presses / on the States or Events pane
  • THEN a filter line SHALL open with the current expression and take the focus, and the list SHALL re-filter on each keystroke
  • AND Enter SHALL keep the expression and give the focus back to the list, and Esc SHALL clear it and give the focus back to the list
  • AND the expression SHALL be kept per pane for the session, not saved

Scenario: Events already received

  • WHEN the filter changes on the Events pane
  • THEN the buffered events received since the last clear (c) SHALL be shown again through it, not only the events that arrive afterwards
  • AND the status line SHALL show the expression and the shown and received counts

Scenario: A bad expression

  • WHEN the expression does not parse
  • THEN the filter line SHALL mark it as an error, the status line SHALL say why, and the list SHALL stay unfiltered until it parses

Scenario: Selection kept

  • WHEN the filter changes on the States pane and the selected key still passes
  • THEN it SHALL stay selected

Scenario: Workers by tag

  • WHEN the user presses / on the Workers pane and types tag:world=act
  • THEN only the workers whose world tag contains act SHALL be listed, and Esc SHALL list all again with the focus on the table

Scenario: Table rows by column

  • WHEN the user presses / on the Instruments pane and types pair:ETH*
  • THEN only the rows whose Pair starts with ETH SHALL be shown, the header SHALL show the expression and shown/total, and Esc SHALL show all rows again

Scenario: Two tables, one filter

  • WHEN the filter on the Portfolio pane names a field
  • THEN each table SHALL be filtered by its own columns, and a table without that column SHALL show no rows

Scenario: Selection by key

  • WHEN the filter changes on a registry pane or the Triggers pane and the selected row still passes
  • THEN it SHALL stay selected

Scenario: Keys while typing

  • WHEN the filter line has the focus
  • THEN left and right SHALL move the cursor in it, not switch the view, and digits SHALL be typed, not pick a sub-tab

Requirement: Flat or Tree

The States and Events panes SHALL show their keys or topics flat or as the value-presentation Name Tree, switched with T and kept per pane for the session.

Scenario: States as a tree

  • WHEN the user presses T on the States pane
  • THEN the table SHALL give way to the tree of the shown keys, each leaf with its value's preview, and T again SHALL bring the table back with the same filter

Scenario: Events by topic

  • WHEN the user presses T on the Events pane
  • THEN the tree of the topics of the buffered events SHALL appear beside the log, growing as events arrive, and picking a node SHALL show only that node's events in the log (a topic, a leaf, opens its stream: Value Representations in the TUI)

Requirement: Value Representations in the TUI

The TUI SHALL implement the value-presentation spec (Values, Value Streams, Kinds by Instance, Representation Mapping, Representations, Conformance) for the States, Events and Indicators panes, and SHALL ship the default representations.json, its JSON Schema and the conformance vectors. The user's mapping SHALL be ~/.config/virtufin/tui/representations.json.

The TUI SHALL draw the representations with Textual widgets; the stream representation plot.line SHALL be drawn with textual-plotext.

Scenario: Cycle representations

  • WHEN a Value or stream is shown and has more than one representation the TUI implements
  • THEN v SHALL show the next one in mapping order, wrapping around

Scenario: A state key in its representations

  • WHEN the user presses Enter on a key in the States pane (table row or tree leaf)
  • THEN the key's value SHALL open in its first representation in place of the list, following the key's newest value, h SHALL switch between the value and the key's stream (the values read while the pane was shown), and Esc SHALL return to the list
  • AND each key's preview in the table and the tree SHALL be its value's first representation on one line

Scenario: A topic in its representations

  • WHEN the user picks a topic (a leaf) in the Events pane's topic tree (Flat or Tree)
  • THEN that topic's stream SHALL be shown in its first stream representation in place of the log, h SHALL switch to its newest event as a Value and back, and Esc SHALL return to the log
  • AND the log of all subscribed topics SHALL stay as it is; picking a node that is not a leaf SHALL narrow it as before

Scenario: An indicator in its representations

  • WHEN the user presses Enter on a pair's row in the Indicators pane
  • THEN that pair's indicator stream (the saved value, then each changed event while the pane shows the indicator) SHALL open in its first stream representation in place of the table, v SHALL show the next one, h SHALL switch between the stream and its newest Value, and Esc SHALL return to the table

Requirement: Portfolio, P&L and Risk Panes

The portfolio, pnl and risk panes SHALL show data, each seeded from State in one read and then following its events (Pushed Data, Not Polling), with names from the owning devkits (virtufin.portfolio, virtufin.positions).

Scenario: Portfolio

  • WHEN the Portfolio pane is shown
  • THEN it SHALL offer the accounts whose account.snapshot topics the gateway has seen (new ones joining by themselves), and for the picked account show its balances (asset, free, locked, total; zero balances hidden until toggled) and open orders (symbol, side, type, qty, filled, price, status, time), seeded from the account state key and followed through account.snapshot, balance.changed and openorder.changed
  • AND a change that arrives while the saved account loads SHALL be applied on top of it, not dropped (the worker publishes a change before its background write of the account)

Scenario: P&L

  • WHEN the P&L pane is shown
  • THEN it SHALL offer the scenarios of the registry, and for the picked scenario show one row per symbol (qty, average cost, mark, unrealized, realized, fees) and a total line, seeded from sc.<S>.pnl.book and followed through pnl.realized.update and pnl.unrealized.update
  • AND a scenario with no P&L book SHALL say that no P&L worker runs for it
  • AND events that arrive while the book is read SHALL cause one more read after it, of the scenario picked by then (not one read per event)

Scenario: Risk

  • WHEN the Risk pane is shown
  • THEN it SHALL show for the picked scenario one row per symbol (qty, mark, notional, share, limit, status) and a total line (gross, net, limit), from risk.exposure.update, seeded from sc.<S>.pnl.book and the registry's limits; a breached row SHALL be red
  • AND l SHALL set the scenario's limits in its registry entry (an empty field removes that limit), and editing the scenario SHALL keep them

Scenario: An account nothing produces

  • WHEN the picked account has no saved account and no event arrives within 10 seconds
  • THEN the Portfolio pane SHALL say that nothing produced it and ask whether a portfolio worker runs for it, and SHALL show the account as soon as a saved account or an event arrives

Requirement: Distribution as a Single Python Package

The TUI SHALL be distributed as a single pip-installable Python package built with hatchling, exposing a virtufin-tui console script entry point that calls virtufin_tui.app:main. It SHALL be runnable without installation via uvx --from virtufin-tui virtufin-tui. The package SHALL depend on textual[syntax], textual-plotext, virtufin-api, grpcio, openai, pydantic, and tomlkit. The version SHALL be pinned in versions.env as LIBRARY_VERSION.

Scenario: uvx run

  • WHEN the user runs uvx --from virtufin-tui virtufin-tui
  • THEN the TUI SHALL launch against the active context (or the config page if none is configured)

Scenario: Pinned version

  • WHEN CI builds the package
  • THEN it SHALL inject LIBRARY_VERSION from versions.env into pyproject.toml before building

Requirement: Order Book Pane

The orderbook pane SHALL show the chosen book (any venue and world the gateway has seen a book topic of) as orderbook.ladder, drawn as the States and Events views draw it: the TUI SHALL draw the bars with block characters (eighths of a cell), asks red and bids green.

Scenario: The pane and the views draw one ladder

  • WHEN the same book is shown in the Order book pane and as orderbook.ladder in the Events pane
  • THEN both SHALL show the same levels with the same bars

Scenario: A book nothing produces

  • WHEN the picked book has no saved book and no event arrives within 10 seconds
  • THEN the Order book pane SHALL say that nothing produced it and ask whether an order-book worker runs for it, and SHALL show the book as soon as one arrives

Requirement: Bounded Table Cells

This is the TUI's binding of the bounded cells of operator-clients Tables.

Every table in the TUI SHALL bound its cells by table_max_column_width (W, default 60) and table_max_row_height (H, default 5) from ~/.config/virtufin/tui/config.toml: a cell wider than W SHALL wrap inside its column, and a row SHALL be at most H lines high.

Scenario: A wide cell

  • WHEN a cell's text is wider than W
  • THEN it SHALL wrap at W (a word longer than W folded), and its column SHALL be no wider than W plus the scrollbar

Scenario: A tall cell

  • WHEN a cell's content is taller than H lines
  • THEN its row SHALL be H lines high and the cell SHALL show H lines and a scrollbar at its right edge whose thumb shows the position

Scenario: Scrolling a row

  • WHEN the user presses shift+down or shift+up on a selected row with a scrollbar
  • THEN its cells SHALL scroll by one line, the mouse wheel SHALL keep scrolling the table, and a refresh of the table SHALL keep the row's position

Scenario: Settings

  • WHEN the user sets table_max_row_height = 3 and table_max_column_width = 40
  • THEN every table SHALL use them from the next start

Requirement: Resizable Columns

This is the TUI's binding of the resizable columns of operator-clients Tables.

The user SHALL be able to set the width of any column of any table in the TUI, by keyboard and by mouse; a width the user set SHALL replace the column's automatic width (Bounded Table Cells) and SHALL be remembered.

Scenario: Sideways

  • WHEN a table is wider than the screen
  • THEN shift+left and shift+right SHALL scroll it sideways (left/right switch tabs), and a column picked with [ or ] SHALL be scrolled into view

Scenario: Resize by keyboard

  • WHEN the user presses [ or ] in a table
  • THEN the previous or next column SHALL be picked and its header highlighted, - and + SHALL make it one character narrower or wider, and its cells SHALL wrap at the new width

Scenario: Back to automatic

  • WHEN the user presses = on a picked column
  • THEN the column SHALL take its automatic width again and the set width SHALL be forgotten

Scenario: Resize by mouse

  • WHEN the user drags a column boundary, in the header or in any row, from within two cells of it
  • THEN the column SHALL follow the pointer, at least one character wide

Scenario: Handles

  • WHEN a table is shown
  • THEN each column boundary SHALL be marked in the header, and the mark SHALL be highlighted while the pointer is within two cells of that boundary

Scenario: Remembered

  • WHEN the user set a column's width and restarts the TUI
  • THEN the same table's column with the same header SHALL have that width, kept in ~/.local/state/virtufin/tui/state.json