Skip to content

feat: 支持在自定义命令中 通过模板变量 获取当前实例所有任务的状态#215

Open
zzc-tongji wants to merge 3 commits into
MistEO:mainfrom
zzc-tongji:pr-notify
Open

feat: 支持在自定义命令中 通过模板变量 获取当前实例所有任务的状态#215
zzc-tongji wants to merge 3 commits into
MistEO:mainfrom
zzc-tongji:pr-notify

Conversation

@zzc-tongji
Copy link
Copy Markdown

@zzc-tongji zzc-tongji commented May 12, 2026

Summary by Sourcery

在运行 launch 特殊任务时,为当前实例所有已选任务的实时状态暴露模板变量,并在 launch UI 中记录其用法。

新功能:

  • 提供一个工具,用于收集给定实例中所有已勾选任务的状态及其本地化名称。
  • 将表示所选任务状态的 launch 参数模板变量(纯文本、CSV、JSON 和 Base64 变体)注入到 MXU 启动操作中。

增强项:

  • 使用 panic 保护和显式错误日志包装 MXU 启动自定义操作注册过程。
  • 更新所有受支持语言中的启动任务“additional-arguments”UI 文案,描述新的状态模板变量及其格式。
Original summary in English

Summary by Sourcery

Expose template variables with real-time statuses of all selected tasks for the current instance when running the launch special task, and document their usage in the launch UI.

New Features:

  • Provide a utility that collects the statuses and localized names of all checked tasks for a given instance.
  • Inject launch-argument template variables (plain text, CSV, JSON, and Base64 variants) representing selected task statuses into the MXU launch action.

Enhancements:

  • Wrap MXU launch custom action registration with panic handling and explicit error logging during registration.
  • Update launch task additional-arguments UI text across supported languages to describe the new status template variables and their formats.

新功能:

  • 在启动操作参数中暴露模板变量,以纯文本、CSV、JSON 和 Base64 编码形式为当前实例注入已选中任务状态。

增强:

  • 引入一个工具,用于收集给定实例中所有已选中任务的状态(支持 i18n 的任务名称),并将其集成到启动流程中。
  • 更新启动任务附加参数的本地化 UI 文案,在各个受支持语言中记录新的状态模板变量。
Original summary in English

Summary by Sourcery

在运行 launch 特殊任务时,为当前实例所有已选任务的实时状态暴露模板变量,并在 launch UI 中记录其用法。

新功能:

  • 提供一个工具,用于收集给定实例中所有已勾选任务的状态及其本地化名称。
  • 将表示所选任务状态的 launch 参数模板变量(纯文本、CSV、JSON 和 Base64 变体)注入到 MXU 启动操作中。

增强项:

  • 使用 panic 保护和显式错误日志包装 MXU 启动自定义操作注册过程。
  • 更新所有受支持语言中的启动任务“additional-arguments”UI 文案,描述新的状态模板变量及其格式。
Original summary in English

Summary by Sourcery

Expose template variables with real-time statuses of all selected tasks for the current instance when running the launch special task, and document their usage in the launch UI.

New Features:

  • Provide a utility that collects the statuses and localized names of all checked tasks for a given instance.
  • Inject launch-argument template variables (plain text, CSV, JSON, and Base64 variants) representing selected task statuses into the MXU launch action.

Enhancements:

  • Wrap MXU launch custom action registration with panic handling and explicit error logging during registration.
  • Update launch task additional-arguments UI text across supported languages to describe the new status template variables and their formats.

@zzc-tongji
Copy link
Copy Markdown
Author

zzc-tongji commented May 12, 2026

基本不改动 UI,只更新选项描述。

图片

运行日志:

[2026-05-12 18:21:11.619] 任务开始: ▶️ 自定义程序
[2026-05-12][18:21:11][INFO][mxu_lib::mxu_actions] [MXU_LAUNCH] Generated task(s) status: [["__MXU_SLEEP__","succeeded"],["__MXU_LAUNCH__","running"]]
[2026-05-12][18:21:11][INFO][mxu_lib::mxu_actions] [MXU_LAUNCH] Received param: {"args":"-c \"echo {{S_JSON_BASE64}}\"","program":"pwsh","skip_if_running":false,"use_cmd":false,"wait_for_exit":false}
[2026-05-12][18:21:11][INFO][mxu_lib::mxu_actions] [MXU_LAUNCH] Launching: program=pwsh, args=-c "echo W1siX19NWFVfU0xFRVBfXyIsInN1Y2NlZWRlZCJdLFsiX19NWFVfTEFVTkNIX18iLCJydW5uaW5nIl1d", wait_for_exit=false
[2026-05-12][18:21:11][INFO][mxu_lib::mxu_actions] [MXU_LAUNCH] Process spawned (not waiting)
[2026-05-12][18:21:11][DEBUG][mxu_lib::commands::state] maa_get_all_states called
[2026-05-12 18:21:12.037] 任务完成: ▶️ 自定义程序

相关内容 #214 MaaEnd/MaaEnd#2843

@zzc-tongji zzc-tongji changed the title update launch task with task status template variable support feat: 支持在自定义命令任务中 通过模板变量 获取当前实例所有任务的状态 May 12, 2026
@zzc-tongji zzc-tongji changed the title feat: 支持在自定义命令任务中 通过模板变量 获取当前实例所有任务的状态 feat: 支持在自定义命令中 通过模板变量 获取当前实例所有任务的状态 May 12, 2026
@zzc-tongji zzc-tongji marked this pull request as ready for review May 12, 2026 10:22
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - 我发现了 3 个问题,并给出了一些总体反馈:

  • get_checked_task_status_of_instance 中,对配置、文案、实例运行时以及 JSON 字段有很多 unwrap() 调用,如果实例 ID 或状态不一致就会导致 panic;建议改用 if let / ? 这类错误处理方式,并在出错时返回空向量或记录错误日志,而不是直接展开导致程序崩溃。
  • get_checked_task_status_of_instance 的实现会在迭代器内部反复对嵌套 JSON(instancestaskstaskName 等)进行 unwrap;可以考虑抽取辅助函数或使用提前返回(early return),让代码在缺失字段时更健壮,也更容易阅读和维护。
  • 新增的 i18n 描述中引用了一个硬编码的 GitHub 链接,其中包含 mxu_actions.rs 的具体行号,这很容易过期;最好改为指向一个稳定的文档页面,或者去掉行号锚点,以减少后续维护成本。
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `get_checked_task_status_of_instance`, there are many `unwrap()` calls on config, translations, instance runtime, and JSON fields that will panic if the instance ID or state is inconsistent; consider replacing these with `if let`/`?`-style handling and returning an empty vector or logging an error instead of unwinding.
- The `get_checked_task_status_of_instance` implementation repeatedly unwraps nested JSON (`instances`, `tasks`, `taskName`, etc.) inside the iterator; extracting helper functions or using early returns would make the code easier to follow and more robust against missing fields.
- The new i18n descriptions reference a hard-coded GitHub URL including a specific line number in `mxu_actions.rs`, which is likely to become stale; it would be safer to link to a stable documentation page or omit the line anchor to reduce future maintenance.

## Individual Comments

