ek-ui 0.9.9

ek 生态常驻主界面(egui/eframe):插件即界面——观测页 + 日志页,车头与 UI 同插件
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! 运行时装配:工厂表(ui 工厂注册)、宿主观察线程(关窗→close_all)、
//! 进程主入口(eframe 主线程 + 宿主观察线程)、**启动阶段机**(0.9.5)。
//!
//! 线程形貌(S1b 双线程纪律):
//! - 主线程:eframe run_native(App 只读 [`UiShared`]);
//! - 观察线程:sleep 轮询 `UiShared::is_stop` → `engine.close_all`;
//! - 等价 headless 形貌见 ek-station bin(不带 ui 工厂)。
//!
//! 阶段机(0.9.5,用户裁定「先配置组件、运行后才出主界面;运行后装配只可看」):
//! - `Setup`:只画组件配置面(勾选/装配/参数面/档案包/导出启动清单),主界面不画;
//! - `Running`:主界面(`render_body`)登场;装配面转**只读**(锁旗在界面层,底层零写死);
//! - 锁只在**启动全成功**后置位(有壳没起来 = 不锁,运维面留修路);
//! - launcher 路 `auto_boot = true` = 装配+启动在开窗前走完(ready 标记协议不破)。

use std::sync::Arc;
use std::time::Duration;

use ek_core::main_engine::{MainEngine, PluginState};
use ek_core::plugin::Plugin;
use ek_dm::plugin::DmConfig;
use ek_station::{PlugKind, StationConfig, default_kinds};

use crate::plugin::{UI_NAME, UiPlugin};
use crate::state::UiShared;

/// ek-station 缺省工厂表(dm/oms/ctp;0.1.12 起 sim 已退场)+ `ui` 工厂 +
/// **rt-on 的 dm 工厂**(S4:UI 宿主观测面需要 `eBarUpdate.` 实时门;
/// ek-station headless 保持 rt-off 缺省不动 —— 两宿主的 dm 配置差异在各自
/// 工厂表,互不影响)。
///
/// `dm_rt` 是装配期参数(非配置文件;ek-ui 零配置口径,缺省 true);
/// 多次 build 同享一个 `UiShared`(ui 插件被 svctl 摘/再注,观测不丢)。
pub fn ui_kinds(shared: &Arc<UiShared>, dm_rt: bool) -> Vec<PlugKind> {
    let mut kinds: Vec<PlugKind> = default_kinds()
        .into_iter()
        .filter(|k| k.name != "dm")
        .collect();
    kinds.push(PlugKind {
        name: "dm",
        doc: "数据管理器(KlineManager;real_time 更新门开,行情板/K线页取 eBarUpdate./eBar.)",
        build: Arc::new(move || -> Arc<dyn Plugin> {
            Arc::new(ek_dm::plugin::DmPlugin::new(DmConfig {
                real_time: dm_rt,
                ..DmConfig::minute("dm")
            }))
        }),
        build_named: None,
        name_validator: None,
    });
    kinds.push(PlugKind {
        name: UI_NAME,
        doc: "常驻观测界面(eLog + eTimer 1s 快照;关窗即 stop)",
        build: {
            let shared = Arc::clone(shared);
            Arc::new(move || -> Arc<dyn Plugin> { Arc::new(UiPlugin::new(Arc::clone(&shared))) })
        },
        build_named: None,
        name_validator: None,
    });
    // 0.9.5 阶段机:天勤桥进勾选器(用户裁定并入本波)。
    // 工厂住在 ek-ui(叶仓零链):tq 不在 ek-station 缺省表,装配由勾选器发起;
    // 凭据面 = `ekapp tq-secret` 写密库 + `tq.ini` 引用行,开机 boot_with_cfg
    // 直调 apply_config 记引用 → on_start 从密库解密灌桥(tq plugin.rs spawn_engine)。
    kinds.push(PlugKind {
        name: "tq",
        doc: "天勤桥(行情/K线接入;凭据走密库引用,口令永不进档案)",
        build: Arc::new(|| -> Arc<dyn Plugin> {
            // 装配环补齐:此前这里给的是 BridgeConfig::default() —— program =
            // "python"、script = **空串**,GUI 里桥永远 spawn 不起来(python -X utf8 "")。
            // 现走 pyenv 择路(venv 优先 → EK_TQ_PYTHON → 系统 python),侧车 = 
            // 仓内 engine_real.py 绝对路径;将来打包成侧车 exe 时在 pyenv 里换择路。
            let bridge_cfg = ek_tq::bridge::BridgeConfig {
                program: ek_tq::pyenv::python_program(),
                script: ek_tq::pyenv::real_script(),
                handshake_ms: ek_tq::consts::BRIDGE_HANDSHAKE_MS,
                ..Default::default()
            };
            Arc::new(ek_tq::plugin::TqPlugin::new(
                ek_tq::plugin::TqPluginSpec::new(bridge_cfg),
            ))
        }),
        build_named: None,
        name_validator: None,
    });
    kinds
}

