Feature: Add MCP cancellation, progress notifications and dry runs

P11 closes the plan's last batch, entirely on the server side: no client
change is required for any of it.

Long-running tools now expose a cancellation flag that every wait loop
checks in 500 ms slices. A cancelled tool returns through the cleanup
branch it already had (late first packets still get absorbed, sub
connections still get closed, pending entries still get deleted), so
there is no second cleanup path to keep in sync, and the host is released
within a second. Three sources set the flag: notifications/cancelled
(matched on the exact JSON-RPC id, with a fallback to the display form so
a request_id copied out of the session list round-trips), mcp_cancel_session
(by request_id, host id or session id), and a failed SSE write when the
client has gone away. The dispatcher rewrites a cancel-induced failure to
-32800 so callers do not mistake it for a host fault.

tools/call requests carrying _meta.progressToken are answered as
text/event-stream on the same POST: the tool runs on its own thread and
both the notifications/progress events and the final JSON-RPC response go
out through one chunked provider. Requests without a token are unchanged.
download_file reports files done vs. expected, upload_file reports bytes
sent vs. total.

Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list
and cancel in-flight sessions (calls, pending one-shots, terminal, remote
control, file transfer, chat). They are deliberately not gated by the
feature switches or readonly mode, since that is the only way out of a
stuck request. The -32003 busy message now names the occupier:
"Device busy: ... (tool=download_file, elapsed=12s)".

power_action gains wait/wait_ms to verify the result against the main
connection's presence (went_offline, came_back, elapsed_ms); not seeing
the transition is reported as ok, not as a failure. kill_process,
operate_window and the four host_control_* tools accept dry_run, which
validates the target against one fresh snapshot and returns what would be
affected without sending anything. Validation rejections now use -32012;
-32008 stays as documented historical alias.

One implementation note worth recording: the per-thread call context uses
FLS, not thread_local. Any static thread_local in this server crashes the
process about a second after start, because some threads come from
shellcode/MemoryModule images that never ran PE TLS initialisation.

Verified against a real Debug server and a real Windows client over MCP:
the smoke test now passes 104 checks with 0 failures, including
cancellation releasing the host in under a second, the cancelled request
returning -32800, notifications/cancelled returning 202, 63 progress
events with exact byte counts for a 64 MB upload, and a cleanly
terminated SSE stream. Not exercised in this pass: power_action's
wait=true path (it would take the test host down) and the -32006
readonly/switch-off section (every switch was on during the run).

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-28 21:25:49 +01:00
1 parent 3d388f8e45
commit 1c832ff7f2
10 files changed
+1855 -107

No files matched your search

