diff --git a/README.md b/README.md index f8e51dc..5162a29 100644 --- a/README.md +++ b/README.md @@ -85,17 +85,27 @@ Application 步骤用于启动外部程序,本身不等待外部程序退出 ![最近方案记录](docs/images/launchflow-plan-history.png) -应用自身的设置、日志、许可和最近记录默认位于 `%LOCALAPPDATA%\LaunchFlow`。测试和自动化可以通过 `LAUNCHFLOW_DATA_DIR` 指向隔离目录。程序不会默认在源码目录、当前工作目录、桌面或 EXE 旁边创建可变数据文件夹。 +当前产品路径(`python -m editor.main` 或 `LaunchFlow.exe`)会把应用自身的设置、日志、许可和最近记录放在 `%LOCALAPPDATA%\LaunchFlow`。Basic 入口(`python -m editor.main_basic`)使用相互隔离的 `%LOCALAPPDATA%\LaunchFlow-Basic`,不会读取或迁移 Professional 数据。测试和自动化可以通过 `LAUNCHFLOW_DATA_DIR` 指向隔离目录,但该覆盖不能用来让 Basic 写入 Professional 目录。程序不会默认在源码目录、当前工作目录、桌面或 EXE 旁边创建可变数据文件夹。 升级前建议备份自己保存的方案 JSON 和 `%LOCALAPPDATA%\LaunchFlow` 中需要保留的数据。LaunchFlow 的迁移策略以保守复制为主,不应覆盖更新的数据;显式选择的方案保存位置和导出位置始终由用户决定。 + +## 🧱 两个版本 + +仓库现在包含 Professional 与 Basic 两套实现路径,但这并不是说已经同时存在两个公开发布包。最近的公开检查点仍是 `v0.1.0-beta.2`,对应当前这条单一产品 / Professional 路径。 + +- Professional:启动 `python -m editor.main`,或打包 `LaunchFlow.exe`。它保留 Command、Wait、高级 Application 配置、现有快捷方式打开方式,以及离线许可。用户数据位于 `%LOCALAPPDATA%\LaunchFlow`。 +- Basic:启动 `python -m editor.main_basic`,或打包 `LaunchFlow-Basic.exe`。它只接受 Application 与 http/https URL,启动时不要求许可证,数据位于 `%LOCALAPPDATA%\LaunchFlow-Basic`。工作台不会提供 Command、Wait、应用启动参数或自定义间隔,导出的独立启动器也使用不含这些能力的受限运行器。 + +开发模式分别使用 `tools/run_editor_dev.ps1`(`LaunchFlow-Dev`)和 `tools/run_editor_basic_dev.ps1`(`LaunchFlow-Basic-Dev`)。默认的 `python tools/build_editor_release.py` 仍然只打包 Professional;Basic 需要显式加上 `--edition basic`。在公开发布 Basic 之前,请不要把源码里的第二条入口当成已经上线的安装包。 + ## 📦 导出 Windows 启动器 完成试运行后,可点击“导出 EXE”或按 `Ctrl+E`。导出对话框会展示输出目录、文件名、方案步骤摘要、携带文件检查以及构建状态。真正开始构建前,用户仍有机会返回编辑器修正方案。 ![导出工作流](docs/images/launchflow-export-workflow.png) -导出的启动器是针对当前方案生成的 Windows onefile 程序。它包含 LaunchFlow 运行方案所需的启动器代码和方案数据,但不会自动捆绑所有第三方运行环境: +导出的启动器是针对当前方案生成的 Windows onefile 程序。它包含运行该方案所需的启动器代码和方案数据,但不会自动捆绑所有第三方运行环境。Professional 入口导出的运行器仍包含 Command 与 Wait;从 Basic 入口导出时,会改用一份不含这些能力的受限运行器: - URL 仍依赖目标电脑的默认浏览器和网络条件。 - Command 仍依赖目标电脑已安装的命令、Shell、PATH 和相关文件。 @@ -132,6 +142,8 @@ python -m pip install "PySide6==6.9.3" "PyInstaller==6.20.0" cryptography python -m editor.main ``` +当前这条命令启动的是 Professional / 现有产品路径。若要在源码模式下启动 Basic(不要求许可证,数据写入 `LaunchFlow-Basic`),使用 `python -m editor.main_basic`。 + 若 PowerShell 的执行策略阻止激活脚本,可以直接调用虚拟环境中的 Python,而不修改系统策略: ```powershell @@ -178,6 +190,7 @@ data/ 源码模式使用的只读默认资源 ```powershell python tools/check_readme_docs_smoke.py +python tools/check_dual_edition_phase2_smoke.py python tools/check_editor_gui_smoke.py python tools/check_step_reorder_smoke.py python tools/check_log_presentation_smoke.py diff --git a/README_EN.md b/README_EN.md index 6422468..260e0d8 100644 --- a/README_EN.md +++ b/README_EN.md @@ -85,17 +85,27 @@ Plans are JSON files saved at a location selected by the user. The Recent Plans ![Recent plan history](docs/images/launchflow-plan-history.png) -LaunchFlow stores its own settings, logs, license state, and recent-plan metadata under `%LOCALAPPDATA%\LaunchFlow` by default. Automated checks can point `LAUNCHFLOW_DATA_DIR` to an isolated location. Normal operation does not create mutable data folders beside the source tree, in the current working directory, on the desktop, or next to a packaged EXE. +The current product path (`python -m editor.main` or `LaunchFlow.exe`) stores its own settings, logs, license state, and recent-plan metadata under `%LOCALAPPDATA%\LaunchFlow`. The Basic entry (`python -m editor.main_basic`) uses a separate `%LOCALAPPDATA%\LaunchFlow-Basic` tree and does not read or migrate Professional data. Automated checks can point `LAUNCHFLOW_DATA_DIR` to an isolated location, but that override must not be used to make Basic write into the Professional directory. Normal operation does not create mutable data folders beside the source tree, in the current working directory, on the desktop, or next to a packaged EXE. Before an upgrade, back up valuable plan JSON files and any application data that must be retained. Legacy migration is intentionally conservative and copy-oriented; it should not overwrite newer data. Explicit plan-save and export destinations remain the user's choice even though background state is centralized. + +## 🧱 Two Editions + +The repository now contains Professional and Basic implementation paths. That does not mean two public release packages already exist. The latest published checkpoint remains `v0.1.0-beta.2`, which corresponds to the current single-product / Professional path. + +- Professional: start `python -m editor.main`, or package `LaunchFlow.exe`. It keeps Command, Wait, advanced Application options, the existing shortcut-open behavior, and offline licensing. User data lives under `%LOCALAPPDATA%\LaunchFlow`. +- Basic: start `python -m editor.main_basic`, or package `LaunchFlow-Basic.exe`. It accepts only Application and http/https URL steps, does not require a license at startup, and stores data under `%LOCALAPPDATA%\LaunchFlow-Basic`. The workbench does not offer Command, Wait, application arguments, or custom delays, and exported standalone launchers use a restricted runner that does not embed those capabilities. + +Developer mode uses `tools/run_editor_dev.ps1` (`LaunchFlow-Dev`) and `tools/run_editor_basic_dev.ps1` (`LaunchFlow-Basic-Dev`). The default `python tools/build_editor_release.py` command still packages only Professional; Basic requires an explicit `--edition basic`. Until a public Basic release exists, do not treat the second source entry as a shipping installer. + ## 📦 Exporting a Windows Launcher After a successful test run, choose Export EXE or press `Ctrl+E`. The export dialog presents the destination, output name, plan summary, bundled-file review, and build state. It keeps the plan visible behind the focused dialog, allowing the user to cancel and correct the workflow before starting a build. ![Export workflow](docs/images/launchflow-export-workflow.png) -The result is a Windows onefile launcher created for the current plan. It contains the LaunchFlow runtime needed to read that plan and the embedded plan data, but it does not automatically bundle every third-party runtime: +The result is a Windows onefile launcher created for the current plan. It contains the runner code needed to read that plan and the embedded plan data, but it does not automatically bundle every third-party runtime. A launcher exported from the Professional entry still includes Command and Wait; a launcher exported from the Basic entry uses a restricted runner that does not include those capabilities: - A URL still depends on the target computer's default browser and network conditions. - A Command still depends on the selected shell, executable, PATH, files, and runtime being present on the target computer. @@ -132,6 +142,8 @@ python -m pip install "PySide6==6.9.3" "PyInstaller==6.20.0" cryptography python -m editor.main ``` +That command starts the Professional / current product path. To start Basic from source (no license required, data written to `LaunchFlow-Basic`), use `python -m editor.main_basic`. + If local PowerShell policy prevents running the activation script, call the virtual environment's Python directly instead of changing machine-wide policy: ```powershell @@ -178,6 +190,7 @@ The repository provides independent smoke scripts that can be run directly on Wi ```powershell python tools/check_readme_docs_smoke.py +python tools/check_dual_edition_phase2_smoke.py python tools/check_editor_gui_smoke.py python tools/check_step_reorder_smoke.py python tools/check_log_presentation_smoke.py diff --git a/docs/beta-testing.md b/docs/beta-testing.md index 63de113..fee55f0 100644 --- a/docs/beta-testing.md +++ b/docs/beta-testing.md @@ -303,7 +303,21 @@ python tools/generate_readme_screenshots.py python tools/check_readme_docs_smoke.py ``` -## 10. 免责声明 +## 10. 双版本实现说明(2026-11-24) + +当前对外测试流程仍然对应 Professional / 现有单一产品路径:启动 `LaunchFlow.exe` 或 `python -m editor.main`,走离线授权,数据位于 `%LOCALAPPDATA%\LaunchFlow`。最近公开检查点仍是 `v0.1.0-beta.2`。 + +仓库里已经增加 Basic 实现入口,但这不是新的公开 Beta 包: + +- 源码启动:`python -m editor.main_basic` +- 开发数据目录:`tools/run_editor_basic_dev.ps1` 指向 `%LOCALAPPDATA%\LaunchFlow-Basic-Dev` +- 正式数据目录:`%LOCALAPPDATA%\LaunchFlow-Basic` +- Basic 不读取、不迁移 Professional 数据,启动时也不要求许可证 +- Basic 只接受 Application 与 http/https URL;工作台不提供 Command、Wait、应用启动参数或自定义间隔;导出使用受限运行器 + +如果当前测试任务是验证已发布的 Beta 体验,请继续使用 Professional 入口和本文件前面的授权流程。不要把源码中的 Basic 入口误认为已经随 `v0.1.0-beta.2` 一起发布。 + +## 11. 免责声明 当前版本仍属于 Beta 测试版。 diff --git a/docs/dual-edition-phase0-contract.md b/docs/dual-edition-phase0-contract.md index 3f27e76..46dd24f 100644 --- a/docs/dual-edition-phase0-contract.md +++ b/docs/dual-edition-phase0-contract.md @@ -410,3 +410,15 @@ Phase 1a 将 Basic 方案校验提升为 `shared/basic_policy.py` 中可复用 - 映射网络驱动器在合同中已被拒绝。Phase 1b 通过注入或真实的 Windows 盘符分类器实施该拒绝;词法盘符路径不会被自动当成本地路径。 - Professional 导出授权在 Phase 1 期间保持不变,仍需后续单独审计。Phase 1b 没有修改许可校验、HWID 采集或导出授权逻辑。 - Basic 校验已按门控方式接入现有方案入口,但默认产品路径仍是当前 Professional / 单一产品行为,因为启动入口尚未引入。 + +--- + +## 附录:Phase 2 实施备注(2026-11-24,Asia/Shanghai) + +本附录不改写 Phase 0 已冻结的历史决策和当时记录的现有行为。 + +- 启动入口、数据目录隔离和 Basic 导出运行器已在 Phase 2 落地,详见 docs/dual-edition-phase2-launch-isolation.md。 +- 当前产品入口仍然是 Professional / 未设置路径;Basic 必须通过独立入口显式激活。 +- Basic 数据根现为 LaunchFlow-Basic;该路径不得回退到 Professional 数据目录,也不得探测或迁移 Professional 数据。 +- Professional EMBEDDED_TEMPLATE 保持不变;Basic 使用独立的受限运行器模板。 +- Professional 导出授权仍待后续单独审计。 diff --git a/docs/dual-edition-phase1b-windows-adapters.md b/docs/dual-edition-phase1b-windows-adapters.md index 7f7ac20..792c631 100644 --- a/docs/dual-edition-phase1b-windows-adapters.md +++ b/docs/dual-edition-phase1b-windows-adapters.md @@ -165,3 +165,15 @@ Phase 1b **没有**引入 Basic / Professional 启动入口,没有切换数据 4. 单独审计 Professional 导出授权,这不在本阶段范围内。 在这些工作完成之前,Phase 1b 提供的是真实 Windows 适配器,以及一条默认关闭的 Basic 校验路径。 + +--- + +## 附录:Phase 2 追加说明(2026-11-24,Asia/Shanghai) + +以下内容不改写上文已记录的 Phase 1b 行为,只补充后续已实现事项: + +- 已新增明确的 Basic 启动入口 `editor/main_basic.py`,并在启动时设置进程级 Basic 上下文。当前产品入口 `editor/main.py` 仍保持 Professional / 未设置路径,不会被改成 Basic。 +- 已实现 `LaunchFlow-Basic` 数据目录隔离,Basic 不会探测或迁移 Professional 数据。 +- 已为 Basic 导出提供独立的受限运行器模板;Professional `EMBEDDED_TEMPLATE` 保持不变。 +- Professional 导出授权仍待后续单独审计。 +- 详见 `docs/dual-edition-phase2-launch-isolation.md`。 diff --git a/docs/dual-edition-phase2-launch-isolation.md b/docs/dual-edition-phase2-launch-isolation.md new file mode 100644 index 0000000..1f71642 --- /dev/null +++ b/docs/dual-edition-phase2-launch-isolation.md @@ -0,0 +1,162 @@ +# LaunchFlow 双版本架构 — Phase 2 启动入口、数据隔离与 Basic 运行器 + +- 状态:Phase 2 已实现明确的 Basic / Professional 启动入口、Basic 数据目录隔离,以及受限的 Basic 导出运行器;这不是一次新的公开发布 +- 日期:2026-11-24(Asia/Shanghai) +- 新增或接线模块:`editor/launch.py`、`editor/main_basic.py`、`tools/basic_embedded_runner.py`、`tools/run_editor_basic_dev.ps1` +- 测试:`tools/check_dual_edition_phase2_smoke.py` +- 上游:`docs/dual-edition-phase1b-windows-adapters.md`、`docs/dual-edition-phase0-contract.md` + +本文记录已经实现的 Phase 2 行为。不得把下文“已知限制”写成已经交付的公开发布能力,也不得把本次实现理解为已经替换 `v0.1.0-beta.2` 的公开产物。 + +Phase 2 **没有**修改最近公开发布检查点 `v0.1.0-beta.2`,没有调用 PyInstaller,没有生成发布 EXE,没有审计或改变 Professional 导出授权,也没有开始后续阶段。`docs/architecture.md` 与 `CHANGELOG.md` 当时存在未提交的本地修改,因此本阶段没有改这两份文件;它们需要在本地改动稳定后另作更新。 + +--- + +## 1. 启动入口 + +当前产品入口仍然是 Professional / 单一产品路径: + +| 入口 | 启动方式 | 进程级版本上下文 | 授权 | 数据目录 | +| --- | --- | --- | --- | --- | +| `editor/main.py` | `python -m editor.main`,默认打包为 `LaunchFlow.exe` | 未设置,视为 Professional | 保持现有离线许可与激活窗口 | `%LOCALAPPDATA%\LaunchFlow` | +| `editor/main_basic.py` | `python -m editor.main_basic`,打包目标为 `LaunchFlow-Basic.exe` | 显式设置为 `basic` | 不校验许可证,不采集 HWID | `%LOCALAPPDATA%\LaunchFlow-Basic` | + +公共逻辑位于 `editor/launch.py`。Professional 入口会在创建数据目录之前把进程上下文复位为未设置,避免残留的 Basic 上下文把当前产品路径改成 Basic。Basic 入口则必须在 `ensure_app_directories()` 之前设置 Basic 上下文。 + +当前入口的 Windows 进程标识仍是 `forgottenlab.launchflow.editor`。Basic 入口使用单独的 `forgottenlab.launchflow.editor.basic`,避免两个版本在任务栏中被当成同一个进程。这只是对现有 `configure_windows_app_id()` 门面传入不同标识,没有新增 Windows API 调用点。 + +开发模式继续通过进程级 `LAUNCHFLOW_DATA_DIR` 切换,而不是改 `get_app_data_dir()` 的默认计算: + +- Professional:`tools/run_editor_dev.ps1` 仍指向 `%LOCALAPPDATA%\LaunchFlow-Dev`,并启动 `python -m editor.main` +- Basic:新增 `tools/run_editor_basic_dev.ps1`,指向 `%LOCALAPPDATA%\LaunchFlow-Basic-Dev`,并启动 `python -m editor.main_basic` + +本次确认 Phase 0 中的未决问题:Basic 开发目录采用 `LaunchFlow-Basic-Dev`。 + +--- + +## 2. 数据目录隔离 + +`shared/app_paths.py` 在 Basic 上下文激活时把目录名切换为 `LaunchFlow-Basic`,Professional / 未设置上下文继续使用 `LaunchFlow`。常量 `APP_DIR_NAME` 仍为 `"LaunchFlow"`,以保持现有兼容测试不变。 + +强制规则: + +- Basic 不得探测、读取、清理或迁移 `%LOCALAPPDATA%\LaunchFlow` 或 `LaunchFlow-Dev` +- `migrate_legacy_data()` 在 Basic 上下文中直接失败关闭并跳过,不检查任何遗留根目录,也不复制 `license.lic` +- Basic 启动路径本身不会调用遗留迁移 +- 若 `LAUNCHFLOW_DATA_DIR` 指向 Professional 默认根(`LaunchFlow` 或 `LaunchFlow-Dev`),Basic 会拒绝该覆盖,而不是回退到 Professional 目录 +- 指向其他绝对路径的测试覆盖仍然可用,但不得成为两个版本共享可变状态的通道 + +--- + +## 3. Basic 导出运行器 + +Professional 的 `EMBEDDED_TEMPLATE` 保持不变,包括 Command、Wait、脚本应用以及 LNK 的 `os.startfile` 行为。Basic 运行器位于单独模块 `tools/basic_embedded_runner.py`,由 `build_single_file_exe()` 在 Basic 上下文中选用。 + +两者可以继续共享临时目录、资源暂存和 PyInstaller 命令组装。它们不得共享无限制的嵌入式执行模板。 + +Basic 运行器限制: + +- 不嵌入 `run_command_step` / `run_wait_step` +- 不处理 PowerShell 脚本或其他脚本后缀应用 +- 不通过 `os.startfile(path)` 盲目打开快捷方式 +- 导出时若方案包含 `.lnk`,必须先解析为本地 `.exe` 后再序列化为进程启动;解析失败则在创建输出目录和查找 PyInstaller 之前失败关闭 +- 只把现有的本地 `.exe` 当作可打包资源,不会打包 `.bat` / `.cmd` / `.com` / `.ps1` +- 运行器日志写入 `LaunchFlow-Basic`(或非 Professional 的测试覆盖目录) +- 若仍写出 `{stem}_embedded_debug.py`,其能力与受限 Basic 运行器一致 +- 不导入许可模块,也不采集硬件身份 + +Professional 导出授权仍待后续单独审计。本次没有把授权检查加进 `build_single_file_exe()`。 + +--- + +## 4. 编辑器界面裁剪 + +Professional / 当前产品入口的工作台保持原样:仍然提供“+ 命令”“+ 等待”、应用启动参数,以及可编辑的后续延迟。 + +Basic 入口会在同一套 `MainWindow` 上裁剪 Professional-only 能力,而不是另做一套窗口: + +- 不显示“+ 命令”和“+ 等待”按钮,直接调用添加接口也会被拒绝 +- 不显示应用启动参数,也不显示可自定义的 `delay_after` 控件;保存步骤时固定为无参数、间隔 1 秒 +- 添加应用时的文件选择只包含本地 `.exe` / `.lnk` +- 首次写入 Basic 数据目录的 `app_templates.json` 不含 Command / Wait;即使文件被污染,加载时也会过滤 +- 空状态提示、侧栏名称和标题栏会标明 LaunchFlow Basic,避免看起来仍是完整 Professional 工作台 + +Basic 仍然可以先添加一个空白网页步骤,再补全 URL。缺失 URL 会在加载、试运行或导出时被拒绝,而不是在点击“+ 网页”时直接失败。 + +当前 GUI 本身在两个版本中都没有提供工作目录或“最小化启动”编辑控件。这是已有界面范围,不是本次为 Professional 新增的能力。Basic 仍会通过方案校验拒绝这些字段。 + +## 5. 打包与发布路径 + +当前默认打包命令仍然只生成 Professional 编辑器: + +```powershell +python tools/build_editor_release.py +``` + +它继续使用 `editor/main.py`,输出 `LaunchFlow.exe`。Basic 需要显式选择: + +```powershell +python tools/build_editor_release.py --edition basic +``` + +这会使用 `editor/main_basic.py`,输出 `LaunchFlow-Basic.exe`。本次实现没有实际调用 PyInstaller,也没有把 Basic 编辑器发布成新的公开 Beta 资产。`v0.1.0-beta.2` 仍是最近的公开发布检查点。 + +--- + +## 6. 测试覆盖 + +`tools/check_dual_edition_phase2_smoke.py` 覆盖: + +1. 当前产品入口保持未设置 / Professional,不会把默认路径改成 Basic +2. Basic 入口会设置进程级 Basic 上下文,且发生在创建数据目录之前 +3. Basic 入口不导入或调用许可、HWID 或遗留迁移 +4. Basic 默认数据根为 `LaunchFlow-Basic`,不会创建或读取 Professional 数据 +5. 指向 `LaunchFlow` / `LaunchFlow-Dev` 的覆盖在 Basic 下失败关闭 +6. `migrate_legacy_data()` 在 Basic 下不复制 Professional 许可或方案 +7. Professional `EMBEDDED_TEMPLATE` 的哈希与 Command / Wait / LNK `shell_open` 合同保持不变 +8. Basic 运行器模板通过 Phase 0 冻结的能力边界检查 +9. Basic 导出在拒绝 Command 方案时不会查找 PyInstaller,也不会创建输出目录或调试脚本 +10. 默认编辑器打包入口仍是 `LaunchFlow.exe` / `editor/main.py`;Basic 打包入口是独立的 +11. Basic 默认模板和 `load_templates()` 不含 Command / Wait;Professional 默认模板保持不变 +12. Basic 工作台隐藏 Command / Wait 按钮、应用参数和自定义延迟;Professional 工作台这些控件仍然可见 + +现有 Phase 0 / 1a / 1b 合同与策略测试,以及无副作用的路径、迁移、平台耦合、应用/URL 与文档冒烟测试应继续通过。 + +--- + +## 7. 平台耦合说明 + +Phase 2 没有新增核心包中的 Windows API 调用。Basic 入口复用已有的 `configure_windows_app_id()` 门面。新增的工具边界包括: + +- `tools/basic_embedded_runner.py`:独立 EXE 运行器中的 `MessageBoxW`、`LOCALAPPDATA` 以及仅用于 http/https 的 `os.startfile(url)` +- `tools/run_editor_basic_dev.ps1`:进程级数据目录覆盖与源码启动 + +这些边界已加入 `tools/check_platform_coupling_smoke.py` 的工具入口扫描。本次已按 Phase 1b 的方式完成审查,并把 Basic 运行器、Basic 开发脚本、Basic 打包后缀以及分版本打包标题中的 Windows 边界作为 `allowed_windows_boundary` 记入 `tools/check_platform_coupling_baseline.json`。它们不是新的核心耦合。同时移除了 `tools/build_editor_release.py` 中因 `print("开始打包 LaunchFlow.exe")` 改为分版本 `heading` 而失效的旧 baseline 记录。CI 的 `macos_ci_report.py coupling` 要求 `new`、`new_core` 和 `stale_baseline` 均为 0。 + +--- + +## 8. 已知限制 + +- 本次没有发布独立的 Basic 安装包或公开 GitHub Release 资产。文档描述的是仓库中已经落地的实现与打包入口。 +- Professional 导出授权仍依赖“此前已进入主窗口”,直接调用 `build_single_file_exe()` 的审计仍待后续任务。 +- Basic 编辑器仍复用现有 `MainWindow`,只按版本隐藏或拒绝 Professional-only 能力,没有做成完全独立的第二套界面。 +- 工作目录和“最小化启动”本来就不在当前 GUI 中编辑;它们继续只存在于方案模型和 Professional 运行/导出路径里。 +- 本阶段未修改 `docs/architecture.md` 和 `CHANGELOG.md`。 + +--- + +## 9. 建议的下一阶段 + +建议的下一阶段不要自动开始。在获得单独授权之前,不应把 Basic 宣传成已经对外发布的产品。 + +推荐顺序: + +1. 单独审计 Professional 导出授权,避免直接调用导出器绕过现有激活前提。 +2. 在本地文档改动稳定后,把本阶段结论同步进 `docs/architecture.md` 和 `CHANGELOG.md`。 +3. 若要作为产品发布 Basic,再补发布说明和经过授权的打包构建。 + +--- + +## English Summary + +Phase 2 adds an explicit Basic launch entry, LaunchFlow-Basic data isolation, a restricted Basic export runner, and Basic workbench trimming, while leaving the current product entry on the Professional path. `python -m editor.main` / `LaunchFlow.exe` still uses `%LOCALAPPDATA%\LaunchFlow`, keeps offline licensing, and shows the full existing UI, including Command, Wait, application arguments, and custom delays. `python -m editor.main_basic` / the `LaunchFlow-Basic.exe` packaging target sets process-wide Basic context first, skips license and legacy migration, refuses to read or fall back to Professional data, and hides Professional-only templates and advanced App controls. The Professional `EMBEDDED_TEMPLATE` is unchanged; Basic export uses a separate runner that cannot embed Command, Wait, script apps, or unvalidated shortcut shell-open behavior, and writes logs under LaunchFlow-Basic. The Basic runner, Basic dev script, packable-suffix checks, and split packaging headings were reviewed and recorded in `tools/check_platform_coupling_baseline.json` as `allowed_windows_boundary`, and the stale `print("开始打包 LaunchFlow.exe")` baseline entry was removed so `macos_ci_report.py coupling` can pass with `new=0`, `new_core=0`, and `stale_baseline=0`. This is an in-repo implementation, not a new public Beta release; `v0.1.0-beta.2` remains the latest published artifact. `docs/architecture.md` and `CHANGELOG.md` still need a later pass after local edits settle. diff --git a/docs/gui-smoke-checklist.md b/docs/gui-smoke-checklist.md index e3dd856..0cde415 100644 --- a/docs/gui-smoke-checklist.md +++ b/docs/gui-smoke-checklist.md @@ -177,3 +177,16 @@ - 将 `LaunchFlow.exe` 单独复制到空目录短启动,目录中应仍只有该 EXE;运行数据应出现在测试覆盖目录或 `%LOCALAPPDATA%\LaunchFlow`。 - 备份/卸载人工确认:`plans/`、`licenses/` 可复制备份;删除 EXE 不会自动删除 AppData。 + +## 双版本入口(2026-11-24) + +当前公开发布检查点和本清单前面的激活、导出检查,仍针对 Professional / 现有产品路径:`LaunchFlow.exe` 或 `python -m editor.main`,数据位于 `%LOCALAPPDATA%\LaunchFlow`。 + +若要额外验证仓库中的 Basic 实现(不是已经发布的公开包): + +- 使用 `python -m editor.main_basic` 或未来的 `LaunchFlow-Basic.exe` 启动,不应出现激活页,也不应读取 `%LOCALAPPDATA%\LaunchFlow`。 +- 确认用户数据出现在 `%LOCALAPPDATA%\LaunchFlow-Basic` 或测试用的 `LAUNCHFLOW_DATA_DIR` 覆盖目录。 +- 工作台不应出现“+ 命令”“+ 等待”、应用启动参数或可改的后续延迟;空状态提示只应引导添加应用和网页。 +- 含 Command / Wait 的方案应在加载、试运行或导出时被拒绝;仅含本地 EXE 与 http/https URL 的方案可以继续。 +- Professional 与 Basic 的数据目录必须保持隔离,不能相互迁移。 +- Professional 工作台仍应保留全部现有添加按钮、启动参数和延迟控件,不能被 Basic 裁剪影响。 diff --git a/editor/edition_ui.py b/editor/edition_ui.py new file mode 100644 index 0000000..8087646 --- /dev/null +++ b/editor/edition_ui.py @@ -0,0 +1,90 @@ +"""Edition-aware editor presentation helpers. + +Professional / the current product entry keeps the full existing workbench: +Command, Wait, application arguments, and custom delay_after. Basic hides or +withholds those Professional-only capabilities so the in-app UI matches the +already-enforced plan contract. +""" + +from __future__ import annotations + +from typing import Any + +from shared.edition_policy import is_basic_edition_active + + +ALL_EDITOR_STEP_TYPES = frozenset({"app", "url", "command", "wait"}) +BASIC_EDITOR_STEP_TYPES = frozenset({"app", "url"}) + +PROFESSIONAL_APP_DIALOG_FILTER = "Applications (*.exe *.bat *.cmd *.ps1 *.lnk)" +BASIC_APP_DIALOG_FILTER = "Applications (*.exe *.lnk)" + +PROFESSIONAL_WORKBENCH_TITLE = "Launch Flow 工作台" +BASIC_WORKBENCH_TITLE = "LaunchFlow Basic 工作台" +PROFESSIONAL_BRAND_TITLE = "Launch Flow" +BASIC_BRAND_TITLE = "LaunchFlow Basic" + +PROFESSIONAL_EMPTY_STEPS_HINT = "请先在左侧点击“+ 应用 / + 网页 / + 命令 / + 等待”来添加步骤。" +BASIC_EMPTY_STEPS_HINT = "请先在左侧点击“+ 应用 / + 网页”来添加步骤。" + +PROFESSIONAL_APP_PATH_PLACEHOLDER = "选择或粘贴 .exe / .bat / .cmd / .ps1 路径" +BASIC_APP_PATH_PLACEHOLDER = "选择或粘贴本地 .exe / .lnk 路径" + +PROFESSIONAL_LOG_HINT = "后台 Command 的标准输出、错误和退出码集中显示在这里。" +BASIC_LOG_HINT = "应用和网页步骤的运行结果会显示在这里。" + +PROFESSIONAL_TRIAL_RUN_MESSAGE = "试运行会真实打开应用、网址和命令窗口。\n确定继续吗?" +BASIC_TRIAL_RUN_MESSAGE = "试运行会真实打开应用和网页。\n确定继续吗?" + + +def visible_editor_step_types() -> frozenset[str]: + """Return the step types the current editor entry should offer.""" + + if is_basic_edition_active(): + return BASIC_EDITOR_STEP_TYPES + return ALL_EDITOR_STEP_TYPES + + +def shows_professional_editor_controls() -> bool: + """True when Command, Wait, app args, and custom delays stay visible.""" + + return not is_basic_edition_active() + + +def application_file_dialog_filter() -> str: + """Return the file-dialog filter for adding an application step.""" + + if is_basic_edition_active(): + return BASIC_APP_DIALOG_FILTER + return PROFESSIONAL_APP_DIALOG_FILTER + + +def workbench_title() -> str: + return BASIC_WORKBENCH_TITLE if is_basic_edition_active() else PROFESSIONAL_WORKBENCH_TITLE + + +def brand_title() -> str: + return BASIC_BRAND_TITLE if is_basic_edition_active() else PROFESSIONAL_BRAND_TITLE + + +def empty_steps_hint() -> str: + return BASIC_EMPTY_STEPS_HINT if is_basic_edition_active() else PROFESSIONAL_EMPTY_STEPS_HINT + + +def application_path_placeholder() -> str: + return BASIC_APP_PATH_PLACEHOLDER if is_basic_edition_active() else PROFESSIONAL_APP_PATH_PLACEHOLDER + + +def log_hint_text() -> str: + return BASIC_LOG_HINT if is_basic_edition_active() else PROFESSIONAL_LOG_HINT + + +def trial_run_confirm_message() -> str: + return BASIC_TRIAL_RUN_MESSAGE if is_basic_edition_active() else PROFESSIONAL_TRIAL_RUN_MESSAGE + + +def filter_templates_for_current_edition(templates: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Return templates the current edition may offer or persist as defaults.""" + + allowed = visible_editor_step_types() + return [template for template in templates if template.get("type") in allowed] diff --git a/editor/launch.py b/editor/launch.py new file mode 100644 index 0000000..f8f4ce7 --- /dev/null +++ b/editor/launch.py @@ -0,0 +1,89 @@ +"""Launch-entry helpers for LaunchFlow edition identity. + +The current product entry (editor.main / LaunchFlow.exe) stays on the +Professional path and must not activate Basic. The Basic entry +(editor.main_basic / LaunchFlow-Basic.exe) sets the process-wide Basic +edition context before any data-directory, migration, or licensing work. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from shared.edition_policy import ( + BASIC_EDITION, + EditionContext, + get_edition_context, + set_process_edition_context, +) + + +CURRENT_PRODUCT_ENTRY = "editor.main" +BASIC_EDITOR_ENTRY = "editor.main_basic" +BASIC_EDITOR_APP_ID = "forgottenlab.launchflow.editor.basic" +BASIC_APP_DISPLAY_NAME = "LaunchFlow Basic" +BASIC_APP_DIR_NAME = "LaunchFlow-Basic" + + +def get_project_root() -> Path: + """Return the source root, or the packaged executable directory.""" + + if getattr(sys, "frozen", False): + return Path(sys.executable).resolve().parent + return Path(__file__).resolve().parent.parent + + +def ensure_project_root_on_path(project_root: Path | None = None) -> Path: + """Insert the project root on sys.path without changing edition context.""" + + root = project_root if project_root is not None else get_project_root() + root_text = str(root) + if root_text not in sys.path: + sys.path.insert(0, root_text) + return root + + +def edition_for_launch_entry(entry: str) -> str | None: + """Return the edition implied by a launch entry. + + The current product entry returns None, which is the Professional path. + """ + + normalized = str(entry or "").strip().replace("\\", "/") + if normalized in { + BASIC_EDITOR_ENTRY, + "editor/main_basic.py", + "main_basic.py", + }: + return BASIC_EDITION + if normalized in { + CURRENT_PRODUCT_ENTRY, + "editor/main.py", + "main.py", + }: + return None + raise ValueError(f"unknown LaunchFlow launch entry: {entry}") + + +def apply_current_product_launch_edition() -> EditionContext: + """Keep the current product entry on the unset Professional path.""" + + set_process_edition_context(EditionContext()) + return get_edition_context() + + +def apply_basic_launch_edition() -> EditionContext: + """Activate Basic edition context for the Basic launch entry.""" + + set_process_edition_context(EditionContext(edition=BASIC_EDITION)) + return get_edition_context() + + +def apply_launch_edition_for_entry(entry: str) -> EditionContext: + """Set process-wide edition context from the entry that was launched.""" + + edition = edition_for_launch_entry(entry) + if edition == BASIC_EDITION: + return apply_basic_launch_edition() + return apply_current_product_launch_edition() diff --git a/editor/main.py b/editor/main.py index 5060cb6..f26c705 100644 --- a/editor/main.py +++ b/editor/main.py @@ -5,9 +5,12 @@ 该模块负责: 1. 解析当前运行环境下的项目根目录; -2. 初始化 Qt 应用; -3. 在进入主工作台前先校验本地授权状态; -4. 根据授权结果决定进入激活窗口或主窗口。 +2. 保持当前产品入口位于 Professional 路径(不激活 Basic); +3. 初始化 Qt 应用; +4. 在进入主工作台前先校验本地授权状态; +5. 根据授权结果决定进入激活窗口或主窗口。 + +当前产品入口是 editor.main / LaunchFlow.exe。Basic 请使用 editor.main_basic。 位置: - editor/main.py @@ -29,6 +32,7 @@ from PySide6.QtWidgets import QApplication, QMessageBox +from editor.launch import CURRENT_PRODUCT_ENTRY, apply_launch_edition_for_entry from shared.app_info import APP_NAME from shared.app_logging import get_app_logger from shared.app_icon import apply_application_icon, configure_windows_app_id, resolve_app_icon_path @@ -70,12 +74,14 @@ def main() -> None: 启动应用程序。 启动流程: - 1. 创建 QApplication; - 2. 校验当前本地授权; - 3. 授权有效则直接进入主窗口; - 4. 授权无效则先进入激活窗口; - 5. 激活成功后再进入主窗口。 + 1. 将进程级版本上下文保持在当前 Professional 路径; + 2. 创建 QApplication; + 3. 校验当前本地授权; + 4. 授权有效则直接进入主窗口; + 5. 授权无效则先进入激活窗口; + 6. 激活成功后再进入主窗口。 """ + apply_launch_edition_for_entry(CURRENT_PRODUCT_ENTRY) # Windows must receive the stable process identity before QApplication or # any top-level window exists, otherwise taskbar grouping can keep the # generic Python/Qt identity. diff --git a/editor/main_basic.py b/editor/main_basic.py new file mode 100644 index 0000000..3cc2747 --- /dev/null +++ b/editor/main_basic.py @@ -0,0 +1,74 @@ +""" +main_basic.py + +LaunchFlow Basic 程序入口。 + +该模块负责: +1. 在任何数据目录或迁移工作之前设置进程级 Basic 版本上下文; +2. 初始化 Qt 应用,并使用与 Professional 分开的 Windows 进程标识; +3. 使用 LaunchFlow-Basic 数据目录直接进入工作台。 + +Basic 入口不校验许可证,不采集硬件身份,也不对 Professional +数据目录运行遗留迁移。 + +位置: +- editor/main_basic.py + +启动方式: +- 源码:python -m editor.main_basic +- 打包目标:LaunchFlow-Basic.exe +""" + +from __future__ import annotations + +import sys + +from PySide6.QtWidgets import QApplication, QMessageBox + +from editor.launch import ( + BASIC_APP_DISPLAY_NAME, + BASIC_EDITOR_APP_ID, + BASIC_EDITOR_ENTRY, + apply_launch_edition_for_entry, + ensure_project_root_on_path, + get_project_root, +) +from shared.app_icon import apply_application_icon, configure_windows_app_id, resolve_app_icon_path +from shared.app_logging import get_app_logger +from shared.app_paths import AppPathError, ensure_app_directories + + +PROJECT_ROOT = ensure_project_root_on_path(get_project_root()) + +from editor.ui.main_window import MainWindow + + +def main() -> None: + """Start the Basic editor without license checks or Professional data access.""" + + apply_launch_edition_for_entry(BASIC_EDITOR_ENTRY) + configure_windows_app_id(BASIC_EDITOR_APP_ID) + app = QApplication(sys.argv) + app.setApplicationName(BASIC_APP_DISPLAY_NAME) + icon = apply_application_icon(app, PROJECT_ROOT) + + try: + ensure_app_directories() + except AppPathError as exc: + QMessageBox.critical(None, "LaunchFlow Basic 无法启动", str(exc)) + return + + logger = get_app_logger() + if icon.isNull(): + logger.warning( + "LaunchFlow Basic icon unavailable at startup: %s", + resolve_app_icon_path(PROJECT_ROOT), + ) + + window = MainWindow(PROJECT_ROOT) + window.show() + sys.exit(app.exec()) + + +if __name__ == "__main__": + main() diff --git a/editor/services/plan_service.py b/editor/services/plan_service.py index 36e6c63..4e47fa4 100644 --- a/editor/services/plan_service.py +++ b/editor/services/plan_service.py @@ -34,7 +34,8 @@ WaitStep, plan_from_dict, ) -from shared.edition_policy import enforce_basic_policy_on_ingress +from editor.edition_ui import filter_templates_for_current_edition +from shared.edition_policy import enforce_basic_policy_on_ingress, is_basic_edition_active from shared.utils import ( read_json, write_json, @@ -125,11 +126,12 @@ def _ensure_default_templates(self) -> None: """ 确保模板文件存在。 - 若模板文件不存在,则写入一份默认模板集合, - 以保证首次启动时即可创建网页、命令和等待步骤。 + 若模板文件不存在,则写入当前版本可用的默认模板。 + Professional 仍包含网页、命令和等待模板;Basic 只写入兼容模板, + 避免把 Command / Wait 写入 LaunchFlow-Basic 数据目录。 """ if not self.templates_path.exists(): - write_json(self.templates_path, DEFAULT_TEMPLATES) + write_json(self.templates_path, filter_templates_for_current_edition(DEFAULT_TEMPLATES)) def _ensure_default_settings(self) -> None: """ @@ -160,11 +162,14 @@ def load_templates(self) -> List[Dict[str, Any]]: - 模板字典列表。 边界行为: - - 若模板文件不存在,则直接返回内置默认模板。 + - 若模板文件不存在,则直接返回当前版本可用的内置默认模板。 + - Basic 会过滤掉 Command / Wait 模板,即使数据文件里仍有这些条目。 """ if not self.templates_path.exists(): - return DEFAULT_TEMPLATES - return read_json(self.templates_path) + templates = DEFAULT_TEMPLATES + else: + templates = read_json(self.templates_path) + return filter_templates_for_current_edition(templates) def load_settings(self) -> Dict[str, Any]: """ @@ -272,6 +277,15 @@ def create_step_from_template(self, template: Dict[str, Any]): else: raise ValueError(f"不支持的模板类型: {step_type}") + # A blank URL is a legitimate in-editor draft. Completeness is still + # enforced when the plan is loaded, trial-run, or exported. + if ( + is_basic_edition_active() + and isinstance(step, UrlStep) + and not str(step.url or "").strip() + ): + step.delay_after = 1.0 + return step enforce_basic_policy_on_ingress(Plan(plan_name="template-step", steps=[step])) return step diff --git a/editor/ui/main_window.py b/editor/ui/main_window.py index 5036155..1ce2165 100644 --- a/editor/ui/main_window.py +++ b/editor/ui/main_window.py @@ -113,6 +113,17 @@ from shared.app_icon import apply_window_icon, load_app_icon from shared.diagnostics import collect_diagnostics, open_logs_directory from shared.platform.shortcuts import get_shortcut_policy +from editor.edition_ui import ( + application_file_dialog_filter, + application_path_placeholder, + brand_title, + empty_steps_hint, + log_hint_text, + shows_professional_editor_controls, + trial_run_confirm_message, + visible_editor_step_types, + workbench_title, +) from editor.services.plan_service import PlanService from editor.ui.log_console import LogConsole, LogKind, infer_log_kind from tools.build_single_exe import PACKABLE_APP_SUFFIXES, build_single_file_exe @@ -1938,11 +1949,11 @@ def _build_ui(self) -> None: text_col.setContentsMargins(0, 0, 0, 0) text_col.setSpacing(0) - brand_title = self._make_label("Launch Flow", "brand_title") + self.brand_title_label = self._make_label(brand_title(), "brand_title") brand_subtitle = self._make_label("快捷封装工作台", "brand_subtitle") text_col.addStretch() - text_col.addWidget(brand_title) + text_col.addWidget(self.brand_title_label) text_col.addWidget(brand_subtitle) text_col.addStretch() @@ -2158,7 +2169,7 @@ def _build_ui(self) -> None: log_main_layout.addWidget(self.log_header) self.log_hint = self._make_label( - "后台 Command 的标准输出、错误和退出码集中显示在这里。", + log_hint_text(), "panel_hint", ) log_main_layout.addWidget(self.log_hint) @@ -2215,6 +2226,32 @@ def _build_ui(self) -> None: right_layout.addWidget(self.main_splitter) content_layout.addWidget(right_container, 1) + self._apply_edition_presentation() + + def _set_form_row_visible(self, form: QFormLayout, field, visible: bool) -> None: + """Show or hide a form row without rebuilding the Professional layout.""" + + label = form.labelForField(field) + if label is not None: + label.setVisible(visible) + field.setVisible(visible) + + def _apply_edition_presentation(self) -> None: + """Trim Professional-only controls in Basic; leave the current entry unchanged.""" + + professional = shows_professional_editor_controls() + self.btn_add_cmd.setVisible(professional) + self.btn_add_wait.setVisible(professional) + self.btn_add_cmd.setEnabled(professional) + self.btn_add_wait.setEnabled(professional) + self._set_form_row_visible(self.app_form, self.app_args_in, professional) + self._set_form_row_visible(self.app_form, self.app_delay_in, professional) + self._set_form_row_visible(self.url_form, self.url_delay_in, professional) + self.title_bar.title_label.setText(workbench_title()) + self.brand_title_label.setText(brand_title()) + self.empty_steps_subtitle.setText(empty_steps_hint()) + self.app_path_in.setPlaceholderText(application_path_placeholder()) + self.log_hint.setText(log_hint_text()) def _build_menu_bar(self) -> QMenuBar: """Build menus whose actions share the toolbar handlers.""" @@ -2296,10 +2333,11 @@ def _build_property_editors(self) -> None: """ self.page_app = QWidget() app_form = QFormLayout(self.page_app) + self.app_form = app_form self.app_name_in = QLineEdit() self.app_path_in = QLineEdit() self.app_args_in = QTextEdit() - self.app_path_in.setPlaceholderText("选择或粘贴 .exe / .bat / .cmd / .ps1 路径") + self.app_path_in.setPlaceholderText(application_path_placeholder()) self.app_args_in.setPlaceholderText("可选:按空格分隔启动参数") self.app_args_in.setMaximumHeight(82) self.app_delay_in = ThemedDoubleSpinBox() @@ -2312,6 +2350,7 @@ def _build_property_editors(self) -> None: self.page_url = QWidget() url_form = QFormLayout(self.page_url) + self.url_form = url_form self.url_name_in = QLineEdit() self.url_in = QLineEdit() self.url_delay_in = ThemedDoubleSpinBox() @@ -2351,7 +2390,8 @@ def _build_property_editors(self) -> None: no_steps_layout.addStretch() title1 = self._make_label("当前方案还没有步骤", "empty_title") - sub1 = self._make_label("请先在左侧点击“+ 应用 / + 网页 / + 命令 / + 等待”来添加步骤。", "empty_subtitle") + sub1 = self._make_label(empty_steps_hint(), "empty_subtitle") + self.empty_steps_subtitle = sub1 title1.setAlignment(Qt.AlignmentFlag.AlignCenter) sub1.setAlignment(Qt.AlignmentFlag.AlignCenter) sub1.setWordWrap(True) @@ -3362,12 +3402,19 @@ def commit_current_step_editor(self) -> StepCommitResult: if isinstance(step, AppStep): step.name = self.app_name_in.text().strip() step.path = self.app_path_in.text().strip() - step.args = self.app_args_in.toPlainText().split() - step.delay_after = self.app_delay_in.value() + if shows_professional_editor_controls(): + step.args = self.app_args_in.toPlainText().split() + step.delay_after = self.app_delay_in.value() + else: + step.args = [] + step.delay_after = 1.0 elif isinstance(step, UrlStep): step.name = self.url_name_in.text().strip() step.url = self.url_in.text().strip() - step.delay_after = self.url_delay_in.value() + if shows_professional_editor_controls(): + step.delay_after = self.url_delay_in.value() + else: + step.delay_after = 1.0 elif isinstance(step, CommandStep): step.name = self.cmd_name_in.text().strip() # Preserve the command exactly. Whitespace is only stripped by preflight checks. @@ -3418,14 +3465,15 @@ def _on_add_app_step(self) -> None: 通过文件选择框添加一个应用步骤。 说明: - - 当前支持 exe / bat / cmd / ps1 / lnk 等常见启动入口; + - Professional 支持 exe / bat / cmd / ps1 / lnk 等常见启动入口; + - Basic 只提供本地 .exe / .lnk 选择; - 选择成功后会立即将步骤加入当前方案并刷新界面。 """ file_path, _ = QFileDialog.getOpenFileName( self, "选择应用程序", "", - "Applications (*.exe *.bat *.cmd *.ps1 *.lnk)" + application_file_dialog_filter(), ) if not file_path: return @@ -3460,6 +3508,9 @@ def _on_add_template_step(self, step_type: str) -> None: template = fresh_templates.get(step_type) if template is None: raise ValueError(f"不支持的步骤类型: {step_type}") + if step_type not in visible_editor_step_types(): + self._error("无法新增步骤", "当前版本不支持该步骤类型。") + return if not self._commit_before_editor_boundary("无法新增步骤"): return @@ -3780,7 +3831,7 @@ def _on_trial_run(self) -> None: if not self._confirm( "确认试运行", - "试运行会真实打开应用、网址和命令窗口。\n确定继续吗?", + trial_run_confirm_message(), "开始试运行", ): return diff --git a/shared/app_paths.py b/shared/app_paths.py index bb51536..17416fa 100644 --- a/shared/app_paths.py +++ b/shared/app_paths.py @@ -13,6 +13,7 @@ APP_DATA_ENV = _DATA_DIR_OVERRIDE_ENV APP_DIR_NAME = "LaunchFlow" +BASIC_APP_DIR_NAME = "LaunchFlow-Basic" APP_SUBDIRECTORIES = ("config", "data", "licenses", "logs", "plans", "cache", "temp") @@ -20,18 +21,59 @@ class AppPathError(RuntimeError): """Raised when LaunchFlow cannot resolve or create its user data path.""" +def get_active_app_dir_name() -> str: + """Return the edition-specific mutable data directory name.""" + + from shared.edition_policy import is_basic_edition_active + + if is_basic_edition_active(): + return BASIC_APP_DIR_NAME + return APP_DIR_NAME + + +def _normalized_path(path: Path) -> str: + return os.path.normcase(os.path.abspath(str(path))) + + +def _professional_default_roots(provider) -> tuple[Path, ...]: + return ( + provider.default_app_root(APP_DIR_NAME, False), + provider.default_app_root(APP_DIR_NAME, True), + ) + + +def _is_professional_data_root(path: Path, provider) -> bool: + target = _normalized_path(path) + return any(target == _normalized_path(root) for root in _professional_default_roots(provider)) + + def get_app_data_dir() -> Path: - """Return the user-writable LaunchFlow root without using cwd or the EXE directory.""" + """Return the user-writable LaunchFlow root without using cwd or the EXE directory. + + The current Professional path keeps %LOCALAPPDATA%\\LaunchFlow. An active + Basic edition context uses %LOCALAPPDATA%\\LaunchFlow-Basic and fails + closed instead of falling back to the Professional directory. + """ provider = _get_platform_path_provider(environment=os.environ) + override = os.environ.get(APP_DATA_ENV, "") try: - return provider.resolve_app_root( - APP_DIR_NAME, + root = provider.resolve_app_root( + get_active_app_dir_name(), False, - os.environ.get(APP_DATA_ENV, ""), + override, ) except ValueError as exc: raise AppPathError(str(exc)) from exc + from shared.edition_policy import is_basic_edition_active + + if is_basic_edition_active() and _is_professional_data_root(root, provider): + raise AppPathError( + "Basic edition refused to use the Professional data directory " + f"{root}" + ) + return root + def get_config_dir() -> Path: return get_app_data_dir() / "config" diff --git a/shared/data_migration.py b/shared/data_migration.py index b317b0c..9a9b995 100644 --- a/shared/data_migration.py +++ b/shared/data_migration.py @@ -86,7 +86,17 @@ def migrate_legacy_data( legacy_roots: Iterable[Path] | None = None, write_marker: bool = True, ) -> MigrationResult: - """Copy known legacy user files into AppData without deleting or overwriting.""" + """Copy known legacy user files into AppData without deleting or overwriting. + + Basic edition must not probe, read, or migrate Professional or other + legacy LaunchFlow data. The Basic path fails closed by skipping + migration entirely. + """ + from shared.edition_policy import is_basic_edition_active + + if is_basic_edition_active(): + return MigrationResult(skipped=["basic-edition:legacy-migration-disabled"]) + ensure_app_directories() marker_path = get_config_dir() / MIGRATION_MARKER if write_marker and marker_path.exists(): diff --git a/tools/basic_embedded_runner.py b/tools/basic_embedded_runner.py new file mode 100644 index 0000000..53d1a31 --- /dev/null +++ b/tools/basic_embedded_runner.py @@ -0,0 +1,305 @@ +"""Restricted Basic standalone-runner template. + +This module holds only the Basic export capability set. The Professional +EMBEDDED_TEMPLATE in tools/build_single_exe.py must remain unchanged. +Shared packaging (temporary directories, asset staging, PyInstaller +invocation) stays in the exporter; this template must not expose +Command, Wait, script-app, or unvalidated shortcut shell-open handlers. +""" + +from __future__ import annotations + + +BASIC_EMBEDDED_TEMPLATE = r''' +from __future__ import annotations + +import ctypes +import os +import sys +import time +import traceback +import subprocess +from pathlib import Path +from datetime import datetime +from urllib.parse import urlparse + + +EMBEDDED_PLAN = __PLAN_DATA__ +APPLICATION_LAUNCH_SCHEMA = 1 +URL_OPEN_SCHEMA = 1 +APPLICATION_ASSET_PREFIX = "__LAUNCHFLOW_ASSET__/" +APPLICATION_ASSET_DIR = "__LAUNCHFLOW_ASSET_DIR__" +BASIC_DATA_DIR_NAME = "LaunchFlow-Basic" +PROFESSIONAL_DATA_DIR_NAMES = {"LaunchFlow", "LaunchFlow-Dev"} +BASIC_ALLOWED_STEP_TYPES = {"app", "url"} +BASIC_ALLOWED_URL_SCHEMES = {"http", "https"} + + +def get_base_dir() -> Path: + if getattr(sys, "frozen", False): + return Path(sys.executable).resolve().parent + return Path(__file__).resolve().parent + + +def get_asset_base_dir() -> Path: + if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"): + return Path(sys._MEIPASS) + return get_base_dir() + + +def ensure_dir(path: Path) -> None: + path.mkdir(parents=True, exist_ok=True) + + +def _is_professional_data_root(path: Path) -> bool: + return path.name in PROFESSIONAL_DATA_DIR_NAMES + + +def default_basic_data_dir() -> Path: + local_app_data = os.environ.get("LOCALAPPDATA", "").strip() + if local_app_data: + return Path(local_app_data) / BASIC_DATA_DIR_NAME + return Path.home() / "AppData" / "Local" / BASIC_DATA_DIR_NAME + + +def resolve_basic_data_dir() -> Path: + override = os.environ.get("LAUNCHFLOW_DATA_DIR", "").strip() + if override: + candidate = Path(os.path.expandvars(override)).expanduser() + if candidate.is_absolute() and not _is_professional_data_root(candidate): + return candidate + return default_basic_data_dir() + + +def get_logs_dir() -> Path: + app_data_dir = resolve_basic_data_dir() + launcher_name = Path(sys.executable).stem if getattr(sys, "frozen", False) else "source-launcher" + logs_dir = app_data_dir / "logs" / "launchers" / launcher_name + ensure_dir(logs_dir) + return logs_dir + + +def get_log_path(): + try: + logs_dir = get_logs_dir() + old_logs = sorted(logs_dir.glob("runtime_*.log"), key=lambda item: item.stat().st_mtime, reverse=True) + for stale_log in old_logs[20:]: + try: + stale_log.unlink() + except OSError: + pass + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + return logs_dir / f"runtime_{ts}.log" + except OSError: + return None + + +LOG_PATH = get_log_path() + + +def log(message: str) -> None: + line = f"[{datetime.now().strftime('%H:%M:%S')}] {message}" + if LOG_PATH is None: + return + try: + with LOG_PATH.open("a", encoding="utf-8") as f: + f.write(line + "\\n") + except OSError: + pass + + +def show_info(title: str, message: str) -> None: + if os.name == "nt": + try: + ctypes.windll.user32.MessageBoxW(None, message, title, 0x40) + except (AttributeError, OSError): + pass + + +def show_error(title: str, message: str) -> None: + if os.name == "nt": + try: + ctypes.windll.user32.MessageBoxW(None, message, title, 0x10) + except (AttributeError, OSError): + pass + + +def resolve_application_value(value): + if value == APPLICATION_ASSET_DIR: + return str(get_asset_base_dir() / "launchflow_assets") + if isinstance(value, str) and value.startswith(APPLICATION_ASSET_PREFIX): + relative_path = value[len(APPLICATION_ASSET_PREFIX):] + return str(get_asset_base_dir() / Path(relative_path)) + return value + + +def application_process_options(launch: dict) -> dict: + options = {} + if launch.get("use_stdin_devnull", False): + options["stdin"] = subprocess.DEVNULL + if launch.get("use_stdout_devnull", False): + options["stdout"] = subprocess.DEVNULL + if launch.get("use_stderr_devnull", False): + options["stderr"] = subprocess.DEVNULL + creationflags = int(launch.get("creationflags", 0)) + if creationflags: + options["creationflags"] = creationflags + if launch.get("use_startupinfo", False): + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags = int(launch.get("startupinfo_dw_flags", 0)) + startupinfo.wShowWindow = int(launch.get("startupinfo_show_window", 0)) + options["startupinfo"] = startupinfo + return options + + +def run_app_step(step: dict) -> None: + launch = step.get("_application_launch") + if not isinstance(launch, dict) or launch.get("schema") != APPLICATION_LAUNCH_SCHEMA: + raise ValueError("应用启动合同缺失或版本不受支持") + + path = str(resolve_application_value(launch.get("resolved_target", ""))) + embedded_asset = str(step.get("_embedded_asset", "")).strip() + launch_mode = str(launch.get("launch_mode", "")) + target_kind = str(launch.get("target_kind", "")) + + if launch_mode != "process": + raise ValueError("Basic 运行器拒绝未经验证的应用启动方式") + if target_kind and target_kind != "executable": + raise ValueError("Basic 运行器只允许启动本地可执行文件") + if not path.lower().endswith(".exe"): + raise ValueError("Basic 运行器只允许启动 .exe 应用") + + if not path: + log("[失败] 应用路径为空") + return + + if not os.path.exists(path): + if embedded_asset: + log(f"[失败] 内置启动文件不存在: {path}") + else: + log(f"[失败] 程序路径不存在: {path}") + return + + command_args = [str(resolve_application_value(value)) for value in launch.get("command_args", [])] + if not command_args: + raise ValueError("应用启动参数无效") + working_dir = resolve_application_value(launch.get("cwd")) + subprocess.Popen( + command_args, + cwd=working_dir, + **application_process_options(launch), + ) + log(f"[成功] 已启动应用: {step.get('name', '应用')}") + + +def url_process_options(launch: dict) -> dict: + options = {} + cwd = launch.get("cwd") + if cwd is not None: + options["cwd"] = cwd + if launch.get("use_stdin_devnull", False): + options["stdin"] = subprocess.DEVNULL + if launch.get("use_stdout_devnull", False): + options["stdout"] = subprocess.DEVNULL + if launch.get("use_stderr_devnull", False): + options["stderr"] = subprocess.DEVNULL + creationflags = int(launch.get("creationflags", 0)) + if creationflags: + options["creationflags"] = creationflags + if launch.get("use_startupinfo", False): + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags = int(launch.get("startupinfo_dw_flags", 0)) + startupinfo.wShowWindow = int(launch.get("startupinfo_show_window", 0)) + options["startupinfo"] = startupinfo + return options + + +def run_url_step(step: dict) -> None: + launch = step.get("_url_open") + if not isinstance(launch, dict) or launch.get("schema") != URL_OPEN_SCHEMA: + raise ValueError("URL 打开合同缺失或版本不受支持") + + url = str(launch.get("url", "")) + if not url: + log("[失败] URL 为空") + return + + scheme = str(urlparse(url).scheme or "").strip().lower() + if scheme not in BASIC_ALLOWED_URL_SCHEMES: + raise ValueError("Basic 运行器只允许 http/https URL") + + open_mode = str(launch.get("open_mode", "")) + if open_mode != "shell_open": + raise ValueError("Basic 运行器只允许通过系统默认浏览器打开 URL") + os.startfile(url) + log(f"[成功] 已打开网页: {step.get('name', '网页')}") + + +def reject_unsupported_step(step: dict, index: int) -> None: + step_type = step.get("type") + raise ValueError(f"Basic 运行器拒绝不受支持的步骤 {index}: {step.get('name', '未命名步骤')} ({step_type})") + + +def main() -> None: + try: + plan_name = str(EMBEDDED_PLAN.get("plan_name", "未命名方案")) + steps = EMBEDDED_PLAN.get("steps", []) + + if not isinstance(steps, list): + raise ValueError("steps 不是有效列表") + + log("=" * 60) + log(f"开始执行方案: {plan_name}") + log(f"日志文件: {LOG_PATH}") + log("=" * 60) + + for index, step in enumerate(steps, start=1): + if not isinstance(step, dict): + raise ValueError(f"步骤 {index} 数据无效") + + step_type = step.get("type") + if step_type not in BASIC_ALLOWED_STEP_TYPES: + reject_unsupported_step(step, index) + + if not step.get("enabled", True): + log(f"[跳过] 步骤 {index}: {step.get('name', '未命名步骤')}(已禁用)") + continue + + log(f"[执行] 步骤 {index}: {step.get('name', '未命名步骤')} ({step_type})") + + if step_type == "app": + run_app_step(step) + elif step_type == "url": + run_url_step(step) + else: + reject_unsupported_step(step, index) + + delay_after = float(step.get("delay_after", 0)) + if delay_after > 0: + log(f"[等待] {delay_after} 秒") + time.sleep(delay_after) + + log("=" * 60) + log("方案执行完成") + log("=" * 60) + log_location = str(LOG_PATH) if LOG_PATH else "日志目录不可写,本次未保存磁盘日志" + show_info("执行完成", f"方案执行完成。\\n\\n日志位置:\\n{log_location}") + + except Exception: + tb = traceback.format_exc() + try: + log("[致命错误] 程序运行异常") + log(tb) + except Exception: + pass + + show_error( + "启动失败", + "程序运行出现异常。\\n\\n" + "请查看 LaunchFlow-Basic 用户数据目录中的启动器日志。" + ) + + +if __name__ == "__main__": + main() +''' diff --git a/tools/build_editor_release.py b/tools/build_editor_release.py index 0f2319d..733236d 100644 --- a/tools/build_editor_release.py +++ b/tools/build_editor_release.py @@ -82,9 +82,18 @@ def clean_old_build(base_dir: Path, exe_name: str) -> None: print(f"[清理] 已删除文件: {path}") -def build_editor_command(project_root: Path, exe_name: str = "LaunchFlow") -> list[str]: - """Build the authoritative PyInstaller command for the editor release.""" - entry_script = project_root / "editor" / "main.py" +def build_editor_command( + project_root: Path, + exe_name: str = "LaunchFlow", + *, + entry_script: Path | None = None, +) -> list[str]: + """Build the authoritative PyInstaller command for the editor release. + + The default remains the current Professional / single-product entry. + Basic packaging must pass the Basic entry script explicitly. + """ + entry_script = Path(entry_script) if entry_script is not None else project_root / "editor" / "main.py" icon_path = project_root / "assets" / "launchflow.ico" public_key_path = project_root / "data" / "public_key.pem" if not entry_script.exists(): @@ -125,19 +134,25 @@ def build_editor_command(project_root: Path, exe_name: str = "LaunchFlow") -> li return command -def build_editor_release(project_root: Path, exe_name: str = "LaunchFlow") -> Path: +def build_editor_release( + project_root: Path, + exe_name: str = "LaunchFlow", + *, + entry_script: Path | None = None, +) -> Path: """ 打包编辑器发布版。 参数: - project_root: 项目根目录; - exe_name: 生成的 exe 名称。 + - entry_script: 可选入口脚本;默认仍是 editor/main.py。 返回值: - 生成后的 exe 文件路径。 """ dist_dir = project_root / "dist" - command = build_editor_command(project_root, exe_name) + command = build_editor_command(project_root, exe_name, entry_script=entry_script) run_command(command, cwd=project_root) @@ -148,10 +163,32 @@ def build_editor_release(project_root: Path, exe_name: str = "LaunchFlow") -> Pa return exe_path -def ensure_runtime_data(project_root: Path) -> None: +def basic_editor_entry_script(project_root: Path) -> Path: + return project_root / "editor" / "main_basic.py" + + +def build_basic_editor_command(project_root: Path, exe_name: str = "LaunchFlow-Basic") -> list[str]: + """Build the PyInstaller command for the Basic editor entry.""" + return build_editor_command( + project_root, + exe_name, + entry_script=basic_editor_entry_script(project_root), + ) + + +def build_basic_editor_release(project_root: Path, exe_name: str = "LaunchFlow-Basic") -> Path: + """Package the Basic editor entry as a separate executable.""" + return build_editor_release( + project_root, + exe_name, + entry_script=basic_editor_entry_script(project_root), + ) + + +def ensure_runtime_data(project_root: Path, *, entry_script: Path | None = None) -> None: """Validate read-only release inputs without creating user data in source.""" required = [ - project_root / "editor" / "main.py", + entry_script or (project_root / "editor" / "main.py"), project_root / "assets" / "launchflow.ico", ] missing = [path for path in required if not path.is_file()] @@ -159,23 +196,44 @@ def ensure_runtime_data(project_root: Path) -> None: raise FileNotFoundError("发布资源缺失: " + ", ".join(str(path) for path in missing)) +def _requested_edition(argv: list[str]) -> str: + """Keep the default build on the current Professional entry.""" + + if not argv: + return "professional" + if argv == ["--edition", "basic"]: + return "basic" + if argv in (["--edition", "professional"], ["--edition", "current"]): + return "professional" + raise SystemExit("用法: python tools/build_editor_release.py [--edition professional|basic]") + + def main() -> None: """ 打包脚本主入口。 """ project_root = Path(__file__).resolve().parent.parent - exe_name = "LaunchFlow" + edition = _requested_edition(sys.argv[1:]) + if edition == "basic": + exe_name = "LaunchFlow-Basic" + entry_script = basic_editor_entry_script(project_root) + heading = "开始打包 LaunchFlow-Basic.exe" + else: + exe_name = "LaunchFlow" + entry_script = project_root / "editor" / "main.py" + heading = "开始打包 LaunchFlow.exe" print("=" * 60) - print("开始打包 LaunchFlow.exe") + print(heading) print("=" * 60) print(f"[项目目录] {project_root}") + print(f"[入口] {entry_script}") try: ensure_pyinstaller() clean_old_build(project_root, exe_name) - ensure_runtime_data(project_root) - exe_path = build_editor_release(project_root, exe_name) + ensure_runtime_data(project_root, entry_script=entry_script) + exe_path = build_editor_release(project_root, exe_name, entry_script=entry_script) print("\n" + "=" * 60) print("[成功] 打包完成") diff --git a/tools/build_single_exe.py b/tools/build_single_exe.py index 3d7cee9..3758213 100644 --- a/tools/build_single_exe.py +++ b/tools/build_single_exe.py @@ -33,14 +33,20 @@ from contextlib import contextmanager from pathlib import Path -from shared.edition_policy import enforce_basic_policy_on_ingress +from shared.edition_policy import ( + enforce_basic_policy_on_ingress, + is_basic_edition_active, + resolve_basic_policy_dependencies, +) from shared.platform.applications import get_application_launcher from shared.platform.process import get_command_backend from shared.platform.urls import get_url_opener +from tools.basic_embedded_runner import BASIC_EMBEDDED_TEMPLATE ASSET_DIR_NAME = "launchflow_assets" PACKABLE_APP_SUFFIXES = {".exe", ".bat", ".cmd", ".com", ".ps1"} +BASIC_PACKABLE_APP_SUFFIXES = {".exe"} APPLICATION_LAUNCH_SCHEMA = 1 URL_OPEN_SCHEMA = 1 APPLICATION_ASSET_PREFIX = "__LAUNCHFLOW_ASSET__/" @@ -611,6 +617,124 @@ def _prepare_embedded_plan_and_assets(plan_dict: dict) -> tuple[dict, list[tuple return embedded_plan, assets + +def _shortcut_resolution_from_resolver(path: str): + """Resolve a shortcut with the active Basic policy dependencies.""" + + dependencies = resolve_basic_policy_dependencies() + resolver = dependencies.shortcut_resolver + if resolver is None: + raise ValueError("Basic export cannot resolve a shortcut without a resolver") + if hasattr(resolver, "resolve_shortcut"): + return resolver.resolve_shortcut(path) + if callable(resolver): + return resolver(path) + raise ValueError("Basic export shortcut resolver is invalid") + + +def _resolved_basic_shortcut_target(path: str) -> str: + """Return the local EXE target of a Basic-compatible shortcut, or fail closed.""" + + resolution = _shortcut_resolution_from_resolver(path) + target = "" + arguments: tuple | list | str | None = () + working = "" + status = "resolved" + if resolution is None: + raise ValueError(f"Basic export could not resolve shortcut: {path}") + if isinstance(resolution, dict): + status = str(resolution.get("status", "resolved") or "resolved") + target = str(resolution.get("target_path", resolution.get("target", "")) or "") + arguments = resolution.get("arguments", ()) + working = str(resolution.get("working_directory", resolution.get("working_dir", "")) or "") + else: + status = str(getattr(resolution, "status", "resolved") or "resolved") + target = str(getattr(resolution, "target_path", "") or "") + arguments = getattr(resolution, "arguments", ()) + working = str(getattr(resolution, "working_directory", "") or "") + if status != "resolved" or not target.strip(): + raise ValueError(f"Basic export could not resolve shortcut: {path}") + if arguments not in (None, "", (), []): + raise ValueError(f"Basic export rejected a shortcut with arguments: {path}") + if working.strip(): + raise ValueError(f"Basic export rejected a shortcut with a working directory: {path}") + if Path(target).suffix.lower() != ".exe": + raise ValueError(f"Basic export rejected a non-EXE shortcut target: {path}") + return target + + +def _prepare_basic_embedded_plan_and_assets(plan_dict: dict) -> tuple[dict, list[tuple[Path, str]]]: + """Prepare a Basic export payload without Professional-only capabilities.""" + + embedded_plan = deepcopy(plan_dict) + assets: list[tuple[Path, str]] = [] + seen_sources: dict[Path, str] = {} + steps = embedded_plan.get("steps", []) + if not isinstance(steps, list): + raise ValueError("steps 不是有效列表") + + for index, step in enumerate(steps, start=1): + if not isinstance(step, dict): + raise ValueError(f"步骤 {index} 数据无效") + step_type = step.get("type") + if step_type == "url": + url = str(step.get("url", "")).strip() + browser_path = str(step.get("browser_path", "")).strip() + if browser_path: + raise ValueError("Basic export rejected a custom browser path") + step["_url_open"] = _serialized_url_open(url, browser_path) + continue + if step_type != "app": + raise ValueError(f"Basic export rejected unsupported step type: {step_type}") + + raw_path = str(step.get("path", "")).strip() + source_path = Path(raw_path) + suffix = source_path.suffix.lower() + if suffix == ".lnk": + launch_path = _resolved_basic_shortcut_target(raw_path) + elif suffix in BASIC_PACKABLE_APP_SUFFIXES: + launch_path = raw_path + else: + raise ValueError(f"Basic export rejected a non-EXE application path: {raw_path}") + + launch_source = Path(launch_path) + if launch_source.suffix.lower() in BASIC_PACKABLE_APP_SUFFIXES and launch_source.is_file(): + launch_source = launch_source.resolve() + asset_name = seen_sources.get(launch_source) + if asset_name is None: + asset_name = _safe_asset_name(len(seen_sources) + 1, launch_source) + seen_sources[launch_source] = asset_name + assets.append((launch_source, asset_name)) + embedded_asset = f"{ASSET_DIR_NAME}/{asset_name}" + step["_embedded_asset"] = embedded_asset + launch_path = f"{APPLICATION_ASSET_PREFIX}{embedded_asset}" + + step["_application_launch"] = _serialized_application_launch( + launch_path, + [], + "", + False, + ) + launch = step["_application_launch"] + if launch.get("launch_mode") != "process": + raise ValueError("Basic export refused to embed an unvalidated application launch") + if str(launch.get("target_kind", "executable") or "executable") not in {"", "executable"}: + raise ValueError("Basic export refused to embed a non-executable application launch") + + return embedded_plan, assets + + +def _select_embedded_export_material(plan_dict: dict) -> tuple[str, dict, list[tuple[Path, str]]]: + """Choose the edition-specific runner template and prepared plan.""" + + if is_basic_edition_active(): + embedded_plan, assets = _prepare_basic_embedded_plan_and_assets(plan_dict) + return BASIC_EMBEDDED_TEMPLATE, embedded_plan, assets + embedded_plan, assets = _prepare_embedded_plan_and_assets(plan_dict) + return EMBEDDED_TEMPLATE, embedded_plan, assets + + + def _get_pyinstaller_command() -> list[str]: """ 获取可用的 PyInstaller 调用命令。 @@ -664,6 +788,7 @@ def build_single_file_exe(plan_dict: dict, output_exe_path: Path) -> Path: 5. 将生成结果复制到目标路径。 """ enforce_basic_policy_on_ingress(plan_dict) + template, embedded_plan, assets = _select_embedded_export_material(plan_dict) output_exe_path.parent.mkdir(parents=True, exist_ok=True) @@ -673,7 +798,6 @@ def build_single_file_exe(plan_dict: dict, output_exe_path: Path) -> Path: script_path = tmp_dir / "embedded_launcher.py" staged_assets_dir = tmp_dir / ASSET_DIR_NAME - embedded_plan, assets = _prepare_embedded_plan_and_assets(plan_dict) if assets: staged_assets_dir.mkdir(parents=True, exist_ok=True) for source_path, asset_name in assets: @@ -681,7 +805,7 @@ def build_single_file_exe(plan_dict: dict, output_exe_path: Path) -> Path: # 这里使用 repr 而不是 json.dumps, # 是为了直接生成可嵌入 Python 源码的字典字面量,避免字符串转义层级更复杂。 - script_content = EMBEDDED_TEMPLATE.replace( + script_content = template.replace( "__PLAN_DATA__", repr(embedded_plan), ) diff --git a/tools/check_dual_edition_contract_smoke.py b/tools/check_dual_edition_contract_smoke.py index e9521f0..d53b916 100644 --- a/tools/check_dual_edition_contract_smoke.py +++ b/tools/check_dual_edition_contract_smoke.py @@ -337,9 +337,11 @@ def check_current_architecture_boundaries() -> None: require('launch_mode == "shell_open"' in runtime_source, "runtime shortcut shell-open path missing") require('".lnk": "shortcut"' in apps_source, "application backend no longer classifies LNK shortcuts") require('APP_DIR_NAME = "LaunchFlow"' in paths_source, "Professional data directory name changed") - require(BASIC_DATA_DIR_NAME not in paths_source, "Basic data directory unexpectedly already implemented in app_paths") + require('BASIC_APP_DIR_NAME = "LaunchFlow-Basic"' in paths_source, "Basic data directory is missing from app_paths") + require("is_basic_edition_active" in paths_source, "Basic data directory is not edition-gated") require("LOCALAPPDATA" in platform_paths, "Windows LOCALAPPDATA path contract missing") require("license.lic" in migration_source, "legacy migration still copies license.lic") + require("basic-edition:legacy-migration-disabled" in migration_source, "Basic migration fail-closed skip is missing") require("get_plans_dir" in plan_service and "get_license_dir" not in plan_service, "PlanService path boundaries changed unexpectedly") # Runtime import is allowed, but executing a plan is not part of Phase 0. diff --git a/tools/check_dual_edition_phase2_smoke.py b/tools/check_dual_edition_phase2_smoke.py new file mode 100644 index 0000000..8eb1155 --- /dev/null +++ b/tools/check_dual_edition_phase2_smoke.py @@ -0,0 +1,643 @@ +"""Verify Phase 2 launch entries, Basic data isolation, restricted runner, and UI trim. + +This smoke is side-effect free with respect to real AppData, licenses, HWID, +and PyInstaller. It uses isolated temporary directories, source inspection, +and an offscreen Qt workbench when checking editor presentation. + +Usage: + python tools/check_dual_edition_phase2_smoke.py +""" + +from __future__ import annotations + +import ast +import hashlib +import inspect +import json +import os +import shutil +import sys +import tempfile +import uuid +from pathlib import Path +from unittest.mock import patch + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from editor.launch import ( + BASIC_APP_DIR_NAME, + BASIC_EDITOR_APP_ID, + BASIC_EDITOR_ENTRY, + CURRENT_PRODUCT_ENTRY, + apply_basic_launch_edition, + apply_current_product_launch_edition, + apply_launch_edition_for_entry, + edition_for_launch_entry, +) +from shared.app_paths import ( + APP_DATA_ENV, + APP_DIR_NAME, + APP_SUBDIRECTORIES, + AppPathError, + ensure_app_directories, + get_active_app_dir_name, + get_app_data_dir, +) +from shared.data_migration import migrate_legacy_data +from shared.edition_policy import ( + BASIC_EDITION, + BasicPolicyViolation, + EditionContext, + get_edition_context, + is_basic_edition_active, + set_process_edition_context, +) +from tools import build_single_exe +from tools.basic_embedded_runner import BASIC_EMBEDDED_TEMPLATE +from tools.build_editor_release import ( + build_basic_editor_command, + build_editor_command, +) +from tools.dual_edition_phase0_contract import ( + BASIC_DATA_DIR_NAME, + basic_runner_source_violations, + data_directory_names, + professional_runner_source_missing, +) + + +FROZEN_PROFESSIONAL_TEMPLATE_SHA256 = ( + "3ba5e0ea8727b8b88644d072cf746602f8d25a93861a1d29e17e165d0c047e35" +) + +BASIC_COMPATIBLE_PLAN = { + "plan_name": "basic-phase2", + "version": "1.0", + "steps": [ + { + "id": "app-1", + "type": "app", + "name": "本地应用", + "enabled": True, + "delay_after": 1.0, + "path": r"C:\Windows\System32\notepad.exe", + "args": [], + "working_dir": "", + "start_minimized": False, + }, + { + "id": "url-1", + "type": "url", + "name": "网页", + "enabled": True, + "delay_after": 1.0, + "url": "https://example.com", + "browser_path": "", + }, + ], +} + +COMMAND_PLAN = { + "plan_name": "professional-command", + "version": "1.0", + "steps": [ + { + "id": "cmd-1", + "type": "command", + "name": "命令", + "enabled": True, + "delay_after": 1.0, + "command": "echo hello", + "shell": "cmd", + "working_dir": "", + "new_window": False, + } + ], +} + + +def require(condition: bool, message: str) -> None: + if not condition: + raise AssertionError(message) + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def check_launch_entries() -> None: + require(edition_for_launch_entry(CURRENT_PRODUCT_ENTRY) is None, "current entry must stay unset/Professional") + require(edition_for_launch_entry("editor/main.py") is None, "editor/main.py must stay Professional") + require(edition_for_launch_entry(BASIC_EDITOR_ENTRY) == BASIC_EDITION, "basic entry must map to basic") + require(edition_for_launch_entry("editor/main_basic.py") == BASIC_EDITION, "main_basic path must map to basic") + + previous = set_process_edition_context(EditionContext(edition=BASIC_EDITION)) + try: + context = apply_current_product_launch_edition() + require(context.edition is None, "current product entry must reset to the unset Professional path") + require(not is_basic_edition_active(), "current product entry must not leave Basic active") + require(get_active_app_dir_name() == APP_DIR_NAME, "Professional path must keep LaunchFlow") + + basic = apply_launch_edition_for_entry(BASIC_EDITOR_ENTRY) + require(basic.edition == BASIC_EDITION, "Basic entry did not set process context") + require(is_basic_edition_active(), "Basic entry must activate Basic context") + require(get_active_app_dir_name() == BASIC_APP_DIR_NAME, "Basic entry must select LaunchFlow-Basic") + + current = apply_launch_edition_for_entry(CURRENT_PRODUCT_ENTRY) + require(current.edition is None, "re-applying the current entry must leave Basic") + require(not is_basic_edition_active(), "Professional relaunch must not stay on Basic") + finally: + set_process_edition_context(previous) + + main_source = (PROJECT_ROOT / "editor" / "main.py").read_text(encoding="utf-8") + basic_source = (PROJECT_ROOT / "editor" / "main_basic.py").read_text(encoding="utf-8") + require("apply_launch_edition_for_entry(CURRENT_PRODUCT_ENTRY)" in main_source, "Professional entry is not wired") + require("apply_launch_edition_for_entry(BASIC_EDITOR_ENTRY)" in basic_source, "Basic entry is not wired") + require("LicenseManager" in main_source and "migrate_legacy_data" in main_source, "Professional startup contract changed") + require("ActivationWindow" in main_source, "Professional activation path changed") + require("LicenseManager" not in basic_source, "Basic entry imported LicenseManager") + require("ActivationWindow" not in basic_source, "Basic entry opened an activation window") + require("migrate_legacy_data" not in basic_source, "Basic entry still calls legacy migration") + require("validate_current_license" not in basic_source, "Basic entry probes licenses") + require("get_machine_id" not in basic_source, "Basic entry probes hardware identity") + require("configure_windows_app_id(BASIC_EDITOR_APP_ID)" in basic_source, "Basic entry is missing a distinct Windows identity") + launch_source = (PROJECT_ROOT / "editor" / "launch.py").read_text(encoding="utf-8") + require(BASIC_EDITOR_APP_ID in launch_source, "Basic Windows identity constant is missing") + + main_tree = ast.parse(main_source) + main_fn = next(node for node in main_tree.body if isinstance(node, ast.FunctionDef) and node.name == "main") + basic_tree = ast.parse(basic_source) + basic_fn = next(node for node in basic_tree.body if isinstance(node, ast.FunctionDef) and node.name == "main") + + def _named_call_lines(function: ast.FunctionDef, name: str) -> list[int]: + lines = [] + for node in ast.walk(function): + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name: + lines.append(node.lineno) + return lines + + require(_named_call_lines(main_fn, "configure_windows_app_id")[0] < _named_call_lines(main_fn, "QApplication")[0], "Professional App ID order changed") + require(_named_call_lines(basic_fn, "configure_windows_app_id")[0] < _named_call_lines(basic_fn, "QApplication")[0], "Basic App ID order changed") + apply_line = min( + node.lineno + for node in ast.walk(basic_fn) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "apply_launch_edition_for_entry" + ) + ensure_line = min( + node.lineno + for node in ast.walk(basic_fn) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "ensure_app_directories" + ) + require(apply_line < ensure_line, "Basic edition context must be set before data directories") + + +def check_data_directory_isolation() -> None: + names = data_directory_names() + require(names["basic"] == BASIC_DATA_DIR_NAME == BASIC_APP_DIR_NAME == "LaunchFlow-Basic", "Basic data dir name drifted") + require(names["professional"] == APP_DIR_NAME == "LaunchFlow", "Professional data dir name drifted") + require(names["basic_dev"] == "LaunchFlow-Basic-Dev", "Basic dev dir name drifted") + + temp_root = Path(tempfile.gettempdir()) / f"launchflow-phase2-paths-{os.getpid()}-{uuid.uuid4().hex}" + local_app_data = temp_root / "Local AppData" + professional_root = local_app_data / "LaunchFlow" + professional_dev = local_app_data / "LaunchFlow-Dev" + basic_root = local_app_data / "LaunchFlow-Basic" + isolated = temp_root / "isolated-basic" + professional_root.mkdir(parents=True) + _write(professional_root / "licenses" / "license.lic", '{"kind":"must-not-read"}') + _write(professional_root / "plans" / "pro.json", '{"plan_name":"pro","steps":[]}') + professional_stamp = (professional_root / "licenses" / "license.lic").read_bytes() + old_override = os.environ.get(APP_DATA_ENV) + old_local = os.environ.get("LOCALAPPDATA") + previous = set_process_edition_context(EditionContext()) + try: + os.environ["LOCALAPPDATA"] = str(local_app_data) + os.environ.pop(APP_DATA_ENV, None) + + apply_current_product_launch_edition() + require(get_app_data_dir() == professional_root, "Professional default data root changed") + require(not basic_root.exists(), "Professional path created LaunchFlow-Basic") + + apply_basic_launch_edition() + require(get_app_data_dir() == basic_root, "Basic default data root is wrong") + require(not basic_root.exists(), "path calculation created LaunchFlow-Basic") + created = ensure_app_directories() + require(created["root"] == basic_root, "Basic ensure_app_directories used the wrong root") + require(all((basic_root / name).is_dir() for name in APP_SUBDIRECTORIES), "Basic subdirectories missing") + require( + (professional_root / "licenses" / "license.lic").read_bytes() == professional_stamp, + "Basic directory creation touched Professional license data", + ) + require( + list((professional_root / "plans").iterdir())[0].name == "pro.json", + "Basic directory creation touched Professional plans", + ) + + os.environ[APP_DATA_ENV] = str(professional_root) + try: + get_app_data_dir() + except AppPathError as exc: + require("Professional data directory" in str(exc), f"unexpected fail-closed message: {exc}") + else: + raise AssertionError("Basic accepted a Professional data-directory override") + + os.environ[APP_DATA_ENV] = str(professional_dev) + try: + get_app_data_dir() + except AppPathError: + pass + else: + raise AssertionError("Basic accepted a LaunchFlow-Dev override") + + os.environ[APP_DATA_ENV] = str(isolated) + require(get_app_data_dir() == isolated, "Basic rejected a non-Professional test override") + + os.environ.pop(APP_DATA_ENV, None) + migration = migrate_legacy_data(PROJECT_ROOT, legacy_roots=[professional_root]) + require(migration.copied == [], f"Basic migration copied files: {migration.copied}") + require( + migration.skipped == ["basic-edition:legacy-migration-disabled"], + f"Basic migration was not skipped closed: {migration}", + ) + require( + (professional_root / "licenses" / "license.lic").read_bytes() == professional_stamp, + "Basic migration read or rewrote a Professional license", + ) + require(not (basic_root / "licenses" / "license.lic").exists(), "Basic migration imported a Professional license") + require(not (isolated / "licenses" / "license.lic").exists(), "Basic migration wrote into the test override") + finally: + set_process_edition_context(previous) + if old_override is None: + os.environ.pop(APP_DATA_ENV, None) + else: + os.environ[APP_DATA_ENV] = old_override + if old_local is None: + os.environ.pop("LOCALAPPDATA", None) + else: + os.environ["LOCALAPPDATA"] = old_local + shutil.rmtree(temp_root, ignore_errors=True) + + +def check_professional_template_unchanged() -> None: + digest = hashlib.sha256(build_single_exe.EMBEDDED_TEMPLATE.encode("utf-8")).hexdigest() + require(digest == FROZEN_PROFESSIONAL_TEMPLATE_SHA256, f"EMBEDDED_TEMPLATE changed: {digest}") + require(not professional_runner_source_missing(build_single_exe.EMBEDDED_TEMPLATE), "Professional runner symbols missing") + require("run_command_step" in build_single_exe.EMBEDDED_TEMPLATE, "Professional template lost Command") + require("os.startfile(path)" in build_single_exe.EMBEDDED_TEMPLATE, "Professional template lost shortcut shell_open") + require( + "Path(local_app_data) / \"LaunchFlow\"" in build_single_exe.EMBEDDED_TEMPLATE + or 'Path(local_app_data) / "LaunchFlow"' in build_single_exe.EMBEDDED_TEMPLATE, + "Professional runner log path changed", + ) + + +def check_basic_runner_restrictions() -> None: + template = BASIC_EMBEDDED_TEMPLATE + require(template is build_single_exe.BASIC_EMBEDDED_TEMPLATE, "exporter is not using the dedicated Basic template") + violations = basic_runner_source_violations(template) + require(violations == [], f"Basic runner still contains forbidden capabilities: {violations}") + require("run_command_step" not in template and "run_wait_step" not in template, "Basic runner embeds Command/Wait handlers") + require("os.startfile(path)" not in template, "Basic runner still shell-opens shortcuts") + require("os.startfile(url)" in template, "Basic runner lost default-browser URL opening") + require("LaunchFlow-Basic" in template, "Basic runner logs are not isolated") + require('Path(local_app_data) / "LaunchFlow"' not in template, "Basic runner still hard-codes the Professional data dir") + require("powershell_script" not in template, "Basic runner still mentions script-app handling") + + +def check_export_selection_and_assets() -> None: + previous = set_process_edition_context(EditionContext()) + temp_dir = Path(tempfile.mkdtemp(prefix="launchflow-phase2-export-")) + try: + apply_current_product_launch_edition() + template, plan, assets = build_single_exe._select_embedded_export_material(COMMAND_PLAN) + require(template is build_single_exe.EMBEDDED_TEMPLATE, "Professional export did not keep EMBEDDED_TEMPLATE") + require(any(step.get("type") == "command" and "_command_launch" in step for step in plan["steps"]), "Professional export stopped serializing Command") + + pyinstaller_lookups = {"count": 0} + + def fake_pyinstaller_command() -> list[str]: + pyinstaller_lookups["count"] += 1 + raise RuntimeError("pyinstaller-probed") + + output = temp_dir / "pro" / "plan.exe" + with patch.object(build_single_exe, "_get_pyinstaller_command", side_effect=fake_pyinstaller_command): + try: + build_single_exe.build_single_file_exe(COMMAND_PLAN, output) + except RuntimeError as exc: + require("pyinstaller-probed" in str(exc), f"unexpected professional export error: {exc}") + else: + raise AssertionError("Professional export did not reach PyInstaller lookup") + require(pyinstaller_lookups["count"] == 1, "Professional export lookup count changed") + + apply_basic_launch_edition() + basic_template, basic_plan, basic_assets = build_single_exe._select_embedded_export_material(BASIC_COMPATIBLE_PLAN) + require(basic_template is BASIC_EMBEDDED_TEMPLATE, "Basic export did not use the restricted template") + require(basic_runner_source_violations(basic_template) == [], "selected Basic template is not restricted") + rendered = basic_template.replace("__PLAN_DATA__", repr(basic_plan)) + require(basic_runner_source_violations(rendered) == [], "rendered Basic debug script leaked Professional handlers") + require(all(step.get("type") in {"app", "url"} for step in basic_plan["steps"]), "Basic export retained unsupported steps") + require(all(step.get("type") != "command" for step in basic_plan["steps"]), "Basic export retained Command") + for step in basic_plan["steps"]: + if step.get("type") == "app": + require(step["_application_launch"]["launch_mode"] == "process", "Basic app launch was not process-only") + if step.get("type") == "url": + require(step["_url_open"]["open_mode"] == "shell_open", "Basic URL launch changed") + + script_suffixes = {".bat", ".cmd", ".com", ".ps1"} + script_plan = { + "plan_name": "script-app", + "version": "1.0", + "steps": [ + { + "id": "app-script", + "type": "app", + "name": "脚本", + "enabled": True, + "delay_after": 1.0, + "path": str(temp_dir / "tool.bat"), + "args": [], + "working_dir": "", + "start_minimized": False, + } + ], + } + _write(temp_dir / "tool.bat", "echo should-not-pack") + exe_source = temp_dir / "tool.exe" + exe_source.write_bytes(b"MZ-fake-exe") + exe_plan = { + "plan_name": "exe-app", + "version": "1.0", + "steps": [ + { + "id": "app-exe", + "type": "app", + "name": "本地 EXE", + "enabled": True, + "delay_after": 1.0, + "path": str(exe_source), + "args": [], + "working_dir": "", + "start_minimized": False, + } + ], + } + + rejected_script = False + try: + build_single_exe._prepare_basic_embedded_plan_and_assets(script_plan) + except ValueError: + rejected_script = True + require(rejected_script, "Basic export packed or accepted a script application") + + _, packed_assets = build_single_exe._prepare_basic_embedded_plan_and_assets(exe_plan) + require(packed_assets and packed_assets[0][0] == exe_source.resolve(), "Basic export did not pack the local EXE") + require(all(Path(source).suffix.lower() not in script_suffixes for source, _name in packed_assets), "Basic export packed a script") + + from shared.edition_policy import BasicPolicyViolation + + basic_output = temp_dir / "basic-nested" / "plan.exe" + pyinstaller_lookups["count"] = 0 + with patch.object(build_single_exe, "_get_pyinstaller_command", side_effect=fake_pyinstaller_command): + rejected = False + try: + build_single_exe.build_single_file_exe(COMMAND_PLAN, basic_output) + except BasicPolicyViolation: + rejected = True + require(rejected, "Basic export must still reject Command plans before packaging") + require(pyinstaller_lookups["count"] == 0, "Basic export looked up PyInstaller after rejecting Command") + require(not basic_output.parent.exists(), "Basic Command rejection created the output directory") + require(not list(temp_dir.glob("*_embedded_debug.py")), "Basic Command rejection wrote a debug script") + finally: + set_process_edition_context(previous) + shutil.rmtree(temp_dir, ignore_errors=True) + + + +def check_basic_template_isolation() -> None: + from editor.services.plan_service import DEFAULT_TEMPLATES, PlanService + + temp_root = Path(tempfile.gettempdir()) / f"launchflow-phase2-templates-{os.getpid()}-{uuid.uuid4().hex}" + basic_root = temp_root / "basic-data" + professional_root = temp_root / "professional-data" + old_override = os.environ.get(APP_DATA_ENV) + previous = set_process_edition_context(EditionContext()) + try: + os.environ[APP_DATA_ENV] = str(basic_root) + apply_basic_launch_edition() + basic_service = PlanService(PROJECT_ROOT) + raw = json.loads(basic_service.templates_path.read_text(encoding="utf-8")) + require(all(item.get("type") != "command" and item.get("type") != "wait" for item in raw), "Basic default templates still include Command or Wait") + require(any(item.get("type") == "url" for item in raw), "Basic default templates lost the URL template") + require(all(item.get("type") in {"url"} for item in basic_service.load_templates()), "Basic load_templates offered Professional templates") + + polluted = raw + [{"type": "command", "name": "should-not-load", "default_command": "echo", "default_shell": "cmd", "delay_after": 1.0}] + basic_service.templates_path.write_text(json.dumps(polluted, ensure_ascii=False, indent=2), encoding="utf-8") + require(all(item.get("type") != "command" for item in basic_service.load_templates()), "Basic load_templates did not filter a polluted file") + + blank_url = basic_service.create_step_from_template( + {"type": "url", "name": "新网页", "default_url": "", "delay_after": 3.0} + ) + require(blank_url.url == "", "Basic cannot create a blank URL draft") + require(blank_url.delay_after == 1.0, "Basic blank URL draft did not keep the fixed delay") + command_rejected = False + try: + basic_service.create_step_from_template( + {"type": "command", "name": "执行命令", "default_command": "echo hello", "default_shell": "cmd"} + ) + except BasicPolicyViolation: + command_rejected = True + require(command_rejected, "Basic create_step_from_template still accepts Command") + + os.environ[APP_DATA_ENV] = str(professional_root) + apply_current_product_launch_edition() + professional_service = PlanService(PROJECT_ROOT) + professional_types = {item.get("type") for item in json.loads(professional_service.templates_path.read_text(encoding="utf-8"))} + require({"url", "command", "wait"} <= professional_types, "Professional default templates changed") + require({"url", "command", "wait"} <= {item.get("type") for item in DEFAULT_TEMPLATES}, "DEFAULT_TEMPLATES lost Professional entries") + require(professional_root not in basic_root.parents and basic_root not in professional_root.parents, "template roots were not isolated") + finally: + set_process_edition_context(previous) + if old_override is None: + os.environ.pop(APP_DATA_ENV, None) + else: + os.environ[APP_DATA_ENV] = old_override + shutil.rmtree(temp_root, ignore_errors=True) + + +def check_editor_ui_trimming() -> None: + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + + from editor.edition_ui import ( + BASIC_APP_DIALOG_FILTER, + BASIC_APP_PATH_PLACEHOLDER, + BASIC_BRAND_TITLE, + BASIC_EMPTY_STEPS_HINT, + BASIC_WORKBENCH_TITLE, + PROFESSIONAL_APP_DIALOG_FILTER, + PROFESSIONAL_APP_PATH_PLACEHOLDER, + PROFESSIONAL_BRAND_TITLE, + PROFESSIONAL_EMPTY_STEPS_HINT, + PROFESSIONAL_LOG_HINT, + PROFESSIONAL_WORKBENCH_TITLE, + application_file_dialog_filter, + ) + from editor.ui.main_window import MainWindow + from shared.app_logging import reset_app_logger_for_tests + from shared.models import AppStep, CommandStep, UrlStep + + app = QApplication.instance() or QApplication([]) + temp_root = Path(tempfile.gettempdir()) / f"launchflow-phase2-ui-{os.getpid()}-{uuid.uuid4().hex}" + old_override = os.environ.get(APP_DATA_ENV) + previous = set_process_edition_context(EditionContext()) + windows: list[MainWindow] = [] + try: + os.environ[APP_DATA_ENV] = str(temp_root / "professional") + apply_current_product_launch_edition() + def add_app_and_select(window: MainWindow) -> AppStep: + step = window.plan_service.create_app_step("Notepad", r"C:\Windows\System32\notepad.exe") + window.current_plan.steps.append(step) + window.current_editor_index = None + window._refresh_flow_list() + window._select_new_step(len(window.current_plan.steps) - 1) + app.processEvents() + return step + + professional = MainWindow(PROJECT_ROOT) + windows.append(professional) + professional.show() + app.processEvents() + require(professional.btn_add_app.isVisible() and professional.btn_add_url.isVisible(), "Professional add-step buttons missing") + require(professional.btn_add_cmd.isVisible() and professional.btn_add_wait.isVisible(), "Professional Command/Wait buttons were hidden") + require(professional.btn_add_cmd.isEnabled() and professional.btn_add_wait.isEnabled(), "Professional Command/Wait buttons were disabled") + add_app_and_select(professional) + require(professional.app_args_in.isVisible(), "Professional app args field was hidden") + require(professional.app_delay_in.isVisible(), "Professional app delay field was hidden") + professional._on_add_template_step("url") + app.processEvents() + require(professional.url_delay_in.isVisible(), "Professional URL delay field was hidden") + # Keep the App inspector selected so later isolation checks can see those fields. + professional.flow_list.setCurrentRow(0) + app.processEvents() + require(professional.app_args_in.isVisible() and professional.app_delay_in.isVisible(), "Professional app inspector lost its advanced fields") + require(professional.empty_steps_subtitle.text() == PROFESSIONAL_EMPTY_STEPS_HINT, "Professional empty-state hint changed") + require(professional.title_bar.title_label.text() == PROFESSIONAL_WORKBENCH_TITLE, "Professional workbench title changed") + require(professional.brand_title_label.text() == PROFESSIONAL_BRAND_TITLE, "Professional brand title changed") + require(professional.app_path_in.placeholderText() == PROFESSIONAL_APP_PATH_PLACEHOLDER, "Professional path placeholder changed") + require(application_file_dialog_filter() == PROFESSIONAL_APP_DIALOG_FILTER, "Professional file-dialog filter changed") + require(professional.log_hint.text() == PROFESSIONAL_LOG_HINT, "Professional log hint changed") + + os.environ[APP_DATA_ENV] = str(temp_root / "basic") + apply_basic_launch_edition() + basic = MainWindow(PROJECT_ROOT) + windows.append(basic) + basic.show() + app.processEvents() + require(basic.btn_add_app.isVisible() and basic.btn_add_url.isVisible(), "Basic lost App/URL add buttons") + require(not basic.btn_add_cmd.isVisible() and not basic.btn_add_wait.isVisible(), "Basic still shows Command or Wait buttons") + require(not basic.btn_add_cmd.isEnabled() and not basic.btn_add_wait.isEnabled(), "Basic still enables Command or Wait buttons") + require(basic.empty_steps_subtitle.text() == BASIC_EMPTY_STEPS_HINT, "Basic empty-state hint is wrong") + require("命令" not in basic.empty_steps_subtitle.text() and "等待" not in basic.empty_steps_subtitle.text(), "Basic empty-state still advertises Professional steps") + require(basic.title_bar.title_label.text() == BASIC_WORKBENCH_TITLE, "Basic workbench title is wrong") + require(basic.brand_title_label.text() == BASIC_BRAND_TITLE, "Basic brand title is wrong") + require(basic.app_path_in.placeholderText() == BASIC_APP_PATH_PLACEHOLDER, "Basic path placeholder is wrong") + require(application_file_dialog_filter() == BASIC_APP_DIALOG_FILTER, "Basic file-dialog filter still includes scripts") + require("Command" not in basic.log_hint.text() and "命令" not in basic.log_hint.text(), "Basic log hint still describes Command") + + add_app_and_select(basic) + require(not basic.app_args_in.isVisible(), "Basic still shows application arguments") + require(not basic.app_delay_in.isVisible(), "Basic still shows a custom App delay control") + require(professional.btn_add_cmd.isVisible() and professional.app_args_in.isVisible(), "creating a Basic window changed the Professional UI") + + recorded: list[tuple[str, str]] = [] + basic._error = lambda title, message: recorded.append((title, message)) + before = list(basic.current_plan.steps) + basic._on_add_template_step("command") + basic._on_add_template_step("wait") + app.processEvents() + require(basic.current_plan.steps == before, "Basic UI created a Professional-only step") + require(not any(isinstance(step, CommandStep) for step in basic.current_plan.steps), "Basic UI created a Command step") + require(recorded, "Basic UI did not reject Command/Wait additions") + + # Hidden fields must not leak into the saved Basic step. + basic.current_step_dirty = True + basic.app_args_in.setPlainText("--should-not-save") + basic.app_delay_in.setValue(3.5) + result = basic.commit_current_step_editor() + require(result.success, "Basic app-step commit failed") + require(isinstance(basic.current_plan.steps[0], AppStep), "Basic app step was lost") + require(basic.current_plan.steps[0].args == [], "Basic commit saved Professional-only arguments") + require(basic.current_plan.steps[0].delay_after == 1.0, "Basic commit saved a custom App delay") + + basic._on_add_template_step("url") + app.processEvents() + require(len(basic.current_plan.steps) == 2, "Basic UI failed to add a URL step") + require(isinstance(basic.current_plan.steps[1], UrlStep), "Basic URL addition created the wrong step type") + require(basic.current_plan.steps[1].url == "", "Basic should allow a blank URL draft to be filled in later") + require(not basic.url_delay_in.isVisible(), "Basic still shows a custom URL delay control") + require(basic.current_plan.steps[1].delay_after == 1.0, "Basic URL step did not keep the fixed delay") + finally: + for window in windows: + window.close() + window.deleteLater() + app.processEvents() + reset_app_logger_for_tests() + set_process_edition_context(previous) + if old_override is None: + os.environ.pop(APP_DATA_ENV, None) + else: + os.environ[APP_DATA_ENV] = old_override + shutil.rmtree(temp_root, ignore_errors=True) + + +def check_packaging_entries() -> None: + professional = build_editor_command(PROJECT_ROOT) + require(str(PROJECT_ROOT / "editor" / "main.py") in professional, "Professional packager entry changed") + require("LaunchFlow" in professional, "Professional exe name changed") + basic = build_basic_editor_command(PROJECT_ROOT) + require(str(PROJECT_ROOT / "editor" / "main_basic.py") in basic, "Basic packager is not using main_basic.py") + require("LaunchFlow-Basic" in basic, "Basic packager exe name is wrong") + require(inspect.signature(build_editor_command).parameters["exe_name"].default == "LaunchFlow", "default editor exe name changed") + + script = (PROJECT_ROOT / "tools" / "run_editor_basic_dev.ps1").read_text(encoding="utf-8") + require("LaunchFlow-Basic-Dev" in script, "Basic dev script is not isolated") + require("editor.main_basic" in script, "Basic dev script is not using the Basic entry") + require("LaunchFlow-Dev`" not in script and 'Join-Path $localAppData "LaunchFlow-Dev"' not in script, "Basic dev script references Professional dev data") + professional_script = (PROJECT_ROOT / "tools" / "run_editor_dev.ps1").read_text(encoding="utf-8") + require("editor.main" in professional_script and "editor.main_basic" not in professional_script, "Professional dev script was retargeted") + + +def main() -> int: + previous = get_edition_context() + try: + check_launch_entries() + check_data_directory_isolation() + check_professional_template_unchanged() + check_basic_runner_restrictions() + check_export_selection_and_assets() + check_packaging_entries() + check_basic_template_isolation() + check_editor_ui_trimming() + finally: + set_process_edition_context(previous) + + print("dual edition phase 2 smoke ok") + print("launch_entries=editor.main:unset-professional,editor.main_basic:basic") + print("data_dirs=LaunchFlow,LaunchFlow-Basic,LaunchFlow-Basic-Dev") + print("professional_template=unchanged") + print("basic_runner=restricted,no-command-wait,no-script,no-lnk-shell-open") + print("packaging=LaunchFlow.exe,LaunchFlow-Basic.exe") + print("editor_ui=basic-trimmed,professional-unchanged") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_platform_coupling_baseline.json b/tools/check_platform_coupling_baseline.json index 0b591bd..1d0f5ba 100644 --- a/tools/check_platform_coupling_baseline.json +++ b/tools/check_platform_coupling_baseline.json @@ -52,16 +52,6 @@ "future_target": "DesktopIntegration", "allowed_to_remain": true }, - { - "fingerprint": "9b8c16fe6a8ce3e038ac", - "path": "editor/ui/main_window.py", - "rule_id": "WIN-ASSET-001", - "area": "artifacts", - "classification": "platform_adapter_candidate", - "reason": "Windows artifact or script suffix", - "future_target": "ApplicationLauncher or PackagingBackend", - "allowed_to_remain": true - }, { "fingerprint": "a6c5a3b4c1a905f1c7c1", "path": "editor/ui/main_window.py", @@ -92,16 +82,6 @@ "future_target": "ApplicationLauncher or PackagingBackend", "allowed_to_remain": true }, - { - "fingerprint": "793b7b4c5b2aa222ec28", - "path": "editor/ui/main_window.py", - "rule_id": "WIN-ASSET-001", - "area": "artifacts", - "classification": "platform_adapter_candidate", - "reason": "Windows artifact or script suffix", - "future_target": "ApplicationLauncher or PackagingBackend", - "allowed_to_remain": true - }, { "fingerprint": "98882f9a695abaf0ad9f", "path": "editor/ui/main_window.py", @@ -812,16 +792,6 @@ "future_target": "ApplicationLauncher or PackagingBackend", "allowed_to_remain": true }, - { - "fingerprint": "9c830d0481d886de9b47", - "path": "tools/build_editor_release.py", - "rule_id": "WIN-ASSET-001", - "area": "artifacts", - "classification": "allowed_windows_boundary", - "reason": "Windows artifact or script suffix", - "future_target": "ApplicationLauncher or PackagingBackend", - "allowed_to_remain": true - }, { "fingerprint": "f46435558acb51db574f", "path": "tools/build_single_exe.py", @@ -1091,6 +1061,206 @@ "reason": "Windows artifact or script suffix in the Phase 1b IShellLink resolver target-kind map", "future_target": "WindowsShortcutResolver", "allowed_to_remain": true + }, + { + "fingerprint": "0e345d6eb72df012eae9", + "path": "editor/edition_ui.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "platform_adapter_candidate", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "e52cde248760b1dceb74", + "path": "editor/edition_ui.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "platform_adapter_candidate", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "f688157bd23bda2094d2", + "path": "editor/edition_ui.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "platform_adapter_candidate", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "ff539f59375847b4544f", + "path": "editor/edition_ui.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "platform_adapter_candidate", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "a2e69162f22baebedcca", + "path": "tools/basic_embedded_runner.py", + "rule_id": "PACK-ONEFILE-001", + "area": "packaging", + "classification": "allowed_windows_boundary", + "reason": "PyInstaller onefile packaging contract", + "future_target": "PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "c1e78078019db20aded8", + "path": "tools/basic_embedded_runner.py", + "rule_id": "PACK-ONEFILE-001", + "area": "packaging", + "classification": "allowed_windows_boundary", + "reason": "PyInstaller onefile packaging contract", + "future_target": "PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "9e5b48cfe74b39b45fdb", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-PATH-001", + "area": "paths", + "classification": "allowed_windows_boundary", + "reason": "Windows user-data path or environment variable", + "future_target": "PlatformPaths", + "allowed_to_remain": true + }, + { + "fingerprint": "b716dd5dc771e3afbf94", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-BRANCH-001", + "area": "platform-branch", + "classification": "allowed_windows_boundary", + "reason": "Explicit Windows platform branch", + "future_target": "shared/platform/detection.py", + "allowed_to_remain": true + }, + { + "fingerprint": "abd87b6a972ab6e41bdb", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-API-001", + "area": "windows-api", + "classification": "allowed_windows_boundary", + "reason": "Windows-only API", + "future_target": "DesktopIntegration", + "allowed_to_remain": true + }, + { + "fingerprint": "abf79db3ae6e2bac0d6c", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-API-001", + "area": "windows-api", + "classification": "allowed_windows_boundary", + "reason": "Windows-only API", + "future_target": "DesktopIntegration", + "allowed_to_remain": true + }, + { + "fingerprint": "2c8e0997a8f6e52accaf", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "01831f958db375813997", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "4a9e569e4dba4f050eb8", + "path": "tools/basic_embedded_runner.py", + "rule_id": "WIN-API-001", + "area": "windows-api", + "classification": "allowed_windows_boundary", + "reason": "Windows-only API", + "future_target": "UrlOpener", + "allowed_to_remain": true + }, + { + "fingerprint": "9f74018f6c42e1a591e7", + "path": "tools/build_editor_release.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "c6fb3a1c0e5a1b4a0487", + "path": "tools/build_editor_release.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "3c46ccd6a9c2290548a1", + "path": "tools/build_single_exe.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "1ee9b3328f7ae39cac96", + "path": "tools/build_single_exe.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "10c503b787274c6364dc", + "path": "tools/build_single_exe.py", + "rule_id": "WIN-ASSET-001", + "area": "artifacts", + "classification": "allowed_windows_boundary", + "reason": "Windows artifact or script suffix", + "future_target": "ApplicationLauncher or PackagingBackend", + "allowed_to_remain": true + }, + { + "fingerprint": "1aeb890415940e3db581", + "path": "tools/run_editor_basic_dev.ps1", + "rule_id": "WIN-PATH-001", + "area": "paths", + "classification": "allowed_windows_boundary", + "reason": "Windows user-data path or environment variable", + "future_target": "PlatformPaths", + "allowed_to_remain": true + }, + { + "fingerprint": "6024d97b3f383f4e7153", + "path": "tools/run_editor_basic_dev.ps1", + "rule_id": "WIN-PATH-001", + "area": "paths", + "classification": "allowed_windows_boundary", + "reason": "Windows user-data path or environment variable", + "future_target": "PlatformPaths", + "allowed_to_remain": true } ] } diff --git a/tools/check_platform_coupling_smoke.py b/tools/check_platform_coupling_smoke.py index 99f1125..04e876d 100644 --- a/tools/check_platform_coupling_smoke.py +++ b/tools/check_platform_coupling_smoke.py @@ -29,6 +29,8 @@ "tools/build_single_exe.py", "tools/generate_app_icon.py", "tools/run_editor_dev.ps1", + "tools/run_editor_basic_dev.ps1", + "tools/basic_embedded_runner.py", ) REFERENCE_FILES = ("README.md", "README_EN.md", "CHANGELOG.md") EXCLUDED_PARTS = { diff --git a/tools/run_editor_basic_dev.ps1 b/tools/run_editor_basic_dev.ps1 new file mode 100644 index 0000000..0c8e8fa --- /dev/null +++ b/tools/run_editor_basic_dev.ps1 @@ -0,0 +1,51 @@ +[CmdletBinding()] +param( + [string]$PythonCommand = "python" +) + +$ErrorActionPreference = "Stop" +$sourceRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "..")).Path +$localAppData = $env:LOCALAPPDATA +if ([string]::IsNullOrWhiteSpace($localAppData)) { + $localAppData = [Environment]::GetFolderPath("LocalApplicationData") +} +if ([string]::IsNullOrWhiteSpace($localAppData)) { + throw "无法定位 LOCALAPPDATA,LaunchFlow Basic 开发模式未启动。" +} + +$devDataRoot = Join-Path $localAppData "LaunchFlow-Basic-Dev" +$previousDataRoot = $env:LAUNCHFLOW_DATA_DIR + +try { + $env:LAUNCHFLOW_DATA_DIR = $devDataRoot + Write-Host "LaunchFlow Basic developer data: $devDataRoot" + Write-Host "Basic 开发模式不读取 Professional 数据目录,也不要求许可证。" + + Push-Location -LiteralPath $sourceRoot + try { + & $PythonCommand -m editor.main_basic + $editorExitCode = $LASTEXITCODE + if ($null -eq $editorExitCode) { + $editorExitCode = 0 + } + } + finally { + Pop-Location + } + + if ($editorExitCode -ne 0) { + throw "LaunchFlow Basic 开发模式退出码:$editorExitCode" + } +} +catch { + Write-Error "LaunchFlow Basic 开发模式启动失败:$($_.Exception.Message)" -ErrorAction Continue + throw +} +finally { + if ($null -eq $previousDataRoot) { + Remove-Item Env:LAUNCHFLOW_DATA_DIR -ErrorAction SilentlyContinue + } + else { + $env:LAUNCHFLOW_DATA_DIR = $previousDataRoot + } +}