/// 宿主观察线程:窗口不复用的引擎在这里按 stop 位收场(close_all join)。
///
/// 纪律:close 顺序也让宿主自己走(逆 start 序),观察线程只送信号不代走步骤。
pub fn spawn_host_watcher(
    engine: &Arc<MainEngine>,
    shared: &Arc<UiShared>,
) -> std::thread::JoinHandle<()> {
    let engine = Arc::clone(engine);
    let shared = Arc::clone(shared);
    std::thread::spawn(move || {
        while !shared.is_stop() {
            std::thread::sleep(Duration::from_millis(120));
        }
        shared.log_line("[host] 窗口关闭,close_all …");
        engine.close_all(Duration::from_secs(3));
        shared.log_line("[host] 已收场");
    })
}

/// 档案包操作(导出/导入)一行回执文本;根不可用 = 显形不炸。
fn bundle_op(shared: &Arc<UiShared>, engine: &MainEngine, dir: &str, export: bool) -> String {
    let host = crate::faces::CfgBridge::new(shared);
    let dest = std::path::Path::new(dir);
    if dir.trim().is_empty() {
        return "目录为空(先填路径)".to_string();
    }
    if export {
        let Some(root) = host.cfg.as_ref().map(|c| c.root().to_path_buf()) else {
            return "导出失败:档案托底根不可用".to_string();
        };
        match crate::pluginwin::export_bundle(&root, dest) {
            Ok((c, s)) => {
                let msg = format!("导出完成:{c} 段 → {}(跳过非段文件 {s})", dest.display());
                shared.log_line(format!("[ui] {msg}"));
                msg
            }
            Err(e) => format!("导出失败:{e}"),
        }
    } else {
        let lines = crate::pluginwin::import_bundle(&host, dest, &|ns, sec| {
            crate::faces::apply_section(engine, ns, sec)
        });
        let msg = lines.join(" | ");
        shared.log_line(format!("[ui] 档案包导入:{msg}"));
        msg
    }
}

/// 阶段机两相(0.9.5)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    /// 组件配置相(主界面未登场)。
    Setup,
    /// 运行相(主界面登场;装配面只读)。
    Running,
}

/// 启动阶段机 App(桌面 = ekapp 与 ek-ui 主程序共用的**唯一**窗口面;
/// 0.9.5 收编:原 ekapp bin 自带的 DesktopApp 副本已删,单源在此)。
pub struct StageApp {
    shared: Arc<UiShared>,
    /// 宿主引擎(0.9.2「插件即 App」:挂载表按装配名单走)。
    engine: Arc<MainEngine>,
    /// 工厂全表(勾选面的行;装配按勾选过滤)。
    kinds: Vec<PlugKind>,
    /// 勾选态(与 `kinds` 同长同序;ui 行恒真)。
    sel: Vec<bool>,
    /// 档案托底根(装配时 `boot_with_cfg` 直调;None = 退回纯装配)。
    store: Option<ek_cfg::Store>,
    /// 当前相。
    stage: Stage,
    /// 配置面回执(装配/启动/导出显形)。
    notice: Option<String>,
    /// 启动清单导出目录草稿(S4 两面对齐)。
    list_dir: String,
    /// 插件面状态包(各面自态 + 通用窗口态)。
    fs: crate::faces::FaceStates,
    /// 逐插件窗的 X 关合记忆(0.9.3)。
    wins_open: std::collections::HashMap<String, bool>,
    /// 「参数面」组钮的上帧态(组开沿时逐窗复位)。
    pluginwin_prev: bool,
    /// 档案包窗口目录草稿与回执。
    bundle_dir: String,
    bundle_notice: Option<String>,
    /// launcher 协议 ready 标记(启动成功后写;无 = 不写)。
    ready_marker: Option<std::path::PathBuf>,
    /// 观察线程句柄(开窗即挂;关窗收场同一条路)。
    watcher: Option<std::thread::JoinHandle<()>>,
}

