Skip to main content

ek_ui/
plugin.rs

1//! `UiPlugin` —— 总线面:`eLog` 入环形日志、`ePlugUp/Down` 记事件 + rev、
2//! `eBar`./`eBarUpdate.` 记行情库(K线窗数据面)、`eTick.` 记 tick 库(v4 行情带
3//! 唯一源,S7 上屏地面)、`eContract.`/`eContractFinish` 记合约表,
4//! **0.5 M1 起 `eOrder.`/`eTrade.`/`ePosition.`/`eAccount.` 四条推送线入交易账本**
5//! (基线 BaseMonitor 同形:后台只 put,界面自己 process_event)。
6//! `eTimer`(1s 宿主自带)那一拍只做三件事:管制面快照(`svctl.list`,每
7//! `LIST_POLL_TICKS` 拍)、**待播种队列**触发的状态播种(`seed_status`:网关刚上线/
8//! 刚重连时一次性问 `{gw}.status`,常态**零轮询** —— 0.7.0 第3刀退役了 0.5 时代的
9//! 摊平状态轮询,登录态读数吃 `eStatus.` 推送)、被标记时才问一次的装配显形
10//! (`oms.pipeline_status`)。**这一拍不再问交易数据,
11//! 也不再辞行操作指令** —— 指令由命令线程执行(0.5 M5,点击即发)。
12//!
13//! 纪律(D1):UI 不周期取数;唯一例外是观测面 `svctl.list`(基线里对应物是同进程
14//! 直读,不是推送)。纪律(D2):后台只 put、不驱动界面 —— 入账 worker 里没有任何 ask。唯一管制面是 ask 契约(svctl / dm.reload /
15//! oms 查询与 submit_order·cancel_order / ctp 配置订阅,全部与
16//! headless 同源;`PluginContext` 只在 worker 可用)。0.1.1 BD-UI-30:
17//! 下单/撤单直发网关的旁路口删除——风控与守卫不可绕过。0.2.10 BD-UI-38:
18//! sim 纸面网关退场(流控查询口随之撤)。
19
20use std::sync::OnceLock;
21use std::time::Duration;
22
23use ek_core::context::PluginContext;
24use ek_core::plugin::Plugin;
25use ek_core::service::{PlugNotice, ServiceDesc};
26use ek_core::{EVENT_PLUG_DOWN, EVENT_PLUG_UP};
27use ek_ctp::plugin::{
28    ConfigureReply, ConfigureReq, DisconnectReply, DisconnectReq, GatewayStatus, StatusReq,
29    SubscribeReply as CtpSubscribeReply, SubscribeReq as CtpSubscribeReq,
30};
31use ek_data::account::AccountData;
32use ek_data::event::{EVENT_BAR, EVENT_CONTRACT, EVENT_LOG, EVENT_TICK};
33use ek_data::log::LogData;
34use ek_data::order::OrderData;
35use ek_data::position::PositionData;
36use ek_data::trade::TradeData;
37use ek_dm::plugin::{EVENT_BAR_UPDATE, ReloadReq};
38use ek_event::EVENT_TIMER;
39use ek_oms::plugin::{
40    GetAllAccountsReq, GetAllOrdersReq, GetAllPositionsReq, GetAllTradesReq, OmsCancelOrderReq,
41    OmsCancelReply, PipelineStatusReq, SubmitOrderReq,
42};
43use ek_oms::{SubmitReply, SubmitStatus};
44use ek_station::wire::{
45    ListReq, PlugRow, RemoveReq, RemoveRes, SVC_LIST, SVC_REMOVE, SVC_START, StartReq, StartRes,
46};
47
48// 配置托底三口的 ask 面(0.6.0 环节8);id 以 ek-cfg `cfg_services()` 单源
49// (逐角取,不本地复定义字面 —— 服务名将来若改,编译/运行端对上就行)。
50// 类型面单源同在 ek-cfg:cfg.save 的 SaveReq/SaveRes ui 现时没有消费方
51// (重存段走 cfg.list 读档发 SaveReq 的是上半执面外的 cmd 线;布局待偿),
52// 0.6.3 clippy 清债撤这两个未用别名 —— 上游契约仍在,用到时再加回。
53//   cfg.list   = CfgListReq/CfgListRes(目录;零值面)
54//   cfg.delete = CfgDeleteReq/CfgDeleteRes(抹键/清段)
55use ek_cfg::wire::{
56    DeleteReq as CfgDeleteReq, DeleteRes as CfgDeleteRes, ListReq as CfgListReq,
57    ListRes as CfgListRes,
58};
59
60/// `cfg.list` / `cfg.delete` 服务 id(单源自 ek-cfg `wire::cfg_services()` 的
61/// 表位;此处取第 2/3 行)。加载期一次,不重复算。
62fn cfg_svc_ids() -> (String, String, String) {
63    let descs = ek_cfg::wire::cfg_services();
64    let id = |i: usize| -> String {
65        descs
66            .get(i)
67            .map_or_else(|| format!("cfg.svc[{i}]"), |d| d.id.clone())
68    };
69    (id(0), id(1), id(2))
70}
71
72/// 配置托底存储根(与 station 工厂 `ek_cfg::CfgPlugin::eco_or_local` 同口径:
73/// eco 成功 = 生态配置目录;失败 = 仓内 `./ekcfg-local`)。命令线程直接落库
74/// 的「重存段」與目录行共根的保证点。
75fn ui_cfg_store() -> ek_cfg::Store {
76    match ek_cfg::Store::eco() {
77        Ok(s) => s,
78        Err(e) => {
79            eprintln!("ek-cfg:运维修复根 eco 失败({e}),回落仓内 ./ekcfg-local(显形口径)");
80            ek_cfg::Store::with_root(std::path::PathBuf::from("ekcfg-local"))
81        }
82    }
83}
84
85/// **主题档的存储键位(0.8.0 配色双档,BD-UI-61)**:`ns="ui"` / `key="theme"`。
86///
87/// 为什么走存储根直用 `Store` 而不是总线:`cfg.list` 回包按契约**只有键名 + 形态标志,
88/// 没有值**(BD-CFG-18 安全视图),契约里没有「读值」的口 → 走总线必然破契约。
89/// 直用 `Store` 是 0.6.0 起的既有口径(BD-CFG-10 soft-centralized,`CfgResave` 同源同根)。
90/// 只有**用户手点过**切换钮才落盘(照参考站「只有点击才存 localStorage」);
91/// 运维窗「清段 ui」= 主题回缺省深色,与既有运维语义自洽。
92pub const THEME_NS: &str = "ui";
93/// 段里的键名。
94pub const THEME_KEY: &str = "theme";
95
96/// 读档(启动时一次,命令线程;选单窗在插件起来之前也用它)。
97/// 读不到(段不存在 / 键不存在 / 脏值 / 读失败)= **缺省深色**(裁定 B:现行为零变化)。
98#[must_use]
99pub fn load_theme() -> crate::tokens::Theme {
100    match ui_cfg_store().load(THEME_NS) {
101        Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => map
102            .get_plain(THEME_KEY)
103            .map(crate::tokens::Theme::from_str)
104            .unwrap_or_default(),
105        Ok(ek_cfg::LoadOutcome::Fresh) => crate::tokens::Theme::default(),
106        Err(e) => {
107            eprintln!("ek-cfg:读主题档失败({e}),按缺省深色起界面");
108            crate::tokens::Theme::default()
109        }
110    }
111}
112
113/// 落盘当前档(命令线程 / eTimer 拍;一次小文件写,只在用户手点后发生)。
114fn save_theme(theme: crate::tokens::Theme) -> Result<(), String> {
115    let map = ek_core::SectionMap::new(1).set(THEME_KEY, ek_core::Field::plain(theme.as_str()));
116    ui_cfg_store()
117        .store(THEME_NS, &map)
118        .map_err(|e| e.to_string())
119}
120
121use crate::state::{BusSnap, UiShared};
122
123/// 注册名 = 工厂名 = `"ui"`(BD-U5:两者一致)。
124pub const UI_NAME: &str = "ui";
125
126/// 界面邮箱**软顶**(0.5 M6 首发;0.7.0 背压刀改语义,数值照旧)。
127///
128/// 0.4 口径:界面是链上唯一覆写容量的插件,10 万格把"30 条/秒的行情 34 秒就丢"
129/// 变成"55 分钟"。0.5.0 起邮箱**无界** → 这个数不再是容量(到顶必丢),而是**软顶**
130/// (到顶才丢的那一格):默认一条都不丢,只有积压堆到 10 万帧才说明界面 worker
131/// 已经被彻底甩开,那时保护进程比保住行情更重要 → 开始丢新帧并把 `spilled` 涨起来。
132/// 数值取 10 万的理由不变:一帧 tick ≈ 30 条/秒 ≈ 55 分钟的量,内存上限也就是这个量级。
133/// 越阈显形(黄 6250 / 红 25000,`state::pending_thresholds`)在运维窗与 toast 双路可见。
134pub const UI_MAILBOX_SOFT_CAP: u64 = 100_000;
135
136/// 交易四表的推送线(基线 `event.py:13-18`;ek-ctp 0.4.0 起发裸键,ek-core 精确匹配)。
137/// 名字单源取 ek-oms::wire —— 同一条线在链上只有一份拼写。
138const W_ORDER: &str = ek_oms::wire::EVENT_ORDER;
139const W_TRADE: &str = ek_oms::wire::EVENT_TRADE;
140const W_POSITION: &str = ek_oms::wire::EVENT_POSITION;
141const W_ACCOUNT: &str = ek_oms::wire::EVENT_ACCOUNT;
142
143/// 常驻观测插件(窗口面在 [`crate::runtime`] 持 [`UiShared`] 渲染)。
144pub struct UiPlugin {
145    shared: std::sync::Arc<UiShared>,
146    ctx: OnceLock<PluginContext>,
147    /// 命令线程的停线位(0.5 M5;on_stop 置真,线程自己退)。
148    cmd_stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
149}
150
151impl UiPlugin {
152    /// 与窗口面共用的共享状态句柄。
153    pub fn new(shared: std::sync::Arc<UiShared>) -> Self {
154        Self {
155            shared,
156            ctx: OnceLock::new(),
157            cmd_stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
158        }
159    }
160
161    /// eTimer 节流回调(0.7.0:管制面快照 + 标记触发的状态播种 + 标记触发的装配显形;
162    /// 0.5 时代的「摊平状态轮询」已被第3刀退役,常态零轮询 = 判据 C13)。
163    fn refresh(&self) {
164        let Some(ctx) = self.ctx.get() else {
165            return; // 未 init 就吃到 eTimer:忽略,等下轮
166        };
167        // 0.5 M3/M5:这一拍只做三件事,而且都不问交易数据。
168        // 指令辞行搬到命令线程(`spawn_cmd_thread`);四张表吃 eOrder. / eTrade. /
169        // ePosition. / eAccount. 推送入账(基线 BaseMonitor 同形)—— 这一拍里再出现
170        // 任何「取数类 ask」就是回到 0.4 的病。
171        if self.shared.list_poll_due() {
172            self.poll_list(ctx);
173        }
174        self.seed_status(ctx);
175        if self.shared.take_pipeline_due() {
176            self.poll_pipeline(ctx);
177        }
178        if self.shared.take_cfg_due() {
179            // 配置托底段目录(0.6.0 环节8):观测面读数,轻 IO 一次(与 poll_pipeline
180            // 同档的「观测面例外」,不进周期节拍 —— 只在钮触/回执后续问触发)。
181            self.poll_cfg(ctx);
182        }
183        if self.shared.take_theme_persist_due() {
184            // 0.8.0 配色双档:用户手点切换钮后的那次落盘(渲染线程零文件 IO,写在这拍)。
185            let theme = self.shared.theme();
186            match save_theme(theme) {
187                Ok(()) => self
188                    .shared
189                    .log_line(format!("[ui] 主题已存(ui.theme={})", theme.as_str())),
190                Err(e) => self
191                    .shared
192                    .log_line(format!("[ui] 主题落盘失败:{e}(本次切换只在本次运行内生效)")),
193            }
194        }
195    }
196
197    /// 配置托底段目录(0.6.0;`cfg.list` 零值面,BD-CFG-17/18)。
198    fn poll_cfg(&self, ctx: &PluginContext) {
199        let (_, svc_list, _) = cfg_svc_ids();
200        match ctx.ask_service::<CfgListReq, CfgListRes>(
201            svc_list.as_str(),
202            CfgListReq,
203            Duration::from_secs(2),
204        ) {
205            Ok(res) => {
206                self.shared.set_cfg_briefs(res.entries);
207                if !res.msg.is_empty() {
208                    self.shared
209                        .log_line(format!("[cfg] 目录:{msg}", msg = res.msg));
210                }
211            }
212            Err(e) => self
213                .shared
214                .log_line(format!("[cfg] 段落目录失败(cfg 缺席或超时): {e:?}")),
215        }
216    }
217
218    /// 管制面快照(`svctl.list`):谁在场 + 服务目录 + 邮箱溢出计数。
219    ///
220    /// 0.5 M3 降到每 `LIST_POLL_TICKS` 拍一次。它给的不是交易数据而是「宿主长什么样」
221    /// 的观测面 —— 基线里的对应物是 `get_all_gateway_names` 的同进程直读,不是推送,
222    /// 所以它留在白名单里(「界面不周期取数」这条纪律的唯一例外)。
223    fn poll_list(&self, ctx: &PluginContext) {
224        match ctx.ask_service::<ListReq, Vec<PlugRow>>(SVC_LIST, ListReq, Duration::from_secs(2)) {
225            Ok(rows) => {
226                let mut services = Vec::with_capacity(rows.len());
227                for r in &rows {
228                    let ids = ctx
229                        .services_of(&r.name)
230                        .map(|v| v.iter().map(|s| s.id.clone()).collect::<Vec<_>>())
231                        .unwrap_or_default();
232                    services.push((r.name.clone(), ids));
233                }
234                // 账户在场位回填 + 「实例没了就作废会话读数」。
235                // 0.5:「新装配」不再由这里检测 —— ePlugUp. 已订阅,即时且不靠轮询。
236                self.shared.sync_accounts_connected(&rows);
237                // 0.4.5(P7d):邮箱溢出的当场显形。运维窗那一列一直有 spilled,
238                // 但 ek-core 的 stderr 诊断每 128 条才打一条 —— 屏上此前没有任何东西。
239                self.shared.note_plugin_spill(&rows);
240                self.shared.set_snapshot(BusSnap { rows, services });
241            }
242            Err(e) => self.shared.log_line(format!("[ui] svctl.list 失败: {e}")),
243        }
244    }
245
246    /// 一次性状态播种(0.7.0 第3刀:周期轮询退役)。
247    ///
248    /// 常态**零轮询**:登录态/断供读数全靠 `eStatus.` 推送到货。这里只处理
249    /// 「网关刚上线(或刚重连)」的待播种队列 —— 每网关运行期至多一次 ask,
250    /// 拿初始快照(推送是变化触发,刚上线还没有变化,界面得有一份起点)。
251    /// 只读口不写日志(ek-ctp D-STATUS ④),播种不冲 eLog 环。
252    fn seed_status(&self, ctx: &PluginContext) {
253        for gw in self.shared.take_status_seeds() {
254            let svc = format!("{gw}.{}", ek_ctp::SVC_STATUS);
255            match ctx.ask_service::<StatusReq, GatewayStatus>(
256                &svc,
257                StatusReq,
258                Duration::from_secs(2),
259            ) {
260                Ok(st) => self.shared.note_gateway_status(&gw, &st),
261                Err(e) => {
262                    // 打 Display(不是 Debug):超时行自带「目标积压 N 帧」(ek-core 0.5.0)。
263                    // **不排回队列重试**:常态零轮询是这一刀的判据(C13),问不到就留在
264                    // 「无证据」态等推送 —— `eStatus.` 一到,读数立刻归位。
265                    self.shared.note_status_unreachable(&gw, &format!("{e}"));
266                }
267            }
268        }
269    }
270
271    /// 装配显形(0.5 M3 改事件触发):`oms.pipeline_status` 只在被标记的那一拍问一次。
272    ///
273    /// 标记来自启动、`ePlugUp.oms` 与运维窗的刷新钮。它此前是每 4 拍一次的轮询 ——
274    /// 装配很少变,而它是 oms worker 上又一次串行 ask;在事件驱动模型里这种轮询是多余的。
275    fn poll_pipeline(&self, ctx: &PluginContext) {
276        match ctx.ask_service::<PipelineStatusReq, Vec<String>>(
277            ek_oms::SVC_PIPELINE_STATUS,
278            PipelineStatusReq,
279            Duration::from_secs(2),
280        ) {
281            Ok(lines) => self.shared.set_pipeline_lines(lines),
282            Err(e) => {
283                // 不每拍刷日志:oms 不在场是合法态(清单里没选它,ask 走 TargetGone
284                // 快错)。只在「从有到无」那一次显形一条,与状态轮询「只读口不冲 eLog 环」
285                // 同口径。读数清空 → 运维窗那一节整节不画。
286                if !self.shared.pipeline_lines().is_empty() {
287                    self.shared
288                        .log_line(format!("[ui] oms.pipeline_status 失手: {e:?}"));
289                }
290                self.shared.set_pipeline_lines(Vec::new());
291            }
292        }
293    }
294
295    /// 启动一次四问(0.5 M4;基线无对应物 —— 插件热插拔是 ek 独有场景)。
296    ///
297    /// 一次性,不是周期:之后四张表只吃推送。走 `note_*` 而不是 `seed_trade_snap`,
298    /// 是为了**合并而不是覆盖** —— 网关可能在 oms 还没消化完之前就已经把委托推给了
299    /// 界面,覆盖式播种会把界面已经看见的那一笔抹掉。
300    ///
301    /// 执行位置 = 命令线程(0.5 执行核查改的):原先它挂在 `on_start` 里,而 `on_start`
302    /// 是宿主启动序列的一部分 —— 四口最坏 4 × 2 秒会把后面插件的启动一起拖住;挂在
303    /// 入账 worker 上又违反「入账 worker 里没有任何 ask」。所以它跟着命令线程走。
304    fn reconcile_trade(shared: &UiShared, ctx: &PluginContext) {
305        let orders = ctx.ask_service::<GetAllOrdersReq, Vec<OrderData>>(
306            "oms.get_all_orders",
307            GetAllOrdersReq,
308            Duration::from_secs(2),
309        );
310        let trades = ctx.ask_service::<GetAllTradesReq, Vec<TradeData>>(
311            "oms.get_all_trades",
312            GetAllTradesReq,
313            Duration::from_secs(2),
314        );
315        let positions = ctx.ask_service::<GetAllPositionsReq, Vec<PositionData>>(
316            "oms.get_all_positions",
317            GetAllPositionsReq,
318            Duration::from_secs(2),
319        );
320        let funds = ctx.ask_service::<GetAllAccountsReq, Vec<AccountData>>(
321            "oms.get_all_accounts",
322            GetAllAccountsReq,
323            Duration::from_secs(2),
324        );
325        let mut n = 0usize;
326        if let Ok(rows) = &orders {
327            for o in rows {
328                shared.note_order(o);
329            }
330            n += rows.len();
331        }
332        if let Ok(rows) = &trades {
333            for t in rows {
334                shared.note_trade(t);
335            }
336            n += rows.len();
337        }
338        if let Ok(rows) = &positions {
339            for p in rows {
340                shared.note_position(p);
341            }
342            n += rows.len();
343        }
344        if let Ok(rows) = &funds {
345            for a in rows {
346                shared.note_funds(a);
347            }
348            n += rows.len();
349        }
350        // 只在真播种到东西时落一条;空清单(刚装配、柜台还没回报)不刷日志。
351        if n > 0 {
352            let bad = usize::from(orders.is_err())
353                + usize::from(trades.is_err())
354                + usize::from(positions.is_err())
355                + usize::from(funds.is_err());
356            shared.log_line(format!(
357                "[ui] 启动播种 {n} 行(委托 {} / 成交 {} / 持仓 {} / 资金 {};失手 {} 口)",
358                orders.as_ref().map_or(0, |v| v.len()),
359                trades.as_ref().map_or(0, |v| v.len()),
360                positions.as_ref().map_or(0, |v| v.len()),
361                funds.as_ref().map_or(0, |v| v.len()),
362                bad
363            ));
364        }
365    }
366
367    /// 命令线程(0.5 M5):点击即发,不等 eTimer 拍,也不占 ui 的入账 worker。
368    ///
369    /// 基线对应物是「UI 主线程直调 `main_engine.send_order`,立即返回」(engine.py:915-923)。
370    /// ek-core 的 ask 是同步的,所以把「等回包」这件事从入账线程挪走:入账线程从此只
371    /// 做「收事件 → 写账本」,每事件 O(1),永不被后端拖住。
372    /// 这一条线程也是「会等的东西」唯一允许待的地方:启动一次四问在这里跑
373    /// (见 `reconcile_trade`),既不占宿主的启动序列,也不占入账 worker。
374    fn spawn_cmd_thread(&self) {
375        let Some(ctx) = self.ctx.get().cloned() else {
376            return; // 未 init:没有管制面可用
377        };
378        let shared = std::sync::Arc::clone(&self.shared);
379        let stop = std::sync::Arc::clone(&self.cmd_stop);
380        if std::thread::Builder::new()
381            .name("ui-cmd".to_string())
382            .spawn(move || {
383                loop {
384                    if stop.load(std::sync::atomic::Ordering::Acquire) {
385                        break;
386                    }
387                    // 用户指令优先于播种:播种最坏 4 × 2 秒,不能把点击排到它后面。
388                    if shared.cmd_pending() {
389                        Self::run_cmds(&shared, &ctx);
390                        continue;
391                    }
392                    // 播种档:启动一次 + 之后每次网关 / oms 上线各一次(标记是消费性的)。
393                    if shared.take_trade_reseed() {
394                        Self::reconcile_trade(&shared, &ctx);
395                        continue;
396                    }
397                    std::thread::sleep(Duration::from_millis(20));
398                }
399            })
400            .is_err()
401        {
402            // 线程起不来 = 指令只会进队列不会执行。这一条必须上屏,不能静默降级。
403            self.shared
404                .log_line("[ui] 命令线程起不来:操作指令会滞留在队列里");
405        }
406    }
407
408    /// 辞行指令队列(0.5 M5:由命令线程调用,不在 ui worker 上;回执进日志,面板语义可断言)。
409    fn run_cmds(shared: &UiShared, ctx: &PluginContext) {
410        for cmd in shared.drain_cmds() {
411            match cmd {
412                crate::state::UiCmd::Start { factory, name } => {
413                    match ctx.ask_service::<StartReq, StartRes>(
414                        SVC_START,
415                        StartReq {
416                            factory: factory.clone(),
417                            name: name.clone(),
418                        },
419                        Duration::from_secs(3),
420                    ) {
421                        Ok(StartRes::Started { name }) => {
422                            shared.log_line(format!("[ops] svctl.start {factory} → {name} 上线"));
423                        }
424                        Ok(StartRes::Rejected { reason }) => {
425                            shared.log_line(format!("[ops] start {factory} 被拒: {reason}"));
426                        }
427                        Err(e) => {
428                            shared.log_line(format!("[ops] start {factory} 失败: {e:?}"));
429                        }
430                    }
431                    // 起停回执之后重问一次管制面:运维窗那一行与账户在场位立刻动。
432                    shared.request_list_refresh();
433                }
434                crate::state::UiCmd::Remove { name } => {
435                    // 观测面自身的闸(0.4.3 BD-UI-64,审核 P1;0.5 M5 换了理由,闸不换):
436                    // 0.4 的理由是「这条指令在 ui 自己的 worker 上执行 → 摘 ui = 自己等自己
437                    // (ek-core `close_one` 只能走到 2 秒超时的 detach 分支)」。
438                    // 0.5 执行者换成命令线程,「自己等自己」这一半不成立了,但结论一样:
439                    // 摘掉 ui 之后没有 eTimer 拍再跑快照与状态轮询、入账 worker 也没了,
440                    // 窗口还开着而里面全是上一帧。所以仍然直拒,不发 svctl。
441                    // 管制面 `svctl` 的同一道闸长在 ek-station supervisor 侧(0.2.11)。
442                    if name == UI_NAME {
443                        shared.log_line(
444                            "[ops] 拒绝移除 ui:观测面自身不可自摘(摘掉后没有下一拍执行任何指令)"
445                                .to_string(),
446                        );
447                        continue;
448                    }
449                    match ctx.ask_service::<RemoveReq, RemoveRes>(
450                        SVC_REMOVE,
451                        RemoveReq { name: name.clone() },
452                        Duration::from_secs(3),
453                    ) {
454                        Ok(RemoveRes::Removed { name }) => {
455                            shared.log_line(format!("[ops] svctl.remove {name} 完成"));
456                        }
457                        Ok(RemoveRes::NoSuchName { name }) => {
458                            shared.log_line(format!("[ops] remove {name} 不存在/不可摘"));
459                        }
460                        // 0.4.3:回执枚举增项(ek-station 0.2.11)—— 名字在场但不可摘,
461                        // 或宿主另有错。原先这一档被塞进 NoSuchName 的 name 栏(错误文本
462                        // 当名字打),这一栏现在照请求回填,错因只进 reason。
463                        Ok(RemoveRes::Rejected { name, reason }) => {
464                            shared.log_line(format!("[ops] remove {name} 被拒: {reason}"));
465                        }
466                        Err(e) => {
467                            shared.log_line(format!("[ops] remove {name} 失败: {e:?}"));
468                        }
469                    }
470                    shared.request_list_refresh();
471                }
472                crate::state::UiCmd::Reload {
473                    interval,
474                    symbol,
475                    bars,
476                } => {
477                    // 回灌走 dm.reload ask(push=true 逐条广播 → 行情板实时见回执面)。
478                    match ctx.ask_service::<ReloadReq, usize>(
479                        "dm.reload",
480                        ReloadReq {
481                            interval,
482                            symbol: symbol.clone(),
483                            bars: bars.clone(),
484                            size: Some(bars.len()),
485                            push: true,
486                        },
487                        Duration::from_secs(5),
488                    ) {
489                        Ok(n) => {
490                            shared.market().note_reload();
491                            shared.log_line(format!(
492                                "[ops] dm.reload {symbol}@{interval}s 回灌 {n} 条"
493                            ));
494                        }
495                        Err(e) => {
496                            shared.log_line(format!("[ops] dm.reload {symbol} 失败: {e:?}"));
497                        }
498                    }
499                }
500                crate::state::UiCmd::SendOrder { req, gateway, mode } => {
501                    // 0.1.1 BD-UI-30 薄下单者:五段管线全走 oms.submit_order
502                    // (拆单/风控/逐腿发送/记账;直发 {gw}.send_order 旁路口删除,
503                    // 守卫不可绕过)。parent 聚合逐腿显形进日志。
504                    match ctx.ask_service::<SubmitOrderReq, SubmitReply>(
505                        "oms.submit_order",
506                        SubmitOrderReq {
507                            req: req.clone(),
508                            gateway_name: gateway.clone(),
509                            mode,
510                        },
511                        Duration::from_secs(10),
512                    ) {
513                        Ok(reply) => {
514                            let tag = match reply.status {
515                                SubmitStatus::Sent => "SENT",
516                                SubmitStatus::Partial => "PARTIAL",
517                                SubmitStatus::Rejected => "REJECTED",
518                            };
519                            for leg in &reply.legs {
520                                match (leg.ok, &leg.en_orderid, &leg.reason) {
521                                    (true, Some(id), _) => shared.log_line(format!(
522                                        "[ops] submit {} {} {}x{} → {id} (parent {})",
523                                        leg.req.symbol,
524                                        leg.req.direction.as_str(),
525                                        leg.req.offset.as_str(),
526                                        leg.req.volume,
527                                        reply.parent_id
528                                    )),
529                                    _ => shared.log_line(format!(
530                                        "[ops] submit {} {} {}x{} 被拒: {} (parent {})",
531                                        leg.req.symbol,
532                                        leg.req.direction.as_str(),
533                                        leg.req.offset.as_str(),
534                                        leg.req.volume,
535                                        leg.reason.as_deref().unwrap_or("?"),
536                                        reply.parent_id
537                                    )),
538                                }
539                            }
540                            if reply.legs.is_empty() {
541                                shared.log_line(format!(
542                                    "[ops] submit {} {}x{} {tag}:可平不足零腿 (parent {})",
543                                    req.symbol,
544                                    req.offset.as_str(),
545                                    req.volume,
546                                    reply.parent_id
547                                ));
548                            }
549                        }
550                        Err(e) => {
551                            shared.log_line(format!("[ops] oms.submit_order 失败: {e:?}"));
552                        }
553                    }
554                }
555                crate::state::UiCmd::CancelOrder { orderid, gateway } => {
556                    // 0.1.1 BD-UI-30:守卫撤单(尝试 ≤4000 在 oms;直发
557                    // {gw}.cancel_order 旁路口删除)。en_orderid 组式与
558                    // OrderData.en_orderid() 同式。
559                    match ctx.ask_service::<OmsCancelOrderReq, OmsCancelReply>(
560                        "oms.cancel_order",
561                        OmsCancelOrderReq {
562                            en_orderid: format!("{gateway}.{orderid}"),
563                            gateway_name: gateway.clone(),
564                        },
565                        Duration::from_secs(10),
566                    ) {
567                        Ok(OmsCancelReply { ok: true, msg }) => {
568                            shared.log_line(format!("[ops] {msg}"));
569                        }
570                        Ok(OmsCancelReply { ok: false, msg }) => {
571                            // 0.11.0 第6刀 R7:屏幕上给人话,机器码原文照留(取证要吃原文)
572                            shared
573                                .log_line(format!("[ops] {}", UiShared::cancel_reject_note(&msg)));
574                        }
575                        Err(e) => {
576                            shared.log_line(format!("[ops] oms.cancel_order 失败: {e:?}"));
577                        }
578                    }
579                }
580                crate::state::UiCmd::CtpConfigure { gateway, form } => {
581                    // 定盘口径:界面手工输入 → 插件自带配置口(插件不读文件)。
582                    // 多账号面:服务名随网关走(`{gw}.configure`),不再硬编码 ctp。
583                    let svc = format!("{gateway}.configure");
584                    match ctx.ask_service::<ConfigureReq, ConfigureReply>(
585                        svc.as_str(),
586                        form.to_configure_req(),
587                        Duration::from_secs(5),
588                    ) {
589                        // `..`:ConfigureReply 0.6.0 起带 product_classes(实际生效值)。
590                        // 这里不回填表单勾选 —— 被拒时回带的是「网关当前仍在跑」的那一份,
591                        // 用它覆盖用户刚点的勾选会把他的意图吃掉;日志里网关已写明收录产品类。
592                        Ok(ConfigureReply { ok: true, msg, .. }) => {
593                            shared.log_line(format!("[ops] {svc} 受理:{msg}"));
594                        }
595                        Ok(ConfigureReply { ok: false, msg, .. }) => {
596                            shared.log_line(format!("[ops] {svc} 被拒:{msg}"));
597                        }
598                        Err(e) => {
599                            shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
600                        }
601                    }
602                }
603                crate::state::UiCmd::Connect { gateway, form } => {
604                    // **四态分离的「连接」**(规划裁定「添加 ≠ 连接」):一次做完
605                    // `svctl.start(factory=ctp)` + `{gw}.configure`,结果回写账户行
606                    // (`Assembling → Assembled / AssembleFailed` + 失败原因留显形)。
607                    // 失败**不回滚清册行** —— 行留着给『重试』(旧口径"必须先移除才能重试"作废)。
608                    shared.note_connect_sent(&gateway);
609                    // 单源纪律在此裁决:非行情源账户的 md 位就地清空,**留档与下发同一份**
610                    // (旧口径只清下发不清留档,编辑页回填会带着一根用不上的行情前置)。
611                    let form = shared.prepare_connect_form(&gateway, form);
612                    let started = match ctx.ask_service::<StartReq, StartRes>(
613                        SVC_START,
614                        StartReq {
615                            factory: "ctp".to_string(),
616                            name: gateway.clone(),
617                        },
618                        Duration::from_secs(3),
619                    ) {
620                        Ok(StartRes::Started { name }) => {
621                            shared.log_line(format!("[ops] svctl.start ctp → {name} 上线"));
622                            true
623                        }
624                        Ok(StartRes::Rejected { reason }) => {
625                            // 防重入(规划 Q7):实例已在场时重复点『连接』/『重试』不是失败,
626                            // 重投凭据即可(否则会把正在跑的账户误判成"装配失败")。
627                            if shared.account(&gateway).is_some_and(|a| a.connected) {
628                                shared
629                                    .log_line(format!("[ops] {gateway} 已在场,重投凭据: {reason}"));
630                                true
631                            } else {
632                                shared.log_line(format!("[ops] {gateway} 装配被拒: {reason}"));
633                                shared.note_connect_result(&gateway, Err(reason));
634                                continue;
635                            }
636                        }
637                        Err(e) => {
638                            shared.log_line(format!("[ops] {gateway} 装配失败: {e:?}"));
639                            shared.note_connect_result(&gateway, Err(format!("{e:?}")));
640                            continue;
641                        }
642                    };
643                    if !started {
644                        continue;
645                    }
646                    let svc = format!("{gateway}.configure");
647                    match ctx.ask_service::<ConfigureReq, ConfigureReply>(
648                        svc.as_str(),
649                        form.to_configure_req(),
650                        Duration::from_secs(5),
651                    ) {
652                        // `..`:ConfigureReply 带的 product_classes(实际生效值)不回填勾选
653                        // (被拒时回带的是「网关仍在跑」的那一份,覆盖用户刚点的勾选会吃掉意图);
654                        // 0.2.18 起把它显示出来(见 state::note_effective_product_classes)。
655                        Ok(ConfigureReply {
656                            ok: true,
657                            msg,
658                            product_classes,
659                        }) => {
660                            shared.log_line(format!("[ops] {svc} 受理:{msg}"));
661                            shared.note_effective_product_classes(&gateway, &product_classes);
662                            shared.note_connect_result(&gateway, Ok(()));
663                        }
664                        Ok(ConfigureReply { ok: false, msg, .. }) => {
665                            shared.log_line(format!("[ops] {svc} 被拒:{msg}"));
666                            shared.note_connect_result(&gateway, Err(msg));
667                        }
668                        Err(e) => {
669                            shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
670                            shared.note_connect_result(&gateway, Err(format!("{e:?}")));
671                        }
672                    }
673                }
674                crate::state::UiCmd::CtpSubscribe { gateway, symbols } => {
675                    // 多账号面:一律路由到行情元账号(渲染侧已按此入列);
676                    // 纯 TD 账号收到订阅会**静默成功**(do_subscribe 恒 ok:true),
677                    // 所以路由正确性靠界面纪律,不靠网关报错(规划 §9.4-21)。
678                    let svc = format!("{gateway}.subscribe");
679                    match ctx.ask_service::<CtpSubscribeReq, CtpSubscribeReply>(
680                        svc.as_str(),
681                        CtpSubscribeReq {
682                            symbols: symbols.clone(),
683                        },
684                        Duration::from_secs(5),
685                    ) {
686                        Ok(CtpSubscribeReply { ok: true, msg }) => {
687                            shared.note_subscriptions(&symbols);
688                            shared.log_line(format!(
689                                "[ops] {svc} {} 受理:{}",
690                                symbols.join(","),
691                                msg
692                            ));
693                        }
694                        Ok(CtpSubscribeReply { ok: false, msg }) => {
695                            shared.log_line(format!(
696                                "[ops] {svc} {} 被拒:{}",
697                                symbols.join(","),
698                                msg
699                            ));
700                        }
701                        Err(e) => {
702                            shared.log_line(format!("[ops] {svc} 失败: {e:?}"));
703                        }
704                    }
705                }
706                crate::state::UiCmd::Disconnect { gateway } => {
707                    // 0.2.19 规划裁定 1:『断开』= `{gw}.disconnect`(停会话),
708                    // 『移除』= `svctl.remove`(停实例)—— 两条走两条不同的口,不共用。
709                    // 发令即把该行标成「已断开」:用户按了钮就要立刻看到,不等下一轮轮询。
710                    let svc = format!("{gateway}.disconnect");
711                    match ctx.ask_service::<DisconnectReq, DisconnectReply>(
712                        svc.as_str(),
713                        DisconnectReq,
714                        Duration::from_secs(5),
715                    ) {
716                        Ok(DisconnectReply { ok: true, msg }) => {
717                            shared.mark_account_stopped(&gateway);
718                            shared.log_line(format!("[账户] 断开 {gateway}:{msg}(实例仍在场)"));
719                        }
720                        Ok(DisconnectReply { ok: false, msg }) => {
721                            shared.log_line(format!("[账户] 断开 {gateway} 未执行:{msg}"));
722                        }
723                        Err(e) => {
724                            shared.log_line(format!(
725                                "[账户] 断开 {gateway} 失败:{e:?}(网关不在场或超时)",
726                            ));
727                        }
728                    }
729                }
730                crate::state::UiCmd::CfgList => {
731                    // 目录刷新(命令线程执行档;与 worker poll_cfg 同一读数面)。
732                    let (_, svc_list, _) = cfg_svc_ids();
733                    match ctx.ask_service::<CfgListReq, CfgListRes>(
734                        svc_list.as_str(),
735                        CfgListReq,
736                        Duration::from_secs(2),
737                    ) {
738                        Ok(res) => {
739                            shared.set_cfg_briefs(res.entries);
740                            if !res.msg.is_empty() {
741                                shared.log_line(format!("[cfg] 目录:{msg}", msg = res.msg));
742                            }
743                        }
744                        Err(e) => shared.log_line(format!("[cfg] 段落目录失败: {e:?}")),
745                    }
746                }
747                crate::state::UiCmd::CfgDelete { ns } => {
748                    // 清段(BD-CFG-20 运维语义;空 key = 整段;零值面)。
749                    let (svc_save, svc_list, svc_delete) = cfg_svc_ids();
750                    let _ = (svc_save, svc_list);
751                    match ctx.ask_service::<CfgDeleteReq, CfgDeleteRes>(
752                        svc_delete.as_str(),
753                        CfgDeleteReq {
754                            ns: ns.clone(),
755                            key: String::new(),
756                        },
757                        Duration::from_secs(2),
758                    ) {
759                        Ok(res) if res.ok => {
760                            shared.log_line(format!(
761                                "[cfg] 清段 {ns}:键 {} / 秘条 {}",
762                                res.removed_keys, res.removed_secrets
763                            ));
764                            shared.request_cfg_refresh();
765                        }
766                        Ok(res) => shared.log_line(format!("[cfg] 清段 {ns} 未执行:{}", res.msg)),
767                        Err(e) => shared.log_line(format!("[cfg] 清段 {ns} 失败: {e:?}")),
768                    }
769                    shared.arm_cfg_delete(None);
770                }
771                crate::state::UiCmd::CfgResave { ns } => {
772                    // 重存段(0.6.0):明面按现状重读 → serialize → store。**值不变
773                    // (BD-CFG-15:不输出 = 不持久,这里连「不重排空行」都不做之外的
774                    // 改动一律没有)**;rev/格式修复口。兜底根与 cfg 实例同口径
775                    // (BD-CFG-10 soft-centralized:直调用库,不拉起注册)。
776                    let store = ui_cfg_store();
777                    let loaded = store
778                        .load(&ns)
779                        .map_err(|e| e.to_string())
780                        .and_then(|o| match o {
781                            ek_cfg::LoadOutcome::Fresh => Err(format!("{ns} 段不存在,不持久空形")),
782                            map @ ek_cfg::LoadOutcome::Loaded { .. } => Ok(map),
783                        });
784                    match loaded {
785                        Ok(ek_cfg::LoadOutcome::Fresh) => {
786                            unreachable!("Fresh 已被上面的 and_then 挡走");
787                        }
788                        Ok(ek_cfg::LoadOutcome::Loaded {
789                            map,
790                            warnings,
791                            backup_used,
792                        }) => {
793                            if !warnings.is_empty() {
794                                shared.log_line(format!("[cfg] {ns} 重读警告:{warnings:?}"));
795                            }
796                            if backup_used {
797                                shared.log_line(format!("[cfg] {ns} 走了 .bak 回落"));
798                            }
799                            match store.store(&ns, &map) {
800                                Ok(()) => {
801                                    shared.log_line(format!("[cfg] {ns} 已重存(rev {})", map.rev))
802                                }
803                                Err(e) => shared.log_line(format!("[cfg] {ns} 重存失败:{e}")),
804                            }
805                        }
806                        Err(msg) => shared.log_line(format!("[cfg] {msg}")),
807                    }
808                }
809            }
810        }
811    }
812}
813
814impl Plugin for UiPlugin {
815    fn name(&self) -> &str {
816        UI_NAME
817    }
818
819    fn deps(&self) -> &[&str] {
820        &[] // 纯观测;谁先上都能看到(bus 契约不依赖启动序)
821    }
822
823    fn routes(&self) -> Vec<std::borrow::Cow<'static, str>> {
824        vec![
825            std::borrow::Cow::Borrowed(EVENT_LOG),
826            std::borrow::Cow::Borrowed(EVENT_PLUG_UP),
827            std::borrow::Cow::Borrowed(EVENT_PLUG_DOWN),
828            std::borrow::Cow::Borrowed(EVENT_BAR),
829            std::borrow::Cow::Borrowed(EVENT_BAR_UPDATE),
830            std::borrow::Cow::Borrowed(EVENT_TICK),
831            std::borrow::Cow::Borrowed(EVENT_CONTRACT),
832            std::borrow::Cow::Borrowed(ek_ctp::EVENT_CONTRACT_FINISH),
833            // 0.5 M1 交易四表的推送线(基线 BaseMonitor 各自订阅自己的线)。
834            // 不订 eTradeSync.:ek-oms 处理完成交后重推的那一条(plugin.rs:305-308),
835            // 与 ek-ctp 的 eTrade. 是同一笔成交的两份 —— 订两条就是重复入账。
836            std::borrow::Cow::Borrowed(W_ORDER),
837            std::borrow::Cow::Borrowed(W_TRADE),
838            std::borrow::Cow::Borrowed(W_POSITION),
839            std::borrow::Cow::Borrowed(W_ACCOUNT),
840            std::borrow::Cow::Borrowed(EVENT_TIMER),
841            // 0.7.0 第3刀:状态变化推送(裸线,载荷自带网关名)—— 界面零轮询的地基
842            std::borrow::Cow::Borrowed(ek_ctp::EVENT_STATUS_PREFIX),
843        ]
844    }
845
846    fn mailbox_soft_cap(&self) -> u64 {
847        UI_MAILBOX_SOFT_CAP
848    }
849
850    fn version(&self) -> std::borrow::Cow<'static, str> {
851        std::borrow::Cow::Borrowed(env!("CARGO_PKG_VERSION"))
852    }
853
854    fn services(&self) -> Vec<ServiceDesc> {
855        Vec::new() // 纯视图零服务;管制面在 svctl
856    }
857
858    fn on_init(&self, ctx: &PluginContext) {
859        let _ = self.ctx.set(ctx.clone());
860    }
861
862    fn on_start(&self) {
863        self.shared.log_line("[ui] 界面插件上线");
864        // 0.5 M5 + M4:命令线程先起(点击即发);启动一次四问在那条线程里跑 ——
865        // `on_start` 是 `engine.start()` 启动链的一环,四口最坏 4 × 2 秒不许把后面
866        // 插件的启动一起拖住,更不许占入账 worker。
867        self.spawn_cmd_thread();
868        // 启动一次四问的标记(on_start 是 `engine.start()` 启动链的一环,四口最坏
869        // 4 × 2 秒不许把后面插件的启动一起拖住,更不许占入账 worker)。
870        self.shared.request_trade_reseed();
871        self.shared.request_pipeline_refresh();
872        // 0.8.0 配色双档:启动读一次档(命令线程,一次小文件读),用户没点过钮 = 缺省深色。
873        let theme = load_theme();
874        self.shared.set_theme(theme);
875        if theme == crate::tokens::Theme::Light {
876            self.shared.log_line("[ui] 主题:浅色(读盘 ui.theme)");
877        }
878    }
879
880    fn on_stop(&self) {
881        self.shared.log_line("[ui] 界面插件下线");
882        // 命令线程停线:它在 20ms 空转切片自查这个位,不会卡在 sleep 里。
883        self.cmd_stop
884            .store(true, std::sync::atomic::Ordering::Release);
885    }
886
887    fn on_mail(&self, event: &ek_event::Event) {
888        let ty = event.event_type.as_str();
889        if ty == EVENT_LOG {
890            if let Some(d) = event.data.downcast_ref::<LogData>() {
891                let tag = if d.is_warning_or_above() {
892                    "WARN"
893                } else {
894                    "INFO"
895                };
896                self.shared
897                    .log_line(format!("[{tag}][{}] {}", d.gateway_name, d.msg));
898                // 0.5.0(用户定「链进行的状态改为事件日志推送」):`[链] ` 前缀的行除了进日志窗,
899                // 还落进账户行的「阶段」栏(ek-ctp 0.9.8 D-QUERY-GATE ⑧)。这一条是纯显示落账,
900                // 不参与 `apply_status` 那套在线/断供判据。
901                // 前缀单源:`crate::state::CHAIN_STATE_PREFIX` = ek-ctp 0.9.8 那一份的 re-export
902                // (state.rs:201;0.6.3 路标兑现,注释同步 —— 无本地字面)。
903                if let Some(note) = d.msg.strip_prefix(crate::state::CHAIN_STATE_PREFIX) {
904                    self.shared.note_chain(&d.gateway_name, note);
905                }
906            } else {
907                self.shared.log_line("[eLog] 载荷类型异常(非 LogData)");
908            }
909            return;
910        }
911        if ty == ek_ctp::EVENT_STATUS_PREFIX {
912            // 0.7.0 第3刀:状态变化推送 → 一次到货三件事(文案 / 状态列 / 去重告警)。
913            if let Some(ev) = event.data.downcast_ref::<ek_ctp::GatewayStatusEvent>() {
914                self.shared.note_status_event(ev);
915            } else {
916                self.shared
917                    .log_line("[eStatus] 载荷类型异常(非 GatewayStatusEvent)");
918            }
919            return;
920        }
921        if ty == EVENT_PLUG_UP || ty == EVENT_PLUG_DOWN {
922            if let Some(n) = event.data.downcast_ref::<PlugNotice>() {
923                let verb = if ty == EVENT_PLUG_UP {
924                    "上线"
925                } else {
926                    "下线"
927                };
928                self.shared
929                    .log_line(format!("[host] 插件{verb} {} v{}", n.name, n.version));
930                // 在场位与运维窗那一行跟着这条线动(不等 4 拍的快照节拍)。
931                self.shared.request_list_refresh();
932                if ty == EVENT_PLUG_UP {
933                    // 0.5 M3:装配显形改吃这条线 —— 不再靠每拍 list 去发现「谁新上线」。
934                    if n.name == ek_oms::NAME {
935                        self.shared.request_pipeline_refresh();
936                    }
937                    // 0.5 执行核查补的第三处:网关 / oms 上线之后重播种一次四张表。
938                    // 摘除一个网关账户会作废它名下的委托与成交行,而 oms 那边那些行还在;
939                    // 重新添加时不重问一次,界面就永久少一段历史。顺带覆盖「ui 先于 oms
940                    // 起来、第一次播种问空了」这一序。
941                    let is_account = self.shared.accounts().iter().any(|a| a.gateway == n.name);
942                    if n.name == ek_oms::NAME || is_account {
943                        self.shared.request_trade_reseed();
944                    }
945                    // 0.7.0 第3刀:网关上线 → 播种一次初始快照(运行期至多这一发 ask;
946                    // 之后登录态/断供全靠 `eStatus.` 推送,界面零轮询)。
947                    if is_account {
948                        self.shared.request_status_seed(&n.name);
949                    }
950                    // 0.5 M3:订阅重放同样改吃这条线(与 `sync_accounts_connected` 的
951                    // newly 回带是同一件事的两条路,留一条:这条即时、那条要等快照拍)。
952                    let md = self.shared.md_source();
953                    let subs = self.shared.subscriptions();
954                    if !md.is_empty() && n.name == md && !subs.is_empty() {
955                        self.shared.push_cmd(crate::state::UiCmd::CtpSubscribe {
956                            gateway: n.name.clone(),
957                            symbols: subs.clone(),
958                        });
959                        self.shared.log_line(format!(
960                            "[ops] 行情源 {} 上线,重放订阅 {} 项",
961                            n.name,
962                            subs.len()
963                        ));
964                    }
965                } else {
966                    // 0.5 M1:网关下线 = 它名下的委托 / 成交 / 持仓 / 资金行全部作废。
967                    // 推送模型里没人再告诉界面「这一行已经不存在了」,不清就是替一个
968                    // 已经不存在的会话说话(与 0.2.19「实例不在场就作废会话读数」同口径)。
969                    let removed = self.shared.clear_gateway_rows(&n.name);
970                    if removed > 0 {
971                        self.shared.log_line(format!(
972                            "[ui] 插件下线 {}:作废 {} 行交易数据",
973                            n.name, removed
974                        ));
975                    }
976                    // 0.5 执行核查补的第二处:摘掉 oms 之后管线读数不会自己清空。
977                    // 0.4 是每 4 拍问一次,4 秒内自己就空了;改事件触发后没人再问,
978                    // 运维窗那一节会替一个已经不存在的 oms 说话。标记一次:下一拍问一次
979                    // → TargetGone 快错 → `poll_pipeline` 的 Err 分支清空并落一条日志。
980                    if n.name == ek_oms::NAME {
981                        self.shared.request_pipeline_refresh();
982                    }
983                }
984            }
985            self.shared.bump();
986            return;
987        }
988        if ty == EVENT_BAR {
989            if let Some(f) = event.data.downcast_ref::<ek_dm::wire::BarsFrame>() {
990                self.shared.market().on_frame(f);
991            }
992            self.shared.bump();
993            return;
994        }
995        if ty == EVENT_BAR_UPDATE {
996            if let Some(b) = event.data.downcast_ref::<ek_data::bar::BarData>() {
997                self.shared.market().on_update(b);
998            }
999            self.shared.bump();
1000            return;
1001        }
1002        if ty == EVENT_TICK {
1003            if let Some(t) = event.data.downcast_ref::<ek_data::tick::TickData>() {
1004                self.shared.update_tick(t);
1005            }
1006            return;
1007        }
1008        if ty == EVENT_CONTRACT {
1009            // 0.11.0 第4刀(ek-ctp R5):合约流分批到货,一帧 ≤2000 行 → 逐行上屏
1010            // (合约窗照旧一段段长出来,只是每一拍长一批);单条形继续受理(兼容)。
1011            if let Some(v) = event
1012                .data
1013                .downcast_ref::<Vec<ek_data::contract::ContractData>>()
1014            {
1015                for c in v {
1016                    self.shared.update_contract(c);
1017                }
1018            } else if let Some(c) = event.data.downcast_ref::<ek_data::contract::ContractData>() {
1019                self.shared.update_contract(c);
1020            }
1021            return;
1022        }
1023        if ty == ek_ctp::EVENT_CONTRACT_FINISH {
1024            let gw = event
1025                .data
1026                .downcast_ref::<String>()
1027                .cloned()
1028                .unwrap_or_else(|| "?".to_string());
1029            self.shared
1030                .log_line(format!("[ctp] 合约流完成 {gw}(查询合约窗可勾选订阅)"));
1031            return;
1032        }
1033        // 0.5 M1 交易四表:后台只把事件推过来,界面自己入账(基线 BaseMonitor.process_event)。
1034        // 这里不 ask 任何东西,所以入账 worker 永不被后端拖住。
1035        if ty == W_ORDER {
1036            match event.data.downcast_ref::<OrderData>() {
1037                Some(o) => self.shared.note_order(o),
1038                None => self.shared.note_bad_payload(W_ORDER),
1039            }
1040            return;
1041        }
1042        if ty == W_TRADE {
1043            match event.data.downcast_ref::<TradeData>() {
1044                Some(t) => self.shared.note_trade(t),
1045                None => self.shared.note_bad_payload(W_TRADE),
1046            }
1047            return;
1048        }
1049        if ty == W_POSITION {
1050            match event.data.downcast_ref::<PositionData>() {
1051                Some(p) => self.shared.note_position(p),
1052                None => self.shared.note_bad_payload(W_POSITION),
1053            }
1054            return;
1055        }
1056        if ty == W_ACCOUNT {
1057            match event.data.downcast_ref::<AccountData>() {
1058                Some(a) => self.shared.note_funds(a),
1059                None => self.shared.note_bad_payload(W_ACCOUNT),
1060            }
1061            return;
1062        }
1063        if ty == EVENT_TIMER {
1064            self.refresh();
1065        }
1066    }
1067}