From 69b29c44dec5996405851dbe054190076976b91a Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 11 Nov 2026 21:47:50 -0500 Subject: [PATCH 01/35] improve go test coverage --- .../responses_test.go | 76 ++++++-- gui/internal/config/store_test.go | 3 +- gui/internal/httpjson/httpjson_test.go | 164 ++++++++++++++++++ 3 files changed, 223 insertions(+), 20 deletions(-) create mode 100644 gui/internal/httpjson/httpjson_test.go diff --git a/gui/cmd/ssl-vision-processor-gui/responses_test.go b/gui/cmd/ssl-vision-processor-gui/responses_test.go index ee5749f..884f369 100644 --- a/gui/cmd/ssl-vision-processor-gui/responses_test.go +++ b/gui/cmd/ssl-vision-processor-gui/responses_test.go @@ -9,29 +9,69 @@ import ( "testing" ) +// checkedGETs is each JSON GET route's spec path and a request for it that +// answers 200 from testServer. +var checkedGETs = map[string]string{ + "/api/health": "/api/health", + "/api/topics": "/api/topics", + "/api/network": "/api/network", + "/api/alerts": "/api/alerts", + "/api/schema": "/api/schema", + "/api/config": "/api/config", + "/api/config/files": "/api/config/files", + "/api/config/cameras/{id}/effective": "/api/config/cameras/0/effective", + "/api/geometry": "/api/geometry", + "/api/geometry/presets": "/api/geometry/presets", + "/api/live_field": "/api/live_field", + "/api/camera/devices": "/api/camera/devices", + "/api/snapshots": "/api/snapshots", + "/api/processes": "/api/processes", + "/api/instances": "/api/instances", + "/api/system": "/api/system", + "/api/logs": "/api/logs", +} + +// notJSON are the GET routes whose 200 isn't a JSON body. +var notJSON = []string{"/api/snapshot/{camID}/{view}", "/ws", "/ws/video/{id}"} + +// A new GET route has to be added to checkedGETs (or notJSON), so its +// responses get checked against the spec too. +func TestEveryGETRouteIsChecked(t *testing.T) { + data, err := openapiSpec() + if err != nil { + t.Fatal(err) + } + + var spec struct { + Paths map[string]map[string]json.RawMessage + } + if err := json.Unmarshal(data, &spec); err != nil { + t.Fatal(err) + } + + for path, ops := range spec.Paths { + if _, ok := ops["get"]; !ok { + continue + } + + if _, ok := checkedGETs[path]; !ok && !slices.Contains(notJSON, path) { + t.Errorf("GET %s isn't in checkedGETs: add a request for it", path) + } + } + + for path := range checkedGETs { + if _, ok := spec.Paths[path]["get"]; !ok { + t.Errorf("checkedGETs has %s, which the spec has no GET for", path) + } + } +} + // The spec says which values can be null and which strings are enums; real // responses must agree, or the generated frontend types would lie. func TestResponsesMatchTheSpec(t *testing.T) { h, _ := testServer(t) - for path, target := range map[string]string{ - "/api/health": "/api/health", - "/api/topics": "/api/topics", - "/api/network": "/api/network", - "/api/alerts": "/api/alerts", - "/api/schema": "/api/schema", - "/api/config": "/api/config", - "/api/config/files": "/api/config/files", - "/api/config/cameras/{id}/effective": "/api/config/cameras/0/effective", - "/api/geometry/presets": "/api/geometry/presets", - "/api/live_field": "/api/live_field", - "/api/camera/devices": "/api/camera/devices", - "/api/snapshots": "/api/snapshots", - "/api/processes": "/api/processes", - "/api/instances": "/api/instances", - "/api/system": "/api/system", - "/api/logs": "/api/logs", - } { + for path, target := range checkedGETs { rec := do(t, h, http.MethodGet, target, nil) if rec.Code != http.StatusOK { t.Errorf("GET %s = %d", target, rec.Code) diff --git a/gui/internal/config/store_test.go b/gui/internal/config/store_test.go index 0cfd65a..2f623f6 100644 --- a/gui/internal/config/store_test.go +++ b/gui/internal/config/store_test.go @@ -503,8 +503,7 @@ func TestAnEditCantChangeFirstRun(t *testing.T) { doc, rev := s.Working() doc.FirstRun = false - rev, err := s.Update(rev, doc) - if err != nil { + if _, err := s.Update(rev, doc); err != nil { t.Fatal(err) } diff --git a/gui/internal/httpjson/httpjson_test.go b/gui/internal/httpjson/httpjson_test.go new file mode 100644 index 0000000..1fdd34e --- /dev/null +++ b/gui/internal/httpjson/httpjson_test.go @@ -0,0 +1,164 @@ +package httpjson + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" +) + +func TestStatusOfEveryCodeAndAnUnknownOne(t *testing.T) { + for code, want := range statuses { + if got := StatusOf(code); got != want { + t.Errorf("StatusOf(%q) = %d, want %d", code, got, want) + } + } + + if got := StatusOf("no_such_code"); got != http.StatusInternalServerError { + t.Errorf("StatusOf(unknown) = %d, want 500", got) + } +} + +// The enum tag is what the spec, and so the frontend's generated types, offer +// as error codes; it has to list exactly the codes the host can answer with. +func TestErrorBodyEnumMatchesTheCodes(t *testing.T) { + field, _ := reflect.TypeFor[ErrorBody]().FieldByName("Error") + enum := strings.Split(field.Tag.Get("enum"), ",") + + codes := make([]string, 0, len(statuses)) + for code := range statuses { + codes = append(codes, code) + } + + slices.Sort(enum) + slices.Sort(codes) + + if !slices.Equal(enum, codes) { + t.Errorf("ErrorBody enum = %v, codes with a status = %v", enum, codes) + } +} + +func TestErrorfFormatsAProblem(t *testing.T) { + p := Errorf(CodeInvalid, "cameras[%d]: %s", 2, "missing") + + if p.Code != CodeInvalid || p.Message != "cameras[2]: missing" || p.Error() != p.Message { + t.Errorf("Errorf = %+v", p) + } +} + +func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Errorf("Content-Type = %q", ct) + } + + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body %q: %v", rec.Body.String(), err) + } + + return body +} + +func TestErrorWritesTheEnvelope(t *testing.T) { + rec := httptest.NewRecorder() + Error(rec, http.StatusBadRequest, CodeInvalid, "rejected", "a: bad", "b: bad") + + if rec.Code != http.StatusBadRequest { + t.Errorf("status = %d", rec.Code) + } + + body := decodeBody(t, rec) + if body["error"] != CodeInvalid || body["message"] != "rejected" { + t.Errorf("body = %v", body) + } + + if issues, _ := body["issues"].([]any); len(issues) != 2 { + t.Errorf("issues = %v", body["issues"]) + } +} + +func TestErrorWithoutIssuesOmitsThem(t *testing.T) { + rec := httptest.NewRecorder() + Error(rec, http.StatusNotFound, CodeNotFound, "gone") + + if _, ok := decodeBody(t, rec)["issues"]; ok { + t.Errorf("issues present: %s", rec.Body.String()) + } +} + +func TestNotFoundNamesTheRequest(t *testing.T) { + rec := httptest.NewRecorder() + NotFound().ServeHTTP(rec, httptest.NewRequest(http.MethodDelete, "/api/nope", nil)) + + body := decodeBody(t, rec) + if rec.Code != http.StatusNotFound || body["error"] != CodeNotFound || body["message"] != "no such endpoint: DELETE /api/nope" { + t.Errorf("%d %v", rec.Code, body) + } +} + +type target struct { + Name string `json:"name"` +} + +func decode(contentType, body string, types ...string) (*httptest.ResponseRecorder, target, bool) { + r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + if contentType != "" { + r.Header.Set("Content-Type", contentType) + } + + rec := httptest.NewRecorder() + + var v target + ok := Decode(rec, r, &v, types...) + + return rec, v, ok +} + +func TestDecodeAcceptsJSONWithParameters(t *testing.T) { + rec, v, ok := decode("application/json; charset=utf-8", `{"name":"cam0"}`) + + if !ok || v.Name != "cam0" || rec.Body.Len() != 0 { + t.Errorf("ok=%v v=%+v body=%q", ok, v, rec.Body.String()) + } +} + +func TestDecodeRejects(t *testing.T) { + for _, tc := range []struct { + name, contentType, body string + types []string + status int + code string + }{ + {"no content type", "", `{"name":"x"}`, nil, http.StatusUnsupportedMediaType, CodeUnsupportedMedia}, + {"form", "application/x-www-form-urlencoded", `name=x`, nil, http.StatusUnsupportedMediaType, CodeUnsupportedMedia}, + {"not one of the given types", "application/json", `{}`, []string{"application/merge-patch+json"}, http.StatusUnsupportedMediaType, CodeUnsupportedMedia}, + {"malformed", "application/json", `{"name":`, nil, http.StatusBadRequest, CodeBadRequest}, + {"unknown field", "application/json", `{"nmae":"x"}`, nil, http.StatusBadRequest, CodeBadRequest}, + {"two values", "application/json", `{"name":"a"} {"name":"b"}`, nil, http.StatusBadRequest, CodeBadRequest}, + {"empty", "application/json", ``, nil, http.StatusBadRequest, CodeBadRequest}, + } { + t.Run(tc.name, func(t *testing.T) { + rec, _, ok := decode(tc.contentType, tc.body, tc.types...) + if ok { + t.Fatal("accepted") + } + + if body := decodeBody(t, rec); rec.Code != tc.status || body["error"] != tc.code { + t.Errorf("%d %v, want %d %s", rec.Code, body, tc.status, tc.code) + } + }) + } +} + +func TestDecodeAcceptsAGivenType(t *testing.T) { + _, v, ok := decode("application/merge-patch+json", `{"name":"x"}`, "application/merge-patch+json") + + if !ok || v.Name != "x" { + t.Errorf("ok=%v v=%+v", ok, v) + } +} From dc00deabb9ea88dbe93f4981e496fed0d737c4a6 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 11 Nov 2026 21:48:30 -0500 Subject: [PATCH 02/35] coverage tooling, bump deps --- gui/frontend/.gitignore | 3 + gui/frontend/package-lock.json | 242 +++++++++++++++++++++++++++++---- gui/frontend/package.json | 2 + gui/frontend/vite.config.ts | 12 ++ 4 files changed, 229 insertions(+), 30 deletions(-) diff --git a/gui/frontend/.gitignore b/gui/frontend/.gitignore index 56fba93..3713577 100644 --- a/gui/frontend/.gitignore +++ b/gui/frontend/.gitignore @@ -30,3 +30,6 @@ dist-ssr # Playwright (make e2e) test-results/ playwright-report/ + +# Vitest coverage (npm run test:coverage) +coverage/ diff --git a/gui/frontend/package-lock.json b/gui/frontend/package-lock.json index d58c28a..e88b1c7 100644 --- a/gui/frontend/package-lock.json +++ b/gui/frontend/package-lock.json @@ -21,6 +21,7 @@ "@tailwindcss/vite": "^4.3.3", "@tsconfig/svelte": "^5.0.8", "@types/node": "^24.12.3", + "@vitest/coverage-v8": "^5.1.0", "eslint": "^10.3.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-svelte": "^3.17.1", @@ -102,6 +103,16 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-validator-identifier": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", @@ -112,6 +123,46 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@bramus/specificity": { "version": "2.4.3", "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", @@ -1702,23 +1753,89 @@ "typescript": "*" } }, + "node_modules/@vitest/coverage-v8": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.0.tgz", + "integrity": "sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^2.1.0", + "@vitest/istanbul-lib-report": "^2.1.0", + "ast-v8-to-istanbul": "^1.0.7", + "magicast": "^0.5.5", + "obug": "^3.0.0", + "std-env": "^4.3.0", + "tinyrainbow": "^3.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "5.1.0", + "vitest": "5.1.0" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/@vitest/istanbul-lib-coverage": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.0.tgz", + "integrity": "sha512-WOjuS+xcjSIy7ruYBQ+9BUcV7XZQ0FyVcbWbWxW9TRx/kLGx5SQaeFRIFDJxjNplb6YsT7SpKo2zuXXUo91OIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/istanbul-lib-report": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.0.tgz", + "integrity": "sha512-+ZFta25nWtGCOBG9/IET8w1RO5Oawsd6H8Uf6AJ9EA/StFuKVtKAEJEJ6uRt84OH+T4YkI0ASmIHAhRA+0KVxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/istanbul-lib-coverage": "2.1.0" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@vitest/mocker": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz", - "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", "dev": true, "license": "MIT", "dependencies": { "@jridgewell/trace-mapping": "0.3.31", - "@vitest/spy": "5.0.3", + "@vitest/spy": "5.1.0", "estree-walker": "^3.0.3", - "magic-string": "^1.2.3" + "magic-string": "^1.4.3" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "msw": "^2.4.9", + "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { @@ -1741,9 +1858,9 @@ } }, "node_modules/@vitest/mocker/node_modules/magic-string": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", - "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, "license": "MIT", "dependencies": { @@ -1751,9 +1868,9 @@ } }, "node_modules/@vitest/spy": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz", - "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", "dev": true, "license": "MIT", "funding": { @@ -1851,6 +1968,35 @@ "node": ">=12" } }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/axobject-query": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", @@ -3189,6 +3335,18 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, "node_modules/mdn-data": { "version": "2.27.1", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", @@ -4009,9 +4167,9 @@ } }, "node_modules/tinybench": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.1.tgz", - "integrity": "sha512-IAbQaPJIIdhVxi0mqy9lez1wEwje0UQf9F1vwtbelEG5Nbgn0nPOxCvU+mNeNS9gyJTAhrHp74CbUaSynQpZcQ==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, "license": "MIT", "engines": { @@ -4045,6 +4203,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tldts": { "version": "7.4.16", "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz", @@ -4315,23 +4483,23 @@ } }, "node_modules/vitest": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz", - "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", "dev": true, "license": "MIT", "dependencies": { "@types/chai": "^5.2.2", - "@vitest/mocker": "5.0.3", - "chai": "^6.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", - "magic-string": "^1.2.3", - "obug": "^2.1.4", + "magic-string": "^1.4.3", + "obug": "^3.0.0", "picomatch": "^4.0.7", - "std-env": "^4.2.0", - "tinybench": "^6.1.4", - "tinyexec": "^1.3.0", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, @@ -4348,12 +4516,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "5.0.3", - "@vitest/browser-preview": "5.0.3", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", - "@vitest/coverage-istanbul": "5.0.3", - "@vitest/coverage-v8": "5.0.3", - "@vitest/ui": "5.0.3", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" @@ -4407,6 +4575,20 @@ "@jridgewell/sourcemap-codec": "^1.6.0" } }, + "node_modules/vitest/node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/w3c-xmlserializer": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", diff --git a/gui/frontend/package.json b/gui/frontend/package.json index b020aaa..293d811 100644 --- a/gui/frontend/package.json +++ b/gui/frontend/package.json @@ -16,6 +16,7 @@ "format": "prettier --write .", "format:check": "prettier --check .", "test": "vitest run", + "test:coverage": "vitest run --coverage", "test:e2e": "playwright test", "gen:api": "openapi-typescript ../openapi.json -o src/lib/generated/api.ts --array-length --alphabetize --default-non-nullable false" }, @@ -27,6 +28,7 @@ "@tailwindcss/vite": "^4.3.3", "@tsconfig/svelte": "^5.0.8", "@types/node": "^24.12.3", + "@vitest/coverage-v8": "^5.1.0", "eslint": "^10.3.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-svelte": "^3.17.1", diff --git a/gui/frontend/vite.config.ts b/gui/frontend/vite.config.ts index 5430d0d..942f919 100644 --- a/gui/frontend/vite.config.ts +++ b/gui/frontend/vite.config.ts @@ -49,6 +49,18 @@ export default defineConfig({ environment: "jsdom", include: ["src/**/*.test.ts", "scripts/**/*.test.mjs"], setupFiles: ["src/test-setup.ts"], + // npm run test:coverage: a report, not a gate. + coverage: { + provider: "v8", + include: ["src/**/*.{ts,svelte}"], + exclude: [ + "src/**/*.test.ts", + "src/proto/**", + "src/lib/generated/**", + "src/test-setup.ts", + ], + reporter: ["text-summary", "text", "html"], + }, }, build: { // One bundle on purpose: the host serves it over the local network, so From 03954796c7354be31401006121059b60904422e8 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 11 Nov 2026 21:48:55 -0500 Subject: [PATCH 03/35] frontend unit tests --- gui/frontend/src/lib/cameraRanges.test.ts | 66 ++++ gui/frontend/src/lib/color.test.ts | 267 +++++++++++++++ gui/frontend/src/lib/config.test.ts | 400 ++++++++++++++++++++++ gui/frontend/src/lib/fieldSplit.test.ts | 111 ++++++ gui/frontend/src/lib/layout/nav.test.ts | 195 +++++++++++ gui/frontend/src/lib/live/draw.test.ts | 229 +++++++++++++ gui/frontend/src/lib/logs/hostLog.test.ts | 164 +++++++++ gui/frontend/src/lib/network.test.ts | 301 ++++++++++++++++ gui/frontend/src/lib/util.test.ts | 23 ++ gui/frontend/src/lib/wrapper-bus.test.ts | 236 +++++++++++++ 10 files changed, 1992 insertions(+) create mode 100644 gui/frontend/src/lib/cameraRanges.test.ts create mode 100644 gui/frontend/src/lib/color.test.ts create mode 100644 gui/frontend/src/lib/config.test.ts create mode 100644 gui/frontend/src/lib/fieldSplit.test.ts create mode 100644 gui/frontend/src/lib/layout/nav.test.ts create mode 100644 gui/frontend/src/lib/live/draw.test.ts create mode 100644 gui/frontend/src/lib/logs/hostLog.test.ts create mode 100644 gui/frontend/src/lib/network.test.ts create mode 100644 gui/frontend/src/lib/util.test.ts create mode 100644 gui/frontend/src/lib/wrapper-bus.test.ts diff --git a/gui/frontend/src/lib/cameraRanges.test.ts b/gui/frontend/src/lib/cameraRanges.test.ts new file mode 100644 index 0000000..7847bf3 --- /dev/null +++ b/gui/frontend/src/lib/cameraRanges.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import { CAMERA_RANGES, toDisplay, toFile, type Range } from "./cameraRanges"; + +const range = (scale: number): Range => ({ + min: 0, + max: 100, + step: 1, + unit: "", + scale, + fallback: 1, +}); + +// Whether value is a whole number of steps above min, within float error. +function onStep(r: Range, value: number): boolean { + const steps = (value - r.min) / r.step; + return Math.abs(steps - Math.round(steps)) < 1e-9; +} + +describe("unit conversion", () => { + it("multiplies by the scale into the file and divides back out", () => { + expect(toFile(range(1000), 5)).toBe(5000); + expect(toDisplay(range(1000), 5000)).toBe(5); + }); + + it("rounds away float noise", () => { + expect(toFile(range(0.001), 166)).toBe(0.166); + expect(toDisplay(range(3), 1)).toBe(0.333333); + }); + + it("round-trips a display value", () => { + for (const scale of [1, 0.001, 1000, 0.01]) + for (const v of [0, 0.5, 7, 166, 20000]) + expect(toDisplay(range(scale), toFile(range(scale), v))).toBe(v); + }); +}); + +describe("CAMERA_RANGES", () => { + const cases = Object.entries(CAMERA_RANGES).flatMap(([driver, ranges]) => + Object.entries(ranges).map( + ([setting, r]) => [`${driver}.${setting}`, r] as [string, Range], + ), + ); + + it.each(cases)("%s is a usable slider", (_, r) => { + expect(r.min).toBeLessThan(r.max); + expect(r.step).toBeGreaterThan(0); + expect(r.scale).toBeGreaterThan(0); + expect(r.step).toBeLessThanOrEqual(r.max - r.min); + }); + + it.each(cases)( + "%s starts manual mode inside the range, on a step", + (_, r) => { + expect(r.fallback).toBeGreaterThanOrEqual(r.min); + expect(r.fallback).toBeLessThanOrEqual(r.max); + expect(onStep(r, r.fallback)).toBe(true); + }, + ); + + it("keeps exposure in µs where the driver takes µs, capped at 20 ms", () => { + for (const driver of ["SPINNAKER", "MVIMPACT", "OPENCV"] as const) { + expect(CAMERA_RANGES[driver].exposure.unit).toBe("µs"); + expect(CAMERA_RANGES[driver].exposure.max).toBe(20000); + } + }); +}); diff --git a/gui/frontend/src/lib/color.test.ts b/gui/frontend/src/lib/color.test.ts new file mode 100644 index 0000000..ac0a3e0 --- /dev/null +++ b/gui/frontend/src/lib/color.test.ts @@ -0,0 +1,267 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + CANONICAL_COLORS, + COLOR_CLASSES, + colorFromDoc, + MAX_REACHABLE_Y, + MIN_REACHABLE_Y, + rgbToCss, + rgbToYuv, + writeColorToDoc, + yuvGamutOverflow, + yuvInGamut, + yuvToRgb, + type ColorConfigData, + type RGB, +} from "./color.svelte"; +import { config, type ConfigDocument } from "./config.svelte"; +import { schema, type Schema } from "./schema.svelte"; + +describe("RGB and YUV", () => { + it("map black and white to the studio-swing Y limits", () => { + expect(rgbToYuv({ r: 0, g: 0, b: 0 })).toEqual({ + y: MIN_REACHABLE_Y, + u: 128, + v: 128, + }); + expect(rgbToYuv({ r: 255, g: 255, b: 255 })).toEqual({ + y: MAX_REACHABLE_Y, + u: 128, + v: 128, + }); + }); + + it("round-trip every canonical color to within rounding", () => { + for (const cls of COLOR_CLASSES) { + const rgb = CANONICAL_COLORS[cls]; + const back = yuvToRgb(rgbToYuv(rgb)); + + for (const ch of ["r", "g", "b"] as const) { + expect( + Math.abs(back[ch] - rgb[ch]), + `${cls}.${ch}`, + ).toBeLessThanOrEqual(3); + } + } + }); + + it("round-trip a grid of colors to within rounding", () => { + for (let r = 0; r <= 255; r += 51) + for (let g = 0; g <= 255; g += 51) + for (let b = 0; b <= 255; b += 51) { + const back = yuvToRgb(rgbToYuv({ r, g, b })); + expect( + Math.max( + Math.abs(back.r - r), + Math.abs(back.g - g), + Math.abs(back.b - b), + ), + ).toBeLessThanOrEqual(3); + } + }); + + it("clamp a decode that falls outside 0-255", () => { + expect(yuvToRgb({ y: 0, u: 128, v: 128 })).toEqual({ r: 0, g: 0, b: 0 }); + expect(yuvToRgb({ y: 255, u: 128, v: 128 })).toEqual({ + r: 255, + g: 255, + b: 255, + }); + }); +}); + +describe("gamut", () => { + it("puts every RGB camera color within rounding of the gamut", () => { + for (let r = 0; r <= 255; r += 15) + for (let g = 0; g <= 255; g += 15) + for (let b = 0; b <= 255; b += 15) { + expect(yuvGamutOverflow(rgbToYuv({ r, g, b }))).toBeLessThan(3); + } + }); + + // Known bug (REVIEW.md T7-8): yuvInGamut has no rounding tolerance, so + // rgbToYuv's integer rounding leaves ~4% of real colors, every saturated + // primary and white among them, outside by up to 2.9. Remove .fails once fixed. + it.fails("holds every color an RGB camera can produce", () => { + for (const cls of COLOR_CLASSES) { + expect(yuvInGamut(rgbToYuv(CANONICAL_COLORS[cls])), cls).toBe(true); + } + expect(yuvInGamut(rgbToYuv({ r: 255, g: 255, b: 255 }))).toBe(true); + }); + + it("excludes saturated chroma at extreme brightness", () => { + const c = { y: MAX_REACHABLE_Y, u: 255, v: 255 }; + + expect(yuvInGamut(c)).toBe(false); + expect(yuvGamutOverflow(c)).toBeGreaterThan(0); + }); + + it("measures how far out a point is, so the nearer of two can be picked", () => { + const near = yuvGamutOverflow({ y: 128, u: 220, v: 128 }); + const far = yuvGamutOverflow({ y: 128, u: 255, v: 128 }); + + expect(near).toBeGreaterThan(0); + expect(far).toBeGreaterThan(near); + }); +}); + +it("rgbToCss writes a CSS rgb()", () => { + expect(rgbToCss({ r: 1, g: 22, b: 255 })).toBe("rgb(1, 22, 255)"); +}); + +// The document side: vision_processor's fallbacks (from the schema) under +// defaults.color, under the camera's own color: block. +const FALLBACK: Record = { + "color.reference_force": 0.5, + "color.history_force": 0.3, + "color.min_reference_force": 0.1, + "color.yellow": [255, 255, 0], + "color.blue": [0, 0, 255], + "color.green": [0, 255, 0], + "color.pink": [255, 0, 255], + "color.orange": [255, 128, 0], + "color.field": [0, 128, 0], +}; + +function docOf(): ConfigDocument { + if (!config.doc) throw new Error("no document loaded"); + return config.doc; +} + +const noop = (): void => undefined; + +const rgb = (r: number, g: number, b: number): RGB => ({ r, g, b }); + +function camera(): { cameraId: number; config?: Record } { + return docOf().cameras[0] as unknown as { + cameraId: number; + config?: Record; + }; +} + +beforeEach(() => { + schema.value = { + settings: Object.fromEntries( + Object.entries(FALLBACK).map(([k, v]) => [k, { default: v }]), + ), + drivers: [], + } as unknown as Schema; + config.doc = { cameras: [{ cameraId: 0 }] } as unknown as ConfigDocument; +}); + +describe("colorFromDoc", () => { + it("is vision_processor's fallbacks for a camera with nothing set", () => { + const c = colorFromDoc(0); + + expect(c.referenceForce).toBe(0.5); + expect(c.orange).toEqual(rgb(255, 128, 0)); + expect(c.field).toEqual(rgb(0, 128, 0)); + }); + + it("layers the shared defaults, then the camera's own overrides", () => { + docOf().defaults = { + color: { orange: [200, 100, 0], history_force: 0.4 }, + }; + camera().config = { color: { orange: [210, 90, 10] } }; + + const c = colorFromDoc(0); + expect(c.orange).toEqual(rgb(210, 90, 10)); + expect(c.historyForce).toBe(0.4); + expect(c.referenceForce).toBe(0.5); + }); + + it("ignores values of the wrong shape", () => { + camera().config = { + color: { + orange: [1, 2], + field: "green", + reference_force: "high", + pink: [1, 2, "3"], + }, + }; + + const c = colorFromDoc(0); + expect(c.orange).toEqual(rgb(255, 128, 0)); + expect(c.field).toEqual(rgb(0, 128, 0)); + expect(c.referenceForce).toBe(0.5); + expect(c.pink).toEqual(rgb(255, 0, 255)); + }); + + it("returns copies, so editing the result doesn't touch the fallbacks", () => { + const a = colorFromDoc(0); + a.orange.r = 1; + + expect(colorFromDoc(0).orange.r).toBe(255); + }); +}); + +describe("writeColorToDoc", () => { + const edit = (change: (c: ColorConfigData) => void): void => { + const c = colorFromDoc(0); + change(c); + writeColorToDoc(0, c); + }; + + it("writes nothing when nothing changed", () => { + edit(noop); + + expect(camera().config).toBeUndefined(); + }); + + it("writes only the values that differ from what the camera inherits", () => { + edit((c) => { + c.orange = rgb(250, 120, 5); + c.minReferenceForce = 0.2; + }); + + expect(camera().config).toEqual({ + color: { orange: [250, 120, 5], min_reference_force: 0.2 }, + }); + }); + + it("keeps an existing override even when set back to the inherited value", () => { + camera().config = { color: { orange: [1, 2, 3] } }; + + edit((c) => { + c.orange = rgb(255, 128, 0); + }); + + expect(camera().config).toEqual({ color: { orange: [255, 128, 0] } }); + }); + + it("keeps keys the Color page doesn't edit", () => { + camera().config = { + color: { something_else: 7 }, + camera: { driver: "OPENCV" }, + }; + + edit((c) => { + c.field = rgb(0, 100, 0); + }); + + expect(camera().config).toEqual({ + color: { field: [0, 100, 0], something_else: 7 }, + camera: { driver: "OPENCV" }, + }); + }); + + it("compares against the shared defaults, not just the fallbacks", () => { + docOf().defaults = { color: { orange: [200, 100, 0] } }; + + edit(noop); + expect(camera().config).toBeUndefined(); + + edit((c) => { + c.orange = rgb(255, 128, 0); + }); + expect(camera().config).toEqual({ color: { orange: [255, 128, 0] } }); + }); + + it("does nothing for a camera that isn't in the document", () => { + const before = JSON.stringify(config.doc); + + writeColorToDoc(9, colorFromDoc(0)); + + expect(JSON.stringify(config.doc)).toBe(before); + }); +}); diff --git a/gui/frontend/src/lib/config.test.ts b/gui/frontend/src/lib/config.test.ts new file mode 100644 index 0000000..353068c --- /dev/null +++ b/gui/frontend/src/lib/config.test.ts @@ -0,0 +1,400 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { app } from "./text/app"; +import type { ConfigDocument } from "./config.svelte"; + +// The shared working document against a stand-in host. Each test loads a fresh +// copy of the module, since it keeps what it last synced at module scope. +type Config = typeof import("./config.svelte"); + +interface Request { + method: string; + url: string; + body: unknown; +} + +type Reply = { status: number; body: unknown } | Error; + +function docOf(c: { doc: ConfigDocument | null }): ConfigDocument { + if (!c.doc) throw new Error("no document loaded"); + return c.doc; +} + +let requests: Request[]; +let replies: Map; + +const doc = () => ({ + version: 2, + field: { fieldLength: 9000 }, + cameras: [{ cameraId: 0 }], +}); +const state = (revision: number) => ({ + revision, + path: "/cfg/vision.yml", + changes: [], + cameras: [], +}); + +function reply(method: string, url: string, ...answers: Reply[]): void { + replies.set(`${method} ${url}`, answers); +} + +function sent(method: string, url: string): Request[] { + return requests.filter((r) => r.method === method && r.url === url); +} + +function fakeFetch(url: string, init: RequestInit = {}): Promise { + const method = init.method ?? "GET"; + const body = + typeof init.body === "string" + ? (JSON.parse(init.body) as unknown) + : undefined; + requests.push({ method, url, body }); + + const queue = replies.get(`${method} ${url}`) ?? []; + const answer = queue.length > 1 ? queue.shift() : queue[0]; + if (answer instanceof Error) return Promise.reject(answer); + const { status, body: out } = answer ?? { status: 200, body: {} }; + + return Promise.resolve( + new Response(JSON.stringify(out), { + status, + headers: { "Content-Type": "application/json" }, + }), + ); +} + +async function settle(ms = 0): Promise { + await vi.advanceTimersByTimeAsync(ms); +} + +async function loaded(): Promise { + const mod = await import("./config.svelte"); + await mod.loadConfig(); + await settle(); + requests = []; + + return mod; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.resetModules(); + requests = []; + replies = new Map(); + vi.stubGlobal("fetch", vi.fn(fakeFetch)); + reply("GET", "/api/schema", { + status: 200, + body: { settings: {}, drivers: [] }, + }); + reply("GET", "/api/geometry", { status: 200, body: {} }); + reply("GET", "/api/config", { + status: 200, + body: { document: doc(), state: state(3) }, + }); + reply("PUT", "/api/config", { status: 200, body: { revision: 4 } }); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe("loadConfig", () => { + it("loads the schema, then the document and its revision", async () => { + const { config, loadConfig } = await import("./config.svelte"); + await loadConfig(); + + expect(requests.map((r) => r.url)).toEqual([ + "/api/schema", + "/api/config", + "/api/geometry", + ]); + expect(config.doc).toEqual(doc()); + expect(config.revision).toBe(3); + expect(config.state?.path).toBe("/cfg/vision.yml"); + }); + + it("doesn't echo a freshly loaded document back to the host", async () => { + await loaded(); + await settle(1000); + + expect(sent("PUT", "/api/config")).toEqual([]); + }); + + it("shows the host's error when the document can't be read", async () => { + reply("GET", "/api/config", { + status: 500, + body: { error: "internal", message: "disk on fire" }, + }); + const { config, loadConfig } = await import("./config.svelte"); + await loadConfig(); + + expect(config.error).toBe("disk on fire"); + expect(config.doc).toBeNull(); + }); +}); + +describe("edits", () => { + it("are debounced into one PUT of the whole document at the confirmed revision", async () => { + const { config } = await loaded(); + + docOf(config).field.fieldLength = 9100; + await settle(100); + docOf(config).field.fieldLength = 9200; + await settle(249); + expect(sent("PUT", "/api/config")).toEqual([]); + + await settle(1); + const puts = sent("PUT", "/api/config"); + expect(puts).toHaveLength(1); + expect(puts[0]?.body).toMatchObject({ + revision: 3, + document: { field: { fieldLength: 9200 } }, + }); + expect(config.revision).toBe(4); + expect(config.error).toBeNull(); + }); + + it("refreshes the field markings after an edit applies", async () => { + const { config } = await loaded(); + + docOf(config).field.fieldLength = 9100; + await settle(300); + + expect(sent("GET", "/api/geometry")).toHaveLength(1); + }); + + it("show the host's reasons when an edit is rejected", async () => { + reply("PUT", "/api/config", { + status: 400, + body: { + error: "invalid", + message: "invalid", + issues: ["field_length: too small", "field_width: too small"], + }, + }); + const { config } = await loaded(); + + docOf(config).field.fieldLength = 1; + await settle(300); + + expect(config.error).toBe( + "field_length: too small\nfield_width: too small", + ); + expect(config.revision).toBe(3); + }); + + it("take the host's document when another tab edited first", async () => { + reply("PUT", "/api/config", { + status: 409, + body: { error: "stale", message: "stale" }, + }); + const { config } = await loaded(); + reply("GET", "/api/config", { + status: 200, + body: { document: doc(), state: state(7) }, + }); + + docOf(config).field.fieldLength = 9100; + await settle(300); + + expect(config.error).toBe(app.editedElsewhere); + expect(config.revision).toBe(7); + expect(config.doc?.field.fieldLength).toBe(9000); + }); + + it("made while a PUT is in flight go out next, at the new revision", async () => { + reply( + "PUT", + "/api/config", + { status: 200, body: { revision: 4 } }, + { status: 200, body: { revision: 5 } }, + ); + const { config } = await loaded(); + let release!: () => void; + const gate = new Promise((r) => (release = r)); + vi.mocked(fetch).mockImplementationOnce(async (url, init) => { + await gate; + return fakeFetch(url as string, init); + }); + + docOf(config).field.fieldLength = 9100; + await settle(300); + docOf(config).field.fieldLength = 9200; + await settle(300); + release(); + await settle(300); + + const puts = sent("PUT", "/api/config"); + expect( + puts.map( + (p) => + (p.body as { document: ReturnType }).document.field + .fieldLength, + ), + ).toEqual([9100, 9200]); + expect(puts[1]?.body).toMatchObject({ revision: 4 }); + expect(config.revision).toBe(5); + }); + + it.todo( + "sent while the host is unreachable are reported and retried (REVIEW.md T4-2)", + ); +}); + +describe("flushEdits", () => { + it("sends a pending edit at once and waits for it", async () => { + const { config, flushEdits } = await loaded(); + + docOf(config).field.fieldLength = 9100; + await settle(); + await flushEdits(); + + expect(sent("PUT", "/api/config")).toHaveLength(1); + expect(config.revision).toBe(4); + }); + + it("does nothing when nothing changed", async () => { + const { flushEdits } = await loaded(); + + await flushEdits(); + + expect(requests).toEqual([]); + }); +}); + +describe("actions", () => { + it("save flushes pending edits first, then saves at the new revision", async () => { + reply("POST", "/api/config/save", { status: 200, body: { revision: 4 } }); + const { config, saveConfig } = await loaded(); + + docOf(config).field.fieldLength = 9100; + await settle(); + const conflict = await saveConfig(); + + expect(requests.map((r) => `${r.method} ${r.url}`).slice(0, 2)).toEqual([ + "PUT /api/config", + "GET /api/geometry", + ]); + expect(sent("POST", "/api/config/save")[0]?.body).toEqual({ + revision: 4, + force: false, + }); + expect(conflict).toBeNull(); + expect(config.busy).toBe(false); + }); + + it("save returns a disk conflict for the caller to resolve", async () => { + const body = { + error: "disk_changed", + message: "vision.yml changed on disk", + }; + reply("POST", "/api/config/save", { status: 409, body }); + const { saveConfig } = await loaded(); + + expect(await saveConfig()).toEqual(body); + }); + + it("save as and load send the file name", async () => { + const { saveConfigAs, loadConfigFrom } = await loaded(); + + await saveConfigAs("lab.yml"); + await loadConfigFrom("event.yml"); + + expect(sent("POST", "/api/config/save-as")[0]?.body).toEqual({ + revision: 3, + name: "lab.yml", + }); + expect(sent("POST", "/api/config/load")[0]?.body).toEqual({ + name: "event.yml", + }); + }); + + it("a failed action shows its reason and reloads the document", async () => { + reply("POST", "/api/config/load", { + status: 400, + body: { error: "invalid", message: "no such file" }, + }); + const { config, loadConfigFrom } = await loaded(); + + await loadConfigFrom("missing.yml"); + + expect(config.error).toBe("no such file"); + expect(sent("GET", "/api/config")).toHaveLength(1); + }); + + it("locking without a live calibration shows the host's reason", async () => { + const url = "/api/config/cameras/0/calibration"; + reply("POST", url, { + status: 409, + body: { error: "no_live_calibration", message: "nothing to lock yet" }, + }); + const { config, lockCalibration } = await loaded(); + + await lockCalibration(0); + + expect(config.error).toBe("nothing to lock yet"); + }); + + it("unlocking deletes the camera's calibration", async () => { + const { unlockCalibration } = await loaded(); + + await unlockCalibration(2); + + expect(sent("DELETE", "/api/config/cameras/2/calibration")).toHaveLength(1); + }); + + it("reload accepts the file on disk", async () => { + const { reloadFromDisk } = await loaded(); + + await reloadFromDisk(); + + expect(sent("POST", "/api/config/reload")).toHaveLength(1); + }); +}); + +describe("helpers", () => { + it("changesFor filters by section and camera, keeping shared changes", async () => { + const { config, changesFor } = await loaded(); + config.state = { + ...state(3), + changes: [ + { section: "camera", cameraId: 0, path: "a" }, + { section: "camera", cameraId: 1, path: "b" }, + { section: "camera", path: "shared" }, + { section: "network", path: "c" }, + ], + } as unknown as NonNullable; + + expect(changesFor("camera", 0).map((c) => c.path)).toEqual(["a", "shared"]); + expect(changesFor("camera").map((c) => c.path)).toEqual([ + "a", + "b", + "shared", + ]); + expect(changesFor("network").map((c) => c.path)).toEqual(["c"]); + }); + + it("cameraDoc and cameraStatus find a camera by id", async () => { + const { config, cameraDoc, cameraStatus } = await loaded(); + config.state = { + ...state(3), + cameras: [{ cameraId: 0, locked: true }], + } as unknown as NonNullable; + + expect(cameraDoc(0)).toEqual({ cameraId: 0 }); + expect(cameraDoc(5)).toBeUndefined(); + expect(cameraStatus(0)).toMatchObject({ locked: true }); + }); + + it("formatValue summarizes blocks and shows scalars as JSON", async () => { + const { formatValue } = await import("./config.svelte"); + + expect(formatValue(undefined)).toBe("(none)"); + expect(formatValue(null)).toBe("(none)"); + expect(formatValue({ a: 1, b: 2 })).toBe("{2 fields}"); + expect(formatValue([1, 2])).toBe("[1,2]"); + expect(formatValue("x")).toBe('"x"'); + expect(formatValue(3)).toBe("3"); + }); +}); diff --git a/gui/frontend/src/lib/fieldSplit.test.ts b/gui/frontend/src/lib/fieldSplit.test.ts new file mode 100644 index 0000000..dd8b2c2 --- /dev/null +++ b/gui/frontend/src/lib/fieldSplit.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; +import { + boxesOverlap, + CAMERA_COUNT_OPTIONS, + computeFieldSlice, + type FieldSlice, +} from "./fieldSplit"; + +// Division B: 9000 × 6000 mm, centered on the origin. +const L = 9000; +const W = 6000; + +const box = (minX: number, minY: number, maxX: number, maxY: number) => ({ + minX, + minY, + maxX, + maxY, +}); + +const slices = (amount: number, length = L, width = W): FieldSlice[] => + Array.from({ length: amount }, (_, id) => + computeFieldSlice(id, amount, length, width), + ); + +const area = (s: FieldSlice) => (s.maxX - s.minX) * (s.maxY - s.minY); + +describe("computeFieldSlice", () => { + it("gives one camera the whole field", () => { + expect(computeFieldSlice(0, 1, L, W)).toEqual( + box(-L / 2, -W / 2, L / 2, W / 2), + ); + }); + + it("treats a camera count below 1 as one camera", () => { + expect(computeFieldSlice(0, 0, L, W)).toEqual( + computeFieldSlice(0, 1, L, W), + ); + }); + + it("splits two cameras along the length: -x, then +x", () => { + expect(slices(2)).toEqual([ + box(-4500, -3000, 0, 3000), + box(0, -3000, 4500, 3000), + ]); + }); + + it("splits four cameras into quadrants, -y before +y within each half", () => { + expect(slices(4)).toEqual([ + box(-4500, -3000, 0, 0), + box(-4500, 0, 0, 3000), + box(0, -3000, 4500, 0), + box(0, 0, 4500, 3000), + ]); + }); + + it("halves whichever side is longer, so a wide field splits along y", () => { + expect(slices(2, 4500, 6000)).toEqual([ + box(-2250, -3000, 2250, 0), + box(-2250, 0, 2250, 3000), + ]); + }); + + it("wraps a camera id past the count", () => { + expect(computeFieldSlice(5, 4, L, W)).toEqual( + computeFieldSlice(1, 4, L, W), + ); + }); + + it.each([1, 2, 4, 8])("tiles the field exactly with %i cameras", (amount) => { + const all = slices(amount); + const total = all.reduce((sum, s) => sum + area(s), 0); + expect(total).toBe(L * W); + + for (const s of all) { + expect(s.minX).toBeGreaterThanOrEqual(-L / 2); + expect(s.maxX).toBeLessThanOrEqual(L / 2); + expect(s.minY).toBeGreaterThanOrEqual(-W / 2); + expect(s.maxY).toBeLessThanOrEqual(W / 2); + } + for (let a = 0; a < all.length; a++) + for (let b = a + 1; b < all.length; b++) { + const [p, q] = [all[a], all[b]]; + if (!p || !q) throw new Error("missing slice"); + const overlapX = Math.min(p.maxX, q.maxX) - Math.max(p.minX, q.minX); + const overlapY = Math.min(p.maxY, q.maxY) - Math.max(p.minY, q.minY); + expect(overlapX <= 0 || overlapY <= 0).toBe(true); + } + }); + + it("is only offered power-of-two camera counts, the ones that tile", () => { + const counts = [...CAMERA_COUNT_OPTIONS.full, ...CAMERA_COUNT_OPTIONS.half]; + for (const n of counts) expect(Math.log2(n) % 1).toBe(0); + }); +}); + +describe("boxesOverlap", () => { + const a = box(0, 0, 10, 10); + + it.each([ + ["overlapping", box(5, 5, 15, 15), true], + ["contained", box(2, 2, 3, 3), true], + ["containing", box(-5, -5, 20, 20), true], + ["touching at an edge", box(10, 0, 20, 10), true], + ["touching at a corner", box(10, 10, 20, 20), true], + ["apart in x", box(11, 0, 20, 10), false], + ["apart in y", box(0, -20, 10, -1), false], + ])("%s: %s", (_, b, want) => { + expect(boxesOverlap(a, b)).toBe(want); + expect(boxesOverlap(b, a)).toBe(want); + }); +}); diff --git a/gui/frontend/src/lib/layout/nav.test.ts b/gui/frontend/src/lib/layout/nav.test.ts new file mode 100644 index 0000000..17af29e --- /dev/null +++ b/gui/frontend/src/lib/layout/nav.test.ts @@ -0,0 +1,195 @@ +import { tick } from "svelte"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { ConfigDocument, ConfigState } from "../config.svelte"; + +// The module reads the URL hash when it loads, so each test sets the hash +// first and loads a fresh copy (with fresh config and preferences). +async function load(hash = "") { + history.replaceState(null, "", `/${hash}`); + vi.resetModules(); + const nav = await import("./nav.svelte"); + const { config } = await import("../config.svelte"); + const { preferences } = await import("../preferences.svelte"); + + return { ...nav, config, preferences }; +} + +function withCameras( + config: { doc: ConfigDocument | null }, + ...ids: number[] +): void { + config.doc = { + cameras: ids.map((cameraId) => ({ + cameraId, + instance: `host${String(cameraId)}`, + })), + } as unknown as ConfigDocument; +} + +beforeEach(() => { + localStorage.clear(); +}); + +describe("the URL hash", () => { + it("selects the camera and page on load", async () => { + const { nav } = await load("#2/geometry"); + + expect(nav.selectedInstanceId).toBe("cam:2"); + expect(nav.selectedCategoryId).toBe("geometry"); + }); + + it("defaults to the field dimensions with no or a malformed hash", async () => { + expect((await load("")).nav.selectedCategoryId).toBe("field_dimensions"); + expect((await load("#geometry")).nav.selectedCategoryId).toBe( + "field_dimensions", + ); + expect((await load("#0/no_such_page")).nav.selectedCategoryId).toBe( + "field_dimensions", + ); + }); + + it("keeps the selected camera when the hash names a shared page only", async () => { + const { nav } = await load("#/network"); + + expect(nav.selectedInstanceId).toBeNull(); + expect(nav.selectedCategoryId).toBe("network"); + }); + + it("follows hash changes, as back and forward make them", async () => { + const { nav } = await load("#0/camera"); + + location.hash = "#1/color"; + window.dispatchEvent(new HashChangeEvent("hashchange")); + + expect(nav.selectedInstanceId).toBe("cam:1"); + expect(nav.selectedCategoryId).toBe("color"); + }); + + it("won't open an expert page unless expert mode is on", async () => { + expect((await load("#0/advanced")).nav.selectedCategoryId).toBe( + "field_dimensions", + ); + + localStorage.setItem( + "vision-processor-gui:preferences", + JSON.stringify({ expertUser: true }), + ); + const expert = await load("#0/advanced"); + expect(expert.preferences.expertUser).toBe(true); + expect(expert.nav.selectedCategoryId).toBe("advanced"); + }); + + it("leaves an expert page when expert mode is turned off", async () => { + localStorage.setItem( + "vision-processor-gui:preferences", + JSON.stringify({ expertUser: true }), + ); + const { nav, preferences } = await load("#0/advanced"); + expect(nav.selectedCategoryId).toBe("advanced"); + + preferences.expertUser = false; + await tick(); + + expect(nav.selectedCategoryId).toBe("field_dimensions"); + }); + + it("is corrected to match the selection, without a history entry", async () => { + const { nav, config } = await load(""); + withCameras(config, 3); + const length = history.length; + + nav.selectedCategoryId = "network"; + await tick(); + + expect(location.hash).toBe("#3/network"); + expect(history.length).toBe(length); + }); +}); + +describe("links", () => { + it("build #camera/page, keeping the other half of the selection", async () => { + const { navHref, categoryHref, instanceHref, nav, config } = + await load("#1/color"); + withCameras(config, 0, 1); + + expect(navHref(undefined, "network")).toBe("#/network"); + expect(navHref(4, "camera")).toBe("#4/camera"); + expect(categoryHref("geometry")).toBe("#1/geometry"); + expect(instanceHref(0)).toBe("#0/color"); + + nav.selectedCategoryId = "stream"; + expect(instanceHref(0)).toBe("#0/stream"); + }); +}); + +describe("instances", () => { + it("are one row per camera in vision.yml", async () => { + const { instances, config } = await load(""); + withCameras(config, 0, 1); + + expect(instances()).toEqual([ + { id: "cam:0", host: "host0", cameraId: 0 }, + { id: "cam:1", host: "host1", cameraId: 1 }, + ]); + }); + + it("select the first camera until one is picked, or when the picked one is gone", async () => { + const { selectedInstance, nav, config } = await load("#5/camera"); + expect(selectedInstance()).toBeUndefined(); + + withCameras(config, 0, 1); + expect(selectedInstance()?.cameraId).toBe(0); + + nav.selectedInstanceId = "cam:1"; + expect(selectedInstance()?.cameraId).toBe(1); + }); +}); + +describe("selectedCategory", () => { + it("is the selected page, or the field dimensions for an unknown id", async () => { + const { selectedCategory, nav } = await load("#0/network"); + expect(selectedCategory().id).toBe("network"); + + nav.selectedCategoryId = "gone"; + expect(selectedCategory().id).toBe("field_dimensions"); + }); +}); + +describe("isCategoryDirty", () => { + async function withChanges(changes: object[]) { + const loaded = await load("#1/camera"); + withCameras(loaded.config, 0, 1); + loaded.config.state = { changes, cameras: [] } as unknown as ConfigState; + + return loaded; + } + + it("marks a per-camera page dirty only for the selected camera's changes", async () => { + const { isCategoryDirty } = await withChanges([ + { section: "camera", cameraId: 0, path: "x" }, + ]); + expect(isCategoryDirty("camera")).toBe(false); + + const other = await withChanges([ + { section: "camera", cameraId: 1, path: "x" }, + ]); + expect(other.isCategoryDirty("camera")).toBe(true); + }); + + it("marks a shared page dirty for a change on any camera", async () => { + const { isCategoryDirty } = await withChanges([ + { section: "network", cameraId: 0, path: "x" }, + ]); + + expect(isCategoryDirty("network")).toBe(true); + }); + + it("never marks pages without a section", async () => { + const { isCategoryDirty } = await withChanges([ + { section: "other", path: "x" }, + ]); + + expect(isCategoryDirty("live_field")).toBe(false); + expect(isCategoryDirty("alerts")).toBe(false); + }); +}); diff --git a/gui/frontend/src/lib/live/draw.test.ts b/gui/frontend/src/lib/live/draw.test.ts new file mode 100644 index 0000000..ef1e795 --- /dev/null +++ b/gui/frontend/src/lib/live/draw.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, it } from "vitest"; +import { + PALETTE, + clear, + drawField, + drawLayer, + extentOf, + viewFor, + type LayerStyle, +} from "./draw"; +import { fromDetection, fromTracked } from "./model"; + +// jsdom has no canvas: a context that records every call and assignment, so a +// test can check what was drawn without pixels. +interface Recorder { + ctx: CanvasRenderingContext2D; + calls: { name: string; args: unknown[] }[]; + sets: { name: string; value: unknown }[]; +} + +function recorder(): Recorder { + const calls: Recorder["calls"] = []; + const sets: Recorder["sets"] = []; + const state: Record = {}; + + const ctx = new Proxy(state, { + get(target, name: string) { + if (name in target) return target[name]; + if (name === "measureText") + return (text: string) => ({ width: text.length * 6 }); + + return (...args: unknown[]) => { + calls.push({ name, args }); + }; + }, + set(target, name: string, value) { + sets.push({ name, value }); + target[name] = value; + + return true; + }, + }) as unknown as CanvasRenderingContext2D; + + return { ctx, calls, sets }; +} + +const count = (r: Recorder, name: string): number => + r.calls.filter((c) => c.name === name).length; +const setTo = (r: Recorder, name: string): unknown[] => + r.sets.filter((s) => s.name === name).map((s) => s.value); + +const FIELD = { + fieldLength: 9000, + fieldWidth: 6000, + goalWidth: 1000, + goalDepth: 180, + boundaryWidth: 300, + fieldLines: [ + { + name: "TopTouchLine", + p1: { x: -4500, y: 3000 }, + p2: { x: 4500, y: 3000 }, + thickness: 10, + }, + { + name: "HalfwayLine", + p1: { x: 0, y: -3000 }, + p2: { x: 0, y: 3000 }, + thickness: 10, + }, + ], + fieldArcs: [ + { + name: "CenterCircle", + center: { x: 0, y: 0 }, + radius: 500, + a1: 0, + a2: 6.28, + thickness: 10, + }, + ], +}; + +const view = viewFor(extentOf(FIELD), 960, 660, 2, false); + +const style = (over: Partial = {}): LayerStyle => ({ + robotStyle: "numbered", + alpha: 0.5, + outline: null, + velocities: false, + confidence: false, + ...over, +}); + +describe("drawField", () => { + it("fills the field color, then draws its lines and arcs", () => { + const r = recorder(); + drawField(r.ctx, view, FIELD); + + expect(r.calls[0]?.name).toBe("setTransform"); + expect(setTo(r, "fillStyle")[0]).toBe(PALETTE.field); + expect(count(r, "fillRect")).toBeGreaterThan(0); + expect(count(r, "lineTo") + count(r, "strokeRect")).toBeGreaterThanOrEqual( + 2, + ); + expect(count(r, "arc")).toBeGreaterThanOrEqual(1); + }); + + it("colors the goals by team only when the sides are known", () => { + const unknown = recorder(); + drawField(unknown.ctx, view, FIELD); + const known = recorder(); + drawField(known.ctx, view, FIELD, { blueOnPositive: true }); + + const styles = (r: Recorder) => [ + ...setTo(r, "strokeStyle"), + ...setTo(r, "fillStyle"), + ]; + expect(styles(unknown)).not.toContain(PALETTE.team.blue); + expect(styles(known)).toContain(PALETTE.team.blue); + expect(styles(known)).toContain(PALETTE.team.yellow); + }); + + it("draws more with the axes on", () => { + const plain = recorder(); + drawField(plain.ctx, view, FIELD); + const axes = recorder(); + drawField(axes.ctx, view, FIELD, { axes: true }); + + expect(axes.calls.length).toBeGreaterThan(plain.calls.length); + }); + + it("copes with a field the host hasn't filled in yet", () => { + expect(() => { + drawField(recorder().ctx, viewFor(extentOf({}), 300, 200, 1, true), {}); + }).not.toThrow(); + }); +}); + +describe("drawLayer", () => { + const detection = fromDetection({ + robotsYellow: [ + { robotId: 3, x: 100, y: -200, orientation: 1.5, confidence: 0.9 }, + ], + robotsBlue: [{ robotId: 1, x: -500, y: 400, confidence: 0.4 }], + balls: [{ x: 10, y: 20, confidence: 0.5 }], + }); + + const tracked = fromTracked({ + robots: [ + { + robotId: { id: 2, team: "BLUE" }, + pos: { x: 1.5, y: -0.25 }, + orientation: 0, + vel: { x: 1, y: 0 }, + }, + ], + balls: [{ pos: { x: 0.1, y: 0.2, z: 0.05 }, vel: { x: 2, y: 0 } }], + kickedBall: { pos: { x: 0, y: 0 }, stopPos: { x: 2, y: 1 } }, + }); + + it("draws at the layer's alpha and restores the context", () => { + const r = recorder(); + drawLayer(r.ctx, view, detection, style({ alpha: 0.3 })); + + expect(setTo(r, "globalAlpha")[0]).toBe(0.3); + expect(count(r, "save")).toBe(count(r, "restore")); + }); + + it("draws every robot and ball", () => { + const empty = recorder(); + drawLayer( + empty.ctx, + view, + { ...detection, robots: [], balls: [] }, + style(), + ); + const full = recorder(); + drawLayer(full.ctx, view, detection, style()); + + expect(count(empty, "arc")).toBe(0); + expect(count(full, "arc")).toBeGreaterThanOrEqual(3); + }); + + it("adds outlines, confidence bars and velocities only when asked", () => { + const calls = (layer: typeof tracked, s: LayerStyle): number => { + const r = recorder(); + drawLayer(r.ctx, view, layer, s); + return r.calls.length; + }; + + expect(calls(tracked, style({ outline: "#f00" }))).toBeGreaterThan( + calls(tracked, style()), + ); + expect(calls(tracked, style({ velocities: true }))).toBeGreaterThan( + calls(tracked, style()), + ); + // Confidence comes with raw detections. + expect(calls(detection, style({ confidence: true }))).toBeGreaterThan( + calls(detection, style()), + ); + }); + + it("numbers every robot, or in the pattern style only those its dots can't show", () => { + const numbered = recorder(); + drawLayer(numbered.ctx, view, detection, style()); + const pattern = recorder(); + drawLayer(pattern.ctx, view, detection, style({ robotStyle: "pattern" })); + + // The blue robot has no orientation, so no dot pattern. + expect(count(numbered, "fillText")).toBe(2); + expect(count(pattern, "fillText")).toBe(1); + }); + + it("draws a kicked ball's path", () => { + const r = recorder(); + drawLayer(r.ctx, view, { ...tracked, robots: [], balls: [] }, style()); + + expect(r.calls.length).toBeGreaterThan(2); + }); +}); + +it("clear resets the transform and clears the whole view", () => { + const r = recorder(); + clear(r.ctx, view); + + expect(r.calls.map((c) => c.name)).toEqual(["setTransform", "clearRect"]); + expect(r.calls[1]?.args).toEqual([0, 0, 960, 660]); +}); diff --git a/gui/frontend/src/lib/logs/hostLog.test.ts b/gui/frontend/src/lib/logs/hostLog.test.ts new file mode 100644 index 0000000..aab507c --- /dev/null +++ b/gui/frontend/src/lib/logs/hostLog.test.ts @@ -0,0 +1,164 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { LogRecord } from "../apiTypes"; + +type HostLog = typeof import("./hostLog.svelte"); + +// GET /api/logs as a queue of pages. Once it's empty a request hangs, like a +// long poll with nothing new, until it's aborted. +let pages: (object | Error)[]; +let urls: string[]; + +function record(n: number): LogRecord { + return { seq: n, message: `record ${String(n)}` } as unknown as LogRecord; +} + +function page(from: number, to: number, missed = false): object { + const records = []; + for (let n = from; n <= to; n++) records.push(record(n)); + return { records, next: to, missed }; +} + +function fakeFetch(url: string, init: RequestInit = {}): Promise { + urls.push(url); + const next = pages.shift(); + + if (next instanceof Error) return Promise.reject(next); + if (next) + return Promise.resolve(new Response(JSON.stringify(next), { status: 200 })); + + return new Promise((_, reject) => { + init.signal?.addEventListener("abort", () => { + reject(new DOMException("aborted", "AbortError")); + }); + }); +} + +let mod: HostLog; + +beforeEach(async () => { + vi.useFakeTimers(); + vi.resetModules(); + pages = []; + urls = []; + vi.stubGlobal("fetch", vi.fn(fakeFetch)); + mod = await import("./hostLog.svelte"); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +const seqs = () => + mod.logRecords().map((r) => (r as unknown as { seq: number }).seq); + +describe("followLog", () => { + it("asks for what's logged at once, then long-polls after the last record", async () => { + pages = [page(1, 3), page(4, 4)]; + const stop = mod.followLog("warn"); + await vi.advanceTimersByTimeAsync(0); + + expect(urls).toEqual([ + "/api/logs?after=0&level=warn&limit=1000", + "/api/logs?after=3&level=warn&limit=1000&wait=25", + "/api/logs?after=4&level=warn&limit=1000&wait=25", + ]); + expect(seqs()).toEqual([1, 2, 3, 4]); + stop(); + }); + + it("reports missed records only after the first page", async () => { + pages = [page(5, 6, true)]; + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + expect(mod.hostLog.missed).toBe(false); + stop(); + + pages = [page(1, 1), page(9, 9, true)]; + const again = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + expect(mod.hostLog.missed).toBe(true); + again(); + }); + + it("shows a failure and retries after 2 s from the same place", async () => { + pages = [page(1, 2), new Error("host unreachable"), page(3, 3)]; + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + + expect(mod.hostLog.error).toBe("host unreachable"); + expect(urls).toHaveLength(2); + + await vi.advanceTimersByTimeAsync(2000); + expect(urls[2]).toContain("after=2&"); + expect(mod.hostLog.error).toBeNull(); + expect(seqs()).toEqual([1, 2, 3]); + stop(); + }); + + it("stops asking once stopped, and starts over on a new level", async () => { + pages = [page(1, 2)]; + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + stop(); + await vi.advanceTimersByTimeAsync(10_000); + expect(urls).toHaveLength(2); + + pages = [page(7, 7)]; + const next = mod.followLog("error"); + await vi.advanceTimersByTimeAsync(0); + expect(urls[2]).toBe("/api/logs?after=0&level=error&limit=1000"); + expect(seqs()).toEqual([7]); + next(); + }); + + it("doesn't retry or show an error for a request it aborted itself", async () => { + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + stop(); + await vi.advanceTimersByTimeAsync(5000); + + expect(mod.hostLog.error).toBeNull(); + expect(urls).toHaveLength(1); + }); + + it("keeps the newest 1000 records", async () => { + pages = [page(1, 900), page(901, 1200)]; + const stop = mod.followLog("debug"); + await vi.advanceTimersByTimeAsync(0); + + expect(seqs()).toHaveLength(1000); + expect(seqs()[0]).toBe(201); + expect(seqs().at(-1)).toBe(1200); + stop(); + }); +}); + +describe("pause and clear", () => { + it("holds records while paused and shows them on resume", async () => { + mod.setPaused(true); + pages = [page(1, 2), page(3, 3)]; + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + + expect(seqs()).toEqual([]); + expect(mod.hostLog.waiting).toBe(3); + + mod.setPaused(false); + expect(seqs()).toEqual([1, 2, 3]); + expect(mod.hostLog.waiting).toBe(0); + stop(); + }); + + it("clear empties the panel and the missed flag", async () => { + pages = [page(1, 2), page(5, 5, true)]; + const stop = mod.followLog("info"); + await vi.advanceTimersByTimeAsync(0); + expect(mod.hostLog.missed).toBe(true); + + mod.clearLog(); + expect(seqs()).toEqual([]); + expect(mod.hostLog.missed).toBe(false); + stop(); + }); +}); diff --git a/gui/frontend/src/lib/network.test.ts b/gui/frontend/src/lib/network.test.ts new file mode 100644 index 0000000..282f7e0 --- /dev/null +++ b/gui/frontend/src/lib/network.test.ts @@ -0,0 +1,301 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { config, type ConfigDocument } from "./config.svelte"; +import type { HostInterface, NetworkState } from "./apiTypes"; +import { + addressAdvice, + addressPresets, + headerSockets, + interfaceSelection, + ipv4Error, + networkFromDoc, + portAdvice, + portError, + portPresets, + STANDARD, + writeInterfaces, + writeNetwork, +} from "./network.svelte"; +import { schema, type Schema } from "./schema.svelte"; +import { network as text } from "./text/network"; + +function docOf(): ConfigDocument { + if (!config.doc) throw new Error("no document loaded"); + return config.doc; +} + +const FALLBACKS = { + vision_ip: "224.5.23.2", + vision_port: 10006, + gc_ip: "224.5.23.1", + gc_port: 10003, +}; + +function iface(name: string, broadcast: string, used = true): HostInterface { + return { + name, + address: "192.168.1.5", + broadcast, + used, + } as unknown as HostInterface; +} + +function netState(extra: Partial = {}): NetworkState { + return { interfaces: [], ...extra } as unknown as NetworkState; +} + +beforeEach(() => { + schema.value = { + settings: Object.fromEntries( + Object.entries(FALLBACKS).map(([k, v]) => [ + `network.${k}`, + { default: v }, + ]), + ), + drivers: [], + } as unknown as Schema; + config.doc = { cameras: [] } as unknown as ConfigDocument; +}); + +describe("the network block", () => { + it("falls back to vision_processor's defaults and the standard tracker group", () => { + expect(networkFromDoc()).toEqual({ + ...FALLBACKS, + tracker_ip: "224.5.23.2", + tracker_port: 10010, + }); + }); + + it("reads what vision.yml sets, ignoring values of the wrong type", () => { + docOf().defaults = { + network: { vision_ip: "239.1.2.3", vision_port: "10020", gc_port: 11003 }, + }; + docOf().tracker = { ip: "239.9.9.9", port: 11010 }; + + expect(networkFromDoc()).toEqual({ + vision_ip: "239.1.2.3", + vision_port: 10006, + gc_ip: "224.5.23.1", + gc_port: 11003, + tracker_ip: "239.9.9.9", + tracker_port: 11010, + }); + }); + + it("writes vision and game controller keys into defaults.network, keeping the rest", () => { + docOf().defaults = { network: { gc_ip: "239.0.0.1" }, other: 1 }; + + writeNetwork("vision_port", 10016); + + expect(docOf().defaults).toEqual({ + network: { gc_ip: "239.0.0.1", vision_port: 10016 }, + other: 1, + }); + }); + + it("creates defaults when vision.yml has none", () => { + writeNetwork("gc_ip", "239.0.0.2"); + + expect(docOf().defaults).toEqual({ network: { gc_ip: "239.0.0.2" } }); + }); + + it("writes the tracker into its own block", () => { + docOf().tracker = { port: 10010 }; + + writeNetwork("tracker_ip", "239.0.0.3"); + + expect(docOf().tracker).toEqual({ ip: "239.0.0.3", port: 10010 }); + expect(docOf().defaults).toBeUndefined(); + }); + + it("writes nothing before the document has loaded", () => { + config.doc = null; + + writeNetwork("vision_ip", "239.0.0.4"); + writeInterfaces(false, ["eth0"]); + + expect(config.doc).toBeNull(); + }); +}); + +describe("interfaces", () => { + it("are automatic with no skip list by default", () => { + expect(interfaceSelection()).toEqual({ auto: true, skip: [] }); + }); + + it("write a skip list only when there is one", () => { + writeInterfaces(false, ["docker0"]); + expect(interfaceSelection()).toEqual({ auto: false, skip: ["docker0"] }); + + writeInterfaces(true, []); + expect(docOf().host?.interfaces).toEqual({ auto: true }); + }); +}); + +describe("headerSockets", () => { + it("shows the configured addresses until the host reports", () => { + const sockets = headerSockets(); + + expect(sockets.map((s) => s.fallback)).toEqual([ + "224.5.23.2:10006", + "224.5.23.1:10003", + "224.5.23.2:10010", + ]); + expect(sockets.every((s) => s.status === undefined)).toBe(true); + }); + + it("has no fallback before the document loads", () => { + config.doc = null; + + expect(headerSockets().map((s) => s.fallback)).toEqual([ + undefined, + undefined, + undefined, + ]); + }); +}); + +describe("format checks", () => { + it.each([ + ["224.5.23.2", null], + ["0.0.0.0", text.errors.zeroAddress], + ["256.1.1.1", text.errors.notIPv4], + ["1.2.3", text.errors.notIPv4], + ["1.2.3.4.5", text.errors.notIPv4], + ["a.b.c.d", text.errors.notIPv4], + ["1.2.3.1234", text.errors.notIPv4], + ["", text.errors.notIPv4], + ])("ipv4Error(%j)", (ip, want) => { + expect(ipv4Error(ip)).toBe(want); + }); + + it.each([ + [1, null], + [65535, null], + [0, text.errors.portRange], + [65536, text.errors.portRange], + [10006.5, text.errors.portRange], + [Number.NaN, text.errors.portRange], + ])("portError(%j)", (port, want) => { + expect(portError(port)).toBe(want); + }); +}); + +describe("presets", () => { + it("offer the standard group, broadcast, and each used interface's broadcast once", () => { + const presets = addressPresets("vision", [ + iface("eth0", "192.168.1.255"), + iface("eth1", "192.168.1.255"), + iface("wlan0", "10.0.0.255", false), + iface("tun0", ""), + ]); + + expect(presets.map((p) => p.value)).toEqual([ + STANDARD.vision.ip, + "255.255.255.255", + "192.168.1.255", + ]); + }); + + it("offer the standard, backup and, for vision only, legacy ports", () => { + expect(portPresets("vision").map((p) => p.value)).toEqual([ + 10006, 10016, 10005, + ]); + expect(portPresets("gc").map((p) => p.value)).toEqual([10003, 10013]); + }); +}); + +describe("addressAdvice", () => { + const advise = ( + ip: string, + kind: "vision" | "gc" | "tracker" = "vision", + state: NetworkState | null = null, + ) => addressAdvice(ip, kind, state); + + it("is silent for the standard group and for malformed input", () => { + expect(advise("224.5.23.2")).toEqual({ warnings: [], notes: [] }); + expect(advise("not an ip")).toEqual({ warnings: [], notes: [] }); + }); + + it("warns about loopback, reserved and source-specific groups", () => { + expect(advise("127.0.0.1").warnings).toEqual([text.address.loopback]); + expect(advise("224.0.0.5").warnings).toEqual([text.address.reserved]); + expect(advise("232.1.1.1").warnings).toEqual([text.address.sourceSpecific]); + }); + + it("notes another kind's standard group, but not one this kind shares", () => { + expect(advise("224.5.23.1", "vision").notes).toContain( + text.address.otherStandard(text.kind.gc), + ); + expect(advise("224.5.23.2", "tracker").notes).toEqual([]); + }); + + it("notes a non-standard group, and one sharing a MAC with a standard group", () => { + expect(advise("239.5.23.2").notes).toEqual([ + text.address.nonStandard, + text.address.sameMac("224.5.23.2"), + ]); + expect(advise("239.255.1.1").notes).toEqual([text.address.nonStandard]); + }); + + it("notes broadcast to all, or on a known interface", () => { + expect(advise("255.255.255.255").notes).toEqual([ + text.address.broadcastAll, + ]); + + const state = netState({ interfaces: [iface("eth0", "192.168.1.255")] }); + expect(advise("192.168.1.255", "vision", state).notes).toEqual([ + text.address.broadcastOn("eth0"), + ]); + }); + + it("warns about an unknown broadcast address and about unicast", () => { + expect(advise("10.1.1.255").warnings).toEqual([ + text.address.unknownBroadcast, + ]); + expect(advise("10.1.1.7").warnings).toEqual([text.address.unicast]); + }); +}); + +describe("portAdvice", () => { + it("is silent for the standard port, and for an invalid one", () => { + expect(portAdvice(10006, "vision", null)).toEqual({ + warnings: [], + notes: [], + }); + expect(portAdvice(0, "vision", null)).toEqual({ warnings: [], notes: [] }); + }); + + it("names the legacy, backup and other known ports", () => { + expect(portAdvice(10005, "vision", null).notes).toEqual([text.port.legacy]); + expect(portAdvice(10016, "vision", null).notes).toEqual([text.port.backup]); + expect(portAdvice(10003, "vision", null).notes).toEqual([ + text.port.known("the game controller"), + ]); + expect(portAdvice(10005, "gc", null).notes).toEqual([ + text.port.known("legacy vision"), + ]); + expect(portAdvice(12345, "gc", null).notes).toEqual([ + text.port.nonStandard, + ]); + }); + + it("notes a privileged port, using the host's own limit and root state", () => { + expect(portAdvice(80, "gc", null).notes[0]).toBe( + text.port.privileged(1024, false), + ); + + const state = netState({ + unprivilegedPortStart: 0, + root: true, + }); + expect(portAdvice(80, "gc", state).notes).toEqual([text.port.nonStandard]); + + const rootState = netState({ + unprivilegedPortStart: 2000, + root: true, + }); + expect(portAdvice(1500, "gc", rootState).notes[0]).toBe( + text.port.privileged(2000, true), + ); + }); +}); diff --git a/gui/frontend/src/lib/util.test.ts b/gui/frontend/src/lib/util.test.ts new file mode 100644 index 0000000..dc1f3d7 --- /dev/null +++ b/gui/frontend/src/lib/util.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { without } from "./util"; + +describe("without", () => { + it("returns a copy without the key, leaving the original alone", () => { + const o = { a: 1, b: 2 }; + + expect(without(o, "a")).toEqual({ b: 2 }); + expect(o).toEqual({ a: 1, b: 2 }); + }); + + it("returns a new object even when the key is absent", () => { + const o = { a: 1 }; + const out = without(o, "z"); + + expect(out).toEqual(o); + expect(out).not.toBe(o); + }); + + it("treats undefined as empty", () => { + expect(without(undefined, "a")).toEqual({}); + }); +}); diff --git a/gui/frontend/src/lib/wrapper-bus.test.ts b/gui/frontend/src/lib/wrapper-bus.test.ts new file mode 100644 index 0000000..db7436f --- /dev/null +++ b/gui/frontend/src/lib/wrapper-bus.test.ts @@ -0,0 +1,236 @@ +import { get } from "svelte/store"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// test-setup.ts mocks this module for everyone else; here it's the real one, +// against a WebSocket stand-in the test drives by hand. +type Bus = typeof import("./wrapper-bus"); + +class FakeSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static all: FakeSocket[] = []; + + readyState = FakeSocket.CONNECTING; + sent: unknown[] = []; + private listeners = new Map void)[]>(); + + constructor(readonly url: string) { + FakeSocket.all.push(this); + } + + addEventListener(type: string, fn: (event: unknown) => void): void { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]); + } + + send(data: string): void { + this.sent.push(JSON.parse(data)); + } + + close(): void { + if (this.readyState === FakeSocket.CLOSED) return; + this.readyState = FakeSocket.CLOSED; + this.emit("close", {}); + } + + open(): void { + this.readyState = FakeSocket.OPEN; + this.emit("open", {}); + } + + receive(data: unknown): void { + this.emit("message", { + data: typeof data === "string" ? data : JSON.stringify(data), + }); + } + + emit(type: string, event: unknown): void { + for (const fn of this.listeners.get(type) ?? []) fn(event); + } +} + +function latest(): FakeSocket { + const socket = FakeSocket.all.at(-1); + if (!socket) throw new Error("no socket opened"); + return socket; +} + +const noop = (): void => undefined; + +async function loadBus(): Promise { + return vi.importActual("./wrapper-bus"); +} + +beforeEach(() => { + FakeSocket.all = []; + vi.useFakeTimers(); + vi.stubGlobal("WebSocket", FakeSocket); + vi.resetModules(); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe("wrapper-bus", () => { + it("connects to /ws on the page's own host", async () => { + await loadBus(); + + expect(latest().url).toBe(`ws://${location.host}/ws`); + }); + + it("subscribes on open to topics asked for before the socket opened", async () => { + const bus = await loadBus(); + const unsubscribe = bus.topic("config.state").subscribe(noop); + + expect(latest().sent).toEqual([]); + latest().open(); + expect(latest().sent).toEqual([ + { action: "subscribe", topic: "config.state" }, + ]); + + unsubscribe(); + }); + + it("sends one subscribe per topic, however many listen", async () => { + const bus = await loadBus(); + latest().open(); + + const a = bus.topic("alerts.state").subscribe(noop); + const b = bus.topic("alerts.state").subscribe(noop); + + expect(latest().sent).toEqual([ + { action: "subscribe", topic: "alerts.state" }, + ]); + a(); + expect(latest().sent).toHaveLength(1); + b(); + expect(latest().sent).toEqual([ + { action: "subscribe", topic: "alerts.state" }, + { action: "unsubscribe", topic: "alerts.state" }, + ]); + }); + + it("delivers a topic's data, and the latest value to a late subscriber", async () => { + const bus = await loadBus(); + latest().open(); + + const first: unknown[] = []; + const stopFirst = bus + .topic("network.state") + .subscribe((v) => first.push(v)); + latest().receive({ topic: "network.state", data: { n: 1 } }); + latest().receive({ topic: "other.state", data: "ignored" }); + + const late = bus.topic("network.state"); + expect(get(late)).toEqual({ n: 1 }); + expect(first).toEqual([null, { n: 1 }]); + + stopFirst(); + }); + + it("forgets a topic's value once nobody listens", async () => { + const bus = await loadBus(); + latest().open(); + + const stop = bus.topic("processes.state").subscribe(noop); + latest().receive({ topic: "processes.state", data: [1] }); + stop(); + + expect(get(bus.topic("processes.state"))).toBeNull(); + }); + + it("ignores malformed frames, error answers and binary data", async () => { + const bus = await loadBus(); + latest().open(); + const warn = vi.spyOn(console, "warn").mockImplementation(noop); + + const seen: unknown[] = []; + const stop = bus.topic("config.state").subscribe((v) => seen.push(v)); + latest().receive("{not json"); + latest().receive({ + error: "unknown_topic", + message: "no such topic", + topic: "x", + }); + latest().emit("message", { data: new ArrayBuffer(4) }); + + expect(seen).toEqual([null]); + expect(warn).toHaveBeenCalledTimes(2); + + stop(); + warn.mockRestore(); + }); + + it("reports the connection state", async () => { + const bus = await loadBus(); + const states: string[] = []; + const stop = bus.connectionState.subscribe((s) => states.push(s)); + + latest().open(); + latest().close(); + + expect(states).toEqual(["connecting", "open", "closed"]); + stop(); + }); + + it("reconnects with backoff and resubscribes every topic", async () => { + const bus = await loadBus(); + const stopA = bus.topic("a.state").subscribe(noop); + const stopB = bus.topic("b.state").subscribe(noop); + latest().open(); + + latest().close(); + expect(FakeSocket.all).toHaveLength(1); + + vi.advanceTimersByTime(999); + expect(FakeSocket.all).toHaveLength(1); + vi.advanceTimersByTime(1); + expect(FakeSocket.all).toHaveLength(2); + + latest().open(); + expect(latest().sent).toEqual([ + { action: "subscribe", topic: "a.state" }, + { action: "subscribe", topic: "b.state" }, + ]); + + stopA(); + stopB(); + }); + + it("doubles the retry delay up to 5 s, and resets it after a connection", async () => { + await loadBus(); + const delays: number[] = []; + + for (let i = 0; i < 5; i++) { + const count = FakeSocket.all.length; + latest().close(); + let waited = 0; + while (FakeSocket.all.length === count) { + vi.advanceTimersByTime(100); + waited += 100; + } + delays.push(waited); + } + expect(delays).toEqual([1000, 2000, 4000, 5000, 5000]); + + latest().open(); + const count = FakeSocket.all.length; + latest().close(); + vi.advanceTimersByTime(1000); + expect(FakeSocket.all).toHaveLength(count + 1); + }); + + it("closes the socket on an error, which schedules a reconnect", async () => { + await loadBus(); + latest().open(); + + latest().emit("error", {}); + + expect(latest().readyState).toBe(FakeSocket.CLOSED); + vi.advanceTimersByTime(1000); + expect(FakeSocket.all).toHaveLength(2); + }); +}); From 64af243cb4996b1c89d83fe9304aab48d2e39c06 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 18 Nov 2026 10:30:02 -0500 Subject: [PATCH 04/35] remvoe debug panel --- gui/REVIEW.md | 634 ++++++++++++++++++ gui/frontend/e2e/smoke.spec.ts | 1 - gui/frontend/src/lib/advanced.svelte.ts | 26 +- gui/frontend/src/lib/advanced.test.ts | 122 ++++ .../src/lib/config/AdvancedPanel.svelte | 1 + gui/frontend/src/lib/config/ColorPanel.svelte | 5 - .../config/ConfigCategoryPlaceholder.svelte | 50 -- .../src/lib/config/ConfigFieldList.svelte | 43 -- .../src/lib/layout/MainContent.svelte | 6 +- .../src/lib/layout/configCategories.ts | 14 +- gui/frontend/src/lib/text/advanced.ts | 12 +- gui/frontend/src/lib/text/configFields.ts | 13 +- gui/frontend/src/lib/text/placeholder.ts | 10 +- gui/internal/config/schema.go | 2 +- 14 files changed, 786 insertions(+), 153 deletions(-) create mode 100644 gui/REVIEW.md create mode 100644 gui/frontend/src/lib/advanced.test.ts delete mode 100644 gui/frontend/src/lib/config/ConfigCategoryPlaceholder.svelte delete mode 100644 gui/frontend/src/lib/config/ConfigFieldList.svelte diff --git a/gui/REVIEW.md b/gui/REVIEW.md new file mode 100644 index 0000000..32ca54d --- /dev/null +++ b/gui/REVIEW.md @@ -0,0 +1,634 @@ +# MVP review: ssl-vision-processor GUI host + +Baseline `09cf1ee` (API Middleware Tests and Cleanup #40) → `267bae0` (`v2.0-alpha`). +The whole `gui/` tree is reviewed, with extra depth on everything new or changed since the baseline. + +## Scope + +In: `gui/` (Go host, Svelte frontend, OpenAPI, packaging, scripts), `.github/workflows`, +root `README.md` / `documentation.md` / `config/`, `flake.nix`, `scripts/`, `setup.sh`, +and alignment with league repos (ssl-game-controller, ssl-go-tools). + +Out: +- `src/` C++, the VP↔host wire protocol, `proto/`. Findings that would need a C++ change are parked (see below). +- Security posture. Deployments are airgapped and security needs its own plan. + Security-shaped correctness or data-loss bugs are still reported, as correctness. + +## Severity + +This is the first release, so first impressions and deployment quality count as ship criteria. + +- **blocker**: must fix before MVP. Includes: a new user can't install, start, or finish first-run setup from the docs alone; wrong or misleading docs or UI text on the main path; a confusing or silent failure on a common error path; data loss; a broken or unreproducible release artifact. +- **major**: should fix before MVP. Inconsistency a user will notice, a rough edge on a secondary path, a test gap on critical logic, an architecture problem that will cost more once others contribute. +- **minor**: fix before MVP if it's cheap; otherwise next release. +- **nit**: style or polish. + +Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs infra). + +## Status + +Updated 2026-11-18. **Open** 62 · **Partial** 3 · **Done** 3 · **Dropped/merged** 2. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, dropped, merged. + +**Next up** (MVP gate order; see the end of this file): +1. T4-1: "Temporary debug utilities" under every page (last blocker). +2. T2-1 with L-1: bind before starting anything; pick the default port. +3. T5-3, T5-2, T5-4: lab path. + +| ID | Sev | Owner | Item | Status | +|---|---|---|---|---| +| T1-1 | blocker | Claude (Will commits) | 18 MB binary tracked in git | done | +| T1-2 | major | Claude | release tag not gated on `make check` / e2e | open | +| T1-3 | major | Claude + Will | package description promises a VP package that doesn't exist | open | +| T1-4 | minor | Claude | tarball and `-bin` amd64 only (absorbs L-3) | open | +| T1-5 | minor | Claude | stale toolchain and dependencies | open | +| T1-6 | minor | Claude | CI skips the `v2.0-alpha` branch | open | +| T1-7 | minor | Claude | no Go linter beyond vet | open | +| T1-8 | minor | Claude | `setup.sh` still offers `geom_publisher` | open | +| T1-9 | nit | Claude | legacy `.gitlab-ci.yml` | open | +| T1-10 | nit | Claude | unpinned nix actions | open | +| T1-11 | nit | Will | `DEB_MAINTAINER` personal address | open | +| T2-1 | major | Will | HTTP bind happens last; "UI is available" logged early | open | +| T2-2 | minor | Will | publish tick is the host's only clock | open | +| T2-3 | minor | Will | `Store.apply` not atomic | open | +| T2-4 | minor | Will | `main.go` too big | open | +| T2-5 | minor | Will | CLI help | open | +| T2-6 | minor | Will | log keys and messages | open | +| T2-7 | nit | Will | staticcheck hits | partial | +| T3-1 | major | Will | WS topic contract in three places | open | +| T3-2 | major | Will | generated `paths` unused | open | +| T3-3 | major | Will | naming pass before freezing API 1.0 | open | +| T3-4 | minor | Will | response-spec test coverage | partial | +| T3-5 | nit | Will | OpenAPI tag descriptions | open | +| T4-1 | blocker | Will | "Temporary debug utilities" on every page | open | +| T4-2 | major | Will | edits lost while host unreachable | open | +| T4-3 | minor | Will | rejected value stays in the form | open | +| T4-4 | minor | Will | no stale-frontend detection | open | +| T4-5 | minor | Will | large components | open | +| T4-6 | minor | Will | bus still on `svelte/store` | open | +| T4-7 | nit | Will | hex colours | open | +| T4-8 | nit | Claude | Flowbite `@source` CSS bloat | open | +| T5-1 | blocker | Will | placeholder Debug page | done | +| T5-2 | major | Will | crash-looping VP raises no alert | open | +| T5-3 | major | Will | SPINNAKER default driver | open | +| T5-4 | major | Will | 4 warnings on a fresh install | open | +| T5-5 | major | Will | accessibility (labels, contrast) | open | +| T5-6 | major | Will | two navigation systems | open | +| T5-7 | minor | Will | first-run wording | open | +| T5-8 | minor | Will | broken image in corner picker | open | +| T5-9 | minor | Will | Camera page edits undeliverable settings | open | +| T5-10 | — | — | phone widths | dropped | +| T5-11 | nit | Will | Gamma toggle label | open | +| T6-1 | major | Claude (Will reviews) | `ARCHITECTURE.md` drift | open | +| T6-2 | minor | Claude (Will decides) | `CLAUDE.md` vs `ARCHITECTURE.md` split | open | +| T6-3 | minor | Claude | frontend README describes old tabs | open | +| T6-4 | minor | Claude | README relative links break when shipped | open | +| T6-5 | major | Claude + Will | quick start stops at first save | open | +| T6-6 | minor | Claude | root README pointers | open | +| T6-7 | nit | Claude | README details | open | +| T7-1 | major | Will | no component tests | open | +| T7-2 | major | Will | untested logic modules | partial | +| T7-3 | major | Will | flowbite `Input` unmount error (`test.fail`) | open | +| T7-4 | major | Will + Claude | e2e scenario gaps, axe | open | +| T7-5 | minor | Claude | frontend coverage tooling | done | +| T7-6 | nit | Claude | coverage for binary-only paths | open | +| T7-7 | nit | Will | `time.Sleep` in Go tests | open | +| T7-8 | minor | Will | `yuvInGamut` rounding tolerance | open | +| T8-1 | major | Will | four product names | open | +| T8-2 | minor | Will + Claude | page names | open | +| T8-3 | minor | Will | identifier naming across layers | open | +| T8-4 | minor | Will | text centralization | open | +| T8-5 | nit | Will | `--` as em dash | open | +| L-1 | major | Will | port 8085 collides with remote-control | open | +| L-2 | minor | Will | league-style address flags | open | +| L-3 | — | — | arm64 assets | merged (T1-4) | +| L-4 | minor | Claude | no dependency bot | open | +| L-5 | major | Will | duplicate GC flaps referee state | open | +| L-6 | nit | Claude | `CLAUDE.md` sslnet note | open | +| L-7 | nit | Will | `-verbose` alias | open | +| L-8 | nit | Claude | docker image | open | + +Upstream proposals (U-1..U-5) are tracked in "League alignment", not here. + +## Plan + +Phase 0, automated gates: `make check`, `make e2e`, `make release-check` from a clean tree; +staticcheck, govulncheck, svelte-check, npm audit, unused deps/exports; +Go and Vitest coverage per module; bundle size; Lighthouse a11y/perf. + +Tracks: +1. Repo hygiene / release: tracked artifacts, CI vs `make check` parity, release workflow, `.deb`, nix/non-nix independence, Makefile. +2. Go architecture: package graph, `main.go` wiring, lifecycle/shutdown, concurrency, error and log conventions, supervisor, config store invariants. +3. API / OpenAPI contract: route conformance, error codes, naming/verb consistency, WS topic shapes, generated TS use. +4. Frontend architecture: state modules, runes and `$effect` hygiene, oversized components, Flowbite/token rules, fetch/WS failure paths, canvas performance. +5. New-user UX (hands-on): first run → wizard → checklist; `-runCameras` webcam lab; competition mode; failure paths; save/load conflict; narrow screens, dark mode, keyboard, a11y; wording. +6. Documentation: every claim and command checked against the code; user vs contributor split; can a new user install from the `.deb` with docs alone. +7. Tests: test-type × module matrix, gaps, flakiness, stale `test.fail`, CI coverage, component tests, e2e vs track 5 scenarios. +8. Cross-cutting consistency: naming, terminology across Go/TS/UI/docs, message style, config keys, text centralization ahead of i18n. +9. League alignment: compare with ssl-game-controller and current ssl-go-tools master. What can we now use from upstream, and what of ours should go upstream? Every upstream candidate must be additive or non-breaking for existing ssl-go-tools users; anything else is listed as "keep local". + +Order: 0 → 1, 3, 7 → 2, 4 → 5 → 6, 8. Track 9 runs alongside. + +## Phase 0 results + +Run 2026-11-11 on `267bae0` (branch `dev/will/code_review_2`), inside the nix shell (go 1.26.7, node 22.23). + +| Gate | Result | +|---|---| +| `make check` | pass, 26 s. e2e: 13/13. `smoke.spec.ts:139` "leaving a page right after an edit" is a `test.fail` known bug, still failing (track 7) | +| loopback multicast tests | **skipped locally** (lo multicast off); they only run in CI | +| `make release-check` | pass | +| `svelte-check` / `tsc` (`npm run check`) | 0 errors, 0 warnings. A bare `npx svelte-check` warns about tsconfig project references; harmless | +| eslint, prettier | clean | +| staticcheck | 2 hits: `internal/config/store_test.go:506` (SA4006 unused `rev`), `internal/logging/logging.go:83` (SA1019 deprecated `tint.NewHandler`) | +| govulncheck | 10 reachable stdlib vulns fixed by go **1.26.11**; `golang.org/x/net` 0.55 → 0.60. Treated as release hygiene: bump before tagging | +| npm audit | 23 (5 high, 12 moderate, 6 low). Almost all in dev/build tooling (vite, eslint, undici, minimatch). Runtime: `svelte` (SSR-only advisories, we're CSR), `flowbite` via `flowbite-datepicker`. `npm update` within ranges clears most | +| Vitest coverage | not measurable: `@vitest/coverage-v8` not installed (track 7) | +| Bundle | one 678 kB JS chunk (192 kB gz), **294 kB CSS** (40 kB gz). Fine on a LAN; CSS size points at an unpurged Flowbite/Tailwind source scan (track 4) | + +Go coverage by package (statements): + +| ≥90% | 70–90% | <70% | +|---|---|---| +| alerts 99, detections 100, origins 99, v4l 97, livefield 96, peers 95, supervisor 93, referee 93, hub 90 | geometry 89, config 89, multicast 86 (more with lo multicast on), discovery 85, snapshot 84, logging 78, buildinfo 73 | **cmd 63**, api 67, video 69, defaults 60, httpjson 0 (no tests), api/gen 0 | + +Lighthouse a11y/perf is deferred to track 5 (needs a running host). + +## Findings + +Format: `ID | severity | owner | location` then the issue, the evidence, and the fix. + +### Track 1: repo hygiene / release + +Overall: strong. Packaging (nfpm, debconf, sysusers, upgrade semantics, lintian, `deb-check.sh` on a real systemd runner), the static release build, `release-check.sh`, and the nix/apt CI split all hold up. The findings are about what ships and when. + +**T1-1 | blocker | Claude (Will commits) | `gui/ssl-vision-processor-gui`** +An 18 MB host binary is tracked in git, added in `97a0669` ("rename binary, initial debian bundle"), even though `.gitignore:47` ignores it, because it was added before the ignore. It is on `v2.0-alpha` but **not** yet in `origin/master`. +Fix: `git rm --cached gui/ssl-vision-processor-gui`. Before `v2.0-alpha` merges to master, drop the blob from the branch: squash-merge, or rewrite `97a0669` on the branch, so master's clone never carries it. +*Progress 2026-11-17 (Claude):* history rewritten locally with `git filter-branch --index-filter` over `97a0669^..` minus `origin/master`, so master's signed commits keep their hashes. Rewritten: `v2.0-alpha` 267bae0→2f14289, `dev/will/code_review_2` 1d081ba→0395479, `dev/will/fixes_from_lab_testing_11102026` fd3f377→9e434d1, `dev/will/distribution` 97a0669→347f9d7. Verified: each tip differs from its backup only by the binary; no branch contains the blob; same commits, metadata and merge base (`5f75bea`); `make check` passes. Backups: tags `backup/*` and `refs/original`. +*Done 2026-11-17 (Claude, Will approved):* force-pushed `v2.0-alpha` (2f14289, PR #37 updated, mergeable), `dev/will/code_review_2` (0395479) and `dev/will/fixes_from_lab_testing_11102026` (9e434d1). No remote branch contains `97a0669`. Follow-up: other clones reset or rebase onto the new tips; after about a week, delete the `backup/*` tags and `refs/original` and gc. + +**T1-2 | major | Claude | `.github/workflows/release.yml`** +A `v*` tag publishes a public GitHub Release after only `release-check` and `deb-check`. `make check` and the e2e suite never run against the tagged commit; CI runs on master pushes and PRs, but a tag can point anywhere. `gh release create` also publishes immediately, with no draft. +Fix: run `make check` (including e2e) in the release job before building, or gate it on the CI workflow for that SHA. Create the release as `--draft` and publish by hand after a smoke install. Mark `-rc`/`-alpha` tags `--prerelease`. + +**T1-3 | major | Claude + Will | `gui/packaging/nfpm.yaml:26`, release notes, `gui/README.md`** +The package description says "The camera processing itself, vision_processor, is packaged separately", but no vision_processor package exists yet (the CV deb is planned). A new user who installs the `.deb` from the first release has a GUI with nothing to talk to, and nothing on the release page says how to get vision_processor. The `v*` tag also reads as a release of the whole repo while it ships only the GUI. +Fix: until the CV deb ships, change the description to "build vision_processor from source: see ". Give the GitHub Release a body template (`--notes-file`) saying what's included and pointing at the vision_processor build steps. Decide whether GUI releases get their own tag prefix once the CV deb exists. + +**T1-4 | minor | Claude | `gui/Makefile:63-75`** +The tarball and `-bin` are built only for the host's `GOARCH` (amd64 in CI), while the debs are amd64 and arm64. arm64 users (Pi, Jetson) get the deb but no standalone binary, though `gui/README.md` presents the standalone binary as the first install path. +Fix: loop `release` over `DEB_ARCHES` (or a `RELEASE_ARCHES`), and include both in `SHA256SUMS`. + +**T1-5 | minor | Claude | `flake.lock`, `gui/go.mod`, `gui/frontend/package-lock.json`** +Stale toolchain and dependencies at release time: go 1.26.7 (10 reachable stdlib advisories fixed by 1.26.11), `golang.org/x/net` 0.55 (0.60), 23 `npm audit` entries, most cleared by in-range `npm update`. +Fix: bump all three before tagging. Add `govulncheck` as a non-blocking CI step, or to a pre-release checklist. + +**T1-6 | minor | Claude | `.github/workflows/ci.yml:3-6`** +CI runs on `push: [master]` and PRs only. `v2.0-alpha`, the integration branch the MVP ships from, is tested only when a PR targets it; direct pushes and merges into it (e.g. `443d12a`, `fd10e0b`) are never built. +Fix: add `v2.0-alpha` (or `v*-alpha`) to `push.branches` until it merges. + +**T1-7 | minor | Claude | `gui/Makefile`, CI** +No Go linter beyond `vet`. staticcheck finds two things today (`internal/config/store_test.go:506` dead assignment; `internal/logging/logging.go:83` deprecated `tint.NewHandler`). +Fix: `go get -tool honnef.co/go/tools/cmd/staticcheck`, run it in `make check` / the `gui-go` job. Will fixes the two hits. + +**T1-8 | minor | Claude | `setup.sh:126-131`** +The C++ setup script still offers a `geom_publisher` user service and never mentions the GUI. A user who answers `y` and later runs the GUI has two geometry publishers. The host raises a `sender_conflict` error for that (`internal/alerts/alerts.go:107`), so it's caught, but it's an avoidable first-day trap. Also a typo: "installationa". +Fix: drop the prompt, or print "the GUI (gui/README.md) replaces this; say no unless you aren't using it", with default `N` (already the default). + +**T1-9 | nit | Claude | `.gitlab-ci.yml`** +A legacy C++-only build on `ubuntu:latest`, duplicating `build-apt` in GitHub CI and pinned to nothing. Remove it, or note who still uses it. + +**T1-10 | nit | Claude | `.github/workflows/*.yml`** +`DeterminateSystems/nix-installer-action@main` and `magic-nix-cache-action@main` are unpinned, so the release build's toolchain setup can change under a tag. Pin to a release tag. + +**T1-11 | nit | Will | `gui/Makefile:84`** +`DEB_MAINTAINER` defaults to a personal address. Decide whether the league package should name a team or committee alias. + +### Track 2: Go architecture + +Overall: sound. The import graph is acyclic and layered, with `cmd` doing the wiring and `alerts` as the only aggregator. `host`/`newHost` separates wiring from running, which is what makes the cmd tests possible. The store's revision and stale-write protocol, the supervisor's crash backoff, and context-driven shutdown are all well thought out. The findings are about startup order, the single 1 Hz tick, and log hygiene. + +**T2-1 | major | Will | `cmd/ssl-vision-processor-gui/main.go:182-243`** +The HTTP listener is bound last, inside a goroutine, after the multicast loops, the geometry publisher and (with `-runCameras`) the supervisor have started. "UI is available" is logged before the bind is known to have worked. Reproduced with the port already in use: +``` +INF main.go:243 UI is available url=http://127.0.0.1:28123 +ERR main.go:233 http server init failed err="listen tcp 127.0.0.1:28123: bind: address already in use" +INF initiating graceful shutdown +INF multicast/endpoint.go:291 socket open endpoint=vision ... (opened during shutdown) +``` +A new user sees a URL that doesn't work. Under the system service (`Restart=on-failure`, 5 s) the host also starts and kills every supervised vision_processor in a loop. Given L-1 (port collision with remote-control), this is a likely first-day failure. +Fix: `net.Listen` synchronously right after `newHost` and before any `runBackground`, then `srv.Serve(ln)`. On `EADDRINUSE`, log a plain-language error naming the port and `-address` (and `/etc/default/ssl-vision-processor-gui` for the service), then exit 1 without starting anything. + +**T2-2 | minor | Will | `main.go:187-207`** +The geometry publish tick is the host's only clock. Every second it also checks for suspend, re-lists interfaces and reapplies the sockets, refreshes the heights file, and publishes config state, status, alerts and processes. That ties unrelated work to `Geometry.Run`'s lifetime and makes a slow step (interface listing, heights-file stat) delay geometry publishing. +Fix: a separate `housekeeping` loop (`runBackground`) for socket/suspend/status work, leaving the geometry tick to send and publish geometry only. + +**T2-3 | minor | Will | `internal/config/store.go:262-274`, `:484-491`** +`apply` is not atomic. It pushes the field (`ApplyConfig`), then the locked calibrations (`SetLocked`), then renders every camera's `config.yml`. A failure after the first step returns an error with live geometry (and, in `update`, the `Unlock` loop) already changed but `working` not updated. `loadLocked` restores `s.path` on failure but not the live state. Unlikely in practice, since the inputs are validated first, but the failure leaves the published geometry disagreeing with the document the GUI shows. +Fix: build everything first (models, locked map, renders into memory), then commit in one step; or on error re-apply the previous `working`. + +**T2-4 | minor | Will | `main.go` (964 lines)** +It mixes flag definitions, path bootstrap, firewall and ufw sniffing, socket management (`networkSockets`), topic publishing and the run loop. +Fix: split by concern (`flags.go`, `bootstrap.go`, `network.go`, `publish.go`) as `paths.go` and `status.go` already are. No behaviour change, but it's the first file a new contributor opens. + +**T2-5 | minor | Will | CLI help (`main.go:42-66`)** +`-h` prints every default twice ("default: :8085 (default ":8085")", "Default: Info (default "Info")"), starts with "Usage of bin/release/…/ssl-vision-processor-gui:" and has no one-line description, no URL hint and no pointer to `-readme` or the man page. `-openapi` is a build-time flag listed among the user options. +Fix: a custom `flag.Usage` (one-line description, "open http://localhost:PORT", "see -readme"), drop the hand-written "Default:" where `flag` prints it, and list `-openapi` under a "development" heading. + +**T2-6 | minor | Will | log keys and messages across `cmd/`, `internal/`** +The camera is logged as `cam` (14), `camera` (6), `id` (6) and `camera_id` (1). Key case mixes `logFile`/`runDir`/`retryIn` with `camera_id`. Messages mix styles: "Init VP GUI" (jargon, title case) next to "mode", "starting", "loaded config" (bare nouns). Users read these in the log panel and journal, and bug reports grep them. +Fix: one key per concept (`camera`, `err`, `path`, `interface`) in one case, and messages as short lower-case sentences. "Init VP GUI" should be "starting ssl-vision-processor-gui". Consider dropping source `file:line` from Info-level console output, keeping it for Debug and the file log. + +**T2-7 | nit | Will | `internal/logging/logging.go:83`, `internal/config/store_test.go:506`** +The staticcheck hits from Phase 0: deprecated `tint.NewHandler` → `tint.NewTextHandler`, and an unused `rev` assignment. +*Progress 2026-11-11 (Claude):* the `store_test.go` dead assignment is fixed. `tint.NewHandler` is application code and remains. + +### Track 3: API / OpenAPI contract + +Overall: the REST half is well disciplined. Every route goes through `api.Route`/`Raw`, every one has an operation summary and tag, `TestMain` in `declared_test.go` fails on any undeclared error code, and the error envelope is uniform. The weak half is the WebSocket contract and the frontend's use of the spec. + +**T3-1 | major | Will | `cmd/ssl-vision-processor-gui/docs.go:33-40`, `main.go:591-833`, `frontend/src/lib/wrapper-bus.ts:141`** +The WS topic contract is hand-maintained in three places and has already drifted. The spec's topic table lists 5 topics; the host serves 7 (`instances.state` at `main.go:790` and `live_field.frames` are missing). Topic names are string literals on both sides. Each frontend subscriber asserts its own payload type (`topic("config.state")`), so a wrong name or type compiles. +Fix: one topic registry in Go (name → payload type → equivalent route) that drives `/api/topics`, the spec's topic table (or an `x-topics` extension with schema refs), and a test that every hub topic is registered. Generate a TS `TopicMap` from it so `topic("config.state")` infers its type and an unknown name fails to compile. + +**T3-2 | major | Will | `frontend/src/lib/*.svelte.ts`, `api.ts`** +The frontend uses only `components["schemas"]` from the generated file, never `paths`. There are 30 hand-written `/api/...` URL strings and 12 `response.json()` results cast to a type, so a wrong path, method, query parameter or body shape still type-checks, which is exactly the drift the generated types exist to catch. +Fix: `openapi-fetch` (same author as `openapi-typescript`, ~6 kB, no runtime schema) typed against `paths`. It makes `client.GET("/api/config/cameras/{id}/effective", {params: {path: {id}}})` checked end to end and removes most casts. `requestJSON`/`errorMessage` can stay as its error middleware. + +**T3-3 | major | Will | public route and topic names; `docs.go:19`** +`specVersion` is `1.0.0`, and its comment promises that changing or removing anything means `/api/v2`. Once the API ships in a release with docs at `/api/docs`, other teams will script against these names; it's cheap to rename now and costly later. Current inconsistencies: +- case: `/api/live_field` (snake) vs `/api/config/save-as` (kebab) +- number: `/api/camera/devices` vs `/api/config/cameras/{id}`; `/api/snapshot/{camID}/{view}` vs `/api/snapshots` +- path params: `{camID}` vs `{id}` +- topics: `wrapper_packet.out` vs `*.state` vs `live_field.frames` +- operationIds: `getConfig`/`getAlerts` vs bare nouns (`network`, `instances`, `load`, `system`). The snapshot route and both WebSockets have none, so generated clients and Redoc anchors fall back to unstable names. + +Fix: pick one convention (kebab-case paths, plural collections, `{id}`, `verbNoun` operationIds, `.state` topics), apply it before the release, and consider `0.x` for the spec version until after the first event. + +**T3-4 | minor | Will | `cmd/ssl-vision-processor-gui/responses_test.go:17-33`** +`TestResponsesMatchTheSpec` checks a hand-kept list of 16 GET routes. A new GET route is silently unchecked, and `/api/geometry`, every write route's 200 body and the error envelope are never validated. `conforms` checks nullability, enums and required fields only. +Fix: derive the GET list from the spec and fail on any route not exercised. Add write-route and error-envelope checks. If the custom validator keeps growing, swap it for `kin-openapi`'s `openapi3filter` in tests only. +*Progress 2026-11-11 (Claude):* `TestEveryGETRouteIsChecked` now fails when a GET route is neither checked nor listed as non-JSON, and `/api/geometry` was added to the checked set. Still open: write-route 200 bodies and the error envelope. + +**T3-5 | nit | Will | `cmd/ssl-vision-processor-gui/routes.go`** +Tags (`Status`, `Host-local`, `Configuration`, `Field`, `Live updates`) have no descriptions and no top-level `tags` order, so Redoc orders groups by first use. `/api/live_field` sits under "Field" while its topic sits under "Live updates". Add a top-level `tags` list with one-line descriptions. + +### Track 4: frontend architecture + +Overall: the state modules (`*.svelte.ts`) are a clean, consistent pattern: one owner module per concern, `$effect.root` for module-level persistence, and `localStorage` wrapped in try/catch everywhere. Flowbite and token discipline holds (every raw ` - - {#if subscribed} - {#if wrapperPacket} -
{JSON.stringify(wrapperPacket, null, 2)}
- {:else} -

Waiting for first frame…

- {/if} - {/if} - - {/snippet} - + - - diff --git a/gui/frontend/src/lib/SnapshotViews.svelte b/gui/frontend/src/lib/SnapshotViews.svelte new file mode 100644 index 0000000..9b4d262 --- /dev/null +++ b/gui/frontend/src/lib/SnapshotViews.svelte @@ -0,0 +1,84 @@ + + + +
+

{intro}

+ +
+ + {#if error} +

{text.failed(error)}

+ {:else if shown.length === 0} +

{empty}

+ {:else} +
+ {#each shown as v (v.view)} +
+ + {`cam + +
+ {v.label} +
+
+ {/each} +
+ {/if} +
diff --git a/gui/frontend/src/lib/advanced.svelte.ts b/gui/frontend/src/lib/advanced.svelte.ts index 8702bde..cf30219 100644 --- a/gui/frontend/src/lib/advanced.svelte.ts +++ b/gui/frontend/src/lib/advanced.svelte.ts @@ -40,7 +40,7 @@ export const ADVANCED: Record< { block: "tracking", key: "max_bot_acceleration" }, ], // debug:'s other keys stay hand-edited in vision.yml: ground_truth is for - // the benchmarks, debug_images writes outside img/, and wait_for_geometry + // the benchmarks, debug_images' files lack a camera prefix, and wait_for_geometry // hangs a first run (nothing is published before the first save). diagnostics: [{ block: "debug", key: "debug_stream_interval_ms" }], }; diff --git a/gui/frontend/src/lib/config/ColorPanel.svelte b/gui/frontend/src/lib/config/ColorPanel.svelte index dfa8462..b694bcb 100644 --- a/gui/frontend/src/lib/config/ColorPanel.svelte +++ b/gui/frontend/src/lib/config/ColorPanel.svelte @@ -1,4 +1,6 @@ + +{#if hostUpdated()} + + {app.hostUpdated(hostVersion.page ?? "", hostVersion.host ?? "")} + + +{/if} diff --git a/gui/frontend/src/lib/alerts/alert-codes.json b/gui/frontend/src/lib/alerts/alert-codes.json index dc9e634..2ec860a 100644 --- a/gui/frontend/src/lib/alerts/alert-codes.json +++ b/gui/frontend/src/lib/alerts/alert-codes.json @@ -8,6 +8,7 @@ "first_run_not_publishing", "heights_unreadable", "loopback_multicast_off", + "process_crashing", "region_uncovered", "render_failed", "seed_aspect_mismatch", diff --git a/gui/frontend/src/lib/alerts/alerts.ts b/gui/frontend/src/lib/alerts/alerts.ts index bf368dd..318c544 100644 --- a/gui/frontend/src/lib/alerts/alerts.ts +++ b/gui/frontend/src/lib/alerts/alerts.ts @@ -160,6 +160,16 @@ function present(a: HostAlert): Alert { detail: text.deviceConflictDetail(str("conflict")), actions: [howTo("device-conflict")], }; + case "process_crashing": + return { + ...base, + title: text.processCrashing(a.cameraId ?? 0, Number(p["crashes"])), + detail: text.processCrashingDetail(str("lastLine"), str("exit")), + actions: [ + howTo("process-crashing"), + page(text.pages.camera, a.cameraId, "camera"), + ], + }; case "first_run_not_publishing": return { ...base, diff --git a/gui/frontend/src/lib/apiTypes.ts b/gui/frontend/src/lib/apiTypes.ts index 985766c..53a2702 100644 --- a/gui/frontend/src/lib/apiTypes.ts +++ b/gui/frontend/src/lib/apiTypes.ts @@ -72,3 +72,4 @@ export type LogRecord = Schemas["LoggingRecord"]; export type LogLevel = LogRecord["level"]; export type BuildInfo = Schemas["BuildinfoInfo"]; export type GitState = Schemas["BuildinfoGit"]; +export type HealthResponse = Schemas["HealthResponse"]; diff --git a/gui/frontend/src/lib/color.svelte.ts b/gui/frontend/src/lib/color.svelte.ts index a39e4f5..9a52b5f 100644 --- a/gui/frontend/src/lib/color.svelte.ts +++ b/gui/frontend/src/lib/color.svelte.ts @@ -56,8 +56,12 @@ export function yuvToRgb(c: YUV): RGB { // ones (YuvPositionPane.svelte shades the unreachable ones on its canvas, // same convention as a CIE chromaticity diagram graying out everything // outside the sRGB triangle). +// rgbToYuv rounds to integers, which can put a real color (white, every +// saturated primary) up to ~2.9 outside, so a smaller overflow still counts. +export const GAMUT_TOLERANCE = 3; + export function yuvInGamut(c: YUV): boolean { - return yuvGamutOverflow(c) === 0; + return yuvGamutOverflow(c) < GAMUT_TOLERANCE; } // How far the unclamped decode lands outside [0,255], summed over R/G/B -- diff --git a/gui/frontend/src/lib/color.test.ts b/gui/frontend/src/lib/color.test.ts index ac0a3e0..68798b7 100644 --- a/gui/frontend/src/lib/color.test.ts +++ b/gui/frontend/src/lib/color.test.ts @@ -79,14 +79,16 @@ describe("gamut", () => { } }); - // Known bug (REVIEW.md T7-8): yuvInGamut has no rounding tolerance, so - // rgbToYuv's integer rounding leaves ~4% of real colors, every saturated - // primary and white among them, outside by up to 2.9. Remove .fails once fixed. - it.fails("holds every color an RGB camera can produce", () => { + it("holds every color an RGB camera can produce", () => { for (const cls of COLOR_CLASSES) { expect(yuvInGamut(rgbToYuv(CANONICAL_COLORS[cls])), cls).toBe(true); } expect(yuvInGamut(rgbToYuv({ r: 255, g: 255, b: 255 }))).toBe(true); + for (let r = 0; r <= 255; r += 5) + for (let g = 0; g <= 255; g += 5) + for (let b = 0; b <= 255; b += 5) { + expect(yuvInGamut(rgbToYuv({ r, g, b }))).toBe(true); + } }); it("excludes saturated chroma at extreme brightness", () => { diff --git a/gui/frontend/src/lib/config.svelte.ts b/gui/frontend/src/lib/config.svelte.ts index 93f9f17..b7a572e 100644 --- a/gui/frontend/src/lib/config.svelte.ts +++ b/gui/frontend/src/lib/config.svelte.ts @@ -57,13 +57,16 @@ export const config = $state<{ }); const PUT_DEBOUNCE_MS = 250; +// How soon an edit the host didn't receive is sent again. +const RETRY_MS = 2_000; -// JSON of the doc as last sent to (or received from) the host -- the root +// JSON of the doc as last accepted by (or received from) the host -- the root // effect compares against this so a doc that just arrived from the host isn't -// echoed straight back. +// echoed straight back, and an edit that never arrived is still unsent. let lastSynced = ""; let putTimer: ReturnType | null = null; -let inFlight: Promise | null = null; +let retryTimer: ReturnType | null = null; +let inFlight: Promise | null = null; export function cameraDoc(cameraId: number): CameraDoc | undefined { return config.doc?.cameras.find((c) => c.cameraId === cameraId); @@ -102,9 +105,11 @@ export async function loadConfig(): Promise { // Resolves once no edit is waiting to be sent or in flight, so a save sees // everything the user has typed. export async function flushEdits(): Promise { - if (putTimer !== null) { - clearTimeout(putTimer); + if (putTimer !== null || retryTimer !== null) { + if (putTimer !== null) clearTimeout(putTimer); + if (retryTimer !== null) clearTimeout(retryTimer); putTimer = null; + retryTimer = null; void sendPending(); } @@ -121,41 +126,66 @@ function schedulePut(): void { } async function sendPending(): Promise { - if (inFlight) { - await inFlight; - } + // A loop: another waiter may have started the next send first. + while (inFlight) await inFlight; const json = JSON.stringify(config.doc); if (!config.doc || json === lastSynced) return; - lastSynced = json; inFlight = putDoc(json); + let delivered: boolean; try { - await inFlight; + delivered = await inFlight; } finally { inFlight = null; } + if (!delivered) { + retryLater(); + + return; + } + // Anything typed while that was in flight goes out next. if (JSON.stringify(config.doc) !== lastSynced) void sendPending(); } -async function putDoc(json: string): Promise { - const response = await fetch("/api/config", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: `{"revision":${String(config.revision)},"document":${json}}`, - }); +function retryLater(): void { + if (retryTimer !== null) return; + + retryTimer = setTimeout(() => { + retryTimer = null; + void sendPending(); + }, RETRY_MS); +} + +// False when the host never answered (restarting, network down): the edit +// stays unsent. Any answer, even a refusal, counts as delivered. +async function putDoc(json: string): Promise { + let response: Response; + + try { + response = await fetch("/api/config", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: `{"revision":${String(config.revision)},"document":${json}}`, + }); + } catch { + config.error = app.notSent; + + return false; + } if (response.ok) { + lastSynced = json; config.revision = ( (await response.json()) as { revision: number } ).revision; config.error = null; await refreshFieldMarkings(); - return; + return true; } if (response.status === 409) { @@ -164,10 +194,14 @@ async function putDoc(json: string): Promise { config.error = app.editedElsewhere; await loadConfig(); - return; + return true; } + // Refused (T4-3: the form keeps the refused value until the next edit). + lastSynced = json; config.error = await errorMessage(response); + + return true; } $effect.root(() => { @@ -179,7 +213,8 @@ $effect.root(() => { // State arrives on every host change and once a second (live calibration // state comes from the network). A revision we don't have means someone // else changed the document -- another tab, or a lock/reload -- so refetch, - // unless our own edit is mid-flight and about to report that revision. + // unless our own edit is mid-flight and about to report that revision, or + // waiting to be retried (a reload would drop it). $effect(() => { return topic("config.state").subscribe((state) => { if (!state) return; @@ -190,7 +225,8 @@ $effect.root(() => { config.doc && state.revision !== config.revision && !inFlight && - putTimer === null + putTimer === null && + retryTimer === null ) { void loadConfig(); } diff --git a/gui/frontend/src/lib/config.test.ts b/gui/frontend/src/lib/config.test.ts index 353068c..ad14af0 100644 --- a/gui/frontend/src/lib/config.test.ts +++ b/gui/frontend/src/lib/config.test.ts @@ -237,9 +237,45 @@ describe("edits", () => { expect(config.revision).toBe(5); }); - it.todo( - "sent while the host is unreachable are reported and retried (REVIEW.md T4-2)", - ); + it("sent while the host is unreachable are reported and retried", async () => { + const { config } = await loaded(); + reply("PUT", "/api/config", new TypeError("Failed to fetch"), { + status: 200, + body: { revision: 4 }, + }); + + docOf(config).field.fieldLength = 9100; + await settle(300); + + expect(sent("PUT", "/api/config")).toHaveLength(1); + expect(config.error).toBe(app.notSent); + expect(docOf(config).field.fieldLength).toBe(9100); + + await settle(2000); + + const puts = sent("PUT", "/api/config"); + expect(puts).toHaveLength(2); + expect(puts[1]?.body).toMatchObject({ + revision: 3, + document: { field: { fieldLength: 9100 } }, + }); + expect(config.error).toBeNull(); + expect(config.revision).toBe(4); + + await settle(5000); + expect(sent("PUT", "/api/config")).toHaveLength(2); + }); + + it("keeps retrying while the host stays unreachable", async () => { + const { config } = await loaded(); + reply("PUT", "/api/config", new TypeError("Failed to fetch")); + + docOf(config).field.fieldLength = 9100; + await settle(300 + 3 * 2000); + + expect(sent("PUT", "/api/config")).toHaveLength(4); + expect(config.error).toBe(app.notSent); + }); }); describe("flushEdits", () => { @@ -254,6 +290,21 @@ describe("flushEdits", () => { expect(config.revision).toBe(4); }); + it("sends an unsent edit at once instead of waiting for the retry", async () => { + const { config, flushEdits } = await loaded(); + reply("PUT", "/api/config", new TypeError("Failed to fetch"), { + status: 200, + body: { revision: 4 }, + }); + + docOf(config).field.fieldLength = 9100; + await settle(300); + await flushEdits(); + + expect(sent("PUT", "/api/config")).toHaveLength(2); + expect(config.revision).toBe(4); + }); + it("does nothing when nothing changed", async () => { const { flushEdits } = await loaded(); diff --git a/gui/frontend/src/lib/config/CalibrationCard.svelte b/gui/frontend/src/lib/config/CalibrationCard.svelte index 30130e1..4d38360 100644 --- a/gui/frontend/src/lib/config/CalibrationCard.svelte +++ b/gui/frontend/src/lib/config/CalibrationCard.svelte @@ -3,7 +3,7 @@ import StatusAlert from "../StatusAlert.svelte"; import { geometry as text } from "../text/geometry"; import SettingsCard from "../SettingsCard.svelte"; - import { Button, Spinner, P } from "flowbite-svelte"; + import { Button, Helper, Spinner, P } from "flowbite-svelte"; import { config, cameraDoc, @@ -106,6 +106,9 @@ {text.calibration.unlock} + {#if !status.live && status.calibration === "none"} + {text.nothingToLockDetail} + {/if} {/if} diff --git a/gui/frontend/src/lib/config/CameraPanel.svelte b/gui/frontend/src/lib/config/CameraPanel.svelte index 8f20960..ce0608e 100644 --- a/gui/frontend/src/lib/config/CameraPanel.svelte +++ b/gui/frontend/src/lib/config/CameraPanel.svelte @@ -493,7 +493,11 @@ max={ranges.gamma.max} step={ranges.gamma.step} unit={ranges.gamma.unit} - auto={{ value: 1, fallback: ranges.gamma.fallback, label: "Off" }} + auto={{ + value: 1, + fallback: ranges.gamma.fallback, + label: "Linear", + }} notes={gammaNotes} warnings={gammaWarnings} onchange={(v: number) => { diff --git a/gui/frontend/src/lib/config/YuvPositionPane.svelte b/gui/frontend/src/lib/config/YuvPositionPane.svelte index 0d665fb..9149076 100644 --- a/gui/frontend/src/lib/config/YuvPositionPane.svelte +++ b/gui/frontend/src/lib/config/YuvPositionPane.svelte @@ -176,7 +176,24 @@ }); } + // The out-of-gamut checkerboard follows the page theme, which the header's + // DarkMode button switches by toggling html.dark. + let dark = $state(document.documentElement.classList.contains("dark")); + + $effect(() => { + const html = document.documentElement; + const observer = new MutationObserver(() => { + dark = html.classList.contains("dark"); + }); + observer.observe(html, { attributes: true, attributeFilter: ["class"] }); + + return () => { + observer.disconnect(); + }; + }); + $effect(() => { + void dark; scheduleRedraw(sliceY); }); @@ -218,6 +235,7 @@ gamutFraction = inGamutCount / (size * size); const image = ctx.createImageData(size, size); + const hatch: [number, number] = dark ? [48, 58] : [212, 226]; const isInGamut = (u: number, v: number): boolean => u >= 0 && u < size && v >= 0 && v < size && inGamut[v * size + u] === 1; @@ -251,7 +269,7 @@ image.data[i + 2] = rgb.b; } } else { - const shade = (u + v) % 16 < 8 ? 212 : 226; + const shade = (u + v) % 16 < 8 ? hatch[0] : hatch[1]; image.data[i] = shade; image.data[i + 1] = shade; image.data[i + 2] = shade; diff --git a/gui/frontend/src/lib/hostVersion.svelte.ts b/gui/frontend/src/lib/hostVersion.svelte.ts new file mode 100644 index 0000000..48c1a98 --- /dev/null +++ b/gui/frontend/src/lib/hostVersion.svelte.ts @@ -0,0 +1,40 @@ +// Notices the host being upgraded under an open page: the bundle comes from +// the host's own binary, so the version it reported when this page connected +// is the bundle's. A different one after a reconnect means the page is stale. +import { requestJSON } from "./api"; +import type { HealthResponse } from "./apiTypes"; +import { connectionState } from "./wrapper-bus"; + +export const hostVersion = $state<{ + // The version this page was loaded from. + page: string | null; + // What the host reports now. + host: string | null; +}>({ page: null, host: null }); + +export function hostUpdated(): boolean { + return ( + hostVersion.page !== null && + hostVersion.host !== null && + hostVersion.page !== hostVersion.host + ); +} + +export async function checkHostVersion(): Promise { + try { + const response = await requestJSON("/api/health"); + const { version } = (await response.json()) as HealthResponse; + hostVersion.page ??= version; + hostVersion.host = version; + } catch { + // Unreachable again; the next reconnect checks. + } +} + +$effect.root(() => { + $effect(() => { + return connectionState.subscribe((state) => { + if (state === "open") void checkHostVersion(); + }); + }); +}); diff --git a/gui/frontend/src/lib/hostVersion.test.ts b/gui/frontend/src/lib/hostVersion.test.ts new file mode 100644 index 0000000..b3d02ee --- /dev/null +++ b/gui/frontend/src/lib/hostVersion.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// The page's version is the first one the host reports; a later different one +// means the host was upgraded under the open page. +let versions: (string | Error)[]; + +beforeEach(() => { + vi.resetModules(); + versions = []; + vi.stubGlobal( + "fetch", + vi.fn(() => { + const next = versions.shift(); + if (next instanceof Error || next === undefined) + return Promise.reject(next ?? new Error("no reply")); + + return Promise.resolve( + new Response(JSON.stringify({ status: "ok", version: next })), + ); + }), + ); +}); + +describe("hostUpdated", () => { + it("is false while the host reports the page's own version", async () => { + const { checkHostVersion, hostUpdated, hostVersion } = + await import("./hostVersion.svelte"); + versions = ["v2.0.0-alpha.1", "v2.0.0-alpha.1"]; + + await checkHostVersion(); + await checkHostVersion(); + + expect(hostVersion.page).toBe("v2.0.0-alpha.1"); + expect(hostUpdated()).toBe(false); + }); + + it("is true once the host reports another version", async () => { + const { checkHostVersion, hostUpdated, hostVersion } = + await import("./hostVersion.svelte"); + versions = ["v2.0.0-alpha.1", "v2.0.0-alpha.2"]; + + await checkHostVersion(); + await checkHostVersion(); + + expect(hostVersion).toEqual({ + page: "v2.0.0-alpha.1", + host: "v2.0.0-alpha.2", + }); + expect(hostUpdated()).toBe(true); + }); + + it("ignores an unreachable host", async () => { + const { checkHostVersion, hostUpdated, hostVersion } = + await import("./hostVersion.svelte"); + versions = ["v2.0.0-alpha.1", new TypeError("Failed to fetch")]; + + await checkHostVersion(); + await checkHostVersion(); + + expect(hostVersion.host).toBe("v2.0.0-alpha.1"); + expect(hostUpdated()).toBe(false); + }); +}); diff --git a/gui/frontend/src/lib/layout/InstanceList.svelte b/gui/frontend/src/lib/layout/InstanceList.svelte index 50da795..ee631f2 100644 --- a/gui/frontend/src/lib/layout/InstanceList.svelte +++ b/gui/frontend/src/lib/layout/InstanceList.svelte @@ -10,6 +10,14 @@ import { instances, selectedInstance, instanceHref } from "./nav.svelte"; import { config } from "../config.svelte"; import { regionLabel, cameraCount } from "../cameraLayout"; + import { processFor, processHealth } from "../processes.svelte"; + + const HEALTH_COLOR = { + running: "green", + starting: "yellow", + failing: "red", + held: "red", + } as const; // Cameras with unsaved changes get a dot, same idea as the tab asterisks. let dirtyCameras = $derived( @@ -40,12 +48,24 @@ active={instance.id === selectedInstance()?.id} > {#snippet subtext()} + {@const proc = processFor(instance.cameraId)} - cam {instance.cameraId}{config.doc && cameraCount(config.doc) > 1 - ? ` · ${regionLabel(config.doc, instance.cameraId)}` - : ""} + cam {instance.cameraId}{config.doc && cameraCount(config.doc) > 1 + ? ` · ${regionLabel(config.doc, instance.cameraId)}` + : ""} + {#if proc} + {@const health = processHealth(proc)} + + {app.sidebar.process[health]} + {/if} {#if dirtyCameras.has(instance.cameraId)} {/if} diff --git a/gui/frontend/src/lib/processes.svelte.ts b/gui/frontend/src/lib/processes.svelte.ts index 8323be3..1763296 100644 --- a/gui/frontend/src/lib/processes.svelte.ts +++ b/gui/frontend/src/lib/processes.svelte.ts @@ -21,6 +21,31 @@ export function processFor(cameraId: number): ProcessStatus | undefined { return processes.list.find((p) => p.cameraId === cameraId); } +// Failed runs in a row before a process counts as crash-looping; the host's +// process_crashing alert uses the same (gui/internal/alerts crashingAfter). +export const CRASHING_AFTER = 2; + +export type ProcessHealth = "running" | "starting" | "failing" | "held"; + +// One word for a supervised process, for a status dot. +export function processHealth(p: ProcessStatus): ProcessHealth { + if (p.state === "conflict") return "held"; + if (p.crashes >= CRASHING_AFTER) return "failing"; + if (p.state === "running") return "running"; + + return "starting"; +} + +// The last non-blank line it printed: usually why it exited. +export function lastLine(p: ProcessStatus): string { + for (let i = p.output.length - 1; i >= 0; i--) { + const line = p.output[i]?.trim(); + if (line) return line; + } + + return ""; +} + export async function restartProcess(cameraId: number): Promise { const response = await requestJSON( `/api/processes/${String(cameraId)}/restart`, diff --git a/gui/frontend/src/lib/processes.test.ts b/gui/frontend/src/lib/processes.test.ts new file mode 100644 index 0000000..c609a33 --- /dev/null +++ b/gui/frontend/src/lib/processes.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { + lastLine, + processHealth, + type ProcessStatus, +} from "./processes.svelte"; + +const proc = (p: Partial): ProcessStatus => ({ + cameraId: 0, + configPath: "cam0.yml", + state: "running", + since: "2026-11-18T00:00:00Z", + restarts: 0, + pendingKeys: [], + crashes: 0, + output: [], + ...p, +}); + +describe("processHealth", () => { + it("names each state for a status dot", () => { + expect(processHealth(proc({}))).toBe("running"); + expect(processHealth(proc({ state: "waiting" }))).toBe("starting"); + expect(processHealth(proc({ state: "waiting", crashes: 1 }))).toBe( + "starting", + ); + expect(processHealth(proc({ state: "waiting", crashes: 2 }))).toBe( + "failing", + ); + expect(processHealth(proc({ state: "running", crashes: 3 }))).toBe( + "failing", + ); + expect(processHealth(proc({ state: "conflict", crashes: 3 }))).toBe("held"); + }); +}); + +describe("lastLine", () => { + it("is the last non-blank line it printed, trimmed", () => { + expect( + lastLine(proc({ output: ["a", " no such device ", "", " "] })), + ).toBe("no such device"); + expect(lastLine(proc({ output: [] }))).toBe(""); + }); +}); diff --git a/gui/frontend/src/lib/text/alerts.ts b/gui/frontend/src/lib/text/alerts.ts index b677a6b..189baae 100644 --- a/gui/frontend/src/lib/text/alerts.ts +++ b/gui/frontend/src/lib/text/alerts.ts @@ -19,6 +19,7 @@ export const alerts = { layout: "Layout", geometry: "Geometry", network: "Network", + camera: "Camera", }, renderFailed: (camera: string): string => @@ -58,6 +59,10 @@ export const alerts = { `Camera ${String(camera)}'s vision_processor isn't started`, deviceConflictDetail: (conflict: string): string => `${conflict.charAt(0).toUpperCase()}${conflict.slice(1)}.`, + processCrashing: (camera: number, crashes: number): string => + `Camera ${String(camera)}'s vision_processor keeps exiting (${String(crashes)} times in a row)`, + processCrashingDetail: (lastLine: string, exit: string): string => + lastLine ? `Last output: ${lastLine}` : `It printed nothing; ${exit}.`, firstRun: "Not publishing until you save", firstRunDetail: "This is a new configuration. Check the field, then save it to start publishing on the network.", diff --git a/gui/frontend/src/lib/text/app.ts b/gui/frontend/src/lib/text/app.ts index a821b45..f3e645b 100644 --- a/gui/frontend/src/lib/text/app.ts +++ b/gui/frontend/src/lib/text/app.ts @@ -46,11 +46,23 @@ export const app = { discardAndReload: (unsaved: number): string => `Discard ${String(unsaved)} unsaved change(s) and reload from disk?`, editedElsewhere: "Edited elsewhere at the same time; reloaded the latest.", + hostUpdated: (from: string, to: string): string => + `The GUI was updated (${from} → ${to}). Reload this page to use the new version; until then it may misbehave.`, + reload: "Reload", + notSent: + "Not sent: the host can't be reached. Your edit is kept here and sent when the host is back.", sidebar: { instancesHelp: "One row per camera role, not per machine -- a host running all 4 cameras of a quad setup appears here 4 times. From vision.yml's cameras list.", noCameras: "Per-instance (no cameras yet)", + // The status dot of a vision_processor the host runs itself. + process: { + running: "vision_processor running", + starting: "vision_processor starting", + failing: "vision_processor keeps exiting", + held: "vision_processor not started: device in use", + }, }, // The settings menu's file dialogs (layout/ConfigDialogs.svelte). diff --git a/gui/frontend/src/lib/text/docs.ts b/gui/frontend/src/lib/text/docs.ts index 12c3920..468ecc3 100644 --- a/gui/frontend/src/lib/text/docs.ts +++ b/gui/frontend/src/lib/text/docs.ts @@ -121,6 +121,17 @@ export const RESOLUTION_DOCS = { "It starts by itself as soon as its device is free. Nothing needs restarting.", ], }, + "process-crashing": { + title: "A camera's vision_processor keeps exiting", + cause: + "The host runs every camera's vision_processor itself (-runCameras) and restarts one that exits, waiting longer each time. This one has failed several times in a row, usually because it can't open its camera: the wrong driver, a device that's missing or busy, or a driver the build doesn't include.", + steps: [ + "Read its last output, here and in full at the bottom of the Camera page. It usually names the problem.", + "Check the camera's driver and device on the Camera page. A webcam needs OPENCV and a /dev/video path; the default, SPINNAKER, is for FLIR cameras only.", + "Check nothing else has the camera open (another vision_processor, a video call, cheese).", + "It restarts by itself after each change. Nothing else needs restarting.", + ], + }, "first-run": { title: "Nothing is published until you save", cause: diff --git a/gui/frontend/src/lib/text/geometry.ts b/gui/frontend/src/lib/text/geometry.ts index 3aa9bdf..76a82ec 100644 --- a/gui/frontend/src/lib/text/geometry.ts +++ b/gui/frontend/src/lib/text/geometry.ts @@ -67,6 +67,9 @@ export const geometry = { cornerPicker: { title: "Corner picker", + noFrame: (camera: number): string => + `No calibration frame from camera ${String(camera)} yet. Its vision_processor saves one when it starts calibrating, on this machine only; Refresh frame checks again.`, + refresh: "Refresh frame", intro: "Drag the four markers onto the real field corners in the image below, then click the number on whichever one sits where the goal line meets the touchline nearest this field's (0,0) corner -- that one turns green and becomes first in the output. The other three can be in any order; the calibration algorithm works that out itself. The goal and penalty area this camera should see are drawn dashed through the markers, as vision_processor will read them: if they don't sit on the real ones, the green marker is on the wrong corner. Changes apply when you let go of a marker; Save keeps them.", region: ( @@ -87,6 +90,8 @@ export const geometry = { lockTitle: "Store the calibration this camera last sent", nothingToLock: "No calibration received from this camera yet", + nothingToLockDetail: + "Nothing to lock yet: this camera hasn't sent a calibration. It sends one once it has calibrated.", relock: "Re-lock latest live calibration", lock: "Lock current calibration", unlockTitle: "Unlock calibration?", diff --git a/gui/frontend/src/lib/text/video.ts b/gui/frontend/src/lib/text/video.ts index 3bcda99..980bf4e 100644 --- a/gui/frontend/src/lib/text/video.ts +++ b/gui/frontend/src/lib/text/video.ts @@ -11,6 +11,15 @@ export const video = { `Can't listen for video on ${address}: ${problem}. Retrying…`, waiting: (address: string): string => `Waiting for video on ${address}. Is the vision_processor running?`, + // When the host runs this camera's vision_processor itself and knows why + // there's no video. + processExiting: (lastLine: string): string => + lastLine + ? `vision_processor keeps exiting: ${lastLine}` + : "vision_processor keeps exiting. Its output is on the Camera page.", + processHeld: (conflict: string): string => + `vision_processor isn't started: ${conflict}.`, + processStarting: "Waiting for video: vision_processor is starting…", waitingKeyframe: "Waiting for a keyframe…", // The rate frames arrive from vision_processor. receivedFps: (fps: number): string => diff --git a/gui/frontend/src/lib/video/VideoPlayer.svelte b/gui/frontend/src/lib/video/VideoPlayer.svelte index b4d4f66..439ed87 100644 --- a/gui/frontend/src/lib/video/VideoPlayer.svelte +++ b/gui/frontend/src/lib/video/VideoPlayer.svelte @@ -7,6 +7,7 @@ type StreamStatus, } from "./videoStream"; import { video as text } from "../text/video"; + import { lastLine, processFor, processHealth } from "../processes.svelte"; // One camera's live stream. Built to be reused by a grid later: each // player owns its own connection, and "keyframes" mode costs a fraction of @@ -93,17 +94,46 @@ }; }); + // The host's own vision_processor for this camera keeps exiting or isn't + // started: no video is coming, so no spinner. + let stuck = $derived.by(() => { + const proc = processFor(cameraId); + + return ( + proc !== undefined && ["failing", "held"].includes(processHealth(proc)) + ); + }); + // Still expecting video, as opposed to an error or streaming being off. let waiting = $derived( - !error && (!status || (status.active && (!status.receiving || !format))), + !error && + !stuck && + (!status || (status.active && (!status.receiving || !format))), ); + // Why there's no video, when the host runs the vision_processor itself. + function notReceiving(address: string): string { + const proc = processFor(cameraId); + if (!proc) return text.waiting(address); + + switch (processHealth(proc)) { + case "failing": + return text.processExiting(lastLine(proc)); + case "held": + return text.processHeld(proc.conflict ?? ""); + case "starting": + return text.processStarting; + case "running": + return text.waiting(address); + } + } + let overlay = $derived.by((): string | null => { if (error) return error; if (!status) return text.connecting; if (!status.active) return text.streamingOff; if (status.problem) return text.cantListen(status.address, status.problem); - if (!status.receiving) return text.waiting(status.address); + if (!status.receiving) return notReceiving(status.address); if (!format) return text.waitingKeyframe; return null; diff --git a/gui/internal/alerts/alerts.go b/gui/internal/alerts/alerts.go index 92e4869..3a5e839 100644 --- a/gui/internal/alerts/alerts.go +++ b/gui/internal/alerts/alerts.go @@ -9,6 +9,7 @@ import ( "fmt" "slices" "strconv" + "strings" "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/config" "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/detections" @@ -40,8 +41,13 @@ const ( CodeSenderConflict = "sender_conflict" CodeFirstRun = "first_run_not_publishing" CodeDeviceConflict = "device_conflict" + CodeProcessCrashing = "process_crashing" ) +// crashingAfter is how many failed runs in a row make a supervised +// vision_processor's crashes an alert: one can be a slow device, two is a loop. +const crashingAfter = 2 + // Alert is one problem. type Alert struct { // ID is stable while the problem lasts, for keyed lists. @@ -72,7 +78,7 @@ func Codes() []string { codes := append([]string{ CodeRenderFailed, CodeCameraIDConflict, CodeRegionUncovered, CodeCameraUnplaced, CodeFileChanged, CodeSocketProblem, CodeSocketSilent, CodeHeightsUnreadable, CodeTeamDefaultHeight, CodeLoopbackMulticast, - CodeSenderConflict, CodeFirstRun, CodeDeviceConflict, + CodeSenderConflict, CodeFirstRun, CodeDeviceConflict, CodeProcessCrashing, }, config.WarningCodes...) slices.Sort(codes) @@ -125,6 +131,15 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { } for _, p := range net.Processes { + if p.State != supervisor.StateConflict && p.Crashes >= crashingAfter { + last := LastLine(p.Output) + add(Alert{ + ID: "crashing-" + strconv.Itoa(p.CameraID), Code: CodeProcessCrashing, Severity: Error, CameraID: ptr(p.CameraID), + Params: map[string]any{"crashes": p.Crashes, "exit": p.LastExit, "lastLine": last}, + Message: fmt.Sprintf("Camera %d's vision_processor keeps exiting (%d times in a row, %s): %s", p.CameraID, p.Crashes, p.LastExit, last), + }) + } + if p.State != supervisor.StateConflict { continue } @@ -414,3 +429,15 @@ func sortedKeys(m map[int]string) []int { } func ptr(v int) *int { return &v } + +// LastLine is the last non-blank line of a process's output: usually why it +// exited. +func LastLine(output []string) string { + for i := len(output) - 1; i >= 0; i-- { + if line := strings.TrimSpace(output[i]); line != "" { + return line + } + } + + return "" +} diff --git a/gui/internal/alerts/alerts_test.go b/gui/internal/alerts/alerts_test.go index 42cfa58..abe33f6 100644 --- a/gui/internal/alerts/alerts_test.go +++ b/gui/internal/alerts/alerts_test.go @@ -92,6 +92,12 @@ func TestCollect(t *testing.T) { {CameraID: 1, State: supervisor.StateConflict, Conflict: "camera 0 already uses OPENCV /dev/video0"}, } }, "device-1", "device_conflict/error"}, + "crash loop": {func(_ *config.Document, _ *config.State, n *Network) { + n.Processes = []supervisor.Status{{ + CameraID: 0, State: supervisor.StateWaiting, Crashes: 2, LastExit: "exit status 1", + Output: []string{"opening /dev/video0", "VIDIOC_REQBUFS: Device or resource busy", ""}, + }} + }, "crashing-0", "process_crashing/error"}, "heights unreadable": {func(_ *config.Document, _ *config.State, n *Network) { n.Referee.HeightsError = "no such file" }, "heights-unreadable", "heights_unreadable/warning"}, @@ -241,3 +247,31 @@ func TestSenderConflictSeverity(t *testing.T) { } } } + +// One failed start can be a slow device; two in a row is a loop worth an +// alert, and its last output line usually says why. +func TestCrashingProcessNeedsTwoFailuresAndQuotesTheLastLine(t *testing.T) { + doc, state, net := healthy() + + net.Processes = []supervisor.Status{{CameraID: 0, State: supervisor.StateWaiting, Crashes: 1, Output: []string{"bad"}}} + for _, a := range Collect(doc, state, net) { + if a.Code == CodeProcessCrashing { + t.Fatalf("one crash raised %v", a) + } + } + + net.Processes[0].Crashes = 3 + net.Processes[0].Output = []string{"opening", " no such device ", " "} + + for _, a := range Collect(doc, state, net) { + if a.Code == CodeProcessCrashing { + if a.Params["lastLine"] != "no such device" || a.Params["crashes"] != 3 { + t.Errorf("params = %v", a.Params) + } + + return + } + } + + t.Fatal("three crashes in a row raised no process_crashing alert") +} diff --git a/gui/internal/api/api.go b/gui/internal/api/api.go index 3331484..42e4904 100644 --- a/gui/internal/api/api.go +++ b/gui/internal/api/api.go @@ -41,6 +41,14 @@ type Info struct { Title string Version string Description string + // Tags lists every route tag, in the order the reference shows them. + Tags []Tag +} + +// Tag is one group of routes in the reference. +type Tag struct { + Name string + Description string } // New returns an API registering on mux. onError writes a handler's error as @@ -48,6 +56,9 @@ type Info struct { func New(mux *http.ServeMux, info Info, onError func(http.ResponseWriter, error)) *API { r := openapi31.NewReflector() r.Spec.Info.WithTitle(info.Title).WithVersion(info.Version).WithDescription(info.Description) + for _, t := range info.Tags { + r.Spec.Tags = append(r.Spec.Tags, openapi31.Tag{Name: t.Name, Description: &t.Description}) + } r.JSONSchemaReflector().DefaultOptions = append(r.JSONSchemaReflector().DefaultOptions, jsonschema.InterceptSchema(describe), // A slice or map the host sends is [] or {}, never null: Go's nil diff --git a/gui/internal/config/store.go b/gui/internal/config/store.go index bb9c588..21598db 100644 --- a/gui/internal/config/store.go +++ b/gui/internal/config/store.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "errors" "fmt" + "log/slog" "os" "path/filepath" "slices" @@ -268,6 +269,9 @@ func (s *Store) update(rev int64, doc Document) (int64, error) { for _, c := range s.working.Cameras { if next := doc.camera(c.CameraID); c.Calibration != nil && (next == nil || next.Calibration == nil) { if err := s.live.Unlock(uint32(c.CameraID)); err != nil { + s.restoreLive() + s.renderErrs = renderAll(s.working, s.dir, s.path) + return 0, err } } @@ -281,8 +285,12 @@ func (s *Store) update(rev int64, doc Document) (int64, error) { // apply pushes doc into the live system and regenerates config.yml files. // doc must already be validated. Callers must hold mu. +// +// All or nothing: everything that can fail on doc's contents is built before +// the live system changes, and a later failure puts the working document's +// state back. func (s *Store) apply(doc Document) error { - models, err := doc.ModelsProto() + models, locked, err := liveState(doc) if err != nil { return err } @@ -291,6 +299,25 @@ func (s *Store) apply(doc Document) error { return err } + if err := s.live.SetLocked(locked); err != nil { + s.restoreLive() + + return err + } + + s.renderErrs = renderAll(doc, s.dir, s.path) + + return nil +} + +// liveState is what the live system gets from doc: its models and its +// locked calibrations by camera_id. +func liveState(doc Document) (*vision.SSL_GeometryModels, map[uint32]*vision.SSL_GeometryCameraCalibration, error) { + models, err := doc.ModelsProto() + if err != nil { + return nil, nil, err + } + locked := map[uint32]*vision.SSL_GeometryCameraCalibration{} for _, c := range doc.Cameras { @@ -300,19 +327,31 @@ func (s *Store) apply(doc Document) error { calib, err := c.Calibration.Proto() if err != nil { - return err + return nil, nil, fmt.Errorf("cameras[%d].calibration: %w", c.CameraID, err) } locked[uint32(c.CameraID)] = calib } - if err := s.live.SetLocked(locked); err != nil { - return err + return models, locked, nil +} + +// restoreLive puts the working document back into the live system after a +// failed change. It applied once, so it applies again; an error here is +// only logged, as the caller is already returning the first one. +func (s *Store) restoreLive() { + models, locked, err := liveState(s.working) + if err == nil { + err = s.live.ApplyConfig(s.working.Field, s.working.OptionalFieldLines, models) } - s.renderErrs = renderAll(doc, s.dir, s.path) + if err == nil { + err = s.live.SetLocked(locked) + } - return nil + if err != nil { + slog.Error("restoring the live geometry after a failed change", "err", err) + } } // checkNotOverActive refuses a document that would render a camera's config.yml diff --git a/gui/internal/config/store_test.go b/gui/internal/config/store_test.go index 2f623f6..cb2d246 100644 --- a/gui/internal/config/store_test.go +++ b/gui/internal/config/store_test.go @@ -21,6 +21,8 @@ type fakeLive struct { locked map[uint32]*vision.SSL_GeometryCameraCalibration unlocked []uint32 live map[uint32]*vision.SSL_GeometryCameraCalibration + // failLocked makes the next SetLocked fail, as a failed encode would. + failLocked bool } func (f *fakeLive) ApplyConfig(field geometry.FieldConfig, _ geometry.OptionalLinesConfig, _ *vision.SSL_GeometryModels) error { @@ -36,6 +38,12 @@ func (f *fakeLive) SetLocked(locked map[uint32]*vision.SSL_GeometryCameraCalibra f.mu.Lock() defer f.mu.Unlock() + if f.failLocked { + f.failLocked = false + + return errors.New("encode failed") + } + f.locked = locked return nil @@ -660,3 +668,52 @@ func TestRenderNamesTheHeightsTableBesideTheSource(t *testing.T) { t.Errorf("render = %s\nwant an absolute bot_heights_file", data) } } + +// A change that fails partway leaves the live system as it was, not with +// the new field and the old calibrations. +func TestUpdateFailingPartwayLeavesTheLiveSystemAsItWas(t *testing.T) { + store, live, _ := testStore(t) + doc, rev := store.Working() + before := live.field + + doc.Field.FieldLength += 1000 + live.mu.Lock() + live.failLocked = true + live.mu.Unlock() + + if _, err := store.Update(rev, doc); err == nil { + t.Fatal("Update succeeded although SetLocked failed") + } + + live.mu.Lock() + defer live.mu.Unlock() + + if live.field != before { + t.Errorf("live field = %+v, want it back to %+v", live.field, before) + } + + if working, after := store.Working(); after != rev || working.Field.FieldLength != before.FieldLength { + t.Errorf("working document changed: revision %d, field length %v", after, working.Field.FieldLength) + } +} + +// A calibration that can't be built is refused before anything changes. +func TestUpdateWithABrokenCalibrationChangesNothing(t *testing.T) { + store, live, _ := testStore(t) + doc, rev := store.Working() + before := live.field + + doc.Field.FieldLength += 1000 + doc.Cameras[0].Calibration = &Calibration{Camera: map[string]any{"cameraId": 0}} + + if _, err := store.Update(rev, doc); err == nil { + t.Fatal("Update accepted an incomplete calibration") + } + + live.mu.Lock() + defer live.mu.Unlock() + + if live.field != before { + t.Errorf("live field changed to %+v before the calibration was refused", live.field) + } +} diff --git a/gui/internal/hub/websocket_test.go b/gui/internal/hub/websocket_test.go index ad90a75..078029b 100644 --- a/gui/internal/hub/websocket_test.go +++ b/gui/internal/hub/websocket_test.go @@ -51,10 +51,9 @@ func TestWebSocketDeliversPublishedData(t *testing.T) { t.Fatalf("WriteJSON: %v", err) } - // Subscribe is handled by the connection's read loop; give it a moment to - // register with the hub before publishing, or the publish can race ahead - // of it. - time.Sleep(50 * time.Millisecond) + // Subscribe is handled by the connection's read loop; publishing before + // it registers would test the latest-on-subscribe path instead. + waitSubscribers(t, h, "geometry", 1) h.Publish("geometry", []byte(`{"fieldLength":9000}`)) @@ -76,13 +75,13 @@ func TestWebSocketUnsubscribeStopsDelivery(t *testing.T) { t.Fatalf("WriteJSON: %v", err) } - time.Sleep(50 * time.Millisecond) + waitSubscribers(t, h, "geometry", 1) if err := conn.WriteJSON(clientMessage{Action: "unsubscribe", Topic: "geometry"}); err != nil { t.Fatalf("WriteJSON: %v", err) } - time.Sleep(50 * time.Millisecond) + waitSubscribers(t, h, "geometry", 0) h.Publish("geometry", []byte(`{"x":1}`)) @@ -105,7 +104,7 @@ func TestWebSocketTwoConnectionsOnSameTopic(t *testing.T) { } } - time.Sleep(50 * time.Millisecond) + waitSubscribers(t, h, "geometry", 2) h.Publish("geometry", []byte(`{"x":1}`)) @@ -156,3 +155,27 @@ func TestWebSocketRejectsWhatItCantAct(t *testing.T) { } } } + +// waitSubscribers waits until topic has n subscribers: the connection's read +// loop registers them some time after the client's message is written. +func waitSubscribers(t *testing.T, h *Hub, topic string, n int) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + + for { + h.mu.Lock() + got := len(h.subs[topic]) + h.mu.Unlock() + + if got == n { + return + } + + if time.Now().After(deadline) { + t.Fatalf("%s has %d subscribers, want %d", topic, got, n) + } + + time.Sleep(time.Millisecond) + } +} diff --git a/gui/internal/referee/source.go b/gui/internal/referee/source.go new file mode 100644 index 0000000..bd7c15e --- /dev/null +++ b/gui/internal/referee/source.go @@ -0,0 +1,45 @@ +package referee + +import ( + "log/slog" + "net" + "sync" + "time" +) + +// SourceTimeout is how long the followed game controller may stay silent +// before another one's packets are followed instead. A game controller +// sends many times a second, so this is a restart or a switch, not jitter. +const SourceTimeout = 3 * time.Second + +// Source picks the one game controller to follow when several send on the +// same group, as in a lab or a team area: the first heard, until it goes +// silent for SourceTimeout. Without it, each sender's packets overwrite the +// team names and sides in turn. The others are still reported as a +// sender conflict elsewhere. +type Source struct { + mu sync.Mutex + ip net.IP + last time.Time +} + +// Accept reports whether a packet from ip at now is from the followed game +// controller, following ip if there is none or the followed one went silent. +func (s *Source) Accept(ip net.IP, now time.Time) bool { + s.mu.Lock() + defer s.mu.Unlock() + + switch { + case s.ip == nil: + slog.Info("following game controller", "address", ip) + case s.ip.Equal(ip): + case now.Sub(s.last) > SourceTimeout: + slog.Info("following another game controller", "address", ip, "previous", s.ip, "silentFor", now.Sub(s.last).Round(time.Millisecond)) + default: + return false + } + + s.ip, s.last = ip, now + + return true +} diff --git a/gui/internal/referee/source_test.go b/gui/internal/referee/source_test.go new file mode 100644 index 0000000..3cd0fbd --- /dev/null +++ b/gui/internal/referee/source_test.go @@ -0,0 +1,33 @@ +package referee + +import ( + "net" + "testing" + "time" +) + +func TestSourceFollowsOneGameControllerUntilItGoesSilent(t *testing.T) { + var s Source + + a, b := net.ParseIP("10.0.0.4"), net.ParseIP("10.0.0.5") + t0 := time.Unix(0, 0) + + steps := []struct { + ip net.IP + at time.Duration + wantA bool + }{ + {a, 0, true}, // the first heard is followed + {b, 100 * time.Millisecond, false}, // a second, while the first sends, isn't + {a, 200 * time.Millisecond, true}, // the first keeps being followed + {b, 200*time.Millisecond + SourceTimeout, false}, // silent for exactly the timeout: not yet + {b, 201*time.Millisecond + SourceTimeout, true}, // past it: the second takes over + {a, 300*time.Millisecond + SourceTimeout, false}, // and the first is now the extra one + } + + for i, step := range steps { + if got := s.Accept(step.ip, t0.Add(step.at)); got != step.wantA { + t.Errorf("step %d: Accept(%s) = %v, want %v", i, step.ip, got, step.wantA) + } + } +} diff --git a/gui/packaging/ssl-vision-processor-gui.1 b/gui/packaging/ssl-vision-processor-gui.1 index 37ecdfd..568f57b 100644 --- a/gui/packaging/ssl-vision-processor-gui.1 +++ b/gui/packaging/ssl-vision-processor-gui.1 @@ -66,6 +66,11 @@ gets a config file, .IR cam.yml , if it has none. Without it, vision_processors run separately. .TP +.B \-verbose +The same as +.BR "\-logLevel Debug" , +as in the other league tools. +.TP .BI \-logLevel " level" .BR Debug , .BR Info , From 34b48f244a1ca86df409bfc247b22b619720154b Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 11:18:49 -0500 Subject: [PATCH 09/35] start new configs with no camera selected --- gui/ARCHITECTURE.md | 6 +- gui/CLAUDE.md | 4 +- gui/README.md | 4 +- gui/REVIEW.md | 10 +- gui/cmd/ssl-vision-processor-gui/main.go | 3 +- gui/cmd/ssl-vision-processor-gui/main_test.go | 2 +- gui/cmd/ssl-vision-processor-gui/routes.go | 2 +- gui/cmd/ssl-vision-processor-gui/server.go | 5 +- gui/frontend/src/lib/alerts/alert-codes.json | 1 + gui/frontend/src/lib/alerts/alerts.ts | 10 + gui/frontend/src/lib/cameraRanges.ts | 4 +- gui/frontend/src/lib/cameraSettings.svelte.ts | 7 +- .../src/lib/checklist/checklist.svelte.ts | 6 + .../src/lib/checklist/checklist.test.ts | 11 + .../src/lib/config/CameraPanel.svelte | 357 +++++++++--------- .../src/lib/layout/InstanceList.svelte | 1 + gui/frontend/src/lib/processes.svelte.ts | 4 +- gui/frontend/src/lib/processes.test.ts | 3 + gui/frontend/src/lib/text/alerts.ts | 4 + gui/frontend/src/lib/text/app.ts | 1 + gui/frontend/src/lib/text/camera.ts | 6 +- gui/frontend/src/lib/text/checklist.ts | 1 + gui/frontend/src/lib/text/configFields.ts | 5 +- gui/frontend/src/lib/text/docs.ts | 12 +- gui/frontend/src/lib/text/video.ts | 1 + gui/frontend/src/lib/video/VideoPlayer.svelte | 5 +- gui/internal/alerts/alerts.go | 28 +- gui/internal/alerts/alerts_test.go | 32 ++ gui/internal/config/camera.go | 17 +- gui/internal/config/camera_test.go | 1 + gui/internal/config/default.go | 1 + gui/internal/config/document_test.go | 54 +++ gui/internal/config/schema.go | 5 +- gui/internal/httpjson/httpjson.go | 4 +- gui/internal/supervisor/supervisor.go | 63 +++- gui/internal/supervisor/supervisor_test.go | 36 ++ 36 files changed, 498 insertions(+), 218 deletions(-) diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index e11b7f9..1fd5cce 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -202,7 +202,9 @@ filled in (`Document.CaptureDevice`: OPENCV opens `/dev/video` when no devic `id`-th camera) and device paths resolved through symlinks. A camera whose device a lower camera_id already uses is held, not started: state `conflict`, a `device_conflict` alert, and a 409 from its restart route. It starts on its own once its device changes. `Document.Validate` already rejects two cameras on one device on the same `instance`; this -also catches cameras on different instances, and two names for one device node. A daemon holding a camera is out of +also catches cameras on different instances, and two names for one device node. A camera with no driver chosen (DUMMY, which today's +vision_processor exits on) is held too: state `no_camera`, a `camera_not_selected` alert, and a 409 `no_camera`. A +daemon holding a camera is out of scope: the process's own output says the device is busy. It watches the store like any other subscriber: on each change it renders every camera's @@ -268,7 +270,7 @@ counting while suspended, with `CLOCK_MONOTONIC`, which doesn't. Neither jumps f means the machine slept, and every socket is reopened. The Camera Settings tab edits each camera's `camera:` block, shown with vision_processor's own fallbacks applied -(`src/driver/cameradriver.cpp`; an unset driver means SPINNAKER). Controls follow the driver: an index for +(`src/driver/cameradriver.cpp`; an unset driver means SPINNAKER; a new config says DUMMY, the protocol's "no camera"). Controls follow the driver: an index for SPINNAKER, MVIMPACT and DC1394, plus a serial number for SPINNAKER, a path for OPENCV, gamma hidden for MVIMPACT, and the OUTDOOR and INDOOR auto white balance profiles only for SPINNAKER. The serial and the path are both `device`, written in place of its former name `path`, which still reads. vision_processor reads `camera:` diff --git a/gui/CLAUDE.md b/gui/CLAUDE.md index af7e47f..7c9fba7 100644 --- a/gui/CLAUDE.md +++ b/gui/CLAUDE.md @@ -225,7 +225,9 @@ every file vision_processor writes to `img/` is prefixed by camera_id; `internal/snapshot` reads the `cam` folders too); the config path and the rendered `bot_heights_file` are absolute for that reason. A camera whose device (`Document.CaptureDevice`, symlinks resolved) a lower camera_id -already uses is held in state `conflict`. `internal/supervisor` observes the store (`Sync` on every +already uses is held in state `conflict`, and one with no driver chosen +(`DUMMY`, what `config.Default` writes; today's vision_processor exits on it, +upstream PR #61 changes that) in `no_camera`. `internal/supervisor` observes the store (`Sync` on every change) rather than sitting in `Store.apply`: the store still writes the file, and the supervisor restarts a process when `config.RestartKeys` (anything not `live`/`host` in the schema, unknown keys included) finds a difference between diff --git a/gui/README.md b/gui/README.md index 58f2674..9cf67c2 100644 --- a/gui/README.md +++ b/gui/README.md @@ -256,8 +256,8 @@ There are two ways to run the cameras: ``` It prints which vision_processor it runs, and exits straight away if it can't find one. A new configuration's - camera 0 is ready to go, on the first webcam (`/dev/video0`) once its driver is set to OPENCV on the Camera - Settings page. + camera 0 has no camera selected, so it isn't started yet. Choose OPENCV as its driver on the Camera page and it + starts on the first webcam (`/dev/video0`). 3. Camera Settings shows each vision_processor's state, its last lines of output, and a Restart button. Choosing the number of cameras on the Camera Layout page adds or removes cameras to match, each with its own config file. diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 09cf27a..5029297 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,11 +27,11 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-18. **Open** 33 · **Partial** 4 · **Done** 29 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 32 · **Partial** 4 · **Done** 30 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T4-1, T2-1, L-1 and the build/docs batch (T1-5, T1-7, T1-9, T1-10, T2-7, T4-8, T6-3, T6-4, T6-6, T6-7, T7-3, L-6) are awaiting commit. -1. T5-3, T5-2, T5-4: lab path. +All blockers are fixed. T5-3 is awaiting commit. +1. T5-4: the rest of the lab path (T5-2 is done). | ID | Sev | Owner | Item | Status | |---|---|---|---|---| @@ -68,7 +68,7 @@ All blockers are fixed. T4-1, T2-1, L-1 and the build/docs batch (T1-5, T1-7, T1 | T4-8 | nit | Claude | Flowbite `@source` CSS bloat | dropped | | T5-1 | blocker | Will | placeholder Debug page | done | | T5-2 | major | Will | crash-looping VP raises no alert | done | -| T5-3 | major | Will | SPINNAKER default driver | open | +| T5-3 | major | Will | SPINNAKER default driver | done | | T5-4 | major | Will | 4 warnings on a fresh install | open | | T5-5 | major | Will | accessibility (labels, contrast) | v2.1 | | T5-6 | major | Will | two navigation systems | open | @@ -372,6 +372,8 @@ Fix: an `Error` alert per camera when `crashes ≥ 2` (or state `waiting` after Every new camera defaults to the **Spinnaker (FLIR)** driver (the schema's `camera.driver` default `SPINNAKER`, vision_processor's own fallback). The planned CV package is FOSS-only (OpenCV/V4L, DC1394) and `-runCameras` targets student labs with webcams, so a new lab user's first `-runCameras` start crash-loops on a driver they don't have, and (T5-2) nothing says so. No C++ change is needed: the host owns the bootstrapped `vision.yml`. Fix: write `defaults.camera.driver: OPENCV` in a new config, or better, a wizard step "What cameras?" (webcam / FLIR / FireWire / mvIMPACT) that sets it and offers the `/api/camera/devices` picker. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* not OPENCV. A new config writes `defaults.camera.driver: DUMMY`, the protocol's "no camera (initial state)" (proto `fdd7988`), so nobody gets a wrong driver. A file without a driver still means SPINNAKER. With `-runCameras` a DUMMY camera is held, not started (state `no_camera`; its restart route answers 409 `no_camera`), starts when a driver is chosen, and never counts as a device conflict. New alert `camera_not_selected` (warning, error on a competition field), except for a camera the host writes no config for that is already sending. The Camera page shows "No camera selected" and hides device, resolution and tuning until one is chosen; sidebar, video placeholder and checklist say so too. Today's vision_processor exits on DUMMY (`openCamera` has no case), so a camera run by hand still needs a driver first. Once upstream PR #61 lands, the hold can go. The wizard step stays a possible later feature. + **T5-4 | major | Will | alert severities on a fresh install** Before the user has done anything, a first run shows **4 warnings and 1 caution**: `first_run_not_publishing`, `socket_silent`, `team_default_height` ×2, `loopback_multicast_off`. In a lab without a game controller, the two height warnings never go away. Users learn to ignore the warning count on day one, and that is exactly the count that should matter before a match. Fix: diff --git a/gui/cmd/ssl-vision-processor-gui/main.go b/gui/cmd/ssl-vision-processor-gui/main.go index ee8fe01..f4f0409 100644 --- a/gui/cmd/ssl-vision-processor-gui/main.go +++ b/gui/cmd/ssl-vision-processor-gui/main.go @@ -454,7 +454,8 @@ const configWatchInterval = time.Second // bootstrapConfig creates the config file from the embedded defaults if it // doesn't exist yet, and with it the robot height table vision_processor // needs. Never touches an existing config. A host that runs its cameras -// (local) gives camera 0 its config_path, cam0.yml, so a webcam works at once. +// (local) gives camera 0 its config_path, cam0.yml, so choosing a driver is enough to +// start it. func bootstrapConfig(dir, name string, local bool) error { path := filepath.Join(dir, name) diff --git a/gui/cmd/ssl-vision-processor-gui/main_test.go b/gui/cmd/ssl-vision-processor-gui/main_test.go index 91beb7d..5e23429 100644 --- a/gui/cmd/ssl-vision-processor-gui/main_test.go +++ b/gui/cmd/ssl-vision-processor-gui/main_test.go @@ -64,7 +64,7 @@ func TestBootstrapConfigLeavesExistingFileAlone(t *testing.T) { } } -// With -runCameras, a webcam works on the first run: camera 0 has a file to +// With -runCameras, choosing a driver is enough on the first run: camera 0 has a file to // run with. func TestBootstrapConfigRunCamerasGivesCameraZeroAFile(t *testing.T) { dir := t.TempDir() diff --git a/gui/cmd/ssl-vision-processor-gui/routes.go b/gui/cmd/ssl-vision-processor-gui/routes.go index 5869ffb..34a9859 100644 --- a/gui/cmd/ssl-vision-processor-gui/routes.go +++ b/gui/cmd/ssl-vision-processor-gui/routes.go @@ -89,7 +89,7 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { api.Route(a, "GET /api/processes", api.Doc{Tags: tagHost}, s.processes) api.Route(a, "POST /api/processes/{id}/restart", api.Doc{ Tags: tagHost, - Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound, httpjson.CodeDeviceConflict}, + Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound, httpjson.CodeDeviceConflict, httpjson.CodeNoCamera}, }, s.restartProcess) api.Route(a, "GET /api/snapshots", api.Doc{Tags: tagHost}, s.snapshots) api.Raw[snapshotRequest](a, "GET /api/snapshot/{camID}/{view}", api.Doc{ diff --git a/gui/cmd/ssl-vision-processor-gui/server.go b/gui/cmd/ssl-vision-processor-gui/server.go index b73525d..2ac4915 100644 --- a/gui/cmd/ssl-vision-processor-gui/server.go +++ b/gui/cmd/ssl-vision-processor-gui/server.go @@ -339,10 +339,13 @@ func (s *VisionServer) processes(*http.Request, none) ([]supervisor.Status, erro // restartProcess restarts the camera's vision_processor now, rather than // waiting for a startup-only setting to change. A 404 not_found means the // host doesn't run that camera's vision_processor; a 409 device_conflict that -// it's held back because another camera uses its device. +// it's held back because another camera uses its device; a 409 no_camera that +// no camera driver is chosen for it. func (s *VisionServer) restartProcess(_ *http.Request, in cameraRequest) ([]supervisor.Status, error) { if err := s.procs.Restart(in.ID); errors.Is(err, supervisor.ErrNotSupervised) { return nil, httpjson.Errorf(httpjson.CodeNotFound, "the host doesn't run camera %d's vision_processor; start the host with -runCameras", in.ID) + } else if errors.Is(err, supervisor.ErrNoCamera) { + return nil, httpjson.Errorf(httpjson.CodeNoCamera, "camera %d has no camera driver chosen", in.ID) } else if errors.Is(err, supervisor.ErrHeld) { return nil, httpjson.Errorf(httpjson.CodeDeviceConflict, "camera %d's vision_processor is held back: another camera uses its device", in.ID) } else if err != nil { diff --git a/gui/frontend/src/lib/alerts/alert-codes.json b/gui/frontend/src/lib/alerts/alert-codes.json index 2ec860a..b68e83b 100644 --- a/gui/frontend/src/lib/alerts/alert-codes.json +++ b/gui/frontend/src/lib/alerts/alert-codes.json @@ -1,6 +1,7 @@ [ "calibration_aspect_mismatch", "camera_id_conflict", + "camera_not_selected", "camera_unplaced", "device_conflict", "field_changed", diff --git a/gui/frontend/src/lib/alerts/alerts.ts b/gui/frontend/src/lib/alerts/alerts.ts index 318c544..d29fa94 100644 --- a/gui/frontend/src/lib/alerts/alerts.ts +++ b/gui/frontend/src/lib/alerts/alerts.ts @@ -160,6 +160,16 @@ function present(a: HostAlert): Alert { detail: text.deviceConflictDetail(str("conflict")), actions: [howTo("device-conflict")], }; + case "camera_not_selected": + return { + ...base, + title: text.cameraNotSelected(a.cameraId ?? 0), + detail: text.cameraNotSelectedDetail, + actions: [ + howTo("camera-not-selected"), + page(text.pages.camera, a.cameraId, "camera"), + ], + }; case "process_crashing": return { ...base, diff --git a/gui/frontend/src/lib/cameraRanges.ts b/gui/frontend/src/lib/cameraRanges.ts index 2fc691f..c2bedf9 100644 --- a/gui/frontend/src/lib/cameraRanges.ts +++ b/gui/frontend/src/lib/cameraRanges.ts @@ -21,7 +21,7 @@ // - exposure: ms, in the 20 µs steps of the AVT shutter timebase. // - gain, white balance: raw registers, IIDC's 12-bit value field. // - gamma: below 1 turns on the camera's lookup table (0.45 on AVT). -import type { Driver } from "./cameraSettings.svelte"; +import type { CameraDriver } from "./cameraSettings.svelte"; export interface Range { // In display units: what the slider and number box show. @@ -42,7 +42,7 @@ export interface CameraRanges { whiteBalance: Range; } -export const CAMERA_RANGES: Record = { +export const CAMERA_RANGES: Record = { SPINNAKER: { exposure: { min: 10, diff --git a/gui/frontend/src/lib/cameraSettings.svelte.ts b/gui/frontend/src/lib/cameraSettings.svelte.ts index 337a064..0f98255 100644 --- a/gui/frontend/src/lib/cameraSettings.svelte.ts +++ b/gui/frontend/src/lib/cameraSettings.svelte.ts @@ -11,7 +11,9 @@ import { config, cameraDoc } from "./config.svelte"; import { fallback, schema } from "./schema.svelte"; import type { VideoDevice } from "./apiTypes"; -export type Driver = "SPINNAKER" | "MVIMPACT" | "DC1394" | "OPENCV"; +// DUMMY is "no camera chosen", what a new config starts with. +export type Driver = "DUMMY" | CameraDriver; +export type CameraDriver = "SPINNAKER" | "MVIMPACT" | "DC1394" | "OPENCV"; export type WhiteBalance = "OUTDOOR" | "INDOOR" | { red: number; blue: number }; @@ -37,7 +39,7 @@ export type CameraKey = keyof CameraSettings; export interface DriverInfo { label: string; // Selected by index in the SDK's camera list, or (OpenCV) by path. - selectsBy: "id" | "path"; + selectsBy: "id" | "path" | "none"; // Also selected by serial number, in device. serial: boolean; gamma: boolean; @@ -46,6 +48,7 @@ export interface DriverInfo { } const DRIVER_LABELS: Record = { + DUMMY: "No camera selected", SPINNAKER: "Spinnaker (FLIR)", MVIMPACT: "mvIMPACT (Bluefox3)", DC1394: "DC1394 (IIDC FireWire)", diff --git a/gui/frontend/src/lib/checklist/checklist.svelte.ts b/gui/frontend/src/lib/checklist/checklist.svelte.ts index 562fb9c..1a5fb53 100644 --- a/gui/frontend/src/lib/checklist/checklist.svelte.ts +++ b/gui/frontend/src/lib/checklist/checklist.svelte.ts @@ -86,6 +86,7 @@ export type Note = | "networkProblem" | "layoutProblem" | "notHeard" + | "noCamera" | "notCalibrated" | "calibratedNotLocked" | "locked" @@ -258,6 +259,11 @@ function cameraRows( } function processorRow(camera: CameraDoc): { status: Status; note: Note } { + const unselected = hostAlerts.list.some( + (a) => a.code === "camera_not_selected" && a.cameraId === camera.cameraId, + ); + if (unselected) return { status: "attention", note: { key: "noCamera" } }; + const source = network.state?.cameras.find( (s) => s.cameraId === camera.cameraId, ); diff --git a/gui/frontend/src/lib/checklist/checklist.test.ts b/gui/frontend/src/lib/checklist/checklist.test.ts index 8373887..65f1c88 100644 --- a/gui/frontend/src/lib/checklist/checklist.test.ts +++ b/gui/frontend/src/lib/checklist/checklist.test.ts @@ -146,6 +146,17 @@ describe("automatic items", () => { expect(itemState("layout").status).toBe("done"); }); + it("a camera with no driver selected puts only its own row in attention", () => { + hostAlerts.list = [{ ...alert("camera_not_selected"), cameraId: 1 }]; + + const item = itemState("processors"); + expect(item.status).toBe("attention"); + expect(item.cameras?.map((c) => c.note?.key)).toEqual([ + "notHeard", + "noCamera", + ]); + }); + it("a caution leaves its item done", () => { hostAlerts.list = [ alert("loopback_multicast_off", "caution"), diff --git a/gui/frontend/src/lib/config/CameraPanel.svelte b/gui/frontend/src/lib/config/CameraPanel.svelte index ce0608e..5fca83f 100644 --- a/gui/frontend/src/lib/config/CameraPanel.svelte +++ b/gui/frontend/src/lib/config/CameraPanel.svelte @@ -35,8 +35,14 @@ let settings = $derived(cameraSettings(cameraId)); let driverInfo = $derived(drivers()); let driver = $derived(driverInfo[settings.driver]); + // The chosen driver; with none, the settings that depend on it are hidden, + // so the stand-in is never shown. + let chosen = $derived(settings.driver !== "DUMMY"); + let realDriver = $derived( + settings.driver === "DUMMY" ? "OPENCV" : settings.driver, + ); // Placeholder slider ranges; see cameraRanges.ts. - let ranges = $derived(CAMERA_RANGES[settings.driver]); + let ranges = $derived(CAMERA_RANGES[realDriver]); let configPath = $derived(cameraDoc(cameraId)?.configPath); let proc = $derived(processFor(cameraId)); let restartError = $state(null); @@ -47,12 +53,15 @@ waiting: "yellow", stopped: "gray", conflict: "red", + no_camera: "yellow", } as const; // One line under the badge: the most pressing of these. let procMessage = $derived.by((): { text: string; error: boolean } => { if (!proc) return { text: "", error: false }; if (restartError) return { text: restartError, error: true }; + if (proc.state === "no_camera") + return { text: text.process.noCamera, error: false }; if (proc.conflict) return { text: text.process.conflict(proc.conflict), error: true }; if (proc.pendingKeys.length > 0) @@ -232,14 +241,14 @@ }); let wbChannelNotes = $derived( - settings.driver === "OPENCV" + realDriver === "OPENCV" ? text.whiteBalance.channelOpencv : [ { SPINNAKER: text.whiteBalance.channelSpinnaker, MVIMPACT: text.whiteBalance.channelMvimpact, DC1394: text.whiteBalance.channelDc1394, - }[settings.driver], + }[realDriver], PLACEHOLDER_RANGE, ], ); @@ -285,7 +294,12 @@
- + { - const choice = - RESOLUTIONS[ - Number((e.currentTarget as HTMLSelectElement).value) - ]; - if (choice) setSize(choice[0], choice[1]); - }} + {#if chosen} + + - {#each RESOLUTIONS as [w, h], i (i)} - - {/each} - - -
- { - setSize(draftSize[0], draftSize[1]); - }} - /> - × - { - setSize(draftSize[0], draftSize[1]); + placeholder="" + value={resolutionIndex} + onchange={(e: Event) => { + const choice = + RESOLUTIONS[ + Number((e.currentTarget as HTMLSelectElement).value) + ]; + if (choice) setSize(choice[0], choice[1]); }} - /> -
-
-
+ > + {#each RESOLUTIONS as [w, h], i (i)} + + {/each} + + +
+ { + setSize(draftSize[0], draftSize[1]); + }} + /> + × + { + setSize(draftSize[0], draftSize[1]); + }} + /> +
+
+
+ {/if}
-
- - { - set("exposure", toFile(ranges.exposure, v)); - }} - /> - - { - set("gain", toFile(ranges.gain, v)); - }} - /> - - {#if driver.gamma} + {#if chosen} +
+ { - set("gamma", toFile(ranges.gamma, v)); + set("exposure", toFile(ranges.exposure, v)); }} /> - {/if} - - - - - - - {#if wbMode === "manual"} - { - set("white_balance", { - ...manualWB, - red: toFile(ranges.whiteBalance, v), - }); - }} - /> { - set("white_balance", { - ...manualWB, - blue: toFile(ranges.whiteBalance, v), - }); + set("gain", toFile(ranges.gain, v)); }} /> - {/if} - -
+ + {#if driver.gamma} + { + set("gamma", toFile(ranges.gamma, v)); + }} + /> + {/if} +
+ + + + + + + {#if wbMode === "manual"} + { + set("white_balance", { + ...manualWB, + red: toFile(ranges.whiteBalance, v), + }); + }} + /> + { + set("white_balance", { + ...manualWB, + blue: toFile(ranges.whiteBalance, v), + }); + }} + /> + {/if} + +
+ {/if} {#if proc} @@ -585,7 +606,7 @@ size="xs" color="alternative" class="ml-auto" - disabled={proc.state === "conflict"} + disabled={proc.state === "conflict" || proc.state === "no_camera"} onclick={() => void restartNow()} > {text.process.restartNow} diff --git a/gui/frontend/src/lib/layout/InstanceList.svelte b/gui/frontend/src/lib/layout/InstanceList.svelte index ee631f2..eca2165 100644 --- a/gui/frontend/src/lib/layout/InstanceList.svelte +++ b/gui/frontend/src/lib/layout/InstanceList.svelte @@ -17,6 +17,7 @@ starting: "yellow", failing: "red", held: "red", + noCamera: "yellow", } as const; // Cameras with unsaved changes get a dot, same idea as the tab asterisks. diff --git a/gui/frontend/src/lib/processes.svelte.ts b/gui/frontend/src/lib/processes.svelte.ts index 1763296..3f22006 100644 --- a/gui/frontend/src/lib/processes.svelte.ts +++ b/gui/frontend/src/lib/processes.svelte.ts @@ -25,10 +25,12 @@ export function processFor(cameraId: number): ProcessStatus | undefined { // process_crashing alert uses the same (gui/internal/alerts crashingAfter). export const CRASHING_AFTER = 2; -export type ProcessHealth = "running" | "starting" | "failing" | "held"; +export type ProcessHealth = + "running" | "starting" | "failing" | "held" | "noCamera"; // One word for a supervised process, for a status dot. export function processHealth(p: ProcessStatus): ProcessHealth { + if (p.state === "no_camera") return "noCamera"; if (p.state === "conflict") return "held"; if (p.crashes >= CRASHING_AFTER) return "failing"; if (p.state === "running") return "running"; diff --git a/gui/frontend/src/lib/processes.test.ts b/gui/frontend/src/lib/processes.test.ts index c609a33..680950c 100644 --- a/gui/frontend/src/lib/processes.test.ts +++ b/gui/frontend/src/lib/processes.test.ts @@ -31,6 +31,9 @@ describe("processHealth", () => { "failing", ); expect(processHealth(proc({ state: "conflict", crashes: 3 }))).toBe("held"); + expect(processHealth(proc({ state: "no_camera", crashes: 3 }))).toBe( + "noCamera", + ); }); }); diff --git a/gui/frontend/src/lib/text/alerts.ts b/gui/frontend/src/lib/text/alerts.ts index 189baae..d562f6d 100644 --- a/gui/frontend/src/lib/text/alerts.ts +++ b/gui/frontend/src/lib/text/alerts.ts @@ -59,6 +59,10 @@ export const alerts = { `Camera ${String(camera)}'s vision_processor isn't started`, deviceConflictDetail: (conflict: string): string => `${conflict.charAt(0).toUpperCase()}${conflict.slice(1)}.`, + cameraNotSelected: (camera: number): string => + `Camera ${String(camera)} has no driver selected`, + cameraNotSelectedDetail: + "Its vision_processor can't run until you choose one.", processCrashing: (camera: number, crashes: number): string => `Camera ${String(camera)}'s vision_processor keeps exiting (${String(crashes)} times in a row)`, processCrashingDetail: (lastLine: string, exit: string): string => diff --git a/gui/frontend/src/lib/text/app.ts b/gui/frontend/src/lib/text/app.ts index f3e645b..690789e 100644 --- a/gui/frontend/src/lib/text/app.ts +++ b/gui/frontend/src/lib/text/app.ts @@ -62,6 +62,7 @@ export const app = { starting: "vision_processor starting", failing: "vision_processor keeps exiting", held: "vision_processor not started: device in use", + noCamera: "vision_processor not started: no camera selected", }, }, diff --git a/gui/frontend/src/lib/text/camera.ts b/gui/frontend/src/lib/text/camera.ts index 639fde7..1143951 100644 --- a/gui/frontend/src/lib/text/camera.ts +++ b/gui/frontend/src/lib/text/camera.ts @@ -21,6 +21,7 @@ export const camera = { waiting: "Waiting to start", stopped: "Stopped", conflict: "Held back", + no_camera: "No camera selected", }, pid: (pid: number): string => `pid ${String(pid)}`, restarts: (n: number): string => @@ -31,6 +32,7 @@ export const camera = { lastExit: (how: string): string => `Last run: ${how}.`, conflict: (why: string): string => `Not started: ${why}. Give it its own device and it starts.`, + noCamera: "Not started: choose a driver above and it starts.", crashes: (n: number): string => `Failed ${String(n)} times in a row; retrying, waiting longer each time. See its output below.`, restartNow: "Restart now", @@ -42,8 +44,10 @@ export const camera = { driver: [ "SPINNAKER, MVIMPACT and DC1394 need vision_processor built with their SDKs.", - "Unset means SPINNAKER.", + "A file without a driver means SPINNAKER. New configurations start with no camera selected.", ], + noDriver: + "Choose the driver for this camera. Its vision_processor can't run without one.", cameraIndex: ["Position in the SDK's camera list, in detection order."], serial: [ "Stays with the camera, where the index shifts when another camera is missing. List them with build/spinnaker_probe --list.", diff --git a/gui/frontend/src/lib/text/checklist.ts b/gui/frontend/src/lib/text/checklist.ts index 7e31911..fd9dec4 100644 --- a/gui/frontend/src/lib/text/checklist.ts +++ b/gui/frontend/src/lib/text/checklist.ts @@ -54,6 +54,7 @@ export const checklist = { ? `Sending detections, ${steady(String(fps), 3)} fps` : "Sending detections", notHeard: "Nothing heard from this camera yet", + noCamera: "No driver selected: choose one on the Camera page", notCalibrated: "Not calibrated yet", calibratedNotLocked: "Calibrated, not locked: lock it so a restart doesn't recalibrate", diff --git a/gui/frontend/src/lib/text/configFields.ts b/gui/frontend/src/lib/text/configFields.ts index 0c2d4d4..d3d29d2 100644 --- a/gui/frontend/src/lib/text/configFields.ts +++ b/gui/frontend/src/lib/text/configFields.ts @@ -5,7 +5,10 @@ import type { ConfigField } from "../layout/configCategories"; export const CONFIG_FIELDS = { camera: [ - { name: "driver", comment: "SPINNAKER, MVIMPACT, DC1394, or OPENCV" }, + { + name: "driver", + comment: "DUMMY (none selected), SPINNAKER, MVIMPACT, DC1394, or OPENCV", + }, { name: "id / device", comment: "Which camera device" }, { name: "width / height", comment: "0 = highest supported resolution" }, { name: "exposure", comment: "µs; 0 = automatic" }, diff --git a/gui/frontend/src/lib/text/docs.ts b/gui/frontend/src/lib/text/docs.ts index 468ecc3..10d6021 100644 --- a/gui/frontend/src/lib/text/docs.ts +++ b/gui/frontend/src/lib/text/docs.ts @@ -121,13 +121,23 @@ export const RESOLUTION_DOCS = { "It starts by itself as soon as its device is free. Nothing needs restarting.", ], }, + "camera-not-selected": { + title: "No camera driver selected", + cause: + "A new configuration doesn't guess which camera you have (driver DUMMY). vision_processor exits with that driver, so a host that runs the cameras (-runCameras) waits for you to choose one.", + steps: [ + "Open the Camera page and choose the driver: OPENCV for a webcam, SPINNAKER for FLIR, MVIMPACT for Bluefox3, DC1394 for FireWire.", + "Choose the device too if there's more than one.", + "With -runCameras it starts by itself. Otherwise restart that camera's vision_processor.", + ], + }, "process-crashing": { title: "A camera's vision_processor keeps exiting", cause: "The host runs every camera's vision_processor itself (-runCameras) and restarts one that exits, waiting longer each time. This one has failed several times in a row, usually because it can't open its camera: the wrong driver, a device that's missing or busy, or a driver the build doesn't include.", steps: [ "Read its last output, here and in full at the bottom of the Camera page. It usually names the problem.", - "Check the camera's driver and device on the Camera page. A webcam needs OPENCV and a /dev/video path; the default, SPINNAKER, is for FLIR cameras only.", + "Check the camera's driver and device on the Camera page. A webcam needs OPENCV and a /dev/video path; SPINNAKER, what a file without a driver means, is for FLIR cameras only.", "Check nothing else has the camera open (another vision_processor, a video call, cheese).", "It restarts by itself after each change. Nothing else needs restarting.", ], diff --git a/gui/frontend/src/lib/text/video.ts b/gui/frontend/src/lib/text/video.ts index 980bf4e..d657dc4 100644 --- a/gui/frontend/src/lib/text/video.ts +++ b/gui/frontend/src/lib/text/video.ts @@ -19,6 +19,7 @@ export const video = { : "vision_processor keeps exiting. Its output is on the Camera page.", processHeld: (conflict: string): string => `vision_processor isn't started: ${conflict}.`, + noCamera: "No camera selected. Choose its driver on the Camera page.", processStarting: "Waiting for video: vision_processor is starting…", waitingKeyframe: "Waiting for a keyframe…", // The rate frames arrive from vision_processor. diff --git a/gui/frontend/src/lib/video/VideoPlayer.svelte b/gui/frontend/src/lib/video/VideoPlayer.svelte index 439ed87..15277b4 100644 --- a/gui/frontend/src/lib/video/VideoPlayer.svelte +++ b/gui/frontend/src/lib/video/VideoPlayer.svelte @@ -100,7 +100,8 @@ const proc = processFor(cameraId); return ( - proc !== undefined && ["failing", "held"].includes(processHealth(proc)) + proc !== undefined && + ["failing", "held", "noCamera"].includes(processHealth(proc)) ); }); @@ -121,6 +122,8 @@ return text.processExiting(lastLine(proc)); case "held": return text.processHeld(proc.conflict ?? ""); + case "noCamera": + return text.noCamera; case "starting": return text.processStarting; case "running": diff --git a/gui/internal/alerts/alerts.go b/gui/internal/alerts/alerts.go index 3a5e839..8350126 100644 --- a/gui/internal/alerts/alerts.go +++ b/gui/internal/alerts/alerts.go @@ -42,6 +42,7 @@ const ( CodeFirstRun = "first_run_not_publishing" CodeDeviceConflict = "device_conflict" CodeProcessCrashing = "process_crashing" + CodeCameraNotSelected = "camera_not_selected" ) // crashingAfter is how many failed runs in a row make a supervised @@ -79,6 +80,7 @@ func Codes() []string { CodeRenderFailed, CodeCameraIDConflict, CodeRegionUncovered, CodeCameraUnplaced, CodeFileChanged, CodeSocketProblem, CodeSocketSilent, CodeHeightsUnreadable, CodeTeamDefaultHeight, CodeLoopbackMulticast, CodeSenderConflict, CodeFirstRun, CodeDeviceConflict, CodeProcessCrashing, + CodeCameraNotSelected, }, config.WarningCodes...) slices.Sort(codes) @@ -131,7 +133,8 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { } for _, p := range net.Processes { - if p.State != supervisor.StateConflict && p.Crashes >= crashingAfter { + held := p.State == supervisor.StateConflict || p.State == supervisor.StateNoCamera + if !held && p.Crashes >= crashingAfter { last := LastLine(p.Output) add(Alert{ ID: "crashing-" + strconv.Itoa(p.CameraID), Code: CodeProcessCrashing, Severity: Error, CameraID: ptr(p.CameraID), @@ -151,6 +154,29 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { }) } + for _, c := range doc.Cameras { + driver, _ := doc.CaptureDevice(c) + if driver != config.DriverNone { + continue + } + + // A camera the host writes no config for has its own; if it's + // sending, it has a driver, whatever this document says. + if c.ConfigPath == "" && len(receivingAddresses(net.Sources, c.CameraID)) > 0 { + continue + } + + severity := Warning + if doc.CompetitionField { + severity = Error + } + + add(Alert{ + ID: "no-camera-" + strconv.Itoa(c.CameraID), Code: CodeCameraNotSelected, Severity: severity, CameraID: ptr(c.CameraID), + Message: fmt.Sprintf("Camera %d has no camera driver chosen, so its vision_processor can't run.", c.CameraID), + }) + } + for _, id := range sortedKeys(state.RenderErrors) { add(Alert{ ID: "render-" + strconv.Itoa(id), Code: CodeRenderFailed, Severity: Error, CameraID: &id, diff --git a/gui/internal/alerts/alerts_test.go b/gui/internal/alerts/alerts_test.go index abe33f6..3d1d773 100644 --- a/gui/internal/alerts/alerts_test.go +++ b/gui/internal/alerts/alerts_test.go @@ -92,6 +92,15 @@ func TestCollect(t *testing.T) { {CameraID: 1, State: supervisor.StateConflict, Conflict: "camera 0 already uses OPENCV /dev/video0"}, } }, "device-1", "device_conflict/error"}, + "no camera chosen": {func(d *config.Document, _ *config.State, _ *Network) { + d.Cameras[1].ConfigPath = "cam1.yml" + d.Cameras[1].Config = noCamera + }, "no-camera-1", "camera_not_selected/warning"}, + "no camera chosen on a competition field": {func(d *config.Document, _ *config.State, n *Network) { + d.CompetitionField = true + d.Cameras[1].Config = noCamera + n.Sources = n.Sources[:1] + }, "no-camera-1", "camera_not_selected/error"}, "crash loop": {func(_ *config.Document, _ *config.State, n *Network) { n.Processes = []supervisor.Status{{ CameraID: 0, State: supervisor.StateWaiting, Crashes: 2, LastExit: "exit status 1", @@ -275,3 +284,26 @@ func TestCrashingProcessNeedsTwoFailuresAndQuotesTheLastLine(t *testing.T) { t.Fatal("three crashes in a row raised no process_crashing alert") } + +var noCamera = config.Settings{"camera": map[string]any{"driver": config.DriverNone}} + +// A camera whose config the host doesn't write has its own; sending, it has a +// driver, whatever this document says. +func TestNoCameraChosenIsFineForAnExternalCameraThatSends(t *testing.T) { + doc, state, net := healthy() + doc.Cameras[1].Config = noCamera + + if got := Collect(doc, state, net); len(got) != 0 { + t.Errorf("Collect = %+v, want nothing", got) + } +} + +// A camera held for having no driver isn't also crash-looping. +func TestNoCameraChosenIsNotCrashing(t *testing.T) { + doc, state, net := healthy() + net.Processes = []supervisor.Status{{CameraID: 0, State: supervisor.StateNoCamera, Crashes: 5}} + + if got := Collect(doc, state, net); len(got) != 0 { + t.Errorf("Collect = %+v, want nothing", got) + } +} diff --git a/gui/internal/config/camera.go b/gui/internal/config/camera.go index 536b341..795c5e0 100644 --- a/gui/internal/config/camera.go +++ b/gui/internal/config/camera.go @@ -10,7 +10,11 @@ import ( // CameraDrivers are vision_processor's camera drivers (src/driver). Which // ones a given build has depends on the SDKs it was compiled against. -var CameraDrivers = []string{"SPINNAKER", "MVIMPACT", "DC1394", "OPENCV"} +var CameraDrivers = []string{DriverNone, "SPINNAKER", "MVIMPACT", "DC1394", "OPENCV"} + +// DriverNone is the protocol's "no camera" driver, what a new config starts +// with until someone chooses one. Today's vision_processor exits on it. +const DriverNone = "DUMMY" // cameraBlock is the YAML shape of a camera: block, as // src/driver/cameradriver.cpp reads it. @@ -28,7 +32,7 @@ type cameraBlock struct { } // deviceKey identifies the physical camera a camera block opens on host, or -// is empty when the block doesn't say which driver. Two cameras with the same +// is empty when the block doesn't say which driver, or says DriverNone. Two cameras with the same // key would fight over one device. func deviceKey(host string, block any) string { driver, device, ok := captureDevice(block, "") @@ -40,7 +44,8 @@ func deviceKey(host string, block any) string { } // CaptureDevice is the driver and device camera c's vision_processor opens, -// with vision_processor's fallbacks filled in: see captureDevice. +// with vision_processor's fallbacks filled in: see captureDevice. DriverNone +// has no device. func (d Document) CaptureDevice(c Camera) (driver, device string) { driver, device, _ = captureDevice(d.Effective(c)["camera"], settings["camera.driver"].Default.(string)) @@ -51,7 +56,7 @@ func (d Document) CaptureDevice(c Camera) (driver, device string) { // src/driver/cameradriver.cpp picks them: device (or its former name path), // else /dev/video for OPENCV, else "id ", the driver's id-th camera. // A block naming no driver uses defaultDriver; ok is false when that's empty -// too. +// too, or for DriverNone, which opens nothing. func captureDevice(block any, defaultDriver string) (driver, device string, ok bool) { var c cameraBlock @@ -67,8 +72,8 @@ func captureDevice(block any, defaultDriver string) (driver, device string, ok b driver = *c.Driver } - if driver == "" { - return "", "", false + if driver == "" || driver == DriverNone { + return driver, "", false } id := 0 diff --git a/gui/internal/config/camera_test.go b/gui/internal/config/camera_test.go index d91bc14..81b5dc1 100644 --- a/gui/internal/config/camera_test.go +++ b/gui/internal/config/camera_test.go @@ -30,6 +30,7 @@ func TestValidateCamera(t *testing.T) { want string // "" for valid }{ "fixture": {map[string]any{"driver": "OPENCV", "path": "/dev/video0"}, ""}, + "none chosen": {map[string]any{"driver": "DUMMY"}, ""}, "dc1394": {map[string]any{"driver": "DC1394", "id": 1}, ""}, "serial": {map[string]any{"driver": "SPINNAKER", "device": "15000001"}, ""}, "manual wb": {map[string]any{"white_balance": map[string]any{"red": 1.2, "blue": 0.9}}, ""}, diff --git a/gui/internal/config/default.go b/gui/internal/config/default.go index ebdb4b8..1741045 100644 --- a/gui/internal/config/default.go +++ b/gui/internal/config/default.go @@ -27,6 +27,7 @@ func Default() (Document, error) { FirstRun: true, Field: field, OptionalFieldLines: optional, + Defaults: Settings{"camera": map[string]any{"driver": DriverNone}}, Cameras: []Camera{{CameraID: 0}}, } diff --git a/gui/internal/config/document_test.go b/gui/internal/config/document_test.go index a9ccb95..5e1222c 100644 --- a/gui/internal/config/document_test.go +++ b/gui/internal/config/document_test.go @@ -370,6 +370,32 @@ func TestDefaultIsDivisionBWithALoneRemoteCamera(t *testing.T) { t.Errorf("cameras = %+v, want a lone camera 0 with no config_path", doc.Cameras) } + if driver, _ := doc.CaptureDevice(doc.Cameras[0]); driver != DriverNone { + t.Errorf("camera 0's driver = %q, want none chosen", driver) + } + + // Several unchosen cameras on one host don't clash over a device. + doc.Layout = &Layout{CameraCount: 4} + doc.AssignLocal("vision.yml") + + if err := doc.Validate(); err != nil { + t.Errorf("four cameras with no driver chosen: %v", err) + } + + // Choosing one driver for all of them gives each its own device. + for i := range doc.Cameras { + doc.Cameras[i].Config = Settings{"camera": mergedCamera(doc.Cameras[i], "OPENCV")} + } + + if err := doc.Validate(); err != nil { + t.Errorf("four cameras on OPENCV: %v", err) + } + + doc, err = Default() + if err != nil { + t.Fatal(err) + } + data, err := Marshal(doc) if err != nil { t.Fatal(err) @@ -428,3 +454,31 @@ func TestValidateAcceptsBareFileNames(t *testing.T) { t.Errorf("Validate: %v", err) } } + +// mergedCamera is c's own camera: block with driver set. +func mergedCamera(c Camera, driver string) map[string]any { + block := map[string]any{"driver": driver} + + if own, ok := c.Config["camera"].(map[string]any); ok { + for k, v := range own { + block[k] = v + } + } + + return block +} + +// A file written before new configs named a driver still means SPINNAKER, as +// vision_processor reads it. +func TestNoDriverStillMeansSpinnaker(t *testing.T) { + if driver, _ := (Document{}).CaptureDevice(Camera{}); driver != "SPINNAKER" { + t.Errorf("driver = %q, want SPINNAKER", driver) + } + + shared := Document{Defaults: Settings{"camera": map[string]any{"driver": DriverNone}}} + own := Camera{Config: Settings{"camera": map[string]any{"driver": "OPENCV"}}} + + if driver, device := shared.CaptureDevice(own); driver != "OPENCV" || device != "/dev/video0" { + t.Errorf("own driver = %s %s, want OPENCV /dev/video0", driver, device) + } +} diff --git a/gui/internal/config/schema.go b/gui/internal/config/schema.go index e817e45..eb227e2 100644 --- a/gui/internal/config/schema.go +++ b/gui/internal/config/schema.go @@ -58,8 +58,8 @@ type Range struct { type Driver struct { ID string `json:"id"` // SelectsBy is how the block picks a device: "id", an index in the SDK's - // camera list, or "path", a device or file path. - SelectsBy string `json:"selectsBy" enum:"id,path"` + // camera list, "path", a device or file path, or "none". + SelectsBy string `json:"selectsBy" enum:"id,path,none"` // Serial is whether device can name the camera's serial number, ahead of // the index. Serial bool `json:"serial"` @@ -149,6 +149,7 @@ var settings = map[string]Setting{ } var drivers = []Driver{ + {ID: DriverNone, SelectsBy: "none"}, {ID: "SPINNAKER", SelectsBy: "id", Serial: true, Gamma: true, WhiteBalanceProfiles: true}, {ID: "MVIMPACT", SelectsBy: "id"}, {ID: "DC1394", SelectsBy: "id", Gamma: true}, diff --git a/gui/internal/httpjson/httpjson.go b/gui/internal/httpjson/httpjson.go index ace6ad0..b37ed92 100644 --- a/gui/internal/httpjson/httpjson.go +++ b/gui/internal/httpjson/httpjson.go @@ -21,6 +21,7 @@ const ( CodeDiskChanged = "disk_changed" // the file changed on disk since it was loaded CodeNoLiveCalibration = "no_live_calibration" // nothing received to lock yet CodeDeviceConflict = "device_conflict" // another camera uses this one's device + CodeNoCamera = "no_camera" // no camera driver chosen CodePrecondition = "precondition" // a required header (If-Match) is missing CodeCrossOrigin = "cross_origin" // a browser request on behalf of another site CodeUnknownHost = "unknown_host" // the request names this host by a name it doesn't answer to @@ -37,6 +38,7 @@ var statuses = map[string]int{ CodeDiskChanged: http.StatusConflict, CodeNoLiveCalibration: http.StatusConflict, CodeDeviceConflict: http.StatusConflict, + CodeNoCamera: http.StatusConflict, CodePrecondition: http.StatusPreconditionRequired, CodeCrossOrigin: http.StatusForbidden, CodeUnknownHost: http.StatusMisdirectedRequest, @@ -71,7 +73,7 @@ func Errorf(code, format string, args ...any) *Problem { // ErrorBody is the body of every non-2xx API response. type ErrorBody struct { - Error string `json:"error" enum:"bad_request,invalid,not_found,stale,disk_changed,no_live_calibration,device_conflict,precondition,cross_origin,unknown_host,unsupported_media,internal"` + Error string `json:"error" enum:"bad_request,invalid,not_found,stale,disk_changed,no_live_calibration,device_conflict,no_camera,precondition,cross_origin,unknown_host,unsupported_media,internal"` Message string `json:"message"` // Issues lists each problem separately for CodeInvalid. Issues []string `json:"issues,omitempty"` diff --git a/gui/internal/supervisor/supervisor.go b/gui/internal/supervisor/supervisor.go index d553581..dc0eb3a 100644 --- a/gui/internal/supervisor/supervisor.go +++ b/gui/internal/supervisor/supervisor.go @@ -6,6 +6,7 @@ package supervisor import ( + "cmp" "context" "encoding/json" "errors" @@ -32,20 +33,25 @@ var ErrNotSupervised = errors.New("no supervised vision_processor for this camer // Status.Conflict. var ErrHeld = errors.New("held back: another camera uses its device") +// ErrNoCamera means no driver is chosen for the camera, so there's nothing +// to run. +var ErrNoCamera = errors.New("no camera driver chosen") + // Process states. const ( StateRunning = "running" StateRestarting = "restarting" // stopping, to start again at once StateWaiting = "waiting" // exited or failed to start; starts again after a delay StateStopped = "stopped" - StateConflict = "conflict" // not started: another camera uses its device + StateConflict = "conflict" // not started: another camera uses its device + StateNoCamera = "no_camera" // not started: no camera driver chosen ) // Status is one supervised vision_processor. type Status struct { CameraID int `json:"cameraId"` ConfigPath string `json:"configPath"` - State string `json:"state" enum:"running,restarting,waiting,stopped,conflict"` + State string `json:"state" enum:"running,restarting,waiting,stopped,conflict,no_camera"` // Conflict says which camera already uses this one's device, while State // is conflict. Conflict string `json:"conflict,omitempty"` @@ -122,13 +128,15 @@ type Supervisor struct { // proc is one config file's vision_processor. type proc struct { - status Status - latest map[string]any // the camera's rendered config now - started map[string]any // what the running process was started with - timer *time.Timer - restart chan struct{} - cancel context.CancelFunc - starts int + status Status + // noCamera is whether the camera has no driver chosen (config.DriverNone). + noCamera bool + latest map[string]any // the camera's rendered config now + started map[string]any // what the running process was started with + timer *time.Timer + restart chan struct{} + cancel context.CancelFunc + starts int // recalibrate is set when the field changed since it started. recalibrate bool // done is closed when the loop last spawned has returned, nil before the @@ -161,7 +169,8 @@ func New(opts Options) *Supervisor { // config_path, which the store has already written. A camera whose // startup-only settings changed restarts after Options.Debounce; a change to // the field restarts every camera to recalibrate. A camera whose device -// another camera already uses is held, not started (StateConflict). +// another camera already uses is held, not started (StateConflict), as is one +// with no driver chosen (StateNoCamera). func (s *Supervisor) Sync(doc config.Document) { conflicts := deviceConflicts(doc) @@ -180,6 +189,8 @@ func (s *Supervisor) Sync(doc config.Document) { seen[c.ConfigPath] = true rendered := doc.Rendered(c) + driver, _ := doc.CaptureDevice(c) + noCamera := driver == config.DriverNone p := s.procs[c.ConfigPath] if p == nil { @@ -189,7 +200,7 @@ func (s *Supervisor) Sync(doc config.Document) { restart: make(chan struct{}, 1), } s.procs[c.ConfigPath] = p - p.status.Conflict = conflicts[c.CameraID] + p.status.Conflict, p.noCamera = conflicts[c.CameraID], noCamera s.spawnLocked(p) continue @@ -197,9 +208,9 @@ func (s *Supervisor) Sync(doc config.Document) { p.status.CameraID = c.CameraID - if held := conflicts[c.CameraID]; held != p.status.Conflict { - p.status.Conflict = held - if held != "" { + if conflict := conflicts[c.CameraID]; conflict != p.status.Conflict || noCamera != p.noCamera { + p.status.Conflict, p.noCamera = conflict, noCamera + if p.held() { s.holdLocked(p) } else { p.latest = rendered @@ -209,7 +220,7 @@ func (s *Supervisor) Sync(doc config.Document) { continue } - if p.status.Conflict != "" { + if p.held() { p.latest = rendered // starts with it once released continue @@ -255,6 +266,10 @@ func (s *Supervisor) Restart(cameraID int) error { continue } + if p.noCamera { + return ErrNoCamera + } + if p.status.Conflict != "" { return ErrHeld } @@ -284,6 +299,9 @@ func (s *Supervisor) Statuses() []Status { if st.Conflict != "" { st.State = StateConflict } + if p.noCamera { + st.State = StateNoCamera + } st.PendingKeys = slices.Clone(st.PendingKeys) st.Output = slices.Clone(st.Output) out = append(out, st) @@ -321,7 +339,7 @@ func (s *Supervisor) notify() { // loop held and then released waits for its previous one to stop the old // process first. func (s *Supervisor) spawnLocked(p *proc) { - if s.ctx == nil || s.ctx.Err() != nil || p.cancel != nil || p.status.Conflict != "" { + if s.ctx == nil || s.ctx.Err() != nil || p.cancel != nil || p.held() { return } @@ -343,13 +361,18 @@ func (s *Supervisor) spawnLocked(p *proc) { }() } -// holdLocked stops p's loop, and with it the process, for a device conflict. +// held is whether p mustn't run: a device conflict, or no camera chosen. +func (p *proc) held() bool { return p.status.Conflict != "" || p.noCamera } + +// holdLocked stops p's loop, and with it the process, while p is held. func (s *Supervisor) holdLocked(p *proc) { s.stopTimerLocked(p) p.status.PendingKeys = []string{} + // Whatever it failed on doesn't count against its next camera. + p.status.Crashes = 0 if p.cancel != nil { - slog.Warn("holding vision_processor back", "cam", p.status.CameraID, "reason", p.status.Conflict) + slog.Warn("holding vision_processor back", "cam", p.status.CameraID, "reason", cmp.Or(p.status.Conflict, ErrNoCamera.Error())) p.cancel() p.cancel = nil } @@ -619,6 +642,10 @@ func deviceConflicts(doc config.Document) map[int]string { } driver, device := doc.CaptureDevice(c) + if driver == config.DriverNone { + continue + } + key := driver + " " + device if strings.HasPrefix(device, "/") { diff --git a/gui/internal/supervisor/supervisor_test.go b/gui/internal/supervisor/supervisor_test.go index 7ba4b30..0079b20 100644 --- a/gui/internal/supervisor/supervisor_test.go +++ b/gui/internal/supervisor/supervisor_test.go @@ -592,3 +592,39 @@ func TestWorkDirLinksImages(t *testing.T) { t.Errorf("workDir over a real img = %v, want refused", err) } } + +// A camera with no driver chosen isn't started, doesn't clash with another, +// starts once one is chosen, and stops if it's taken away. +func TestNoCameraChosenHeldUntilChosen(t *testing.T) { + none := config.Settings{"camera": map[string]any{"driver": config.DriverNone}} + h := newHarness(t, Options{}) + path := h.camera(0, "", none) + h.camera(1, "", none) + + time.Sleep(100 * time.Millisecond) + + for id := range 2 { + if st := h.status(id); st.State != StateNoCamera || st.Conflict != "" { + t.Errorf("camera %d = %+v, want held with no camera", id, st) + } + } + + if n := starts(path); n != 0 { + t.Fatalf("unchosen camera started %d times", n) + } + + if err := h.sup.Restart(0); !errors.Is(err, ErrNoCamera) { + t.Errorf("Restart(0) = %v, want ErrNoCamera", err) + } + + h.camera(0, "", config.Settings{"camera": map[string]any{"driver": "OPENCV"}}) + eventually(t, "camera 0 running", func() bool { return h.status(0).State == StateRunning && starts(path) == 1 }) + + pid := h.status(0).PID + h.camera(0, "", none) + eventually(t, "process gone", func() bool { return syscall.Kill(pid, 0) != nil }) + + if st := h.status(0); st.State != StateNoCamera { + t.Errorf("camera 0 = %+v, want held again", st) + } +} From b32e24b7e813efcd7ebc0aded80d05ba8ff13453 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 11:38:06 -0500 Subject: [PATCH 10/35] deliniate network conflicts, improve error levels --- gui/ARCHITECTURE.md | 5 +- gui/README.md | 10 +- gui/REVIEW.md | 36 ++++- gui/cmd/ssl-vision-processor-gui/main.go | 17 ++- gui/cmd/ssl-vision-processor-gui/peers.go | 2 +- gui/cmd/ssl-vision-processor-gui/status.go | 2 + gui/frontend/src/lib/alerts/alert-codes.json | 1 + gui/frontend/src/lib/alerts/alerts.ts | 13 ++ .../src/lib/checklist/checklist.svelte.ts | 12 +- .../src/lib/checklist/checklist.test.ts | 17 ++- .../src/lib/config/HostInterfaces.svelte | 9 +- gui/frontend/src/lib/text/alerts.ts | 6 +- gui/frontend/src/lib/text/checklist.ts | 1 + gui/frontend/src/lib/text/docs.ts | 19 ++- gui/frontend/src/lib/text/network.ts | 7 +- gui/internal/alerts/alerts.go | 93 +++++++++++- gui/internal/alerts/alerts_test.go | 44 +++++- gui/internal/multicast/arrivals.go | 136 ++++++++++++++++++ gui/internal/multicast/arrivals_test.go | 80 +++++++++++ gui/internal/multicast/endpoint.go | 27 +++- gui/internal/multicast/endpoint_test.go | 49 ++++++- gui/internal/multicast/host.go | 17 ++- gui/internal/multicast/host_test.go | 28 ++++ gui/internal/multicast/socket.go | 33 ++++- gui/internal/peers/peers_test.go | 57 ++++++++ gui/internal/peers/watch.go | 30 +++- gui/internal/video/assembler.go | 9 ++ gui/internal/video/manager.go | 20 +++ gui/internal/video/source.go | 11 ++ gui/internal/video/video_test.go | 52 +++++++ 30 files changed, 786 insertions(+), 57 deletions(-) create mode 100644 gui/internal/multicast/arrivals.go create mode 100644 gui/internal/multicast/arrivals_test.go diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index 1fd5cce..3c0cbe3 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -257,8 +257,9 @@ raises no alert, since running without an autoref is normal; one that can't open Which interfaces the host's own sockets use is `host.interfaces`, a section no vision_processor reads, since interface names only mean something on one machine. `auto` (the default) uses interfaces that are up, have carrier, support multicast, and have an IPv4 address, and skips loopback and virtual ones (Docker and VM bridges, -VPN tunnels); it is re-evaluated every second. Otherwise `skip` is a blacklist. At startup the host warns if the -loopback interface has multicast off, as Ubuntu ships it, and suggests the command that enables it. +VPN tunnels); it is re-evaluated every second. Otherwise `skip` is a blacklist. With nothing +else to use, `auto` falls back to loopback if it has multicast on. With no network and loopback multicast off, as +Ubuntu ships it, the host warns at startup, raises an alert, and suggests the commands that enable it. Every endpoint receives on one plain socket that hears only the group it joined (Linux `IP_MULTICAST_ALL` off; Go binds a multicast address as `0.0.0.0`, so binding the group alone doesn't do it), joined on all used interfaces at diff --git a/gui/README.md b/gui/README.md index 9cf67c2..5c266cd 100644 --- a/gui/README.md +++ b/gui/README.md @@ -178,7 +178,7 @@ Multicast addresses are set on the GUI's Network page; these are the defaults. | Live video, per camera | UDP `224.5.23.100:10100` for camera 0, `.101` for camera 1, and so on | In | The GUI uses every network interface that is up, has a cable or link, supports multicast, and has an IPv4 address. -It skips loopback, Docker and VM bridges, and VPNs. The Network page lets you exclude interfaces. +It skips Docker and VM bridges, VPNs, and loopback unless there's nothing else. The Network page lets you exclude interfaces. Three settings can trip you up on a stock Ubuntu machine. All need root, so the GUI can't change them for you. @@ -203,13 +203,17 @@ sudo sysctl --system ``` **Nothing is heard with vision_processor on the same machine and no network cable.** Traffic then has to go over -loopback, where Ubuntu turns multicast off. The GUI logs this at startup. Turn it on, which lasts until the next -reboot: +loopback, where Ubuntu turns multicast off. The GUI logs this at startup and raises an alert. Turn it on and route +multicast there, which lasts until the next reboot, then restart vision_processor: ```sh sudo ip link set lo multicast on +sudo ip route add 224.0.0.0/4 dev lo src 127.0.0.1 ``` +With automatic interfaces, the GUI uses loopback by itself while there's no network. Before connecting one again, +remove the route, or multicast keeps going to loopback only: `sudo ip route del 224.0.0.0/4 dev lo`. + ### Browser Live video needs H.264 support. Google Chrome includes it. Chromium and Firefox on Linux rely on the system's diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 5029297..8c4d825 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,11 +27,12 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-25. **Open** 32 · **Partial** 4 · **Done** 30 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 32 · **Partial** 4 · **Done** 33 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T5-3 is awaiting commit. -1. T5-4: the rest of the lab path (T5-2 is done). +All blockers are fixed. T5-4, T2-8 and T2-9 are awaiting commit; with T5-4 the lab path (T5-2, T5-3, T5-4) is done. + +**Needs the lab PoE machine:** T2-10. | ID | Sev | Owner | Item | Status | |---|---|---|---|---| @@ -53,6 +54,9 @@ All blockers are fixed. T5-3 is awaiting commit. | T2-5 | minor | Will | CLI help | open | | T2-6 | minor | Will | log keys and messages | open | | T2-7 | nit | Will | staticcheck hits | done | +| T2-8 | major | Will | one vision_processor's video restarts are reported as two senders | done | +| T2-9 | major | Will | duplicate video packets (several interfaces) break the picture, no warning | done | +| T2-10 | major | Will + Claude | console warnings while vision/GC use the PoE camera NICs | open (needs lab machine) | | T3-1 | major | Will | WS topic contract in three places | open | | T3-2 | major | Will | generated `paths` unused | open | | T3-3 | major | Will | naming pass before freezing API 1.0 | open | @@ -69,7 +73,7 @@ All blockers are fixed. T5-3 is awaiting commit. | T5-1 | blocker | Will | placeholder Debug page | done | | T5-2 | major | Will | crash-looping VP raises no alert | done | | T5-3 | major | Will | SPINNAKER default driver | done | -| T5-4 | major | Will | 4 warnings on a fresh install | open | +| T5-4 | major | Will | 4 warnings on a fresh install | done | | T5-5 | major | Will | accessibility (labels, contrast) | v2.1 | | T5-6 | major | Will | two navigation systems | open | | T5-7 | minor | Will | first-run wording | open | @@ -258,6 +262,26 @@ The staticcheck hits from Phase 0: deprecated `tint.NewHandler` → `tint.NewTex *Done 2026-11-18 (Claude, at Will's request):* `tint.NewHandler` → `tint.NewTextHandler`. staticcheck is now clean and enforced (T1-7). +**T2-8 | major | Will | `internal/peers/watch.go`, video watch in `cmd/.../peers.go`** +Senders are told apart by IP and port. vision_processor's streamer reopens its socket, on a new port, whenever the streamed view changes size, and it cycles views. For 3 s both ports count, so one vision_processor is reported as "several senders claim the same thing". 393 such warnings in Will's log (2026-11-07/08), every one with both senders on the same machine. +Fix: for video, a new port (and RTP SSRC) from the same IP replaces the old one once the old one stops; a conflict needs both to keep sending, interleaved. + +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the video watch has `Restarts`: a sender that stopped within 100 ms of another starting on its IP is the same program. Two that keep sending are still a conflict, on one machine or two. + +**T2-9 | major | Will | `internal/video/assembler.go`, `internal/multicast/socket.go`** +The video socket joins its group on every used interface, so a stream that reaches the machine on two of them arrives twice from the same IP and port. The assembler reads a repeated sequence number as packet loss: with every packet doubled, a synthetic 60-frame stream yields no frames. Nothing warns about it. The double delivery was reproduced in a namespace with a local sender, only with `accept_local=1` and loose or no rp_filter: with the default `accept_local=0` the kernel drops a machine's own packets coming back in. A sender on another machine reaching both interfaces is untested. Not known to be what Will sees in the lab (T2-10). +Fix: drop packets already seen (same SSRC, recent sequence number), and alert when one sender's packets arrive on several interfaces (needs the arrival interface from IP_PKTINFO). + +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the assembler ignores packets at or up to 1024 behind the newest. Every endpoint (vision, game controller, tracker, video) notes the interface each counted packet arrives on; a sender on several at once is logged once, listed in `Status.duplicates`, and raises `duplicate_packets` (warning, one per interface set, with a how-to). Checked in namespaces: a sender on another machine, with the host's static and link-local interfaces on one switch, was doubled and caught with `rp_filter=2`; with `rp_filter=1` the kernel dropped the copies. + +**T2-10 | major | Will + Claude | interface selection; cause unknown, needs the lab machine** +Reported by Will 2026-11-25: on a lab machine with a field network NIC and a dual-port PoE NIC for FLIR cameras, the console prints warnings. They stopped when he unticked the PoE interfaces for the vision/GC network on the Network page. Not video related, though video may be affected too. The PoE ports are always static or link-local, on another subnet than the field network. The warning text isn't recorded and nothing has been reproduced. +Workaround: untick those interfaces on the Network page. +To collect there, with the PoE interfaces ticked: the exact warning lines and which program prints them, `ip -br addr`, `ip route`, `sysctl net.ipv4.conf.all.rp_filter`, and `GET /api/network` and `/api/alerts`. Then the same with them unticked. +Idea, pending the cause: automatic selection skips link-local (169.254/16) interfaces while another is usable. Static PoE ports look like any other NIC, so those would need a hint on the Network page instead. + +*2026-11-25:* T2-9's alert may name the cause: check whether it appears there with the PoE interfaces ticked. It won't if the prints come from something other than one sender being heard twice. + ### Track 3: API / OpenAPI contract Overall: the REST half is well disciplined. Every route goes through `api.Route`/`Raw`, every one has an operation summary and tag, `TestMain` in `declared_test.go` fails on any undeclared error code, and the error envelope is uniform. The weak half is the WebSocket contract and the frontend's use of the spec. @@ -372,7 +396,7 @@ Fix: an `Error` alert per camera when `crashes ≥ 2` (or state `waiting` after Every new camera defaults to the **Spinnaker (FLIR)** driver (the schema's `camera.driver` default `SPINNAKER`, vision_processor's own fallback). The planned CV package is FOSS-only (OpenCV/V4L, DC1394) and `-runCameras` targets student labs with webcams, so a new lab user's first `-runCameras` start crash-loops on a driver they don't have, and (T5-2) nothing says so. No C++ change is needed: the host owns the bootstrapped `vision.yml`. Fix: write `defaults.camera.driver: OPENCV` in a new config, or better, a wizard step "What cameras?" (webcam / FLIR / FireWire / mvIMPACT) that sets it and offers the `/api/camera/devices` picker. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* not OPENCV. A new config writes `defaults.camera.driver: DUMMY`, the protocol's "no camera (initial state)" (proto `fdd7988`), so nobody gets a wrong driver. A file without a driver still means SPINNAKER. With `-runCameras` a DUMMY camera is held, not started (state `no_camera`; its restart route answers 409 `no_camera`), starts when a driver is chosen, and never counts as a device conflict. New alert `camera_not_selected` (warning, error on a competition field), except for a camera the host writes no config for that is already sending. The Camera page shows "No camera selected" and hides device, resolution and tuning until one is chosen; sidebar, video placeholder and checklist say so too. Today's vision_processor exits on DUMMY (`openCamera` has no case), so a camera run by hand still needs a driver first. Once upstream PR #61 lands, the hold can go. The wizard step stays a possible later feature. +*Done 2026-11-25 (Claude, at Will's request; committed `34b48f2`):* not OPENCV. A new config writes `defaults.camera.driver: DUMMY`, the protocol's "no camera (initial state)" (proto `fdd7988`), so nobody gets a wrong driver. A file without a driver still means SPINNAKER. With `-runCameras` a DUMMY camera is held, not started (state `no_camera`; its restart route answers 409 `no_camera`), starts when a driver is chosen, and never counts as a device conflict. New alert `camera_not_selected` (warning, error on a competition field), except for a camera the host writes no config for that is already sending. The Camera page shows "No camera selected" and hides device, resolution and tuning until one is chosen; sidebar, video placeholder and checklist say so too. Today's vision_processor exits on DUMMY (`openCamera` has no case), so a camera run by hand still needs a driver first. Once upstream PR #61 lands, the hold can go. The wizard step stays a possible later feature. **T5-4 | major | Will | alert severities on a fresh install** Before the user has done anything, a first run shows **4 warnings and 1 caution**: `first_run_not_publishing`, `socket_silent`, `team_default_height` ×2, `loopback_multicast_off`. In a lab without a game controller, the two height warnings never go away. Users learn to ignore the warning count on day one, and that is exactly the count that should matter before a match. @@ -381,6 +405,8 @@ Fix: - `socket_silent` on the vision group should be info/caution until a vision_processor has ever been heard. - Check the loopback caution's wording. "vision_processor on this machine can't be heard here" is only true when no other interface carries the multicast; on a machine with a NIC, the local VP is normally heard via `IP_MULTICAST_LOOP` on that interface. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* vision silent is a caution until something is heard, except on a competition field or while a vision_processor this host runs is running. The default-height alert is a caution only with nothing set and no game controller heard (still an error on a competition field; a lab can clear it with a height per color). Loopback multicast off is hidden while a network is in use and a warning otherwise. The checklist's Teams step stays to do on that height caution. Automatic interface selection falls back to loopback when nothing else is usable and its multicast is on. The how-to was incomplete: a plain sender like vision_processor also needs a multicast route (`ip route add 224.0.0.0/4 dev lo src 127.0.0.1`), or its sends fail with ENETUNREACH. Checked in a network namespace. + **T5-5 | major | Will | accessibility (axe, every page)** - **Critical `label`:** unlabeled form controls on Camera (3), Geometry (4) and Color (1), in light and dark, at every width. - **Serious `color-contrast`:** on every page except Stream. Worst on Color in dark mode (29 nodes) and on Layout/Advanced in dark (10 each). Among the flagged nodes: the tab-bar section headers (`.after:content-['/']`) and the inactive tab text. diff --git a/gui/cmd/ssl-vision-processor-gui/main.go b/gui/cmd/ssl-vision-processor-gui/main.go index f4f0409..f6b38f6 100644 --- a/gui/cmd/ssl-vision-processor-gui/main.go +++ b/gui/cmd/ssl-vision-processor-gui/main.go @@ -182,7 +182,7 @@ func run() int { ctx, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stopSignals() - warnLoopbackMulticast() + warnLoopbackMulticast(h.store) warnFirewall(ufwConfig, *address, udpPorts(h.store)) // Reverse lookups can be slow; until they finish, the host is still @@ -714,12 +714,17 @@ func cameraStreams(doc config.Document) map[int]video.Stream { return streams } -// warnLoopbackMulticast logs once at startup if the loopback interface has -// multicast off, as Ubuntu ships it. The fix needs root, so it's only -// suggested. -func warnLoopbackMulticast() { +// warnLoopbackMulticast logs once at startup if no network is in use and the +// loopback interface has multicast off, as Ubuntu ships it. The fix needs +// root, so it's only suggested. +func warnLoopbackMulticast(store *config.Store) { + if _, _, _, ifaces := currentNetwork(store); multicast.Networked(ifaces) { + return + } + if name, enabled, ok := multicast.LoopbackMulticast(); ok && !enabled { - slog.Warn("multicast is off on the loopback interface", "interface", name, "enable with", "sudo ip link set "+name+" multicast on") + slog.Warn("no network is in use and multicast is off on the loopback interface, so programs on this machine can't hear each other", "interface", name, + "enable with", "sudo ip link set "+name+" multicast on && sudo ip route add 224.0.0.0/4 dev "+name+" src 127.0.0.1") } } diff --git a/gui/cmd/ssl-vision-processor-gui/peers.go b/gui/cmd/ssl-vision-processor-gui/peers.go index 2a3f54c..8c81a48 100644 --- a/gui/cmd/ssl-vision-processor-gui/peers.go +++ b/gui/cmd/ssl-vision-processor-gui/peers.go @@ -42,7 +42,7 @@ func newPeerWatches() *peerWatches { // vision_processor announces once a second. instance: peers.NewWatch(peers.Options{Kind: peers.KindInstance, Window: discovery.Stale, MinCount: 2}, names), referee: peers.NewWatch(peers.Options{Kind: peers.KindReferee, Window: 3 * time.Second, MinCount: 2}, names), - video: peers.NewWatch(peers.Options{Kind: peers.KindVideo, Window: 3 * time.Second, MinCount: 10}, names), + video: peers.NewWatch(peers.Options{Kind: peers.KindVideo, Window: 3 * time.Second, MinCount: 10, Restarts: true}, names), } } diff --git a/gui/cmd/ssl-vision-processor-gui/status.go b/gui/cmd/ssl-vision-processor-gui/status.go index 592d417..5e04a62 100644 --- a/gui/cmd/ssl-vision-processor-gui/status.go +++ b/gui/cmd/ssl-vision-processor-gui/status.go @@ -95,6 +95,8 @@ func (h *hostStatus) Alerts() []alerts.Alert { Referee: n.Referee, Loopback: n.Loopback, LoopbackMulticast: n.LoopbackMulticast, + Networked: multicast.Networked(n.Interfaces), + VideoDuplicates: h.sockets.video.Duplicates(time.Now()), Processes: h.procs.Statuses(), }) } diff --git a/gui/frontend/src/lib/alerts/alert-codes.json b/gui/frontend/src/lib/alerts/alert-codes.json index b68e83b..a2fc466 100644 --- a/gui/frontend/src/lib/alerts/alert-codes.json +++ b/gui/frontend/src/lib/alerts/alert-codes.json @@ -4,6 +4,7 @@ "camera_not_selected", "camera_unplaced", "device_conflict", + "duplicate_packets", "field_changed", "file_changed", "first_run_not_publishing", diff --git a/gui/frontend/src/lib/alerts/alerts.ts b/gui/frontend/src/lib/alerts/alerts.ts index d29fa94..68b301f 100644 --- a/gui/frontend/src/lib/alerts/alerts.ts +++ b/gui/frontend/src/lib/alerts/alerts.ts @@ -236,6 +236,19 @@ function present(a: HostAlert): Alert { ], }; } + case "duplicate_packets": { + const list = (key: string) => (p[key] as string[] | undefined) ?? []; + + return { + ...base, + title: text.duplicates(list("interfaces")), + detail: text.duplicatesDetail(list("streams"), list("senders")), + actions: [ + howTo("duplicate-packets"), + page(text.pages.network, undefined, "network"), + ], + }; + } case "loopback_multicast_off": return { ...base, diff --git a/gui/frontend/src/lib/checklist/checklist.svelte.ts b/gui/frontend/src/lib/checklist/checklist.svelte.ts index 1a5fb53..7ecafde 100644 --- a/gui/frontend/src/lib/checklist/checklist.svelte.ts +++ b/gui/frontend/src/lib/checklist/checklist.svelte.ts @@ -61,7 +61,7 @@ export const ITEMS: Record = { }; // Which host alert codes put an automatic item in "attention". Cautions -// don't: they're often fine, so they leave the item done. +// don't: they're often fine, so they leave the item done (teams aside). const ALERT_CODES: Partial> = { network: ["socket_problem", "loopback_multicast_off"], layout: ["camera_unplaced", "region_uncovered", "camera_id_conflict"], @@ -91,6 +91,7 @@ export type Note = | "calibratedNotLocked" | "locked" | "teamsProblem" + | "noHeights" | "firstRun" | "saved"; }; @@ -349,6 +350,15 @@ export function itemState(id: ItemId): ItemState { })), ); case "teams": + // A caution here means no heights are set at all: not a problem yet, + // but not done either. + if ( + !alertOpen(id) && + hostAlerts.list.some((a) => a.code === "team_default_height") + ) { + return { id, status: "todo", note: { key: "noHeights" } }; + } + return alertItem(id, { key: "teamsProblem" }); case "save": { const unsaved = config.state?.changes.length ?? 0; diff --git a/gui/frontend/src/lib/checklist/checklist.test.ts b/gui/frontend/src/lib/checklist/checklist.test.ts index 65f1c88..753920d 100644 --- a/gui/frontend/src/lib/checklist/checklist.test.ts +++ b/gui/frontend/src/lib/checklist/checklist.test.ts @@ -158,12 +158,21 @@ describe("automatic items", () => { }); it("a caution leaves its item done", () => { - hostAlerts.list = [ - alert("loopback_multicast_off", "caution"), - alert("team_default_height", "caution"), - ]; + hostAlerts.list = [alert("socket_problem", "caution")]; expect(itemState("network").status).toBe("done"); + }); + + it("teams stays to do while no heights are set", () => { expect(itemState("teams").status).toBe("done"); + + hostAlerts.list = [alert("team_default_height", "caution")]; + expect(itemState("teams")).toMatchObject({ + status: "todo", + note: { key: "noHeights" }, + }); + + hostAlerts.list = [alert("team_default_height")]; + expect(itemState("teams").status).toBe("attention"); }); it("a per-camera item with no cameras isn't done", () => { diff --git a/gui/frontend/src/lib/config/HostInterfaces.svelte b/gui/frontend/src/lib/config/HostInterfaces.svelte index 8b49634..1953826 100644 --- a/gui/frontend/src/lib/config/HostInterfaces.svelte +++ b/gui/frontend/src/lib/config/HostInterfaces.svelte @@ -31,7 +31,7 @@ return { name: i.name, detail: detail(i.address, i.autoReason), - checked: i.autoUse, + checked: i.used, disabled: true, }; } @@ -78,7 +78,7 @@ // the switch itself changes nothing. const skip = !auto && selection.skip.length === 0 - ? ifaces.filter((i) => i.usable && !i.autoUse).map((i) => i.name) + ? ifaces.filter((i) => i.usable && !i.used).map((i) => i.name) : selection.skip; writeInterfaces(auto, skip); @@ -91,8 +91,11 @@ writeInterfaces(false, skip); } + // Only matters with no network in use, as in the host's alert. let loopbackOff = $derived( - network.state !== null && !network.state.loopbackMulticast, + network.state !== null && + !network.state.loopbackMulticast && + !ifaces.some((i) => i.used && i.autoReason !== "loopback"), ); diff --git a/gui/frontend/src/lib/text/alerts.ts b/gui/frontend/src/lib/text/alerts.ts index d562f6d..1e3c5df 100644 --- a/gui/frontend/src/lib/text/alerts.ts +++ b/gui/frontend/src/lib/text/alerts.ts @@ -81,9 +81,13 @@ export const alerts = { video: (camera: number): string => `Camera ${String(camera)}'s video is coming from several senders`, }, + duplicates: (interfaces: string[]): string => + `The same packets arrive on ${interfaces.join(" and ")}`, + duplicatesDetail: (streams: string[], senders: string[]): string => + `Each is heard more than once: ${streams.join(", ")}, from ${senders.join(", ")}.`, loopback: (iface: string): string => `Multicast is off on ${iface}`, loopbackDetail: - "Only matters when programs on this machine talk over loopback.", + "No network is in use either, so programs on this machine can't hear each other.", // Titles for the host's per-camera warning codes (gui/internal/config's // status.go). The host's own message is the detail. Unlisted codes show diff --git a/gui/frontend/src/lib/text/checklist.ts b/gui/frontend/src/lib/text/checklist.ts index fd9dec4..95a3ae1 100644 --- a/gui/frontend/src/lib/text/checklist.ts +++ b/gui/frontend/src/lib/text/checklist.ts @@ -60,6 +60,7 @@ export const checklist = { "Calibrated, not locked: lock it so a restart doesn't recalibrate", locked: "Calibrated and locked", teamsProblem: "A team height alert is open.", + noHeights: "No robot heights set, and no game controller heard yet", firstRun: "Not saved yet: nothing is published until the first save", unsaved: (n: number): string => `${String(n)} unsaved ${plural(n, "change")}`, diff --git a/gui/frontend/src/lib/text/docs.ts b/gui/frontend/src/lib/text/docs.ts index 10d6021..07fe899 100644 --- a/gui/frontend/src/lib/text/docs.ts +++ b/gui/frontend/src/lib/text/docs.ts @@ -92,6 +92,16 @@ export const RESOLUTION_DOCS = { "Stop the game controller that shouldn't run, or move it to another address and port.", ], }, + "duplicate-packets": { + title: "The same packets arrive on several interfaces", + cause: + "One sender's multicast reaches this machine through more than one network interface: two interfaces on one network, or a switch or cable joining two networks that should be separate. Each packet is then heard more than once, which wastes bandwidth and CPU.", + steps: [ + "Open the Network page and turn off automatic host interfaces.", + "Leave on only the interface on the field network. Camera (PoE) interfaces don't need to be used.", + "If the networks should be separate, check the cabling and the switch's VLANs.", + ], + }, "sender-conflict-video": { title: "A camera's video comes from several senders", cause: @@ -163,11 +173,14 @@ export const RESOLUTION_DOCS = { "loopback-multicast-off": { title: "Multicast is off on the loopback interface", cause: - "Programs on this machine that multicast over loopback (e.g. a vision_processor and the GUI on one laptop with no network) won't hear each other.", + "This machine has no network in use, so its programs (a vision_processor and the GUI on one laptop) can only reach each other over loopback, where Ubuntu turns multicast off.", steps: [ - "Enable it until the next reboot:", + "Connect a network, or turn loopback multicast on until the next reboot:", "$ sudo ip link set lo multicast on", - "Not needed when every program uses a real network interface.", + "$ sudo ip route add 224.0.0.0/4 dev lo src 127.0.0.1", + "With automatic interfaces the GUI then uses lo by itself. Restart any vision_processor already running.", + "Before connecting a network again, remove the route, or multicast keeps going to loopback only:", + "$ sudo ip route del 224.0.0.0/4 dev lo", ], }, "region-uncovered": { diff --git a/gui/frontend/src/lib/text/network.ts b/gui/frontend/src/lib/text/network.ts index 08fc60e..fcc01fb 100644 --- a/gui/frontend/src/lib/text/network.ts +++ b/gui/frontend/src/lib/text/network.ts @@ -11,14 +11,15 @@ export const network = { reopening: (address: string): string => `Reopening on ${address}…`, interfaces: { - autoHint: "(skips loopback, disconnected, and virtual interfaces)", + autoHint: + "(skips disconnected and virtual interfaces, and loopback unless it's the only one)", waiting: "Waiting for the host…", scope: "Only this host's sockets; vision_processors use their system's default route. Broadcast receiving listens on every interface.", loopbackOff: (iface: string): string => - `Multicast is off on \`${iface}\`. Programs on this machine that multicast over loopback won't hear each other. To enable it until reboot:`, + `Multicast is off on \`${iface}\`. No network is in use either, so programs on this machine won't hear each other. To enable it until reboot:`, loopbackFix: (iface: string): string => - `sudo ip link set ${iface} multicast on`, + `sudo ip link set ${iface} multicast on\nsudo ip route add 224.0.0.0/4 dev ${iface} src 127.0.0.1`, }, errors: { diff --git a/gui/internal/alerts/alerts.go b/gui/internal/alerts/alerts.go index 8350126..9e4ad6b 100644 --- a/gui/internal/alerts/alerts.go +++ b/gui/internal/alerts/alerts.go @@ -7,6 +7,7 @@ package alerts import ( "cmp" "fmt" + "maps" "slices" "strconv" "strings" @@ -43,6 +44,7 @@ const ( CodeDeviceConflict = "device_conflict" CodeProcessCrashing = "process_crashing" CodeCameraNotSelected = "camera_not_selected" + CodeDuplicatePackets = "duplicate_packets" ) // crashingAfter is how many failed runs in a row make a supervised @@ -80,7 +82,7 @@ func Codes() []string { CodeRenderFailed, CodeCameraIDConflict, CodeRegionUncovered, CodeCameraUnplaced, CodeFileChanged, CodeSocketProblem, CodeSocketSilent, CodeHeightsUnreadable, CodeTeamDefaultHeight, CodeLoopbackMulticast, CodeSenderConflict, CodeFirstRun, CodeDeviceConflict, CodeProcessCrashing, - CodeCameraNotSelected, + CodeCameraNotSelected, CodeDuplicatePackets, }, config.WarningCodes...) slices.Sort(codes) @@ -98,6 +100,11 @@ type Network struct { Referee referee.State Loopback string LoopbackMulticast bool + // Networked is whether any interface besides loopback is in use. + Networked bool + // VideoDuplicates are, by camera, senders of its video heard on several + // interfaces; the other sockets' are in their Status. + VideoDuplicates map[int][]multicast.Duplicate // Conflicts are things claimed by more senders than they should be. Conflicts []peers.Conflict // Processes are the host's own vision_processors (-runCameras). @@ -261,8 +268,13 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { } severity := Warning - if socket.kind == "gc" { + + switch { + case socket.kind == "gc": severity = Error + case socket.status.LastHeard == nil && !doc.CompetitionField && !running(net.Processes): + // A lab where no vision_processor has been started yet. + severity = Caution } params["everHeard"] = socket.status.LastHeard != nil @@ -287,8 +299,14 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { } severity := Warning - if doc.CompetitionField { + + switch { + case doc.CompetitionField: severity = Error + case issue == IssueNoHeight && net.Referee.Heard == nil: + // Nothing set, and no game controller to name a team: a lab + // may never need it. + severity = Caution } team := teamName(net, color) @@ -319,11 +337,20 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { }) } - if !net.LoopbackMulticast { + for _, d := range duplicates(net) { add(Alert{ - ID: "loopback-multicast", Code: CodeLoopbackMulticast, Severity: Caution, + ID: "duplicates-" + strings.Join(d.interfaces, "-"), Code: CodeDuplicatePackets, Severity: Warning, + Params: map[string]any{"interfaces": d.interfaces, "streams": d.streams, "senders": d.senders}, + Message: fmt.Sprintf("Packets arrive on %v at once, so each is heard more than once (%v from %v).", d.interfaces, d.streams, d.senders), + }) + } + + // With a network, programs on this machine hear each other through it. + if !net.LoopbackMulticast && !net.Networked { + add(Alert{ + ID: "loopback-multicast", Code: CodeLoopbackMulticast, Severity: Warning, Params: map[string]any{"interface": net.Loopback}, - Message: fmt.Sprintf("Multicast is off on %s, so vision_processor on this machine can't be heard here.", net.Loopback), + Message: fmt.Sprintf("Multicast is off on %s and no network is in use, so programs on this machine can't hear each other.", net.Loopback), }) } @@ -467,3 +494,57 @@ func LastLine(output []string) string { return "" } + +// running is whether the host is running any vision_processor itself: one +// announces itself every second, so silence then is a fault. +func running(processes []supervisor.Status) bool { + return slices.ContainsFunc(processes, func(p supervisor.Status) bool { return p.State == supervisor.StateRunning }) +} + +// duplicate is everything arriving on one set of interfaces at once. +type duplicate struct { + interfaces []string + streams []string // "vision", "gc", "tracker", "camera 0 video" + senders []string +} + +// duplicates groups every socket's duplicates by the interfaces involved: one +// wiring mistake is one alert, however many senders it doubles. +func duplicates(net Network) []*duplicate { + byInterfaces := map[string]*duplicate{} + + record := func(stream string, found []multicast.Duplicate) { + for _, f := range found { + key := strings.Join(f.Interfaces, " ") + + d := byInterfaces[key] + if d == nil { + d = &duplicate{interfaces: f.Interfaces} + byInterfaces[key] = d + } + + if !slices.Contains(d.streams, stream) { + d.streams = append(d.streams, stream) + } + + if !slices.Contains(d.senders, f.Address) { + d.senders = append(d.senders, f.Address) + } + } + } + + record("vision", net.Vision.Duplicates) + record("gc", net.GC.Duplicates) + record("tracker", net.Tracker.Duplicates) + + for _, id := range slices.Sorted(maps.Keys(net.VideoDuplicates)) { + record(fmt.Sprintf("camera %d video", id), net.VideoDuplicates[id]) + } + + out := []*duplicate{} + for _, key := range slices.Sorted(maps.Keys(byInterfaces)) { + out = append(out, byInterfaces[key]) + } + + return out +} diff --git a/gui/internal/alerts/alerts_test.go b/gui/internal/alerts/alerts_test.go index 3d1d773..33c3e83 100644 --- a/gui/internal/alerts/alerts_test.go +++ b/gui/internal/alerts/alerts_test.go @@ -24,6 +24,7 @@ func healthy() (config.Document, config.State, Network) { Sources: []detections.Source{{CameraID: 0, Address: "10.0.0.1", Receiving: true}, {CameraID: 1, Address: "10.0.0.2", Receiving: true}}, Referee: referee.State{Heard: &now, Yellow: referee.Team{Name: "A"}, Blue: referee.Team{Name: "B"}, Heights: map[string]float64{"A": 150, "B": 140}}, LoopbackMulticast: true, + Networked: true, } } @@ -73,9 +74,33 @@ func TestCollect(t *testing.T) { "socket problem": {func(_ *config.Document, _ *config.State, n *Network) { n.Vision.Problem = "no usable network interface" }, "socket-vision", "socket_problem/error"}, - "vision silent": {func(_ *config.Document, _ *config.State, n *Network) { + "vision never heard": {func(_ *config.Document, _ *config.State, n *Network) { n.Vision.Receiving = false + }, "silent-vision", "socket_silent/caution"}, + "vision went silent": {func(_ *config.Document, _ *config.State, n *Network) { + n.Vision.Receiving = false + n.Vision.LastHeard = n.Referee.Heard }, "silent-vision", "socket_silent/warning"}, + "vision never heard on a competition field": {func(d *config.Document, _ *config.State, n *Network) { + d.CompetitionField = true + n.Vision.Receiving = false + }, "silent-vision", "socket_silent/warning"}, + "vision never heard though one runs here": {func(_ *config.Document, _ *config.State, n *Network) { + n.Vision.Receiving = false + n.Processes = []supervisor.Status{{State: supervisor.StateRunning}} + }, "silent-vision", "socket_silent/warning"}, + "no height, no game controller heard": {func(_ *config.Document, _ *config.State, n *Network) { + n.Referee.Heard = nil + n.Referee.Yellow.Name = "" + }, "team-height-yellow", "team_default_height/caution"}, + "no height, game controller heard": {func(_ *config.Document, _ *config.State, n *Network) { + n.Referee.Yellow.Name = "" + }, "team-height-yellow", "team_default_height/warning"}, + "half-entered height, no game controller heard": {func(d *config.Document, _ *config.State, n *Network) { + n.Referee.Heard = nil + n.Referee.Yellow.Name = "" + d.Teams = &config.Teams{ByColor: &config.ColorOverrides{Yellow: &config.TeamOverride{}}} + }, "team-height-yellow", "team_default_height/warning"}, "gc silent on a competition field": {func(d *config.Document, _ *config.State, n *Network) { d.CompetitionField = true n.GC.Receiving = false @@ -137,10 +162,16 @@ func TestCollect(t *testing.T) { {Address: "10.0.0.1:50000"}, {Address: "10.0.0.2:50000"}, }}} }, "sender-video-camera 1 video", "sender_conflict/error"}, + "packets on two interfaces": {func(_ *config.Document, _ *config.State, n *Network) { + both := []string{"eth0", "eth1"} + n.Vision.Duplicates = []multicast.Duplicate{{Address: "10.0.0.1:10006", Interfaces: both}, {Address: "10.0.0.2:10006", Interfaces: both}} + n.VideoDuplicates = map[int][]multicast.Duplicate{0: {{Address: "10.0.0.1:50000", Interfaces: both}}} + }, "duplicates-eth0-eth1", "duplicate_packets/warning"}, "loopback": {func(_ *config.Document, _ *config.State, n *Network) { n.LoopbackMulticast = false + n.Networked = false n.Loopback = "lo" - }, "loopback-multicast", "loopback_multicast_off/caution"}, + }, "loopback-multicast", "loopback_multicast_off/warning"}, } { t.Run(name, func(t *testing.T) { doc, state, net := healthy() @@ -307,3 +338,12 @@ func TestNoCameraChosenIsNotCrashing(t *testing.T) { t.Errorf("Collect = %+v, want nothing", got) } } + +func TestLoopbackMulticastOffIsFineWithANetwork(t *testing.T) { + doc, state, net := healthy() + net.LoopbackMulticast = false + + if got := Collect(doc, state, net); len(got) != 0 { + t.Errorf("Collect = %+v, want nothing", got) + } +} diff --git a/gui/internal/multicast/arrivals.go b/gui/internal/multicast/arrivals.go new file mode 100644 index 0000000..5fec3eb --- /dev/null +++ b/gui/internal/multicast/arrivals.go @@ -0,0 +1,136 @@ +package multicast + +import ( + "log/slog" + "net" + "slices" + "strings" + "time" +) + +// Duplicate is one sender whose packets arrive on several interfaces at once, +// so each is heard more than once: two interfaces on one network, or a switch +// that joins two networks. +type Duplicate struct { + // Address is the sender's "ip:port". + Address string `json:"address"` + Interfaces []string `json:"interfaces"` +} + +const ( + // arrivalCount is how many packets in a row (none ReceivingWindow apart) + // an interface needs to count, so one stray isn't a duplicate. + arrivalCount = 3 + // maxArrivals is how many senders are kept before the silent ones are + // dropped. + maxArrivals = 64 +) + +// arrivals tracks which interfaces each sender's packets come in on. Its +// Endpoint's mu guards it. +type arrivals map[string]*senderArrivals + +type senderArrivals struct { + on map[string]*arrival // by interface name + warned bool +} + +type arrival struct { + last time.Time + count int +} + +// note records one packet from from on iface. It returns the interfaces to +// warn about when the sender has just become a duplicate, else nil. +func (a arrivals) note(from *net.UDPAddr, iface string, now time.Time) []string { + if from == nil || iface == "" { + return nil + } + + key := from.String() + + s := a[key] + if s == nil { + if len(a) >= maxArrivals { + a.prune(now) + } + + s = &senderArrivals{on: map[string]*arrival{}} + a[key] = s + } + + on := s.on[iface] + if on == nil || now.Sub(on.last) > ReceivingWindow { + on = &arrival{} + s.on[iface] = on + } + + on.last = now + on.count++ + + if len(s.on) == 1 { + return nil // the usual case: nothing to compare + } + + ifaces := s.active(now) + + switch { + case len(ifaces) < 2: + s.warned = false + case !s.warned: + s.warned = true + + return ifaces + } + + return nil +} + +// active lists the interfaces s is arriving on as of now. +func (s *senderArrivals) active(now time.Time) []string { + var out []string + + for name, on := range s.on { + if on.count >= arrivalCount && now.Sub(on.last) <= ReceivingWindow { + out = append(out, name) + } + } + + slices.Sort(out) + + return out +} + +func (a arrivals) prune(now time.Time) { + for key, s := range a { + for name, on := range s.on { + if now.Sub(on.last) > ReceivingWindow { + delete(s.on, name) + } + } + + if len(s.on) == 0 { + delete(a, key) + } + } +} + +// duplicates lists every sender arriving on several interfaces. +func (a arrivals) duplicates(now time.Time) []Duplicate { + var out []Duplicate + + for key, s := range a { + if ifaces := s.active(now); len(ifaces) > 1 { + out = append(out, Duplicate{Address: key, Interfaces: ifaces}) + } + } + + slices.SortFunc(out, func(a, b Duplicate) int { return strings.Compare(a.Address, b.Address) }) + + return out +} + +func warnDuplicate(endpoint string, from *net.UDPAddr, ifaces []string) { + slog.Warn("one sender's packets arrive on several interfaces; exclude all but one on the Network page", + "endpoint", endpoint, "from", from, "interfaces", ifaces) +} diff --git a/gui/internal/multicast/arrivals_test.go b/gui/internal/multicast/arrivals_test.go new file mode 100644 index 0000000..2e8d7d6 --- /dev/null +++ b/gui/internal/multicast/arrivals_test.go @@ -0,0 +1,80 @@ +package multicast + +import ( + "net" + "slices" + "testing" + "time" +) + +func TestArrivalsFindASenderOnSeveralInterfaces(t *testing.T) { + a := arrivals{} + vp := &net.UDPAddr{IP: net.IPv4(10, 0, 0, 7), Port: 10006} + gc := &net.UDPAddr{IP: net.IPv4(10, 0, 0, 8), Port: 10003} + now := time.Now() + warnings := 0 + + for i := range 10 { + now = now.Add(10 * time.Millisecond) + + for _, iface := range []string{"eth1", "eth0"} { + if got := a.note(vp, iface, now); got != nil { + warnings++ + + if !slices.Equal(got, []string{"eth0", "eth1"}) { + t.Errorf("warned about %v", got) + } + } + } + + a.note(gc, "eth0", now) + + if i == 0 { + a.note(gc, "eth1", now) // one stray + } + } + + if warnings != 1 { + t.Errorf("warned %d times, want once", warnings) + } + + got := a.duplicates(now) + if len(got) != 1 || got[0].Address != "10.0.0.7:10006" || !slices.Equal(got[0].Interfaces, []string{"eth0", "eth1"}) { + t.Fatalf("duplicates = %+v, want only the sender on both", got) + } + + // eth1 stops: no longer a duplicate, and a return warns again. + later := now.Add(2 * ReceivingWindow) + a.note(vp, "eth0", later) + + if got := a.duplicates(later); len(got) != 0 { + t.Errorf("still duplicates = %+v", got) + } + + for range arrivalCount { + a.note(vp, "eth0", later) + + if a.note(vp, "eth1", later) != nil { + warnings++ + } + } + + if warnings != 2 { + t.Errorf("%d warnings after it came back, want 2", warnings) + } +} + +// Many short-lived senders don't grow the table for ever. +func TestArrivalsForgetSilentSenders(t *testing.T) { + a := arrivals{} + now := time.Now() + + for port := range 10 * maxArrivals { + now = now.Add(time.Second) + a.note(&net.UDPAddr{IP: net.IPv4(10, 0, 0, 7), Port: port + 1}, "eth0", now) + } + + if len(a) > maxArrivals { + t.Errorf("%d senders kept, want at most %d", len(a), maxArrivals) + } +} diff --git a/gui/internal/multicast/endpoint.go b/gui/internal/multicast/endpoint.go index 0348355..055be7b 100644 --- a/gui/internal/multicast/endpoint.go +++ b/gui/internal/multicast/endpoint.go @@ -61,7 +61,11 @@ type sockets struct { // opener opens sockets on address over the interfaces marked Used, // delivering datagrams to receive. Swapped out in tests, which can't rely on // joining a real multicast group. -type opener func(address string, ifaces []Interface, opts Options, receive func([]byte, *net.UDPAddr)) sockets +type opener func(address string, ifaces []Interface, opts Options, receive receiver) sockets + +// receiver takes one datagram, its sender, and the interface it arrived on +// ("" if unknown). +type receiver func(data []byte, from *net.UDPAddr, iface string) // Endpoint is one multicast group the host listens on, and optionally sends to. type Endpoint struct { @@ -84,6 +88,7 @@ type Endpoint struct { heard uint64 lastHeard time.Time source string + arrivals arrivals } // Status is an endpoint's address and what it has heard there. @@ -99,6 +104,8 @@ type Status struct { Receiving bool `json:"receiving"` // Problem is why the sockets aren't fully open, if they aren't. Problem string `json:"problem,omitempty"` + // Duplicates are the senders heard on several interfaces at once. + Duplicates []Duplicate `json:"duplicates,omitempty"` } // NewEndpoint prepares an endpoint on address (e.g. "224.5.23.2:10006") @@ -117,6 +124,8 @@ func NewEndpoint(name, address string, ifaces []Interface, opts Options, consume poke: make(chan struct{}, 1), address: address, ifaces: ifaces, + + arrivals: arrivals{}, } } @@ -144,6 +153,7 @@ func (e *Endpoint) SetAddress(address string) { e.heard = 0 e.lastHeard = time.Time{} e.source = "" + e.arrivals = arrivals{} e.mu.Unlock() e.reopen() @@ -162,6 +172,7 @@ func (e *Endpoint) SetInterfaces(ifaces []Interface) { } e.ifaces = ifaces + e.arrivals = arrivals{} e.mu.Unlock() e.reopen() @@ -273,8 +284,8 @@ func (e *Endpoint) interfaces() []Interface { } func (e *Endpoint) start(address string, ifaces []Interface, retrying bool) sockets { - s := e.open(address, ifaces, e.opts, func(data []byte, from *net.UDPAddr) { - e.receive(address, data, from) + s := e.open(address, ifaces, e.opts, func(data []byte, from *net.UDPAddr, iface string) { + e.receive(address, data, from, iface) }) e.mu.Lock() @@ -299,7 +310,7 @@ func (e *Endpoint) start(address string, ifaces []Interface, retrying bool) sock // receive handles a datagram that arrived on address. A closing socket can // still deliver one after a move; it's dropped rather than counted against // the new address. -func (e *Endpoint) receive(address string, data []byte, from *net.UDPAddr) { +func (e *Endpoint) receive(address string, data []byte, from *net.UDPAddr, iface string) { if !e.consume(data, from) { return } @@ -314,6 +325,10 @@ func (e *Endpoint) receive(address string, data []byte, from *net.UDPAddr) { e.heard++ e.lastHeard = time.Now() + if ifaces := e.arrivals.note(from, iface, e.lastHeard); ifaces != nil { + warnDuplicate(e.name, from, ifaces) + } + if from != nil { e.source = from.IP.String() } @@ -342,6 +357,8 @@ func (e *Endpoint) Status(now time.Time) Status { Heard: e.heard, Source: e.source, Problem: e.problem, + + Duplicates: e.arrivals.duplicates(now), } if !e.lastHeard.IsZero() { @@ -371,7 +388,7 @@ func modeOf(address string) string { // openSockets is the real opener: a plain receiving socket (openSocket) and, // for Options.Send, a sender on every used interface (openSender). -func openSockets(address string, ifaces []Interface, opts Options, receive func([]byte, *net.UDPAddr)) sockets { +func openSockets(address string, ifaces []Interface, opts Options, receive receiver) sockets { stopReceiver, receiverProblem := openSocket(address, ifaces, opts, receive) if !opts.Send { diff --git a/gui/internal/multicast/endpoint_test.go b/gui/internal/multicast/endpoint_test.go index 23bf967..452dfcd 100644 --- a/gui/internal/multicast/endpoint_test.go +++ b/gui/internal/multicast/endpoint_test.go @@ -23,7 +23,7 @@ type fakeNet struct { mu sync.Mutex opened []string stopped []string - receive func([]byte, *net.UDPAddr) + receive receiver sent [][]byte open chan string // problems is what each successive open reports as unhealthy; opens @@ -35,7 +35,7 @@ func newFakeNet() *fakeNet { return &fakeNet{open: make(chan string, 8)} } -func (f *fakeNet) opener(address string, _ []Interface, opts Options, receive func([]byte, *net.UDPAddr)) sockets { +func (f *fakeNet) opener(address string, _ []Interface, opts Options, receive receiver) sockets { f.mu.Lock() f.opened = append(f.opened, address) f.receive = receive @@ -75,7 +75,15 @@ func (f *fakeNet) deliver(data []byte) { receive := f.receive f.mu.Unlock() - receive(data, &net.UDPAddr{IP: net.IPv4(10, 0, 0, 7), Port: 10006}) + receive(data, &net.UDPAddr{IP: net.IPv4(10, 0, 0, 7), Port: 10006}, "eth0") +} + +func (f *fakeNet) deliverOn(iface string, data []byte) { + f.mu.Lock() + receive := f.receive + f.mu.Unlock() + + receive(data, &net.UDPAddr{IP: net.IPv4(10, 0, 0, 7), Port: 10006}, iface) } func (f *fakeNet) waitOpen(t *testing.T, want string) { @@ -184,7 +192,7 @@ func TestEndpointDropsLatePacketFromOldSocket(t *testing.T) { e.SetAddress("224.5.23.9:10010") f.waitOpen(t, "224.5.23.9:10010") - oldReceive([]byte("late"), nil) + oldReceive([]byte("late"), nil, "") if s := e.Status(time.Now()); s.Heard != 0 { t.Fatalf("late packet from the old socket counted: %+v", s) @@ -519,3 +527,36 @@ func TestTrackerConsumer(t *testing.T) { t.Fatal("a packet without a uuid counted as heard") } } + +// Only what the consumer counts is compared, so noise and the host's own +// packets never look like duplicates; a new interface selection starts over. +func TestEndpointReportsDuplicates(t *testing.T) { + e, f, stop := startEndpoint(t, "224.5.23.2:10006", Options{}, func(data []byte, _ *net.UDPAddr) bool { + return string(data) == "valid" + }) + defer stop() + + for range arrivalCount { + f.deliverOn("eth0", []byte("valid")) + f.deliverOn("eth1", []byte("own")) + } + + if d := e.Status(time.Now()).Duplicates; len(d) != 0 { + t.Errorf("Duplicates = %+v, want none", d) + } + + for range arrivalCount { + f.deliverOn("eth1", []byte("valid")) + } + + if d := e.Status(time.Now()).Duplicates; len(d) != 1 || len(d[0].Interfaces) != 2 { + t.Errorf("Duplicates = %+v, want one sender on two interfaces", d) + } + + e.SetInterfaces([]Interface{{Name: "eth0", Address: "10.0.0.2", Used: true}, {Name: "eth9", Address: "10.0.0.9", Used: true}}) + f.waitOpen(t, "224.5.23.2:10006") + + if d := e.Status(time.Now()).Duplicates; len(d) != 0 { + t.Errorf("Duplicates after a new selection = %+v, want none", d) + } +} diff --git a/gui/internal/multicast/host.go b/gui/internal/multicast/host.go index ae9e72c..1ae0d55 100644 --- a/gui/internal/multicast/host.go +++ b/gui/internal/multicast/host.go @@ -93,7 +93,7 @@ func describe(f ifaceFacts) Interface { switch { case f.flags&net.FlagLoopback != 0: - i.AutoReason = "loopback" + i.AutoReason = onLoopback case !up: i.AutoReason = "down" case f.flags&net.FlagRunning == 0: @@ -117,17 +117,28 @@ func isVirtual(name string) bool { }) } +// onLoopback is the AutoReason of a loopback interface. +const onLoopback = "loopback" + +// Networked reports whether ifaces uses any interface besides loopback. +func Networked(ifaces []Interface) bool { + return slices.ContainsFunc(ifaces, func(i Interface) bool { return i.Used && i.AutoReason != onLoopback }) +} + // Select marks which interfaces the host uses, automatically or by skipping -// the named ones, and returns the names of all the others: the skip list for +// the named ones. With nothing else to use, automatic selection falls back to +// loopback if it has multicast on, for a machine with no network. It returns +// the marked interfaces and the names of all the others: the skip list for // the sockets. func Select(ifaces []Interface, auto bool, skip []string) ([]Interface, []string) { out := slices.Clone(ifaces) + lonely := auto && !slices.ContainsFunc(out, func(i Interface) bool { return i.AutoUse }) var skipped []string for i := range out { if auto { - out[i].Used = out[i].AutoUse + out[i].Used = out[i].AutoUse || lonely && out[i].Usable && out[i].AutoReason == onLoopback } else { out[i].Used = out[i].Usable && !slices.Contains(skip, out[i].Name) } diff --git a/gui/internal/multicast/host_test.go b/gui/internal/multicast/host_test.go index 8b16fcf..8826c2a 100644 --- a/gui/internal/multicast/host_test.go +++ b/gui/internal/multicast/host_test.go @@ -65,3 +65,31 @@ func TestSelectAutoAndManual(t *testing.T) { t.Errorf("manual skipped %v, marked %+v, want only enp10s0 skipped", skipped, marked) } } + +// With no network, automatic selection uses loopback, but only then and only +// with multicast on. +func TestSelectAutoFallsBackToLoopback(t *testing.T) { + lo := net.FlagUp | net.FlagRunning | net.FlagLoopback + on := describe(facts("lo", lo|net.FlagMulticast, "127.0.0.1")) + off := describe(facts("lo", lo, "127.0.0.1")) + unplugged := describe(facts("eth0", physical&^net.FlagRunning, "10.0.0.2")) + plugged := describe(facts("eth0", physical, "10.0.0.2")) + docker := describe(facts("docker0", physical, "172.17.0.1")) + + for name, tc := range map[string]struct { + ifaces []Interface + auto bool + lo bool + networked bool + }{ + "no network": {[]Interface{on, unplugged, docker}, true, true, false}, + "no network, multicast off": {[]Interface{off, unplugged}, true, false, false}, + "network": {[]Interface{on, plugged}, true, false, true}, + "manual follows its choices": {[]Interface{on, plugged}, false, true, true}, + } { + got, _ := Select(tc.ifaces, tc.auto, nil) + if got[0].Used != tc.lo || Networked(got) != tc.networked { + t.Errorf("%s: lo used %v, networked %v; want %v, %v", name, got[0].Used, Networked(got), tc.lo, tc.networked) + } + } +} diff --git a/gui/internal/multicast/socket.go b/gui/internal/multicast/socket.go index 2b26503..0040ba6 100644 --- a/gui/internal/multicast/socket.go +++ b/gui/internal/multicast/socket.go @@ -30,7 +30,7 @@ var errNoInterface = errors.New("no usable network interface") // broadcast (or unicast to this host) on every interface. The returned // problem is "" if the socket is fully set up. Even with a problem, stop is // safe to call. -func openSocket(address string, ifaces []Interface, opts Options, receive func([]byte, *net.UDPAddr)) (stop func(), problem string) { +func openSocket(address string, ifaces []Interface, opts Options, receive receiver) (stop func(), problem string) { noop := func() {} addr, err := net.ResolveUDPAddr("udp4", address) @@ -69,6 +69,12 @@ func openSocket(address string, ifaces []Interface, opts Options, receive func([ } } + // For the interface each datagram arrives on. + pc4 := ipv4.NewPacketConn(conn) + if err := pc4.SetControlMessage(ipv4.FlagInterface, true); err != nil { + slog.Debug("can't tell which interface packets arrive on", "address", address, "err", err) + } + var done sync.WaitGroup done.Add(1) @@ -77,14 +83,16 @@ func openSocket(address string, ifaces []Interface, opts Options, receive func([ defer done.Done() buf := make([]byte, 65536) + names := map[int]string{} for { - n, from, err := conn.ReadFromUDP(buf) + n, cm, src, err := pc4.ReadFrom(buf) if err != nil { return // closed by stop } - receive(buf[:n], from) + from, _ := src.(*net.UDPAddr) + receive(buf[:n], from, interfaceName(names, cm)) } }() @@ -94,6 +102,25 @@ func openSocket(address string, ifaces []Interface, opts Options, receive func([ }, problem } +// interfaceName is the interface cm says its datagram arrived on, "" if it +// doesn't. names caches them by index, for as long as the socket is open. +func interfaceName(names map[int]string, cm *ipv4.ControlMessage) string { + if cm == nil || cm.IfIndex == 0 { + return "" + } + + name, ok := names[cm.IfIndex] + if !ok { + if ifi, err := net.InterfaceByIndex(cm.IfIndex); err == nil { + name = ifi.Name + } + + names[cm.IfIndex] = name + } + + return name +} + // join joins addr's group on every used interface. It fails only if it // joined none: some interfaces refusing (one without multicast, say) is fine // as long as another works. diff --git a/gui/internal/peers/peers_test.go b/gui/internal/peers/peers_test.go index 2d327c4..4b98010 100644 --- a/gui/internal/peers/peers_test.go +++ b/gui/internal/peers/peers_test.go @@ -172,3 +172,60 @@ func TestDescribe(t *testing.T) { t.Errorf("Describe of loopback = %q", got) } } + +// vision_processor's streamer reopens its socket whenever the streamed view +// changes size: one sender, on a new port each time. +func TestRestartsOnANewPortAreOneSender(t *testing.T) { + w := NewWatch(Options{Kind: KindVideo, Window: 3 * time.Second, MinCount: 10, Restarts: true}, testNames()) + now := time.Now() + send := func(from string, n int) { + for range n { + now = now.Add(2 * time.Millisecond) + w.Record("camera 0 video", nil, addr(from), now) + + if c := w.Conflicts(now); len(c) != 0 { + t.Fatalf("%s: %+v", from, c) + } + } + } + + send("10.0.0.1:40000", 300) + send("10.0.0.1:40001", 300) + send("10.0.0.1:40002", 300) + // A straggler from the closed socket. + w.Record("camera 0 video", nil, addr("10.0.0.1:40003"), now) + w.Record("camera 0 video", nil, addr("10.0.0.1:40002"), now.Add(time.Millisecond)) + send("10.0.0.1:40003", 300) +} + +// Two that keep sending are a conflict, on one machine or two, even if one +// also restarts; so is one that takes over from another machine. +func TestRestartsStillFindsTwoSenders(t *testing.T) { + for _, other := range []string{"10.0.0.1:40009", "10.0.0.2:40000"} { + w := NewWatch(Options{Kind: KindVideo, Window: 3 * time.Second, MinCount: 10, Restarts: true}, testNames()) + now := time.Now() + + for i := range 400 { + now = now.Add(2 * time.Millisecond) + w.Record("camera 0 video", nil, addr("10.0.0.1:40000"), now) + + if i > 100 { + w.Record("camera 0 video", nil, addr(other), now) + } + } + + if c := w.Conflicts(now); len(c) != 1 || len(c[0].Senders) != 2 { + t.Errorf("%s alongside: %+v, want 2 senders", other, c) + } + + for range 100 { + now = now.Add(2 * time.Millisecond) + w.Record("camera 0 video", nil, addr("10.0.0.1:40001"), now) + w.Record("camera 0 video", nil, addr(other), now) + } + + if c := w.Conflicts(now); len(c) != 1 { + t.Errorf("%s after the other restarted: %+v, want a conflict", other, c) + } + } +} diff --git a/gui/internal/peers/watch.go b/gui/internal/peers/watch.go index bb1690e..b9fc40a 100644 --- a/gui/internal/peers/watch.go +++ b/gui/internal/peers/watch.go @@ -30,6 +30,10 @@ type Options struct { // WithSelf marks something this host sends too, so a single other // sender is already a conflict. WithSelf bool + // Restarts is for a program that reopens its socket on a new port as it + // runs: a sender that stopped when another on its IP began is the same + // one, not a second. + Restarts bool } // Conflict is something claimed by more senders than it should be. @@ -61,9 +65,26 @@ type subject struct { type heard struct { from *net.UDPAddr times []time.Time // within Window, newest last + // first is when it began sending, after any silence longer than Window. + first time.Time last time.Time } +// overlap is how long after another began a sender must still be heard to +// count as sending alongside it, against packets arriving out of order. +const overlap = 100 * time.Millisecond + +// replaced reports whether h stopped as another of senders on its IP began. +func (h *heard) replaced(senders map[string]*heard) bool { + for _, other := range senders { + if other != h && other.from.IP.Equal(h.from.IP) && other.first.After(h.first) && h.last.Before(other.first.Add(overlap)) { + return true + } + } + + return false +} + // NewWatch returns a Watch naming senders through names. func NewWatch(opts Options, names *Names) *Watch { opts.MinCount = max(opts.MinCount, 1) @@ -99,7 +120,12 @@ func (w *Watch) Record(name string, cameraID *int, from *net.UDPAddr, now time.T sub.senders[key] = h } - h.times = append(w.trim(h.times, now), now) + h.times = w.trim(h.times, now) + if len(h.times) == 0 { + h.first = now + } + + h.times = append(h.times, now) h.last = now active, changed := w.update(sub, now) @@ -183,7 +209,7 @@ func (w *Watch) update(sub *subject, now time.Time) ([]*net.UDPAddr, bool) { for _, h := range sub.senders { h.times = w.trim(h.times, now) - if len(h.times) >= w.opts.MinCount { + if len(h.times) >= w.opts.MinCount && (!w.opts.Restarts || !h.replaced(sub.senders)) { active = append(active, h.from) } } diff --git a/gui/internal/video/assembler.go b/gui/internal/video/assembler.go index 07155c8..fc595f5 100644 --- a/gui/internal/video/assembler.go +++ b/gui/internal/video/assembler.go @@ -26,6 +26,9 @@ const ( // drops frames until a keyframe arrives rather than passing on a corrupt // picture. A new SSRC means the encoder restarted (vision_processor does this // whenever the streamed view changes size), which starts over the same way. +// +// A packet at or behind the newest one is ignored: it's a copy (the stream +// arriving on two interfaces), or too late for a frame already given up on. type assembler struct { started bool ssrc uint32 @@ -39,6 +42,10 @@ type assembler struct { needKey bool // dropping until a keyframe } +// behindWindow is how far behind the newest sequence number a packet still +// counts as a copy or late. Further back, the sender started over. +const behindWindow = 1024 + // push takes one packet and returns any frames it completed: the previous // frame when this packet starts a new one, and this one if it carries the // marker bit. Payload bytes are copied; pkt may reuse its buffer. @@ -47,6 +54,8 @@ func (a *assembler) push(pkt *rtp.Packet) [][][]byte { if !a.started || pkt.SSRC != a.ssrc { *a = assembler{started: true, ssrc: pkt.SSRC, timestamp: pkt.Timestamp, needKey: true} + } else if a.seq-pkt.SequenceNumber < behindWindow { + return nil } else { gap := pkt.SequenceNumber != a.seq+1 if gap { diff --git a/gui/internal/video/manager.go b/gui/internal/video/manager.go index 79d5050..cf328bf 100644 --- a/gui/internal/video/manager.go +++ b/gui/internal/video/manager.go @@ -2,8 +2,10 @@ package video import ( "errors" + "maps" "net" "sync" + "time" "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/multicast" ) @@ -60,6 +62,24 @@ func (m *Manager) Configure(streams map[int]Stream, ifaces []multicast.Interface } } +// Duplicates lists, by camera, the senders heard on several interfaces at +// once on each open stream. +func (m *Manager) Duplicates(now time.Time) map[int][]multicast.Duplicate { + m.mu.Lock() + sources := maps.Clone(m.sources) + m.mu.Unlock() + + out := map[int][]multicast.Duplicate{} + + for id, src := range sources { + if d := src.duplicates(now); len(d) > 0 { + out[id] = d + } + } + + return out +} + // Reopen reopens every open stream's socket, after a suspend. func (m *Manager) Reopen() { m.mu.Lock() diff --git a/gui/internal/video/source.go b/gui/internal/video/source.go index 90a4a2a..d354520 100644 --- a/gui/internal/video/source.go +++ b/gui/internal/video/source.go @@ -118,6 +118,17 @@ func (s *source) configure(active bool, address string, ifaces []multicast.Inter } } +func (s *source) duplicates(now time.Time) []multicast.Duplicate { + s.mu.Lock() + defer s.mu.Unlock() + + if s.endpoint == nil { + return nil + } + + return s.endpoint.Status(now).Duplicates +} + // reopen reopens a running socket, after a suspend. func (s *source) reopen() { s.mu.Lock() diff --git a/gui/internal/video/video_test.go b/gui/internal/video/video_test.go index d740d04..724b00d 100644 --- a/gui/internal/video/video_test.go +++ b/gui/internal/video/video_test.go @@ -225,6 +225,58 @@ func TestAssemblerDropsUntilKeyframeAfterLoss(t *testing.T) { } } +// A stream arriving on two interfaces: every packet twice, the copy right +// behind the original or a few packets later, across a sequence wrap. +func TestAssemblerIgnoresCopies(t *testing.T) { + clip := loadClip(t, "320x240.h264") + + for _, lag := range []int{0, 1, 7, 40} { + p := &packetizer{ssrc: 1, seq: 65530} + + var pkts []*rtp.Packet + for _, au := range clip { + pkts = append(pkts, p.packets(au)...) + } + + var a assembler + + got := 0 + + for i, pkt := range pkts { + got += len(a.push(pkt)) + + if i >= lag { + got += len(a.push(pkts[i-lag])) + } + } + + if got != len(clip) { + t.Errorf("copies %d packets behind: %d frames, want %d", lag, got, len(clip)) + } + } +} + +// A sender that starts over far back with the same SSRC is still followed. +func TestAssemblerFollowsAJumpBack(t *testing.T) { + clip := loadClip(t, "320x240.h264") + + var a assembler + + p := &packetizer{ssrc: 1, seq: 30000} + for _, au := range clip[:5] { + assemble(&a, p.packets(au)) + } + + p = &packetizer{ssrc: 1, seq: 100, timestamp: 900000} + if got := assemble(&a, p.packets(clip[0])); len(got) != 0 { + t.Errorf("%d frames from the first frame after a gap, want none", len(got)) + } + + if got := assemble(&a, p.packets(clip[0])); len(got) != 1 { + t.Errorf("%d frames from the next keyframe, want 1", len(got)) + } +} + func TestAssemblerRestartsOnNewSSRC(t *testing.T) { small := loadClip(t, "160x120.h264") big := loadClip(t, "320x240.h264") From 03307fa51cc0b9e72b784938c313983b73aaf584 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 11:56:56 -0500 Subject: [PATCH 11/35] fix release check for configs with uninit camera configs --- gui/scripts/release-check.sh | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/gui/scripts/release-check.sh b/gui/scripts/release-check.sh index 059e9f9..1195eb5 100755 --- a/gui/scripts/release-check.sh +++ b/gui/scripts/release-check.sh @@ -65,7 +65,7 @@ got=$(run "$work/version" -version) [ "$got" = "ssl-vision-processor-gui $version" ] || fail "-version printed: $got" [ -z "$(ls -A "$work/version")" ] || fail "-version created files" -(run "$work/readme" -readme) | grep -q '^# vision_processor GUI' || fail "-readme didn't print the user guide" +(run "$work/readme" -readme) | grep -q '^# SSL Vision Processor GUI' || fail "-readme didn't print the user guide" [ -z "$(ls -A "$work/readme")" ] || fail "-readme created files" port=$((20000 + RANDOM % 20000)) @@ -139,6 +139,16 @@ grep -qF "bot_heights_file: $config/robot-heights.yml" "$config/cam0.yml" || fail "cam0.yml doesn't name the height table by its full path" grep -qF "$fakebin/vision_processor" "$work/local.log" || fail "startup didn't print which vision_processor it runs" +# A new config has no camera selected: nothing runs until a driver is chosen. +curl -sf "http://127.0.0.1:$port/api/processes" | grep -q '"state":"no_camera"' || + fail "a new config's camera isn't waiting for a driver" +[ ! -e "$state/run/cam0/args" ] || fail "vision_processor ran with no camera selected" + +etag=$(curl -sfI -X GET "http://127.0.0.1:$port/api/config" | tr -d '\r' | sed -n 's/^[Ee][Tt]ag: //p') +curl -sf -o /dev/null -X PATCH -H "If-Match: $etag" -H 'Content-Type: application/merge-patch+json' \ + -d '{"defaults":{"camera":{"driver":"OPENCV"}}}' "http://127.0.0.1:$port/api/config" || + fail "choosing a driver was refused" + for _ in $(seq 1 100); do [ -e "$state/run/cam0/args" ] && [ -e "$state/img/cam0/0.raw.jpg" ] && break sleep 0.1 From 6da403223e03d1355745f57c35d21adc45a76d7f Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 11:58:34 -0500 Subject: [PATCH 12/35] normalize API names before finalizing version --- gui/cmd/ssl-vision-processor-gui/docs.go | 11 ++-- gui/cmd/ssl-vision-processor-gui/livefield.go | 4 +- gui/cmd/ssl-vision-processor-gui/logs.go | 4 +- gui/cmd/ssl-vision-processor-gui/main.go | 6 +- .../ssl-vision-processor-gui/openapi_test.go | 50 ++++++++++++++++ .../responses_test.go | 6 +- gui/cmd/ssl-vision-processor-gui/routes.go | 45 +++++++------- gui/cmd/ssl-vision-processor-gui/server.go | 60 +++++++++---------- gui/cmd/ssl-vision-processor-gui/system.go | 4 +- gui/frontend/src/lib/apiTypes.ts | 2 +- gui/internal/api/api.go | 16 +++-- gui/internal/snapshot/snapshot.go | 4 +- gui/internal/snapshot/snapshot_test.go | 14 ++--- 13 files changed, 144 insertions(+), 82 deletions(-) diff --git a/gui/cmd/ssl-vision-processor-gui/docs.go b/gui/cmd/ssl-vision-processor-gui/docs.go index 4a5cac2..f6c17f7 100644 --- a/gui/cmd/ssl-vision-processor-gui/docs.go +++ b/gui/cmd/ssl-vision-processor-gui/docs.go @@ -15,9 +15,10 @@ import ( "github.com/swaggest/jsonschema-go" ) -// specVersion is the API's version in the spec. Fields and endpoints may be -// added freely; changing or removing one means /api/v2. -const specVersion = "1.0.0" +// specVersion is the API's version in the spec. Below 1.0 names may still +// change; from 1.0, fields and endpoints may be added freely, and changing or +// removing one means /api/v2. +const specVersion = "0.1.0" const specIntro = `The GUI host's control API: the shared vision.yml document, its state, and what the host's sockets hear. Every error is JSON, ` + "`{\"error\": code, \"message\": text, \"issues\": [...]}`" + `; clients branch on @@ -36,7 +37,7 @@ is the body of a REST endpoint documented here: | ` + "`network.state`" + ` | GET /api/network | | ` + "`alerts.state`" + ` | GET /api/alerts | | ` + "`processes.state`" + ` | GET /api/processes | -| ` + "`wrapper_packet.out`" + ` | GET /api/geometry | +| ` + "`geometry.state`" + ` | GET /api/geometry | ` // openapiSpec is the host's OpenAPI spec as JSON. It depends only on the @@ -52,7 +53,7 @@ func openapiSpec() ([]byte, error) { // newAPI is the host's typed route registry and spec. func newAPI(mux *http.ServeMux) *api.API { - a := api.New(mux, api.Info{Title: "vision_processor GUI host", Version: specVersion, Description: specIntro, Tags: specTags}, + a := api.New(mux, api.Info{Title: "SSL Vision Processor GUI", Version: specVersion, Description: specIntro, Tags: specTags}, func(w http.ResponseWriter, err error) { respondConfigErr(w, err, "handling request") }) a.SchemaFor(reflect.TypeFor[config.Settings](), settingsSchema()) diff --git a/gui/cmd/ssl-vision-processor-gui/livefield.go b/gui/cmd/ssl-vision-processor-gui/livefield.go index cf43602..8432e7b 100644 --- a/gui/cmd/ssl-vision-processor-gui/livefield.go +++ b/gui/cmd/ssl-vision-processor-gui/livefield.go @@ -13,7 +13,7 @@ import ( // liveFieldTopic carries livefield.Snapshot: every camera's latest detection // frame and every autoref's latest tracked frame. -const liveFieldTopic = "live_field.frames" +const liveFieldTopic = "live-field.state" // Detections arrive at 60 to 75 Hz per camera; publishing faster than a // browser draws gains nothing. @@ -63,7 +63,7 @@ func publishLiveField(ctx context.Context, wsHub *hub.Hub, live *livefield.Feed) } // getLiveField serves every camera's latest detection frame and every -// autoref's latest tracked frame, as the live_field.frames topic carries +// autoref's latest tracked frame, as the live-field.state topic carries // them. // // Sources silent for a second are listed without a frame, and dropped after diff --git a/gui/cmd/ssl-vision-processor-gui/logs.go b/gui/cmd/ssl-vision-processor-gui/logs.go index 55a2260..22a7625 100644 --- a/gui/cmd/ssl-vision-processor-gui/logs.go +++ b/gui/cmd/ssl-vision-processor-gui/logs.go @@ -41,11 +41,11 @@ type logsResponse struct { Missed bool `json:"missed"` } -// logs serves the host's recent log records, its supervised vision_processors' +// getLogs serves the host's recent log records, its supervised vision_processors' // output included, whatever level its console logs at. Poll with after set to // the last response's next to follow the log; add wait to be answered as soon // as a record is logged. -func (s *VisionServer) logs(r *http.Request, in logsRequest) (logsResponse, error) { +func (s *VisionServer) getLogs(r *http.Request, in logsRequest) (logsResponse, error) { level := slog.LevelDebug if in.Level != "" { diff --git a/gui/cmd/ssl-vision-processor-gui/main.go b/gui/cmd/ssl-vision-processor-gui/main.go index f6b38f6..d8682eb 100644 --- a/gui/cmd/ssl-vision-processor-gui/main.go +++ b/gui/cmd/ssl-vision-processor-gui/main.go @@ -39,7 +39,7 @@ import ( "google.golang.org/protobuf/encoding/protojson" ) -var address = flag.String("address", ":8080", "The address on which the vision processor GUI and API are served, default: :8080") +var address = flag.String("address", ":8080", "The address on which the SSL Vision Processor GUI and API are served, default: :8080") // The vision and game controller addresses (vision.yml's defaults.network) // and the interfaces the host uses (host.interfaces) can change at runtime, so @@ -121,7 +121,7 @@ func run() int { } build := buildinfo.Get() - slog.Info("Init VP GUI", "version", build.Version, "commit", build.Repo.Commit, "dirty", build.Repo.Dirty, "proto", build.Proto.Commit) + slog.Info("starting SSL Vision Processor GUI", "version", build.Version, "commit", build.Repo.Commit, "dirty", build.Repo.Dirty, "proto", build.Proto.Commit) logPaths(p) var vpCommand []string @@ -858,7 +858,7 @@ func withSend(opts multicast.Options) multicast.Options { // wrapperPacketTopic is the hub topic name the frontend already subscribes to // (see gui/frontend/src/App.svelte). -const wrapperPacketTopic = "wrapper_packet.out" +const wrapperPacketTopic = "geometry.state" // sendGeometry publishes the geometry on the vision group, unless this is a // first run: a host somebody is only trying out has no business telling a real diff --git a/gui/cmd/ssl-vision-processor-gui/openapi_test.go b/gui/cmd/ssl-vision-processor-gui/openapi_test.go index c52f952..ba0c730 100644 --- a/gui/cmd/ssl-vision-processor-gui/openapi_test.go +++ b/gui/cmd/ssl-vision-processor-gui/openapi_test.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "net/http" + "regexp" "testing" ) @@ -84,3 +85,52 @@ func TestEveryTagIsDescribed(t *testing.T) { } } } + +// The API's naming rules, so a new route or topic keeps to them: kebab-case +// paths, {id} for a camera, verbNoun operationIds, .state topics. +func TestNamesFollowTheRules(t *testing.T) { + data, err := openapiSpec() + if err != nil { + t.Fatal(err) + } + + var spec struct { + Paths map[string]map[string]struct { + OperationID string + } + } + if err := json.Unmarshal(data, &spec); err != nil { + t.Fatal(err) + } + + path := regexp.MustCompile(`^(/([a-z]+(-[a-z]+)*|\{[a-z]+\}))+$`) + id := regexp.MustCompile(`^(get|list|put|patch|lock|unlock|load|reload|save|restart|open)[A-Z][A-Za-z]*$`) + topic := regexp.MustCompile(`^[a-z]+(-[a-z]+)*\.state$`) + seen := map[string]string{} + + for p, ops := range spec.Paths { + if !path.MatchString(p) { + t.Errorf("path %s isn't kebab-case", p) + } + + for method, op := range ops { + at := method + " " + p + if !id.MatchString(op.OperationID) { + t.Errorf("%s: operationId %q isn't verbNoun", at, op.OperationID) + } + + if other, ok := seen[op.OperationID]; ok { + t.Errorf("%s and %s share operationId %q", at, other, op.OperationID) + } + + seen[op.OperationID] = at + } + } + + h, _ := testHost(t) + for _, name := range h.hub.Topics() { + if !topic.MatchString(name) { + t.Errorf("topic %s isn't .state", name) + } + } +} diff --git a/gui/cmd/ssl-vision-processor-gui/responses_test.go b/gui/cmd/ssl-vision-processor-gui/responses_test.go index bb35b30..6111424 100644 --- a/gui/cmd/ssl-vision-processor-gui/responses_test.go +++ b/gui/cmd/ssl-vision-processor-gui/responses_test.go @@ -24,8 +24,8 @@ var checkedGETs = map[string]string{ "/api/config/cameras/{id}/effective": "/api/config/cameras/0/effective", "/api/geometry": "/api/geometry", "/api/geometry/presets": "/api/geometry/presets", - "/api/live_field": "/api/live_field", - "/api/camera/devices": "/api/camera/devices", + "/api/live-field": "/api/live-field", + "/api/capture-devices": "/api/capture-devices", "/api/snapshots": "/api/snapshots", "/api/processes": "/api/processes", "/api/instances": "/api/instances", @@ -34,7 +34,7 @@ var checkedGETs = map[string]string{ } // notJSON are the GET routes whose 200 isn't a JSON body. -var notJSON = []string{"/api/snapshot/{camID}/{view}", "/ws", "/ws/video/{id}"} +var notJSON = []string{"/api/snapshots/{id}/{view}", "/ws", "/ws/video/{id}"} // A new GET route has to be added to checkedGETs (or notJSON), so its // responses get checked against the spec too. diff --git a/gui/cmd/ssl-vision-processor-gui/routes.go b/gui/cmd/ssl-vision-processor-gui/routes.go index 34a9859..c28f6f1 100644 --- a/gui/cmd/ssl-vision-processor-gui/routes.go +++ b/gui/cmd/ssl-vision-processor-gui/routes.go @@ -34,12 +34,12 @@ var bodyErrors = []string{httpjson.CodeBadRequest, httpjson.CodeUnsupportedMedia // addRoutes registers every route. Each is in the OpenAPI spec at // /api/openapi.json, documented from its handler's types and doc comment. func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { - api.Route(a, "GET /api/health", api.Doc{Tags: tagStatus}, s.health) - api.Route(a, "GET /api/alerts", api.Doc{Tags: tagStatus}, s.getAlerts) - api.Route(a, "GET /api/network", api.Doc{Tags: tagStatus}, s.network) - api.Route(a, "GET /api/instances", api.Doc{Tags: tagStatus}, s.instances) - api.Route(a, "GET /api/system", api.Doc{Tags: tagStatus}, s.system) - api.Route(a, "GET /api/logs", api.Doc{Tags: tagStatus, Errors: []string{httpjson.CodeBadRequest}}, s.logs) + api.Route(a, "GET /api/health", api.Doc{Tags: tagStatus}, s.getHealth) + api.Route(a, "GET /api/alerts", api.Doc{Tags: tagStatus}, s.listAlerts) + api.Route(a, "GET /api/network", api.Doc{Tags: tagStatus}, s.getNetwork) + api.Route(a, "GET /api/instances", api.Doc{Tags: tagStatus}, s.listInstances) + api.Route(a, "GET /api/system", api.Doc{Tags: tagStatus}, s.getSystem) + api.Route(a, "GET /api/logs", api.Doc{Tags: tagStatus, Errors: []string{httpjson.CodeBadRequest}}, s.getLogs) api.Route(a, "GET /api/schema", api.Doc{Tags: tagConfig}, s.getSchema) api.Route(a, "GET /api/config", api.Doc{Tags: tagConfig}, s.getConfig) @@ -54,7 +54,7 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { api.Route(a, "GET /api/config/cameras/{id}/effective", api.Doc{ Tags: tagConfig, Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound}, - }, s.effectiveConfig) + }, s.getEffectiveConfig) api.Route(a, "POST /api/config/cameras/{id}/calibration", api.Doc{ Tags: tagConfig, Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound, httpjson.CodeNoLiveCalibration}, @@ -63,50 +63,53 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { Tags: tagConfig, Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound}, }, s.unlockCalibration) - api.Route(a, "GET /api/config/files", api.Doc{Tags: tagConfig}, s.configFiles) + api.Route(a, "GET /api/config/files", api.Doc{Tags: tagConfig}, s.listConfigFiles) api.Route(a, "POST /api/config/save", api.Doc{ Tags: tagConfig, Errors: append([]string{httpjson.CodeInvalid, httpjson.CodeStale, httpjson.CodeDiskChanged}, bodyErrors...), - }, s.save) + }, s.saveConfig) api.Route(a, "POST /api/config/save-as", api.Doc{ Tags: tagConfig, Errors: append([]string{httpjson.CodeInvalid, httpjson.CodeStale}, bodyErrors...), - }, s.saveAs) + }, s.saveConfigAs) api.Route(a, "POST /api/config/load", api.Doc{ Tags: tagConfig, Errors: append([]string{httpjson.CodeInvalid}, bodyErrors...), - }, s.load) + }, s.loadConfig) api.Route(a, "POST /api/config/reload", api.Doc{ Tags: tagConfig, Errors: []string{httpjson.CodeInvalid}, - }, s.reload) + }, s.reloadConfig) api.Route(a, "GET /api/geometry", api.Doc{Tags: tagField}, s.getGeometry) - api.Route(a, "GET /api/geometry/presets", api.Doc{Tags: tagField}, s.fieldPresets) - api.Route(a, "GET /api/live_field", api.Doc{Tags: tagUpdates}, s.getLiveField) + api.Route(a, "GET /api/geometry/presets", api.Doc{Tags: tagField}, s.listFieldPresets) + api.Route(a, "GET /api/live-field", api.Doc{Tags: tagUpdates}, s.getLiveField) - api.Route(a, "GET /api/camera/devices", api.Doc{Tags: tagHost}, s.cameraDevices) - api.Route(a, "GET /api/processes", api.Doc{Tags: tagHost}, s.processes) + api.Route(a, "GET /api/capture-devices", api.Doc{Tags: tagHost}, s.listCaptureDevices) + api.Route(a, "GET /api/processes", api.Doc{Tags: tagHost}, s.listProcesses) api.Route(a, "POST /api/processes/{id}/restart", api.Doc{ Tags: tagHost, Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound, httpjson.CodeDeviceConflict, httpjson.CodeNoCamera}, }, s.restartProcess) - api.Route(a, "GET /api/snapshots", api.Doc{Tags: tagHost}, s.snapshots) - api.Raw[snapshotRequest](a, "GET /api/snapshot/{camID}/{view}", api.Doc{ + api.Route(a, "GET /api/snapshots", api.Doc{Tags: tagHost}, s.listSnapshots) + api.Raw[snapshotRequest](a, "GET /api/snapshots/{id}/{view}", api.Doc{ Tags: tagHost, + ID: "getSnapshot", Summary: "Serves a camera's latest debug image for one view", Description: "The most recently written of the views GET /api/snapshots lists, as vision_processor wrote it.", Errors: []string{httpjson.CodeNotFound}, }, snapshot.HandleGet(s.imgDir), api.RawResponse{Status: http.StatusOK, ContentType: "image/*", Description: "The image, PNG or JPEG."}) - api.Route(a, "GET /api/topics", api.Doc{Tags: tagUpdates}, s.topics) + api.Route(a, "GET /api/topics", api.Doc{Tags: tagUpdates}, s.listTopics) api.Raw[none](a, "GET /ws", api.Doc{ Tags: tagUpdates, + ID: "openUpdates", Summary: "Opens the live-updates WebSocket", Description: "Subscribe to topics as described in Live updates above.", }, hub.HandleWebSocket(s.hub, s.origins.Allowed), api.RawResponse{Status: http.StatusSwitchingProtocols, Description: "Upgraded to a WebSocket."}) api.Raw[videoRequest](a, "GET /ws/video/{id}", api.Doc{ Tags: tagUpdates, + ID: "openVideo", Summary: "Opens a camera's live video WebSocket", Description: "JSON status (once a second) and format (codec and size) messages, and binary fragmented MP4 " + "segments ready for a MediaSource SourceBuffer in sequence mode. A new viewer starts at the last keyframe.", @@ -119,8 +122,8 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { // snapshotRequest names a debug image. type snapshotRequest struct { - // CamID is the camera's camera_id. - CamID int `path:"camID"` + // ID is the camera's camera_id. + ID int `path:"id"` // View is the image's view, as GET /api/snapshots lists it, e.g. raw or // geomcalib_input. View string `path:"view"` diff --git a/gui/cmd/ssl-vision-processor-gui/server.go b/gui/cmd/ssl-vision-processor-gui/server.go index 2ac4915..532886e 100644 --- a/gui/cmd/ssl-vision-processor-gui/server.go +++ b/gui/cmd/ssl-vision-processor-gui/server.go @@ -65,32 +65,32 @@ type healthResponse struct { Version string `json:"version"` } -// health reports that the host is up and serving. -func (s *VisionServer) health(*http.Request, none) (healthResponse, error) { +// getHealth reports that the host is up and serving. +func (s *VisionServer) getHealth(*http.Request, none) (healthResponse, error) { return healthResponse{Status: "ok", Version: buildinfo.Version()}, nil } -// topics lists the WebSocket topics /ws accepts. -func (s *VisionServer) topics(*http.Request, none) ([]string, error) { +// listTopics lists the WebSocket topics /ws accepts. +func (s *VisionServer) listTopics(*http.Request, none) ([]string, error) { return s.hub.Topics(), nil } -// network reports each multicast socket's address and what it hears: +// getNetwork reports each multicast socket's address and what it hears: // network.state on demand. -func (s *VisionServer) network(*http.Request, none) (NetworkState, error) { +func (s *VisionServer) getNetwork(*http.Request, none) (NetworkState, error) { return s.status.Network(), nil } -// getAlerts lists every problem the host sees right now, most serious first: +// listAlerts lists every problem the host sees right now, most serious first: // alerts.state on demand. -func (s *VisionServer) getAlerts(*http.Request, none) ([]alerts.Alert, error) { +func (s *VisionServer) listAlerts(*http.Request, none) ([]alerts.Alert, error) { return s.status.Alerts(), nil } -// instances lists every vision_processor heard announcing itself on the vision +// listInstances lists every vision_processor heard announcing itself on the vision // group in the last 30 seconds, with the configuration it last announced, by // camera_id then instance name. One unheard for 3 seconds is no longer live. -func (s *VisionServer) instances(*http.Request, none) ([]discovery.Instance, error) { +func (s *VisionServer) listInstances(*http.Request, none) ([]discovery.Instance, error) { return s.status.Instances(), nil } @@ -201,8 +201,8 @@ func (s *VisionServer) patchConfig(_ *http.Request, in patchConfigRequest) (revi return revisionOf(next), err } -// configFiles lists the YAML files in the config folder, for load and save-as. -func (s *VisionServer) configFiles(*http.Request, none) ([]config.File, error) { +// listConfigFiles lists the YAML files in the config folder, for load and save-as. +func (s *VisionServer) listConfigFiles(*http.Request, none) ([]config.File, error) { return s.store.Files() } @@ -215,10 +215,10 @@ type saveRequest struct { Force bool `json:"force"` } -// save writes the working document to vision.yml. A 409 disk_changed means +// saveConfig writes the working document to vision.yml. A 409 disk_changed means // the file was edited elsewhere since it was loaded (config.state's external // describes how); force overwrites it anyway. -func (s *VisionServer) save(_ *http.Request, req saveRequest) (revisionResponse, error) { +func (s *VisionServer) saveConfig(_ *http.Request, req saveRequest) (revisionResponse, error) { if err := s.store.Save(req.Revision, req.Force); err != nil { return revisionResponse{}, err } @@ -234,9 +234,9 @@ type saveAsRequest struct { Name string `json:"name"` } -// saveAs writes the working document to another file in the config folder. The +// saveConfigAs writes the working document to another file in the config folder. The // host loads from, saves to, and watches that file from then on. -func (s *VisionServer) saveAs(_ *http.Request, req saveAsRequest) (revisionResponse, error) { +func (s *VisionServer) saveConfigAs(_ *http.Request, req saveAsRequest) (revisionResponse, error) { if req.Name == "" { return revisionResponse{}, &httpjson.Problem{Code: httpjson.CodeInvalid, Message: "name: required", Issues: []string{"name: required"}} } @@ -254,9 +254,9 @@ type loadRequest struct { Name string `json:"name"` } -// load switches to editing another vision.yml in the config folder. It replaces the working +// loadConfig switches to editing another vision.yml in the config folder. It replaces the working // document, unsaved changes included, and applies it live. -func (s *VisionServer) load(_ *http.Request, req loadRequest) (revisionResponse, error) { +func (s *VisionServer) loadConfig(_ *http.Request, req loadRequest) (revisionResponse, error) { if req.Name == "" { return revisionResponse{}, &httpjson.Problem{Code: httpjson.CodeInvalid, Message: "name: required", Issues: []string{"name: required"}} } @@ -268,10 +268,10 @@ func (s *VisionServer) load(_ *http.Request, req loadRequest) (revisionResponse, return revisionOf(s.store.Revision()), nil } -// reload accepts vision.yml as it is on disk. It discards unsaved changes: +// reloadConfig accepts vision.yml as it is on disk. It discards unsaved changes: // the "load from disk" answer to the external-change prompt, and "revert to // disk". -func (s *VisionServer) reload(*http.Request, none) (revisionResponse, error) { +func (s *VisionServer) reloadConfig(*http.Request, none) (revisionResponse, error) { if err := s.store.Reload(); err != nil { return revisionResponse{}, err } @@ -285,10 +285,10 @@ type cameraRequest struct { ID int `path:"id"` } -// effectiveConfig lists every setting of one camera as its vision_processor +// getEffectiveConfig lists every setting of one camera as its vision_processor // runs it. Each value says where it comes from: the camera, the shared // defaults, the host, or vision_processor's fallback. -func (s *VisionServer) effectiveConfig(_ *http.Request, in cameraRequest) (config.EffectiveConfig, error) { +func (s *VisionServer) getEffectiveConfig(_ *http.Request, in cameraRequest) (config.EffectiveConfig, error) { doc, _ := s.store.Working() return doc.EffectiveConfig(in.ID) @@ -313,10 +313,10 @@ func (s *VisionServer) unlockCalibration(_ *http.Request, in cameraRequest) (rev return revisionOf(rev), err } -// cameraDevices lists this host's capture devices: candidates for a camera's +// listCaptureDevices lists this host's capture devices: candidates for a camera's // camera.path, stable by-id and by-path links first. Empty on a machine // without Video4Linux. -func (s *VisionServer) cameraDevices(*http.Request, none) ([]v4l.Device, error) { +func (s *VisionServer) listCaptureDevices(*http.Request, none) ([]v4l.Device, error) { devices := v4l.List(v4l.System) if devices == nil { devices = []v4l.Device{} @@ -325,14 +325,14 @@ func (s *VisionServer) cameraDevices(*http.Request, none) ([]v4l.Device, error) return devices, nil } -// snapshots lists the debug images on this host, by camera and view. -func (s *VisionServer) snapshots(*http.Request, none) ([]snapshot.Entry, error) { +// listSnapshots lists the debug images on this host, by camera and view. +func (s *VisionServer) listSnapshots(*http.Request, none) ([]snapshot.Entry, error) { return snapshot.List(s.imgDir) } -// processes lists the vision_processors the host runs itself (-runCameras), by +// listProcesses lists the vision_processors the host runs itself (-runCameras), by // camera_id: processes.state on demand. Empty when it runs none. -func (s *VisionServer) processes(*http.Request, none) ([]supervisor.Status, error) { +func (s *VisionServer) listProcesses(*http.Request, none) ([]supervisor.Status, error) { return s.procs.Statuses(), nil } @@ -392,8 +392,8 @@ type fieldPresetResponse struct { OptionalFieldLines geometry.OptionalLinesConfig `json:"optionalFieldLines"` } -// fieldPresets lists the rulebook field dimensions, Division A and B. -func (s *VisionServer) fieldPresets(*http.Request, none) ([]fieldPresetResponse, error) { +// listFieldPresets lists the rulebook field dimensions, Division A and B. +func (s *VisionServer) listFieldPresets(*http.Request, none) ([]fieldPresetResponse, error) { embedded, err := defaults.Presets() if err != nil { return nil, err diff --git a/gui/cmd/ssl-vision-processor-gui/system.go b/gui/cmd/ssl-vision-processor-gui/system.go index 184bf01..6135f85 100644 --- a/gui/cmd/ssl-vision-processor-gui/system.go +++ b/gui/cmd/ssl-vision-processor-gui/system.go @@ -72,10 +72,10 @@ type netInterface struct { Addresses []string `json:"addresses"` } -// system describes this host and the build it runs, for a bug report: the +// getSystem describes this host and the build it runs, for a bug report: the // build's git state, the OS, the process, every network interface, and its // latest warnings and errors. -func (s *VisionServer) system(*http.Request, none) (systemResponse, error) { +func (s *VisionServer) getSystem(*http.Request, none) (systemResponse, error) { hostname, _ := os.Hostname() return systemResponse{ diff --git a/gui/frontend/src/lib/apiTypes.ts b/gui/frontend/src/lib/apiTypes.ts index 53a2702..e6a1ea5 100644 --- a/gui/frontend/src/lib/apiTypes.ts +++ b/gui/frontend/src/lib/apiTypes.ts @@ -60,7 +60,7 @@ export type VideoDevice = Schemas["V4LDevice"]; export type SnapshotEntry = Schemas["SnapshotEntry"]; export type ProcessStatus = Schemas["SupervisorStatus"]; -export type ApiError = Schemas["HttpjsonErrorBody"]; +export type ApiError = Schemas["ErrorBody"]; export type ErrorCode = ApiError["error"]; export type LiveFieldSnapshot = Schemas["LivefieldSnapshot"]; diff --git a/gui/internal/api/api.go b/gui/internal/api/api.go index 42e4904..96b5f0e 100644 --- a/gui/internal/api/api.go +++ b/gui/internal/api/api.go @@ -74,6 +74,11 @@ func New(mux *http.ServeMux, info Info, onError func(http.ResponseWriter, error) return strings.ToUpper(t.Name()[:1]) + t.Name()[1:] } + // Every client sees this one, so it's named for what it is. + if t == reflect.TypeFor[httpjson.ErrorBody]() { + return "ErrorBody" + } + return name }), ) @@ -84,13 +89,13 @@ func New(mux *http.ServeMux, info Info, onError func(http.ResponseWriter, error) // Doc is a route's documentation. The summary is its first sentence; the // rest of Description follows it. type Doc struct { + // ID is the operationId: the handler's name unless set. + ID string Summary string Description string Tags []string // Errors are the httpjson codes the route can return, besides internal. Errors []string - - id string } // withHandlerComment fills an empty Summary and Description from h's Go doc @@ -98,7 +103,9 @@ type Doc struct { // summary, the rest the description. func (d Doc) withHandlerComment(h any) Doc { name := canonical(strings.TrimSuffix(runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name(), "-fm")) - d.id = name[strings.LastIndex(name, ".")+1:] + if d.ID == "" { + d.ID = name[strings.LastIndex(name, ".")+1:] + } summary, rest, _ := strings.Cut(comments[name], ". ") @@ -257,6 +264,7 @@ func (a *API) documentRaw(method, path string, doc Doc, in input, responses []Ra } oc.SetSummary(doc.Summary) + oc.SetID(doc.ID) oc.SetDescription(doc.Description) oc.SetTags(doc.Tags...) @@ -311,7 +319,7 @@ func (a *API) document(method, path string, doc Doc, in input, out reflect.Type) oc.SetSummary(doc.Summary) oc.SetDescription(doc.Description) - oc.SetID(doc.id) + oc.SetID(doc.ID) oc.SetTags(doc.Tags...) if in.params != nil { diff --git a/gui/internal/snapshot/snapshot.go b/gui/internal/snapshot/snapshot.go index ad2a6e8..7b132eb 100644 --- a/gui/internal/snapshot/snapshot.go +++ b/gui/internal/snapshot/snapshot.go @@ -111,10 +111,10 @@ func addEntry(seen map[Entry]struct{}, name string) { var validSegment = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`) // HandleGet serves a camera's latest debug image for one view, e.g. -// /api/snapshot/0/raw. +// /api/snapshots/0/raw. func HandleGet(dir string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - camID := r.PathValue("camID") + camID := r.PathValue("id") view := r.PathValue("view") if !validSegment.MatchString(camID) || !validSegment.MatchString(view) { diff --git a/gui/internal/snapshot/snapshot_test.go b/gui/internal/snapshot/snapshot_test.go index 356b599..90b18d3 100644 --- a/gui/internal/snapshot/snapshot_test.go +++ b/gui/internal/snapshot/snapshot_test.go @@ -112,7 +112,7 @@ func TestListReadsEachCameraFolder(t *testing.T) { func snapshotMux(dir string) http.Handler { mux := http.NewServeMux() - mux.Handle("GET /api/snapshot/{camID}/{view}", HandleGet(dir)) + mux.Handle("GET /api/snapshots/{id}/{view}", HandleGet(dir)) return mux } @@ -122,7 +122,7 @@ func TestHandleGetServesTheFile(t *testing.T) { writeFile(t, dir, "0.raw.jpg") rec := httptest.NewRecorder() - snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshot/0/raw", nil)) + snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshots/0/raw", nil)) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) @@ -145,7 +145,7 @@ func TestHandleGetServesTheMostRecentlyModifiedMatch(t *testing.T) { writeFile(t, dir, "0.raw.png") // written just now, newer rec := httptest.NewRecorder() - snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshot/0/raw", nil)) + snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshots/0/raw", nil)) if rec.Body.String() != "0.raw.png" { t.Errorf("body = %q, want the newer file", rec.Body.String()) @@ -157,7 +157,7 @@ func TestHandleGetServesADottedViewName(t *testing.T) { writeFile(t, dir, "0.pixels.corner.png") rec := httptest.NewRecorder() - snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshot/0/pixels.corner", nil)) + snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshots/0/pixels.corner", nil)) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) @@ -172,7 +172,7 @@ func TestHandleGetReturns404ForNoMatch(t *testing.T) { dir := t.TempDir() rec := httptest.NewRecorder() - snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshot/9/raw", nil)) + snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshots/9/raw", nil)) if rec.Code != http.StatusNotFound { t.Errorf("status = %d, want %d", rec.Code, http.StatusNotFound) @@ -186,7 +186,7 @@ func TestHandleGetRejectsUnsafeSegments(t *testing.T) { writeFile(t, dir, "0.raw.jpg") for _, view := range []string{"*", "..", "raw/../../etc"} { - req := httptest.NewRequest(http.MethodGet, "/api/snapshot/0/"+view, nil) + req := httptest.NewRequest(http.MethodGet, "/api/snapshots/0/"+view, nil) rec := httptest.NewRecorder() snapshotMux(dir).ServeHTTP(rec, req) @@ -212,7 +212,7 @@ func TestHandleGetServesFromTheCameraFolder(t *testing.T) { writeFile(t, filepath.Join(dir, "cam1"), "1.raw.png") // newer, in the camera's folder rec := httptest.NewRecorder() - snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshot/1/raw", nil)) + snapshotMux(dir).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/snapshots/1/raw", nil)) if rec.Body.String() != "1.raw.png" { t.Errorf("body = %q, want the camera folder's newer file", rec.Body.String()) From 45132e3fbb07997771a93483d4c637a3c1231249 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 11:59:53 -0500 Subject: [PATCH 13/35] remove redundant navigation system --- gui/frontend/e2e/smoke.spec.ts | 10 +-- gui/frontend/src/lib/layout/ConfigNav.svelte | 65 ------------------- gui/frontend/src/lib/layout/Shell.svelte | 4 +- gui/frontend/src/lib/layout/TabBar.svelte | 16 ++--- .../src/lib/layout/configCategories.ts | 25 ++----- gui/frontend/src/lib/layout/nav.svelte.ts | 4 +- 6 files changed, 21 insertions(+), 103 deletions(-) delete mode 100644 gui/frontend/src/lib/layout/ConfigNav.svelte diff --git a/gui/frontend/e2e/smoke.spec.ts b/gui/frontend/e2e/smoke.spec.ts index 943ff8e..d97185f 100644 --- a/gui/frontend/e2e/smoke.spec.ts +++ b/gui/frontend/e2e/smoke.spec.ts @@ -74,7 +74,7 @@ test("every page renders", async ({ page }) => { for (const hash of PAGES) { // Same-document navigation: only the hash changes, as when clicking - // through the sidebar. + // through the tabs. await page.goto(`/#${hash}`); await expect(page).toHaveURL(new RegExp(`#${hash}$`)); await expect( @@ -95,7 +95,7 @@ test("an edit applies live and shows as unsaved", async ({ page }) => { expect((await put).status()).toBe(200); await expect( - page.getByRole("link", { name: "Dimensions*" }).first(), + page.getByRole("tab", { name: "Dimensions*" }).first(), ).toBeVisible(); const geometry = (await (await page.request.get("/api/geometry")).json()) as { @@ -236,7 +236,7 @@ test("saving writes the file and clears the unsaved marker", async ({ await page.getByRole("button", { name: "Save 1 change" }).click(); await expect( - page.getByRole("link", { name: "Dimensions", exact: true }).first(), + page.getByRole("tab", { name: "Dimensions", exact: true }).first(), ).toBeVisible(); expect(readFileSync(path, "utf8")).toContain("field_width: 6100"); }); @@ -271,7 +271,7 @@ test("debug snapshots reach the page", async ({ page }) => { // The corner picker's calibration input. const picker = page - .locator('img[src*="/api/snapshot/0/geomcalib_input"]') + .locator('img[src*="/api/snapshots/0/geomcalib_input"]') .first(); await expect(picker).toBeVisible(); expect( @@ -357,7 +357,7 @@ test("the settings menu opens the API reference", async ({ page, context }) => { await docs.waitForLoadState(); expect(docs.url()).toMatch(/\/api\/docs$/); await expect( - docs.getByText("vision_processor GUI host").first(), + docs.getByText("SSL Vision Processor GUI").first(), ).toBeVisible(); await docs.close(); }); diff --git a/gui/frontend/src/lib/layout/ConfigNav.svelte b/gui/frontend/src/lib/layout/ConfigNav.svelte deleted file mode 100644 index da88be9..0000000 --- a/gui/frontend/src/lib/layout/ConfigNav.svelte +++ /dev/null @@ -1,65 +0,0 @@ - - - diff --git a/gui/frontend/src/lib/layout/Shell.svelte b/gui/frontend/src/lib/layout/Shell.svelte index 539fca6..d166594 100644 --- a/gui/frontend/src/lib/layout/Shell.svelte +++ b/gui/frontend/src/lib/layout/Shell.svelte @@ -13,7 +13,6 @@ import { links } from "../text/links"; import { competitionField, setCompetitionField } from "../teams.svelte"; import { alarmLevel } from "../alerts/alerts"; - import ConfigNav from "./ConfigNav.svelte"; import MainContent from "./MainContent.svelte"; import { untrack } from "svelte"; import { CogOutline } from "flowbite-svelte-icons"; @@ -215,7 +214,7 @@ >

- SSL Vision Processor + SSL Vision Processor GUI

@@ -406,7 +405,6 @@ > -
diff --git a/gui/frontend/src/lib/layout/TabBar.svelte b/gui/frontend/src/lib/layout/TabBar.svelte index f4f2780..bf9bae2 100644 --- a/gui/frontend/src/lib/layout/TabBar.svelte +++ b/gui/frontend/src/lib/layout/TabBar.svelte @@ -15,10 +15,8 @@ import { untrack } from "svelte"; import { app } from "../text/app"; - // Same source data as the sidebar (CONFIG_CATEGORIES), just a curated - // subset in a fixed order -- both follow nav.selectedCategoryId, so picking - // a tab here and picking the matching entry in the sidebar do the exact - // same thing and stay in sync automatically. + // Every page except Alerts (reached from the sidebar), for the camera + // picked in the sidebar. let tabs = $derived( TAB_CATEGORY_IDS.map((id) => CONFIG_CATEGORIES.find((c) => c.id === id), @@ -47,8 +45,7 @@ }); // Flowbite's Tabs component keeps exactly one tab selected and ignores - // pages that aren't tabs (Stream, Debug, ... from the sidebar), so it - // can't follow nav. These are plain links styled with its own "underline" + // pages that aren't tabs (Alerts), so it can't follow nav. These are plain links styled with its own "underline" // theme instead: they look like Flowbite Tabs, and none is selected on a // page that isn't a tab. const theme = tabsTheme({ tabStyle: "underline" }); @@ -108,7 +105,7 @@ untrack(fit); }); - // Keeps the selected tab in view, picked here or from the sidebar. By hand + // Keeps the selected tab in view, picked here or by a link. By hand // rather than scrollIntoView, which would also scroll the page to the bar. const REVEAL_MARGIN = 32; @@ -134,7 +131,8 @@ -
{/each} - + diff --git a/gui/internal/config/document.go b/gui/internal/config/document.go index f7d5a59..451dd8c 100644 --- a/gui/internal/config/document.go +++ b/gui/internal/config/document.go @@ -28,7 +28,7 @@ import ( // than µs. const Version = 2 -const fileHeader = `# vision-processor-gui configuration. Edit freely: the GUI watches this file +const fileHeader = `# SSL Vision Processor GUI configuration. Edit freely: the GUI watches this file # and asks before applying or overwriting changes made here. Comments are not # preserved when the GUI saves. ` diff --git a/gui/packaging/debian/templates b/gui/packaging/debian/templates index b5712d2..fe13a05 100644 --- a/gui/packaging/debian/templates +++ b/gui/packaging/debian/templates @@ -3,7 +3,7 @@ Type: select Choices-C: none, boot, now Choices: Don't run it as a service, Start it at boot, Start it at boot and now Default: none -Description: Run the vision_processor GUI as a system service? +Description: Run the SSL Vision Processor GUI as a system service? As a service, the GUI runs in the background as the rcssl-vp-gui user and keeps its configuration in /var/lib/rcssl/vision-processor-gui. . diff --git a/gui/packaging/nfpm.yaml b/gui/packaging/nfpm.yaml index 6cd79ff..95072ff 100644 --- a/gui/packaging/nfpm.yaml +++ b/gui/packaging/nfpm.yaml @@ -18,7 +18,8 @@ maintainer: "@MAINTAINER@" homepage: https://github.com/RoboCup-SSL/ssl-vision-processor license: Apache-2.0 description: |- - Browser interface for the RoboCup SSL vision_processor + SSL Vision Processor GUI + Browser interface for the RoboCup SSL vision_processor. Sets up and runs the league's shared vision system: field geometry, camera settings, locked calibrations, live video and the live field. It publishes the field geometry to the rest of the league's software. diff --git a/gui/packaging/ssl-vision-processor-gui.1 b/gui/packaging/ssl-vision-processor-gui.1 index 568f57b..629d080 100644 --- a/gui/packaging/ssl-vision-processor-gui.1 +++ b/gui/packaging/ssl-vision-processor-gui.1 @@ -2,7 +2,7 @@ .\" TestManPageListsEveryFlag checks. .TH SSL-VISION-PROCESSOR-GUI 1 "" "ssl-vision-processor-gui" "RoboCup SSL" .SH NAME -ssl-vision-processor-gui \- browser interface for the RoboCup SSL vision_processor +ssl-vision-processor-gui \- SSL Vision Processor GUI, browser interface for the RoboCup SSL vision_processor .SH SYNOPSIS .B ssl-vision-processor-gui .RI [ options ] diff --git a/gui/packaging/ssl-vision-processor-gui.service b/gui/packaging/ssl-vision-processor-gui.service index 2e3a04c..1e68135 100644 --- a/gui/packaging/ssl-vision-processor-gui.service +++ b/gui/packaging/ssl-vision-processor-gui.service @@ -1,4 +1,4 @@ -# The vision_processor GUI as a system service. Whether it's enabled, and the +# The SSL Vision Processor GUI as a system service. Whether it's enabled, and the # address in /etc/default/ssl-vision-processor-gui, are the package's setup # questions: sudo dpkg-reconfigure ssl-vision-processor-gui. Extra options go # in that file's ARGS. @@ -10,7 +10,7 @@ # runs as its own service. [Unit] -Description=vision_processor GUI (RoboCup SSL) +Description=SSL Vision Processor GUI (RoboCup SSL) Documentation=file:///usr/share/doc/ssl-vision-processor-gui/README.md Wants=network-online.target After=network-online.target diff --git a/gui/packaging/ssl-vision-processor-gui.user.service b/gui/packaging/ssl-vision-processor-gui.user.service index 700879c..7464bf9 100644 --- a/gui/packaging/ssl-vision-processor-gui.user.service +++ b/gui/packaging/ssl-vision-processor-gui.user.service @@ -1,4 +1,4 @@ -# The vision_processor GUI as your own user service, with the same file +# The SSL Vision Processor GUI as your own user service, with the same file # locations as running it by hand: # # systemctl --user enable --now ssl-vision-processor-gui @@ -6,7 +6,7 @@ # It stops when you log out unless lingering is on: loginctl enable-linger. [Unit] -Description=vision_processor GUI (RoboCup SSL) +Description=SSL Vision Processor GUI (RoboCup SSL) Documentation=file:///usr/share/doc/ssl-vision-processor-gui/README.md [Service] diff --git a/gui/packaging/sysusers.conf b/gui/packaging/sysusers.conf index f9d90df..1e2f56c 100644 --- a/gui/packaging/sysusers.conf +++ b/gui/packaging/sysusers.conf @@ -1,5 +1,5 @@ # rcssl is shared by every RoboCup SSL tool's package: each runs as its own # user, in this group, so members can read every tool's files. g rcssl - -u rcssl-vp-gui - "vision_processor GUI" /var/lib/rcssl/vision-processor-gui +u rcssl-vp-gui - "SSL Vision Processor GUI" /var/lib/rcssl/vision-processor-gui m rcssl-vp-gui rcssl From 149339191cd1354fd75496d28c7b687885c1484f Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 12:06:32 -0500 Subject: [PATCH 15/35] singel typed topic list --- gui/ARCHITECTURE.md | 7 +- gui/CLAUDE.md | 13 ++- gui/REVIEW.md | 22 ++-- gui/cmd/ssl-vision-processor-gui/docs.go | 9 +- gui/cmd/ssl-vision-processor-gui/livefield.go | 17 +-- gui/cmd/ssl-vision-processor-gui/main.go | 54 ++------- gui/cmd/ssl-vision-processor-gui/routes.go | 4 + gui/cmd/ssl-vision-processor-gui/topics.go | 62 +++++++++++ .../ssl-vision-processor-gui/topics_test.go | 82 ++++++++++++++ .../ssl-vision-processor-gui/wiring_test.go | 8 +- gui/frontend/README.md | 10 +- .../src/lib/alerts/hostAlerts.svelte.ts | 6 +- gui/frontend/src/lib/apiTypes.ts | 8 ++ ...wrapper-bus.test.ts => bus.svelte.test.ts} | 105 ++++++++++++++---- .../src/lib/{wrapper-bus.ts => bus.svelte.ts} | 84 +++++++++----- .../src/lib/checklist/checklist.svelte.ts | 6 +- gui/frontend/src/lib/config.svelte.ts | 6 +- gui/frontend/src/lib/hostVersion.svelte.ts | 7 +- gui/frontend/src/lib/layout/Shell.svelte | 6 +- .../src/lib/live/LiveFieldPanel.svelte | 23 +--- gui/frontend/src/lib/network.svelte.ts | 6 +- gui/frontend/src/lib/processes.svelte.ts | 6 +- gui/frontend/src/lib/report/systemReport.ts | 5 +- gui/frontend/src/test-setup.ts | 10 +- gui/internal/api/topics.go | 97 ++++++++++++++++ 25 files changed, 471 insertions(+), 192 deletions(-) create mode 100644 gui/cmd/ssl-vision-processor-gui/topics.go create mode 100644 gui/cmd/ssl-vision-processor-gui/topics_test.go rename gui/frontend/src/lib/{wrapper-bus.test.ts => bus.svelte.test.ts} (65%) rename gui/frontend/src/lib/{wrapper-bus.ts => bus.svelte.ts} (65%) create mode 100644 gui/internal/api/topics.go diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index 2169be3..674735f 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -361,10 +361,11 @@ UI, can administer the host. { "action": "unsubscribe", "topic": "geometry.state" } // server -> client { "topic": "geometry.state", "data": { /* protojson */ } } -{ "error": "unknown_topic", "message": "...", "topic": "wrapper_pakcet.out" } +{ "error": "unknown_topic", "message": "...", "topic": "geomtry.state" } ``` -`GET /api/topics` lists the topics. A new subscriber gets the topic's latest value at once, then every later one. +`GET /api/topics` lists the topics, from the one list in `cmd/ssl-vision-processor-gui/topics.go`, which also drives +the API reference's table and the frontend's types (the spec's `Topics` schema). A new subscriber gets the topic's latest value at once, then every later one. A message the server can't act on is answered with an error (`bad_request`, `unknown_topic`, `unknown_action`) and the connection stays open. @@ -383,6 +384,8 @@ source's rate and receive time and the host's clock (`at`), so a client can tell senders' clocks. Detections are in mm, tracked frames in m. A source silent for a second is listed without a frame, and dropped after 30 s. It is published at up to 60 Hz, only while someone subscribes and something new arrived (and once a second otherwise); `GET /api/live-field` returns the same snapshot. +`instances.state` carries every vision_processor heard announcing itself (`internal/discovery`), once per second and +on every config change; the same as `GET /api/instances`. `alerts.state` carries every problem the host can see (`internal/alerts`), on the same schedule: a stable `id`, a `code`, a `severity` (`error`, `warning`, `caution`), an optional `cameraId`, the facts behind it as `params`, and a plain English `message`. The host decides which alerts exist and how serious they are; a client words and diff --git a/gui/CLAUDE.md b/gui/CLAUDE.md index 7c9fba7..d0afec5 100644 --- a/gui/CLAUDE.md +++ b/gui/CLAUDE.md @@ -102,12 +102,12 @@ buf.gen.yaml generates both internal/{vision,gamecontroller} and 8 KB receive buffer. It also leaks the socket when `JoinGroup` fails, and races `Stop` against its own reconnect. Re-evaluate once ssl-go-tools PR #29 (`UdpServer`) is released, if it also has a settable receive buffer and - a health accessor (REVIEW.md U-1, U-2); `pkg/sourcefilter` is fine to use. + a health accessor (REVIEW.md U-1, U-2); ssl-go-tools is GPL-3.0 and + this repo is Apache-2.0: don't import or copy from it without settling that. - **`google.golang.org/protobuf` + `protojson`**, never `encoding/json` on a generated message (see Gotchas). -- **Svelte 5 runes only**, no stores added beyond what predates this work - (`wrapper-bus.ts` still uses `svelte/store`'s `readable` -- not yet migrated, - not a blocker). +- **Svelte 5 runes only**, no stores. WebSocket topics come from + `bus.svelte.ts` (`topicState`, `onTopic`), typed by the host's list. - **flowbite-svelte for every UI element**, with the theme tokens in `frontend/src/app.css` for color. New UI uses a Flowbite component where one exists (Button, Input, Select, Toggle, Range, Alert, Helper, Toast, Card, @@ -325,6 +325,11 @@ calibrated against a real skewed webcam view, and the calibration came back and was absorbed with no wire-format surprises between C++ and Go protobuf. Not automated -- there is no CI hardware to run it on. +WebSocket topics are listed once, in `cmd/.../topics.go`: add one there with +`newTopic` and publish it through it. The hub, `/api/topics`, the API reference +and the frontend's `TopicMap` (the spec's `Topics` schema) follow; +`TestEveryTopicMatchesItsSchema` has to see it published. + Routes go through `api.Route` (typed input and output) or `api.Raw`, never `mux.Handle`, so the spec stays complete. A handler's doc comment is its API summary (first sentence) and description: write it for API readers, keep the diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 4ed0024..e69e1b6 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,11 +27,11 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-25. **Open** 28 · **Partial** 4 · **Done** 37 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 26 · **Partial** 4 · **Done** 39 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T3-3, T5-6, T8-1 and T1-2 are awaiting commit. -1. API freeze: T3-1 with T4-6, then T3-2 (Will approved `openapi-fetch`). +All blockers are fixed. T3-1 and T4-6 are awaiting commit. +1. API freeze: T3-2 (Will approved `openapi-fetch`). 2. T1-3, T6-1, T6-5, T4-3. **Needs the lab PoE machine:** T2-10. @@ -59,7 +59,7 @@ All blockers are fixed. T3-3, T5-6, T8-1 and T1-2 are awaiting commit. | T2-8 | major | Will | one vision_processor's video restarts are reported as two senders | done | | T2-9 | major | Will | duplicate video packets (several interfaces) break the picture, no warning | done | | T2-10 | major | Will + Claude | console warnings while vision/GC use the PoE camera NICs | open (needs lab machine) | -| T3-1 | major | Will | WS topic contract in three places | open | +| T3-1 | major | Will | WS topic contract in three places | done | | T3-2 | major | Will | generated `paths` unused | open | | T3-3 | major | Will | naming pass before freezing API 1.0 | done | | T3-4 | minor | Will | response-spec test coverage | done | @@ -69,7 +69,7 @@ All blockers are fixed. T3-3, T5-6, T8-1 and T1-2 are awaiting commit. | T4-3 | minor | Will | rejected value stays in the form | open | | T4-4 | minor | Will | no stale-frontend detection | done | | T4-5 | minor | Will | large components | open | -| T4-6 | minor | Will | bus still on `svelte/store` | open | +| T4-6 | minor | Will | bus still on `svelte/store` | done | | T4-7 | nit | Will | hex colours | partial | | T4-8 | nit | Claude | Flowbite `@source` CSS bloat | dropped | | T5-1 | blocker | Will | placeholder Debug page | done | @@ -176,7 +176,7 @@ Fix: `git rm --cached gui/ssl-vision-processor-gui`. Before `v2.0-alpha` merges A `v*` tag publishes a public GitHub Release after only `release-check` and `deb-check`. `make check` and the e2e suite never run against the tagged commit; CI runs on master pushes and PRs, but a tag can point anywhere. `gh release create` also publishes immediately, with no draft. Fix: run `make check` (including e2e) in the release job before building, or gate it on the CI workflow for that SHA. Create the release as `--draft` and publish by hand after a smoke install. Mark `-rc`/`-alpha` tags `--prerelease`. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the release workflow runs `make check` on the tagged commit (failing without Chrome, so the browser tests can't be skipped), then drafts the release for Will to publish by hand. Tags with a suffix are pre-releases. Not run: it needs a tag push. +*Done 2026-11-25 (Claude, at Will's request; committed):* the release workflow runs `make check` on the tagged commit (failing without Chrome, so the browser tests can't be skipped), then drafts the release for Will to publish by hand. Tags with a suffix are pre-releases. Not run: it needs a tag push. **T1-3 | major | Claude + Will | `gui/packaging/nfpm.yaml:26`, release notes, `gui/README.md`** The package description says "The camera processing itself, vision_processor, is packaged separately", but no vision_processor package exists yet (the CV deb is planned). A new user who installs the `.deb` from the first release has a GUI with nothing to talk to, and nothing on the release page says how to get vision_processor. The `v*` tag also reads as a release of the whole repo while it ships only the GUI. @@ -294,6 +294,8 @@ Overall: the REST half is well disciplined. Every route goes through `api.Route` The WS topic contract is hand-maintained in three places and has already drifted. The spec's topic table lists 5 topics; the host serves 7 (`instances.state` at `main.go:790` and `live_field.frames` are missing). Topic names are string literals on both sides. Each frontend subscriber asserts its own payload type (`topic("config.state")`), so a wrong name or type compiles. Fix: one topic registry in Go (name → payload type → equivalent route) that drives `/api/topics`, the spec's topic table (or an `x-topics` extension with schema refs), and a test that every hub topic is registered. Generate a TS `TopicMap` from it so `topic("config.state")` infers its type and an unknown name fails to compile. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* `cmd/.../topics.go` is the only topic list: typed `newTopic[T]` values that publish themselves. The hub, `/api/topics`, the reference's table and the spec's `Topics` schema (name → data, from the GET route each topic mirrors) come from it, and the frontend's `TopicMap` from that schema, so an unknown topic or a wrong payload doesn't compile. All 7 topics are documented. `TestEveryTopicMatchesItsSchema` publishes each and checks it against its schema. + **T3-2 | major | Will | `frontend/src/lib/*.svelte.ts`, `api.ts`** The frontend uses only `components["schemas"]` from the generated file, never `paths`. There are 30 hand-written `/api/...` URL strings and 12 `response.json()` results cast to a type, so a wrong path, method, query parameter or body shape still type-checks, which is exactly the drift the generated types exist to catch. Fix: `openapi-fetch` (same author as `openapi-typescript`, ~6 kB, no runtime schema) typed against `paths`. It makes `client.GET("/api/config/cameras/{id}/effective", {params: {path: {id}}})` checked end to end and removes most casts. `requestJSON`/`errorMessage` can stay as its error middleware. @@ -308,7 +310,7 @@ Fix: `openapi-fetch` (same author as `openapi-typescript`, ~6 kB, no runtime sch Fix: pick one convention (kebab-case paths, plural collections, `{id}`, `verbNoun` operationIds, `.state` topics), apply it before the release, and consider `0.x` for the spec version until after the first event. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* `/api/live-field`, `/api/capture-devices`, `/api/snapshots/{id}/{view}`; topics `live-field.state` and `geometry.state`; verbNoun operationIds on every route, the WebSockets included; `ErrorBody`; spec version 0.1.0. No aliases. `TestNamesFollowTheRules` keeps new names to the rules. +*Done 2026-11-25 (Claude, at Will's request; committed):* `/api/live-field`, `/api/capture-devices`, `/api/snapshots/{id}/{view}`; topics `live-field.state` and `geometry.state`; verbNoun operationIds on every route, the WebSockets included; `ErrorBody`; spec version 0.1.0. No aliases. `TestNamesFollowTheRules` keeps new names to the rules. **T3-4 | minor | Will | `cmd/ssl-vision-processor-gui/responses_test.go:17-33`** `TestResponsesMatchTheSpec` checks a hand-kept list of 16 GET routes. A new GET route is silently unchecked, and `/api/geometry`, every write route's 200 body and the error envelope are never validated. `conforms` checks nullability, enums and required fields only. @@ -364,6 +366,8 @@ Fix: pull the coordinate and colour math into `.ts` modules (which also closes m The bus is the last `svelte/store` user (`readable`). Consumers wrap it in `$effect` plus a manual `subscribe`, and App.svelte needs a 10-line comment explaining why a `$store` reference wouldn't have gated the subscription. Fix: a runes-native `topicState(name)` built on `createSubscriber` (svelte/reactivity), which subscribes while something reads it. Do it together with T3-1's typed `TopicMap`. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* `bus.svelte.ts` replaces `wrapper-bus.ts`: `connection.state`, `onTopic(name, fn)` for state modules, `topicState(name).current` (`createSubscriber`) for components. No `svelte/store` left. + **T4-7 | nit | Will | hex colours** `App.svelte:151-165` hand-styles a warning box in hex, against the token rule (it goes away with T4-1). In canvas/SVG drawing, where hex is allowed, the field green `#0a5c2e` is repeated in three files (`FieldSketch`, `WizardFieldPreview`, `WizardDimensionsPreview`) and the danger stroke `#b00020` in `WeightTriangle`. Fix: one CSS custom property each in `app.css`. @@ -427,7 +431,7 @@ Fix: label the controls (likely the slider/number pairs; each needs `aria-label` There are two navigation systems with different contents. The sidebar lists Live Field, Teams, Network, Dimensions and Layout, then Camera, Geometry, Color, Stream and Debug. The top tab bar repeats them under "GLOBAL CONFIGS" and "PER-CAMERA CONFIGS - FIELD CAM #0", but has no Stream, Debug, Alerts or Advanced. A new user can't tell which is primary, or why some pages appear in only one. Fix: pick one. Keep the sidebar (it scales to several cameras) and drop the tab bar, or keep the tabs only on narrow screens as a replacement for the sidebar. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* Will's choice: the tab bar is the navigation. The sidebar keeps Alerts and the camera list, unchanged; `ConfigNav.svelte` (the page links) is gone and Stream is now a tab. The sidebar's free space is for camera summaries later (Future features). +*Done 2026-11-25 (Claude, at Will's request; committed):* Will's choice: the tab bar is the navigation. The sidebar keeps Alerts and the camera list, unchanged; `ConfigNav.svelte` (the page links) is gone and Stream is now a tab. The sidebar's free space is for camera summaries later (Future features). **T5-7 | minor | Will | first-run wording** - The wizard's Finish step still says "Applying… doesn't save -- use Save in the settings menu (or Ctrl+S)", although Apply immediately opens the save dialog. @@ -584,7 +588,7 @@ Fix: treat an overflow under ~3 as in gamut (or compare against the rounded deco The product has four names. The browser title and header say **"SSL Vision Processor"**, which reads as if this page *is* the vision processor. The README, man page, package description and systemd unit say **"vision_processor GUI"** (11 uses), with "vision-processor GUI", "vision processor GUI" and the log's "Init VP GUI" mixed in. The binary and package are `ssl-vision-processor-gui`. First-time users meet all of these in their first ten minutes. Fix: pick one display name (for example "SSL Vision Processor GUI") for the title, header, README H1, man page NAME, package description, unit `Description=` and startup log. Keep `vision_processor` in code font only for the C++ binary. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* "SSL Vision Processor GUI" everywhere it's displayed: title, header, About, README, man page, package, units, account description, API docs, startup log, config file header. `vision_processor` is only the C++ program. Binary, package, folder and account names are unchanged. +*Done 2026-11-25 (Claude, at Will's request; committed):* "SSL Vision Processor GUI" everywhere it's displayed: title, header, About, README, man page, package, units, account description, API docs, startup log, config file header. `vision_processor` is only the C++ program. Binary, package, folder and account names are unchanged. **T8-2 | minor | Will + Claude | page names** The same pages have different names in the sidebar ("Camera", "Layout", "Dimensions"), page headings ("Camera settings", "Field dimensions"), README ("Camera Settings page", "Camera Layout page") and the frontend README ("Field Dimensions", "Camera Layout"). Headings use sentence case and the README uses title case. diff --git a/gui/cmd/ssl-vision-processor-gui/docs.go b/gui/cmd/ssl-vision-processor-gui/docs.go index f6c17f7..a75804c 100644 --- a/gui/cmd/ssl-vision-processor-gui/docs.go +++ b/gui/cmd/ssl-vision-processor-gui/docs.go @@ -31,13 +31,6 @@ sockets hear. Every error is JSON, ` + "`{\"error\": code, \"message\": text, \" once. A message the host can't act on is answered with an error and the connection stays open. Each topic's data is the body of a REST endpoint documented here: -| Topic | Same as | -| --- | --- | -| ` + "`config.state`" + ` | ` + "`state`" + ` in GET /api/config | -| ` + "`network.state`" + ` | GET /api/network | -| ` + "`alerts.state`" + ` | GET /api/alerts | -| ` + "`processes.state`" + ` | GET /api/processes | -| ` + "`geometry.state`" + ` | GET /api/geometry | ` // openapiSpec is the host's OpenAPI spec as JSON. It depends only on the @@ -53,7 +46,7 @@ func openapiSpec() ([]byte, error) { // newAPI is the host's typed route registry and spec. func newAPI(mux *http.ServeMux) *api.API { - a := api.New(mux, api.Info{Title: "SSL Vision Processor GUI", Version: specVersion, Description: specIntro, Tags: specTags}, + a := api.New(mux, api.Info{Title: "SSL Vision Processor GUI", Version: specVersion, Description: specIntro + api.TopicTable(registeredTopics), Tags: specTags}, func(w http.ResponseWriter, err error) { respondConfigErr(w, err, "handling request") }) a.SchemaFor(reflect.TypeFor[config.Settings](), settingsSchema()) diff --git a/gui/cmd/ssl-vision-processor-gui/livefield.go b/gui/cmd/ssl-vision-processor-gui/livefield.go index 8432e7b..3320a7c 100644 --- a/gui/cmd/ssl-vision-processor-gui/livefield.go +++ b/gui/cmd/ssl-vision-processor-gui/livefield.go @@ -2,8 +2,6 @@ package main import ( "context" - "encoding/json" - "log/slog" "net/http" "time" @@ -11,10 +9,6 @@ import ( "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/livefield" ) -// liveFieldTopic carries livefield.Snapshot: every camera's latest detection -// frame and every autoref's latest tracked frame. -const liveFieldTopic = "live-field.state" - // Detections arrive at 60 to 75 Hz per camera; publishing faster than a // browser draws gains nothing. const ( @@ -40,7 +34,7 @@ func publishLiveField(ctx context.Context, wsHub *hub.Hub, live *livefield.Feed) case <-ctx.Done(): return nil case now := <-ticker.C: - if !wsHub.Watched(liveFieldTopic) { + if !wsHub.Watched(liveFieldTopic.name) { continue } @@ -49,14 +43,7 @@ func publishLiveField(ctx context.Context, wsHub *hub.Hub, live *livefield.Feed) continue } - data, err := json.Marshal(live.Snapshot(now)) - if err != nil { - slog.Error("marshalling live field", "err", err) - - continue - } - - wsHub.Publish(liveFieldTopic, data) + liveFieldTopic.publish(wsHub, live.Snapshot(now)) version, published = v, now } } diff --git a/gui/cmd/ssl-vision-processor-gui/main.go b/gui/cmd/ssl-vision-processor-gui/main.go index d8682eb..1191745 100644 --- a/gui/cmd/ssl-vision-processor-gui/main.go +++ b/gui/cmd/ssl-vision-processor-gui/main.go @@ -2,7 +2,6 @@ package main import ( "context" - "encoding/json" "errors" "flag" "fmt" @@ -221,7 +220,7 @@ func run() int { // store changes. publishConfigState(wsHub, store) publishStatus(wsHub, status) - publishJSON(wsHub, processesStateTopic, h.procs.Statuses()) + processesTopic.publish(wsHub, h.procs.Statuses()) }) }) runBackground(&wg, "config file watcher", func() error { return store.Watch(ctx, configWatchInterval) }) @@ -371,7 +370,7 @@ func newHost(path string, opts hostOptions) (*host, error) { sockets.apply(store) match.SetHeightsFile(botHeightsFile(store)) - wsHub := hub.New(wrapperPacketTopic, configStateTopic, networkStateTopic, alertsStateTopic, processesStateTopic, liveFieldTopic, instancesStateTopic) + wsHub := newHub() status := &hostStatus{store: store, sockets: sockets, match: match, live: live, instances: instances} policy.SetStrict(competitionField(store)) @@ -384,7 +383,7 @@ func newHost(path string, opts hostOptions) (*host, error) { RunDir: opts.runDir, ImgDir: opts.imgDir, OnChange: func() { - publishJSON(wsHub, processesStateTopic, procs.Statuses()) + processesTopic.publish(wsHub, procs.Statuses()) // A camera held for a device conflict is an alert. publishStatus(wsHub, status) }, @@ -610,18 +609,8 @@ func flagSet(name string) bool { return set } -// configStateTopic carries config.Store's State to the frontend. -const configStateTopic = "config.state" - func publishConfigState(wsHub *hub.Hub, store *config.Store) { - data, err := json.Marshal(store.State()) - if err != nil { - slog.Error("marshalling config state", "err", err) - - return - } - - wsHub.Publish(configStateTopic, data) + configTopic.publish(wsHub, store.State()) } // networkSockets is the host's multicast groups. @@ -806,35 +795,12 @@ func ufwEnabled(path string) bool { return false } -// networkStateTopic carries NetworkState, and alertsStateTopic every -// current alert. -const ( - networkStateTopic = "network.state" - alertsStateTopic = "alerts.state" - // processesStateTopic carries the supervised vision_processors - // (-runCameras). - processesStateTopic = "processes.state" - // instancesStateTopic carries every vision_processor heard announcing. - instancesStateTopic = "instances.state" -) - // publishStatus publishes the network state and the alerts, which depend on // it and on the store, and the vision_processors announcing. func publishStatus(wsHub *hub.Hub, status StatusSource) { - publishJSON(wsHub, networkStateTopic, status.Network()) - publishJSON(wsHub, alertsStateTopic, status.Alerts()) - publishJSON(wsHub, instancesStateTopic, status.Instances()) -} - -func publishJSON(wsHub *hub.Hub, topic string, v any) { - data, err := json.Marshal(v) - if err != nil { - slog.Error("marshalling websocket topic", "topic", topic, "err", err) - - return - } - - wsHub.Publish(topic, data) + networkTopic.publish(wsHub, status.Network()) + alertsTopic.publish(wsHub, status.Alerts()) + instancesTopic.publish(wsHub, status.Instances()) } // hostNetwork is doc's network block. The store only holds validated @@ -856,10 +822,6 @@ func withSend(opts multicast.Options) multicast.Options { return opts } -// wrapperPacketTopic is the hub topic name the frontend already subscribes to -// (see gui/frontend/src/App.svelte). -const wrapperPacketTopic = "geometry.state" - // sendGeometry publishes the geometry on the vision group, unless this is a // first run: a host somebody is only trying out has no business telling a real // network what the field looks like. @@ -880,7 +842,7 @@ func publishGeometryToHub(wsHub *hub.Hub, geom *geometry.Geometry) { return } - wsHub.Publish(wrapperPacketTopic, data) + geometryTopic.publish(wsHub, data) } // listenUI binds the GUI's port. Its error is a whole sentence for the log, diff --git a/gui/cmd/ssl-vision-processor-gui/routes.go b/gui/cmd/ssl-vision-processor-gui/routes.go index c28f6f1..656912b 100644 --- a/gui/cmd/ssl-vision-processor-gui/routes.go +++ b/gui/cmd/ssl-vision-processor-gui/routes.go @@ -116,6 +116,10 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { Errors: []string{httpjson.CodeBadRequest, httpjson.CodeNotFound}, }, video.HandleWebSocket(s.video, s.origins.Allowed), api.RawResponse{Status: http.StatusSwitchingProtocols, Description: "Upgraded to a WebSocket."}) + if err := a.Topics(registeredTopics); err != nil { + panic(err) + } + mux.Handle("/api/", httpjson.NotFound()) mux.Handle("/", frontend.HandleFrontend()) } diff --git a/gui/cmd/ssl-vision-processor-gui/topics.go b/gui/cmd/ssl-vision-processor-gui/topics.go new file mode 100644 index 0000000..eafda25 --- /dev/null +++ b/gui/cmd/ssl-vision-processor-gui/topics.go @@ -0,0 +1,62 @@ +package main + +import ( + "encoding/json" + "log/slog" + + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/alerts" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/api" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/config" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/discovery" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/hub" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/livefield" + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/supervisor" +) + +// The WebSocket topics, the only list of them: the hub, GET /api/topics, the +// API reference and the frontend's TopicMap (through the spec's Topics schema) +// all come from here. +var ( + registeredTopics []api.Topic + + alertsTopic = newTopic[[]alerts.Alert](api.Topic{Name: "alerts.state", Route: "/api/alerts", Description: everySecond}) + configTopic = newTopic[config.State](api.Topic{Name: "config.state", Route: "/api/config", Field: "state", Description: everySecond}) + geometryTopic = newTopic[wrapperPacket](api.Topic{Name: "geometry.state", Route: "/api/geometry", Description: "Once a second."}) + instancesTopic = newTopic[[]discovery.Instance](api.Topic{Name: "instances.state", Route: "/api/instances", Description: everySecond}) + liveFieldTopic = newTopic[livefield.Snapshot](api.Topic{Name: "live-field.state", Route: "/api/live-field", Description: "Up to 60 times a second while something new arrives, else once a second; only while subscribed."}) + networkTopic = newTopic[NetworkState](api.Topic{Name: "network.state", Route: "/api/network", Description: everySecond}) + processesTopic = newTopic[[]supervisor.Status](api.Topic{Name: "processes.state", Route: "/api/processes", Description: "Once a second, and on every state change."}) +) + +const everySecond = "Once a second, and on every configuration change." + +// topic is a WebSocket topic carrying T. +type topic[T any] struct{ name string } + +func newTopic[T any](t api.Topic) topic[T] { + registeredTopics = append(registeredTopics, t) + + return topic[T]{t.Name} +} + +// publish sends v to the topic's subscribers. +func (t topic[T]) publish(wsHub *hub.Hub, v T) { + data, err := json.Marshal(v) + if err != nil { + slog.Error("marshalling websocket topic", "topic", t.name, "err", err) + + return + } + + wsHub.Publish(t.name, data) +} + +// newHub is a hub with every topic. +func newHub() *hub.Hub { + names := make([]string, len(registeredTopics)) + for i, t := range registeredTopics { + names[i] = t.Name + } + + return hub.New(names...) +} diff --git a/gui/cmd/ssl-vision-processor-gui/topics_test.go b/gui/cmd/ssl-vision-processor-gui/topics_test.go new file mode 100644 index 0000000..632af06 --- /dev/null +++ b/gui/cmd/ssl-vision-processor-gui/topics_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "encoding/json" + "slices" + "strings" + "testing" + "time" + + "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/api" +) + +// Every topic is published, with data matching its documented schema: what +// the frontend's TopicMap is generated from. +func TestEveryTopicMatchesItsSchema(t *testing.T) { + h, _ := testHost(t) + + data, err := openapiSpec() + if err != nil { + t.Fatal(err) + } + + var spec struct { + Components struct{ Schemas map[string]map[string]any } + } + if err := json.Unmarshal(data, &spec); err != nil { + t.Fatal(err) + } + + documented, _ := spec.Components.Schemas["Topics"]["properties"].(map[string]any) + + if len(documented) != len(h.hub.Topics()) { + t.Errorf("%d topics documented, %d served", len(documented), len(h.hub.Topics())) + } + + received := map[string]<-chan []byte{} + + for _, name := range h.hub.Topics() { + ch, unsubscribe := h.hub.Subscribe(name) + t.Cleanup(unsubscribe) + + received[name] = ch + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + go func() { _ = publishLiveField(ctx, h.hub, h.status.live) }() + + configTopic.publish(h.hub, h.store.State()) + publishStatus(h.hub, h.status) + processesTopic.publish(h.hub, h.procs.Statuses()) + publishGeometryToHub(h.hub, h.geom) + + for name, ch := range received { + schema, ok := documented[name].(map[string]any) + if !ok { + t.Errorf("topic %s isn't documented", name) + + continue + } + + select { + case raw := <-ch: + var value any + if err := json.Unmarshal(raw, &value); err != nil { + t.Errorf("%s: %v", name, err) + } + + for _, problem := range conforms(name, value, schema, spec.Components.Schemas) { + t.Error(problem) + } + case <-time.After(5 * time.Second): + t.Errorf("nothing published on %s", name) + } + } + + if !slices.IsSortedFunc(registeredTopics, func(a, b api.Topic) int { return strings.Compare(a.Name, b.Name) }) { + t.Error("registeredTopics isn't sorted by name, so neither is the reference's table") + } +} diff --git a/gui/cmd/ssl-vision-processor-gui/wiring_test.go b/gui/cmd/ssl-vision-processor-gui/wiring_test.go index 4388d51..cf8ba02 100644 --- a/gui/cmd/ssl-vision-processor-gui/wiring_test.go +++ b/gui/cmd/ssl-vision-processor-gui/wiring_test.go @@ -133,7 +133,7 @@ func TestAChangeReachesWebSocketSubscribers(t *testing.T) { } t.Cleanup(func() { conn.Close() }) - for _, topic := range []string{configStateTopic, alertsStateTopic} { + for _, topic := range []string{configTopic.name, alertsTopic.name} { if err := conn.WriteJSON(map[string]string{"action": "subscribe", "topic": topic}); err != nil { t.Fatal(err) } @@ -141,7 +141,7 @@ func TestAChangeReachesWebSocketSubscribers(t *testing.T) { // Subscriptions are handled on the server's read loop; wait for them // before changing anything. - for _, topic := range []string{configStateTopic, alertsStateTopic} { + for _, topic := range []string{configTopic.name, alertsTopic.name} { waitUntil(t, topic+" subscribed", func() bool { return h.hub.Watched(topic) }) } @@ -155,12 +155,12 @@ func TestAChangeReachesWebSocketSubscribers(t *testing.T) { until(t, conn, "config.state at the new revision", func(m envelope) bool { var state config.State - return m.Topic == configStateTopic && json.Unmarshal(m.Data, &state) == nil && state.Revision == int64(rev) + return m.Topic == configTopic.name && json.Unmarshal(m.Data, &state) == nil && state.Revision == int64(rev) }) until(t, conn, "alerts.state with the uncovered regions", func(m envelope) bool { var list []alerts.Alert - if m.Topic != alertsStateTopic || json.Unmarshal(m.Data, &list) != nil { + if m.Topic != alertsTopic.name || json.Unmarshal(m.Data, &list) != nil { return false } diff --git a/gui/frontend/README.md b/gui/frontend/README.md index eabc447..f21e82e 100644 --- a/gui/frontend/README.md +++ b/gui/frontend/README.md @@ -79,10 +79,12 @@ Node 22 (`.nvmrc`); the nix dev shell provides it. `collect()` and point its actions at a page and/or a doc. - `src/lib/api.ts` holds the fetch helpers (`requestJSON`, `withLoadingState`) every panel's load and save functions are built on. -- `src/lib/wrapper-bus.ts` is a single `WebSocket` client. It exposes - `connectionState` (a Svelte store) and `topic(name)` (a store of the - latest message on that topic). A topic subscribes lazily on first reader - and unsubscribes when the last reader goes away. It reconnects on close +- `src/lib/bus.svelte.ts` is a single `WebSocket` client. It exposes + `connection.state`, `topicState(name)` (the topic's latest message as + `current`, for components) and `onTopic(name, fn)` (for state modules). Both + are typed by the topic's name, from the host's topic list; an unknown name + doesn't compile. A topic subscribes with its first reader and unsubscribes + with its last. It reconnects on close with exponential backoff, from 1 second up to 30. - `src/lib/SnapshotViews.svelte` is the debug image card on the Color and Geometry pages: the views a camera has written, listed on demand (not diff --git a/gui/frontend/src/lib/alerts/hostAlerts.svelte.ts b/gui/frontend/src/lib/alerts/hostAlerts.svelte.ts index 39a9d79..f7f90b1 100644 --- a/gui/frontend/src/lib/alerts/hostAlerts.svelte.ts +++ b/gui/frontend/src/lib/alerts/hostAlerts.svelte.ts @@ -1,7 +1,7 @@ // The host's alerts (gui/internal/alerts), from the alerts.state topic: which // problems exist, how serious, and the facts behind each. alerts.ts words and // links them. -import { topic } from "../wrapper-bus"; +import { onTopic } from "../bus.svelte"; import type { HostAlert } from "../apiTypes"; export type { HostAlert, Severity } from "../apiTypes"; @@ -10,8 +10,8 @@ export const hostAlerts = $state<{ list: HostAlert[] }>({ list: [] }); $effect.root(() => { $effect(() => { - return topic("alerts.state").subscribe((list) => { - if (list) hostAlerts.list = list; + return onTopic("alerts.state", (list) => { + hostAlerts.list = list; }); }); }); diff --git a/gui/frontend/src/lib/apiTypes.ts b/gui/frontend/src/lib/apiTypes.ts index e6a1ea5..d709f66 100644 --- a/gui/frontend/src/lib/apiTypes.ts +++ b/gui/frontend/src/lib/apiTypes.ts @@ -3,6 +3,7 @@ // than writing a copy of a Go type: the generated file follows the Go code, // and CI fails when it's out of date. import type { components } from "./generated/api"; +import type { SSL_WrapperPacketJson } from "../proto/vision/ssl_vision_wrapper_pb"; type Schemas = components["schemas"]; @@ -73,3 +74,10 @@ export type LogLevel = LogRecord["level"]; export type BuildInfo = Schemas["BuildinfoInfo"]; export type GitState = Schemas["BuildinfoGit"]; export type HealthResponse = Schemas["HealthResponse"]; + +// The WebSocket topics and their data, from the host's topic list. geometry's +// is a league message, typed by its protobuf definition. +export type TopicMap = Omit & { + "geometry.state": SSL_WrapperPacketJson; +}; +export type Topic = keyof TopicMap; diff --git a/gui/frontend/src/lib/wrapper-bus.test.ts b/gui/frontend/src/lib/bus.svelte.test.ts similarity index 65% rename from gui/frontend/src/lib/wrapper-bus.test.ts rename to gui/frontend/src/lib/bus.svelte.test.ts index db7436f..419ce1f 100644 --- a/gui/frontend/src/lib/wrapper-bus.test.ts +++ b/gui/frontend/src/lib/bus.svelte.test.ts @@ -1,9 +1,9 @@ -import { get } from "svelte/store"; +import { flushSync } from "svelte"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // test-setup.ts mocks this module for everyone else; here it's the real one, // against a WebSocket stand-in the test drives by hand. -type Bus = typeof import("./wrapper-bus"); +type Bus = typeof import("./bus.svelte"); class FakeSocket { static readonly CONNECTING = 0; @@ -58,15 +58,18 @@ function latest(): FakeSocket { const noop = (): void => undefined; +let copies = 0; + async function loadBus(): Promise { - return vi.importActual("./wrapper-bus"); + // A new query is a fresh copy of this module alone. vi.resetModules would + // give it a Svelte of its own, whose signals this file's effects can't see. + return vi.importActual(`./bus.svelte.ts?copy=${String(++copies)}`); } beforeEach(() => { FakeSocket.all = []; vi.useFakeTimers(); vi.stubGlobal("WebSocket", FakeSocket); - vi.resetModules(); }); afterEach(() => { @@ -74,7 +77,7 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe("wrapper-bus", () => { +describe("bus", () => { it("connects to /ws on the page's own host", async () => { await loadBus(); @@ -83,7 +86,7 @@ describe("wrapper-bus", () => { it("subscribes on open to topics asked for before the socket opened", async () => { const bus = await loadBus(); - const unsubscribe = bus.topic("config.state").subscribe(noop); + const unsubscribe = bus.onTopic("config.state", noop); expect(latest().sent).toEqual([]); latest().open(); @@ -98,8 +101,8 @@ describe("wrapper-bus", () => { const bus = await loadBus(); latest().open(); - const a = bus.topic("alerts.state").subscribe(noop); - const b = bus.topic("alerts.state").subscribe(noop); + const a = bus.onTopic("alerts.state", noop); + const b = bus.onTopic("alerts.state", noop); expect(latest().sent).toEqual([ { action: "subscribe", topic: "alerts.state" }, @@ -118,28 +121,30 @@ describe("wrapper-bus", () => { latest().open(); const first: unknown[] = []; - const stopFirst = bus - .topic("network.state") - .subscribe((v) => first.push(v)); + const stopFirst = bus.onTopic("network.state", (v) => first.push(v)); latest().receive({ topic: "network.state", data: { n: 1 } }); latest().receive({ topic: "other.state", data: "ignored" }); - const late = bus.topic("network.state"); - expect(get(late)).toEqual({ n: 1 }); - expect(first).toEqual([null, { n: 1 }]); + const late: unknown[] = []; + const stopLate = bus.onTopic("network.state", (v) => late.push(v)); + expect(late).toEqual([{ n: 1 }]); + expect(first).toEqual([{ n: 1 }]); stopFirst(); + stopLate(); }); it("forgets a topic's value once nobody listens", async () => { const bus = await loadBus(); latest().open(); - const stop = bus.topic("processes.state").subscribe(noop); + const stop = bus.onTopic("processes.state", noop); latest().receive({ topic: "processes.state", data: [1] }); stop(); - expect(get(bus.topic("processes.state"))).toBeNull(); + const seen: unknown[] = []; + bus.onTopic("processes.state", (v) => seen.push(v))(); + expect(seen).toEqual([]); }); it("ignores malformed frames, error answers and binary data", async () => { @@ -148,7 +153,7 @@ describe("wrapper-bus", () => { const warn = vi.spyOn(console, "warn").mockImplementation(noop); const seen: unknown[] = []; - const stop = bus.topic("config.state").subscribe((v) => seen.push(v)); + const stop = bus.onTopic("config.state", (v) => seen.push(v)); latest().receive("{not json"); latest().receive({ error: "unknown_topic", @@ -157,7 +162,7 @@ describe("wrapper-bus", () => { }); latest().emit("message", { data: new ArrayBuffer(4) }); - expect(seen).toEqual([null]); + expect(seen).toEqual([]); expect(warn).toHaveBeenCalledTimes(2); stop(); @@ -167,19 +172,73 @@ describe("wrapper-bus", () => { it("reports the connection state", async () => { const bus = await loadBus(); const states: string[] = []; - const stop = bus.connectionState.subscribe((s) => states.push(s)); + const stop = $effect.root(() => { + $effect(() => { + states.push(bus.connection.state); + }); + }); + flushSync(); latest().open(); + flushSync(); latest().close(); + flushSync(); expect(states).toEqual(["connecting", "open", "closed"]); stop(); }); + it("topicState follows a topic while something reads it", async () => { + const bus = await loadBus(); + latest().open(); + + const state = bus.topicState("network.state"); + expect(state.current).toBeNull(); + expect(latest().sent).toEqual([]); + + const seen: unknown[] = []; + const read = () => + $effect.root(() => { + const value = $derived(state.current); + $effect(() => { + seen.push(value); + }); + }); + + const stop = read(); + flushSync(); + latest().receive({ topic: "network.state", data: { n: 1 } }); + flushSync(); + latest().receive({ topic: "network.state", data: { n: 2 } }); + flushSync(); + expect(seen).toEqual([null, { n: 1 }, { n: 2 }]); + + // Another reader of the topic gets the latest at once. + const other = bus.topicState("network.state"); + const stopOther = $effect.root(() => { + $effect(() => { + seen.push(other.current); + }); + }); + flushSync(); + expect(seen.at(-1)).toEqual({ n: 2 }); + expect(seen).toHaveLength(4); + + // Nobody reads it any more: unsubscribed, and forgotten. + stop(); + stopOther(); + await vi.advanceTimersByTimeAsync(0); + expect(latest().sent).toEqual([ + { action: "subscribe", topic: "network.state" }, + { action: "unsubscribe", topic: "network.state" }, + ]); + expect(state.current).toBeNull(); + }); + it("reconnects with backoff and resubscribes every topic", async () => { const bus = await loadBus(); - const stopA = bus.topic("a.state").subscribe(noop); - const stopB = bus.topic("b.state").subscribe(noop); + const stopA = bus.onTopic("alerts.state", noop); + const stopB = bus.onTopic("network.state", noop); latest().open(); latest().close(); @@ -192,8 +251,8 @@ describe("wrapper-bus", () => { latest().open(); expect(latest().sent).toEqual([ - { action: "subscribe", topic: "a.state" }, - { action: "subscribe", topic: "b.state" }, + { action: "subscribe", topic: "alerts.state" }, + { action: "subscribe", topic: "network.state" }, ]); stopA(); diff --git a/gui/frontend/src/lib/wrapper-bus.ts b/gui/frontend/src/lib/bus.svelte.ts similarity index 65% rename from gui/frontend/src/lib/wrapper-bus.ts rename to gui/frontend/src/lib/bus.svelte.ts index 539a08c..a6170a2 100644 --- a/gui/frontend/src/lib/wrapper-bus.ts +++ b/gui/frontend/src/lib/bus.svelte.ts @@ -1,4 +1,7 @@ -import { readable, type Readable } from "svelte/store"; +// The WebSocket to the host: what it publishes, by topic (the host's +// cmd/.../topics.go lists them), and whether it's connected. +import { createSubscriber } from "svelte/reactivity"; +import type { Topic, TopicMap } from "./apiTypes"; export type ConnectionState = "connecting" | "open" | "closed"; @@ -10,6 +13,11 @@ const BACKOFF_INITIAL_MS = 1_000; // costs nothing, and the page comes back soon after a host restart. const BACKOFF_MAX_MS = 5_000; +// The connection, reactive. +export const connection = $state<{ state: ConnectionState }>({ + state: "connecting", +}); + interface ClientMessage { action: "subscribe" | "unsubscribe"; topic: string; @@ -21,10 +29,8 @@ type ServerMessage = | { topic: string; data: unknown } | { error: string; message: string; topic?: string }; -class WrapperBus { +class Bus { private socket: WebSocket | null = null; - private state: ConnectionState = "connecting"; - private stateListeners = new Set<(s: ConnectionState) => void>(); private topicListeners = new Map void>>(); private latest = new Map(); private backoffMs = BACKOFF_INITIAL_MS; @@ -34,18 +40,14 @@ class WrapperBus { this.connect(); } - subscribeState(listener: (s: ConnectionState) => void): () => void { - listener(this.state); - this.stateListeners.add(listener); - return () => this.stateListeners.delete(listener); - } - subscribeTopic( topic: string, listener: (value: unknown) => void, ): () => void { let listeners = this.topicListeners.get(topic); if (!listeners) { + // Not reactive: nothing renders from the listeners themselves. + // eslint-disable-next-line svelte/prefer-svelte-reactivity listeners = new Set(); this.topicListeners.set(topic, listeners); this.send({ action: "subscribe", topic }); @@ -66,12 +68,12 @@ class WrapperBus { } private connect(): void { - this.setState("connecting"); + connection.state = "connecting"; const socket = new WebSocket(this.url); this.socket = socket; socket.addEventListener("open", () => { - this.setState("open"); + connection.state = "open"; this.backoffMs = BACKOFF_INITIAL_MS; for (const topic of this.topicListeners.keys()) { this.send({ action: "subscribe", topic }); @@ -83,7 +85,7 @@ class WrapperBus { }); socket.addEventListener("close", () => { - this.setState("closed"); + connection.state = "closed"; this.socket = null; this.scheduleReconnect(); }); @@ -102,11 +104,6 @@ class WrapperBus { }, this.backoffMs); } - private setState(state: ConnectionState): void { - this.state = state; - for (const listener of this.stateListeners) listener(state); - } - private send(message: ClientMessage): void { if (this.socket?.readyState === WebSocket.OPEN) { this.socket.send(JSON.stringify(message)); @@ -119,11 +116,11 @@ class WrapperBus { try { parsed = JSON.parse(raw) as ServerMessage; } catch { - console.warn("wrapper-bus: malformed frame", raw); + console.warn("bus: malformed frame", raw); return; } if ("error" in parsed) { - console.warn("wrapper-bus: server error", parsed); + console.warn("bus: server error", parsed); return; } const listeners = this.topicListeners.get(parsed.topic); @@ -133,15 +130,48 @@ class WrapperBus { } } -const bus = new WrapperBus(DEFAULT_URL); +const bus = new Bus(DEFAULT_URL); -export const connectionState: Readable = - readable("connecting", (set) => bus.subscribeState(set)); +// Calls fn with each message on a topic, starting with the latest one if it's +// known, until the returned function is called. +export function onTopic( + name: K, + fn: (data: TopicMap[K]) => void, +): () => void { + return bus.subscribeTopic(name, (data) => { + fn(data as TopicMap[K]); + }); +} -export function topic(name: string): Readable { - return readable(null, (set) => { - return bus.subscribeTopic(name, (value) => { - set(value as T); +// A topic's latest message as current, null before the first. The host sends +// the topic only while an effect or template reads it. +export function topicState( + name: K, +): { readonly current: TopicMap[K] | null } { + let value: TopicMap[K] | null = null; + + const track = createSubscriber((update) => { + // A message known already arrives within onTopic, before anyone has read + // the value: nothing to update. + let started = false; + + const stop = onTopic(name, (data) => { + value = data; + if (started) update(); }); + started = true; + + return () => { + stop(); + value = null; + }; }); + + return { + get current() { + track(); + + return value; + }, + }; } diff --git a/gui/frontend/src/lib/checklist/checklist.svelte.ts b/gui/frontend/src/lib/checklist/checklist.svelte.ts index 7ecafde..6ae3af8 100644 --- a/gui/frontend/src/lib/checklist/checklist.svelte.ts +++ b/gui/frontend/src/lib/checklist/checklist.svelte.ts @@ -15,7 +15,7 @@ import { config, type CameraDoc } from "../config.svelte"; import { network } from "../network.svelte"; import { hostAlerts } from "../alerts/hostAlerts.svelte"; -import { connectionState, type ConnectionState } from "../wrapper-bus"; +import { connection, type ConnectionState } from "../bus.svelte"; export type Status = "done" | "todo" | "attention" | "recheck"; @@ -415,9 +415,7 @@ export function restartChecklist(): void { $effect.root(() => { $effect(() => { - return connectionState.subscribe((state) => { - checklist.connection = state; - }); + checklist.connection = connection.state; }); // Each config file keeps its own ticks: load them when the file changes diff --git a/gui/frontend/src/lib/config.svelte.ts b/gui/frontend/src/lib/config.svelte.ts index b7a572e..b35cc76 100644 --- a/gui/frontend/src/lib/config.svelte.ts +++ b/gui/frontend/src/lib/config.svelte.ts @@ -14,7 +14,7 @@ import type { ConfigState, Section, } from "./apiTypes"; -import { topic } from "./wrapper-bus"; +import { onTopic } from "./bus.svelte"; import { refreshFieldMarkings } from "./geometry.svelte"; import { app } from "./text/app"; @@ -216,9 +216,7 @@ $effect.root(() => { // unless our own edit is mid-flight and about to report that revision, or // waiting to be retried (a reload would drop it). $effect(() => { - return topic("config.state").subscribe((state) => { - if (!state) return; - + return onTopic("config.state", (state) => { config.state = state; if ( diff --git a/gui/frontend/src/lib/hostVersion.svelte.ts b/gui/frontend/src/lib/hostVersion.svelte.ts index 48c1a98..6ac4cf1 100644 --- a/gui/frontend/src/lib/hostVersion.svelte.ts +++ b/gui/frontend/src/lib/hostVersion.svelte.ts @@ -1,9 +1,10 @@ // Notices the host being upgraded under an open page: the bundle comes from // the host's own binary, so the version it reported when this page connected // is the bundle's. A different one after a reconnect means the page is stale. +import { untrack } from "svelte"; import { requestJSON } from "./api"; import type { HealthResponse } from "./apiTypes"; -import { connectionState } from "./wrapper-bus"; +import { connection } from "./bus.svelte"; export const hostVersion = $state<{ // The version this page was loaded from. @@ -33,8 +34,6 @@ export async function checkHostVersion(): Promise { $effect.root(() => { $effect(() => { - return connectionState.subscribe((state) => { - if (state === "open") void checkHostVersion(); - }); + if (connection.state === "open") void untrack(checkHostVersion); }); }); diff --git a/gui/frontend/src/lib/layout/Shell.svelte b/gui/frontend/src/lib/layout/Shell.svelte index d166594..f86f467 100644 --- a/gui/frontend/src/lib/layout/Shell.svelte +++ b/gui/frontend/src/lib/layout/Shell.svelte @@ -1,6 +1,6 @@ diff --git a/gui/frontend/src/lib/api.test.ts b/gui/frontend/src/lib/api.test.ts new file mode 100644 index 0000000..0f38ec2 --- /dev/null +++ b/gui/frontend/src/lib/api.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { api, apiPath, unwrap } from "./api"; + +function answer(status: number, body: string, type = "application/json"): void { + vi.stubGlobal( + "fetch", + vi.fn(() => + Promise.resolve( + new Response(body, { + status, + statusText: "Bad Gateway", + headers: { "Content-Type": type }, + }), + ), + ), + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("unwrap", () => { + it("gives the answer's data", async () => { + answer(200, '["config.state"]'); + expect(await unwrap(api.GET("/api/topics"))).toEqual(["config.state"]); + }); + + it("throws the host's message, one issue per line if it lists them", async () => { + answer( + 400, + '{"error":"invalid","message":"2 problems","issues":["a","b"]}', + ); + await expect(unwrap(api.GET("/api/config"))).rejects.toThrow("a\nb"); + + answer(404, '{"error":"not_found","message":"no such camera"}'); + await expect(unwrap(api.GET("/api/config"))).rejects.toThrow( + "no such camera", + ); + }); + + it("throws what a proxy answered, or else the status", async () => { + answer(502, "upstream is down", "text/plain"); + await expect(unwrap(api.GET("/api/config"))).rejects.toThrow( + "upstream is down", + ); + + answer(502, "", "text/plain"); + await expect(unwrap(api.GET("/api/config"))).rejects.toThrow( + "502 Bad Gateway", + ); + }); + + it("rejects when the host doesn't answer", async () => { + vi.stubGlobal( + "fetch", + vi.fn(() => Promise.reject(new TypeError("Failed to fetch"))), + ); + await expect(unwrap(api.GET("/api/health"))).rejects.toThrow( + "Failed to fetch", + ); + }); +}); + +describe("apiPath", () => { + it("fills in a path's parameters", () => { + expect( + apiPath("/api/snapshots/{id}/{view}", { id: 0, view: "pixels.corner" }), + ).toBe("/api/snapshots/0/pixels.corner"); + expect(apiPath("/ws/video/{id}", { id: 3 })).toBe("/ws/video/3"); + expect(() => apiPath("/ws/video/{id}")).toThrow("no id"); + }); +}); diff --git a/gui/frontend/src/lib/api.ts b/gui/frontend/src/lib/api.ts index 7bfd919..a283980 100644 --- a/gui/frontend/src/lib/api.ts +++ b/gui/frontend/src/lib/api.ts @@ -1,56 +1,56 @@ -// Shared fetch helpers, used by every module that owns request state -// (geometry.svelte.ts, App.svelte's snapshot poll): -// the same "set a loading/saving flag, clear the error, run the request, -// catch and format any failure, always clear the flag" and "throw the -// backend's own error text on a non-2xx response" shapes were previously -// hand-repeated at every call site. - -// Runs fn with setLoading(true) for its duration. Clears the error first; -// sets it (formatted the same way everywhere) if fn throws. -export async function withLoadingState( - setLoading: (loading: boolean) => void, - setError: (message: string | null) => void, - fn: () => Promise, -): Promise { - setLoading(true); - setError(null); - - try { - await fn(); - } catch (err) { - setError(err instanceof Error ? err.message : String(err)); - } finally { - setLoading(false); - } -} - +// The host's HTTP API, typed by its OpenAPI spec (generated/api.ts): a wrong +// path, method, parameter or body doesn't compile. +import createClient from "openapi-fetch"; import type { ApiError } from "./apiTypes"; +import type { paths } from "./generated/api"; + +// Call it as api.GET("/api/config"), api.POST("/api/config/load", { body }). +// It rejects only when the host doesn't answer; unwrap also throws for an +// error answer. +export const api = createClient({ + baseUrl: location.origin, + // Looked up per call, so tests can replace it. + fetch: (request) => globalThis.fetch(request), +}); + +// What an error answer carries: the host's error body, or the text of +// something in between, such as a proxy. +type ErrorAnswer = ApiError | string | undefined; + +// The host's error, as text for a banner: each issue on its own line when +// there are several. +export function errorMessage(error: ErrorAnswer, response: Response): string { + if (typeof error === "object") { + return error.issues?.join("\n") ?? error.message; + } -export type { ApiError }; + if (error) return error; -// The host's error for a non-2xx response, as text for a banner: each issue -// on its own line when there are several. -export async function errorMessage(response: Response): Promise { - const text = await response.text(); + return `${String(response.status)} ${response.statusText}`; +} - try { - const body = JSON.parse(text) as ApiError; +// The data of a call's answer, throwing the host's error message if it +// answered with one. +export async function unwrap( + call: Promise<{ data?: T; error?: ErrorAnswer; response: Response }>, +): Promise { + const { data, error, response } = await call; + if (!response.ok) throw new Error(errorMessage(error, response)); - return body.issues?.join("\n") ?? body.message; - } catch { - return text || `${String(response.status)} ${response.statusText}`; - } + return data as T; } -// fetch that throws the host's error message on a non-2xx status. -export async function requestJSON( - url: string, - init?: RequestInit, -): Promise { - const response = await fetch(url, init); - if (!response.ok) { - throw new Error(await errorMessage(response)); - } - - return response; +// One of the spec's paths with its {parameters} filled in, for what isn't +// fetched here: an image's src, a WebSocket. +export function apiPath( + path: keyof paths, + params: Record = {}, +): string { + return path.replace(/\{(\w+)\}/g, (_, name: string) => { + const value = params[name]; + // text-ok: an internal invariant, not shown to users. + if (value === undefined) throw new Error(`${path}: no ${name}`); + + return encodeURIComponent(String(value)); + }); } diff --git a/gui/frontend/src/lib/apiTypes.ts b/gui/frontend/src/lib/apiTypes.ts index d709f66..721552c 100644 --- a/gui/frontend/src/lib/apiTypes.ts +++ b/gui/frontend/src/lib/apiTypes.ts @@ -38,6 +38,7 @@ export type Change = Schemas["ConfigChange"]; export type Section = Change["section"]; export type CameraStatus = Schemas["ConfigCameraStatus"]; export type Warning = Schemas["ConfigWarning"]; +export type PutConfigRequest = Schemas["PutConfigRequest"]; export type RevisionResponse = Schemas["RevisionResponse"]; export type NetworkState = Schemas["NetworkState"]; diff --git a/gui/frontend/src/lib/bus.svelte.ts b/gui/frontend/src/lib/bus.svelte.ts index a6170a2..1e04ea4 100644 --- a/gui/frontend/src/lib/bus.svelte.ts +++ b/gui/frontend/src/lib/bus.svelte.ts @@ -1,13 +1,14 @@ // The WebSocket to the host: what it publishes, by topic (the host's // cmd/.../topics.go lists them), and whether it's connected. import { createSubscriber } from "svelte/reactivity"; +import { apiPath } from "./api"; import type { Topic, TopicMap } from "./apiTypes"; export type ConnectionState = "connecting" | "open" | "closed"; // Same-origin: the Go host serves /ws itself, alongside /api and the frontend. // wss:// when the page itself was loaded over https. -const DEFAULT_URL = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`; +const DEFAULT_URL = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${apiPath("/ws")}`; const BACKOFF_INITIAL_MS = 1_000; // Low, since the host is on the local network: a retry every few seconds // costs nothing, and the page comes back soon after a host restart. diff --git a/gui/frontend/src/lib/cameraSettings.svelte.ts b/gui/frontend/src/lib/cameraSettings.svelte.ts index e2b2ba2..37426f1 100644 --- a/gui/frontend/src/lib/cameraSettings.svelte.ts +++ b/gui/frontend/src/lib/cameraSettings.svelte.ts @@ -7,6 +7,7 @@ // // vision_processor reads camera: only at startup, so nothing here takes // effect until it restarts. +import { api, unwrap } from "./api"; import { config, cameraDoc } from "./config.svelte"; import { fallback, schema } from "./schema.svelte"; import type { VideoDevice } from "./apiTypes"; @@ -168,9 +169,7 @@ export type { VideoDevice } from "./apiTypes"; export async function loadVideoDevices(): Promise { try { - const response = await fetch("/api/capture-devices"); - - return response.ok ? ((await response.json()) as VideoDevice[]) : []; + return await unwrap(api.GET("/api/capture-devices")); } catch { return []; } diff --git a/gui/frontend/src/lib/config.svelte.ts b/gui/frontend/src/lib/config.svelte.ts index b35cc76..1bce6bb 100644 --- a/gui/frontend/src/lib/config.svelte.ts +++ b/gui/frontend/src/lib/config.svelte.ts @@ -3,7 +3,7 @@ // file. Components bind straight into config.doc -- a root effect below // notices any change and debounces a PUT, so no component needs to call a // setter or remember to save. -import { errorMessage, requestJSON } from "./api"; +import { api, errorMessage, unwrap } from "./api"; import type { ApiError, CameraDoc, @@ -12,6 +12,7 @@ import type { ConfigDocument, ConfigResponse, ConfigState, + PutConfigRequest, Section, } from "./apiTypes"; import { onTopic } from "./bus.svelte"; @@ -86,12 +87,20 @@ export function changesFor(section: Section, cameraId?: number): Change[] { ); } +// The GUI edits defaults and each camera's config generically, guided by +// GET /api/schema, where the spec types them key by key; these two are where +// one becomes the other. +export async function getConfig(): Promise { + return (await unwrap(api.GET("/api/config"))) as ConfigResponse; +} + +type SpecDocument = PutConfigRequest["document"]; + export async function loadConfig(): Promise { try { // Before the document, so everything rendered from it has the schema. await loadSchema(); - const response = await requestJSON("/api/config"); - const data = (await response.json()) as ConfigResponse; + const data = await getConfig(); lastSynced = JSON.stringify(data.document); config.doc = data.document; config.revision = data.state.revision; @@ -163,13 +172,14 @@ function retryLater(): void { // False when the host never answered (restarting, network down): the edit // stays unsent. Any answer, even a refusal, counts as delivered. async function putDoc(json: string): Promise { - let response: Response; + let answer; try { - response = await fetch("/api/config", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: `{"revision":${String(config.revision)},"document":${json}}`, + answer = await api.PUT("/api/config", { + body: { + revision: config.revision, + document: JSON.parse(json) as SpecDocument, + }, }); } catch { config.error = app.notSent; @@ -177,18 +187,16 @@ async function putDoc(json: string): Promise { return false; } - if (response.ok) { + if (answer.data) { lastSynced = json; - config.revision = ( - (await response.json()) as { revision: number } - ).revision; + config.revision = answer.data.revision; config.error = null; await refreshFieldMarkings(); return true; } - if (response.status === 409) { + if (answer.response.status === 409) { // Another tab edited first. Take the host's version rather than // clobbering it. config.error = app.editedElsewhere; @@ -199,7 +207,7 @@ async function putDoc(json: string): Promise { // Refused (T4-3: the form keeps the refused value until the next edit). lastSynced = json; - config.error = await errorMessage(response); + config.error = errorMessage(answer.error, answer.response); return true; } @@ -232,22 +240,18 @@ $effect.root(() => { }); }); +// Runs a call that changes the document on the host, then reloads it. A 409 +// comes back for the caller to handle; any other error throws. async function action( - url: string, - init: RequestInit = {}, + call: () => Promise<{ error?: ApiError; response: Response }>, ): Promise { config.busy = true; try { - const response = await fetch(url, init); + const { error, response } = await call(); - if (response.status === 409) { - return (await response.json()) as ConflictResponse; - } - - if (!response.ok) { - throw new Error(await errorMessage(response)); - } + if (response.status === 409 && error) return error; + if (!response.ok) throw new Error(errorMessage(error, response)); config.error = null; @@ -258,14 +262,6 @@ async function action( } } -function post(url: string, body?: unknown): Promise { - return action(url, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: body === undefined ? undefined : JSON.stringify(body), - }); -} - // Writes the working document to vision.yml. A conflict comes back rather // than throwing: "disk_changed" means the file was edited elsewhere and the // caller should let the user choose (state.external now describes it). @@ -275,31 +271,45 @@ export async function saveConfig( await flushEdits(); return guarded(() => - post("/api/config/save", { revision: config.revision, force }), + action(() => + api.POST("/api/config/save", { + body: { revision: config.revision, force }, + }), + ), ); } export async function saveConfigAs(name: string): Promise { await flushEdits(); await guarded(() => - post("/api/config/save-as", { revision: config.revision, name }), + action(() => + api.POST("/api/config/save-as", { + body: { revision: config.revision, name }, + }), + ), ); } export async function loadConfigFrom(name: string): Promise { - await guarded(() => post("/api/config/load", { name })); + await guarded(() => + action(() => api.POST("/api/config/load", { body: { name } })), + ); } // Accepts vision.yml as it is on disk, discarding unsaved edits. export async function reloadFromDisk(): Promise { - await guarded(() => post("/api/config/reload")); + await guarded(() => action(() => api.POST("/api/config/reload"))); } export async function lockCalibration(cameraId: number): Promise { await flushEdits(); const conflict = await guarded(() => - post(`/api/config/cameras/${String(cameraId)}/calibration`), + action(() => + api.POST("/api/config/cameras/{id}/calibration", { + params: { path: { id: cameraId } }, + }), + ), ); if (conflict) config.error = conflict.message; } @@ -307,9 +317,11 @@ export async function lockCalibration(cameraId: number): Promise { export async function unlockCalibration(cameraId: number): Promise { await flushEdits(); await guarded(() => - action(`/api/config/cameras/${String(cameraId)}/calibration`, { - method: "DELETE", - }), + action(() => + api.DELETE("/api/config/cameras/{id}/calibration", { + params: { path: { id: cameraId } }, + }), + ), ); } diff --git a/gui/frontend/src/lib/config.test.ts b/gui/frontend/src/lib/config.test.ts index ad14af0..2302a58 100644 --- a/gui/frontend/src/lib/config.test.ts +++ b/gui/frontend/src/lib/config.test.ts @@ -42,25 +42,22 @@ function sent(method: string, url: string): Request[] { return requests.filter((r) => r.method === method && r.url === url); } -function fakeFetch(url: string, init: RequestInit = {}): Promise { - const method = init.method ?? "GET"; - const body = - typeof init.body === "string" - ? (JSON.parse(init.body) as unknown) - : undefined; +async function fakeFetch(request: globalThis.Request): Promise { + const { method } = request; + const url = new URL(request.url).pathname; + const text = await request.text(); + const body = text ? (JSON.parse(text) as unknown) : undefined; requests.push({ method, url, body }); const queue = replies.get(`${method} ${url}`) ?? []; const answer = queue.length > 1 ? queue.shift() : queue[0]; - if (answer instanceof Error) return Promise.reject(answer); + if (answer instanceof Error) throw answer; const { status, body: out } = answer ?? { status: 200, body: {} }; - return Promise.resolve( - new Response(JSON.stringify(out), { - status, - headers: { "Content-Type": "application/json" }, - }), - ); + return new Response(JSON.stringify(out), { + status, + headers: { "Content-Type": "application/json" }, + }); } async function settle(ms = 0): Promise { @@ -213,9 +210,9 @@ describe("edits", () => { const { config } = await loaded(); let release!: () => void; const gate = new Promise((r) => (release = r)); - vi.mocked(fetch).mockImplementationOnce(async (url, init) => { + vi.mocked(fetch).mockImplementationOnce(async (request) => { await gate; - return fakeFetch(url as string, init); + return fakeFetch(request as globalThis.Request); }); docOf(config).field.fieldLength = 9100; diff --git a/gui/frontend/src/lib/geometry.svelte.ts b/gui/frontend/src/lib/geometry.svelte.ts index 4dc7943..19a9f79 100644 --- a/gui/frontend/src/lib/geometry.svelte.ts +++ b/gui/frontend/src/lib/geometry.svelte.ts @@ -6,7 +6,7 @@ import type { SSL_FieldLineSegmentJson, SSL_FieldCircularArcJson, } from "../proto/vision/ssl_vision_geometry_pb"; -import { requestJSON } from "./api"; +import { api, unwrap } from "./api"; import type { FieldConfig, FieldPreset } from "./apiTypes"; // The editable field (dimensions, optional lines) and a rulebook preset @@ -62,8 +62,7 @@ export const virtualField = $state<{ // Go handler's graceful degradation) just leaves the list empty. export async function loadFieldPresets(): Promise { try { - const response = await requestJSON("/api/geometry/presets"); - virtualField.presets = (await response.json()) as FieldPreset[]; + virtualField.presets = await unwrap(api.GET("/api/geometry/presets")); } catch { // An empty list just means there's nothing to offer. } @@ -73,8 +72,7 @@ export async function loadFieldPresets(): Promise { // regenerates from the field whenever the working document changes. export async function refreshFieldMarkings(): Promise { try { - const response = await requestJSON("/api/geometry"); - const geometry = (await response.json()) as GeometryResponse; + const geometry: GeometryResponse = await unwrap(api.GET("/api/geometry")); virtualField.fieldLines = geometry.geometry?.field?.fieldLines ?? []; virtualField.fieldArcs = geometry.geometry?.field?.fieldArcs ?? []; } catch { diff --git a/gui/frontend/src/lib/hostVersion.svelte.ts b/gui/frontend/src/lib/hostVersion.svelte.ts index 6ac4cf1..3ac90aa 100644 --- a/gui/frontend/src/lib/hostVersion.svelte.ts +++ b/gui/frontend/src/lib/hostVersion.svelte.ts @@ -2,8 +2,7 @@ // the host's own binary, so the version it reported when this page connected // is the bundle's. A different one after a reconnect means the page is stale. import { untrack } from "svelte"; -import { requestJSON } from "./api"; -import type { HealthResponse } from "./apiTypes"; +import { api, unwrap } from "./api"; import { connection } from "./bus.svelte"; export const hostVersion = $state<{ @@ -23,8 +22,7 @@ export function hostUpdated(): boolean { export async function checkHostVersion(): Promise { try { - const response = await requestJSON("/api/health"); - const { version } = (await response.json()) as HealthResponse; + const { version } = await unwrap(api.GET("/api/health")); hostVersion.page ??= version; hostVersion.host = version; } catch { diff --git a/gui/frontend/src/lib/logs/hostLog.svelte.ts b/gui/frontend/src/lib/logs/hostLog.svelte.ts index 8837baa..37d13bc 100644 --- a/gui/frontend/src/lib/logs/hostLog.svelte.ts +++ b/gui/frontend/src/lib/logs/hostLog.svelte.ts @@ -2,8 +2,8 @@ // long-polled while the panel is open, at the panel's own level, so the // host's console level doesn't matter. -import { requestJSON } from "../api"; -import type { LogLevel, LogRecord, LogsResponse } from "../apiTypes"; +import { api, unwrap } from "../api"; +import type { LogLevel, LogRecord } from "../apiTypes"; // Records kept in this tab, and asked for when the panel opens. const KEEP = 1000; @@ -94,14 +94,21 @@ export function followLog(level: LogLevel): () => void { let first = true; while (!stopped()) { - // The first request answers at once, with what's already logged. - const wait = first ? "" : `&wait=${String(WAIT)}`; - const url = `/api/logs?after=${String(after)}&level=${level}&limit=${String(KEEP)}${wait}`; - try { - const page = (await ( - await requestJSON(url, { signal }) - ).json()) as LogsResponse; + const page = await unwrap( + api.GET("/api/logs", { + params: { + query: { + after, + level, + limit: KEEP, + // The first request answers at once, with what's logged. + ...(first ? {} : { wait: WAIT }), + }, + }, + signal, + }), + ); if (stopped()) return; // The first page leaving older records out is expected. diff --git a/gui/frontend/src/lib/logs/hostLog.test.ts b/gui/frontend/src/lib/logs/hostLog.test.ts index aab507c..6cedb59 100644 --- a/gui/frontend/src/lib/logs/hostLog.test.ts +++ b/gui/frontend/src/lib/logs/hostLog.test.ts @@ -18,8 +18,9 @@ function page(from: number, to: number, missed = false): object { return { records, next: to, missed }; } -function fakeFetch(url: string, init: RequestInit = {}): Promise { - urls.push(url); +function fakeFetch(request: Request): Promise { + const url = new URL(request.url); + urls.push(url.pathname + url.search); const next = pages.shift(); if (next instanceof Error) return Promise.reject(next); @@ -27,7 +28,7 @@ function fakeFetch(url: string, init: RequestInit = {}): Promise { return Promise.resolve(new Response(JSON.stringify(next), { status: 200 })); return new Promise((_, reject) => { - init.signal?.addEventListener("abort", () => { + request.signal.addEventListener("abort", () => { reject(new DOMException("aborted", "AbortError")); }); }); diff --git a/gui/frontend/src/lib/processes.svelte.ts b/gui/frontend/src/lib/processes.svelte.ts index 6bd854f..3cf2296 100644 --- a/gui/frontend/src/lib/processes.svelte.ts +++ b/gui/frontend/src/lib/processes.svelte.ts @@ -2,7 +2,7 @@ // processes.state topic. Empty when the host runs none: then each one is // started and restarted by hand. import { onTopic } from "./bus.svelte"; -import { requestJSON } from "./api"; +import { api, unwrap } from "./api"; import type { ProcessStatus } from "./apiTypes"; export type { ProcessStatus }; @@ -49,10 +49,9 @@ export function lastLine(p: ProcessStatus): string { } export async function restartProcess(cameraId: number): Promise { - const response = await requestJSON( - `/api/processes/${String(cameraId)}/restart`, - { method: "POST" }, + processes.list = await unwrap( + api.POST("/api/processes/{id}/restart", { + params: { path: { id: cameraId } }, + }), ); - - processes.list = (await response.json()) as ProcessStatus[]; } diff --git a/gui/frontend/src/lib/report/hostSystem.svelte.ts b/gui/frontend/src/lib/report/hostSystem.svelte.ts index 7efce7d..ce841b7 100644 --- a/gui/frontend/src/lib/report/hostSystem.svelte.ts +++ b/gui/frontend/src/lib/report/hostSystem.svelte.ts @@ -2,7 +2,7 @@ // menu's issue link. Loaded again each time either opens: a restarted host // may be a different build. -import { requestJSON } from "../api"; +import { api, unwrap } from "../api"; import type { SystemInfo } from "../apiTypes"; export const hostSystem = $state<{ @@ -12,9 +12,7 @@ export const hostSystem = $state<{ export async function loadHostSystem(): Promise { try { - hostSystem.info = (await ( - await requestJSON("/api/system") - ).json()) as SystemInfo; + hostSystem.info = await unwrap(api.GET("/api/system")); hostSystem.error = null; } catch (err) { hostSystem.error = err instanceof Error ? err.message : String(err); diff --git a/gui/frontend/src/lib/report/systemReport.test.ts b/gui/frontend/src/lib/report/systemReport.test.ts index 5c78b0a..df73d9e 100644 --- a/gui/frontend/src/lib/report/systemReport.test.ts +++ b/gui/frontend/src/lib/report/systemReport.test.ts @@ -25,19 +25,21 @@ describe("buildReport", () => { }); it("asks for the configuration only when it's included", async () => { - const fetch = vi.fn<(url: string) => Promise>(() => + const fetch = vi.fn<(request: Request) => Promise>(() => Promise.resolve(new Response(JSON.stringify([]))), ); vi.stubGlobal("fetch", fetch); const without = await buildReport(); - const urls = fetch.mock.calls.map(([url]) => url); + const paths = () => + fetch.mock.calls.map(([request]) => new URL(request.url).pathname); + const urls = paths(); expect(urls).toContain("/api/alerts"); expect(urls).not.toContain("/api/config"); expect(without).not.toHaveProperty("config"); const report = await buildReport({ includeConfig: true }); - expect(fetch.mock.calls.map(([url]) => url)).toContain("/api/config"); + expect(paths()).toContain("/api/config"); expect(report.config).toEqual([]); }); diff --git a/gui/frontend/src/lib/report/systemReport.ts b/gui/frontend/src/lib/report/systemReport.ts index 661c290..6e7f938 100644 --- a/gui/frontend/src/lib/report/systemReport.ts +++ b/gui/frontend/src/lib/report/systemReport.ts @@ -7,7 +7,8 @@ // vision_processor's own state (its logs, its announced config) isn't in it // yet. -import { requestJSON } from "../api"; +import { api, unwrap } from "../api"; +import { getConfig } from "../config.svelte"; import type { ConfigResponse, HostAlert, @@ -48,9 +49,9 @@ export function isUnavailable(value: object): value is Unavailable { return "error" in value && typeof value.error === "string"; } -async function fetchOr(url: string): Promise { +async function orUnavailable(answer: Promise): Promise { try { - return (await (await requestJSON(url)).json()) as T; + return await answer; } catch (err) { return { error: err instanceof Error ? err.message : String(err) }; } @@ -166,10 +167,10 @@ export async function buildReport( ): Promise { const now = new Date(); const [host, network, alerts, config, browserInfo] = await Promise.all([ - fetchOr("/api/system"), - fetchOr("/api/network"), - fetchOr("/api/alerts"), - options.includeConfig ? fetchOr("/api/config") : undefined, + orUnavailable(unwrap(api.GET("/api/system"))), + orUnavailable(unwrap(api.GET("/api/network"))), + orUnavailable(unwrap(api.GET("/api/alerts"))), + options.includeConfig ? orUnavailable(getConfig()) : undefined, browser(), ]); diff --git a/gui/frontend/src/lib/schema.svelte.ts b/gui/frontend/src/lib/schema.svelte.ts index ed9b963..3d21da1 100644 --- a/gui/frontend/src/lib/schema.svelte.ts +++ b/gui/frontend/src/lib/schema.svelte.ts @@ -3,7 +3,7 @@ // whether a change needs a restart. The one copy of what src/Resources.cpp // does with config.yml, so nothing here repeats it. loadConfig loads it before // the document, so anything rendered from the document can rely on it. -import { requestJSON } from "./api"; +import { api, unwrap } from "./api"; import type { Setting, SettingsSchema as Schema } from "./apiTypes"; // Each setting's type, fallback, bounds and when a change takes effect: the @@ -22,10 +22,9 @@ let loading: Promise | null = null; // Loads the schema once; later calls wait on the same request. A failure is // thrown to the caller and retried on the next call. export function loadSchema(): Promise { - loading ??= requestJSON("/api/schema") - .then((response) => response.json()) + loading ??= unwrap(api.GET("/api/schema")) .then((value) => { - schema.value = value as Schema; + schema.value = value; }) .catch((err: unknown) => { loading = null; diff --git a/gui/frontend/src/lib/video/videoStream.ts b/gui/frontend/src/lib/video/videoStream.ts index f6b9aac..ad7d1d5 100644 --- a/gui/frontend/src/lib/video/videoStream.ts +++ b/gui/frontend/src/lib/video/videoStream.ts @@ -8,6 +8,7 @@ // falls more than maxLag behind the newest frame, and trims what's been // watched so memory stays bounded. +import { apiPath } from "../api"; import { video as text } from "../text/video"; export type Mode = "full" | "keyframes"; @@ -97,7 +98,7 @@ export class VideoStream { private connect(): void { const scheme = location.protocol === "https:" ? "wss" : "ws"; const ws = new WebSocket( - `${scheme}://${location.host}/ws/video/${String(this.cameraId)}?mode=${this.mode}`, + `${scheme}://${location.host}${apiPath("/ws/video/{id}", { id: this.cameraId })}?mode=${this.mode}`, ); ws.binaryType = "arraybuffer"; From 5ab223b6af0996017ebdbf66db518e0da26f9705 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 12:54:06 -0500 Subject: [PATCH 17/35] architecture documentation updates --- .github/workflows/release.yml | 3 +- gui/ARCHITECTURE.md | 80 +++++++++++++++++++-------- gui/README.md | 40 ++++++++++---- gui/REVIEW.md | 25 ++++++--- gui/frontend/e2e/smoke.spec.ts | 9 ++- gui/frontend/src/lib/config.svelte.ts | 19 ++++++- gui/frontend/src/lib/config.test.ts | 52 +++++++++++++++++ gui/packaging/nfpm.yaml | 6 +- gui/packaging/release-notes.md | 6 ++ 9 files changed, 192 insertions(+), 48 deletions(-) create mode 100644 gui/packaging/release-notes.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 444344a..dcea84f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,5 +54,6 @@ jobs: run: | prerelease=() case "$GITHUB_REF_NAME" in *-*) prerelease=(--prerelease) ;; esac - gh release create "$GITHUB_REF_NAME" --draft "${prerelease[@]}" --verify-tag --generate-notes \ + gh release create "$GITHUB_REF_NAME" --draft "${prerelease[@]}" --verify-tag \ + --notes-file gui/packaging/release-notes.md --generate-notes \ gui/bin/release/*.tar.gz gui/bin/release/*-bin gui/bin/release/*.deb gui/bin/release/SHA256SUMS diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index 674735f..f045db6 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -10,15 +10,16 @@ over multicast, and serves the frontend, a JSON API, and a WebSocket for live up ## System overview -A venue runs one or more vision_processor instances, one per camera. Each instance shares a filesystem with the -gui host (debug images in `img/`, the instance's generated `config.yml`) and exchanges SSL vision protocol messages -with it over the same multicast group the rest of the league uses. +A venue runs one or more vision_processor instances, one per camera, on the gui host's machine or others. Each +exchanges SSL vision protocol messages with the host over the same multicast group the rest of the league uses. One +on the host's own machine also shares files with it: debug images in `img/`, and its generated `config.yml`. ```mermaid graph LR - subgraph Venue Host + VP1["vision_processor cam 1"] + + subgraph Host machine VP0["vision_processor cam 0"] - VP1["vision_processor cam 1"] FS[("shared filesystem\nimg/, config.yml")] end @@ -26,9 +27,9 @@ graph LR MC(("multicast\n224.5.23.2:10006")) Browser["Browser UI"] - VP0 -->|"detections"| MC - VP1 -->|"detections"| MC - MC -->|"calibration"| GUI + VP0 -->|"detections, calibration,\nannounce"| MC + VP1 -->|"detections, calibration,\nannounce"| MC + MC --> GUI GUI -->|"field template,\nmerged wrapper packet"| MC MC -->|"field template"| VP0 MC -->|"field template"| VP1 @@ -38,15 +39,16 @@ graph LR GUI --> Browser ``` -The gui host does not talk to a vision_processor instance directly. Both sides only ever speak to the multicast +The gui host does not talk to a vision_processor instance directly (with `-runCameras` it starts them, and hands +each its config file). Both sides only ever speak to the multicast group, the same way any other league consumer would. This keeps the host interchangeable with the legacy `geom_publisher.py` service from the vision_processor's point of view. The browser talks to the gui host over HTTP and a WebSocket instead, covered under HTTP API and WebSocket protocol below. ## Process layout -`ssl-vision-processor-gui` is one process with seven concurrent responsibilities, wired together in -`cmd/ssl-vision-processor-gui/main.go`. +`ssl-vision-processor-gui` is one process running these concurrently, wired together in +`cmd/ssl-vision-processor-gui/main.go`. It claims its port first and starts nothing else if that fails. ```mermaid graph TD @@ -57,6 +59,8 @@ graph TD tracker["autoref tracker multicast\ngoroutine"] publish["geometry publish loop\ngoroutine, 1Hz"] watch["vision.yml watcher\ngoroutine, 1Hz"] + house["housekeeping loop\ngoroutine, 1Hz"] + procs["supervisor, -runCameras only\ngoroutine"] live["live field publish loop\ngoroutine, 60Hz while watched"] main --> http @@ -66,16 +70,23 @@ graph TD main --> publish main --> watch main --> live + main --> house + main --> procs vision -- "Absorb(calib)" --> Geometry publish -- "Encoded()" --> Geometry http -- "reads/writes" --> Store watch -- "checkDisk()" --> Store Store -- "ApplyConfig / SetLocked" --> Geometry - Store -- "SetAddress" --> vision - Store -- "SetAddress" --> gc - Store -- "SetAddress" --> tracker + house -- "addresses, interfaces" --> vision + house -- "addresses, interfaces" --> gc + house -- "addresses, interfaces" --> tracker + Store -- "Sync" --> procs ``` +The housekeeping loop follows the network and the machine (interfaces, suspends, the height table) and publishes +status to browsers. It has its own clock so that a slow step can't delay publishing geometry. An edit to an address +applies at once; the loop is what catches everything else. + The goroutines share one `*config.Store` and one `*geometry.Geometry`, each guarded by its own mutex. The store pushes into the geometry, never the other way around. Shutdown is graceful: an `os.Interrupt`/`SIGTERM` cancels a shared context, the HTTP server drains in-flight requests, and `main` waits for the other goroutines to exit @@ -92,6 +103,10 @@ before returning. | `internal/multicast` | The vision, game controller, autoref tracker, and video sockets: interface selection, reopening on changes, retrying while unhealthy, suspend detection. | | `internal/api` | Typed route registration and the OpenAPI 3.1 spec reflected from the handlers' own types and doc comments. | | `internal/hub` | In-process topic pub/sub and the `/ws` WebSocket handler. | +| `internal/httpjson` | The JSON error body and its codes. | +| `internal/origins` | Which browser pages and host names may use the API. | +| `internal/alerts` | Every problem the host can see: which, how serious, and the facts behind each. | +| `internal/discovery` | vision_processor instances, from their announces. | | `internal/livefield` | The latest detection frame per camera and tracked frame per autoref, for the Live Field page. | | `internal/detections` | Which camera_ids the vision socket hears, from which address, at what rate. Feeds the Camera Layout page. | | `internal/referee` | The current match's teams, from the game controller, and their robot heights from `bot_heights_file`. | @@ -134,13 +149,31 @@ another host's mistake) would otherwise stop that camera until someone unlocked The host drops its own looped-back packets by sender address: every send socket records its local address (`multicast.IsOwn`), which is exactly what its echoes arrive from. Everything else is compared by IP and port, so two programs on one machine are told apart. `internal/peers` watches who sends each camera's calibration, -detections and video, the game controller's referee messages, and field geometry, which only this host should +detections and video, each instance name, the game controller's referee messages, and field geometry, which only this host should publish once a second. A second sender is logged once when it appears (`several senders claim the same thing`, with each sender's IP, port, hostname from reverse DNS, and whether it's this machine) and again when it's gone, -and served as a `sender_conflict` alert on `network.state`/`GET /api/network`: an error for calibration and -field geometry, a warning for the game controller and video, and an error for every kind on a competition field. Two vision_processors on one +and served as a `sender_conflict` alert on `network.state`/`GET /api/network`: an error for calibration, +field geometry and instance names, a warning for the game controller and video, and an error for every kind on a competition field. Two vision_processors on one machine both send from the vision port, so they share an address and can't be told apart this way. +A vision_processor's video streamer opens a new port whenever the streamed view changes size, so for video a sender +that stops as another begins on its IP is the same program; two that keep sending are a conflict. + +Every endpoint also notes which interface each packet arrives on. One sender heard on several at once (two +interfaces on one network) is logged once and raises a `duplicate_packets` alert, one per set of interfaces. + +The teams come from one game controller, the first heard, until it's silent for 3 s (`referee.Source`). Others still +count towards the conflict alert. + +## Discovery + +vision_processor announces itself on the vision group about once a second, as an `SSL_WrapperPacket` with `config` +set. `internal/discovery` keeps the latest per `SSL_VPConfig.instance`: live while heard within 3 s, forgotten after +30 s. `GET /api/instances` and `instances.state` serve them; no page shows them yet. Two senders of one instance name +are a `sender_conflict`. Packets are told apart by `config` being present, not by `source`: the host's own geometry +packets have the same `source`. vision_processor builds its announce once, at startup, and sends it between frames, so +one whose camera blocks doesn't announce, and a reloaded config isn't reflected. + ## Configuration: vision.yml `vision.yml` is the one file the host owns. It holds the field template, shared `defaults` in vision_processor's @@ -270,7 +303,7 @@ when the problem changes. The host also notices a suspend: each second it compar counting while suspended, with `CLOCK_MONOTONIC`, which doesn't. Neither jumps for NTP or clock changes, so a gap means the machine slept, and every socket is reopened. -The Camera Settings tab edits each camera's `camera:` block, shown with vision_processor's own fallbacks applied +The Camera page edits each camera's `camera:` block, shown with vision_processor's own fallbacks applied (`src/driver/cameradriver.cpp`; an unset driver means SPINNAKER; a new config says DUMMY, the protocol's "no camera"). Controls follow the driver: an index for SPINNAKER, MVIMPACT and DC1394, plus a serial number for SPINNAKER, a path for OPENCV, gamma hidden for MVIMPACT, and the OUTDOOR and INDOOR auto white balance profiles only for SPINNAKER. The serial and the path are @@ -299,7 +332,8 @@ None of the spec's inputs or outputs are committed; `make` builds them. `interna Go doc comments (`go generate`, from the source), `gui/openapi.json` comes from the host itself (`-openapi `, which writes the spec and exits), the frontend's API types (`frontend/src/lib/generated/api.ts`) from that by openapi-typescript, and the viewer (`internal/api/viewer/`) is Redoc's bundle fetched at a pinned version and checked -against its SHA-256. The frontend imports its API types from `frontend/src/lib/apiTypes.ts`, never a hand copy. +against its SHA-256. The frontend imports its API types from `frontend/src/lib/apiTypes.ts`, never a hand copy, +and calls the API through `frontend/src/lib/api.ts`, a client typed by the same file. A handler takes one input struct and returns one output. Input fields tagged `path:`, `query:` or `header:` are parameters, and a field tagged `body:""` is the body; an input with only JSON fields is itself the @@ -314,7 +348,8 @@ frontend, with a fallback to `index.html` for client side routes. Every error is JSON, `{"error": code, "message": text, "issues": [...]}` (`internal/httpjson`). Clients branch on `error`: `bad_request`, `invalid` (with one `issues` entry per problem), `not_found`, `stale`, -`disk_changed`, `no_live_calibration`, `precondition`, `unsupported_media`, `cross_origin`, `internal`. +`disk_changed`, `no_live_calibration`, `device_conflict`, `no_camera`, `precondition`, `unsupported_media`, +`cross_origin`, `unknown_host`, `internal`. Request bodies must be `Content-Type: application/json` (PATCH also takes `application/merge-patch+json`), and unknown keys are rejected, so a misspelled key fails instead of silently resetting the value it named. @@ -405,7 +440,7 @@ burst of packets. Packets are reassembled into frames (RFC 6184 single units, STAP-A, FU-A; there is no SDP, so payload type and packetization mode 1 are assumed). After a lost packet, frames are dropped until the next keyframe, since the ones -in between can't decode. A new SSRC means the encoder restarted, which it does whenever the streamed view changes +in between can't decode. Packets at or behind the newest are ignored: copies, or too late. A new SSRC means the encoder restarted, which it does whenever the streamed view changes size; the parameter sets that come with the next keyframe start a new init segment. Frames are muxed as fragmented MP4, one per segment, timed by arrival rather than the encoder's nominal 30 fps. @@ -424,8 +459,7 @@ regenerates them as an ordinary build prerequisite. See `gui/DEVELOPMENT.md` for ## Not yet built -- **Discovery.** Parsing `SSL_VPConfig` announces off multicast into an instance table. The C++ side does not - emit these yet. +- **Discovery page.** Showing the announced instances, and comparing each one's config with what it should be. - **Host owned config push.** Diffing an instance's announced config against a desired one and pushing the difference, rather than regenerating a local `config.yml` as the host does today. This also needs a way to ask a running instance to recalibrate. diff --git a/gui/README.md b/gui/README.md index e3ee8aa..aa349b1 100644 --- a/gui/README.md +++ b/gui/README.md @@ -44,6 +44,17 @@ These steps are for 64-bit Linux, tested on Ubuntu 24.04. 4. Save when the wizard asks. **The GUI publishes nothing on the network until this first save**, so you can try it on a live network without disturbing anyone. Until then, an alert reminds you that it isn't publishing. +5. Connect your cameras. The GUI doesn't include vision_processor, which does the camera processing, so first + build it from source: see the [main README](https://github.com/RoboCup-SSL/ssl-vision-processor#readme). Then: + + - **A webcam or other camera on this machine:** stop the GUI and start it again with `-runCameras`, which runs + vision_processor for you. Then choose the camera's driver on the Camera page. See + [Running a webcam with the GUI](#running-a-webcam-with-the-gui). + - **Cameras on other machines:** start vision_processor there. The Layout page shows each one it hears, once + they're on the same network and vision address. See [Cameras](#cameras). + + The Setup Checklist at the top of the page covers the rest: the image, calibration, colors and teams. + The program stops when you close the terminal or press Ctrl+C, and picks up where it left off the next time you run it. To have it start with the machine, [install the package](#installing-the-package). @@ -263,8 +274,8 @@ There are two ways to run the cameras: camera 0 has no camera selected, so it isn't started yet. Choose OPENCV as its driver on the Camera page and it starts on the first webcam (`/dev/video0`). -3. Camera Settings shows each vision_processor's state, its last lines of output, and a Restart button. Choosing the - number of cameras on the Camera Layout page adds or removes cameras to match, each with its own config file. +3. The Camera page shows each vision_processor's state, its last lines of output, and a Restart button. Choosing the + number of cameras on the Layout page adds or removes cameras to match, each with its own config file. Each camera needs its own capture device. If two cameras name the same one, only the lower camera ID starts, and an alert says which. The GUI doesn't know about a vision_processor started some other way: if one already has the @@ -277,16 +288,21 @@ files stay apart. Its snapshots go to its own folder in the image folder, `img/c Check the GUI's Alerts page first; most alerts have a how-to. The printed log file has the details. -| Problem | Likely cause and fix | -| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `can't open the GUI on …` and it exits | Something else is using the port, often another copy of the GUI. Stop it, or use another `-address`. | -| `no default config folder, set -configDir` | `HOME` isn't set, as in some service environments. Set `-configDir`, `-logFile`, and `-imgDir`. | -| Page doesn't load from another machine | It allows this machine only: check the address it printed, or the service's [setting](#installing-the-package). Then the firewall, if it's on; see [Network setup](#network-setup). | -| "This host doesn't answer to..." | You're using a name the GUI doesn't know. Add it with `-allowHost`. | -| Nothing is published | First run: save once. Then check the Alerts page. | -| Your old settings seem to be gone | The GUI no longer reads `vision.yml` from the current folder. Pass `-configDir .` from that folder. | -| `config_path: ... want a file name` | `vision.yml` names a full path. Move the file to the config folder and use only its name. | -| `-runCameras needs vision_processor on PATH` | Build vision_processor and add its folder to `PATH`; see [Cameras](#cameras). | +| Problem | Likely cause and fix | +| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `can't open the GUI on …` and it exits | Something else is using the port, often another copy of the GUI. Stop it, or use another `-address`. | +| `no default config folder, set -configDir` | `HOME` isn't set, as in some service environments. Set `-configDir`, `-logFile`, and `-imgDir`. | +| Page doesn't load from another machine | It allows this machine only: check the address it printed, or the service's [setting](#installing-the-package). Then the firewall, if it's on; see [Network setup](#network-setup). | +| "This host doesn't answer to..." | You're using a name the GUI doesn't know. Add it with `-allowHost`. | +| Nothing is published | First run: save once. Then check the Alerts page. | +| Your old settings seem to be gone | The GUI no longer reads `vision.yml` from the current folder. Pass `-configDir .` from that folder. | +| `config_path: ... want a file name` | `vision.yml` names a full path. Move the file to the config folder and use only its name. | +| `-runCameras needs vision_processor on PATH` | Build vision_processor and add its folder to `PATH`; see [Cameras](#cameras). | +| "No camera selected" | A new configuration doesn't guess your camera. Choose its driver on the Camera page. | +| vision_processor keeps exiting | Read its last output, on the Camera page. Usually the wrong driver, a device that's missing or already open in another program, or a driver the build doesn't include. A webcam needs OPENCV and its `/dev/video` path. | +| Nothing heard from a camera | Check its vision_processor is running, on the same vision address, and on a network this machine uses; see [Network setup](#network-setup). The Alerts page says which sockets are silent. | +| No video in Chromium or Firefox | They need the system's H.264 libraries; Google Chrome includes its own. See [Browser](#browser). | +| "The same packets arrive on..." | Two of this machine's interfaces reach the same network. Leave only the field network's on, on the Network page. | ## Upgrading diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 19f4494..3a87869 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,11 +27,12 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-25. **Open** 25 · **Partial** 4 · **Done** 40 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 21 · **Partial** 4 · **Done** 44 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T3-2 is awaiting commit; with it the API freeze (T3-1, T3-2, T3-3) is done. -1. T1-3, T6-1, T6-5, T4-3. +All blockers are fixed. T1-3, T6-1, T6-5 and T4-3 are awaiting commit; the API freeze is done. +1. T1-5: decide on `flake.lock`. +2. T7-1, T7-2, T7-4: tests (can trail the tag). **Needs the lab PoE machine:** T2-10. @@ -39,7 +40,7 @@ All blockers are fixed. T3-2 is awaiting commit; with it the API freeze (T3-1, T |---|---|---|---|---| | T1-1 | blocker | Claude (Will commits) | 18 MB binary tracked in git | done | | T1-2 | major | Claude | release tag not gated on `make check` / e2e | done | -| T1-3 | major | Claude + Will | package description promises a VP package that doesn't exist | open | +| T1-3 | major | Claude + Will | package description promises a VP package that doesn't exist | done | | T1-4 | minor | Claude | tarball and `-bin` amd64 only (absorbs L-3) | open | | T1-5 | minor | Claude | stale toolchain and dependencies | partial | | T1-6 | minor | Claude | CI skips the `v2.0-alpha` branch | open | @@ -65,7 +66,7 @@ All blockers are fixed. T3-2 is awaiting commit; with it the API freeze (T3-1, T | T3-5 | nit | Will | OpenAPI tag descriptions | done | | T4-1 | blocker | Will | "Temporary debug utilities" on every page | done | | T4-2 | major | Will | edits lost while host unreachable | done | -| T4-3 | minor | Will | rejected value stays in the form | open | +| T4-3 | minor | Will | rejected value stays in the form | done | | T4-4 | minor | Will | no stale-frontend detection | done | | T4-5 | minor | Will | large components | open | | T4-6 | minor | Will | bus still on `svelte/store` | done | @@ -82,11 +83,11 @@ All blockers are fixed. T3-2 is awaiting commit; with it the API freeze (T3-1, T | T5-9 | minor | Will | Camera page edits undeliverable settings | open | | T5-10 | — | — | phone widths | dropped | | T5-11 | nit | Will | Gamma toggle label | done | -| T6-1 | major | Claude (Will reviews) | `ARCHITECTURE.md` drift | open | +| T6-1 | major | Claude (Will reviews) | `ARCHITECTURE.md` drift | done | | T6-2 | minor | Claude (Will decides) | `CLAUDE.md` vs `ARCHITECTURE.md` split | open | | T6-3 | minor | Claude | frontend README describes old tabs | done | | T6-4 | minor | Claude | README relative links break when shipped | done | -| T6-5 | major | Claude + Will | quick start stops at first save | open | +| T6-5 | major | Claude + Will | quick start stops at first save | done | | T6-6 | minor | Claude | root README pointers | done | | T6-7 | nit | Claude | README details | partial | | T7-1 | major | Will | no component tests | open | @@ -181,6 +182,8 @@ Fix: run `make check` (including e2e) in the release job before building, or gat The package description says "The camera processing itself, vision_processor, is packaged separately", but no vision_processor package exists yet (the CV deb is planned). A new user who installs the `.deb` from the first release has a GUI with nothing to talk to, and nothing on the release page says how to get vision_processor. The `v*` tag also reads as a release of the whole repo while it ships only the GUI. Fix: until the CV deb ships, change the description to "build vision_processor from source: see ". Give the GitHub Release a body template (`--notes-file`) saying what's included and pointing at the vision_processor build steps. Decide whether GUI releases get their own tag prefix once the CV deb exists. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the package description says to build vision_processor from source. `packaging/release-notes.md` heads the generated release notes with the same and what each file is. Open question for later: a separate tag prefix once the vision_processor package exists. + **T1-4 | minor | Claude | `gui/Makefile:63-75`** The tarball and `-bin` are built only for the host's `GOARCH` (amd64 in CI), while the debs are amd64 and arm64. arm64 users (Pi, Jetson) get the deb but no standalone binary, though `gui/README.md` presents the standalone binary as the first install path. Fix: loop `release` over `DEB_ARCHES` (or a `RELEASE_ARCHES`), and include both in `SHA256SUMS`. @@ -299,7 +302,7 @@ Fix: one topic registry in Go (name → payload type → equivalent route) that The frontend uses only `components["schemas"]` from the generated file, never `paths`. There are 30 hand-written `/api/...` URL strings and 12 `response.json()` results cast to a type, so a wrong path, method, query parameter or body shape still type-checks, which is exactly the drift the generated types exist to catch. Fix: `openapi-fetch` (same author as `openapi-typescript`, ~6 kB, no runtime schema) typed against `paths`. It makes `client.GET("/api/config/cameras/{id}/effective", {params: {path: {id}}})` checked end to end and removes most casts. `requestJSON`/`errorMessage` can stay as its error middleware. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* every call goes through `api.ts`'s `openapi-fetch` client, typed by the generated `paths`; `unwrap` throws the host's message, `apiPath` fills in the image and WebSocket URLs. `requestJSON` and the unused `withLoadingState` are gone. Two casts remain, both where the GUI's generic view of `defaults` and `config` meets the spec's typed one (`getConfig`, `putDoc`), plus the league messages. New `api.test.ts`. +*Done 2026-11-25 (Claude, at Will's request; committed `e6802c2`):* every call goes through `api.ts`'s `openapi-fetch` client, typed by the generated `paths`; `unwrap` throws the host's message, `apiPath` fills in the image and WebSocket URLs. `requestJSON` and the unused `withLoadingState` are gone. Two casts remain, both where the GUI's generic view of `defaults` and `config` meets the spec's typed one (`getConfig`, `putDoc`), plus the league messages. New `api.test.ts`. **T3-3 | major | Will | public route and topic names; `docs.go:19`** `specVersion` is `1.0.0`, and its comment promises that changing or removing anything means `/api/v2`. Once the API ships in a release with docs at `/api/docs`, other teams will script against these names; it's cheap to rename now and costly later. Current inconsistencies: @@ -353,6 +356,8 @@ Fix: set `lastSynced` only after a 2xx. On a network error, set `config.error` ( After a 400 (validation), the rejected value stays in the local document while the host keeps the old one, and `lastSynced` now equals the rejected JSON, so nothing reconciles them until the next edit or a reload. The banner shows the reason, but the form shows a value the host isn't using. The "a rejected edit shows the host's reason" e2e test checks the banner, not the field. Fix: on 400, keep the message and restore the host's document. Better, map `issues` to the field (FormRow already has message slots) so the user sees which value was refused. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* a refused edit goes back to the host's document; while a field is focused, once it's left, so typing through a refused value isn't interrupted. Two unit tests, and the e2e test now checks the field. + **T4-4 | minor | Will | `frontend/src/lib/wrapper-bus.ts`, `config.svelte.ts`** No stale-frontend detection. After a `.deb` upgrade restarts the service, every open browser keeps the old bundle and talks to the new API. Mismatched shapes then surface as odd errors, not as "reload". Fix: embed the build version in the page. On WS reconnect, compare it with `/api/health`'s `version`, and show a "the GUI was updated, reload" notice when they differ. @@ -473,6 +478,8 @@ Overall: `gui/README.md` is a genuinely good user guide: quick start, package qu Fix: correct both. Then decide which document is canonical for humans (below). +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* checked the whole file against the code, not only the two cases: added Discovery, the housekeeping loop and supervisor, the missing packages and error codes, video restarts, duplicate packets and the followed game controller; corrected the shared-filesystem claim, page names and "Not yet built". The canonical-document decision is T6-2. + **T6-2 | minor | Claude (Will decides) | `gui/CLAUDE.md` (384 lines) vs `gui/ARCHITECTURE.md` (429)** The design rationale is split between an agent-facing file and the human architecture doc, and some of it exists only in `CLAUDE.md`: the drop-stale hub channels, why `WriteTimeout` must not be set, `Pdeathsig` and process groups, the sslnet rationale. Human contributors don't read `CLAUDE.md`, and two copies are how T6-1 happened. Fix: make `ARCHITECTURE.md` the single home for decisions and gotchas, and slim `CLAUDE.md` to commands, rules and links into it. @@ -495,6 +502,8 @@ Fix: - Drop the OPENCV caveat once T5-3 lands. - Add troubleshooting rows: "vision_processor keeps restarting" (Camera page output, driver, `/dev/video*` busy) and "no video in Firefox/Chromium". +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* quick start step 5 branches to a local camera or other machines, with the build link. New troubleshooting rows: no camera selected, vision_processor keeps exiting, nothing heard, no video, duplicate packets. Page names match the tabs. + **T6-6 | minor | Claude | root `README.md:19-20`** - It sends readers who want to "work on it" to `gui/CLAUDE.md` for the `buf` setup; that's `DEVELOPMENT.md`'s job. - Its frontend line (`make proto && cd frontend && npm install && npm run dev`) bypasses the Makefile's own prerequisites (`npm ci`, generated API types) that `DEVELOPMENT.md` documents. Followed literally, `src/lib/generated/api.ts` is never created, so `npm run check` and the editor's type checking fail. The dev server itself probably runs, since Vite erases the type-only import (not verified). diff --git a/gui/frontend/e2e/smoke.spec.ts b/gui/frontend/e2e/smoke.spec.ts index d97185f..10d0466 100644 --- a/gui/frontend/e2e/smoke.spec.ts +++ b/gui/frontend/e2e/smoke.spec.ts @@ -107,11 +107,18 @@ test("an edit applies live and shows as unsaved", async ({ page }) => { test("a rejected edit shows the host's reason", async ({ page }) => { await page.goto("/#0/field_dimensions"); - await page.getByRole("spinbutton", { name: "Field width" }).fill("0"); + const width = page.getByRole("spinbutton", { name: "Field width" }); + const before = await width.inputValue(); + await width.fill("0"); await expect(page.getByRole("alert")).toContainText( "field_width: must be greater than 0", ); + + // Kept while it's being typed in, then back to what the host has. + await expect(width).toHaveValue("0"); + await width.blur(); + await expect(width).toHaveValue(before); }); test("unlocking a calibration goes through the API", async ({ page }) => { diff --git a/gui/frontend/src/lib/config.svelte.ts b/gui/frontend/src/lib/config.svelte.ts index 1bce6bb..9a203c6 100644 --- a/gui/frontend/src/lib/config.svelte.ts +++ b/gui/frontend/src/lib/config.svelte.ts @@ -205,13 +205,30 @@ async function putDoc(json: string): Promise { return true; } - // Refused (T4-3: the form keeps the refused value until the next edit). + // Refused: the host still has its own version. lastSynced = json; config.error = errorMessage(answer.error, answer.response); + dropRefused(json); return true; } +// Goes back to the host's document after it refused json, so the form shows +// what's in use. Not while a field is being typed in (a number often passes +// through a refused value): then once it's left. A later edit is sent as +// usual, and its own answer decides. +function dropRefused(json: string): void { + const restore = (): void => { + if (JSON.stringify(config.doc) === json) void loadConfig(); + }; + + if (document.activeElement?.matches("input, textarea")) { + document.addEventListener("focusout", restore, { once: true }); + } else { + restore(); + } +} + $effect.root(() => { $effect(() => { const json = JSON.stringify(config.doc); diff --git a/gui/frontend/src/lib/config.test.ts b/gui/frontend/src/lib/config.test.ts index 2302a58..a695bfd 100644 --- a/gui/frontend/src/lib/config.test.ts +++ b/gui/frontend/src/lib/config.test.ts @@ -181,6 +181,58 @@ describe("edits", () => { expect(config.revision).toBe(3); }); + it("go back to the host's document once refused", async () => { + reply("PUT", "/api/config", { + status: 400, + body: { error: "invalid", message: "too small" }, + }); + const { config } = await loaded(); + + docOf(config).field.fieldLength = 1; + await settle(300); + + expect(docOf(config).field.fieldLength).toBe(9000); + expect(config.error).toBe("too small"); + await settle(1000); + expect(sent("PUT", "/api/config")).toHaveLength(1); + }); + + it("aren't taken back from a field still being typed in", async () => { + reply( + "PUT", + "/api/config", + { status: 400, body: { error: "invalid", message: "too small" } }, + { status: 200, body: { revision: 4 } }, + { status: 400, body: { error: "invalid", message: "too small" } }, + ); + const { config } = await loaded(); + const input = document.body.appendChild(document.createElement("input")); + input.focus(); + + docOf(config).field.fieldLength = 9; + await settle(300); + expect(docOf(config).field.fieldLength).toBe(9); + + // Typed on to a value the host takes: leaving keeps it. + docOf(config).field.fieldLength = 9100; + await settle(300); + input.blur(); + await settle(); + expect(docOf(config).field.fieldLength).toBe(9100); + expect(config.error).toBeNull(); + + // Left on a refused one: back to the host's. + input.focus(); + docOf(config).field.fieldLength = 9; + await settle(300); + expect(docOf(config).field.fieldLength).toBe(9); + input.blur(); + await settle(); + expect(docOf(config).field.fieldLength).toBe(9000); + + input.remove(); + }); + it("take the host's document when another tab edited first", async () => { reply("PUT", "/api/config", { status: 409, diff --git a/gui/packaging/nfpm.yaml b/gui/packaging/nfpm.yaml index 95072ff..3c52bad 100644 --- a/gui/packaging/nfpm.yaml +++ b/gui/packaging/nfpm.yaml @@ -24,8 +24,10 @@ description: |- settings, locked calibrations, live video and the live field. It publishes the field geometry to the rest of the league's software. . - The setup questions decide whether it runs as a system service. The camera - processing itself, vision_processor, is packaged separately. + The setup questions decide whether it runs as a system service. + . + It doesn't include vision_processor, which does the camera processing: build + that from source, see the homepage. depends: - systemd diff --git a/gui/packaging/release-notes.md b/gui/packaging/release-notes.md new file mode 100644 index 0000000..f6a9c0c --- /dev/null +++ b/gui/packaging/release-notes.md @@ -0,0 +1,6 @@ +This release is the **SSL Vision Processor GUI** only. It doesn't include `vision_processor`, which does the camera processing: [build that from source](https://github.com/RoboCup-SSL/ssl-vision-processor#readme). + +- `.tar.gz`: the program with its user guide, for any 64-bit Linux. Start with the [quick start](https://github.com/RoboCup-SSL/ssl-vision-processor/blob/master/gui/README.md#quick-start). +- `.deb`: the same program for Ubuntu 24.04, which can also run it as a service. +- `SHA256SUMS`: check your download with `sha256sum --check --ignore-missing SHA256SUMS`. + From eeed60b21cb19aa755faa8eb65231e5fd2de6767 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 13:06:23 -0500 Subject: [PATCH 18/35] update all dependencies --- .github/workflows/ci.yml | 2 +- flake.lock | 6 ++-- flake.nix | 2 +- gui/DEVELOPMENT.md | 2 +- gui/REVIEW.md | 20 +++++++------ gui/go.mod | 2 +- gui/internal/geometry/field_config.go | 42 +++++++++++++-------------- gui/packaging/go.mod | 2 +- 8 files changed, 40 insertions(+), 38 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index adf7a4f..d81a26e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,7 +126,7 @@ jobs: # Ubuntu doesn't package buf. Keep the version in step with the flake's # (nix develop -c buf --version) and gui/DEVELOPMENT.md. - name: Install buf - run: go install github.com/bufbuild/buf/cmd/buf@v1.72.0 + run: go install github.com/bufbuild/buf/cmd/buf@v1.75.0 - name: Enable loopback multicast run: sudo scripts/lo-multicast.sh on diff --git a/flake.lock b/flake.lock index 66621c9..1b51811 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1788179007, - "narHash": "sha256-hn1oU2rue2SYK8dAr8+WNZWtbsz1S2W5mnHlSEuh3bo=", + "lastModified": 1795234589, + "narHash": "sha256-f/VVvxf5RsQgWVhUtefoca5ktVg0DA2bnkMOcmSnozo=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "34ab99075ac4f7e40cf037eef32cb1c360bb85e9", + "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index f2a294b..dec728d 100644 --- a/flake.nix +++ b/flake.nix @@ -73,7 +73,7 @@ opencv # core imgproc imgcodecs videoio yaml-cpp # Must match the ffmpeg nixpkgs built opencv against, currently - # 8.1.2. The default `ffmpeg` is 9.x, which links fine but loads a + # 8.1.3. The default `ffmpeg` is 9.x, which links fine but loads a # second set of libav* sonames alongside the ones opencv's videoio # pulls in -- two copies of ffmpeg's global state in one process. ffmpeg_8 # libavformat libavcodec libavutil diff --git a/gui/DEVELOPMENT.md b/gui/DEVELOPMENT.md index 61ace5a..84a40e4 100644 --- a/gui/DEVELOPMENT.md +++ b/gui/DEVELOPMENT.md @@ -15,7 +15,7 @@ The root `flake.nix` provides everything needed: `go`, `buf`, `nodejs_22`, and t the repo. Run `nix develop` from the repo root before any command below, and `git submodule update --init` once for the protobuf definitions in `proto/`. -Without nix, you need `buf` 1.72.0 on your `PATH` (`go install github.com/bufbuild/buf/cmd/buf@v1.72.0`), a Go toolchain matching the `go` directive in `gui/go.mod`, and +Without nix, you need `buf` 1.75.0 on your `PATH` (`go install github.com/bufbuild/buf/cmd/buf@v1.75.0`), a Go toolchain matching the `go` directive in `gui/go.mod`, and Node 22 (`frontend/.nvmrc`). `protoc-gen-go` and `protoc-gen-es` do not need to be installed separately: `go tool protoc-gen-go` is resolved from `gui/go.mod`'s `tool` directive, and `protoc-gen-es` is a `frontend/package.json` devDependency. diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 3a87869..9540d62 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,12 +27,11 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-25. **Open** 21 · **Partial** 4 · **Done** 44 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 21 · **Partial** 3 · **Done** 45 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T1-3, T6-1, T6-5 and T4-3 are awaiting commit; the API freeze is done. -1. T1-5: decide on `flake.lock`. -2. T7-1, T7-2, T7-4: tests (can trail the tag). +All blockers are fixed. T1-5 is awaiting commit. Left of the MVP gate: the tests, and T2-10 (lab machine). +1. T7-1, T7-2, T7-4: tests (can trail the tag). **Needs the lab PoE machine:** T2-10. @@ -42,7 +41,7 @@ All blockers are fixed. T1-3, T6-1, T6-5 and T4-3 are awaiting commit; the API f | T1-2 | major | Claude | release tag not gated on `make check` / e2e | done | | T1-3 | major | Claude + Will | package description promises a VP package that doesn't exist | done | | T1-4 | minor | Claude | tarball and `-bin` amd64 only (absorbs L-3) | open | -| T1-5 | minor | Claude | stale toolchain and dependencies | partial | +| T1-5 | minor | Claude | stale toolchain and dependencies | done | | T1-6 | minor | Claude | CI skips the `v2.0-alpha` branch | open | | T1-7 | minor | Claude | no Go linter beyond vet | done | | T1-8 | minor | Claude | `setup.sh` still offers `geom_publisher` | open | @@ -182,7 +181,7 @@ Fix: run `make check` (including e2e) in the release job before building, or gat The package description says "The camera processing itself, vision_processor, is packaged separately", but no vision_processor package exists yet (the CV deb is planned). A new user who installs the `.deb` from the first release has a GUI with nothing to talk to, and nothing on the release page says how to get vision_processor. The `v*` tag also reads as a release of the whole repo while it ships only the GUI. Fix: until the CV deb ships, change the description to "build vision_processor from source: see ". Give the GitHub Release a body template (`--notes-file`) saying what's included and pointing at the vision_processor build steps. Decide whether GUI releases get their own tag prefix once the CV deb exists. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the package description says to build vision_processor from source. `packaging/release-notes.md` heads the generated release notes with the same and what each file is. Open question for later: a separate tag prefix once the vision_processor package exists. +*Done 2026-11-25 (Claude, at Will's request; committed):* the package description says to build vision_processor from source. `packaging/release-notes.md` heads the generated release notes with the same and what each file is. Open question for later: a separate tag prefix once the vision_processor package exists. **T1-4 | minor | Claude | `gui/Makefile:63-75`** The tarball and `-bin` are built only for the host's `GOARCH` (amd64 in CI), while the debs are amd64 and arm64. arm64 users (Pi, Jetson) get the deb but no standalone binary, though `gui/README.md` presents the standalone binary as the first install path. @@ -194,6 +193,8 @@ Fix: bump all three before tagging. Add `govulncheck` as a non-blocking CI step, *Progress 2026-11-18 (Claude):* Go modules bumped within their majors (`x/net` 0.55→0.63, `x/sys`, `tint`, `mediacommon`, `pion/rtp`); `npm update` within ranges took `npm audit` from 16 findings to 0 (lockfile only). `make vulncheck` (govulncheck, pinned in `go.mod`) runs in CI as a non-blocking step. **Left for Will:** `flake.lock`. `nix flake update` brings Go 1.27.3, but also protobuf 35→36 and yaml-cpp 0.8→0.9 for vision_processor's C++ build, so it was reverted. govulncheck still reports 10 stdlib advisories that only a newer Go clears. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* `flake.lock` updated (Go 1.27.3, protobuf 36.2, yaml-cpp 0.9.0, ffmpeg 8.1.3, buf 1.75.0; OpenCV and Eigen unchanged). The `go` directives and the non-nix buf pin follow. vision_processor builds without errors on both toolchains. Run on one test video in a namespace with the GUI host, its debug images are byte-identical and its packet counts match at equal start times. The benchmarks need ground truth that isn't in the repo, so they weren't run. protobuf 36 adds `nodiscard` warnings for unchecked `ParseFromArray`/`SerializeToString` (C++, not changed). govulncheck: 10 standard-library advisories down to 1 (fixed in Go 1.27.4, not in nixpkgs yet), plus 1 in gorilla/websocket. + **T1-6 | minor | Claude | `.github/workflows/ci.yml:3-6`** CI runs on `push: [master]` and PRs only. `v2.0-alpha`, the integration branch the MVP ships from, is tested only when a PR targets it; direct pushes and merges into it (e.g. `443d12a`, `fd10e0b`) are never built. Fix: add `v2.0-alpha` (or `v*-alpha`) to `push.branches` until it merges. @@ -356,7 +357,7 @@ Fix: set `lastSynced` only after a 2xx. On a network error, set `config.error` ( After a 400 (validation), the rejected value stays in the local document while the host keeps the old one, and `lastSynced` now equals the rejected JSON, so nothing reconciles them until the next edit or a reload. The banner shows the reason, but the form shows a value the host isn't using. The "a rejected edit shows the host's reason" e2e test checks the banner, not the field. Fix: on 400, keep the message and restore the host's document. Better, map `issues` to the field (FormRow already has message slots) so the user sees which value was refused. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* a refused edit goes back to the host's document; while a field is focused, once it's left, so typing through a refused value isn't interrupted. Two unit tests, and the e2e test now checks the field. +*Done 2026-11-25 (Claude, at Will's request; committed):* a refused edit goes back to the host's document; while a field is focused, once it's left, so typing through a refused value isn't interrupted. Two unit tests, and the e2e test now checks the field. **T4-4 | minor | Will | `frontend/src/lib/wrapper-bus.ts`, `config.svelte.ts`** No stale-frontend detection. After a `.deb` upgrade restarts the service, every open browser keeps the old bundle and talks to the new API. Mismatched shapes then surface as odd errors, not as "reload". @@ -478,7 +479,7 @@ Overall: `gui/README.md` is a genuinely good user guide: quick start, package qu Fix: correct both. Then decide which document is canonical for humans (below). -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* checked the whole file against the code, not only the two cases: added Discovery, the housekeeping loop and supervisor, the missing packages and error codes, video restarts, duplicate packets and the followed game controller; corrected the shared-filesystem claim, page names and "Not yet built". The canonical-document decision is T6-2. +*Done 2026-11-25 (Claude, at Will's request; committed):* checked the whole file against the code, not only the two cases: added Discovery, the housekeeping loop and supervisor, the missing packages and error codes, video restarts, duplicate packets and the followed game controller; corrected the shared-filesystem claim, page names and "Not yet built". The canonical-document decision is T6-2. **T6-2 | minor | Claude (Will decides) | `gui/CLAUDE.md` (384 lines) vs `gui/ARCHITECTURE.md` (429)** The design rationale is split between an agent-facing file and the human architecture doc, and some of it exists only in `CLAUDE.md`: the drop-stale hub channels, why `WriteTimeout` must not be set, `Pdeathsig` and process groups, the sslnet rationale. Human contributors don't read `CLAUDE.md`, and two copies are how T6-1 happened. @@ -502,7 +503,7 @@ Fix: - Drop the OPENCV caveat once T5-3 lands. - Add troubleshooting rows: "vision_processor keeps restarting" (Camera page output, driver, `/dev/video*` busy) and "no video in Firefox/Chromium". -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* quick start step 5 branches to a local camera or other machines, with the build link. New troubleshooting rows: no camera selected, vision_processor keeps exiting, nothing heard, no video, duplicate packets. Page names match the tabs. +*Done 2026-11-25 (Claude, at Will's request; committed):* quick start step 5 branches to a local camera or other machines, with the build link. New troubleshooting rows: no camera selected, vision_processor keeps exiting, nothing heard, no video, duplicate packets. Page names match the tabs. **T6-6 | minor | Claude | root `README.md:19-20`** - It sends readers who want to "work on it" to `gui/CLAUDE.md` for the `buf` setup; that's `DEVELOPMENT.md`'s job. @@ -715,6 +716,7 @@ These came up during the review. They're out of scope for the MVP and not findin Not findings against this review. Recorded so they aren't lost. - **vision_processor's `camera.driver` fallback is `SPINNAKER`** (mirrored by `/api/schema`). The host-side fix is T5-3. A FOSS-first default in C++ belongs with the CV `.deb` work. +- **Geometry ping-pong, seen while testing T1-5.** With a locked calibration whose aspect doesn't match the image, vision_processor and the host kept replacing each other's geometry: about one "New geometry received" a second, each a ~95 ms frame on a CPU, and the host raised its "another host is sending" conflict. It depended on start timing. Not investigated. - **The announce is sent from inside the frame loop and built once at startup** (`gui/CLAUDE.md` "Not yet built"). A vision_processor whose camera blocks never announces, so it is invisible to discovery exactly when it's broken. Related to T5-2, which covers the supervised case host-side. - **SIGTERM is checked only between frames**, so a blocked `readImage()` needs the supervisor's SIGKILL fallback. That works today; a cleaner C++ shutdown would shorten restarts. - **No way to ask a running instance to recalibrate.** Field changes restart supervised cameras to force it, and external cameras need a manual restart. diff --git a/gui/go.mod b/gui/go.mod index 6013c6c..ec74cfc 100644 --- a/gui/go.mod +++ b/gui/go.mod @@ -1,6 +1,6 @@ module github.com/RoboCup-SSL/ssl-vision-processor/gui -go 1.26.7 +go 1.27.3 require ( github.com/lmittmann/tint v1.2.1 diff --git a/gui/internal/geometry/field_config.go b/gui/internal/geometry/field_config.go index 6cf518b..af378ad 100644 --- a/gui/internal/geometry/field_config.go +++ b/gui/internal/geometry/field_config.go @@ -79,27 +79,27 @@ func (c FieldConfig) Validate() error { // with no Geometry involved). func fieldConfigFrom(field *vision.SSL_GeometryFieldSize, optional optionalLines) (FieldConfig, OptionalLinesConfig) { return FieldConfig{ - FieldLength: field.GetFieldLength(), - FieldWidth: field.GetFieldWidth(), - GoalWidth: field.GetGoalWidth(), - GoalDepth: field.GetGoalDepth(), - GoalHeight: field.GetGoalHeight(), - PenaltyAreaDepth: field.GetPenaltyAreaDepth(), - PenaltyAreaWidth: field.GetPenaltyAreaWidth(), - GoalCenterToPenaltyMark: field.GetGoalCenterToPenaltyMark(), - BoundaryWidth: field.GetBoundaryWidth(), - BoundaryWidthGoalLine: field.GetBoundaryWidthGoalLine(), - CenterCircleRadius: field.GetCenterCircleRadius(), - LineThickness: field.GetLineThickness(), - BallRadius: field.GetBallRadius(), - MaxRobotRadius: field.GetMaxRobotRadius(), - GoalSubstitutionAreaWidth: field.GetGoalSubstitutionAreaWidth(), - }, OptionalLinesConfig{ - Goal2Goal: optional.enabled(optional.Goal2Goal), - Halfway: optional.enabled(optional.Halfway), - CenterCircle: optional.enabled(optional.CenterCircle), - Penalty: optional.enabled(optional.Penalty), - } + FieldLength: field.GetFieldLength(), + FieldWidth: field.GetFieldWidth(), + GoalWidth: field.GetGoalWidth(), + GoalDepth: field.GetGoalDepth(), + GoalHeight: field.GetGoalHeight(), + PenaltyAreaDepth: field.GetPenaltyAreaDepth(), + PenaltyAreaWidth: field.GetPenaltyAreaWidth(), + GoalCenterToPenaltyMark: field.GetGoalCenterToPenaltyMark(), + BoundaryWidth: field.GetBoundaryWidth(), + BoundaryWidthGoalLine: field.GetBoundaryWidthGoalLine(), + CenterCircleRadius: field.GetCenterCircleRadius(), + LineThickness: field.GetLineThickness(), + BallRadius: field.GetBallRadius(), + MaxRobotRadius: field.GetMaxRobotRadius(), + GoalSubstitutionAreaWidth: field.GetGoalSubstitutionAreaWidth(), + }, OptionalLinesConfig{ + Goal2Goal: optional.enabled(optional.Goal2Goal), + Halfway: optional.enabled(optional.Halfway), + CenterCircle: optional.enabled(optional.CenterCircle), + Penalty: optional.enabled(optional.Penalty), + } } // ParseFieldFile parses a geometry YAML file (geometry-*.yml; name is only for diff --git a/gui/packaging/go.mod b/gui/packaging/go.mod index 5e59e3c..f1841f0 100644 --- a/gui/packaging/go.mod +++ b/gui/packaging/go.mod @@ -1,6 +1,6 @@ module github.com/RoboCup-SSL/ssl-vision-processor/gui/packaging -go 1.26.7 +go 1.27.3 tool github.com/goreleaser/nfpm/v2/cmd/nfpm From f3fb82ba4695918b4b61f7f867eed79c1928ca43 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Wed, 25 Nov 2026 13:19:24 -0500 Subject: [PATCH 19/35] fixes from e2e tests --- gui/REVIEW.md | 13 +++-- gui/frontend/e2e/cameras.spec.ts | 85 ++++++++++++++++++++++++++++++++ gui/frontend/e2e/host.ts | 58 ++++++++++++++++++++++ gui/frontend/e2e/restart.spec.ts | 67 +++++++++++++++++++++++++ gui/frontend/e2e/serve.mjs | 59 +++++++++++++++++----- gui/frontend/e2e/smoke.spec.ts | 49 +++++++++++++++++- 6 files changed, 314 insertions(+), 17 deletions(-) create mode 100644 gui/frontend/e2e/cameras.spec.ts create mode 100644 gui/frontend/e2e/host.ts create mode 100644 gui/frontend/e2e/restart.spec.ts diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 9540d62..1eec67d 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,11 +27,10 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-25. **Open** 21 · **Partial** 3 · **Done** 45 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-25. **Open** 20 · **Partial** 3 · **Done** 46 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T1-5 is awaiting commit. Left of the MVP gate: the tests, and T2-10 (lab machine). -1. T7-1, T7-2, T7-4: tests (can trail the tag). +All blockers are fixed. T7-4 is awaiting commit. Left of the MVP gate: T7-1 and T7-2 (can trail the tag), and T2-10 (lab machine). **Needs the lab PoE machine:** T2-10. @@ -92,7 +91,7 @@ All blockers are fixed. T1-5 is awaiting commit. Left of the MVP gate: the tests | T7-1 | major | Will | no component tests | open | | T7-2 | major | Will | untested logic modules | partial | | T7-3 | major | Will | flowbite `Input` unmount error (`test.fail`) | done | -| T7-4 | major | Will + Claude | e2e scenario gaps, axe | open | +| T7-4 | major | Will + Claude | e2e scenario gaps, axe | done | | T7-5 | minor | Claude | frontend coverage tooling | done | | T7-6 | nit | Claude | coverage for binary-only paths | done | | T7-7 | nit | Will | `time.Sleep` in Go tests | done | @@ -193,7 +192,7 @@ Fix: bump all three before tagging. Add `govulncheck` as a non-blocking CI step, *Progress 2026-11-18 (Claude):* Go modules bumped within their majors (`x/net` 0.55→0.63, `x/sys`, `tint`, `mediacommon`, `pion/rtp`); `npm update` within ranges took `npm audit` from 16 findings to 0 (lockfile only). `make vulncheck` (govulncheck, pinned in `go.mod`) runs in CI as a non-blocking step. **Left for Will:** `flake.lock`. `nix flake update` brings Go 1.27.3, but also protobuf 35→36 and yaml-cpp 0.8→0.9 for vision_processor's C++ build, so it was reverted. govulncheck still reports 10 stdlib advisories that only a newer Go clears. -*Done 2026-11-25 (Claude, at Will's request; uncommitted):* `flake.lock` updated (Go 1.27.3, protobuf 36.2, yaml-cpp 0.9.0, ffmpeg 8.1.3, buf 1.75.0; OpenCV and Eigen unchanged). The `go` directives and the non-nix buf pin follow. vision_processor builds without errors on both toolchains. Run on one test video in a namespace with the GUI host, its debug images are byte-identical and its packet counts match at equal start times. The benchmarks need ground truth that isn't in the repo, so they weren't run. protobuf 36 adds `nodiscard` warnings for unchecked `ParseFromArray`/`SerializeToString` (C++, not changed). govulncheck: 10 standard-library advisories down to 1 (fixed in Go 1.27.4, not in nixpkgs yet), plus 1 in gorilla/websocket. +*Done 2026-11-25 (Claude, at Will's request; committed `eeed60b`):* `flake.lock` updated (Go 1.27.3, protobuf 36.2, yaml-cpp 0.9.0, ffmpeg 8.1.3, buf 1.75.0; OpenCV and Eigen unchanged). The `go` directives and the non-nix buf pin follow. vision_processor builds without errors on both toolchains. Run on one test video in a namespace with the GUI host, its debug images are byte-identical and its packet counts match at equal start times. The benchmarks need ground truth that isn't in the repo, so they weren't run. protobuf 36 adds `nodiscard` warnings for unchecked `ParseFromArray`/`SerializeToString` (C++, not changed). govulncheck: 10 standard-library advisories down to 1 (fixed in Go 1.27.4, not in nixpkgs yet), plus 1 in gorilla/websocket. **T1-6 | minor | Claude | `.github/workflows/ci.yml:3-6`** CI runs on `push: [master]` and PRs only. `v2.0-alpha`, the integration branch the MVP ships from, is tested only when a PR targets it; direct pushes and merges into it (e.g. `443d12a`, `fd10e0b`) are never built. @@ -353,6 +352,8 @@ Fix: set `lastSynced` only after a 2xx. On a network error, set `config.error` ( *Done 2026-11-18 (Claude, at Will's request):* `lastSynced` moves only when the host answers. A PUT the host never answers (fetch rejects) shows "Not sent: the host can't be reached…", keeps the edit, and retries every 2 s; `flushEdits` (Save, lock) sends it at once. The `config.state` refetch holds off while a retry is pending, so a reconnect doesn't drop the edit. If the host restarted at another revision, the retry gets a 409 and the usual "edited elsewhere" reload applies. Also fixed: two waiters could both send the same edit after an in-flight PUT (`while (inFlight)`). The `it.todo` is now three tests in `config.test.ts`. +*2026-11-25, remaining gap:* an edit made while the host is down is still lost if the page had already edited since the host started (its revision is then ahead of the restarted host's 1): the retry gets a 409, and the page says "Edited elsewhere" and reloads. Unsaved edits from before the restart are lost too, since they live in the host. Found with a throwaway e2e probe. + **T4-3 | minor | Will | `config.svelte.ts:170`** After a 400 (validation), the rejected value stays in the local document while the host keeps the old one, and `lastSynced` now equals the rejected JSON, so nothing reconciles them until the next edit or a reload. The banner shows the reason, but the form shows a value the host isn't using. The "a rejected edit shows the host's reason" e2e test checks the banner, not the field. Fix: on 400, keep the message and restore the host's document. Better, map `issues` to the field (FormRow already has message slots) so the user sees which value was refused. @@ -573,6 +574,8 @@ E2E doesn't cover the first-release paths most likely to go wrong. Missing scena Fix: add `@axe-core/playwright` to "every page renders" (cheap, catches label and contrast regressions), then the scenarios above. Track 5 will refine the list. +*Done 2026-11-25 (Claude, at Will's request; uncommitted):* the four scenarios Will chose, on hosts the tests start and stop themselves (`e2e/host.ts`): no camera selected → driver chosen → running, a crash loop and its recovery (`cameras.spec.ts`), a host restart under an open page (`restart.spec.ts`), and save as/load (`smoke.spec.ts`). `serve.mjs` now also isolates the tracker and video groups. Mutating the code behind them makes them fail; 5 repeats of the new specs passed. Left out: competition-mode alerts (Go tests), narrow viewport (no phone support), accessibility (v2.1). + **T7-5 | minor | Claude | `frontend/package.json`** No way to measure frontend coverage (`@vitest/coverage-v8` isn't installed, so `vitest --coverage` fails). Add it and a `test:coverage` script; report only, don't gate. *Done 2026-11-11 (Claude, `759871b`):* `@vitest/coverage-v8` added, `npm run test:coverage`, `coverage/` ignored. Frontend statements: 9.7% → 19.3% (`.ts` logic modules high; the remainder is Svelte components, see T7-1). diff --git a/gui/frontend/e2e/cameras.spec.ts b/gui/frontend/e2e/cameras.spec.ts new file mode 100644 index 0000000..3fedc5b --- /dev/null +++ b/gui/frontend/e2e/cameras.spec.ts @@ -0,0 +1,85 @@ +// -runCameras: the host runs each camera's vision_processor itself, here a +// stand-in that can be told to crash. +import { rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { expect, test, type Locator, type Page } from "@playwright/test"; +import { Host } from "./host"; + +const host = new Host(8098, ["--run-cameras"]); + +test.beforeAll(() => host.start()); +test.afterAll(() => host.remove()); + +// Camera 0's row in the sidebar, whose status dot is named for screen readers. +function row(page: Page): Locator { + return page.getByRole("complementary").getByRole("link", { name: /cam 0/ }); +} + +test("a camera starts once its driver is chosen, and stops without one", async ({ + page, +}) => { + await page.goto(`${host.url}/#0/camera`); + + const driver = page.getByLabel("Driver", { exact: true }); + const state = page.getByText("Running", { exact: true }); + + await expect(driver).toHaveValue("DUMMY"); + await expect( + page.getByText(/Choose the driver for this camera/), + ).toBeVisible(); + await expect(page.getByText(/^No camera selected\. Choose/)).toBeVisible(); + await expect(row(page)).toContainText("no camera selected"); + await expect( + page.getByRole("button", { name: "Restart now" }), + ).toBeDisabled(); + await expect(page.getByText("Exposure", { exact: true })).toHaveCount(0); + + // Really not started, rather than only said to be. + await expect(page.getByText(/stand-in running/)).toHaveCount(0); + + await driver.selectOption("OPENCV"); + await expect(state).toBeVisible(); + await expect(page.getByText(/stand-in running .*cam0\.yml/)).toBeVisible(); + await expect(row(page)).toContainText("vision_processor running"); + await expect(page.getByText("Exposure", { exact: true })).toBeVisible(); + + await page.goto(`${host.url}/#0/alerts`); + await expect(page.getByText("Camera 1 has no driver selected")).toBeVisible(); + await expect(page.getByText("Camera 0 has no driver selected")).toHaveCount( + 0, + ); + + await page.goto(`${host.url}/#0/camera`); + await driver.selectOption("DUMMY"); + await expect(state).toHaveCount(0); + await expect(row(page)).toContainText("no camera selected"); +}); + +test("a crash loop shows, with its cause, until it recovers", async ({ + page, +}) => { + const crash = join(host.dir, "crash"); + writeFileSync(crash, ""); + + await page.goto(`${host.url}/#0/camera`); + await page.getByLabel("Driver", { exact: true }).selectOption("OPENCV"); + + await expect( + page.getByText("vision_processor keeps exiting: VIDIOC_REQBUFS"), + ).toBeVisible({ timeout: 15_000 }); + await expect(row(page)).toContainText("vision_processor keeps exiting"); + + await page.goto(`${host.url}/#0/alerts`); + await expect( + page.getByText(/Camera 0's vision_processor keeps exiting/), + ).toBeVisible(); + await expect( + page.getByText("Last output: VIDIOC_REQBUFS: Device or resource busy"), + ).toBeVisible(); + + // The cause is fixed: Restart now doesn't wait for the next retry. + rmSync(crash); + await page.goto(`${host.url}/#0/camera`); + await page.getByRole("button", { name: "Restart now" }).click(); + await expect(page.getByText("Running", { exact: true })).toBeVisible(); +}); diff --git a/gui/frontend/e2e/host.ts b/gui/frontend/e2e/host.ts new file mode 100644 index 0000000..f46f838 --- /dev/null +++ b/gui/frontend/e2e/host.ts @@ -0,0 +1,58 @@ +// A host of a test's own, which it can stop and start again: for what the +// shared ones (playwright.config.ts) can't be put through. +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect } from "@playwright/test"; + +export class Host { + readonly dir = mkdtempSync(join(tmpdir(), "vision-gui-e2e-")); + readonly url: string; + private process: ChildProcess | null = null; + private readonly port: number; + private readonly flags: string[]; + + constructor(port: number, flags: string[] = []) { + this.port = port; + this.flags = flags; + this.url = `http://127.0.0.1:${String(port)}`; + } + + async start(): Promise { + this.process = spawn( + "node", + ["e2e/serve.mjs", String(this.port), "--dir", this.dir, ...this.flags], + { stdio: "ignore" }, + ); + + await expect + .poll( + async () => { + try { + return (await fetch(`${this.url}/api/health`)).ok; + } catch { + return false; + } + }, + { timeout: 15_000 }, + ) + .toBe(true); + } + + // Stops it cleanly, as a service manager would. + async stop(): Promise { + const running = this.process; + this.process = null; + if (running?.exitCode !== null) return; + + const exited = new Promise((resolve) => running.once("exit", resolve)); + running.kill("SIGTERM"); + await exited; + } + + async remove(): Promise { + await this.stop(); + rmSync(this.dir, { recursive: true, force: true }); + } +} diff --git a/gui/frontend/e2e/restart.spec.ts b/gui/frontend/e2e/restart.spec.ts new file mode 100644 index 0000000..cbeee19 --- /dev/null +++ b/gui/frontend/e2e/restart.spec.ts @@ -0,0 +1,67 @@ +// The host going away and coming back under an open page. +import { expect, test } from "@playwright/test"; +import { Host } from "./host"; + +const host = new Host(8099); + +test.beforeEach(() => host.start()); +test.afterEach(() => host.stop()); +test.afterAll(() => host.remove()); + +test("an edit made while the host is down is kept, and sent once it's back", async ({ + page, +}) => { + const errors: string[] = []; + page.on("pageerror", (err) => errors.push(err.message)); + + await page.goto(`${host.url}/#0/field_dimensions`); + const width = page.getByRole("spinbutton", { name: "Field width" }); + await expect(width).toHaveValue("6000"); + await expect(page.getByText("User Interface - OPEN")).toBeVisible(); + + await host.stop(); + await expect(page.getByText("User Interface - CLOSED")).toBeVisible(); + + await width.fill("6100"); + await expect(page.getByRole("alert")).toContainText("Not sent"); + await expect(width).toHaveValue("6100"); + + await host.start(); + await expect(page.getByText("User Interface - OPEN")).toBeVisible({ + timeout: 15_000, + }); + await expect(page.getByRole("alert")).toHaveCount(0); + await expect(width).toHaveValue("6100"); + + await expect + .poll(async () => { + const config = (await ( + await page.request.get(`${host.url}/api/config`) + ).json()) as { document: { field: { fieldWidth: number } } }; + + return config.document.field.fieldWidth; + }) + .toBe(6100); + expect(errors).toEqual([]); +}); + +test("a page that edited before a restart takes the host's config", async ({ + page, +}) => { + await page.goto(`${host.url}/#0/field_dimensions`); + const width = page.getByRole("spinbutton", { name: "Field width" }); + await expect(width).toHaveValue("6000"); + + for (const value of ["6100", "6200"]) { + const put = page.waitForResponse((r) => r.request().method() === "PUT"); + await width.fill(value); + await put; + } + + await host.stop(); + await expect(page.getByText("User Interface - CLOSED")).toBeVisible(); + await host.start(); + + // Unsaved edits live in the host, so they went with it. + await expect(width).toHaveValue("6000", { timeout: 15_000 }); +}); diff --git a/gui/frontend/e2e/serve.mjs b/gui/frontend/e2e/serve.mjs index 40d582d..8ab30ee 100644 --- a/gui/frontend/e2e/serve.mjs +++ b/gui/frontend/e2e/serve.mjs @@ -2,21 +2,30 @@ // fixture, so a test can never write to a tracked file, with sample debug // snapshots for camera 0. The binary is // GUI_BIN, which `make e2e` builds. +// +// serve.mjs [--first-run] [--run-cameras] [--dir ] +// --first-run a config the host would have just created itself +// --run-cameras -runCameras, with no camera selected and a stand-in +// vision_processor, which crashes while /crash exists +// --dir the host's folder: kept, so a host restarted there goes on +// with its files import { spawn } from "node:child_process"; import { copyFileSync, + existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { delimiter, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const port = process.argv[2] ?? "8096"; -// A config the host would have just created itself, for the first run tests. -const firstRun = process.argv[3] === "--first-run"; +const [port = "8096", ...args] = process.argv.slice(2); +const firstRun = args.includes("--first-run"); +const runCameras = args.includes("--run-cameras"); +const givenDir = args.includes("--dir") && args[args.indexOf("--dir") + 1]; const bin = process.env["GUI_BIN"]; if (!bin) { @@ -26,16 +35,17 @@ if (!bin) { const here = dirname(fileURLToPath(import.meta.url)); const repo = resolve(here, "../../.."); -const dir = mkdtempSync(join(tmpdir(), "vision-gui-e2e-")); +const dir = givenDir || mkdtempSync(join(tmpdir(), "vision-gui-e2e-")); const config = join(dir, "vision.yml"); copyFileSync(join(repo, "robot-heights.yml"), join(dir, "robot-heights.yml")); // The fixture uses the league's default vision and game controller groups, // where this host would publish the fixture's calibrations to every real // GUI host and vision_processor on the network. A private group and ports -// keep it to itself. +// keep it to itself; the tracker and video groups too, which it only hears. const octet = () => 1 + Math.floor(Math.random() * 254); -const group = `239.255.${String(octet())}.${String(octet())}`; +const prefix = `239.255.${String(octet())}.`; +const group = `${prefix}${String(octet())}`; const base = 20000 + Math.floor(Math.random() * 20000); const fixture = readFileSync( join(repo, "gui/internal/config/testdata/vision.yml"), @@ -43,7 +53,7 @@ const fixture = readFileSync( ); const isolated = fixture.replace( /^defaults:\n/m, - `defaults:\n network:\n vision_ip: ${group}\n vision_port: ${String(base)}\n gc_ip: ${group}\n gc_port: ${String(base + 1)}\n`, + `defaults:\n network:\n vision_ip: ${group}\n vision_port: ${String(base)}\n gc_ip: ${group}\n gc_port: ${String(base + 1)}\n stream:\n ip_base_prefix: "${prefix}"\n port: ${String(base + 3)}\n`, ); if (isolated === fixture) { @@ -51,7 +61,11 @@ if (isolated === fixture) { process.exit(1); } -writeFileSync(config, firstRun ? `${isolated}\nfirst_run: true\n` : isolated); +let text = `${isolated}\ntracker:\n ip: ${group}\n port: ${String(base + 2)}\n`; +if (firstRun) text += "first_run: true\n"; +if (runCameras) text = text.replace("driver: OPENCV", "driver: DUMMY"); + +if (!existsSync(config)) writeFileSync(config, text); console.error( `e2e host: vision ${group}:${String(base)}, game controller ${group}:${String(base + 1)}`, ); @@ -59,11 +73,33 @@ console.error( // Debug snapshots for camera 0, as vision_processor writes them: the corner // picker's calibration input, a calibration view and a detection view. const img = join(dir, "img"); -mkdirSync(img); +mkdirSync(img, { recursive: true }); for (const view of ["geomcalib_input", "pixels", "flat"]) { copyFileSync(join(repo, "line_corners.png"), join(img, `0.${view}.png`)); } +const env = { ...process.env }; + +if (runCameras) { + const path = join(dir, "bin"); + mkdirSync(path, { recursive: true }); + writeFileSync( + join(path, "vision_processor"), + `#!/bin/sh +echo "stand-in running $1" +if [ -e "${dir}/crash" ]; then + echo "VIDIOC_REQBUFS: Device or resource busy" >&2 + exit 1 +fi +trap 'exit 0' TERM +while :; do sleep 0.1; done +`, + { mode: 0o755 }, + ); + env["PATH"] = `${path}${delimiter}${env["PATH"] ?? ""}`; + env["XDG_STATE_HOME"] = join(dir, "state"); +} + const host = spawn( bin, [ @@ -79,11 +115,12 @@ const host = spawn( "", "-logLevel", "Warn", + ...(runCameras ? ["-runCameras"] : []), ], // Its own process group: Playwright signals this script's group, and a // second signal (that one plus the forwarded one) makes the host quit // without its clean shutdown, losing make e2e-cover's coverage. - { cwd: repo, stdio: "inherit", detached: true }, + { cwd: repo, env, stdio: "inherit", detached: true }, ); for (const signal of ["SIGINT", "SIGTERM"]) { diff --git a/gui/frontend/e2e/smoke.spec.ts b/gui/frontend/e2e/smoke.spec.ts index 10d0466..dd297b1 100644 --- a/gui/frontend/e2e/smoke.spec.ts +++ b/gui/frontend/e2e/smoke.spec.ts @@ -2,7 +2,8 @@ // error, and the main paths through the API (edit, reject, unlock) work from // the UI. The host runs on testdata/vision.yml: two cameras, camera 0 with a // locked calibration. -import { readFileSync, writeFileSync } from "node:fs"; +import { readFileSync, rmSync, writeFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; import { expect, test, @@ -249,6 +250,52 @@ test("saving writes the file and clears the unsaved marker", async ({ }); }); +test("a configuration can be saved under another name, and loaded again", async ({ + page, + request, +}) => { + await withConfigFile(request, async (path, original) => { + const copy = join(dirname(path), "copy.yml"); + const width = page.getByRole("spinbutton", { name: "Field width" }); + const choose = async (item: string): Promise => { + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await page.getByRole("button", { name: item }).click(); + }; + + try { + await page.goto("/#0/field_dimensions"); + const put = page.waitForResponse((r) => r.request().method() === "PUT"); + await width.fill("6100"); + await put; + + await choose("Save as…"); + const dialog = page.getByRole("dialog"); + await dialog.getByLabel("File name").fill("copy.yml"); + await dialog.getByRole("button", { name: "Save", exact: true }).click(); + await expect(dialog).toHaveCount(0); + expect(readFileSync(copy, "utf8")).toContain("field_width: 6100"); + expect(readFileSync(path, "utf8")).toBe(original); + + // A name outside the folder is refused, and the dialog stays. + await choose("Load…"); + await dialog.getByLabel("File name").fill("../vision.yml"); + await dialog.getByRole("button", { name: "Load", exact: true }).click(); + await expect(page.getByRole("alert").last()).toContainText("vision.yml"); + await expect(dialog).toBeVisible(); + + await dialog.getByLabel("File name").fill("vision.yml"); + await dialog.getByRole("button", { name: "Load", exact: true }).click(); + await expect(dialog).toHaveCount(0); + await expect(width).toHaveValue("6000"); + } finally { + await request.post("/api/config/load", { + data: { name: basename(path) }, + }); + rmSync(copy, { force: true }); + } + }); +}); + test("a file changed on disk can be loaded", async ({ page, request }) => { await withConfigFile(request, async (path, original) => { await page.goto("/#0/field_dimensions"); From e984aa6767785ffe8478a39ad1d0969f8411c372 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Sun, 29 Nov 2026 14:34:00 -0500 Subject: [PATCH 20/35] fix load/save behavior and l/s cache coherence --- gui/ARCHITECTURE.md | 6 + gui/REVIEW.md | 3 + gui/frontend/e2e/restart.spec.ts | 89 +++++++++++++- gui/frontend/e2e/smoke.spec.ts | 3 + .../src/lib/checklist/checklist.svelte.ts | 17 +-- .../src/lib/checklist/checklist.test.ts | 1 + gui/frontend/src/lib/config.svelte.ts | 77 +++++++++++- gui/frontend/src/lib/config.test.ts | 111 +++++++++++++++++- .../src/lib/layout/ConfigDialogs.svelte | 65 +++++++++- gui/frontend/src/lib/teams.test.ts | 1 + gui/frontend/src/lib/text/app.ts | 11 ++ gui/frontend/src/lib/util.ts | 14 +++ gui/internal/config/store.go | 16 ++- gui/internal/config/store_test.go | 24 ++++ 14 files changed, 411 insertions(+), 27 deletions(-) diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index f045db6..da359a0 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -207,6 +207,12 @@ sequenceDiagram Store-->>Browser: config.state (WebSocket) ``` +The working copy lives in the host, so a restart loses what wasn't saved. `config.state` carries a `run` that changes +with each start, and revisions start at random, so a revision from an earlier run is always stale. A page that finds +the run changed, and that had unsaved changes or an edit the host never got, shows the host's document and asks +whether to put its own back (`keepLostWork` in `config.svelte.ts`). Once one page has, the others with the same +document stop asking. + A vision_processor skips calibrating at startup only if the geometry packet it receives already holds a calibration for its camera. Publishing locked calibrations is what keeps a restart of either side from triggering a recalibration. Unlocking stops publishing that camera's calibration. A running vision_processor keeps the model diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 1eec67d..6e668e0 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -354,6 +354,9 @@ Fix: set `lastSynced` only after a 2xx. On a network error, set `config.error` ( *2026-11-25, remaining gap:* an edit made while the host is down is still lost if the page had already edited since the host started (its revision is then ahead of the restarted host's 1): the retry gets a 409, and the page says "Edited elsewhere" and reloads. Unsaved edits from before the restart are lost too, since they live in the host. Found with a throwaway e2e probe. +*2026-11-25, gap closed (Claude, at Will's request; uncommitted):* `config.state` has a `run`, and revisions start at random, so a page can tell a restart from another page's edit and an old revision never matches by luck. A page that lost unsaved changes or an unsent edit asks: use its version or the host's. 6 unit tests, 4 e2e. +Found by the new e2e test, and fixed: Save as and Load reset the file name being typed every second, when `config.state` arrived, so a save could go to the current file instead. + **T4-3 | minor | Will | `config.svelte.ts:170`** After a 400 (validation), the rejected value stays in the local document while the host keeps the old one, and `lastSynced` now equals the rejected JSON, so nothing reconciles them until the next edit or a reload. The banner shows the reason, but the form shows a value the host isn't using. The "a rejected edit shows the host's reason" e2e test checks the banner, not the field. Fix: on 400, keep the message and restore the host's document. Better, map `issues` to the field (FormRow already has message slots) so the user sees which value was refused. diff --git a/gui/frontend/e2e/restart.spec.ts b/gui/frontend/e2e/restart.spec.ts index cbeee19..ff78f47 100644 --- a/gui/frontend/e2e/restart.spec.ts +++ b/gui/frontend/e2e/restart.spec.ts @@ -27,9 +27,15 @@ test("an edit made while the host is down is kept, and sent once it's back", asy await expect(width).toHaveValue("6100"); await host.start(); - await expect(page.getByText("User Interface - OPEN")).toBeVisible({ + const dialog = page + .getByRole("dialog") + .filter({ hasText: "The host restarted" }); + await expect(dialog).toContainText("made while the host was away", { timeout: 15_000, }); + await expect(page.getByText("Edited elsewhere")).toHaveCount(0); + await dialog.getByRole("button", { name: "Use my version" }).click(); + await expect(dialog).toHaveCount(0); await expect(page.getByRole("alert")).toHaveCount(0); await expect(width).toHaveValue("6100"); @@ -45,23 +51,94 @@ test("an edit made while the host is down is kept, and sent once it's back", asy expect(errors).toEqual([]); }); -test("a page that edited before a restart takes the host's config", async ({ +test("edits from before a restart are offered back, once for every page", async ({ page, + context, }) => { - await page.goto(`${host.url}/#0/field_dimensions`); + const other = await context.newPage(); const width = page.getByRole("spinbutton", { name: "Field width" }); - await expect(width).toHaveValue("6000"); + const goal = page.getByRole("spinbutton", { name: "Goal width" }); + + for (const p of [page, other]) { + await p.goto(`${host.url}/#0/field_dimensions`); + await expect( + p.getByRole("spinbutton", { name: "Field width" }), + ).toHaveValue("6000"); + } + // Well ahead of where a new run starts, then one the host never gets. for (const value of ["6100", "6200"]) { const put = page.waitForResponse((r) => r.request().method() === "PUT"); await width.fill(value); await put; } + await expect( + other.getByRole("spinbutton", { name: "Field width" }), + ).toHaveValue("6200"); + + await host.stop(); + await expect(page.getByText("User Interface - CLOSED")).toBeVisible(); + await goal.fill("1100"); + await expect(page.getByRole("alert")).toContainText("Not sent"); + await goal.fill("1000"); + await expect(page.getByText("User Interface - CLOSED")).toBeVisible(); + await host.start(); + + const asked = (p: typeof page) => + p.getByRole("dialog").filter({ hasText: "The host restarted" }); + for (const p of [page, other]) { + await expect(asked(p)).toContainText("field.field_width", { + timeout: 15_000, + }); + } + + // One page putting them back answers for the other, which had the same. + await asked(page).getByRole("button", { name: "Use my version" }).click(); + await expect(width).toHaveValue("6200"); + await expect(asked(other)).toHaveCount(0); + await expect( + other.getByRole("spinbutton", { name: "Field width" }), + ).toHaveValue("6200"); +}); + +test("keeping the host's version drops the page's edits", async ({ page }) => { + await page.goto(`${host.url}/#0/field_dimensions`); + const width = page.getByRole("spinbutton", { name: "Field width" }); + const put = page.waitForResponse((r) => r.request().method() === "PUT"); + await width.fill("6100"); + await put; + + await host.stop(); + await host.start(); + + // It needs an answer: Escape and a click outside don't close it. + const dialog = page + .getByRole("dialog") + .filter({ hasText: "The host restarted" }); + await expect(dialog).toBeVisible({ timeout: 15_000 }); + await page.keyboard.press("Escape"); + await page.keyboard.press("Escape"); + await page.mouse.click(5, 5); + await page.waitForTimeout(500); + await expect(dialog).toBeVisible(); + + await page + .getByRole("button", { name: "Keep the host's" }) + .click({ timeout: 15_000 }); + await expect(width).toHaveValue("6000"); +}); + +test("a restart with nothing unsaved asks nothing", async ({ page }) => { + await page.goto(`${host.url}/#0/field_dimensions`); + await expect(page.getByText("User Interface - OPEN")).toBeVisible(); await host.stop(); await expect(page.getByText("User Interface - CLOSED")).toBeVisible(); await host.start(); - // Unsaved edits live in the host, so they went with it. - await expect(width).toHaveValue("6000", { timeout: 15_000 }); + await expect(page.getByText("User Interface - OPEN")).toBeVisible({ + timeout: 15_000, + }); + await page.waitForTimeout(1500); + await expect(page.getByRole("dialog")).toHaveCount(0); }); diff --git a/gui/frontend/e2e/smoke.spec.ts b/gui/frontend/e2e/smoke.spec.ts index dd297b1..609abb2 100644 --- a/gui/frontend/e2e/smoke.spec.ts +++ b/gui/frontend/e2e/smoke.spec.ts @@ -271,6 +271,9 @@ test("a configuration can be saved under another name, and loaded again", async await choose("Save as…"); const dialog = page.getByRole("dialog"); await dialog.getByLabel("File name").fill("copy.yml"); + // Outlasts the state the host publishes every second. + await page.waitForTimeout(1500); + await expect(dialog.getByLabel("File name")).toHaveValue("copy.yml"); await dialog.getByRole("button", { name: "Save", exact: true }).click(); await expect(dialog).toHaveCount(0); expect(readFileSync(copy, "utf8")).toContain("field_width: 6100"); diff --git a/gui/frontend/src/lib/checklist/checklist.svelte.ts b/gui/frontend/src/lib/checklist/checklist.svelte.ts index 6ae3af8..455788d 100644 --- a/gui/frontend/src/lib/checklist/checklist.svelte.ts +++ b/gui/frontend/src/lib/checklist/checklist.svelte.ts @@ -12,6 +12,7 @@ // // Ticks are per browser and per config file, in localStorage like // preferences.svelte.ts. Restarting clears the ticks and never touches config. +import { stableJSON } from "../util"; import { config, type CameraDoc } from "../config.svelte"; import { network } from "../network.svelte"; import { hostAlerts } from "../alerts/hostAlerts.svelte"; @@ -173,20 +174,7 @@ function saveTicks(): void { } } -// JSON with object keys sorted, so the same settings fingerprint the same -// whatever order the host or a preset happened to list them in. -function stableJSON(value: unknown): string { - return JSON.stringify(value, (_key, v: unknown) => - v && typeof v === "object" && !Array.isArray(v) - ? Object.fromEntries( - Object.entries(v as Record).sort(([a], [b]) => - a.localeCompare(b), - ), - ) - : v, - ); -} - +// What a manual tick judged, so a later change to it asks for a recheck. function cameraBlock(camera: CameraDoc, block: string): unknown { return { defaults: config.doc?.defaults?.[block], @@ -194,7 +182,6 @@ function cameraBlock(camera: CameraDoc, block: string): unknown { }; } -// What a manual tick judged, so a later change to it asks for a recheck. function fingerprint(key: string): string { const [id, camera] = key.split(":"); const cam = config.doc?.cameras.find((c) => String(c.cameraId) === camera); diff --git a/gui/frontend/src/lib/checklist/checklist.test.ts b/gui/frontend/src/lib/checklist/checklist.test.ts index 753920d..9e22366 100644 --- a/gui/frontend/src/lib/checklist/checklist.test.ts +++ b/gui/frontend/src/lib/checklist/checklist.test.ts @@ -49,6 +49,7 @@ function state( file: over.path ?? "vision.yml", firstRun: over.firstRun ?? false, revision: 1, + run: "a", changes: Array.from({ length: over.changes ?? 0 }, (_, i): Change => ({ path: `p${String(i)}`, jsonPath: `p${String(i)}`, diff --git a/gui/frontend/src/lib/config.svelte.ts b/gui/frontend/src/lib/config.svelte.ts index 9a203c6..3045d25 100644 --- a/gui/frontend/src/lib/config.svelte.ts +++ b/gui/frontend/src/lib/config.svelte.ts @@ -19,6 +19,7 @@ import { onTopic } from "./bus.svelte"; import { refreshFieldMarkings } from "./geometry.svelte"; import { app } from "./text/app"; +import { stableJSON } from "./util"; import { loadSchema } from "./schema.svelte"; // The API's types (apiTypes.ts, generated from the host's spec), re-exported @@ -41,6 +42,17 @@ export type { // A 409's body: "stale", "disk_changed" or "no_live_calibration" in error. type ConflictResponse = ApiError; +export interface Restarted { + // This page's document from before the restart. + mine: ConfigDocument; + // What it changed and hadn't saved, as the host last reported. + changes: Change[]; + // It also has an edit the host never got. + unsent: boolean; + // The file the host was editing, if it's now on another one. + from?: string; +} + export const config = $state<{ doc: ConfigDocument | null; // Revision doc was last confirmed at by the host. @@ -49,12 +61,16 @@ export const config = $state<{ // Last failed request, shown as a banner (e.g. a rejected edit). error: string | null; busy: boolean; + // Set while the user is asked what to do with this page's version, which + // the host lost by restarting. + restarted: Restarted | null; }>({ doc: null, revision: 0, state: null, error: null, busy: false, + restarted: null, }); const PUT_DEBOUNCE_MS = 250; @@ -96,11 +112,58 @@ export async function getConfig(): Promise { type SpecDocument = PutConfigRequest["document"]; +// The same document, whatever order its keys are in. The host owns firstRun. +function sameDocument(a: ConfigDocument, b: ConfigDocument): boolean { + return ( + stableJSON({ ...a, firstRun: undefined }) === + stableJSON({ ...b, firstRun: undefined }) + ); +} + +// Called with the host's document before it replaces this page's. If the host +// restarted, what this page had unsaved is gone from it: kept, to ask about. +function keepLostWork(data: ConfigResponse): void { + const before = config.state; + + if (config.doc && before && before.run !== data.state.run) { + for (const timer of [putTimer, retryTimer]) { + if (timer !== null) clearTimeout(timer); + } + putTimer = retryTimer = null; + + const unsent = JSON.stringify(config.doc) !== lastSynced; + + if (!config.restarted && (unsent || before.changes.length > 0)) { + config.error = null; + config.restarted = { + mine: $state.snapshot(config.doc), + changes: $state.snapshot(before.changes), + unsent, + ...(before.path === data.state.path ? {} : { from: before.path }), + }; + } + } + + // Nothing to ask once the host has it again, such as from another page. + if (config.restarted && sameDocument(config.restarted.mine, data.document)) { + config.restarted = null; + } +} + +// Answers config.restarted: this page's version back as an edit, or the +// host's, which is what the page shows meanwhile. +export function resolveRestart(keepMine: boolean): void { + if (keepMine && config.restarted) config.doc = config.restarted.mine; + + config.restarted = null; +} + export async function loadConfig(): Promise { try { // Before the document, so everything rendered from it has the schema. await loadSchema(); const data = await getConfig(); + keepLostWork(data); lastSynced = JSON.stringify(data.document); config.doc = data.document; config.revision = data.state.revision; @@ -197,10 +260,11 @@ async function putDoc(json: string): Promise { } if (answer.response.status === 409) { - // Another tab edited first. Take the host's version rather than - // clobbering it. - config.error = app.editedElsewhere; + // Another tab edited first, or the host restarted (loadConfig finds + // out). Take the host's version rather than clobbering it. + const run = config.state?.run; await loadConfig(); + if (config.state?.run === run) config.error = app.editedElsewhere; return true; } @@ -242,6 +306,13 @@ $effect.root(() => { // waiting to be retried (a reload would drop it). $effect(() => { return onTopic("config.state", (state) => { + // The host restarted: loadConfig compares with the state before. + if (config.doc && config.state && config.state.run !== state.run) { + void loadConfig(); + + return; + } + config.state = state; if ( diff --git a/gui/frontend/src/lib/config.test.ts b/gui/frontend/src/lib/config.test.ts index a695bfd..eed6870 100644 --- a/gui/frontend/src/lib/config.test.ts +++ b/gui/frontend/src/lib/config.test.ts @@ -27,8 +27,9 @@ const doc = () => ({ field: { fieldLength: 9000 }, cameras: [{ cameraId: 0 }], }); -const state = (revision: number) => ({ +const state = (revision: number, run = "a") => ({ revision, + run, path: "/cfg/vision.yml", changes: [], cameras: [], @@ -327,6 +328,114 @@ describe("edits", () => { }); }); +describe("a host restart", () => { + const changed = [{ path: "field.field_length" }]; + const hostHas = (fieldLength: number, over: object = {}, run = "b"): void => { + reply("GET", "/api/config", { + status: 200, + body: { + document: { ...doc(), field: { fieldLength } }, + state: { ...state(90, run), ...over }, + }, + }); + }; + + async function editedThenRestarted(): Promise { + hostHas(9100, { changes: changed }, "a"); + const mod = await loaded(); + hostHas(9000); + await mod.loadConfig(); + + return mod; + } + + it("asks about unsaved changes, showing the host's meanwhile", async () => { + const { config, resolveRestart } = await editedThenRestarted(); + + expect(docOf(config).field.fieldLength).toBe(9000); + expect(config.restarted).toMatchObject({ + mine: { field: { fieldLength: 9100 } }, + changes: changed, + unsent: false, + }); + expect(config.restarted).not.toHaveProperty("from"); + + resolveRestart(true); + await settle(300); + + expect(config.restarted).toBeNull(); + expect(sent("PUT", "/api/config").at(-1)?.body).toMatchObject({ + revision: 90, + document: { field: { fieldLength: 9100 } }, + }); + }); + + it("drops them when the host's are kept", async () => { + const { config, resolveRestart } = await editedThenRestarted(); + + resolveRestart(false); + await settle(1000); + + expect(config.restarted).toBeNull(); + expect(docOf(config).field.fieldLength).toBe(9000); + expect(sent("PUT", "/api/config")).toEqual([]); + }); + + it("asks about an edit the host never got, not saying another page edited", async () => { + const { config } = await loaded(); + reply("PUT", "/api/config", new TypeError("Failed to fetch"), { + status: 409, + body: { error: "stale", message: "stale" }, + }); + docOf(config).field.fieldLength = 9200; + await settle(300); + expect(config.error).toBe(app.notSent); + + hostHas(9000); + await settle(2000); + + expect(config.error).toBeNull(); + expect(config.restarted).toMatchObject({ + mine: { field: { fieldLength: 9200 } }, + changes: [], + unsent: true, + }); + await settle(5000); + expect(sent("PUT", "/api/config")).toHaveLength(2); + }); + + it("just takes the host's when nothing was lost", async () => { + const { config, loadConfig } = await loaded(); + hostHas(9500); // edited on disk while it was down + await loadConfig(); + + expect(config.restarted).toBeNull(); + expect(docOf(config).field.fieldLength).toBe(9500); + }); + + it("stops asking once the host has the changes again", async () => { + const { config, loadConfig } = await editedThenRestarted(); + hostHas(9100); + await loadConfig(); + + expect(config.restarted).toBeNull(); + }); + + it("keeps the first version through a second restart, and says if the file changed", async () => { + const { config, loadConfig } = await editedThenRestarted(); + hostHas(9000, { path: "/cfg/other.yml" }, "c"); + await loadConfig(); + expect(config.restarted?.mine.field.fieldLength).toBe(9100); + + vi.resetModules(); + hostHas(9100, { changes: changed }, "a"); + const other = await loaded(); + hostHas(9000, { path: "/cfg/other.yml" }); + await other.loadConfig(); + expect(other.config.restarted?.from).toBe("/cfg/vision.yml"); + }); +}); + describe("flushEdits", () => { it("sends a pending edit at once and waits for it", async () => { const { config, flushEdits } = await loaded(); diff --git a/gui/frontend/src/lib/layout/ConfigDialogs.svelte b/gui/frontend/src/lib/layout/ConfigDialogs.svelte index af48ce0..0c1efd4 100644 --- a/gui/frontend/src/lib/layout/ConfigDialogs.svelte +++ b/gui/frontend/src/lib/layout/ConfigDialogs.svelte @@ -1,4 +1,5 @@ @@ -134,7 +92,7 @@ {#each slots(doc) as slot (slot.cameraId)} {@const camera = slot.camera} {@const video = camera !== undefined && layoutView.feeds !== "off"} - {@const at = corner(slot)} + {@const at = detailsCorner(slot.slice, { length, width }, flip)} diff --git a/gui/frontend/src/lib/config/WeightTriangle.svelte b/gui/frontend/src/lib/config/WeightTriangle.svelte index 830a4b0..751e319 100644 --- a/gui/frontend/src/lib/config/WeightTriangle.svelte +++ b/gui/frontend/src/lib/config/WeightTriangle.svelte @@ -379,14 +379,14 @@ } .floor-line { - stroke: #b00020; + stroke: var(--danger-stroke); stroke-width: 0.4; stroke-dasharray: 2 1.5; pointer-events: none; } .floor-label { - fill: #b00020; + fill: var(--danger-stroke); font-size: 3.2px; text-anchor: middle; pointer-events: none; diff --git a/gui/frontend/src/lib/layout/ConfigDialogs.svelte b/gui/frontend/src/lib/layout/ConfigDialogs.svelte index 0c1efd4..27d6eda 100644 --- a/gui/frontend/src/lib/layout/ConfigDialogs.svelte +++ b/gui/frontend/src/lib/layout/ConfigDialogs.svelte @@ -126,7 +126,8 @@ {/if} - {#if changes.length === 0} + + {#if changes.length === 0 && !firstRun}

{text.noChanges}

{:else} diff --git a/gui/frontend/src/lib/layout/InstanceList.svelte b/gui/frontend/src/lib/layout/InstanceList.svelte index eca2165..f73d849 100644 --- a/gui/frontend/src/lib/layout/InstanceList.svelte +++ b/gui/frontend/src/lib/layout/InstanceList.svelte @@ -3,7 +3,6 @@ import { Heading, Indicator, - P, SidebarGroup, SidebarItem, } from "flowbite-svelte"; @@ -32,13 +31,11 @@ Vision processors -

- {app.sidebar.instancesHelp} -

{#each instances() as instance (instance.id)} diff --git a/gui/frontend/src/lib/layout/Shell.svelte b/gui/frontend/src/lib/layout/Shell.svelte index f86f467..f9ea8f8 100644 --- a/gui/frontend/src/lib/layout/Shell.svelte +++ b/gui/frontend/src/lib/layout/Shell.svelte @@ -222,6 +222,7 @@ rounded color={CONNECTION_COLOR[connection.state]} class="shrink-0 whitespace-nowrap" + title={text.connectionTitle(location.host)} > User Interface - {connection.state.toUpperCase()} ({location.host}) diff --git a/gui/frontend/src/lib/text/app.ts b/gui/frontend/src/lib/text/app.ts index 25a8335..31dc85e 100644 --- a/gui/frontend/src/lib/text/app.ts +++ b/gui/frontend/src/lib/text/app.ts @@ -50,12 +50,16 @@ export const app = { hostUpdated: (from: string, to: string): string => `The GUI was updated (${from} → ${to}). Reload this page to use the new version; until then it may misbehave.`, reload: "Reload", + // The top bar's connection badge. + connectionTitle: (host: string): string => + `This page's live connection to the GUI host at ${host}. OPEN means settings and status are arriving; anything else means the page is reconnecting and may be out of date.`, notSent: "Not sent: the host can't be reached. Your edit is kept here and sent when the host is back.", sidebar: { + // The "Vision processors" heading's tooltip. instancesHelp: - "One row per camera role, not per machine -- a host running all 4 cameras of a quad setup appears here 4 times. From vision.yml's cameras list.", + "One row per camera role, not per machine: a host running all 4 cameras of a quad setup appears here 4 times. From vision.yml's cameras list.", // The status dot of a vision_processor the host runs itself. process: { running: "vision_processor running", diff --git a/gui/frontend/src/lib/text/color.ts b/gui/frontend/src/lib/text/color.ts index 75807c3..3e8e4c9 100644 --- a/gui/frontend/src/lib/text/color.ts +++ b/gui/frontend/src/lib/text/color.ts @@ -9,10 +9,10 @@ export const color = { updateWeights: { heading: "Update weights", intro: - "How much each new color leans on its configured reference vs. last frame's color vs. what was actually sampled this frame. Drag the marker, or edit the minimum reference weight directly -- see src/blobs/colorupdate.cpp's updateColor for the exact blend this mirrors.", + "How much each new color leans on its configured reference vs. last frame's color vs. what was actually sampled this frame. Drag the marker, or edit the minimum reference weight directly — see src/blobs/colorupdate.cpp's updateColor for the exact blend this mirrors.", unlockTitle: "Unlock the reference weight floor?", unlockBody: - "This floor keeps the reference color from being tuned toward 0. Reference is the only weight never gated on having samples this frame -- without a floor, a color that goes sample-starved for a while has nothing left pulling it back toward its configured value.", + "This floor keeps the reference color from being tuned toward 0. Reference is the only weight never gated on having samples this frame — without a floor, a color that goes sample-starved for a while has nothing left pulling it back toward its configured value.", unlockConfirm: "I understand, unlock", }, @@ -21,9 +21,9 @@ export const color = { restoreAllBody: "Resets all six reference colors to their defaults. Undo can step back through them one color at a time.", smallGamut: (percent: number, dark: boolean): string => - `Only ${String(percent)}% of the square is a real color at this brightness -- the outlined shape, not a full square, is expected here: brightness this close to ${dark ? "black" : "white"} genuinely has few reachable colors. Not a rendering glitch.`, + `Only ${String(percent)}% of the square is a real color at this brightness — the outlined shape, not a full square, is expected here: brightness this close to ${dark ? "black" : "white"} genuinely has few reachable colors. Not a rendering glitch.`, help: (label: string): string => - `Drag or click inside the square to set ${label}'s color at the brightness shown. Dragging the slider (or scrolling over either control) only previews a different brightness -- the marker stays exactly where the saved color actually is, even inside the shaded region if that color isn't reachable at the previewed brightness; nothing is saved until you click or drag inside the square again. Ctrl+Z (Cmd+Z on Mac) undoes the last drag, one gesture at a time. The currently-autoadapted position and per-frame blob samples aren't shown yet: both need the other contributor's protobuf work to reach this host.`, + `Drag or click inside the square to set ${label}'s color at the brightness shown. Dragging the slider (or scrolling over either control) only previews a different brightness — the marker stays exactly where the saved color actually is, even inside the shaded region if that color isn't reachable at the previewed brightness; nothing is saved until you click or drag inside the square again. Ctrl+Z (Cmd+Z on Mac) undoes the last drag, one gesture at a time. The currently-autoadapted position and per-frame blob samples aren't shown yet: both need the other contributor's protobuf work to reach this host.`, defaultLabel: "the reference color", }, }; diff --git a/gui/frontend/src/lib/text/geometry.ts b/gui/frontend/src/lib/text/geometry.ts index 76a82ec..f49eb1d 100644 --- a/gui/frontend/src/lib/text/geometry.ts +++ b/gui/frontend/src/lib/text/geometry.ts @@ -71,7 +71,7 @@ export const geometry = { `No calibration frame from camera ${String(camera)} yet. Its vision_processor saves one when it starts calibrating, on this machine only; Refresh frame checks again.`, refresh: "Refresh frame", intro: - "Drag the four markers onto the real field corners in the image below, then click the number on whichever one sits where the goal line meets the touchline nearest this field's (0,0) corner -- that one turns green and becomes first in the output. The other three can be in any order; the calibration algorithm works that out itself. The goal and penalty area this camera should see are drawn dashed through the markers, as vision_processor will read them: if they don't sit on the real ones, the green marker is on the wrong corner. Changes apply when you let go of a marker; Save keeps them.", + "Drag the four markers onto the real field corners in the image below, then click the number on whichever one sits where the goal line meets the touchline nearest this field's (0,0) corner — that one turns green and becomes first in the output. The other three can be in any order; the calibration algorithm works that out itself. The goal and penalty area this camera should see are drawn dashed through the markers, as vision_processor will read them: if they don't sit on the real ones, the green marker is on the wrong corner. Changes apply when you let go of a marker; Save keeps them.", region: ( camera: number, count: number, @@ -83,7 +83,7 @@ export const geometry = { `Corners were picked at ${picked}, but this image is ${image}. Same aspect ratio, so they can be scaled to fit.`, rescale: (image: string): string => `Rescale corners to ${image}`, otherAspect: (picked: string, image: string): string => - `Corners were picked at ${picked}, but this image is ${image} -- a different aspect ratio, so they can't be scaled. Re-pick them on this image.`, + `Corners were picked at ${picked}, but this image is ${image} — a different aspect ratio, so they can't be scaled. Re-pick them on this image.`, unknownResolution: "These corners were saved without the resolution they were picked at, so a camera resolution change can't be detected. Move any marker to record it.", }, diff --git a/gui/frontend/src/lib/text/wizard.ts b/gui/frontend/src/lib/text/wizard.ts index 7f2dc54..a663783 100644 --- a/gui/frontend/src/lib/text/wizard.ts +++ b/gui/frontend/src/lib/text/wizard.ts @@ -3,11 +3,16 @@ import { plural } from "./common"; export const wizard = { start: "Start from a regulation field, or configure a custom one.", + // Shown above start on a first run. + welcome: + "Welcome. This sets up the field vision_processor measures against. Nothing goes out on the network until you save.", markings: "Which markings does this field have?", review: "Review, then apply to put these values live on the field.", // `backticks` show as code. - applyNote: (path: string): string => - `Applying takes effect immediately but doesn't save -- use Save in the settings menu (or Ctrl+S) to write \`${path}\`, then calibrate each camera on its own Geometry tab.`, + applyNote: (path: string, firstRun: boolean): string => + firstRun + ? `Applying puts these values live and opens Save: saving writes \`${path}\` and starts publishing. Then calibrate each camera on its own Geometry tab.` + : `Applying puts these values live but doesn't save: use Save in the settings menu (or Ctrl+S) to write \`${path}\`, then calibrate each camera on its own Geometry tab.`, // The dimensions step. Saying which way each runs keeps length and width // from being swapped. halfLength: (full: number): string => diff --git a/gui/frontend/src/lib/wizard/steps/WizardDimensionsPreview.svelte b/gui/frontend/src/lib/wizard/steps/WizardDimensionsPreview.svelte index b0797f6..7d8ed25 100644 --- a/gui/frontend/src/lib/wizard/steps/WizardDimensionsPreview.svelte +++ b/gui/frontend/src/lib/wizard/steps/WizardDimensionsPreview.svelte @@ -217,7 +217,7 @@ svg { width: 100%; height: auto; - background: #0a5c2e; + background: var(--field-green); border-radius: 4px; } diff --git a/gui/frontend/src/lib/wizard/steps/WizardFieldPreview.svelte b/gui/frontend/src/lib/wizard/steps/WizardFieldPreview.svelte index 9080f2c..cb29cfc 100644 --- a/gui/frontend/src/lib/wizard/steps/WizardFieldPreview.svelte +++ b/gui/frontend/src/lib/wizard/steps/WizardFieldPreview.svelte @@ -115,7 +115,7 @@ max-width: 20rem; height: auto; aspect-ratio: 1; - background: #0a5c2e; + background: var(--field-green); border-radius: 4px; } diff --git a/gui/frontend/src/lib/wizard/steps/WizardFinish.svelte b/gui/frontend/src/lib/wizard/steps/WizardFinish.svelte index 964e810..26b12ca 100644 --- a/gui/frontend/src/lib/wizard/steps/WizardFinish.svelte +++ b/gui/frontend/src/lib/wizard/steps/WizardFinish.svelte @@ -37,6 +37,11 @@

- +

diff --git a/gui/frontend/src/lib/wizard/steps/WizardStart.svelte b/gui/frontend/src/lib/wizard/steps/WizardStart.svelte index 413c58e..a0031cd 100644 --- a/gui/frontend/src/lib/wizard/steps/WizardStart.svelte +++ b/gui/frontend/src/lib/wizard/steps/WizardStart.svelte @@ -4,6 +4,7 @@ import { Button, P, Spinner } from "flowbite-svelte"; import { virtualField, loadFieldPresets } from "../../geometry.svelte"; import { skipToFinish, nextStep, applyPresetToDraft } from "../wizard.svelte"; + import { config } from "../../config.svelte"; onMount(() => { if (virtualField.presets.length === 0) void loadFieldPresets(); @@ -19,6 +20,9 @@
+ {#if config.state?.firstRun} +

{text.welcome}

+ {/if}

{text.start}

diff --git a/setup.sh b/setup.sh index 3cf1825..80e72e6 100755 --- a/setup.sh +++ b/setup.sh @@ -123,11 +123,15 @@ read -p " » Install systemd service(s)? [yn]» " enable_systemd if [ "$enable_systemd" = "y" ]; then install_service vision_processor build/vision_processor + # The GUI (gui/README.md) publishes geometry itself; two publishers + # conflict. + echo " » geom_publisher publishes geometry from geometry.yml. The GUI" + echo " (gui/README.md) replaces it: say no if you use the GUI." read -p " » Enable geom_publisher service? [yN]» " enable_geom if [ "$enable_geom" = "y" ]; then install_service geom_publisher "python/geom_publisher.py geometry.yml" else - echo " » Skipping geom_publisher service installationa" + echo " » Skipping geom_publisher service installation" fi else echo " » Skipping systemd service installation" From d7c3f73589f982b54ae4073f0acbe42e901ed2c9 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Sun, 29 Nov 2026 16:10:33 -0500 Subject: [PATCH 24/35] add web component tests, fix foudn bugs --- gui/CLAUDE.md | 11 + gui/REVIEW.md | 12 +- gui/frontend/README.md | 2 +- gui/frontend/package-lock.json | 160 ++++++++++ gui/frontend/package.json | 1 + .../src/lib/CornerPicker.svelte.test.ts | 222 ++++++++++++++ .../src/lib/config/CameraPanel.svelte.test.ts | 276 ++++++++++++++++++ .../src/lib/config/LayoutMap.svelte.test.ts | 147 ++++++++++ .../src/lib/config/WeightTriangle.svelte | 4 +- .../lib/config/WeightTriangle.svelte.test.ts | 168 +++++++++++ .../lib/config/YuvPositionPane.svelte.test.ts | 244 ++++++++++++++++ .../src/lib/testing/YuvHarness.svelte | 26 ++ gui/frontend/src/lib/testing/dom.ts | 103 +++++++ gui/frontend/src/test-setup.ts | 61 ++++ gui/frontend/vite.config.ts | 18 +- 15 files changed, 1444 insertions(+), 11 deletions(-) create mode 100644 gui/frontend/src/lib/CornerPicker.svelte.test.ts create mode 100644 gui/frontend/src/lib/config/CameraPanel.svelte.test.ts create mode 100644 gui/frontend/src/lib/config/LayoutMap.svelte.test.ts create mode 100644 gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts create mode 100644 gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts create mode 100644 gui/frontend/src/lib/testing/YuvHarness.svelte create mode 100644 gui/frontend/src/lib/testing/dom.ts diff --git a/gui/CLAUDE.md b/gui/CLAUDE.md index 84e3b38..d2aa8e2 100644 --- a/gui/CLAUDE.md +++ b/gui/CLAUDE.md @@ -351,6 +351,17 @@ checks real responses against the spec for that. words every alert code the host can raise. After adding a code, regenerate it with `go test ./internal/alerts -run Codes -update`. +Frontend logic lives in `.ts` modules with plain Vitest tests next to them +(`corners.ts`, `config/yuvPlane.ts`, ...); a component keeps only wiring. +Components are tested through `@testing-library/svelte` in +`.svelte.test.ts` (the extra `.svelte` keeps the name apart from a +same-named module's test on case-insensitive filesystems). jsdom lacks layout, +SVG screen transforms, pointer capture and canvas: `src/lib/testing/dom.ts` +stubs them per test, and `src/test-setup.ts` fills in what every component +needs (`matchMedia`, ``, `animate`). A component whose props are bound +by its parent is tested through a harness that binds them the same way +(`src/lib/testing/YuvHarness.svelte`). Tailwind is left out under Vitest. + Real multicast is tested over loopback (`internal/multicast/loopback_test.go`, `internal/video/loopback_test.go`, `cmd/.../realsockets_test.go`, helpers in `internal/multicast/mctest`). Ubuntu ships loopback with multicast off, so diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 80557fb..959d0b8 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -27,10 +27,10 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i ## Status -Updated 2026-11-29. **Open** 14 · **Partial** 2 · **Done** 53 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +Updated 2026-11-29. **Open** 14 · **Partial** 1 · **Done** 54 · **v2.1** 1 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. **Next up** (MVP gate order; see the end of this file): -All blockers are fixed. T1-8, T2-5, T4-7, T5-7 and T8-5 are awaiting commit. Left of the MVP gate: T7-1's component tests (`@testing-library/svelte`, Will to decide) and T2-10 (lab machine). +All blockers are fixed. T7-1's component tests are awaiting commit. Left of the MVP gate: T2-10 (lab machine). **Needs the lab PoE machine:** T2-10. @@ -88,7 +88,7 @@ All blockers are fixed. T1-8, T2-5, T4-7, T5-7 and T8-5 are awaiting commit. Lef | T6-5 | major | Claude + Will | quick start stops at first save | done | | T6-6 | minor | Claude | root README pointers | done | | T6-7 | nit | Claude | README details | partial | -| T7-1 | major | Will | no component tests | partial | +| T7-1 | major | Will | no component tests | done | | T7-2 | major | Will | untested logic modules | done | | T7-3 | major | Will | flowbite `Input` unmount error (`test.fail`) | done | | T7-4 | major | Will + Claude | e2e scenario gaps, axe | done | @@ -545,7 +545,7 @@ Overall: the Go side is excellent. Integration-first tests, real sockets, a fake | Unit | broad, every package | 8 files: alerts, cameraLayout, checklist, corners, live, teams, report ×2 | | Integration (real sockets, fake VP) | `realsockets_test`, `supervised_test`, loopback suites (CI only) | none | | API contract | `responses_test`, `declared_test`, `openapi_test` | none (see T3-2) | -| Component | n/a | **none** (62 components, 10.5k lines) | +| Component | n/a | **none** (62 components, 10.5k lines); *2026-11-29:* the five math-heavy ones (T7-1) | | E2E (real host, Chrome) | | 13 tests, 1 known-bug marker | | Packaging / release | `release-check.sh`, `deb-check.sh` on systemd | | | Accessibility | | **none** | @@ -554,7 +554,9 @@ Overall: the Go side is excellent. Integration-first tests, real sockets, a fake There are no component tests. The interactive, math-heavy components (`config/YuvPositionPane.svelte` 1047 lines, `config/CameraPanel.svelte` 650, `config/WeightTriangle.svelte` 529, `CornerPicker.svelte` 450, `config/LayoutMap.svelte` 320) are covered only by e2e tests that mostly assert "it renders". Fix: follow the repo's existing pattern of pulling logic out into `.ts` modules and unit-testing those (as `corners.ts` and `cameraLayout.ts` already are). For the remainder, add `@testing-library/svelte` on the existing `jsdom` dev dependency. Priority: corner picking, YUV plane and weight-triangle coordinate math, layout map drag and assignment. -*Progress 2026-11-29 (Claude, at Will's request; uncommitted):* the math is out of the five components and tested: `config/yuvPlane.ts` (screen/V flip, pointer to U/V, gamut fit, wheel step, the painted plane), `config/weights.ts` (barycentric round trip, clamping to the floor, typed-percent input), `corners.ts` (starting corners, clamping, resolution check, rescale), `config/layoutTiles.ts` (tile placement, details corner, video orientation, checked against the composed CSS transforms for all 32 cases) and `config/cameraPanel.ts` (process message priority, device path notes, resolution check, white balance modes). Components keep their behaviour; checked in Chrome against the committed build (plane and triangle drags, tile styles identical). Mutating each module makes its tests fail. **Bug found and fixed:** the corner picker's starting rectangle was fractional on images whose size isn't a multiple of 20 (1280x1024, 2048x1536); the host refused the whole PUT and the first dragged corner jumped back on release. Rounded in `initialCorners`; an e2e test ("a dragged corner stays where it's dropped") fails without it. **Still open:** component tests proper (`@testing-library/svelte`, a new dev dependency; Will to decide). +*Progress 2026-11-29 (Claude, at Will's request; committed `77fd81d`):* the math is out of the five components and tested: `config/yuvPlane.ts` (screen/V flip, pointer to U/V, gamut fit, wheel step, the painted plane), `config/weights.ts` (barycentric round trip, clamping to the floor, typed-percent input), `corners.ts` (starting corners, clamping, resolution check, rescale), `config/layoutTiles.ts` (tile placement, details corner, video orientation, checked against the composed CSS transforms for all 32 cases) and `config/cameraPanel.ts` (process message priority, device path notes, resolution check, white balance modes). Components keep their behaviour; checked in Chrome against the committed build (plane and triangle drags, tile styles identical). Mutating each module makes its tests fail. **Bug found and fixed:** the corner picker's starting rectangle was fractional on images whose size isn't a multiple of 20 (1280x1024, 2048x1536); the host refused the whole PUT and the first dragged corner jumped back on release. Rounded in `initialCorners`; an e2e test ("a dragged corner stays where it's dropped") fails without it. **Still open:** component tests proper (`@testing-library/svelte`, a new dev dependency; Will to decide). + +*Done 2026-11-29 (Claude, at Will's request):* `@testing-library/svelte` (dev dependency) and 46 component tests for the five: `WeightTriangle` (drags, floor, restore defaults, unlock, typed percent), `YuvPositionPane` (click to set U/V, undo/redo by button and keyboard, Ctrl+Z left to text fields, wheel preview, restore one and all, selecting by marker), `CornerPicker` (no frame, starting corners, drag and clamp, origin choice, saved, rescalable and other-aspect seeds), `LayoutMap` (tiles, selection, mirrored and rotated views, video only while feeds are on) and `CameraPanel` (driver choice, OpenCV path from the host's list, SDK index and serial, resolution, white balance modes, the supervised process). Named `.svelte.test.ts`; helpers in `src/lib/testing/`, browser stand-ins in `test-setup.ts`, Tailwind off under Vitest; described in `gui/CLAUDE.md` Testing. Nine mutations to the components each fail a test. **Bug found and fixed:** clearing the minimum reference weight box (or typing something a number input can't read) set the floor to 0, since the input reports "" and `Number("")` is 0; it now puts the last floor back. **T7-2 | major | Will | untested logic modules** None of these has a test: diff --git a/gui/frontend/README.md b/gui/frontend/README.md index efe0c34..29153ff 100644 --- a/gui/frontend/README.md +++ b/gui/frontend/README.md @@ -122,7 +122,7 @@ npm run preview # serve the production build locally npm run check # svelte-check + tsc (type-check everything) npm run lint # eslint over src/ npm run check:text # user-facing text only in src/lib/text/ -npm test # vitest unit tests (src/**/*.test.ts, scripts/) +npm test # vitest: unit and component tests (src/**/*.test.ts, scripts/) npm run format # prettier --write . npm run format:check # prettier --check . (CI-style) ``` diff --git a/gui/frontend/package-lock.json b/gui/frontend/package-lock.json index cc696db..ae12af2 100644 --- a/gui/frontend/package-lock.json +++ b/gui/frontend/package-lock.json @@ -20,6 +20,7 @@ "@playwright/test": "^1.64.1", "@sveltejs/vite-plugin-svelte": "^7.1.2", "@tailwindcss/vite": "^4.3.3", + "@testing-library/svelte": "^5.4.2", "@tsconfig/svelte": "^5.0.8", "@types/node": "^24.12.3", "@vitest/coverage-v8": "^5.1.0", @@ -147,6 +148,16 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.16.tgz", + "integrity": "sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/types": { "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", @@ -1596,6 +1607,76 @@ "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/dom/node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@testing-library/svelte": { + "version": "5.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/svelte/-/svelte-5.4.2.tgz", + "integrity": "sha512-4o31E4HGo5BU5KwPkulNRocEden+7Tt9JYm9uhln5ajF7DULeyFA46BBWVfKJ8Ms9B3JmOFPTIiVamH7n3KpuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@testing-library/dom": "9.x.x || 10.x.x", + "@testing-library/svelte-core": "1.1.3" + }, + "engines": { + "node": ">= 10" + }, + "peerDependencies": { + "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0", + "vite": "*", + "vitest": "*" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + }, + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/svelte-core": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@testing-library/svelte-core/-/svelte-core-1.1.3.tgz", + "integrity": "sha512-KkMAvXeWorxN2Yn0kdC1lfoAItxpoj4uOWzxK5leDrNxonLvS5nwBFvztrroyTszQ0Wf/EU6iLT8JhY5qcn22g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0" + } + }, "node_modules/@tsconfig/svelte": { "version": "5.0.9", "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.9.tgz", @@ -1614,6 +1695,13 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -2080,6 +2168,29 @@ "node": ">=6" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/apexcharts": { "version": "5.16.0", "resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-5.16.0.tgz", @@ -2323,6 +2434,16 @@ "node": ">=0.10.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2338,6 +2459,13 @@ "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", "license": "MIT" }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, "node_modules/enhanced-resolve": { "version": "5.27.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", @@ -3469,6 +3597,16 @@ "node": "20 || >=22" } }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, "node_modules/magic-string": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", @@ -3951,6 +4089,21 @@ "svelte": "^3.2.0 || ^4.0.0-next.0 || ^5.0.0-next.0" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -3981,6 +4134,13 @@ "dev": true, "license": "MIT" }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT" + }, "node_modules/readdirp": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", diff --git a/gui/frontend/package.json b/gui/frontend/package.json index c837812..a037e0d 100644 --- a/gui/frontend/package.json +++ b/gui/frontend/package.json @@ -26,6 +26,7 @@ "@playwright/test": "^1.64.1", "@sveltejs/vite-plugin-svelte": "^7.1.2", "@tailwindcss/vite": "^4.3.3", + "@testing-library/svelte": "^5.4.2", "@tsconfig/svelte": "^5.0.8", "@types/node": "^24.12.3", "@vitest/coverage-v8": "^5.1.0", diff --git a/gui/frontend/src/lib/CornerPicker.svelte.test.ts b/gui/frontend/src/lib/CornerPicker.svelte.test.ts new file mode 100644 index 0000000..f0d9c75 --- /dev/null +++ b/gui/frontend/src/lib/CornerPicker.svelte.test.ts @@ -0,0 +1,222 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/svelte"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import CornerPicker from "./CornerPicker.svelte"; +import { cameraDoc, config, type CameraDoc } from "./config.svelte"; +import { blankField } from "./geometry.svelte"; +import { geometry } from "./text/geometry"; +import { pointer, stubPointerCapture, stubSvgScreen } from "./testing/dom"; + +const text = geometry.cornerPicker; + +// The calibration frame: 1424 x 1224, shown at half size. +const WIDTH = 1424; +const HEIGHT = 1224; +const SCALE = 0.5; + +function load(seed?: CameraDoc["seed"]): void { + config.doc = { + version: 2, + field: { ...blankField(), fieldLength: 9000, fieldWidth: 6000 }, + optionalFieldLines: { + goal2Goal: true, + halfway: true, + centerCircle: true, + penalty: true, + }, + cameras: [{ cameraId: 0, ...(seed ? { seed } : {}) }], + }; +} + +function snapshots(list: { cameraId: number; view: string }[]): void { + vi.spyOn(globalThis, "fetch").mockImplementation((input) => { + const url = input instanceof Request ? input.url : String(input); + const body = url.endsWith("/api/snapshots") + ? JSON.stringify(list) + : JSON.stringify({ error: "internal", message: "not in this test" }); + + return Promise.resolve( + new Response(body, { + status: url.endsWith("/api/snapshots") ? 200 : 500, + headers: { "Content-Type": "application/json" }, + }), + ); + }); +} + +// Shows the picker with its frame loaded. +async function shown(): Promise { + render(CornerPicker, { cameraId: 0 }); + const img = await screen.findByAltText("cam 0 calibration input"); + Object.defineProperty(img, "naturalWidth", { value: WIDTH }); + Object.defineProperty(img, "naturalHeight", { value: HEIGHT }); + await fireEvent.load(img); +} + +function handles(): { x: number; y: number }[] { + return [...document.querySelectorAll("circle.handle")].map((c) => ({ + x: Number(c.getAttribute("cx")), + y: Number(c.getAttribute("cy")), + })); +} + +function seed(): NonNullable { + const s = cameraDoc(0)?.seed; + if (!s) throw new Error("no seed written"); + return s; +} + +// Drags handle index to image point (x, y). +async function drag(index: number, x: number, y: number): Promise { + const circle = document.querySelectorAll("circle.handle")[index]; + const container = screen.getByRole("application", { + name: "Calibration corner picker", + }); + if (!circle) throw new Error(`no handle ${String(index)}`); + + await fireEvent(circle, pointer("pointerdown", 0, 0)); + await fireEvent(container, pointer("pointermove", x * SCALE, y * SCALE)); + await fireEvent(container, pointer("pointerup", x * SCALE, y * SCALE)); +} + +beforeEach(() => { + stubSvgScreen(SCALE); + stubPointerCapture(); + config.state = null; + load(); + snapshots([{ cameraId: 0, view: "geomcalib_input" }]); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("CornerPicker", () => { + it("says so when the camera has saved no frame", async () => { + snapshots([{ cameraId: 1, view: "geomcalib_input" }]); + render(CornerPicker, { cameraId: 0 }); + + expect(await screen.findByText(text.noFrame(0))).toBeTruthy(); + expect(screen.queryByAltText("cam 0 calibration input")).toBeNull(); + }); + + it("starts with an inset rectangle on whole pixels", async () => { + await shown(); + + expect(handles()).toEqual([ + { x: 214, y: 184 }, + { x: 1210, y: 184 }, + { x: 1210, y: 1040 }, + { x: 214, y: 1040 }, + ]); + }); + + it("writes the corners on release, at the image's resolution", async () => { + await shown(); + await drag(1, 1100.4, 250.6); + + expect(handles()[1]).toEqual({ x: 1100, y: 251 }); + expect(seed()).toMatchObject({ + resolution: [WIDTH, HEIGHT], + lineCorners: [ + [214, 184], + [1100, 251], + [1210, 1040], + [214, 1040], + ], + goalSideMarker: 1, + slot: { cameraId: 0, cameraCount: 1 }, + }); + }); + + it("keeps a dragged corner on the image", async () => { + await shown(); + await drag(0, -50, 99999); + + expect(handles()[0]).toEqual({ x: 0, y: HEIGHT }); + }); + + it("puts the chosen origin first, the rest following around", async () => { + await shown(); + const labels = screen.getAllByRole("button", { name: /^[1-4]$/ }); + await fireEvent.click(labels[2] as Element); + + expect(seed()).toMatchObject({ + lineCorners: [ + [1210, 1040], + [214, 1040], + [214, 184], + [1210, 184], + ], + goalSideMarker: 3, + }); + expect(document.querySelector("circle.origin")?.getAttribute("cx")).toBe( + "1210", + ); + }); + + it("shows saved corners that fit the image", async () => { + load({ + resolution: [WIDTH, HEIGHT], + lineCorners: [ + [100, 100], + [1300, 120], + [1310, 1100], + [90, 1110], + ], + goalSideMarker: 1, + }); + await shown(); + + expect(handles()[1]).toEqual({ x: 1300, y: 120 }); + expect(screen.getByText(/line_corners:/).textContent).toContain( + "- [100, 100]", + ); + }); + + it("offers to rescale corners picked at the same aspect", async () => { + load({ + resolution: [WIDTH * 2, HEIGHT * 2], + lineCorners: [ + [200, 200], + [2600, 240], + [2620, 2200], + [180, 2220], + ], + goalSideMarker: 1, + }); + await shown(); + const size = `${String(WIDTH)}x${String(HEIGHT)}`; + + await fireEvent.click( + screen.getByRole("button", { name: text.rescale(size) }), + ); + + expect(seed().resolution).toEqual([WIDTH, HEIGHT]); + expect(seed().lineCorners[1]).toEqual([1300, 120]); + await waitFor(() => { + expect( + screen.queryByRole("button", { name: text.rescale(size) }), + ).toBeNull(); + }); + }); + + it("explains corners picked at another aspect", async () => { + load({ + resolution: [1920, 1080], + lineCorners: [ + [10, 10], + [20, 10], + [20, 20], + [10, 20], + ], + goalSideMarker: 1, + }); + await shown(); + + expect( + screen.getByText( + text.otherAspect("1920x1080", `${String(WIDTH)}x${String(HEIGHT)}`), + ), + ).toBeTruthy(); + }); +}); diff --git a/gui/frontend/src/lib/config/CameraPanel.svelte.test.ts b/gui/frontend/src/lib/config/CameraPanel.svelte.test.ts new file mode 100644 index 0000000..3ad35c2 --- /dev/null +++ b/gui/frontend/src/lib/config/CameraPanel.svelte.test.ts @@ -0,0 +1,276 @@ +import { fireEvent, render, screen } from "@testing-library/svelte"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cameraDoc, config } from "../config.svelte"; +import { blankField } from "../geometry.svelte"; +import { processes, type ProcessStatus } from "../processes.svelte"; +import { schema, type Schema } from "../schema.svelte"; +import { camera as text } from "../text/camera"; +import CameraPanel from "./CameraPanel.svelte"; + +// gui/internal/config's schema.go: the camera: keys and the drivers. +const SCHEMA = { + settings: { + "camera.driver": { type: "string", default: "SPINNAKER", apply: "restart" }, + "camera.id": { type: "integer", default: 0, apply: "restart" }, + "camera.device": { type: "string", apply: "restart" }, + "camera.path": { type: "string", apply: "restart" }, + "camera.width": { type: "integer", default: 0, apply: "restart" }, + "camera.height": { type: "integer", default: 0, apply: "restart" }, + "camera.exposure": { type: "number", default: 0, apply: "restart" }, + "camera.gain": { type: "number", default: 0, apply: "restart" }, + "camera.gamma": { type: "number", default: 1, apply: "restart" }, + "camera.white_balance": { + type: "white_balance", + default: "OUTDOOR", + apply: "restart", + }, + }, + drivers: [ + { + id: "DUMMY", + selectsBy: "none", + serial: false, + gamma: false, + whiteBalanceProfiles: false, + }, + { + id: "SPINNAKER", + selectsBy: "id", + serial: true, + gamma: true, + whiteBalanceProfiles: true, + }, + { + id: "MVIMPACT", + selectsBy: "id", + serial: true, + gamma: true, + whiteBalanceProfiles: false, + }, + { + id: "DC1394", + selectsBy: "id", + serial: false, + gamma: true, + whiteBalanceProfiles: false, + }, + { + id: "OPENCV", + selectsBy: "path", + serial: false, + gamma: false, + whiteBalanceProfiles: false, + }, + ], +} as unknown as Schema; + +const DEVICES = [ + { path: "/dev/v4l/by-id/usb-cam", kind: "by-id", name: "Webcam" }, + { path: "/dev/video0", kind: "node", name: "Webcam" }, +]; + +const INSTANCE = { id: "host-a/0", host: "host-a", cameraId: 0 }; + +let restart: Response; + +function load(block: Record): void { + config.doc = { + version: 2, + field: { ...blankField(), fieldLength: 9000, fieldWidth: 6000 }, + optionalFieldLines: { + goal2Goal: true, + halfway: true, + centerCircle: true, + penalty: true, + }, + cameras: [ + { + cameraId: 0, + instance: "host-a", + configPath: "/cfg/cam0.yml", + config: { camera: block }, + }, + ], + }; +} + +function block(): Record | undefined { + return cameraDoc(0)?.config?.["camera"] as + Record | undefined; +} + +function proc(over: Partial = {}): ProcessStatus { + return { + cameraId: 0, + configPath: "/cfg/cam0.yml", + crashes: 0, + output: ["starting"], + pendingKeys: [], + restarts: 2, + since: "2026-11-29T00:00:00Z", + state: "running", + pid: 4242, + ...over, + }; +} + +async function choose(select: HTMLElement, value: string): Promise { + await fireEvent.change(select, { target: { value } }); +} + +beforeEach(() => { + vi.stubGlobal("MediaSource", undefined); + schema.value = SCHEMA; + config.state = null; + processes.list = []; + restart = new Response( + JSON.stringify({ error: "internal", message: "restart refused" }), + { status: 500, headers: { "Content-Type": "application/json" } }, + ); + vi.spyOn(globalThis, "fetch").mockImplementation((input) => { + const url = input instanceof Request ? input.url : String(input); + if (url.endsWith("/api/capture-devices")) { + return Promise.resolve( + new Response(JSON.stringify(DEVICES), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + if (url.includes("/restart")) return Promise.resolve(restart); + return new Promise(() => undefined); + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("CameraPanel", () => { + it("asks to pick a camera instance when none is", () => { + render(CameraPanel, { instance: undefined }); + expect(screen.getByText(text.noInstance)).toBeTruthy(); + }); + + it("asks for a driver, and hides what depends on one, until it's chosen", async () => { + load({ driver: "DUMMY" }); + render(CameraPanel, { instance: INSTANCE }); + + expect(screen.getByText(text.noDriver)).toBeTruthy(); + expect(screen.queryByText("Resolution")).toBeNull(); + expect(screen.queryByText("White balance")).toBeNull(); + + await choose(screen.getByLabelText("Driver"), "OPENCV"); + expect(block()).toEqual({ driver: "OPENCV" }); + expect(screen.queryByText(text.noDriver)).toBeNull(); + expect(screen.getByText("Resolution")).toBeTruthy(); + }); + + it("selects an OpenCV camera by path, from the host's list", async () => { + load({ driver: "OPENCV" }); + render(CameraPanel, { instance: INSTANCE }); + + const list = screen.getByLabelText("Cameras on this host"); + expect( + await screen.findByText(/Webcam \(this camera, any port\)/), + ).toBeTruthy(); + expect(screen.getByText(text.path.unstable)).toBeTruthy(); + + await choose(list, "0"); + expect(block()).toEqual({ driver: "OPENCV", device: DEVICES[0]?.path }); + expect(screen.queryByText(text.path.unstable)).toBeNull(); + expect(screen.queryByLabelText("Camera index")).toBeNull(); + }); + + it("retires the old path key when a device is set", async () => { + load({ driver: "OPENCV", path: "/dev/video3" }); + render(CameraPanel, { instance: INSTANCE }); + + const path = screen.getByLabelText("Path"); + await fireEvent.change(path, { target: { value: " /dev/v4l/by-id/x " } }); + expect(block()).toEqual({ driver: "OPENCV", device: "/dev/v4l/by-id/x" }); + }); + + it("selects an SDK camera by index or serial", async () => { + load({ driver: "SPINNAKER" }); + render(CameraPanel, { instance: INSTANCE }); + + expect(screen.queryByLabelText("Path")).toBeNull(); + await fireEvent.change(screen.getByLabelText("Camera index"), { + target: { value: "2" }, + }); + await fireEvent.change(screen.getByLabelText("Serial"), { + target: { value: "21290001" }, + }); + expect(block()).toEqual({ driver: "SPINNAKER", id: 2, device: "21290001" }); + }); + + it("writes a resolution from the list, and refuses half of one", async () => { + load({ driver: "OPENCV" }); + render(CameraPanel, { instance: INSTANCE }); + + await choose(screen.getByLabelText("Size"), "4"); + expect(block()).toMatchObject({ width: 1280, height: 720 }); + + const height = screen.getByLabelText("Height"); + await fireEvent.input(height, { target: { value: "0" } }); + await fireEvent.change(height); + expect(screen.getByText(text.resolution.setBoth)).toBeTruthy(); + expect(block()).toMatchObject({ width: 1280, height: 720 }); + }); + + it("offers a driver's white balance profiles, or plain auto", async () => { + load({ driver: "SPINNAKER" }); + const { unmount } = render(CameraPanel, { instance: INSTANCE }); + const options = (): string[] => + [...screen.getByLabelText("Mode").options].map( + (o) => o.value, + ); + + expect(options()).toEqual(["OUTDOOR", "INDOOR", "manual"]); + await choose(screen.getByLabelText("Mode"), "INDOOR"); + expect(block()).toMatchObject({ white_balance: "INDOOR" }); + unmount(); + + load({ driver: "OPENCV" }); + render(CameraPanel, { instance: INSTANCE }); + expect(options()).toEqual(["auto", "manual"]); + }); + + it("shows manual gains once manual is chosen", async () => { + load({ driver: "SPINNAKER" }); + render(CameraPanel, { instance: INSTANCE }); + expect(screen.queryByText("Red")).toBeNull(); + + await choose(screen.getByLabelText("Mode"), "manual"); + expect(typeof block()?.["white_balance"]).toBe("object"); + expect(screen.getByText("Red")).toBeTruthy(); + expect(screen.getByText("Blue")).toBeTruthy(); + }); + + it("shows the supervised process, and why a restart failed", async () => { + load({ driver: "OPENCV" }); + processes.list = [proc({ crashes: 3 })]; + render(CameraPanel, { instance: INSTANCE }); + + expect(screen.getByText(text.process.pid(4242))).toBeTruthy(); + expect(screen.getByText(text.process.crashes(3))).toBeTruthy(); + + await fireEvent.click( + screen.getByRole("button", { name: text.process.restartNow }), + ); + expect(await screen.findByText("restart refused")).toBeTruthy(); + }); + + it("can't restart a process that has no camera", () => { + load({ driver: "DUMMY" }); + processes.list = [proc({ state: "no_camera" })]; + render(CameraPanel, { instance: INSTANCE }); + + const button = screen.getByRole("button", { + name: text.process.restartNow, + }); + expect(button.disabled).toBe(true); + expect(screen.getByText(text.process.noCamera)).toBeTruthy(); + }); +}); diff --git a/gui/frontend/src/lib/config/LayoutMap.svelte.test.ts b/gui/frontend/src/lib/config/LayoutMap.svelte.test.ts new file mode 100644 index 0000000..0d8693f --- /dev/null +++ b/gui/frontend/src/lib/config/LayoutMap.svelte.test.ts @@ -0,0 +1,147 @@ +import { fireEvent, render, screen } from "@testing-library/svelte"; +import { flushSync } from "svelte"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { config, type CameraDoc, type ConfigDocument } from "../config.svelte"; +import { blankField } from "../geometry.svelte"; +import { layoutView } from "../layoutView.svelte"; +import LayoutMap from "./LayoutMap.svelte"; + +function doc(cameras: CameraDoc[], regions: number): ConfigDocument { + return { + version: 2, + field: { ...blankField(), fieldLength: 9000, fieldWidth: 6000 }, + optionalFieldLines: { + goal2Goal: true, + halfway: true, + centerCircle: true, + penalty: true, + }, + cameras, + layout: { cameraCount: regions }, + }; +} + +const TWO = doc( + [ + { cameraId: 0, instance: "host-a" }, + { cameraId: 1, instance: "host-b" }, + ], + 2, +); + +function tiles(): HTMLButtonElement[] { + return [...document.querySelectorAll("button.tile")]; +} + +function left(tile: HTMLElement | undefined): number { + return Number( + /left:\s*([\d.]+)%/.exec(tile?.getAttribute("style") ?? "")?.[1], + ); +} + +function top(tile: HTMLElement | undefined): number { + return Number( + /top:\s*([\d.]+)%/.exec(tile?.getAttribute("style") ?? "")?.[1], + ); +} + +function corners(): (string | undefined)[] { + return tiles().map( + (t) => t.querySelector("[data-corner]")?.dataset["corner"], + ); +} + +beforeEach(() => { + config.state = null; + layoutView.rotate180 = false; + layoutView.mirror = false; + layoutView.feeds = "off"; +}); + +describe("LayoutMap", () => { + it("draws a tile per region, saying which have no camera", () => { + render(LayoutMap, { + doc: doc([{ cameraId: 0, instance: "host-a" }], 4), + selected: 0, + onselect: vi.fn(), + }); + + expect(tiles()).toHaveLength(4); + expect(screen.getAllByText("No camera")).toHaveLength(3); + expect(screen.getByText("host-a")).toBeTruthy(); + }); + + it("selects a camera from its tile", async () => { + const onselect = vi.fn(); + render(LayoutMap, { doc: TWO, selected: 0, onselect }); + + expect(tiles().map((t) => t.getAttribute("aria-pressed"))).toEqual([ + "true", + "false", + ]); + await fireEvent.click(tiles()[1] as HTMLElement); + expect(onselect).toHaveBeenCalledWith(1); + }); + + it("puts camera 0 on the -x side, details in the outer top corners", () => { + render(LayoutMap, { doc: TWO, selected: 0, onselect: vi.fn() }); + + expect(left(tiles()[0])).toBeLessThan(left(tiles()[1])); + expect(corners()).toEqual(["top-left", "top-right"]); + }); + + it("swaps sides for a mirrored view", () => { + layoutView.mirror = true; + render(LayoutMap, { doc: TWO, selected: 0, onselect: vi.fn() }); + + expect(left(tiles()[0])).toBeGreaterThan(left(tiles()[1])); + expect(corners()).toEqual(["top-right", "top-left"]); + }); + + it("turns the field around for a rotated view", () => { + layoutView.rotate180 = true; + const four = doc( + [0, 1, 2, 3].map((cameraId) => ({ cameraId, instance: "host-a" })), + 4, + ); + render(LayoutMap, { doc: four, selected: 0, onselect: vi.fn() }); + const turned = tiles().map((t) => [left(t), top(t)]); + const turnedCorners = corners(); + document.body.innerHTML = ""; + + layoutView.rotate180 = false; + render(LayoutMap, { doc: four, selected: 0, onselect: vi.fn() }); + const upright = tiles().map((t) => [left(t), top(t)]); + + // Every tile swaps both sides, and keeps its details outermost. + for (let i = 0; i < 4; i++) { + expect(turned[i]?.[0]).not.toBe(upright[i]?.[0]); + expect(turned[i]?.[1]).not.toBe(upright[i]?.[1]); + } + expect(new Set(turnedCorners).size).toBe(4); + expect(corners()).not.toEqual(turnedCorners); + }); + + it("is upright again when rotated and mirrored", () => { + layoutView.rotate180 = true; + layoutView.mirror = true; + render(LayoutMap, { doc: TWO, selected: 0, onselect: vi.fn() }); + + expect(left(tiles()[0])).toBeLessThan(left(tiles()[1])); + }); + + it("shows video only while feeds are on", () => { + vi.stubGlobal("MediaSource", undefined); + render(LayoutMap, { doc: TWO, selected: 0, onselect: vi.fn() }); + expect(document.querySelectorAll("video")).toHaveLength(0); + + layoutView.feeds = "keyframes"; + flushSync(); + expect(document.querySelectorAll("video")).toHaveLength(2); + + layoutView.feeds = "off"; + flushSync(); + expect(document.querySelectorAll("video")).toHaveLength(0); + vi.unstubAllGlobals(); + }); +}); diff --git a/gui/frontend/src/lib/config/WeightTriangle.svelte b/gui/frontend/src/lib/config/WeightTriangle.svelte index 751e319..a77851b 100644 --- a/gui/frontend/src/lib/config/WeightTriangle.svelte +++ b/gui/frontend/src/lib/config/WeightTriangle.svelte @@ -184,7 +184,9 @@ function commitMinForce(): void { const parsed = Number(minForceText); - if (Number.isNaN(parsed)) { + // A number input reports text it can't read as "", which Number makes 0: + // put the floor back rather than drop it. + if (minForceText.trim() === "" || Number.isNaN(parsed)) { minForceText = String(minReferenceForce); return; diff --git a/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts b/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts new file mode 100644 index 0000000..2f1da23 --- /dev/null +++ b/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts @@ -0,0 +1,168 @@ +import { fireEvent, render, screen } from "@testing-library/svelte"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { minReferenceForceUnlock } from "../color.svelte"; +import { preferences } from "../preferences.svelte"; +import { pointer, stubPointerCapture, stubSvgScreen } from "../testing/dom"; +import WeightTriangle from "./WeightTriangle.svelte"; + +// The triangle is drawn at 4 screen pixels per viewBox unit. +const SCALE = 4; + +function readout(): Record { + const terms = [...document.querySelectorAll(".readout dt")]; + return Object.fromEntries( + terms.map((dt) => [ + dt.textContent, + dt.nextElementSibling?.textContent ?? "", + ]), + ); +} + +function svg(): Element { + return screen.getByRole("application", { name: "Color weight triangle" }); +} + +// A drag from viewBox point a to b. +async function drag( + a: { x: number; y: number }, + b: { x: number; y: number }, +): Promise { + await fireEvent(svg(), pointer("pointerdown", a.x * SCALE, a.y * SCALE)); + await fireEvent(svg(), pointer("pointermove", b.x * SCALE, b.y * SCALE)); + await fireEvent(svg(), pointer("pointerup", b.x * SCALE, b.y * SCALE)); +} + +function minForce(): HTMLInputElement { + return screen.getByLabelText("Minimum reference weight"); +} + +beforeEach(() => { + stubSvgScreen(SCALE); + stubPointerCapture(); + minReferenceForceUnlock.unlocked = false; + preferences.expertUser = false; +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("WeightTriangle", () => { + it("shows the weights it's given", () => { + render(WeightTriangle, { + referenceForce: 0.2, + historyForce: 0.5, + minReferenceForce: 0.05, + }); + + expect(readout()).toEqual({ + Reference: "20.0%", + History: "50.0%", + "Current frame": "30.0%", + }); + }); + + it("puts all the weight on the vertex it's dragged to", async () => { + render(WeightTriangle, {}); + await drag({ x: 50, y: 50 }, { x: 50, y: 6 }); + + expect(readout()).toEqual({ + Reference: "100.0%", + History: "0.0%", + "Current frame": "0.0%", + }); + }); + + it("keeps the reference weight at the floor", async () => { + render(WeightTriangle, { minReferenceForce: 0.05 }); + await drag({ x: 50, y: 50 }, { x: 6, y: 94 }); + + expect(readout()).toMatchObject({ Reference: "5.0%", History: "95.0%" }); + }); + + it("pulls a drag past an edge back onto it", async () => { + render(WeightTriangle, { minReferenceForce: 0 }); + await drag({ x: 50, y: 50 }, { x: 50, y: 200 }); + + expect(readout()).toEqual({ + Reference: "0.0%", + History: "50.0%", + "Current frame": "50.0%", + }); + }); + + it("restores vision_processor's default weights", async () => { + render(WeightTriangle, {}); + await drag({ x: 50, y: 50 }, { x: 50, y: 6 }); + await fireEvent.click( + screen.getByRole("button", { name: "Restore default weights" }), + ); + + expect(readout()).toEqual({ + Reference: "10.0%", + History: "70.0%", + "Current frame": "20.0%", + }); + }); + + it("locks the floor until unlocked", async () => { + render(WeightTriangle, {}); + expect(minForce().disabled).toBe(true); + + await fireEvent.click(screen.getByRole("button", { name: "Unlock" })); + const confirm = screen + .getAllByRole("button", { hidden: true }) + .find((b) => b.textContent.includes("I understand")); + if (!confirm) throw new Error("no confirm button"); + await fireEvent.click(confirm); + + expect(minForce().disabled).toBe(false); + }); + + it("starts unlocked for an expert", () => { + preferences.expertUser = true; + render(WeightTriangle, {}); + + expect(minForce().disabled).toBe(false); + }); + + it("reads a typed floor as a percent, and moves the marker above it", async () => { + preferences.expertUser = true; + render(WeightTriangle, { + referenceForce: 0.1, + historyForce: 0.7, + minReferenceForce: 0.05, + }); + + await fireEvent.focus(minForce()); + await fireEvent.input(minForce(), { target: { value: "20" } }); + await fireEvent.keyDown(minForce(), { key: "Enter" }); + + expect(minForce().value).toBe("0.2"); + // History and current frame keep their 70:20 ratio. + expect(readout()).toEqual({ + Reference: "20.0%", + History: "62.2%", + "Current frame": "17.8%", + }); + }); + + it.each([ + ["isn't a number", "abc"], + ["is cleared", ""], + ])("puts back the last floor when what's typed %s", async (_, typed) => { + preferences.expertUser = true; + render(WeightTriangle, { + referenceForce: 0.1, + historyForce: 0.7, + minReferenceForce: 0.05, + }); + + await fireEvent.focus(minForce()); + await fireEvent.input(minForce(), { target: { value: typed } }); + await fireEvent.blur(minForce()); + + expect(minForce().value).toBe("0.05"); + expect(screen.getByText("min 5.0%")).toBeTruthy(); + }); +}); diff --git a/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts b/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts new file mode 100644 index 0000000..00ac9e0 --- /dev/null +++ b/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts @@ -0,0 +1,244 @@ +import { fireEvent, render, screen } from "@testing-library/svelte"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + CLASS_LABELS, + COLOR_CLASSES, + rgbToYuv, + type ColorClass, + type RGB, +} from "../color.svelte"; +import { preferences } from "../preferences.svelte"; +import { schema, type Schema } from "../schema.svelte"; +import { + pointer, + stubCanvas, + stubLayout, + stubPointerCapture, +} from "../testing/dom"; +import YuvHarness from "../testing/YuvHarness.svelte"; + +// vision_processor's fallback colors, as /api/schema has them. +const FALLBACK: Record = { + yellow: [255, 128, 0], + blue: [0, 128, 255], + green: [0, 255, 128], + pink: [255, 0, 128], + orange: [200, 120, 60], + field: [0, 90, 0], +}; + +const GRAY: RGB = { r: 128, g: 128, b: 128 }; + +function colors(): Record { + return Object.fromEntries( + COLOR_CLASSES.map((cls) => [cls, { ...GRAY }]), + ) as Record; +} + +function readout(): { y: number; u: number; v: number } { + const dd = [...document.querySelectorAll(".readout dd")].map((d) => + Number(d.textContent), + ); + return { y: dd[0] ?? NaN, u: dd[1] ?? NaN, v: dd[2] ?? NaN }; +} + +function plane(): Element { + return screen.getByRole("application", { name: "YUV reference plane" }); +} + +function button(name: string): HTMLButtonElement { + return screen.getByRole("button", { name }); +} + +// A click on the plane at (u, v): it's laid out 255 pixels square, V up. +async function clickAt(u: number, v: number): Promise { + await fireEvent(plane(), pointer("pointerdown", u, 255 - v)); + await fireEvent(plane(), pointer("pointerup", u, 255 - v)); +} + +// The colors as the harness holds them. +function held(): Record { + return JSON.parse(screen.getByTestId("colors").textContent) as Record< + ColorClass, + RGB + >; +} + +function selected(): string | null { + return ( + document.querySelector(".current-swatch")?.getAttribute("title") ?? null + ); +} + +beforeEach(() => { + stubLayout({ left: 0, top: 0, width: 255, height: 255 }); + stubCanvas(); + stubPointerCapture(); + preferences.expertUser = false; + preferences.tooltipsEnabled = false; + schema.value = { + settings: { + ...Object.fromEntries( + COLOR_CLASSES.map((cls) => [ + `color.${cls}`, + { type: "color", default: FALLBACK[cls], apply: "live" }, + ]), + ), + "color.reference_force": { type: "number", default: 0.1, apply: "live" }, + "color.history_force": { type: "number", default: 0.7, apply: "live" }, + "color.min_reference_force": { + type: "number", + default: 0.05, + apply: "live", + }, + }, + drivers: [], + } as unknown as Schema; +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("YuvPositionPane", () => { + it("shows the color's own Y, U and V", () => { + render(YuvHarness, { colors: colors() }); + + expect(readout()).toEqual(rgbToYuv(GRAY)); + }); + + it("sets the color's U and V where the plane is clicked", async () => { + render(YuvHarness, { colors: colors() }); + await clickAt(150, 110); + + const { u, v } = readout(); + expect(Math.abs(u - 150)).toBeLessThanOrEqual(1); + expect(Math.abs(v - 110)).toBeLessThanOrEqual(1); + }); + + it("undoes and redoes a click, from the buttons or the keyboard", async () => { + render(YuvHarness, { colors: colors() }); + expect(button("↶ Undo").disabled).toBe(true); + + await clickAt(150, 110); + const moved = readout(); + await fireEvent.click(button("↶ Undo")); + expect(readout()).toEqual(rgbToYuv(GRAY)); + + await fireEvent.click(button("↷ Redo")); + expect(readout()).toEqual(moved); + + await fireEvent.keyDown(window, { key: "z", ctrlKey: true }); + expect(readout()).toEqual(rgbToYuv(GRAY)); + await fireEvent.keyDown(window, { + key: "z", + ctrlKey: true, + shiftKey: true, + }); + expect(readout()).toEqual(moved); + await fireEvent.keyDown(window, { key: "z", metaKey: true }); + await fireEvent.keyDown(window, { key: "y", ctrlKey: true }); + expect(readout()).toEqual(moved); + }); + + it("undoes a move of another class, selecting it again", async () => { + render(YuvHarness, { colors: colors(), selectedClass: "orange" }); + await clickAt(150, 110); + const moved = held().orange; + await fireEvent.click(button("Pink (shell, side)")); + + await fireEvent.click(button("↶ Undo")); + expect(selected()).toBe("Orange (ball) reference"); + expect(held().orange).toEqual(GRAY); + expect(held().pink).toEqual(GRAY); + + await fireEvent.click(button("↷ Redo")); + expect(held().orange).toEqual(moved); + }); + + it("leaves Ctrl+Z to a text field that has focus", async () => { + render(YuvHarness, { colors: colors() }); + await clickAt(150, 110); + const moved = readout(); + + const field = document.createElement("input"); + document.body.append(field); + field.focus(); + await fireEvent.keyDown(window, { key: "z", ctrlKey: true }); + field.remove(); + + expect(readout()).toEqual(moved); + }); + + it("previews another brightness on the wheel without changing the color", async () => { + render(YuvHarness, { colors: colors() }); + const y = rgbToYuv(GRAY).y; + + await fireEvent.wheel(plane(), { deltaY: 100 }); + await fireEvent.wheel(plane(), { deltaY: 100 }); + + expect(screen.getByText(`Y=${String(y - 2)}`)).toBeTruthy(); + expect(readout().y).toBe(y); + }); + + it("restores the selected color to vision_processor's, as an undoable step", async () => { + render(YuvHarness, { colors: colors(), selectedClass: "orange" }); + await fireEvent.click(button("Restore selected color")); + + const [r, g, b] = FALLBACK.orange; + expect(readout()).toEqual(rgbToYuv({ r, g, b })); + + await fireEvent.click(button("↶ Undo")); + expect(readout()).toEqual(rgbToYuv(GRAY)); + }); + + it("asks before restoring every color, unless the user is an expert", async () => { + render(YuvHarness, { colors: colors() }); + + await fireEvent.click(button("Restore all colors")); + expect(screen.getByText("Restore all colors?")).toBeTruthy(); + expect(held().blue).toEqual(GRAY); + + await fireEvent.click(screen.getByRole("button", { name: "Restore all" })); + for (const cls of COLOR_CLASSES) { + const [r, g, b] = FALLBACK[cls]; + expect(held()[cls]).toEqual({ r, g, b }); + } + + // One undo per class puts them all back, last first, selecting each. + for (const cls of [...COLOR_CLASSES].reverse()) { + await fireEvent.click(button("↶ Undo")); + expect(selected()).toBe(`${CLASS_LABELS[cls]} reference`); + } + for (const cls of COLOR_CLASSES) expect(held()[cls]).toEqual(GRAY); + }); + + it("restores every color at once for an expert", async () => { + preferences.expertUser = true; + render(YuvHarness, { colors: colors() }); + + await fireEvent.click(button("Restore all colors")); + const [r, g, b] = FALLBACK.pink; + expect(held().pink).toEqual({ r, g, b }); + expect(screen.queryByText("Restore all colors?")).toBeNull(); + }); + + it("selects another class from its marker, without moving the selected one", async () => { + const all = colors(); + all.blue = { r: 0, g: 128, b: 255 }; + render(YuvHarness, { colors: all, selectedClass: "orange" }); + + const marker = screen.getByTitle("Blue (shell, center) reference"); + await fireEvent(marker, pointer("pointerdown", 0, 0)); + + expect(selected()).toBe("Blue (shell, center) reference"); + expect(button("↶ Undo").disabled).toBe(true); + }); + + it("selects a class from its button", async () => { + render(YuvHarness, { colors: colors() }); + await fireEvent.click(button("Pink (shell, side)")); + + expect(selected()).toBe("Pink (shell, side) reference"); + }); +}); diff --git a/gui/frontend/src/lib/testing/YuvHarness.svelte b/gui/frontend/src/lib/testing/YuvHarness.svelte new file mode 100644 index 0000000..abdd21b --- /dev/null +++ b/gui/frontend/src/lib/testing/YuvHarness.svelte @@ -0,0 +1,26 @@ + + + +
{JSON.stringify(colors)}
diff --git a/gui/frontend/src/lib/testing/dom.ts b/gui/frontend/src/lib/testing/dom.ts new file mode 100644 index 0000000..7c3256c --- /dev/null +++ b/gui/frontend/src/lib/testing/dom.ts @@ -0,0 +1,103 @@ +// What component tests need from a browser that jsdom doesn't have: an SVG's +// screen transform and pointer capture. Each stub is undone by +// vi.restoreAllMocks(). +import { vi } from "vitest"; + +interface Matrix { + a: number; + d: number; + e: number; + f: number; + inverse: () => Matrix; +} + +function matrix(scale: number, x: number, y: number): Matrix { + return { + a: scale, + d: scale, + e: x, + f: y, + inverse: () => matrix(1 / scale, -x / scale, -y / scale), + }; +} + +// Every drawn at scale screen pixels per user unit, its origin at +// (left, top) on screen. +export function stubSvgScreen(scale: number, left = 0, top = 0): void { + const proto = SVGSVGElement.prototype as unknown as Record; + + proto["getScreenCTM"] ??= () => null; + proto["createSVGPoint"] ??= () => null; + + vi.spyOn(SVGSVGElement.prototype, "getScreenCTM").mockImplementation( + () => matrix(scale, left, top) as unknown as DOMMatrix, + ); + vi.spyOn(SVGSVGElement.prototype, "createSVGPoint").mockImplementation(() => { + const point = { + x: 0, + y: 0, + matrixTransform: (m: Matrix) => ({ + x: m.a * point.x + m.e, + y: m.d * point.y + m.f, + }), + }; + return point as unknown as DOMPoint; + }); +} + +// setPointerCapture and friends, which jsdom leaves out. +export function stubPointerCapture(): void { + const proto = Element.prototype as unknown as Record; + + for (const name of [ + "setPointerCapture", + "releasePointerCapture", + "hasPointerCapture", + ]) { + proto[name] ??= () => false; + } + + vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation( + () => undefined, + ); +} + +// A pointer event at screen (x, y). jsdom's PointerEvent drops clientX/Y, +// so they're set on a MouseEvent of the pointer type instead. +export function pointer(type: string, x: number, y: number): Event { + const event = new MouseEvent(type, { + bubbles: true, + cancelable: true, + clientX: x, + clientY: y, + }); + Object.defineProperty(event, "pointerId", { value: 1 }); + + return event; +} + +// Every element laid out as the same box on screen. +export function stubLayout(rect: { + left: number; + top: number; + width: number; + height: number; +}): void { + vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation( + () => ({ + ...rect, + x: rect.left, + y: rect.top, + right: rect.left + rect.width, + bottom: rect.top + rect.height, + toJSON: () => rect, + }), + ); +} + +// No 2D canvas, quietly: jsdom logs an error for getContext otherwise. +export function stubCanvas(): void { + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation( + () => null, + ); +} diff --git a/gui/frontend/src/test-setup.ts b/gui/frontend/src/test-setup.ts index b3be2d7..8dad471 100644 --- a/gui/frontend/src/test-setup.ts +++ b/gui/frontend/src/test-setup.ts @@ -7,3 +7,64 @@ vi.mock("./lib/bus.svelte", () => ({ onTopic: () => () => undefined, topicState: () => ({ current: null }), })); + +// Adds a method jsdom leaves out, where it isn't a function yet. +function polyfill(target: object, name: string, value: unknown): void { + if (typeof (target as Record)[name] !== "function") { + Object.defineProperty(target, name, { + value, + configurable: true, + writable: true, + }); + } +} + +// jsdom has no matchMedia, which flowbite-svelte reads on import: nothing +// matches. +polyfill( + window, + "matchMedia", + (query: string) => + ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => undefined, + removeEventListener: () => undefined, + dispatchEvent: () => false, + }) as unknown as MediaQueryList, +); + +// Nor 's modal methods, which flowbite-svelte's Modal calls. +function openDialog(this: HTMLDialogElement): void { + this.open = true; +} + +function closeDialog(this: HTMLDialogElement): void { + this.open = false; + this.dispatchEvent(new Event("close")); +} + +polyfill(HTMLDialogElement.prototype, "showModal", openDialog); +polyfill(HTMLDialogElement.prototype, "show", openDialog); +polyfill(HTMLDialogElement.prototype, "close", closeDialog); + +// Nor the Web Animations API, which Svelte's transitions use: every +// animation finishes at once. +polyfill(Element.prototype, "animate", () => { + const animation = { + onfinish: null as (() => void) | null, + oncancel: null, + currentTime: 0, + playState: "finished", + finished: Promise.resolve(), + cancel: () => undefined, + finish: () => undefined, + pause: () => undefined, + play: () => undefined, + reverse: () => undefined, + }; + queueMicrotask(() => animation.onfinish?.()); + + return animation; +}); diff --git a/gui/frontend/vite.config.ts b/gui/frontend/vite.config.ts index f39cc78..934c9ce 100644 --- a/gui/frontend/vite.config.ts +++ b/gui/frontend/vite.config.ts @@ -1,6 +1,7 @@ /// import { defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { svelteTesting } from "@testing-library/svelte/vite"; import tailwindcss from "@tailwindcss/vite"; import { readFileSync } from "node:fs"; @@ -39,11 +40,19 @@ const frontendBuild = { export default defineConfig({ // tailwindcss() must come before svelte() so Tailwind's own PostCSS-less // Vite transform sees .svelte files before vite-plugin-svelte compiles them. - plugins: [tailwindcss(), svelte()], + // Tests leave Tailwind out: they don't need the styles, and its dev-mode + // transform rejects components' -o cam.json # dump one camera diff --git a/config/README.md b/config/README.md index 5271c59..57b4b01 100644 --- a/config/README.md +++ b/config/README.md @@ -11,8 +11,8 @@ accident. | File | What it is | | --- | --- | | `vision.yml` | The unified config the GUI host owns: field, shared and per-camera settings, locked calibrations. Start here. | -| `legacy/config.yml` | vision_processor's own config, with every setting and its default documented. The GUI generates one of these per local camera from `vision.yml`. | -| `legacy/config-minimal.yml` | The smallest vision_processor config: just what has no usable default. | +| `legacy/config.yml` | ssl-vision-processor's own config, with every setting and its default documented. The GUI generates one of these per local camera from `vision.yml`. | +| `legacy/config-minimal.yml` | The smallest ssl-vision-processor config: just what has no usable default. | | `legacy/geometry-divA.yml` | Division A field (12 x 9 m). Embedded as the GUI's Division A preset. | | `legacy/geometry-divB.yml` | Division B field (9 x 6 m). Embedded as the GUI's Division B preset. | @@ -23,11 +23,11 @@ cp config/vision.yml vision.yml cd gui && make run ``` -For a vision_processor run by hand, without the GUI: +For an ssl-vision-processor run by hand, without the GUI: ```sh cp config/legacy/config.yml config.yml -./build/vision_processor config.yml +./build/ssl-vision-processor config.yml ``` ## Read-only diff --git a/config/legacy/config-minimal.yml b/config/legacy/config-minimal.yml index f4c0d2f..14c991d 100644 --- a/config/legacy/config-minimal.yml +++ b/config/legacy/config-minimal.yml @@ -1,6 +1,6 @@ -# Minimal vision_processor configuration +# Minimal ssl-vision-processor configuration -# Vision camera ID handled by this vision_processor instance. +# Vision camera ID handled by this ssl-vision-processor instance. # On multi camera fields the IDs have to be ordered according to camera_ids.png. cam_id: 0 diff --git a/config/vision.yml b/config/vision.yml index 07db12f..25482c4 100644 --- a/config/vision.yml +++ b/config/vision.yml @@ -63,12 +63,12 @@ layout: # A match setup with a game controller, rather than lab use. Changes how the # GUI keeps robot height choices and how loudly it reports missing setup; -# vision_processor doesn't read it. +# ssl-vision-processor doesn't read it. # competition_field: true # Robot height choices. A team or color without one uses bot_heights_file, # looked up by the game controller's team name. Shown in the GUI only for -# now; vision_processor still uses the game controller and the table. +# now; ssl-vision-processor still uses the game controller and the table. # teams: # # On a competition field: by the game controller's team name, so each # # follows its team if the colors are switched. @@ -80,7 +80,7 @@ layout: # yellow: { height: 150 } # blue: { name: ER-Force } -# Settings every camera shares, in vision_processor's own config.yml layout +# Settings every camera shares, in ssl-vision-processor's own config.yml layout # (see legacy/config.yml for every key and its default). A camera's own # `config` below overrides these key by key. defaults: @@ -118,10 +118,10 @@ defaults: # host running four cameras appears four times. cameras: - camera_id: 0 - # The machine running this camera's vision_processor. + # The machine running this camera's ssl-vision-processor. instance: lab-pc - # A config.yml on this host the GUI regenerates from this file, for a - # vision_processor on the same machine. Omit for a remote one. Use a + # A config.yml on this host the GUI regenerates from this file, for an + # ssl-vision-processor on the same machine. Omit for a remote one. Use a # git-ignored name such as config-local.yml. config_path: config-local.yml # This camera's overrides of `defaults`, same layout. @@ -149,7 +149,7 @@ cameras: # display: { rotate: 0, mirror: false } # The group autorefs send their tracker output to (TrackerWrapperPacket). Only -# the GUI host listens, for the Live Field page; vision_processor doesn't read +# the GUI host listens, for the Live Field page; ssl-vision-processor doesn't read # it. Unset keys take the standard group. # tracker: # ip: 224.5.23.2 diff --git a/flake.nix b/flake.nix index dec728d..f14b001 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "SSL vision_processor build environment"; + description = "ssl-vision-processor build environment"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; @@ -34,7 +34,7 @@ # default shell because ROCm is a multi-gigabyte download nobody # without an AMD card needs. The host's own /etc/OpenCL/vendors can't # be used instead: those drivers link against the distro's libraries, - # not nixpkgs'. vision_processor takes the first GPU it finds; ROCm + # not nixpkgs'. ssl-vision-processor takes the first GPU it finds; ROCm # lists integrated GPUs too (Ryzen 9000's gfx1036 shows up after a # discrete gfx1201), so if the "Using device" log line names the # wrong one, ROCR_VISIBLE_DEVICES=0 (or the right index, from @@ -90,7 +90,7 @@ ]; # The ICD loader finds runtimes through this. Without it the loader - # reports zero platforms and vision_processor exits at startup. + # reports zero platforms and ssl-vision-processor exits at startup. OCL_ICD_VENDORS = "${openclRuntime}/etc/OpenCL/vendors"; # The other league Go tools carry a `toolchain` line newer than the @@ -101,7 +101,7 @@ GOTOOLCHAIN = "local"; shellHook = '' - echo "vision_processor dev shell" + echo "ssl-vision-processor dev shell" echo " eigen ${pkgs.eigen.version}" echo " opencv ${pkgs.opencv.version}" echo " ffmpeg ${pkgs.ffmpeg_8.version}" @@ -110,7 +110,7 @@ echo " node ${pkgs.nodejs_22.version}" echo " buf ${pkgs.buf.version}" echo - echo " cmake -B build . && make -C build -j vision_processor" + echo " cmake -B build . && make -C build -j ssl-vision-processor" echo echo "Camera SDKs (Spinnaker, mvIMPACT) are proprietary and not" echo "packaged here; the OpenCV and DC1394 backends are available." diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index da359a0..58817f9 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -1,25 +1,25 @@ # gui Architecture -This document describes the design of `gui`, the Go host and browser UI for vision_processor. It covers the -subsystem in this directory only. The C++ vision_processor and the Python scripts in `python/` are described in +This document describes the design of `gui`, the Go host and browser UI for ssl-vision-processor. It covers the +subsystem in this directory only. The C++ ssl-vision-processor and the Python scripts in `python/` are described in the root README and are not modified by this subsystem. `gui` replaces `python/geom_publisher.py` for anyone running it. It is a single Go binary with an embedded -Svelte frontend. It owns the shared field geometry, absorbs camera calibrations from vision_processor instances +Svelte frontend. It owns the shared field geometry, absorbs camera calibrations from ssl-vision-processor instances over multicast, and serves the frontend, a JSON API, and a WebSocket for live updates, all on one port. ## System overview -A venue runs one or more vision_processor instances, one per camera, on the gui host's machine or others. Each +A venue runs one or more ssl-vision-processor instances, one per camera, on the gui host's machine or others. Each exchanges SSL vision protocol messages with the host over the same multicast group the rest of the league uses. One on the host's own machine also shares files with it: debug images in `img/`, and its generated `config.yml`. ```mermaid graph LR - VP1["vision_processor cam 1"] + VP1["ssl-vision-processor cam 1"] subgraph Host machine - VP0["vision_processor cam 0"] + VP0["ssl-vision-processor cam 0"] FS[("shared filesystem\nimg/, config.yml")] end @@ -39,10 +39,10 @@ graph LR GUI --> Browser ``` -The gui host does not talk to a vision_processor instance directly (with `-runCameras` it starts them, and hands +The gui host does not talk to an ssl-vision-processor instance directly (with `-runCameras` it starts them, and hands each its config file). Both sides only ever speak to the multicast group, the same way any other league consumer would. This keeps the host interchangeable with the legacy -`geom_publisher.py` service from the vision_processor's point of view. The browser talks to the gui host over +`geom_publisher.py` service from the ssl-vision-processor's point of view. The browser talks to the gui host over HTTP and a WebSocket instead, covered under HTTP API and WebSocket protocol below. ## Process layout @@ -106,14 +106,14 @@ before returning. | `internal/httpjson` | The JSON error body and its codes. | | `internal/origins` | Which browser pages and host names may use the API. | | `internal/alerts` | Every problem the host can see: which, how serious, and the facts behind each. | -| `internal/discovery` | vision_processor instances, from their announces. | +| `internal/discovery` | ssl-vision-processor instances, from their announces. | | `internal/livefield` | The latest detection frame per camera and tracked frame per autoref, for the Live Field page. | | `internal/detections` | Which camera_ids the vision socket hears, from which address, at what rate. Feeds the Camera Layout page. | | `internal/referee` | The current match's teams, from the game controller, and their robot heights from `bot_heights_file`. | | `internal/snapshot` | Debug image listing and serving. | | `internal/video` | Live video: each camera's H.264 RTP stream relayed to browsers as fragmented MP4. | | `internal/peers` | Names senders (IP, port, hostname) and logs and alerts when two of them claim one thing. | -| `internal/supervisor` | `-runCameras`: runs every camera's vision_processor and restarts it when a startup-only setting changes. | +| `internal/supervisor` | `-runCameras`: runs every camera's ssl-vision-processor and restarts it when a startup-only setting changes. | | `internal/v4l` | Lists this host's Video4Linux capture devices for the camera path picker. | | `internal/logging` | slog setup: a coloured console handler, a rotating file handler, and the last warnings and errors kept in memory for the system report. | | `internal/buildinfo` | What the binary was built from: the git state of this repository and the proto submodule, stamped by the Makefile. | @@ -140,7 +140,7 @@ A calibration missing a required proto2 field is rejected with `proto.CheckIniti A received calibration is also rejected, and logged with its sender, unless it could be a real camera's (`geometry.CheckCalibration`): every number finite, a positive focal length, a unit rotation quaternion, a non-empty -image, and the camera above the field. The host republishes what it absorbs every second, and a vision_processor +image, and the camera above the field. The host republishes what it absorbs every second, and an ssl-vision-processor that receives a calibration for its camera skips calibrating and uses it, so one bad packet (a NaN, a test fixture, another host's mistake) would otherwise stop that camera until someone unlocked it by hand. @@ -153,10 +153,10 @@ detections and video, each instance name, the game controller's referee messages publish once a second. A second sender is logged once when it appears (`several senders claim the same thing`, with each sender's IP, port, hostname from reverse DNS, and whether it's this machine) and again when it's gone, and served as a `sender_conflict` alert on `network.state`/`GET /api/network`: an error for calibration, -field geometry and instance names, a warning for the game controller and video, and an error for every kind on a competition field. Two vision_processors on one +field geometry and instance names, a warning for the game controller and video, and an error for every kind on a competition field. Two ssl-vision-processors on one machine both send from the vision port, so they share an address and can't be told apart this way. -A vision_processor's video streamer opens a new port whenever the streamed view changes size, so for video a sender +An ssl-vision-processor's video streamer opens a new port whenever the streamed view changes size, so for video a sender that stops as another begins on its IP is the same program; two that keep sending are a conflict. Every endpoint also notes which interface each packet arrives on. One sender heard on several at once (two @@ -167,16 +167,16 @@ count towards the conflict alert. ## Discovery -vision_processor announces itself on the vision group about once a second, as an `SSL_WrapperPacket` with `config` +ssl-vision-processor announces itself on the vision group about once a second, as an `SSL_WrapperPacket` with `config` set. `internal/discovery` keeps the latest per `SSL_VPConfig.instance`: live while heard within 3 s, forgotten after 30 s. `GET /api/instances` and `instances.state` serve them; no page shows them yet. Two senders of one instance name are a `sender_conflict`. Packets are told apart by `config` being present, not by `source`: the host's own geometry -packets have the same `source`. vision_processor builds its announce once, at startup, and sends it between frames, so +packets have the same `source`. ssl-vision-processor builds its announce once, at startup, and sends it between frames, so one whose camera blocks doesn't announce, and a reloaded config isn't reflected. ## Configuration: vision.yml -`vision.yml` is the one file the host owns. It holds the field template, shared `defaults` in vision_processor's +`vision.yml` is the one file the host owns. It holds the field template, shared `defaults` in ssl-vision-processor's own `config.yml` layout, and a `cameras` list keyed by `camera_id`. Each camera carries its own overrides, its corner picker `seed` (corners plus the image resolution and slot they were picked at), optionally a locked `calibration`, and a GUI-only video `display` orientation. `layout.camera_count` (1, 2 or 4) splits the field into @@ -195,7 +195,7 @@ sequenceDiagram participant Store as config.Store participant Geometry participant Disk as vision.yml - participant VP as vision_processor + participant VP as ssl-vision-processor Browser->>Store: PUT /api/config (working document) Store->>Geometry: ApplyConfig, SetLocked @@ -213,36 +213,36 @@ the run changed, and that had unsaved changes or an edit the host never got, sho whether to put its own back (`keepLostWork` in `config.svelte.ts`). Once one page has, the others with the same document stop asking. -A vision_processor skips calibrating at startup only if the geometry packet it receives already holds a +An ssl-vision-processor skips calibrating at startup only if the geometry packet it receives already holds a calibration for its camera. Publishing locked calibrations is what keeps a restart of either side from triggering -a recalibration. Unlocking stops publishing that camera's calibration. A running vision_processor keeps the model +a recalibration. Unlocking stops publishing that camera's calibration. A running ssl-vision-processor keeps the model it already has, since the protocol has no way to ask for a live recalibration, so it recalibrates on its next restart. -Until vision_processor accepts configuration over the network, a camera with a `config_path` gets its +Until ssl-vision-processor accepts configuration over the network, a camera with a `config_path` gets its `config.yml` regenerated from `vision.yml` on every change, written only when the content differs. The file starts with a header saying it is generated. `reloadConfigIfChanged()` in `src/Resources.cpp` hot reloads `thresholds`, `tracking`, `color`, and `debug` every half second, but never `geometry`, `camera`, `network`, or `stream`. Changes to those take effect when the instance restarts. With `-runCameras`, the host also runs those instances itself (`internal/supervisor`), one per `config_path`, -using the `vision_processor` it finds on `PATH` at startup; it exits if there is none. A host runs every camera or +using the `ssl-vision-processor` it finds on `PATH` at startup; it exits if there is none. A host runs every camera or none, so in this mode every camera gets a `config_path`: `Document.AssignConfigPaths` names it `cam.yml` (or `cam-2.yml` and so on if taken) whenever a document is loaded or edited without one. One assigned on load shows as an unsaved change. Two cameras can't share a `config_path`. Each process runs in its own directory, `run/cam` in the state folder, with `img` there linking to `cam` in `-imgDir`, so the debug files -vision_processor writes relative to its working directory never collide or land in the config folder. Its own image +ssl-vision-processor writes relative to its working directory never collide or land in the config folder. Its own image folder matters because not every file it writes to `img/` is prefixed by camera_id; the snapshot routes read both `-imgDir` and its `cam` folders. It gets its config file's full path, and the rendered file names `bot_heights_file` by its full path too. -Before starting anything, the supervisor compares the cameras' capture devices, with vision_processor's fallbacks +Before starting anything, the supervisor compares the cameras' capture devices, with ssl-vision-processor's fallbacks filled in (`Document.CaptureDevice`: OPENCV opens `/dev/video` when no device is named, other drivers their `id`-th camera) and device paths resolved through symlinks. A camera whose device a lower camera_id already uses is held, not started: state `conflict`, a `device_conflict` alert, and a 409 from its restart route. It starts on its own once its device changes. `Document.Validate` already rejects two cameras on one device on the same `instance`; this also catches cameras on different instances, and two names for one device node. A camera with no driver chosen (DUMMY, which today's -vision_processor exits on) is held too: state `no_camera`, a `camera_not_selected` alert, and a 409 `no_camera`. A +ssl-vision-processor exits on) is held too: state `no_camera`, a `camera_not_selected` alert, and a 409 `no_camera`. A daemon holding a camera is out of scope: the process's own output says the device is busy. @@ -250,11 +250,11 @@ It watches the store like any other subscriber: on each change it renders every config and compares it with what each process was started with. A difference in a setting the schema marks `live` or `host` needs nothing more, since the file is already rewritten; any other difference (startup-only, derived, or unknown) restarts the process once edits have been quiet for a second, so a slider drag restarts it once. -Stopping is SIGTERM, then SIGKILL after 3 s, since vision_processor only checks for SIGTERM between frames. A +Stopping is SIGTERM, then SIGKILL after 3 s, since ssl-vision-processor only checks for SIGTERM between frames. A process that exits on its own is started again: after 1 s for a clean exit, doubling per crash in a row up to 30 s. A change to the field or its optional lines restarts every supervised camera to recalibrate: between stopping the process and starting it again, the host unlocks the camera's calibration and drops the one it last -received, since vision_processor skips calibrating when the geometry packet already holds one for its camera. +received, since ssl-vision-processor skips calibrating when the geometry packet already holds one for its camera. `processes.state` and `GET /api/processes` carry each one's state, pending restart keys, last exit, and last lines of output; `POST /api/processes/{id}/restart` restarts one at once. @@ -279,21 +279,21 @@ it bumps no revision, so the GUI reads it from `config.state`. Its wizard opens dialog, which allows saving with no changes so the defaults can be accepted. The host's own sockets use the shared `defaults.network` block (`vision_ip`, `vision_port`, `gc_ip`, `gc_port`), -with vision_processor's defaults for missing keys. Each is a `multicast.Endpoint`. When an edit changes an +with ssl-vision-processor's defaults for missing keys. Each is a `multicast.Endpoint`. When an edit changes an address, the endpoint closes its sockets and opens new ones on the new address straight away. A multicast address joins the group. Any other IPv4 address, normally a broadcast address for switches whose IGMP snooping -drops multicast, listens on the port instead; vision_processor handles broadcast too, since its socket sets +drops multicast, listens on the port instead; ssl-vision-processor handles broadcast too, since its socket sets `SO_BROADCAST`. The Network page offers the standard, backup (port + 10), legacy (10005), and broadcast choices, warns about addresses that aren't multicast or broadcast, and notes non-standard and privileged (below -`ip_unprivileged_port_start`) choices when extra tooltips are on. vision_processor reads the same block, but only +`ip_unprivileged_port_start`) choices when extra tooltips are on. ssl-vision-processor reads the same block, but only at startup. The autoref tracker socket uses the top-level `tracker` block (`ip`, `port`, default 224.5.23.2:10010) instead, -since no vision_processor listens for tracker output. It is never rendered into a camera's `config.yml`. It may +since no ssl-vision-processor listens for tracker output. It is never rendered into a camera's `config.yml`. It may share the vision group's IP, which is the standard setup, but not its address and port. A silent tracker socket raises no alert, since running without an autoref is normal; one that can't open does. -Which interfaces the host's own sockets use is `host.interfaces`, a section no vision_processor reads, since +Which interfaces the host's own sockets use is `host.interfaces`, a section no ssl-vision-processor reads, since interface names only mean something on one machine. `auto` (the default) uses interfaces that are up, have carrier, support multicast, and have an IPv4 address, and skips loopback and virtual ones (Docker and VM bridges, VPN tunnels); it is re-evaluated every second. Otherwise `skip` is a blacklist. With nothing @@ -309,11 +309,11 @@ when the problem changes. The host also notices a suspend: each second it compar counting while suspended, with `CLOCK_MONOTONIC`, which doesn't. Neither jumps for NTP or clock changes, so a gap means the machine slept, and every socket is reopened. -The Camera page edits each camera's `camera:` block, shown with vision_processor's own fallbacks applied +The Camera page edits each camera's `camera:` block, shown with ssl-vision-processor's own fallbacks applied (`src/driver/cameradriver.cpp`; an unset driver means SPINNAKER; a new config says DUMMY, the protocol's "no camera"). Controls follow the driver: an index for SPINNAKER, MVIMPACT and DC1394, plus a serial number for SPINNAKER, a path for OPENCV, gamma hidden for MVIMPACT, and the OUTDOOR and INDOOR auto white balance profiles only for SPINNAKER. The serial and the path are -both `device`, written in place of its former name `path`, which still reads. vision_processor reads `camera:` +both `device`, written in place of its former name `path`, which still reads. ssl-vision-processor reads `camera:` only at startup. Validation rejects what it would misread instead of refusing: an unknown driver (fatal at startup) and any white balance string other than OUTDOOR or INDOOR (it treats every other string as INDOOR). @@ -364,7 +364,7 @@ reload, lock, unlock) answers `{"revision": n}` with the new revision as its `ET merge, `null` removes a key, and arrays (`cameras`) are replaced whole. PATCH is the safer write for a client that doesn't model the whole document: PUT replaces it, so a key the client dropped is removed. -Some document keys only matter to this GUI and no vision_processor reads them: a camera's `display` (video +Some document keys only matter to this GUI and no ssl-vision-processor reads them: a camera's `display` (video orientation) and `seed.goalSideMarker` (which corner marker was picked). Other clients should leave them as they are. `teams` and `competitionField` are read by the host's alerts, and `tracker` by its tracker socket. Each `Change` in `config.state` has both `path` (vision.yml's spelling, `field.field_width`) and `jsonPath` (the JSON document's, `field.fieldWidth`); in both, @@ -373,7 +373,7 @@ are. `teams` and `competitionField` are read by the host's alerts, and `tracker` `calibration.camera` keep proto field names (`pixel_image_width`), matching how they're stored in vision.yml. "Host-local" endpoints describe the machine running the host, and only describe a camera when its -vision_processor runs on the same machine: device paths and debug images aren't available for remote instances. +ssl-vision-processor runs on the same machine: device paths and debug images aren't available for remote instances. Browser pages from other origins are handled by `internal/origins`. The host's own pages are always allowed. In a lab, so is any page served from this network: `localhost`, a loopback, private or link-local IP, a `.local` name, or @@ -417,7 +417,7 @@ status comes from the network rather than the store. `network.state` carries each multicast socket's address and what it has heard there: vision detection packets (the host's own looped back geometry doesn't count), game controller referee messages, and autoref tracker packets. It is published once per second and on every config change. -`processes.state` carries the vision_processors the host runs (`-runCameras`), on every state change and once per +`processes.state` carries the ssl-vision-processors the host runs (`-runCameras`), on every state change and once per second; an empty list without `-runCameras`. `live-field.state` carries the latest detection frame from each camera (by camera_id and sender) and the latest tracked frame from each autoref (by the uuid it sends), as canonical protojson inside a small envelope with each @@ -425,7 +425,7 @@ source's rate and receive time and the host's clock (`at`), so a client can tell senders' clocks. Detections are in mm, tracked frames in m. A source silent for a second is listed without a frame, and dropped after 30 s. It is published at up to 60 Hz, only while someone subscribes and something new arrived (and once a second otherwise); `GET /api/live-field` returns the same snapshot. -`instances.state` carries every vision_processor heard announcing itself (`internal/discovery`), once per second and +`instances.state` carries every ssl-vision-processor heard announcing itself (`internal/discovery`), once per second and on every config change; the same as `GET /api/instances`. `alerts.state` carries every problem the host can see (`internal/alerts`), on the same schedule: a stable `id`, a `code`, a `severity` (`error`, `warning`, `caution`), an optional `cameraId`, the facts behind it as `params`, @@ -438,7 +438,7 @@ value once it catches up, never a growing backlog of stale ones. ## Live video -Each vision_processor multicasts H.264 over RTP (`src/rtpstreamer.cpp`) to `ip_base_prefix + (ip_base_end + +Each ssl-vision-processor multicasts H.264 over RTP (`src/rtpstreamer.cpp`) to `ip_base_prefix + (ip_base_end + cam_id):port` from its `stream` settings, 224.5.23.100+id:10100 by default. `internal/video` relays it without re-encoding. A camera's socket opens on its first viewer and closes 5 s after its last. Like every endpoint it hears only its own group, so cameras sharing port 10100 don't mix, with a 4 MB receive buffer for a keyframe's @@ -469,7 +469,7 @@ regenerates them as an ordinary build prerequisite. See `gui/DEVELOPMENT.md` for - **Host owned config push.** Diffing an instance's announced config against a desired one and pushing the difference, rather than regenerating a local `config.yml` as the host does today. This also needs a way to ask a running instance to recalibrate. -- **Remote snapshots.** `internal/snapshot` assumes the gui host and the vision_processor instance share a +- **Remote snapshots.** `internal/snapshot` assumes the gui host and the ssl-vision-processor instance share a filesystem. Live video (above) works remotely, but the full-resolution snapshots the corner picker needs do not. - **Translation (i18n), planned for v2.1.** User-facing text moving into one catalog per language, looked up by key. Until then the text stays English and in the source. diff --git a/gui/CLAUDE.md b/gui/CLAUDE.md index d2aa8e2..e2419e2 100644 --- a/gui/CLAUDE.md +++ b/gui/CLAUDE.md @@ -57,14 +57,14 @@ internal/ geometry/ live field template + published calibrations + 1Hz publish loop multicast/ vision + game controller + tracker sockets, interface selection, reopened on address/interface changes - discovery/ vision_processor instances from their SSL_VPConfig announces + discovery/ ssl-vision-processor instances from their SSL_VPConfig announces api/ typed routes + the OpenAPI spec (/api/openapi.json, /api/docs) hub/ topic pub/sub + the /ws handler livefield/ latest detection + autoref tracked frames for the Live Field page snapshot/ debug image listing/serving video/ live video: RTP H.264 -> fMP4 over /ws/video/{id} for MSE v4l/ this host's capture devices, for the camera path picker - supervisor/ -runCameras: runs a vision_processor per config_path, restarting + supervisor/ -runCameras: runs an ssl-vision-processor per config_path, restarting it on startup-only setting changes (config.RestartKeys); holds a camera whose device another already uses logging/ slog setup: tint console + lumberjack file, plus the last 50 @@ -180,15 +180,15 @@ records edits made outside the GUI so the browser can offer load-or-overwrite. Comments in `vision.yml` are not preserved on save; it's machine-written. **Calibrations are locked explicitly, never auto-persisted.** A camera's -published calibration is its locked one, else the latest absorbed. A -vision_processor only skips startup calibration if the packet holds a +published calibration is its locked one, else the latest absorbed. An +ssl-vision-processor only skips startup calibration if the packet holds a calibration for its camera_id, so publishing locked ones is what stops host or VP restarts from triggering recalibration. Unlock withholds the camera's calibration; a running VP keeps its model (no live recalibrate in the protocol), so it recalibrates on its next restart. **Each local camera's `config.yml` is generated, not edited.** It's the -transport until vision_processor accepts config over the network: +transport until ssl-vision-processor accepts config over the network: `defaults` deep-merged with the camera's `config`, plus derived `cam_id`, `camera_amount` (`layout.camera_count`, else the number of cameras rounded up to a power of 2) and `line_corners` (from the seed). This @@ -211,22 +211,22 @@ host owns the flag: `Store.update` keeps it whatever an edit says, and `writeLocked` clears it only once the file is written. Read it from `config.state`, since clearing it bumps no revision. -**`-runCameras` runs every camera's vision_processor, for a single-machine +**`-runCameras` runs every camera's ssl-vision-processor, for a single-machine setup such as a student lab's webcam; events run them as their own services instead.** All or nothing: a host with `-runCameras` gives every region a camera, each with this host as its instance, the driver's camera_id-th device and a `config_path` (`Document.AssignLocal`, via `config.Options.LocalCameras`; `config.state.localCameras` tells the frontend, whose smaller camera count then removes cameras instead of being refused) -and finds `vision_processor` on `PATH` once at startup (no override flag: put +and finds `ssl-vision-processor` on `PATH` once at startup (no override flag: put `build/` first on `PATH`). Each process runs in `/run/cam` with an `img` link to `<-imgDir>/cam`, so its relative debug writes stay apart (not -every file vision_processor writes to `img/` is prefixed by camera_id; +every file ssl-vision-processor writes to `img/` is prefixed by camera_id; `internal/snapshot` reads the `cam` folders too); the config path and the rendered `bot_heights_file` are absolute for that reason. A camera whose device (`Document.CaptureDevice`, symlinks resolved) a lower camera_id already uses is held in state `conflict`, and one with no driver chosen -(`DUMMY`, what `config.Default` writes; today's vision_processor exits on it, +(`DUMMY`, what `config.Default` writes; today's ssl-vision-processor exits on it, upstream PR #61 changes that) in `no_camera`. `internal/supervisor` observes the store (`Sync` on every change) rather than sitting in `Store.apply`: the store still writes the file, and the supervisor restarts a process when `config.RestartKeys` (anything not @@ -234,7 +234,7 @@ and the supervisor restarts a process when `config.RestartKeys` (anything not what it started with and the current render, debounced 1 s. Keyed by `config_path`, so moving a camera to another slot is a restart, not a stop and start. Children get their own process group (terminal Ctrl-C reaches only the -host) and `Pdeathsig`. vision_processor checks SIGTERM only between frames, so +host) and `Pdeathsig`. ssl-vision-processor checks SIGTERM only between frames, so a blocked `readImage()` needs the SIGKILL fallback. A field change restarts every supervised camera and, while it's stopped, unlocks its calibration (`Options.Recalibrate` -> `Store.UnlockCalibration`): otherwise the host keeps @@ -262,13 +262,13 @@ without a file in `dist/`, and the host is compiled before the frontend's first build, to write the OpenAPI spec the frontend's API types are generated from. `make` restores it after each build, since Vite empties `dist/`. -**Discovery is multicast-announce-based.** vision_processor sends +**Discovery is multicast-announce-based.** ssl-vision-processor sends `SSL_WrapperPacket{config}` about once a second on the vision group; `internal/discovery` keys it by `SSL_VPConfig.instance` (live within 3 s, forgotten after 30 s), served as `GET /api/instances` and `instances.state`. Key on `config` being present, never on `source`: the host's own geometry packets say `SSL_SOURCE_VISION_PROCESSOR` too. An announce counts as hearing -the vision group, since a vision_processor without a camera sends nothing else. +the vision group, since an ssl-vision-processor without a camera sends nothing else. Two senders of one instance name raise a `sender_conflict` of kind `instance`. ## Gotchas @@ -319,8 +319,8 @@ and `cmd/.../server_test.go` load real `testdata/*.yml` fixtures rather than constructing Go structs by hand. The full loop (this package's `Geometry`/vision `multicast.Endpoint` against a real -`vision_processor` binary and a real camera) has been manually verified once, -end to end: the Go host published a field template, `vision_processor` +`ssl-vision-processor` binary and a real camera) has been manually verified once, +end to end: the Go host published a field template, `ssl-vision-processor` calibrated against a real skewed webcam view, and the calibration came back and was absorbed with no wire-format surprises between C++ and Go protobuf. Not automated -- there is no CI hardware to run it on. diff --git a/gui/DEVELOPMENT.md b/gui/DEVELOPMENT.md index 82a0ee3..54f9cbe 100644 --- a/gui/DEVELOPMENT.md +++ b/gui/DEVELOPMENT.md @@ -1,13 +1,13 @@ # Developing the GUI -How to build, test, and release `gui`: the Go host and browser UI for vision_processor. It owns `vision.yml` (the -field geometry, per camera settings, and locked calibrations), absorbs camera calibrations from vision_processor +How to build, test, and release `gui`: the Go host and browser UI for ssl-vision-processor. It owns `vision.yml` (the +field geometry, per camera settings, and locked calibrations), absorbs camera calibrations from ssl-vision-processor instances over multicast, and serves the frontend, a JSON API, and a WebSocket for live updates, all on one port. - To run the GUI rather than change it, see [README.md](README.md). - For how it fits together and why, see [ARCHITECTURE.md](ARCHITECTURE.md). - For the frontend's layout and scripts, see [frontend/README.md](frontend/README.md). -- For running vision_processor at a venue, see the root [README.md](../README.md). +- For running ssl-vision-processor at a venue, see the root [README.md](../README.md). ## Requirements @@ -73,15 +73,15 @@ Without one, the host creates a default from the files embedded in `internal/def `README.md` documents the flags and file locations that users see. -### Running vision_processor from the host +### Running ssl-vision-processor from the host -With `-runCameras`, the host starts one vision_processor per camera, using the `vision_processor` it finds on `PATH`. +With `-runCameras`, the host starts one ssl-vision-processor per camera, using the `ssl-vision-processor` it finds on `PATH`. There's no flag to name another binary: to use your own build, put it first on `PATH`. Every camera gets a `config_path`, `cam.yml`, if it has none. Each runs in its own folder, `run/cam` in the state folder (`~/.local/state/rcssl/vision-processor-gui`), with `img` there linking to its own folder in `-imgDir`, `cam`. It gets the full path of its config file. A camera whose capture device another camera already uses isn't started until that's fixed. -Settings vision_processor hot reloads (thresholds, tracking, color, debug) only rewrite the file. A change to any +Settings ssl-vision-processor hot reloads (thresholds, tracking, color, debug) only rewrite the file. A change to any other setting (camera, geometry, network, stream) restarts it once edits stop for a second. The Camera Settings page shows its state and output and has a Restart button. A crash is retried, waiting longer each time; a clean exit, such as a video file ending, is started again after a second. @@ -92,10 +92,10 @@ For a bench test, from the repo root: PATH=$PWD/build:$PATH make run ARGS="-configFile config-camtest.vision.yml -runCameras" ``` -Stop any vision_processor already using the camera first. A restart recalibrates geometry unless the camera's +Stop any ssl-vision-processor already using the camera first. A restart recalibrates geometry unless the camera's calibration is locked. `make run` passes `-imgDir img`, so snapshots still land in the repo's `img/`. -`make release-check` also runs the release binary with `-runCameras` and a stand-in vision_processor script. +`make release-check` also runs the release binary with `-runCameras` and a stand-in ssl-vision-processor script. ### Network settings @@ -119,7 +119,7 @@ internal/ livefield/ latest detections and autoref tracker frames, for the Live Field page snapshot/ debug image listing and serving video/ live video, relayed to the browser - supervisor/ runs and restarts every camera's vision_processor (-runCameras) + supervisor/ runs and restarts every camera's ssl-vision-processor (-runCameras) v4l/ this host's capture devices logging/ slog setup vision/ generated protobuf bindings, not committed @@ -149,10 +149,10 @@ nothing, so it's safe on any network. ## Live video The Camera Settings tab shows the selected camera's live video beside its `camera:` settings (driver, device, -resolution, exposure, gain, gamma, white balance). Those settings apply when the camera's vision_processor -restarts. The Stream page also shows the selected camera's live video. The host relays the vision_processor's H.264 +resolution, exposure, gain, gamma, white balance). Those settings apply when the camera's ssl-vision-processor +restarts. The Stream page also shows the selected camera's live video. The host relays the ssl-vision-processor's H.264 stream to the browser without re-encoding, and only while someone watches. The stream cycles through the -vision_processor's views unless its `stream.raw_feed` is set. +ssl-vision-processor's views unless its `stream.raw_feed` is set. ## Releasing @@ -165,7 +165,7 @@ through a `/nix/store` interpreter that doesn't exist on other machines. `make r The version comes from `git describe`, and `-version` and `/api/health` report it. Other builds say `dev`. -One tag releases both programs: the GUI's files above, and vision_processor's `.deb` for each Ubuntu LTS +One tag releases both programs: the GUI's files above, and ssl-vision-processor's `.deb` for each Ubuntu LTS (`packaging/README.md` at the repository root). Both packages take their version from the same tag. ### Making a release @@ -174,7 +174,7 @@ One tag releases both programs: the GUI's files above, and vision_processor's `. CI green on it. The tag runs every check again on that commit, so a red CI only costs a wasted run. 2. **Optionally, check it locally first.** From `gui/`, in `nix develop`: `make check` and `make release-check`. - For vision_processor's packages, from the repository root: `packaging/build-deb.sh`, then + For ssl-vision-processor's packages, from the repository root: `packaging/build-deb.sh`, then `packaging/deb-check-container.sh` (needs Docker). 3. **Pick the version.** `v..`, with `-alpha.`, `-beta.` or `-rc.` for a pre-release: @@ -191,7 +191,7 @@ One tag releases both programs: the GUI's files above, and vision_processor's `. 5. **Wait for the Release workflow.** It can take a few minutes to appear. `gh run list --event push --limit 3` shows it, then `gh run watch ` follows it; or the repository's Actions tab. (`gh run watch` alone lists only runs already in progress, and `gh run list --workflow release.yml` answers 404 until the workflow's first run.) - vision_processor's two + ssl-vision-processor's two packages build and are checked first, each under systemd in a container. Then one job runs `make check`, `make release-check` and the GUI's package checks on the tagged commit, and drafts the GitHub Release. If any step fails, nothing is drafted. @@ -240,19 +240,19 @@ before it, and later commits add `+git.g`. With no tag yet it's `0.0.0+g What the package installs, all under `packaging/`: -| File | Installed as | -| ---------------------------------------- | ------------------------------------------------------------------------------ | -| `ssl-vision-processor-gui.service` | The system service, as `rcssl-vp-gui` in group `rcssl`, hardened | -| `ssl-vision-processor-gui.user.service` | The same as a user service, with the usual file locations | -| `sysusers.conf` | The `rcssl` group and the `rcssl-vp-gui` user, via `systemd-sysusers` | -| `sysctl.conf` | `/usr/lib/sysctl.d/60-rcssl-multicast.conf`: `net.core.rmem_max` for video | -| `configure-service` | Applies the setup answers: enables or starts the service, sets `ADDRESS` | -| `debian/templates`, `debian/config` | The two debconf questions: service, and who can reach it | -| `debian/postinst`, `prerm`, `postrm` | Users, sysctl, then the answers or an upgrade; stop on remove; purge | -| `ssl-vision-processor-gui.1` | The man page. `TestManPageListsEveryFlag` fails if an option is missing | -| `changelog` | The Debian changelog: one entry for the version built, pointing at releases | -| `copyright` | Licenses: Apache-2.0, the MIT protocol definitions, and the bundled notices | -| `lintian-overrides` | The findings that are intended, each with its reason | +| File | Installed as | +| --------------------------------------- | --------------------------------------------------------------------------- | +| `ssl-vision-processor-gui.service` | The system service, as `rcssl-vp-gui` in group `rcssl`, hardened | +| `ssl-vision-processor-gui.user.service` | The same as a user service, with the usual file locations | +| `sysusers.conf` | The `rcssl` group and the `rcssl-vp-gui` user, via `systemd-sysusers` | +| `sysctl.conf` | `/usr/lib/sysctl.d/60-rcssl-multicast.conf`: `net.core.rmem_max` for video | +| `configure-service` | Applies the setup answers: enables or starts the service, sets `ADDRESS` | +| `debian/templates`, `debian/config` | The two debconf questions: service, and who can reach it | +| `debian/postinst`, `prerm`, `postrm` | Users, sysctl, then the answers or an upgrade; stop on remove; purge | +| `ssl-vision-processor-gui.1` | The man page. `TestManPageListsEveryFlag` fails if an option is missing | +| `changelog` | The Debian changelog: one entry for the version built, pointing at releases | +| `copyright` | Licenses: Apache-2.0, the MIT protocol definitions, and the bundled notices | +| `lintian-overrides` | The findings that are intended, each with its reason | `configure-service` holds the logic and debconf only asks, so more tools' packages can follow the same shape. A new install and `dpkg-reconfigure` run it to apply the answers. It changes only the `ADDRESS` line of @@ -264,7 +264,7 @@ calibrations. The unit file in `/usr/lib` is replaced on every upgrade. Admins customize with `ARGS` or a drop-in, as the README explains, so a change to the unit here reaches them without overwriting theirs. -The service never uses `-runCameras`: on a machine set up with packages, each vision_processor runs as its own +The service never uses `-runCameras`: on a machine set up with packages, each ssl-vision-processor runs as its own service. CI builds the packages, runs lintian, and runs `scripts/deb-check.sh` as root on the runner. That script installs @@ -279,5 +279,5 @@ runs systemd. If the GUI's service runs on your development machine, `make run` can't take port 8080 (`can't open the GUI on :8080`). On another port, both publish geometry on the same multicast group, and the Network page shows a sender conflict. Stop the service while developing: `sudo systemctl stop ssl-vision-processor-gui`. The same goes for -vision_processor's camera services (`ssl-vision-processor@`) and a source-built vision_processor for the +ssl-vision-processor's camera services (`ssl-vision-processor@`) and a source-built ssl-vision-processor for the same camera: `sudo systemctl stop 'ssl-vision-processor@*'`. diff --git a/gui/Makefile b/gui/Makefile index 5edb98d..6904c28 100644 --- a/gui/Makefile +++ b/gui/Makefile @@ -34,7 +34,7 @@ help: ## List these targets /^## / { printf "\n%s\n", substr($$0, 4) } \ /^[a-z][a-z0-9-]*:.*## / { printf " make %-13s %s\n", $$1, $$2 }' $(MAKEFILE_LIST) -# Run from the repo root, as vision_processor is, keeping everything in it +# Run from the repo root, as ssl-vision-processor is, keeping everything in it # rather than the installed default folders. ARGS come last, so they win. run: frontend ## Build everything and run the host from the repo root; flags go in ARGS="..." go build -ldflags "$(BUILD_LDFLAGS)" -o bin/$(BINARY) ./cmd/$(BINARY) diff --git a/gui/README.md b/gui/README.md index ecc1fe7..52851f8 100644 --- a/gui/README.md +++ b/gui/README.md @@ -1,6 +1,6 @@ # SSL Vision Processor GUI -A browser interface for setting up and running [vision_processor](https://github.com/RoboCup-SSL/ssl-vision-processor#readme), the SSL's shared vision system. +A browser interface for setting up and running [ssl-vision-processor](https://github.com/RoboCup-SSL/ssl-vision-processor#readme), the SSL's shared vision system. It holds your field geometry and camera settings, locks in camera calibrations, shows live video and the live field, and publishes the field geometry to the rest of the league's software. @@ -44,16 +44,16 @@ These steps are for 64-bit Linux, tested on Ubuntu 24.04. 4. Save when the wizard asks. **The GUI publishes nothing on the network until this first save**, so you can try it on a live network without disturbing anyone. Until then, an alert reminds you that it isn't publishing. -5. Connect your cameras. The GUI doesn't include vision_processor, which does the camera processing: on Ubuntu, +5. Connect your cameras. The GUI doesn't include ssl-vision-processor, which does the camera processing: on Ubuntu, install the `ssl-vision-processor` package from the same release (see [`packaging/README.md`](https://github.com/RoboCup-SSL/ssl-vision-processor/blob/master/packaging/README.md)), or build it from source: see the [main README](https://github.com/RoboCup-SSL/ssl-vision-processor#readme). Then: - **A webcam or other camera on this machine:** stop the GUI and start it again with `-runCameras`, which runs - vision_processor for you. Then choose the camera's driver on the Camera page. See + ssl-vision-processor for you. Then choose the camera's driver on the Camera page. See [Running a webcam with the GUI](#running-a-webcam-with-the-gui). - **Cameras on other machines, or as services:** install the `ssl-vision-processor` package there and set the - cameras up with `ssl-vision-processor-cameras` (`man ssl-vision-processor-cameras`), or start vision_processor + cameras up with `ssl-vision-processor-cameras` (`man ssl-vision-processor-cameras`), or start ssl-vision-processor by hand. The Layout page shows each one it hears, once they're on the same network and vision address. See [Cameras](#cameras). @@ -84,12 +84,12 @@ To change your answers: `sudo dpkg-reconfigure ssl-vision-processor-gui`. The service runs as its own user, `rcssl-vp-gui`, in the `rcssl` group that every RoboCup SSL tool's package shares: -| What | Where | -| ---------------------- | ------------------------------------------------------------------------------ | -| Config folder | `/var/lib/rcssl/vision-processor-gui/`. Members of `rcssl` can read it. | -| Log | `journalctl -u ssl-vision-processor-gui` | -| Address, extra options | `/etc/default/ssl-vision-processor-gui`. Restart the service after editing. | -| Start, stop, restart | `sudo systemctl start ssl-vision-processor-gui`, and so on | +| What | Where | +| ---------------------- | --------------------------------------------------------------------------- | +| Config folder | `/var/lib/rcssl/vision-processor-gui/`. Members of `rcssl` can read it. | +| Log | `journalctl -u ssl-vision-processor-gui` | +| Address, extra options | `/etc/default/ssl-vision-processor-gui`. Restart the service after editing. | +| Start, stop, restart | `sudo systemctl start ssl-vision-processor-gui`, and so on | To read the config folder without `sudo`, join the group (`sudo usermod -aG rcssl $USER`), then log in again. @@ -124,8 +124,8 @@ Removing the package (`sudo apt remove`) keeps your settings, and purging it (`s folder too, since it holds your locked calibrations. Delete `/var/lib/rcssl/vision-processor-gui` yourself if you want it gone. -The package doesn't include vision_processor; see [Cameras](#cameras). The service never runs cameras itself: on a -machine set up with packages, each vision_processor runs as its own service, from the `ssl-vision-processor` +The package doesn't include ssl-vision-processor; see [Cameras](#cameras). The service never runs cameras itself: on a +machine set up with packages, each ssl-vision-processor runs as its own service, from the `ssl-vision-processor` package. ## Where things are @@ -172,8 +172,8 @@ Every option is optional. `-h` lists them all. | `-configDir` | see above | The config folder. Created if missing. | | `-configFile` | `vision.yml` | The file to use in the config folder: a file name, not a path. Created if missing. | | `-logFile` | see above | Rotating log file. `-logFile ""` turns it off. | -| `-imgDir` | see above | Where the GUI looks for vision_processor's debug images. | -| `-runCameras` | off | Run every camera's vision_processor on this machine; see [Cameras](#cameras). | +| `-imgDir` | see above | Where the GUI looks for ssl-vision-processor's debug images. | +| `-runCameras` | off | Run every camera's ssl-vision-processor on this machine; see [Cameras](#cameras). | | `-logLevel` | `Info` | `Debug`, `Info`, `Warn`, or `Error`. | | `-verbose` | off | The same as `-logLevel Debug`, as in the other league tools. | | `-allowOrigin` | none | Other web pages allowed to use the API on a competition field. | @@ -218,9 +218,9 @@ echo 'net.core.rmem_max=4194304' | sudo tee /etc/sysctl.d/60-rcssl-multicast.con sudo sysctl --system ``` -**Nothing is heard with vision_processor on the same machine and no network cable.** Traffic then has to go over +**Nothing is heard with ssl-vision-processor on the same machine and no network cable.** Traffic then has to go over loopback, where Ubuntu turns multicast off. The GUI logs this at startup and raises an alert. Turn it on and route -multicast there, which lasts until the next reboot, then restart vision_processor: +multicast there, which lasts until the next reboot, then restart ssl-vision-processor: ```sh sudo ip link set lo multicast on @@ -245,29 +245,29 @@ as a competition field limits which web pages can use the API, but that only app ## Cameras -This download is the GUI only. It doesn't include vision_processor, which does the camera processing. For now you -build that from source: see the [main README](https://github.com/RoboCup-SSL/ssl-vision-processor#readme). The GUI finds running vision_processors through the +This download is the GUI only. It doesn't include ssl-vision-processor, which does the camera processing. For now you +build that from source: see the [main README](https://github.com/RoboCup-SSL/ssl-vision-processor#readme). The GUI finds running ssl-vision-processors through the multicast traffic they send, wherever they run. There are two ways to run the cameras: - **On this machine, run by the GUI** (`-runCameras`). Simplest for one or two cameras, such as a lab webcam. The - GUI starts a vision_processor for every camera, and restarts it when you change a setting it only reads at + GUI starts an ssl-vision-processor for every camera, and restarts it when you change a setting it only reads at startup. Camera settings reach it through a file the GUI writes in the config folder, `cam0.yml` for camera 0 and so on. -- **As their own services**, the default. For events and larger labs. The GUI starts nothing; each vision_processor +- **As their own services**, the default. For events and larger labs. The GUI starts nothing; each ssl-vision-processor is started separately, on this machine or others. Packages that set these up are planned. ### Running a webcam with the GUI -1. Build vision_processor, then make sure the shell finds it: +1. Build ssl-vision-processor, then make sure the shell finds it: ```sh export PATH=/path/to/vision-processor/build:$PATH - which vision_processor + which ssl-vision-processor ``` - The GUI uses the `vision_processor` on your `PATH`. There is no option to point it elsewhere. + The GUI uses the `ssl-vision-processor` on your `PATH`. There is no option to point it elsewhere. 2. Start the GUI with `-runCameras`: @@ -275,39 +275,39 @@ There are two ways to run the cameras: ./ssl-vision-processor-gui -runCameras ``` - It prints which vision_processor it runs, and exits straight away if it can't find one. A new configuration's + It prints which ssl-vision-processor it runs, and exits straight away if it can't find one. A new configuration's camera 0 has no camera selected, so it isn't started yet. Choose OPENCV as its driver on the Camera page and it starts on the first webcam (`/dev/video0`). -3. The Camera page shows each vision_processor's state, its last lines of output, and a Restart button. Choosing the +3. The Camera page shows each ssl-vision-processor's state, its last lines of output, and a Restart button. Choosing the number of cameras on the Layout page adds or removes cameras to match, each with its own config file. Each camera needs its own capture device. If two cameras name the same one, only the lower camera ID starts, and -an alert says which. The GUI doesn't know about a vision_processor started some other way: if one already has the +an alert says which. The GUI doesn't know about an ssl-vision-processor started some other way: if one already has the camera open, the GUI's copy says so in its output. -Each vision_processor runs in its own folder, `~/.local/state/rcssl/vision-processor-gui/run/cam`, so its debug +Each ssl-vision-processor runs in its own folder, `~/.local/state/rcssl/vision-processor-gui/run/cam`, so its debug files stay apart. Its snapshots go to its own folder in the image folder, `img/cam`. ## Troubleshooting Check the GUI's Alerts page first; most alerts have a how-to. The printed log file has the details. -| Problem | Likely cause and fix | -| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `can't open the GUI on …` and it exits | Something else is using the port, often another copy of the GUI. Stop it, or use another `-address`. | -| `no default config folder, set -configDir` | `HOME` isn't set, as in some service environments. Set `-configDir`, `-logFile`, and `-imgDir`. | -| Page doesn't load from another machine | It allows this machine only: check the address it printed, or the service's [setting](#installing-the-package). Then the firewall, if it's on; see [Network setup](#network-setup). | -| "This host doesn't answer to..." | You're using a name the GUI doesn't know. Add it with `-allowHost`. | -| Nothing is published | First run: save once. Then check the Alerts page. | -| Your old settings seem to be gone | The GUI no longer reads `vision.yml` from the current folder. Pass `-configDir .` from that folder. | -| `config_path: ... want a file name` | `vision.yml` names a full path. Move the file to the config folder and use only its name. | -| `-runCameras needs vision_processor on PATH` | Build vision_processor and add its folder to `PATH`; see [Cameras](#cameras). | -| "No camera selected" | A new configuration doesn't guess your camera. Choose its driver on the Camera page. | -| vision_processor keeps exiting | Read its last output, on the Camera page. Usually the wrong driver, a device that's missing or already open in another program, or a driver the build doesn't include. A webcam needs OPENCV and its `/dev/video` path. | -| Nothing heard from a camera | Check its vision_processor is running, on the same vision address, and on a network this machine uses; see [Network setup](#network-setup). The Alerts page says which sockets are silent. | -| No video in Chromium or Firefox | They need the system's H.264 libraries; Google Chrome includes its own. See [Browser](#browser). | -| "The same packets arrive on..." | Two of this machine's interfaces reach the same network. Leave only the field network's on, on the Network page. | +| Problem | Likely cause and fix | +| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `can't open the GUI on …` and it exits | Something else is using the port, often another copy of the GUI. Stop it, or use another `-address`. | +| `no default config folder, set -configDir` | `HOME` isn't set, as in some service environments. Set `-configDir`, `-logFile`, and `-imgDir`. | +| Page doesn't load from another machine | It allows this machine only: check the address it printed, or the service's [setting](#installing-the-package). Then the firewall, if it's on; see [Network setup](#network-setup). | +| "This host doesn't answer to..." | You're using a name the GUI doesn't know. Add it with `-allowHost`. | +| Nothing is published | First run: save once. Then check the Alerts page. | +| Your old settings seem to be gone | The GUI no longer reads `vision.yml` from the current folder. Pass `-configDir .` from that folder. | +| `config_path: ... want a file name` | `vision.yml` names a full path. Move the file to the config folder and use only its name. | +| `-runCameras needs ssl-vision-processor on PATH` | Build ssl-vision-processor and add its folder to `PATH`; see [Cameras](#cameras). | +| "No camera selected" | A new configuration doesn't guess your camera. Choose its driver on the Camera page. | +| ssl-vision-processor keeps exiting | Read its last output, on the Camera page. Usually the wrong driver, a device that's missing or already open in another program, or a driver the build doesn't include. A webcam needs OPENCV and its `/dev/video` path. | +| Nothing heard from a camera | Check its ssl-vision-processor is running, on the same vision address, and on a network this machine uses; see [Network setup](#network-setup). The Alerts page says which sockets are silent. | +| No video in Chromium or Firefox | They need the system's H.264 libraries; Google Chrome includes its own. See [Browser](#browser). | +| "The same packets arrive on..." | Two of this machine's interfaces reach the same network. Leave only the field network's on, on the Network page. | ## Upgrading diff --git a/gui/REVIEW.md b/gui/REVIEW.md index 7ce5999..de90a1d 100644 --- a/gui/REVIEW.md +++ b/gui/REVIEW.md @@ -29,6 +29,8 @@ Owner per finding: **Will** (Go/Svelte) or **Claude** (build/CI/packaging/docs i Updated 2026-11-29. **Open** 11 · **Partial** 1 · **Done** 55 · **v2.1** 3 · **Dropped/merged** 3. Each finding below keeps its own *Progress* or *Done* note; this table is the index. Statuses: open, partial, done, v2.1 (deferred to that release), dropped, merged. +*2026-11-29:* the `vision_processor` binary is now `ssl-vision-processor` everywhere (CMake target, package, GUI, docs), with Felix's approval. Notes in this file keep the name they were written with. + **Next up** (MVP gate order; see the end of this file): All blockers are fixed. Left of the MVP gate: T2-10 (lab machine). diff --git a/gui/cmd/ssl-vision-processor-gui/docs.go b/gui/cmd/ssl-vision-processor-gui/docs.go index a75804c..4232e95 100644 --- a/gui/cmd/ssl-vision-processor-gui/docs.go +++ b/gui/cmd/ssl-vision-processor-gui/docs.go @@ -92,12 +92,12 @@ func newAPI(mux *http.ServeMux) *api.API { } // settingsSchema is config.CurrentSchema() as JSON Schema: one object per -// config.yml block, one property per key, with vision_processor's fallback, +// config.yml block, one property per key, with ssl-vision-processor's fallback, // bounds, and when a change takes effect. func settingsSchema() jsonschema.Schema { applies := map[string]string{ config.ApplyLive: "Reloaded live, within a second.", - config.ApplyRestart: "Takes effect when vision_processor restarts.", + config.ApplyRestart: "Takes effect when ssl-vision-processor restarts.", config.ApplyDerived: "Written by the host from the document; don't set it.", config.ApplyHost: "Read only by the GUI host.", } @@ -172,7 +172,7 @@ func settingsSchema() jsonschema.Schema { return mustSchema(map[string]any{ "type": "object", - "description": "vision_processor's config.yml layout, as GET /api/schema describes it. A key it doesn't read is kept but raises an unknown_setting warning.", + "description": "ssl-vision-processor's config.yml layout, as GET /api/schema describes it. A key it doesn't read is kept but raises an unknown_setting warning.", "properties": top, }) } diff --git a/gui/cmd/ssl-vision-processor-gui/logs.go b/gui/cmd/ssl-vision-processor-gui/logs.go index 22a7625..46176fa 100644 --- a/gui/cmd/ssl-vision-processor-gui/logs.go +++ b/gui/cmd/ssl-vision-processor-gui/logs.go @@ -41,7 +41,7 @@ type logsResponse struct { Missed bool `json:"missed"` } -// getLogs serves the host's recent log records, its supervised vision_processors' +// getLogs serves the host's recent log records, its supervised ssl-vision-processors' // output included, whatever level its console logs at. Poll with after set to // the last response's next to follow the log; add wait to be answered as soon // as a record is logged. diff --git a/gui/cmd/ssl-vision-processor-gui/main.go b/gui/cmd/ssl-vision-processor-gui/main.go index 627f0e8..6dbfbf9 100644 --- a/gui/cmd/ssl-vision-processor-gui/main.go +++ b/gui/cmd/ssl-vision-processor-gui/main.go @@ -45,7 +45,7 @@ var address = flag.String("address", ":8080", "The address on which the SSL Visi // there are no flags for them. // vision.yml holds everything the host owns: the field template, shared and -// per-camera vision_processor settings, and locked calibrations. It lives in +// per-camera ssl-vision-processor settings, and locked calibrations. It lives in // one flat folder; see config.ValidName. var configDir = flag.String("configDir", "", "Folder holding every config file, created if missing. Default: $XDG_CONFIG_HOME or ~/.config, then rcssl/vision-processor-gui") var configFile = flag.String("configFile", "vision.yml", "Config file (field, cameras, calibrations): a file name in -configDir, created if missing") @@ -57,9 +57,9 @@ var imgDir = flag.String("imgDir", "", "Directory the vision processor writes de var logLevelFlag = flag.String("logLevel", "Info", "Log level: Debug, Info, Warn, Error") var verbose = flag.Bool("verbose", false, "Same as -logLevel Debug, as in the other league tools") -// A host either runs every camera's vision_processor or none: then they run +// A host either runs every camera's ssl-vision-processor or none: then they run // as their own services, configured over the network. -var runCameras = flag.Bool("runCameras", false, "Run every camera's vision_processor on this machine, found on PATH, restarting it when a startup-only setting changes. Each camera gets a config_path, cam.yml, if it has none. Default: off, they run as their own services") +var runCameras = flag.Bool("runCameras", false, "Run every camera's ssl-vision-processor on this machine, found on PATH, restarting it when a startup-only setting changes. Each camera gets a config_path, cam.yml, if it has none. Default: off, they run as their own services") var logFile = flag.String("logFile", "", "Rotating log file to write alongside stderr, empty to disable. Default: $XDG_STATE_HOME or ~/.local/state, then rcssl/vision-processor-gui/logs/vision-processor-gui.log") var showVersion = flag.Bool("version", false, "Print the version and exit") @@ -128,12 +128,12 @@ func run() int { if *runCameras { vp, err := findVisionProcessor() if err != nil { - slog.Error("-runCameras needs vision_processor on PATH", "err", err) + slog.Error("-runCameras needs ssl-vision-processor on PATH", "err", err) return 1 } - slog.Info("mode", "cameras", "local", "vision_processor", vp) + slog.Info("mode", "cameras", "local", "binary", vp) vpCommand = []string{vp} } else { slog.Info("mode", "cameras", "external") @@ -169,7 +169,7 @@ func run() int { // Bound before anything starts, so a taken port stops the host before it // opens sockets or starts (and, restarted by systemd, keeps killing) the - // supervised vision_processors. + // supervised ssl-vision-processors. ln, err := listenUI(*address) if err != nil { slog.Error(err.Error()) @@ -227,7 +227,7 @@ func run() int { runBackground(&wg, "live field publish loop", func() error { return publishLiveField(ctx, wsHub, status.live) }) if h.procs != nil { - runBackground(&wg, "vision_processor supervisor", func() error { return h.procs.Run(ctx) }) + runBackground(&wg, "ssl-vision-processor supervisor", func() error { return h.procs.Run(ctx) }) } // Shutdown waits for every request to finish, so the ones that wait for @@ -297,7 +297,7 @@ type host struct { hub *hub.Hub status *hostStatus policy *origins.Policy - // procs is nil unless the host runs the vision_processors itself + // procs is nil unless the host runs the ssl-vision-processors itself // (-runCameras). procs *supervisor.Supervisor handler http.Handler @@ -308,10 +308,10 @@ type hostOptions struct { allowedHosts []string imgDir string verbose bool - // vpCommand runs a vision_processor per camera; empty for none. The host + // vpCommand runs an ssl-vision-processor per camera; empty for none. The host // then gives every camera a config_path. vpCommand []string - // runDir holds each camera's vision_processor working directory. + // runDir holds each camera's ssl-vision-processor working directory. runDir string } @@ -451,7 +451,7 @@ func writeOpenAPI(path string) int { const configWatchInterval = time.Second // bootstrapConfig creates the config file from the embedded defaults if it -// doesn't exist yet, and with it the robot height table vision_processor +// doesn't exist yet, and with it the robot height table ssl-vision-processor // needs. Never touches an existing config. A host that runs its cameras // (local) gives camera 0 its config_path, cam0.yml, so choosing a driver is enough to // start it. @@ -521,9 +521,9 @@ func printReadme() int { return 0 } -// findVisionProcessor is vision_processor's absolute path, from PATH. +// findVisionProcessor is ssl-vision-processor's absolute path, from PATH. func findVisionProcessor() (string, error) { - vp, err := exec.LookPath("vision_processor") + vp, err := exec.LookPath("ssl-vision-processor") if err != nil { return "", err } @@ -796,7 +796,7 @@ func ufwEnabled(path string) bool { } // publishStatus publishes the network state and the alerts, which depend on -// it and on the store, and the vision_processors announcing. +// it and on the store, and the ssl-vision-processors announcing. func publishStatus(wsHub *hub.Hub, status StatusSource) { networkTopic.publish(wsHub, status.Network()) alertsTopic.publish(wsHub, status.Alerts()) diff --git a/gui/cmd/ssl-vision-processor-gui/paths.go b/gui/cmd/ssl-vision-processor-gui/paths.go index 14e4b17..cbd535b 100644 --- a/gui/cmd/ssl-vision-processor-gui/paths.go +++ b/gui/cmd/ssl-vision-processor-gui/paths.go @@ -21,7 +21,7 @@ type pathFlags struct { configFile string logFile *string imgDir *string - // runCameras is -runCameras: the host runs the vision_processors, each in + // runCameras is -runCameras: the host runs the ssl-vision-processors, each in // its own directory under runDir. runCameras bool } @@ -34,7 +34,7 @@ type paths struct { // logFile is empty for no log file. logFile string imgDir string - // runDir holds each camera's vision_processor working directory, empty + // runDir holds each camera's ssl-vision-processor working directory, empty // without -runCameras. runDir string } diff --git a/gui/cmd/ssl-vision-processor-gui/paths_test.go b/gui/cmd/ssl-vision-processor-gui/paths_test.go index 23ce0fe..d03c196 100644 --- a/gui/cmd/ssl-vision-processor-gui/paths_test.go +++ b/gui/cmd/ssl-vision-processor-gui/paths_test.go @@ -110,7 +110,7 @@ func TestResolvePathsRefusesAPathAsTheConfigFile(t *testing.T) { } } -// With -runCameras each camera's vision_processor runs in its own folder in +// With -runCameras each camera's ssl-vision-processor runs in its own folder in // the state directory; snapshots still default to the shared image directory. func TestResolvePathsRunCameras(t *testing.T) { t.Setenv("HOME", "/home/someone") diff --git a/gui/cmd/ssl-vision-processor-gui/peers.go b/gui/cmd/ssl-vision-processor-gui/peers.go index 8c81a48..2fae87b 100644 --- a/gui/cmd/ssl-vision-processor-gui/peers.go +++ b/gui/cmd/ssl-vision-processor-gui/peers.go @@ -31,15 +31,15 @@ func newPeerWatches() *peerWatches { return &peerWatches{ names: names, - // vision_processor sends its calibration once, after calibrating; a + // ssl-vision-processor sends its calibration once, after calibrating; a // host republishing one sends it every second. Five minutes catches // either next to the other. calibration: peers.NewWatch(peers.Options{Kind: peers.KindCalibration, Window: 5 * time.Minute}, names), detections: peers.NewWatch(peers.Options{Kind: peers.KindDetections, Window: 3 * time.Second, MinCount: 2}, names), - // vision_processor sends the field back now and then; only another + // ssl-vision-processor sends the field back now and then; only another // host publishes it every second, as this one does. geometry: peers.NewWatch(peers.Options{Kind: peers.KindGeometry, Window: 10 * time.Second, MinCount: 3, WithSelf: true}, names), - // vision_processor announces once a second. + // ssl-vision-processor announces once a second. instance: peers.NewWatch(peers.Options{Kind: peers.KindInstance, Window: discovery.Stale, MinCount: 2}, names), referee: peers.NewWatch(peers.Options{Kind: peers.KindReferee, Window: 3 * time.Second, MinCount: 2}, names), video: peers.NewWatch(peers.Options{Kind: peers.KindVideo, Window: 3 * time.Second, MinCount: 10, Restarts: true}, names), @@ -91,7 +91,7 @@ func (p *peerWatches) absorber(geom *geometry.Geometry) func(*vision.SSL_Geometr } } -// announcer passes each vision_processor announce on to instances, recording +// announcer passes each ssl-vision-processor announce on to instances, recording // who sent which instance name. func (p *peerWatches) announcer(instances *discovery.Registry) func(*vision.SSL_VPConfig, *net.UDPAddr) { return func(config *vision.SSL_VPConfig, from *net.UDPAddr) { diff --git a/gui/cmd/ssl-vision-processor-gui/routes.go b/gui/cmd/ssl-vision-processor-gui/routes.go index 656912b..6549745 100644 --- a/gui/cmd/ssl-vision-processor-gui/routes.go +++ b/gui/cmd/ssl-vision-processor-gui/routes.go @@ -21,11 +21,11 @@ var ( ) var specTags = []api.Tag{ - {Name: tagStatus[0], Description: "The host's health, version, sockets, alerts, logs, and the vision_processors it hears."}, + {Name: tagStatus[0], Description: "The host's health, version, sockets, alerts, logs, and the ssl-vision-processors it hears."}, {Name: tagConfig[0], Description: "The shared vision.yml document: read, edit, save, load, and lock calibrations."}, {Name: tagField[0], Description: "The field geometry the host publishes, and the rulebook presets it starts from."}, {Name: tagUpdates[0], Description: "What the host is hearing right now, and the WebSocket topics that push it."}, - {Name: tagHost[0], Description: "This machine only: its capture devices, its supervised vision_processors, and debug images on its disk."}, + {Name: tagHost[0], Description: "This machine only: its capture devices, its supervised ssl-vision-processors, and debug images on its disk."}, } // Error codes every route with a JSON body can answer, from decoding it. @@ -96,7 +96,7 @@ func (s *VisionServer) addRoutes(mux *http.ServeMux, a *api.API) { Tags: tagHost, ID: "getSnapshot", Summary: "Serves a camera's latest debug image for one view", - Description: "The most recently written of the views GET /api/snapshots lists, as vision_processor wrote it.", + Description: "The most recently written of the views GET /api/snapshots lists, as ssl-vision-processor wrote it.", Errors: []string{httpjson.CodeNotFound}, }, snapshot.HandleGet(s.imgDir), api.RawResponse{Status: http.StatusOK, ContentType: "image/*", Description: "The image, PNG or JPEG."}) diff --git a/gui/cmd/ssl-vision-processor-gui/server.go b/gui/cmd/ssl-vision-processor-gui/server.go index 532886e..a12d89f 100644 --- a/gui/cmd/ssl-vision-processor-gui/server.go +++ b/gui/cmd/ssl-vision-processor-gui/server.go @@ -87,7 +87,7 @@ func (s *VisionServer) listAlerts(*http.Request, none) ([]alerts.Alert, error) { return s.status.Alerts(), nil } -// listInstances lists every vision_processor heard announcing itself on the vision +// listInstances lists every ssl-vision-processor heard announcing itself on the vision // group in the last 30 seconds, with the configuration it last announced, by // camera_id then instance name. One unheard for 3 seconds is no longer live. func (s *VisionServer) listInstances(*http.Request, none) ([]discovery.Instance, error) { @@ -106,7 +106,7 @@ func (s *VisionServer) getGeometry(*http.Request, none) (wrapperPacket, error) { return protojson.Marshal(s.geometry.Snapshot()) } -// getSchema describes every vision_processor setting: type, fallback, bounds, +// getSchema describes every ssl-vision-processor setting: type, fallback, bounds, // and when a change takes effect. func (s *VisionServer) getSchema(*http.Request, none) (config.Schema, error) { return config.CurrentSchema(), nil @@ -285,9 +285,9 @@ type cameraRequest struct { ID int `path:"id"` } -// getEffectiveConfig lists every setting of one camera as its vision_processor +// getEffectiveConfig lists every setting of one camera as its ssl-vision-processor // runs it. Each value says where it comes from: the camera, the shared -// defaults, the host, or vision_processor's fallback. +// defaults, the host, or ssl-vision-processor's fallback. func (s *VisionServer) getEffectiveConfig(_ *http.Request, in cameraRequest) (config.EffectiveConfig, error) { doc, _ := s.store.Working() @@ -305,7 +305,7 @@ func (s *VisionServer) lockCalibration(_ *http.Request, in cameraRequest) (revis } // unlockCalibration removes the camera's locked calibration. The host stops -// publishing any calibration for it, so its vision_processor calibrates again +// publishing any calibration for it, so its ssl-vision-processor calibrates again // the next time it starts. func (s *VisionServer) unlockCalibration(_ *http.Request, in cameraRequest) (revisionResponse, error) { rev, err := s.store.UnlockCalibration(in.ID) @@ -330,24 +330,24 @@ func (s *VisionServer) listSnapshots(*http.Request, none) ([]snapshot.Entry, err return snapshot.List(s.imgDir) } -// listProcesses lists the vision_processors the host runs itself (-runCameras), by +// listProcesses lists the ssl-vision-processors the host runs itself (-runCameras), by // camera_id: processes.state on demand. Empty when it runs none. func (s *VisionServer) listProcesses(*http.Request, none) ([]supervisor.Status, error) { return s.procs.Statuses(), nil } -// restartProcess restarts the camera's vision_processor now, rather than +// restartProcess restarts the camera's ssl-vision-processor now, rather than // waiting for a startup-only setting to change. A 404 not_found means the -// host doesn't run that camera's vision_processor; a 409 device_conflict that +// host doesn't run that camera's ssl-vision-processor; a 409 device_conflict that // it's held back because another camera uses its device; a 409 no_camera that // no camera driver is chosen for it. func (s *VisionServer) restartProcess(_ *http.Request, in cameraRequest) ([]supervisor.Status, error) { if err := s.procs.Restart(in.ID); errors.Is(err, supervisor.ErrNotSupervised) { - return nil, httpjson.Errorf(httpjson.CodeNotFound, "the host doesn't run camera %d's vision_processor; start the host with -runCameras", in.ID) + return nil, httpjson.Errorf(httpjson.CodeNotFound, "the host doesn't run camera %d's ssl-vision-processor; start the host with -runCameras", in.ID) } else if errors.Is(err, supervisor.ErrNoCamera) { return nil, httpjson.Errorf(httpjson.CodeNoCamera, "camera %d has no camera driver chosen", in.ID) } else if errors.Is(err, supervisor.ErrHeld) { - return nil, httpjson.Errorf(httpjson.CodeDeviceConflict, "camera %d's vision_processor is held back: another camera uses its device", in.ID) + return nil, httpjson.Errorf(httpjson.CodeDeviceConflict, "camera %d's ssl-vision-processor is held back: another camera uses its device", in.ID) } else if err != nil { return nil, err } diff --git a/gui/cmd/ssl-vision-processor-gui/status.go b/gui/cmd/ssl-vision-processor-gui/status.go index 5e04a62..ebac04e 100644 --- a/gui/cmd/ssl-vision-processor-gui/status.go +++ b/gui/cmd/ssl-vision-processor-gui/status.go @@ -17,7 +17,7 @@ import ( // StatusSource is the live host state the API serves beside the store's: // what the sockets hear, the alerts derived from it all, the latest -// detections and tracked frames, and the vision_processors announcing. +// detections and tracked frames, and the ssl-vision-processors announcing. type StatusSource interface { Network() NetworkState Alerts() []alerts.Alert @@ -53,7 +53,7 @@ type hostStatus struct { match *referee.Match live *livefield.Feed instances *discovery.Registry - // procs is nil unless the host runs the vision_processors. + // procs is nil unless the host runs the ssl-vision-processors. procs *supervisor.Supervisor } diff --git a/gui/cmd/ssl-vision-processor-gui/supervised_test.go b/gui/cmd/ssl-vision-processor-gui/supervised_test.go index c8e8244..94bdc61 100644 --- a/gui/cmd/ssl-vision-processor-gui/supervised_test.go +++ b/gui/cmd/ssl-vision-processor-gui/supervised_test.go @@ -19,7 +19,7 @@ import ( "google.golang.org/protobuf/proto" ) -// TestFakeVisionProcessor stands in for vision_processor under -runCameras: it notes +// TestFakeVisionProcessor stands in for ssl-vision-processor under -runCameras: it notes // each start beside its config and runs until SIGTERM. func TestFakeVisionProcessor(t *testing.T) { if os.Getenv("FAKE_VISION_PROCESSOR") != "1" { @@ -44,7 +44,7 @@ func TestFakeVisionProcessor(t *testing.T) { } // An edit to a startup-only setting through the API restarts the camera's -// vision_processor; an edit to a live one only rewrites its config.yml. The +// ssl-vision-processor; an edit to a live one only rewrites its config.yml. The // fixture's camera 1 gets a config_path too, but opens camera 0's device, so // it's held back. func TestEditRestartsSupervisedVisionProcessor(t *testing.T) { @@ -154,7 +154,7 @@ func TestRestartUnsupervisedIs404(t *testing.T) { } // A field change unlocks the camera's calibration, solved against the old -// field, and restarts its vision_processor so it calibrates again. +// field, and restarts its ssl-vision-processor so it calibrates again. func TestFieldChangeUnlocksAndRestarts(t *testing.T) { t.Setenv("FAKE_VISION_PROCESSOR", "1") diff --git a/gui/frontend/README.md b/gui/frontend/README.md index 29153ff..4b24cfa 100644 --- a/gui/frontend/README.md +++ b/gui/frontend/README.md @@ -16,7 +16,7 @@ writes it to disk, and a tab shows an asterisk while it has unsaved changes. Dimensions edits the shared field. Geometry holds the selected camera's calibration lock and the corner picker, which marks calibration corners on a debug snapshot. The snapshots (via `GET /api/snapshots`) exist only when the -host and the vision_processor share a filesystem; see "Not yet built" in +host and the ssl-vision-processor share a filesystem; see "Not yet built" in [`gui/ARCHITECTURE.md`](../ARCHITECTURE.md). ## Run diff --git a/gui/frontend/e2e/cameras.spec.ts b/gui/frontend/e2e/cameras.spec.ts index 3fedc5b..e5ae745 100644 --- a/gui/frontend/e2e/cameras.spec.ts +++ b/gui/frontend/e2e/cameras.spec.ts @@ -1,4 +1,4 @@ -// -runCameras: the host runs each camera's vision_processor itself, here a +// -runCameras: the host runs each camera's ssl-vision-processor itself, here a // stand-in that can be told to crash. import { rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -40,7 +40,7 @@ test("a camera starts once its driver is chosen, and stops without one", async ( await driver.selectOption("OPENCV"); await expect(state).toBeVisible(); await expect(page.getByText(/stand-in running .*cam0\.yml/)).toBeVisible(); - await expect(row(page)).toContainText("vision_processor running"); + await expect(row(page)).toContainText("ssl-vision-processor running"); await expect(page.getByText("Exposure", { exact: true })).toBeVisible(); await page.goto(`${host.url}/#0/alerts`); @@ -65,13 +65,13 @@ test("a crash loop shows, with its cause, until it recovers", async ({ await page.getByLabel("Driver", { exact: true }).selectOption("OPENCV"); await expect( - page.getByText("vision_processor keeps exiting: VIDIOC_REQBUFS"), + page.getByText("ssl-vision-processor keeps exiting: VIDIOC_REQBUFS"), ).toBeVisible({ timeout: 15_000 }); - await expect(row(page)).toContainText("vision_processor keeps exiting"); + await expect(row(page)).toContainText("ssl-vision-processor keeps exiting"); await page.goto(`${host.url}/#0/alerts`); await expect( - page.getByText(/Camera 0's vision_processor keeps exiting/), + page.getByText(/Camera 0's ssl-vision-processor keeps exiting/), ).toBeVisible(); await expect( page.getByText("Last output: VIDIOC_REQBUFS: Device or resource busy"), diff --git a/gui/frontend/e2e/serve.mjs b/gui/frontend/e2e/serve.mjs index 8ab30ee..ebe41e1 100644 --- a/gui/frontend/e2e/serve.mjs +++ b/gui/frontend/e2e/serve.mjs @@ -6,7 +6,7 @@ // serve.mjs [--first-run] [--run-cameras] [--dir ] // --first-run a config the host would have just created itself // --run-cameras -runCameras, with no camera selected and a stand-in -// vision_processor, which crashes while /crash exists +// ssl-vision-processor, which crashes while /crash exists // --dir the host's folder: kept, so a host restarted there goes on // with its files import { spawn } from "node:child_process"; @@ -41,7 +41,7 @@ copyFileSync(join(repo, "robot-heights.yml"), join(dir, "robot-heights.yml")); // The fixture uses the league's default vision and game controller groups, // where this host would publish the fixture's calibrations to every real -// GUI host and vision_processor on the network. A private group and ports +// GUI host and ssl-vision-processor on the network. A private group and ports // keep it to itself; the tracker and video groups too, which it only hears. const octet = () => 1 + Math.floor(Math.random() * 254); const prefix = `239.255.${String(octet())}.`; @@ -70,7 +70,7 @@ console.error( `e2e host: vision ${group}:${String(base)}, game controller ${group}:${String(base + 1)}`, ); -// Debug snapshots for camera 0, as vision_processor writes them: the corner +// Debug snapshots for camera 0, as ssl-vision-processor writes them: the corner // picker's calibration input, a calibration view and a detection view. const img = join(dir, "img"); mkdirSync(img, { recursive: true }); @@ -84,7 +84,7 @@ if (runCameras) { const path = join(dir, "bin"); mkdirSync(path, { recursive: true }); writeFileSync( - join(path, "vision_processor"), + join(path, "ssl-vision-processor"), `#!/bin/sh echo "stand-in running $1" if [ -e "${dir}/crash" ]; then diff --git a/gui/frontend/src/lib/CornerPicker.svelte b/gui/frontend/src/lib/CornerPicker.svelte index eb0ce94..7dab9c8 100644 --- a/gui/frontend/src/lib/CornerPicker.svelte +++ b/gui/frontend/src/lib/CornerPicker.svelte @@ -194,7 +194,7 @@ : undefined, ); // The goals and penalty areas of this camera's region, drawn through the - // corners as vision_processor will match them: the first to the region's + // corners as ssl-vision-processor will match them: the first to the region's // (minX, minY) corner, the rest clockwise. If they don't land on the real // ones, the wrong corner is marked first. let markings = $derived.by(() => { diff --git a/gui/frontend/src/lib/advanced.svelte.ts b/gui/frontend/src/lib/advanced.svelte.ts index cf30219..cdb1086 100644 --- a/gui/frontend/src/lib/advanced.svelte.ts +++ b/gui/frontend/src/lib/advanced.svelte.ts @@ -1,4 +1,4 @@ -// vision_processor's thresholds:, tracking: and debug: settings, edited in +// ssl-vision-processor's thresholds:, tracking: and debug: settings, edited in // vision.yml's defaults so every camera shares them. Fallbacks, ranges, and which keys need // a restart come from the host's schema. import { without } from "./util"; @@ -46,7 +46,7 @@ export const ADVANCED: Record< }; export interface AdvancedSpec { - // vision_processor's fallback when the key is unset. + // ssl-vision-processor's fallback when the key is unset. fallback: number; // The slider's range; the number box takes anything valid. min: number; @@ -78,7 +78,7 @@ function block(name: Block): Record | undefined { : undefined; } -// The shared value, or undefined when vision_processor's fallback applies. +// The shared value, or undefined when ssl-vision-processor's fallback applies. export function advancedValue(s: AdvancedSetting): number | undefined { const v = block(s.block)?.[s.key]; diff --git a/gui/frontend/src/lib/apiTypes.ts b/gui/frontend/src/lib/apiTypes.ts index 721552c..a9b00d1 100644 --- a/gui/frontend/src/lib/apiTypes.ts +++ b/gui/frontend/src/lib/apiTypes.ts @@ -7,7 +7,7 @@ import type { SSL_WrapperPacketJson } from "../proto/vision/ssl_vision_wrapper_p type Schemas = components["schemas"]; -// vision_processor's config.yml layout (defaults, a camera's config). The +// ssl-vision-processor's config.yml layout (defaults, a camera's config). The // spec types it key by key, but the GUI edits it generically, guided by // GET /api/schema at run time. export type Settings = Record; diff --git a/gui/frontend/src/lib/cameraLayout.ts b/gui/frontend/src/lib/cameraLayout.ts index 2b83d40..8c0c079 100644 --- a/gui/frontend/src/lib/cameraLayout.ts +++ b/gui/frontend/src/lib/cameraLayout.ts @@ -189,7 +189,7 @@ function consequence(camera: CameraDoc, to: number): Consequence { }; } -// Whether the host runs every camera's vision_processor itself +// Whether the host runs every camera's ssl-vision-processor itself // (-runCameras). It then gives every region a camera, so a smaller count // removes the cameras whose regions are gone. export function hostRunsCameras(): boolean { @@ -208,7 +208,7 @@ export interface PendingMove { // Whether the physical field is half of the one vision.yml describes // (layout.half_field). Only the GUI reads it: the field is stored as the full -// field it's half of, and vision_processor only ever sees the regions. +// field it's half of, and ssl-vision-processor only ever sees the regions. export function isHalfField(doc: ConfigDocument): boolean { return doc.layout?.halfField === true; } diff --git a/gui/frontend/src/lib/cameraRanges.ts b/gui/frontend/src/lib/cameraRanges.ts index c2bedf9..147d43e 100644 --- a/gui/frontend/src/lib/cameraRanges.ts +++ b/gui/frontend/src/lib/cameraRanges.ts @@ -1,7 +1,7 @@ // Slider ranges for the Camera Settings tab. // // PLACEHOLDERS. A camera's real limits are only known to whoever can talk to -// it: the vision_processor, through its SDK or V4L2. Once it reports them +// it: the ssl-vision-processor, through its SDK or V4L2. Once it reports them // over the network (SSL_VPConfig), these become fallbacks. The number box next // to each slider takes any value, so a range here never limits a setting. // @@ -11,7 +11,7 @@ // exposure_time_absolute unit. // // OPENCV's other ranges use the team's UC70 dev webcam (v4l2-ctl -// --list-ctrls), in the units vision_processor's OpenCV driver actually +// --list-ctrls), in the units ssl-vision-processor's OpenCV driver actually // sends (src/driver/opencvdriver.cpp): // - gain: sent as is. The UC70 takes 0-8. // - gamma: sent as is, where V4L2 means gamma × 100. The UC70 takes diff --git a/gui/frontend/src/lib/cameraSettings.svelte.ts b/gui/frontend/src/lib/cameraSettings.svelte.ts index 37426f1..8280f7c 100644 --- a/gui/frontend/src/lib/cameraSettings.svelte.ts +++ b/gui/frontend/src/lib/cameraSettings.svelte.ts @@ -1,11 +1,11 @@ -// A camera's camera: block (vision_processor's src/driver/cameradriver.cpp), +// A camera's camera: block (ssl-vision-processor's src/driver/cameradriver.cpp), // as the Camera Settings tab edits it. Values shown are effective ones: the // C++ fallbacks (from the host's schema), then vision.yml's defaults.camera, then the camera's own // config.camera. Edits go into the camera's own block, like the color panel: // a key is written when it differs from what the camera would inherit, and // removed when it's set back. // -// vision_processor reads camera: only at startup, so nothing here takes +// ssl-vision-processor reads camera: only at startup, so nothing here takes // effect until it restarts. import { api, unwrap } from "./api"; import { config, cameraDoc } from "./config.svelte"; @@ -83,7 +83,7 @@ const FALLBACK_KEYS = [ "white_balance", ] as const; -// vision_processor's fallbacks for keys the block leaves out. +// ssl-vision-processor's fallbacks for keys the block leaves out. function cppDefaults(): CameraSettings { return Object.fromEntries( FALLBACK_KEYS.map((key) => [key, fallback(`camera.${key}`)]), diff --git a/gui/frontend/src/lib/cameraSettings.test.ts b/gui/frontend/src/lib/cameraSettings.test.ts index 0d083e4..f8b4f44 100644 --- a/gui/frontend/src/lib/cameraSettings.test.ts +++ b/gui/frontend/src/lib/cameraSettings.test.ts @@ -106,7 +106,7 @@ describe("drivers", () => { }); describe("cameraSettings", () => { - it("falls back to vision_processor's defaults", () => { + it("falls back to ssl-vision-processor's defaults", () => { expect(cameraSettings(0)).toEqual({ driver: "SPINNAKER", id: 0, diff --git a/gui/frontend/src/lib/checklist/ChecklistItem.svelte b/gui/frontend/src/lib/checklist/ChecklistItem.svelte index 48dec46..d6852ec 100644 --- a/gui/frontend/src/lib/checklist/ChecklistItem.svelte +++ b/gui/frontend/src/lib/checklist/ChecklistItem.svelte @@ -46,7 +46,7 @@ let page = $derived(PAGE[item.id]); let before = $derived(pendingBefore(item.id, items)); let doneWhen = $derived( - // This host runs the vision_processors itself (-runCameras). + // This host runs the ssl-vision-processors itself (-runCameras). item.id === "processors" && processes.list.length > 0 ? text.items.processors.doneWhenSupervised : words.doneWhen, diff --git a/gui/frontend/src/lib/color.svelte.ts b/gui/frontend/src/lib/color.svelte.ts index 9a52b5f..d22b384 100644 --- a/gui/frontend/src/lib/color.svelte.ts +++ b/gui/frontend/src/lib/color.svelte.ts @@ -158,7 +158,7 @@ export interface ColorConfigData { pink: RGB; } -// vision_processor's own fallbacks, from the host's schema -- what a camera +// ssl-vision-processor's own fallbacks, from the host's schema -- what a camera // runs for anything neither it nor the shared defaults set. export function defaultColorConfig(): ColorConfigData { const rgb = (cls: ColorClass): RGB => { @@ -247,7 +247,7 @@ function fromBlock(block: Block, base: ColorConfigData): ColorConfigData { return out; } -// What a camera runs before its own overrides: vision_processor's built-in +// What a camera runs before its own overrides: ssl-vision-processor's built-in // fallbacks under the document's shared defaults.color. function inheritedColor(): ColorConfigData { return fromBlock( diff --git a/gui/frontend/src/lib/color.test.ts b/gui/frontend/src/lib/color.test.ts index 68798b7..f263929 100644 --- a/gui/frontend/src/lib/color.test.ts +++ b/gui/frontend/src/lib/color.test.ts @@ -111,7 +111,7 @@ it("rgbToCss writes a CSS rgb()", () => { expect(rgbToCss({ r: 1, g: 22, b: 255 })).toBe("rgb(1, 22, 255)"); }); -// The document side: vision_processor's fallbacks (from the schema) under +// The document side: ssl-vision-processor's fallbacks (from the schema) under // defaults.color, under the camera's own color: block. const FALLBACK: Record = { "color.reference_force": 0.5, @@ -152,7 +152,7 @@ beforeEach(() => { }); describe("colorFromDoc", () => { - it("is vision_processor's fallbacks for a camera with nothing set", () => { + it("is ssl-vision-processor's fallbacks for a camera with nothing set", () => { const c = colorFromDoc(0); expect(c.referenceForce).toBe(0.5); diff --git a/gui/frontend/src/lib/config/CameraPanel.svelte b/gui/frontend/src/lib/config/CameraPanel.svelte index 741da07..925603f 100644 --- a/gui/frontend/src/lib/config/CameraPanel.svelte +++ b/gui/frontend/src/lib/config/CameraPanel.svelte @@ -241,7 +241,7 @@
@@ -551,7 +551,7 @@ {#if proc} - +
0 ? "red" : PROCESS_COLOR[proc.state]}> {text.process.state[proc.state]} diff --git a/gui/frontend/src/lib/config/HostInterfaces.svelte b/gui/frontend/src/lib/config/HostInterfaces.svelte index 1953826..2e62740 100644 --- a/gui/frontend/src/lib/config/HostInterfaces.svelte +++ b/gui/frontend/src/lib/config/HostInterfaces.svelte @@ -13,7 +13,7 @@ } from "../network.svelte"; // Which interfaces the GUI host's own sockets use. Host only: interface - // names mean nothing on another machine, and vision_processor always uses + // names mean nothing on another machine, and ssl-vision-processor always uses // the system's default route. let selection = $derived(interfaceSelection()); let ifaces = $derived(network.state?.interfaces ?? []); diff --git a/gui/frontend/src/lib/config/NetworkPanel.svelte b/gui/frontend/src/lib/config/NetworkPanel.svelte index 86bb7e3..f667a7e 100644 --- a/gui/frontend/src/lib/config/NetworkPanel.svelte +++ b/gui/frontend/src/lib/config/NetworkPanel.svelte @@ -77,7 +77,7 @@ } // Cameras whose own config overrides the shared block: their - // vision_processor uses different groups than the host. + // ssl-vision-processor uses different groups than the host. let overriding = $derived( (config.doc?.cameras ?? []) .filter((c) => c.config?.["network"] !== undefined) diff --git a/gui/frontend/src/lib/config/SliderField.svelte b/gui/frontend/src/lib/config/SliderField.svelte index 257ffbb..8304ef3 100644 --- a/gui/frontend/src/lib/config/SliderField.svelte +++ b/gui/frontend/src/lib/config/SliderField.svelte @@ -5,7 +5,7 @@ // One numeric setting: a slider for the usual range and a number box for // anything outside it. With `auto`, a toggle switches to the value that - // means automatic (vision_processor's 0 for exposure and gain), and + // means automatic (ssl-vision-processor's 0 for exposure and gain), and // remembers the manual value for switching back. interface Props { id: string; diff --git a/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts b/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts index 2f1da23..96b3b1c 100644 --- a/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts +++ b/gui/frontend/src/lib/config/WeightTriangle.svelte.test.ts @@ -91,7 +91,7 @@ describe("WeightTriangle", () => { }); }); - it("restores vision_processor's default weights", async () => { + it("restores ssl-vision-processor's default weights", async () => { render(WeightTriangle, {}); await drag({ x: 50, y: 50 }, { x: 50, y: 6 }); await fireEvent.click( diff --git a/gui/frontend/src/lib/config/YuvPositionPane.svelte b/gui/frontend/src/lib/config/YuvPositionPane.svelte index da65491..e917ebf 100644 --- a/gui/frontend/src/lib/config/YuvPositionPane.svelte +++ b/gui/frontend/src/lib/config/YuvPositionPane.svelte @@ -286,7 +286,7 @@ applyHistoryEntry(redoStack, undoStack); } - // Resets to vision_processor's own default reference color + // Resets to ssl-vision-processor's own default reference color // (defaultColorConfig -- same values shown before the first /api/config/color // response arrives), not the "All" view's fixed identity color // (CANONICAL_COLORS is a display-only convenience for telling markers diff --git a/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts b/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts index 00ac9e0..2593d5b 100644 --- a/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts +++ b/gui/frontend/src/lib/config/YuvPositionPane.svelte.test.ts @@ -17,7 +17,7 @@ import { } from "../testing/dom"; import YuvHarness from "../testing/YuvHarness.svelte"; -// vision_processor's fallback colors, as /api/schema has them. +// ssl-vision-processor's fallback colors, as /api/schema has them. const FALLBACK: Record = { yellow: [255, 128, 0], blue: [0, 128, 255], @@ -181,7 +181,7 @@ describe("YuvPositionPane", () => { expect(readout().y).toBe(y); }); - it("restores the selected color to vision_processor's, as an undoable step", async () => { + it("restores the selected color to ssl-vision-processor's, as an undoable step", async () => { render(YuvHarness, { colors: colors(), selectedClass: "orange" }); await fireEvent.click(button("Restore selected color")); diff --git a/gui/frontend/src/lib/config/weights.test.ts b/gui/frontend/src/lib/config/weights.test.ts index 96076bd..5fbbd77 100644 --- a/gui/frontend/src/lib/config/weights.test.ts +++ b/gui/frontend/src/lib/config/weights.test.ts @@ -84,7 +84,7 @@ describe("clampToValidWeights", () => { } }); - it("puts restore defaults on vision_processor's fallback", () => { + it("puts restore defaults on ssl-vision-processor's fallback", () => { const w = clampToValidWeights( { r: DEFAULT_REFERENCE_FORCE, diff --git a/gui/frontend/src/lib/config/weights.ts b/gui/frontend/src/lib/config/weights.ts index dc81676..fb78adf 100644 --- a/gui/frontend/src/lib/config/weights.ts +++ b/gui/frontend/src/lib/config/weights.ts @@ -13,7 +13,7 @@ export interface Point { y: number; } -// vision_processor's own fallback (Resources.cpp:202-203, colorconfig.go's +// ssl-vision-processor's own fallback (Resources.cpp:202-203, colorconfig.go's // ReadColorConfig) -- what a color update uses when config.yml has neither // force set at all. "Restore defaults" puts the marker back here, not at // some arbitrary triangle centroid. diff --git a/gui/frontend/src/lib/corners.ts b/gui/frontend/src/lib/corners.ts index b23b0fb..372e8f3 100644 --- a/gui/frontend/src/lib/corners.ts +++ b/gui/frontend/src/lib/corners.ts @@ -1,8 +1,8 @@ // Geometry for the corner picker's four line corners (CornerPicker.svelte). -// Only the first one matters to vision_processor (see the note there), but +// Only the first one matters to ssl-vision-processor (see the note there), but // the picker draws them as a polygon in list order, so the other three must // go around the quadrilateral, not cross it. It also draws the goals and -// penalty areas through them, as vision_processor would read them. +// penalty areas through them, as ssl-vision-processor would read them. import type { FieldSlice } from "./fieldSplit"; import type { FieldConfig } from "./apiTypes"; @@ -34,7 +34,7 @@ export function aroundFirst(points: Point[]): Point[] { return rotateTo(sorted, sorted.indexOf(first)); } -// The corners in the order vision_processor matches them to its region's +// The corners in the order ssl-vision-processor matches them to its region's // field corners (minX,minY), (minX,maxY), (maxX,maxY), (maxX,minY): the first // one first, the rest clockwise on screen (GeomModel.cpp's cornerCalibration, // isClockwiseConvexQuadrilateral and PointGeometryFit). diff --git a/gui/frontend/src/lib/layout/configCategories.ts b/gui/frontend/src/lib/layout/configCategories.ts index 2ba30ce..7bf3de6 100644 --- a/gui/frontend/src/lib/layout/configCategories.ts +++ b/gui/frontend/src/lib/layout/configCategories.ts @@ -53,7 +53,7 @@ export const CONFIG_CATEGORIES: ConfigCategory[] = [ id: "network", label: "Network", // vision.yml's defaults.network: one pair of groups for the host and - // every vision_processor. Edited by config/NetworkPanel.svelte. + // every ssl-vision-processor. Edited by config/NetworkPanel.svelte. scope: "shared", yamlKey: "network", fields: CONFIG_FIELDS.network, diff --git a/gui/frontend/src/lib/lineDetection.svelte.ts b/gui/frontend/src/lib/lineDetection.svelte.ts index 1c339a3..68f650a 100644 --- a/gui/frontend/src/lib/lineDetection.svelte.ts +++ b/gui/frontend/src/lib/lineDetection.svelte.ts @@ -1,11 +1,11 @@ // A camera's field line detection settings: config.yml's geometry: block, // minus what the host derives (camera_amount, line_corners). Per camera, like // the camera: block in cameraSettings.svelte.ts: the camera's own value, else -// vision.yml's defaults.geometry, else vision_processor's fallback. Edits go +// vision.yml's defaults.geometry, else ssl-vision-processor's fallback. Edits go // into the camera's own block, and setting a key back to what it would // inherit removes it. // -// vision_processor uses these only while it calibrates: at startup, and only +// ssl-vision-processor uses these only while it calibrates: at startup, and only // when the host isn't publishing a locked calibration for the camera. import { config, cameraDoc } from "./config.svelte"; import { fallback, setting } from "./schema.svelte"; diff --git a/gui/frontend/src/lib/live/patterns.ts b/gui/frontend/src/lib/live/patterns.ts index c919de4..39dfe24 100644 --- a/gui/frontend/src/lib/live/patterns.ts +++ b/gui/frontend/src/lib/live/patterns.ts @@ -1,4 +1,4 @@ -// The league's standard robot pattern, as vision_processor detects it +// The league's standard robot pattern, as ssl-vision-processor detects it // (src/pattern.h): a team-colored center dot and four ID dots, green or pink. // Robot frame, mm: +x along the robot's orientation, +y to its left. diff --git a/gui/frontend/src/lib/live/sources.ts b/gui/frontend/src/lib/live/sources.ts index f58b309..291ef0f 100644 --- a/gui/frontend/src/lib/live/sources.ts +++ b/gui/frontend/src/lib/live/sources.ts @@ -1,4 +1,4 @@ -// The Live Field's sources: the vision_processors' raw detections (one +// The Live Field's sources: the ssl-vision-processors' raw detections (one // source, made of every camera heard) and each autoref's tracker, found by // what the host hears on the tracker group. import type { SSL_DetectionFrameJson } from "../../proto/vision/ssl_vision_detection_pb"; @@ -100,7 +100,7 @@ export function layersOf( } // A camera's processing time: capture to send, both by the -// vision_processor's own clock, in ms. +// ssl-vision-processor's own clock, in ms. export function processingMs(camera: LiveFieldCamera): number | null { const frame: SSL_DetectionFrameJson | undefined = camera.frame; const sent = Number(frame?.tSent); diff --git a/gui/frontend/src/lib/network.svelte.ts b/gui/frontend/src/lib/network.svelte.ts index c1ad12b..51aeb5d 100644 --- a/gui/frontend/src/lib/network.svelte.ts +++ b/gui/frontend/src/lib/network.svelte.ts @@ -1,6 +1,6 @@ // The vision, game controller and autoref tracker addresses. Vision and game // controller live in vision.yml's defaults.network (the same block every -// vision_processor reads from its generated config.yml); the tracker, which +// ssl-vision-processor reads from its generated config.yml); the tracker, which // only the host listens to, in the top-level tracker block. Editing them goes // through config.doc like any other setting; the host reopens its sockets as // soon as the edit lands. Socket status arrives separately, once a second, on diff --git a/gui/frontend/src/lib/network.test.ts b/gui/frontend/src/lib/network.test.ts index 282f7e0..848ba83 100644 --- a/gui/frontend/src/lib/network.test.ts +++ b/gui/frontend/src/lib/network.test.ts @@ -57,7 +57,7 @@ beforeEach(() => { }); describe("the network block", () => { - it("falls back to vision_processor's defaults and the standard tracker group", () => { + it("falls back to ssl-vision-processor's defaults and the standard tracker group", () => { expect(networkFromDoc()).toEqual({ ...FALLBACKS, tracker_ip: "224.5.23.2", diff --git a/gui/frontend/src/lib/preferences.svelte.ts b/gui/frontend/src/lib/preferences.svelte.ts index c881ce2..12d4646 100644 --- a/gui/frontend/src/lib/preferences.svelte.ts +++ b/gui/frontend/src/lib/preferences.svelte.ts @@ -1,5 +1,5 @@ // Global, client-only UI preferences -- these control how this browser's UI -// behaves, not anything vision_processor or config.yml cares about, so they +// behaves, not anything ssl-vision-processor or config.yml cares about, so they // live in localStorage rather than going through any /api/config endpoint. // Same module-level $state pattern as color.svelte.ts's colorConfig; any // component can import `preferences` and both read it and bind: to it diff --git a/gui/frontend/src/lib/processes.svelte.ts b/gui/frontend/src/lib/processes.svelte.ts index 3cf2296..ac00fec 100644 --- a/gui/frontend/src/lib/processes.svelte.ts +++ b/gui/frontend/src/lib/processes.svelte.ts @@ -1,4 +1,4 @@ -// The vision_processors the host runs itself (started with -runCameras), from the +// The ssl-vision-processors the host runs itself (started with -runCameras), from the // processes.state topic. Empty when the host runs none: then each one is // started and restarted by hand. import { onTopic } from "./bus.svelte"; diff --git a/gui/frontend/src/lib/report/systemReport.ts b/gui/frontend/src/lib/report/systemReport.ts index 6e7f938..b6abc1a 100644 --- a/gui/frontend/src/lib/report/systemReport.ts +++ b/gui/frontend/src/lib/report/systemReport.ts @@ -4,7 +4,7 @@ // /api/config, if the user includes it) plus what the browser knows about // itself, and only ever downloaded or copied, never sent. // -// vision_processor's own state (its logs, its announced config) isn't in it +// ssl-vision-processor's own state (its logs, its announced config) isn't in it // yet. import { api, unwrap } from "../api"; diff --git a/gui/frontend/src/lib/schema.svelte.ts b/gui/frontend/src/lib/schema.svelte.ts index 3d21da1..15c7147 100644 --- a/gui/frontend/src/lib/schema.svelte.ts +++ b/gui/frontend/src/lib/schema.svelte.ts @@ -1,4 +1,4 @@ -// What the host says about vision_processor's settings (GET /api/schema; see +// What the host says about ssl-vision-processor's settings (GET /api/schema; see // gui/internal/config's schema.go): each key's type, fallback, bounds, and // whether a change needs a restart. The one copy of what src/Resources.cpp // does with config.yml, so nothing here repeats it. loadConfig loads it before @@ -43,7 +43,7 @@ export function setting(path: string): Setting { return s; } -// vision_processor's fallback for path. +// ssl-vision-processor's fallback for path. export function fallback(path: string): unknown { return setting(path).default; } diff --git a/gui/frontend/src/lib/teams.svelte.ts b/gui/frontend/src/lib/teams.svelte.ts index 2091883..a19875e 100644 --- a/gui/frontend/src/lib/teams.svelte.ts +++ b/gui/frontend/src/lib/teams.svelte.ts @@ -15,7 +15,7 @@ export type Color = "yellow" | "blue"; export const COLORS: Color[] = ["yellow", "blue"]; // The GUI's robot height for a team or color with nothing set, in mm: the -// Division A limit. vision_processor's own fallback is its table's mean. +// Division A limit. ssl-vision-processor's own fallback is its table's mean. export const DEFAULT_ROBOT_HEIGHT = 150; // Issues that only mean the default height applies, as opposed to a choice @@ -95,7 +95,7 @@ function setChoice(slot: Slot, value: TeamOverride | undefined): void { } // On: no choice, so the height comes from the table (by game controller -// name) or vision_processor's default. Off: a choice, starting as a custom +// name) or ssl-vision-processor's default. Off: a choice, starting as a custom // height not entered yet. export function setFromTable(slot: Slot, on: boolean): void { setChoice(slot, on ? undefined : (choice(slot) ?? {})); @@ -111,7 +111,7 @@ export function setCustomHeight(slot: Slot, height: number): void { setChoice(slot, { height }); } -// Why a color's robots would get vision_processor's default height, or null +// Why a color's robots would get ssl-vision-processor's default height, or null // if they have a known one: // notInTable: the game controller's team isn't in the table, no choice // noHeight: no game controller team and no choice for the color diff --git a/gui/frontend/src/lib/text/about.ts b/gui/frontend/src/lib/text/about.ts index 582bbda..7721e48 100644 --- a/gui/frontend/src/lib/text/about.ts +++ b/gui/frontend/src/lib/text/about.ts @@ -39,7 +39,7 @@ export const about = { includeConfigNote: "The working copy, unsaved changes included: cameras, calibrations, colors and network addresses.", notIncluded: - "Not included: camera images, or vision_processor's own logs. Attach them separately if the issue needs them.", + "Not included: camera images, or ssl-vision-processor's own logs. Attach them separately if the issue needs them.", privacy: "Check it before posting it publicly: hostnames, IP addresses and file paths can identify your network.", gathering: "Gathering…", diff --git a/gui/frontend/src/lib/text/advanced.ts b/gui/frontend/src/lib/text/advanced.ts index 8d0f6c5..6034b00 100644 --- a/gui/frontend/src/lib/text/advanced.ts +++ b/gui/frontend/src/lib/text/advanced.ts @@ -1,4 +1,4 @@ -// Advanced page (config/AdvancedPanel.svelte): vision_processor's +// Advanced page (config/AdvancedPanel.svelte): ssl-vision-processor's // thresholds:, tracking: and debug: settings, shared by every camera. Notes are // from config.yml's comments and src/Resources.cpp. `backticks` show as code. @@ -6,10 +6,10 @@ import { plural } from "./common"; export const advanced = { heading: "Advanced", intro: - "Detection thresholds, tracking limits and diagnostics, shared by every camera (vision.yml's `defaults.thresholds`, `defaults.tracking` and `defaults.debug`). The defaults suit most fields; change these only to fix a specific detection problem. Most apply live; the ones marked restart need a vision_processor restart.", + "Detection thresholds, tracking limits and diagnostics, shared by every camera (vision.yml's `defaults.thresholds`, `defaults.tracking` and `defaults.debug`). The defaults suit most fields; change these only to fix a specific detection problem. Most apply live; the ones marked restart need an ssl-vision-processor restart.", overriding: (cameras: number[]): string => `${plural(cameras.length, "Camera")} ${cameras.join(", ")} override${cameras.length === 1 ? "s" : ""} some of these in their own config, so they don't follow this page for those values.`, - restart: "Applies when vision_processor restarts.", + restart: "Applies when ssl-vision-processor restarts.", defaultIs: (value: string): string => `Default: ${value}.`, reset: "Reset to default", @@ -35,7 +35,7 @@ export const advanced = { blobs: { label: "Max blobs", notes: [ - "Most blobs processed per frame. Shouldn't need changing; vision_processor logs a warning when a frame hits it.", + "Most blobs processed per frame. Shouldn't need changing; ssl-vision-processor logs a warning when a frame hits it.", ], }, min_confidence: { diff --git a/gui/frontend/src/lib/text/alerts.ts b/gui/frontend/src/lib/text/alerts.ts index 1e3c5df..c6642e8 100644 --- a/gui/frontend/src/lib/text/alerts.ts +++ b/gui/frontend/src/lib/text/alerts.ts @@ -25,7 +25,7 @@ export const alerts = { renderFailed: (camera: string): string => `Can't write camera ${camera}'s config.yml`, conflict: (camera: number): string => - `Camera ID ${String(camera)} is sent by several vision_processors`, + `Camera ID ${String(camera)} is sent by several ssl-vision-processors`, heardFrom: (addresses: string[]): string => `Heard from ${addresses.join(", ")}.`, uncovered: (camera: number, region: string): string => @@ -56,15 +56,15 @@ export const alerts = { colorDefaultHeight: (color: string): string => `${color} robots would get a default robot height`, deviceConflict: (camera: number): string => - `Camera ${String(camera)}'s vision_processor isn't started`, + `Camera ${String(camera)}'s ssl-vision-processor isn't started`, deviceConflictDetail: (conflict: string): string => `${conflict.charAt(0).toUpperCase()}${conflict.slice(1)}.`, cameraNotSelected: (camera: number): string => `Camera ${String(camera)} has no driver selected`, cameraNotSelectedDetail: - "Its vision_processor can't run until you choose one.", + "Its ssl-vision-processor can't run until you choose one.", processCrashing: (camera: number, crashes: number): string => - `Camera ${String(camera)}'s vision_processor keeps exiting (${String(crashes)} times in a row)`, + `Camera ${String(camera)}'s ssl-vision-processor keeps exiting (${String(crashes)} times in a row)`, processCrashingDetail: (lastLine: string, exit: string): string => lastLine ? `Last output: ${lastLine}` : `It printed nothing; ${exit}.`, firstRun: "Not publishing until you save", diff --git a/gui/frontend/src/lib/text/app.ts b/gui/frontend/src/lib/text/app.ts index 31dc85e..909e098 100644 --- a/gui/frontend/src/lib/text/app.ts +++ b/gui/frontend/src/lib/text/app.ts @@ -60,13 +60,13 @@ export const app = { // The "Vision processors" heading's tooltip. instancesHelp: "One row per camera role, not per machine: a host running all 4 cameras of a quad setup appears here 4 times. From vision.yml's cameras list.", - // The status dot of a vision_processor the host runs itself. + // The status dot of an ssl-vision-processor the host runs itself. process: { - running: "vision_processor running", - starting: "vision_processor starting", - failing: "vision_processor keeps exiting", - held: "vision_processor not started: device in use", - noCamera: "vision_processor not started: no camera selected", + running: "ssl-vision-processor running", + starting: "ssl-vision-processor starting", + failing: "ssl-vision-processor keeps exiting", + held: "ssl-vision-processor not started: device in use", + noCamera: "ssl-vision-processor not started: no camera selected", }, }, diff --git a/gui/frontend/src/lib/text/camera.ts b/gui/frontend/src/lib/text/camera.ts index 1143951..6fac018 100644 --- a/gui/frontend/src/lib/text/camera.ts +++ b/gui/frontend/src/lib/text/camera.ts @@ -6,15 +6,15 @@ export const camera = { heading: "Camera settings", // The banner above the video. `backticks` show as code. restartBanner: (camera: number): string => - `These apply when cam ${String(camera)}'s vision_processor restarts: it reads \`camera:\` only at startup.`, + `These apply when cam ${String(camera)}'s ssl-vision-processor restarts: it reads \`camera:\` only at startup.`, writesTo: (path: string): string => `The host writes them to \`${path}\`.`, noConfigPath: "This camera has no `config_path`, so the host doesn't write its config file; copy these to it by hand.", - // The host's own vision_processor for this camera (gui started with + // The host's own ssl-vision-processor for this camera (gui started with // -runCameras). process: { banner: (camera: number): string => - `The host runs cam ${String(camera)}'s vision_processor and restarts it when a setting it reads only at startup changes.`, + `The host runs cam ${String(camera)}'s ssl-vision-processor and restarts it when a setting it reads only at startup changes.`, state: { running: "Running", restarting: "Restarting", @@ -43,11 +43,11 @@ export const camera = { noInstance: SELECT_INSTANCE, driver: [ - "SPINNAKER, MVIMPACT and DC1394 need vision_processor built with their SDKs.", + "SPINNAKER, MVIMPACT and DC1394 need ssl-vision-processor built with their SDKs.", "A file without a driver means SPINNAKER. New configurations start with no camera selected.", ], noDriver: - "Choose the driver for this camera. Its vision_processor can't run without one.", + "Choose the driver for this camera. Its ssl-vision-processor can't run without one.", cameraIndex: ["Position in the SDK's camera list, in detection order."], serial: [ "Stays with the camera, where the index shifts when another camera is missing. List them with build/spinnaker_probe --list.", @@ -90,7 +90,7 @@ export const camera = { "At or above the frame time (33 ms at 30 fps) the frame rate drops.", ], opencv: [ - "V4L2 sets exposure in 100 µs steps. The host writes config.yml in the unit vision_processor's OpenCV driver expects (5000 µs is 0.05).", + "V4L2 sets exposure in 100 µs steps. The host writes config.yml in the unit ssl-vision-processor's OpenCV driver expects (5000 µs is 0.05).", ], sdk: [ "The host writes config.yml in milliseconds, the unit this driver reads.", @@ -117,12 +117,12 @@ export const camera = { "Below 1 evens out bright and dark areas; above 1 adds color contrast.", ], opencv: [ - "V4L2 counts gamma × 100 and vision_processor sends the file's value unscaled, so 100 here is a gamma of 1.0.", + "V4L2 counts gamma × 100 and ssl-vision-processor sends the file's value unscaled, so 100 here is a gamma of 1.0.", "Placeholder range: the UC70 dev camera's 100-300.", ], sdk: [PLACEHOLDER_RANGE], opencvIgnored: - "vision_processor's OpenCV driver currently ignores gamma other than 1.0 (opencvdriver.cpp:43 checks the wrong way round).", + "ssl-vision-processor's OpenCV driver currently ignores gamma other than 1.0 (opencvdriver.cpp:43 checks the wrong way round).", }, whiteBalance: { diff --git a/gui/frontend/src/lib/text/checklist.ts b/gui/frontend/src/lib/text/checklist.ts index 95a3ae1..1dd627f 100644 --- a/gui/frontend/src/lib/text/checklist.ts +++ b/gui/frontend/src/lib/text/checklist.ts @@ -100,7 +100,7 @@ export const checklist = { title: "Vision processors running", why: "A vision processor reads one camera and sends its detections. The host only sees a camera once its processor is running.", doneWhen: - "Every camera below shows as sending. If one stays silent, check that its vision_processor is running and its camera is plugged in.", + "Every camera below shows as sending. If one stays silent, check that its ssl-vision-processor is running and its camera is plugged in.", doneWhenSupervised: "Every camera below shows as sending. This host starts them itself; if one stays silent, check its camera is plugged in and look at the Camera page.", action: "Open Camera", diff --git a/gui/frontend/src/lib/text/common.ts b/gui/frontend/src/lib/text/common.ts index fed531e..e8778c7 100644 --- a/gui/frontend/src/lib/text/common.ts +++ b/gui/frontend/src/lib/text/common.ts @@ -1,7 +1,7 @@ // Phrases more than one page uses. export const PLACEHOLDER_RANGE = - "Placeholder range until vision_processor reports the camera's."; + "Placeholder range until ssl-vision-processor reports the camera's."; export const NO_HOST = "(no host)"; diff --git a/gui/frontend/src/lib/text/docs.ts b/gui/frontend/src/lib/text/docs.ts index 07fe899..8bf6d49 100644 --- a/gui/frontend/src/lib/text/docs.ts +++ b/gui/frontend/src/lib/text/docs.ts @@ -17,7 +17,7 @@ export const RESOLUTION_DOCS = { "config-render-failed": { title: "A camera's config.yml can't be written", cause: - "The host regenerates each local camera's config.yml from vision.yml on every change. Writing it failed, so that vision_processor keeps its old settings.", + "The host regenerates each local camera's config.yml from vision.yml on every change. Writing it failed, so that ssl-vision-processor keeps its old settings.", steps: [ "Read the error on the alert: usually a missing directory or a permission problem.", "Check the camera's config_path in vision.yml points somewhere this host can write.", @@ -25,13 +25,13 @@ export const RESOLUTION_DOCS = { ], }, "camera-id-conflict": { - title: "Two vision_processors send the same camera ID", + title: "Two ssl-vision-processors send the same camera ID", cause: - "Each vision_processor must have its own cam_id. Two with the same one overwrite each other's detections and fight over one calibration.", + "Each ssl-vision-processor must have its own cam_id. Two with the same one overwrite each other's detections and fight over one calibration.", steps: [ "Open Layout and note the addresses listed for this camera ID.", "On one of those machines, change cam_id in its config.yml to the free region it actually covers.", - "Restart that vision_processor. The conflict clears within a few seconds.", + "Restart that ssl-vision-processor. The conflict clears within a few seconds.", ], }, "socket-problem": { @@ -47,9 +47,9 @@ export const RESOLUTION_DOCS = { "vision-silent": { title: "No detections heard", cause: - "No vision_processor detection packets arrived on the vision address. Either nothing is running, or the address, port, or network differs.", + "No ssl-vision-processor detection packets arrived on the vision address. Either nothing is running, or the address, port, or network differs.", steps: [ - "Check at least one vision_processor is running.", + "Check at least one ssl-vision-processor is running.", "On the Network page, check the vision address and port match its config.yml (defaults.network in vision.yml).", "Check both machines are on the same network and the switch passes multicast.", ], @@ -66,18 +66,18 @@ export const RESOLUTION_DOCS = { "sender-conflict-calibration": { title: "A camera's calibration comes from several senders", cause: - "Each camera's calibration should come from its own vision_processor only. Another GUI host, a test, or a second vision_processor with the same cam_id is also sending one, and whichever arrived last is what every vision_processor for that camera uses instead of calibrating.", + "Each camera's calibration should come from its own ssl-vision-processor only. Another GUI host, a test, or a second ssl-vision-processor with the same cam_id is also sending one, and whichever arrived last is what every ssl-vision-processor for that camera uses instead of calibrating.", steps: [ "Read the senders on the alert: address, port, and hostname. The host's log has the same, under 'several senders claim the same thing'.", - "A sender on port 10006 is a vision_processor; any other port is usually another GUI host or a tool.", + "A sender on port 10006 is an ssl-vision-processor; any other port is usually another GUI host or a tool.", "Stop the one that shouldn't be there, or move it to its own vision address and port.", - "Then unlock this camera's calibration on the Geometry page and restart its vision_processor so it calibrates again.", + "Then unlock this camera's calibration on the Geometry page and restart its ssl-vision-processor so it calibrates again.", ], }, "sender-conflict-geometry": { title: "Another host is publishing field geometry", cause: - "This GUI host publishes the field and every camera's calibration once a second. Another host doing the same on this vision address makes vision_processors switch between the two.", + "This GUI host publishes the field and every camera's calibration once a second. Another host doing the same on this vision address makes ssl-vision-processors switch between the two.", steps: [ "Read the sender on the alert: address, port, and hostname. 'this machine' means another program here, such as a second GUI host, a test, or geom_publisher.py.", "Stop it, or move one of the two to its own vision address and port on the Network page.", @@ -105,27 +105,27 @@ export const RESOLUTION_DOCS = { "sender-conflict-video": { title: "A camera's video comes from several senders", cause: - "Two vision_processors stream to the same address, usually because they share a cam_id or stream settings. The video interleaves both and breaks up.", + "Two ssl-vision-processors stream to the same address, usually because they share a cam_id or stream settings. The video interleaves both and breaks up.", steps: [ "Read the senders on the alert: address, port, and hostname.", - "Give each vision_processor its own cam_id, or change one's stream settings.", + "Give each ssl-vision-processor its own cam_id, or change one's stream settings.", ], }, "team-height-missing": { title: "A team would get a default robot height", cause: - "vision_processor looks each team up in its height table by its exact game controller name. A team that isn't listed keeps that color's previous height: the table's mean before any known team has played, otherwise the last known team's, which after a color switch is the other team's. Robots are then placed at the wrong height, which shifts them on the field.", + "ssl-vision-processor looks each team up in its height table by its exact game controller name. A team that isn't listed keeps that color's previous height: the table's mean before any known team has played, otherwise the last known team's, which after a color switch is the other team's. Robots are then placed at the wrong height, which shifts them on the field.", steps: [ "Open the Teams page and find the team in its list.", "Turn off Derive from game controller, then pick the table entry that matches the team, or Custom and enter its robot height in mm.", "Save. The override is kept by team name, so it follows the team if the colors are switched.", - "Until vision_processor reads these overrides, also add the team to the height table (bot_heights_file, robot-heights.yml by default) under its exact game controller name, and restart the vision_processors.", + "Until ssl-vision-processor reads these overrides, also add the team to the height table (bot_heights_file, robot-heights.yml by default) under its exact game controller name, and restart the ssl-vision-processors.", ], }, "device-conflict": { title: "Two cameras would open one device", cause: - "The host runs every camera's vision_processor itself (-runCameras), and two cameras name the same capture device: the same driver and device, or two names for one /dev/video node. Only the lower camera ID is started; the other waits, so they don't fight over the camera.", + "The host runs every camera's ssl-vision-processor itself (-runCameras), and two cameras name the same capture device: the same driver and device, or two names for one /dev/video node. Only the lower camera ID is started; the other waits, so they don't fight over the camera.", steps: [ "Open the camera on the Camera page and choose its own device under camera, or remove the camera if it's a leftover.", "It starts by itself as soon as its device is free. Nothing needs restarting.", @@ -134,21 +134,21 @@ export const RESOLUTION_DOCS = { "camera-not-selected": { title: "No camera driver selected", cause: - "A new configuration doesn't guess which camera you have (driver DUMMY). vision_processor exits with that driver, so a host that runs the cameras (-runCameras) waits for you to choose one.", + "A new configuration doesn't guess which camera you have (driver DUMMY). ssl-vision-processor exits with that driver, so a host that runs the cameras (-runCameras) waits for you to choose one.", steps: [ "Open the Camera page and choose the driver: OPENCV for a webcam, SPINNAKER for FLIR, MVIMPACT for Bluefox3, DC1394 for FireWire.", "Choose the device too if there's more than one.", - "With -runCameras it starts by itself. Otherwise restart that camera's vision_processor.", + "With -runCameras it starts by itself. Otherwise restart that camera's ssl-vision-processor.", ], }, "process-crashing": { - title: "A camera's vision_processor keeps exiting", + title: "A camera's ssl-vision-processor keeps exiting", cause: - "The host runs every camera's vision_processor itself (-runCameras) and restarts one that exits, waiting longer each time. This one has failed several times in a row, usually because it can't open its camera: the wrong driver, a device that's missing or busy, or a driver the build doesn't include.", + "The host runs every camera's ssl-vision-processor itself (-runCameras) and restarts one that exits, waiting longer each time. This one has failed several times in a row, usually because it can't open its camera: the wrong driver, a device that's missing or busy, or a driver the build doesn't include.", steps: [ "Read its last output, here and in full at the bottom of the Camera page. It usually names the problem.", "Check the camera's driver and device on the Camera page. A webcam needs OPENCV and a /dev/video path; SPINNAKER, what a file without a driver means, is for FLIR cameras only.", - "Check nothing else has the camera open (another vision_processor, a video call, cheese).", + "Check nothing else has the camera open (another ssl-vision-processor, a video call, cheese).", "It restarts by itself after each change. Nothing else needs restarting.", ], }, @@ -164,7 +164,7 @@ export const RESOLUTION_DOCS = { "heights-unreadable": { title: "The robot height table can't be read", cause: - "vision_processor needs its bot_heights_file to place robots at the right height, and fails to start without it.", + "ssl-vision-processor needs its bot_heights_file to place robots at the right height, and fails to start without it.", steps: [ "Check the file named by vision.yml's defaults.bot_heights_file (robot-heights.yml when unset) is in the config folder. The host prints that folder at startup.", "Check the file is valid YAML: one `team name: height in mm` per line.", @@ -173,12 +173,12 @@ export const RESOLUTION_DOCS = { "loopback-multicast-off": { title: "Multicast is off on the loopback interface", cause: - "This machine has no network in use, so its programs (a vision_processor and the GUI on one laptop) can only reach each other over loopback, where Ubuntu turns multicast off.", + "This machine has no network in use, so its programs (an ssl-vision-processor and the GUI on one laptop) can only reach each other over loopback, where Ubuntu turns multicast off.", steps: [ "Connect a network, or turn loopback multicast on until the next reboot:", "$ sudo ip link set lo multicast on", "$ sudo ip route add 224.0.0.0/4 dev lo src 127.0.0.1", - "With automatic interfaces the GUI then uses lo by itself. Restart any vision_processor already running.", + "With automatic interfaces the GUI then uses lo by itself. Restart any ssl-vision-processor already running.", "Before connecting a network again, remove the route, or multicast keeps going to loopback only:", "$ sudo ip route del 224.0.0.0/4 dev lo", ], @@ -189,11 +189,11 @@ export const RESOLUTION_DOCS = { "The camera count splits the field into regions, and no camera is assigned to this one. Nothing there is detected.", steps: [ "Open Layout.", - "Assign a camera to the region, add the vision_processor heard for it, or lower the camera count.", + "Assign a camera to the region, add the ssl-vision-processor heard for it, or lower the camera count.", ], }, "camera-unplaced": { - title: "A vision_processor isn't in the layout", + title: "An ssl-vision-processor isn't in the layout", cause: "Detections arrive with a camera ID that no camera in vision.yml has, so the GUI can't configure or calibrate it.", steps: [ @@ -217,7 +217,7 @@ export const RESOLUTION_DOCS = { steps: [ "Open the camera's Geometry tab.", "Move the corner markers onto the corners of the new region; the first goes on the region's (minX, minY) corner, as the picker says.", - "Restart the vision_processor so it recalibrates.", + "Restart the ssl-vision-processor so it recalibrates.", ], }, "seed-resolution": { @@ -243,16 +243,16 @@ export const RESOLUTION_DOCS = { "The field dimensions changed after this calibration was locked, so it was solved against the old field lines.", steps: [ "Open the camera's Geometry tab.", - "Unlock the calibration and restart the vision_processor to recalibrate, then lock the new one.", + "Unlock the calibration and restart the ssl-vision-processor to recalibrate, then lock the new one.", ], }, "calibration-resolution": { title: "Locked calibration doesn't match the camera resolution", cause: - "The calibration was solved at a different aspect ratio than the camera now sends; vision_processor can't rescale it.", + "The calibration was solved at a different aspect ratio than the camera now sends; ssl-vision-processor can't rescale it.", steps: [ "Open the camera's Geometry tab.", - "Unlock, restart the vision_processor to recalibrate, then lock again.", + "Unlock, restart the ssl-vision-processor to recalibrate, then lock again.", ], }, } satisfies Record; diff --git a/gui/frontend/src/lib/text/geometry.ts b/gui/frontend/src/lib/text/geometry.ts index f49eb1d..2a17735 100644 --- a/gui/frontend/src/lib/text/geometry.ts +++ b/gui/frontend/src/lib/text/geometry.ts @@ -11,12 +11,12 @@ export const geometry = { lineDetection: { title: "Field line detection", restart: - "Used when vision_processor calibrates, at startup. With the host running it (-runCameras), it restarts on its own.", + "Used when ssl-vision-processor calibrates, at startup. With the host running it (-runCameras), it restarts on its own.", locked: "This camera's calibration is locked, so it doesn't calibrate and these have no effect until you unlock it.", reset: "Back to the shared default", defaultIs: (value: string): string => - `vision_processor's default: ${value}.`, + `ssl-vision-processor's default: ${value}.`, refinement: { label: "Refinement", notes: [ @@ -68,10 +68,10 @@ export const geometry = { cornerPicker: { title: "Corner picker", noFrame: (camera: number): string => - `No calibration frame from camera ${String(camera)} yet. Its vision_processor saves one when it starts calibrating, on this machine only; Refresh frame checks again.`, + `No calibration frame from camera ${String(camera)} yet. Its ssl-vision-processor saves one when it starts calibrating, on this machine only; Refresh frame checks again.`, refresh: "Refresh frame", intro: - "Drag the four markers onto the real field corners in the image below, then click the number on whichever one sits where the goal line meets the touchline nearest this field's (0,0) corner — that one turns green and becomes first in the output. The other three can be in any order; the calibration algorithm works that out itself. The goal and penalty area this camera should see are drawn dashed through the markers, as vision_processor will read them: if they don't sit on the real ones, the green marker is on the wrong corner. Changes apply when you let go of a marker; Save keeps them.", + "Drag the four markers onto the real field corners in the image below, then click the number on whichever one sits where the goal line meets the touchline nearest this field's (0,0) corner — that one turns green and becomes first in the output. The other three can be in any order; the calibration algorithm works that out itself. The goal and penalty area this camera should see are drawn dashed through the markers, as ssl-vision-processor will read them: if they don't sit on the real ones, the green marker is on the wrong corner. Changes apply when you let go of a marker; Save keeps them.", region: ( camera: number, count: number, @@ -97,5 +97,5 @@ export const geometry = { unlockTitle: "Unlock calibration?", unlockConfirm: "Unlock", confirmUnlock: (camera: number): string => - `Unlock camera ${String(camera)}'s calibration? It stops being published now, and the camera recalibrates the next time its vision_processor restarts.`, + `Unlock camera ${String(camera)}'s calibration? It stops being published now, and the camera recalibrates the next time its ssl-vision-processor restarts.`, }; diff --git a/gui/frontend/src/lib/text/layout.ts b/gui/frontend/src/lib/text/layout.ts index 10d22d4..868dfac 100644 --- a/gui/frontend/src/lib/text/layout.ts +++ b/gui/frontend/src/lib/text/layout.ts @@ -5,17 +5,17 @@ import { plural } from "./common"; export const layout = { heading: "Camera Layout", intro: - "Each vision_processor covers one region of the field. Its camera ID and the camera count decide which region, and so the corners its calibration fits to. One host can run any number of cameras.", + "Each ssl-vision-processor covers one region of the field. Its camera ID and the camera count decide which region, and so the corners its calibration fits to. One host can run any number of cameras.", cameraCount: [ - "vision_processor's geometry.camera_amount. The field is halved along its longer side for each doubling.", + "ssl-vision-processor's geometry.camera_amount. The field is halved along its longer side for each doubling.", ], field: { label: "Field", full: "Full field", half: "Half field", notes: [ - "A half field is entered as the full field it's half of, with each camera covering one region of it; vision_processor only sees the regions.", + "A half field is entered as the full field it's half of, with each camera covering one region of it; ssl-vision-processor only sees the regions.", "Set by the setup wizard too.", ], }, @@ -33,7 +33,7 @@ export const layout = { "Click a region to select it; it plays live. The view is saved in this browser only.", conflict: - "Several vision_processors send this camera ID. Each must have its own; check their cam_id.", + "Several ssl-vision-processors send this camera ID. Each must have its own; check their cam_id.", cameraPicker: ["Picking a camera that covers another region swaps the two."], videoOrientation: [ "Turns this camera's video to match the field, for a camera mounted at an angle. Only the GUI uses it.", @@ -44,7 +44,7 @@ export const layout = { unplaced: { title: "Heard but not placed", intro: - "These vision_processors send detections with a camera ID that no camera here has.", + "These ssl-vision-processors send detections with a camera ID that no camera here has.", outside: (count: number): string => `Outside the ${String(count)}-camera layout; its cam_id is wrong or the count is too low.`, }, @@ -70,9 +70,9 @@ export const layout = { seedStale: "Its line corners are kept but marked for re-picking: they were picked for the old region.", calibrationRemoved: - "Its locked calibration is removed. It recalibrates when its vision_processor restarts.", + "Its locked calibration is removed. It recalibrates when its ssl-vision-processor restarts.", remote: "Remote: set its cam_id by hand.", restart: - "vision_processor reads its camera ID and count only at startup. Restart the affected ones after saving.", + "ssl-vision-processor reads its camera ID and count only at startup. Restart the affected ones after saving.", }, }; diff --git a/gui/frontend/src/lib/text/liveField.ts b/gui/frontend/src/lib/text/liveField.ts index 3c81f4d..735a110 100644 --- a/gui/frontend/src/lib/text/liveField.ts +++ b/gui/frontend/src/lib/text/liveField.ts @@ -6,7 +6,7 @@ import { steady } from "./common"; export const liveField = { heading: "Live Field", intro: - "Robots and balls as the vision_processors detect them, unfiltered, and as each autoref's tracker reports them. Autorefs appear as the host hears them on the tracker group.", + "Robots and balls as the ssl-vision-processors detect them, unfiltered, and as each autoref's tracker reports them. Autorefs appear as the host hears them on the tracker group.", waitingForField: "Waiting for the field geometry from the host…", @@ -48,9 +48,9 @@ export const liveField = { rate: "Rate", processing: "Processing", processingHint: - "Capture to send, by the vision_processor's own clock. Age is since the host received the frame.", + "Capture to send, by the ssl-vision-processor's own clock. Age is since the host received the frame.", shown: "Shown", - none: "No vision_processor heard yet.", + none: "No ssl-vision-processor heard yet.", ms: (ms: number): string => `${steady(ms.toFixed(1), 5)} ms`, }, diff --git a/gui/frontend/src/lib/text/network.ts b/gui/frontend/src/lib/text/network.ts index fcc01fb..d67da2f 100644 --- a/gui/frontend/src/lib/text/network.ts +++ b/gui/frontend/src/lib/text/network.ts @@ -7,7 +7,7 @@ export const network = { heading: "Network", // `backticks` show as code. intro: - "Vision and game controller are shared by the host and every vision_processor (vision.yml's `defaults.network`); vision_processors read them only at startup, so restart them after a change. The autoref tracker is only the host's (vision.yml's `tracker`). The host reopens its sockets as soon as a change applies.", + "Vision and game controller are shared by the host and every ssl-vision-processor (vision.yml's `defaults.network`); ssl-vision-processors read them only at startup, so restart them after a change. The autoref tracker is only the host's (vision.yml's `tracker`). The host reopens its sockets as soon as a change applies.", reopening: (address: string): string => `Reopening on ${address}…`, interfaces: { @@ -15,7 +15,7 @@ export const network = { "(skips disconnected and virtual interfaces, and loopback unless it's the only one)", waiting: "Waiting for the host…", scope: - "Only this host's sockets; vision_processors use their system's default route. Broadcast receiving listens on every interface.", + "Only this host's sockets; ssl-vision-processors use their system's default route. Broadcast receiving listens on every interface.", loopbackOff: (iface: string): string => `Multicast is off on \`${iface}\`. No network is in use either, so programs on this machine won't hear each other. To enable it until reboot:`, loopbackFix: (iface: string): string => @@ -72,7 +72,7 @@ export const network = { gcWhat: "referee messages", trackerWhat: "tracker packets", overriding: (cameras: number[]): string => - `${plural(cameras.length, "Camera")} ${cameras.join(", ")} override${cameras.length === 1 ? "s" : ""} these in their own config, so their vision_processor uses different groups than the host.`, + `${plural(cameras.length, "Camera")} ${cameras.join(", ")} override${cameras.length === 1 ? "s" : ""} these in their own config, so their ssl-vision-processor uses different groups than the host.`, }, address: { @@ -88,7 +88,7 @@ export const network = { sameMac: (group: string): string => `Same Ethernet MAC as ${group}: switches can't filter them apart.`, broadcastAll: - "Broadcast: floods the subnet. vision_processor sends it out its default route only.", + "Broadcast: floods the subnet. ssl-vision-processor sends it out its default route only.", broadcastOn: (iface: string): string => `Subnet broadcast on ${iface}: floods the subnet.`, unknownBroadcast: @@ -99,7 +99,7 @@ export const network = { port: { privileged: (start: number, root: boolean): string => - `Below ${String(start)}: binding needs root or CAP_NET_BIND_SERVICE, here and on every vision_processor${root ? " (this host runs as root)" : ""}.`, + `Below ${String(start)}: binding needs root or CAP_NET_BIND_SERVICE, here and on every ssl-vision-processor${root ? " (this host runs as root)" : ""}.`, legacy: "Legacy 2014 format port: old clients get detections but not this geometry.", backup: "Backup (+10) port, for a redundant second system.", diff --git a/gui/frontend/src/lib/text/placeholder.ts b/gui/frontend/src/lib/text/placeholder.ts index 47b2948..d50c5bf 100644 --- a/gui/frontend/src/lib/text/placeholder.ts +++ b/gui/frontend/src/lib/text/placeholder.ts @@ -3,5 +3,5 @@ export const stream = { heading: "Live video", intro: (host: string, camera: number): string => - `${host} / cam ${String(camera)}'s H.264 stream, relayed by the host without re-encoding. vision_processor cycles through its views (raw, then processed) unless \`stream.raw_feed\` is set. For exact pixels, such as picking corners, use the snapshots on the Geometry tab.`, + `${host} / cam ${String(camera)}'s H.264 stream, relayed by the host without re-encoding. ssl-vision-processor cycles through its views (raw, then processed) unless \`stream.raw_feed\` is set. For exact pixels, such as picking corners, use the snapshots on the Geometry tab.`, }; diff --git a/gui/frontend/src/lib/text/snapshots.ts b/gui/frontend/src/lib/text/snapshots.ts index 8db06a5..0a65ec6 100644 --- a/gui/frontend/src/lib/text/snapshots.ts +++ b/gui/frontend/src/lib/text/snapshots.ts @@ -1,5 +1,5 @@ // Debug image cards (SnapshotViews.svelte) on the Color and Geometry pages: -// images vision_processor writes to img/, which the host lists and serves. +// images ssl-vision-processor writes to img/, which the host lists and serves. export interface SnapshotView { // The in img/... diff --git a/gui/frontend/src/lib/text/teamAssignment.ts b/gui/frontend/src/lib/text/teamAssignment.ts index 3a32cf7..1d2b8e7 100644 --- a/gui/frontend/src/lib/text/teamAssignment.ts +++ b/gui/frontend/src/lib/text/teamAssignment.ts @@ -5,7 +5,7 @@ export const teamAssignment = { teams: { title: "Teams", notApplied: - "Shown here only for now: vision_processor still takes the team names from the game controller and looks their heights up in its height table.", + "Shown here only for now: ssl-vision-processor still takes the team names from the game controller and looks their heights up in its height table.", yellow: "Yellow", blue: "Blue", fromGameController: "Derive from game controller", @@ -23,14 +23,14 @@ export const teamAssignment = { noName: "(no name)", height: (mm: number): string => `${String(mm)} mm`, notInTable: "not in the height table", - // Why a team would get vision_processor's default height. + // Why a team would get ssl-vision-processor's default height. issue: { notInTable: - "Not in the height table, so vision_processor uses a default height. Turn off Derive and enter a custom height, then Save.", + "Not in the height table, so ssl-vision-processor uses a default height. Turn off Derive and enter a custom height, then Save.", customMissing: "Custom height not entered, so the default height applies. Enter it, then Save.", noHeight: - "No game controller team and no height set, so vision_processor uses a default height. Turn off Derive and enter a custom height, then Save.", + "No game controller team and no height set, so ssl-vision-processor uses a default height. Turn off Derive and enter a custom height, then Save.", unsaved: "Not saved yet. Save to write it to disk.", }, table: (file: string, fallback: number, max: number): string => diff --git a/gui/frontend/src/lib/text/video.ts b/gui/frontend/src/lib/text/video.ts index d657dc4..9208b05 100644 --- a/gui/frontend/src/lib/text/video.ts +++ b/gui/frontend/src/lib/text/video.ts @@ -10,24 +10,24 @@ export const video = { cantListen: (address: string, problem: string): string => `Can't listen for video on ${address}: ${problem}. Retrying…`, waiting: (address: string): string => - `Waiting for video on ${address}. Is the vision_processor running?`, - // When the host runs this camera's vision_processor itself and knows why + `Waiting for video on ${address}. Is the ssl-vision-processor running?`, + // When the host runs this camera's ssl-vision-processor itself and knows why // there's no video. processExiting: (lastLine: string): string => lastLine - ? `vision_processor keeps exiting: ${lastLine}` - : "vision_processor keeps exiting. Its output is on the Camera page.", + ? `ssl-vision-processor keeps exiting: ${lastLine}` + : "ssl-vision-processor keeps exiting. Its output is on the Camera page.", processHeld: (conflict: string): string => - `vision_processor isn't started: ${conflict}.`, + `ssl-vision-processor isn't started: ${conflict}.`, noCamera: "No camera selected. Choose its driver on the Camera page.", - processStarting: "Waiting for video: vision_processor is starting…", + processStarting: "Waiting for video: ssl-vision-processor is starting…", waitingKeyframe: "Waiting for a keyframe…", - // The rate frames arrive from vision_processor. + // The rate frames arrive from ssl-vision-processor. receivedFps: (fps: number): string => `${steady(fps.toFixed(3), 7)} fps received`, fps: (fps: number): string => `${steady(fps.toFixed(3), 7)} fps`, fpsTitle: - "Frames per second arriving from vision_processor, not the rate shown here.", + "Frames per second arriving from ssl-vision-processor, not the rate shown here.", noMSE: "This browser doesn't support Media Source Extensions.", unsupportedCodec: (codec: string): string => `This browser can't play ${codec} (H.264). On Linux, Chromium and Firefox need the system's FFmpeg libraries; Google Chrome bundles its own.`, diff --git a/gui/frontend/src/lib/text/wizard.ts b/gui/frontend/src/lib/text/wizard.ts index a663783..be5f3c1 100644 --- a/gui/frontend/src/lib/text/wizard.ts +++ b/gui/frontend/src/lib/text/wizard.ts @@ -5,7 +5,7 @@ export const wizard = { start: "Start from a regulation field, or configure a custom one.", // Shown above start on a first run. welcome: - "Welcome. This sets up the field vision_processor measures against. Nothing goes out on the network until you save.", + "Welcome. This sets up the field ssl-vision-processor measures against. Nothing goes out on the network until you save.", markings: "Which markings does this field have?", review: "Review, then apply to put these values live on the field.", // `backticks` show as code. diff --git a/gui/frontend/src/lib/video/VideoPlayer.svelte b/gui/frontend/src/lib/video/VideoPlayer.svelte index 15277b4..235feea 100644 --- a/gui/frontend/src/lib/video/VideoPlayer.svelte +++ b/gui/frontend/src/lib/video/VideoPlayer.svelte @@ -94,7 +94,7 @@ }; }); - // The host's own vision_processor for this camera keeps exiting or isn't + // The host's own ssl-vision-processor for this camera keeps exiting or isn't // started: no video is coming, so no spinner. let stuck = $derived.by(() => { const proc = processFor(cameraId); @@ -112,7 +112,7 @@ (!status || (status.active && (!status.receiving || !format))), ); - // Why there's no video, when the host runs the vision_processor itself. + // Why there's no video, when the host runs the ssl-vision-processor itself. function notReceiving(address: string): string { const proc = processFor(cameraId); if (!proc) return text.waiting(address); diff --git a/gui/frontend/src/lib/video/videoStream.ts b/gui/frontend/src/lib/video/videoStream.ts index 29eeb71..f41421f 100644 --- a/gui/frontend/src/lib/video/videoStream.ts +++ b/gui/frontend/src/lib/video/videoStream.ts @@ -20,7 +20,7 @@ export interface StreamStatus { active: boolean; receiving: boolean; packets: number; - // The rate frames arrive from vision_processor over the last 200 ms, not + // The rate frames arrive from ssl-vision-processor over the last 200 ms, not // what this player shows (keyframes mode shows about one a second). fps: number; source?: string; diff --git a/gui/internal/alerts/alerts.go b/gui/internal/alerts/alerts.go index 9e4ad6b..8de203c 100644 --- a/gui/internal/alerts/alerts.go +++ b/gui/internal/alerts/alerts.go @@ -48,7 +48,7 @@ const ( ) // crashingAfter is how many failed runs in a row make a supervised -// vision_processor's crashes an alert: one can be a slow device, two is a loop. +// ssl-vision-processor's crashes an alert: one can be a slow device, two is a loop. const crashingAfter = 2 // Alert is one problem. @@ -90,7 +90,7 @@ func Codes() []string { return codes } -// Network is what the host's sockets report, and the vision_processors it +// Network is what the host's sockets report, and the ssl-vision-processors it // runs itself. type Network struct { Vision multicast.Status @@ -107,13 +107,13 @@ type Network struct { VideoDuplicates map[int][]multicast.Duplicate // Conflicts are things claimed by more senders than they should be. Conflicts []peers.Conflict - // Processes are the host's own vision_processors (-runCameras). + // Processes are the host's own ssl-vision-processors (-runCameras). Processes []supervisor.Status } // conflictSeverity is how serious each kind of sender conflict is: a second -// calibration or field geometry source changes what every vision_processor -// uses, and two vision_processors announcing one instance name can't be told +// calibration or field geometry source changes what every ssl-vision-processor +// uses, and two ssl-vision-processors announcing one instance name can't be told // apart to configure; two game controllers or video streams only confuse what's shown, in // a lab. On a competition field Collect raises those to errors too: a match // can't run with two game controllers, and setup needs every camera's video. @@ -146,7 +146,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { add(Alert{ ID: "crashing-" + strconv.Itoa(p.CameraID), Code: CodeProcessCrashing, Severity: Error, CameraID: ptr(p.CameraID), Params: map[string]any{"crashes": p.Crashes, "exit": p.LastExit, "lastLine": last}, - Message: fmt.Sprintf("Camera %d's vision_processor keeps exiting (%d times in a row, %s): %s", p.CameraID, p.Crashes, p.LastExit, last), + Message: fmt.Sprintf("Camera %d's ssl-vision-processor keeps exiting (%d times in a row, %s): %s", p.CameraID, p.Crashes, p.LastExit, last), }) } @@ -157,7 +157,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { add(Alert{ ID: "device-" + strconv.Itoa(p.CameraID), Code: CodeDeviceConflict, Severity: Error, CameraID: ptr(p.CameraID), Params: map[string]any{"conflict": p.Conflict}, - Message: fmt.Sprintf("Camera %d's vision_processor isn't started: %s.", p.CameraID, p.Conflict), + Message: fmt.Sprintf("Camera %d's ssl-vision-processor isn't started: %s.", p.CameraID, p.Conflict), }) } @@ -180,7 +180,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { add(Alert{ ID: "no-camera-" + strconv.Itoa(c.CameraID), Code: CodeCameraNotSelected, Severity: severity, CameraID: ptr(c.CameraID), - Message: fmt.Sprintf("Camera %d has no camera driver chosen, so its vision_processor can't run.", c.CameraID), + Message: fmt.Sprintf("Camera %d has no camera driver chosen, so its ssl-vision-processor can't run.", c.CameraID), }) } @@ -273,7 +273,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { case socket.kind == "gc": severity = Error case socket.status.LastHeard == nil && !doc.CompetitionField && !running(net.Processes): - // A lab where no vision_processor has been started yet. + // A lab where no ssl-vision-processor has been started yet. severity = Caution } @@ -313,7 +313,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { add(Alert{ ID: "team-height-" + color, Code: CodeTeamDefaultHeight, Severity: severity, Params: map[string]any{"color": color, "team": team, "issue": issue}, - Message: fmt.Sprintf("The %s team's robots get vision_processor's default height: %s.", color, issueText[issue]), + Message: fmt.Sprintf("The %s team's robots get ssl-vision-processor's default height: %s.", color, issueText[issue]), }) } } @@ -360,7 +360,7 @@ func Collect(doc config.Document, state config.State, net Network) []Alert { return out } -// Height issues: why a color's robots would get vision_processor's default +// Height issues: why a color's robots would get ssl-vision-processor's default // height. const ( IssueNotInTable = "notInTable" // the game controller's team isn't in the table, no choice @@ -376,7 +376,7 @@ var issueText = map[string]string{ IssueUnsaved: "the height choice isn't saved yet", } -// HeightIssue is why color's robots would get vision_processor's default +// HeightIssue is why color's robots would get ssl-vision-processor's default // height, or "" if they have a known one. func HeightIssue(doc config.Document, state config.State, net Network, color string) string { team := teamName(net, color) @@ -495,7 +495,7 @@ func LastLine(output []string) string { return "" } -// running is whether the host is running any vision_processor itself: one +// running is whether the host is running any ssl-vision-processor itself: one // announces itself every second, so silence then is a fault. func running(processes []supervisor.Status) bool { return slices.ContainsFunc(processes, func(p supervisor.Status) bool { return p.State == supervisor.StateRunning }) diff --git a/gui/internal/config/camera.go b/gui/internal/config/camera.go index 795c5e0..1896374 100644 --- a/gui/internal/config/camera.go +++ b/gui/internal/config/camera.go @@ -8,12 +8,12 @@ import ( "gopkg.in/yaml.v3" ) -// CameraDrivers are vision_processor's camera drivers (src/driver). Which +// CameraDrivers are ssl-vision-processor's camera drivers (src/driver). Which // ones a given build has depends on the SDKs it was compiled against. var CameraDrivers = []string{DriverNone, "SPINNAKER", "MVIMPACT", "DC1394", "OPENCV"} // DriverNone is the protocol's "no camera" driver, what a new config starts -// with until someone chooses one. Today's vision_processor exits on it. +// with until someone chooses one. Today's ssl-vision-processor exits on it. const DriverNone = "DUMMY" // cameraBlock is the YAML shape of a camera: block, as @@ -43,8 +43,8 @@ func deviceKey(host string, block any) string { return fmt.Sprintf("%s|%s|%s", host, driver, device) } -// CaptureDevice is the driver and device camera c's vision_processor opens, -// with vision_processor's fallbacks filled in: see captureDevice. DriverNone +// CaptureDevice is the driver and device camera c's ssl-vision-processor opens, +// with ssl-vision-processor's fallbacks filled in: see captureDevice. DriverNone // has no device. func (d Document) CaptureDevice(c Camera) (driver, device string) { driver, device, _ = captureDevice(d.Effective(c)["camera"], settings["camera.driver"].Default.(string)) @@ -96,7 +96,7 @@ func captureDevice(block any, defaultDriver string) (driver, device string, ok b return driver, fmt.Sprintf("id %d", id), true } -// validateCamera checks a camera block for what vision_processor would +// validateCamera checks a camera block for what ssl-vision-processor would // misread rather than reject: an unknown driver is fatal at startup, and any // white_balance string other than OUTDOOR silently means INDOOR. func validateCamera(block any) error { diff --git a/gui/internal/config/color.go b/gui/internal/config/color.go index ad29a97..92c3d66 100644 --- a/gui/internal/config/color.go +++ b/gui/internal/config/color.go @@ -14,7 +14,7 @@ import ( const defaultMinReferenceForce = 0.05 // colorReferenceDefaults mirrors src/Resources.cpp's applyTunables fallbacks -// -- what vision_processor itself uses for a color left unset. +// -- what ssl-vision-processor itself uses for a color left unset. var colorReferenceDefaults = map[string]RGB{ "orange": {192, 128, 64}, "field": {128, 128, 128}, @@ -31,7 +31,7 @@ type RGB struct { B int } -// ColorConfig is a camera's effective color: block, with vision_processor's +// ColorConfig is a camera's effective color: block, with ssl-vision-processor's // own fallbacks filled in for anything unset. MinReferenceForce has no // protocol equivalent: it's a GUI-only floor on ReferenceForce, stored as // min_reference_force in the color block (yaml-cpp ignores unknown keys). @@ -48,7 +48,7 @@ type ColorConfig struct { } // colorBlock is the YAML shape of a color: block. Scalars are pointers so a -// missing key falls back to vision_processor's default rather than Go's zero +// missing key falls back to ssl-vision-processor's default rather than Go's zero // value, which would silently disagree with what the instance runs. type colorBlock struct { ReferenceForce *float64 `yaml:"reference_force"` diff --git a/gui/internal/config/default.go b/gui/internal/config/default.go index 1741045..85b2a2b 100644 --- a/gui/internal/config/default.go +++ b/gui/internal/config/default.go @@ -49,7 +49,7 @@ func Default() (Document, error) { return doc, doc.Validate() } -// AssignLocal readies d for a host that runs every camera's vision_processor: +// AssignLocal readies d for a host that runs every camera's ssl-vision-processor: // a camera in every region, each run on this host from a config file of its // own. func (d *Document) AssignLocal(ownFile string) { diff --git a/gui/internal/config/document.go b/gui/internal/config/document.go index 451dd8c..9d55741 100644 --- a/gui/internal/config/document.go +++ b/gui/internal/config/document.go @@ -1,5 +1,5 @@ // Package config owns vision.yml: the single host-owned file holding the -// field template, shared and per-camera vision_processor settings, and +// field template, shared and per-camera ssl-vision-processor settings, and // explicitly locked camera calibrations. See Store for the live working copy // and its relationship to the file on disk. package config @@ -44,39 +44,39 @@ type Document struct { OptionalFieldLines geometry.OptionalLinesConfig `yaml:"optional_field_lines" json:"optionalFieldLines"` // Models is SSL_GeometryModels in protojson (proto field names). Models map[string]any `yaml:"models,omitempty" json:"models,omitempty"` - // Defaults uses vision_processor's own config.yml layout (camera:, + // Defaults uses ssl-vision-processor's own config.yml layout (camera:, // geometry:, color:, thresholds:, ...) and applies to every camera. Defaults Settings `yaml:"defaults,omitempty" json:"defaults,omitempty"` Layout *Layout `yaml:"layout,omitempty" json:"layout,omitempty"` // Teams overrides robot heights by team. Shown in the GUI only for now: - // vision_processor still looks heights up in bot_heights_file by game + // ssl-vision-processor still looks heights up in bot_heights_file by game // controller team name. Teams *Teams `yaml:"teams,omitempty" json:"teams,omitempty"` // CompetitionField is a match setup, with a game controller, rather than // casual lab use. The GUI keys height choices by team and raises missing - // setup to errors; vision_processor doesn't read it. + // setup to errors; ssl-vision-processor doesn't read it. CompetitionField bool `yaml:"competition_field,omitempty" json:"competitionField,omitempty"` Cameras []Camera `yaml:"cameras" json:"cameras"` // Tracker is the autoref tracker group. The GUI host listens on it for - // the Live Field page; no vision_processor reads it. + // the Live Field page; no ssl-vision-processor reads it. Tracker *Tracker `yaml:"tracker,omitempty" json:"tracker,omitempty"` - // Host is settings for this GUI host alone; no vision_processor reads it. + // Host is settings for this GUI host alone; no ssl-vision-processor reads it. Host *Host `yaml:"host,omitempty" json:"host,omitempty"` } -// Settings is vision_processor's config.yml layout: blocks (camera, +// Settings is ssl-vision-processor's config.yml layout: blocks (camera, // thresholds, color, ...) of keys, as GET /api/schema describes them. type Settings map[string]any // Layout is how the field is split between cameras. type Layout struct { // CameraCount is the number of regions the field is split into - // (vision_processor's geometry.camera_amount). It can exceed the number of + // (ssl-vision-processor's geometry.camera_amount). It can exceed the number of // cameras, leaving some regions uncovered. CameraCount int `yaml:"camera_count" json:"cameraCount"` // HalfField marks a physical field that's half of the one described: // the field is entered as the full field it's half of, and its cameras - // cover half the regions. Only the GUI reads it; vision_processor only + // cover half the regions. Only the GUI reads it; ssl-vision-processor only // ever sees the regions. HalfField bool `yaml:"half_field,omitempty" json:"halfField,omitempty"` } @@ -87,7 +87,7 @@ func (d Document) HalfField() bool { } // Teams overrides robot heights by team. Keyed by the game controller's -// team name, as vision_processor's height table is, so an override follows +// team name, as ssl-vision-processor's height table is, so an override follows // its team through a color switch (the game controller swaps the whole team // record, name included, between colors). type Teams struct { @@ -129,7 +129,7 @@ func (t TeamOverride) validate(prefix string) error { return errs } -// CameraCounts are the supported Layout.CameraCount values. vision_processor +// CameraCounts are the supported Layout.CameraCount values. ssl-vision-processor // accepts any power of 2; the GUI supports up to 4 for now. var CameraCounts = []int{1, 2, 4} @@ -175,14 +175,14 @@ func (d Document) InterfaceSelection() (auto bool, skip []string) { return i.Auto == nil || *i.Auto, i.Skip } -// Camera is one vision_processor instance, keyed by camera_id (its position +// Camera is one ssl-vision-processor instance, keyed by camera_id (its position // on the field), not by which machine runs it. type Camera struct { CameraID int `yaml:"camera_id" json:"cameraId"` Instance string `yaml:"instance,omitempty" json:"instance,omitempty"` // ConfigPath is a host-local config.yml, a file name in the config folder, // to regenerate from this document - // for a vision_processor on the same machine. Empty for remote instances. + // for an ssl-vision-processor on the same machine. Empty for remote instances. ConfigPath string `yaml:"config_path,omitempty" json:"configPath,omitempty"` // Config overrides Defaults, same config.yml layout, deep-merged. Config Settings `yaml:"config,omitempty" json:"config,omitempty"` @@ -213,7 +213,7 @@ type Seed struct { Resolution [2]int `yaml:"resolution,flow" json:"resolution"` LineCorners [][2]int `yaml:"line_corners,flow" json:"lineCorners"` // GoalSideMarker records which corner-picker marker (1-4) was chosen as - // the goal-side corner. vision_processor never reads it. + // the goal-side corner. ssl-vision-processor never reads it. GoalSideMarker int `yaml:"goal_side_marker,omitempty" json:"goalSideMarker,omitempty"` // Slot is the slot the corners were picked for. Moving the camera to // another slot makes them stale. Nil for corners saved before slots were @@ -222,7 +222,7 @@ type Seed struct { } // Calibration is a locked SSL_GeometryCameraCalibration, published in place -// of whatever the camera's vision_processor last sent. +// of whatever the camera's ssl-vision-processor last sent. type Calibration struct { LockedAt time.Time `yaml:"locked_at" json:"lockedAt"` // FieldHash identifies the field dimensions the calibration was solved @@ -719,7 +719,7 @@ func deepCopy(v any) any { } } -// DefaultBotHeightsFile is vision_processor's bot_heights_file when unset +// DefaultBotHeightsFile is ssl-vision-processor's bot_heights_file when unset // (src/Resources.cpp). const DefaultBotHeightsFile = "robot-heights.yml" diff --git a/gui/internal/config/document_test.go b/gui/internal/config/document_test.go index 5e1222c..a1a8fe5 100644 --- a/gui/internal/config/document_test.go +++ b/gui/internal/config/document_test.go @@ -469,7 +469,7 @@ func mergedCamera(c Camera, driver string) map[string]any { } // A file written before new configs named a driver still means SPINNAKER, as -// vision_processor reads it. +// ssl-vision-processor reads it. func TestNoDriverStillMeansSpinnaker(t *testing.T) { if driver, _ := (Document{}).CaptureDevice(Camera{}); driver != "SPINNAKER" { t.Errorf("driver = %q, want SPINNAKER", driver) diff --git a/gui/internal/config/effective.go b/gui/internal/config/effective.go index 92ba767..500ebf0 100644 --- a/gui/internal/config/effective.go +++ b/gui/internal/config/effective.go @@ -10,10 +10,10 @@ const ( SourceCamera = "camera" // the camera's own config SourceDefaults = "defaults" // the document's shared defaults SourceDerived = "derived" // written by the host from the document - SourceFallback = "fallback" // unset: vision_processor's own fallback + SourceFallback = "fallback" // unset: ssl-vision-processor's own fallback ) -// EffectiveSetting is one setting as camera's vision_processor runs it. +// EffectiveSetting is one setting as camera's ssl-vision-processor runs it. type EffectiveSetting struct { Value any `json:"value"` Source string `json:"source" enum:"camera,defaults,derived,fallback"` @@ -29,8 +29,8 @@ type EffectiveConfig struct { Settings map[string]EffectiveSetting `json:"settings"` } -// EffectiveConfig resolves camera id's settings the way its vision_processor -// will: its generated config.yml, then vision_processor's fallbacks for +// EffectiveConfig resolves camera id's settings the way its ssl-vision-processor +// will: its generated config.yml, then ssl-vision-processor's fallbacks for // anything that leaves out. ErrUnknownCamera if there's no such camera. func (d Document) EffectiveConfig(id int) (EffectiveConfig, error) { c := d.camera(id) diff --git a/gui/internal/config/exposure.go b/gui/internal/config/exposure.go index 4f5bd57..91346ac 100644 --- a/gui/internal/config/exposure.go +++ b/gui/internal/config/exposure.go @@ -17,7 +17,7 @@ func microsPerFileUnit(driver string) float64 { return 1000 } -// blockDriver is a camera: block's driver, vision_processor's SPINNAKER when +// blockDriver is a camera: block's driver, ssl-vision-processor's SPINNAKER when // unset. func blockDriver(block map[string]any) string { if d, ok := block["driver"].(string); ok && d != "" { diff --git a/gui/internal/config/layout_test.go b/gui/internal/config/layout_test.go index a26dc34..b261bf0 100644 --- a/gui/internal/config/layout_test.go +++ b/gui/internal/config/layout_test.go @@ -287,7 +287,7 @@ func TestHalfFieldNeedsTwoRegions(t *testing.T) { t.Error("HalfField() = false") } - // GUI-only: never rendered for vision_processor. + // GUI-only: never rendered for ssl-vision-processor. data, err := Render(doc, doc.Cameras[0], "vision.yml") if err != nil { t.Fatal(err) diff --git a/gui/internal/config/names.go b/gui/internal/config/names.go index a0c4fed..bc69e13 100644 --- a/gui/internal/config/names.go +++ b/gui/internal/config/names.go @@ -93,7 +93,7 @@ func (d Document) validateFileNames() error { // AssignConfigPaths gives every camera without a config_path one of its own: // cam.yml, or cam-2.yml and so on when that name is another camera's, // the robot height table, or ownFile, the config file itself. For a host that -// runs every camera's vision_processor, which each need a file to read. +// runs every camera's ssl-vision-processor, which each need a file to read. func (d *Document) AssignConfigPaths(ownFile string) { taken := map[string]bool{d.BotHeightsFile(): true, ownFile: true} diff --git a/gui/internal/config/network.go b/gui/internal/config/network.go index d084b7d..452a47b 100644 --- a/gui/internal/config/network.go +++ b/gui/internal/config/network.go @@ -11,7 +11,7 @@ import ( ) // Network is the vision and game controller multicast addresses, from the -// config.yml-layout network: block. vision_processor reads the same block at +// config.yml-layout network: block. ssl-vision-processor reads the same block at // startup, and the host uses it for its own sockets, so both always agree. type Network struct { VisionIP string @@ -20,7 +20,7 @@ type Network struct { GCPort int } -// The vision_processor's own fallbacks (Resources.cpp) for keys the network +// The ssl-vision-processor's own fallbacks (Resources.cpp) for keys the network // block leaves out. var defaultNetwork = Network{ VisionIP: "224.5.23.2", diff --git a/gui/internal/config/network_test.go b/gui/internal/config/network_test.go index e0cfdd0..74620b3 100644 --- a/gui/internal/config/network_test.go +++ b/gui/internal/config/network_test.go @@ -15,7 +15,7 @@ func TestNetworkFallsBackToVisionProcessorDefaults(t *testing.T) { } if n.VisionAddress() != "224.5.23.2:10006" || n.GCAddress() != "224.5.23.1:10003" { - t.Fatalf("addresses = %s / %s, want the vision_processor defaults", n.VisionAddress(), n.GCAddress()) + t.Fatalf("addresses = %s / %s, want the ssl-vision-processor defaults", n.VisionAddress(), n.GCAddress()) } } diff --git a/gui/internal/config/render.go b/gui/internal/config/render.go index c0a2d30..e9e5378 100644 --- a/gui/internal/config/render.go +++ b/gui/internal/config/render.go @@ -12,17 +12,17 @@ import ( "gopkg.in/yaml.v3" ) -// Render produces the config.yml vision_processor reads for camera c: the +// Render produces the config.yml ssl-vision-processor reads for camera c: the // document's defaults with c's own config merged over, plus the values // derived from the document as a whole (cam_id, camera_amount, and the seed's // line_corners). sourcePath is named in the header comment. // // bot_heights_file is written as a path beside sourcePath, so absolute when -// sourcePath is: vision_processor opens it from its working directory, which +// sourcePath is: ssl-vision-processor opens it from its working directory, which // needn't be the config folder. // -// This is the stand-in transport until vision_processor accepts config over -// the network; vision_processor hot-reloads color/thresholds/tracking/debug +// This is the stand-in transport until ssl-vision-processor accepts config over +// the network; ssl-vision-processor hot-reloads color/thresholds/tracking/debug // from it and needs a restart for everything else. func Render(doc Document, c Camera, sourcePath string) ([]byte, error) { merged := doc.Rendered(c) @@ -118,7 +118,7 @@ func renderAll(doc Document, dir, sourcePath string) map[int]string { } // writeIfChanged writes data to path only if it differs from what's there, -// so an unchanged render doesn't bump the mtime vision_processor polls. +// so an unchanged render doesn't bump the mtime ssl-vision-processor polls. func writeIfChanged(path string, data []byte) (bool, error) { if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, data) { return false, nil @@ -132,7 +132,7 @@ func writeIfChanged(path string, data []byte) (bool, error) { var errReadOnly = errors.New("file is read-only") // atomicWrite replaces path via a temp file and rename, so a reader (the -// watcher, vision_processor's own reload) never sees a half-written file. +// watcher, ssl-vision-processor's own reload) never sees a half-written file. // A rename replaces a file whatever its permissions, so a read-only file is // refused here instead. func atomicWrite(path string, data []byte) error { diff --git a/gui/internal/config/restart.go b/gui/internal/config/restart.go index 841a319..4deb720 100644 --- a/gui/internal/config/restart.go +++ b/gui/internal/config/restart.go @@ -6,9 +6,9 @@ import ( ) // RestartKeys lists the settings that differ between two of a camera's -// rendered config.yml contents (Document.Rendered) and that vision_processor +// rendered config.yml contents (Document.Rendered) and that ssl-vision-processor // reads only at startup: everything but live and host-only settings. Unknown -// keys count, since nothing says vision_processor reloads them. +// keys count, since nothing says ssl-vision-processor reloads them. func RestartKeys(before, after map[string]any) []string { paths := map[string]bool{} diff --git a/gui/internal/config/schema.go b/gui/internal/config/schema.go index eb227e2..258e4c9 100644 --- a/gui/internal/config/schema.go +++ b/gui/internal/config/schema.go @@ -21,17 +21,17 @@ const ( // When a change to a setting takes effect. const ( - ApplyLive = "live" // vision_processor reloads it from config.yml within a second - ApplyRestart = "restart" // vision_processor reads it only at startup + ApplyLive = "live" // ssl-vision-processor reloads it from config.yml within a second + ApplyRestart = "restart" // ssl-vision-processor reads it only at startup ApplyDerived = "derived" // the host writes it from the document; don't set it ApplyHost = "host" // only the GUI host reads it ) -// Setting is one key of vision_processor's config.yml layout, as the +// Setting is one key of ssl-vision-processor's config.yml layout, as the // defaults block and each camera's config hold it. type Setting struct { Type string `json:"type" enum:"integer,number,boolean,string,rgb,whiteBalance,points"` - // Default is vision_processor's own fallback for an unset key, nil when + // Default is ssl-vision-processor's own fallback for an unset key, nil when // there is none (derived) or it depends on other keys (camera.path). Default any `json:"default"` Apply string `json:"apply" enum:"live,restart,derived,host"` @@ -68,7 +68,7 @@ type Driver struct { WhiteBalanceProfiles bool `json:"whiteBalanceProfiles"` } -// Schema describes everything a client needs to edit vision_processor +// Schema describes everything a client needs to edit ssl-vision-processor // settings without reading the C++: served as GET /api/schema. type Schema struct { // Settings by dotted config.yml path, e.g. "thresholds.blobs". @@ -83,7 +83,7 @@ func bound(v float64) *float64 { return &v } func rangeOf(lo, hi, step float64) *Range { return &Range{Min: lo, Max: hi, Step: step} } // settings mirrors src/Resources.cpp and src/driver/cameradriver.cpp: every -// key vision_processor reads, its fallback, and whether applyTunables +// key ssl-vision-processor reads, its fallback, and whether applyTunables // reloads it. Keep it in step with them. var settings = map[string]Setting{ "cam_id": {Type: TypeInteger, Apply: ApplyDerived}, diff --git a/gui/internal/config/status.go b/gui/internal/config/status.go index 0c771ba..d74ba55 100644 --- a/gui/internal/config/status.go +++ b/gui/internal/config/status.go @@ -78,7 +78,7 @@ func cameraStatus(doc Document, c Camera, live *vision.SSL_GeometryCameraCalibra if locked, err := c.Calibration.Proto(); err == nil && liveKnown { lockedRes := [2]int{int(locked.GetPixelImageWidth()), int(locked.GetPixelImageHeight())} if lockedRes[0] > 0 && lockedRes[1] > 0 && !sameAspect(lockedRes, liveRes) { - warn(WarningCalibrationAspectMismatch, "Locked calibration was solved at %dx%d but the camera now reports %dx%d, a different aspect ratio. vision_processor can't rescale across aspect ratios; unlock and recalibrate.", lockedRes[0], lockedRes[1], liveRes[0], liveRes[1]) + warn(WarningCalibrationAspectMismatch, "Locked calibration was solved at %dx%d but the camera now reports %dx%d, a different aspect ratio. ssl-vision-processor can't rescale across aspect ratios; unlock and recalibrate.", lockedRes[0], lockedRes[1], liveRes[0], liveRes[1]) } } } @@ -95,7 +95,7 @@ func cameraStatus(doc Document, c Camera, live *vision.SSL_GeometryCameraCalibra slices.Sort(unknown) for _, path := range unknown { - warn(WarningUnknownSetting, "%s isn't a setting vision_processor reads, so it has no effect. Check the spelling.", path) + warn(WarningUnknownSetting, "%s isn't a setting ssl-vision-processor reads, so it has no effect. Check the spelling.", path) } } diff --git a/gui/internal/config/store.go b/gui/internal/config/store.go index fccaafa..a526754 100644 --- a/gui/internal/config/store.go +++ b/gui/internal/config/store.go @@ -67,7 +67,7 @@ type Store struct { // Options configures a Store. type Options struct { - // LocalCameras is a host that runs every camera's vision_processor + // LocalCameras is a host that runs every camera's ssl-vision-processor // itself: every region gets a camera, each with this host as its instance // and a config_path of its own (Document.AssignLocal), when loaded or // edited. @@ -583,7 +583,7 @@ func (s *Store) LockCalibration(camID int) (int64, error) { } // UnlockCalibration removes camID's locked calibration and stops publishing -// any calibration for it, so its vision_processor calibrates the next time +// any calibration for it, so its ssl-vision-processor calibrates the next time // it starts. func (s *Store) UnlockCalibration(camID int) (int64, error) { rev, err := s.editCamera(camID, func(_ *Document, c *Camera) error { diff --git a/gui/internal/config/stream.go b/gui/internal/config/stream.go index c961f6a..1c46757 100644 --- a/gui/internal/config/stream.go +++ b/gui/internal/config/stream.go @@ -8,15 +8,15 @@ import ( "gopkg.in/yaml.v3" ) -// Stream is where a camera's vision_processor sends its live H.264 video, from -// its config.yml-layout stream: block. vision_processor builds the address +// Stream is where a camera's ssl-vision-processor sends its live H.264 video, from +// its config.yml-layout stream: block. ssl-vision-processor builds the address // as ip_base_prefix + (ip_base_end + cam_id) : port (src/Resources.cpp). type Stream struct { Active bool Address string } -// defaultStream is vision_processor's fallbacks (Resources.cpp) for keys the +// defaultStream is ssl-vision-processor's fallbacks (Resources.cpp) for keys the // stream block leaves out. var defaultStream = struct { prefix string @@ -24,7 +24,7 @@ var defaultStream = struct { }{prefix: "224.5.23.", end: 100, port: 10100} // streamBlock is the YAML shape of a stream: block. Pointers tell a missing -// key (use vision_processor's fallback) from a zero one. +// key (use ssl-vision-processor's fallback) from a zero one. type streamBlock struct { Active *bool `yaml:"active"` IPBasePrefix *string `yaml:"ip_base_prefix"` diff --git a/gui/internal/config/tracker.go b/gui/internal/config/tracker.go index f00a7be..bdd63b4 100644 --- a/gui/internal/config/tracker.go +++ b/gui/internal/config/tracker.go @@ -8,7 +8,7 @@ import ( ) // Tracker is the group autorefs send TrackerWrapperPacket to. Only this host -// listens on it; no vision_processor does, so it lives at the top level +// listens on it; no ssl-vision-processor does, so it lives at the top level // rather than in defaults.network, and is never rendered into a camera's // config.yml. Unset keys take the league's standard group. type Tracker struct { diff --git a/gui/internal/detections/tracker.go b/gui/internal/detections/tracker.go index d46868e..dca4fcc 100644 --- a/gui/internal/detections/tracker.go +++ b/gui/internal/detections/tracker.go @@ -1,4 +1,4 @@ -// Package detections tracks which vision_processors are sending detection +// Package detections tracks which ssl-vision-processors are sending detection // frames: each camera_id heard, from which address, and how often. The Camera // Layout page uses it to show which slots are live and to catch two // processors claiming the same camera_id. diff --git a/gui/internal/discovery/discovery.go b/gui/internal/discovery/discovery.go index eefe46c..1e221f8 100644 --- a/gui/internal/discovery/discovery.go +++ b/gui/internal/discovery/discovery.go @@ -1,4 +1,4 @@ -// Package discovery keeps the table of vision_processor instances heard +// Package discovery keeps the table of ssl-vision-processor instances heard // announcing themselves: the SSL_VPConfig each sends on the vision group about // once a second, keyed by its instance name. package discovery @@ -29,7 +29,7 @@ type Config []byte func (c Config) MarshalJSON() ([]byte, error) { return c, nil } -// Instance is one vision_processor, as it last announced itself. +// Instance is one ssl-vision-processor, as it last announced itself. type Instance struct { Name string `json:"instance"` CameraID uint32 `json:"cameraId"` @@ -79,18 +79,18 @@ func (r *Registry) Record(config *vision.SSL_VPConfig, from *net.UDPAddr, now ti encoded, err := protojson.Marshal(config) if err != nil { - slog.Warn("dropping vision_processor announce", "instance", name, "from", address, "err", err) + slog.Warn("dropping ssl-vision-processor announce", "instance", name, "from", address, "err", err) return } switch { case e == nil: - slog.Info("vision_processor discovered", "instance", name, "cam", config.GetCameraId(), "from", address) + slog.Info("ssl-vision-processor discovered", "instance", name, "cam", config.GetCameraId(), "from", address) case e.address != address: - slog.Info("vision_processor moved", "instance", name, "from", address, "was", e.address) + slog.Info("ssl-vision-processor moved", "instance", name, "from", address, "was", e.address) default: - slog.Info("vision_processor config changed", "instance", name, "cam", config.GetCameraId()) + slog.Info("ssl-vision-processor config changed", "instance", name, "cam", config.GetCameraId()) } r.instances[name] = &entry{config: config, encoded: encoded, address: address, last: now} @@ -105,7 +105,7 @@ func (r *Registry) Instances(now time.Time) []Instance { for name, e := range r.instances { if now.Sub(e.last) > Forget { - slog.Info("vision_processor gone", "instance", name, "from", e.address) + slog.Info("ssl-vision-processor gone", "instance", name, "from", e.address) delete(r.instances, name) continue diff --git a/gui/internal/geometry/calibcheck.go b/gui/internal/geometry/calibcheck.go index ec963b9..e0097b5 100644 --- a/gui/internal/geometry/calibcheck.go +++ b/gui/internal/geometry/calibcheck.go @@ -9,7 +9,7 @@ import ( ) // CheckCalibration reports why calib can't be a real camera's calibration, -// or nil. Publishing one that isn't makes every vision_processor for that +// or nil. Publishing one that isn't makes every ssl-vision-processor for that // camera skip calibrating and use it, so a NaN, a test fixture or another // host's mistake would stop that camera for good. func CheckCalibration(calib *vision.SSL_GeometryCameraCalibration) error { diff --git a/gui/internal/geometry/geometry.go b/gui/internal/geometry/geometry.go index 88fd202..749487e 100644 --- a/gui/internal/geometry/geometry.go +++ b/gui/internal/geometry/geometry.go @@ -251,7 +251,7 @@ func cloneModels(models *vision.SSL_GeometryModels) *vision.SSL_GeometryModels { // Run publishes immediately, then republishes via publish once per // PublishInterval until ctx is cancelled. Publishing before the first wait -// (not after) matters here: real vision_processor instances on the network +// (not after) matters here: real ssl-vision-processor instances on the network // wait to receive the field-geometry template before they can calibrate, so // a restart of this host should hand it to them right away, not after an // extra idle PublishInterval. diff --git a/gui/internal/geometry/geometry_test.go b/gui/internal/geometry/geometry_test.go index 9340e92..38ee193 100644 --- a/gui/internal/geometry/geometry_test.go +++ b/gui/internal/geometry/geometry_test.go @@ -238,7 +238,7 @@ func TestSetLockedRejectsAnIncompleteCalibration(t *testing.T) { } } -// Real vision_processor instances wait for the field-geometry template +// Real ssl-vision-processor instances wait for the field-geometry template // before they can calibrate -- Run must hand it to them immediately on // startup, not only after the first interval elapses. func TestRunPublishesImmediatelyBeforeTheFirstInterval(t *testing.T) { diff --git a/gui/internal/livefield/livefield.go b/gui/internal/livefield/livefield.go index 0284805..d6d3191 100644 --- a/gui/internal/livefield/livefield.go +++ b/gui/internal/livefield/livefield.go @@ -1,5 +1,5 @@ // Package livefield keeps what the Live Field page draws: the latest -// detection frame from each vision_processor and the latest tracked frame +// detection frame from each ssl-vision-processor and the latest tracked frame // from each autoref, with when the host received them and how often they // arrive. Frames are kept as received and encoded as canonical protojson // only when a snapshot asks for them, once per new frame. diff --git a/gui/internal/livefield/livefield_test.go b/gui/internal/livefield/livefield_test.go index db7e532..ef97b6b 100644 --- a/gui/internal/livefield/livefield_test.go +++ b/gui/internal/livefield/livefield_test.go @@ -44,7 +44,7 @@ func TestSnapshotKeepsTheLatestFramePerCameraAndAddress(t *testing.T) { f.RecordDetection(detection(1, 10), vpA, t0) f.RecordDetection(detection(1, 11), vpA, t0.Add(10*time.Millisecond)) f.RecordDetection(detection(0, 5), vpA, t0.Add(20*time.Millisecond)) - // A second vision_processor claiming camera 1 is listed separately. + // A second ssl-vision-processor claiming camera 1 is listed separately. f.RecordDetection(detection(1, 99), vpB, t0.Add(30*time.Millisecond)) s := f.Snapshot(t0.Add(40 * time.Millisecond)) diff --git a/gui/internal/multicast/consumers.go b/gui/internal/multicast/consumers.go index e286b04..f8a738c 100644 --- a/gui/internal/multicast/consumers.go +++ b/gui/internal/multicast/consumers.go @@ -10,7 +10,7 @@ import ( ) // VisionConsumer hands the geometry from every wrapper packet to absorb, each -// detection frame to track, and each vision_processor announce to announce, +// detection frame to track, and each ssl-vision-processor announce to announce, // each with its sender. The host's own looped-back packets are dropped. Only // packets carrying a detection frame or an announce count as heard: those come // from vision processors, and one without a camera only announces. diff --git a/gui/internal/multicast/endpoint_test.go b/gui/internal/multicast/endpoint_test.go index 452dfcd..f74f57d 100644 --- a/gui/internal/multicast/endpoint_test.go +++ b/gui/internal/multicast/endpoint_test.go @@ -283,7 +283,7 @@ func TestVisionConsumerAbsorbsGeometryButCountsOnlyDetections(t *testing.T) { } } -// A vision_processor without a camera sends nothing but its announce, and +// An ssl-vision-processor without a camera sends nothing but its announce, and // still shows the vision group is right. func TestVisionConsumerHandsOnAnnounces(t *testing.T) { var got []string diff --git a/gui/internal/peers/peers_test.go b/gui/internal/peers/peers_test.go index 4b98010..9812e05 100644 --- a/gui/internal/peers/peers_test.go +++ b/gui/internal/peers/peers_test.go @@ -121,7 +121,7 @@ func TestMinCountIgnoresOneOffs(t *testing.T) { w := NewWatch(Options{Kind: KindGeometry, Window: 10 * time.Second, MinCount: 3, WithSelf: true}, testNames()) now := time.Now() - // A vision_processor sending the field back once is not a publisher. + // An ssl-vision-processor sending the field back once is not a publisher. w.Record("field geometry", nil, addr("10.0.0.1:10006"), now) if c := w.Conflicts(now); len(c) != 0 { @@ -173,7 +173,7 @@ func TestDescribe(t *testing.T) { } } -// vision_processor's streamer reopens its socket whenever the streamed view +// ssl-vision-processor's streamer reopens its socket whenever the streamed view // changes size: one sender, on a new port each time. func TestRestartsOnANewPortAreOneSender(t *testing.T) { w := NewWatch(Options{Kind: KindVideo, Window: 3 * time.Second, MinCount: 10, Restarts: true}, testNames()) diff --git a/gui/internal/peers/watch.go b/gui/internal/peers/watch.go index b9fc40a..96d7bbc 100644 --- a/gui/internal/peers/watch.go +++ b/gui/internal/peers/watch.go @@ -11,10 +11,10 @@ import ( // What a Watch watches. const ( - KindCalibration = "calibration" // a camera's calibration, from vision_processors + KindCalibration = "calibration" // a camera's calibration, from ssl-vision-processors KindDetections = "detections" // a camera's detection frames KindGeometry = "geometry" // the field geometry this host publishes - KindInstance = "instance" // a vision_processor's announced instance name + KindInstance = "instance" // an ssl-vision-processor's announced instance name KindReferee = "referee" // game controller referee messages KindVideo = "video" // a camera's RTP stream ) diff --git a/gui/internal/referee/referee.go b/gui/internal/referee/referee.go index 86ee1c6..91dd9e7 100644 --- a/gui/internal/referee/referee.go +++ b/gui/internal/referee/referee.go @@ -1,8 +1,8 @@ // Package referee follows the game controller's referee messages for what // matters to vision: which teams are playing, and so (from the robot height -// table vision_processor also reads) how tall their robots are. +// table ssl-vision-processor also reads) how tall their robots are. // -// vision_processor does the same lookup itself (src/udpsocket.cpp, +// ssl-vision-processor does the same lookup itself (src/udpsocket.cpp, // GCSocket::parse): a team found in the table sets that color's height; a // team that isn't keeps whatever height that color had, which is the table's // mean before any known team has played. This package reports what it can @@ -117,10 +117,10 @@ type State struct { // BlueOnPositiveHalf is whether blue defends the goal at +x, from the // referee's blue_team_on_positive_half; absent when it doesn't say. BlueOnPositiveHalf *bool `json:"blueOnPositiveHalf,omitempty"` - // HeightsFile is the table vision_processor reads (bot_heights_file). + // HeightsFile is the table ssl-vision-processor reads (bot_heights_file). HeightsFile string `json:"heightsFile"` HeightsError string `json:"heightsError,omitempty"` - // MeanHeight is vision_processor's height for a team not in the table, + // MeanHeight is ssl-vision-processor's height for a team not in the table, // until a known team has played; MaxHeight is the tallest in the table, // which it uses for its field extent checks. MeanHeight float64 `json:"meanHeight,omitempty"` @@ -180,7 +180,7 @@ type Match struct { file string } -// SetHeightsFile chooses the height table, vision_processor's +// SetHeightsFile chooses the height table, ssl-vision-processor's // bot_heights_file. func (m *Match) SetHeightsFile(path string) { m.mu.Lock() diff --git a/gui/internal/snapshot/snapshot.go b/gui/internal/snapshot/snapshot.go index 7b132eb..78a5443 100644 --- a/gui/internal/snapshot/snapshot.go +++ b/gui/internal/snapshot/snapshot.go @@ -1,7 +1,7 @@ // Package snapshot serves the debug images the C++ vision processor writes to // disk as ..{jpg,png}, via tmp-then-rename so reads never see a // torn frame. They're in the image directory itself, or in its cam -// folder for a vision_processor the host runs (-runCameras). +// folder for an ssl-vision-processor the host runs (-runCameras). // // This assumes the Go host and the vision processor share a filesystem, which // only holds for a single-host setup; it does not work for a remote instance. @@ -36,7 +36,7 @@ type Entry struct { // camFolder matches a camera's own folder in the image directory. var camFolder = regexp.MustCompile(`^cam\d+$`) -// List is the debug images vision_processor has written to dir (-imgDir) and +// List is the debug images ssl-vision-processor has written to dir (-imgDir) and // its cam folders, one entry per camera and view, sorted. A missing dir // has none. func List(dir string) ([]Entry, error) { diff --git a/gui/internal/supervisor/supervisor.go b/gui/internal/supervisor/supervisor.go index dc0eb3a..195807a 100644 --- a/gui/internal/supervisor/supervisor.go +++ b/gui/internal/supervisor/supervisor.go @@ -1,7 +1,7 @@ -// Package supervisor runs a vision_processor for each local camera (one with +// Package supervisor runs an ssl-vision-processor for each local camera (one with // a config_path) and restarts it when a setting it reads only at startup // changes. Settings it hot-reloads reach it through the regenerated -// config.yml alone. A stand-in until vision_processor accepts config over +// config.yml alone. A stand-in until ssl-vision-processor accepts config over // the network. package supervisor @@ -26,10 +26,10 @@ import ( "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/config" ) -// ErrNotSupervised means no supervised vision_processor runs that camera. -var ErrNotSupervised = errors.New("no supervised vision_processor for this camera") +// ErrNotSupervised means no supervised ssl-vision-processor runs that camera. +var ErrNotSupervised = errors.New("no supervised ssl-vision-processor for this camera") -// ErrHeld means the camera's vision_processor is held back: see +// ErrHeld means the camera's ssl-vision-processor is held back: see // Status.Conflict. var ErrHeld = errors.New("held back: another camera uses its device") @@ -47,7 +47,7 @@ const ( StateNoCamera = "no_camera" // not started: no camera driver chosen ) -// Status is one supervised vision_processor. +// Status is one supervised ssl-vision-processor. type Status struct { CameraID int `json:"cameraId"` ConfigPath string `json:"configPath"` @@ -73,17 +73,17 @@ type Status struct { // Options configures a Supervisor. Zero durations take the defaults. type Options struct { - // Command runs vision_processor; the config path is appended. + // Command runs ssl-vision-processor; the config path is appended. Command []string // ConfigDir is the folder the config_paths are in. Empty means the host's // working directory. ConfigDir string // RunDir holds each camera's working directory, cam, where its - // vision_processor writes debug files, so that no two share one. Empty + // ssl-vision-processor writes debug files, so that no two share one. Empty // means the host's working directory, for every camera. RunDir string // ImgDir holds a folder per camera, cam, linked as img in its - // working directory under RunDir: where vision_processor writes its + // working directory under RunDir: where ssl-vision-processor writes its // snapshots. A folder each, since not every debug file it writes there // is prefixed by camera_id. ImgDir string @@ -100,7 +100,7 @@ type Options struct { // OnChange runs after any status change, without the lock held. OnChange func() // Recalibrate runs, without the lock held, between stopping a camera's - // vision_processor and starting it again after the field changed. It + // ssl-vision-processor and starting it again after the field changed. It // must stop the host publishing any calibration for the camera, or the // new process reuses the one solved against the old field. Recalibrate func(cameraID int) @@ -113,7 +113,7 @@ const FieldKey = "field" // outputLines is how many lines of output Status keeps. const outputLines = 20 -// Supervisor runs one vision_processor per config_path. +// Supervisor runs one ssl-vision-processor per config_path. type Supervisor struct { opts Options @@ -126,7 +126,7 @@ type Supervisor struct { field string } -// proc is one config file's vision_processor. +// proc is one config file's ssl-vision-processor. type proc struct { status Status // noCamera is whether the camera has no driver chosen (config.DriverNone). @@ -252,7 +252,7 @@ func (s *Supervisor) Sync(doc config.Document) { s.notify() } -// Restart restarts the camera's vision_processor now. +// Restart restarts the camera's ssl-vision-processor now. func (s *Supervisor) Restart(cameraID int) error { if s == nil { return ErrNotSupervised @@ -282,7 +282,7 @@ func (s *Supervisor) Restart(cameraID int) error { return ErrNotSupervised } -// Statuses lists every supervised vision_processor by camera_id. Empty for +// Statuses lists every supervised ssl-vision-processor by camera_id. Empty for // a nil Supervisor, which supervises nothing. func (s *Supervisor) Statuses() []Status { if s == nil { @@ -372,7 +372,7 @@ func (s *Supervisor) holdLocked(p *proc) { p.status.Crashes = 0 if p.cancel != nil { - slog.Warn("holding vision_processor back", "cam", p.status.CameraID, "reason", cmp.Or(p.status.Conflict, ErrNoCamera.Error())) + slog.Warn("holding ssl-vision-processor back", "cam", p.status.CameraID, "reason", cmp.Or(p.status.Conflict, ErrNoCamera.Error())) p.cancel() p.cancel = nil } @@ -501,7 +501,7 @@ func (s *Supervisor) start(p *proc) (*exec.Cmd, <-chan error, error) { p.starts++ s.mu.Unlock() - slog.Info("started vision_processor", "cam", id, "config", path, "pid", cmd.Process.Pid) + slog.Info("started ssl-vision-processor", "cam", id, "config", path, "pid", cmd.Process.Pid) s.setState(p, StateRunning, cmd.Process.Pid) return cmd, exited, nil @@ -516,7 +516,7 @@ func (s *Supervisor) stop(p *proc, cmd *exec.Cmd, exited <-chan error) { select { case err = <-exited: case <-time.After(s.opts.StopTimeout): - slog.Warn("vision_processor ignored SIGTERM, killing it", "pid", cmd.Process.Pid) + slog.Warn("ssl-vision-processor ignored SIGTERM, killing it", "pid", cmd.Process.Pid) _ = cmd.Process.Kill() err = <-exited } @@ -551,7 +551,7 @@ func (s *Supervisor) ended(p *proc, how string, crashed bool, ran time.Duration) id, path := p.status.CameraID, p.status.ConfigPath s.mu.Unlock() - slog.Warn("vision_processor exited", "cam", id, "config", path, "how", how, "retryIn", delay) + slog.Warn("ssl-vision-processor exited", "cam", id, "config", path, "how", how, "retryIn", delay) s.setState(p, StateWaiting, 0) return delay @@ -576,7 +576,7 @@ func (s *Supervisor) output(p *proc, level slog.Level, line string) { id := p.status.CameraID s.mu.Unlock() - slog.Log(context.Background(), level, "vision_processor: "+line, "cam", id) + slog.Log(context.Background(), level, "ssl-vision-processor: "+line, "cam", id) } // workDir makes camera id's working directory, RunDir/cam, with img in it diff --git a/gui/internal/supervisor/supervisor_test.go b/gui/internal/supervisor/supervisor_test.go index 0079b20..d2ef270 100644 --- a/gui/internal/supervisor/supervisor_test.go +++ b/gui/internal/supervisor/supervisor_test.go @@ -16,7 +16,7 @@ import ( "github.com/RoboCup-SSL/ssl-vision-processor/gui/internal/config" ) -// TestHelperProcess is the fake vision_processor the tests run: this test +// TestHelperProcess is the fake ssl-vision-processor the tests run: this test // binary again, with the config path last. It logs each start beside the // config and behaves as the config's text says: "crash" exits 1 at once, // "ignore_term" ignores SIGTERM, anything else exits cleanly on SIGTERM. diff --git a/gui/internal/supervisor/sysproc_linux.go b/gui/internal/supervisor/sysproc_linux.go index 9456e1a..27b2e9b 100644 --- a/gui/internal/supervisor/sysproc_linux.go +++ b/gui/internal/supervisor/sysproc_linux.go @@ -2,7 +2,7 @@ package supervisor import "syscall" -// sysProcAttr puts vision_processor in its own process group, so a Ctrl-C +// sysProcAttr puts ssl-vision-processor in its own process group, so a Ctrl-C // in the host's terminal reaches only the host, which then stops it with // SIGTERM; and has the kernel SIGTERM it if the host dies without doing so. func sysProcAttr() *syscall.SysProcAttr { diff --git a/gui/internal/video/assembler.go b/gui/internal/video/assembler.go index fc595f5..c48e1fb 100644 --- a/gui/internal/video/assembler.go +++ b/gui/internal/video/assembler.go @@ -1,4 +1,4 @@ -// Package video bridges a vision_processor's H.264 RTP stream to browsers: +// Package video bridges an ssl-vision-processor's H.264 RTP stream to browsers: // it reassembles frames from the multicast RTP packets, repackages them as // fragmented MP4 without transcoding, and fans the result out to WebSocket // viewers, who play it through Media Source Extensions. @@ -24,7 +24,7 @@ const ( // A lost packet ruins the frame it belongs to, and every frame after it until // the next keyframe, since they're predicted from it. So on a sequence gap it // drops frames until a keyframe arrives rather than passing on a corrupt -// picture. A new SSRC means the encoder restarted (vision_processor does this +// picture. A new SSRC means the encoder restarted (ssl-vision-processor does this // whenever the streamed view changes size), which starts over the same way. // // A packet at or behind the newest one is ignored: it's a copy (the stream diff --git a/gui/internal/video/muxer.go b/gui/internal/video/muxer.go index c1d9e27..c38852c 100644 --- a/gui/internal/video/muxer.go +++ b/gui/internal/video/muxer.go @@ -37,7 +37,7 @@ type output struct { } // muxer packages frames as fragmented MP4, one frame per segment, so a -// segment is ready the moment its frame is. vision_processor stamps frames +// segment is ready the moment its frame is. ssl-vision-processor stamps frames // at a nominal 30 fps whatever rate it really runs at, so timing comes from // arrival time instead. type muxer struct { diff --git a/gui/internal/video/source.go b/gui/internal/video/source.go index d354520..b6ec2e6 100644 --- a/gui/internal/video/source.go +++ b/gui/internal/video/source.go @@ -385,7 +385,7 @@ type Status struct { Active bool `json:"active"` Receiving bool `json:"receiving"` Packets uint64 `json:"packets"` - // FPS is the rate frames arrive from vision_processor, over the last + // FPS is the rate frames arrive from ssl-vision-processor, over the last // fpsWindow, whatever a viewer's mode shows. 0 when nothing arrives. FPS float64 `json:"fps"` Source string `json:"source,omitempty"` diff --git a/gui/packaging/nfpm.yaml b/gui/packaging/nfpm.yaml index 3aa25e8..3f12557 100644 --- a/gui/packaging/nfpm.yaml +++ b/gui/packaging/nfpm.yaml @@ -18,15 +18,15 @@ maintainer: "@MAINTAINER@" homepage: https://github.com/RoboCup-SSL/ssl-vision-processor license: Apache-2.0 description: |- - Browser interface for the RoboCup SSL vision_processor + Browser interface for ssl-vision-processor (RoboCup SSL) Sets up and runs the league's shared vision system: field geometry, camera settings, locked calibrations, live video and the live field. It publishes the field geometry to the rest of the league's software. . The setup questions decide whether it runs as a system service. . - It doesn't include vision_processor, which does the camera processing: that's - the ssl-vision-processor package. + It doesn't include ssl-vision-processor, which does the camera processing: + that's the ssl-vision-processor package. depends: - systemd diff --git a/gui/packaging/release-notes.md b/gui/packaging/release-notes.md index b744dfd..b481346 100644 --- a/gui/packaging/release-notes.md +++ b/gui/packaging/release-notes.md @@ -1,6 +1,6 @@ -This release has two programs, packaged separately: the **SSL Vision Processor GUI**, and **`vision_processor`**, which does the camera processing. Install either or both. +This release has two programs, packaged separately: the **SSL Vision Processor GUI**, and **`ssl-vision-processor`**, which does the camera processing. Install either or both. - `ssl-vision-processor-gui` `.tar.gz`: the GUI with its user guide, for any 64-bit Linux. Start with the [quick start](https://github.com/RoboCup-SSL/ssl-vision-processor/blob/master/gui/README.md#quick-start). - `ssl-vision-processor-gui_*.deb`: the same GUI for Ubuntu, which can also run it as a service. -- `ssl-vision-processor_*~ubuntu_amd64.deb`: `vision_processor` for Ubuntu 24.04 or 26.04 (take your release's), with one service per camera. FOSS camera drivers only: V4L (webcams, capture cards) and FireWire. Without a GPU's OpenCL driver it runs on the CPU, which doesn't work yet on 26.04: there it needs a GPU's driver. See [its packaging notes](https://github.com/RoboCup-SSL/ssl-vision-processor/blob/master/packaging/README.md). +- `ssl-vision-processor_*~ubuntu_amd64.deb`: `ssl-vision-processor` for Ubuntu 24.04 or 26.04 (take your release's), with one service per camera. FOSS camera drivers only: V4L (webcams, capture cards) and FireWire. Without a GPU's OpenCL driver it runs on the CPU, which doesn't work yet on 26.04: there it needs a GPU's driver. See [its packaging notes](https://github.com/RoboCup-SSL/ssl-vision-processor/blob/master/packaging/README.md). - `SHA256SUMS`: check your download with `sha256sum --check --ignore-missing SHA256SUMS`. diff --git a/gui/packaging/ssl-vision-processor-gui.1 b/gui/packaging/ssl-vision-processor-gui.1 index 629d080..6552fc1 100644 --- a/gui/packaging/ssl-vision-processor-gui.1 +++ b/gui/packaging/ssl-vision-processor-gui.1 @@ -2,13 +2,13 @@ .\" TestManPageListsEveryFlag checks. .TH SSL-VISION-PROCESSOR-GUI 1 "" "ssl-vision-processor-gui" "RoboCup SSL" .SH NAME -ssl-vision-processor-gui \- SSL Vision Processor GUI, browser interface for the RoboCup SSL vision_processor +ssl-vision-processor-gui \- SSL Vision Processor GUI, browser interface for ssl-vision-processor (RoboCup SSL) .SH SYNOPSIS .B ssl-vision-processor-gui .RI [ options ] .SH DESCRIPTION .B ssl-vision-processor-gui -sets up and runs vision_processor, the Small Size League's shared vision +sets up and runs ssl-vision-processor, the Small Size League's shared vision system. It holds the field geometry and camera settings, locks in camera calibrations, shows live video and the live field, and publishes the field geometry on the vision multicast group. Open the address it prints in a @@ -52,19 +52,19 @@ or under without it. .TP .BI \-imgDir " dir" -Where vision_processor's debug snapshot images are. Default +Where ssl-vision-processor's debug snapshot images are. Default .I img in the same state folder. .TP .B \-runCameras -Run every camera's vision_processor on this machine, using the -.B vision_processor +Run every camera's ssl-vision-processor on this machine, using the +.B ssl-vision-processor on .BR PATH , and restart it when a setting it reads only at startup changes. Each camera gets a config file, .IR cam.yml , -if it has none. Without it, vision_processors run separately. +if it has none. Without it, ssl-vision-processors run separately. .TP .B \-verbose The same as @@ -156,7 +156,7 @@ in the default locations. .B PATH Where .B \-runCameras -finds vision_processor. +finds ssl-vision-processor. .SH SECURITY The GUI has no login. Anyone who can reach its port can change the running configuration and overwrite files in the config folder, including locked diff --git a/gui/packaging/ssl-vision-processor-gui.service b/gui/packaging/ssl-vision-processor-gui.service index 1e68135..791d5ff 100644 --- a/gui/packaging/ssl-vision-processor-gui.service +++ b/gui/packaging/ssl-vision-processor-gui.service @@ -6,7 +6,7 @@ # This file is replaced on upgrade. To change anything else, use a drop-in that # upgrades keep: sudo systemctl edit ssl-vision-processor-gui # -# Never -runCameras: on a machine set up with packages, each vision_processor +# Never -runCameras: on a machine set up with packages, each ssl-vision-processor # runs as its own service. [Unit] diff --git a/gui/scripts/release-check.sh b/gui/scripts/release-check.sh index 1195eb5..ccf4689 100755 --- a/gui/scripts/release-check.sh +++ b/gui/scripts/release-check.sh @@ -2,7 +2,7 @@ # # What a new user does: run the release binary with no arguments on a machine # that has nothing else of ours, and check it works. Then the same with -# -runCameras and a stand-in vision_processor. A first run publishes nothing +# -runCameras and a stand-in ssl-vision-processor. A first run publishes nothing # on the network, so this is safe to run on any network. # # Usage: scripts/release-check.sh @@ -105,18 +105,18 @@ kill "$host_pid" wait "$host_pid" || fail "the host didn't exit cleanly on SIGTERM" host_pid="" -# -runCameras finds vision_processor on PATH, and won't start without it. +# -runCameras finds ssl-vision-processor on PATH, and won't start without it. if (run "$work/no-vp" -runCameras -address "127.0.0.1:$port") >"$work/no-vp.log" 2>&1; then - fail "-runCameras without vision_processor on PATH exited 0" + fail "-runCameras without ssl-vision-processor on PATH exited 0" fi -grep -q 'vision_processor' "$work/no-vp.log" || fail "-runCameras without vision_processor didn't say why: $(cat "$work/no-vp.log")" +grep -q 'ssl-vision-processor' "$work/no-vp.log" || fail "-runCameras without ssl-vision-processor didn't say why: $(cat "$work/no-vp.log")" -# A stand-in vision_processor: it records its arguments, writes a snapshot and +# A stand-in ssl-vision-processor: it records its arguments, writes a snapshot and # a debug dump as the real one does, relative to its working directory, and # runs until SIGTERM. fakebin="$work/bin" mkdir -p "$fakebin" -cat >"$fakebin/vision_processor" <<'FAKE' +cat >"$fakebin/ssl-vision-processor" <<'FAKE' #!/bin/sh echo "$@" >args : >img/0.raw.jpg @@ -124,7 +124,7 @@ echo "$@" >args trap 'exit 0' TERM while :; do sleep 0.1; done FAKE -chmod +x "$fakebin/vision_processor" +chmod +x "$fakebin/ssl-vision-processor" home="$work/local" config="$home/.config/rcssl/vision-processor-gui" @@ -137,12 +137,12 @@ wait_healthy "$work/local.log" grep -q '^ *config_path: cam0.yml$' "$config/vision.yml" || fail "camera 0 has no config_path under -runCameras" grep -qF "bot_heights_file: $config/robot-heights.yml" "$config/cam0.yml" || fail "cam0.yml doesn't name the height table by its full path" -grep -qF "$fakebin/vision_processor" "$work/local.log" || fail "startup didn't print which vision_processor it runs" +grep -qF "$fakebin/ssl-vision-processor" "$work/local.log" || fail "startup didn't print which ssl-vision-processor it runs" # A new config has no camera selected: nothing runs until a driver is chosen. curl -sf "http://127.0.0.1:$port/api/processes" | grep -q '"state":"no_camera"' || fail "a new config's camera isn't waiting for a driver" -[ ! -e "$state/run/cam0/args" ] || fail "vision_processor ran with no camera selected" +[ ! -e "$state/run/cam0/args" ] || fail "ssl-vision-processor ran with no camera selected" etag=$(curl -sfI -X GET "http://127.0.0.1:$port/api/config" | tr -d '\r' | sed -n 's/^[Ee][Tt]ag: //p') curl -sf -o /dev/null -X PATCH -H "If-Match: $etag" -H 'Content-Type: application/merge-patch+json' \ @@ -154,7 +154,7 @@ for _ in $(seq 1 100); do sleep 0.1 done [ "$(cat "$state/run/cam0/args" 2>/dev/null)" = "$config/cam0.yml" ] || - fail "vision_processor wasn't run with cam0.yml's full path: $(cat "$state/run/cam0/args" 2>/dev/null)" + fail "ssl-vision-processor wasn't run with cam0.yml's full path: $(cat "$state/run/cam0/args" 2>/dev/null)" [ -e "$state/img/cam0/0.raw.jpg" ] || fail "the snapshot didn't reach camera 0's image folder" [ -e "$state/run/cam0/.flat.1.png" ] || fail "the debug dump isn't in camera 0's own directory" [ -z "$(ls -A "$config" | grep -v '\.yml$')" ] || fail "something besides config files landed in the config folder: $(ls -A "$config")" diff --git a/packaging/README.md b/packaging/README.md index 986baa3..466727c 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -1,9 +1,9 @@ -# vision_processor's Debian package +# ssl-vision-processor's Debian package -`ssl-vision-processor` packages `vision_processor` for Ubuntu LTS releases, with one systemd service per camera. It's +`ssl-vision-processor` packages `ssl-vision-processor` for Ubuntu LTS releases, with one systemd service per camera. It's independent of the GUI's package (`gui/packaging/`): neither depends on the other, they share no files, and each installs alone. The one thing they share is the `rcssl` group, which both create (idempotently, via sysusers). The -GUI's `-runCameras` uses whichever `vision_processor` is on `PATH`, this package's or a source build. +GUI's `-runCameras` uses whichever `ssl-vision-processor` is on `PATH`, this package's or a source build. ## Building @@ -20,7 +20,7 @@ mvIMPACT can't be redistributed this way; a restricted release is a separate, la ### Why Docker -`vision_processor` links against shared libraries whose versions differ by release (OpenCV is `406` on 24.04 and `410` on +`ssl-vision-processor` links against shared libraries whose versions differ by release (OpenCV is `406` on 24.04 and `410` on 26.04; FFmpeg 6 and 8), so a package only installs on the release it was built on. The [`Dockerfile`](Dockerfile) is that build machine: a stock `ubuntu:` with the release's `-dev` packages and the packaging tools. Nothing from it ships. It's not nix: an Ubuntu package has to be built against Ubuntu's libraries. @@ -48,21 +48,21 @@ built differently. The maintainer scripts, units and `ssl-vision-processor-camer ## What it installs -| File in `packaging/` | Installed as | -| --------------------------------------- | ------------------------------------------------------------------------------------ | -| (built) | `/usr/bin/vision_processor` | -| `ssl-vision-processor-cameras` | `/usr/bin/`: sets up cameras, system or `--user`. The setup logic lives here | -| `ssl-vision-processor@.service` | The system service template, one instance per camera ID, as `rcssl-vp`, hardened | -| `ssl-vision-processor@.user.service` | The same as a user service template | -| `configure-service` | `/usr/lib/ssl-vision-processor/`: applies the setup answers, through the command | -| `debian/templates`, `debian/config` | The two debconf questions: run cameras as services, and which camera IDs | -| `debian/postinst`, `prerm`, `postrm` | Users, udev, then the answers or an upgrade's restart; stop on remove; purge | -| `sysusers.conf` | The `rcssl` group and the `rcssl-vp` user | -| `udev/70-ssl-vision-processor-*.rules` | One file per camera family: V4L and IIDC FireWire devices for the `video` group | -| `default` | `/etc/default/ssl-vision-processor` (conffile): environment for every camera | -| `vision_processor.1`, `ssl-vision-processor-cameras.1` | The man pages | -| `changelog`, `copyright` | The Debian changelog (one entry, pointing at the releases) and licenses | -| `deb-version.sh` | The version, from git; the same scheme as the GUI's, plus `~ubuntu` | +| File in `packaging/` | Installed as | +| ---------------------------------------------------------- | -------------------------------------------------------------------------------- | +| (built) | `/usr/bin/ssl-vision-processor` | +| `ssl-vision-processor-cameras` | `/usr/bin/`: sets up cameras, system or `--user`. The setup logic lives here | +| `ssl-vision-processor@.service` | The system service template, one instance per camera ID, as `rcssl-vp`, hardened | +| `ssl-vision-processor@.user.service` | The same as a user service template | +| `configure-service` | `/usr/lib/ssl-vision-processor/`: applies the setup answers, through the command | +| `debian/templates`, `debian/config` | The two debconf questions: run cameras as services, and which camera IDs | +| `debian/postinst`, `prerm`, `postrm` | Users, udev, then the answers or an upgrade's restart; stop on remove; purge | +| `sysusers.conf` | The `rcssl` group and the `rcssl-vp` user | +| `udev/70-ssl-vision-processor-*.rules` | One file per camera family: V4L and IIDC FireWire devices for the `video` group | +| `default` | `/etc/default/ssl-vision-processor` (conffile): environment for every camera | +| `ssl-vision-processor.1`, `ssl-vision-processor-cameras.1` | The man pages | +| `changelog`, `copyright` | The Debian changelog (one entry, pointing at the releases) and licenses | +| `deb-version.sh` | The version, from git; the same scheme as the GUI's, plus `~ubuntu` | Each system camera `N` is configured in `/etc/rcssl/vision-processor/camN.yml`, works in `/var/lib/rcssl/vision-processor/camN` (its debug images go to `img/` there) and caches OpenCL kernels in @@ -100,13 +100,13 @@ Rusticl also needs `RUSTICL_ENABLE=radeonsi` in `/etc/default/ssl-vision-process The CPU fallback doesn't work everywhere yet, so those machines need a GPU's OpenCL driver: -| Release | PoCL | CPU fallback | -| ------- | ---- | ---------------------------------------------------------------------------------------------------- | -| 24.04 | 5.0 | Works | -| 26.04 | 6.0 | Doesn't work: it refuses one of vision_processor's image formats (`Image creation error: -59`) | +| Release | PoCL | CPU fallback | +| ------- | ---- | -------------------------------------------------------------------------------------------------- | +| 24.04 | 5.0 | Works | +| 26.04 | 6.0 | Doesn't work: it refuses one of ssl-vision-processor's image formats (`Image creation error: -59`) | On 26.04 the warning at install says so when there's no GPU driver. Mesa's software Rusticl -(`mesa-opencl-icd` with `RUSTICL_ENABLE=llvmpipe`) does run vision_processor there, and `deb-check.sh` uses it to stand +(`mesa-opencl-icd` with `RUSTICL_ENABLE=llvmpipe`) does run ssl-vision-processor there, and `deb-check.sh` uses it to stand in for a GPU; it isn't the package's default. Ubuntu 22.04 isn't built. Its PoCL (1.8, LLVM 13) fails on CPUs newer than its LLVM, such as AMD Zen 4 and 5 diff --git a/packaging/build-in-container.sh b/packaging/build-in-container.sh index 770f1f6..3d45784 100755 --- a/packaging/build-in-container.sh +++ b/packaging/build-in-container.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # -# Runs in the build container, from build-deb.sh: compiles vision_processor +# Runs in the build container, from build-deb.sh: compiles ssl-vision-processor # against this release's libraries, packages it, and checks the package with # lintian. /src is the checkout, read-only; the .deb goes to /out. @@ -21,18 +21,18 @@ tar -C /src -cf - CMakeLists.txt cmake kernel src proto tools | tar -C "$work" - cmake -S "$work" -B "$work/build" -DCMAKE_BUILD_TYPE=Release -DTOOLCHAIN_CHECK=OFF \ -DNATIVE_ARCH=OFF -DCMAKE_CXX_FLAGS="-march=$baseline" \ -DWITH_SPINNAKER=OFF -DWITH_MVIMPACT=OFF -DWITH_DC1394=ON >/dev/null -if ! cmake --build "$work/build" --target vision_processor -j"$(nproc)" >"$work/build.log" 2>&1; then +if ! cmake --build "$work/build" --target ssl-vision-processor -j"$(nproc)" >"$work/build.log" 2>&1; then cat "$work/build.log" >&2 exit 1 fi -install -m 0755 "$work/build/vision_processor" "$stage/vision_processor" -strip --strip-unneeded --remove-section=.comment "$stage/vision_processor" -if readelf -lW "$stage/vision_processor" | grep -q 'GNU_STACK.*RWE'; then +install -m 0755 "$work/build/ssl-vision-processor" "$stage/ssl-vision-processor" +strip --strip-unneeded --remove-section=.comment "$stage/ssl-vision-processor" +if readelf -lW "$stage/ssl-vision-processor" | grep -q 'GNU_STACK.*RWE'; then echo "build-in-container: the binary has an executable stack" >&2 exit 1 fi -readelf -d "$stage/vision_processor" | grep -q 'libdc1394' || { +readelf -d "$stage/ssl-vision-processor" | grep -q 'libdc1394' || { echo "build-in-container: built without FireWire (DC1394) support" >&2 exit 1 } @@ -49,7 +49,7 @@ fill() { } fill /src/packaging/changelog | gzip -9n >"$stage/changelog.gz" -for page in vision_processor ssl-vision-processor-cameras; do +for page in ssl-vision-processor ssl-vision-processor-cameras; do gzip -9n <"/src/packaging/$page.1" >"$stage/$page.1.gz" done @@ -58,8 +58,8 @@ done # a debian/control, and the binary in the package's folder. mkdir -p "$work/shlibs/debian/ssl-vision-processor/usr/bin" printf 'Source: ssl-vision-processor\n\nPackage: ssl-vision-processor\nArchitecture: any\n' >"$work/shlibs/debian/control" -cp "$stage/vision_processor" "$work/shlibs/debian/ssl-vision-processor/usr/bin/" -shlibs=$(cd "$work/shlibs" && dpkg-shlibdeps -O debian/ssl-vision-processor/usr/bin/vision_processor) +cp "$stage/ssl-vision-processor" "$work/shlibs/debian/ssl-vision-processor/usr/bin/" +shlibs=$(cd "$work/shlibs" && dpkg-shlibdeps -O debian/ssl-vision-processor/usr/bin/ssl-vision-processor) shlibs=${shlibs#shlibs:Depends=} printf '%s\n' "$shlibs" | sed 's/, /\n/g' | sed 's/^\(.*\)$/ - "\1"/' >"$work/shlibs.yaml" diff --git a/packaging/copyright b/packaging/copyright index 67485c5..0b8539f 100644 --- a/packaging/copyright +++ b/packaging/copyright @@ -1,7 +1,7 @@ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: ssl-vision-processor Source: https://github.com/RoboCup-SSL/ssl-vision-processor -Comment: vision_processor links against the distribution's own libraries +Comment: ssl-vision-processor links against the distribution's own libraries (OpenCV, FFmpeg, protobuf, yaml-cpp, libdc1394, the OpenCL loader), which their packages license. It bundles none. diff --git a/packaging/deb-check.sh b/packaging/deb-check.sh index c5e82fc..184a58a 100755 --- a/packaging/deb-check.sh +++ b/packaging/deb-check.sh @@ -25,7 +25,7 @@ unit() { echo "$package@$1.service" } -# wait_using_device waits for camera $1's vision_processor to set up OpenCL. +# wait_using_device waits for camera $1's ssl-vision-processor to set up OpenCL. wait_using_device() { for _ in $(seq 1 600); do if journalctl -u "$(unit "$1")" --no-pager -o cat 2>/dev/null | grep -q 'Using device:'; then @@ -56,12 +56,12 @@ reconfigure() { [ -d /run/systemd/system ] || fail "needs systemd running: use deb-check-container.sh" -# A test video, readable by the service user. vision_processor reads a file as +# A test video, readable by the service user. ssl-vision-processor reads a file as # fast as it can and exits at its end: half an hour of video lasts a minute or # so, long enough for each check. ffmpeg -loglevel error -y -f lavfi -i testsrc=size=640x480:rate=30 -t 1800 -preset ultrafast -pix_fmt yuv420p "$video" -# Ubuntu 26.04's PoCL can't run vision_processor (packaging/README.md): Mesa's +# Ubuntu 26.04's PoCL can't run ssl-vision-processor (packaging/README.md): Mesa's # software Rusticl stands in for a GPU's driver there. opencl_env="" if [ "$(. /etc/os-release && echo "$VERSION_ID")" = 26.04 ]; then @@ -71,8 +71,8 @@ fi # A non-interactive install takes the defaults: no camera services. DEBIAN_FRONTEND=noninteractive apt-get install -y "$deb" >/dev/null -if ldd /usr/bin/vision_processor | grep 'not found'; then - fail "vision_processor is missing libraries" +if ldd /usr/bin/ssl-vision-processor | grep 'not found'; then + fail "ssl-vision-processor is missing libraries" fi id -nG rcssl-vp | tr ' ' '\n' | grep -qx rcssl || fail "rcssl-vp isn't in the rcssl group" [ -z "$($helper list | tail -n +2)" ] || fail "a default install set up cameras" @@ -192,7 +192,7 @@ as_user $helper --user remove 5 # Remove stops every camera and keeps their configuration. DEBIAN_FRONTEND=noninteractive apt-get remove -y "$package" >/dev/null ! systemctl --quiet is-active "$(unit 3)" || fail "remove left camera 3 running" -! command -v vision_processor >/dev/null || fail "remove left the binary" +! command -v ssl-vision-processor >/dev/null || fail "remove left the binary" [ -f $conf/cam3.yml ] || fail "remove deleted cam3.yml" # Purge removes what the package and its command made for system cameras, and diff --git a/packaging/debian/postinst b/packaging/debian/postinst index 26a9e12..50fade0 100755 --- a/packaging/debian/postinst +++ b/packaging/debian/postinst @@ -49,7 +49,7 @@ configure | abort-upgrade | abort-deconfigure | abort-remove) fi # Says which OpenCL driver a GPU here is missing, if any: without one, - # vision_processor runs on the CPU (PoCL), much slower. + # ssl-vision-processor runs on the CPU (PoCL), much slower. ssl-vision-processor-cameras opencl --hint || true ;; esac diff --git a/packaging/debian/templates b/packaging/debian/templates index 9f60512..d824949 100644 --- a/packaging/debian/templates +++ b/packaging/debian/templates @@ -5,7 +5,7 @@ Choices: Don't run cameras as services, Start them at boot, Start them at boot a Default: none Description: Run cameras on this machine as system services? Each camera gets its own service, ssl-vision-processor@, which runs - vision_processor as the rcssl-vp user. Its configuration is + ssl-vision-processor as the rcssl-vp user. Its configuration is /etc/rcssl/vision-processor/cam.yml. . Otherwise, run cameras as your own user services diff --git a/packaging/default b/packaging/default index aa873e5..32ea76e 100644 --- a/packaging/default +++ b/packaging/default @@ -1,8 +1,8 @@ -# Environment for every vision_processor system service (ssl-vision-processor@N). +# Environment for every ssl-vision-processor system service (ssl-vision-processor@N). # Restart the cameras after editing: # sudo systemctl restart 'ssl-vision-processor@*' # -# vision_processor takes the first OpenCL GPU it finds, on any platform, and +# ssl-vision-processor takes the first OpenCL GPU it finds, on any platform, and # otherwise any device, such as PoCL on the CPU. ssl-vision-processor-cameras # opencl shows what's installed and what's missing. # diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml index 22d8c1f..81820b2 100644 --- a/packaging/nfpm.yaml +++ b/packaging/nfpm.yaml @@ -1,4 +1,4 @@ -# vision_processor's .deb, built by nfpm (pinned in this folder's go.mod) inside +# ssl-vision-processor's .deb, built by nfpm (pinned in this folder's go.mod) inside # an Ubuntu build container: packaging/build-deb.sh. build-in-container.sh # fills in the @...@ values, since nfpm only expands the environment in a few # fields, and replaces the @SHLIBS@ line with the libraries the binary links @@ -20,7 +20,7 @@ homepage: https://github.com/RoboCup-SSL/ssl-vision-processor license: Apache-2.0 description: |- SSL Vision Processor, the RoboCup SSL's camera processing - vision_processor finds the robots and the ball in one camera's picture and + ssl-vision-processor finds the robots and the ball in one camera's picture and publishes their positions, and a debug video stream, over multicast. It replaces ssl-vision's processing. . @@ -42,8 +42,8 @@ depends: - debconf (>= 0.5) | debconf-2.0 contents: - - src: "@STAGE@/vision_processor" - dst: /usr/bin/vision_processor + - src: "@STAGE@/ssl-vision-processor" + dst: /usr/bin/ssl-vision-processor file_info: mode: 0755 - src: ssl-vision-processor-cameras @@ -113,8 +113,8 @@ contents: dst: /usr/share/doc/ssl-vision-processor/examples/config-minimal.yml file_info: mode: 0644 - - src: "@STAGE@/vision_processor.1.gz" - dst: /usr/share/man/man1/vision_processor.1.gz + - src: "@STAGE@/ssl-vision-processor.1.gz" + dst: /usr/share/man/man1/ssl-vision-processor.1.gz file_info: mode: 0644 - src: "@STAGE@/ssl-vision-processor-cameras.1.gz" diff --git a/packaging/ssl-vision-processor-cameras b/packaging/ssl-vision-processor-cameras index be5c423..f725fe9 100755 --- a/packaging/ssl-vision-processor-cameras +++ b/packaging/ssl-vision-processor-cameras @@ -1,5 +1,5 @@ #!/bin/sh -# Sets up which cameras this machine runs, each as its own vision_processor +# Sets up which cameras this machine runs, each as its own ssl-vision-processor # service: a system service (ssl-vision-processor@N, as rcssl-vp) or, with # --user, your own user service. The package's setup questions (sudo # dpkg-reconfigure ssl-vision-processor) run this too. See @@ -172,7 +172,7 @@ write_config() { # # Every key, with its default, is in # /usr/share/doc/ssl-vision-processor/examples/config.yml. Until -# vision_processor takes its configuration over the network, the rest of the +# ssl-vision-processor takes its configuration over the network, the rest of the # camera's setup goes here too: geometry, colors, thresholds. cam_id: $1 @@ -379,7 +379,7 @@ cmd_devices() { done $found || echo " none" - echo "FireWire cameras (DC1394), counted in GUID order as vision_processor does:" + echo "FireWire cameras (DC1394), counted in GUID order as ssl-vision-processor does:" n=0 for guid_dev in $(for d in /sys/bus/firewire/devices/fw*; do [ -e "$d/units" ] || continue @@ -441,7 +441,7 @@ opencl_advice() { esac done - # Ubuntu 26.04's PoCL (6.0) can't run vision_processor yet: it refuses one + # Ubuntu 26.04's PoCL (6.0) can't run ssl-vision-processor yet: it refuses one # of its image formats. Without another driver it fails at startup. if [ "$(. /etc/os-release 2>/dev/null && echo "${VERSION_ID:-}")" = 26.04 ]; then other=false @@ -449,7 +449,7 @@ opencl_advice() { [ -e "$icd" ] || continue [ "${icd##*/}" = pocl.icd ] || other=true done - $other || echo "On Ubuntu 26.04, vision_processor needs a GPU's OpenCL driver: the CPU fallback (PoCL) doesn't work with it yet" + $other || echo "On Ubuntu 26.04, ssl-vision-processor needs a GPU's OpenCL driver: the CPU fallback (PoCL) doesn't work with it yet" fi } @@ -483,7 +483,7 @@ cmd_opencl() { echo " none" fi echo - echo "vision_processor takes the first OpenCL GPU, and otherwise any device:" + echo "ssl-vision-processor takes the first OpenCL GPU, and otherwise any device:" echo "PoCL (pocl.icd) runs on the CPU, which works but is much slower. Its" echo "log's \"Using device:\" line says which it took." if [ -n "$advice" ]; then diff --git a/packaging/ssl-vision-processor-cameras.1 b/packaging/ssl-vision-processor-cameras.1 index 46b43a3..f546749 100644 --- a/packaging/ssl-vision-processor-cameras.1 +++ b/packaging/ssl-vision-processor-cameras.1 @@ -34,7 +34,7 @@ ssl-vision-processor-cameras \- set up the cameras this machine runs .B ssl-vision-processor-cameras opencl .SH DESCRIPTION Each camera runs as its own -.BR vision_processor (1) +.BR ssl-vision-processor (1) service. Without .BR \-\-user , these are system services, @@ -124,7 +124,7 @@ The cameras plugged in now, as sources for .TP .B opencl The GPUs and OpenCL drivers installed, and the driver package a GPU is -missing. Without a GPU's driver, vision_processor runs on the CPU (PoCL), +missing. Without a GPU's driver, ssl-vision-processor runs on the CPU (PoCL), much slower. .SH EXAMPLES .nf @@ -141,6 +141,6 @@ Environment for every system camera service, such as OpenCL settings. .I ~/.config/rcssl/vision-processor/environment The same for your user services. .SH SEE ALSO -.BR vision_processor (1), +.BR ssl-vision-processor (1), .BR systemctl (1), .BR journalctl (1) diff --git a/packaging/vision_processor.1 b/packaging/ssl-vision-processor.1 similarity index 87% rename from packaging/vision_processor.1 rename to packaging/ssl-vision-processor.1 index 62c431b..c026438 100644 --- a/packaging/vision_processor.1 +++ b/packaging/ssl-vision-processor.1 @@ -1,12 +1,12 @@ -.\" vision_processor's man page, installed by the ssl-vision-processor package. -.TH VISION_PROCESSOR 1 "" "ssl-vision-processor" "RoboCup SSL" +.\" ssl-vision-processor's man page, installed by the ssl-vision-processor package. +.TH SSL-VISION-PROCESSOR 1 "" "ssl-vision-processor" "RoboCup SSL" .SH NAME -vision_processor \- RoboCup SSL camera processing for one camera +ssl-vision-processor \- RoboCup SSL camera processing for one camera .SH SYNOPSIS -.B vision_processor +.B ssl-vision-processor .RI [ config.yml ] .SH DESCRIPTION -.B vision_processor +.B ssl-vision-processor reads one camera, finds the robots and the ball in its picture, and publishes their positions over multicast as SSL vision packets, with a debug video stream. Run one per camera. @@ -38,7 +38,7 @@ or Its log: .BR "journalctl -u ssl-vision-processor@N" . .SH OPENCL -.B vision_processor +.B ssl-vision-processor needs an OpenCL driver. It takes the first GPU it finds, on any platform, and otherwise any device, such as PoCL on the CPU, which works but is much slower. Its log says which: the diff --git a/packaging/ssl-vision-processor@.service b/packaging/ssl-vision-processor@.service index 46368e7..cf1e9c9 100644 --- a/packaging/ssl-vision-processor@.service +++ b/packaging/ssl-vision-processor@.service @@ -1,4 +1,4 @@ -# One vision_processor as a system service, for camera %i (0 to 7, the league's +# One ssl-vision-processor as a system service, for camera %i (0 to 7, the league's # camera IDs): systemctl enable --now ssl-vision-processor@2 runs camera 2, # configured in /etc/rcssl/vision-processor/cam2.yml. Set cameras up with # ssl-vision-processor-cameras, or the package's setup questions: sudo @@ -15,10 +15,10 @@ [Unit] Description=SSL Vision Processor, camera %i (RoboCup SSL) -Documentation=man:vision_processor(1) man:ssl-vision-processor-cameras(1) +Documentation=man:ssl-vision-processor(1) man:ssl-vision-processor-cameras(1) Wants=network-online.target After=network-online.target -# Fails with a clear status, not vision_processor's "bad file". +# Fails with a clear status, not ssl-vision-processor's "bad file". AssertPathExists=%E/rcssl/vision-processor/cam%i.yml [Service] @@ -30,10 +30,10 @@ SupplementaryGroups=video render EnvironmentFile=-/etc/default/ssl-vision-processor # A camera without a source yet is skipped, not started to fail and restart # again and again. It starts once ssl-vision-processor-cameras add gives it -# one. (Until vision_processor can wait for one itself.) +# one. (Until ssl-vision-processor can wait for one itself.) ExecCondition=/usr/bin/ssl-vision-processor-cameras ready %i -ExecStart=/usr/bin/vision_processor %E/rcssl/vision-processor/cam%i.yml -# vision_processor writes its debug images to img/ in its working folder: one +ExecStart=/usr/bin/ssl-vision-processor %E/rcssl/vision-processor/cam%i.yml +# ssl-vision-processor writes its debug images to img/ in its working folder: one # folder per camera. StateDirectory=rcssl/vision-processor/cam%i rcssl/vision-processor/cam%i/img StateDirectoryMode=0750 diff --git a/packaging/ssl-vision-processor@.user.service b/packaging/ssl-vision-processor@.user.service index 334ac5e..51bc8d8 100644 --- a/packaging/ssl-vision-processor@.user.service +++ b/packaging/ssl-vision-processor@.user.service @@ -1,4 +1,4 @@ -# One vision_processor as your own user service, for camera %i (0 to 7): +# One ssl-vision-processor as your own user service, for camera %i (0 to 7): # # ssl-vision-processor-cameras --user add 0 /dev/video0 # @@ -13,7 +13,7 @@ [Unit] Description=SSL Vision Processor, camera %i (RoboCup SSL) -Documentation=man:vision_processor(1) man:ssl-vision-processor-cameras(1) +Documentation=man:ssl-vision-processor(1) man:ssl-vision-processor-cameras(1) AssertPathExists=%E/rcssl/vision-processor/cam%i.yml [Service] @@ -21,9 +21,9 @@ Type=exec EnvironmentFile=-%E/rcssl/vision-processor/environment # A camera without a source yet is skipped, not started to fail and restart # again and again. It starts once ssl-vision-processor-cameras add gives it -# one. (Until vision_processor can wait for one itself.) +# one. (Until ssl-vision-processor can wait for one itself.) ExecCondition=/usr/bin/ssl-vision-processor-cameras --user ready %i -ExecStart=/usr/bin/vision_processor %E/rcssl/vision-processor/cam%i.yml +ExecStart=/usr/bin/ssl-vision-processor %E/rcssl/vision-processor/cam%i.yml StateDirectory=rcssl/vision-processor/cam%i rcssl/vision-processor/cam%i/img WorkingDirectory=%S/rcssl/vision-processor/cam%i Restart=on-failure diff --git a/python/blob_benchmark.py b/python/blob_benchmark.py index 8895b12..1ff49c7 100755 --- a/python/blob_benchmark.py +++ b/python/blob_benchmark.py @@ -99,7 +99,7 @@ def stdoutprocessor(line: str): for video, _ in zip(dataset.images(), range(args.scenes_per_field if args.scenes_per_field else 1000000)): print(f"Processing {video}") - run_binary(args.binary, recorder, dataset, video, stdoutconsumer=stdoutprocessor) # , ground_truth=video.with_suffix('.vision_processor.json') + run_binary(args.binary, recorder, dataset, video, stdoutconsumer=stdoutprocessor) # , ground_truth=video.with_suffix('.ssl-vision-processor.json') threaded_field_iter(args.data_folder, consumer, field_filter=args.field) #, workers=1 diff --git a/scripts/README.md b/scripts/README.md index 9f0f150..387e048 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,6 +1,6 @@ # scripts -Small utilities for developing and running vision_processor and its GUI host. Run them from anywhere; each prints +Small utilities for developing and running ssl-vision-processor and its GUI host. Run them from anywhere; each prints its usage for an argument it doesn't know. | Script | What it does | @@ -9,7 +9,7 @@ its usage for an argument it doesn't know. ## lo-multicast.sh -vision_processor and the GUI host exchange multicast packets. When both run on one machine, or a test sends and +ssl-vision-processor and the GUI host exchange multicast packets. When both run on one machine, or a test sends and receives on the same machine, those packets go over loopback, which Ubuntu ships with multicast off. The GUI host warns about this at startup. diff --git a/scripts/lo-multicast.sh b/scripts/lo-multicast.sh index 55611c1..98abb88 100755 --- a/scripts/lo-multicast.sh +++ b/scripts/lo-multicast.sh @@ -2,7 +2,7 @@ # # Check, enable, or disable multicast on the loopback interface. # -# vision_processor and the gui host talk over multicast. When both run on one +# ssl-vision-processor and the gui host talk over multicast. When both run on one # machine, or a test sends and receives on the same machine, the packets go # over loopback, which Ubuntu ships with multicast off. The change takes effect # at once and lasts until reboot. diff --git a/setup.sh b/setup.sh index 80e72e6..2bb25b4 100755 --- a/setup.sh +++ b/setup.sh @@ -81,13 +81,13 @@ else fi -# Compile vision_processor +# Compile ssl-vision-processor SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) cd "$SCRIPT_DIR" echo -e "\e[92m » Updating protocol definitions submodule\e[39m" git submodule update --init --recursive cmake -B build . -make -j -C build vision_processor +make -j -C build ssl-vision-processor # Install systemd service(s) @@ -121,7 +121,14 @@ EOL read -p " » Install systemd service(s)? [yn]» " enable_systemd if [ "$enable_systemd" = "y" ]; then - install_service vision_processor build/vision_processor + # Before the rename, the service was vision_processor, running + # build/vision_processor: replace it. + old_service="$HOME/.local/share/systemd/user/vision_processor.service" + if [ -f "$old_service" ]; then + systemctl --user disable --now vision_processor.service || true + rm -f "$old_service" + fi + install_service ssl-vision-processor build/ssl-vision-processor # The GUI (gui/README.md) publishes geometry itself; two publishers # conflict. diff --git a/src/Perspective.cpp b/src/Perspective.cpp index 1172393..c85513a 100644 --- a/src/Perspective.cpp +++ b/src/Perspective.cpp @@ -56,7 +56,7 @@ void Perspective::geometryCheck(const int width, const int height, const double } if(!calibFound) { - if(socket->getGeometry().calib_size() == 0) // Don't recalibrate when its just another vision_processor instance sending it's camera calibration + if(socket->getGeometry().calib_size() == 0) // Don't recalibrate when its just another ssl-vision-processor instance sending it's camera calibration geometryVersion = 0; // Camera calibration has been cleared, recalibrate return; diff --git a/src/main.cpp b/src/main.cpp index 97a5bd4..73028e3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -435,6 +435,6 @@ int main(int argc, char* argv[]) { } } - VP_LOG("Stopping vision_processor"); + VP_LOG("Stopping ssl-vision-processor"); return 0; } diff --git a/tools/spinnaker_probe.cpp b/tools/spinnaker_probe.cpp index 2e7ffa5..9b07125 100644 --- a/tools/spinnaker_probe.cpp +++ b/tools/spinnaker_probe.cpp @@ -14,12 +14,12 @@ limitations under the License. */ -/* Dumps a Spinnaker camera's GenICam node maps as JSON, together with the pixel format vision_processor's +/* Dumps a Spinnaker camera's GenICam node maps as JSON, together with the pixel format ssl-vision-processor's * Spinnaker driver selects on it (see src/driver/spinnakerfeatures.h). * * Strictly read-only: it never writes a node or executes a command, so it is safe to run against * shared (e.g. league) cameras. It does not start acquisition. A GigE camera can only be opened by - * one process, so stop vision_processor first. */ + * one process, so stop ssl-vision-processor first. */ #include #include @@ -457,7 +457,7 @@ static int dumpCamera(JsonWriter& json, Spinnaker::CameraPtr& cam, const std::st writeNodeMap(json, cam->GetNodeMap(), all); json.endObject(); - json.key("vision_processor"); + json.key("ssl-vision-processor"); writeDriverView(json, cam->GetNodeMap()); json.endObject(); From 1896cbee801f8a022d5255d414ccf79d68009c93 Mon Sep 17 00:00:00 2001 From: Will Stuckey Date: Sun, 29 Nov 2026 19:40:43 -0500 Subject: [PATCH 33/35] udpate architecture document --- gui/ARCHITECTURE.md | 765 ++++++++++-------- gui/CLAUDE.md | 467 ++--------- gui/DEVELOPMENT.md | 30 + gui/REVIEW.md | 14 +- .../src/lib/FieldDimensionsEditor.svelte | 2 +- gui/frontend/src/lib/FieldSketch.svelte | 2 +- gui/frontend/src/lib/cameraLayout.ts | 2 +- gui/frontend/src/lib/layout/nav.svelte.ts | 2 +- 8 files changed, 519 insertions(+), 765 deletions(-) diff --git a/gui/ARCHITECTURE.md b/gui/ARCHITECTURE.md index 58817f9..871aea1 100644 --- a/gui/ARCHITECTURE.md +++ b/gui/ARCHITECTURE.md @@ -1,18 +1,27 @@ -# gui Architecture +# GUI Architecture -This document describes the design of `gui`, the Go host and browser UI for ssl-vision-processor. It covers the -subsystem in this directory only. The C++ ssl-vision-processor and the Python scripts in `python/` are described in -the root README and are not modified by this subsystem. +This page describes how the SSL Vision Processor GUI is built: the Go host, the browser interface it serves, and how +both fit around the camera processing done by ssl-vision-processor. It's written for anyone about to change the GUI. +If you just want to run it, see the [README](README.md). If you want to build and test it, see +[DEVELOPMENT.md](DEVELOPMENT.md). -`gui` replaces `python/geom_publisher.py` for anyone running it. It is a single Go binary with an embedded -Svelte frontend. It owns the shared field geometry, absorbs camera calibrations from ssl-vision-processor instances -over multicast, and serves the frontend, a JSON API, and a WebSocket for live updates, all on one port. +The page starts with where the GUI sits on a field, then walks through the host process, its state, the network, +and the browser. It ends with the rules that hold the code together and what isn't built yet. The C++ +ssl-vision-processor and the Python scripts in `python/` are covered by the [root README](../README.md), not here. -## System overview +## Where the GUI Fits -A venue runs one or more ssl-vision-processor instances, one per camera, on the gui host's machine or others. Each -exchanges SSL vision protocol messages with the host over the same multicast group the rest of the league uses. One -on the host's own machine also shares files with it: debug images in `img/`, and its generated `config.yml`. +A field runs one ssl-vision-processor per camera. Each one reads its camera, finds the robots and the ball, and +publishes detections to the league's vision [multicast](https://en.wikipedia.org/wiki/Multicast) group, where teams, +autorefs and the game controller read them. Before it can do that, each ssl-vision-processor needs the field +geometry, so it can calibrate its camera against the real field lines. + +The GUI is the piece that owns that geometry. It's one program, `ssl-vision-processor-gui`, that: + +- holds the field dimensions and every camera's settings in one file, `vision.yml` +- publishes the field geometry to the vision group once a second +- hears each camera's calibration and republishes it, or a locked one in its place +- serves a browser interface to set all of this up, with live video and a live view of the field ```mermaid graph LR @@ -39,16 +48,23 @@ graph LR GUI --> Browser ``` -The gui host does not talk to an ssl-vision-processor instance directly (with `-runCameras` it starts them, and hands -each its config file). Both sides only ever speak to the multicast -group, the same way any other league consumer would. This keeps the host interchangeable with the legacy -`geom_publisher.py` service from the ssl-vision-processor's point of view. The browser talks to the gui host over -HTTP and a WebSocket instead, covered under HTTP API and WebSocket protocol below. +**The GUI never talks to an ssl-vision-processor directly.** Both only speak to the multicast group, the same way +any other league program would. From a camera's point of view, the GUI is just another sender of geometry, which is +why it could replace the older `python/geom_publisher.py` without any change to the camera side. (That script still +exists: `setup.sh` and a few Python tools use it, so it stays.) The browser talks to the GUI over HTTP and a +[WebSocket](https://en.wikipedia.org/wiki/WebSocket). + +There are two exceptions, both for cameras on the GUI's own machine. The GUI writes each local camera's `config.yml`, +and reads the debug images it saves. With `-runCameras` it also starts and restarts those cameras' processes itself. + +All the calibration math lives in C++, in ssl-vision-processor. The GUI only does bookkeeping: merging calibrations, +laying out the field lines from the dimensions, and publishing the result. An earlier design split this across a Go +host and a Python service; once it was clear the Python side did no math, it was folded into the one Go program. -## Process layout +## The Host Process -`ssl-vision-processor-gui` is one process running these concurrently, wired together in -`cmd/ssl-vision-processor-gui/main.go`. It claims its port first and starts nothing else if that fails. +`ssl-vision-processor-gui` is one process. `cmd/ssl-vision-processor-gui/main.go` wires it together and runs these +loops side by side: ```mermaid graph TD @@ -83,49 +99,64 @@ graph TD Store -- "Sync" --> procs ``` -The housekeeping loop follows the network and the machine (interfaces, suspends, the height table) and publishes -status to browsers. It has its own clock so that a slow step can't delay publishing geometry. An edit to an address -applies at once; the loop is what catches everything else. - -The goroutines share one `*config.Store` and one `*geometry.Geometry`, each guarded by its own mutex. The store -pushes into the geometry, never the other way around. Shutdown is graceful: an `os.Interrupt`/`SIGTERM` cancels a -shared context, the HTTP server drains in-flight requests, and `main` waits for the other goroutines to exit -before returning. - -## Package responsibilities - -| Package | Responsibility | -| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cmd/ssl-vision-processor-gui` | Flags, wiring, HTTP handlers and routes. | -| `internal/config` | `vision.yml`: the working document, save and load, locked calibrations, the disk watcher, and generated `config.yml` files. | -| `internal/defaults` | Files embedded in the binary so it needs nothing beside it: the rulebook fields and the robot height table. | -| `internal/geometry` | The live field template, published calibrations, and the 1Hz publish loop. Holds no file state. | -| `internal/multicast` | The vision, game controller, autoref tracker, and video sockets: interface selection, reopening on changes, retrying while unhealthy, suspend detection. | -| `internal/api` | Typed route registration and the OpenAPI 3.1 spec reflected from the handlers' own types and doc comments. | -| `internal/hub` | In-process topic pub/sub and the `/ws` WebSocket handler. | -| `internal/httpjson` | The JSON error body and its codes. | -| `internal/origins` | Which browser pages and host names may use the API. | -| `internal/alerts` | Every problem the host can see: which, how serious, and the facts behind each. | -| `internal/discovery` | ssl-vision-processor instances, from their announces. | -| `internal/livefield` | The latest detection frame per camera and tracked frame per autoref, for the Live Field page. | -| `internal/detections` | Which camera_ids the vision socket hears, from which address, at what rate. Feeds the Camera Layout page. | -| `internal/referee` | The current match's teams, from the game controller, and their robot heights from `bot_heights_file`. | -| `internal/snapshot` | Debug image listing and serving. | -| `internal/video` | Live video: each camera's H.264 RTP stream relayed to browsers as fragmented MP4. | -| `internal/peers` | Names senders (IP, port, hostname) and logs and alerts when two of them claim one thing. | -| `internal/supervisor` | `-runCameras`: runs every camera's ssl-vision-processor and restarts it when a startup-only setting changes. | -| `internal/v4l` | Lists this host's Video4Linux capture devices for the camera path picker. | -| `internal/logging` | slog setup: a coloured console handler, a rotating file handler, and the last warnings and errors kept in memory for the system report. | -| `internal/buildinfo` | What the binary was built from: the git state of this repository and the proto submodule, stamped by the Makefile. | -| `internal/vision`, `internal/gamecontroller` | Generated protobuf bindings. Not committed, see Build-time codegen below. | -| `frontend` | Svelte 5 and TypeScript, embedded into the binary via `//go:embed`. | - -## Data flow: geometry state - -`Geometry` holds one `SSL_WrapperPacket`: the field template plus one calibration per camera. A camera's published -calibration is its locked one if set, otherwise the latest one absorbed from the network. It keeps a cached -protobuf encoding alongside the live message, since `proto.Marshal` writes to the message's own size cache and is -not safe to call from multiple goroutines without a lock. +The host claims its HTTP port first, and starts nothing else if it can't. Two pieces of state are shared by +everything: the config store (`*config.Store`) and the live geometry (`*geometry.Geometry`), each guarded by its own +mutex. **The store pushes into the geometry, never the other way around.** + +The housekeeping loop follows the machine and the network: interfaces coming and going, a suspend, a changed height +table. It also publishes status to the browsers. It has its own clock, so a slow step there can never delay the +geometry going out. An edited address applies at once; housekeeping catches everything else within a second. + +Shutdown is graceful. `SIGINT` or `SIGTERM` cancels a shared context, the HTTP server drains the requests in flight, +and `main` waits for every loop to finish. + +### Packages + +| Package | What it does | +| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `cmd/ssl-vision-processor-gui` | Flags, wiring, HTTP handlers and routes, and the WebSocket topic list. | +| `internal/config` | `vision.yml`: the working document, save and load, locked calibrations, the disk watcher, and generated `config.yml` files. | +| `internal/defaults` | Files built into the binary, so it needs nothing beside it: the rulebook fields and the robot height table. | +| `internal/geometry` | The live field template, the published calibrations, and the 1Hz publish loop. Holds no file state. | +| `internal/multicast` | The vision, game controller, autoref tracker and video sockets: interfaces, reopening, retrying, suspend detection. | +| `internal/api` | Route registration, and the OpenAPI spec built from the handlers' own types and doc comments. | +| `internal/hub` | Topic publish/subscribe inside the process, and the `/ws` WebSocket handler. | +| `internal/httpjson` | The JSON error body and its codes. | +| `internal/origins` | Which browser pages and host names may use the API. | +| `internal/alerts` | Every problem the host can see: which, how serious, and the facts behind each. | +| `internal/discovery` | The ssl-vision-processors heard announcing themselves. | +| `internal/livefield` | The latest detection frame per camera and tracked frame per autoref, for the Live Field page. | +| `internal/detections` | Which camera IDs the vision group carries, from which sender, at what rate. | +| `internal/referee` | The current match's teams, from the game controller, and their robot heights. | +| `internal/peers` | Names each sender, and notices when two of them claim the same thing. | +| `internal/snapshot` | Lists and serves the debug images a local camera saves. | +| `internal/video` | Live video: each camera's H.264 stream relayed to browsers. | +| `internal/supervisor` | `-runCameras`: runs every camera's ssl-vision-processor, and restarts it when it has to. | +| `internal/v4l` | Lists this machine's capture devices, for the camera device picker. | +| `internal/logging` | Logging to the console and a rotating file, with recent records kept in memory for the log panel and system report. | +| `internal/buildinfo` | What the binary was built from: the git state of this repository and of `proto/`. | +| `internal/vision`, `internal/gamecontroller` | Generated protobuf code, not committed. See [Generated Code](#generated-code). | +| `frontend` | The browser interface: Svelte 5 and TypeScript, built into the binary. | + +### Libraries + +The host leans on the standard library and a short list of dependencies: + +- **HTTP:** Go's own `net/http`, with no router library. Routes are patterns like `"GET /api/health"`, and + `r.PathValue(...)` reads their `{wildcard}` parts. +- **WebSocket:** [gorilla/websocket](https://github.com/gorilla/websocket). +- **Multicast:** plain sockets, through `go-reuseport` and `golang.org/x/net/ipv4`. Most league Go tools use + ssl-go-tools' `sslnet` instead, but it couldn't do what the host needs: it crashed when no interface was usable, + listened on one interface at a time, mixed groups that share a port, and leaked sockets. It's also GPL-3.0, and + this repository is Apache-2.0, so **don't import or copy code from ssl-go-tools.** +- **Protobuf:** `google.golang.org/protobuf`, with `protojson` for anything that goes to a browser (see + [Protobuf and JSON](#protobuf-and-json)). + +## Field Geometry and Calibrations + +`internal/geometry` holds one `SSL_WrapperPacket`: the field template, plus one calibration per camera. This is +exactly what the host multicasts once a second. A camera's published calibration is its **locked** one if it has +one, and otherwise the latest one heard from that camera. ```mermaid graph LR @@ -135,59 +166,61 @@ graph LR State -->|"Snapshot() -> protojson"| API["GET /api/geometry"] ``` -A calibration missing a required proto2 field is rejected with `proto.CheckInitialized` before it can touch -`State`, so a malformed message from one instance never desyncs the held message from its cached encoding. +The geometry keeps a cached encoding next to the message, behind its mutex. Encoding a protobuf message writes to the +message's internal size cache, so even reading it out is a write. `Absorb` re-encodes after each change; the publish +loop and the WebSocket only ever send the cached bytes. Anyone who needs the message itself gets a copy from +`Snapshot()`. + +### Locking + +Why lock a calibration at all? An ssl-vision-processor only skips calibrating at startup if the geometry packet it +hears already holds a calibration for its camera. Publishing a locked calibration is what lets either side restart +without the camera recalibrating. **Calibrations are locked explicitly, never saved automatically.** Unlocking stops +publishing that camera's calibration. A camera that's already running keeps the model it has, since the protocol has +no way to ask for a live recalibration, so it recalibrates on its next restart. + +### Validation -A received calibration is also rejected, and logged with its sender, unless it could be a real camera's -(`geometry.CheckCalibration`): every number finite, a positive focal length, a unit rotation quaternion, a non-empty -image, and the camera above the field. The host republishes what it absorbs every second, and an ssl-vision-processor -that receives a calibration for its camera skips calibrating and uses it, so one bad packet (a NaN, a test fixture, -another host's mistake) would otherwise stop that camera until someone unlocked it by hand. +Every calibration heard is checked before it touches the stored state: -## Senders and conflicts +- **Complete:** the SSL messages are proto2, with about a dozen required fields. A calibration missing one is logged + and dropped (`proto.CheckInitialized`). Merging it first would leave a message the host can no longer encode. +- **Plausible:** every number finite, a positive focal length, a unit rotation, a non-empty image, and a camera that's + above the field (`geometry.CheckCalibration`). Because the host republishes what it hears, and a camera that hears a + calibration for itself uses it, one bad packet would otherwise stop that camera until someone unlocked it by hand. -The host drops its own looped-back packets by sender address: every send socket records its local address -(`multicast.IsOwn`), which is exactly what its echoes arrive from. Everything else is compared by IP and port, -so two programs on one machine are told apart. `internal/peers` watches who sends each camera's calibration, -detections and video, each instance name, the game controller's referee messages, and field geometry, which only this host should -publish once a second. A second sender is logged once when it appears (`several senders claim the same thing`, -with each sender's IP, port, hostname from reverse DNS, and whether it's this machine) and again when it's gone, -and served as a `sender_conflict` alert on `network.state`/`GET /api/network`: an error for calibration, -field geometry and instance names, a warning for the game controller and video, and an error for every kind on a competition field. Two ssl-vision-processors on one -machine both send from the vision port, so they share an address and can't be told apart this way. +### Field Coordinates -An ssl-vision-processor's video streamer opens a new port whenever the streamed view changes size, so for video a sender -that stops as another begins on its IP is the same program; two that keep sending are a conflict. +Positions are in millimeters. The origin is the center of the field, `+x` points toward the right goal, and `+y` +toward the top touchline, the same as the SSL vision protocol. Field markings are generated from the dimensions +(`internal/geometry/field.go`), and lines the physical field doesn't have are left out, since publishing a line the +camera can't see disturbs its calibration. -Every endpoint also notes which interface each packet arrives on. One sender heard on several at once (two -interfaces on one network) is logged once and raises a `duplicate_packets` alert, one per set of interfaces. +`field_length` always means the full field. `layout.camera_count` (1, 2 or 4) splits the field into regions, halving +it along its length for each doubling, and a camera's ID picks its region, as in +[`camera_ids.png`](../camera_ids.png). A physical half field is entered as the full field it's half of, with its +cameras covering half the regions (one camera is region 0 of 2). `layout.half_field` records that, and only the GUI +reads it, to show the field as the user set it up. -The teams come from one game controller, the first heard, until it's silent for 3 s (`referee.Source`). Others still -count towards the conflict alert. +## Configuration -## Discovery +`vision.yml` is the one file the host owns. It holds: -ssl-vision-processor announces itself on the vision group about once a second, as an `SSL_WrapperPacket` with `config` -set. `internal/discovery` keeps the latest per `SSL_VPConfig.instance`: live while heard within 3 s, forgotten after -30 s. `GET /api/instances` and `instances.state` serve them; no page shows them yet. Two senders of one instance name -are a `sender_conflict`. Packets are told apart by `config` being present, not by `source`: the host's own geometry -packets have the same `source`. ssl-vision-processor builds its announce once, at startup, and sends it between frames, so -one whose camera blocks doesn't announce, and a reloaded config isn't reflected. +- the field template +- `defaults`, settings every camera shares, in ssl-vision-processor's own `config.yml` layout +- `cameras`, keyed by camera ID: each camera's own overrides, the corner picker's `seed`, an optional locked + `calibration`, and a GUI-only video `display` orientation +- `layout`, `teams`, `tracker`, `host` and `competitionField`, which only the host reads -## Configuration: vision.yml +The file is machine-written, so comments in it aren't kept on save. `config/vision.yml` at the repository root is a +commented reference. -`vision.yml` is the one file the host owns. It holds the field template, shared `defaults` in ssl-vision-processor's -own `config.yml` layout, and a `cameras` list keyed by `camera_id`. Each camera carries its own overrides, its -corner picker `seed` (corners plus the image resolution and slot they were picked at), optionally a locked -`calibration`, and a GUI-only video `display` orientation. `layout.camera_count` (1, 2 or 4) splits the field into -regions. `layout.half_field` marks a physical half field, entered as the full field it's half of with its cameras -covering half the regions (one camera is region 0 of 2); only the GUI reads it, to show the field and the camera -count as the user set them up. A camera's `camera_id` picks its region, as in `camera_ids.png`. Any mix of hosts and cameras is valid; -one host may run several cameras. +### Working Copy and Disk Copy -`config.Store` keeps two copies of the document: the working copy and the copy last loaded from or saved to disk. -Edits from the browser replace the working copy and apply live straight away. Save writes the working copy to -disk. The difference between the two is what the browser shows as unsaved changes. +`config.Store` keeps two copies of the document: the working copy, and the copy last loaded from or saved to disk. +**Edits from the browser replace the working copy and apply live, right away.** Save writes the working copy to disk. +The difference between the two is what the browser shows as unsaved changes, and which page each belongs to puts the +asterisks on the tabs. ```mermaid sequenceDiagram @@ -207,194 +240,158 @@ sequenceDiagram Store-->>Browser: config.state (WebSocket) ``` -The working copy lives in the host, so a restart loses what wasn't saved. `config.state` carries a `run` that changes -with each start, and revisions start at random, so a revision from an earlier run is always stale. A page that finds -the run changed, and that had unsaved changes or an edit the host never got, shows the host's document and asks -whether to put its own back (`keepLostWork` in `config.svelte.ts`). Once one page has, the others with the same -document stop asking. - -An ssl-vision-processor skips calibrating at startup only if the geometry packet it receives already holds a -calibration for its camera. Publishing locked calibrations is what keeps a restart of either side from triggering -a recalibration. Unlocking stops publishing that camera's calibration. A running ssl-vision-processor keeps the model -it already has, since the protocol has no way to ask for a live recalibration, so it recalibrates on its next -restart. - -Until ssl-vision-processor accepts configuration over the network, a camera with a `config_path` gets its -`config.yml` regenerated from `vision.yml` on every change, written only when the content differs. The file -starts with a header saying it is generated. `reloadConfigIfChanged()` in `src/Resources.cpp` hot reloads -`thresholds`, `tracking`, `color`, and `debug` every half second, but never `geometry`, `camera`, `network`, or -`stream`. Changes to those take effect when the instance restarts. - -With `-runCameras`, the host also runs those instances itself (`internal/supervisor`), one per `config_path`, -using the `ssl-vision-processor` it finds on `PATH` at startup; it exits if there is none. A host runs every camera or -none, so in this mode every camera gets a `config_path`: `Document.AssignConfigPaths` names it `cam.yml` (or -`cam-2.yml` and so on if taken) whenever a document is loaded or edited without one. One assigned on load shows -as an unsaved change. Two cameras can't share a `config_path`. Each process runs in its own directory, -`run/cam` in the state folder, with `img` there linking to `cam` in `-imgDir`, so the debug files -ssl-vision-processor writes relative to its working directory never collide or land in the config folder. Its own image -folder matters because not every file it writes to `img/` is prefixed by camera_id; the snapshot routes read both -`-imgDir` and its `cam` folders. It gets its config file's full path, -and the rendered file names `bot_heights_file` by its full path too. - -Before starting anything, the supervisor compares the cameras' capture devices, with ssl-vision-processor's fallbacks -filled in (`Document.CaptureDevice`: OPENCV opens `/dev/video` when no device is named, other drivers their -`id`-th camera) and device paths resolved through symlinks. A camera whose device a lower camera_id already uses is -held, not started: state `conflict`, a `device_conflict` alert, and a 409 from its restart route. It starts on its own -once its device changes. `Document.Validate` already rejects two cameras on one device on the same `instance`; this -also catches cameras on different instances, and two names for one device node. A camera with no driver chosen (DUMMY, which today's -ssl-vision-processor exits on) is held too: state `no_camera`, a `camera_not_selected` alert, and a 409 `no_camera`. A -daemon holding a camera is out of -scope: the process's own output says the device is busy. - -It watches the store like any other subscriber: on each change it renders every camera's -config and compares it with what each process was started with. A difference in a setting the schema marks `live` -or `host` needs nothing more, since the file is already rewritten; any other difference (startup-only, derived, -or unknown) restarts the process once edits have been quiet for a second, so a slider drag restarts it once. -Stopping is SIGTERM, then SIGKILL after 3 s, since ssl-vision-processor only checks for SIGTERM between frames. A -process that exits on its own is started again: after 1 s for a clean exit, doubling per crash in a row up to -30 s. A change to the field or its optional lines restarts every supervised camera to recalibrate: between -stopping the process and starting it again, the host unlocks the camera's calibration and drops the one it last -received, since ssl-vision-processor skips calibrating when the geometry packet already holds one for its camera. -`processes.state` and `GET /api/processes` carry each one's state, pending restart keys, last exit, and last -lines of output; `POST /api/processes/{id}/restart` restarts one at once. - -### Files on disk - -`-configDir` is one flat folder holding every config file. The API has no authentication and can reach the disk, so -everything it names is checked by `config.ValidName`: one path component, not hidden, ending in `.yml` or `.yaml`. -`Store.Load` and `Store.SaveAs` take a name rather than a path, and refuse symlinks, since `Load` switches the file -a later save writes to. `Document.Validate` applies the same check to `config_path` and `bot_heights_file`, on every -parse and edit, because rendering writes a file wherever `config_path` says. A config also can't render over itself -or Save As over a file it uses. Flags can name anything, since whoever starts the process already has that access. - -A host with no config creates one from `internal/defaults`, which embeds the rulebook fields and robot height table -so the binary needs nothing beside it. The Makefile copies those in, since `go:embed` can't reach outside the -module, and a test checks the copies match their sources. - -The new config has `first_run: true`. While it's set, the host sends no geometry on the vision group, so running the -binary to try it can't tell a real network about a field nobody has confirmed. Everything else works, and the -browser still gets live updates. The first successful Save or Save As removes the key. The host owns it: edits can't -change it, so it never appears in the change list, and a save that fails to reach the disk leaves it set. Clearing -it bumps no revision, so the GUI reads it from `config.state`. Its wizard opens on a first run and ends in the save -dialog, which allows saving with no changes so the defaults can be accepted. - -The host's own sockets use the shared `defaults.network` block (`vision_ip`, `vision_port`, `gc_ip`, `gc_port`), -with ssl-vision-processor's defaults for missing keys. Each is a `multicast.Endpoint`. When an edit changes an -address, the endpoint closes its sockets and opens new ones on the new address straight away. A multicast -address joins the group. Any other IPv4 address, normally a broadcast address for switches whose IGMP snooping -drops multicast, listens on the port instead; ssl-vision-processor handles broadcast too, since its socket sets -`SO_BROADCAST`. The Network page offers the standard, backup (port + 10), legacy (10005), and broadcast choices, -warns about addresses that aren't multicast or broadcast, and notes non-standard and privileged (below -`ip_unprivileged_port_start`) choices when extra tooltips are on. ssl-vision-processor reads the same block, but only -at startup. - -The autoref tracker socket uses the top-level `tracker` block (`ip`, `port`, default 224.5.23.2:10010) instead, -since no ssl-vision-processor listens for tracker output. It is never rendered into a camera's `config.yml`. It may -share the vision group's IP, which is the standard setup, but not its address and port. A silent tracker socket -raises no alert, since running without an autoref is normal; one that can't open does. - -Which interfaces the host's own sockets use is `host.interfaces`, a section no ssl-vision-processor reads, since -interface names only mean something on one machine. `auto` (the default) uses interfaces that are up, have -carrier, support multicast, and have an IPv4 address, and skips loopback and virtual ones (Docker and VM bridges, -VPN tunnels); it is re-evaluated every second. Otherwise `skip` is a blacklist. With nothing -else to use, `auto` falls back to loopback if it has multicast on. With no network and loopback multicast off, as -Ubuntu ships it, the host warns at startup, raises an alert, and suggests the commands that enable it. - -Every endpoint receives on one plain socket that hears only the group it joined (Linux `IP_MULTICAST_ALL` off; Go -binds a multicast address as `0.0.0.0`, so binding the group alone doesn't do it), joined on all used interfaces at -once, and sends from each used interface. Endpoints heal themselves: if a socket can't be -fully set up (no usable interface, a failed join, a send socket lost when an interface went away), the endpoint -reports the problem in its status, shown on the Network page and the badges, and retries every 5 s, logging only -when the problem changes. The host also notices a suspend: each second it compares `CLOCK_BOOTTIME`, which keeps -counting while suspended, with `CLOCK_MONOTONIC`, which doesn't. Neither jumps for NTP or clock changes, so a gap -means the machine slept, and every socket is reopened. - -The Camera page edits each camera's `camera:` block, shown with ssl-vision-processor's own fallbacks applied -(`src/driver/cameradriver.cpp`; an unset driver means SPINNAKER; a new config says DUMMY, the protocol's "no camera"). Controls follow the driver: an index for -SPINNAKER, MVIMPACT and DC1394, plus a serial number for SPINNAKER, a path for OPENCV, gamma hidden for -MVIMPACT, and the OUTDOOR and INDOOR auto white balance profiles only for SPINNAKER. The serial and the path are -both `device`, written in place of its former name `path`, which still reads. ssl-vision-processor reads `camera:` -only at startup. Validation rejects what it -would misread instead of refusing: an unknown driver (fatal at startup) and any white balance string other than -OUTDOOR or INDOOR (it treats every other string as INDOOR). - -`camera.exposure` is µs in `vision.yml` for every driver. The host converts it when it writes `config.yml` -(`internal/config/exposure.go`): SPINNAKER and MVIMPACT read milliseconds, and OPENCV -sends the value × 1000 to V4L2's `exposure_time_absolute`, which counts 100 µs. Format version 1 stored the file's -unit; a version 1 document is migrated on load and saved as version 2. - -Every number in the free form blocks is normalized to an int or a float64. The browser sends every number as a -JSON float and YAML decodes integers as ints, so without this every edit would show spurious changes such as -`1920 -> 1920`. - -## HTTP API +A watcher checks the file once a second. If something else changed it, the browser offers to load the new file or +keep the working copy. -Every route is registered in `cmd/ssl-vision-processor-gui/routes.go` through `internal/api`, which builds an -OpenAPI 3.1 spec from each handler's request and response types, and its summary, descriptions and field docs -from their Go doc comments. The host serves the spec at `GET /api/openapi.json` and a reference for it at -`GET /api/docs` (Redoc, embedded, so it works offline), linked from the GUI's settings menu. +Every write carries a revision, and a write from a page that's behind is refused, so two open pages can't silently +overwrite each other. The working copy lives in the host, so a host restart loses what wasn't saved. Each start has +its own `run` ID, and revisions start at random, so a page always notices the restart. A page that had unsaved changes +then shows the host's document and asks whether to put its own back. Once one page has, the others stop asking. + +Every number in the free-form blocks is normalized to an integer or a float. The browser sends every number as a JSON +float and YAML reads integers as integers, so without this every edit would show changes like `1920 -> 1920`. + +### First Run + +A host with no config creates one, from the fields and robot heights built into the binary (`internal/defaults`). The +new file has `first_run: true`, and **while it's set, the host publishes nothing on the vision group.** That makes it +safe to try the GUI on a live network: nobody hears about a field nobody has confirmed. The first successful save +removes the flag. The host owns it: edits can't change it, and a save that fails to reach the disk leaves it set. + +### One Flat Folder + +Every config file lives in one folder, `-configDir`. The API has no authentication, so it must not be able to write +anywhere the host can. Every file name it takes goes through `config.ValidName`: one path component, not hidden, +ending in `.yml` or `.yaml`. That covers load, Save As, a camera's `config_path`, and `bot_heights_file`. Load +counts as a write too, since it changes where the next save goes. Command line flags can name any path, since whoever +starts the host already has that access. + +### Each Camera's config.yml + +ssl-vision-processor doesn't take its configuration over the network yet. Until it does, each local camera with a +`config_path` gets its `config.yml` **generated** from `vision.yml`: `defaults` merged with the camera's own settings, +plus `cam_id`, `camera_amount` and `line_corners`, which the host works out. The file is rewritten on every change +that alters it, and says at the top that it's generated. + +ssl-vision-processor reloads `thresholds`, `tracking`, `color` and `debug` from the file within a second. It reads +`geometry`, `camera`, `network` and `stream` only at startup. + +The Camera page edits a camera's `camera:` block, with ssl-vision-processor's own fallbacks shown. A new config's +driver is `DUMMY`, the protocol's "no camera". Controls follow the driver, and validation refuses what +ssl-vision-processor would misread, such as an unknown driver. `camera.exposure` is microseconds in `vision.yml` for +every driver; the host converts it to each driver's own unit when it writes `config.yml` +(`internal/config/exposure.go`). + +## Running Cameras Locally + +Events run each ssl-vision-processor as its own service. A student lab with one webcam doesn't want to, so +`-runCameras` has the host run every camera itself (`internal/supervisor`). It's all or nothing: in this mode every +camera is local, and gets a `config_path` (`cam.yml`) if it has none. + +The host looks for `ssl-vision-processor` on `PATH` once, at startup, and exits if it isn't there. There's no flag to +name another binary: to run your own build, put it first on `PATH`. Each process runs in its own folder, +`run/cam` in the host's state folder, with an `img` link to its own folder of debug images. That keeps the files +each camera writes apart, since not all of them carry the camera ID. + +The supervisor follows the store like any other subscriber. On each change it renders every camera's config and +compares it with what that process started with: + +- a setting ssl-vision-processor reloads, or one only the host reads: nothing more to do +- anything else, including settings it doesn't know: restart that camera, once edits have been quiet for a second +- a change to the field: restart every camera, unlocking each one's calibration while it's stopped, so it calibrates + against the new field + +A camera isn't started while it has no driver chosen (state `no_camera`), or while a camera with a lower ID uses the +same capture device (state `conflict`). Both raise an alert, and the camera starts on its own once it's fixed. A +process that exits is started again, waiting longer after each crash in a row, up to 30 seconds. + +Each process gets its own process group, so Ctrl-C in a terminal reaches only the host, and dies with the host. +Stopping one is `SIGTERM`, then `SIGKILL` after 3 seconds, since ssl-vision-processor only checks for `SIGTERM` +between frames. + +## The Network + +### Sockets -None of the spec's inputs or outputs are committed; `make` builds them. `internal/api/comments_gen.go` holds the -Go doc comments (`go generate`, from the source), `gui/openapi.json` comes from the host itself (`-openapi `, -which writes the spec and exits), the frontend's API types (`frontend/src/lib/generated/api.ts`) from that by -openapi-typescript, and the viewer (`internal/api/viewer/`) is Redoc's bundle fetched at a pinned version and checked -against its SHA-256. The frontend imports its API types from `frontend/src/lib/apiTypes.ts`, never a hand copy, -and calls the API through `frontend/src/lib/api.ts`, a client typed by the same file. +The host has a socket for each league group it uses: vision, game controller, and the autoref tracker, plus one per +camera for live video while someone watches. Each is a `multicast.Endpoint`. + +- **Vision and game controller** use `defaults.network`, the same addresses every ssl-vision-processor reads. +- **The autoref tracker** uses `tracker`, which only the host reads. +- **Interfaces** come from `host.interfaces`: `auto` uses every interface that's up, has an IPv4 address and supports + multicast, skipping loopback and virtual ones like Docker bridges and VPNs. With nothing else, it falls back to + loopback if multicast is on there. + +A multicast address joins the group. Any other IPv4 address, normally a +[broadcast](https://en.wikipedia.org/wiki/Broadcast_address) address for switches that drop multicast, listens on the +port instead. Each socket hears only the group it joined, on every interface in use at once, and sends from each +interface. + +**Endpoints heal themselves.** An address change reopens the sockets at once. If a socket can't be fully set up (no +usable interface, a failed join, an interface that went away), the endpoint reports why in its status, which the +Network page shows, and retries every 5 seconds. The host also notices a suspend, by comparing a clock that keeps +counting while suspended with one that doesn't, and reopens everything. + +### Senders and Conflicts + +The host ignores its own packets when they loop back, by the address each socket sends from. Everything else is told +apart by IP and port, so two programs on one machine count as two senders. + +`internal/peers` watches who sends each camera's calibration, detections and video, each instance name, the game +controller's referee messages, and the field geometry, which only one host should publish. When a second sender +claims the same thing, the host logs it, with each sender's address and hostname, and raises a `sender_conflict` +alert. How serious it is depends on what's claimed, and every kind is an error on a competition field. The teams come +from the first game controller heard, until it's been silent for 3 seconds. + +### Discovery + +Each ssl-vision-processor announces itself on the vision group about once a second: an `SSL_WrapperPacket` with its +`config` set. `internal/discovery` keeps the latest announce for each instance name, live while heard within 3 +seconds, and forgotten after 30. **Discovery keys on `config` being present, never on `source`:** the host's own +geometry packets carry the same `source`. + +## The Browser Interface + +The host serves everything the browser needs on one port: the frontend itself, a JSON API, the `/ws` WebSocket for +live state, `/ws/video/{id}` for each camera's video, and the debug images. + +### HTTP API + +Every route is registered in `cmd/ssl-vision-processor-gui/routes.go` through `internal/api`, which builds an +[OpenAPI](https://www.openapis.org/) 3.1 spec from each handler's input and output types and its doc comment. The +host serves the spec at `/api/openapi.json`, and a reference page for it at `/api/docs`, linked from the GUI's +settings menu. The frontend's API types are generated from that same spec, so the browser and the host can't drift +apart. A handler takes one input struct and returns one output. Input fields tagged `path:`, `query:` or `header:` are -parameters, and a field tagged `body:""` is the body; an input with only JSON fields is itself the -body. Output fields tagged `header:` are response headers. Each route lists the error codes it can return, which -the spec shows per status; the `cmd` tests fail if any route answers a code it doesn't list. Routes whose -responses aren't one JSON value (the snapshot image, the two WebSocket upgrades) use `api.Raw` and are -documented the same way. - -An unrouted `/api/*` path returns 404 rather than falling through to the frontend, so a typo'd endpoint fails -with a clear status instead of returning HTML to a caller expecting JSON. Every other path serves the embedded -frontend, with a fallback to `index.html` for client side routes. - -Every error is JSON, `{"error": code, "message": text, "issues": [...]}` (`internal/httpjson`). Clients branch -on `error`: `bad_request`, `invalid` (with one `issues` entry per problem), `not_found`, `stale`, -`disk_changed`, `no_live_calibration`, `device_conflict`, `no_camera`, `precondition`, `unsupported_media`, -`cross_origin`, `unknown_host`, `internal`. -Request bodies must be `Content-Type: application/json` (PATCH also takes `application/merge-patch+json`), and -unknown keys are rejected, so a misspelled key fails instead of silently resetting the value it named. - -`GET /api/config` returns the revision as its `ETag`, and every config write (PUT, PATCH, save, save-as, load, -reload, lock, unlock) answers `{"revision": n}` with the new revision as its `ETag`. PATCH follows RFC 7396: objects -merge, `null` removes a key, and arrays (`cameras`) are replaced whole. PATCH is the safer write for a client that -doesn't model the whole document: PUT replaces it, so a key the client dropped is removed. - -Some document keys only matter to this GUI and no ssl-vision-processor reads them: a camera's `display` (video -orientation) and `seed.goalSideMarker` (which corner marker was picked). Other clients should leave them as they -are. `teams` and `competitionField` are read by the host's alerts, and `tracker` by its tracker socket. Each `Change` in `config.state` has both `path` -(vision.yml's spelling, `field.field_width`) and `jsonPath` (the JSON document's, `field.fieldWidth`); in both, -`cameras[N]` is the camera with camera_id N, not a list index. `section` is the GUI page the change belongs to. Protobuf messages appear in two spellings: `/api/geometry` and -`geometry.state` use canonical protojson (`pixelImageWidth`), while the document's `models` and -`calibration.camera` keep proto field names (`pixel_image_width`), matching how they're stored in vision.yml. - -"Host-local" endpoints describe the machine running the host, and only describe a camera when its -ssl-vision-processor runs on the same machine: device paths and debug images aren't available for remote instances. - -Browser pages from other origins are handled by `internal/origins`. The host's own pages are always allowed. In a -lab, so is any page served from this network: `localhost`, a loopback, private or link-local IP, a `.local` name, or -a single-label name such as `laptop`. No public website can have such an origin, because the browser sets `Origin` -from the page's real address. On a competition field (`competitionField`, switched live) only the host's own pages -and the `-allowOrigin http://host:port,...` list are allowed; `*` allows any. A page that isn't allowed can't change -state (the `http.CrossOriginProtection` test: `Sec-Fetch-Site`, else `Origin` against `Host`) or open `/ws` and -`/ws/video`. An allowed page from another origin gets CORS headers (preflights answered, `ETag` exposed). Clients -outside a browser send no `Origin` and are unaffected. - -Every request must also name the host by something it is: any IP literal, `localhost`, a `.local` or single-label -name, its hostname, the names its addresses reverse-resolve to, or a `-allowHost` alias (`*` turns the check off). -Anything else gets 421 `unknown_host`. This stops DNS rebinding, where an attacker points their own domain at this -host so the browser treats their page as same-origin. - -There is no authentication: anyone who can reach the port, including another team on a venue network using this -UI, can administer the host. - -## WebSocket protocol - -`/ws` is a single connection carrying a topic based publish/subscribe protocol, implemented in `internal/hub`. +parameters, and the rest is the JSON body. Each route lists the error codes it can return, and the tests fail if a +route answers one it doesn't list. + +Every error is JSON: `{"error": code, "message": text, "issues": [...]}`. Clients branch on `error`. Request bodies +are refused if they hold a key the host doesn't know, so a misspelled key fails loudly instead of resetting the value +it meant. + +The config routes use the document's revision as their [ETag](https://en.wikipedia.org/wiki/HTTP_ETag). `PUT +/api/config` replaces the whole working document; `PATCH` merges into it +([RFC 7396](https://www.rfc-editor.org/rfc/rfc7396)), which is safer for a client that doesn't model every key. + +An unrouted `/api/...` path returns 404, rather than falling through to the frontend and answering with a page of +HTML. Every other path serves the frontend, falling back to `index.html` for the browser's own routes. + +### Who Can Use It + +**There is no authentication.** Anyone who can reach the port can administer the host, including another team on a +venue network. What the host does check: + +- **Origins** (`internal/origins`): a page from another site can't change anything or open a WebSocket. In a lab, + pages from the local network are allowed (`localhost`, private addresses, `.local` names). On a competition field, + only the host's own pages and the `-allowOrigin` list. +- **Host names:** every request must name the host by something it is, such as an IP address, its hostname, or an + `-allowHost` alias. This stops [DNS rebinding](https://en.wikipedia.org/wiki/DNS_rebinding). + +### WebSocket Topics + +`/ws` is one connection carrying a publish/subscribe protocol (`internal/hub`): ```json // client -> server @@ -405,71 +402,127 @@ UI, can administer the host. { "error": "unknown_topic", "message": "...", "topic": "geomtry.state" } ``` -`GET /api/topics` lists the topics, from the one list in `cmd/ssl-vision-processor-gui/topics.go`, which also drives -the API reference's table and the frontend's types (the spec's `Topics` schema). A new subscriber gets the topic's latest value at once, then every later one. -A message the server can't act on is answered with an error (`bad_request`, `unknown_topic`, `unknown_action`) -and the connection stays open. - -`geometry.state` carries the current `SSL_WrapperPacket` as canonical protojson, published once per second. -`config.state` carries `config.Store`'s state: the revision, unsaved changes, any change made to the file on disk, -and per camera calibration status. It is published on every change and once per second, since live calibration -status comes from the network rather than the store. -`network.state` carries each multicast socket's address and what it has heard there: vision detection packets -(the host's own looped back geometry doesn't count), game controller referee messages, and autoref tracker packets. It is published once per -second and on every config change. -`processes.state` carries the ssl-vision-processors the host runs (`-runCameras`), on every state change and once per -second; an empty list without `-runCameras`. -`live-field.state` carries the latest detection frame from each camera (by camera_id and sender) and the latest -tracked frame from each autoref (by the uuid it sends), as canonical protojson inside a small envelope with each -source's rate and receive time and the host's clock (`at`), so a client can tell a source's age without trusting the -senders' clocks. Detections are in mm, tracked frames in m. A source silent for a second is listed without a frame, -and dropped after 30 s. It is published at up to 60 Hz, only while someone subscribes and something new arrived (and -once a second otherwise); `GET /api/live-field` returns the same snapshot. -`instances.state` carries every ssl-vision-processor heard announcing itself (`internal/discovery`), once per second and -on every config change; the same as `GET /api/instances`. -`alerts.state` carries every problem the host can see (`internal/alerts`), on the same schedule: a stable `id`, -a `code`, a `severity` (`error`, `warning`, `caution`), an optional `cameraId`, the facts behind it as `params`, -and a plain English `message`. The host decides which alerts exist and how serious they are; a client words and -links them by `code`, falling back to `message` for codes it doesn't know. - -Every channel in this path, from a topic's own subscriber channel to a connection's shared outbound channel, is -size limited and drops the oldest queued value in favor of the newest one. A slow client sees only the latest -value once it catches up, never a growing backlog of stale ones. - -## Live video - -Each ssl-vision-processor multicasts H.264 over RTP (`src/rtpstreamer.cpp`) to `ip_base_prefix + (ip_base_end + -cam_id):port` from its `stream` settings, 224.5.23.100+id:10100 by default. `internal/video` relays it without -re-encoding. A camera's socket opens on its first viewer and closes 5 s after its last. Like every endpoint it -hears only its own group, so cameras sharing port 10100 don't mix, with a 4 MB receive buffer for a keyframe's -burst of packets. - -Packets are reassembled into frames (RFC 6184 single units, STAP-A, FU-A; there is no SDP, so payload type and -packetization mode 1 are assumed). After a lost packet, frames are dropped until the next keyframe, since the ones -in between can't decode. Packets at or behind the newest are ignored: copies, or too late. A new SSRC means the encoder restarted, which it does whenever the streamed view changes -size; the parameter sets that come with the next keyframe start a new init segment. Frames are muxed as fragmented -MP4, one per segment, timed by arrival rather than the encoder's nominal 30 fps. - -`/ws/video/{id}` sends JSON `status` (once a second) and `format` (codec string and size) messages, and binary -segments. `full` is every frame; `keyframes` is about one a second, for grids. A new viewer gets the frames since -the last keyframe, so the picture appears at once. A viewer whose queue fills skips to the next keyframe. The -browser appends in sequence mode, jumps forward when it falls behind, and disconnects while its tab is hidden. -The host's cost is about 1% of a core per watched stream; the browser's H.264 decode is the real cost. - -## Build-time codegen - -`internal/vision`, `internal/gamecontroller`, and `frontend/src/proto` are `buf generate` output and are not -committed. `buf.gen.yaml` uses local plugins (`go tool protoc-gen-go`, `protoc-gen-es` from the frontend's own -`node_modules`), so generation needs no network beyond the already checked out `proto/` submodule. `gui/Makefile` -regenerates them as an ordinary build prerequisite. See `gui/DEVELOPMENT.md` for the exact commands. - -## Not yet built - -- **Discovery page.** Showing the announced instances, and comparing each one's config with what it should be. -- **Host owned config push.** Diffing an instance's announced config against a desired one and pushing the - difference, rather than regenerating a local `config.yml` as the host does today. This also needs a way to ask - a running instance to recalibrate. -- **Remote snapshots.** `internal/snapshot` assumes the gui host and the ssl-vision-processor instance share a - filesystem. Live video (above) works remotely, but the full-resolution snapshots the corner picker needs do not. -- **Translation (i18n), planned for v2.1.** User-facing text moving into one catalog per language, looked up by - key. Until then the text stays English and in the source. +A new subscriber gets the topic's latest value at once, then every later one. The topics are listed once, in +`cmd/ssl-vision-processor-gui/topics.go`, which also feeds `GET /api/topics`, the API reference, and the frontend's +types. + +| Topic | What it carries | When | +| ------------------ | ----------------------------------------------------------------------------------------- | ----------------------------------------------------- | +| `geometry.state` | The published `SSL_WrapperPacket` | Every second | +| `config.state` | The revision, the unsaved changes, a change on disk, and each camera's calibration status | On every change, and every second | +| `network.state` | Each socket's address and status, and what it has heard | Every second, and on config changes | +| `processes.state` | The cameras the host runs itself (`-runCameras`); empty otherwise | On every change, and every second | +| `live-field.state` | The latest detection frame per camera and tracked frame per autoref | Up to 60 Hz while someone watches, with something new | +| `instances.state` | Every ssl-vision-processor heard announcing itself | Every second, and on config changes | +| `alerts.state` | Every problem the host sees, with a code, a severity and the facts behind it | Every second, and on config changes | + +**A slow client only ever sees the latest value.** Every channel on the way out, from a topic's subscriber channel +to a connection's outbound queue, holds one value and drops the older one for the newer. Nobody builds up a backlog +of stale state. Unsubscribing closes that topic's channel, which is what ends its forwarding goroutine. + +The hub pings each connection about once a minute and sets read and write deadlines, so a client that vanishes +without closing (a laptop lid, dead wifi) is noticed and cleaned up. + +The host decides which alerts exist and how serious they are; the browser words them by `code`, falling back to the +host's `message` for a code it doesn't know. + +### Live Video + +Each ssl-vision-processor streams H.264 over [RTP](https://en.wikipedia.org/wiki/Real-time_Transport_Protocol) to its +own multicast group, `224.5.23.100 + camera ID` on port 10100 by default. `internal/video` relays it to the browser +without re-encoding: packets are put back together into frames, packed as fragmented MP4, and sent over +`/ws/video/{id}` for the browser's [Media Source Extensions](https://en.wikipedia.org/wiki/Media_Source_Extensions) to +play. A camera's socket opens on its first viewer and closes 5 seconds after its last. + +After a lost packet, frames are skipped until the next keyframe, since the ones between can't be decoded. A viewer +that falls behind skips ahead to the next keyframe too. A grid of cameras can ask for keyframes only, about one a +second. The host's cost is about 1% of a core per watched stream; the browser's decoding is the real cost. + +This was chosen over WebRTC because latency doesn't matter for setup, and it avoids Firefox's limits on WebRTC H.264. + +### Debug Images + +The corner picker needs full-resolution stills from the camera, which the video stream isn't. Those come from the +debug images ssl-vision-processor saves to its `img/` folder, which `internal/snapshot` lists and serves. **This only +works for a camera on the host's own machine,** since the two share a filesystem. Path segments are checked against a +strict set of characters before they reach the filesystem, so a request can't list or read anything else. + +## The Frontend + +The frontend is [Svelte 5](https://svelte.dev/) and TypeScript, built with Vite and compiled into the host binary. + +- **State uses Svelte's runes, not stores.** Shared state is a module-level `$state` object, such as `config` in + `config.svelte.ts`. Components bind straight into `config.doc`, and one effect notices any change and sends it to + the host, so no component has to remember to save. +- **Live state comes from the WebSocket** through `bus.svelte.ts` (`topicState`, `onTopic`), typed by the host's + topic list. +- **The API is called through `lib/api.ts`,** a client typed by the generated spec, with the types imported by name + from `lib/apiTypes.ts`. There are no hand-written copies of the host's types or hand-written URLs. +- **The interface is built from [Flowbite Svelte](https://flowbite-svelte.com/) components,** laid out with Tailwind, + with colors from the theme tokens in `src/app.css` (matched to the SSL Game Controller), never hex values in + components. Settings forms are + `FormRow` rows inside a `SettingsCard`. Drawing is the exception, written by hand: the YUV plane, the weight + triangle, the corner overlay and the field sketches. +- **The words live apart from the components,** one file per page in `lib/text/`, so they can be edited (and later + translated) without touching the components. See its [README](frontend/src/lib/text/README.md). +- **Logic lives in plain `.ts` modules,** tested on their own, and components keep only the wiring. + +The frontend's own layout and scripts are in its [README](frontend/README.md). + +## Rules That Hold It Together + +A few rules aren't obvious from any one file, but the design depends on them. + +### Protobuf and JSON + +The SSL messages are **proto2**. Every field is a pointer, and most are required. Read them through the generated +`Get...()` methods, which are safe on nil, and write them with `proto.String(...)`, `proto.Float32(...)` and the like. +A required field left unset makes encoding fail, and the host relies on that. + +Anything sent to a browser is JSON from **`protojson`, never `encoding/json`** on a generated message. +`encoding/json` compiles and seems to work, then writes enums as numbers and mishandles `oneof` fields. The multicast +wire is the one place raw protobuf goes out, because that's the SSL protocol. + +The API spells protobuf fields two ways. `/api/geometry` and `geometry.state` use protojson's names +(`pixelImageWidth`), while the config document keeps proto field names (`pixel_image_width`), as `vision.yml` stores +them. + +### HTTP Server + +- **`ReadHeaderTimeout` is set, and `WriteTimeout` must not be.** A write timeout is a deadline on the whole response, + and would cut every WebSocket and video stream after that many seconds. +- **Routes match by how specific they are, not the order they were added.** `/api/` is registered as a catch-all 404 + for exactly that reason. +- **Every route goes through `internal/api`,** so the spec stays complete. + +### Generated Code + +The protobuf code (`internal/vision`, `internal/gamecontroller`, `frontend/src/proto`), the OpenAPI spec, the +frontend's API types, and the API reference page are all generated by `make`, and none of them are committed. `buf` +reads the `proto/` submodule directly, so there's no copy of the definitions to drift, and both of its plugins run +locally, so generating needs no network. + +`frontend/dist/.gitkeep` is the one exception that stays committed: the host is compiled before the frontend's first +build (to write the spec the frontend is typed from), and Go's `embed` fails without a file in `dist/`. + +**Anything shipped is built with `CGO_ENABLED=0`** (`make release`). A normal build under nix links against a +`/nix/store` path that doesn't exist on anyone else's machine. + +## Not Yet Built + +These are planned or open, and the code is shaped around them: + +- **A discovery page.** The host hears every ssl-vision-processor's announce, but no page shows them yet, and nothing + compares an announced config with the one it should have. +- **Sending configuration over the network.** Today a local camera's configuration is a generated `config.yml`. The + plan is for the host to push each camera the difference between what it announces and what it should run, which + needs an endpoint in ssl-vision-processor, and a way to ask a running camera to recalibrate. +- **A first name for a new camera.** Each announce names its instance, but once configuration comes over the + network there's no local file to name a camera that has never been set up. +- **What an announce carries.** It's built once at startup, and sent between frames, so a camera whose capture blocks + never announces, and a reloaded config isn't reflected. Whether it should carry a camera's full current config, + which pushing a difference needs, is still open. +- **Debug images from other machines.** Live video already works across the network; the full-resolution stills the + corner picker needs don't. +- **Translation (i18n), planned for v2.1.** Every user-facing string moves to a catalog per language, looked up by + key. Until then the GUI is English, with its text kept together in `lib/text/`. diff --git a/gui/CLAUDE.md b/gui/CLAUDE.md index e2419e2..6db84a0 100644 --- a/gui/CLAUDE.md +++ b/gui/CLAUDE.md @@ -1,408 +1,77 @@ -# CLAUDE.md — gui/ +# Agent instructions: gui/ -Single Go binary plus an embedded Svelte frontend: the browser-facing host for -vision-processor. Owns field geometry, absorbs calibrations from vision -processor instances over multicast, and serves the frontend, a JSON API, a -WebSocket, and debug snapshot images all on one port. +For coding agents working in `gui/`, the Go host and browser interface for ssl-vision-processor. The human docs are +the source of truth; this file is the short list of rules an agent must not miss. -Replaces `python/geom_publisher.py` for anyone running it. Does not replace it -in `setup.sh` or for `python/dataset.py` / `overlap_benchmark.py` / `replay.py`, -which still import it directly — do not delete `geom_publisher.py`. - -User-facing setup is in `README.md`; contributor setup is in `DEVELOPMENT.md`. +- [ARCHITECTURE.md](ARCHITECTURE.md): how the host and frontend are built. Read it before changing design. +- [DEVELOPMENT.md](DEVELOPMENT.md): commands, testing, adding routes, topics and alerts, releasing. +- [README.md](README.md): what users see: flags, files, setup. Keep it in step with user-facing changes. +- [frontend/README.md](frontend/README.md) and [frontend/src/lib/text/README.md](frontend/src/lib/text/README.md): + the frontend's layout, and where its words live. ## Commands -All run from `gui/`. - -``` -make # list the targets -make run # build everything, run the host from the repo root on :8080 (ARGS="..." for flags) -make test # go test -race + the frontend's checks and unit tests -make check # everything CI checks: gofmt, vet, staticcheck, tests, generated files, browser tests -make vulncheck # govulncheck (needs the network; CI reports it, doesn't fail on it) -make e2e # Playwright browser tests (frontend/e2e/): real host, installed Google Chrome -make e2e-cover # make e2e with a coverage-built host, so main's startup shows up (bin/cover/e2e.out) -make generate # rewrite the one committed generated file: the alert codes -make release-check # build the static release, run it as a new user would -make clean # remove everything built, generated or fetched -``` - -Every target builds what it needs first: npm packages (reinstalled when -`package-lock.json` changes), the protobuf bindings, the Redoc bundle, the -OpenAPI spec and the TS types generated from it, the embedded defaults, and -the frontend. - -`proto` (and so every target) needs `git submodule update --init` to have -been run at least once, but no -network beyond that: `buf generate`'s two plugins are both local, not -buf.build remotes. Not using `nix develop`? You need `buf` itself, plus: -`go get -tool google.golang.org/protobuf/cmd/protoc-gen-go` (records the -version in `go.mod`; already a direct dependency so this needs no extra -network fetch) and `npm ci` in `frontend/` (installs `@bufbuild/protoc-gen-es` -from `package.json`). +Run from `gui/`, inside `nix develop` (from the repository root) unless the machine has the tools itself. ``` -cd frontend && npm run dev # Vite HMR on :5173, proxies /api and /ws to :8080 +make test # go test -race, frontend type checks, lint, unit tests, format +make check # everything CI checks, browser tests included +make run # build and run the host on :8080 (ARGS="..." for flags) +make generate # regenerate the alert code list after adding an alert +make release-check # build the static release and run it as a new user would ``` -## Repository layout - -``` -cmd/ssl-vision-processor-gui/ entry point: flags, paths, wiring, HTTP server -internal/ - config/ vision.yml store: working/disk copies, save/load, locked - calibrations, disk watcher, generated config.yml files - defaults/ embedded rulebook fields and robot heights; make copies them in - geometry/ live field template + published calibrations + 1Hz publish loop - multicast/ vision + game controller + tracker sockets, interface selection, - reopened on address/interface changes - discovery/ ssl-vision-processor instances from their SSL_VPConfig announces - api/ typed routes + the OpenAPI spec (/api/openapi.json, /api/docs) - hub/ topic pub/sub + the /ws handler - livefield/ latest detection + autoref tracked frames for the Live Field page - snapshot/ debug image listing/serving - video/ live video: RTP H.264 -> fMP4 over /ws/video/{id} for MSE - v4l/ this host's capture devices, for the camera path picker - supervisor/ -runCameras: runs an ssl-vision-processor per config_path, restarting - it on startup-only setting changes (config.RestartKeys); holds - a camera whose device another already uses - logging/ slog setup: tint console + lumberjack file, plus the last 50 - warnings/errors in memory for the system report, and the last - 1000 records of each level for GET /api/logs (the log panel), - kept whatever -logLevel says - buildinfo/ git state of this repo and proto/, stamped by the Makefile - (scripts/build-ldflags.sh); GET /api/system, the About dialog - vision/ generated Go protobuf, not committed -- run `make proto` (DO NOT EDIT) - gamecontroller/ generated Go protobuf, not committed -frontend/ Svelte 5 + TypeScript + Vite, embedded via //go:embed - (src/proto/ is generated, not committed) -packaging/ the .deb (make deb): nfpm config, systemd units, debconf, - maintainer scripts; nfpm pinned in its own go.mod -scripts/ release-check.sh, deb-check.sh (root, CI only), - deb-version.sh, third-party-notices.sh -buf.gen.yaml generates both internal/{vision,gamecontroller} and - frontend/src/proto from ../proto/proto (the submodule, read - directly -- no vendored copy) -``` - -## Stack - -- **Go 1.22+ `net/http`**, no router library. Method-prefixed patterns - (`"GET /api/health"`) and `{wildcard}` path values do the routing; - `r.PathValue(...)` reads them. -- **`gorilla/websocket`** for `/ws`. Not stdlib; there is no other serious - option (`golang.org/x/net/websocket` is legacy/incomplete). -- **Plain sockets for multicast** (`internal/multicast`: `go-reuseport` plus - `x/net/ipv4`), not `ssl-go-tools/pkg/sslnet`, which the rest of the league - uses. sslnet's `MulticastServer.Stop` dereferences a nil connection if it - never connected, which crashed the host whenever no interface was usable - (a suspend, an unplugged cable); its receiver also listens on one interface - at a time, binds `0.0.0.0` (mixing groups that share a port), and uses an - 8 KB receive buffer. It also leaks the socket when `JoinGroup` fails, and - races `Stop` against its own reconnect. Re-evaluate once ssl-go-tools PR - #29 (`UdpServer`) is released, if it also has a settable receive buffer and - a health accessor (REVIEW.md U-1, U-2); ssl-go-tools is GPL-3.0 and - this repo is Apache-2.0: don't import or copy from it without settling that. -- **`google.golang.org/protobuf` + `protojson`**, never `encoding/json` on a - generated message (see Gotchas). -- **Svelte 5 runes only**, no stores. WebSocket topics come from - `bus.svelte.ts` (`topicState`, `onTopic`), typed by the host's list. -- **flowbite-svelte for every UI element**, with the theme tokens in - `frontend/src/app.css` for color. New UI uses a Flowbite component where one - exists (Button, Input, Select, Toggle, Range, Alert, Helper, Toast, Card, - ...) and Tailwind utilities for layout, not hand-written CSS for controls. - Settings forms use `FormRow.svelte` (label, control, gated notes, messages) - inside `SettingsCard.svelte`. There is no base-layer style for raw - `