diff --git a/CLAUDE.md b/CLAUDE.md index 26bae0c..aa71b0d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,8 @@ ETTerms 是一個 **C# .NET 8 WinForms** 的原生 Windows 終端機工作台, **進度:** Phase 1–5 ✅、Phase 6 ✅(TTL 引擎 + Group 同步,SSH 待驗收)、Phase 7 ✅(Settings/About)、Phase 8 ✅(PDU + Shell/ConPTY + SFTP + Settings 擴充)、Phase 9 ✅(Serial MCP server:**GUI 持有 COM port,MCP 經本機 named pipe 橋接**,AI 收發的資料即時以 `[AI]` 標色顯示在 GUI)、**Phase 10 ✅(v0.6.0)內建 AI Assistant**(見下)。打包待指示。 +**v0.7.1:** 新增 TTL 指令 **`sendlnretry '文字' '確認關鍵字' [最多送出次數]`**(`TTLInterpreter.SendLnRetry` + `WaitConfirm`)——送出後等確認關鍵字,沒等到就**重送**;次數省略 = 無限重送,命中 `result=1`、用完次數 `result=0` 且**繼續執行**(不中止腳本)。**動機**:裝置開機、console 剛被 shell 接手的瞬間會丟棄輸入(tty 重開 / termios flush),`sendln` 送出的整行無聲消失(裝置不回顯、不執行),後面的 `wait` 就永遠卡住;這是機率性的,`pause` 只能調機率、無法根治(實測 45 輪 power-cycle 中 3 輪中招,且**中招時間點與成功時完全重疊**)。**為何需要新指令而非用 `wait` 重試**:單字串 `wait` 逾時是 throw 中止腳本(刻意設計,見下方「注意事項」),TeraTerm 的 `wait`→`if result = 0 then goto retry` 重送寫法在 ETTerms 寫不出來。**語意**:每次送出前清空 `_recv`(確保比對到的是這次送出的回應);命中只消費到**第一次**出現處,後續輸出留給接下來的 `wait`;刻意**不套 `SettleAndConsume` 的 settle**(關鍵字出現本身就證明裝置收到了);每次等待逾時 `timeout`/`mtimeout` 有設就用設定值、**沒設預設 3 秒**(此處 0=無限等於永不重送,故不沿用 `wait` 的 0=無限)。⚠️ 確認關鍵字要挑「命令真的有跑」的輸出,**不要挑指令回顯**——tty echo 由核心產生,不保證命令被 shell 讀走。文件:[docs/ttl-script-reference.md](docs/ttl-script-reference.md#送出並確認sendlnretry)。 + **v0.7.0:** **AI Chat 改用 WebView2 渲染**(真氣泡 + Markdown + thinking 動畫泡)。訊息區從 RichTextBox 換成 `WebView2`:user 右泡 / AI 左泡、AI 回覆走 **Markdig** markdown→HTML(程式碼區塊/表格/清單)、送出後顯示會動的 thinking「…」泡(`AgentHost.Status "thinking"` → `showThinking()`,收到 `AssistantText` 時 `hideThinking()` 再加 AI 泡)。HTML 模板全內嵌於 `Ai/ChatHtml.cs`(`NavigateToString`,無外部依賴),C# 經 `ExecuteScriptAsync` 呼叫 JS 函式;WebView2 async 初始化,就緒前的呼叫先入 `_pending` 佇列、`NavigationCompleted` 後 flush。使用者資料夾 `%LocalAppData%\ETTerms\WebView2`(避開 Program Files 唯讀)。底部控制列(輸入框/模型下拉/Send)仍 WinForms。新增 NuGet `Microsoft.Web.WebView2` + `Markdig`;依賴 WebView2 Runtime(Win11 內建,缺時 hint 顯示錯誤)。⚠️ **publish 要確認 WebView2 native(`runtimes/win-x64/native/WebView2Loader.dll`)有進產物**。**工具呼叫上限可設定**(`AppSettings.AiMaxToolRounds`,Settings → AI Assistant,`AgentHost` 建構子傳入):**0 = 無上限**(自動化長跑;每輪燒 token,聊天視窗 Send 鈕在執行中變 **Stop**,經 `CancellationToken` 中止),預設 30。 **v0.6.0:** **內建 AI Assistant(Phase 10)** — 不經 Claude / Kiro,GUI 內建 ✨ AI 聊天**分頁**,自然語言驅動 serial + PDU。**AI 是 Workspace 的一種 pane**(工具列 `✨ AI Chat` 開啟,`WorkspaceView.Session` 抽象化為可容納 `SessionPage` 或 `AiChatView` 的 `Content`),可用 Layout 與 serial 分頁**並排同時用**(像 Claude/Kiro);AI 分頁無 Group/Log/Script。**UI 走乾淨逐字稿風**(user 靠右 accent、AI 靠左、工具灰字、thinking 收進 Send 按鈕不洗版;與終端機美學一致,非氣泡——真氣泡+Markdown 的 WebView2 版列 v0.7.0)。**模型下拉**(右下角)打端點 `/v1/models` 列可選模型、即時切換並記住;**Settings 只留 Base URL / API Key / 系統提示詞,不再設 model**(`configured` 只看 Base URL)。**BYO endpoint**:`Settings → AI Assistant` 填 Base URL / Model / API Key(任意 OpenAI 相容 gateway:本機 Ollama、LiteLLM、公司 gateway、OpenAI…),**預設全空白=功能停用**;🚫 **發佈版不含任何私人端點**,API key 存 Windows Credential Manager(`ETTerms/AiApiKey`)、Base URL/Model 存 settings.json,程式碼範例一律 `localhost`/假 IP。**架構(in-process,不經 MCP)**:`Ai/OpenAiChatClient`(極簡 OpenAI 相容 `/chat/completions`,HttpClient 非串流)+ `Ai/AgentHost`(手寫 agent loop,tool_calls→執行→role=tool 餵回→迴圈上限 8 輪)+ `Ai/AiTools`(serial list/attach/write/read 經 `SerialBridge`——與 MCP 同一路徑、AI 的 TX 照樣 `[AI]` 標色顯示在終端機;PDU connect/status/set_port/power_cycle 經 `ETTerms.PduCore`)。**安全**:破壞性 PDU 動作(關插座 / power-cycle)一律 `AiTools.ConfirmAsync` → GUI MessageBox(預設 No)確認,AI 不能自己斷電;每筆工具呼叫寫 AppLogger(`[AI tool] …`)。**刻意不引入 `Microsoft.Extensions.AI`**(手寫 client+loop,依賴最小、對任意 gateway 相容性自己掌控)。既有 SerialMcp/PduMcp(Settings → AI MCP)**不受影響**,繼續服務外部 AI CLI;兩者是「內建 agent(in-process)vs 外部 AI(MCP 跨行程)」的分工。新增 `src/ETTerms/Ai/`(3 檔)+ `App/AiChatView.cs`,`ActivityRail` 加 `Ai` view,`SettingsView` 加 AI Assistant 分頁,`AppSettings` 加 `AiBaseUrl/AiModel/AiSystemPrompt`。 diff --git a/docs/release-notes/v0.7.1.md b/docs/release-notes/v0.7.1.md new file mode 100644 index 0000000..60bc10e --- /dev/null +++ b/docs/release-notes/v0.7.1.md @@ -0,0 +1,59 @@ +# v0.7.1 — Scripts stop losing commands to a booting device + +## ✨ New features + +**`sendlnretry` — send a command, confirm it ran, resend if it didn't** +* New TTL command: `sendlnretry '' '' [max attempts]`. + It sends the text, then **waits for proof the device actually ran it**, and **resends** if that + proof never arrives. Leave the attempt count out and it retries until it gets through. +* Drop it in wherever you send a command right after a boot — the fragile + `pause` + `sendln` + `wait` dance becomes one line: + + ``` + wait 'root@(none):/#' + sendlnretry 'tpm2' 'TPM 2p0' ; retry until the device really runs it + wait 'PASS' + ``` +* Cap the attempts and handle the failure yourself — on success `result` is **1**; + when the attempts run out `result` is **0** and **the script carries on** instead of dying: + + ``` + sendlnretry 'tpm2' 'TPM 2p0' 3 + if result = 0 then + dispstr 'tpm2 got no response after 3 tries' + endif + ``` +* Pick the confirm keyword from the command's **own output** (`TPM 2p0`), not its echo (`tpm2`) — + an echo is produced by the device's tty and doesn't prove the shell ever read the line. +* Each attempt waits **3 seconds** by default, or your `timeout` / `mtimeout` if you've set one. + (Unlike `wait`, `0` doesn't mean "wait forever" here — that would mean never retrying.) + +## 🐛 Bug fixes + +**Scripts no longer hang forever when a booting device swallows a command** +* Fixed: a device that is still booting can **silently discard console input** the moment its shell + takes over the tty. The line you sent is gone — the device never echoes it and never runs it — + so the `wait` that follows blocks forever and the test rig sits dead until someone notices. +* This is a race, not a delay: adding `pause` before `sendln` only lowers the odds of hitting the + window, it can never close it. In one overnight 45-cycle power-cycle run, **3 cycles hung this + way** — and the swallowed sends landed at exactly the same moment as the 42 that worked. +* Use the new `sendlnretry` above to make these sends reliable. + +## 📦 Downloads + +Two builds are produced: + +| Build | Needs .NET 8 Desktop Runtime? | Notes | +|-------|-------------------------------|-------| +| **Standard** (`ETTerms_v0.7.1`) | ✅ Yes | Smaller; for machines that already have the runtime | +| **Portable** (`ETTerms_v0.7.1_portable`) | ❌ No | Runtime bundled — unzip and run, no install / admin needed | + +Run `ETTerms v0.7.1.exe`. + +## 🔗 Links +* TTL reference (see **送出並確認 / sendlnretry**): + [docs/ttl-script-reference.md](https://github.com/ETWen/ETTerms/blob/main/docs/ttl-script-reference.md) +* Architecture: + [ARCHITECTURE.md](https://github.com/ETWen/ETTerms/blob/main/ARCHITECTURE.md) + +**Full changelog:** [v0.7.0...v0.7.1](https://github.com/ETWen/ETTerms/compare/v0.7.0...v0.7.1) diff --git a/docs/ttl-script-reference.md b/docs/ttl-script-reference.md index 3b65077..c5bdc11 100644 --- a/docs/ttl-script-reference.md +++ b/docs/ttl-script-reference.md @@ -43,6 +43,42 @@ # 一、ETTerms 獨有指令 +## 送出並確認(sendlnretry) + +| 指令 | 語法 | 說明 | +|------|------|------| +| `sendlnretry` | `sendlnretry '文字' '確認關鍵字' [最多送出次數]` | 送出 `文字` + `\r\n`,然後等 `確認關鍵字`;沒等到就**重送**。次數省略 = 一直重送到收到為止。命中 `result=1`;用完次數 `result=0` 且**繼續執行**(不中止腳本)。 | + +**為什麼需要它**:裝置在開機、console 剛被 shell 接手的瞬間,可能把收到的輸入直接丟掉 +(tty 重開 / termios flush)。此時 `sendln` 送出的整行會**無聲無息地消失**——裝置不會回顯、 +也不會執行,後面的 `wait` 就永遠等不到,腳本整個卡死。這是**機率性**的: +在 `sendln` 前面加 `pause` 只是降低撞上那個窗口的機率,**不可能根治**。 +`sendlnretry` 的作法是送完就確認對方真的有反應,沒反應就再送一次。 + +``` +; 開機後下 tpm2,沒跑到就自動重送(無限重送) +wait 'root@(none):/#' +sendlnretry 'tpm2' 'TPM 2p0' +wait 'PASS' + +; 最多送 3 次,還是不行就自己處置 +sendlnretry 'tpm2' 'TPM 2p0' 3 +if result = 0 then + dispstr 'tpm2 送了 3 次都沒反應' +endif +``` + +使用要點: + +- **確認關鍵字要挑「命令真的有跑」才會出現的輸出**(例:`TPM 2p0`), + **不要挑指令回顯**(例:`tpm2`)——tty 的 echo 由核心產生,不保證命令有被 shell 讀走。 +- **每次送出前會清空接收緩衝**,確保比對到的是「這次送出」的回應而不是殘留輸出。 + 命中後只消費到**第一次**出現處,後面的輸出留在緩衝裡給接下來的 `wait` 用 + (所以上例的 `wait 'PASS'` 照常會等到)。 +- 每次送出後等確認的逾時:`timeout`/`mtimeout` 有設就用設定值,**沒設預設 3 秒** + (注意這與 `wait` 不同——`wait` 的 0 是無限等,但無限等在這裡等於永不重送)。 +- **指令最好是可重複執行的**:若逾時設得太短、而裝置其實只是回應慢,會造成同一個指令送兩次。 + ## Group 同步(多分頁協同) 以下指令**只能在 Run Group 模式**下使用(toolbar 的 `▶ Group1-3`)。 @@ -89,7 +125,7 @@ wait 'login:' | 項目 | ETTerms 行為 | |------|--------------| -| `wait`(**單字串**) | 命中後需裝置**安靜 300ms**(無新資料)才接受,並取「最後一次」出現——排除輸出中途的指令回顯(如 `SVOS> help`)造成腳本搶跑。**逾時會中止腳本**(TeraTerm 是 `result=0` 繼續)。 | +| `wait`(**單字串**) | 命中後需裝置**安靜 300ms**(無新資料)才接受,並取「最後一次」出現——排除輸出中途的指令回顯(如 `SVOS> help`)造成腳本搶跑。**逾時會中止腳本**(TeraTerm 是 `result=0` 繼續),因此 TeraTerm 常見的 `wait` → `if result = 0 then goto retry` 重送寫法在單字串 `wait` 上做不到;要「送出後確認、沒回應就重送」請用 [`sendlnretry`](#送出並確認sendlnretry)。 | | `wait`(**多字串**) | TeraTerm 相容:任一命中即繼續,`result` = 第幾個字串(1 起算);逾時 `result=0` **繼續執行**、無 settle。 | | `goto` / 跨區塊跳轉 | `goto` 跳出 `if`/`while` 區塊後,該區塊的迴圈控制即結束(同層繼續直行)。避免 goto 跳「進」區塊中間。 | | `call` | 可以在迴圈 / if 內使用(行內執行,返回後迴圈續跑)。 | diff --git a/src/ETTerms/App/AboutView.cs b/src/ETTerms/App/AboutView.cs index 7d98841..9ee958e 100644 --- a/src/ETTerms/App/AboutView.cs +++ b/src/ETTerms/App/AboutView.cs @@ -183,6 +183,14 @@ public sealed class AboutView : UserControl private static readonly ChangelogEntry[] Changelog = [ + new("0.7.1", new DateOnly(2026, 7, 16), "Scripts no longer hang when a booting device swallows a command", + [ + "Fixed: a device that is still booting can silently throw away what you send it, the moment its shell takes over the console — the line never echoes and never runs, so the wait after it sat there forever and your test rig was dead until someone noticed. Adding a pause before the send only made it rarer: in one overnight 45-cycle power-cycle run, 3 cycles still hung this way.", + "New scripting command: sendlnretry '' '' [max attempts] — it sends, waits for proof the device actually ran the command, and sends again if that proof never arrives. Leave the attempt count out and it keeps trying until it gets through.", + "Use it anywhere you currently send a command right after a boot: sendlnretry 'tpm2' 'TPM 2p0' followed by wait 'PASS'. Pick the confirm keyword from the command's own output, not its echo — an echo comes from the device's tty and doesn't prove the command was ever read.", + "If it runs out of attempts, result is 0 and the script carries on, so you can handle the failure yourself. Each attempt waits 3 seconds, or your timeout / mtimeout if you've set one.", + "See docs/ttl-script-reference.md for the full details.", + ]), new("0.7.0", new DateOnly(2026, 7, 5), "AI chat gets real bubbles, Markdown & a thinking indicator", [ "The AI Chat pane now renders proper chat bubbles (your messages on the right, the AI's on the left) with full Markdown — code blocks, tables, lists and inline `code` all display nicely.", diff --git a/src/ETTerms/ETTerms.csproj b/src/ETTerms/ETTerms.csproj index 6c80eb1..58f18ca 100644 --- a/src/ETTerms/ETTerms.csproj +++ b/src/ETTerms/ETTerms.csproj @@ -10,7 +10,7 @@ ETTerms - 0.7.0 + 0.7.1 ETTerms ETTerms Project diff --git a/src/ETTerms/Scripting/TTLInterpreter.cs b/src/ETTerms/Scripting/TTLInterpreter.cs index a7c7115..ebd5360 100644 --- a/src/ETTerms/Scripting/TTLInterpreter.cs +++ b/src/ETTerms/Scripting/TTLInterpreter.cs @@ -33,6 +33,7 @@ public sealed class TTLInterpreter : IDisposable private const int SettleMs = 300; // wait 命中關鍵字後,需連續安靜這麼久(無新資料)才接受,避免比對到輸出中途的回顯 private const int MaxRecvChars = 1_000_000; // _recv 上限:長時間無 wait 消費時避免無限成長 + private const int SendRetryTimeoutMs = 3000; // sendlnretry 每次送出後等確認關鍵字的預設逾時(timeout/mtimeout 有設就以設定值為準) private GroupSyncContext? _groupSync; private string _groupMemberLabel = ""; @@ -193,6 +194,7 @@ public sealed class TTLInterpreter : IDisposable // ── 通訊 ── case "send": Send(args, false); break; case "sendln": Send(args, true); break; + case "sendlnretry": SendLnRetry(TokenizeArgs(args)); break; case "wait": DispatchWait(args); break; case "waitln": WaitLn(TokenizeArgs(args)); break; case "waitregex": WaitRegex(TokenizeArgs(args)); break; @@ -740,6 +742,92 @@ public sealed class TTLInterpreter : IDisposable Output?.Invoke($">> {text}"); } + /// + /// sendlnretry '文字' '確認關鍵字' [最多送出次數] + /// —— 送出後確認裝置真的收到;沒等到確認關鍵字就重送。次數省略 = 一直重送到收到為止。 + /// 命中 result = 1;用完次數 result = 0 且**繼續執行**(不中止腳本,讓腳本自行處置)。 + /// 存在理由:裝置在開機/console 剛接手的瞬間可能丟棄輸入(tty 重開 / flush), + /// 此時 sendln 送出的整行會被吃掉、後面的 wait 便永遠等不到, + /// 而任何固定長度的 pause 都只是在調機率、無法根治。 + /// 每次送出前會清空接收緩衝,確保比對到的是「這次送出」的回應而非殘留輸出; + /// 命中後只消費到**第一次**出現處為止,後續輸出留在緩衝裡給接下來的 wait 用。 + /// 確認關鍵字請挑「命令真的有跑」才會出現的輸出,不要挑指令回顯—— + /// tty 的 echo 不保證命令有被 shell 讀走。 + /// + private void SendLnRetry(List tokens) + { + if (tokens.Count < 2) + { + Output?.Invoke("[ttl] sendlnretry: 用法 sendlnretry '文字' '確認關鍵字' [最多送出次數]"); + return; + } + + string text = ValS(tokens[0]); + string confirm = ValS(tokens[1]); + if (confirm.Length == 0) + { + Output?.Invoke("[ttl] sendlnretry: 確認關鍵字不可為空"); + return; + } + + int maxAttempts = tokens.Count > 2 ? ValI(tokens[2]) : 0; // 省略 / <= 0 = 無限 + int perTryMs = EffectiveTimeoutMs > 0 ? EffectiveTimeoutMs : SendRetryTimeoutMs; + + for (int attempt = 1; maxAttempts <= 0 || attempt <= maxAttempts; attempt++) + { + ThrowIfCancelled(); + + lock (_recv) _recv.Clear(); // 只認這次送出之後的回應 + _channel.Write(_enc.GetBytes(text + "\r\n")); + _logWriter?.WriteLine($">> {text}"); + Output?.Invoke(attempt == 1 ? $">> {text}" : $">> {text} (attempt {attempt})"); + + if (WaitConfirm(confirm, perTryMs)) + { + _result = 1; + if (attempt > 1) _logWriter?.WriteLine($"[sendlnretry] '{text}' 於第 {attempt} 次送出後確認"); + return; + } + + Output?.Invoke($"[sendlnretry] {perTryMs}ms 內未見 '{confirm}' — 重送"); + _logWriter?.WriteLine($"[sendlnretry] no '{confirm}' after attempt {attempt}: {text}"); + } + + _result = 0; + Output?.Invoke($"[sendlnretry] 送出 {maxAttempts} 次仍未確認 '{confirm}' — 放棄(result = 0)"); + _logWriter?.WriteLine($"[sendlnretry] gave up after {maxAttempts} attempt(s): {text}"); + } + + /// 等確認關鍵字出現,逾時回 false(不丟例外、不中止腳本)。 + /// 刻意不套 的 settle:關鍵字「有出現」本身就證明裝置收到了, + /// 且只消費到第一次出現處,後面的輸出要留給後續的 wait。 + private bool WaitConfirm(string text, int timeoutMs) + { + int elapsed = 0, lastLen = -1; + while (elapsed < timeoutMs) + { + ThrowIfCancelled(); + lock (_recv) + { + if (_recv.Length != lastLen) + { + lastLen = _recv.Length; + string buf = _recv.ToString(); + int idx = buf.IndexOf(text, StringComparison.Ordinal); + if (idx >= 0) + { + _recv.Clear(); + _recv.Append(buf[(idx + text.Length)..]); + return true; + } + } + } + Thread.Sleep(50); + elapsed += 50; + } + return false; + } + private int EffectiveTimeoutMs => _timeout + _mtimeout; // 0 = 無限 private void DispatchWait(string args)