impl StageApp {
    /// 配置相起步(桌面 ekapp 用:开窗时引擎**未装配未启动**)。
    #[must_use]
    pub fn new_setup(
        engine: Arc<MainEngine>,
        shared: Arc<UiShared>,
        kinds: Vec<PlugKind>,
        store: Option<ek_cfg::Store>,
        ready_marker: Option<std::path::PathBuf>,
    ) -> Self {
        let sel = kinds.iter().map(|_| true).collect::<Vec<bool>>();
        Self {
            shared,
            engine,
            kinds,
            sel,
            store,
            stage: Stage::Setup,
            notice: None,
            list_dir: String::new(),
            fs: crate::faces::FaceStates::new(),
            wins_open: std::collections::HashMap::new(),
            pluginwin_prev: false,
            bundle_dir: String::new(),
            bundle_notice: None,
            ready_marker,
            watcher: None,
        }
    }

    /// 当前相(判据面读路)。
    #[must_use]
    pub fn stage(&self) -> Stage {
        self.stage
    }

    /// 勾选项(工厂名表;ui 行恒真)。
    #[must_use]
    pub fn picked(&self) -> Vec<String> {
        self.kinds
            .iter()
            .zip(self.sel.iter())
            .filter(|(_, ok)| **ok)
            .map(|(k, _)| k.name.to_string())
            .collect()
    }

    /// 装配相 = 引擎里已有壳(装配已发生)。
    #[must_use]
    pub fn assembled(&self) -> bool {
        !self.engine.plugin_names().is_empty()
    }

    /// 勾选开关(判据面与后续持久化用;ui 行恒真不受它影响)。
    pub fn set_selected(&mut self, name: &str, on: bool) {
        if let Some(i) = self.kinds.iter().position(|k| k.name == name) {
            self.sel[i] = on && name != UI_NAME;
        }
    }

    /// 「装配(按勾选)」:按勾选过滤工厂表 → boot(带 cfg 回灌口径)。
    ///
    /// 失败 = 显形回执,**不锁**(审核定案:装配失败留在配置相)。
    pub fn do_assemble(&mut self) -> String {
        let kinds: Vec<PlugKind> = self
            .kinds
            .iter()
            .enumerate()
            .filter(|(i, _)| self.sel[*i])
            .map(|(_, k)| k.clone())
            .collect();
        let names: Vec<String> = kinds.iter().map(|k| k.name.to_string()).collect();
        let cfg = StationConfig {
            plugins: names.clone(),
        };
        let r = match &self.store {
            Some(s) => ek_station::boot_with_cfg(&self.engine, &kinds, &cfg, Some(s)),
            None => ek_station::boot(&self.engine, &kinds, &cfg),
        };
        match r {
            Ok(_) => {
                self.shared
                    .log_line(format!("[ui] 装配:{} 壳(未启动)", names.join(",")));
                format!(
                    "已装配 {} 壳(未启动;参数面可改):{}",
                    names.len(),
                    names.join(",")
                )
            }
            Err(e) => {
                let msg = format!("装配失败:{e:?}");
                self.shared.log_line(format!("[ui] {msg}"));
                msg
            }
        }
    }

