feat(webui): keep the Model setup step open until the provider credential resolves (#1045)
Quality / check (push) Successful in 4m40s
deploy / gate (push) Successful in 6m15s
deploy / archied-image (push) Successful in 2m57s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped

This commit is contained in:
sam committed 2026-10-31 20:04:06 +11:00
1 parent ebc6dd67e6
commit 812d9004a7
4 files changed
+481 -91

No files matched your search

+161 -4
View File
@@ -2,8 +2,15 @@ package webui
import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/config"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
@@ -23,6 +30,44 @@ type ModelReader interface {
CallerModels(ctx context.Context) (org string, aliases map[string]string, err error)
}
// The control-plane resources the effective-model read layers: the org's own
// providers and the credential bindings that carry their keys. Spelled here
// rather than imported so the dashboard package stays a leaf, as
// api_harness.go does for "credential-bindings".
const (
providerSettingsKind = "provider-settings"
credentialBindingsKind = "credential-bindings"
)
// providerDoc is the part of one provider-settings entry the read needs: where
// the provider's key comes from.
type providerDoc struct {
Class string `json:"class"`
APIKeyEnv string `json:"api_key_env,omitempty"`
APIKeyRef config.SecretRef `json:"api_key_ref"`
}
// credentialBindingDoc is the part of one credential-bindings entry the read
// needs: the org secret the service's key resolves through.
type credentialBindingDoc struct {
Service string `json:"service"`
Secret config.SecretRef `json:"secret"`
}
// effectiveModel is one model alias the caller's org may use, with the state
// of the provider credential it runs on. An alias whose provider's credential
// is missing or does not resolve cannot run a task, so the Model setup step
// stays open and names it.
type effectiveModel struct {
Alias string
Model string
Provider string
// Credential reports that the provider's credential is present and
// resolves; Detail names what is missing when it does not.
Credential bool
Detail string
}
// handleSetup reports which setup steps are still missing in the caller's
// organisation, from live state. Optional capabilities (a chat channel, a
// repository) are set up where they are used, not listed here.
@@ -43,15 +88,127 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
steps = append(steps, SetupStep{Title: "First task", Done: total > 0, Path: "/tasks"})
}
if s.Models != nil {
// Shown only while the org has no model to run, so a working setup
// carries no extra step.
if _, aliases, err := s.Models.CallerModels(r.Context()); err == nil && len(aliases) == 0 {
steps = append(steps, SetupStep{Title: "Model", Path: "/org/models"})
// Shown only while the org has no runnable model, so a working setup
// carries no extra step: an alias whose provider credential does not
// resolve is no more runnable than no alias at all.
if models, err := s.callerEffectiveModels(r.Context()); err == nil {
if step, open := modelSetupStep(models); open {
steps = append(steps, step)
}
}
}
writeJSON(w, map[string]any{"steps": steps})
}
// modelSetupStep is the Model checklist step for the caller's effective
// models. The step stays open until every alias's provider credential
// resolves; its detail names the credential that does not.
func modelSetupStep(models []effectiveModel) (SetupStep, bool) {
if len(models) == 0 {
return SetupStep{Title: "Model", Path: "/org/models", Detail: "no model alias configured"}, true
}
for _, model := range models {
if !model.Credential {
return SetupStep{Title: "Model", Path: "/org/models", Detail: model.Detail}, true
}
}
return SetupStep{}, false
}
// callerEffectiveModels reads the caller's effective models: the aliases the
// org may use, each with the validity of the provider credential it runs on.
// The credential surfaces are optional; without them the read reports the
// aliases alone with every credential taken as valid.
func (s *Server) callerEffectiveModels(ctx context.Context) ([]effectiveModel, error) {
_, aliases, err := s.Models.CallerModels(ctx)
if err != nil {
return nil, err
}
models := make([]effectiveModel, 0, len(aliases))
for _, alias := range slices.Sorted(maps.Keys(aliases)) {
provider, _, _ := strings.Cut(aliases[alias], "/")
models = append(models, effectiveModel{Alias: alias, Model: aliases[alias], Provider: provider, Credential: true})
}
if s.ControlPlane == nil || s.CheckSecret == nil || len(models) == 0 {
return models, nil
}
orgID := string(org.OrgFromContext(ctx))
var providers map[string]providerDoc
if err := s.queryResourceValue(ctx, providerSettingsKind, &providers); err != nil {
return nil, err
}
if providers == nil {
providers = map[string]providerDoc{}
}
var bindings []credentialBindingDoc
if err := s.queryResourceValue(ctx, credentialBindingsKind, &bindings); err != nil {
return nil, err
}
for i := range models {
models[i].Credential, models[i].Detail = s.providerCredential(ctx, orgID, models[i].Provider, providers, bindings)
}
return models, nil
}
// queryResourceValue decodes one control-plane resource of the caller's org
// into into; an absent resource leaves into untouched.
func (s *Server) queryResourceValue(ctx context.Context, kind string, into any) error {
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: kind})
if err != nil {
return err
}
if response.Resource == nil || len(response.Resource.ValueJson) == 0 {
return nil
}
return json.Unmarshal(response.Resource.ValueJson, into)
}
// providerCredential reports whether provider's credential is present and
// resolves for orgID, and names what is missing when it does not. The key
// comes from the provider's own api_key_ref, or from the org's credential
// binding named after the provider, or from its api_key_env; a binding with no
// secret is OAuth, whose credential is the captured token set. A provider
// that is not the org's own and has no binding is an instance provider: its
// credential is the instance admin's, not this org's to configure.
func (s *Server) providerCredential(ctx context.Context, orgID, provider string, providers map[string]providerDoc, bindings []credentialBindingDoc) (bool, string) {
doc, own := providers[provider]
if own && doc.APIKeyRef != (config.SecretRef{}) {
return s.secretCredential(ctx, provider, doc.APIKeyRef)
}
for _, binding := range bindings {
if binding.Service != provider {
continue
}
if binding.Secret != (config.SecretRef{}) {
return s.secretCredential(ctx, provider, binding.Secret)
}
if s.HarnessSecrets != nil {
if token, err := s.HarnessSecrets.GetHarnessSecret(ctx, orgID, provider); err == nil && token.Validate() == nil {
return true, ""
}
return false, fmt.Sprintf("provider %q has no captured sign-in for credential binding %q", provider, provider)
}
return false, fmt.Sprintf("credential binding %q names no secret and no sign-in is captured", provider)
}
if own {
if doc.APIKeyEnv != "" {
return s.secretCredential(ctx, provider, config.SecretRef{Engine: "env", Key: doc.APIKeyEnv})
}
return false, fmt.Sprintf("provider %q declares no credential: set its api_key_ref or add a credential binding named %q", provider, provider)
}
return true, ""
}
// secretCredential reports whether ref resolves through the gateway's secret
// engines, naming the reference when it does not.
func (s *Server) secretCredential(ctx context.Context, provider string, ref config.SecretRef) (bool, string) {
resolved, err := s.CheckSecret(ctx, ref)
if err == nil && resolved {
return true, ""
}
return false, fmt.Sprintf("provider %q credential %s:%s does not resolve", provider, ref.Engine, ref.Key)
}
// hasActiveAgent reports whether the caller's org has an active bot or
// service account assigned; ok is false when that cannot be read.
func (s *Server) hasActiveAgent(r *http.Request) (done, ok bool) {
+230
View File
@@ -0,0 +1,230 @@
package webui
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"google.golang.org/grpc"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/secret"
)
type setupStore struct {
storecontract.TaskStore
}
func (setupStore) StatusCounts(context.Context) (map[string]int, error) {
return map[string]int{"done": 1}, nil
}
type setupModels struct {
aliases map[string]string
err error
}
func (m setupModels) CallerModels(context.Context) (string, map[string]string, error) {
return "org", m.aliases, m.err
}
// setupControl answers provider-settings and credential-bindings queries from
// fixed documents, the way the State Store would for one org.
type setupControl struct {
controlpb.ControlPlaneServiceClient
providers string
bindings string
}
func (c setupControl) Query(_ context.Context, r *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) {
var value string
switch r.Kind {
case providerSettingsKind:
value = c.providers
case credentialBindingsKind:
value = c.bindings
default:
value = "null"
}
return &controlpb.QueryResponse{Resource: &controlpb.Resource{Kind: r.Kind, ValueJson: []byte(value)}}, nil
}
type setupHarnessSecrets struct {
storecontract.HarnessSecretStore
tokens map[string]harnesssecret.Secret
}
func (h setupHarnessSecrets) GetHarnessSecret(_ context.Context, _, service string) (harnesssecret.Secret, error) {
if token, ok := h.tokens[service]; ok {
return token, nil
}
return harnesssecret.Secret{}, storecontract.ErrHarnessSecretNotFound
}
func setupRequest(t *testing.T, srv *Server) []SetupStep {
t.Helper()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/setup", nil)
response := httptest.NewRecorder()
srv.handleSetup(response, req)
if response.Code != http.StatusOK {
t.Fatalf("response = %d %s", response.Code, response.Body.String())
}
var body struct {
Steps []SetupStep `json:"steps"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response %q: %v", response.Body.String(), err)
}
return body.Steps
}
func modelStep(steps []SetupStep) *SetupStep {
for i := range steps {
if steps[i].Title == "Model" {
return &steps[i]
}
}
return nil
}
func TestHandleSetupModelStep(t *testing.T) {
resolving := func(_ context.Context, ref secret.SecretRef) (bool, error) {
return ref == (secret.SecretRef{Engine: "env", Key: "GOOD_KEY"}), nil
}
for _, tt := range []struct {
name string
aliases map[string]string
providers string
bindings string
tokens map[string]harnesssecret.Secret
check func(context.Context, secret.SecretRef) (bool, error)
open bool
detail string
}{
{
name: "no aliases leaves the step open",
aliases: map[string]string{},
open: true,
detail: "no model alias configured",
},
{
name: "resolving api_key_ref completes the step",
aliases: map[string]string{"default": "openai/gpt-5"},
providers: `{"openai":{"class":"openai","api_key_ref":{"engine":"env","key":"GOOD_KEY"}}}`,
check: resolving,
open: false,
},
{
name: "unresolving api_key_ref keeps the step open and names it",
aliases: map[string]string{"default": "openai/gpt-5"},
providers: `{"openai":{"class":"openai","api_key_ref":{"engine":"env","key":"BAD_KEY"}}}`,
check: resolving,
open: true,
detail: `provider "openai" credential env:BAD_KEY does not resolve`,
},
{
name: "provider declaring no credential keeps the step open",
aliases: map[string]string{"default": "openai/gpt-5"},
providers: `{"openai":{"class":"openai"}}`,
check: resolving,
open: true,
detail: `provider "openai" declares no credential`,
},
{
name: "credential binding secret resolves for an org provider",
aliases: map[string]string{"default": "acme/gpt-5"},
providers: `{"acme":{"class":"openai"}}`,
bindings: `[{"service":"acme","secret":{"engine":"env","key":"GOOD_KEY"}}]`,
check: resolving,
open: false,
},
{
name: "credential binding secret that does not resolve keeps the step open",
aliases: map[string]string{"default": "acme/gpt-5"},
providers: `{"acme":{"class":"openai"}}`,
bindings: `[{"service":"acme","secret":{"engine":"env","key":"BAD_KEY"}}]`,
check: resolving,
open: true,
detail: `provider "acme" credential env:BAD_KEY does not resolve`,
},
{
name: "org provider without a binding keeps the step open",
aliases: map[string]string{"default": "acme/gpt-5"},
providers: `{"acme":{"class":"openai"}}`,
check: resolving,
open: true,
detail: `provider "acme" declares no credential`,
},
{
name: "instance provider is not the org's credential to configure",
aliases: map[string]string{"default": "shared/gpt-5"},
providers: `{}`,
check: resolving,
open: false,
},
{
name: "oauth binding with a captured token set completes the step",
aliases: map[string]string{"default": "acme/gpt-5"},
providers: `{"acme":{"class":"openai"}}`,
bindings: `[{"service":"acme"}]`,
tokens: map[string]harnesssecret.Secret{"acme": {Org: "org", Service: "acme", AccessToken: "token"}},
check: resolving,
open: false,
},
{
name: "oauth binding without a captured token set keeps the step open",
aliases: map[string]string{"default": "acme/gpt-5"},
providers: `{"acme":{"class":"openai"}}`,
bindings: `[{"service":"acme"}]`,
tokens: map[string]harnesssecret.Secret{},
check: resolving,
open: true,
detail: `provider "acme" has no captured sign-in for credential binding "acme"`,
},
{
name: "api_key_env resolves through the env engine",
aliases: map[string]string{"default": "openai/gpt-5"},
providers: `{"openai":{"class":"openai","api_key_env":"GOOD_KEY"}}`,
check: resolving,
open: false,
},
{
name: "without the control plane the aliases alone decide",
aliases: map[string]string{"default": "openai/gpt-5"},
check: resolving,
open: false,
},
} {
t.Run(tt.name, func(t *testing.T) {
srv := &Server{Store: setupStore{}, Models: setupModels{aliases: tt.aliases}}
if tt.providers != "" || tt.bindings != "" {
srv.ControlPlane = setupControl{providers: tt.providers, bindings: tt.bindings}
}
srv.CheckSecret = tt.check
if tt.tokens != nil {
srv.HarnessSecrets = setupHarnessSecrets{tokens: tt.tokens}
}
step := modelStep(setupRequest(t, srv))
if !tt.open {
if step != nil {
t.Fatalf("Model step = %+v, want it complete (absent)", *step)
}
return
}
if step == nil {
t.Fatalf("Model step absent, want it open with detail %q", tt.detail)
}
if step.Done {
t.Fatalf("Model step done, want it open")
}
if !strings.Contains(step.Detail, tt.detail) {
t.Fatalf("Model step detail = %q, want it to contain %q", step.Detail, tt.detail)
}
})
}
}