visionA/local-agent/server/internal/api/ws/hub_broadcast_test.go
jim800121chen 3f0175f1a9 feat(local-agent): Phase 0.5 visionA Agent — Wails 桌面 + tunnel client + 配對 UI
從 local-tool 複製出獨立的「visionA Agent」桌面應用(A3 純橋樑:
tunnel client + 配對 UI + 設定,不開 HTTP port、不做本機裝置/推論 UI)。
Bundle ID 與 local-tool 不同(com.innovedus.visiona-agent vs visiona-local),
雙 app 可共存。fork 後不主動 sync,需要時手動 cherry-pick。

Backend / Wails Go(AB1-AB13):
- internal/tunnel:6 狀態機(Idle/Connecting/Connected/Reconnecting/Failed/Stopped)
  + Pair/Unpair/Reconnect/Disconnect binding + ClientHooks event
- internal/auth:encrypted file token store(AES-GCM + scrypt + machineID
  fallback salt + 13 tests)
- internal/config:YAML validation + atomic write + 11 tests
- internal/log:ring buffer + ExportLog 升級 zip
- visionA-backend /api/pairing/exchange:SessionTokenStore + 17 new tests
- 三平台 build 驗證(macOS DMG 160 MB / Windows EXE / Linux AppImage)
- end-to-end 5 milestone 全綠(pairing → tunnel → forward → reuse 防護
  → tunnel drop failover)

Frontend / Next.js(AF1-AF7,沿用 visionA-frontend 基礎):
- AppShell + Header + TabNav(StatusView / PairView / SettingsView 三 tab)
- ConnectionStatusBadge 5 種狀態
- TokenInput regex 驗證 + 7 種錯誤 + 0.5s auto-switch 到狀態頁
- 設定頁 4 區塊(含重新配對 AlertDialog)
- agent-api.ts 封裝 Wails bindings(mock/real 雙實作)+ 90 tests

Phase 0.7 review-driven fix(Round 2):
- A1 Session fixation 防護(RotateSessionID)
- A3 mock pairing 預設改 false(必須明確 opt-in)+ startup log
- A4 Pair 失敗後 state 清理矩陣(exchange/Save/Start fail 各自終態)
- A5 Pair/Unpair/Reconnect lifecycleMu + 50 goroutine race test
- F1 重新配對次按鈕 / F2 PairView Esc cancel / F3 Wails BrowserOpenURL
  / F4 Settings draft 持久 + 未儲存 badge

驗證:agent backend go test -race -count=3 ./... 4 packages 全綠 /
agent frontend pnpm test 119 tests 全綠

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 11:22:01 +08:00

133 lines
3.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ws
// hub_broadcast_test.go — MAJ-4 補丁:驗證 Hub.BroadcastToRoom 在 system room 的行為
//
// 涵蓋:
// 1. 多個 client 都收到同一則訊息
// 2. 空 room無 client不 panic、不 block
// 3. client send channel 滿時不 block hub會 drop 該 client
import (
"encoding/json"
"testing"
"time"
)
// makeRegisteredClient 註冊一個 buffered send channel 的 dummy client 到指定 room。
func makeRegisteredClient(h *Hub, room string, bufSize int) *Client {
c := &Client{Send: make(chan []byte, bufSize)}
h.RegisterSync(&Subscription{Client: c, Room: room})
return c
}
func TestHub_BroadcastToRoom_MultipleClients(t *testing.T) {
hub := NewHub()
go hub.Run()
c1 := makeRegisteredClient(hub, "system", 4)
c2 := makeRegisteredClient(hub, "system", 4)
c3 := makeRegisteredClient(hub, "system", 4)
payload := map[string]interface{}{
"type": "server:shutdown-imminent",
"reason": "quit",
"ts": int64(1234567890),
}
hub.BroadcastToRoom("system", payload)
for i, c := range []*Client{c1, c2, c3} {
select {
case msg := <-c.Send:
var got map[string]interface{}
if err := json.Unmarshal(msg, &got); err != nil {
t.Fatalf("client %d bad json: %v", i, err)
}
if got["type"] != "server:shutdown-imminent" || got["reason"] != "quit" {
t.Errorf("client %d wrong payload: %+v", i, got)
}
case <-time.After(500 * time.Millisecond):
t.Fatalf("client %d did not receive broadcast within 500ms", i)
}
}
}
func TestHub_BroadcastToRoom_EmptyRoom(t *testing.T) {
hub := NewHub()
go hub.Run()
// 無 client 註冊在 "system" room → BroadcastToRoom 應該 no-op 且不 panic
done := make(chan struct{})
go func() {
defer close(done)
hub.BroadcastToRoom("system", map[string]string{"type": "server:shutdown-imminent"})
}()
select {
case <-done:
// OK
case <-time.After(500 * time.Millisecond):
t.Fatalf("BroadcastToRoom with empty room blocked > 500ms")
}
}
func TestHub_BroadcastToRoom_FullChannelDoesNotBlock(t *testing.T) {
hub := NewHub()
go hub.Run()
// buffer = 1 的 slow client先塞滿 → hub 接著 broadcast 時會打到 default case
// select 非 blocking sendhub goroutine 必須仍能繼續處理後續訊息。
//
// 同時註冊一個 healthy client 觀察hub 沒被卡住的證據 = healthy client 仍能收到訊息。
slow := makeRegisteredClient(hub, "system", 1)
slow.Send <- []byte("pre-existing") // 塞滿 slow 的 buffer
healthy := makeRegisteredClient(hub, "system", 4)
// 先量 broadcast 的時間,若 hub 被 slow client 卡住,這行會 block 直到 test timeout
done := make(chan struct{})
go func() {
defer close(done)
hub.BroadcastToRoom("system", map[string]string{"type": "server:shutdown-imminent"})
}()
select {
case <-done:
// OK — broadcast 沒 block
case <-time.After(500 * time.Millisecond):
t.Fatalf("BroadcastToRoom blocked — slow client 未被 drop")
}
// healthy client 必須收到訊息(證明 hub goroutine 沒被 slow client 卡住)
select {
case msg := <-healthy.Send:
var got map[string]interface{}
if err := json.Unmarshal(msg, &got); err != nil {
t.Fatalf("healthy client bad json: %v", err)
}
if got["type"] != "server:shutdown-imminent" {
t.Errorf("healthy client wrong payload: %+v", got)
}
case <-time.After(500 * time.Millisecond):
t.Fatalf("healthy client did not receive broadcast — hub 被 slow client 卡住")
}
// 再次 broadcast 驗證 hub 持續工作slow 已被 dropbroadcast 仍該回來)
done2 := make(chan struct{})
go func() {
defer close(done2)
hub.BroadcastToRoom("system", map[string]string{"type": "server:shutdown-imminent", "n": "2"})
}()
select {
case <-done2:
// OK
case <-time.After(500 * time.Millisecond):
t.Fatalf("second BroadcastToRoom blocked")
}
// healthy 應收到第二則
select {
case <-healthy.Send:
case <-time.After(500 * time.Millisecond):
t.Fatalf("healthy client 未收到第二則")
}
}