    /// 「启动运行」:engine.start() + ready 标记 + 账户清点;
    /// **全壳 Running 才置装配锁**(有壳没起来 = 不锁,运维面留修路)。
    pub fn do_start(&mut self) -> String {
        if let Err(e) = self.engine.start() {
            // start 整段失败:主界面照常出(半运行态),不锁,显形留修路。
            self.stage = Stage::Running;
            self.shared.set_assembly_locked(false);
            self.ensure_watcher();
            let msg = format!("启动失败:{e:}(运维面可修,装配不锁定)");
            self.shared.log_line(format!("[ui] {msg}"));
            return msg;
        }
        let not_ready: Vec<String> = self
            .engine
            .plugin_names()
            .into_iter()
            .filter(|n| !matches!(self.engine.get_state(n), Some(PluginState::Running)))
            .collect();
        self.stage = Stage::Running;
        self.shared.set_assembly_locked(not_ready.is_empty());
        self.ensure_watcher();
        self.write_ready_marker();
        // 账户清点(手点连接裁定:桌面 = 清点列回,手点才连;起连在运行相)。
        let shared_restore = Arc::clone(&self.shared);
        std::thread::spawn(move || {
            let rows = shared_restore.restore_saved_accounts();
            let _ = rows;
        });
        let msg = if not_ready.is_empty() {
            "已启动:装配面已锁定(只可看不可动)".to_string()
        } else {
            format!(
                "已启动,{} 壳未就绪:{} — 装配**不锁定**(运维面留修路)",
                not_ready.len(),
                not_ready.join(",")
            )
        };
        self.shared.log_line(format!("[ui] {msg}"));
        msg
    }

    /// 「导出启动清单」:勾选 → `--from` 可用文件(一行一名;ek-station 读路同形)。
    ///
    /// 只导**无界面面认得的行**(ek-station 工厂表 = `default_kinds`):`ui`/`tq` 是
    /// ek-ui 宿主自带的工厂,headless 路线没有这两名 —— 混进清单会让 `--from` 直接报错。
    /// 被跳过的行在回执里显形,不静默。
    pub fn export_plugin_list(&mut self, dir: &str) -> String {
        let factory_names: Vec<String> = default_kinds()
            .into_iter()
            .map(|k| k.name.to_string())
            .collect();
        let picked = self.picked();
        let exportable: Vec<String> = picked
            .iter()
            .filter(|n| factory_names.iter().any(|f| f == *n))
            .cloned()
            .collect();
        let skipped: Vec<String> = picked
            .iter()
            .filter(|n| !factory_names.iter().any(|f| f == *n))
            .cloned()
            .collect();
        if exportable.is_empty() {
            return "无可导出(勾选里没有无界面可用的组件)".to_string();
        }
        if dir.trim().is_empty() {
            return "目录为空(先填路径)".to_string();
        }
        let path = std::path::Path::new(dir).join("ek-plugins.txt");
        let header = if skipped.is_empty() {
            "# ek-station 启动清单(ek-ui 阶段机导出,一行一名)".to_string()
        } else {
            format!(
                "# ek-station 启动清单(ek-ui 阶段机导出,一行一名;跳过界面自带工厂:{})",
                skipped.join(",")
            )
        };
        let body = format!("{}\n{}\n", header, exportable.join("\n"));
        match std::fs::File::create(&path).and_then(|mut f| {
            use std::io::Write;
            f.write_all(body.as_bytes())
        }) {
            Ok(()) => {
                self.shared
                    .log_line(format!("[ui] 启动清单已导出:{}", path.display()));
                if skipped.is_empty() {
                    format!("清单已导出:{}({} 项)", path.display(), exportable.len())
                } else {
                    format!(
                        "清单已导出:{}({} 项;跳过界面自带工厂 {})",
                        path.display(),
                        exportable.len(),
                        skipped.join(",")
                    )
                }
            }
            Err(e) => format!("导出失败:{e}"),
        }
    }

    fn ensure_watcher(&mut self) {
        if self.watcher.is_none() {
            self.watcher = Some(spawn_host_watcher(&self.engine, &self.shared));
        }
    }

