A fresh shop PC could never authenticate to its own engine

The agent read the engine's generated credential file once, at startup.
On a brand new install that file does not exist yet: the agent starts the
engine, and the engine writes its credential seconds later. So the agent
held an empty credential for the life of the process and every call it
makes - health, stats, camera sync, the embedding for a visit - came back
401, with a tray showing a red engine that was running perfectly.

Measured on a fresh state directory today: three 401s, no camera ever
reconciled, and the engine left running the YAML-seeded main stream
instead of the sub-stream head office holds. The install script hid this
on Windows because setup runs the engine once before the app starts.

config.Creds resolves lazily and re-reads on a rejection; the camera
client, the supervisor and the desktop app's engine client all retry once
when it changes. A configured BEHAVISION_API_USER is never re-read - an
operator who set one means it. Tests pin the actual first-run ordering.

Also adds demo/, a one-screen live console for showing the whole chain:
camera, the six steps with a measured camera-to-cloud latency, the
customer editable in place, and the raw JSON a phone and a dashboard
receive from production side by side.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KGcjxF1cNLcuwc3DAPcnfj
This commit is contained in:
2026-09-24 13:40:28 +05:30
parent 9062d2fc51
commit 16f0e69cec
10 changed files with 758 additions and 11 deletions

View File

@@ -25,6 +25,8 @@ import (
"strconv"
"strings"
"sync"
"github.com/loyaly/behavision-agent/pkg/config"
"time"
)
@@ -59,6 +61,9 @@ type Options struct {
// no captured output is undiagnosable, which on a customer site means a
// site visit.
LogWriter io.Writer
// Creds re-reads the engine's generated credential when one is rejected,
// which is the ordinary case on a first run.
Creds *config.Creds
// HealthURL, StatsURL, User, Password address the engine's own API.
HealthURL string
StatsURL string
@@ -409,14 +414,24 @@ func (s *Supervisor) getJSON(ctx context.Context, url string, out any) error {
if err != nil {
return err
}
if s.opts.User != "" {
req.SetBasicAuth(s.opts.User, s.opts.Password)
user, pass := s.opts.User, s.opts.Password
if s.opts.Creds != nil {
user, pass = s.opts.Creds.Get()
}
if user != "" {
req.SetBasicAuth(user, pass)
}
resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized && s.opts.Creds != nil && s.opts.Creds.Refresh() {
// See cameras.EngineClient: on a fresh install the engine writes its
// credential after the agent has already read for one.
resp.Body.Close()
return s.getJSON(ctx, url, out)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s returned %s", url, resp.Status)
}