Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

companion: address follow-up review findings

Barack Sokullu56202d43edea
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.go
index ebfe61f45..3b0f9b5e8 100644
--- a/webbrain-systray/internal/app/app.go
+++ b/webbrain-systray/internal/app/app.go
@@ -476,11 +476,29 @@ func (a *App) SetPort(port int) error {
if port < 1024 || port > 65535 {
return errors.New("choose a port between 1024 and 65535")
}
+ previous := a.Store.Get()
+ previousPort := a.Proxy.Port()
+ panelOpen := a.listeners() > 0
s, err := a.Store.Update(func(s *settings.Settings) { s.Port = port })
if err != nil {
return err
}
- return a.restartProxy(s)
+ if err := a.restartProxy(s); err != nil {
+ restored, saveErr := a.Store.Update(func(s *settings.Settings) { s.Port = previous.Port })
+ restorePort := previousPort
+ if restorePort == 0 {
+ restorePort = previous.Port
+ }
+ restartErr := a.restartOn(restored, restorePort, previousPort != 0)
+ if restartErr == nil {
+ a.setNotice(fmt.Sprintf(i18n.T("port_failed"), port, a.Proxy.Port()))
+ if panelOpen && a.OpenPanel != nil {
+ go a.OpenPanel("")
+ }
+ }
+ return errors.Join(err, saveErr, restartErr)
+ }
+ return nil
}
func (a *App) restartProxy(s settings.Settings) error {
diff --git a/webbrain-systray/internal/app/port_test.go b/webbrain-systray/internal/app/port_test.go
new file mode 100644
index 000000000..3be333261
--- /dev/null
+++ b/webbrain-systray/internal/app/port_test.go
@@ -0,0 +1,45 @@
+package app
+
+import (
+ "net"
+ "strings"
+ "testing"
+
+ "github.com/esokullu/webbrain-systray/internal/paths"
+ "github.com/esokullu/webbrain-systray/internal/settings"
+)
+
+func TestSetPortRestoresWorkingProxyWhenLastPortIsOccupied(t *testing.T) {
+ t.Setenv("WBC_HOME", t.TempDir())
+ if err := paths.Ensure(); err != nil {
+ t.Fatal(err)
+ }
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := New("test", store)
+ if err := a.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer a.Shutdown()
+ previous := store.Get().Port
+ active := a.Proxy.Port()
+ busy, err := net.Listen("tcp", "127.0.0.1:65535")
+ if err != nil {
+ t.Skipf("port 65535 is unavailable: %v", err)
+ }
+ defer busy.Close()
+ if err := a.SetPort(65535); err == nil {
+ t.Fatal("SetPort should fail when port 65535 is occupied")
+ }
+ if got := store.Get().Port; got != previous {
+ t.Fatalf("saved port = %d, want previous %d", got, previous)
+ }
+ if !a.Proxy.Running() || a.Proxy.Port() != active {
+ t.Fatalf("proxy stopped or moved after failed port change: running=%v port=%d, want %d", a.Proxy.Running(), a.Proxy.Port(), active)
+ }
+ if !strings.Contains(a.Snapshot().Notice, "65535") {
+ t.Fatal("panel has no notice explaining the rejected port")
+ }
+}
diff --git a/webbrain-systray/internal/d1/manager.go b/webbrain-systray/internal/d1/manager.go
index 520963d32..335d45643 100644
--- a/webbrain-systray/internal/d1/manager.go
+++ b/webbrain-systray/internal/d1/manager.go
@@ -96,6 +96,14 @@ func ortLibPath() string {
return filepath.Join(ortDir(), filepath.FromSlash(a.lib))
}
+type ortMarker struct {
+ ArchiveSHA string `json:"archive_sha"`
+ LibrarySize int64 `json:"library_size"`
+ LibrarySHA string `json:"library_sha"`
+}
+
+func ortMarkerPath() string { return filepath.Join(ortDir(), ".installed") }
+
type Status struct {
Model string `json:"model"`
Phase string `json:"phase"`
@@ -125,18 +133,11 @@ type Manager struct {
cancel context.CancelFunc
eng *engine
evalMu sync.Mutex
- verifyMu sync.Mutex
- verified map[string]verifiedFile
+ verified download.Verifier
requests int64
latency float64
}
-type verifiedFile struct {
- size int64
- modTime time.Time
- sha string
-}
-
func NewManager(store *settings.Store, onChange func()) *Manager {
return &Manager{store: store, onChange: onChange, phase: PhaseIdle}
}
@@ -152,48 +153,57 @@ func okFile(path string, size int64) bool {
return err == nil && st.Size() == size
}
-// validFile checks the pinned hash once per unchanged file in this process.
-// Status calls this often, so rehashing the 1.9 GB model on every refresh
-// would make the panel unusable.
func (m *Manager) validFile(path string, size int64, sha string) bool {
- m.verifyMu.Lock()
- defer m.verifyMu.Unlock()
- st, err := os.Stat(path)
- if err != nil || !st.Mode().IsRegular() || st.Size() != size {
- delete(m.verified, path)
+ return m.verified.Valid(path, size, sha)
+}
+
+// The library may exist after an interrupted extraction. Only a marker
+// written after the full extraction and verified against the library makes
+// this runtime usable.
+func (m *Manager) ortReady(asset ortAsset) bool {
+ data, err := os.ReadFile(ortMarkerPath())
+ if err != nil {
return false
}
- if sha == "" {
- return true
+ var marker ortMarker
+ if json.Unmarshal(data, &marker) != nil || marker.ArchiveSHA != asset.sha || marker.LibrarySize <= 0 || marker.LibrarySHA == "" {
+ return false
}
- if v, ok := m.verified[path]; ok && v.size == size && v.modTime.Equal(st.ModTime()) && v.sha == sha {
- return true
+ return m.validFile(ortLibPath(), marker.LibrarySize, marker.LibrarySHA)
+}
+
+func (m *Manager) markORT(asset ortAsset) error {
+ path := ortLibPath()
+ st, err := os.Stat(path)
+ if err != nil || !st.Mode().IsRegular() || st.Size() == 0 {
+ return errors.New("ONNX Runtime library missing from the archive")
}
- delete(m.verified, path)
f, err := os.Open(path)
if err != nil {
- return false
+ return err
}
h := sha256.New()
_, err = io.Copy(h, f)
_ = f.Close()
- if err != nil || !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), sha) {
- return false
+ if err != nil {
+ return err
}
- after, err := os.Stat(path)
- if err != nil || after.Size() != size || !after.ModTime().Equal(st.ModTime()) {
- return false
+ marker := ortMarker{ArchiveSHA: asset.sha, LibrarySize: st.Size(), LibrarySHA: hex.EncodeToString(h.Sum(nil))}
+ data, err := json.Marshal(marker)
+ if err != nil {
+ return err
}
- if m.verified == nil {
- m.verified = make(map[string]verifiedFile)
+ tmp := ortMarkerPath() + ".tmp"
+ if err := os.WriteFile(tmp, data, 0o600); err != nil {
+ return err
}
- m.verified[path] = verifiedFile{size: size, modTime: st.ModTime(), sha: sha}
- return true
+ return os.Rename(tmp, ortMarkerPath())
}
// Installed reports whether the model files and runtime are present.
func (m *Manager) Installed() bool {
- if _, ok := ortForPlatform(); !ok {
+ asset, ok := ortForPlatform()
+ if !ok || !m.ortReady(asset) {
return false
}
for _, f := range modelFiles {
@@ -201,8 +211,7 @@ func (m *Manager) Installed() bool {
return false
}
}
- _, err := os.Stat(ortLibPath())
- return err == nil
+ return true
}
func (m *Manager) Status() Status {
@@ -222,7 +231,7 @@ func (m *Manager) Status() Status {
st.DownloadBytes += rem
}
if a, ok := ortForPlatform(); ok {
- if _, err := os.Stat(ortLibPath()); err != nil {
+ if !m.ortReady(a) {
st.DownloadBytes += a.size
}
}
@@ -308,7 +317,7 @@ func (m *Manager) install(ctx context.Context, asset ortAsset) error {
filepath.Join(modelDir(), filepath.FromSlash(f.name)), f.size, f.sha})
}
archive := filepath.Join(paths.Runtimes(), "_downloads", asset.archive)
- needORT := !okFileAny(ortLibPath())
+ needORT := !m.ortReady(asset)
if needORT {
items = append(items, item{"ONNX Runtime " + ortVersion, "https://github.com/microsoft/onnxruntime/releases/download/v" + ortVersion + "/" + asset.archive,
archive, asset.size, asset.sha})
@@ -346,7 +355,9 @@ func (m *Manager) install(ctx context.Context, asset ortAsset) error {
}
if needORT {
m.set(PhaseInstalling, "Unpacking ONNX Runtime", nil)
- _ = os.RemoveAll(ortDir())
+ if err := os.RemoveAll(ortDir()); err != nil {
+ return fmt.Errorf("replace ONNX Runtime: %w", err)
+ }
keep := func(rel string) bool {
// Only the runtime libraries: skip headers, symbols (a 430 MB .pdb) and test data.
if !strings.HasPrefix(rel, "lib/") || strings.Contains(rel, ".dSYM") {
@@ -360,19 +371,14 @@ func (m *Manager) install(ctx context.Context, asset ortAsset) error {
if runtime.GOOS == "darwin" {
trustMac(ortDir())
}
- if !okFileAny(ortLibPath()) {
- return errors.New("ONNX Runtime library missing from the archive")
+ if err := m.markORT(asset); err != nil {
+ return err
}
_ = os.Remove(archive)
}
return nil
}
-func okFileAny(p string) bool {
- st, err := os.Stat(p)
- return err == nil && !st.IsDir()
-}
-
// Load creates the ONNX Runtime sessions (about 2 GB of memory).
func (m *Manager) Load() error {
m.evalMu.Lock()
diff --git a/webbrain-systray/internal/d1/manager_files_test.go b/webbrain-systray/internal/d1/manager_files_test.go
index 5fa41bf97..94c2d6bd4 100644
--- a/webbrain-systray/internal/d1/manager_files_test.go
+++ b/webbrain-systray/internal/d1/manager_files_test.go
@@ -40,3 +40,34 @@ func TestValidFileRejectsSameSizeCorruption(t *testing.T) {
t.Fatal("changed file reused a previous successful checksum")
}
}
+
+func TestORTRuntimeNeedsCompletedExtraction(t *testing.T) {
+ asset, ok := ortForPlatform()
+ if !ok {
+ t.Skip("no runtime archive for this platform")
+ }
+ t.Setenv("WBC_HOME", t.TempDir())
+ path := ortLibPath()
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("complete runtime"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ m := NewManager(nil, nil)
+ if m.ortReady(asset) {
+ t.Fatal("library without completed-extraction marker was accepted")
+ }
+ if err := m.markORT(asset); err != nil {
+ t.Fatal(err)
+ }
+ if !m.ortReady(asset) {
+ t.Fatal("marked runtime was rejected")
+ }
+ if err := os.WriteFile(path, []byte("short"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if m.ortReady(asset) {
+ t.Fatal("truncated runtime was accepted")
+ }
+}
diff --git a/webbrain-systray/internal/download/verifier.go b/webbrain-systray/internal/download/verifier.go
new file mode 100644
index 000000000..7c7f0c9a1
--- /dev/null
+++ b/webbrain-systray/internal/download/verifier.go
@@ -0,0 +1,49 @@
+package download
+
+import (
+ "os"
+ "sync"
+ "time"
+)
+
+type verifiedFile struct {
+ size int64
+ modTime time.Time
+ sha string
+}
+
+// Verifier checks a pinned file's SHA-256 once per unchanged file in a
+// process. Status snapshots can then check multi-gigabyte models cheaply.
+type Verifier struct {
+ mu sync.Mutex
+ valid map[string]verifiedFile
+}
+
+func (v *Verifier) Valid(path string, size int64, sha string) bool {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ st, err := os.Stat(path)
+ if err != nil || !st.Mode().IsRegular() || (size > 0 && st.Size() != size) {
+ delete(v.valid, path)
+ return false
+ }
+ if sha == "" {
+ return true
+ }
+ if cached, ok := v.valid[path]; ok && cached.size == st.Size() && cached.modTime.Equal(st.ModTime()) && cached.sha == sha {
+ return true
+ }
+ delete(v.valid, path)
+ if ok, _ := verify(path, sha); !ok {
+ return false
+ }
+ after, err := os.Stat(path)
+ if err != nil || !after.Mode().IsRegular() || after.Size() != st.Size() || !after.ModTime().Equal(st.ModTime()) {
+ return false
+ }
+ if v.valid == nil {
+ v.valid = make(map[string]verifiedFile)
+ }
+ v.valid[path] = verifiedFile{size: st.Size(), modTime: st.ModTime(), sha: sha}
+ return true
+}
diff --git a/webbrain-systray/internal/i18n/i18n.go b/webbrain-systray/internal/i18n/i18n.go
index e9e2143dc..8f0e1160d 100644
--- a/webbrain-systray/internal/i18n/i18n.go
+++ b/webbrain-systray/internal/i18n/i18n.go
@@ -25,6 +25,7 @@ var catalog = map[string]map[string]string{
"dur_hours": "%dh %02dm",
"dur_minutes": "%dm",
"port_moved": "Another app (often CLIProxyAPI or EasyCLIProxyAPI) uses port %d, so the companion runs on %d. Use the address shown here in WebBrain.",
+ "port_failed": "Port %d is unavailable. The companion is still running on port %d.",
"network_failed": "Network access stays off: another app uses port %d on the network. Pick another port in Settings and try again.",
},
"tr": {
@@ -43,6 +44,7 @@ var catalog = map[string]map[string]string{
"dur_hours": "%d sa %02d dk",
"dur_minutes": "%d dk",
"port_moved": "%d portunu başka bir uygulama (çoğu zaman CLIProxyAPI ya da EasyCLIProxyAPI) kullanıyor, bu yüzden Companion %d portunda çalışıyor. WebBrain'de burada gösterilen adresi kullan.",
+ "port_failed": "%d portu kullanılamıyor. Companion hâlâ %d portunda çalışıyor.",
"network_failed": "Ağ erişimi kapalı kaldı: %d portunu ağda başka bir uygulama kullanıyor. Ayarlar'dan başka bir port seçip tekrar dene.",
},
}
diff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.go
index b9e46ea6d..6f94257b3 100644
--- a/webbrain-systray/internal/localmodel/manager.go
+++ b/webbrain-systray/internal/localmodel/manager.go
@@ -60,6 +60,7 @@ type Status struct {
type Manager struct {
mu sync.Mutex
+ verified download.Verifier
store *settings.Store
register func([]core.LocalUpstream) error
onChange func()
@@ -73,6 +74,7 @@ type Manager struct {
plan Plan
cancel context.CancelFunc
cmd *exec.Cmd
+ starting chan struct{} // closed after Start either publishes cmd or fails
exited chan struct{}
stopping bool
stopErr error // why the server was stopped, when it was not the user
@@ -131,15 +133,15 @@ func fileOK(path string, size int64) bool {
return err == nil && !st.IsDir() && (size <= 0 || st.Size() == size)
}
-func ggufInstalled(p Plan) bool {
- return fileOK(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size) &&
- fileOK(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size) &&
+func (m *Manager) ggufInstalled(p Plan) bool {
+ return m.verified.Valid(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size, gguf.Model.SHA256) &&
+ m.verified.Valid(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size, gguf.Proj.SHA256) &&
fileOK(filepath.Join(runtimeDir(p), ".installed"), 0)
}
-func mlxInstalled() bool {
+func (m *Manager) mlxInstalled() bool {
for _, f := range mlxPack.Files {
- if !fileOK(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size) {
+ if !m.verified.Valid(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size, f.SHA256) {
return false
}
}
@@ -159,8 +161,8 @@ func dirSize(dir string) int64 {
return n
}
-func remaining(path string, size int64) int64 {
- if fileOK(path, size) {
+func (m *Manager) remaining(path string, size int64, sha string) int64 {
+ if m.verified.Valid(path, size, sha) {
return 0
}
if st, err := os.Stat(path + ".part"); err == nil && st.Size() < size {
@@ -179,17 +181,17 @@ func (m *Manager) Status() Status {
st := Status{
ModelID: ModelID, ModelName: ModelName, Vendor: ModelVendor, PageURL: ModelPageURL,
Format: format, Formats: Formats(info), Plan: plan,
- Installed: map[string]bool{"gguf": ggufInstalled(MakePlan(info, s.Local, "gguf"))},
+ Installed: map[string]bool{"gguf": m.ggufInstalled(MakePlan(info, s.Local, "gguf"))},
AutoStart: s.Local.AutoStart,
VisionMode: s.Local.Vision,
System: info, SystemSummary: info.Summary(),
}
if info.AppleSilicon {
- st.Installed["mlx"] = mlxInstalled()
+ st.Installed["mlx"] = m.mlxInstalled()
}
if format == "gguf" {
- st.DownloadBytes = remaining(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size) +
- remaining(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size)
+ st.DownloadBytes = m.remaining(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size, gguf.Model.SHA256) +
+ m.remaining(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size, gguf.Proj.SHA256)
if !fileOK(filepath.Join(runtimeDir(plan), ".installed"), 0) {
for _, a := range plan.Assets {
st.DownloadBytes += llamaAssetSizes[a]
@@ -198,7 +200,7 @@ func (m *Manager) Status() Status {
st.DiskBytes = dirSize(ggufDir())
} else {
for _, f := range mlxPack.Files {
- st.DownloadBytes += remaining(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size)
+ st.DownloadBytes += m.remaining(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size, f.SHA256)
}
st.DiskBytes = dirSize(mlxDir())
}
@@ -303,13 +305,13 @@ func (m *Manager) Cancel() {
func (m *Manager) fetchAll(ctx context.Context, items []item) error {
var total, done int64
for _, it := range items {
- total += remaining(it.dest, it.size)
+ total += m.remaining(it.dest, it.size, it.sha)
}
for _, it := range items {
- if fileOK(it.dest, it.size) && it.sha == "" {
+ if m.verified.Valid(it.dest, it.size, it.sha) {
continue
}
- before := it.size - remaining(it.dest, it.size)
+ before := it.size - m.remaining(it.dest, it.size, it.sha)
step := it.label
if fileOK(it.dest, it.size) {
step = "Verifying " + it.label // complete file: download.File only re-checks its SHA-256
@@ -490,18 +492,34 @@ func freePort(preferred int) int {
// Start launches the local server for the selected format and registers it
// with the proxy once it answers.
-func (m *Manager) Start() error {
+func (m *Manager) Start() (startErr error) {
info := sysinfo.Get()
s := m.store.Get()
format := m.format(info)
plan := MakePlan(info, s.Local, format)
m.mu.Lock()
- if m.cmd != nil {
+ if m.cmd != nil || m.starting != nil {
m.mu.Unlock()
return nil
}
+ starting := make(chan struct{})
+ m.starting = starting
+ m.phase, m.step, m.err = PhaseStarting, "Preparing the local model", ""
m.mu.Unlock()
+ m.changed()
+ defer func() {
+ m.mu.Lock()
+ m.starting = nil
+ if startErr != nil {
+ m.phase, m.step, m.err = PhaseError, "", startErr.Error()
+ }
+ close(starting)
+ m.mu.Unlock()
+ if startErr != nil {
+ m.changed()
+ }
+ }()
port := freePort(max(s.Local.Port, 18081))
var (
@@ -511,7 +529,7 @@ func (m *Manager) Start() error {
)
switch format {
case "mlx":
- if !mlxInstalled() {
+ if !m.mlxInstalled() {
return errors.New("the MLX pack is not installed")
}
py := filepath.Join(mlxVenv(), "bin", "python")
@@ -521,7 +539,7 @@ func (m *Manager) Start() error {
cmd.Env = append(os.Environ(), "HF_HOME="+filepath.Join(paths.Runtimes(), "hf-home"), "HF_HUB_OFFLINE=1")
health = fmt.Sprintf("http://127.0.0.1:%d/v1/models", port)
default:
- if !ggufInstalled(plan) {
+ if !m.ggufInstalled(plan) {
return errors.New("the GGUF model or its runtime is not installed")
}
bin := findBinary(runtimeDir(plan), "llama-server")
@@ -639,6 +657,12 @@ func (m *Manager) waitForExit(cmd *exec.Cmd, exited chan struct{}) {
// Stop terminates the local server.
func (m *Manager) Stop() {
m.mu.Lock()
+ if starting := m.starting; starting != nil {
+ m.mu.Unlock()
+ <-starting
+ m.Stop()
+ return
+ }
cmd, exited := m.cmd, m.exited
m.stopping = true
if cmd != nil {
diff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.go
index 15414fbb9..680014784 100644
--- a/webbrain-systray/internal/localmodel/manager_test.go
+++ b/webbrain-systray/internal/localmodel/manager_test.go
@@ -1,13 +1,17 @@
package localmodel
import (
+ "crypto/sha256"
+ "encoding/hex"
"os"
+ "path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/esokullu/webbrain-systray/internal/core"
"github.com/esokullu/webbrain-systray/internal/osutil"
+ "github.com/esokullu/webbrain-systray/internal/settings"
)
func TestLocalModelExitHelper(t *testing.T) {
@@ -16,6 +20,97 @@ func TestLocalModelExitHelper(t *testing.T) {
}
}
+func TestStartClaimPreventsOverlappingLaunches(t *testing.T) {
+ t.Setenv("WBC_HOME", t.TempDir())
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := NewManager(store, func([]core.LocalUpstream) error { return nil }, nil)
+ starting := make(chan struct{})
+ m.starting = starting // first launch has claimed Start but not published cmd
+ if err := m.Start(); err != nil {
+ t.Fatalf("overlapping Start should reuse the pending launch: %v", err)
+ }
+ stopped := make(chan struct{})
+ go func() {
+ m.Stop()
+ close(stopped)
+ }()
+ select {
+ case <-stopped:
+ t.Fatal("Stop returned before the in-flight Start settled")
+ case <-time.After(25 * time.Millisecond):
+ }
+ m.mu.Lock()
+ m.starting = nil
+ m.mu.Unlock()
+ close(starting)
+ select {
+ case <-stopped:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Stop did not finish after Start settled")
+ }
+}
+
+func TestGGUFInstalledRejectsSameSizeCorruption(t *testing.T) {
+ t.Setenv("WBC_HOME", t.TempDir())
+ previous := gguf
+ defer func() { gguf = previous }()
+ hash := func(data []byte) string {
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:])
+ }
+ weights, projector := []byte("weights"), []byte("projector")
+ gguf.Model = File{Name: "weights.gguf", Size: int64(len(weights)), SHA256: hash(weights)}
+ gguf.Proj = File{Name: "projector.gguf", Size: int64(len(projector)), SHA256: hash(projector)}
+ if err := os.MkdirAll(ggufDir(), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ weightPath := filepath.Join(ggufDir(), gguf.Model.Name)
+ projectorPath := filepath.Join(ggufDir(), gguf.Proj.Name)
+ if err := os.WriteFile(weightPath, weights, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(projectorPath, projector, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ plan := Plan{Assets: []string{"llama-test.tar.gz"}}
+ if err := os.MkdirAll(runtimeDir(plan), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(runtimeDir(plan), ".installed"), []byte("ready"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ m := NewManager(nil, nil, nil)
+ if !m.ggufInstalled(plan) {
+ t.Fatal("valid cached weights and projector were rejected")
+ }
+ bad := []byte("Weights")
+ if err := os.WriteFile(weightPath, bad, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ modified := time.Now().Add(time.Minute)
+ if err := os.Chtimes(weightPath, modified, modified); err != nil {
+ t.Fatal(err)
+ }
+ if m.ggufInstalled(plan) || m.remaining(weightPath, gguf.Model.Size, gguf.Model.SHA256) != gguf.Model.Size {
+ t.Fatal("same-sized corrupt weights were reported as installed")
+ }
+ if err := os.WriteFile(weightPath, weights, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(projectorPath, []byte("Projector"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(projectorPath, modified, modified); err != nil {
+ t.Fatal(err)
+ }
+ if m.ggufInstalled(plan) {
+ t.Fatal("same-sized corrupt projector was reported as installed")
+ }
+}
+
func TestStopWaitsForExitCleanup(t *testing.T) {
executable, err := os.Executable()
if err != nil {