    fn write_ready_marker(&self) {
        let Some(marker) = &self.ready_marker else {
            return;
        };
        use std::io::Write;
        if let Ok(mut f) = std::fs::File::create(marker) {
            let _ = f.write_all(crate::launch::READY_TEXT.as_bytes());
        }
    }

    /// 组件配置面板(Setup 相中央面板;判据 U-S1a 的查控件面在此,判据面可见)。
    pub fn render_setup_panel(&mut self, ui: &mut egui::Ui) {
        ui.heading("组件配置(启动前)");
        ui.label("勾选要装载的组件 → 装配 → 参数面可改 → 启动运行;启动后装配锁定(只可看不可动)。");
        ui.separator();
        egui::ScrollArea::vertical()
            .max_height(210.0)
            .show(ui, |ui| {
                for (i, k) in self.kinds.iter().enumerate() {
                    ui.horizontal(|ui| {
                        if k.name == UI_NAME {
                            // S4b:ui 行恒勾灰显(勾掉 = 主界面自灭,逻辑不许成立)。
                            let mut t = true;
                            ui.add_enabled(false, egui::Checkbox::new(&mut t, k.name));
                            self.sel[i] = true;
                        } else {
                            ui.checkbox(&mut self.sel[i], k.name);
                        }
                        let _ = ui.label(egui::RichText::new(k.doc.to_string()).small().weak());
                    });
                }
            });
        ui.separator();
        let picked = self.picked();
        ui.label(if picked.is_empty() {
            "已选: (无)".to_string()
        } else {
            format!("已选: {}", picked.join(", "))
        });
        ui.horizontal(|ui| {
            let assembled = self.assembled();
            if ui
                .add_enabled(
                    !assembled && !picked.is_empty(),
                    egui::Button::new("装配(按勾选)"),
                )
                .clicked()
            {
                let msg = self.do_assemble();
                self.notice = Some(msg);
            }
            if ui
                .add_enabled(assembled, egui::Button::new("启动运行"))
                .clicked()
            {
                let msg = self.do_start();
                self.notice = Some(msg);
            }
            if ui.button("参数面(改参数)").clicked() {
                self.shared
                    .set_pluginwin_open(!self.shared.pluginwin_open());
            }
            if ui.button("档案包(导入参数)").clicked() {
                self.shared.set_bundle_open(!self.shared.bundle_open());
            }
        });
        ui.horizontal(|ui| {
            ui.add(
                egui::TextEdit::singleline(&mut self.list_dir)
                    .desired_width(300.0)
                    .hint_text("启动清单导出目录,如 C:\\Users\\<你>\\Documents"),
            );
            if ui.button("导出启动清单(--from 可用)").clicked() {
                let dir = self.list_dir.clone();
                let msg = self.export_plugin_list(&dir);
                self.notice = Some(msg);
            }
        });
        if self.assembled() && self.stage == Stage::Setup {
            ui.label(
                egui::RichText::new("已装配(未启动):参数面窗可改,启动时按档案回灌。")
                    .color(crate::tokens::info(ui.ctx()))
                    .small(),
            );
        }
        if let Some(n) = &self.notice {
            ui.label(egui::RichText::new(n.as_str()).monospace().small());
        }
    }
}

