lycheedev 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/lycheedev.js CHANGED
@@ -40,6 +40,7 @@ commands
40
40
  use --character <n> pin the window that reports character <n>
41
41
  use --clear drop the pin
42
42
  send <text> type one slash command into the running game
43
+ reload reload and locally confirm readiness; --resume <nonce> resumes without reloading
43
44
  capture poll the game window and decode the completion notice
44
45
  run --task <id> deliver, decode, reload once and read the result ticket
45
46
  bugs --count <n> snapshot recent errors and read the result ticket
@@ -597,7 +598,7 @@ function main(argv) {
597
598
  // Commands that type into the game must target a live window, and the
598
599
  // executable name cannot tell two instances apart, so resolve which running
599
600
  // instance to use before forwarding.
600
- const runtime = ['send', 'capture', 'run', 'bugs'].includes(command)
601
+ const runtime = ['send', 'capture', 'run', 'bugs', 'reload'].includes(command)
601
602
  ? resolveRuntime(flags)
602
603
  : null;
603
604
  if (runtime && runtime.error) return 1;
@@ -615,6 +616,9 @@ function main(argv) {
615
616
  if (!live) return 1;
616
617
  return forward(['send', ...targetArgs(live), '--text', text, ...passthrough(flags)]);
617
618
  }
619
+ case 'reload':
620
+ if (!live) return 1;
621
+ return forward(['reload', ...targetArgs(live), ...passthrough(flags)]);
618
622
  case 'capture':
619
623
  if (!live) return 1;
620
624
  return forward(['capture', ...targetArgs(live), ...passthrough(flags)]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lycheedev",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "lycheedev: install the World of Warcraft inspection addon, its in-game automation tooling, and drive it from the command line.",
5
5
  "keywords": [
6
6
  "wow",
@@ -276,7 +276,7 @@ ns.L = {
276
276
  AUTO_STATUS_LINE = "任务 %s | 请求 %s | 状态 %s | 结果 %s",
277
277
  AUTO_RESULT_EXPIRED = "结果已过期",
278
278
  AUTO_RESULT_MISSING = "没有找到 Ticket %s 对应的已保存结果。",
279
- AUTO_USAGE = "用法:/dev auto run <任务ID> | bug <1-100> [请求ID] | status <任务ID> | show <Ticket> | ack <Ticket> received|failed | cancel <任务ID> | identify | unidentify | stop",
279
+ AUTO_USAGE = "用法:/dev auto run <任务ID> | bug <1-100> [请求ID] | reload <编号> [Ticket] | status <任务ID> | show <Ticket> | ack <Ticket> received|failed | cancel <任务ID> | identify | unidentify | stop",
280
280
  AUTO_PROVIDER_FAILED = "错误快照失败:%s",
281
281
  AUTO_BUG_TITLE = "错误快照(%d 条)",
282
282
  AUTO_EXECUTION_COUNT = "%d 条执行记录",
@@ -283,7 +283,7 @@ local english = {
283
283
  AUTO_STATUS_LINE = "Task %s | request %s | status %s | result %s",
284
284
  AUTO_RESULT_EXPIRED = "Result expired",
285
285
  AUTO_RESULT_MISSING = "No saved result found for ticket %s.",
286
- AUTO_USAGE = "Usage: /dev auto run <task-id> | bug <1-100> [request-id] | status <task-id> | show <ticket> | ack <ticket> received|failed | cancel <task-id> | identify | unidentify | stop",
286
+ AUTO_USAGE = "Usage: /dev auto run <task-id> | bug <1-100> [request-id] | reload <nonce> [ticket] | status <task-id> | show <ticket> | ack <ticket> received|failed | cancel <task-id> | identify | unidentify | stop",
287
287
  AUTO_PROVIDER_FAILED = "Error snapshot failed: %s",
288
288
  AUTO_BUG_TITLE = "Bug snapshot (%d)",
289
289
  AUTO_EXECUTION_COUNT = "%d executions",
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.1.1
9
+ ## Version: 1.2.0
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -33,6 +33,7 @@ Modules\Events\Monitor.lua
33
33
  Libs\AutomationQR.lua
34
34
  UI\Export.lua
35
35
  UI\AutomationOverlay.lua
36
+ Modules\Automation\Reload.lua
36
37
  UI\Pages\ExportRecords.lua
37
38
  UI\Features.lua
38
39
  UI\Pages\Object.lua
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.1.1
9
+ ## Version: 1.2.0
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -33,6 +33,7 @@ Modules\Events\Monitor.lua
33
33
  Libs\AutomationQR.lua
34
34
  UI\Export.lua
35
35
  UI\AutomationOverlay.lua
36
+ Modules\Automation\Reload.lua
36
37
  UI\Pages\ExportRecords.lua
37
38
  UI\Features.lua
38
39
  UI\Pages\Object.lua
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.1.1
9
+ ## Version: 1.2.0
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -33,6 +33,7 @@ Modules\Events\Monitor.lua
33
33
  Libs\AutomationQR.lua
34
34
  UI\Export.lua
35
35
  UI\AutomationOverlay.lua
36
+ Modules\Automation\Reload.lua
36
37
  UI\Pages\ExportRecords.lua
37
38
  UI\Features.lua
38
39
  UI\Pages\Object.lua
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.1.1
9
+ ## Version: 1.2.0
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -33,6 +33,7 @@ Modules\Events\Monitor.lua
33
33
  Libs\AutomationQR.lua
34
34
  UI\Export.lua
35
35
  UI\AutomationOverlay.lua
36
+ Modules\Automation\Reload.lua
36
37
  UI\Pages\ExportRecords.lua
37
38
  UI\Features.lua
38
39
  UI\Pages\Object.lua
@@ -643,6 +643,7 @@ function Controller.Stop()
643
643
  end
644
644
 
645
645
  function Controller.StopIdentify(nonce)
646
+ if ns.AutomationReload then ns.AutomationReload.Clear(nonce) end
646
647
  if nonce and nonce ~= identityReceiptNonce then
647
648
  return
648
649
  end
@@ -782,7 +783,18 @@ end
782
783
  function Controller.HandleCommand(text)
783
784
  local action, rest = tostring(text or ""):match("^(%S+)%s*(.-)%s*$")
784
785
  action = action and action:lower() or ""
785
- if action == "run" then
786
+ if action ~= "reload" and action ~= "unidentify" and ns.AutomationReload then
787
+ ns.AutomationReload.Clear()
788
+ end
789
+ if action == "reload" then
790
+ local nonce, ticket = rest:match("^(%S+)%s+(%S+)$")
791
+ if not nonce then nonce = rest:match("^(%S+)$") end
792
+ if activeContext or not IsValidRequestId(nonce) or (ticket and not IsValidTicket(ticket))
793
+ or (awaitingNotice and awaitingNotice.ticket ~= ticket)
794
+ or not ns.AutomationReload or not ns.AutomationReload.Request(nonce) then
795
+ Print(L.AUTO_USAGE)
796
+ end
797
+ elseif action == "run" then
786
798
  local taskId = rest:match("^(%S+)$")
787
799
  if not taskId then
788
800
  Print(L.AUTO_USAGE)
@@ -0,0 +1,101 @@
1
+ local ADDON_NAME, ns = ...
2
+
3
+ -- One bootstrap listener is required to read a pending request after SV load.
4
+ -- Without a request it unregisters immediately; no overlay or timer is built.
5
+ local Reload = {}
6
+ ns.AutomationReload = Reload
7
+ local driver = CreateFrame("Frame")
8
+ local pending, expiry, markerShown
9
+ local entered, loadingDone = false, false
10
+ local requestedThisSession = false
11
+ local TTL = 120
12
+
13
+ local function ValidNonce(value)
14
+ return type(value) == "string" and #value > 0 and #value <= 64
15
+ and value:match("^[A-Za-z0-9%.%-]+$") ~= nil
16
+ end
17
+
18
+ local function PlainText(value)
19
+ return not (issecretvalue and issecretvalue(value)) and type(value) == "string" and value ~= ""
20
+ end
21
+
22
+ function Reload.Clear(nonce)
23
+ if nonce and (not pending or pending.nonce ~= nonce) then return false end
24
+ if expiry then expiry:Cancel(); expiry = nil end
25
+ driver:UnregisterAllEvents()
26
+ if markerShown then ns.AutomationOverlay.HideIdentity() end
27
+ markerShown, pending = nil, nil
28
+ return true
29
+ end
30
+
31
+ local function TryReady()
32
+ if not pending or not entered or not loadingDone or ns.IsCombatBlocked() then return end
33
+ if not SlashCmdList.LYCHEEDEV or not ns.Automation or not ns.AutomationOverlay then return end
34
+ local character, realm = UnitName("player"), GetRealmName()
35
+ if not PlainText(character) or not PlainText(realm)
36
+ or character ~= pending.character or realm ~= pending.realm then Reload.Clear(); return end
37
+ local version, build = GetBuildInfo()
38
+ local json = string.format(
39
+ '{"v":1,"kind":"reload","run":"%s","status":"ready","ts":%d,"client":"%s","build":"%s.%s"}',
40
+ pending.nonce, time(), ns.Client.id, version, build)
41
+ markerShown = ns.AutomationOverlay.ShowIdentity(json) and true or false
42
+ driver:UnregisterEvent("PLAYER_ENTERING_WORLD")
43
+ driver:UnregisterEvent("LOADING_SCREEN_DISABLED")
44
+ end
45
+
46
+ function Reload.Request(nonce)
47
+ if not ValidNonce(nonce) or ns.IsCombatBlocked() or requestedThisSession then return false end
48
+ ns.InitializeDatabase()
49
+ -- Do not overwrite an unknown/newer request format.
50
+ if LycheeDevDB.reloadHandshake ~= nil then return false end
51
+ local character, realm = UnitName("player"), GetRealmName()
52
+ if not PlainText(character) or not PlainText(realm) then return false end
53
+ Reload.Clear()
54
+ ns.EnsureSafety()
55
+ local request = {schema=1, nonce=nonce, requestedAt=time(),
56
+ character=character, realm=realm}
57
+ LycheeDevDB.reloadHandshake = request
58
+ requestedThisSession = true
59
+ local ok = pcall(ReloadUI)
60
+ if not ok then
61
+ if LycheeDevDB.reloadHandshake == request then LycheeDevDB.reloadHandshake = nil end
62
+ return false
63
+ end
64
+ -- Only the next Lua session can publish ready, never this call stack.
65
+ return true
66
+ end
67
+
68
+ driver:RegisterEvent("ADDON_LOADED")
69
+ driver:SetScript("OnEvent", function(_, event, name, isReloadingUi)
70
+ if event == "ADDON_LOADED" then
71
+ if name ~= ADDON_NAME then return end
72
+ driver:UnregisterEvent("ADDON_LOADED")
73
+ local request = type(LycheeDevDB) == "table" and LycheeDevDB.reloadHandshake
74
+ if type(request) ~= "table" or request.schema ~= 1 then return end
75
+ LycheeDevDB.reloadHandshake = nil
76
+ if not ValidNonce(request.nonce) or type(request.requestedAt) ~= "number"
77
+ or time() < request.requestedAt or time() - request.requestedAt > TTL
78
+ or not PlainText(request.character) or not PlainText(request.realm) then return end
79
+ pending = {nonce=request.nonce,character=request.character,realm=request.realm}
80
+ ns.EnsureSafety()
81
+ driver:RegisterEvent("PLAYER_ENTERING_WORLD")
82
+ driver:RegisterEvent("LOADING_SCREEN_DISABLED")
83
+ driver:RegisterEvent("LOADING_SCREEN_ENABLED")
84
+ driver:RegisterEvent("PLAYER_LEAVING_WORLD")
85
+ expiry = C_Timer.NewTimer(TTL, function() Reload.Clear() end)
86
+ elseif event == "PLAYER_ENTERING_WORLD" then
87
+ if not isReloadingUi then Reload.Clear(); return end
88
+ entered = true
89
+ TryReady()
90
+ elseif event == "LOADING_SCREEN_DISABLED" then
91
+ loadingDone = true
92
+ TryReady()
93
+ elseif event == "LOADING_SCREEN_ENABLED" then
94
+ loadingDone = false
95
+ if markerShown then Reload.Clear() end
96
+ elseif event == "PLAYER_LEAVING_WORLD" then
97
+ Reload.Clear()
98
+ end
99
+ end)
100
+
101
+ ns.RegisterCombatShutdown(function() Reload.Clear() end)
@@ -21,6 +21,8 @@ description: 编排 Lychee Dev 的 WoW 后台自动化任务、错误快照、
21
21
 
22
22
  无焦点要求不等于所有窗口状态都可用:最小化、客户端切换、战斗、尚未载入世界、其他游戏编辑框和自定义聊天键位可能影响操作。只报告本次实际验证的客户端/版本/状态。消息成功入队不证明游戏执行;二维码出现不证明 SV 已落盘。
23
23
 
24
+ 支持重载握手的插件与脚本应配套更新。自动化重载使用 `reload --mode messages`:脚本本地识别本次 nonce 的就绪二维码并清理,只向 Agent 返回简短 JSON。正常流程不要采集整图交给 Agent 判断。`run`/`bugs` 的输出重载同样等待就绪;超时查看日志中的阶段和本地截图,使用 `reload --resume <nonce>` 继续等待/清理,禁止重新发送重载。该信号证明命令通路已在重载后进入世界,不代表任意第三方异步任务都已完成。
25
+
24
26
  ## 完成标准
25
27
 
26
28
  一次自动调查需要取得匹配 task/requestId/Ticket 的完整报告,核对身份与校验信息、保存证据、确认 ACK,并完成该回执的界面清理。未完成的阶段必须明确说明。不要为了清理画面重跑任务。
@@ -46,18 +46,20 @@ task-id 是 `[A-Za-z0-9_-]{1,64}`;requestId 建议只用字母、数字、点
46
46
 
47
47
  同步调查返回紧凑结构。异步调查调用 `SetAsync()`,通过 `Finish(...)` 或 `Fail(message, code)` 完成,用 `OnCleanup(fn)` 释放自己创建的资源,检查 `IsCancelled()`;`Log` 与 `print` 输出有界。不得返回尚未完成的表并指望后来修改自动保存。
48
48
 
49
- 输入侧 reload:发送 `/reload` 后等待客户端恢复可交互状态再发执行命令。SV mtime 变化只证明开始写盘,不证明加载已结束。用 WGC 观察世界画面恢复或验证过的就绪信号;固定等待数秒不能单独作为就绪证明。不得因暂时加载中而连续发命令试探。
49
+ 输入侧 reload 使用下面的专用命令。Python 生成 nonce,插件保存一次性请求后重载;新 Lua 会话收到重载的 `PLAYER_ENTERING_WORLD` 和 `LOADING_SCREEN_DISABLED`、核对角色及命令模块后才显示 ready QR。Python 在本地解码并按 nonce 清理,正常只返回 `reload_ready` JSON,不向 Agent 传图。SV mtime 变化和固定等待都不能替代就绪握手。该协议需要插件和脚本配套更新,旧插件不能识别时应停止,不自动降级或循环重载。
50
50
 
51
51
  ## 执行已绑定账户的任务
52
52
 
53
53
  下面示例的全局 `--data-dir`(如有)放在子命令前。全部窗口操作沿用本次绑定:
54
54
 
55
55
  ```text
56
- python <skill>/scripts/automation.py --installation <binding> send --mode messages --hwnd <hwnd> --pid <pid> --exe-path <exe> --text "/reload"
56
+ python <skill>/scripts/automation.py --installation <binding> reload --mode messages --hwnd <hwnd> --pid <pid> --exe-path <exe> --timeout 60
57
57
  python <skill>/scripts/automation.py --installation <binding> run --mode messages --hwnd <hwnd> --pid <pid> --exe-path <exe> --task <task> --install-dir <addon> --sv <verified-sv> --timeout 120
58
58
  ```
59
59
 
60
- 不要把两条命令无条件贴在同一个连续执行脚本里:输入 reload 后需先确认就绪。`run` 读取安装区块的 requestId/revision,提交 `/dev auto run <task>`,过滤旧完成码,记录输出 reload 去重键,再校验 SV 并保存完整报告。
60
+ 只有 `reload` 返回 0、状态为 `reload_ready` 后才运行下一条命令。`run` 读取安装区块的 requestId/revision,提交 `/dev auto run <task>`,过滤旧完成码,记录输出 reload 去重键,通过同一个握手等待就绪,再校验 SV 并保存完整报告。输出重载将已核对的 Ticket 传给插件,不覆盖其他待处理回执。
61
+
62
+ 日志分别记录 `reload_handshake_requested`、`reload_ready_confirmed`、`reload_ready_cleared`。超时返回原 nonce、失败阶段和本地 `reload/<nonce>/timeout.png`(没有图像时为 null),不上传图片正文。仅失败时 Agent 才有必要打开图片。恢复命令为 `reload --resume <nonce>`,沿用相同 installation/HWND/PID/exe;它绝不再次发送重载,确认过 ready 则只补清理。marker 最长存活 120 秒,超出后保持未解决,不自动制造新重载。
61
63
 
62
64
  账户未绑定时按 [clients.md](clients.md) 分段执行:`send` 运行、`capture` 取码、Agent 验证 task/run、带 requestId/Ticket 发送一次 `/reload`、定位精确记录,再 `sv read`。`capture` 本身只验证 QR 格式,不知道本次预期 task/run,不能拿任何码直接触发 reload。
63
65
 
@@ -86,7 +88,7 @@ SV 内容已完整验证后发送 received;读失败但已明确决定结束
86
88
  python <skill>/scripts/automation.py --installation <binding> ack --mode messages --hwnd <hwnd> --pid <pid> --exe-path <exe> --ticket <ticket> --status received --timeout 30
87
89
  ```
88
90
 
89
- 输出 reload 后先确认世界已恢复。ACK 分配新 nonce,等待含该 nonce、Ticket 和 outcome 的 QR;随后发送 `/dev auto unidentify <nonce>`,只隐藏对应 ACK 标记,再观察该码消失。`ticket_ack_confirmed` 和 `ticket_ack_cleared` 分开记录;确认成功但清理超时不等于任务失败。
91
+ `run`/`bugs` 已通过握手确认输出 reload 后进入世界;ACK 前不需要再次给 Agent 看截图。若是旧版或手动 `/reload`,仍须有明确就绪证据。ACK 分配新 nonce,等待含该 nonce、Ticket 和 outcome 的 QR;随后发送 `/dev auto unidentify <nonce>`,只隐藏对应 ACK 标记,再观察该码消失。`ticket_ack_confirmed` 和 `ticket_ack_cleared` 分开记录;确认成功但清理超时不等于任务失败。
90
92
 
91
93
  旧版插件只支持两参数 ACK,不支持 nonce 清理。使用前核对工具与插件协议版本;授权的测试/更新应备份后同步相应源码并 reload。不能在旧插件上持续重试不支持的命令。`/dev auto unidentify` 无参数会隐藏身份标记,仅在明确属于自己的标记且没有新回执时用;不能用通用 stop 掩盖未处理证据。
92
94
 
@@ -0,0 +1,121 @@
1
+ """Nonce-bound reload readiness; images remain on the host, not in model input."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import struct
8
+ import time
9
+ import zlib
10
+
11
+ NONCE = re.compile(r"[A-Za-z0-9.-]{1,64}\Z")
12
+
13
+
14
+ class ReloadError(Exception):
15
+ pass
16
+
17
+
18
+ def marker(payload, nonce):
19
+ if not isinstance(payload, str) or len(payload.encode("utf-8")) > 512:
20
+ return None
21
+ try:
22
+ value = json.loads(payload)
23
+ except (ValueError, TypeError):
24
+ return None
25
+ if not isinstance(value, dict) or value.get("v") != 1:
26
+ return None
27
+ if value.get("kind") != "reload" or value.get("run") != nonce or value.get("status") != "ready":
28
+ return None
29
+ if type(value.get("ts")) is not int or value["ts"] <= 0:
30
+ return None
31
+ if not all(isinstance(value.get(k), str) and 0 < len(value[k]) <= 64 for k in ("client", "build")):
32
+ return None
33
+ return value
34
+
35
+
36
+ def save_timeout_image(session, nonce, roi):
37
+ if roi is None:
38
+ return None
39
+ # WGC's bounded ROI is BGR(A); write RGB PNG with the stdlib, no new dependency.
40
+ height, width = roi.shape[:2]
41
+ raw = b"".join(b"\0" + roi[y, :, :3][:, ::-1].tobytes() for y in range(height))
42
+ def chunk(kind, data):
43
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
44
+ png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
45
+ png += chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
46
+ directory = session.state_path(os.path.join("reload", nonce))
47
+ os.makedirs(directory, exist_ok=True)
48
+ path = os.path.join(directory, "timeout.png")
49
+ with open(path, "wb") as handle:
50
+ handle.write(png)
51
+ return path
52
+
53
+
54
+ def wait_ready(windows, session, args, nonce):
55
+ deadline = time.monotonic() + args.timeout
56
+ interval = getattr(args, "interval", None) or .1
57
+ last_roi = None
58
+ with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
59
+ while time.monotonic() < deadline:
60
+ if capture.window_closed:
61
+ break
62
+ roi = capture.latest_roi()
63
+ if roi is not None:
64
+ last_roi = roi
65
+ for payload in windows.decode_qr(roi):
66
+ ready = marker(payload, nonce)
67
+ if ready:
68
+ return ready
69
+ time.sleep(interval)
70
+ path = save_timeout_image(session, nonce, last_roi)
71
+ session.log_event("reload_ready_timeout", nonce=nonce, screenshot=path)
72
+ raise ReloadError(f"reload readiness unresolved for {nonce}; resume this nonce without reloading; screenshot={path}")
73
+
74
+
75
+ def wait_cleared(windows, args, nonce):
76
+ deadline = time.monotonic() + min(args.timeout, 5)
77
+ interval = getattr(args, "interval", None) or .1
78
+ absent = 0
79
+ with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
80
+ while time.monotonic() < deadline:
81
+ if capture.window_closed:
82
+ return False
83
+ roi = capture.latest_roi()
84
+ if roi is not None:
85
+ visible = any(marker(payload, nonce) for payload in windows.decode_qr(roi))
86
+ absent = 0 if visible else absent + 1
87
+ if absent >= 2:
88
+ return True
89
+ time.sleep(interval)
90
+ return False
91
+
92
+
93
+ def execute(windows, session, args, deliver, nonce, *, ticket=None, resume=False):
94
+ if not NONCE.fullmatch(nonce):
95
+ raise ReloadError("invalid reload nonce")
96
+ history = [e for e in session.read_events() if e.get("nonce") == nonce]
97
+ previous = next((e for e in history if e["event"] == "reload_handshake_requested"), None)
98
+ if resume:
99
+ if not previous or any(previous.get(k) != getattr(args, attr, None)
100
+ for k, attr in (("hwnd", "hwnd"), ("pid", "pid"), ("exePath", "exe_path"))):
101
+ raise ReloadError("reload resume requires the original nonce and window binding")
102
+ if any(e["event"] == "reload_ready_cleared" for e in history):
103
+ return {"status": "already_completed", "nonce": nonce}
104
+ else:
105
+ if previous:
106
+ raise ReloadError("reload nonce was already submitted; use --resume, do not reload again")
107
+ session.log_event("reload_handshake_requested", nonce=nonce, ticket=ticket,
108
+ hwnd=args.hwnd, pid=args.pid, exePath=args.exe_path)
109
+ deliver(session, windows, args, f"/dev auto reload {nonce}" + (f" {ticket}" if ticket else ""))
110
+ started = time.monotonic()
111
+ confirmed = next((e for e in history if e["event"] == "reload_ready_confirmed"), None)
112
+ ready = confirmed.get("ready") if confirmed else wait_ready(windows, session, args, nonce)
113
+ if not confirmed:
114
+ session.log_event("reload_ready_confirmed", nonce=nonce, ready=ready)
115
+ deliver(session, windows, args, f"/dev auto unidentify {nonce}")
116
+ if not wait_cleared(windows, args, nonce):
117
+ session.log_event("reload_ready_cleanup_unresolved", nonce=nonce)
118
+ raise ReloadError(f"reload ready, but marker cleanup unresolved; resume {nonce}")
119
+ session.log_event("reload_ready_cleared", nonce=nonce)
120
+ return {"status": "reload_ready", "nonce": nonce, "elapsedSeconds": round(time.monotonic() - started, 2),
121
+ "client": ready["client"], "build": ready["build"], "markerCleared": True}
@@ -7,7 +7,8 @@ Subcommand groups (design section 9):
7
7
  - ``profile`` bind one WoW client installation, addon dir and SV path
8
8
  - ``sv`` find account-level SavedVariables candidates; read a Ticket
9
9
  - ``capture`` poll the game window and decode the completion notice QR
10
- - ``send`` deliver one slash command through focus/clipboard/Enter
10
+ - ``send`` deliver one slash command through the selected input transport
11
+ - ``reload`` reload, recognize the nonce-bound ready QR locally, then clear it
11
12
  - ``run`` task flow: run command, notice, output reload, SavedVariables
12
13
  read and artifact save (the input-side reload that loads the
13
14
  new task block is a separate, operator-visible step)
@@ -42,6 +43,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
42
43
 
43
44
  from automation import registry, saved_variables as svlib # noqa: E402
44
45
  from automation import session as session_mod # noqa: E402
46
+ from automation import reload as reload_mod # noqa: E402
45
47
  from automation.registry import RegistryError # noqa: E402
46
48
  from automation.saved_variables import SavedVariablesError # noqa: E402
47
49
 
@@ -415,6 +417,22 @@ def cmd_send(args) -> int:
415
417
  return 0
416
418
 
417
419
 
420
+ def reload_ready(session, windows, args, *, ticket=None, nonce=None, resume=False):
421
+ try:
422
+ return reload_mod.execute(windows, session, args, _deliver, nonce or new_request_id(),
423
+ ticket=ticket, resume=resume)
424
+ except reload_mod.ReloadError as error:
425
+ raise CliError(str(error), code=EXIT_NOTICE_TIMEOUT) from error
426
+
427
+
428
+ def cmd_reload(args) -> int:
429
+ session = session_mod.Session(data_dir=args.data_dir, installation=args.installation)
430
+ result = reload_ready(session, _window_module(), args, nonce=args.resume or args.nonce,
431
+ resume=bool(args.resume))
432
+ print(json.dumps(result, sort_keys=True))
433
+ return 0
434
+
435
+
418
436
  def ack_command(ticket: str, outcome: str, nonce: str | None = None) -> str:
419
437
  """Build the in-game command that reports a ticket's read outcome.
420
438
 
@@ -678,7 +696,7 @@ def _notice_to_sv(session: session_mod.Session, windows, notice: dict, args,
678
696
  f"reload for {ticket} was already requested; check the saved "
679
697
  "variables file before repeating the reload")
680
698
  baseline = session.file_snapshot(args.sv)
681
- _deliver(session, windows, args, "/reload")
699
+ reload_ready(session, windows, args, ticket=ticket)
682
700
  if not session.wait_for_saved_variables(args.sv, timeout=args.timeout,
683
701
  baseline=baseline):
684
702
  session.log_event("sv_write_timeout", ticket=ticket)
@@ -805,7 +823,15 @@ def cmd_recover(args) -> int:
805
823
  for ticket in pending:
806
824
  print(f"UNRESOLVED: reload requested for {ticket} but not received yet; "
807
825
  "inspect the saved variables file manually before any retry")
808
- if not pending:
826
+ requests = {(e.get("installation"), e.get("nonce")) for e in
827
+ session.read_events("reload_handshake_requested", installation=scope)}
828
+ cleared = {(e.get("installation"), e.get("nonce")) for e in
829
+ session.read_events("reload_ready_cleared", installation=scope)}
830
+ unresolved = requests - cleared
831
+ for installation, nonce in sorted(unresolved):
832
+ print(f"UNRESOLVED: installation {installation!r}, reload handshake {nonce}; "
833
+ f"use reload --resume {nonce} with its original window binding; do not reload again")
834
+ if not pending and not unresolved:
809
835
  print(f"no unresolved reload requests in installation "
810
836
  f"{session.installation!r}")
811
837
  return 0
@@ -900,6 +926,13 @@ def build_parser() -> argparse.ArgumentParser:
900
926
  send.add_argument("--ticket", help="ticket used to dedup a '/reload' command")
901
927
  send.set_defaults(func=cmd_send)
902
928
 
929
+ reload_parser = sub.add_parser("reload", parents=[window, polling],
930
+ help="reload and locally confirm the nonce-bound ready marker")
931
+ identity = reload_parser.add_mutually_exclusive_group()
932
+ identity.add_argument("--nonce", help="unique reload identity (default: generated)")
933
+ identity.add_argument("--resume", help="wait/clean up this existing nonce without another reload")
934
+ reload_parser.set_defaults(func=cmd_reload)
935
+
903
936
  ack = sub.add_parser("ack", parents=[window, polling],
904
937
  help="report a ticket's read outcome to the running game")
905
938
  ack.add_argument("--ticket", required=True, help="exact ticket that was read")
@@ -0,0 +1,120 @@
1
+ """Offline protocol tests. No input is sent to a real window."""
2
+ import argparse
3
+ import json
4
+ import tempfile
5
+ import importlib.util
6
+ from pathlib import Path
7
+ import unittest
8
+ from unittest.mock import patch
9
+
10
+ from automation import reload as reload_mod
11
+ from automation.session import Session
12
+
13
+
14
+ def ready(nonce="current", **changes):
15
+ data = {"v":1,"kind":"reload","run":nonce,"status":"ready","ts":1000,
16
+ "client":"retail","build":"12.1.0.69875"}
17
+ data.update(changes)
18
+ return json.dumps(data)
19
+
20
+
21
+ class Capture:
22
+ window_closed = False
23
+ def __init__(self, frames): self.frames = iter(frames)
24
+ def __enter__(self): return self
25
+ def __exit__(self, *_): pass
26
+ def latest_roi(self): return next(self.frames, None)
27
+
28
+
29
+ class Windows:
30
+ def __init__(self, captures): self.captures = iter(captures)
31
+ def open_notice_capture(self, *_args, **_kwargs): return Capture(next(self.captures))
32
+ def decode_qr(self, frame): return frame
33
+
34
+
35
+ class ReloadTests(unittest.TestCase):
36
+ def setUp(self):
37
+ self.directory = tempfile.TemporaryDirectory()
38
+ self.addCleanup(self.directory.cleanup)
39
+ self.session = Session(self.directory.name, "reload-test")
40
+ self.args = argparse.Namespace(hwnd=1,pid=2,exe_path="Wow.exe",timeout=.01,interval=.0001)
41
+ self.sent = []
42
+ self.deliver = lambda _s,_w,_a,text: self.sent.append(text)
43
+
44
+ def execute(self, windows, **kwargs):
45
+ return reload_mod.execute(windows,self.session,self.args,self.deliver,"current",**kwargs)
46
+
47
+ def test_marker(self):
48
+ self.assertIsNotNone(reload_mod.marker(ready(), "current"))
49
+ for value in (ready("old"),ready(v=2),ready(status="pending"),ready(kind="ack"),
50
+ ready(ts=True),ready(build=""),"[]","bad","x"*513):
51
+ self.assertIsNone(reload_mod.marker(value,"current"))
52
+
53
+ def test_success_stale_and_cleanup(self):
54
+ result = self.execute(Windows([[[ready("old")],[ready()]], [[ready()],[],[]]]))
55
+ self.assertEqual(result["status"],"reload_ready")
56
+ self.assertEqual(self.sent,["/dev auto reload current","/dev auto unidentify current"])
57
+ self.assertEqual(self.session.read_events()[-1]["event"],"reload_ready_cleared")
58
+ self.assertEqual(self.execute(Windows([]),resume=True)["status"],"already_completed")
59
+ self.assertEqual(len(self.sent),2)
60
+
61
+ def test_no_repeat_on_timeout_then_resume(self):
62
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([[]]))
63
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([]))
64
+ self.assertEqual(len(self.sent),1)
65
+ self.execute(Windows([[[ready()]], [[],[]]]),resume=True)
66
+ self.assertEqual(self.sent.count("/dev auto reload current"),1)
67
+
68
+ def test_no_frame_is_not_cleanup(self):
69
+ with self.assertRaises(reload_mod.ReloadError):
70
+ self.execute(Windows([[[ready()]], []]))
71
+ self.assertTrue(self.session.read_events("reload_ready_confirmed"))
72
+ self.assertFalse(self.session.read_events("reload_ready_cleared"))
73
+ self.execute(Windows([[[],[]]]),resume=True)
74
+ self.assertEqual(self.sent.count("/dev auto reload current"),1)
75
+
76
+ def test_wrong_binding_and_nonce(self):
77
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([]),resume=True)
78
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([[]]))
79
+ self.args.pid=3
80
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([]),resume=True)
81
+ self.assertEqual(len(self.sent),1)
82
+
83
+ def test_ticket_forwarding(self):
84
+ self.execute(Windows([[[ready()]], [[],[]]]),ticket="LYCHEE-TEST-1")
85
+ self.assertEqual(self.sent[0],"/dev auto reload current LYCHEE-TEST-1")
86
+
87
+ def test_timeout_artifact_only_on_failure(self):
88
+ with patch.object(reload_mod,"save_timeout_image",return_value="timeout.png") as save:
89
+ with self.assertRaises(reload_mod.ReloadError): self.execute(Windows([[]]))
90
+ save.assert_called_once()
91
+ self.assertEqual(self.session.read_events("reload_ready_timeout")[-1]["screenshot"],"timeout.png")
92
+
93
+ def test_output_flow_waits_before_read(self):
94
+ spec=importlib.util.spec_from_file_location("reload_cli_test",Path(__file__).with_name("automation.py"))
95
+ cli=importlib.util.module_from_spec(spec);spec.loader.exec_module(cli)
96
+ args=argparse.Namespace(**vars(self.args),sv="unused",data_dir=self.directory.name,installation="reload-test")
97
+ notice={"task":"probe","run":"request","ticket":"LYCHEE-TEST-1","ts":1000}
98
+ order=[]
99
+ with patch.object(cli,"reload_ready",side_effect=lambda *a,**k: order.append("ready")), \
100
+ patch.object(self.session,"wait_for_saved_variables",side_effect=lambda *a,**k: order.append("disk") or True), \
101
+ patch.object(cli,"cmd_sv",side_effect=lambda *a: order.append("read") or 0):
102
+ self.assertEqual(cli._notice_to_sv(self.session,object(),notice,args,revision="r1",request_type="task"),0)
103
+ self.assertEqual(order,["ready","disk","read"])
104
+ self.assertTrue(self.session.reload_already_requested("request","LYCHEE-TEST-1"))
105
+
106
+ def test_png_rgb(self):
107
+ try:
108
+ import numpy as np
109
+ except ImportError:
110
+ self.skipTest("optional capture dependency not installed")
111
+ import struct,zlib
112
+ image=np.array([[[0,0,255],[255,0,0]]],dtype=np.uint8)
113
+ path=reload_mod.save_timeout_image(self.session,"current",image)
114
+ data=Path(path).read_bytes()
115
+ self.assertEqual(data[:8],b"\x89PNG\r\n\x1a\n")
116
+ size=struct.unpack(">I",data[33:37])[0]
117
+ self.assertEqual(zlib.decompress(data[41:41+size]),b"\x00\xff\x00\x00\x00\x00\xff")
118
+
119
+
120
+ if __name__ == "__main__": unittest.main()