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

250 lines
6.4 KiB
Go

package kneron
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"visiona-agent/server/internal/driver"
)
// ResolvePython finds the best Python interpreter for the given script path.
//
// Search order:
// 1. VISIONA_PYTHON env var (highest priority — set by Wails shell when it
// has already provisioned a bundled venv)
// 2. Script-local venv / parent venv
// 3. %APPDATA%\visiona-agent\runtime\venv (Windows installer seeded venv)
// 4. ~/.local/share/visiona-agent/runtime/venv (Linux)
// 5. ~/Library/Application Support/visiona-agent/runtime/venv (macOS)
// 6. Legacy: ~/.edge-ai-platform/venv / %LOCALAPPDATA%\EdgeAIPlatform\venv
// 7. System python3 / python
func ResolvePython(scriptPath string) string {
// 1. Environment variable override (set by Wails shell)
if p := os.Getenv("VISIONA_PYTHON"); p != "" {
if _, err := os.Stat(p); err == nil {
return p
}
}
scriptDir := filepath.Dir(scriptPath)
parentDir := filepath.Dir(scriptDir)
// 2. Script-local / parent venv
var candidates []string
for _, base := range []string{scriptDir, parentDir} {
candidates = append(candidates,
filepath.Join(base, "venv", "bin", "python3"), // Unix
filepath.Join(base, "venv", "Scripts", "python.exe"), // Windows
)
}
// 3-5. Platform-specific data dir (visiona-agent)
if home, err := os.UserHomeDir(); err == nil {
candidates = append(candidates,
// Windows: %APPDATA%\visiona-agent\runtime\venv
filepath.Join(os.Getenv("APPDATA"), "visiona-agent", "runtime", "venv", "Scripts", "python.exe"),
// macOS
filepath.Join(home, "Library", "Application Support", "visiona-agent", "runtime", "venv", "bin", "python3"),
// Linux
filepath.Join(home, ".local", "share", "visiona-agent", "runtime", "venv", "bin", "python3"),
// 6. Legacy edge-ai-platform paths (backwards compat for upgrades)
filepath.Join(home, ".edge-ai-platform", "venv", "bin", "python3"),
filepath.Join(home, ".edge-ai-platform", "venv", "Scripts", "python.exe"),
)
}
// 6b. Legacy %LOCALAPPDATA%\EdgeAIPlatform\venv
if appData := os.Getenv("LOCALAPPDATA"); appData != "" {
candidates = append(candidates,
filepath.Join(appData, "EdgeAIPlatform", "venv", "Scripts", "python.exe"),
)
}
for _, p := range candidates {
if p == "" {
continue
}
if _, err := os.Stat(p); err == nil {
return p
}
}
// 7. Fallback to system python
for _, name := range []string{"python3", "python"} {
if p, err := exec.LookPath(name); err == nil {
return p
}
}
return "python3"
}
// KneronVendorID is the USB vendor ID for Kneron devices.
const KneronVendorID uint16 = 0x3231
// Known Kneron product IDs.
const (
ProductIDKL520 = "0x0100"
ProductIDKL720 = "0x0200"
ProductIDKL720Alt = "0x0720"
)
// chipFromProductID returns the chip name and device type from the product_id
// reported by the Python bridge scan result.
func chipFromProductID(productID string) (chip string, deviceType string) {
pid := strings.ToLower(strings.TrimSpace(productID))
switch pid {
case "0x0100":
return "KL520", "kneron_kl520"
case "0x0200", "0x0720":
return "KL720", "kneron_kl720"
default:
// Unknown product — default to KL520 for USB Boot devices,
// otherwise use the raw product ID as suffix.
return "KL520", "kneron_kl520"
}
}
// DetectDevices attempts to discover all connected Kneron devices (KL520, KL720, etc.)
// by invoking the Python bridge script with a scan command. If Python or
// the bridge script is not available, it returns an empty list.
func DetectDevices(scriptPath string) []driver.DeviceInfo {
// Try to run the bridge script with a scan command via a short-lived process.
pythonBin := ResolvePython(scriptPath)
cmd := exec.Command(pythonBin, scriptPath)
cmd.Stdin = nil
// Ensure libusb-1.0.dll can be found on Windows by adding the binary's
// directory to PATH (the installer places the DLL there).
scriptDir := filepath.Dir(scriptPath)
installDir := filepath.Dir(scriptDir)
cmd.Env = append(os.Environ(),
fmt.Sprintf("PATH=%s;%s;%s", installDir, scriptDir, os.Getenv("PATH")),
)
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return nil
}
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
stdinPipe.Close()
return nil
}
if err := cmd.Start(); err != nil {
return nil
}
defer func() {
stdinPipe.Close()
cmd.Process.Kill()
cmd.Wait()
}()
// Read the ready signal.
decoder := json.NewDecoder(stdoutPipe)
var readyResp map[string]interface{}
done := make(chan error, 1)
go func() {
done <- decoder.Decode(&readyResp)
}()
select {
case err := <-done:
if err != nil {
return nil
}
case <-time.After(5 * time.Second):
return nil
}
if status, ok := readyResp["status"].(string); !ok || status != "ready" {
return nil
}
// Send the scan command.
scanCmd, _ := json.Marshal(map[string]interface{}{"cmd": "scan"})
scanCmd = append(scanCmd, '\n')
if _, err := stdinPipe.Write(scanCmd); err != nil {
return nil
}
// Read the scan response.
var scanResp map[string]interface{}
scanDone := make(chan error, 1)
go func() {
scanDone <- decoder.Decode(&scanResp)
}()
select {
case err := <-scanDone:
if err != nil {
return nil
}
case <-time.After(5 * time.Second):
return nil
}
// Parse detected devices from the response.
devicesRaw, ok := scanResp["devices"].([]interface{})
if !ok || len(devicesRaw) == 0 {
return nil
}
// Track per-chip counters for naming (e.g. "KL520 #1", "KL720 #1").
chipCount := map[string]int{}
var devices []driver.DeviceInfo
for _, devRaw := range devicesRaw {
dev, ok := devRaw.(map[string]interface{})
if !ok {
continue
}
port := ""
if p, ok := dev["port"].(string); ok {
port = p
}
fw := ""
if f, ok := dev["firmware"].(string); ok {
fw = f
}
productID := ""
if p, ok := dev["product_id"].(string); ok {
productID = p
}
chip, devType := chipFromProductID(productID)
chipCount[chip]++
idx := chipCount[chip]
info := driver.DeviceInfo{
ID: fmt.Sprintf("%s-%d", strings.ToLower(chip), idx-1),
Name: fmt.Sprintf("Kneron %s #%d", chip, idx),
Type: devType,
Port: port,
VendorID: KneronVendorID,
Status: driver.StatusDetected,
FirmwareVer: fw,
}
devices = append(devices, info)
}
return devices
}
// DetectKL720Devices is a backward-compatible alias for DetectDevices.
// Deprecated: Use DetectDevices instead.
func DetectKL720Devices(scriptPath string) []driver.DeviceInfo {
return DetectDevices(scriptPath)
}