impl eframe::App for StageApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        let host = crate::faces::CfgBridge::new(&self.shared);
        let mounted = crate::faces::mounted(&self.engine);
        // 「参数面」钮开 = 整组挂载窗亮;逐窗 X 关合**持久**(wins_open 记账,0.9.3)。
        let pw = self.shared.pluginwin_open();
        if pw && !self.pluginwin_prev {
            self.wins_open.clear();
        }
        self.pluginwin_prev = pw;
        if pw {
            for (name, title) in mounted.iter() {
                let mut open = *self.wins_open.get(name).unwrap_or(&true);
                egui::Window::new(title.as_str())
                    .id(egui::Id::new(format!("pluginwin-{name}")))
                    .open(&mut open)
                    .default_width(460.0)
                    .show(ctx, |ui| {
                        crate::faces::render_face(ui, &self.engine, name, &host, &mut self.fs);
                    });
                self.wins_open.insert(name.clone(), open);
            }
        }
        // 档案包窗口:导出/导入 + 逐段回执显形;X 关合落回 shared(0.9.3)。
        // Setup 相导出钮 disable(还没跑,导出无内容 = 多余钮,审核定案)。
        if self.shared.bundle_open() {
            let mut open = true;
            let setup = self.stage == Stage::Setup;
            egui::Window::new("档案包")
                .id(egui::Id::new("bundlewin"))
                .open(&mut open)
                .default_width(430.0)
                .show(ctx, |ui| {
                    ui.label("目录(导出目标 / 导入来源,同一目录可两用):");
                    ui.add(
                        egui::TextEdit::singleline(&mut self.bundle_dir)
                            .desired_width(400.0)
                            .hint_text("C:\\Users\\<你>\\Documents\\ek-bundle"),
                    );
                    ui.horizontal(|ui| {
                        if ui
                            .add_enabled(
                                !setup,
                                egui::Button::new("导出(段文件整批复制)"),
                            )
                            .clicked()
                        {
                            self.bundle_notice =
                                Some(bundle_op(&self.shared, &self.engine, &self.bundle_dir, true));
                        }
                        if ui.button("导入(逐段收编+受理)").clicked() {
                            self.bundle_notice = Some(bundle_op(
                                &self.shared,
                                &self.engine,
                                &self.bundle_dir,
                                false,
                            ));
                        }
                    });
                    if let Some(n) = &self.bundle_notice {
                        ui.label(egui::RichText::new(n.as_str()).monospace().small());
                    }
                    ui.label(
                        egui::RichText::new("密码不落包(在 Windows 凭据管理器);换机后口令走 ekapp add-account(stdin)")
                            .small()
                            .weak(),
                    );
                });
            self.shared.set_bundle_open(open);
        }
        // 中央面板唯一形貌:配置相 = 组件配置面;运行相 = 主界面
        // (官方纪律:CentralPanel 最后,BD-UI-29;两相各只画一个 CentralPanel)。
        if self.stage == Stage::Setup {
            egui::CentralPanel::default().show(ctx, |ui| {
                self.render_setup_panel(ui);
            });
        } else {
            crate::render_body(ctx, &self.shared);
        }
        ctx.request_repaint_after(Duration::from_secs(1));
    }
}

/// 运行选项(S1c ready 标记 + S4 dm real_time 装配参数;ek-ui 零配置口径,
/// 无任何配置文件输入 —— 结构只由 StationConfig 清单决定)。
#[derive(Debug, Clone)]
pub struct RunOpts {
    /// launcher 协议:`start 成功后写 "ready\n"` 的标记路径。
    pub ready_marker: Option<std::path::PathBuf>,
    /// dm 工厂 real_time 门(装配参数,缺省 true —— UI 宿主观测面要实时门)。
    pub dm_rt: bool,
    /// 0.9.5 阶段机:true = 开窗前装配+启动走完(launcher/headless 式一次性启动,
    /// ready 协议不破);false = 从配置相起步(桌面 ekapp 裁定面)。
    pub auto_boot: bool,
}

impl Default for RunOpts {
    /// 缺省:无 ready 标记 + **dm_rt = true**(UI 宿主缺省实时门;
    /// 勿改回 derive(Default) —— bool 缺省 false 会静默关实时门)
    /// + **auto_boot = true**(launcher/主程序旧口径:开窗即运行相)。
    fn default() -> Self {
        Self {
            ready_marker: None,
            dm_rt: true,
            auto_boot: true,
        }
    }
}

impl RunOpts {
    /// 空选项(无 ready 标记)。
    pub fn plain() -> Self {
        Self::default()
    }
}