### Comment 1
<location path="src-tauri/src/commands/utils.rs" line_range="339-324" />
<code_context>
+
+    return instance_runtime
+        .task_run_state
+        .pending_task_ids
+        .iter()
+        .filter_map(|&maa_task_id| {
+            if let Some(selected_task_id) =
</code_context>
<issue_to_address>
**question (bug_risk):** 使用 `pending_task_ids` 看起来与“返回所有已勾选任务”的既定意图不一致。

文档注释中提到该函数会返回所有已勾选任务的状态,并且返回类型也支持非 pending 状态(idle、running 等),但当前代码只遍历了 `pending_task_ids`。

如果已勾选的任务有可能已经处于 running / succeeded / failed 等状态,这段逻辑就会遗漏它们。如果真实意图其实是“仅返回已勾选且处于 pending 状态的任务”,则应当更新文档注释以明确这一点;否则,遍历时应覆盖所有已勾选任务,而不只是 `pending_task_ids`。
</issue_to_address>

### Comment 2
<location path="src-tauri/src/commands/utils.rs" line_range="385" />
<code_context>
+                    } else {
+                        task_name
+                    };
+                    Some(vec![name, status.to_string()])
+                } else {
+                    None
</code_context>
<issue_to_address>
**suggestion:** 依赖 `Vec<String>` 中的索引位置来表示 `(name, status)` 会让下游代码非常脆弱。

当前在 `mxu_launch_action_fn` 中格式化字符串时已经默认依赖了这种索引约定。建议改为返回一个专门的结构体,或者至少使用 `Vec<(String, String)>`,这样意图更清晰,将来也更不容易因为字段或顺序变化而出错。

建议实现如下:

```rust
                    let name: String = if !custom_name.is_empty() {
                        custom_name
                    } else if !task_name_i18n.is_empty() {
                        task_name_i18n
                    } else {
                        task_name
                    };
                    Some(vec![(name, status.to_string())])

```

如果要彻底落实这个建议并消除基于位置索引的脆弱性,还需要:

1. 更新该迭代器/collect 链的返回类型:
   - 如果当前函数的返回类型是 `Option<Vec<String>>`,将其改为 `Option<Vec<(String, String)>>`- 如果这是在某个 `map`/`filter_map` 中,并最终 `collect::<Vec<_>>()`,要确保最终类型相应变为 `Vec<Option<Vec<(String, String)>>>` 或其他与上下文匹配的类型。

2. 更新所有消费此结果的调用方(尤其是你提到的 `mxu_launch_action_fn`):
   - 不要再使用数字索引(如 `value[0]`, `value[1]`),而是通过模式匹配或解构元组:
     ```rust
     for (name, status) in pair_vec {
         // 使用 `name` 和 `status`
     }
     ```
   - 调整字符串格式化逻辑,使用 `(name, status)` 而非位置访问。

3. 如果这些数据会被序列化(例如通过 Tauri 命令传到前端):
   - 可以考虑改用一个小结构体(如 `struct TaskInfo { name: String, status: String }`),并返回 `Vec<TaskInfo>` 而不是 `Vec<(String, String)>`,以获得更清晰的 JSON 结构(具名字段而不是数组索引)。
   - 相应更新任何 TypeScript 类型或前端对数据结构的预期。

你可以根据使用范围以及你对消费者(前端、其他 crate 等)的掌控程度,在 `Vec<(String, String)>`(改动较小)和独立结构体(意图更清晰)之间进行选择。
</issue_to_address>

### Comment 3
<location path="src/i18n/locales/en-US.ts" line_range="144" />
<code_context>
       argsLabel: 'Additional Arguments',
-      argsPlaceholder: 'Enter additional arguments (optional)',
+      argsPlaceholder: 'Enter additional arguments (optional, template variables supported)',
+      argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 for details.',
       waitLabel: 'Wait for Exit',
       waitDescription:
</code_context>
<issue_to_address>
**suggestion:** 在面向用户的文案中硬编码带具体行号的 GitHub 链接会非常脆弱。

这段字符串中硬编码了指向 `.../mxu_actions.rs#L207` 的链接。随着文件的修改,该行号很可能会发生变化,而要在每个本地化文案中同步更新这一行号会非常容易出错且难以维护。

建议改为不带行号锚点的文件链接、指向一个专门的 README/文档章节,或者指向一个稳定的永久链接(例如某个打过标签的版本)。其他语言的本地化文件中对应的字符串同样适用。

建议实现如下:

```typescript
      argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs for details.',

```

1. 对其他语言的本地化文件中的对应 `argsDescription` 条目(如 `zh-CN.ts``ja-JP.ts` 等)也做同样修改(移除 URL 中的 `#L207`),这样所有本地化字符串都不会依赖易变的行号锚点。
2. 如果未来新增专门的文档页面或稳定的永久链接(例如某个打标签的代码树),可以考虑在所有语言的本地化文件中,将该 URL 统一调整为那个更稳定的链接,而不是当前指向 `main` 分支源码路径的链接。
</issue_to_address>

Sourcery 对开源项目免费 —— 如果你觉得这些评论有帮助,欢迎分享 ✨
帮我变得更有用!请在每条评论上点击 👍 或 👎,我会根据你的反馈改进后续评审。
Original comment in English

Hey - I've found 3 issues, and left some high level feedback:

  • In get_checked_task_status_of_instance, there are many unwrap() calls on config, translations, instance runtime, and JSON fields that will panic if the instance ID or state is inconsistent; consider replacing these with if let/?-style handling and returning an empty vector or logging an error instead of unwinding.
  • The get_checked_task_status_of_instance implementation repeatedly unwraps nested JSON (instances, tasks, taskName, etc.) inside the iterator; extracting helper functions or using early returns would make the code easier to follow and more robust against missing fields.
  • The new i18n descriptions reference a hard-coded GitHub URL including a specific line number in mxu_actions.rs, which is likely to become stale; it would be safer to link to a stable documentation page or omit the line anchor to reduce future maintenance.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `get_checked_task_status_of_instance`, there are many `unwrap()` calls on config, translations, instance runtime, and JSON fields that will panic if the instance ID or state is inconsistent; consider replacing these with `if let`/`?`-style handling and returning an empty vector or logging an error instead of unwinding.
- The `get_checked_task_status_of_instance` implementation repeatedly unwraps nested JSON (`instances`, `tasks`, `taskName`, etc.) inside the iterator; extracting helper functions or using early returns would make the code easier to follow and more robust against missing fields.
- The new i18n descriptions reference a hard-coded GitHub URL including a specific line number in `mxu_actions.rs`, which is likely to become stale; it would be safer to link to a stable documentation page or omit the line anchor to reduce future maintenance.

## Individual Comments

### Comment 1
<location path="src-tauri/src/commands/utils.rs" line_range="339-324" />
<code_context>
+
+    return instance_runtime
+        .task_run_state
+        .pending_task_ids
+        .iter()
+        .filter_map(|&maa_task_id| {
+            if let Some(selected_task_id) =
</code_context>
<issue_to_address>
**question (bug_risk):** Using `pending_task_ids` seems to contradict the stated intent of returning all checked tasks.

The docstring says this returns statuses for all checked tasks, and the type supports non-pending states (idle, running, etc.), but the code only iterates over `pending_task_ids`.

If checked tasks can already be running/succeeded/failed, this logic will miss them. If the intent is actually “checked pending tasks only”, the docstring should be updated to say so; otherwise the iteration should cover all checked tasks, not just `pending_task_ids`.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/commands/utils.rs" line_range="385" />
<code_context>
+                    } else {
+                        task_name
+                    };
+                    Some(vec![name, status.to_string()])
+                } else {
+                    None
</code_context>
<issue_to_address>
**suggestion:** Relying on `Vec<String>` index positions for `(name, status)` makes downstream code brittle.

This is already assumed in `mxu_launch_action_fn` when formatting strings. Consider returning a dedicated struct or at least `Vec<(String, String)>` instead so the intent is clearer and future changes to fields or ordering are less error-prone.

Suggested implementation:

```rust
                    let name: String = if !custom_name.is_empty() {
                        custom_name
                    } else if !task_name_i18n.is_empty() {
                        task_name_i18n
                    } else {
                        task_name
                    };
                    Some(vec![(name, status.to_string())])

```

To fully implement the suggestion and remove brittleness from positional indexing, you should also:

1. Update the return type of this iterator/collect chain:
   - If this code is in a function that currently returns `Option<Vec<String>>`, change it to `Option<Vec<(String, String)>>`.
   - If it is inside a `map`/`filter_map` feeding into a `collect::<Vec<_>>()`, ensure the resulting type becomes `Vec<Option<Vec<(String, String)>>>` or whatever is appropriate for the surrounding context.

2. Update all callers that consume this result (notably `mxu_launch_action_fn` per your comment) to:
   - Stop using numeric indices (e.g. `value[0]`, `value[1]`) and instead pattern-match or destructure tuples:
     ```rust
     for (name, status) in pair_vec {
         // use `name` and `status`
     }
     ```
   - Adjust string formatting logic to use `(name, status)` instead of positional access.

3. If this data is serialized (e.g. via Tauri commands into the frontend):
   - Consider switching to a small struct (e.g. `struct TaskInfo { name: String, status: String }`) and returning `Vec<TaskInfo>` instead of `Vec<(String, String)>` to get clearer JSON shape (named fields instead of array indices).
   - Update any TypeScript types or frontend expectations accordingly.

You may choose between `Vec<(String, String)>` (minimal change) or a dedicated struct (clearer intent) depending on how widely this is used and whether you control the consumer side (frontend, other crates, etc.).
</issue_to_address>

### Comment 3
<location path="src/i18n/locales/en-US.ts" line_range="144" />
<code_context>
       argsLabel: 'Additional Arguments',
-      argsPlaceholder: 'Enter additional arguments (optional)',
+      argsPlaceholder: 'Enter additional arguments (optional, template variables supported)',
+      argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 for details.',
       waitLabel: 'Wait for Exit',
       waitDescription:
</code_context>
<issue_to_address>
**suggestion:** Hardcoding a GitHub link with a specific line number in user-facing text is brittle.

This string hardcodes a link to `.../mxu_actions.rs#L207`. As the file changes, that line number will likely drift, and updating every localized string to keep it in sync is brittle.

Consider linking to the file without a line anchor, to a dedicated README/docs section, or to a stable permalink (e.g., a tagged version). The same applies to the equivalent strings in other locale files.

Suggested implementation:

```typescript
      argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs for details.',

```

1. Apply the same change (remove `#L207` from the URL) to the corresponding `argsDescription` entries in other locale files (e.g., `zh-CN.ts`, `ja-JP.ts`, etc.) so all localized strings avoid the brittle line-anchored link.
2. If you later introduce a dedicated documentation page or stable permalink (e.g., a tagged tree), consider updating this URL across all locale files to that more stable target instead of the `main` branch file path.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src-tauri/src/commands/utils.rs
Comment thread src-tauri/src/commands/utils.rs Outdated
Comment thread src/i18n/locales/en-US.ts Outdated
Copy link
Copy Markdown
Owner

@MistEO MistEO left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 方向 OK,属于 MXU 自家 launch action 扩展,没碰 PI 硬编码那条线。

不过实现上有几处想对齐一下:

  1. get_checked_task_status_of_instance 里 unwrap 太多,配置/实例稍微不一致就可能炸,建议落空 vec + log
  2. 遍历的是 pending_task_ids,但文案像「所有已勾选任务」——如果跑 pipeline 时已有任务 succeeded/running,会不会漏?确认下语义要不要改成按已选任务全集来拼
  3. i18n 里 GitHub 链接带 #L207 容易过期,建议去掉行号或链到文档

改完我再看一轮~

@zzc-tongji
Copy link
Copy Markdown
Author

zzc-tongji commented May 18, 2026

关于第2点可以先回答你,根据 AI 分析和实际代码测试的结果,pending_task_ids 就是指「所有已勾选任务」,这个变量的命名是有歧义的。出于 PR 改动最小化的原则,我没有重命名这个变量。

其他的我抽空搞一下。

@zzc-tongji
Copy link
Copy Markdown
Author

@MistEO 改完了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants