Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(cloud): enhance VXControl Cloud API usage and add PentAGI version checks
Dmitry Ng6f34a010e1f4
diff --git a/.env.example b/.env.exampleindex 81e4f908..9e52ae73 100644--- a/.env.example+++ b/.env.example@@ -57,6 +57,10 @@ JAEGER_IMAGE=jaegertracing/all-in-one:1.56.0## An unrecognised value falls back to preview.UPDATE_STRATEGY=+## How often the server checks PentAGI Cloud API for a newer available version+## (shown as a version badge in the web UI), as a Go duration.+UPDATE_CHECK_INTERVAL=+## PentAGI Cloud API endpoint, as host[:port] — the client always uses HTTPS, so a## scheme here is redundant and a path is ignored. Leave empty for update.pentagi.com.UPDATE_SERVER_HOST=diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f6bc8210..29071f3b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -112,6 +112,22 @@ jobs:run: go mod downloadcontinue-on-error: true+ # The installer embeds the deployment descriptors it extracts onto a host —+ # the compose files, the observability configuration, the Jaeger plugin — and+ # that embedded copy is GENERATED from symlinks in cmd/installer/files/links,+ # not committed (see cmd/installer/files/.gitignore).+ #+ # It has to run before the tests, not only before a build: the checker's+ # compose-consistency tests read the generated copy, because that copy is what+ # a host actually gets. Without this step they fail on a missing file, and an+ # installer built in this workflow would ship compose files with the image tags+ # hardcoded instead of the ${COMPONENT_IMAGE:-default} variables the update+ # mechanism writes into — an update that resolves correctly and then applies+ # nothing.+ - name: Backend - Generate embedded installer files+ working-directory: backend/cmd/installer/files+ run: go run generate.go+- name: Backend - Lintuses: golangci/golangci-lint-action@v9with:diff --git a/.vscode/launch.json b/.vscode/launch.jsonindex bde7768a..dabce03d 100644--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -5,7 +5,8 @@"type": "go","request": "launch","name": "Launch Go Backend",- "program": "${workspaceFolder}/backend/cmd/pentagi/main.go",+ "program": "${workspaceFolder}/backend/cmd/pentagi/",+ "buildFlags": "-ldflags='-X pentagi/pkg/version.PackageName=pentagi -X pentagi/pkg/version.PackageVer=2.1.0 -X pentagi/pkg/version.PackageRev=93e99748'","envFile": "${workspaceFolder}/.env","env": {"CORS_ORIGINS": "http://localhost:*,https://localhost:*",@@ -76,6 +77,7 @@// "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.5-27b-fp8.provider.yml",// "-config", "${workspaceFolder}/examples/configs/vllm-qwen332b-fp16.provider.yml",// "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.6-27b-fp8.provider.yml",+ // "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.8-27b-fp8.provider.yml",// "-config", "${workspaceFolder}/examples/configs/vllm-mixed.provider.yml",// "-config", "${workspaceFolder}/examples/configs/hcnsec.provider.yml",// "-config", "${workspaceFolder}/examples/configs/custom-openai.provider.yml",@@ -96,6 +98,7 @@// "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.5-27b-fp8.report.md",// "-report", "${workspaceFolder}/examples/tests/vllm-qwen332b-fp16-report.md",// "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.6-27b-fp8.report.md",+ // "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.8-27b-fp8.report.md",// "-report", "${workspaceFolder}/examples/tests/vllm-mixed.report.md","-report", "${workspaceFolder}/examples/tests/moonshot-report.md",// "-report", "${workspaceFolder}/examples/tests/deepseek-report.md",diff --git a/Dockerfile b/Dockerfileindex 04ae03c2..5fdb657a 100644--- a/Dockerfile+++ b/Dockerfile@@ -199,6 +199,11 @@ USER pentagiENTRYPOINT ["/opt/pentagi/bin/entrypoint.sh", "/opt/pentagi/bin/pentagi"]+# Version of the PentAGI binary inside+ARG PACKAGE_VER+ARG PACKAGE_REV+LABEL com.pentagi.version="${PACKAGE_VER:-develop}${PACKAGE_REV:+-${PACKAGE_REV}}"+# Image MetadataLABEL org.opencontainers.image.source="https://github.com/vxcontrol/pentagi"LABEL org.opencontainers.image.description="Fully autonomous AI Agents system capable of performing complex penetration testing tasks"diff --git a/backend/cmd/installer/checker/components.go b/backend/cmd/installer/checker/components.goindex 2e979b67..2b46bd2a 100644--- a/backend/cmd/installer/checker/components.go+++ b/backend/cmd/installer/checker/components.go@@ -22,11 +22,16 @@ import (// told, so a component left out comes back as "nothing to report" — which reads exactly// like "up to date" and is the more dangerous of the two mistakes.-// maxReportedComponents is the server-side ceiling on one request. The inventory is well-// under it today, but the list grows with every stack, so the limit is enforced here and-// what gets dropped is written to the log — a silently truncated list would report the-// remaining components as complete.-const maxReportedComponents = 30+// maxReportedComponents is the server-side ceiling on one request, and it IS the+// contract's constant rather than a number that agrees with it today. A local literal+// can only be wrong in two ways, and both are silent: too high and the service refuses+// the whole request — losing the answer for every component, not just the ones past the+// bound — too low and the tail is trimmed here while the service would have taken it.+//+// The inventory is well under it, but the list grows with every stack, so the limit is+// enforced before sending and what gets dropped is written to the log: a silently+// truncated list would report the remaining components as complete.+const maxReportedComponents = models.MaxReportedComponents// JaegerPluginDir holds the Jaeger storage plugin, relative to the directory the// environment file lives in.diff --git a/backend/cmd/installer/checker/components_test.go b/backend/cmd/installer/checker/components_test.goindex eed70e01..964d5e9d 100644--- a/backend/cmd/installer/checker/components_test.go+++ b/backend/cmd/installer/checker/components_test.go@@ -173,6 +173,16 @@ func TestInventoryFitsTheRequestCeiling(t *testing.T) {t.Fatalf("the inventory is %d components, above the %d a request carries: "+"some would be dropped and never reported on", total, maxReportedComponents)}++ // The ceiling has to BE the contract's, not a number that matches it today. Too+ // high and the service refuses the whole request, costing the answer for every+ // component; too low and the tail is trimmed here while the service would have+ // accepted it. Both are invisible from inside this package, because every other+ // test in this file measures against this same constant.+ if maxReportedComponents != models.MaxReportedComponents {+ t.Errorf("the installer caps a request at %d artefacts, the contract at %d",+ maxReportedComponents, models.MaxReportedComponents)+ }}// TestEveryReportedComponentIsInTheListForItsKind.diff --git a/backend/cmd/installer/checker/product_info.go b/backend/cmd/installer/checker/product_info.goindex 16378b95..cc9ea5e4 100644--- a/backend/cmd/installer/checker/product_info.go+++ b/backend/cmd/installer/checker/product_info.go@@ -11,6 +11,7 @@ import ("github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"+ "github.com/vxcontrol/cloud/models")// productInfoCommand asks the running product to describe its own state.@@ -28,7 +29,13 @@ const productInfoTimeout = 20 * time.Second// The contract that carries this field refuses anything larger, so reading more// would only build a request the service rejects whole — losing the answer for// every component along with it.-const maxProductInfoBytes = 64 * 1024+//+// It is the contract's own constant rather than a number that agrees with it+// today. This was written as 64 KiB against a 16 KiB contract: a product whose+// description landed in between passed every check here and cost the installation+// the answer for all of its components, and the local test could not see it+// because it measured against this same constant.+const maxProductInfoBytes = models.MaxProductInfoBytes// gatherProductInfo asks the running product for its state and returns it exactly// as it was given.diff --git a/backend/cmd/installer/checker/product_info_test.go b/backend/cmd/installer/checker/product_info_test.goindex 4839a460..028650bb 100644--- a/backend/cmd/installer/checker/product_info_test.go+++ b/backend/cmd/installer/checker/product_info_test.go@@ -8,6 +8,7 @@ import ("testing""github.com/moby/moby/api/pkg/stdcopy"+ "github.com/vxcontrol/cloud/models")// frame writes one chunk the way the docker daemon does on a non-TTY exec: an@@ -109,6 +110,41 @@ func TestNothingThatIsNotADocumentIsCarried(t *testing.T) {}}+// TestTheDocumentBoundIsTheContractsOwn.+//+// The bound here has one job: never build a request the service will refuse whole.+// That makes it the CONTRACT's number, and asserting it as a literal is what let it+// be wrong — it stood at 64 KiB against a 16 KiB contract, and every other test in+// this file measures against the same constant, so they all agreed with each other+// and none of them agreed with the server.+//+// Both halves are pinned: that the constant IS the contract's, and that a document+// one byte over the contract is refused. The second would still fail if somebody+// reintroduced a local number that happened to be larger.+func TestTheDocumentBoundIsTheContractsOwn(t *testing.T) {+ if maxProductInfoBytes != models.MaxProductInfoBytes {+ t.Errorf("the installer accepts %d bytes, the contract accepts %d — a document in "++ "between costs the whole update check", maxProductInfoBytes, models.MaxProductInfoBytes)+ }++ padding := models.MaxProductInfoBytes // the envelope around it pushes this over+ oversized := `{"schema":1,"padding":"` + strings.Repeat("x", padding) + `"}`+ if len(oversized) <= models.MaxProductInfoBytes {+ t.Fatalf("the fixture is not oversized: %d bytes (test bug)", len(oversized))+ }+ if info := productInfoFromOutput([]byte(oversized)); info != nil {+ t.Errorf("a document of %d bytes was carried into a request the contract bounds at %d",+ len(oversized), models.MaxProductInfoBytes)+ }++ // And one that fits is still carried: a bound that refuses everything would+ // pass the assertion above and quietly drop the document on every check.+ fitting := `{"schema":1,"version":"0.9.3"}`+ if info := productInfoFromOutput([]byte(fitting)); info == nil {+ t.Error("a document well inside the bound was dropped")+ }+}+// TestADocumentIsCarriedWithoutBeingUnderstood.//// The installer and the product ship separately, so anything the installer knewdiff --git a/backend/cmd/installer/cloud/calls_test.go b/backend/cmd/installer/cloud/calls_test.goindex f0ff2b62..e7525e0b 100644--- a/backend/cmd/installer/cloud/calls_test.go+++ b/backend/cmd/installer/cloud/calls_test.go@@ -305,10 +305,16 @@ func TestDownloadPackageRefusesAMalformedRequestBeforeSending(t *testing.T) {},}- // Only file-distributed components can be downloaded; an image component has no- // package behind it.+ // Only components an executable is published for can be downloaded, and neo4j is+ // somebody else's container image — there is no file behind it under any+ // circumstances.+ //+ // Deliberately NOT pentagi, which is the one component where "delivered as an+ // image" and "has no package" came apart: it ships an executable a running+ // product can replace itself with, so it is a valid download and would make this+ // test pass for the wrong reason.request := models.DownloadPackageRequest{- Component: models.ComponentTypePentagi,+ Component: models.ComponentTypeNeo4j,Version: "2.0.0",OS: models.OSTypeLinux,Arch: models.ArchTypeAMD64,diff --git a/backend/cmd/pentagi/info.go b/backend/cmd/pentagi/info.gonew file mode 100644index 00000000..08cb2e80--- /dev/null+++ b/backend/cmd/pentagi/info.go@@ -0,0 +1,135 @@+package main++import (+ "context"+ "database/sql"+ "fmt"+ "io"+ "os"+ "time"++ "pentagi/pkg/config"+ "pentagi/pkg/database"+ "pentagi/pkg/providers"+ "pentagi/pkg/providers/embeddings"++ "github.com/sirupsen/logrus"+)++// infoFlag prints a description of this server and exits.+const infoFlag = "-info"++// infoDeadline bounds the whole description. Chosen so that a caller which gave+// this process ten seconds still gets a document rather than a killed process,+// and so that a database answering slowly costs a `skipped` entry instead of a+// wait nobody budgeted for.+const infoDeadline = 8 * time.Second++// wantsInfo reports whether the process was asked to describe itself.+//+// Argument parsing rather than the flag package: the server takes no flags at+// all, and introducing a FlagSet would make every unrecognised argument a fatal+// error for a program that has always ignored them.+func wantsInfo(args []string) bool {+ for _, arg := range args {+ if arg == infoFlag || arg == "--info" {+ return true+ }+ }+ return false+}++// runInfo writes the current state of this server to stdout as JSON.+//+// stdout carries the document and nothing else. Framework logging is silenced+// rather than merely redirected: a library that decides to greet the operator+// would otherwise land in the middle of the document, and whoever reads this+// output is entitled to hand it straight to a JSON parser. Diagnostics go to+// stderr, where they belong and where they cannot corrupt the result.+//+// A document is produced even when the database cannot be reached. The parts+// that could not be gathered are named in `skipped`, which is a description of a+// server that is having trouble — still more useful than an error, and honest in+// a way that a page of zeroes would not be.+func runInfo(ctx context.Context) int {+ logrus.SetOutput(io.Discard)++ // A ceiling on the whole description, not just on each part of it. Every+ // aggregate has its own deadline, but a database that accepts connections and+ // then stops answering would let them run one after another — thirteen times+ // three seconds is not a flag anybody wants to wait for, and whoever runs this+ // programmatically gives up long before that and reports nothing at all.+ ctx, cancel := context.WithTimeout(ctx, infoDeadline)+ defer cancel()++ cfg, err := config.NewConfig()+ if err != nil {+ fmt.Fprintf(os.Stderr, "cannot load configuration: %v\n", err)+ return 1+ }++ // The tenant's schema has to be on the search_path or every count reads the+ // wrong rows — or none. This is the read-only half of the tenant bootstrap:+ // it rewrites the DSN and never touches the catalog, which is what a flag+ // that only describes things is allowed to do.+ if err := database.RewriteDatabaseURLForTenant(cfg); err != nil {+ fmt.Fprintf(os.Stderr, "cannot resolve tenant schema: %v\n", err)+ return 1+ }++ options := database.SummaryOptions{+ Features: database.InstanceFeatures{+ Debug: cfg.Debug,+ AskUser: cfg.AskUser,+ DockerInside: cfg.DockerInside,+ AssistantUseAgents: cfg.AssistantUseAgents,+ },+ OAuth: configuredOAuthProviders(cfg),+ DefaultProviders: providers.EnabledDefaultProviderTypes(cfg),+ EmbeddingProvider: embeddings.ResolvedProviderType(cfg),+ }++ // sql.Open does not connect, so an unreachable database costs nothing here+ // and shows up as skipped aggregates below — which is the intended shape.+ db, err := sql.Open("postgres", cfg.DatabaseURL)+ if err != nil {+ fmt.Fprintf(os.Stderr, "cannot open database: %v\n", err)+ return 1+ }+ defer db.Close()++ // One connection and a short life: this process exists for a fraction of a+ // second and must not take a slot from the server that is actually running.+ db.SetMaxOpenConns(1)+ db.SetConnMaxLifetime(time.Minute)++ summary := database.New(db).GetInstanceSummary(ctx, options)++ encoded, err := summary.MarshalIndent()+ if err != nil {+ fmt.Fprintf(os.Stderr, "cannot render the summary: %v\n", err)+ return 1+ }++ fmt.Println(string(encoded))+ return 0+}++// configuredOAuthProviders names the sign-in providers this server offers.+//+// The names of the providers, never of a user. A provider counts as configured+// under exactly the conditions the router uses to register it, so this list+// cannot claim a sign-in route that does not exist.+func configuredOAuthProviders(cfg *config.Config) []string {+ providers := []string{}+ if cfg.PublicURL == "" {+ return providers+ }+ if cfg.OAuthGoogleClientID != "" && cfg.OAuthGoogleClientSecret != "" {+ providers = append(providers, "google")+ }+ if cfg.OAuthGithubClientID != "" && cfg.OAuthGithubClientSecret != "" {+ providers = append(providers, "github")+ }+ return providers+}diff --git a/backend/cmd/pentagi/main.go b/backend/cmd/pentagi/main.goindex ecf3715a..a3511c5b 100644--- a/backend/cmd/pentagi/main.go+++ b/backend/cmd/pentagi/main.go@@ -22,6 +22,7 @@ import ("pentagi/pkg/observability/profiling""pentagi/pkg/providers"router "pentagi/pkg/server"+ "pentagi/pkg/server/update""pentagi/pkg/version""github.com/jackc/pgx/v5/pgxpool"@@ -41,6 +42,13 @@ func main() {)defer cancelOnSignal()+ // Before anything is logged or started. `-info` describes this server and+ // exits, and its output is a JSON document on stdout — a greeting printed+ // first would be the first thing a reader has to strip back out.+ if wantsInfo(os.Args[1:]) {+ os.Exit(runInfo(ctx))+ }+logrus.Infof("Starting PentAGI %s", version.GetBinaryVersion())cfg, err := config.NewConfig()@@ -165,6 +173,25 @@ func main() {logrus.Info("Database schema updated successfully")+ // Keep the update service informed about this installation, periodically.+ // After the migrations, deliberately: on a first boot the tables it reads do+ // not exist until this point, and a summary of a schema that is not there yet+ // describes an installation with nothing in it — which is also what an+ // installation nobody uses looks like.+ //+ // A goroutine that owns nothing: it reads, it sends, and every failure along+ // the way is a debug line. A server must not fail to start because something+ // it only talks to is unreachable. What it learns is handed to the router, so+ // the UI can show whether this build is current; nil means it never runs, and+ // the UI says so.+ var updates *update.Service+ if built, err := update.New(cfg, queries); err != nil {+ logrus.WithError(err).Debug("update service integration is not configured")+ } else {+ updates = built+ go updates.Run(ctx)+ }+if cfg.PprofAddr != "" {go profiling.Start(cfg.PprofAddr)}@@ -185,7 +212,7 @@ func main() {logrus.WithError(err).Fatal("Active flows restoration failed")}- r := router.NewRouter(queries, orm, cfg, providers, controller, subscriptions, client)+ r := router.NewRouter(queries, orm, cfg, providers, controller, subscriptions, client, updates)// Launch HTTP/HTTPS server in background goroutineserverErrChan := make(chan error, 1)diff --git a/backend/docs/config.md b/backend/docs/config.mdindex 923a51d8..9c3e1f0b 100644--- a/backend/docs/config.md+++ b/backend/docs/config.md@@ -17,6 +17,11 @@ This document serves as a comprehensive guide to the configuration system in Pen- [Extensions installed outside `public` (`DATABASE_EXTENSIONS_SCHEMA`)](#extensions-installed-outside-public-database_extensions_schema)- [Multi-tenant PostgreSQL access through PgBouncer](#multi-tenant-postgresql-access-through-pgbouncer)- [Multi-tenant PostgreSQL through Supabase's Supavisor pooler (`DATABASE_SEARCH_PATH_VIA_OPTIONS`)](#multi-tenant-postgresql-through-supabases-supavisor-pooler-database_search_path_via_options)+ - [PentAGI Cloud API Settings](#pentagi-cloud-api-settings)+ - [`UPDATE_STRATEGY`](#update_strategy)+ - [`UPDATE_CHECK_INTERVAL`](#update_check_interval)+ - [`UPDATE_SERVER_HOST`](#update_server_host)+ - [`SUPPORT_SERVER_HOST`](#support_server_host)- [Usage Details](#usage-details)- [Docker Settings](#docker-settings)- [Worker Docker Access (`DOCKER_INSIDE_*`)](#worker-docker-access-docker_inside_)@@ -80,13 +85,13 @@ This document serves as a comprehensive guide to the configuration system in Pen- [Data Flow, Search, and Tenancy](#data-flow-search-and-tenancy)- [Deployment Ownership](#deployment-ownership)- [Agent Supervision Settings](#agent-supervision-settings)- - [Usage Details](#usage-details-13)+ - [Usage Details](#usage-details-12)- [Supervision System Integration](#supervision-system-integration)- [Recommended Settings](#recommended-settings)- [Observability Settings](#observability-settings)- [Telemetry](#telemetry)- [Langfuse](#langfuse)- - [Usage Details](#usage-details-14)+ - [Usage Details](#usage-details-13)## Configuration Basics@@ -156,6 +161,10 @@ These settings control basic application behavior and are foundational for the s| DockerPortsBase | `DOCKER_PORTS_BASE` | `0` (means `28000`) | First host port for per-flow sandbox port publishing; each instance owns `[base, base+2000)` || InstallationID | `INSTALLATION_ID` | *(none)* | Unique installation identifier for PentAGI Cloud API communication || LicenseKey | `LICENSE_KEY` | *(none)* | License key for PentAGI Cloud API authentication and feature activation |+| UpdateStrategy | `UPDATE_STRATEGY` | `preview` | Which builds this installation is offered: `nightly`, `preview` or `stable`. An unrecognised value falls back to `preview`. See [PentAGI Cloud API Settings](#pentagi-cloud-api-settings). |+| UpdateCheckInterval | `UPDATE_CHECK_INTERVAL` | `3h` | How often the running server reports its own state to the Cloud API. `0` disables the report. See [PentAGI Cloud API Settings](#pentagi-cloud-api-settings). |+| UpdateServerHost | `UPDATE_SERVER_HOST` | `update.pentagi.com` | PentAGI Cloud API endpoint as `host[:port]`, **without a scheme** — the connection is always HTTPS. See [PentAGI Cloud API Settings](#pentagi-cloud-api-settings). |+| SupportServerHost | `SUPPORT_SERVER_HOST` | `support.pentagi.com` | PentAGI Support API endpoint as `host[:port]`, same shape as `UPDATE_SERVER_HOST`. See [PentAGI Cloud API Settings](#pentagi-cloud-api-settings). |### Multi-Instance Deployment (`TENANT_ID`)@@ -262,6 +271,62 @@ This sends the tenant's search_path as `options=--search_path=<tenant>,<DATABASEThis flag changes nothing for a direct PostgreSQL connection or a PgBouncer setup already following the recipe above; both accept `search_path` and `options` equally, so there is no reason to enable it outside a Supavisor-fronted deployment.+### PentAGI Cloud API Settings++These four are **shared**: one value in one `.env`, read by the installer and by the running PentAGI server alike. The server parses them into the `Config` struct as `UpdateServerHost`, `UpdateStrategy`, `UpdateCheckInterval` and `SupportServerHost`, and `docker-compose.yml` passes all four into the container; the installer's own calls read them straight from the file, and its *Server Settings* form edits every one of them except `UPDATE_CHECK_INTERVAL`, which concerns only the server and is set by hand. There is deliberately no per-component variant of any of them — an installation that pointed the installer at one endpoint and the server at another would be talking about itself in two places at once.++`UPDATE_SERVER_HOST`, together with `INSTALLATION_ID` and `LICENSE_KEY`, is behind every call either side makes to the PentAGI Cloud API: the update check the installer runs while gathering the state of the machine, the package info and download calls behind the installer build it offers, the same pair of calls used to fetch the Jaeger ClickHouse storage plugin whenever the observability stack is updated — that plugin is a file mounted into the container rather than an image, so a broken `UPDATE_SERVER_HOST` stops it from being installed as surely as it stops a check — and the running server's own periodic report, described under [`UPDATE_CHECK_INTERVAL`](#update_check_interval). `UPDATE_STRATEGY` travels only in the update check; the package calls name a component, a version and a platform, and nothing else.++Both sides honour `PROXY_URL`. The installer's own proxy setting takes precedence over `HTTP_PROXY`/`HTTPS_PROXY` in the environment, because it is the one the operator configured deliberately and often the only one carrying credentials. See [Network and Proxy Settings](#network-and-proxy-settings).++#### `UPDATE_STRATEGY`++Which builds this installation is offered. The value is trimmed and lower-cased before it is matched, so `NIGHTLY` and ` preview ` are accepted. Empty means `preview`; an unrecognised value logs a warning and also falls back to `preview`, deliberately, because a typo must not leave an installation quietly unable to hear about security updates.++| Value | What the installation is offered |+| --- | --- |+| `preview` (default) | Pre-release builds from the channels this installation already follows, offered as soon as they are published, without waiting for a release to be cut. The version, changelog and release notes that come with the answer still describe the stack's latest *release*, so they name the last release crossed and not the preview build itself. |+| `stable` | Only artefacts belonging to the latest curated stable release. The whole installation moves onto one released set, which is what lets it be described by a single version. A component that release does not cover is answered `unknown` with a reason rather than a newer build from elsewhere — offering part of an installation from outside the curated set is exactly the promise `stable` makes. |+| `nightly` | The newest build published, with no release attached to it. The answer carries no version metadata, so the update overview can report that a newer build exists and little else about it. |++The default is `preview` rather than `stable`, and the difference is not caution versus eagerness. Under `stable` the answer is measured against curated releases, so a stack with no published release is offered nothing at all — which reads as "no updates exist" when it means "we are not publishing releases for this yet". `preview` follows the channels the client is already on, which is what an installation wants until releases are something it can rely on.++The strategy is sent with each update check and applies to every stack in the answer, including the installer's own build — so it also decides which installer version is offered for download. Offered, not applied: the installer downloads that build next to the environment file under a name carrying its version, verifies it, and prints the command that moves it into place. It never writes over the binary it is running — a process cannot reliably replace its own executable, so "download the installer" and "update the installer" are the same operation, and putting the new build in place stays a deliberate step the operator takes.++#### `UPDATE_CHECK_INTERVAL`++How often the **running server** reports its own state to the Cloud API, as a Go duration (`3h` by default, `90m` and `1h30m` are the same value). `0`, or any negative value, disables the report entirely.++This is the other half of the picture the update check cannot see. An installer's check describes the artefacts on the machine and says nothing about the server itself, so an installation deployed once and never started looks exactly like one in daily use. The report closes that gap: on each tick it sends the build that is running, the platform it was compiled for, the sha256 of that binary, and a summary of how the server is configured — quantities and closed vocabularies produced by `GetInstanceSummary`, nothing that identifies a person and nothing anybody wrote. Those first three are read off this process and travel **inside** the summary as well as beside it, because the same summary is what `-info` prints for a caller that will forward it: whoever carries a description cannot produce the platform of the process that wrote it, and the executable's digest is not something an image digest can stand in for.++The answer is kept in memory and shown in the web UI as a version badge — in the main sidebar header and at the bottom of the settings sidebar — read through the `versionInfo` GraphQL query (permission `settings.view`). The badge shows a yellow **↓** when the service names a newer version, and a yellow **?** whenever no verdict is available: the first check has not completed yet, the service could not be reached, it answered without naming a version to move to, it could not match the running build to a published release, or checks are disabled. A verdict, once reached, outlives the failures that follow it — an update that was available an hour ago is still available — so a badge keeps its arrow through an outage and the popover dates both the last answer and the last failure. Nothing is applied from the UI: the tooltip and the popover say to run the installer.++Two properties are worth knowing when reading logs. The first send is delayed by a random wait of up to two minutes, so a fleet restarted at once does not arrive as one burst. And nothing here can interrupt the product: a missing or malformed `INSTALLATION_ID` means the service is never built, every later failure is a debug line, and the next tick simply tries again — an endpoint that is down or a licence that has expired are ordinary states of the world for something the server does not depend on.++#### `UPDATE_SERVER_HOST`++The address is `host[:port]` with **no scheme** — the connection is always TLS, so writing one is redundant. Empty, which is the normal case, means `update.pentagi.com`.++A full URL is still accepted because this setting historically held one: an `https://` prefix is stripped, so is anything after the host (path, query string, fragment), surrounding whitespace is trimmed, and the remainder is lower-cased. What has to be left over is a host, and five shapes are refused outright rather than repaired:++| Value | Result |+| --- | --- |+| `http://update.example.com` | **Rejected.** The transport is HTTPS-only, and silently upgrading a value someone deliberately wrote as `http` would hide the misconfiguration instead of reporting it. |+| Any other scheme (`ftp://`, `tcp://`, ...) | **Rejected** as unsupported. |+| `https://` or `https:///some/path` | **Rejected** — dropping the scheme and the path leaves nothing, so there is no host to connect to. |+| `user:[email protected]` | **Rejected** — credentials in the host are not supported. Authentication to the Cloud API is `LICENSE_KEY`, and a proxy's credentials belong in `PROXY_URL`. |+| `update .example.com` (a space or a tab inside the host) | **Rejected.** Whitespace around the value is trimmed, but whitespace inside it is a typo rather than an address. |++Writing a scheme is the common mistake here, and `https://…` being tolerated makes `http://…` look like it should work too. A rejected value does not abort the installer: the client is never built, the update check is recorded as failed with the reason `unreachable`, and the reason is written to the installer log. The visible symptom is therefore an unreachable update server, which is worth checking the log about before concluding the server is actually down.++The repairs and the refusals above are the installer's. The running server hands the value to the Cloud SDK as written — nothing normalises it and nothing reports it — so a value the SDK cannot build a client from costs one debug line at startup and then no product report at all. Write a bare host and both sides agree.++#### `SUPPORT_SERVER_HOST`++The PentAGI Support API endpoint, in exactly the shape `UPDATE_SERVER_HOST` takes: `host[:port]`, no scheme, empty meaning `support.pentagi.com`. It is a separate service from the update endpoint and is configured separately, so that an installation reaching the Cloud API through a mirror or an internal proxy can point the two at different places.++It is written by the installer's *Server Settings* form and parsed by the server, and no call targets it yet — the support integration that will use it is not in place. Setting it today changes nothing; leaving it empty costs nothing either.+### Usage Details- **DatabaseURL**: This is a critical setting used throughout the application for all database connections. It is used to:diff --git a/backend/docs/installer/checker-test-scenarios.md b/backend/docs/installer/checker-test-scenarios.mdindex 97f4aa85..dc7e2d63 100644--- a/backend/docs/installer/checker-test-scenarios.md+++ b/backend/docs/installer/checker-test-scenarios.md@@ -2,6 +2,8 @@This document outlines test scenarios for the installer's system checking functionality, focusing on failure modes and their detection.+The scenarios fall into two groups. The first is what the checker observes about this machine — Docker, disk, memory, local connectivity. The second is what the PentAGI Cloud API answers, and there the interesting part is that a failed call is not one condition: "the server could not be reached", "the daily allowance is spent" and "this license tier has no access" need different things from the user, and each has its own reason code and its own test.+## Test Scenarios### 1. Docker Not Installed@@ -42,29 +44,40 @@ This document outlines test scenarios for the installer's system checking functi- UI shows: "Write Permissions Required" with chmod instructions### 6. Network Issues - DNS Failure-**Setup**: Block DNS resolution (modify /etc/hosts or firewall)+**Setup**: Break name resolution itself — firewall port 53, or point the resolver at a dead server. Adding `127.0.0.1 docker.io` to /etc/hosts does **not** trigger this: the name resolves, and what fails is scenario 7.**Expected**:- `SysNetworkFailures`: ["• DNS resolution failed for docker.io"]+- `SysNetworkOK`: false- UI shows specific DNS failure with resolution steps+The probe is a plain host lookup and it never goes through `PROXY_URL`. On a network where only the proxy can resolve names, this line appears while everything the installer actually does works — treat it as a hint, not a verdict.+### 7. Network Issues - HTTPS Blocked-**Setup**: Block outbound HTTPS (port 443)+**Setup**: Block outbound HTTPS (port 443), or point docker.io at a closed port**Expected**:- `SysNetworkFailures`: ["• Cannot reach external services via HTTPS"]- UI shows HTTPS failure with proxy configuration info+The probe is a 5-second GET to https://docker.io through `PROXY_URL` when one is set, and **any answer below 500 counts as reachable** — an interception proxy replying 403 to the probe passes it. It says the path is open, not that the registry is usable.+### 8. Network Issues - Docker Registry Blocked-**Setup**: Block docker.io specifically+**Setup**: Block docker.io for the Docker daemon**Expected**:- `SysNetworkFailures`: ["• Cannot pull Docker images from registry"]- UI shows registry access failure+The probe pulls `debian:latest` and succeeds if **either** the main daemon or the worker daemon can pull it, so a broken remote worker alone does not raise this line. It is skipped entirely when either client is absent — an unreachable daemon is scenarios 2-4, not this one.+### 9. Behind Corporate Proxy-**Setup**: Network requires proxy, but not configured+**Setup**: Network requires a proxy; `PROXY_URL` unset, or set while the daemon has no proxy of its own**Expected**:- Multiple network failures- UI shows proxy configuration instructions for HTTP_PROXY/HTTPS_PROXY+Only the HTTPS probe uses `PROXY_URL`. The lookup resolves locally, and the pull goes through the Docker daemon with the daemon's own proxy configuration — so a correctly configured `PROXY_URL` can still leave two of the three lines standing.++**None of these three probes touches update.pentagi.com.** `SysNetworkOK` is not evidence that the update check will work, and a failed update check is not evidence that the registry is blocked. The update server has its own scenarios below.+### 10. Low Memory**Setup**: System with < 2GB available RAM**Expected**:@@ -85,6 +98,135 @@ This document outlines test scenarios for the installer's system checking functi- `WorkerEnvApiAccessible`: false- UI shows worker environment troubleshooting+## Update Server Scenarios++The installer talks to the PentAGI Cloud API over three calls — `POST /api/v1/proxy/updates/check`, `GET /api/v1/proxy/packages/info` and `GET /api/v1/proxy/packages/download`. Every one of them negotiates TLS and solves a proof-of-work challenge before the request is sent, so there is no local server to point the installer at: these scenarios are exercised in unit tests by substituting the call function with the error the transport would have produced (`cmd/installer/cloud/calls_test.go`, `cmd/installer/cloud/errors_test.go`), and observed in the field the way a support case arrives.++A call that produces no answer is classified into one of eight reasons. The distinction is the whole point — a spent allowance and a broken proxy call for opposite reactions, and collapsing them into one "update server unavailable" flag tells the user nothing they can act on.++| `reason` | What it means | `retryable` | `retry_after` |+|---|---|---|---|+| `unreachable` | never reached a verdict: no network, no DNS, refused proxy, connection died mid-flight | true | — |+| `timeout` | a deadline: the caller's, or the proof-of-work budget | true | — |+| `rate_limited` | too many requests in a rolling window | true | when the server sent one |+| `quota_exceeded` | the allowance for the period is spent | true | when the server sent one |+| `forbidden` | the license tier has no access to this call, or the client is blocked | false | — |+| `not_found` | no such package or version — an answer, not an outage | false | — |+| `rejected` | the server refused the request as malformed | false | — |+| `server_error` | the server failed on its side | true | — |++**What holds for every failed update check**, and is worth asserting in each scenario below:++- `UpdateServerAccessible`: false, `StackUpdates`: nil, and **all six** per-stack verdicts (`PentagiIsUpToDate`, `WorkerIsUpToDate`, `InstallerIsUpToDate`, `GraphitiIsUpToDate`, `LangfuseIsUpToDate`, `ObservabilityIsUpToDate`) reset to false. Leaving one behind is how a verdict from an earlier successful check gets presented as a current one, with nothing on screen to suggest it is old — the worker flag was the one that used to be missed.+- `update_failure`: `{reason, message, retry_after, retryable}` on the check result, plus a warning line `update check failed (<reason>): <error>` in the log.+- The gather continues. A check that could not be made is a fact about the installation, not a reason to abandon everything else the checker learned, so no other field is affected.+- The update overview screen says the check did not complete and that applying an update will pull whatever the compose files currently point at. It must **never** print "Everything is up to date" — that sentence belongs to an answer that arrived and listed nothing.+- The "Update Installer" entry disappears from Maintenance: it requires the server, and without a package description there is nothing that could be verified. The "Update PentAGI" entry stays **for any stack that is installed**, because none of them is known to be current — it leads to the overview, which says exactly that. On a machine with no compose stack installed the entry is absent whatever the check did: the offer is gated on a stack being installed *and* not up to date, so resetting the verdicts is only half of what makes it appear.+- The reason and the cooldown are what separate these scenarios; the overview's failure text is currently the same sentence for all of them. Assert the reason on the check result and in the log, not a per-reason wording that does not exist.++### 1. Update Server Unreachable+**Setup**: point `UPDATE_SERVER_HOST` at a name that does not resolve or a host that drops 443, or set `PROXY_URL` to a port nothing listens on+**Expected**:+- `update_failure.reason`: "unreachable", `retryable`: true, `retry_after`: 0+- `message` carries the transport error (`dial tcp ...`, proxy refused, TLS failure)+**Must not**:+- claim any stack is up to date, or keep the previous answer on screen+- be read as evidence about the Docker registry — that is scenarios 6-8, a different probe against a different host++A configuration the client refuses to build with never becomes a call at all: `UPDATE_SERVER_HOST=http://...` is an error rather than a silent upgrade to https (a user who wrote `http` meant it), as is a `PROXY_URL` with no host. It is still recorded as a failed check, but as an *unclassified* error — `reason` falls back to "unreachable" and `retryable` stays false, while the message names the setting. Read the message before blaming the network.++### 2. Proof-of-Work Challenge Times Out+**Setup**: in tests, return the SDK's challenge-timeout error from the substituted call. In the field it appears on CPU-limited VMs and throttled laptops — **do not manufacture load to reproduce it**; record the host it happened on instead.+**Expected**:+- `update_failure.reason`: "timeout", `retryable`: true+- The budget is 60 seconds per call, deliberately double the SDK default, because slow hardware genuinely needs the extra seconds+**Must not**:+- be presented as a network failure. The network was fine and the client ran out of budget; the two lead to opposite investigations, which is the entire reason this reason exists.+- be assumed to have been retried. A timed-out challenge is not retried by the transport — if a retry is wanted, the installer has to make it.++### 3. Request Rate Limited+**Setup**: several checks inside one rolling window. Note how easily this happens: each update step refreshes the answer in a deferred call, and updating everything recurses over the stacks — one press of "Update PentAGI" is therefore one check per stack touched, not one check. A limit sized for a single request breaks the client instead of throttling it.+**Expected**:+- `update_failure.reason`: "rate_limited", `retryable`: true+- `retry_after`: the server-advertised cooldown when it sent one, 0 otherwise. It is recorded on the check result and rendered nowhere — the overview prints its single failure sentence and the operation panel prints `failed to check updates: <message>`. Assert the value on the result, not a screen that tells the user when to come back: that screen does not exist yet.+**Must not**:+- retry in a tight loop. The per-minute and general limits are already retried by the transport (up to three attempts, waiting the advertised cooldown capped at 10 seconds); the per-hour and per-day ones are not retried at all, because that wait is too long to hold a screen — so what the installer sees for those is the final answer.+- report anything as up to date.++### 4. Daily Allowance Exhausted+**Setup**: spend the account's daily allowance (in tests: a quota error with the daily scope and a `Retry-After`)+**Expected**:+- `update_failure.reason`: "quota_exceeded", `retryable`: true+- `retry_after`: time until the allowance resets, taken from the server's answer — again recorded, not displayed+- On screen this is indistinguishable from any other failed check: the same overview sentence, the same `failed to check updates: <message>` line. What separates it is the reason and the cooldown on the check result and the warning in the log, so that is what the test asserts+**Must not**:+- be shown as a permission problem — the license is fine, the period's allowance is not+- be retried before the reset; the allowance does not return sooner for being asked+- report anything as up to date++Every check costs a slice of that allowance, which is why the answer is gathered once and shared, and why the package description is held rather than requested twice for the same build.++### 5. Access Forbidden for the License Tier+**Setup**: call an endpoint the tier does not carry, or run as a blocked client+**Expected**:+- `update_failure.reason`: "forbidden", `retryable`: false, `retry_after`: 0+- This includes a quota answer whose scope is "blocked": a tier that never had access is not an allowance that is spent, and there is nothing to wait for+- Nothing on screen names the license: the failure text is the same sentence as for every other reason. The distinction lives in `reason` and in the log line — and it is the one failure where waiting cannot help, because the license, not time, is what would have to change+**Must not**:+- offer "try again later", schedule a retry, or count down a cooldown that does not exist+- report anything as up to date++Related: a license key the client cannot introspect is dropped **before** the call and the request goes anonymously, with `license key is not usable, continuing without it` in the log. The client is still built — the update check is the one thing that works without a license, and refusing to run would leave the user with no way to learn that the key is the problem. The symptom of ignoring that warning is precisely this scenario: a tier nobody expected.++### 6. Package Not Published for This Platform (404)+**Setup**: ask `packages/info` for a component, version, os and arch combination that has no published package — a plugin version the server never published for one of the two plugin architectures, or an installer build that exists for another platform only+**Expected**:+- Reason "not_found", `retryable`: false. This arrives on the package calls, so the check result is untouched — the update check itself may well have succeeded.+- Installer self-update: the screen shows `Could not get the package description: ...` and Enter does nothing. Without the description there is no length, sha256 or signature to check a file against, so there is nothing that could be fetched safely.+- Jaeger plugin: the observability stack update aborts **before any image is pulled** — the plugin step runs first for exactly this reason — and the installation keeps the plugin it had.+**Must not**:+- retry. A 404 is an answer; asking again produces the same one.+- download anything without a description to verify it against.+- leave a staged `.new` file behind. Staging files are removed on failure, and again at the start of the next attempt, because nothing else ever looks for them.++An unfamiliar platform never produces this 404 on the plugin path: a component whose OS is not linux is dropped before anything is fetched, and an architecture with no plugin file defined for it fails locally with `no jaeger plugin file is defined for architecture <a>` before the call is made. A "not_found" here means the server publishes no package for a version and platform the installer legitimately asked about.++### 7. Malformed Request Refused (400)+**Setup**: in a test, hand the client a request the contract does not accept — an unknown update strategy, more than 30 reported artefacts, an image digest carrying its `sha256:` prefix, a file component reported under `images`, a version that is not semver+**Expected** — two distinct paths:+- **Caught locally.** The client validates before marshalling and does not send. Only the update check leaves a mark on the check result: `update check request is malformed: <field>` is recorded as a failed check with the fallback reason "unreachable" and `retryable` false, because nothing classified it. The package calls produce `package info request is malformed: ...` and `package download request is malformed: ...`, which are returned to their caller and surface as an operation error or as `Could not get the package description: ...` — the check result is untouched, exactly as in scenario 6. Either way the message, which names the offending field, is the useful half, and catching it here costs no call and no slice of the allowance.+- **Refused by the server.** Reason "rejected", `retryable`: false.+**Must not**:+- resend the identical request. It cannot start succeeding, and each attempt costs a challenge and a slice of the allowance.+- be presented to the user as a server outage. This is the installer's own bug; the field name in the message is what makes it fixable.++### 8. Download Does Not Match Its Description+**Setup**: serve a package that is truncated, padded, altered while keeping its length, or signed with a key that is not the release key+**Expected** — three checks, all describing the plain file (transport encryption is transparent and changes none of them), all decided only after the last byte has arrived:+- Length ≠ `size` → `package is <n> bytes, expected <m>`. The encrypted response carries no `Content-Length`, so the size from `packages/info` is the only length the client ever learns — this is a real check, not a formality, and it is also what the progress percentage is computed against.+- sha256 ≠ `hash` → `package sha256 is <x>, expected <y>`+- Ed25519 signature over the file's SHA-512 does not verify → `package signature does not verify: ...`+**Must not**:+- treat the destination as usable before the call returns nil. Bytes are written as they arrive, so a failed download leaves a partial or unverified file: the installer build is deleted, and the Jaeger plugin's `.new` is deleted with the target left untouched — which is the entire reason it is staged next to the target rather than written in place.+- keep using the description the failed download was checked against. A build republished under the same version since it was described fails all three checks identically forever; the held description is dropped so the next attempt asks again.+- report success on a matching length and hash alone. The signature is what makes the package ours rather than merely intact.++### 9. Server Failed on Its Side+**Setup**: the server answers an internal error or a bad gateway+**Expected**:+- `update_failure.reason`: "server_error", `retryable`: true+- This is one of the few failures the client retries on its own — up to three attempts, a few seconds apart — so what the installer sees is the state after them, not the first failure+**Must not**: report anything as up to date; suggest the user reconfigure anything — nothing on this machine caused it.++### 10. The Confirming Check After an Update Fails+**Setup**: apply an update, then make the check that follows it fail — any of scenarios 1-5 and 9 at that moment+**Expected**:+- The local comparison still runs and reports per component: `<component>: expected <a>, got <b>`, or `no published digest to compare against` when the answer named none+- The menus keep offering the update, because no stack is known to be current+**Must not**:+- report the stack as current on the strength of the local comparison alone. Only the server knows whether something newer appeared while the update was being applied.+- report a component that differs from its target as "newer than the offered build". That verdict — the registry legitimately moving on between the answer and the pull — is only available when a fresh answer says there is nothing left to apply; without one, a difference is a mismatch and is reported as such.+## Environment Variable Tests### 1. HTTP_PROXY Auto-Detection@@ -132,7 +274,8 @@ sudo gpasswd -d $USER docker# Simulate network issuessudo iptables -A OUTPUT -p tcp --dport 443 -j DROP-# Simulate DNS issues+# Simulate an unreachable registry — NOT a DNS failure: the name still resolves,+# so this trips the HTTPS probe (scenario 7), not the lookup (scenario 6)echo "127.0.0.1 docker.io" | sudo tee -a /etc/hosts# Test with proxy@@ -143,6 +286,25 @@ export HTTPS_PROXY=http://proxy:3128export DOCKER_HOST=tcp://remote:2376export DOCKER_TLS_VERIFY=1export DOCKER_CERT_PATH=/path/to/certs # auto-migrated to PENTAGI_DOCKER_CERT_PATH on startup++# Update server unreachable: a name that does not resolve+export UPDATE_SERVER_HOST=update.invalid++# Update server unreachable: a proxy nothing listens on+export PROXY_URL=http://127.0.0.1:1++# Refused before a call is ever made — http is an error, not a silent upgrade to https.+# Recorded as a failed check whose message names the setting.+export UPDATE_SERVER_HOST=http://update.pentagi.com+```++`UPDATE_STRATEGY` cannot be used to trigger the malformed-request path: an unrecognised value is validated, logged and replaced with `preview`, because a typo must not leave an installation unable to learn about security updates.++Everything the environment cannot produce — rate limits, exhausted allowances, a forbidden tier, a timed-out challenge, a 404, a tampered download — is driven in unit tests by substituting the call function with the error the transport would have returned:++```bash+go test ./cmd/installer/cloud/... # classification, envelope, download verification+go test ./cmd/installer/checker/... # what a failed check does to the check result```## Verification@@ -153,3 +315,8 @@ Each scenario should:3. Provide actionable fix instructions4. Not block other checks unnecessarily5. Work under both privileged and unprivileged users++For the update server scenarios, two more, and they are the ones that matter:++6. Never claim an installation is up to date on the strength of a check that produced no answer — "nothing to update" and "we never found out" are different sentences, and only the first may be printed as reassurance+7. Never retry what cannot succeed. `retryable` is the property to branch on: telling a user to wait out a forbidden endpoint wastes their time, and discarding a cooldown the server did advertise wastes the license. Both are carried on the check result for whoever branches on them — no screen reads either one today, so assert them there.diff --git a/backend/docs/installer/checker.md b/backend/docs/installer/checker.mdindex 08d9ee92..a4e04313 100644--- a/backend/docs/installer/checker.md+++ b/backend/docs/installer/checker.md@@ -17,11 +17,11 @@ The `checker` package is responsible for gathering system facts and verifying in#### CheckResult StructureCentral data structure that holds all system check results:-- Installation status for each component (PentAGI, Langfuse, Observability)+- Installation status for each component (PentAGI, Graphiti, Langfuse, Observability)- System resource availability (CPU, memory, disk)- Docker environment status- Network connectivity status-- Update availability information+- The update check: the answer per stack (`StackUpdates`), why there is no answer (`UpdateFailure`), and what the check observed on this machine (`InstalledComponents`), plus the per-stack `*IsUpToDate` booleans the menus read- Computed values for UI display:- CPU count- Required and available memory in GB@@ -37,6 +37,7 @@ type CheckHandler interface {GatherDockerInfo(ctx context.Context, c *CheckResult) errorGatherWorkerInfo(ctx context.Context, c *CheckResult) errorGatherPentagiInfo(ctx context.Context, c *CheckResult) error+ GatherGraphitiInfo(ctx context.Context, c *CheckResult) errorGatherLangfuseInfo(ctx context.Context, c *CheckResult) errorGatherObservabilityInfo(ctx context.Context, c *CheckResult) errorGatherSystemInfo(ctx context.Context, c *CheckResult) error@@ -64,6 +65,7 @@ type CheckHandler interface {- **Memory**: Dynamic calculation based on components to be installed- Base: 0.5GB free- PentAGI: +0.5GB+ - Graphiti: +2GB- Langfuse: +1.5GB- Observability: +1.5GB- **Disk Space**: Context-aware requirements@@ -75,11 +77,11 @@ type CheckHandler interface {Three-tier verification process:1. **DNS Resolution**: Tests ability to resolve docker.io2. **HTTP Connectivity**: Verifies HTTPS access (proxy-aware)-3. **Docker Pull Test**: Attempts to pull `debian:latest` (the default worker image) when both Docker clients are available+3. **Docker Pull Test**: Attempts to pull `debian:latest` — a small probe image, the default of `DOCKER_DEFAULT_IMAGE`, not the pentest worker image — when both Docker clients are available#### Restricted Network Troubleshooting-The current checker validates Docker Hub reachability by resolving `docker.io`, making an HTTPS connectivity check, and — when both Docker clients are available — attempting a pull of `debian:latest` (the default worker image). This means the installer can fail network validation even when the host has general internet access but Docker itself is not configured for the target network.+The current checker validates Docker Hub reachability by resolving `docker.io`, making an HTTPS connectivity check, and — when both Docker clients are available — attempting a pull of `debian:latest` (the default of `DOCKER_DEFAULT_IMAGE`, used here only as a small reachability probe — the pentest worker image `vxcontrol/kali-linux` is not pulled by this check). This means the installer can fail network validation even when the host has general internet access but Docker itself is not configured for the target network.Recommended remediation order:@@ -93,10 +95,111 @@ PentAGI variables such as `PENTAGI_IMAGE`, `DOCKER_DEFAULT_IMAGE`, and `DOCKER_DSee Docker's official documentation for [registry mirrors](https://docs.docker.com/docker-hub/image-library/mirror/) and [daemon proxy configuration](https://docs.docker.com/engine/daemon/proxy/).### 5. Update Availability Checks-- Communicates with update server to check latest versions-- Sends current component versions and configuration-- Supports proxy configuration-- Checks updates for: Installer, PentAGI, Langfuse, Observability, Worker images++`GatherUpdatesInfo` (`checker/updates.go`) asks the PentAGI Cloud API what is available for this installation. It never fails the surrounding gather: a check that cannot be made is a fact *about* the installation, recorded in the result, not a reason to throw away everything else the checker learned.++The call goes to `https://update.pentagi.com` (`UPDATE_SERVER_HOST` overrides the host) through the installer's own `PROXY_URL`, and carries `LICENSE_KEY` when it is present and holds up. A key that does not hold up is deliberately **not** fatal — the check runs without it and the reason is written to the log, because otherwise the only symptom is a tier the user did not expect. `UPDATE_STRATEGY` selects the release channel (`preview` by default, also `stable` and `nightly`); an unrecognised value falls back to `preview` with a warning rather than failing the check, since a typo should not leave an installation unable to learn about security updates. The default is `preview` because `stable` measures the answer against curated releases, and a stack with no published release is then offered nothing at all — which reads as "no updates exist" when it means "no releases are published for this yet".++#### Facts are gathered per component, not per stack++`checker/components.go` turns the running installation into the component list the request carries. Two lists are sent, and they are separate all the way through: an **image** is identified by a registry reference and a digest, a **file** by a version and a hash, and no artefact is ever both.++The list has to be complete. The answer only covers what was asked about, so a component left out comes back as "nothing to report" — which reads exactly like "up to date", and that is the more dangerous of the two mistakes.++For every container image the request carries:++- **Component** — the artefact's own name, taken from an explicit component → container table. Nothing here is derived: for four of the sixteen images the container name is neither the compose service name nor the component name — Langfuse's `postgres`, `clickhouse`, `redis` and `minio` services run in containers called `langfuse-postgres`, `langfuse-clickhouse`, `langfuse-redis` and `langfuse-minio`, while the component sent stays the bare `postgres`, `clickhouse`, `redis`, `minio` — and a wrong container name is indistinguishable from an absent one, so a guess would silently drop the component instead of failing. The container name is what the table holds and what `ContainerInspect` is given; the compose `hostname:` field (`otelcol` for the `otel` service) is never read.+- **Status** — `running` when the container is up, `installed` when it exists but is stopped.+- **OS and Arch** — the **image's**, read from `ImageInspect` (`.Os`, `.Architecture`), never the host's. A container image is `linux` even on macOS and Windows, where Docker runs in a VM, and on Apple silicon an `amd64` image may well be running under emulation. Substituting `runtime.GOOS`/`runtime.GOARCH` is not caught by validation — `darwin` is a valid value, it just matches no published artefact — so the installation would silently be told "no updates" forever. An image on a platform the contract has no name for (say `arm/v7`) is dropped with a log line rather than rounded to the nearest value: rounding asks about one image and gets an answer about another.+- **Repository and Tag** — parsed from the reference the container was configured with, with the registry prefix and the implicit `library/` removed, and the tag `docker pull` would apply filled in when the reference omits one. Both halves are required: an update is the newest image *under a reference*, so a component that cannot name its reference cannot be resolved at all.+- **Image hash** — the image's **config digest**, i.e. what `docker inspect` returns as `Id`.++Note the order: `ContainerInspect` first, then `ImageInspect` **by the config digest that inspection returned**, not by the tag. A tag can have been moved onto a different image since the container started, and inspecting by tag would describe something other than what is actually running.++#### The three digests, and which one is sent++Every image has three sha256 identities: the **index digest** (the whole multi-platform publication, and what a pull by tag records in `RepoDigests`), the per-platform **manifest digest**, and the **config digest** (`docker inspect` → `Id`).++The installer sends the config digest, for three reasons: it is always present, it is per-platform — so it confirms the architecture as well as the build — and it needs no round-trip to the registry. The answer may carry all three (`image_hash`, `config_hash`, `index_hash`), and a match against **any one of them** means the installed artefact is what is being offered.++Digests are sent as **bare lowercase hex, 64 characters, without the `sha256:` prefix** (`normalizeDigest`). The daemon reports the prefixed form, so the conversion is mandatory, and it is not cosmetic: the contract validates against `^[0-9a-f]{64}$`, so the prefixed form and the same 64 characters in uppercase are both rejected — and a rejected request costs the answer for every component in it, not just the offending one. A value that does not normalise is **omitted** rather than sent: a missing digest means "nothing to compare", a malformed one takes the whole request down. Never truncate a digest to the 12 characters the CLI displays.++#### The three components that are not compose containers++- **Worker image.** It has no container and no compose service — it is pulled into the worker Docker environment on demand — so it is reported only when that environment is reachable and the image is actually present. What is reported is what is there, taken from `DOCKER_DEFAULT_IMAGE_FOR_PENTEST` (default `vxcontrol/kali-linux`); substituting the built-in default would claim an image the machine may not have. Status is always `installed`, because the image being present is the whole story. The image is authoritative about its own platform; the host architecture is used only as a fallback for a daemon that will not describe it, and if the result is still not a contract value the component is dropped.+- **Installer binary.** The one component that is a file on *this* host, and therefore the only one whose `os`/`arch` are legitimately the host's own. It is reported with its normalised version and, when the executable path can be read, the sha256 of the running binary. The hash is a nice-to-have — installer builds are identified by version — so failing to read our own path does not drop the component. The request's top-level `installer_version` / `installer_os` / `installer_arch` describe the host for the same reason.+- **Jaeger storage plugin** (`jaeger-clickhouse`). Reported as a **file** component, **once per architecture**, from `observability/jaeger/bin/jaeger-clickhouse-linux-amd64` and `…-arm64` relative to the directory the environment file lives in. Both are reported whatever the host is, because which one runs is decided *inside* the Jaeger container by the architecture of the Docker VM. Each is identified by the **sha256 of the file** and nothing else — the plugin ships without a version — with `os: linux`, because the binary runs in the container. A file that cannot be read is skipped; the two are emitted in a fixed order so two runs on the same machine produce the same request. The directory and file names are exported (`JaegerPluginDir`, `JaegerPluginBinaries`) so that the path the processor downloads into and the path reported here stay one table: if they drift, an update writes a file nothing reads.++#### What is deliberately left out++- A **container that does not exist** — the component is not deployed here, and is not worth a slot in the request.+- Every image of a stack pointing at an **external address**. Such a stack runs somewhere that cannot be inspected, so there is no reference to resolve, and reporting it would claim somebody else's deployment as ours. The Jaeger plugin is skipped for an external observability stack for the same reason.+- Every component of a stack that is **not configured at all**.+- Any component whose platform or image reference cannot be described completely — see above. One dropped component costs one answer; one invalid field costs all of them.++The request may report at most **30 artefacts, counting images and files together**. Today's inventory is 16 stack images + worker + installer + two plugin files = 20, but the list grows with every stack, so the ceiling is enforced during gathering. Components are ordered so the stacks whose updates matter most come first, files are trimmed before images, and whatever is dropped is **named in the log** — a silently truncated list would report the dropped components as complete.++#### Stack statuses++Alongside the components the request says how each product stack is deployed: `installed`, `connected`, `external` or `unused`. Nothing in the answer depends on this — it is reported for its own sake, because a stack hosted elsewhere contributes no components at all and is otherwise indistinguishable from a stack nobody uses. Every stack is reported, including the unused ones: silence cannot be told from a client too old to speak about stacks. `external` takes precedence over `installed`, since it is the more specific statement — it says who *operates* the stack — and an installation pointing at somebody else's Langfuse may well also have the compose file on disk.++#### What the answer contains++`CheckResult.StackUpdates` holds the answer in full; the per-stack `*IsUpToDate` booleans the menus read are the same verdict reduced to one bit. A stack **missing from the answer stays up to date**: the answer covers what was asked about, and silence is not evidence — offering an update nobody has grounds for is the worse failure.++`StackUpdate`:++| Field | Meaning |+|---|---|+| `HasUpdate` | The stack-level verdict, and the only thing the menu needs. |+| `CurrentVersion` / `LatestVersion` | What this installation is attributed to, and what is offered. |+| `CurrentVersionMixed` | The stack's components were attributed to **different** releases, so `CurrentVersion` names the oldest of them rather than a version this installation as a whole ever was. Legitimate — a component nobody rebuilt stays on its old release — but "you are on 2.1.0" and "the oldest thing you have is from 2.1.0" are different sentences, and a screen must not print the first when it means the second. |+| `Releases` | Every curated release this update crosses, **oldest first, the last entry being the target**. Empty for two different reasons: there is genuinely nothing to cross, or the answer predates the field — so an empty list is not by itself evidence of a single-step update. |+| `ReleasesTruncated` | The list was cut, and it is the **oldest** entries that went. |+| `Changelog` / `ReleaseNotes` | The **target** release's text only. When `Releases` is present its last entry carries the same text. |+| `Resolution` | How the answer was arrived at: `release`, `channel`, `ahead_of_release`, `no_artifact_for_tag`, `not_tracked`. **Diagnostic only** — it is logged and nothing more. It exists so that `has_update: false` can be *read* instead of guessed at, most of all in the case that used to be silent: an installation running something newer than anything curated. Branching on it would couple the installer to wording that is free to grow. |+| `Components` | The per-artefact plan, below. |++`ComponentUpdate`. Being listed here does **not** mean the artefact is outdated: under `stable` the answer names every artefact of the release that matches something reported, whether or not it differs, so the installation can be attributed to a version with release notes.++| Field | Meaning |+|---|---|+| `Action` | What to do about this artefact: `current`, `install`, `upgrade`, `downgrade`, `unknown`. Exactly one comes back per reported component, including the ones nothing could be resolved for. |+| `Reason` | Set only for `unknown`: `tag_not_published` (the component is published, but nothing under the reference this installation follows), `repository_not_tracked` (an image nobody publishes — usually a private rebuild), `component_not_tracked` (nothing published for this component on this platform at all), `no_release_artifact_for_tag` (the component exists, but the release the stack is measured against links no artefact of it). This is the difference between "nothing to do" and "we publish nothing for what you are running" — opposite situations that used to arrive identically. |+| `PullReference` | What to write into the compose variable before pulling, ready to use. It is **not** always `repository:tag`: under `stable` it pins the most specific immutable tag so the pull is reproducible, under `preview` and `nightly` it names the moving tag. Write it as given — composing a reference locally undoes that. |+| `Outdated` | Whether this artefact would actually change. |+| `Verifiable` | Whether **this machine** had something to compare — a digest for an image, a version or hash for a file. It describes the installed side only; it says nothing about what the answer carried. |+| `CurrentVersion` | What is installed, in whatever identity the comparison used: the config digest for an image, the version — or, for the plugin, the file hash — for a file. |+| `TargetVersion` | For an image, the offered **config digest**: the same identity the installed side is measured in, and therefore the value post-update verification compares a pulled image against. For a file, the offered version. Empty when it is not known, and verification then degrades honestly to "cannot verify". |++#### How `Outdated` and `Verifiable` are decided++Images are compared **by digest, not by tag** — a moving tag such as `latest` points at different bytes over time, so the tag alone says nothing — and a match against any of the three offered identities counts. Files are compared by version, and by hash when no version was reported, which is the Jaeger plugin's case.++Where the comparison has nothing to work with, **the server's `Action` is the authority**:++- `install`, `upgrade`, `downgrade` set `Outdated` unconditionally. `install` is the case that matters: nothing has been pulled, so there is no digest to compare and the comparison alone leaves `Outdated` false — which reads as "nothing to do" for exactly the component that most needs doing.+- `unknown` clears both `Outdated` and `Verifiable`: there is no artefact at all, so whatever a local comparison produced means nothing.+- An artefact with no installed counterpart is reported **unverifiable, not mismatched** — "this will change" and "we cannot tell" are different statements, and conflating them offers an update on no evidence. The guard is on the **installed** side only, though: `Verifiable` is set whenever this machine had a digest to compare, whatever the answer carried. An offer that names the image only by `image_hash` — the per-platform manifest digest, which no Docker API reports and which therefore can never equal the config digest the installer sends — comes back verifiable *and* outdated, not "cannot tell". Where that case does degrade honestly is one layer later: `TargetVersion` stays empty, so the post-update verification reports "cannot verify" instead of a mismatch.++`CheckResult.InstalledComponents` keeps what this check observed on the machine, recorded **before** the call is made, since it is a local fact whether or not the server answers. Post-update verification reads it instead of interrogating Docker for a second time.++#### When there is no answer++A failed check sets `UpdateServerAccessible = false`, clears `StackUpdates`, and resets **all six** per-stack flags. Resetting all of them matters: a flag left behind keeps whatever verdict an earlier successful check put there, and the interface then presents a stale answer as a current one — the worker flag used to be the one left behind.++`UpdateFailure` says why, in terms the interface can act on, because a spent quota and a broken proxy call for opposite reactions. `Retryable` separates "come back later" from "this needs a different license", and `RetryAfter` carries the advertised cooldown when there is one.++| Reason | What it means | Retryable |+|---|---|---|+| `unreachable` | Nothing reached a verdict: no network, no DNS, a proxy that refused, a connection that died mid-flight. | yes |+| `timeout` | A deadline — the caller's, or the proof-of-work challenge exceeding its budget on slow hardware. | yes |+| `rate_limited` | Too many requests in a rolling window; `RetryAfter` says when it reopens. | yes |+| `quota_exceeded` | The allowance for the period is spent; `RetryAfter` says when it resets. | yes |+| `server_error` | The server failed on its side. | yes |+| `forbidden` | This client is not allowed to make the call at all — a license tier without it, or a blocked client. Waiting does not help; a different license does. | no |+| `not_found` | No such package or version. That is an answer, not an outage. | no |+| `rejected` | The request was refused as malformed, including replay and signature refusals. That is our bug, not the user's, and resending an identical request cannot succeed. | no |## Public APIdiff --git a/backend/docs/installer/installer-architecture-design.md b/backend/docs/installer/installer-architecture-design.mdindex 6f3881ee..3a781c32 100644--- a/backend/docs/installer/installer-architecture-design.md+++ b/backend/docs/installer/installer-architecture-design.md@@ -46,6 +46,7 @@ func (a *App) View() string {- **Controller Layer**: Business logic, environment variables, configuration- **Styles Layer**: Presentation, theming, responsive calculations- **Window Layer**: Terminal size management, dimension coordination+- **Cloud Layer**: The only route out to the PentAGI Cloud API — request construction, envelope handling, error classification## 🏗️ **Navigation Architecture**@@ -140,6 +141,80 @@ func (a *App) createModelForScreen(screenID ScreenID, data any) tea.Model {}```+## 🏗️ **Screen Registration Architecture**++### **Where the Update Screens Sit**+Two screens were inserted into the maintenance branch of the navigation graph, and both took over a destination that used to belong to the generic processor operation form:++```+MaintenanceScreen (list)+ ├── UpdateOverviewScreen ──enter──> UpdatePentagiScreen ("processor_operation_form§compose§update")+ └── InstallerUpdateScreen (replaced "processor_operation_form§installer§update")+```++- **`UpdateOverviewScreen`** stands *between* the menu entry and the operation form.+The entry used to lead straight into "are you sure?", asking for consent to something the interface had never described.+The overview describes it, then continues to the same form — the confirmation there is untouched.+The screen makes no network call: everything it renders comes from the last check result held by the controller, so it cannot fail and has no error state.+`Enter` is deliberately *not* bound to page-down as it is on the EULA screen: this screen asks for no consent, so its one unambiguous key belongs to its one action.++- **`InstallerUpdateScreen`** is a screen rather than an operation form because what it does is describe a build and download one verified file, and the generic form's help text claimed the running binary would be replaced and the app would exit — something no version of the installer has ever done.+It names version, platform, size and target path *first*, then offers a single action, and confirms only the one thing worth confirming: a file already occupying the target name.++### **The Four Registration Steps**+A new screen is not a single file. It is four edits, and only the first of them is enforced by the compiler:++| # | Where | What |+|---|---|---|+| 1 | `wizard/models/types.go` | the `ScreenID` constant |+| 2 | `wizard/models/types.go` — `RestoreModel` | a `case` for the concrete model type |+| 3 | `wizard/registry/registry.go` — `initScreens` | construct the screen and store it under its `ScreenID` |+| 4 | `wizard/locale/locale.go` + `app.initHotkeysLocale` | the screen's strings, and a caption for every hotkey it returns |++```go+// Step 2 — the branch without which the screen is inert+func RestoreModel(model tea.Model) BaseScreenModel {+ switch m := model.(type) {+ // ...+ case *UpdateOverviewModel:+ return m+ case *InstallerUpdateModel:+ return m+ default:+ return nil+ }+}+```++### **Why Step 2 Is the Dangerous One**+`RestoreModel` is the *only* path by which a model returned from `Update` gets back into the+app:++```go+func (app *App) forwardMsgToCurrentModel(msg tea.Msg) tea.Cmd {+ model, cmd := app.currentModel.Update(msg)+ if newModel := models.RestoreModel(model); newModel != nil {+ app.currentModel = newModel+ }+ return cmd+}+```++A type the switch does not know yields `nil` and the app keeps the model it already had.++What that costs is worth stating precisely, because the obvious answer is wrong: every screen here has a pointer receiver on `Update` and returns itself, so the mutation has already happened in place and the pointer the app is holding *is* the updated model — nothing freezes.++The branch is load-bearing for the case the signature allows but no screen has used yet: a model whose `Update` returns a *different* model. That one is dropped silently, with no panic, no log line and no error anywhere.++The compile-time assertion each screen carries (`var _ BaseScreenModel = (*InstallerUpdateModel)(nil)`) does **not** catch it either, because `RestoreModel` is a runtime type switch and a missing `case` is not a type error.++`TestEveryScreenModelIsRestorable` therefore enumerates both new screens, and that test is the only guard there is. The contract it encodes is "every screen is listed" rather than "list the ones that need it", because the day a screen starts returning something else is not the day anybody remembers this rule.++Steps 3 and 4 fail just as quietly, which is why they are listed rather than assumed:++- A screen missing from `initScreens` is not a crash — `GetScreen` falls back to `initMockScreen` and the user gets a placeholder form where the feature should be.+- The footer renders a hotkey only if its key is present in `app.hotkeys` (`if localeHotKey, ok := app.hotkeys[hotkey]; ok`). A screen returning a key with no caption simply shows nothing in the footer.+## 🏗️ **Adaptive Layout Strategy**### **Responsive Design Pattern**@@ -455,6 +530,125 @@ func (c *StateController) loadProviderConfig(providerID string) ProviderConfig {}```+## 🏗️ **Cloud Client Architecture**++### **Single Egress Pattern**+Everything the installer asks of the PentAGI Cloud API goes through one package: `cmd/installer/cloud`.++Both `checker` and `processor` build a `cloud.Config` from the installer state and call methods on the client. Neither constructs requests, parses responses, or opens connections to `update.pentagi.com` directly.++The `cloud` package is independent from the rest of the installer — it does not depend on `checker`, `processor`, or `wizard`. The dependency arrow points only one way. In tests, the client can be exercised by substituting the call functions, with no actual server involved.++```go+// cloud/client.go — three routes bound in one build+const (+ routeUpdatesCheck = "updates_check" // POST /api/v1/proxy/updates/check+ routePackagesInfo = "packages_info" // GET /api/v1/proxy/packages/info+ routePackagesDownload = "packages_download" // GET /api/v1/proxy/packages/download+)++type Client struct {+ checkUpdates sdk.CallReqBytesRespBytes+ packageInfo sdk.CallReqQueryRespBytes+ downloadPackage sdk.CallReqQueryRespWriter+ // ...+}+```++Route names are part of the contract, not internal labels: the server dispatches on the name, and one it does not recognise is refused outright rather than reported as a missing page.++### **One Proxy Setting Governs Every Call**+The SDK's default transport reads the proxy from the process environment. The installer has its own `PROXY_URL` setting — often carrying credentials the environment does not — and that setting has to win, because it is the one the user actually configured.++```go+func newTransport(proxyURL string) (*http.Transport, error) {+ transport := sdk.DefaultTransport()+ value := strings.TrimSpace(proxyURL)+ if value == "" {+ return transport, nil // nothing configured: leave the environment behaviour alone+ }+ parsed, err := url.Parse(value)+ // ... reject a URL with no host ...+ transport.Proxy = http.ProxyURL(parsed)+ return transport, nil+}+```++The transport is built once in `New` and shared by all three calls, so there is no route that can quietly bypass it. Both construction sites — the checker's update check and the processor's package download — read the same `PROXY_URL`, which is what makes "one setting" true in practice rather than only by intent.++Two neighbouring normalisations belong to the same idea of a single, predictable egress:++- **`NormalizeHost`** reduces the configured address to `host[:port]`. A scheme and trailing path are tolerated because the setting historically held a full URL, but an explicit `http://` is an **error** rather than a silent upgrade: the connection is always encrypted, and quietly doing the opposite of what the user wrote would hide a misconfiguration.++- **`NormalizeVersion`** turns the build version into one the contract accepts, falling back to `0.0.0` for anything that is not a version number — a branch name, a bare commit hash, an empty string. The original is not lost: it travels in the `User-Agent`, where it identifies the exact build without having to satisfy the version grammar.++### **The License Key Is Validated Before It Is Handed Over**+```go+if key := strings.TrimSpace(cfg.LicenseKey); key != "" {+ if _, err := sdk.IntrospectLicenseKey(key); err != nil {+ client.licenseWarning = fmt.Errorf("license key is not usable, continuing without it: %w", err)+ } else {+ options = append(options, sdk.WithLicenseKey(key))+ }+}+```++The SDK drops a key it cannot decode without saying so, and the call then runs anonymously — which from the outside looks exactly like the license not being honoured. Validating first turns that into a stated reason, available from `LicenseWarning()`.++An unusable key is deliberately **not** fatal. The update check is the one thing that still works without a license, so refusing to build the client would leave the user with no way to discover that their key is the problem. `New` fails only on configuration that cannot produce working calls at all: an unusable host or an unusable proxy.++### **Answers Arrive Inside an Envelope**+Every non-streaming answer is wrapped as `{"status": …, "data": …}`, and unwrapping it is not optional:++```go+answer, err := c.checkUpdates(ctx, body)+if err != nil {+ return nil, Classify(err)+}+// Decoding straight into the response type SUCCEEDS against the wrapper — every field+// simply stays at its zero value. Skipping this reports "no updates" for every answer.+response, err := models.ParseEnvelope[models.CheckUpdatesResponse](answer)+```++This is the sharpest edge in the whole client. `json.Unmarshal` of an envelope into the payload type produces no error and no populated fields, so the installer concludes there is nothing to install and never learns it was wrong.++`ParseEnvelope` also turns a `2xx` body whose status is not `success` into an `*APIError` describing what the server reported. Binary downloads are the one exception — they carry the file itself, with no envelope around it.++### **Failure Classification**+`Classify` maps SDK errors onto reasons the interface can act on, wrapping the original so `errors.Is`/`errors.As` keep working through it:++| Reason | What the user can do about it |+|---|---|+| `unreachable` | check the network — nothing ever reached a verdict |+| `timeout` | a deadline, including the proof-of-work budget on slow hardware |+| `rate_limited` / `quota_exceeded` | wait; `RetryAfter` says how long |+| `forbidden` | retrying never helps; the license does |+| `not_found` | an answer, not an outage — no such package or version |+| `rejected` | the request was malformed: our bug, and resending it cannot succeed |+| `server_error` | worth retrying later |++`Retryable()` collapses the table back down for callers that only need the one bit. Ordering inside `Classify` matters: the typed errors are matched before the sentinels they wrap, because that is where the server-advertised cooldown lives. Collapsing all of this into a single "update server unavailable" flag — as the installer used to — tells the user nothing they can act on.++### **Verification Belongs to the Client, Not the Caller**++`PackageInfo` validates the answer before returning it, because everything `DownloadPackage` checks is taken from that answer: an unverified description of a file is not a basis for trusting the file.++The download then feeds one pass over the stream into three checks at once:++```go+digest := sha256.New()+counter := &countingWriter{}+signed := info.Signature.ValidateWrapWriter(io.MultiWriter(dst, digest, counter))+```++The expected length has to come from `info.Size` because the encrypted response carries no `Content-Length` — there is no header to read it from. It catches nothing the sha256 and the signature would miss; what it buys is a legible error ("package is N bytes, expected M") ahead of a bare hash mismatch.++Verification can only complete once the last byte is written, so on any error `dst` holds a partial or unverified file. Discarding it is the caller's job, and the two callers discharge that obligation differently on purpose.++`installPluginFile` streams into `<target>.new` and renames only once the write has returned clean, because the file it replaces is the one a running Jaeger has mounted — a download that dies halfway would otherwise leave a truncated plugin and the container would come back up unable to start.++`fetchInstaller` does the opposite: it writes the binary under its final name in the environment directory and removes it on error. Staging an executable through the system temp directory and moving it into place is a pattern antivirus and EDR products score heavily, and a false positive there costs the user their update.+## 🏗️ **Resource Estimation Architecture**### **Token Calculation Pattern**@@ -587,4 +781,5 @@ This architecture provides:- **State Persistence**: Complete session restoration- **Responsive Design**: Adaptive to terminal capabilities- **Resource Awareness**: Real-time estimation and optimization-- **User Experience**: Professional interaction patterns\ No newline at end of file+- **User Experience**: Professional interaction patterns+- **Single Egress**: One package, one proxy setting, one place where answers are unwrapped and failures are classified\ No newline at end of filediff --git a/backend/docs/installer/installer-base-screen.md b/backend/docs/installer/installer-base-screen.mdindex 75d92565..f1f74894 100644--- a/backend/docs/installer/installer-base-screen.md+++ b/backend/docs/installer/installer-base-screen.md@@ -22,7 +22,6 @@ type BaseScreen struct {window *window.Window// State- args []stringinitialized boolhasChanges boolfocusedIndex int@@ -46,7 +45,8 @@ type BaseScreen struct {```gotype BaseScreenHandler interface {- BuildForm()+ BuildForm() tea.Cmd+ GetFormSummary() stringGetFormTitle() stringGetHelpContent() stringHandleSave() error@@ -263,6 +263,197 @@ func (m *ListFormModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {}```+> The two examples above predate two changes to the base: `NewBaseScreen` no longer takes an `args []string` parameter, and `BuildForm()` now returns a `tea.Cmd`.+> The two screens below are written against the current shape.++### **3. Document Screen (viewport, no BaseScreen)**++`wizard/models/update_overview.go` is the shape to copy when a screen shows *text* rather than fields. It does not embed `BaseScreen` at all — it implements `BaseScreenModel` directly, the way `eula.go` does.++Everything `BaseScreen` contributes (fields, focus, save/reset, the form/help split) is dead weight for a document, and the one thing a document needs — a full-width scrolling viewport over rendered markdown — `BaseScreen` does not provide.++```go+type UpdateOverviewModel struct {+ styles styles.Styles+ window window.Window+ controller controller.Controller++ viewport viewport.Model++ source string // the markdown+ content string // that markdown, rendered at renderedAt columns+ renderedAt int+ ready bool+ scrolled bool+}++// only the model interface: there is no form, so there is no handler+var _ BaseScreenModel = (*UpdateOverviewModel)(nil)+```++**Keep the markdown and its rendered form as two separate fields.** A resize re-renders *from the source*. Re-wrapping the already-rendered string would wrap the ANSI escape sequences glamour wrote into it, and the screen fills with fragments of colour codes.++**Re-render only when the wrap width actually changed:**++```go+func (m *UpdateOverviewModel) updateViewport() {+ contentWidth, contentHeight := m.window.GetContentSize()+ if contentWidth <= 0 || contentHeight <= 0 || m.source == "" {+ return+ }++ if m.content == "" || m.renderedAt != contentWidth {+ rendered, err := m.styles.GetRendererForWidth(contentWidth).Render(m.source)+ // ... on error, fall back to the raw markdown plus the error+ m.content = rendered+ m.renderedAt = contentWidth+ }++ if !m.ready {+ m.viewport = viewport.New(contentWidth, contentHeight)+ m.ready = true+ } else {+ m.viewport.Width, m.viewport.Height = contentWidth, contentHeight+ }++ m.viewport.SetContent(m.content)+ m.updateScrollStatus()+}+```++Dragging a window border delivers one `tea.WindowSizeMsg` per column and glamour is not cheap, so `renderedAt` is what stops the whole changelog being re-rendered for a resize that cannot change how it wraps — a height-only drag, or one of the resizes `registry.HandleMsg` forwards to *every* registered screen whether or not the user is looking at it. The comparison is against the raw content width, so widths outside the clamp band below still re-render (into identical output); the renderer itself is memoised in either case.++**Create the viewport on the first real size, never in the constructor.**+`window.GetContentSize()` is 0×0 until the first `WindowSizeMsg` arrives, and a viewport built at that size shows nothing afterwards. `ready` is the flag that says the viewport exists, and each of its readers does something different: `View()` falls back to the loading text, `GetScrollInfo()` returns zeroes rather than measure an unsized viewport, and every scrolling key sits behind an `if !m.ready { break }` guard.+`enter` is deliberately *in front of* that guard — continuing needs no rendered document, so the one action the screen offers is never blocked by a size message that has not arrived yet.++**Deliver the content as a message even when nothing is fetched.**+`loadOverview` only reads the last check result out of the controller and cannot fail, but it is still a `tea.Cmd` returning `UpdateOverviewLoadedMsg` — the same shape as the EULA screen, and it keeps `Init()` the single place that decides what a fresh visit shows.++**`GetFormTitle()` returns the empty string.**+The document carries its own H1, and the header would otherwise print the heading twice.++**`GetScrollInfo() (scrolled, atEnd bool, percent int)`** is the accessor a footer uses to show scroll position; it returns zeroes while `!ready` rather than reading an unsized viewport.+`app.renderFooter` consults it only on the EULA screen today, which needs "you have reached the end" for consent.+This screen instead announces what the keys do, and only once there is something to scroll:++```go+func (m *UpdateOverviewModel) GetFormHotKeys() []string {+ hotkeys := []string{"enter"}+ if m.ready && m.content != "" {+ hotkeys = append(hotkeys, "up|down", "pgup|pgdown", "home|end")+ }+ return hotkeys+}+```++**Build the document in a pure function.**+`overviewDocument(updates []checker.StackUpdate, checkSucceeded bool) string` lives+outside the model and `update_overview_test.go` tests that function. There is no+harness for a bubbletea screen in the wizard, and what is worth testing is what the+document *says*, not how it scrolls.++### **4. Action Screen with a Terminal Panel**++`wizard/models/installer_update.go` is the other new shape: no form fields at all, but+the `BaseScreen` layout and help panel are worth keeping. It embeds `BaseScreen`,+implements `BaseScreenHandler` with empty form plumbing, and puts a+`terminal.Terminal` where the form viewport would be.++```go+type InstallerUpdateModel struct {+ *BaseScreen++ processor processor.ProcessorModel+ terminal terminal.Terminal++ offered *processor.InstallerPackage // what the server offers+ offerErr error // ...or why there is none++ running bool+ confirming bool+}++var _ BaseScreenModel = (*InstallerUpdateModel)(nil)+var _ BaseScreenHandler = (*InstallerUpdateModel)(nil)+```++**`BuildForm()` builds the panel, not fields — and sets `initialized` itself:**++```go+func (m *InstallerUpdateModel) BuildForm() tea.Cmd {+ m.SetFormFields([]FormField{}) // action screen: nothing to focus, nothing to save++ contentWidth, contentHeight := m.getViewportFormSize()+ if m.terminal == nil {+ if !m.isVerticalLayout() {+ contentWidth -= 2+ }+ m.terminal = terminal.NewTerminal(contentWidth-2, contentHeight-1,+ terminal.WithAutoScroll(), terminal.WithAutoPoll(), terminal.WithCurrentEnv())+ } else {+ m.terminal.Clear()+ }++ m.terminal.Append(locale.InstallerUpdateAsking)++ if !m.initialized {+ m.initialized = true+ return m.terminal.Init()+ }++ return nil+}+```++The overridden `View()` also calls `BuildForm()` while `!initialized` and discards the command it returns. Without setting the flag here, every frame would clear the panel and re-append the first line, wiping out the output of a running download on each redraw.++**Re-size the terminal by hand.** The terminal is not part of the `BaseScreen` viewports, so `updateViewports()` does not manage it. In the `tea.WindowSizeMsg` branch, the same arithmetic from `BuildForm` is repeated (`getViewportFormSize()`, subtracting two columns in horizontal layout and accounting for the border) before calling `m.terminal.SetSize(...)`. It is important to keep these two pieces of arithmetic in sync.++**Never let key messages fall through to `BaseScreen`.** In the base screen logic, `enter` means save-and-return and `ctrl+r` means reset. On an action screen, this behavior is undesirable, as pressing `enter` could exit mid-download. Therefore, the `tea.KeyMsg` branch for this model handles `enter`, `y`, and `n` itself and passes all other keys to the terminal for scrolling. While `m.terminal.IsRunning()` is true, every key message goes directly to the terminal unfiltered, making the screen's own keys unreachable by construction rather than by explicit checks.++**Load asynchronously, and carry the failure in the same message.**++```go+func (m *InstallerUpdateModel) Init() tea.Cmd {+ m.running, m.confirming = false, false+ m.offered, m.offerErr = nil, nil++ return tea.Batch(m.BaseScreen.Init(), m.loadPackage)+}++type InstallerPackageLoadedMsg struct {+ Package *processor.InstallerPackage+ Err error+}+```++Registry screens are singletons that are built once at start-up, but `Init()` runs on every navigation to the screen. This means per-visit state has to be cleared here. Otherwise, on a second visit, the screen would display the previous answer, and if `confirming` were still set, pressing `y` could act on an outdated offer. Both the package and error outcomes travel in a single message and are stored, because the logic for allowing a download is based on `canDownload()`—defined as `!running && offered != nil && offerErr == nil`. If the screen fails to load the package, it becomes inactive: pressing `enter` has no effect, and `GetFormHotKeys()` returns no keys to show available actions.++**A confirmation only where there is a question.** Pressing `enter` starts the download immediately. The confirmation prompt appears only if the file about to be written already exists—only in this case do `y` and `n` have meaning. The hotkeys are managed to match these three states exactly, ensuring that the footer never suggests a key that the screen would ignore.++```go+func (m *InstallerUpdateModel) GetFormHotKeys() []string {+ if m.terminal != nil && m.terminal.IsRunning() {+ return nil+ }+ if m.confirming {+ return []string{"y|n"}+ }+ if !m.canDownload() {+ return nil+ }++ return []string{"enter"}+}+```++Note that this shadows `BaseScreen.GetFormHotKeys()`. The base gates `down|up`, `ctrl+s`, and `ctrl+r` behind having fields or a list, so on a screen with neither it offers none of them — but it appends `enter` unconditionally. `enter` is exactly the key this screen has to be able to withhold: while the download is running, and on a screen whose offer never arrived, pressing it does nothing and the footer must not say otherwise.++The declining branch matters as much as the confirming one: `n` clears `confirming` and rewrites the panel with what the user now needs, rather than returning to a screen that still reads as if nothing happened.++**Text in a pure function, again.** `installerUpdateLines(running, offered, err)` returns the panel contents as `[]string`, so `installer_update_test.go` can assert what the screen *claims* without a terminal.+## 🔄 **Migrating Existing Screens**### **Step 1: Analyze Current Screen**@@ -323,7 +514,7 @@ func NewNewFormModel(...) *NewFormModel {// Initialize list if neededm.initializeList()- m.BaseScreen = NewBaseScreen(controller, styles, window, args, m, m)+ m.BaseScreen = NewBaseScreen(controller, styles, window, m, m)return m}```@@ -352,7 +543,7 @@ Delete these methods from migrated screens:Follow existing patterns for environment variable handling:```go-func (m *FormModel) BuildForm() {+func (m *FormModel) BuildForm() tea.Cmd {// Track initially set fields for cleanupm.initiallySetFields = make(map[string]bool)@@ -365,6 +556,8 @@ func (m *FormModel) BuildForm() {}m.SetFormFields(fields)++ return nil // a form screen has nothing to start; only a panel screen returns a cmd}func (m *FormModel) HandleSave() error {@@ -390,21 +583,84 @@ func (m *FormModel) HandleSave() error {## 🎯 **Navigation Integration**-### **Screen Registration**+### **Screen Registration — four mandatory steps**-Add new screen to navigation system:+All four are required. Skipping any of them fails *quietly*: nothing panics and nothing is logged. Three of them show a symptom somewhere other than the code you changed; the fourth — step 2 — shows no symptom at all with the screens written so far, which is exactly why it is the one that gets skipped.++**1. The `ScreenID` constant** in `wizard/models/types.go`:```go-// In types.goconst (ExampleFormScreen ScreenID = "example_form"+ // parameterised screens join their arguments with "§"+ UpdatePentagiScreen ScreenID = "processor_operation_form§compose§update")+```++The ID is the only key the navigator, the registry and every menu share. Without it there is nothing to push onto the navigation stack and nothing to key the registry by.++**2. A case in `models.RestoreModel`** (`types.go`):-// In app.go createModelForScreen()-case ExampleFormScreen:- return NewExampleFormModel(a.controller, a.styles, a.window, args)+```go+case *ExampleFormModel:+ return m```+`app.forwardMsgToCurrentModel` calls `Update` on the current model and adopts the result only when `RestoreModel` recognises it — when it returns `nil` there is no fallback and no log: the app keeps the pointer it already holds, and returns the command either way. What a missing branch actually costs is worth stating precisely, because the obvious answer is wrong. Every screen in `wizard/models` has a pointer receiver on `Update` and returns *itself*, so the object the app renders is the object `Update` has just mutated — nothing freezes, and a missing branch shows no symptom at all. The branch is load-bearing for the case the type allows but nobody has written yet: a model that returns a *different* model, dropped silently with nothing anywhere to say why. That is why the contract is "every screen is listed" rather than "list the ones that need it" — the day a screen starts returning something else is not the day anybody remembers this rule. The `nil` is load-bearing in the other direction too: a `MaintenanceModel` delegates `Update` to its embedded `*ListScreen`, which returns *itself*, and `RestoreModel` not knowing `*ListScreen` is exactly what keeps the app pointing at the whole screen instead of one of its parts — so list the concrete screen type and nothing else.++`TestEveryScreenModelIsRestorable` in `installer_update_test.go` pins membership:++```go+for name, model := range map[string]tea.Model{+ "InstallerUpdateModel": (*InstallerUpdateModel)(nil),+ "UpdateOverviewModel": (*UpdateOverviewModel)(nil),+} {+ if RestoreModel(model) == nil {+ t.Errorf("%s is missing its branch in RestoreModel", name)+ }+}+```++**3. Construction in `registry.initScreens`** (`wizard/registry/registry.go`):++```go+r.screens[models.ExampleFormScreen] = models.NewExampleFormModel(r.controller, r.styles, r.window)+```++Screens are built once here and reused; `registry.GetScreen` falls back to a `MockFormModel` for an unknown ID **and caches it under that ID**, so the screen you wrote is never constructed at all. The first symptom is not the screen but the menu: `ListScreen` labels each entry by asking the registry for the model behind its ID (`GetFormName`, `GetFormOverview`, `GetCurrentConfiguration`, `IsConfigured`), so the entry reads "Development Screen" and opens a placeholder. An unregistered screen also never receives `tea.WindowSizeMsg`, which `registry.HandleMsg` forwards to registered screens only.++**4. Strings in `wizard/locale/locale.go`, and hotkey captions in `app.initHotkeysLocale`** (`wizard/app.go`). All user-visible text lives in `locale`; the footer resolves each name from `GetFormHotKeys()` through the caption map:++```go+if localeHotKey, ok := app.hotkeys[hotkey]; ok {+ actions = append(actions, localeHotKey)+}+```++An unknown name is skipped without complaint, so the key keeps working and is simply never announced — the quietest of the four failures, and the only one whose symptom is a hint that is missing rather than a screen that is wrong. Neither new screen needed a new caption: `enter`, `up|down`, `pgup|pgdown`, `home|end` and `y|n` are already in the map.++### **Width-aware markdown rendering**++`styles.GetRenderer()` returns a single renderer built once with `glamour.WithWordWrap(DefaultRenderWidth)` — 80 columns, whatever the terminal is doing. That was enough while the only markdown screen was the EULA, which renders once at load and is prose written to be read at a fixed measure. It is not enough for a changelog: at 80 columns in a 200-column window the document uses a third of the screen, and in a terminal narrower than 80 every line breaks two or three times, which is what a list of component names does worst.++`styles.GetRendererForWidth(width)` is the replacement for screens that know how much room they have:++```go+func (s *Styles) GetRendererForWidth(width int) *glamour.TermRenderer {+ width = min(max(width, MinRenderWidth), MaxRenderWidth) // [40, 120]+ // ... memoised per width; on any failure returns the fixed 80-column renderer+}+```++Four properties are worth knowing before you use it:++- **It clamps to `[MinRenderWidth, MaxRenderWidth]` = `[40, 120]`.** The floor keeps a narrow terminal from splitting every line; the ceiling is a readability limit — a line spanning a maximised terminal is measurably harder to read.+- **It never returns `nil`.** A width that cannot be built falls back to the default renderer, so no render path needs a nil check — and a nil check that someone forgets is how a changelog ends up not being shown at all.+- **The cache is behind a pointer** (`renderers *rendererCache`), because `styles.Styles` is copied by value into every screen and a value cache would be cloned per screen, defeating the point.+- **The cache is mutex-guarded**, because renderers are built inside `tea.Cmd` goroutines — off the update loop, where two screens can ask for the same width at once.++`GetRenderer()` still exists and still wraps at 80; prefer `GetRendererForWidth` on anything that renders inside a sized panel.+### **Navigation Usage**```go@@ -429,6 +685,14 @@ Add compile-time interface checks:// Ensure interfaces are implementedvar _ BaseScreenHandler = (*ExampleFormModel)(nil)var _ BaseListHandler = (*ListFormModel)(nil)++// A screen that embeds BaseScreen asserts both: the registry stores it as a model,+// and BaseScreen calls back into it as a handler+var _ BaseScreenModel = (*InstallerUpdateModel)(nil)+var _ BaseScreenHandler = (*InstallerUpdateModel)(nil)++// A document screen has no form, so it asserts only the model interface+var _ BaseScreenModel = (*UpdateOverviewModel)(nil)```## 📊 **Benefits Summary**@@ -445,6 +709,8 @@ var _ BaseListHandler = (*ListFormModel)(nil)1. **Simple Form**: Inherit BaseScreen, implement BaseScreenHandler2. **Form with List**: Inherit BaseScreen, implement both handlers3. **Menu Screen**: Use existing patterns without BaseScreen+4. **Document**: No BaseScreen — implement BaseScreenModel over a viewport (`eula.go`, `update_overview.go`)+5. **Action with terminal panel**: Inherit BaseScreen with zero fields, own the terminal and override `View()` (`installer_update.go`, `apply_changes.go`)### **Required Methods**diff --git a/backend/docs/installer/installer-overview.md b/backend/docs/installer/installer-overview.mdindex 957e2290..ef69d4a0 100644--- a/backend/docs/installer/installer-overview.md+++ b/backend/docs/installer/installer-overview.md@@ -80,6 +80,8 @@ backend/cmd/installer/│ │ ├── llm_provider_form.go│ │ ├── summarizer.go│ │ ├── summarizer_form.go+│ │ ├── update_overview.go # What an update changes (informational)+│ │ ├── installer_update.go # Installer build download│ │ └── types.go # Shared types│ ├── styles/ # Styling and layout│ │ └── styles.go@@ -111,7 +113,7 @@ backend/cmd/installer/#### **Styles Layer** (`styles/`)- Centralized styling and theming- Dimension management (singleton pattern)-- Shared glamour renderer (prevents freezing)+- Memoised glamour renderers: one per wrap width, plus the default 80-column one- Responsive style calculations#### **Window Layer** (`window/`)@@ -203,6 +205,36 @@ Forms automatically scroll to keep focused fields visible:- **Assistant**: Specialized settings for AI assistant contexts- **Token Estimation**: Real-time calculation of context size+## 🎯 **Update Screens**++Two screens under **Maintenance** stand outside the generic operation form: neither edits configuration, and neither is an operation the form framework describes for itself. They sit at different distances from the form system — the overview is a plain viewport over a rendered document, while the installer update is still a `BaseScreen`, built with an empty field list, which is what gives it the help panel and the vertical/horizontal layout.++The two entries appear under different conditions. **Update Installer** shows only when a newer build is on offer *and* the update server answered. **Update PentAGI** shows whenever an installed stack is not known to be up to date — which includes a check that failed, because a failed check resets every per-stack verdict instead of leaving a stale one in place. So the overview is reachable with nothing yet known to need doing, and that is exactly why it has to be able to say the check did not complete.++### **Update Overview** (`models/update_overview.go`)++Sits **between** the "Update PentAGI" menu entry and the apply form, which the entry used to point at directly — so the first thing the user saw was "are you sure?" about something the interface had never described. The overview describes it, then continues to the same form, confirmation and all.++- **Informational only**: the document is built from the update check already in memory, so the screen makes no network call and cannot fail+- **Per stack**: the version move (`current → target`), a note when components come from different releases and the version shown is therefore the oldest of them, and the per-component plan+- **Three component verdicts, spelled out in words**: `will be updated`, `unchanged`, and `cannot verify — nothing to compare against`. The third is not a synonym for the second — a component with nothing to compare against is not a component that is current, and collapsing the two is how an installation gets told it is up to date on no evidence at all+- **The release notes of every release the update crosses**, oldest first, each with its date and a `(preview)` marker when it is not stable. An answer that carries no release list falls back to the target release's changelog and release notes+- **Stacks with nothing to do** are gathered in one list at the bottom rather than omitted: silence about a stack reads as "not installed"+- **A check that did not complete** says so instead of saying "up to date" — the screen is reachable from a menu drawn by an earlier check, and "up to date" there would be the opposite claim+- **Keys**: `enter` continues to the apply form; `↑`/`↓`, `pgup`/`pgdown`, `home`/`end` scroll. Deliberately *not* the EULA's `enter`-pages-down: this screen asks for no consent, so the one unambiguous key belongs to the one action it offers+- **Width-aware markdown**: rendered through `styles.GetRendererForWidth()` (clamped to a readable band, memoised) instead of the fixed 80-column renderer, and re-rendered only when the wrap width actually changes — a drag-resize delivers a `WindowSizeMsg` per column and glamour is not cheap++### **Installer Update** (`models/installer_update.go`)++Its own screen rather than an operation form, because the operation is a single verified download and the generic form described it as replacing the running binary and exiting.++- **Says what it will do before it does it**: running version, offered version, platform (`os/arch`), download size and the full path the file will be written to. The package description is fetched on entry so the size is on screen *before* the user agrees to the download; the answer is reused by the download itself rather than asked for twice+- **Download and verification are the whole operation.** Length, `sha256` and signature are checked in a single pass as the bytes arrive; anything that fails is deleted rather than left behind under a release-looking name+- **The installer never replaces itself**, and that is deliberate rather than unfinished: a process cannot reliably overwrite the binary it is executing — Linux refuses the write, Windows holds the file locked — and failing halfway leaves the user with no installer at all. Instead the screen prints the exact command: `mv "<downloaded file>" "<running installer>"`, or `move /Y` on Windows plus a note to close the installer first. Both paths are quoted, so an installation under a path with a space does not become two arguments; when the running executable's path cannot be determined, no command is printed at all, because a command with a guessed destination is worse than none+- **One confirmation, for one thing**: a file already sitting under that exact name — a previous download, or one interrupted partway. Writing over empty space is not a question, so it is not asked. Declining still prints the move command, since the file the user chose to keep is the build they came for+- **Where the file lands**: beside the environment file, named `installer_<version>` (`.exe` on Windows), written directly under its final name — staging an executable through the system temp directory and moving it is a pattern antivirus and EDR products score heavily. A download that would land on the running binary is refused outright+- **Progress** is reported against the size from the package description rather than a `Content-Length`, which the encrypted response body does not carry, and printed once per 10% rather than once per read — a line every few kilobytes would bury everything around it in a panel that scrolls, and the path and the verification result are printed after the last of them+## 🎯 **Localization Architecture**### **Centralized Constants**@@ -245,7 +277,7 @@ Detailed guidance integrated into forms:### **Optimizations**- **Lazy Loading**: Content loaded on-demand when screens accessed-- **Single Renderer**: Shared glamour instance prevents freezing+- **Memoised Renderers**: one cached glamour instance per wrap width, built once instead of per render- **Efficient Scrolling**: Viewport-based rendering for large content- **Memory Management**: Proper cleanup and resource sharingdiff --git a/backend/docs/installer/processor-implementation.md b/backend/docs/installer/processor-implementation.mdindex 2617975d..f687eff2 100644--- a/backend/docs/installer/processor-implementation.md+++ b/backend/docs/installer/processor-implementation.md@@ -1,16 +1,17 @@# Processor Implementation Summary## Overview-Processor package implements the operational engine for PentAGI installer operations per [processor.md](processor.md). Core lifecycle flows, file integrity logic, Docker/Compose orchestration, and Bubble Tea integration are implemented. Installer self-update flows are stubbed and intentionally not finalized yet.+Processor package implements the operational engine for PentAGI installer operations per [processor.md](processor.md). Core lifecycle flows, file integrity logic, Docker/Compose orchestration, and Bubble Tea integration are implemented. Cloud-facing work — the update check, the installer download and the Jaeger storage plugin — is implemented too and talks to the PentAGI Cloud API through `cmd/installer/cloud`. Post-update verification is implemented as well, but it makes no request of its own: it compares the components observed after the update against targets captured locally from the answer that was already in hand.## Implementation Notes### Architecture Decisions- **Interface-based design**: Internal interfaces per operation type (`fileSystemOperations`, `dockerOperations`, `composeOperations`, `updateOperations`) enable separation of concerns and testability- **Two-track execution**: Docker API SDK for worker environment; Compose stacks via console commands with live output streaming-- **OperationOption pattern**: Functional options applied to an internal `operationState` support force mode and embedded terminal integration via `WithForce` and `WithTerminal`-- **State machine logic**: `ApplyChanges` implements three-phase stack management (Observability → Langfuse → PentAGI) with integrity validation; the wizard performs a pre-phase interactive integrity check with Y/N decision for force mode+- **OperationOption pattern**: Functional options applied to an internal `operationState` support force mode, embedded terminal integration and the reset-password value via `WithForce`, `WithTerminal` and `WithPasswordValue`+- **State machine logic**: `ApplyChanges` implements four-phase stack management (Observability → Langfuse → Graphiti → PentAGI) with integrity validation; the wizard performs a pre-phase interactive integrity check with Y/N decision for force mode- **Single-responsibility operations**: business logic delegates to compose layer; strict purge of images is implemented as `purgeImagesStack` alongside other compose operations+- **One lock for everything**: every entry point on `Processor` takes the processor mutex, including `InstallerPackage`, which changes nothing. It takes it because it *remembers* something the download that follows will read — see [Installer package description](#installer-package-description)### Key Features Implemented1. **File System Operations** (`fs.go`):@@ -18,7 +19,7 @@ Processor package implements the operational engine for PentAGI installer operat- Handle embedded directory trees (observability) and compose files- YAML validation and automatic file recovery- Support deployment modes (embedded/external/disabled) for applicable stacks- - Excluded files policy for integrity verification: `observability/otel/config.yml`, `observability/grafana/config/grafana.ini`, `example.custom.provider.yml`, `example.ollama.provider.yml` (presence ensured, content changes tolerated)+ - Excluded files policy for integrity verification (`filesToExcludeFromVerification`): presence ensured, content changes tolerated — service configs (`observability/otel/config.yml`, `observability/grafana/config/grafana.ini`), user-editable presets (`example.custom.provider.yml`, `example.ollama.provider.yml`, `neo4j/conf/neo4j.conf`, `neo4j/conf/apoc.conf`, `graphiti/{custom,gemini,litellm,openai}.yaml`) and both Jaeger storage plugin binaries2. **Docker Operations** (`docker.go`):- Worker and default image management with progress reporting@@ -32,21 +33,93 @@ Processor package implements the operational engine for PentAGI installer operat- Environment variable injection for compose commands- `purgeStack` (down -v) and `purgeImagesStack` (down --rmi all -v) placed together for clarity-4. **Update Operations** (`update.go`):- - Update server communication and binary replacement helpers are scaffolded (checksum, atomic replace/backup)- - Installer update/download/remove operations are currently stubs and return "not implemented"; network calls use placeholder logic for now+4. **Update Operations** (`update.go`, `jaeger_plugin.go`, `verify.go`):+ - `checkUpdates` refreshes the shared `checker.CheckResult` through `GatherUpdatesInfo` and returns nothing: the menus, the update screens and the operations all read the answer from there, and a second copy would be a second thing to keep current. Nothing calls it today — the answer is refreshed by `GatherAllInfo` at startup and by the re-gather every operation does when it finishes — so it is an entry point on the interface rather than a step on any current code path+ - `downloadInstaller` / `updateInstaller` fetch the offered build over `/api/v1/proxy/packages/info` → `/api/v1/proxy/packages/download` and leave it beside the environment file as `installer_<version>[.exe]`; both are the same operation reported under two names, because what would separate them — swapping the running binary — is out of scope+ - `installerPackage` describes the offered build without downloading it, for the screen that asks the user to agree to the download+ - `updateJaegerPlugin` fetches the Jaeger storage plugin, which is a mounted file rather than an image and so is invisible to `docker compose pull`+ - `removeInstaller` is the one member of the interface still returning "not implemented". It is reached by `Remove`/`Purge` on the installer stack, and the `all` fan-out visits that stack last, so both maintenance screens report a failure from their final step. Under "Remove" that is the whole cost: everything ahead of it has already run and nothing follows the loop. Under "Purge" it costs more — the error aborts the fan-out, and what sits after the loop never happens: the three custom Docker networks are not removed, and the deferred refresh of the update answer is skipped because it returns early on a failed operation5. **Remove/Purge Operations**:- Soft removal (preserve data) vs purge (complete cleanup); strict image purge via compose in `purgeImagesStack`- Proper cleanup ordering and external/existing deployment handling### Critical Implementation Details-- **Three-phase execution**: Observability → Langfuse → PentAGI with state validation after each phase+- **Four-phase execution**: Observability → Langfuse → Graphiti → PentAGI with state validation after each phase- **Force mode behavior**: Aggressive file overwriting and state correction when explicitly requested- **File integrity logic**: `ensureStackIntegrity` for missing files, `verifyStackIntegrity` for existing files; modified files are explicitly skipped and logged when `force=false`; excluded files are ensured to exist but not overwritten when modified- **State consistency**: `Gather*Info` calls after each phase validate operation success- **Error isolation**: Phase failures don't affect other stacks, partial state preserved- **Compose environment tweaks**: `COMPOSE_IGNORE_ORPHANS=1`, `PYTHONUNBUFFERED=1`; ANSI disabled on narrow terminals via `COMPOSE_ANSI=never`+- **Ordering inside a stack update**: the Jaeger plugin first — for observability only — then `downloadStack`, then `updateStack`, then a `restart` of the jaeger service when the plugin was actually replaced, and last the refresh of the answer. Writing the pull references is not a step in this sequence: `applyPullReferences` runs at the top of `downloadStack` and `updateStack` themselves, the only two compose operations that fetch anything, rather than at each of the five call sites that reach them — a call site that forgot would not fail to compile, because `${<COMPONENT>_IMAGE:-<default>}` quietly resolves to the default the compose file ships with and the operation would report success having fetched something the update server never offered. The plugin goes first because it is a mounted file no pull can bring up to date, and one that cannot be fetched must abort the update with nothing else disturbed, rather than leave images pulled and the stack restarted around a plugin that never arrived. The restart goes last because `up -d` recreates a container only when its spec changed, and a different file inside a bind mount is not a spec change — without it Jaeger goes on serving through the plugin it exec'd when it started, and the update reports success anyway+- **The Jaeger plugin is exempt from integrity verification**: both plugin paths are in `filesToExcludeFromVerification`, because the embedded copy and the update server are two sources for one path. Without the exemption a downloaded plugin reads as "modified", and a stack update — which runs with force — copies the embedded version back over it, undoing itself++### Operation Interfaces+The four internal interfaces in `processor.go` are how the business logic in `logic.go` reaches anything external. A method takes the `*operationState` when it produces output, because that is what carries the terminal panel and the message chain; the three that produce a value instead of output — `checkStackIntegrity`, `determineComposeFile` and `installerPackage` — do not:++```go+type updateOperations interface {+ checkUpdates(ctx context.Context, state *operationState) error+ downloadInstaller(ctx context.Context, state *operationState) error+ updateInstaller(ctx context.Context, state *operationState) error+ removeInstaller(ctx context.Context, state *operationState) error+ installerPackage(ctx context.Context) (*InstallerPackage, error)+ updateJaegerPlugin(ctx context.Context, state *operationState) (bool, error)+}+```++`installerPackage` is the odd one out here: it produces a value for a screen to render rather than output for a panel to show. `updateJaegerPlugin` is both at once: it takes a `state` because it downloads tens of megabytes and has to say so while it does, and it returns a `bool` beside the error — whether it actually replaced a file — because that is what decides the jaeger restart afterwards.++`updateOperationsImpl` is the only implementation and holds two mutable fields — `described` and `describedKey`, the remembered package description. They are plain fields rather than guarded ones because every path that touches them runs under the processor mutex: `installerPackage` takes it in `processor.InstallerPackage`, and the operations that reach `fetchInstaller` run under it too.++### Streaming Output Into the Terminal Panel+There are two producers of panel content, and they differ in whether the output is a whole view or a single line.++- `runCommand` hands the `*exec.Cmd` to `state.terminal.Execute`, waits for both the process and the terminal, and then sends `terminal.View()` as a **full** replacement (`isPartial=false`). Compose redraws its own progress in place, so the panel has to be the terminal's rendering rather than an append-only log.+- `appendLog` writes one line through `terminal.Append` and again sends the whole `View()`. This is what every cloud-facing operation uses: download progress, the plugin lines, the verification verdicts.++Both end at `operationState.sendOutput`, which appends a `ProcessorOutputMsg` to `state.msgs` under `state.mx`, stamped with its own 1-based position. Nothing is pushed to Bubble Tea — `HandleMsg` polls: handed a message numbered *n*, it returns `msgs[n]` (the next one) when it has arrived, and otherwise a `ProcessorWaitMsg` carrying the same *n* after 100 ms, which brings it back. The operation itself runs in a goroutine started by `wrapCommand`, which returns the first `ProcessorWaitMsg` as soon as the operation finishes or after 500 ms, whichever comes first. `ProcessorCompletionMsg` ends the chain by returning no command, and a `ProcessorWaitMsg` carrying an error stops the polling too. Walking an accumulated slice rather than draining a channel is what keeps the chain ordered and replayable when the screen is slower than the operation.++When no terminal is supplied, `newOperationState` builds a headless one (80×24, `WithNoPty`), so an operation invoked outside the wizard still produces the same message chain.++### Installer Package Description+`InstallerPackage` is the plain form of what the update server offers for this host — version, OS, arch, size — plus three fields the screen cannot compute for itself:++- `Path`: where the download will land, `installer_<version>[.exe]` in the directory holding `.env`. It is computed here rather than by the caller so that the name the screen promises and the name the download produces cannot drift apart.+- `Downloaded`: whether a file already sits at `Path`. It is the only thing the screen asks the user to confirm — downloading over nothing needs no permission, downloading over a file somebody may have put there on purpose does.+- `CurrentPath`: the running binary, or `""` when the OS would not say. `MoveCommand()` turns the pair into the exact `mv` (`move /Y` on Windows) the user runs afterwards, with both paths quoted so an installation under a directory with a space does not become two arguments. The installer never runs it: a process cannot reliably replace the binary it is executing — Linux answers `ETXTBSY`, Windows holds the file locked — so the operation honestly ends at "downloaded and verified".++**Why the description is reused by the download.** The screen has to state the size *before* the user agrees, which means `packages/info` is called on entering the screen and not only inside the download. Asking twice would cost a second proof-of-work challenge and a second slice of the account's daily allowance for one keypress, so `packageInfo` caches the answer in `described` and `fetchInstaller` reuses it.++The cache key is `version/GOOS/GOARCH`, not the version alone: the same version is published per platform with its own size, sha256 and signature, so a description of another platform's build would fail all three checks with a message about a corrupt download. On a failed download the description is dropped along with the partial file — it was the yardstick every check used, so a build republished under the same version would otherwise make every retry fail identically forever.++### Where Downloaded Files Are Written+Neither download goes through the system temp directory. Writing an executable to `%TEMP%` and then moving it is a pattern antivirus and EDR products score heavily, and a false positive there costs the user the update.++- **The installer** is written straight under its final name in the directory the installation lives in. Before opening it, `fetchInstaller` refuses to write to a path that is the running binary, comparing by inode rather than by string — a symlink or a different spelling of the same directory compares unequal as text while naming one file. The versioned name normally makes the collision impossible, but an installer renamed to `installer_<its own version>` lands exactly there, and `O_TRUNC` would empty the binary the user is running: Linux answers `ETXTBSY`, macOS does not.+- **The Jaeger plugin** is staged as `<target>.new` in the *same* directory as its target and moved with `os.Rename`, which is atomic only within one filesystem. Staging matters because the file being replaced is the one a running Jaeger has loaded; an in-place write cut short would leave a truncated plugin and the container would come back up with an opaque gRPC error. Mode `0755` is set at creation and not afterwards — `os.Rename` does not preserve the destination's mode, so a plugin created `0644` and renamed over an executable one ends up not executable, and Jaeger again fails with a gRPC error rather than a permission one.++On failure both paths delete what they wrote: verification only completes on the last byte, so anything left behind is unverified. Leftover `.new` files from an interrupted run are removed at the start of `updateJaegerPlugin` — always, even when there is nothing to fetch, because integrity verification only walks the files the installer ships and would never see a ~28 MB stranger. They are deleted by exact name rather than by globbing `*.new`: the directory is mounted into a container and an operator may keep their own files in it.++Both architectures of the plugin are kept in step regardless of the host, because which one runs is decided inside the container by the Docker VM's architecture — the compose entrypoint picks the file by `uname -m` at start. Only components the check marked outdated are fetched: membership in the answer is not the test, since a curated release names every artefact it knows about, and fetching everything listed would mean ~28 MB per architecture on every observability update. A component whose OS is not linux is skipped — the file name says `linux`, and content for another platform would be written under a linux name.++### Download Progress+`progressWriter` sits in an `io.MultiWriter` beside the destination file, so the bytes are counted on their way past without a second pass.++Its percentage is computed against `info.Size` from the package description, **not** a `Content-Length`: the response body is encrypted, which removes that header, so the description is the only size the client ever learns. This is also why `installerPackage` and `fetchInstaller` both need a description in hand before anything can start.++Two details are deliberate. A line is printed once per `progressStepPercent` (10%) rather than per read — a line every few kilobytes would bury the file path and the verification verdict in a panel that scrolls. And the percentage is clamped to 100: a stream longer than advertised is caught by the length check in `cloud.DownloadPackage`, and it is not the indicator's job to report it. With `total == 0` the writer stays silent instead of dividing by zero.++`FormatSize` is exported so the screen and the progress lines it prints into use one renderer; they end up in the same panel, and two formatters would eventually disagree about the same number in front of the user.++`cloud.DownloadPackage` checks three things in the same single pass the progress writer counts in — the byte count against `info.Size`, the sha256 against `info.Hash`, and an Ed25519 signature over the file's SHA-512 digest. The verdict therefore already exists when the call returns, which is why the line printed after it is past tense: `Checksum and signature verified`.++### Post-Update Verification+`verify.go` answers one question after a stack update: did the artefacts now installed become the ones that were offered? Targets are captured **before** the update (`captureStackTargets`), because the deferred `GatherUpdatesInfo` replaces the answer — comparing against the refreshed one would compare the result with itself and always agree.++The comparison runs inside the same `defer`, after the refresh, because the fresh answer is what decides whether anything is still pending. That distinction is made on evidence rather than heuristics: when a component differs from its captured target *and* the fresh answer no longer offers an update for the stack, the registry moved ahead between the answer and the pull, and the line says so; when the offer is still there, it is a mismatch. A failed refresh has no appeal — `stackHasNoUpdate` returns false — and a difference counts as a mismatch.++Verification never fails the operation. The update either worked or already reported an error; turning "the registry moved ahead" into a failed update would be worse than saying nothing. The installer stack is excluded from `verifiableUpdateStacks` on purpose: its operation downloads a build without applying it, so comparing against the running binary would report the intended outcome as a mismatch.### Testing StrategyComprehensive tests include:@@ -54,6 +127,10 @@ Comprehensive tests include:- Unit tests for file system integrity operations (ensure/verify/cleanup, excluded files policy, YAML validation)- Validation tests for operation applicability- Factory reset, lifecycle, and ordering behavior at logic level+- `update_test.go` — progress stepping and clamping, silence without a size, the description key, cleanup of file and description after a failed download, the versioned file name, the inode comparison guarding the running binary, `MoveCommand` quoting, `FormatSize`+- `jaeger_plugin_test.go` — only outdated linux components are fetched, a failed download leaves the running plugin alone, the installed plugin is executable, staging leftovers are removed by exact name, the plugin is exempt from integrity verification+- `verify_test.go` — targets captured before the answer is replaced, an already current component's target is what it runs, an unverifiable component carries no target, "newer" is distinguished from "wrong", the installer is not verified against the running binary+- `pull_reference_test.go` — the compose variable is derived from the component name, only resolved components get a reference, and every `image:` in the shipped compose files is parameterised### Integration Points- **State management**: Integrates with `state.State` for configuration and environment variables@@ -64,25 +141,32 @@ Comprehensive tests include:## Files Created/Modified### Core Implementation-- `processor.go` - Processor interface, options, and synchronous operations entry points+- `processor.go` - Processor interface, options, operation interfaces, and synchronous operations entry points- `model.go` - Bubble Tea `ProcessorModel` with `HandleMsg` polling- `logic.go` - Business logic (ApplyChanges, lifecycle operations, factory reset)+- `state.go` - `operationState`, message types and the `sendOutput`/`sendCompletion` chain- `fs.go` - File system operations and integrity verification- `docker.go` - Docker API/CLI operations and worker image/volumes management- `compose.go` - Docker Compose stack lifecycle management (including `purgeImagesStack`)-- `update.go` - Scaffolding for update mechanisms (stubs for installer update flows)+- `update.go` - Update check, installer package description and download, progress reporting+- `jaeger_plugin.go` - Jaeger storage plugin download with staged install+- `verify.go` - Post-update comparison of installed artefacts against what was offered+- `pull_reference.go` - Writing the server-chosen image reference into `.env` before a pull+- `reference_drift.go` - Reporting compose variables that differ from what this build ships+- `locale.go` - Operation message strings### Testing- `mock_test.go` - Mocks for interfaces with call tracking- `logic_test.go` - Business logic tests (state machine and sequencing)- `fs_test.go` - File system operations tests (including excluded files policy)+- `update_test.go`, `jaeger_plugin_test.go`, `verify_test.go`, `pull_reference_test.go`, `compose_test.go`## Status-✅ **MOSTLY COMPLETE** - Core processor functionality implemented and tested+✅ **COMPLETE** - Processor functionality implemented and tested, with one known gap- Lifecycle, file integrity, Docker/Compose orchestration are production-ready- Bubble Tea integration via `ProcessorModel` is complete-- Installer self-update flows (download/update/remove) are stubbed and not enabled yet-- All current tests pass; additional tests will be added once update flows are finalized+- Installer download/update, Jaeger plugin download and post-update verification are implemented and covered by tests+- `removeInstaller` remains unimplemented; because `Remove`/`Purge` on `all` end on the installer stack, both maintenance screens finish with a "not implemented" error. Under "Remove" the real work is already done by then; under "Purge" the failure also skips everything after the fan-out — the three custom Docker networks stay in place and the update answer is not refreshed## Current Architecture@@ -103,10 +187,16 @@ type ProcessorModel interface {Start(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.CmdStop(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.CmdRestart(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.Cmd+ ResetPassword(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.CmdHandleMsg(msg tea.Msg) tea.Cmd++ // InstallerPackage describes the installer build on offer without downloading it.+ InstallerPackage(ctx context.Context) (*InstallerPackage, error)}```+`InstallerPackage` is blocking rather than a `tea.Cmd`, unlike everything above it: it is one short request with one answer, not an operation that streams output into a terminal panel, and the screen that needs it already wraps it in a command of its own.+### Message TypesProcessor operations communicate via messages:- `ProcessorStartedMsg` - operation started@@ -116,4 +206,4 @@ Processor operations communicate via messages:- `ProcessorWaitMsg` - polling tick### Terminal Integration-Operations support real-time terminal output through `WithTerminal(term terminal.Terminal)`; ANSI is auto-disabled for narrow terminals. Compose commands inherit current env plus `COMPOSE_IGNORE_ORPHANS=1` and `PYTHONUNBUFFERED=1`.+Operations support real-time terminal output through `WithTerminal(term terminal.Terminal)`; ANSI is auto-disabled for narrow terminals (< 56 columns) and on Windows. Compose commands inherit current env plus `COMPOSE_IGNORE_ORPHANS=1` and `PYTHONUNBUFFERED=1`. Without the option an operation still runs, against a headless 80×24 terminal built by `newOperationState`. See [Streaming Output Into the Terminal Panel](#streaming-output-into-the-terminal-panel) for how a line becomes a message.diff --git a/backend/docs/installer/processor-wizard-integration.md b/backend/docs/installer/processor-wizard-integration.mdindex e5736217..d35256b3 100644--- a/backend/docs/installer/processor-wizard-integration.md+++ b/backend/docs/installer/processor-wizard-integration.md@@ -44,15 +44,21 @@ type Processor interface {Stop(ctx context.Context, stack ProductStack, opts ...OperationOption) errorRestart(ctx context.Context, stack ProductStack, opts ...OperationOption) errorResetPassword(ctx context.Context, stack ProductStack, opts ...OperationOption) error++ // InstallerPackage describes the installer build on offer without downloading it.+ InstallerPackage(ctx context.Context) (*InstallerPackage, error)}```**Bubble Tea integration** in [`model.go`](../../cmd/installer/processor/model.go), [`state.go`](../../cmd/installer/processor/state.go), and [`logic.go`](../../cmd/installer/processor/logic.go):- Wraps processor operations as `tea.Cmd` values through `ProcessorModel`- Streams operation updates through `ProcessorStartedMsg`, `ProcessorOutputMsg`, `ProcessorFilesCheckMsg`, and `ProcessorCompletionMsg`+- Pumps that stream with `ProcessorWaitMsg` — the screen's reply to each message is what asks for the next one (see [The message chain](#the-message-chain))- Executes commands through the shared `terminal.Terminal` abstraction when available- Falls back to non-ANSI compose output on small terminals and Windows by setting `COMPOSE_ANSI=never`+`ProcessorModel.InstallerPackage(ctx)` is the one exception to the pattern: it returns `(*InstallerPackage, error)` rather than a `tea.Cmd`. It is a single short request with a single answer, not an operation that streams into a terminal panel, and the one screen that needs it wraps it in a command of its own.+### Integration Pattern**Wizard Screen Integration** (see [`apply_changes.go`](../../cmd/installer/wizard/models/apply_changes.go)):@@ -72,7 +78,7 @@ return m.processor.ApplyChanges(context.Background(), processor.WithTerminal(m.t## Message Flow Architecture-The integration uses a **buffered channel-based approach** for real-time terminal output streaming:+The integration is **message-driven in both directions**: the operation appends messages to its own state and the screen asks for the next one, while the terminal panel is fed directly by the running command and signals the UI when its content changes (see [The message chain](#the-message-chain)):```mermaidgraph TD@@ -135,11 +141,63 @@ Depending on choice, `processor.ApplyChanges()` is called with/without `WithForcNote: the integrity prompt lists only modified files; missing files are considered normal on a fresh installation and are not shown to the user.**Key Improvements:**-- **50ms polling** via `waitForOutput()` for responsive UI updates-- **Buffered channel** (100 messages) prevents blocking+- **Message replay, not polling** — the operation appends to `operationState.msgs` and `HandleMsg` hands back the next entry; it falls back to a 100 ms wait only when there is nothing new+- **No message cap and no shared channel** — `msgs` is a slice that grows with the operation, so nothing about a slow screen can block the operation- **Direct key mapping** - no intermediate input buffers- **Viewport delegation** for scrolling (PageUp/PageDown, mouse wheel)+## Maintenance entries and the screens behind them++The maintenance list ([`maintenance.go`](../../cmd/installer/wizard/models/maintenance.go)) carries no behaviour of its own: `LoadItems` appends a `ListItem` holding a `ScreenID`, and `HandleSelection` turns the selected one into a `NavigationMsg{Target: item.ID}`. Changing what an entry does is therefore changing which screen its `ScreenID` names. Two entries no longer name the generic operation form.++**Update PentAGI** points at `UpdateOverviewScreen` (`"update_overview"`), not at `UpdatePentagiScreen` (`"processor_operation_form§compose§update"`). [`update_overview.go`](../../cmd/installer/wizard/models/update_overview.go) renders what the update would change — the version move per stack, the per-component plan, and the release notes crossed on the way — and on `enter` emits `NavigationMsg{Target: UpdatePentagiScreen}`. The overview is inserted **between** the entry and the form; the form, its availability check and its `y/n` confirmation are untouched, so the sequence is entry → overview → form, not a replacement.++The overview screen holds no `ProcessorModel` and starts no operation — `NewUpdateOverviewModel` takes only the controller, styles and window. Everything it shows already sits in the last check result read through `controller.GetChecker()`, so it makes no network call and cannot fail. What separates "nothing to update" from "we never found out" is `CheckResult.UpdateFailure`, not the emptiness of `StackUpdates`: the screen is reachable from a menu entry drawn off an earlier check, and printing "up to date" after a check that never completed would be a claim in exactly the wrong direction.++`enter` here means *continue*, not *page down* as it does on the EULA screen. EULA spends `enter` on paging because consent there is given by separate `y`/`n` keys; the overview asks for no consent, so its one unambiguous key belongs to the one action it offers, and scrolling is left to the arrows, `pgup`/`pgdown` and `home`/`end`.++**Update Installer** points at `InstallerUpdateScreen` (`"installer_update"`), a screen of its own in [`installer_update.go`](../../cmd/installer/wizard/models/installer_update.go). The `ScreenID` it replaced was `"processor_operation_form§installer§update"` — a generic operation form — and the `ProductStackInstaller` branches went out with it: `getOperationInfo`, `isActionAvailable` and `renderEffectsText` in [`processor_operation_form.go`](../../cmd/installer/wizard/models/processor_operation_form.go) no longer mention that stack, and the help and effects strings those branches used — `ProcessorHelpUpdateInstaller`, `EffectsUpdateInstaller` — are gone from the locale. The two the menu entry itself is drawn from stayed: `MaintenanceUpdateInstaller` and `MaintenanceUpdateInstallerDesc` are what the new screen returns from `GetFormName`, `GetFormTitle` and `GetFormDescription`, deliberately, so the entry reads the way it always did. This is a replacement rather than a rename: the form's help promised to replace the running binary and exit, which no version of the installer has ever done, and a confirmation guarding an operation that does not exist is worse than none. The screen names the running version, the offered version, the platform, the download size and the full target path first, then offers one action.++`processor.ProductStackInstaller` itself still exists and is still what the screen passes to `processor.Update` — only the wizard's generic branch for it is gone.++**Confirmation is not shared between the two screens.** The generic form keeps `requiresConfirmation` for the stack operations that have it — update of `all`/`compose`, factory reset, purge — and on `enter` it clears the terminal, prints the confirmation and waits for `y`/`n`. The installer screen asks nothing about the download itself; its only question is whether to write over a file already sitting at the target path (`InstallerPackage.Downloaded`), because downloading over nothing needs no permission. `n` there is not a dead end: the file the user chose to keep is the build they came for, so the screen prints the same move command a finished download would have printed.++**Adding a screen takes four registrations, and the second one has no symptom when it is missing.** A `ScreenID` constant in [`types.go`](../../cmd/installer/wizard/models/types.go); a branch in `models.RestoreModel` in the same file; registration in `registry.initScreens` ([`registry.go`](../../cmd/installer/wizard/registry/registry.go)); and the locale strings, plus a hotkey caption in `app.initHotkeysLocale` if the screen uses a combination the map does not already have.++What a missing `RestoreModel` branch costs is worth stating precisely, because the obvious answer is wrong. `app.forwardMsgToCurrentModel` calls `app.currentModel.Update(msg)` and reassigns `app.currentModel` only when `RestoreModel` returns non-nil — but every screen here has a pointer receiver and returns itself, so the mutation has already happened in place and the returned `tea.Cmd` is propagated either way. Nothing freezes today; the skipped step is a reassignment of a pointer the app already holds. The branch is load-bearing for the case the type allows but nobody has written yet: a screen whose `Update` returns a *different* model, which would then be dropped with no error anywhere. `installer_update_test.go` asserts every screen's presence in `RestoreModel` for that reason — the contract is "every screen is listed" rather than "list the ones that need it", because the day a screen starts returning something else is not the day anybody remembers this rule.++## The message chain++A screen does not poll the processor; it answers it. Understanding this is the difference between a screen that finishes an operation and one that appears to hang halfway through.++`wrapCommand` in [`model.go`](../../cmd/installer/processor/model.go) starts the operation on a goroutine under the processor mutex and then waits before returning a `tea.Cmd` producing a `ProcessorWaitMsg` — until the operation returns, until the context is cancelled, or 500 ms, whichever comes first. That wait happens inside the caller, so the screen's `Update` or key handler can be held for up to half a second before the first frame is drawn. Meanwhile the operation appends messages to `operationState.msgs` ([`state.go`](../../cmd/installer/processor/state.go)): `ProcessorStartedMsg`, one `ProcessorOutputMsg` per output update, `ProcessorFilesCheckMsg` where files are scanned, and a final `ProcessorCompletionMsg`. Each message carries the state it came from and its own index.++`ProcessorModel.HandleMsg` is what advances it: given a message, it replays the next entry of `state.msgs` if one exists, and otherwise waits 100 ms and emits another `ProcessorWaitMsg` for the same index. So the rule for a screen is mechanical — **return `m.processor.HandleMsg(msg)` for every processor message received**, including the ones it has nothing to do with:++```go+case processor.ProcessorStartedMsg:+ return m, m.processor.HandleMsg(msg)++case processor.ProcessorOutputMsg:+ // ignore (handled by terminal)+ return m, m.processor.HandleMsg(msg)++case processor.ProcessorWaitMsg:+ return m, m.processor.HandleMsg(msg)++case processor.ProcessorCompletionMsg:+ m.handleCompletion(msg)+ return m, m.processor.HandleMsg(msg)+```++Swallow any one of these types and the chain stops there: no further output arrives and the completion never does, so the screen sits on its "in progress" line forever with the operation actually finished behind it.++Two ends are deliberate. `HandleMsg` returns `nil` for `ProcessorCompletionMsg` — it is the last message, and asking for another would only spin. It also returns `nil` for a `ProcessorWaitMsg` carrying an error, which is how a cancelled context stops the polling rather than leaving a command re-arming itself every 100 ms.++`ProcessorOutputMsg` is forwarded but its content is ignored by screens that pass `WithTerminal(m.terminal)`: the operation writes into that same terminal directly, so the panel is already current, and the message exists here only to keep the chain moving. What a screen actually reacts to is `ProcessorCompletionMsg` — that is where it clears its `running` flag and appends whatever it has left to say. In [`installer_update.go`](../../cmd/installer/wizard/models/installer_update.go) that is `handleCompletion`: on `msg.Error != nil` it appends the failure line and stops, and otherwise it appends the move instructions — where the build is, and the exact command that puts it in place, replaced by a plain "move it over the installer you launched" when `os.Executable` gave no path to build a command from. Windows gets one line more, because it will not replace a program that is running. What the screen does not repeat is the verification: the operation has already reported that the checksum and signature matched, and saying it twice would read as a second event.++Only the current screen sees these messages. `app.Update` broadcasts `tea.WindowSizeMsg` to every registered screen through `registry.HandleMsg`, but everything else goes to `forwardMsgToCurrentModel` — which is why each screen that runs operations spells out the processor cases itself rather than inheriting them.+## Implementation Guide### 1. Screen Model Setup@@ -172,43 +230,72 @@ func (m *YourFormModel) BuildForm() tea.Cmd {### 2. Update Method Integration-Handle terminal model updates with proper type assertion and input delegation:+Route each message to exactly one owner. Terminal updates are restored through `terminal.RestoreModel`, processor messages are answered with `HandleMsg`, and anything unrecognised falls through to the terminal so scrolling keeps working:```gofunc (m *YourFormModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {- var cmds []tea.Cmd+ handleTerminal := func(msg tea.Msg) (tea.Model, tea.Cmd) {+ if m.terminal == nil {+ return m, nil+ }- // Update terminal model first (handles real-time output)- if m.terminal != nil {- updatedModel, terminalCmd := m.terminal.Update(msg)+ updatedModel, cmd := m.terminal.Update(msg)if terminalModel := terminal.RestoreModel(updatedModel); terminalModel != nil {m.terminal = terminalModel}- if terminalCmd != nil {- cmds = append(cmds, terminalCmd)- }++ return m, cmd}switch msg := msg.(type) {case tea.WindowSizeMsg:- // Update terminal size dynamically+ contentWidth, contentHeight := m.getViewportFormSize()if m.terminal != nil {- contentWidth, contentHeight := m.getViewportFormSize()+ if !m.isVerticalLayout() {+ contentWidth -= 2+ }m.terminal.SetSize(contentWidth-2, contentHeight-1)}+ m.updateViewports()++ return m, nil++ case terminal.TerminalUpdateMsg:+ return handleTerminal(msg)++ // every processor message is answered, or the chain stops here+ case processor.ProcessorCompletionMsg:+ m.handleCompletion(msg)+ return m, m.processor.HandleMsg(msg)++ case processor.ProcessorStartedMsg:+ return m, m.processor.HandleMsg(msg)++ case processor.ProcessorOutputMsg:+ // ignore (handled by terminal)+ return m, m.processor.HandleMsg(msg)++ case processor.ProcessorWaitMsg:+ return m, m.processor.HandleMsg(msg)case tea.KeyMsg:- // Terminal takes priority when operation is running+ // terminal takes priority while a command is runningif m.terminal != nil && m.terminal.IsRunning() {- return m, tea.Batch(cmds...) // Terminal already processed input+ return handleTerminal(msg)}- // Your screen-specific hotkeys here...- }+ // your screen-specific hotkeys here...- return m, tea.Batch(cmds...)+ // pass other keys to terminal for scrolling etc.+ return handleTerminal(msg)++ default:+ return handleTerminal(msg)+ }}```+See [The message chain](#the-message-chain) for why the three processor cases that appear to do nothing still have to be there.+### 3. Operation TriggersStart processor operations through terminal model:@@ -216,6 +303,8 @@ Start processor operations through terminal model:```go// In your action handlerfunc (m *YourFormModel) startProcess() tea.Cmd {+ m.running = true+return m.processor.Install(context.Background(),processor.WithTerminal(m.terminal),@@ -223,6 +312,8 @@ func (m *YourFormModel) startProcess() tea.Cmd {}```+Operations taking a `ProductStack` take it as the second argument — the installer screen, for instance, runs `m.processor.Update(ctx, processor.ProductStackInstaller, processor.WithTerminal(m.terminal))`. The `running` flag is the screen's own; it is set here and cleared on `ProcessorCompletionMsg`, and it is what keeps `enter` from starting a second operation while the first is still going.+### 4. Display IntegrationRender terminal within your screen layout - simplified approach:@@ -247,7 +338,7 @@ func (m *YourFormModel) renderMainPanel() string {## Features & Capabilities### Interactive Terminal-- **Real-time output**: 50ms polling via buffered channel (100 messages)+- **Real-time output**: the running command's stdout/stderr are read by scanner goroutines straight into the terminal's buffer, and a single-waiter notifier wakes the UI with a `TerminalUpdateMsg` when the content changes — no polling interval to tune- **Native input handling**: Direct key-to-terminal-sequence conversion- **ANSI support**: Colors, formatting, progress bars rendered correctly- **Smart scrolling**: PageUp/PageDown and mouse wheel for viewport, all other keys to PTY@@ -285,10 +376,10 @@ Choose integration method based on screen requirements:## Limitations & Considerations### Performance-- **Memory usage**: Output buffer auto-managed, channel limited to 100 messages-- **Goroutine management**: Automatic cleanup via `defer close(outputChan)`-- **Resource overhead**: Minimal - one goroutine per operation, 1ms throttling-- **Update frequency**: 50ms polling prevents UI blocking+- **Memory usage**: `operationState.msgs` grows for the life of the operation and is not capped — a very chatty operation keeps every message it produced until the state is dropped+- **Goroutine management**: one goroutine per operation, started by `wrapCommand` and finished when the operation returns; the terminal's reader goroutines end with the command's pipes+- **Resource overhead**: minimal — nothing spins while an operation is idle+- **Update frequency**: `HandleMsg` returns the next message immediately when one exists, and waits 100 ms only when none has arrived yet### Platform Compatibility- **Unix/Linux/macOS**: Full pseudoterminal support via `github.com/creack/pty v1.1.21`@@ -329,4 +420,4 @@ Processor model behavior can be tested independently of wizard integration (see- **Operation queuing**: Sequential command execution with progress tracking- **Error recovery**: Automatic retry mechanisms with user confirmation-This clean, channel-based architecture provides a maintainable foundation for embedding professional terminal functionality within Bubble Tea applications while maximizing screen real estate and user experience.+This clean, message-driven architecture provides a maintainable foundation for embedding professional terminal functionality within Bubble Tea applications while maximizing screen real estate and user experience.diff --git a/backend/docs/installer/processor.md b/backend/docs/installer/processor.mdindex 915e9e15..c4eb5a94 100644--- a/backend/docs/installer/processor.md+++ b/backend/docs/installer/processor.md@@ -20,7 +20,7 @@ graph TBsubgraph "External Systems"Docker[Docker Engine<br/>Container Management]FS[File System<br/>Host OS]- UpdateServer[Update Server<br/>pentagi.com]+ UpdateServer[PentAGI Cloud API<br/>update.pentagi.com]Compose[Docker Compose<br/>Stack Orchestration]end@@ -47,7 +47,7 @@ graph TB## Terms and Definitions-- **ProductStack**: Logical grouping of services that can be managed as a unit (pentagi, langfuse, observability, worker, installer, all)+- **ProductStack**: Logical grouping of services that can be managed as a unit (pentagi, graphiti, langfuse, observability, compose, worker, installer, all)- **Deployment Modes**: embedded (full local stack), external (existing service), disabled (no functionality)- **State**: Persistent configuration storage including .env variables and wizard navigation stack- **Checker**: System environment assessment providing current installation status and capabilities@@ -69,7 +69,11 @@ graph TB- **docker.go**: Docker API/CLI interactions for images, containers, networks, and volumes (worker + main)- **fs.go**: File system operations and embedded content extraction with excluded files policy- **logic.go**: Business logic (ApplyChanges state machine, lifecycle operations, factory reset)-- **update.go**: Update/download/remove scaffolding (installer flows currently stubbed)+- **update.go**: Cloud-facing operations — update check, installer package description, installer download with progress reporting+- **pull_reference.go**: Writes the image references the cloud chose into `.env` before a compose pull+- **jaeger_plugin.go**: Downloads the Jaeger storage plugin (a file, not an image) and puts it in place+- **verify.go**: Post-update comparison of what is installed against what was offered+- **reference_drift.go**: Reports compose image variables pointing at a repository this build does not ship- **state.go**: Operation state, messages, and terminal integration helpers### ProductStack Types@@ -78,12 +82,14 @@ graph TBtype ProductStack stringconst (- StackPentAGI ProductStack = "pentagi" // Main stack (docker-compose.yml)- StackLangfuse ProductStack = "langfuse" // LLM observability (docker-compose-langfuse.yml)- StackObservability ProductStack = "observability" // System monitoring (docker-compose-observability.yml)- StackWorker ProductStack = "worker" // Docker images for AI agent tasks- StackInstaller ProductStack = "installer" // Installer binary itself- StackAll ProductStack = "all" // Context-dependent multi-stack operation+ ProductStackPentagi ProductStack = "pentagi" // Main stack (docker-compose.yml)+ ProductStackGraphiti ProductStack = "graphiti" // Knowledge graph (docker-compose-graphiti.yml)+ ProductStackLangfuse ProductStack = "langfuse" // LLM observability (docker-compose-langfuse.yml)+ ProductStackObservability ProductStack = "observability" // System monitoring (docker-compose-observability.yml)+ ProductStackCompose ProductStack = "compose" // The four compose stacks together+ ProductStackWorker ProductStack = "worker" // Docker images for AI agent tasks+ ProductStackInstaller ProductStack = "installer" // Installer binary itself+ ProductStackAll ProductStack = "all" // Context-dependent multi-stack operation)```@@ -106,24 +112,78 @@ const (### Installation & Content Management- **Download(stack)**:- - pentagi/langfuse/observability: `docker compose pull`- - worker: `docker pull ${DOCKER_DEFAULT_IMAGE_FOR_PENTEST}` (default 6GB+)- - installer: stubbed (not implemented fully yet)- - all: download all applicable stacks+ - pentagi: `docker compose pull`; graphiti/langfuse/observability: the same, but only in embedded mode (external/disabled stacks are skipped)+ - worker: `docker pull ${DOCKER_DEFAULT_IMAGE_FOR_PENTEST}` (default 6GB+), then refresh worker and update facts+ - installer: download and verify the offered installer build (no-op when already current, error when the update server is unreachable) — see *Installer self-update* below+ - compose: the four compose stacks in order+ - all: compose stacks, then worker, then installer- **Install(stack)**:- pentagi: extract compose file and example provider config- langfuse: extract compose file (embedded mode only)- observability: extract compose file and directory tree (embedded mode only)+ - graphiti: extract compose file plus the `graphiti/` and `neo4j/` directory trees (embedded mode only)- worker: download images- installer: not applicable- - all: install all configured stacks+ - all: install all configured stacks (only the ones not yet installed)- **Update(stack)**:- - pentagi/langfuse/observability: download → `docker compose up -d`- - worker: download only (no forced restart)- - installer: stubbed (checksum/replace helpers exist, flow returns not implemented)- - all: sequence with dependency ordering+ - pentagi/graphiti/langfuse/observability: no-op when the checker already says the stack is up to date; otherwise (observability only) update the Jaeger storage plugin → `docker compose pull` → `docker compose up -d` → restart the `jaeger` service if that plugin was actually replaced → re-gather that stack's facts. Writing the image references is not a separate first step: the pull and the `up -d` each write them into `.env` themselves (see *Image references are written before the pull*)+ - worker: pull worker images only (no forced restart)+ - installer: same download-and-verify as `Download`; the running binary is never replaced+ - compose: the four compose stacks in order observability → langfuse → graphiti → pentagi+ - all: the compose stacks in that order, then worker, then installer+ - every update ends with a fresh update check followed by a verification report (see *Post-update verification*)++#### Image references are written before the pull++Every `image:` in the shipped compose files is `${<COMPONENT>_IMAGE:-<default>}`, so the variable — not the file — decides what `docker compose pull` fetches. `applyPullReferences(stack)` reads `PullReference` from the components of that stack in the last check answer and writes them into `.env` via `state.WriteVars`, logging every `NAME=reference` it wrote.++`WriteVars` and **not** `SetVars`. Everything else in the state package stages: `SetVar`/`SetVars` record an intention that reaches `.env` only when the user applies their changes. The pull that follows is `docker compose --env-file <.env>`, so a staged variable is one compose has never heard of — `${PENTAGI_IMAGE:-vxcontrol/pentagi:latest}` falls back to the default, the pull fetches something the server never offered, and the update reports success. `WriteVars` re-reads the file from disk, sets these values on it and saves, so the user's pending edits are neither applied nor lost, and the installation is not left dirty by a value the installer wrote for itself.++- The variable name is derived from the component name (upper case, `-` → `_`, suffix `_IMAGE`) rather than kept in a table, so a new component needs no second registration; a mismatch degrades to "the compose default was used", which `docker compose config` shows.+- It runs **before** the pull. Writing afterwards would pull the old reference and then record the new intention — an update that reports success and changes nothing.+- The installer does not choose a tag. `pull_reference` is ready to use as it arrives and is not always `repository:tag` — it may name a more specific, immutable tag than the one the compose file carries, and a client that rebuilt `repository:tag` locally would silently pull something it was never offered.+- Components the answer did not resolve carry no reference and are skipped. Writing an empty value would work (`${VAR:-default}` treats empty as absent) but would erase a reference an earlier answer pinned.+- A write failure is returned rather than logged and swallowed, for the same reason.+- Skipping is safe by construction: an installation that never got an answer falls back to the reference the compose file shipped with and behaves exactly as before.+- Every operation that fetches writes them, because the write lives in `updateStack` and `downloadStack` rather than at the call sites. There are more call sites than is comfortable — `Update` (which calls both), `Download`, `Install` and the four `ApplyChanges` phases — and the one that forgot would not be a compile error: `${COMPONENT_IMAGE:-default}` would quietly resolve to the shipped default and the operation would report success having fetched something the server never offered. The tear-down operations deliberately do not write: `down` needs no reference, and writing one while removing a stack would be a side effect nobody asked for.+- `ReferenceDrift()` is the separate query for the opposite problem: variables pointing at a different *repository* than this build ships. A different tag of the same repository is the mechanism working, not drift, so it is not reported; realignment is a deliberate user action, never a side effect of an update.++#### Jaeger storage plugin (observability only)++The plugin is a **file** mounted into the Jaeger container, which loads it over gRPC — no amount of image pulling updates it. Both architectures (`observability/jaeger/bin/jaeger-clickhouse-linux-amd64` and `-arm64`) are kept in step, because which one runs is decided inside the container by the architecture of the Docker VM and the entrypoint picks the file by `uname -m` at start.++- Fetched **before** the images. A plugin that cannot be downloaded aborts the stack update with nothing else disturbed; doing it afterwards would leave images pulled and the stack restarted around a plugin that never arrived.+- `updateJaegerPlugin` reports **whether it replaced anything**, and when it did, the update restarts the `jaeger` service after `up -d`. The `up -d` is not enough on its own: compose recreates a container only when its *spec* changes, and a different file inside a bind mount is not a spec change. The plugin is exec'd by the entrypoint at container start, so when the plugin was replaced but the Jaeger image was not, the container keeps running the plugin it loaded when it came up — the update looks applied while nothing about it is. The restart is skipped when nothing was replaced, so an observability update that only moves images does not bounce Jaeger for no reason.+- Only components the checker marked outdated are fetched. Membership in the answer is not the test — it also lists artefacts that are already current — so "download everything listed" would mean ~28MB per architecture on every observability update. Components whose OS is not linux are skipped as well: the file name says linux, and content for another platform would land under a linux name.+- Written to `<target>.new` **in the target's own directory** and renamed into place. The file being replaced is the one a running Jaeger loads, so an interrupted in-place write would leave a truncated plugin and the container would come back up with an opaque gRPC error. The staging file is a sibling because `os.Rename` is atomic only within one filesystem, and because writing an executable to the system temp directory and moving it is the pattern antivirus and EDR products score heavily.+- Created with mode `0755` **at creation**, not afterwards: `os.Rename` does not carry the destination's mode, the result keeps the staging file's, and a plugin created `0644` ends up non-executable — with Jaeger failing on a gRPC plugin error rather than a permission one.+- Leftover `.new` files are removed at the start of every run, whether or not anything is to be fetched: an interrupted download leaves ~28MB that nothing else would ever clean up, because integrity verification only walks files the installer ships. Removal is by exact name and never by glob — the directory is mounted into a container and an operator may keep their own files there.+- Both plugin paths are in `filesToExcludeFromVerification` with the "create if missing, never overwrite" policy. Without that the update would undo itself: the downloaded plugin differs from the embedded copy, so integrity verification calls it modified and under force — which is the path a stack update takes — copies the shipped version back over it.++#### Post-update verification++Every successful update answers one question in two steps: did the artefacts that are now installed become the ones that were offered?++- The targets are captured **before** the update runs, because the update replaces the answer; comparing against the new answer would compare the result with itself and always agree.+- **Step 1 — local re-check.** The components observed after the update are compared with the captured targets, and three outcomes are stated in different words: *matches the published build*, *no published digest to compare against* (the answer carried no digest, or nothing is installed — not a failure), and *expected X, got Y*.+- **Step 2 — a fresh check against the cloud.** It runs in the same deferred call, and its answer is what repaints the maintenance menu: only the server knows whether something newer appeared in the meantime.+- The comparison runs **after** the fresh check, because the fresh check settles the one legitimate disagreement. A moving tag can move between the answer and the pull, so what is installed may match no target and still be right. If the server no longer offers an update for the stack, the difference is reported as *newer than the offered build*; if the offer stands, it is a mismatch. A re-check that itself failed is no authority, so a difference stays a mismatch.+- Verification never fails the operation. The update either worked or reported an error; this is a report about the result, and turning a registry that moved ahead into a failed update would be worse than saying nothing.+- The installer stack is excluded from verification deliberately: its operation downloads a build without applying it, so comparing against the running binary would report the intended outcome as a mismatch.++#### Installer self-update++`Download(installer)` and `Update(installer)` are two menu entries over the same operation, and that operation ends at "downloaded and verified".++- The build is described first (`packages/info`), then streamed to `installer_<version>` (`.exe` on Windows) in the directory holding `.env`, with length, sha256 and Ed25519 signature checked as the bytes arrive. Progress is printed every 10% — one line per read would bury the surrounding output.+- **The running binary is never replaced.** A process cannot reliably replace the file it is executing: Linux refuses the write (`ETXTBSY`), Windows holds it locked, and getting it wrong leaves the user with no installer at all. Instead the screen prints the exact command — `mv "<downloaded>" "<running installer>"`, or `move /Y` on Windows, both paths quoted so an installation under a path with a space does not become two arguments. If `os.Executable` says nothing, no command is printed at all: a command with a guessed destination is worse than none.+- The version is part of the file name so a download cannot overwrite the installer in use, and an inode-based guard refuses to write to a file that *is* the running binary (Linux would answer `ETXTBSY`, macOS would silently truncate it).+- The file is written under its final name in the installation directory rather than through the system temp directory, for the same antivirus/EDR reason as the Jaeger plugin.+- An unfinished download is deleted — verification only completes on the last byte, so a file named like a release but unverified must not be left next to the installation — and the held package description is dropped with it, so a build republished under the same version does not make every retry fail identically.+- `InstallerPackage(ctx)` describes the offer without downloading: version, os/arch, size, the exact path the download will use, whether a file is already there, and the running binary's path. The screen needs the size *before* asking for consent; the description is remembered and reused by the download, so one press of the action does not pay for the same request twice (every call carries a proof-of-work challenge and counts against the account's daily allowance). The only thing the screen asks the user to confirm is overwriting a file that is already there.+- `removeInstaller` is the one operation still unimplemented: it returns an error.### Removal Operations- **Remove(stack)**:@@ -143,8 +203,10 @@ const (- pre-phase (wizard): integrity scan, user selects overwrite (force) or keep (no force)- phase 1: observability (ensure/verify files → update stack or remove if external/disabled)- phase 2: langfuse (same logic; local start requires `LangfuseConnected`)- - phase 3: pentagi (always embedded; ensure/verify → update)+ - phase 3: graphiti (same logic; local start requires `GraphitiConnected`)+ - phase 4: pentagi (always embedded; ensure/verify → update)- refresh checker state after each phase+ - `Install` reuses the same four phases, each guarded by "not installed yet"- **ResetChanges()**:- Call `state.State.Reset()` to discard pending configuration changes@@ -158,9 +220,9 @@ Each specialized file should contain business-logic level methods that directly### Stack-Specific Operations- **compose.go**:- - `installPentAGI()`, `installLangfuse()`, `installObservability()` - extract compose files with environment patching- `startStack(stack)`, `stopStack(stack)`, `restartStack(stack)` - orchestrate docker compose commands- - `updateStack(stack)` - rolling updates with health checks+ - `updateStack(stack)` / `downloadStack(stack)` - the only two operations that fetch, and the two that write the chosen image references first+ - `removeStack(stack)` / `purgeStack(stack)` / `purgeImagesStack(stack)` - `down`, `down -v`, `down --rmi all -v`- **docker.go**:- `pullWorkerImage()` - download pentest image (DOCKER_DEFAULT_IMAGE_FOR_PENTEST: vxcontrol/kali-linux)- `pullDefaultImage()` - download general image (DOCKER_DEFAULT_IMAGE: debian:latest)@@ -173,12 +235,16 @@ Each specialized file should contain business-logic level methods that directly- File integrity validation with YAML syntax checking- Embedded directory tree handling for observability stack- **update.go**:- - `checkUpdates()` - communicate with pentagi.com update server- - `downloadInstaller()` - atomic binary replacement with backup- - `updateStackImages(stack)` - orchestrate image updates with rollback-- **remove.go**:- - `removeStack(stack)` - soft removal preserving data- - `purgeStack(stack)` - complete cleanup including volumes and images+ - `checkUpdates()` - refresh what the PentAGI Cloud API says about this installation; the answer lands on the shared `checker.CheckResult` instead of being returned, so there is only one copy of it+ - `installerPackage()` - describe the offered build (version, platform, size, target path) without downloading it+ - `downloadInstaller()` / `updateInstaller()` - the same operation under two names: fetch `installer_<version>` and verify it; the running binary is left alone+ - `updateJaegerPlugin()` - bring the Jaeger storage plugin files up to the offered version (in `jaeger_plugin.go`)+- **pull_reference.go**:+ - `applyPullReferences(stack)` - write the chosen image references into `.env` before a pull+- **verify.go**:+ - `captureStackTargets(result, stack)` / `verifyStackUpdate(stack, targets, state)` - the two halves of the post-update comparison+- **logic.go**:+ - `remove(stack)` / `purge(stack)` - the removal orchestration; the compose helpers above do the work### Critical Implementation Details- **Two-Track Command Execution**:@@ -191,12 +257,12 @@ Each specialized file should contain business-logic level methods that directly- **Deployment Mode Handling**:- Langfuse: embedded (full stack), external (existing server), disabled (no analytics); local start guarded by `LangfuseConnected`- Observability: embedded (full stack), external (OTEL collector), disabled (no monitoring)-- **Environment Variable Handling**: Compose files use --env-file parameter for environment variables, only special cases require file patching-- **Progress Tracking**: Worker downloads (vxcontrol/kali-linux 6GB+ → 13GB disk) with real-time progress via terminal+- **Environment Variable Handling**: Compose files use --env-file parameter for environment variables, only special cases require file patching. Image references are part of this: every `image:` is `${<COMPONENT>_IMAGE:-<default>}`, and every operation that fetches writes those variables from the cloud answer into `.env` before pulling — bypassing the staging area, since compose reads the file+- **Progress Tracking**: Worker downloads (vxcontrol/kali-linux 6GB+ → 13GB disk) with real-time progress via terminal; file downloads (installer build, Jaeger plugin) report every 10% against the size the package description gave- **Docker Configuration**: Support NET_ADMIN capability for network scanning, Docker socket access for container management- **Dependency Ordering**: PentAGI must start before Langfuse/Observability for network creation- **State Persistence**: All operations update checker.CheckResult and state.State for consistency-- **Atomic Operations**: Install/Update operations must be reversible on failure+- **Atomicity**: Only file downloads are atomic (staged sibling + rename for the Jaeger plugin, delete-on-failure for the installer build). Compose operations are not reversible — a failed update leaves whatever compose managed to do### Integration Patterns- **Wizard → Processor**: Called via `wizard.controllers.StateController` on user action@@ -217,7 +283,7 @@ Each specialized file should contain business-logic level methods that directly- **Validation errors**: validate stack applicability before operation- **System errors**: Docker API failures, file permissions, network issues- **State conflicts**: partial installations, conflicting configs, version mismatches-- **Rollback logic**: atomic replace helpers for installer binary; compose operations are fail-fast without rollback+- **Rollback logic**: none for compose operations — they are fail-fast. Only file downloads are protected: the Jaeger plugin is staged next to its target and renamed only after a clean write, and an unverified installer download is deleted rather than left behind## Integration Points@@ -230,7 +296,7 @@ Each specialized file should contain business-logic level methods that directly### External Systems- Docker Compose CLI for stack orchestration- Docker API for container/image management-- HTTP client for installer updates from pentagi.com+- HTTP client (`cloud` package) for update checks and file downloads from the PentAGI Cloud API- File system for content extraction and cleanup## ApplyChanges State Machine@@ -394,10 +460,10 @@ func WithTerminalModel(terminal ProcessorTerminalModel) CommandOption {```### Update Server Protocol-- Uses existing `checker.CheckUpdatesRequest`/`CheckUpdatesResponse` structures-- Binary download with SHA256 verification-- Atomic replacement via temporary file + rename-- Post-update exit with restart instruction message+- Every call goes through the `cloud` package to the PentAGI Cloud API at `UPDATE_SERVER_HOST` (default `update.pentagi.com`), always honoring `PROXY_URL` — the installer's own proxy setting, which the process environment may not carry. `SUPPORT_SERVER_HOST` (default `support.pentagi.com`) is written by the same settings form and belongs to the Support API; no call here targets it yet+- `/api/v1/proxy/updates/check` reports the installed components and answers per stack: whether an update exists, the version transition, and per component the action, the pull reference and the target digest+- `/api/v1/proxy/packages/info` then `/api/v1/proxy/packages/download` fetch a file (installer build, Jaeger storage plugin). The description carries the size, sha256 and signature the stream is checked against; that size is also the only length the client ever learns, since the encrypted body carries no `Content-Length`, so download progress is computed from it+- No atomic self-replacement and no post-update exit: the downloaded installer is left on disk with the command to move it into place### Critical Safety Measures- **Pre-flight Checks**: Validate system resources before major operations@@ -413,11 +479,13 @@ func WithTerminalModel(terminal ProcessorTerminalModel) CommandOption {- **logic.go**: Business logic (ApplyChanges, lifecycle operations)- **state.go**: Operation state management- **compose.go, docker.go, fs.go, update.go**: Specialized operations+- **pull_reference.go, jaeger_plugin.go, verify.go, reference_drift.go**: The update path — image references, plugin file, post-update comparison, drift reporting**Testing Infrastructure**:- **mock_test.go**: Comprehensive mocks with call tracking- **logic_test.go**: Business logic tests- **fs_test.go**: File system operation tests+- **update_test.go, pull_reference_test.go, jaeger_plugin_test.go, verify_test.go**: Download progress and package description reuse, image reference selection, plugin staging and cleanup, the four verification outcomes- **Mock CheckHandler**: Flexible system state simulation**Integration Points**:diff --git a/backend/docs/observability.md b/backend/docs/observability.mdindex a0b92bd7..e91dc48d 100644--- a/backend/docs/observability.md+++ b/backend/docs/observability.md@@ -16,6 +16,7 @@- [Infrastructure Requirements](#infrastructure-requirements)- [Components](#components)- [Setup](#setup)+ - [Jaeger Storage Plugin](#jaeger-storage-plugin)- [Configuration](#configuration)- [Environment Variables](#environment-variables)- [Initialization](#initialization)@@ -248,6 +249,43 @@ docker-compose -f docker-compose-observability.yml up -dFor detailed setup instructions, refer to the README.md file in the repository.+### Jaeger Storage Plugin++Jaeger keeps its traces in ClickHouse through the `jaeger-clickhouse` gRPC storage plugin. Unlike everything else in the stack, the plugin is not an image: it is a binary bind-mounted into the Jaeger container, which loads it over gRPC at start.++```yaml+# docker-compose-observability.yml, service jaeger (abridged)+entrypoint: >+ /bin/sh -c '+ if [ "$$(uname -m)" = "x86_64" ]; then ARCH="amd64"+ elif [ "$$(uname -m)" = "aarch64" ]; then ARCH="arm64"+ ... fi &&+ /go/bin/all-in-one-linux+ --grpc-storage-plugin.binary=/etc/jaeger/bin/jaeger-clickhouse-linux-$$ARCH+ --grpc-storage-plugin.configuration-file=/etc/jaeger/plugin-config.yml'+environment:+ SPAN_STORAGE_TYPE: grpc-plugin+volumes:+ - ./observability/jaeger:/etc/jaeger:rw+```++Both files — `jaeger-clickhouse-linux-amd64` and `jaeger-clickhouse-linux-arm64` — are kept in `observability/jaeger/bin/` next to the environment file regardless of the host, because which one runs is decided *inside* the container by `uname -m`: that is the architecture of the Docker VM, not of the machine the installer runs on. The entrypoint picks the file at start.++Because it is a file and not an image, no amount of `docker compose pull` brings it up to date. The installer updates it as part of an observability stack update: it sends the sha256 of each file it finds on disk with the update check, and the answer names a hash, a version and an action per file. The digest comparison is only the first word on the matter — a file whose hash differs from the offered one is marked outdated, and then the action overrides that verdict either way: `install`, `upgrade` and `downgrade` mark the file outdated whatever the hashes say, which is also how a file that is not on disk at all — and therefore was never reported, so there was no digest to compare — gets fetched, while `unknown` marks it current. Fetched, then, is every plugin component left marked outdated that also carries a target version (an empty one leaves nothing to ask the server for) and is for `linux` (the file name says `linux`, and the plugin is a linux binary whatever the host is). For each file that needs fetching:++1. `GET /api/v1/proxy/packages/info` describes the package — its size, its sha256 and the signature over it;+2. `GET /api/v1/proxy/packages/download` is streamed into `<name>.new`, a sibling of the target, created with mode `0755`;+3. the length, the sha256 and an Ed25519 signature are verified over the whole stream;+4. only then is the staging file renamed over the target.++None of those three checks can be decided before the last byte arrives, so what is on disk before step 4 is unverified — that is why the download is staged rather than written in place: an interrupted attempt would otherwise leave a truncated plugin under the name a running Jaeger loads. The staging file is a sibling of the target because `os.Rename` is atomic only within one filesystem. The mode is set at creation and not afterwards, because the rename does not preserve the destination's mode: a plugin created `0644` and moved over an executable one ends up not executable, and Jaeger then fails with an opaque gRPC plugin error rather than a permission one. A leftover `.new` from an interrupted download is removed at the start of the next observability update, by exact name — the directory is mounted into a container and may hold an operator's own files, so nothing is deleted by glob.++The download runs *before* anything else in the stack update touches the installation: the images are pulled, and the image references the server chose are written into the environment file, only afterwards — both of those happen inside the `pull` and the `up` that follow. So a plugin that cannot be fetched aborts the stack update with nothing else disturbed.++Replacing the file does not affect a running Jaeger, and the `docker compose up -d` that follows does not either: compose recreates a container only when its *spec* changes, and a different file inside a bind mount is not a spec change. The plugin is exec'd by the container's entrypoint at start, so a container left running is still serving through the plugin it loaded when it came up. The installer therefore reports whether it actually replaced anything, and when it did it restarts the `jaeger` service explicitly once the stack is up — without that, the update reports success while nothing about it is in effect.++Both plugin paths are excluded from the installer's file-integrity verification. The copy shipped inside the installer seeds a first install, and is never written over afterwards. Without that exclusion the update would undo itself: a downloaded plugin differs from the shipped one, so verification would call it modified and offer to repair it. A stack update never repairs files, but two paths do — answering yes to the integrity prompt on Apply Changes, and a factory reset, which does it without asking — and either would copy the shipped file straight back over the downloaded one.+## Configuration### Environment Variablesdiff --git a/backend/go.mod b/backend/go.modindex d326fa1b..a2fd8e19 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -53,7 +53,7 @@ require (github.com/swaggo/gin-swagger v1.3.0github.com/swaggo/swag v1.8.7github.com/vektah/gqlparser/v2 v2.5.19- github.com/vxcontrol/cloud v1.0.0+ github.com/vxcontrol/cloud v1.0.1github.com/vxcontrol/graphiti-go-client v0.9.0github.com/vxcontrol/langchaingo v0.1.14-update.7github.com/wasilibs/go-re2 v1.10.0diff --git a/backend/go.sum b/backend/go.sumindex 115487b6..d37007e2 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -628,8 +628,8 @@ github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbgithub.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI=github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=-github.com/vxcontrol/cloud v1.0.0 h1:2T8xM0z6+38Uj8a4lKfDxRP2/iXZVoS2vZmNgt6VQmk=-github.com/vxcontrol/cloud v1.0.0/go.mod h1:AeiQFqiMgJJAXy6FYXtDS2a3P/PMB56iiBNY2vGrZhQ=+github.com/vxcontrol/cloud v1.0.1 h1:sskfyc3F09SQEbSvj0w3QQbTU1cAWfi4hF6dDxGLyIM=+github.com/vxcontrol/cloud v1.0.1/go.mod h1:AeiQFqiMgJJAXy6FYXtDS2a3P/PMB56iiBNY2vGrZhQ=github.com/vxcontrol/graphiti-go-client v0.9.0 h1:3GxpFmQoHmz/d7/9tyEqD8+S99v2cuqG1UEmrbAFrLU=github.com/vxcontrol/graphiti-go-client v0.9.0/go.mod h1:6UHL5uqAKp4KAdziva4qgcAxFtBzU05Hm/BAo4NkAuo=github.com/vxcontrol/langchaingo v0.1.14-update.7 h1:iQnSNMmYQGbPQK5622JewlruaY6MIc7wzJklWq0Fja4=diff --git a/backend/pkg/config/config.go b/backend/pkg/config/config.goindex 4e7acb3f..32f65c8b 100644--- a/backend/pkg/config/config.go+++ b/backend/pkg/config/config.go@@ -7,6 +7,7 @@ import ("reflect""regexp""strings"+ "time""github.com/caarlos0/env/v10""github.com/google/uuid"@@ -231,6 +232,16 @@ type Config struct {// === Network Proxy Settings ===ProxyURL string `env:"PROXY_URL"`+ // === PentAGI Cloud API ===+ // UpdateStrategy is the strategy to use for updates. It can be "preview", "stable" or "nightly".+ UpdateStrategy string `env:"UPDATE_STRATEGY" envDefault:"preview"`+ // UpdateCheckInterval is how often this server reports its own state. Zero disables it.+ UpdateCheckInterval time.Duration `env:"UPDATE_CHECK_INTERVAL" envDefault:"3h"`+ // UpdateServerHost is the endpoint as host[:port]; empty means the default.+ UpdateServerHost string `env:"UPDATE_SERVER_HOST" envDefault:"update.pentagi.com"`+ // SupportServerHost is the endpoint as host[:port]; empty means the default.+ SupportServerHost string `env:"SUPPORT_SERVER_HOST" envDefault:"support.pentagi.com"`+// SSL Trusted CA Certificate Path (for external communication with LLM backends)ExternalSSLCAPath string `env:"EXTERNAL_SSL_CA_PATH" envDefault:""`ExternalSSLInsecure bool `env:"EXTERNAL_SSL_INSECURE" envDefault:"false"`diff --git a/backend/pkg/database/querier.go b/backend/pkg/database/querier.goindex 7cb656e1..d0718859 100644--- a/backend/pkg/database/querier.go+++ b/backend/pkg/database/querier.go@@ -11,6 +11,17 @@ import (type Querier interface {AddFavoriteFlow(ctx context.Context, arg AddFavoriteFlowParams) (UserPreference, error)+ CountAPITokens(ctx context.Context) (int64, error)+ CountActiveFlows(ctx context.Context) (int64, error)+ CountAssistants(ctx context.Context) (int64, error)+ CountContainers(ctx context.Context) (int64, error)+ CountFlowTemplates(ctx context.Context) (int64, error)+ CountFlows(ctx context.Context) (int64, error)+ CountPrompts(ctx context.Context) (int64, error)+ CountSubtasks(ctx context.Context) (int64, error)+ CountTasks(ctx context.Context) (int64, error)+ CountToolcalls(ctx context.Context) (int64, error)+ CountUsers(ctx context.Context) (int64, error)CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error)CreateAgentLog(ctx context.Context, arg CreateAgentLogParams) (Agentlog, error)CreateAssistant(ctx context.Context, arg CreateAssistantParams) (Assistant, error)@@ -159,6 +170,11 @@ type Querier interface {GetSubtaskVectorStoreLogs(ctx context.Context, subtaskID sql.NullInt64) ([]Vecstorelog, error)// Get all subtasks for multiple tasksGetSubtasksForTasks(ctx context.Context, taskIds []int64) ([]GetSubtasksForTasksRow, error)+ // Number of configured providers per type, for the instance summary.+ GetSummaryProviderCounts(ctx context.Context) ([]GetSummaryProviderCountsRow, error)+ // Aggregate LLM usage per provider type, over the whole life of the instance,+ // for the instance summary.+ GetSummaryUsageByProvider(ctx context.Context) ([]GetSummaryUsageByProviderRow, error)GetTask(ctx context.Context, id int64) (Task, error)GetTaskAgentLogs(ctx context.Context, taskID sql.NullInt64) ([]Agentlog, error)GetTaskCompletedSubtasks(ctx context.Context, taskID int64) ([]Subtask, error)diff --git a/backend/pkg/database/summary.go b/backend/pkg/database/summary.gonew file mode 100644index 00000000..23651e0c--- /dev/null+++ b/backend/pkg/database/summary.go@@ -0,0 +1,324 @@+package database++import (+ "context"+ "encoding/json"+ "runtime"+ "sort"+ "time"++ "pentagi/pkg/version"+)++// InstanceSummarySchema is the version of the document GetInstanceSummary+// produces. It travels inside the document so a reader that meets a newer one+// can tell that it is newer rather than malformed.+//+// Bump it when a field changes meaning or disappears. Adding a field does not+// need a bump: a reader that does not know a key ignores it, which is the whole+// reason the document is JSON rather than a fixed record.+const InstanceSummarySchema = 1++// summaryQueryTimeout bounds each aggregate on its own.+//+// The point of this document is to describe a server cheaply. A count over a+// table that has grown for a year is a sequential scan in PostgreSQL, and an+// installation big enough for that to be slow is exactly the one that must not+// be disturbed to produce a number. So every aggregate gets its own deadline and+// a missed deadline costs one field, named in Skipped, rather than the document.+const summaryQueryTimeout = 10 * time.Second++// InstanceSummary describes what this server currently holds and how it is set+// up. Quantities and closed vocabularies only — no names, no addresses, no+// contents of anything a user wrote.+type InstanceSummary struct {+ Schema int `json:"schema"`+ Version string `json:"version"`+ Develop bool `json:"develop"`++ // OS, Arch and BinaryHash describe the process that produced this document, and+ // they are in the document because nothing that carries it can produce them.+ //+ // A caller that runs this binary inside a container to obtain the description+ // knows the platform of the HOST — on a macOS host that is `darwin` while this+ // process is linux — and the image digest it can see names a filesystem rather+ // than the file that is executing. Both are inferences about a process drawn from+ // its surroundings, and both are wrong in ways that are hard to notice. The+ // process states them instead: the platform it was compiled for, and the sha256+ // of the executable it was started from.+ //+ // BinaryHash is what tells two builds carrying the same version string apart,+ // which outside a release is every build. Empty when it could not be read.+ OS string `json:"os"`+ Arch string `json:"arch"`+ BinaryHash string `json:"binary_hash"`++ Features InstanceFeatures `json:"features"`++ Providers []InstanceProvider `json:"providers"`+ OAuth []string `json:"oauth"`++ // EmbeddingProvider is the provider type actually used for embeddings, as+ // resolved by the caller — empty when embeddings are disabled ("none").+ EmbeddingProvider string `json:"embedding_provider"`++ Counts InstanceCounts `json:"counts"`+ Usage []InstanceUsage `json:"usage"`++ // Skipped names the aggregates that could not be produced — a timeout, a+ // table that is not there yet on a partially migrated instance. It exists+ // because a zero and a failure are indistinguishable otherwise, and the two+ // mean opposite things about an installation.+ Skipped []string `json:"skipped,omitempty"`+}++// InstanceFeatures are the switches this server runs with. They come from the+// configuration rather than from the database, so the caller supplies them.+type InstanceFeatures struct {+ Debug bool `json:"debug"`+ AskUser bool `json:"ask_user"`+ DockerInside bool `json:"docker_inside"`+ AssistantUseAgents bool `json:"assistant_use_agents"`+}++// InstanceProvider is one configured provider type and how many of it there are.+// The type only: the names and credentials of individual providers are not part+// of a description of the server and must never be put in one.+type InstanceProvider struct {+ Type string `json:"type"`+ Count uint32 `json:"count"`+}++// InstanceCounts are the sizes of the things this server holds.+type InstanceCounts struct {+ Users uint32 `json:"users"`+ Flows uint32 `json:"flows"`+ FlowsActive uint32 `json:"flows_active"`+ Tasks uint32 `json:"tasks"`+ Subtasks uint32 `json:"subtasks"`+ Containers uint32 `json:"containers"`+ Assistants uint32 `json:"assistants"`+ FlowTemplates uint32 `json:"flow_templates"`+ Prompts uint32 `json:"prompts"`+ APITokens uint32 `json:"api_tokens"`+ Toolcalls uint64 `json:"toolcalls"`+}++// InstanceUsage is what has been consumed through one provider type over the+// whole life of this server.+type InstanceUsage struct {+ Provider string `json:"provider"`+ Flows uint32 `json:"flows"`+ Chains uint64 `json:"chains"`+ TokensIn uint64 `json:"tokens_in"`+ TokensOut uint64 `json:"tokens_out"`+ CacheIn uint64 `json:"cache_in"`+ CacheOut uint64 `json:"cache_out"`+ CostIn float64 `json:"cost_in"`+ CostOut float64 `json:"cost_out"`+}++// SummaryOptions carries the facts that are not in the database.+type SummaryOptions struct {+ Features InstanceFeatures+ // OAuth is the set of configured OAuth provider names — the names of the+ // providers, not of any user.+ OAuth []string+ // DefaultProviders lists the built-in provider types this instance would+ // construct from its environment configuration (see+ // providers.EnabledDefaultProviderTypes). They never get a row in the+ // `providers` table — that table only holds per-user providers added+ // through the Settings UI — so without this the summary would undercount,+ // or on an installation that configures everything through the+ // environment, report no providers at all despite active usage.+ DefaultProviders []string+ // EmbeddingProvider is the provider type actually used for embeddings, as+ // resolved by the caller (see embeddings.ResolvedProviderType).+ EmbeddingProvider string+}++// GetInstanceSummary describes this server.+//+// Every aggregate is a single statement over a single table. The analytics the+// UI runs are shaped for a different question — they walk one flow at a time and+// combine the rows in Go — and reusing them here would make describing a server+// cost as much as rendering a dashboard for it.+//+// It does not fail as a whole. An aggregate that cannot be produced is named in+// Skipped and the rest of the document is still returned, because a description+// missing one number is useful and an error instead of a description is not.+func (q *Queries) GetInstanceSummary(ctx context.Context, opts SummaryOptions) InstanceSummary {+ summary := InstanceSummary{+ Schema: InstanceSummarySchema,+ Version: version.GetBinaryVersion(),+ Develop: version.IsDevelopMode(),+ // Read off the running process rather than taken from the caller, for the+ // same reason the version is: every caller would compute the identical+ // value, and one that got it wrong — or that was updated to fill it and one+ // that was not — would put two answers to the same question in circulation.+ OS: runtime.GOOS,+ Arch: runtime.GOARCH,+ BinaryHash: version.BinaryHash(),+ Features: opts.Features,+ Providers: []InstanceProvider{},+ OAuth: []string{},+ EmbeddingProvider: opts.EmbeddingProvider,+ Usage: []InstanceUsage{},+ }+ if opts.OAuth != nil {+ summary.OAuth = append(summary.OAuth, opts.OAuth...)+ sort.Strings(summary.OAuth)+ }++ // Counters, each independent of the others: one that cannot be produced must+ // not cost the ones that can.+ counters := []struct {+ name string+ query func(context.Context) (int64, error)+ into func(uint64)+ }{+ {"users", q.CountUsers,+ func(v uint64) { summary.Counts.Users = uint32(v) }},+ {"flows", q.CountFlows,+ func(v uint64) { summary.Counts.Flows = uint32(v) }},+ {"flows_active", q.CountActiveFlows,+ func(v uint64) { summary.Counts.FlowsActive = uint32(v) }},+ {"tasks", q.CountTasks,+ func(v uint64) { summary.Counts.Tasks = uint32(v) }},+ {"subtasks", q.CountSubtasks,+ func(v uint64) { summary.Counts.Subtasks = uint32(v) }},+ {"containers", q.CountContainers,+ func(v uint64) { summary.Counts.Containers = uint32(v) }},+ {"assistants", q.CountAssistants,+ func(v uint64) { summary.Counts.Assistants = uint32(v) }},+ {"flow_templates", q.CountFlowTemplates,+ func(v uint64) { summary.Counts.FlowTemplates = uint32(v) }},+ {"prompts", q.CountPrompts,+ func(v uint64) { summary.Counts.Prompts = uint32(v) }},+ {"api_tokens", q.CountAPITokens,+ func(v uint64) { summary.Counts.APITokens = uint32(v) }},+ {"toolcalls", q.CountToolcalls,+ func(v uint64) { summary.Counts.Toolcalls = v }},+ }+ for _, counter := range counters {+ value, err := q.countOne(ctx, counter.query)+ if err != nil {+ summary.Skipped = append(summary.Skipped, counter.name)+ continue+ }+ counter.into(value)+ }++ if providers, err := q.summaryProviders(ctx); err != nil {+ summary.Skipped = append(summary.Skipped, "providers")+ } else {+ summary.Providers = providers+ }+ summary.Providers = mergeDefaultProviderCounts(summary.Providers, opts.DefaultProviders)++ if usage, err := q.summaryUsage(ctx); err != nil {+ summary.Skipped = append(summary.Skipped, "usage")+ } else {+ summary.Usage = usage+ }++ return summary+}++// MarshalIndent renders the summary as the document callers print or forward.+//+// Indented because the first consumer of this is a person reading a terminal,+// and a wall of one line is not a description of anything.+func (s InstanceSummary) MarshalIndent() ([]byte, error) {+ return json.MarshalIndent(s, "", " ")+}++func (q *Queries) countOne(ctx context.Context, query func(context.Context) (int64, error)) (uint64, error) {+ queryCtx, cancel := context.WithTimeout(ctx, summaryQueryTimeout)+ defer cancel()++ count, err := query(queryCtx)+ if err != nil {+ return 0, err+ }+ if count < 0 {+ return 0, nil+ }+ return uint64(count), nil+}++// mergeDefaultProviderCounts folds the environment-configured (built-in)+// provider types into the per-type counts read from the `providers` table.+// Those types never get a database row — see SummaryOptions.DefaultProviders+// — so without this step a type used only through the environment would be+// invisible here even while it accumulates real usage.+func mergeDefaultProviderCounts(dbProviders []InstanceProvider, defaultTypes []string) []InstanceProvider {+ counts := make(map[string]uint32, len(dbProviders)+len(defaultTypes))+ for _, p := range dbProviders {+ counts[p.Type] = p.Count+ }+ for _, t := range defaultTypes {+ counts[t]+++ }++ merged := make([]InstanceProvider, 0, len(counts))+ for t, c := range counts {+ merged = append(merged, InstanceProvider{Type: t, Count: c})+ }+ sort.Slice(merged, func(i, j int) bool { return merged[i].Type < merged[j].Type })++ return merged+}++// summaryProviders reports which provider types are configured and how many of+// each. One grouped scan of a small table.+func (q *Queries) summaryProviders(ctx context.Context) ([]InstanceProvider, error) {+ queryCtx, cancel := context.WithTimeout(ctx, summaryQueryTimeout)+ defer cancel()++ rows, err := q.GetSummaryProviderCounts(queryCtx)+ if err != nil {+ return nil, err+ }++ providers := make([]InstanceProvider, 0, len(rows))+ for _, row := range rows {+ providers = append(providers, InstanceProvider{Type: string(row.Type), Count: uint32(row.Total)})+ }++ return providers, nil+}++// summaryUsage reports consumption grouped by provider type.+//+// One grouped scan of msgchains and nothing else. The per-flow variant of this+// question joins subtasks, tasks and flows to attribute each chain to a flow;+// none of that is needed to answer "how much has gone through each provider",+// and on a busy instance those joins are the difference between a description+// and an outage.+func (q *Queries) summaryUsage(ctx context.Context) ([]InstanceUsage, error) {+ queryCtx, cancel := context.WithTimeout(ctx, summaryQueryTimeout)+ defer cancel()++ rows, err := q.GetSummaryUsageByProvider(queryCtx)+ if err != nil {+ return nil, err+ }++ usage := make([]InstanceUsage, 0, len(rows))+ for _, row := range rows {+ usage = append(usage, InstanceUsage{+ Provider: row.ModelProvider,+ Flows: uint32(row.Flows),+ Chains: uint64(row.Chains),+ TokensIn: uint64(row.TokensIn),+ TokensOut: uint64(row.TokensOut),+ CacheIn: uint64(row.CacheIn),+ CacheOut: uint64(row.CacheOut),+ CostIn: row.CostIn,+ CostOut: row.CostOut,+ })+ }++ return usage, nil+}diff --git a/backend/pkg/database/summary.sql.go b/backend/pkg/database/summary.sql.gonew file mode 100644index 00000000..f9012f75--- /dev/null+++ b/backend/pkg/database/summary.sql.go@@ -0,0 +1,231 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.27.0+// source: summary.sql++package database++import (+ "context"+)++const countAPITokens = `-- name: CountAPITokens :one+SELECT count(*) FROM api_tokens+`++func (q *Queries) CountAPITokens(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countAPITokens)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countActiveFlows = `-- name: CountActiveFlows :one+SELECT count(*) FROM flows WHERE deleted_at IS NULL AND status IN ('created', 'running', 'waiting')+`++func (q *Queries) CountActiveFlows(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countActiveFlows)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countAssistants = `-- name: CountAssistants :one+SELECT count(*) FROM assistants WHERE deleted_at IS NULL+`++func (q *Queries) CountAssistants(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countAssistants)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countContainers = `-- name: CountContainers :one+SELECT count(*) FROM containers+`++func (q *Queries) CountContainers(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countContainers)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countFlowTemplates = `-- name: CountFlowTemplates :one+SELECT count(*) FROM flow_templates+`++func (q *Queries) CountFlowTemplates(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countFlowTemplates)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countFlows = `-- name: CountFlows :one+SELECT count(*) FROM flows WHERE deleted_at IS NULL+`++func (q *Queries) CountFlows(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countFlows)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countPrompts = `-- name: CountPrompts :one+SELECT count(*) FROM prompts+`++func (q *Queries) CountPrompts(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countPrompts)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countSubtasks = `-- name: CountSubtasks :one+SELECT count(*) FROM subtasks+`++func (q *Queries) CountSubtasks(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countSubtasks)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countTasks = `-- name: CountTasks :one+SELECT count(*) FROM tasks+`++func (q *Queries) CountTasks(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countTasks)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countToolcalls = `-- name: CountToolcalls :one+SELECT count(*) FROM toolcalls+`++func (q *Queries) CountToolcalls(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countToolcalls)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const countUsers = `-- name: CountUsers :one+SELECT count(*) FROM users+`++func (q *Queries) CountUsers(ctx context.Context) (int64, error) {+ row := q.db.QueryRowContext(ctx, countUsers)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const getSummaryProviderCounts = `-- name: GetSummaryProviderCounts :many+SELECT type, count(*) AS total+FROM providers+WHERE deleted_at IS NULL+GROUP BY type+ORDER BY type+`++type GetSummaryProviderCountsRow struct {+ Type ProviderType `json:"type"`+ Total int64 `json:"total"`+}++// Number of configured providers per type, for the instance summary.+func (q *Queries) GetSummaryProviderCounts(ctx context.Context) ([]GetSummaryProviderCountsRow, error) {+ rows, err := q.db.QueryContext(ctx, getSummaryProviderCounts)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var items []GetSummaryProviderCountsRow+ for rows.Next() {+ var i GetSummaryProviderCountsRow+ if err := rows.Scan(&i.Type, &i.Total); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Close(); err != nil {+ return nil, err+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const getSummaryUsageByProvider = `-- name: GetSummaryUsageByProvider :many+SELECT+ model_provider,+ count(DISTINCT flow_id) AS flows,+ count(*) AS chains,+ COALESCE(SUM(usage_in), 0)::bigint AS tokens_in,+ COALESCE(SUM(usage_out), 0)::bigint AS tokens_out,+ COALESCE(SUM(usage_cache_in), 0)::bigint AS cache_in,+ COALESCE(SUM(usage_cache_out), 0)::bigint AS cache_out,+ COALESCE(SUM(usage_cost_in), 0.0)::double precision AS cost_in,+ COALESCE(SUM(usage_cost_out), 0.0)::double precision AS cost_out+FROM msgchains+GROUP BY model_provider+ORDER BY model_provider+`++type GetSummaryUsageByProviderRow struct {+ ModelProvider string `json:"model_provider"`+ Flows int64 `json:"flows"`+ Chains int64 `json:"chains"`+ TokensIn int64 `json:"tokens_in"`+ TokensOut int64 `json:"tokens_out"`+ CacheIn int64 `json:"cache_in"`+ CacheOut int64 `json:"cache_out"`+ CostIn float64 `json:"cost_in"`+ CostOut float64 `json:"cost_out"`+}++// Aggregate LLM usage per provider type, over the whole life of the instance,+// for the instance summary.+func (q *Queries) GetSummaryUsageByProvider(ctx context.Context) ([]GetSummaryUsageByProviderRow, error) {+ rows, err := q.db.QueryContext(ctx, getSummaryUsageByProvider)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var items []GetSummaryUsageByProviderRow+ for rows.Next() {+ var i GetSummaryUsageByProviderRow+ if err := rows.Scan(+ &i.ModelProvider,+ &i.Flows,+ &i.Chains,+ &i.TokensIn,+ &i.TokensOut,+ &i.CacheIn,+ &i.CacheOut,+ &i.CostIn,+ &i.CostOut,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Close(); err != nil {+ return nil, err+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/backend/pkg/database/summary_test.go b/backend/pkg/database/summary_test.gonew file mode 100644index 00000000..e7eb536b--- /dev/null+++ b/backend/pkg/database/summary_test.go@@ -0,0 +1,351 @@+package database++import (+ "context"+ "database/sql"+ "database/sql/driver"+ "errors"+ "runtime"+ "strings"+ "sync"+ "testing"++ "pentagi/pkg/version"+)++// The stand-in for a database that is reachable but answers nothing: a driver+// rather than a hand-rolled DBTX.+//+// A fake DBTX cannot be built honestly. *sql.Row carries its error in unexported+// fields, so the only *sql.Row a test can construct is the zero value — and that+// one PANICS on Scan rather than returning an error, which is a different thing+// entirely from what a broken database does. Going through database/sql with a+// failing driver exercises the real machinery and records what was asked.+var (+ errStubDriver = errors.New("stub driver: nothing is answered here")+ registerStubOnce sync.Once+ stubQueryRecorder = &queryRecorder{}+)++type queryRecorder struct {+ mu sync.Mutex+ queries []string+}++func (r *queryRecorder) record(query string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.queries = append(r.queries, query)+}++func (r *queryRecorder) taken() []string {+ r.mu.Lock()+ defer r.mu.Unlock()+ taken := append([]string(nil), r.queries...)+ r.queries = nil+ return taken+}++type stubDriver struct{}++func (stubDriver) Open(string) (driver.Conn, error) { return stubConn{}, nil }++type stubConn struct{}++func (stubConn) Prepare(query string) (driver.Stmt, error) {+ stubQueryRecorder.record(query)+ return nil, errStubDriver+}+func (stubConn) Close() error { return nil }+func (stubConn) Begin() (driver.Tx, error) { return nil, errStubDriver }++// answersNothing opens a database that connects and then refuses every statement,+// and hands back the statements it was asked, in order.+func answersNothing(t *testing.T) (*Queries, func() []string) {+ t.Helper()++ registerStubOnce.Do(func() { sql.Register("pentagi-summary-stub", stubDriver{}) })++ db, err := sql.Open("pentagi-summary-stub", "")+ if err != nil {+ t.Fatalf("open stub database: %v", err)+ }+ t.Cleanup(func() { _ = db.Close() })++ stubQueryRecorder.taken()+ return New(db), stubQueryRecorder.taken+}++// TestADescriptionSurvivesADatabaseThatAnswersNothing.+//+// The document is produced to be read by something that has already decided to+// ask. Returning an error instead of a document turns "this server is having+// trouble" into "this server said nothing", and those are the two readings the+// whole exercise exists to tell apart.+func TestADescriptionSurvivesADatabaseThatAnswersNothing(t *testing.T) {+ queries, _ := answersNothing(t)++ summary := queries.GetInstanceSummary(context.Background(), SummaryOptions{})++ if summary.Schema != InstanceSummarySchema {+ t.Errorf("schema lost: %d", summary.Schema)+ }+ if summary.Version == "" {+ t.Error("the version must be present even when nothing else is: it is what a reader groups by")+ }+ if len(summary.Skipped) == 0 {+ t.Fatal("nothing could be gathered, yet nothing was reported as skipped — a page of zeroes " ++ "would read as a measured empty installation")+ }+ for _, name := range []string{"users", "flows", "toolcalls", "providers", "usage"} {+ if !contains(summary.Skipped, name) {+ t.Errorf("%q could not be gathered but is not named in skipped: %v", name, summary.Skipped)+ }+ }++ // Empty rather than nil, all the way out. A nil slice marshals to `null`, and+ // a reader that walks the list then has to special-case a value that means the+ // same thing as an empty list.+ if summary.Providers == nil || summary.OAuth == nil || summary.Usage == nil {+ t.Error("list fields left nil; they must marshal as empty lists, not as null")+ }+}++// TestTheDescriptionSelectsOnlyQuantitiesAndClosedVocabularies.+//+// The promise this document makes is that it holds counts and closed vocabularies+// and nothing else. That promise lives in the SELECT list of every statement, and+// nowhere else: reading a row of `prompts` to count it is a quantity, reading its+// text is a person's words, and the two statements differ only in their+// projection.+//+// An allowlist rather than a blocklist, deliberately. A blocklist passes every+// column nobody thought to forbid, which is exactly the column that gets added+// next year; this fails on anything not named here, so widening the document is a+// decision somebody has to write down.+func TestTheDescriptionSelectsOnlyQuantitiesAndClosedVocabularies(t *testing.T) {+ queries, taken := answersNothing(t)+ queries.GetInstanceSummary(context.Background(), SummaryOptions{})+ issued := taken()++ if len(issued) == 0 {+ t.Fatal("no statements were issued; the check below would pass vacuously")+ }++ // The only bare columns a description may project. Both are closed+ // vocabularies defined in this repository — a provider type and the provider a+ // chain ran through — so neither can carry anything a user typed.+ allowed := map[string]bool{"type": true, "model_provider": true}++ for _, query := range issued {+ projection := selectList(t, query)+ if projection == "" {+ t.Errorf("could not read the projection of:\n%s", query)+ continue+ }+ for _, item := range splitProjection(projection) {+ item = strings.ToLower(strings.TrimSpace(item))+ if item == "" {+ continue+ }+ // Anything that is an aggregate is a quantity by construction: it+ // reduces however many rows to one number.+ if strings.HasPrefix(item, "count(") || strings.HasPrefix(item, "coalesce(sum(") ||+ strings.HasPrefix(item, "sum(") {+ continue+ }+ if allowed[item] {+ continue+ }+ t.Errorf("the description projects %q, which is neither a quantity nor a closed "++ "vocabulary — this is how a person's data reaches a document that promises "++ "neither:\n%s", item, query)+ }+ }+}++// splitProjection splits a SELECT list on the commas that separate its items —+// which is not every comma. `COALESCE(SUM(usage_in), 0)` contains one that+// belongs to the call, and splitting on it turns a legitimate aggregate into two+// fragments, neither of which is anything.+func splitProjection(projection string) []string {+ var (+ items []string+ depth int+ start int+ )+ for i, char := range projection {+ switch char {+ case '(':+ depth+++ case ')':+ depth--+ case ',':+ if depth == 0 {+ items = append(items, projection[start:i])+ start = i + 1+ }+ }+ }+ return append(items, projection[start:])+}++// selectList returns everything between SELECT and the matching FROM.+func selectList(t *testing.T, query string) string {+ t.Helper()++ flat := strings.Join(strings.Fields(query), " ")+ lowered := strings.ToLower(flat)++ start := strings.Index(lowered, "select ")+ if start < 0 {+ return ""+ }+ end := strings.Index(lowered, " from ")+ if end < 0 || end <= start {+ return ""+ }+ return flat[start+len("select ") : end]+}++// TestTheDescriptionAsksOneTableAtATime.+//+// The cost of this document is the reason it can be produced on a schedule. The+// analytics behind the product's own dashboard join msgchains to subtasks to+// tasks to flows in order to attribute consumption per flow; none of that is+// needed to answer "how much went through each provider", and on an installation+// large enough to be interesting those joins are the difference between a+// description and an outage.+func TestTheDescriptionAsksOneTableAtATime(t *testing.T) {+ queries, taken := answersNothing(t)+ queries.GetInstanceSummary(context.Background(), SummaryOptions{})++ for _, query := range taken() {+ lowered := strings.ToLower(query)+ if strings.Contains(lowered, " join ") {+ t.Errorf("a join crept into the description; it is meant to stay cheap enough to run "++ "unattended:\n%s", query)+ }+ }+}++// TestOptionsAreCarriedThroughRatherThanGuessed pins that the facts which are not+// in the database arrive from the caller. They describe how the server is+// configured, and the database has no opinion about that.+func TestOptionsAreCarriedThroughRatherThanGuessed(t *testing.T) {+ queries, _ := answersNothing(t)++ summary := queries.GetInstanceSummary(context.Background(), SummaryOptions{+ Features: InstanceFeatures{AskUser: true, DockerInside: true},+ OAuth: []string{"google", "github"},+ DefaultProviders: []string{"anthropic", "custom"},+ EmbeddingProvider: "custom",+ })++ if !summary.Features.AskUser || !summary.Features.DockerInside {+ t.Errorf("configuration switches lost: %+v", summary.Features)+ }+ if summary.Features.Debug || summary.Features.AssistantUseAgents {+ t.Errorf("switches invented that the caller did not set: %+v", summary.Features)+ }+ // Sorted, so that two installations with the same providers produce the same+ // document and a diff between two reports means something changed.+ if len(summary.OAuth) != 2 || summary.OAuth[0] != "github" || summary.OAuth[1] != "google" {+ t.Errorf("oauth providers lost or unordered: %v", summary.OAuth)+ }+ if summary.EmbeddingProvider != "custom" {+ t.Errorf("embedding provider lost: %q", summary.EmbeddingProvider)+ }+ if !contains(providerTypes(summary.Providers), "anthropic") || !contains(providerTypes(summary.Providers), "custom") {+ t.Errorf("default providers lost: %+v", summary.Providers)+ }+}++// TestTheProcessDescribesItselfRatherThanBeingTold.+//+// The platform and the executable digest are read off the running process, not taken+// from SummaryOptions like the configuration switches beside them, and the difference+// is the point. Every caller would compute the same value, so a caller that got it+// wrong — or one that was updated to supply it while another was not — would put two+// answers to "which build is running" into circulation. There are two callers today:+// the `-info` flag and the periodic report.+//+// And they have to be in the DOCUMENT, not only in the request the report sends,+// because a description obtained by executing this binary inside a container is+// forwarded by somebody who cannot produce either fact: that caller knows the+// platform of the HOST, and the image digest it can see names a filesystem rather+// than the file that is executing.+func TestTheProcessDescribesItselfRatherThanBeingTold(t *testing.T) {+ queries, _ := answersNothing(t)++ summary := queries.GetInstanceSummary(context.Background(), SummaryOptions{})++ if summary.OS != runtime.GOOS || summary.Arch != runtime.GOARCH {+ t.Errorf("platform = %q/%q, want the platform this binary was compiled for (%q/%q)",+ summary.OS, summary.Arch, runtime.GOOS, runtime.GOARCH)+ }+ if summary.BinaryHash != version.BinaryHash() {+ t.Errorf("binary hash = %q, want the digest of the running executable", summary.BinaryHash)+ }+ if len(summary.BinaryHash) != 64 {+ t.Errorf("binary hash = %q, want a sha256 in hex", summary.BinaryHash)+ }++ // And all three have to be IN the rendered document, not merely on the struct.+ // An `omitempty` added later would make an unknown platform indistinguishable+ // from a document too old to carry one, on the route where nothing else can+ // supply it.+ document, err := summary.MarshalIndent()+ if err != nil {+ t.Fatalf("the description must serialise: %v", err)+ }+ for _, key := range []string{`"os"`, `"arch"`, `"binary_hash"`} {+ if !strings.Contains(string(document), key) {+ t.Errorf("the document does not carry %s: %s", key, document)+ }+ }+}++// TestDefaultProvidersFillTheGapTheDatabaseCannot pins the reason+// DefaultProviders exists at all: an installation configured entirely through+// the environment never gets a row in the `providers` table (that table only+// holds providers added through the Settings UI), so without this the summary+// would report zero providers despite every one of them being usable.+func TestDefaultProvidersFillTheGapTheDatabaseCannot(t *testing.T) {+ queries, _ := answersNothing(t)++ summary := queries.GetInstanceSummary(context.Background(), SummaryOptions{+ DefaultProviders: []string{"openai", "openai", "anthropic"},+ })++ // A type present only via configuration must still show up, with a count+ // of one per default provider entry — here "openai" appears twice on+ // purpose, to pin that repeats accumulate rather than collapsing to one.+ got := make(map[string]uint32, len(summary.Providers))+ for _, p := range summary.Providers {+ got[p.Type] = p.Count+ }+ if got["openai"] != 2 {+ t.Errorf("expected openai count 2 from two default entries, got %+v", summary.Providers)+ }+ if got["anthropic"] != 1 {+ t.Errorf("expected anthropic count 1, got %+v", summary.Providers)+ }+}++func providerTypes(providers []InstanceProvider) []string {+ types := make([]string, 0, len(providers))+ for _, p := range providers {+ types = append(types, p.Type)+ }+ return types+}++func contains(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }+ }+ return false+}diff --git a/backend/pkg/graph/generated.go b/backend/pkg/graph/generated.goindex aac0cce2..7ba9b824 100644--- a/backend/pkg/graph/generated.go+++ b/backend/pkg/graph/generated.go@@ -521,6 +521,7 @@ type ComplexityRoot struct {UsageStatsByProvider func(childComplexity int) intUsageStatsTotal func(childComplexity int) intVectorStoreLogs func(childComplexity int, flowID int64) int+ VersionInfo func(childComplexity int) int}ReasoningConfig struct {@@ -751,6 +752,15 @@ type ComplexityRoot struct {SubtaskID func(childComplexity int) intTaskID func(childComplexity int) int}++ VersionInfo struct {+ CheckedAt func(childComplexity int) int+ Current func(childComplexity int) int+ FailedAt func(childComplexity int) int+ Latest func(childComplexity int) int+ State func(childComplexity int) int+ Strategy func(childComplexity int) int+ }}type MutationResolver interface {@@ -820,6 +830,7 @@ type QueryResolver interface {FlowStatsByFlow(ctx context.Context, flowID int64) (*model.FlowStats, error)FlowsExecutionStatsByPeriod(ctx context.Context, period model.UsageStatsPeriod) ([]*model.FlowExecutionStats, error)Settings(ctx context.Context) (*model.Settings, error)+ VersionInfo(ctx context.Context) (*model.VersionInfo, error)SettingsProviders(ctx context.Context) (*model.ProvidersConfig, error)SettingsPrompts(ctx context.Context) (*model.PromptsConfig, error)SettingsUser(ctx context.Context) (*model.UserPreferences, error)@@ -3558,6 +3569,13 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity inreturn e.complexity.Query.VectorStoreLogs(childComplexity, args["flowId"].(int64)), true+ case "Query.versionInfo":+ if e.complexity.Query.VersionInfo == nil {+ break+ }++ return e.complexity.Query.VersionInfo(childComplexity), true+case "ReasoningConfig.effort":if e.complexity.ReasoningConfig.Effort == nil {break@@ -4836,6 +4854,48 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity inreturn e.complexity.VectorStoreLog.TaskID(childComplexity), true+ case "VersionInfo.checkedAt":+ if e.complexity.VersionInfo.CheckedAt == nil {+ break+ }++ return e.complexity.VersionInfo.CheckedAt(childComplexity), true++ case "VersionInfo.current":+ if e.complexity.VersionInfo.Current == nil {+ break+ }++ return e.complexity.VersionInfo.Current(childComplexity), true++ case "VersionInfo.failedAt":+ if e.complexity.VersionInfo.FailedAt == nil {+ break+ }++ return e.complexity.VersionInfo.FailedAt(childComplexity), true++ case "VersionInfo.latest":+ if e.complexity.VersionInfo.Latest == nil {+ break+ }++ return e.complexity.VersionInfo.Latest(childComplexity), true++ case "VersionInfo.state":+ if e.complexity.VersionInfo.State == nil {+ break+ }++ return e.complexity.VersionInfo.State(childComplexity), true++ case "VersionInfo.strategy":+ if e.complexity.VersionInfo.Strategy == nil {+ break+ }++ return e.complexity.VersionInfo.Strategy(childComplexity), true+}return 0, false}@@ -25417,6 +25477,64 @@ func (ec *executionContext) fieldContext_Query_settings(_ context.Context, fieldreturn fc, nil}+func (ec *executionContext) _Query_versionInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_Query_versionInfo(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return ec.resolvers.Query().VersionInfo(rctx)+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ if !graphql.HasFieldError(ctx, fc) {+ ec.Errorf(ctx, "must not be null")+ }+ return graphql.Null+ }+ res := resTmp.(*model.VersionInfo)+ fc.Result = res+ return ec.marshalNVersionInfo2ᚖpentagiᚋpkgᚋgraphᚋmodelᚐVersionInfo(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_Query_versionInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "Query",+ Field: field,+ IsMethod: true,+ IsResolver: true,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ switch field.Name {+ case "current":+ return ec.fieldContext_VersionInfo_current(ctx, field)+ case "state":+ return ec.fieldContext_VersionInfo_state(ctx, field)+ case "latest":+ return ec.fieldContext_VersionInfo_latest(ctx, field)+ case "strategy":+ return ec.fieldContext_VersionInfo_strategy(ctx, field)+ case "checkedAt":+ return ec.fieldContext_VersionInfo_checkedAt(ctx, field)+ case "failedAt":+ return ec.fieldContext_VersionInfo_failedAt(ctx, field)+ }+ return nil, fmt.Errorf("no field named %q was found under type VersionInfo", field.Name)+ },+ }+ return fc, nil+}+func (ec *executionContext) _Query_settingsProviders(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {fc, err := ec.fieldContext_Query_settingsProviders(ctx, field)if err != nil {@@ -35245,6 +35363,261 @@ func (ec *executionContext) fieldContext_VectorStoreLog_createdAt(_ context.Contreturn fc, nil}+func (ec *executionContext) _VersionInfo_current(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_current(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.Current, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ if !graphql.HasFieldError(ctx, fc) {+ ec.Errorf(ctx, "must not be null")+ }+ return graphql.Null+ }+ res := resTmp.(string)+ fc.Result = res+ return ec.marshalNString2string(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_current(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type String does not have child fields")+ },+ }+ return fc, nil+}++func (ec *executionContext) _VersionInfo_state(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_state(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.State, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ if !graphql.HasFieldError(ctx, fc) {+ ec.Errorf(ctx, "must not be null")+ }+ return graphql.Null+ }+ res := resTmp.(model.UpdateState)+ fc.Result = res+ return ec.marshalNUpdateState2pentagiᚋpkgᚋgraphᚋmodelᚐUpdateState(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_state(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type UpdateState does not have child fields")+ },+ }+ return fc, nil+}++func (ec *executionContext) _VersionInfo_latest(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_latest(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.Latest, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ return graphql.Null+ }+ res := resTmp.(*string)+ fc.Result = res+ return ec.marshalOString2ᚖstring(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_latest(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type String does not have child fields")+ },+ }+ return fc, nil+}++func (ec *executionContext) _VersionInfo_strategy(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_strategy(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.Strategy, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ if !graphql.HasFieldError(ctx, fc) {+ ec.Errorf(ctx, "must not be null")+ }+ return graphql.Null+ }+ res := resTmp.(string)+ fc.Result = res+ return ec.marshalNString2string(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_strategy(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type String does not have child fields")+ },+ }+ return fc, nil+}++func (ec *executionContext) _VersionInfo_checkedAt(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_checkedAt(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.CheckedAt, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ return graphql.Null+ }+ res := resTmp.(*time.Time)+ fc.Result = res+ return ec.marshalOTime2ᚖtimeᚐTime(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_checkedAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type Time does not have child fields")+ },+ }+ return fc, nil+}++func (ec *executionContext) _VersionInfo_failedAt(ctx context.Context, field graphql.CollectedField, obj *model.VersionInfo) (ret graphql.Marshaler) {+ fc, err := ec.fieldContext_VersionInfo_failedAt(ctx, field)+ if err != nil {+ return graphql.Null+ }+ ctx = graphql.WithFieldContext(ctx, fc)+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ ret = graphql.Null+ }+ }()+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {+ ctx = rctx // use context from middleware stack in children+ return obj.FailedAt, nil+ })+ if err != nil {+ ec.Error(ctx, err)+ return graphql.Null+ }+ if resTmp == nil {+ return graphql.Null+ }+ res := resTmp.(*time.Time)+ fc.Result = res+ return ec.marshalOTime2ᚖtimeᚐTime(ctx, field.Selections, res)+}++func (ec *executionContext) fieldContext_VersionInfo_failedAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {+ fc = &graphql.FieldContext{+ Object: "VersionInfo",+ Field: field,+ IsMethod: false,+ IsResolver: false,+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {+ return nil, errors.New("field of type Time does not have child fields")+ },+ }+ return fc, nil+}+func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {fc, err := ec.fieldContext___Directive_name(ctx, field)if err != nil {@@ -41238,6 +41611,28 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) grfunc(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })}+ out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })+ case "versionInfo":+ field := field++ innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {+ defer func() {+ if r := recover(); r != nil {+ ec.Error(ctx, ec.Recover(ctx, r))+ }+ }()+ res = ec._Query_versionInfo(ctx, field)+ if res == graphql.Null {+ atomic.AddUint32(&fs.Invalids, 1)+ }+ return res+ }++ rrm := func(ctx context.Context) graphql.Marshaler {+ return ec.OperationContext.RootResolverMiddleware(ctx,+ func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })+ }+out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })case "settingsProviders":field := field@@ -42853,6 +43248,61 @@ func (ec *executionContext) _VectorStoreLog(ctx context.Context, sel ast.Selectireturn out}+var versionInfoImplementors = []string{"VersionInfo"}++func (ec *executionContext) _VersionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.VersionInfo) graphql.Marshaler {+ fields := graphql.CollectFields(ec.OperationContext, sel, versionInfoImplementors)++ out := graphql.NewFieldSet(fields)+ deferred := make(map[string]*graphql.FieldSet)+ for i, field := range fields {+ switch field.Name {+ case "__typename":+ out.Values[i] = graphql.MarshalString("VersionInfo")+ case "current":+ out.Values[i] = ec._VersionInfo_current(ctx, field, obj)+ if out.Values[i] == graphql.Null {+ out.Invalids+++ }+ case "state":+ out.Values[i] = ec._VersionInfo_state(ctx, field, obj)+ if out.Values[i] == graphql.Null {+ out.Invalids+++ }+ case "latest":+ out.Values[i] = ec._VersionInfo_latest(ctx, field, obj)+ case "strategy":+ out.Values[i] = ec._VersionInfo_strategy(ctx, field, obj)+ if out.Values[i] == graphql.Null {+ out.Invalids+++ }+ case "checkedAt":+ out.Values[i] = ec._VersionInfo_checkedAt(ctx, field, obj)+ case "failedAt":+ out.Values[i] = ec._VersionInfo_failedAt(ctx, field, obj)+ default:+ panic("unknown field " + strconv.Quote(field.Name))+ }+ }+ out.Dispatch(ctx)+ if out.Invalids > 0 {+ return graphql.Null+ }++ atomic.AddInt32(&ec.deferred, int32(len(deferred)))++ for label, dfs := range deferred {+ ec.processDeferredGroup(graphql.DeferredGroup{+ Label: label,+ Path: graphql.GetPath(ctx),+ FieldSet: dfs,+ Context: ctx,+ })+ }++ return out+}+var __DirectiveImplementors = []string{"__Directive"}func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler {@@ -45079,6 +45529,16 @@ func (ec *executionContext) unmarshalNUpdateKnowledgeDocumentInput2pentagiᚋpkgreturn res, graphql.ErrorOnPath(ctx, err)}+func (ec *executionContext) unmarshalNUpdateState2pentagiᚋpkgᚋgraphᚋmodelᚐUpdateState(ctx context.Context, v interface{}) (model.UpdateState, error) {+ var res model.UpdateState+ err := res.UnmarshalGQL(v)+ return res, graphql.ErrorOnPath(ctx, err)+}++func (ec *executionContext) marshalNUpdateState2pentagiᚋpkgᚋgraphᚋmodelᚐUpdateState(ctx context.Context, sel ast.SelectionSet, v model.UpdateState) graphql.Marshaler {+ return v+}+func (ec *executionContext) marshalNUsageStats2pentagiᚋpkgᚋgraphᚋmodelᚐUsageStats(ctx context.Context, sel ast.SelectionSet, v model.UsageStats) graphql.Marshaler {return ec._UsageStats(ctx, sel, &v)}@@ -45213,6 +45673,20 @@ func (ec *executionContext) marshalNVectorStoreLog2ᚖpentagiᚋpkgᚋgraphᚋmoreturn ec._VectorStoreLog(ctx, sel, v)}+func (ec *executionContext) marshalNVersionInfo2pentagiᚋpkgᚋgraphᚋmodelᚐVersionInfo(ctx context.Context, sel ast.SelectionSet, v model.VersionInfo) graphql.Marshaler {+ return ec._VersionInfo(ctx, sel, &v)+}++func (ec *executionContext) marshalNVersionInfo2ᚖpentagiᚋpkgᚋgraphᚋmodelᚐVersionInfo(ctx context.Context, sel ast.SelectionSet, v *model.VersionInfo) graphql.Marshaler {+ if v == nil {+ if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {+ ec.Errorf(ctx, "the requested element is null which the schema does not allow")+ }+ return graphql.Null+ }+ return ec._VersionInfo(ctx, sel, v)+}+func (ec *executionContext) marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler {return ec.___Directive(ctx, sel, &v)}diff --git a/backend/pkg/graph/model/models_gen.go b/backend/pkg/graph/model/models_gen.goindex 37872d2b..41092eff 100644--- a/backend/pkg/graph/model/models_gen.go+++ b/backend/pkg/graph/model/models_gen.go@@ -647,6 +647,15 @@ type VectorStoreLog struct {CreatedAt time.Time `json:"createdAt"`}+type VersionInfo struct {+ Current string `json:"current"`+ State UpdateState `json:"state"`+ Latest *string `json:"latest,omitempty"`+ Strategy string `json:"strategy"`+ CheckedAt *time.Time `json:"checkedAt,omitempty"`+ FailedAt *time.Time `json:"failedAt,omitempty"`+}+type AgentConfigType stringconst (@@ -1634,6 +1643,55 @@ func (e ToolCallStatus) MarshalGQL(w io.Writer) {fmt.Fprint(w, strconv.Quote(e.String()))}+type UpdateState string++const (+ UpdateStateDisabled UpdateState = "disabled"+ UpdateStatePending UpdateState = "pending"+ UpdateStateUnreachable UpdateState = "unreachable"+ UpdateStateUnknown UpdateState = "unknown"+ UpdateStateUpToDate UpdateState = "up_to_date"+ UpdateStateUpdateAvailable UpdateState = "update_available"+)++var AllUpdateState = []UpdateState{+ UpdateStateDisabled,+ UpdateStatePending,+ UpdateStateUnreachable,+ UpdateStateUnknown,+ UpdateStateUpToDate,+ UpdateStateUpdateAvailable,+}++func (e UpdateState) IsValid() bool {+ switch e {+ case UpdateStateDisabled, UpdateStatePending, UpdateStateUnreachable, UpdateStateUnknown, UpdateStateUpToDate, UpdateStateUpdateAvailable:+ return true+ }+ return false+}++func (e UpdateState) String() string {+ return string(e)+}++func (e *UpdateState) UnmarshalGQL(v interface{}) error {+ str, ok := v.(string)+ if !ok {+ return fmt.Errorf("enums must be strings")+ }++ *e = UpdateState(str)+ if !e.IsValid() {+ return fmt.Errorf("%s is not a valid UpdateState", str)+ }+ return nil+}++func (e UpdateState) MarshalGQL(w io.Writer) {+ fmt.Fprint(w, strconv.Quote(e.String()))+}+type UsageStatsPeriod stringconst (diff --git a/backend/pkg/graph/resolver.go b/backend/pkg/graph/resolver.goindex 8307b348..45a64236 100644--- a/backend/pkg/graph/resolver.go+++ b/backend/pkg/graph/resolver.go@@ -8,6 +8,7 @@ import ("pentagi/pkg/graph/subscriptions""pentagi/pkg/providers""pentagi/pkg/server/auth"+ "pentagi/pkg/server/update""pentagi/pkg/templates""github.com/sirupsen/logrus"@@ -29,4 +30,5 @@ type Resolver struct {Subscriptions subscriptions.SubscriptionsControllerKnowledge knowledge.KnowledgeStoreReplacer anonymizer.Replacer+ Updates *update.Service}diff --git a/backend/pkg/graph/schema.graphqls b/backend/pkg/graph/schema.graphqlsindex 863d7011..1632afbe 100644--- a/backend/pkg/graph/schema.graphqls+++ b/backend/pkg/graph/schema.graphqls@@ -206,6 +206,24 @@ type Settings {assistantUseAgents: Boolean!}+enum UpdateState {+ disabled+ pending+ unreachable+ unknown+ up_to_date+ update_available+}++type VersionInfo {+ current: String!+ state: UpdateState!+ latest: String+ strategy: String!+ checkedAt: Time+ failedAt: Time+}+# ==================== User Preferences Types ====================type UserPreferences {@@ -1034,6 +1052,7 @@ type Query {# System settingssettings: Settings!+ versionInfo: VersionInfo!settingsProviders: ProvidersConfig!settingsPrompts: PromptsConfig!settingsUser: UserPreferences!diff --git a/backend/pkg/graph/schema.resolvers.go b/backend/pkg/graph/schema.resolvers.goindex 90a84c95..35fe72db 100644--- a/backend/pkg/graph/schema.resolvers.go+++ b/backend/pkg/graph/schema.resolvers.go@@ -28,6 +28,7 @@ import ("pentagi/pkg/providers/qwen""pentagi/pkg/resources""pentagi/pkg/server/auth"+ "pentagi/pkg/server/update""pentagi/pkg/templates""pentagi/pkg/templates/validator""pentagi/pkg/version"@@ -2082,6 +2083,24 @@ func (r *queryResolver) Settings(ctx context.Context) (*model.Settings, error) {return settings, nil}+// VersionInfo is the resolver for the versionInfo field.+func (r *queryResolver) VersionInfo(ctx context.Context) (*model.VersionInfo, error) {+ _, _, err := validatePermission(ctx, "settings.view")+ if err != nil {+ return nil, err+ }++ // No service means checks were never configured — an installation id that is+ // missing or malformed — which to whoever reads the badge is the same as+ // checks switched off. The build itself is still named either way.+ status := update.DisabledStatus(r.Config)+ if r.Updates != nil {+ status = r.Updates.Status()+ }++ return versionInfoFromStatus(status), nil+}+// SettingsProviders is the resolver for the settingsProviders field.func (r *queryResolver) SettingsProviders(ctx context.Context) (*model.ProvidersConfig, error) {uid, _, err := validatePermission(ctx, "settings.providers.view")diff --git a/backend/pkg/graph/version_info.go b/backend/pkg/graph/version_info.gonew file mode 100644index 00000000..9ef5f5e0--- /dev/null+++ b/backend/pkg/graph/version_info.go@@ -0,0 +1,55 @@+package graph++import (+ "pentagi/pkg/graph/model"+ "pentagi/pkg/server/update"+)++// versionInfoFromStatus is the GraphQL shape of what the update service knows.+//+// Zero times become nulls rather than the year 1: a "checked at" of 0001-01-01 is+// a date the UI would happily format, and "checked 2025 years ago" is worse than+// "not checked yet". An empty version becomes null for the same reason — the+// badge treats "no version named" as a verdict of its own.+func versionInfoFromStatus(status update.Status) *model.VersionInfo {+ info := &model.VersionInfo{+ Current: status.Current,+ State: updateStateFromStatus(status.State),+ Strategy: status.Strategy,+ }+ if status.Latest != "" {+ latest := status.Latest+ info.Latest = &latest+ }+ if !status.CheckedAt.IsZero() {+ checkedAt := status.CheckedAt+ info.CheckedAt = &checkedAt+ }+ if !status.FailedAt.IsZero() {+ failedAt := status.FailedAt+ info.FailedAt = &failedAt+ }+ return info+}++// updateStateFromStatus maps the service's vocabulary onto the schema's.+//+// Anything unrecognised — including the zero value of a Status that never went+// through the service — reads as unknown rather than as any verdict: the schema+// enum is closed, and "cannot say" is the only answer that is never wrong.+func updateStateFromStatus(state update.State) model.UpdateState {+ switch state {+ case update.StateDisabled:+ return model.UpdateStateDisabled+ case update.StatePending:+ return model.UpdateStatePending+ case update.StateUnreachable:+ return model.UpdateStateUnreachable+ case update.StateUpToDate:+ return model.UpdateStateUpToDate+ case update.StateUpdateAvailable:+ return model.UpdateStateUpdateAvailable+ default:+ return model.UpdateStateUnknown+ }+}diff --git a/backend/pkg/graph/version_info_test.go b/backend/pkg/graph/version_info_test.gonew file mode 100644index 00000000..27577c88--- /dev/null+++ b/backend/pkg/graph/version_info_test.go@@ -0,0 +1,76 @@+package graph++import (+ "testing"+ "time"++ "pentagi/pkg/graph/model"+ "pentagi/pkg/server/update"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// A status that has never heard from the service carries zero times and no+// version. Those have to leave as nulls: a formatted zero time is a date, and a+// date is a claim.+func TestVersionInfo_NothingKnownIsNull(t *testing.T) {+ t.Parallel()++ info := versionInfoFromStatus(update.Status{+ Current: "2.1.0-93e99748",+ State: update.StatePending,+ Strategy: "preview",+ })++ assert.Equal(t, "2.1.0-93e99748", info.Current)+ assert.Equal(t, model.UpdateStatePending, info.State)+ assert.Equal(t, "preview", info.Strategy)+ assert.Nil(t, info.Latest)+ assert.Nil(t, info.CheckedAt)+ assert.Nil(t, info.FailedAt)+}++func TestVersionInfo_AVerdictCarriesItsEvidence(t *testing.T) {+ t.Parallel()++ checked := time.Date(2026, 9, 2, 10, 0, 0, 0, time.UTC)+ failed := checked.Add(3 * time.Hour)++ info := versionInfoFromStatus(update.Status{+ Current: "2.1.0",+ State: update.StateUpdateAvailable,+ Latest: "2.4.0",+ Strategy: "stable",+ CheckedAt: checked,+ FailedAt: failed,+ })++ assert.Equal(t, model.UpdateStateUpdateAvailable, info.State)+ require.NotNil(t, info.Latest)+ assert.Equal(t, "2.4.0", *info.Latest)+ require.NotNil(t, info.CheckedAt)+ assert.True(t, info.CheckedAt.Equal(checked))+ require.NotNil(t, info.FailedAt)+ assert.True(t, info.FailedAt.Equal(failed))+}++// Every state the service can be in has a name in the schema, and a state the+// schema has never heard of reads as "cannot say" rather than as a verdict.+func TestVersionInfo_EveryStateHasASchemaName(t *testing.T) {+ t.Parallel()++ for state, expected := range map[update.State]model.UpdateState{+ update.StateDisabled: model.UpdateStateDisabled,+ update.StatePending: model.UpdateStatePending,+ update.StateUnreachable: model.UpdateStateUnreachable,+ update.StateUnknown: model.UpdateStateUnknown,+ update.StateUpToDate: model.UpdateStateUpToDate,+ update.StateUpdateAvailable: model.UpdateStateUpdateAvailable,+ update.State(""): model.UpdateStateUnknown,+ update.State("surprise"): model.UpdateStateUnknown,+ } {+ assert.Equal(t, expected, updateStateFromStatus(state), "state %q", state)+ assert.True(t, expected.IsValid(), "state %q maps outside the schema", state)+ }+}diff --git a/backend/pkg/providers/embeddings/embedder.go b/backend/pkg/providers/embeddings/embedder.goindex f551771a..fed53765 100644--- a/backend/pkg/providers/embeddings/embedder.go+++ b/backend/pkg/providers/embeddings/embedder.go@@ -35,6 +35,14 @@ func (e *embedder) IsAvailable() bool {return e.Embedder != nil}+// ResolvedProviderType reports the embedding provider type actually in effect.+func ResolvedProviderType(cfg *config.Config) string {+ if cfg.EmbeddingProvider == "openai" && cfg.EmbeddingURL != "" {+ return "custom"+ }+ return cfg.EmbeddingProvider+}+func New(cfg *config.Config) (Embedder, error) {httpClient, err := system.GetHTTPClient(cfg)if err != nil {diff --git a/backend/pkg/providers/embeddings/embedder_test.go b/backend/pkg/providers/embeddings/embedder_test.goindex 45c360c5..1fd4f7f6 100644--- a/backend/pkg/providers/embeddings/embedder_test.go+++ b/backend/pkg/providers/embeddings/embedder_test.go@@ -58,6 +58,34 @@ func TestNew_UnsupportedProvider(t *testing.T) {assert.False(t, e.IsAvailable())}+// TestResolvedProviderType pins that an "openai"-typed embedder pointed at a+// custom EMBEDDING_URL is reported as "custom" — it is not really talking to+// OpenAI — while every other combination is reported verbatim.+func TestResolvedProviderType(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ provider string+ url string+ want string+ }{+ {"openai without a custom url stays openai", "openai", "", "openai"},+ {"openai with a custom url becomes custom", "openai", "https://my-gateway/v1", "custom"},+ {"non-openai provider is untouched even with a url", "ollama", "https://my-gateway/v1", "ollama"},+ {"none stays none", "none", "", "none"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()++ cfg := &config.Config{EmbeddingProvider: tt.provider, EmbeddingURL: tt.url}+ assert.Equal(t, tt.want, ResolvedProviderType(cfg))+ })+ }+}+func TestNew_OpenAI_DefaultModel(t *testing.T) {t.Parallel()diff --git a/backend/pkg/providers/registry.go b/backend/pkg/providers/registry.goindex 828f35ef..fd59a2f2 100644--- a/backend/pkg/providers/registry.go+++ b/backend/pkg/providers/registry.go@@ -148,3 +148,14 @@ func entryForType(t provider.ProviderType) (registryEntry, bool) {}return registryEntry{}, false}++// EnabledDefaultProviderTypes reports the built-in (environment-configured)+func EnabledDefaultProviderTypes(cfg *config.Config) []string {+ types := make([]string, 0, len(providerRegistry))+ for _, e := range providerRegistry {+ if e.Enabled(cfg) {+ types = append(types, string(e.Type))+ }+ }+ return types+}diff --git a/backend/pkg/providers/registry_test.go b/backend/pkg/providers/registry_test.goindex 205177f1..96a3abd4 100644--- a/backend/pkg/providers/registry_test.go+++ b/backend/pkg/providers/registry_test.go@@ -3,6 +3,7 @@ package providersimport ("testing"+ "pentagi/pkg/config""pentagi/pkg/providers/provider""github.com/stretchr/testify/assert"@@ -38,3 +39,38 @@ func TestProviderRegistryMatchesAllProviderTypes(t *testing.T) {assert.Truef(t, ok, "%q is in providerRegistry but missing from AllProviderTypes", pt)}}++// TestEnabledDefaultProviderTypes pins that it reports exactly the types whose+// registry gate is satisfied — the same gate NewProviderController uses to+// decide what to construct — without requiring a database or Docker client.+func TestEnabledDefaultProviderTypes(t *testing.T) {+ t.Run("nothing configured", func(t *testing.T) {+ assert.Empty(t, EnabledDefaultProviderTypes(&config.Config{}))+ })++ t.Run("only credentialed types are reported", func(t *testing.T) {+ cfg := &config.Config{+ OpenAIKey: "key",+ AnthropicAPIKey: "key",+ KimiAPIKey: "key",+ }++ types := EnabledDefaultProviderTypes(cfg)++ assert.ElementsMatch(t, []string{+ string(provider.ProviderOpenAI),+ string(provider.ProviderAnthropic),+ string(provider.ProviderKimi),+ }, types)+ })++ t.Run("custom needs both a URL and a model or config path", func(t *testing.T) {+ assert.Empty(t, EnabledDefaultProviderTypes(&config.Config{LLMServerURL: "http://llm"}))++ types := EnabledDefaultProviderTypes(&config.Config{+ LLMServerURL: "http://llm",+ LLMServerModel: "some-model",+ })+ assert.Equal(t, []string{string(provider.ProviderCustom)}, types)+ })+}diff --git a/backend/pkg/server/router.go b/backend/pkg/server/router.goindex d2449207..a013b40e 100644--- a/backend/pkg/server/router.go+++ b/backend/pkg/server/router.go@@ -25,6 +25,7 @@ import ("pentagi/pkg/server/logger""pentagi/pkg/server/oauth""pentagi/pkg/server/services"+ "pentagi/pkg/server/update"_ "pentagi/pkg/server/docs" // swagger docs@@ -88,6 +89,7 @@ func NewRouter(controller controller.FlowController,subscriptions subscriptions.SubscriptionsController,dockerClient docker.DockerClient,+ updates *update.Service,) *gin.Engine {gin.SetMode(gin.ReleaseMode)if cfg.Debug {@@ -203,6 +205,7 @@ func NewRouter(anonymizerService := services.NewAnonymizerService(textReplacer)graphqlService := services.NewGraphqlService(db, cfg, baseURL, cfg.CorsOrigins, tokenCache, providers, controller, subscriptions, knowledgeStore, textReplacer,+ updates,)router := gin.Default()diff --git a/backend/pkg/server/services/graphql.go b/backend/pkg/server/services/graphql.goindex c9ff618f..2fd12b92 100644--- a/backend/pkg/server/services/graphql.go+++ b/backend/pkg/server/services/graphql.go@@ -17,6 +17,7 @@ import ("pentagi/pkg/providers""pentagi/pkg/server/auth""pentagi/pkg/server/logger"+ "pentagi/pkg/server/update""pentagi/pkg/templates""github.com/99designs/gqlgen/graphql"@@ -60,6 +61,7 @@ func NewGraphqlService(subscriptions subscriptions.SubscriptionsController,knowledgeStore knowledge.KnowledgeStore,replacer anonymizer.Replacer,+ updates *update.Service,) *GraphqlService {srv := handler.New(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{DB: db,@@ -72,6 +74,7 @@ func NewGraphqlService(Subscriptions: subscriptions,Knowledge: knowledgeStore,Replacer: replacer,+ Updates: updates,}}))component := "pentagi-gql"diff --git a/backend/pkg/server/update/update.go b/backend/pkg/server/update/update.gonew file mode 100644index 00000000..04b756a6--- /dev/null+++ b/backend/pkg/server/update/update.go@@ -0,0 +1,521 @@+// Package update asks the update service what this installation should be running.+//+// An update check made by the installer says which artefacts are on the machine+// and nothing about the server itself, and it only happens when somebody is+// installing something. This asks directly and on a schedule: it sends the build+// that is running and a summary of how the server is set up, and is told which+// build to move to — as a container image to pull, and, where one is published, as+// an executable that can replace this process's own binary.+//+// What it sends about the installation is produced by database.GetInstanceSummary+// and carried through untouched: quantities and closed vocabularies, nothing that+// identifies a person and nothing anybody wrote. The summary is versioned inside+// itself, so its shape can grow without this package, or anything in between,+// knowing what it holds.+//+// Nothing here ACTS on the answer. The verdict is kept, as a Status the rest of the+// server can read and show — the version badge in the UI is what it exists for —+// but applying an update is a decision for whoever operates the installation, and+// this package's whole contract with the rest of the server is that it cannot fail+// it and cannot slow it down.+package update++import (+ "context"+ "encoding/json"+ "fmt"+ "math/rand"+ "net/http"+ "net/url"+ "strings"+ "sync"+ "time"++ "pentagi/pkg/config"+ "pentagi/pkg/database"+ "pentagi/pkg/providers"+ "pentagi/pkg/providers/embeddings"+ "pentagi/pkg/version"++ "github.com/google/uuid"+ "github.com/sirupsen/logrus"+ "github.com/vxcontrol/cloud/models"+ "github.com/vxcontrol/cloud/sdk"+)++const (+ // The route name IS the endpoint code the service rate-limits, quotas and+ // authorises by — a name of our own invention is a name it does not recognise,+ // and the failure is a 403 or a quota rejection rather than "no such endpoint".+ // Neither this nor the path is ours to choose.+ routeProductUpdate = "pentagi_updates_check"+ pathProductUpdate = "/api/v1/proxy/updates/pentagi/check"++ // requestTimeout bounds one exchange. The transport fetches a proof-of-work+ // ticket first, so the budget covers two round trips and the work between.+ requestTimeout = 30 * time.Second++ // startupDelay staggers the first exchange.+ //+ // Every installation in the fleet starts its clock at its own boot, but a+ // power cut across a datacentre or a fleet-wide upgrade restarts many at once,+ // and a call that fires immediately would turn that into a thundering herd+ // against one endpoint. A random wait inside this window costs nothing and+ // spreads them.+ startupDelay = 2 * time.Minute+)++// State is what the last exchange with the update service established about the+// build this process runs.+type State string++const (+ // StateDisabled says update checks are switched off by configuration, or were+ // never configured well enough to run.+ StateDisabled State = "disabled"+ // StatePending says no exchange has completed since this process started.+ StatePending State = "pending"+ // StateUnreachable says every exchange so far failed before an answer arrived.+ StateUnreachable State = "unreachable"+ // StateUnknown says the service answered but could not say whether this build+ // has an update: it did not recognise the build, named no version to move to,+ // or publishes nothing for this platform.+ StateUnknown State = "unknown"+ // StateUpToDate says this build is the newest offered on its channel.+ StateUpToDate State = "up_to_date"+ // StateUpdateAvailable says a newer version is offered; Status.Latest names it.+ StateUpdateAvailable State = "update_available"+)++// Status is what this installation knows about updates to itself.+//+// A verdict, once reached, outlives the failures that follow it: an update that+// was available an hour ago is still available, and the build this process runs+// cannot change underneath it — a replaced binary is a new process, which starts+// from pending. What a failure changes is how old the verdict is, and FailedAt+// says so.+type Status struct {+ // Current is the build this process runs.+ Current string+ // State is the verdict of the most recent answer, or why there is none.+ State State+ // Latest is the newest version the service offered, when it named one. It is+ // kept beside StateUnknown too, when the service named the newest published+ // build without being able to say whether this one is behind it.+ Latest string+ // Strategy is the channel the answer is computed under.+ Strategy string+ // CheckedAt is when the answer behind State arrived; zero until one has.+ CheckedAt time.Time+ // FailedAt is when the most recent exchange failed; zero when the last one+ // produced an answer.+ FailedAt time.Time+}++// DisabledStatus describes an installation whose checks never run — because the+// service could not be built, typically over a missing or malformed installation+// id. To whoever reads the badge that is the same thing as checks switched off,+// and it still names the build, which is the half of the badge that never depends+// on the service.+func DisabledStatus(cfg *config.Config) Status {+ return Status{+ Current: version.GetBinaryVersion(),+ State: StateDisabled,+ Strategy: string(effectiveStrategy(cfg)),+ }+}++// Service sends this installation's state to the update service periodically and+// keeps what it answers.+type Service struct {+ cfg *config.Config+ queries *database.Queries+ client *client+ logger *logrus.Entry++ mu sync.RWMutex+ status Status+}++// New builds the service, or explains why there will not be one.+//+// A missing or malformed installation id is the only hard stop: a message that+// cannot say which installation it describes says nothing, and inventing an+// identity would create an installation that never existed.+func New(cfg *config.Config, queries *database.Queries) (*Service, error) {+ if cfg == nil || queries == nil {+ return nil, fmt.Errorf("update: configuration and database are both required")+ }++ built, err := newClient(cfg)+ if err != nil {+ return nil, fmt.Errorf("update: %w", err)+ }++ return &Service{+ cfg: cfg,+ queries: queries,+ client: built,+ logger: logrus.WithField("component", "update"),+ status: Status{+ Current: version.GetBinaryVersion(),+ State: StatePending,+ Strategy: string(effectiveStrategy(cfg)),+ },+ }, nil+}++// Status is a copy of what is currently known. Safe to call from any goroutine,+// and cheap enough to answer on every page load.+func (r *Service) Status() Status {+ r.mu.RLock()+ defer r.mu.RUnlock()+ return r.status+}++// Run keeps going until the context ends.+//+// Nothing here is allowed to interrupt the product. Every failure is a debug line+// and the next tick tries again; an endpoint that is down, a licence that has+// expired, a network that is not there are all ordinary states of the world for+// something that talks to a service it does not depend on.+func (r *Service) Run(ctx context.Context) {+ interval := r.cfg.UpdateCheckInterval+ if interval <= 0 {+ r.logger.Debug("disabled by configuration")+ r.mu.Lock()+ r.status.State = StateDisabled+ r.mu.Unlock()+ return+ }++ select {+ case <-ctx.Done():+ return+ case <-time.After(time.Duration(rand.Int63n(int64(startupDelay)))):+ }++ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ r.sendOnce(ctx)++ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ }+ }+}++// sendOnce gathers the current state and sends it.+func (r *Service) sendOnce(ctx context.Context) {+ ctx, cancel := context.WithTimeout(ctx, requestTimeout)+ defer cancel()++ summary := r.queries.GetInstanceSummary(ctx, database.SummaryOptions{+ Features: database.InstanceFeatures{+ Debug: r.cfg.Debug,+ AskUser: r.cfg.AskUser,+ DockerInside: r.cfg.DockerInside,+ AssistantUseAgents: r.cfg.AssistantUseAgents,+ },+ OAuth: configuredOAuthProviders(r.cfg),+ DefaultProviders: providers.EnabledDefaultProviderTypes(r.cfg),+ EmbeddingProvider: embeddings.ResolvedProviderType(r.cfg),+ })++ document, err := json.Marshal(summary)+ if err != nil {+ r.recordFailure(fmt.Errorf("cannot render the state summary: %w", err))+ return+ }+ if len(document) > models.MaxProductInfoBytes {+ // Refusing here rather than being refused there. The service would reject+ // the whole request, and the reason would arrive as a validation error+ // about a field nobody can see from this side.+ r.recordFailure(fmt.Errorf("the state summary is %d bytes, larger than the service accepts",+ len(document)))+ return+ }++ request := models.ProductUpdateRequest{+ Schema: uint16(summary.Schema),+ Version: normalizeVersion(summary.Version),+ // The platform of THIS PROCESS, which for a container is the platform of its+ // image — so it selects both the image the service matches us against and the+ // executable it offers beside it.+ //+ // Read out of the summary rather than computed here, exactly like the schema+ // and the version above. The document carries all three as well, because a+ // description forwarded by somebody else has to stand on its own, and two+ // places computing the same fact is how the envelope and the document come to+ // disagree about which build is running.+ OS: models.OSType(summary.OS),+ Arch: models.ArchType(summary.Arch),+ BinaryHash: summary.BinaryHash,+ Strategy: updateStrategy(r.cfg),+ Info: json.RawMessage(document),+ }++ answer, err := r.client.send(ctx, request)+ if err != nil {+ r.recordFailure(err)+ return+ }++ r.record(answer)+}++// record keeps what the service answered, and says so in the log. Nothing acts+// on it: a server that started pulling images or replacing its own binary on a+// timer would be doing something nobody asked it to.+func (r *Service) record(answer *models.ProductUpdateResponse) {+ verdict := interpret(answer)++ r.mu.Lock()+ r.status.State = verdict.state+ r.status.Latest = verdict.latest+ r.status.CheckedAt = time.Now()+ r.status.FailedAt = time.Time{}+ r.mu.Unlock()++ entry := r.logger.WithField("state", verdict.state)+ if answer != nil && answer.Update != nil {+ entry = entry.WithField("resolution", answer.Update.Resolution)+ }+ if verdict.latest != "" {+ entry = entry.WithField("offered", verdict.latest)+ }+ if answer != nil && answer.Binary != nil {+ entry = entry.WithField("executable", answer.Binary.Version)+ }+ entry.Debug(verdict.message)+}++// recordFailure notes that an exchange produced no answer.+//+// A verdict already reached stays — see Status — and only an installation that+// has never heard anything becomes unreachable: nothing is known, and the reason+// is that nothing could be asked.+func (r *Service) recordFailure(err error) {+ r.logger.WithError(err).Debug("not delivered")++ r.mu.Lock()+ defer r.mu.Unlock()+ r.status.FailedAt = time.Now()+ if r.status.State == StatePending {+ r.status.State = StateUnreachable+ }+}++// verdict is what one answer says, reduced to what the badge and the log need.+type verdict struct {+ state State+ latest string+ message string+}++// interpret reads an answer.+//+// `identified` is why this is more than one branch. When the service could not+// match the running build to an image it published — a development build, a+// private rebuild — the answer describes the newest published build rather than a+// step from this one, and reading it as "an update is available" would announce+// an update on every single check, forever. The version it names is still kept:+// "the newest published is 2.4.0" is worth showing beside "this build could not be+// matched".+//+// A `has_update` that names no version is not an update either. There is nothing+// to tell the operator to move to, and a badge pointing at nothing cannot be acted+// on — which is what the operator would try to do with it.+func interpret(answer *models.ProductUpdateResponse) verdict {+ if answer == nil || answer.Update == nil {+ return verdict{+ state: StateUnknown,+ message: "delivered; no update information for this platform",+ }+ }++ latest := offeredVersion(answer)+ switch {+ case !answer.Identified:+ return verdict{+ state: StateUnknown,+ latest: latest,+ message: "delivered; this build is not one we published, so the answer names " ++ "the newest available rather than a step from here",+ }+ case !answer.Update.HasUpdate:+ return verdict{state: StateUpToDate, latest: latest, message: "delivered; up to date"}+ case latest == "":+ return verdict{+ state: StateUnknown,+ message: "delivered; an update is offered but no version is named for it",+ }+ default:+ return verdict{state: StateUpdateAvailable, latest: latest, message: "delivered; an update is available"}+ }+}++// offeredVersion is the version the answer points at, from whichever field+// carries it: the offered image's version first, the stack's latest release when+// the image declares none.+func offeredVersion(answer *models.ProductUpdateResponse) string {+ if answer.Version != nil && *answer.Version != "" {+ return *answer.Version+ }+ if answer.Update != nil && answer.Update.LatestVersion != nil {+ return *answer.Update.LatestVersion+ }+ return ""+}++// updateStrategy is which channel to be answered from.+//+// Sent rather than left to the service's default so that one installation reads the+// same channel everywhere: UPDATE_STRATEGY is what the installer applies to the+// images it pulls, and an answer here computed under a different one would disagree+// with what the operator configured. An unrecognised value is dropped rather than+// forwarded — the field is validated on both sides, and a whole check refused over+// a typo in a variable is worse than a check answered under the default.+func updateStrategy(cfg *config.Config) models.UpdateStrategy {+ if cfg == nil {+ return ""+ }+ strategy := models.UpdateStrategy(strings.TrimSpace(cfg.UpdateStrategy))+ if strategy.Valid() != nil {+ return ""+ }+ return strategy+}++// effectiveStrategy is the channel the service actually answers under: the+// configured one when it is forwarded, otherwise the default both sides share.+func effectiveStrategy(cfg *config.Config) models.UpdateStrategy {+ if strategy := updateStrategy(cfg); strategy != "" {+ return strategy+ }+ return models.UpdateStrategyPreview+}++// normalizeVersion converts a build version into one the service accepts.+//+// A development build is named after its branch rather than a release, and the+// service validates this field as a version. Sending the branch name would have+// the whole request refused over a field that is decoration; "0.0.0" says "some+// build, older than anything published", which is exactly true.+func normalizeVersion(raw string) string {+ if err := models.GetValidator().Var(raw, "semver"); err != nil {+ return "0.0.0"+ }+ return raw+}++// configuredOAuthProviders names the sign-in providers this server offers — the+// providers, never a user.+func configuredOAuthProviders(cfg *config.Config) []string {+ providers := []string{}+ if cfg.PublicURL == "" {+ return providers+ }+ if cfg.OAuthGoogleClientID != "" && cfg.OAuthGoogleClientSecret != "" {+ providers = append(providers, "google")+ }+ if cfg.OAuthGithubClientID != "" && cfg.OAuthGithubClientSecret != "" {+ providers = append(providers, "github")+ }+ return providers+}++// client is the transport half: one SDK call, built once.+type client struct {+ call sdk.CallReqBytesRespBytes+}++func newClient(cfg *config.Config) (*client, error) {+ buildVersion := version.GetBinaryVersion()++ installationID, err := uuid.Parse(cfg.InstallationID)+ if err != nil {+ return nil, fmt.Errorf("update: installation id %q is not a uuid: %w", cfg.InstallationID, err)+ }++ transport := sdk.DefaultTransport()+ if value := strings.TrimSpace(cfg.ProxyURL); value != "" {+ parsed, err := url.Parse(value)+ if err != nil {+ return nil, fmt.Errorf("proxy %q is not a valid URL: %w", cfg.ProxyURL, err)+ }+ if parsed.Host == "" {+ return nil, fmt.Errorf("proxy %q has no host", cfg.ProxyURL)+ }+ transport.Proxy = http.ProxyURL(parsed)+ }++ built := &client{}++ options := []sdk.Option{+ sdk.WithTransport(transport),+ sdk.WithInstallationID(installationID),+ sdk.WithClient("PentAGI", buildVersion),+ }++ // Validated before it is handed over: the SDK drops a key it cannot decode+ // without saying so, and the call then runs anonymously — which looks from+ // the outside exactly like a licence that is not being honoured.+ if key := strings.TrimSpace(cfg.LicenseKey); key != "" {+ if _, err := sdk.IntrospectLicenseKey(key); err == nil {+ options = append(options, sdk.WithLicenseKey(key))+ }+ }++ configs := []sdk.CallConfig{+ {+ Calls: []any{&built.call},+ Host: cfg.UpdateServerHost,+ Name: routeProductUpdate,+ Path: pathProductUpdate,+ Method: sdk.CallMethodPOST,+ },+ }++ if err := sdk.Build(configs, options...); err != nil {+ return nil, fmt.Errorf("failed to build the client: %w", err)+ }++ return built, nil+}++func (c *client) send(+ ctx context.Context, request models.ProductUpdateRequest,+) (*models.ProductUpdateResponse, error) {+ if c == nil || c.call == nil {+ return nil, fmt.Errorf("the client is not initialised")+ }+ if err := request.Valid(); err != nil {+ return nil, fmt.Errorf("the request does not satisfy the contract: %w", err)+ }++ body, err := json.Marshal(request)+ if err != nil {+ return nil, fmt.Errorf("failed to encode the request: %w", err)+ }++ response, err := c.call(ctx, body)+ if err != nil {+ return nil, err+ }++ // Through the envelope, never straight into the payload. Every answer is+ // wrapped in {"status": …, "data": …}: decoding the body directly into the+ // payload type SUCCEEDS and yields a zero value, so a client that skips this+ // step reads every answer as "nothing to do" and never finds out.+ answer, err := models.ParseEnvelope[models.ProductUpdateResponse](response)+ if err != nil {+ return nil, fmt.Errorf("failed to decode the answer: %w", err)+ }++ return &answer, nil+}diff --git a/backend/pkg/server/update/update_test.go b/backend/pkg/server/update/update_test.gonew file mode 100644index 00000000..94879cb2--- /dev/null+++ b/backend/pkg/server/update/update_test.go@@ -0,0 +1,439 @@+package update++import (+ "encoding/json"+ "errors"+ "io"+ "strings"+ "sync"+ "testing"++ "pentagi/pkg/config"+ "pentagi/pkg/database"+ "pentagi/pkg/version"++ "github.com/sirupsen/logrus"+ "github.com/vxcontrol/cloud/models"+)++// A development build is named after its branch, and the contract validates this+// field as a version. Sending "develop" would have the ENTIRE request refused+// over a field that is decoration — and refused silently, because the failure+// arrives as a validation error nobody on this side can see. The build itself is+// not lost: it travels in the User-Agent.+func TestABranchBuildIsStillAcceptedByTheContract(t *testing.T) {+ for name, raw := range map[string]string{+ "a branch name": "develop",+ "a commit hash": "a1b2c3d",+ "nothing": "",+ "a tag with v": "v2.1.0",+ } {+ normalised := normalizeVersion(raw)+ if err := models.GetValidator().Var(normalised, "semver"); err != nil {+ t.Errorf("%s (%q) normalised to %q, which the contract refuses: %v",+ name, raw, normalised, err)+ }+ }++ // A real version passes through untouched — the normalisation must not be a+ // blanket replacement, or every report would claim the same build.+ if got := normalizeVersion("2.1.0"); got != "2.1.0" {+ t.Errorf("a valid version was rewritten to %q", got)+ }+ if got := normalizeVersion("2.1.0-93e99748"); got != "2.1.0-93e99748" {+ t.Errorf("a branch build with a version core was rewritten to %q", got)+ }+}++// TestAReportFitsWhatTheContractAccepts.+//+// The document is bounded by the contract, and the bound is not generous next to+// a summary that grows with the provider list. Exceeding it does not truncate+// anything — the service refuses the whole request — so the size is checked+// before sending rather than discovered afterwards.+func TestAReportFitsWhatTheContractAccepts(t *testing.T) {+ summary := database.InstanceSummary{+ Schema: database.InstanceSummarySchema,+ Version: "2.1.0",+ }+ // Every provider type there is, each with usage: the widest a real document+ // gets today.+ for _, provider := range []string{+ "openai", "anthropic", "gemini", "bedrock", "ollama", "custom",+ "deepseek", "glm", "kimi", "qwen", "minimax",+ } {+ summary.Providers = append(summary.Providers,+ database.InstanceProvider{Type: provider, Count: 3})+ summary.Usage = append(summary.Usage, database.InstanceUsage{+ Provider: provider, Chains: 99999, TokensIn: 123456789, TokensOut: 987654321,+ CacheIn: 1234567, CacheOut: 7654321, CostIn: 12345.67, CostOut: 7654.32,+ })+ }+ summary.OAuth = []string{"google", "github"}+ summary.Skipped = []string{"toolcalls", "usage"}++ document, err := json.Marshal(summary)+ if err != nil {+ t.Fatalf("the description must serialise: %v", err)+ }+ if len(document) > models.MaxProductInfoBytes {+ t.Errorf("a full description is %d bytes, over the %d the contract accepts — "++ "every report from a fully configured installation would be refused whole",+ len(document), models.MaxProductInfoBytes)+ }+}++// TestTheDescriptionNamesNoOne is the last gate before the document leaves the+// process. The summary is built elsewhere and tested there; this checks the thing+// that actually goes on the wire, because that is what cannot be taken back.+func TestTheDescriptionNamesNoOne(t *testing.T) {+ summary := database.InstanceSummary{+ Schema: database.InstanceSummarySchema,+ Version: "2.1.0",+ Providers: []database.InstanceProvider{{Type: "openai", Count: 2}},+ OAuth: []string{"google"},+ Usage: []database.InstanceUsage{{Provider: "openai", TokensIn: 10}},+ }+ summary.Counts.Users = 3+ summary.Counts.Flows = 12++ document, err := json.Marshal(summary)+ if err != nil {+ t.Fatalf("serialise: %v", err)+ }++ // Keys, not values: a value could legitimately be any string, but a key names+ // what kind of thing the document is prepared to carry.+ var shape map[string]json.RawMessage+ if err := json.Unmarshal(document, &shape); err != nil {+ t.Fatalf("the document must be an object: %v", err)+ }++ allowed := map[string]bool{+ "schema": true, "version": true, "develop": true, "features": true,+ "providers": true, "oauth": true, "counts": true, "usage": true, "skipped": true,+ // The provider type embeddings actually go to, as the product resolves it.+ // A closed vocabulary and a deliberate choice: an "openai" embedder pointed+ // at a custom URL is not talking to OpenAI, and the base URL — which would+ // name somebody's infrastructure — is never sent.+ "embedding_provider": true,+ // What this process is, and it has to be in the document rather than only in+ // the request envelope: whoever forwards a description cannot produce these.+ // A caller running this binary in a container sees the platform of the HOST,+ // and the image digest it can see is not the file that is executing.+ //+ // Neither says anything about the machine or the people on it. `os`/`arch`+ // are the two-value vocabularies we compile for, and `binary_hash` is the+ // sha256 of an executable we published — it identifies OUR build, not this+ // installation, and it is the only thing that tells two builds carrying the+ // same version string apart.+ "os": true, "arch": true, "binary_hash": true,+ }+ for key := range shape {+ if !allowed[key] {+ t.Errorf("the document carries %q, which nobody decided to send — every key here "++ "has to be a deliberate choice, because this leaves the machine", key)+ }+ }++ // And the one thing no key list can catch: an identifier smuggled inside a+ // value. The installation is identified by the SDK headers, never by content.+ if strings.Contains(strings.ToLower(string(document)), "@") {+ t.Errorf("the document contains an address-shaped value: %s", document)+ }+}++// TestAMisconfiguredStrategyIsDroppedRatherThanForwarded.+//+// UPDATE_STRATEGY is an operator-supplied string and the field is validated on both+// sides, so forwarding a typo would have the whole check refused — and a check that+// is refused is an installation that stops being told about updates AND stops being+// visible, over one misspelt variable. Omitting the field has the service answer+// under its own default, which is the same channel this product defaults to.+func TestAMisconfiguredStrategyIsDroppedRatherThanForwarded(t *testing.T) {+ for _, valid := range []string{"preview", "stable", "nightly"} {+ if got := updateStrategy(&config.Config{UpdateStrategy: valid}); string(got) != valid {+ t.Errorf("%q must be forwarded, got %q", valid, got)+ }+ }+ // Whitespace is the shape a .env value actually arrives in.+ if got := updateStrategy(&config.Config{UpdateStrategy: " stable "}); got != models.UpdateStrategyStable {+ t.Errorf("a padded value must still be recognised, got %q", got)+ }+ for _, invalid := range []string{"", "Stable", "latest", "beta"} {+ if got := updateStrategy(&config.Config{UpdateStrategy: invalid}); got != "" {+ t.Errorf("%q must be dropped, got %q", invalid, got)+ }+ }++ // And an omitted strategy has to leave the request valid: this is the field+ // that made the difference between being answered and being refused.+ request := models.ProductUpdateRequest{+ Schema: 1,+ Version: "2.1.0",+ OS: models.OSTypeLinux,+ Arch: models.ArchTypeAMD64,+ Strategy: updateStrategy(&config.Config{UpdateStrategy: "nonsense"}),+ Info: json.RawMessage(`{"schema":1}`),+ }+ if err := request.Valid(); err != nil {+ t.Errorf("a request with no strategy must satisfy the contract: %v", err)+ }+}++// TestTheAnswerIsReadThroughTheEnvelope.+//+// Every answer is wrapped in {"status": …, "data": …}. Decoding a body straight+// into the payload type SUCCEEDS and yields a zero value, so a client that skips+// the envelope reads every answer as "nothing to do" and never finds out — which is+// indistinguishable from a fleet that is perfectly up to date.+func TestTheAnswerIsReadThroughTheEnvelope(t *testing.T) {+ const body = `{"status":"success","data":{+ "update":{"stack":"pentagi","has_update":true,"resolution":"channel"},+ "version":"2.4.0","identified":true}}`++ answer, err := models.ParseEnvelope[models.ProductUpdateResponse]([]byte(body))+ if err != nil {+ t.Fatalf("the answer must decode: %v", err)+ }+ if answer.Update == nil || !answer.Update.HasUpdate {+ t.Fatalf("the update was lost: %+v", answer.Update)+ }+ if answer.Version == nil || *answer.Version != "2.4.0" {+ t.Errorf("the offered version was lost: %v", answer.Version)+ }++ // The failure this guards: the same bytes read WITHOUT the envelope.+ var direct models.ProductUpdateResponse+ if err := json.Unmarshal([]byte(body), &direct); err != nil {+ t.Fatalf("the wrong way must still parse, which is what makes it dangerous: %v", err)+ }+ if direct.Update != nil {+ t.Error("decoding past the envelope must not accidentally work; this test is measuring nothing")+ }+}++// TestAnAnswerWithoutAMatchedBuildIsNotReportedAsAnUpdate.+//+// `has_update` is true whenever the service has something to offer, including when+// it could not work out which image the running build is — a development build, a+// private rebuild — in which case the offer is "the newest we publish" rather than+// a step from here. Reading that as an update available would announce one on every+// check, forever, for every such installation. The version it names is still kept,+// beside a verdict that says it could not be compared to this build.+//+// The two empty shapes are here for a different reason: both have a nil Update, and+// reaching into it is a panic in a goroutine the server does not supervise.+func TestAnAnswerWithoutAMatchedBuildIsNotReportedAsAnUpdate(t *testing.T) {+ offered := "2.4.0"+ cases := map[string]struct {+ answer *models.ProductUpdateResponse+ state State+ latest string+ expect string+ }{+ "nothing at all": {nil, StateUnknown, "", "no update information"},+ "nothing for this platform": {+ &models.ProductUpdateResponse{}, StateUnknown, "", "no update information",+ },+ "a build we do not recognise": {+ &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi, HasUpdate: true},+ Version: &offered,+ Identified: false,+ },+ StateUnknown, "2.4.0", "not one we published",+ },+ "up to date": {+ &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi},+ Identified: true,+ },+ StateUpToDate, "", "up to date",+ },+ "a real update": {+ &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi, HasUpdate: true},+ Version: &offered,+ Identified: true,+ },+ StateUpdateAvailable, "2.4.0", "an update is available",+ },+ // An offer with nothing to move to is not something the operator can act+ // on, and a badge pointing at nothing is exactly what they would try to+ // act on.+ "an update with no version to move to": {+ &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi, HasUpdate: true},+ Identified: true,+ },+ StateUnknown, "", "no version is named",+ },+ // The version can also arrive on the stack rather than on the image.+ "a version named only on the stack": {+ &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{+ Stack: models.ProductStackPentagi, HasUpdate: true, LatestVersion: &offered,+ },+ Identified: true,+ },+ StateUpdateAvailable, "2.4.0", "an update is available",+ },+ }++ for name, tc := range cases {+ logger, recorded := recordingLogger()+ service := &Service{logger: logger}+ service.record(tc.answer)++ if len(*recorded) != 1 {+ t.Fatalf("%s: expected exactly one line, got %d", name, len(*recorded))+ }+ if !strings.Contains((*recorded)[0], tc.expect) {+ t.Errorf("%s: said %q, expected it to mention %q", name, (*recorded)[0], tc.expect)+ }++ status := service.Status()+ if status.State != tc.state {+ t.Errorf("%s: kept state %q, expected %q", name, status.State, tc.state)+ }+ if status.Latest != tc.latest {+ t.Errorf("%s: kept latest %q, expected %q", name, status.Latest, tc.latest)+ }+ if status.CheckedAt.IsZero() {+ t.Errorf("%s: an answer must be dated", name)+ }+ if !status.FailedAt.IsZero() {+ t.Errorf("%s: an answer clears the last failure", name)+ }+ }+}++// TestAVerdictOutlivesTheFailuresThatFollowIt.+//+// The service is asked every few hours and the answer is shown for the whole+// interval. A failure in between does not make an update that was available an+// hour ago unavailable — the build has not changed, a replaced binary being a new+// process — so the verdict stays and the failure is dated beside it. Only an+// installation that has never heard anything reads as unreachable.+func TestAVerdictOutlivesTheFailuresThatFollowIt(t *testing.T) {+ logger, _ := recordingLogger()+ offered := "2.4.0"+ service := &Service{logger: logger, status: Status{State: StatePending}}++ service.recordFailure(errors.New("no route to host"))+ if got := service.Status(); got.State != StateUnreachable || got.FailedAt.IsZero() {+ t.Fatalf("a failure before any answer must read as unreachable and be dated: %+v", got)+ }++ service.record(&models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi, HasUpdate: true},+ Version: &offered,+ Identified: true,+ })+ if got := service.Status(); got.State != StateUpdateAvailable || !got.FailedAt.IsZero() {+ t.Fatalf("an answer must set the verdict and clear the failure: %+v", got)+ }++ service.recordFailure(errors.New("no route to host"))+ got := service.Status()+ if got.State != StateUpdateAvailable || got.Latest != "2.4.0" {+ t.Errorf("a failure must not take back a verdict: %+v", got)+ }+ if got.FailedAt.IsZero() {+ t.Errorf("the failure must still be dated beside the verdict: %+v", got)+ }+}++// TestARunWithNoIntervalSaysSo.+//+// The badge distinguishes "switched off" from "never answered": an operator who set+// UPDATE_CHECK_INTERVAL=0 should not be told the update service is unreachable.+func TestARunWithNoIntervalSaysSo(t *testing.T) {+ logger, _ := recordingLogger()+ service := &Service{cfg: &config.Config{}, logger: logger, status: Status{State: StatePending}}++ service.Run(t.Context())++ if got := service.Status().State; got != StateDisabled {+ t.Errorf("a zero interval must read as disabled, got %q", got)+ }+}++// TestAnInstallationWithoutAServiceStillNamesItsBuild.+//+// The half of the badge that never depends on the service is the version itself,+// and it has to be right even when the service could not be built at all.+func TestAnInstallationWithoutAServiceStillNamesItsBuild(t *testing.T) {+ status := DisabledStatus(&config.Config{UpdateStrategy: "stable"})+ if status.Current != version.GetBinaryVersion() {+ t.Errorf("the build is %q, expected %q", status.Current, version.GetBinaryVersion())+ }+ if status.State != StateDisabled {+ t.Errorf("state %q, expected disabled", status.State)+ }+ if status.Strategy != "stable" {+ t.Errorf("a configured channel must be reported, got %q", status.Strategy)+ }+ // The channel the service actually answers under, not the misspelt one.+ if got := DisabledStatus(&config.Config{UpdateStrategy: "nonsense"}).Strategy; got != "preview" {+ t.Errorf("an unrecognised channel must report the default, got %q", got)+ }+ if got := DisabledStatus(nil).Strategy; got != "preview" {+ t.Errorf("no configuration must still report the default, got %q", got)+ }+}++// TestStatusIsSafeToReadWhileItChanges is for the race detector: the resolver+// reads on every page load, and the ticker writes from its own goroutine.+func TestStatusIsSafeToReadWhileItChanges(t *testing.T) {+ logger, _ := recordingLogger()+ offered := "2.4.0"+ service := &Service{logger: logger, status: Status{State: StatePending}}+ answer := &models.ProductUpdateResponse{+ Update: &models.UpdateInfo{Stack: models.ProductStackPentagi, HasUpdate: true},+ Version: &offered,+ Identified: true,+ }++ var wg sync.WaitGroup+ for range 16 {+ wg.Add(3)+ go func() { defer wg.Done(); service.record(answer) }()+ go func() { defer wg.Done(); service.recordFailure(errors.New("flaky")) }()+ go func() { defer wg.Done(); _ = service.Status() }()+ }+ wg.Wait()++ if got := service.Status(); got.State != StateUpdateAvailable {+ t.Errorf("a verdict was lost to a concurrent failure: %+v", got)+ }+}++// recordingLogger is a logger whose messages can be read back. Debug level because+// that is the level this package speaks at, and a hook attached above it would+// record nothing.+func recordingLogger() (*logrus.Entry, *[]string) {+ recorded := &[]string{}+ base := logrus.New()+ base.SetLevel(logrus.DebugLevel)+ base.SetOutput(io.Discard)+ base.AddHook(&collector{recorded: recorded})+ return base.WithField("component", "update"), recorded+}++// collector is safe to fire from several goroutines: logrus invokes hooks outside+// its own lock, and the service logs from whichever goroutine records.+type collector struct {+ mu sync.Mutex+ recorded *[]string+}++func (c *collector) Levels() []logrus.Level { return logrus.AllLevels }++func (c *collector) Fire(entry *logrus.Entry) error {+ c.mu.Lock()+ defer c.mu.Unlock()+ *c.recorded = append(*c.recorded, entry.Message)+ return nil+}diff --git a/backend/pkg/version/version.go b/backend/pkg/version/version.goindex b6b16dad..0fa24735 100644--- a/backend/pkg/version/version.go+++ b/backend/pkg/version/version.go@@ -1,7 +1,12 @@package versionimport (+ "crypto/sha256"+ "encoding/hex""fmt"+ "io"+ "os"+ "sync")// PackageName is service name or binary name@@ -34,3 +39,44 @@ func GetBinaryName() string {}return "pentagi"}++// BinaryHash is the sha256 of the executable this process was started from.+//+// It answers what the version string cannot: two builds cut from the same branch+// carry the same "develop" or the same "0.9.3-87ac00f", and outside a release that+// is the normal case rather than the exception. Anything describing this process to+// somebody else needs it, and the value belongs here beside GetBinaryVersion for the+// same reason — both answer "which build is this".+//+// Computed once. Reading a hundred megabytes is not free, and the file this process+// was started from cannot become a different file while it runs: replacing the+// binary on disk produces a new file that this process is not executing, so hashing+// again would report something that is not running.+//+// Empty when it cannot be read — a hash that could not be computed is not a fact+// worth inventing, and every reader of this treats an empty value as "unknown".+func BinaryHash() string {+ binaryHashOnce.Do(func() {+ path, err := os.Executable()+ if err != nil {+ return+ }+ file, err := os.Open(path)+ if err != nil {+ return+ }+ defer file.Close()++ digest := sha256.New()+ if _, err := io.Copy(digest, file); err != nil {+ return+ }+ binaryHash = hex.EncodeToString(digest.Sum(nil))+ })+ return binaryHash+}++var (+ binaryHashOnce sync.Once+ binaryHash string+)diff --git a/backend/pkg/version/version_test.go b/backend/pkg/version/version_test.goindex 41a3799f..986501fc 100644--- a/backend/pkg/version/version_test.go+++ b/backend/pkg/version/version_test.go@@ -1,9 +1,13 @@package versionimport (+ "crypto/sha256"+ "encoding/hex"+ "os""testing""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require")func TestGetBinaryVersion_Default(t *testing.T) {@@ -71,3 +75,29 @@ func TestGetBinaryName_Custom(t *testing.T) {result := GetBinaryName()assert.Equal(t, "myservice", result)}++// TestBinaryHashIdentifiesThisExecutable.+//+// It has to be the digest of the file this process was started from — the test+// binary here — and it has to be the SAME on every call: the value is cached+// precisely because reading the executable again could only produce a different+// answer if somebody replaced a file this process is no longer executing.+func TestBinaryHashIdentifiesThisExecutable(t *testing.T) {+ hash := BinaryHash()+ require.Len(t, hash, 64, "a sha256 in hex, or empty when unreadable — nothing else")+ assert.Regexp(t, "^[0-9a-f]{64}$", hash)++ path, err := os.Executable()+ require.NoError(t, err)+ content, err := os.ReadFile(path)+ require.NoError(t, err)+ assert.Equal(t, hex.EncodeToString(sha256Sum(content)), hash,+ "the hash must be of the running executable, not of anything else on the path")++ assert.Equal(t, hash, BinaryHash(), "the answer must not change under a running process")+}++func sha256Sum(data []byte) []byte {+ sum := sha256.Sum256(data)+ return sum[:]+}diff --git a/backend/sqlc/models/summary.sql b/backend/sqlc/models/summary.sqlnew file mode 100644index 00000000..e86f0f0a--- /dev/null+++ b/backend/sqlc/models/summary.sql@@ -0,0 +1,57 @@+-- name: CountUsers :one+SELECT count(*) FROM users;++-- name: CountFlows :one+SELECT count(*) FROM flows WHERE deleted_at IS NULL;++-- name: CountActiveFlows :one+SELECT count(*) FROM flows WHERE deleted_at IS NULL AND status IN ('created', 'running', 'waiting');++-- name: CountTasks :one+SELECT count(*) FROM tasks;++-- name: CountSubtasks :one+SELECT count(*) FROM subtasks;++-- name: CountContainers :one+SELECT count(*) FROM containers;++-- name: CountAssistants :one+SELECT count(*) FROM assistants WHERE deleted_at IS NULL;++-- name: CountFlowTemplates :one+SELECT count(*) FROM flow_templates;++-- name: CountPrompts :one+SELECT count(*) FROM prompts;++-- name: CountAPITokens :one+SELECT count(*) FROM api_tokens;++-- name: CountToolcalls :one+SELECT count(*) FROM toolcalls;++-- name: GetSummaryProviderCounts :many+-- Number of configured providers per type, for the instance summary.+SELECT type, count(*) AS total+FROM providers+WHERE deleted_at IS NULL+GROUP BY type+ORDER BY type;++-- name: GetSummaryUsageByProvider :many+-- Aggregate LLM usage per provider type, over the whole life of the instance,+-- for the instance summary.+SELECT+ model_provider,+ count(DISTINCT flow_id) AS flows,+ count(*) AS chains,+ COALESCE(SUM(usage_in), 0)::bigint AS tokens_in,+ COALESCE(SUM(usage_out), 0)::bigint AS tokens_out,+ COALESCE(SUM(usage_cache_in), 0)::bigint AS cache_in,+ COALESCE(SUM(usage_cache_out), 0)::bigint AS cache_out,+ COALESCE(SUM(usage_cost_in), 0.0)::double precision AS cost_in,+ COALESCE(SUM(usage_cost_out), 0.0)::double precision AS cost_out+FROM msgchains+GROUP BY model_provider+ORDER BY model_provider;diff --git a/docker-compose.yml b/docker-compose.ymlindex 47f3b03b..992c88e5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -42,6 +42,10 @@ services:- COOKIE_SIGNING_SALT=${COOKIE_SIGNING_SALT:-}- INSTALLATION_ID=${INSTALLATION_ID:-}- LICENSE_KEY=${LICENSE_KEY:-}+ - UPDATE_STRATEGY=${UPDATE_STRATEGY:-}+ - UPDATE_CHECK_INTERVAL=${UPDATE_CHECK_INTERVAL:-}+ - UPDATE_SERVER_HOST=${UPDATE_SERVER_HOST:-}+ - SUPPORT_SERVER_HOST=${SUPPORT_SERVER_HOST:-}- ASK_USER=${ASK_USER:-false}- TENANT_ID=${TENANT_ID:-}- PPROF_ADDR=${PPROF_ADDR:-}diff --git a/examples/guides/worker_node.md b/examples/guides/worker_node.mdindex 1d8b5177..b56fd7f1 100644--- a/examples/guides/worker_node.md+++ b/examples/guides/worker_node.md@@ -620,11 +620,11 @@ sudo tee /usr/local/bin/run-node-exporter > /dev/null << EOFset -e-CONTAINER_NAME=node_exporter+CONTAINER_NAME=node-exporterIMAGE=prom/node-exporter:v1.5.0LISTEN_IP=${METRICS_IP}LISTEN_PORT=9100-TEXTFILE_DIR=/var/lib/node_exporter/textfile_collector+TEXTFILE_DIR=/var/lib/node-exporter/textfile_collectorRESTART_POLICY=unless-stoppedLOG_MAX_SIZE=50mLOG_MAX_FILE=7diff --git a/frontend/graphql-schema.graphql b/frontend/graphql-schema.graphqlindex 0547b3d0..00a1dc54 100644--- a/frontend/graphql-schema.graphql+++ b/frontend/graphql-schema.graphql@@ -9,6 +9,15 @@ fragment settingsFragment on Settings {assistantUseAgents}+fragment versionInfoFragment on VersionInfo {+ current+ state+ latest+ strategy+ checkedAt+ failedAt+}+fragment flowFragment on Flow {idtitle@@ -555,6 +564,12 @@ query settings {}}+query versionInfo {+ versionInfo {+ ...versionInfoFragment+ }+}+query settingsProviders {settingsProviders {enabled {diff --git a/frontend/src/app.tsx b/frontend/src/app.tsxindex 1f078b94..4b543f87 100644--- a/frontend/src/app.tsx+++ b/frontend/src/app.tsx@@ -31,6 +31,7 @@ import { SidebarFlowsProvider } from '@/providers/sidebar-flows-provider';import { TemplatesProvider } from '@/providers/templates-provider';import { ThemeProvider } from '@/providers/theme-provider';import { UserProvider } from '@/providers/user-provider';+import { VersionInfoProvider } from '@/providers/version-info-provider';import { SystemSettingsProvider } from './providers/system-settings-provider';@@ -73,11 +74,13 @@ function ProtectedAppLayout() {return (<ProtectedRoute><SystemSettingsProvider>- <ProvidersProvider>- <SidebarFlowsProvider>- <AppLayout />- </SidebarFlowsProvider>- </ProvidersProvider>+ <VersionInfoProvider>+ <ProvidersProvider>+ <SidebarFlowsProvider>+ <AppLayout />+ </SidebarFlowsProvider>+ </ProvidersProvider>+ </VersionInfoProvider></SystemSettingsProvider></ProtectedRoute>);diff --git a/frontend/src/components/layouts/main/main-sidebar.test.tsx b/frontend/src/components/layouts/main/main-sidebar.test.tsxindex 6cab7bee..347fb90c 100644--- a/frontend/src/components/layouts/main/main-sidebar.test.tsx+++ b/frontend/src/components/layouts/main/main-sidebar.test.tsx@@ -17,6 +17,19 @@ vi.mock('@/providers/sidebar-flows-provider', () => ({ useSidebarFlows: () => ({vi.mock('@/features/resources/use-resources-upload', () => ({useResourcesUpload: () => ({ fileInputKey: 'k', fileInputProps: {}, openFilePicker: vi.fn() }),}));+vi.mock('@/providers/version-info-provider', () => ({+ useVersionInfo: () => ({+ isLoading: false,+ versionInfo: {+ checkedAt: null,+ current: '2.1.0-93e99748',+ failedAt: null,+ latest: '2.4.0',+ state: 'update_available',+ strategy: 'preview',+ },+ }),+}));import { SidebarProvider } from '@/components/ui/sidebar';@@ -52,6 +65,16 @@ function renderSidebar() {);}+describe('MainSidebar version badge', () => {+ it('shows the running version under the product name, with the update indicator', () => {+ renderSidebar();++ expect(screen.getByRole('button', { name: /PentAGI v2\.1\.0/ })).toHaveTextContent('v2.1.0');+ expect(screen.getByTestId('version-indicator-update')).toBeInTheDocument();+ expect(screen.getByTestId('version-attention-dot')).toBeInTheDocument();+ });+});+describe('MainSidebar settings entry points', () => {it('the Settings link carries the current path as the return origin', async () => {const user = userEvent.setup();diff --git a/frontend/src/components/layouts/main/main-sidebar.tsx b/frontend/src/components/layouts/main/main-sidebar.tsxindex d917965b..7ef5eec9 100644--- a/frontend/src/components/layouts/main/main-sidebar.tsx+++ b/frontend/src/components/layouts/main/main-sidebar.tsx@@ -48,6 +48,7 @@ import {} from '@/components/ui/sidebar';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { useResourcesUpload } from '@/features/resources/use-resources-upload';+import { VersionAttentionDot, VersionBadge } from '@/features/version/version-badge';import { useTheme } from '@/hooks/use-theme';import { routes } from '@/lib/routes';import { useFavorites } from '@/providers/favorites-provider';@@ -103,11 +104,13 @@ export function MainSidebar() {<SidebarHeader><SidebarMenu><SidebarMenuItem className="flex items-center gap-2">- <div className="flex aspect-square size-8 items-center justify-center">+ <div className="relative flex aspect-square size-8 items-center justify-center"><Logo className="hover:animate-logo-spin size-6" />+ <VersionAttentionDot className="absolute top-0 right-0 hidden group-data-[collapsible=icon]:block" /></div><div className="grid flex-1 text-left leading-tight"><span className="truncate font-semibold">PentAGI</span>+ <VersionBadge className="-ml-1 justify-self-start group-data-[collapsible=icon]:hidden" /></div></SidebarMenuItem></SidebarMenu>diff --git a/frontend/src/components/layouts/settings/settings-sidebar.test.tsx b/frontend/src/components/layouts/settings/settings-sidebar.test.tsxindex 3a443218..a84ba7c2 100644--- a/frontend/src/components/layouts/settings/settings-sidebar.test.tsx+++ b/frontend/src/components/layouts/settings/settings-sidebar.test.tsx@@ -1,7 +1,21 @@import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, Route, Routes } from 'react-router-dom';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/providers/version-info-provider', () => ({+ useVersionInfo: () => ({+ isLoading: false,+ versionInfo: {+ checkedAt: null,+ current: '2.1.0-93e99748',+ failedAt: null,+ latest: null,+ state: 'up_to_date',+ strategy: 'preview',+ },+ }),+}));import { SidebarProvider } from '@/components/ui/sidebar';@@ -29,6 +43,14 @@ function renderSidebar(entry: { pathname: string; state?: unknown }) {const backToApp = () => screen.getByRole('link', { name: /Back to App/ });+describe('SettingsSidebar version', () => {+ it('names the product and the running version at the bottom of the menu', () => {+ renderSidebar({ pathname: '/settings/account' });++ expect(screen.getByRole('button', { name: /PentAGI v2\.1\.0/ })).toHaveTextContent('PentAGI v2.1.0');+ });+});+describe('SettingsSidebar "Back to App"', () => {it('returns to the page the user came from', () => {renderSidebar({ pathname: '/settings/account', state: { from: '/dashboard' } });diff --git a/frontend/src/components/layouts/settings/settings-sidebar.tsx b/frontend/src/components/layouts/settings/settings-sidebar.tsxindex 1ea570f2..233a8f89 100644--- a/frontend/src/components/layouts/settings/settings-sidebar.tsx+++ b/frontend/src/components/layouts/settings/settings-sidebar.tsx@@ -15,6 +15,7 @@ import {SidebarMenuButton,SidebarMenuItem,} from '@/components/ui/sidebar';+import { VersionBadge } from '@/features/version/version-badge';import { routes } from '@/lib/routes';import { getSafeReturnUrl } from '@/lib/utils/auth';@@ -91,6 +92,9 @@ export function SettingsSidebar() {</SidebarGroup></SidebarContent><SidebarFooter>+ <div className="flex items-center px-1 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0">+ <VersionBadge showProductName />+ </div><SidebarMenuButton asChild><NavLink to={returnUrl}><ArrowLeft />diff --git a/frontend/src/features/version/version-badge.test.tsx b/frontend/src/features/version/version-badge.test.tsxnew file mode 100644index 00000000..6053be42--- /dev/null+++ b/frontend/src/features/version/version-badge.test.tsx@@ -0,0 +1,158 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { VersionInfoFragmentFragment } from '@/graphql/types';++import { UpdateState } from '@/graphql/types';++const provider = vi.hoisted(() => ({+ value: { isLoading: false, versionInfo: null as null | VersionInfoFragmentFragment },+}));++vi.mock('@/providers/version-info-provider', () => ({ useVersionInfo: () => provider.value }));++import { VersionAttentionDot, VersionBadge } from './version-badge';++function info(overrides: Partial<VersionInfoFragmentFragment> = {}): VersionInfoFragmentFragment {+ return {+ checkedAt: null,+ current: '2.1.0-93e99748',+ failedAt: null,+ latest: null,+ state: UpdateState.UpToDate,+ strategy: 'preview',+ ...overrides,+ };+}++const badge = () => screen.getByRole('button', { name: /PentAGI v2\.1\.0/ });++describe('VersionBadge', () => {+ beforeEach(() => {+ provider.value = { isLoading: false, versionInfo: null };+ });++ it('renders nothing until the server has said which version it runs', () => {+ const { container } = render(<VersionBadge />);++ expect(container).toBeEmptyDOMElement();+ });++ it('shows the version without an indicator when the build is current', () => {+ provider.value = { isLoading: false, versionInfo: info() };+ render(<VersionBadge />);++ expect(badge()).toHaveTextContent('v2.1.0');+ expect(screen.queryByTestId('version-indicator-update')).not.toBeInTheDocument();+ expect(screen.queryByTestId('version-indicator-question')).not.toBeInTheDocument();+ });++ it('can carry the product name where there is no logo beside it', () => {+ provider.value = { isLoading: false, versionInfo: info() };+ render(<VersionBadge showProductName />);++ expect(badge()).toHaveTextContent('PentAGI v2.1.0');+ });++ it('shows the yellow arrow and the installer hint when an update is offered', async () => {+ const user = userEvent.setup();+ provider.value = {+ isLoading: false,+ versionInfo: info({ latest: '2.4.0', state: UpdateState.UpdateAvailable }),+ };+ render(<VersionBadge />);++ expect(screen.getByTestId('version-indicator-update')).toHaveClass('text-yellow-500');++ await user.hover(badge());++ expect(await screen.findByRole('tooltip')).toHaveTextContent(+ 'New version v2.4.0 is available. Run the installer tool to update.',+ );+ });++ it.each([+ [UpdateState.Unreachable, 'the update service could not be reached'],+ [UpdateState.Unknown, 'could not tell whether a newer version exists'],+ [UpdateState.Pending, 'Checking for updates'],+ [UpdateState.Disabled, 'Update checks are disabled'],+ ])('shows the yellow question mark when the verdict is %s', async (state, tooltip) => {+ const user = userEvent.setup();+ provider.value = { isLoading: false, versionInfo: info({ state }) };+ render(<VersionBadge />);++ expect(screen.getByTestId('version-indicator-question')).toHaveClass('text-yellow-500');++ await user.hover(badge());++ expect(await screen.findByRole('tooltip')).toHaveTextContent(tooltip);+ });++ it('opens the details with the build, the channel, the instruction and the release links', async () => {+ const user = userEvent.setup();+ provider.value = {+ isLoading: false,+ versionInfo: info({+ checkedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),+ latest: '2.4.0',+ state: UpdateState.UpdateAvailable,+ strategy: 'stable',+ }),+ };+ render(<VersionBadge />);++ await user.click(badge());++ const dialog = await screen.findByRole('dialog');++ expect(dialog).toHaveTextContent('PentAGI v2.1.0');+ expect(dialog).toHaveTextContent('build 93e99748');+ expect(dialog).toHaveTextContent('stable');+ expect(dialog).toHaveTextContent('New version v2.4.0 is available');+ expect(dialog).toHaveTextContent('Run the installer tool on the host where PentAGI is deployed');+ expect(dialog).toHaveTextContent('Checked 10 minutes ago');+ expect(screen.getByRole('link', { name: /Release notes for v2\.4\.0/ })).toHaveAttribute(+ 'href',+ 'https://github.com/vxcontrol/pentagi/releases/tag/v2.4.0',+ );+ expect(screen.getByRole('link', { name: /All releases/ })).toHaveAttribute(+ 'href',+ 'https://github.com/vxcontrol/pentagi/releases',+ );+ });++ it('offers no release notes link when there is no release to point at', async () => {+ const user = userEvent.setup();+ provider.value = { isLoading: false, versionInfo: info({ state: UpdateState.Unreachable }) };+ render(<VersionBadge />);++ await user.click(badge());++ expect(await screen.findByRole('dialog')).toHaveTextContent('Update status unknown');+ expect(screen.queryByRole('link', { name: /Release notes/ })).not.toBeInTheDocument();+ expect(screen.getByRole('link', { name: /All releases/ })).toBeInTheDocument();+ });+});++describe('VersionAttentionDot', () => {+ it('appears only when the badge would carry an indicator', () => {+ provider.value = { isLoading: false, versionInfo: info() };+ const { rerender } = render(<VersionAttentionDot />);++ expect(screen.queryByTestId('version-attention-dot')).not.toBeInTheDocument();++ provider.value = {+ isLoading: false,+ versionInfo: info({ latest: '2.4.0', state: UpdateState.UpdateAvailable }),+ };+ rerender(<VersionAttentionDot />);++ expect(screen.getByTestId('version-attention-dot')).toBeInTheDocument();++ provider.value = { isLoading: false, versionInfo: info({ state: UpdateState.Unreachable }) };+ rerender(<VersionAttentionDot />);++ expect(screen.getByTestId('version-attention-dot')).toBeInTheDocument();+ });+});diff --git a/frontend/src/features/version/version-badge.tsx b/frontend/src/features/version/version-badge.tsxnew file mode 100644index 00000000..ce4d49ed--- /dev/null+++ b/frontend/src/features/version/version-badge.tsx@@ -0,0 +1,206 @@+import { CircleArrowDown, CircleCheck, CircleQuestionMark, ExternalLink, Info } from 'lucide-react';+import { useState } from 'react';++import type { VersionInfoFragmentFragment } from '@/graphql/types';++import { Badge } from '@/components/ui/badge';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { Separator } from '@/components/ui/separator';+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';+import { useVersionInfo } from '@/providers/version-info-provider';++import {+ describeTiming,+ describeVersion,+ PENTAGI_RELEASES_URL,+ releaseNotesUrl,+ type VersionIndicator,+ type VersionPresentation,+} from './version-status';++interface VersionBadgeProps {+ className?: string;+ /** Prefix the version with the product name, for places without the logo beside it. */+ showProductName?: boolean;+}++const INDICATOR_ICON: Record<Exclude<VersionIndicator, 'none'>, typeof CircleArrowDown> = {+ question: CircleQuestionMark,+ update: CircleArrowDown,+};++const INDICATOR_CLASS = 'text-yellow-500 dark:text-yellow-400';++/**+ * A dot for the places where the badge itself cannot fit — the logo of a sidebar+ * collapsed to icons. Rendered only when the badge would carry an indicator.+ */+export function VersionAttentionDot({ className }: { className?: string }) {+ const { versionInfo } = useVersionInfo();++ if (!versionInfo || describeVersion(versionInfo).indicator === 'none') {+ return null;+ }++ return (+ <span+ aria-hidden+ className={cn('size-2 rounded-full bg-yellow-500 dark:bg-yellow-400', className)}+ data-testid="version-attention-dot"+ />+ );+}++/**+ * The running version, with a yellow "?" when nothing is known about updates and a+ * yellow "↓" when a newer version is offered. Hover explains in a line; click opens+ * the details with links to the release notes.+ *+ * Inside a collapsible sidebar the version text hides in the icon state and only+ * the indicator stays, which is the part that matters when space is short.+ */+export function VersionBadge({ className, showProductName = false }: VersionBadgeProps) {+ const { versionInfo } = useVersionInfo();+ const [popoverOpen, setPopoverOpen] = useState(false);+ const [tooltipOpen, setTooltipOpen] = useState(false);++ if (!versionInfo) {+ return null;+ }++ const presentation = describeVersion(versionInfo);+ const Indicator = presentation.indicator === 'none' ? null : INDICATOR_ICON[presentation.indicator];+ const label = showProductName ? `PentAGI ${presentation.label}` : presentation.label;++ return (+ <Popover+ onOpenChange={setPopoverOpen}+ open={popoverOpen}+ >+ <TooltipProvider delayDuration={300}>+ <Tooltip+ onOpenChange={setTooltipOpen}+ open={tooltipOpen && !popoverOpen}+ >+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <button+ aria-label={`PentAGI ${presentation.label}. ${presentation.tooltip}`}+ className={cn(+ 'text-sidebar-foreground/70 hover:text-sidebar-foreground focus-visible:ring-sidebar-ring data-[state=open]:text-sidebar-foreground inline-flex h-6 max-w-full min-w-0 items-center gap-1 overflow-hidden rounded-md px-1 text-xs outline-hidden transition-colors focus-visible:ring-2',+ className,+ )}+ type="button"+ >+ <span className="truncate group-data-[collapsible=icon]:hidden">{label}</span>+ {Indicator ? (+ <Indicator+ aria-hidden+ className={cn('size-3.5 shrink-0', INDICATOR_CLASS)}+ data-testid={`version-indicator-${presentation.indicator}`}+ />+ ) : (+ <Info+ aria-hidden+ className="hidden size-3.5 shrink-0 group-data-[collapsible=icon]:block"+ />+ )}+ </button>+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent+ className="max-w-64"+ side="right"+ >+ {presentation.tooltip}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <PopoverContent+ align="start"+ className="w-80 p-0"+ side="right"+ >+ <VersionDetails+ presentation={presentation}+ versionInfo={versionInfo}+ />+ </PopoverContent>+ </Popover>+ );+}++function ExternalLinkRow({ children, href }: { children: React.ReactNode; href: string }) {+ return (+ <a+ className="text-foreground hover:bg-accent hover:text-accent-foreground -mx-2 flex items-center justify-between gap-2 rounded-md px-2 py-1"+ href={href}+ rel="noreferrer"+ target="_blank"+ >+ <span className="truncate">{children}</span>+ <ExternalLink+ aria-hidden+ className="text-muted-foreground size-3.5 shrink-0"+ />+ </a>+ );+}++function VersionDetails({+ presentation,+ versionInfo,+}: {+ presentation: VersionPresentation;+ versionInfo: VersionInfoFragmentFragment;+}) {+ const timing = describeTiming(versionInfo);+ const StatusIcon = presentation.indicator === 'none' ? CircleCheck : INDICATOR_ICON[presentation.indicator];+ const statusClass = presentation.indicator === 'none' ? 'text-green-600 dark:text-green-400' : INDICATOR_CLASS;+ const releaseNotes =+ presentation.indicator === 'update' && versionInfo.latest ? releaseNotesUrl(versionInfo.latest) : null;++ return (+ <div className="flex flex-col gap-3 p-4 text-sm">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="truncate font-semibold">PentAGI {presentation.label}</div>+ {presentation.revision && (+ <div className="text-muted-foreground truncate text-xs">build {presentation.revision}</div>+ )}+ </div>+ <Badge+ className="shrink-0 capitalize"+ variant="secondary"+ >+ {versionInfo.strategy}+ </Badge>+ </div>++ <Separator />++ <div className="flex gap-2">+ <StatusIcon+ aria-hidden+ className={cn('mt-0.5 size-4 shrink-0', statusClass)}+ />+ <div className="flex min-w-0 flex-col gap-1">+ <div className="font-medium">{presentation.headline}</div>+ <p className="text-muted-foreground">{presentation.detail}</p>+ {presentation.action && <p className="text-muted-foreground">{presentation.action}</p>}+ {timing.length > 0 && <p className="text-muted-foreground text-xs">{timing.join(' · ')}</p>}+ </div>+ </div>++ <Separator />++ <div className="flex flex-col gap-1">+ {releaseNotes && (+ <ExternalLinkRow href={releaseNotes}>Release notes for {presentation.latest}</ExternalLinkRow>+ )}+ <ExternalLinkRow href={PENTAGI_RELEASES_URL}>All releases</ExternalLinkRow>+ </div>+ </div>+ );+}diff --git a/frontend/src/features/version/version-status.test.ts b/frontend/src/features/version/version-status.test.tsnew file mode 100644index 00000000..4ec197aa--- /dev/null+++ b/frontend/src/features/version/version-status.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from 'vitest';++import type { VersionInfoFragmentFragment } from '@/graphql/types';++import { UpdateState } from '@/graphql/types';++import {+ describeTiming,+ describeVersion,+ formatVersionLabel,+ PENTAGI_RELEASES_URL,+ releaseNotesUrl,+ splitVersion,+ UPDATE_INSTRUCTION,+} from './version-status';++function info(overrides: Partial<VersionInfoFragmentFragment> = {}): VersionInfoFragmentFragment {+ return {+ checkedAt: null,+ current: '2.1.0-93e99748',+ failedAt: null,+ latest: null,+ state: UpdateState.UpToDate,+ strategy: 'preview',+ ...overrides,+ };+}++describe('splitVersion', () => {+ it('separates the git revision the release pipeline stamps onto a build', () => {+ expect(splitVersion('2.1.0-93e99748')).toEqual({ revision: '93e99748', version: '2.1.0' });+ });++ it('leaves a prerelease suffix in the version, since it is not a revision', () => {+ expect(splitVersion('2.2.0-rc1')).toEqual({ revision: null, version: '2.2.0-rc1' });+ });++ it('leaves a bare version and a branch name alone', () => {+ expect(splitVersion('2.1.0')).toEqual({ revision: null, version: '2.1.0' });+ expect(splitVersion('develop')).toEqual({ revision: null, version: 'develop' });+ });+});++describe('formatVersionLabel', () => {+ it('prefixes a numeric version with v and leaves a branch name alone', () => {+ expect(formatVersionLabel('2.1.0')).toBe('v2.1.0');+ expect(formatVersionLabel('develop')).toBe('develop');+ });+});++describe('releaseNotesUrl', () => {+ it('points at the tagged release, whether or not the version already carries the v', () => {+ expect(releaseNotesUrl('2.4.0')).toBe(`${PENTAGI_RELEASES_URL}/tag/v2.4.0`);+ expect(releaseNotesUrl('v2.4.0')).toBe(`${PENTAGI_RELEASES_URL}/tag/v2.4.0`);+ });+});++describe('describeVersion', () => {+ it('shows the yellow arrow and tells the operator to run the installer when an update is offered', () => {+ const presentation = describeVersion(info({ latest: '2.4.0', state: UpdateState.UpdateAvailable }));++ expect(presentation.indicator).toBe('update');+ expect(presentation.label).toBe('v2.1.0');+ expect(presentation.revision).toBe('93e99748');+ expect(presentation.latest).toBe('v2.4.0');+ expect(presentation.headline).toBe('New version v2.4.0 is available');+ expect(presentation.tooltip).toBe('New version v2.4.0 is available. Run the installer tool to update.');+ expect(presentation.action).toBe(UPDATE_INSTRUCTION);+ });++ it('shows no indicator when the build is current', () => {+ const presentation = describeVersion(info());++ expect(presentation.indicator).toBe('none');+ expect(presentation.tooltip).toBe('PentAGI v2.1.0 is up to date.');+ expect(presentation.detail).toContain('preview channel');+ expect(presentation.action).toBeNull();+ });++ it.each([+ [UpdateState.Pending, 'Checking for updates…'],+ [UpdateState.Unreachable, 'Update status unknown: the update service could not be reached.'],+ [+ UpdateState.Unknown,+ 'Update status unknown: the update service could not tell whether a newer version exists.',+ ],+ [UpdateState.Disabled, 'Update checks are disabled in the server configuration.'],+ ])('shows the yellow question mark for %s', (state, tooltip) => {+ const presentation = describeVersion(info({ state }));++ expect(presentation.indicator).toBe('question');+ expect(presentation.tooltip).toBe(tooltip);+ });++ it('mentions the newest published version when the build could not be matched to one', () => {+ const presentation = describeVersion(info({ latest: '2.4.0', state: UpdateState.Unknown }));++ expect(presentation.indicator).toBe('question');+ expect(presentation.detail).toContain('The newest published version is v2.4.0.');+ });++ it('treats an update that names no version as unknown rather than pointing an arrow at nothing', () => {+ const presentation = describeVersion(info({ latest: null, state: UpdateState.UpdateAvailable }));++ expect(presentation.indicator).toBe('question');+ expect(presentation.action).toBeNull();+ });++ it('treats a state it has never heard of as unknown', () => {+ const presentation = describeVersion(info({ state: 'surprise' as UpdateState }));++ expect(presentation.indicator).toBe('question');+ });+});++describe('describeTiming', () => {+ const now = new Date('2026-09-02T12:00:00Z');++ it('says nothing when nothing has happened yet', () => {+ expect(describeTiming(info(), now)).toEqual([]);+ });++ it('dates the answer and the failure separately', () => {+ expect(+ describeTiming(info({ checkedAt: '2026-09-02T09:00:00Z', failedAt: '2026-09-02T11:55:00Z' }), now),+ ).toEqual(['Checked about 3 hours ago', 'Last check failed 5 minutes ago']);+ });+});diff --git a/frontend/src/features/version/version-status.ts b/frontend/src/features/version/version-status.tsnew file mode 100644index 00000000..a63409a5--- /dev/null+++ b/frontend/src/features/version/version-status.ts@@ -0,0 +1,149 @@+import { formatDistance } from 'date-fns';++import type { VersionInfoFragmentFragment } from '@/graphql/types';++import { UpdateState } from '@/graphql/types';++export const PENTAGI_RELEASES_URL = 'https://github.com/vxcontrol/pentagi/releases';++// What the badge tells the operator to do. Nothing is applied from the UI: the+// installer is the tool that pulls images and restarts the stack, and it lives on+// the host, not behind a button here.+export const UPDATE_INSTRUCTION =+ 'Run the installer tool on the host where PentAGI is deployed and choose Maintenance → Update PentAGI.';++export type VersionIndicator = 'none' | 'question' | 'update';++export interface VersionPresentation {+ /** What the operator should do, when there is something to do. */+ action: null | string;+ /** A sentence or two for the popover, under the headline. */+ detail: string;+ /** One line that names the situation. */+ headline: string;+ indicator: VersionIndicator;+ /** The running version as the badge shows it: "v2.1.0", or "develop". */+ label: string;+ /** The newest version the server offers, as the badge shows it. */+ latest: null | string;+ /** Git revision baked into the build, when the version carries one. */+ revision: null | string;+ /** The hover text. Short, and complete on its own. */+ tooltip: string;+}++// A build is "<version>-<git revision>" when the release pipeline stamps one. The+// revision is worth showing, but not inside a badge that should read as a version.+const REVISION_SUFFIX = /^(.+)-([0-9a-f]{7,40})$/i;++/** When the verdict was reached, and when the last attempt failed, as relative times. */+export function describeTiming(info: VersionInfoFragmentFragment, now: Date = new Date()): string[] {+ const lines: string[] = [];++ if (info.checkedAt) {+ lines.push(`Checked ${formatDistance(new Date(info.checkedAt), now, { addSuffix: true })}`);+ }++ if (info.failedAt) {+ lines.push(`Last check failed ${formatDistance(new Date(info.failedAt), now, { addSuffix: true })}`);+ }++ return lines;+}++export function describeVersion(info: VersionInfoFragmentFragment): VersionPresentation {+ const { revision, version } = splitVersion(info.current);+ const label = formatVersionLabel(version);+ const latest = info.latest ? formatVersionLabel(info.latest) : null;+ const base = { action: null, label, latest, revision };++ switch (info.state) {+ case UpdateState.Disabled:+ return {+ ...base,+ detail: 'Automatic update checks are switched off in the server configuration.',+ headline: 'Update checks are disabled',+ indicator: 'question',+ tooltip: 'Update checks are disabled in the server configuration.',+ };+ case UpdateState.Pending:+ return {+ ...base,+ detail: 'The first update check has not completed yet. It runs shortly after the server starts.',+ headline: 'Checking for updates',+ indicator: 'question',+ tooltip: 'Checking for updates…',+ };+ case UpdateState.Unreachable:+ return {+ ...base,+ detail: 'The update service could not be reached, so it is unknown whether a newer version exists.',+ headline: 'Update status unknown',+ indicator: 'question',+ tooltip: 'Update status unknown: the update service could not be reached.',+ };+ case UpdateState.UpdateAvailable:+ if (latest) {+ return {+ ...base,+ action: UPDATE_INSTRUCTION,+ detail: `You are running ${label}. Update to ${latest} to get the latest fixes and features.`,+ headline: `New version ${latest} is available`,+ indicator: 'update',+ tooltip: `New version ${latest} is available. Run the installer tool to update.`,+ };+ }++ // The server never reports an update without naming it, but a schema is+ // a promise about shape, not about content — and an arrow pointing at+ // nothing is not something the operator can act on.+ return describeUnknown(base);+ case UpdateState.UpToDate:+ return {+ ...base,+ detail: `${label} is the newest version on the ${info.strategy} channel.`,+ headline: 'PentAGI is up to date',+ indicator: 'none',+ tooltip: `PentAGI ${label} is up to date.`,+ };+ case UpdateState.Unknown:+ default:+ return describeUnknown(base);+ }+}++/** "2.1.0" reads as "v2.1.0"; a branch name such as "develop" is left alone. */+export function formatVersionLabel(version: string): string {+ return /^\d/.test(version) ? `v${version}` : version;+}++/** Where to read what changed in a release. Tags on GitHub carry a `v` prefix. */+export function releaseNotesUrl(version: string): string {+ const tag = version.startsWith('v') ? version : `v${version}`;++ return `${PENTAGI_RELEASES_URL}/tag/${encodeURIComponent(tag)}`;+}++export function splitVersion(current: string): { revision: null | string; version: string } {+ const match = REVISION_SUFFIX.exec(current);+ const version = match?.[1];+ const revision = match?.[2];++ if (version && revision) {+ return { revision, version };+ }++ return { revision: null, version: current };+}++function describeUnknown(base: Pick<VersionPresentation, 'action' | 'label' | 'latest' | 'revision'>) {+ const newest = base.latest ? ` The newest published version is ${base.latest}.` : '';++ return {+ ...base,+ detail: `The update service could not tell whether a newer version exists for this build.${newest}`,+ headline: 'Update status unknown',+ indicator: 'question' as const,+ tooltip: 'Update status unknown: the update service could not tell whether a newer version exists.',+ };+}diff --git a/frontend/src/graphql/types.ts b/frontend/src/graphql/types.tsindex a1a2533e..bf2fa0c1 100644--- a/frontend/src/graphql/types.ts+++ b/frontend/src/graphql/types.ts@@ -293,6 +293,15 @@ export type UpdateKnowledgeDocumentInput = {question?: string | null | undefined;};+export enum UpdateState {+ Disabled = 'disabled',+ Pending = 'pending',+ Unknown = 'unknown',+ Unreachable = 'unreachable',+ UpToDate = 'up_to_date',+ UpdateAvailable = 'update_available',+}+export enum UsageStatsPeriod {Month = 'month',Quarter = 'quarter',@@ -313,6 +322,15 @@ export type SettingsFragmentFragment = {assistantUseAgents: boolean;};+export type VersionInfoFragmentFragment = {+ current: string;+ state: UpdateState;+ latest: string | null;+ strategy: string;+ checkedAt: string | null;+ failedAt: string | null;+};+export type FlowFragmentFragment = {id: string;title: string;@@ -719,6 +737,10 @@ export type SettingsQueryVariables = Exact<{ [key: string]: never }>;export type SettingsQuery = { settings: SettingsFragmentFragment };+export type VersionInfoQueryVariables = Exact<{ [key: string]: never }>;++export type VersionInfoQuery = { versionInfo: VersionInfoFragmentFragment };+export type SettingsProvidersQueryVariables = Exact<{ [key: string]: never }>;export type SettingsProvidersQuery = {@@ -1434,6 +1456,27 @@ export const SettingsFragmentFragmentDoc = {},],} as unknown as DocumentNode<SettingsFragmentFragment, unknown>;+export const VersionInfoFragmentFragmentDoc = {+ kind: 'Document',+ definitions: [+ {+ kind: 'FragmentDefinition',+ name: { kind: 'Name', value: 'versionInfoFragment' },+ typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'VersionInfo' } },+ selectionSet: {+ kind: 'SelectionSet',+ selections: [+ { kind: 'Field', name: { kind: 'Name', value: 'current' } },+ { kind: 'Field', name: { kind: 'Name', value: 'state' } },+ { kind: 'Field', name: { kind: 'Name', value: 'latest' } },+ { kind: 'Field', name: { kind: 'Name', value: 'strategy' } },+ { kind: 'Field', name: { kind: 'Name', value: 'checkedAt' } },+ { kind: 'Field', name: { kind: 'Name', value: 'failedAt' } },+ ],+ },+ },+ ],+} as unknown as DocumentNode<VersionInfoFragmentFragment, unknown>;export const TerminalFragmentFragmentDoc = {kind: 'Document',definitions: [@@ -3528,6 +3571,47 @@ export const SettingsDocument = {},],} as unknown as DocumentNode<SettingsQuery, SettingsQueryVariables>;+export const VersionInfoDocument = {+ kind: 'Document',+ definitions: [+ {+ kind: 'OperationDefinition',+ operation: 'query',+ name: { kind: 'Name', value: 'versionInfo' },+ selectionSet: {+ kind: 'SelectionSet',+ selections: [+ {+ kind: 'Field',+ name: { kind: 'Name', value: 'versionInfo' },+ selectionSet: {+ kind: 'SelectionSet',+ selections: [+ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'versionInfoFragment' } },+ ],+ },+ },+ ],+ },+ },+ {+ kind: 'FragmentDefinition',+ name: { kind: 'Name', value: 'versionInfoFragment' },+ typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'VersionInfo' } },+ selectionSet: {+ kind: 'SelectionSet',+ selections: [+ { kind: 'Field', name: { kind: 'Name', value: 'current' } },+ { kind: 'Field', name: { kind: 'Name', value: 'state' } },+ { kind: 'Field', name: { kind: 'Name', value: 'latest' } },+ { kind: 'Field', name: { kind: 'Name', value: 'strategy' } },+ { kind: 'Field', name: { kind: 'Name', value: 'checkedAt' } },+ { kind: 'Field', name: { kind: 'Name', value: 'failedAt' } },+ ],+ },+ },+ ],+} as unknown as DocumentNode<VersionInfoQuery, VersionInfoQueryVariables>;export const SettingsProvidersDocument = {kind: 'Document',definitions: [diff --git a/frontend/src/providers/version-info-provider.test.tsx b/frontend/src/providers/version-info-provider.test.tsxnew file mode 100644index 00000000..6838b733--- /dev/null+++ b/frontend/src/providers/version-info-provider.test.tsx@@ -0,0 +1,97 @@+import { render, renderHook, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { UpdateState } from '@/graphql/types';++const apollo = vi.hoisted(() => ({+ data: undefined as undefined | { versionInfo: { state: UpdateState } },+ startPolling: vi.fn(),+ stopPolling: vi.fn(),+}));+const user = vi.hoisted(() => ({ authenticated: true }));++vi.mock('@apollo/client/react', () => ({+ useQuery: () => ({+ data: apollo.data,+ loading: false,+ startPolling: apollo.startPolling,+ stopPolling: apollo.stopPolling,+ }),+}));+vi.mock('@/providers/user-provider', () => ({ useUser: () => ({ isAuthenticated: () => user.authenticated }) }));++import {+ useVersionInfo,+ VERSION_PENDING_POLL_INTERVAL_MS,+ VERSION_POLL_INTERVAL_MS,+ VersionInfoProvider,+} from './version-info-provider';++function Probe() {+ const { versionInfo } = useVersionInfo();++ return <span data-testid="state">{versionInfo?.state ?? 'none'}</span>;+}++describe('VersionInfoProvider', () => {+ beforeEach(() => {+ apollo.data = undefined;+ apollo.startPolling.mockClear();+ apollo.stopPolling.mockClear();+ user.authenticated = true;+ });++ it('polls quickly while the first verdict is pending, since it lands within minutes of a restart', () => {+ apollo.data = { versionInfo: { state: UpdateState.Pending } };+ render(+ <VersionInfoProvider>+ <Probe />+ </VersionInfoProvider>,+ );++ expect(screen.getByTestId('state')).toHaveTextContent('pending');+ expect(apollo.startPolling).toHaveBeenLastCalledWith(VERSION_PENDING_POLL_INTERVAL_MS);+ });++ it('slows down once there is a verdict, which changes at most every few hours', () => {+ apollo.data = { versionInfo: { state: UpdateState.UpToDate } };+ render(+ <VersionInfoProvider>+ <Probe />+ </VersionInfoProvider>,+ );++ expect(apollo.startPolling).toHaveBeenLastCalledWith(VERSION_POLL_INTERVAL_MS);+ });++ it('does not poll for a visitor who is not signed in', () => {+ user.authenticated = false;+ render(+ <VersionInfoProvider>+ <Probe />+ </VersionInfoProvider>,+ );++ expect(screen.getByTestId('state')).toHaveTextContent('none');+ expect(apollo.startPolling).not.toHaveBeenCalled();+ });++ it('stops polling when it unmounts', () => {+ apollo.data = { versionInfo: { state: UpdateState.UpToDate } };+ const { unmount } = render(+ <VersionInfoProvider>+ <Probe />+ </VersionInfoProvider>,+ );++ unmount();++ expect(apollo.stopPolling).toHaveBeenCalled();+ });++ it('refuses to be read outside the provider', () => {+ expect(() => renderHook(() => useVersionInfo())).toThrow(+ 'useVersionInfo must be used within a VersionInfoProvider',+ );+ });+});diff --git a/frontend/src/providers/version-info-provider.tsx b/frontend/src/providers/version-info-provider.tsxnew file mode 100644index 00000000..b1c2bb7e--- /dev/null+++ b/frontend/src/providers/version-info-provider.tsx@@ -0,0 +1,62 @@+import type { ReactNode } from 'react';++import { useQuery } from '@apollo/client/react';+import { createContext, use, useEffect, useMemo } from 'react';++import type { VersionInfoFragmentFragment } from '@/graphql/types';++import { UpdateState, VersionInfoDocument } from '@/graphql/types';+import { useUser } from '@/providers/user-provider';++// The server asks the update service every few hours, so most polls return the+// answer they got last time. Polling exists for two moments: the minutes right+// after a restart, when the verdict is still pending and arrives within two+// minutes, and the once-in-a-while moment a new release lands mid-session.+export const VERSION_POLL_INTERVAL_MS = 15 * 60 * 1000;+export const VERSION_PENDING_POLL_INTERVAL_MS = 30 * 1000;++interface VersionInfoContextType {+ isLoading: boolean;+ versionInfo: null | VersionInfoFragmentFragment;+}++const VersionInfoContext = createContext<undefined | VersionInfoContextType>(undefined);++export function useVersionInfo() {+ const context = use(VersionInfoContext);++ if (context === undefined) {+ throw new Error('useVersionInfo must be used within a VersionInfoProvider');+ }++ return context;+}++export function VersionInfoProvider({ children }: { children: ReactNode }) {+ const { isAuthenticated } = useUser();+ const skip = !isAuthenticated();++ const { data, loading, startPolling, stopPolling } = useQuery(VersionInfoDocument, { skip });+ const versionInfo = data?.versionInfo ?? null;+ const state = versionInfo?.state;++ useEffect(() => {+ if (skip) {+ return undefined;+ }++ startPolling(state === UpdateState.Pending ? VERSION_PENDING_POLL_INTERVAL_MS : VERSION_POLL_INTERVAL_MS);++ return () => stopPolling();+ }, [skip, state, startPolling, stopPolling]);++ const value = useMemo<VersionInfoContextType>(+ () => ({+ isLoading: loading,+ versionInfo,+ }),+ [loading, versionInfo],+ );++ return <VersionInfoContext value={value}>{children}</VersionInfoContext>;+}