/// 进程主入口:装配(dm/oms/ctp/ui 按清单)→ start → 就绪标记(可选)
/// → eframe 主循环 → 观察线程收场。
pub fn run_station_ui(cfg: &StationConfig, opts: &RunOpts) -> Result<(), String> {
    let engine = Arc::new(MainEngine::new(None));
    let shared = Arc::new(UiShared::new());
    let store = ek_cfg::Store::eco();

    // 配置托底根(0.6.0/BD-CFG 环节8):UI 宿主与 headless 同口径 ——
    // `Store::eco()` 成功 → `boot_with_cfg`(开机逐插件 apply_persisted,
    // 受理三行序在插件 worker 面);eco 失败(平台缺配置目录,罕见)→
    // 退回 `boot()`(cfg 收件壳仍在场,fallback 直写仍通,UI 行为即旧版零变)。
    let store_ok = store.ok();
    if opts.auto_boot {
        let boot = match &store_ok {
            Some(s) => {
                ek_station::boot_with_cfg(&engine, &ui_kinds(&shared, opts.dm_rt), cfg, Some(s))
            }
            None => ek_station::boot(&engine, &ui_kinds(&shared, opts.dm_rt), cfg),
        };
        boot.map_err(|e| format!("boot: {e:?}"))?;
        // start 失败也要走 close_all(0.4.3 BD-UI-64,审核 P3;与 ek-station headless
        // main.rs 的 start 失败路径同口径):start 是逐个 launch 的,失败时已有插件在
        // Running —— 不闭就没有 on_stop(网关侧的会话收尾与流目录处理被跳过)。
        // boot 失败不用闭:那时插件只登记未 launch,没有 worker 要收。
        if let Err(e) = engine.start() {
            engine.close_all(Duration::from_secs(3));
            return Err(format!("start: {e:?}"));
        }
        shared.set_assembly_locked(true);
    }

    let mut app = StageApp::new_setup(
        Arc::clone(&engine),
        Arc::clone(&shared),
        ui_kinds(&shared, opts.dm_rt),
        store_ok,
        opts.ready_marker.clone(),
    );
    if opts.auto_boot {
        app = StageApp {
            stage: Stage::Running,
            ..app
        };
        app.write_ready_marker();
    }

    let watcher = spawn_host_watcher(&engine, &shared);
    // 观察线程句柄交 App 之外统一 join(与 0.9.4 同路;App 内 ensure_watcher 幂等)。
    let _ = &watcher;

    let opts = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([1280.0, 860.0])
            .with_title("ek-station"),
        ..Default::default()
    };
    // 关窗即收:run_native 返回 = 窗口已关 → 置 stop → 观察线程 close_all(BD-UI-11)。
    let result = eframe::run_native(
        "ek-station",
        opts,
        Box::new(|cc| {
            crate::fonts::apply_cjk_fonts(&cc.egui_ctx); // BD-UI-26:CJK 回退,中文不乱码
            Ok(Box::new(app) as Box<dyn eframe::App>)
        }),
    );
    shared.request_stop();
    let _ = watcher.join();
    result.map_err(|e| format!("ui: {e:?}"))
}

/// 桌面产品入口(ekapp 无参数路,0.9.5 起单源在此):**从配置相起步** ——
/// 开窗不装配不启动(用户裁定「先配置组件、运行后才出主界面」);
/// 观察线程在开窗即挂(Setup 关窗也走 close_all 收尾,U-S3b 口径)。
pub fn run_desktop() -> Result<(), String> {
    let engine = Arc::new(MainEngine::new(None));
    let shared = Arc::new(UiShared::new());
    let store = ek_cfg::Store::eco().ok();
    let app = StageApp::new_setup(
        Arc::clone(&engine),
        Arc::clone(&shared),
        ui_kinds(&shared, true),
        store,
        None,
    );
    let watcher = spawn_host_watcher(&engine, &shared);
    let opts = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([1280.0, 860.0])
            .with_title("ek-station 桌面"),
        ..Default::default()
    };
    let result = eframe::run_native(
        "ek-station 桌面",
        opts,
        Box::new(|cc| {
            crate::fonts::apply_cjk_fonts(&cc.egui_ctx);
            Ok(Box::new(app) as Box<dyn eframe::App>)
        }),
    );
    shared.request_stop();
    let _ = watcher.join();
    result.map_err(|e| format!("ui: {e:?}"))
}