+332
View File
@@ -9,6 +9,14 @@
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
后整棵删掉,不碰沙箱以外的任何东西。
[6] 是 P11 的验收:-32012(校验拒绝,历史别名 -32008 不再出现)、dry_run
只校验不下发、mcp_list_sessions / mcp_cancel_session 与 notifications/cancelled
的取消路径(取消后 1s 内释放主机、被取消的请求回 -32800)、以及 SSE 进度通知。
其中「真实取消」会起一条能在目标机跑够 ~25s 的无副作用命令(Windows 上是
ping -n 25 127.0.0.1,没有 exec_command 时退回 get_keylog 20s),1s 后取消;
命令本身会在目标机上自己跑完,不影响结果。SSE 进度一节同样要求 -FileWriteDir,
会往那个目录上传一个 4 MB 临时文件并在结束时删掉。
用法:
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
@@ -44,6 +52,9 @@ param(
)
$ErrorActionPreference = 'Stop'
# Start-RpcAsync 用 HttpClient 发并发请求;Windows PowerShell 5.1 默认没加载这个程序集,
# 而类型字面量在执行该语句时就要能解析,所以放在脚本开头加载。
try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop } catch { }
$script:pass = 0
$script:fail = 0
$script:failures = @()
@@ -97,6 +108,58 @@ function HasPaging($obj) {
return $true
}
# 工具是否出现在 tools/list 里:不可见多半是开关关着(正常配置),相关断言跳过而不是报失败。
function HasTool([string]$name) {
return (@($tools | Where-Object { $_.name -eq $name }).Count -gt 0)
}
# 并发发起一个 tools/call:取消测试要在请求还在飞的时候去查表、去取消,
# 单线程的 Invoke-WebRequest 做不到。返回句柄交给 Receive-RpcAsync 收尾。
#
# 用 HttpClient.SendAsync(真异步,立即返回 Task)。别用 HttpWebRequest + BeginGetResponse:
# 实测 EndGetResponse 之前 BeginGetResponse 自己就会阻塞到响应头到达(服务端在工具跑完
# 才写响应头),于是「异步」调用其实是同步的,被测的长调用根本没在飞。
$script:HttpClient = $null
function Get-SmokeHttpClient() {
if (-not $script:HttpClient) {
$c = New-Object System.Net.Http.HttpClient
$c.Timeout = [TimeSpan]::FromSeconds(180)
$script:HttpClient = $c
}
return $script:HttpClient
}
function Start-RpcAsync([string]$json) {
$req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Post, $Base)
$req.Content = New-Object System.Net.Http.StringContent($json, [System.Text.Encoding]::UTF8, 'application/json')
$req.Headers.Add('Authorization', 'Bearer ' + $Token)
$req.Headers.Add('Accept', 'application/json, text/event-stream')
return @{ Request = $req; Task = (Get-SmokeHttpClient).SendAsync($req) }
}
function Receive-RpcAsync($handle) {
$resp = $null
try {
$resp = $handle.Task.GetAwaiter().GetResult() # 非 2xx 不抛异常(没调 EnsureSuccessStatusCode)
return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult()
} catch {
return ''
} finally {
if ($resp) { $resp.Dispose() }
$handle.Request.Dispose()
}
}
# 带 Accept: text/event-stream 的请求:带 _meta.progressToken 的 tools/call 会以
# chunked SSE 回应,Invoke-WebRequest 读完整条流后一次性返回正文。
function Send-Sse([string]$json, [string]$auth) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
$headers = @{ Authorization = 'Bearer ' + $auth; Accept = 'application/json, text/event-stream' }
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes -ContentType 'application/json' `
-Headers $headers -TimeoutSec 300 -UseBasicParsing
return @{ Status = [int]$resp.StatusCode; Body = [string]$resp.Content
ContentType = [string]$resp.Headers['Content-Type'] }
}
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
function HasJsonText($rpc) {
@@ -147,6 +210,12 @@ $ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
# P11:在飞会话的观测 / 取消入口必须一直可见——它是卡住请求的唯一出路,
# 因此不受功能开关与只读模式限制(只读时也在列表里)。
foreach ($n in @('mcp_list_sessions', 'mcp_cancel_session')) {
Check ('tools/list 含 ' + $n) (@($tools | Where-Object { $_.name -eq $n }).Count -eq 1)
}
# ===== 2b. 协议层错误码 =====
Write-Host "`n[2b] 协议层错误码"
$um = Rpc 'bogus/method' @{} $null $null
@@ -271,6 +340,14 @@ if (-not $SkipHost) {
($byPid.error -eq $null -and [int]$bp.total -ge 1 -and
@($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) `
("pid=" + $ppid + " total=" + $bp.total)
# 6b 的 dry_run 断言要拿一个真能操作的进程:pid 0 是内核伪进程([System Process]),
# kill_process 按约定拒绝非零以外的 PID,host_control_process 也认不出它。
$sample = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 50 }
if ($null -eq $sample.error) {
$realProc = @($sample.result.structuredContent.processes | Where-Object { [int]$_.pid -gt 4 })[0]
if ($realProc) { $ppid = [int]$realProc.pid }
}
}
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
@@ -567,6 +644,261 @@ if ($offGate) {
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
}
# ===== 6. P11:校验码 / dry_run / 在飞会话观测与取消 / SSE 进度 =====
# 每条都对应 P11 的一条验收:
# 6a -32012(校验拒绝)取代历史别名 -32008;
# 6b dry_run 统一「只校验目标、不下发动作」;
# 6c mcp_list_sessions 快照 + mcp_cancel_session 与 notifications/cancelled 的取消,
# 以及「取消后主机 1s 内释放」(用 get_server_status.sessions.pending 复核);
# 6d 带 _meta.progressToken 的 tools/call 走 text/event-stream,长任务的进度通知计数 > 0。
Write-Host "`n[6] P11 校验码、dry_run 与中断"
# 取消测试要同时挂着长请求、还要再发短请求,需要比 .NET 默认(每主机 2 条)更多的连接。
[System.Net.ServicePointManager]::DefaultConnectionLimit = 16
$p11Host = (-not $SkipHost) -and [bool]$HostId
$isWindowsHost = ($null -eq $caps) -or (@('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform)
# 6a. -32012:命令里的 shell 元字符属于「参数被校验拒绝」,不是白名单拒绝(-32007)
if ($p11Host -and (HasTool 'exec_command')) {
$badCmd = Rpc '' $null 'exec_command' @{ id = $HostId; command = 'dir & whoami' }
Check 'exec_command 含 shell 元字符返回 -32012' ((ErrCode $badCmd) -eq -32012) (Detail $badCmd)
Check '校验拒绝不再使用历史别名 -32008' ((ErrCode $badCmd) -ne -32008) (Detail $badCmd)
} else {
Write-Host " exec_command 不可用,跳过 -32012 检查。" -ForegroundColor Yellow
}
# 6b. dry_run:只取一次快照校验目标存在,结构化结果带 dry_run=true,
# 且不能出现「动作后才有」的字段(remaining / changed)——那意味着动作真的下发了。
if ($p11Host -and (HasTool 'kill_process')) {
$drBad = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @(4); dry_run = 'yes' }
Check 'kill_process dry_run 非布尔返回 -32602' ((ErrCode $drBad) -eq -32602) (Detail $drBad)
if ($null -ne $ppid) {
$dr = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @($ppid); dry_run = $true }
$drs = $dr.result.structuredContent
Check 'kill_process dry_run=true 只校验(targets/missing,无 remaining)' `
(($null -eq $dr.error) -and ($drs.dry_run -eq $true) -and
(@($drs.targets).Count -ge 1) -and
($drs.PSObject.Properties.Name -contains 'missing') -and
-not ($drs.PSObject.Properties.Name -contains 'remaining')) (Detail $dr)
}
} else {
Write-Host " kill_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
}
$win0 = $null
if ($null -ne $wins -and $null -ne $wins.result) { $win0 = @($wins.result.structuredContent.windows)[0] }
if ($p11Host -and (HasTool 'operate_window') -and $win0 -and $null -ne $win0.hwnd) {
$owBad = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = 'yes' }
Check 'operate_window dry_run 非布尔返回 -32602' ((ErrCode $owBad) -eq -32602) (Detail $owBad)
$ow = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = $true }
$ows = $ow.result.structuredContent
Check 'operate_window dry_run=true 只校验(window 有值、无 changed)' `
(($null -eq $ow.error) -and ($ows.dry_run -eq $true) -and ($null -ne $ows.window) -and
-not ($ows.PSObject.Properties.Name -contains 'changed')) (Detail $ow)
} else {
Write-Host " operate_window 不可用(或没有可见窗口),跳过该 dry_run 检查。" -ForegroundColor Yellow
}
if ($p11Host -and (HasTool 'host_control_process') -and $null -ne $ppid) {
$hc = Rpc '' $null 'host_control_process' @{ id = $HostId; action = 'freeze'; pid = $ppid; dry_run = $true }
$hcs = $hc.result.structuredContent
Check 'host_control_process dry_run=true 只校验(state/detail,无 changed)' `
(($null -eq $hc.error) -and ($hcs.dry_run -eq $true) -and ([string]$hcs.target -ne '') -and
-not ($hcs.PSObject.Properties.Name -contains 'changed')) (Detail $hc)
} else {
Write-Host " host_control_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
}
# 6c. 观测与取消。参数拒绝 / 空命中先测(不依赖主机),真实取消再单独跑。
$ls0 = Rpc '' $null 'mcp_list_sessions' @{}
Check 'mcp_list_sessions 返回 sessions/count' `
(($null -eq $ls0.error) -and ($null -ne $ls0.result.structuredContent.sessions) -and
([int]$ls0.result.structuredContent.count -eq @($ls0.result.structuredContent.sessions).Count)) (Detail $ls0)
$lsBad = Rpc '' $null 'mcp_list_sessions' @{ kind = 'zzz-no-such-kind' }
Check 'mcp_list_sessions 非法 kind 返回 -32602' ((ErrCode $lsBad) -eq -32602) (Detail $lsBad)
$cnBad = Rpc '' $null 'mcp_cancel_session' @{}
Check 'mcp_cancel_session 缺参数返回 -32602' ((ErrCode $cnBad) -eq -32602) (Detail $cnBad)
$cnNone = Rpc '' $null 'mcp_cancel_session' @{ request_id = 'zzz-no-such-request' }
Check 'mcp_cancel_session 未命中返回 cancelled=0' `
(($null -eq $cnNone.error) -and ([int]$cnNone.result.structuredContent.cancelled -eq 0)) (Detail $cnNone)
# 真实取消:起一个确定会跑够 20s+ 的无副作用调用,等它进了在飞表再取消。
# Windows 主机用 exec_command 跑 ping(白名单内、不需要管理员),其他平台退回 get_keylog。
$longCall = $null
if ($p11Host) {
if ((HasTool 'exec_command') -and $isWindowsHost) {
$longCall = @{ tool = 'exec_command'
args = @{ id = $HostId; command = 'ping -n 25 127.0.0.1'; timeout_ms = 60000 } }
} elseif (HasTool 'get_keylog') {
$longCall = @{ tool = 'get_keylog'; args = @{ id = $HostId; duration_ms = 20000; max_bytes = 4096 } }
}
}
function Wait-Session([string]$rid, [int]$tries = 40) {
# 轮询 mcp_list_sessions 直到出现这次调用(或超时),返回快照项。
for ($i = 0; $i -lt $tries; $i++) {
Start-Sleep -Milliseconds 100
$snap = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
if ($null -eq $snap.error) {
$hit = @($snap.result.structuredContent.sessions | Where-Object { [string]$_.request_id -eq $rid })[0]
if ($hit) { return $hit }
}
}
return $null
}
if (-not $longCall) {
Write-Host " 没有能跑长的工具(exec_command/get_keylog),跳过取消与 SSE 进度检查。" -ForegroundColor Yellow
} else {
$rid = 'p11-cancel-' + (Get-Random -Minimum 1000 -Maximum 9999)
$payload = @{ jsonrpc = '2.0'; id = $rid; method = 'tools/call'
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
ConvertTo-Json -Depth 8 -Compress
$h = Start-RpcAsync $payload
$seen = Wait-Session $rid
Check '在飞调用出现在 mcp_list_sessions 里' ($null -ne $seen) ("request_id=" + $rid)
if (-not $seen) {
$null = Receive-RpcAsync $h
Check '取消测试的前置条件(长调用进入在飞表)' $false '长任务没有进入在飞表,取消路径未验证'
} else {
Check '会话快照字段齐全(host_id/kind/tool/elapsed_ms)' `
((([string]$seen.host_id) -eq $HostId) -and ([string]$seen.kind -eq 'call') -and
([string]$seen.tool -eq $longCall.tool) -and ($null -ne $seen.elapsed_ms)) `
("host_id=" + $seen.host_id + " kind=" + $seen.kind + " tool=" + $seen.tool)
# -32003 的正文要点名占用者(P11 之前只有一句通用话)。它来自「同一主机的一次性
# 待响应请求单飞行」:exec_command 走的是终端子连接,与 list_processes 这类请求
# 并不互斥,所以占用者要用「并发打同一台主机」来制造,而不是拿长调用去当占用者。
if (HasTool 'list_processes') {
$raceHandles = @()
for ($i = 0; $i -lt 8; $i++) {
$raceHandles += Start-RpcAsync (@{ jsonrpc = '2.0'; id = ('race-' + $i); method = 'tools/call'
params = @{ name = 'list_processes'
arguments = @{ id = $HostId; limit = 5 } } } |
ConvertTo-Json -Depth 8 -Compress)
}
$raceErrs = @()
foreach ($rh in $raceHandles) {
$rb = [string](Receive-RpcAsync $rh)
$rj = $null
try { $rj = $rb | ConvertFrom-Json } catch { continue }
if ($null -ne $rj.error) { $raceErrs += $rj }
}
$busy = @($raceErrs | Where-Object { [int]$_.error.code -eq -32003 })[0]
Check '并发请求同一主机时被拒的返回 -32003 且点名占用者' `
(($null -ne $busy) -and ([string]$busy.error.message).Contains('tool=')) `
(($raceErrs | ForEach-Object { [string]$_.error.message }) -join ' | ')
}
$cn = Rpc '' $null 'mcp_cancel_session' @{ request_id = $rid }
$cns = $cn.result.structuredContent
Check 'mcp_cancel_session 按 request_id 取消' `
(($null -eq $cn.error) -and ([int]$cns.cancelled -eq 1)) (Detail $cn)
Check '取消后主机 1s 内释放' `
(($cns.released -eq $true) -and ([int]$cns.waited_ms -le 1000)) `
("released=" + $cns.released + " waited_ms=" + $cns.waited_ms)
$body = [string](Receive-RpcAsync $h)
$jr = $null
try { $jr = $body | ConvertFrom-Json } catch { }
if ($body.Length -gt 160) { $body = $body.Substring(0, 160) }
Check '被取消的请求回 -32800' (($null -ne $jr) -and ($null -ne $jr.error) -and
([int]$jr.error.code -eq -32800)) $body
# 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status
Check '取消后 get_server_status 无挂起(sessions.pending=0)' `
([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending)
if (HasTool 'list_processes') {
$again = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 1 }
Check '取消后主机可再次正常调用' ($null -eq $again.error) (Detail $again)
}
# notifications/cancelled:与 mcp_cancel_session 等价的通知路径(202 无响应体)
$rid2 = 'p11-notify-' + (Get-Random -Minimum 1000 -Maximum 9999)
$payload2 = @{ jsonrpc = '2.0'; id = $rid2; method = 'tools/call'
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
ConvertTo-Json -Depth 8 -Compress
$h2 = Start-RpcAsync $payload2
$seen2 = Wait-Session $rid2
if (-not $seen2) {
$null = Receive-RpcAsync $h2
Check '第二个长调用进入在飞表(通知取消前置)' $false '长任务没有进入在飞表'
} else {
$note = '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"' +
$rid2 + '","reason":"smoke"}}'
$nr = Send-Raw $note $Token
Check 'notifications/cancelled 返回 202' ($nr.Status -eq 202) ("status=" + $nr.Status)
$body2 = [string](Receive-RpcAsync $h2)
$jr2 = $null
try { $jr2 = $body2 | ConvertFrom-Json } catch { }
if ($body2.Length -gt 160) { $body2 = $body2.Substring(0, 160) }
Check '通知取消后请求回 -32800' (($null -ne $jr2) -and ($null -ne $jr2.error) -and
([int]$jr2.error.code -eq -32800)) $body2
# 通知路径没有「等释放」的返回值,只能自己轮询(≤2s)
$freed = $false
for ($i = 0; $i -lt 20 -and -not $freed; $i++) {
$snap3 = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
if (@($snap3.result.structuredContent.sessions |
Where-Object { [string]$_.request_id -eq $rid2 }).Count -eq 0) { $freed = $true }
else { Start-Sleep -Milliseconds 100 }
}
Check '通知取消后 2s 内从在飞表消失' $freed
}
}
}
# 6d. SSE:带 _meta.progressToken 的 tools/call 以 text/event-stream 回应。
# 先用一个立即返回的工具验证传输与收尾(进度天然为 0 条),再用一次真实上传验证进度。
$probe = '{"jsonrpc":"2.0","id":7001,"method":"tools/call","params":{"name":"get_server_status","arguments":{},"_meta":{"progressToken":"smoke-probe"}}}'
$sse = Send-Sse $probe $Token
Check 'SSE:Content-Type 是 text/event-stream' ($sse.ContentType -like 'text/event-stream*') $sse.ContentType
$sseProbeLast = $null
foreach ($line in ($sse.Body -split "`n")) {
if ($line.StartsWith('data: ')) { try { $sseProbeLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
}
Check 'SSE:流末尾是完整 JSON-RPC 响应' `
(($null -ne $sseProbeLast) -and ([string]$sseProbeLast.id -eq '7001') -and
($null -ne $sseProbeLast.result) -and ($null -eq $sseProbeLast.error))
if (-not $p11Host -or -not $FileWriteDir -or -not (HasTool 'upload_file') -or -not (HasTool 'delete_path')) {
Write-Host " 未给 -FileWriteDir 或文件写入工具不可见,跳过 SSE 进度检查(进度 > 0 需一次真实长任务)。" -ForegroundColor Yellow
} else {
# 4 MB 分 64 KB 一片:即使局域网很快也能产生多个进度回调(首个回调不受 1s 节流限制)。
$progLocal = Join-Path $env:TEMP ('mcp_smoke_prog_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.bin')
$fs = [System.IO.File]::Create($progLocal)
$chunk = New-Object byte[] (64 * 1024)
for ($i = 0; $i -lt 64; $i++) { $fs.Write($chunk, 0, $chunk.Length) }
$fs.Close()
$progName = [System.IO.Path]::GetFileName($progLocal)
# 注意:PowerShell 变量名大小写不敏感,别用 $tok —— 会覆盖掉 bearer token $Token。
$progToken = 'smoke-progress-' + (Get-Random -Minimum 1000 -Maximum 9999)
$sseBody = @{ jsonrpc = '2.0'; id = 7002; method = 'tools/call'
params = @{ name = 'upload_file'
arguments = @{ id = $HostId; local_path = $progLocal; remote_dir = $FileWriteDir }
_meta = @{ progressToken = $progToken } } } |
ConvertTo-Json -Depth 10 -Compress
try {
$up = Send-Sse $sseBody $Token
$progCount = ([regex]::Matches($up.Body, [regex]::Escape('notifications/progress'))).Count
Check 'SSE:长任务收到 notifications/progress(计数 > 0)' ($progCount -gt 0) ("count=" + $progCount)
Check 'SSE:进度通知回显 progressToken 且带 progress' `
(($up.Body -match ('"progressToken":"' + [regex]::Escape($progToken) + '"')) -and
($up.Body -match '"progress":'))
$upLast = $null
foreach ($line in ($up.Body -split "`n")) {
if ($line.StartsWith('data: ')) { try { $upLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
}
Check 'SSE:流末尾是 upload_file 的最终响应(未取消)' `
(($null -ne $upLast) -and ([string]$upLast.id -eq '7002') -and
($null -ne $upLast.result) -and ($null -eq $upLast.error))
Check 'SSE 进度测试上传的文件已落盘' ((ListingNames $FileWriteDir) -contains $progName)
} finally {
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($FileWriteDir.TrimEnd('\') + '\' + $progName) }
Remove-Item -LiteralPath $progLocal -Force -ErrorAction SilentlyContinue
}
}
# ===== 汇总 =====
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
if ($script:fail -gt 0) {