Files
archie/internal/app/archieui/run.go
T
sam f92c5b4536
ci/woodpecker/pr/quality Pipeline was successful
Quality / check (pull_request) Canceled after 7m39s
chore(runtime): delete Kit and external agent harness support (#1877)
Archie runs its own agent loop only. Removes Kit resolution and launch,
the harness runner and adapters, the setup terminal and sandbox view,
harness secrets and OAuth capture (table dropped in migration 0075), the
task-tools contract that only Kit containers reached, and the
sandbox-kit-spec dependency. Agent profiles carry image and tools only.
The egress proxy keeps the model-session path; the sandbox relay code
stays for #1867.
2026-11-12 21:29:05 +11:00

186 lines
7.0 KiB
Go

package archieui
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/presence"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
"github.com/samcharles93/archie-core/internal/webui"
)
// buildAccessChain starts the live access engine over the stored policies.
// It refuses every request until the first load succeeds, so a State Store or
// database that is down or slow at start closes the dashboard rather than
// opening it or stopping it.
func buildAccessChain(ctx context.Context, store *staterpc.Client, log *slog.Logger) *infraaccess.Live {
return infraaccess.StartLive(ctx, store.ListPolicies, store.PoliciesVersion, log)
}
// resolveTraced resolves the options and starts trace export from them.
func resolveLogged(ctx context.Context, options Options) (Options, servicekit.Logs, error) {
opts, err := Resolve(options, slog.New(slog.NewJSONHandler(os.Stderr, nil)))
if err != nil {
return Options{}, servicekit.Logs{}, err
}
logs, err := servicekit.Logging(ctx, opts.logging, "ui")
return opts, logs, err
}
// Run serves the dashboard until ctx is cancelled. It resolves its own
// options, dials the Gateway and State Store contracts itself, composes the
// HTTP surface over them, and unwinds listener then clients in reverse order
// on shutdown.
func Run(ctx context.Context, options Options) error {
opts, logs, err := resolveLogged(ctx, options)
if err != nil {
return err
}
defer func() { _ = logs.Closer.Close() }()
log, feed := logs.Log.With("service", presence.UI), logs.Feed
warnPlainHTTP(log, opts)
var cleanups []func()
defer func() {
for _, cleanup := range slices.Backward(cleanups) {
cleanup()
}
}()
tasks, closeState, err := staterpc.Dial(opts.State.Target, presence.UI, opts.identity)
if err != nil {
return err
}
cleanups = append(cleanups, closeState)
chat, closeGateway, err := gatewayrpc.Dial(opts.Gateway.Target, opts.identity)
if err != nil {
return err
}
cleanups = append(cleanups, closeGateway)
chain := buildAccessChain(ctx, tasks, log)
provider, err := signInProvider(opts)
if err != nil {
return err
}
login, err := dashboardLoginFlow(provider, opts)
if err != nil {
return err
}
runtimeOIDC := &accountOIDC{settings: tasks, subjects: tasks, fallbackFlow: login, fallbackProvider: provider, fallback: identity.AuthenticationSettings{PublicURL: strings.TrimSuffix(opts.OidcRedirectURL, "/oauth2/callback"), OIDCIssuer: opts.OidcIssuer, OIDCAudience: opts.OidcAudience, OIDCClientID: opts.OidcClientID}}
srv := compose(ctx, deps{
Options: opts,
Log: log,
Store: tasks,
Usage: tasks,
Chat: chat,
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
ControlPlane: tasks.ControlPlane(),
Identities: tasks,
Authenticate: runtimeOIDC.Authenticate,
AuthenticateBrowser: runtimeOIDC.AuthenticateBrowser,
Login: runtimeOIDC,
Access: chain,
Principals: tasks,
Denials: tasks,
})
stopLogs, err := wireServiceLogs(opts, srv, tasks, chat, feed)
if err != nil {
return err
}
cleanups = append(cleanups, stopLogs)
if err := wireDaemon(opts, srv, &cleanups); err != nil {
return err
}
// Priming event history must not delay the listener.
go pumpEvents(ctx, srv, opts.EventPollInterval, log)
go presence.Run(ctx, presence.UI, servicekit.Build(), tasks, srv.Health, log)
liveCtx, stopLive := context.WithCancel(ctx)
defer stopLive()
go srv.RunLive(liveCtx)
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", opts.Listen)
if err != nil {
return fmt.Errorf("listen for ui: %w", err)
}
cleanups = append(cleanups, func() { _ = listener.Close() })
attrs := []any{
"addr", listener.Addr().String(),
"open", webui.DashboardURL(listener.Addr().String()),
"gateway", opts.Gateway.Target,
"state", opts.State.Target,
}
log.InfoContext(ctx, "archie-ui running", attrs...)
return serve(ctx, listener, srv.Handler(), opts)
}
// warnPlainHTTP names the exposure of a dashboard published off-host. The
// process serves plain HTTP, so the session cookie and the provider token
// cross the network in clear unless a TLS-terminating proxy sits in front of
// it -- which [web].trust_forwarded_headers declares. A loopback bind is
// reached over a tunnel or on the host, so it needs no warning.
func warnPlainHTTP(log *slog.Logger, opts Options) {
if webui.IsLoopback(opts.Listen) || opts.trustForwardedHeaders() {
return
}
log.Warn("dashboard is reachable off-host over plain HTTP; session and provider tokens travel in clear unless TLS terminates in front of it (set [web].trust_forwarded_headers behind a TLS proxy)",
"listen", opts.Listen)
}
func wireDaemon(opts Options, srv *webui.Server, cleanups *[]func()) error {
checks, closeChecks, err := daemonrpc.Dial(opts.Daemon.Target, opts.identity)
if err != nil {
return fmt.Errorf("repository checks: %w", err)
}
srv.RepositoryChecks = checks
*cleanups = append(*cleanups, closeChecks)
return nil
}
// serve runs handler until ctx ends, then shuts down within
// ShutdownTimeout.
func serve(ctx context.Context, listener net.Listener, handler http.Handler, opts Options) error {
server := &http.Server{Handler: telemetry.Handler(handler), ReadHeaderTimeout: opts.ReadHeaderTimeout}
serveErr := make(chan error, 1)
go func() { serveErr <- server.Serve(listener) }()
select {
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), opts.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
// Shutdown returned once the drain deadline elapsed with a request
// still in flight. Force-close what is left so shutdown finishes
// and the process exits cleanly rather than carrying a deadline
// error to the operator as a fatal exit.
_ = server.Close()
}
return nil
case err := <-serveErr:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
}
func pumpEvents(ctx context.Context, srv *webui.Server, interval time.Duration, log *slog.Logger) {
if err := srv.PumpEvents(ctx, interval); err != nil {
log.ErrorContext(ctx, "event pump stopped; the activity feed will only show history", "err", err)
}
}