diff --git a/internal/webui/api_capabilities.go b/internal/webui/api_capabilities.go index b61dc9d9c..f85d964f7 100644 --- a/internal/webui/api_capabilities.go +++ b/internal/webui/api_capabilities.go @@ -2,21 +2,8 @@ package webui import "net/http" -// handleCapabilities reports which dashboard sections this process can -// actually serve. -// -// The dashboard is served by the extracted UI process, which holds two remote -// contracts (Gateway ChatContract and the State Store) and nothing else. -// Sections whose capability lives only in the daemon still answer -- with an -// empty list, a "disabled" marker, or a 501 -- and the page cannot tell that -// apart from a deployment where nothing has happened yet. Rather than have -// every page guess, the server says which sections it can back, and the -// browser hides the rest. -// -// A section is reported available when the handle behind it is wired, which -// is the same condition its handler already uses to decide between real data -// and its degraded answer. Sections backed by the task store are absent from -// this list: the store is mandatory. +// handleCapabilities reports which dashboard sections this process can serve, +// so the browser hides the rest. func (s *Server) handleCapabilities(w http.ResponseWriter, _ *http.Request) { writeJSON(w, map[string]any{ "sections": map[string]bool{ diff --git a/internal/webui/api_capture.go b/internal/webui/api_capture.go index 565946bd5..952a0f03e 100644 --- a/internal/webui/api_capture.go +++ b/internal/webui/api_capture.go @@ -5,22 +5,11 @@ import ( "strconv" ) -// defaultCapturesListLimit is used when the limit query param is absent, -// non-numeric, non-positive, or wider than the int32 SQL LIMIT the store -// binds. A raw strconv.ParseInt zero value (its error -// case) must never reach ListCaptures directly -- SQL "LIMIT 0" returns zero -// rows, which would make an unrecognised or missing limit look identical to -// "no captures exist" instead of "show the default page." +// defaultCapturesListLimit applies when the limit parameter is missing, +// invalid or out of range. const defaultCapturesListLimit = 100 -// handleCaptures lists recent captured events, newest first, for the -// dashboard's event inspector. Token-gated like every other -// /api/* route -- captured payloads are visible only to an authenticated -// operator. -// -// This is the read half of event capture. The write half is the receiver in -// internal/infrastructure/captureintake, mounted on the bypass mux via -// CaptureIntake; the dashboard displays captures and mounts the route. +// handleCaptures lists recent captured events, newest first. func (s *Server) handleCaptures(w http.ResponseWriter, r *http.Request) { if s.Captures == nil { writeJSON(w, map[string]any{"captures": []any{}, "enabled": false}) diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index 144a19ae1..67d630781 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -62,12 +62,7 @@ type chatMessageView struct { Media []chatMediaView `json:"media,omitempty"` } -// chatMediaView is one attachment a message carried, as the dashboard reads -// it. The bytes are turn-scoped and are gone before a record is stored, so -// this view carries only what survived persistence, and FileID is left out on -// purpose: it is the platform's download handle, not an address, so handing -// it to a browser only invites a fetch that cannot work. URL is present -// exactly when the attachment itself carried one. +// chatMediaView is a stored message attachment as the dashboard reads it. type chatMediaView struct { Type string `json:"type"` FileName string `json:"file_name,omitempty"` @@ -326,15 +321,7 @@ func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]string{"reply": reply.Text, "session_id": reply.SessionID}) } -// chatStreamEvent is one `data: {...}` frame of the chat stream. A tool frame -// names the tool in Tool, carries its one-line outcome in Text, and signals -// failure through Failed -- a structured field, so the browser styles the -// two apart by reading it rather than by sniffing a "failed:" prefix out of -// Text, which a successful tool's own output can start with too. -// -// Text is always emitted, empty or not: the browser concatenates it and -// assigns it, so a missing key would put the string "undefined" into the -// transcript on a turn whose reply is empty. +// chatStreamEvent is one frame of the chat stream. Text is always emitted. type chatStreamEvent struct { Type string `json:"type"` Text string `json:"text"` @@ -350,16 +337,8 @@ type chatStreamEvent struct { Label string `json:"label,omitempty"` } -// chatStreamSink adapts the stream writer to messaging.TurnStream so text and -// tool activity reach the browser through one ordered path. -// -// showToolCalls gates ToolCall the same way Telegram's liveReply gates its -// own tool narration: config.ChatConfig.ShowToolCalls is one setting for -// every chat channel, so an operator who turned it off gets no tool frames -// on the dashboard either, not just in Telegram. It is snapshotted into the -// sink at stream start rather than read live, for the same reason Telegram -// snapshots it per-reply -- a config reload mid-turn must not change what a -// turn already in flight narrates. +// chatStreamSink writes turn text and tool activity to the browser stream. +// showToolCalls is fixed for the stream. type chatStreamSink struct { write func(chatStreamEvent) showToolCalls bool @@ -400,16 +379,8 @@ func (s chatStreamSink) ToolCall(event messaging.ToolCallEvent) { }) } -// Media has no inline rendering path on the dashboard yet, so it degrades to a -// link in the delta stream -- the same fallback Telegram's liveReply uses when -// its own SendMedia call fails. -// -// A local file cannot be linked and this channel cannot upload one, so it -// is REPORTED as undelivered rather than skipped. Skipping was right while -// media meant a hosted URL; once send_file could hand this sink a host -// path, silence here meant the model announced a file it had sent and -// nothing arrived -- the precise defect send_file was built to end, -// reappearing on the channel that cannot deliver. +// Media is sent as a link in the text stream; a local file is reported as +// undelivered. func (s chatStreamSink) Media(event messaging.MediaEvent) { att := event.Attachment switch { @@ -427,14 +398,8 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) { } } -// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, the one setting -// shared by every chat channel. It reads the configuration projection this -// process renders, so a dashboard that displays a published snapshot honours -// the operator's setting instead of assuming it off. -// -// Off (the default) when no projection is available, matching the field's own -// off-by-default doc comment: a dashboard without config must not narrate tool -// activity nobody opted into. +// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, false when no +// config is available. func (s *Server) chatShowToolCalls(ctx context.Context) bool { view, found, err := s.configSource()(ctx) if err != nil || !found { diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 7aa9e24d5..40ed36227 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -143,26 +143,13 @@ type ConfigView struct { // dashboard to the reason. The UI renders these rows disabled rather // than silently omitting the edit affordance. Locked map[string]string `json:"locked,omitempty"` - // MultiIdentity reports that the deployment configures [[identities]], - // so Identity and Repositories describe the default identity alone. - // Identities below carries the rest; a consumer attributing a task to - // its forge reads that, and a document that sets this flag without - // carrying them (one published by an older daemon) must withhold the - // links rather than guess. + // MultiIdentity reports that [[identities]] is configured, so Identity and + // Repositories describe only the default identity. MultiIdentity bool `json:"multi_identity,omitempty"` - // Identities publishes each configured identity's forge and the - // repositories it owns, which is everything a process rendering task - // rows needs to answer "which forge owns this task" -- see - // Server.resolveForge (api_tasks.go). Empty for a single-identity - // deployment, whose forge is Identity above. + // Identities lists each identity's forge and repositories. Empty for a + // single-identity deployment. Identities []ForgeIdentityView `json:"identities,omitempty"` - // Schema is the field-descriptor catalog attached to - // this view's own values and locked reasons -- see config_schema.go. It - // carries the labels, sections and types a generic configuration renderer - // needs, instead of making each rendering process hardcode them; the flat - // fields stay for existing consumers (structured cards, provenance, - // reload/lock plumbing) rather than being removed in the same change that - // adds their replacement. + // Schema is the field-descriptor catalog for the configuration page. Schema []ConfigSection `json:"schema"` } @@ -185,11 +172,7 @@ type ForgeRepoView struct { Name string `json:"name"` } -// ForgeIdentityView is one configured identity's forge coordinates plus the -// repositories it owns. It is deliberately narrower than IdentityView and -// RepoView: the task board needs to locate a repository, not to render the -// configuration page, and an identity's token -- or any of its other -// settings -- must not travel to the browser for either purpose. +// ForgeIdentityView is an identity's forge coordinates and repositories. type ForgeIdentityView struct { Name string `json:"name"` ForgeType string `json:"forge_type"` @@ -279,26 +262,12 @@ type WebView struct { TrustForwardedHeaders bool `json:"trust_forwarded_headers"` } -// handleConfig returns a read-only, secret-free view of the running -// configuration. -// -// This handler builds ConfigView field by field from an explicit allowlist -// rather than marshalling config.Config and stripping fields afterward: -// config.Config carries config.SecretRef values (forge tokens, provider API -// keys) and there is no way to guarantee a strip-after-marshal approach -// keeps working as fields are added to Config in the future. An allowlist -// fails safe -- a new secret field added upstream is simply absent here -// until someone deliberately adds it. -// ConfigViewSchema names the projection's shape. It travels with a published -// snapshot so a reader can refuse a document it does not understand, and it -// changes when ConfigView's JSON shape changes incompatibly. +// ConfigViewSchema names ConfigView's JSON shape; it changes on incompatible +// changes. const ConfigViewSchema = "webui.ConfigView/1" -// ConfigViewSource supplies the configuration projection the page renders. -// The process that owns configuration builds it; a process that only displays -// configuration reads the published snapshot instead. found is false when no -// configuration is available to render, which the handler answers with an -// empty object rather than an error. +// ConfigViewSource supplies the configuration view. found is false when there +// is none. type ConfigViewSource func(ctx context.Context) (ConfigView, bool, error) // configSource returns the projection source, or an empty one when @@ -352,14 +321,8 @@ type CatalogProviderView struct { Models []string `json:"models"` } -// BuildConfigView renders the dashboard's secret-free configuration -// projection. The configuration owner calls it -- the daemon publishes the -// result as a snapshot (storecontract.ConfigSnapshot) and a process that only -// displays configuration reads that snapshot back through RemoteConfigView. -// -// It is deliberately a function, not a method: rendering the view is not a -// property of an HTTP server, and the process that owns configuration is not -// the process that serves this page. +// BuildConfigView renders the secret-free configuration view from an explicit +// allowlist of fields. func BuildConfigView(in ConfigViewInput) ConfigView { cfg := in.Config provenance := append([]ConfigOrigin(nil), in.Provenance...) @@ -421,13 +384,7 @@ func BuildConfigView(in ConfigViewInput) ConfigView { return view } -// chatChannelConfigured reports whether any conversational front-end is -// configured. The setup checklist needs the answer, not the tokens, so the -// projection carries the boolean. -// -// The definition lives in config.ChatConfig.FrontEnds, not here: the daemon's -// channel status manager answers the same question on /api/channels, and -// deciding it twice is how the two answers drifted apart. +// chatChannelConfigured reports whether any chat front-end is configured. func chatChannelConfigured(chat config.ChatConfig) bool { return chat.AnyFrontEndConfigured() } @@ -440,11 +397,8 @@ type ChannelStatusSource interface { Snapshot() []status.Status } -// RemoteChannelStatus reads channel state from the State Store, where the -// process hosting the channels publishes it. It is the reader half of the same -// split RemoteConfigView serves: the writer is another process and the reader is -// this one, so a reader that cannot reach the store reports nothing rather than -// inventing a state, and the page shows no channels instead of wrong ones. +// RemoteChannelStatus reads channel state from the State Store; unreachable +// reports none. func RemoteChannelStatus(channels storecontract.ChannelStatusStore) ChannelStatusSource { return remoteChannelStatus{channels: channels} } @@ -519,13 +473,8 @@ func reposView(repos []config.Repo) []RepoView { return out } -// identityForgesView renders each configured identity's forge coordinates and -// the repositories it owns. This is the half of a multi-identity deployment's -// configuration the task board needs: a process that holds no configuration -// answers "which forge owns this task" from here (api_tasks.go's -// resolveForge). Only the coordinates and the repository names cross -- an -// identity's token is a secret reference and must not, and nothing else on -// IdentityConfig is needed to locate a repository. +// identityForgesView returns each identity's forge coordinates and +// repository names. func identityForgesView(identities []config.IdentityConfig) []ForgeIdentityView { out := make([]ForgeIdentityView, 0, len(identities)) for _, id := range identities { diff --git a/internal/webui/api_curators.go b/internal/webui/api_curators.go index 645a27d24..2e19f6519 100644 --- a/internal/webui/api_curators.go +++ b/internal/webui/api_curators.go @@ -15,13 +15,7 @@ type CuratorActionView struct { Reason string `json:"reason"` } -// CuratorStatus is the webui-owned surface over the running curator -// registry: the names, point-in-time health, and recent activity the -// dashboard's curator view renders. It is deliberately narrower than the -// registry itself -- whose engine contract drags in the agent toolchain -- -// so the UI process holds the view without linking it. -// Whoever owns the registry supplies an adapter at -// bootstrap. +// CuratorStatus is the dashboard's view of the curator registry. type CuratorStatus interface { Names() []string Health(ctx context.Context) map[string]CuratorHealthView @@ -42,11 +36,7 @@ type CuratorActivity struct { type CuratorView struct { Name string `json:"name"` Health CuratorHealthView `json:"health"` - // LastRunAt is a pointer so a curator that has never run omits the - // field entirely instead of serializing time.Time's zero value - // ("0001-01-01T00:00:00Z") -- json's "omitempty" does not treat a - // zero-valued struct as empty, and a non-empty string is truthy to - // the dashboard's "has this run yet" check. + // LastRunAt is nil when the curator has never run. LastRunAt *time.Time `json:"last_run_at,omitempty"` LastRunActions int `json:"last_run_actions"` RecentActions []CuratorActionView `json:"recent_actions"` diff --git a/internal/webui/api_harness.go b/internal/webui/api_harness.go index 11004ee8f..c6055d919 100644 --- a/internal/webui/api_harness.go +++ b/internal/webui/api_harness.go @@ -46,16 +46,8 @@ type harnessProfileDoc struct { Kit string `json:"kit"` } -// HarnessTerminal opens an ephemeral setup session for one Kit profile: a -// duplex byte stream to the container's PTY, on the same egress path a Kit -// task runs on. -// -// It is a seam, not an implementation. The container, the sandbox network and -// the egress session belong to the daemon, and the dashboard process is -// forbidden from linking them. A composition wires whichever transport carries -// the session; nil answers the route 503 rather than pretending a terminal -// exists. The interface's method types are stdlib only, so a future transport -// that implements it cannot drag a banned package into the UI binary. +// HarnessTerminal opens a setup session to a Kit profile's container PTY. +// Nil answers 503. type HarnessTerminal interface { Open(ctx context.Context, orgID, profile string) (io.ReadWriteCloser, error) } diff --git a/internal/webui/api_health.go b/internal/webui/api_health.go index a738ecf24..10eb9deb2 100644 --- a/internal/webui/api_health.go +++ b/internal/webui/api_health.go @@ -2,25 +2,14 @@ package webui import "net/http" -// handleHealth is a liveness probe: the process is up and able to serve a -// request. It deliberately bypasses requireToken, like /healthz -- a local -// orchestration tool (systemd, a watchdog, a container healthcheck) must be -// able to ask "is the process alive?" without the dashboard token. It does no -// subsystem work and always answers 200 when the process can respond at all. +// handleHealth is an unauthenticated liveness probe. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok")) } -// handleHealthDetailed is the authenticated readiness surface. It runs every -// registered readiness probe and returns each subsystem's live result plus -// the overall rollup, so an operator can see exactly which subsystem is -// degraded rather than only that the daemon is unhealthy. -// -// It requires the dashboard token (and is mounted behind requireToken) because -// it exposes real subsystem state -- a remote caller should not be able to -// probe the disk layout or provider reachability unauthenticated. When no -// probe registry is wired, it answers 503 rather than pretending to know. +// handleHealthDetailed runs every readiness probe and returns each result and +// the rollup. Authenticated; 503 when no probes are wired. func (s *Server) handleHealthDetailed(w http.ResponseWriter, r *http.Request) { if s.Health == nil { http.Error(w, "readiness probes are not configured", http.StatusServiceUnavailable) diff --git a/internal/webui/api_logs.go b/internal/webui/api_logs.go index d7744b3cb..03a854f44 100644 --- a/internal/webui/api_logs.go +++ b/internal/webui/api_logs.go @@ -10,12 +10,6 @@ import ( ) // handleLogs serves a page of log history. -// -// This handler is transport only: parsing the log format belongs to the -// logging package, which owns it. Live output reaches the dashboard over the -// existing /api/stream stream; this endpoint exists so the view has history from -// before the browser connected, which is the whole reason file logging landed -// first. func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) { path := s.logFile() if path == "" { @@ -94,11 +88,7 @@ func mergeComponents(history []string, live []logging.Entry) []string { return components } -// logFile reports the log path this process can read, or "" when it has -// none. It is deliberately this process's own setting rather than the -// daemon's [log].file: the history lives on the daemon's disk, so a -// dashboard running elsewhere cannot read it by learning its path. Serving -// remote log history needs a contract, which /api/logs does not yet have. +// logFile returns this process's readable log path, or "". func (s *Server) logFile() string { return strings.TrimSpace(s.LogFile) } diff --git a/internal/webui/api_mapping.go b/internal/webui/api_mapping.go index 4de9d1802..9ee12e8a3 100644 --- a/internal/webui/api_mapping.go +++ b/internal/webui/api_mapping.go @@ -240,18 +240,12 @@ func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.Cap return nil, nil } -// captureScanWindowDefault bounds captureByID's linear scan when -// CaptureMaxEvents is unset (zero or negative, matching CaptureConfig's own -// "zero means default" convention). Matches CaptureConfig's documented -// default so an unconfigured deployment's scan window still covers its -// whole table. +// captureScanWindowDefault bounds captureByID's scan when CaptureMaxEvents is +// unset. const captureScanWindowDefault = 5000 -// mappingCaptureScanWindow ties captureByID's scan bound to the operator's -// actual configured retention (CaptureMaxEvents), rather than a constant -// that silently drifts out of sync with it -- an operator raising -// [capture] max_events above the old hardcoded 5000 would otherwise make a -// genuinely still-retained capture 404 as "not found" during preview. +// mappingCaptureScanWindow returns the configured capture retention, or the +// default. func mappingCaptureScanWindow(configuredMaxEvents int) int { if configuredMaxEvents <= 0 { return captureScanWindowDefault diff --git a/internal/webui/api_setup.go b/internal/webui/api_setup.go index 2ec415f33..f15556551 100644 --- a/internal/webui/api_setup.go +++ b/internal/webui/api_setup.go @@ -12,16 +12,7 @@ type SetupStep struct { Done bool `json:"done"` } -// handleSetup reports which parts of archied are configured. -// -// The checklist exists so a new operator is told what is missing rather than -// shown a dashboard of zeroes and left to infer it. Steps are phrased as -// actions in plain language -- "Connect a chat channel", not "channels.telegram -// .bot_token unset" -- because someone who already knows the config key does -// not need the checklist. -// -// Every step is derived from live state, so the list disappears on its own -// once setup is complete rather than needing to be dismissed. +// handleSetup reports which setup steps are still missing, from live state. func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { steps := []SetupStep{} diff --git a/internal/webui/api_skills.go b/internal/webui/api_skills.go index 31ed8de44..8324b91b7 100644 --- a/internal/webui/api_skills.go +++ b/internal/webui/api_skills.go @@ -11,12 +11,7 @@ type SkillView struct { Source string `json:"source"` } -// SkillCatalog is the webui-owned source of the dashboard's skill -// catalogue. It is deliberately a view over already-discovered entries, not -// the discovery machinery: the cataloguer (internal/skill) drags the agent -// toolchain in, and the UI process must not link it. -// Whoever owns the runtime -- the daemon, via its config -- supplies an -// adapter at bootstrap; an unwired catalog degrades to an empty page. +// SkillCatalog lists the discovered skills. Unwired returns an empty list. type SkillCatalog interface { Skills() []SkillView } diff --git a/internal/webui/api_task_meta.go b/internal/webui/api_task_meta.go index 2b10044e0..a47e39d3a 100644 --- a/internal/webui/api_task_meta.go +++ b/internal/webui/api_task_meta.go @@ -28,14 +28,8 @@ type taskMetaView struct { ConfigSchema string `json:"config_schema"` } -// buildTaskMeta derives the lifecycle presentation catalog: the status -// vocabulary (with label, pill severity, "needs you" grouping), the operator -// action controls (with label, button variant, confirm prompt), the retry -// worktree modes (with label, description and which is the default), the -// changes_captured status labels and the schema stamp a config_captured -// payload carries. Everything the dashboard can present that also exists on -// the server is derived here, so the frontend never has to keep a hand-synced -// copy of the vocabulary or the control set. +// buildTaskMeta returns the task status vocabulary, operator actions, retry +// modes and capture labels the dashboard renders. func buildTaskMeta() taskMetaView { return taskMetaView{ Statuses: taskstate.Statuses(), diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 1bb540d30..533cb82c5 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -77,16 +77,8 @@ type forgeCoordinates struct { forgeType string } -// resolveForge reads the forge layout once for a request and returns each -// task's coordinates from it. -// -// The projection publishes per-identity forges (ConfigView.Identities), so a -// multi-identity deployment links each task to the forge that owns it. The -// matching rules are the ones recovered from the pre-cutover resolver -// (forgeConfigForTask, 57d9be5): an exact identity name first, then repository -// ownership, and an ambiguous repository -- two identities claiming the same -// owner/name -- falling back to the default forge rather than pointing at -// either. Without this, every row in such a deployment renders unlinked. +// resolveForge returns a function mapping a task to its forge: by identity +// name, then repository owner, else the default forge. func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates { unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} } view, ok, err := s.configSource()(ctx) @@ -94,11 +86,7 @@ func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordina return unlinked } if len(view.Identities) == 0 { - // Nothing per-identity was published. A single-identity deployment's - // one forge is the whole answer. A document that reports identities - // but carries none is one an older daemon published, and there is - // nothing to attribute a task to -- so the links are withheld rather - // than pointed at the wrong forge. + // No per-identity forges published: links are withheld. if view.MultiIdentity { return unlinked } @@ -198,11 +186,7 @@ type taskActionRequest struct { // absent selection means all of them. It is ignored by every other // action. Findings []string `json:"findings"` - // RetryMode is the operator's worktree choice for a retry - // (taskstate.RetryMode): refresh onto the base branch, or continue the - // work already pushed on the task's branch. The retry control sends one; - // an empty value means the explicit default, refresh_onto_base. It is - // ignored by every other action. + // RetryMode is the worktree mode for a retry; empty means refresh_onto_base. RetryMode string `json:"retry_mode"` } @@ -281,17 +265,9 @@ func taskMutation(action taskstate.Action) bool { } } -// authorizeTaskMutation applies the browser mutation contract at the handler -// boundary: JSON only, a non-simple custom header, and a matching Origin when -// the browser supplies one. The custom header forces cross-origin callers -// through a CORS preflight, which this server never permits. -// -// Origin comparison previously validated against the daemon's own direct network -// connection (r.TLS). It now validates against the effective external scheme -// and host, deriving them from X-Forwarded-Proto and X-Forwarded-Host only when -// explicit proxy header trust is enabled (Web.TrustForwardedHeaders). When trust -// is disabled (the default), forwarded headers are ignored to prevent untrusted -// clients from forging Origin scheme checks on exposed daemons. +// authorizeTaskMutation requires JSON, a custom header and, when present, a +// same-origin Origin. Forwarded headers are trusted only with +// TrustForwardedHeaders. func (s *Server) authorizeTaskMutation(w http.ResponseWriter, r *http.Request) bool { if r.Header.Get("X-Archie-CSRF") != "1" { http.Error(w, "missing CSRF header", http.StatusForbidden) @@ -355,15 +331,7 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool { return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost) } -// applyOperatorTaskAction sends the action to whoever owns task execution. -// The dashboard operator is authenticated and acts across identities, which -// the Gateway contract carries as its own method. -// -// The UI process cannot run this itself: retry limits come from the daemon's -// configuration, closing the forge issue needs its forge client, the -// timeline needs its event bus, and stopping running work needs the -// goroutine or container that is executing it. Composing a local service -// over the task store alone would silently drop all four. +// applyOperatorTaskAction sends an operator's task action to the Gateway. func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error { if s.Chat == nil || s.Chat.Contract == nil { return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable) diff --git a/internal/webui/api_tasks_attempts.go b/internal/webui/api_tasks_attempts.go index 668196f32..7718f1dbd 100644 --- a/internal/webui/api_tasks_attempts.go +++ b/internal/webui/api_tasks_attempts.go @@ -39,11 +39,8 @@ type taskAttemptsView struct { Attempts []taskAttemptView `json:"attempts"` } -// taskAttemptView is one attempt's rail entry. The bounds and duration are -// measured from the attempt's own events: the span between its first and last -// recorded event, which therefore includes any waiting-for-a-human gap rather -// than understating wall time (design AMENDMENTS 0.1, F3). Every optional -// field is omitted when it is not known rather than sent as a zero. +// taskAttemptView is one attempt, bounded by its first and last event. +// Unknown fields are omitted. type taskAttemptView struct { Attempt int `json:"attempt"` Status string `json:"status"` @@ -66,13 +63,8 @@ type taskStageView struct { Error string `json:"error"` } -// handleTaskAttempts serves the stage rail: one task's attempts, each with the -// stages it recorded. Attempt bounds, event counts and which attempt numbers -// exist still come from the task's events (an attempt can carry events with -// no step, e.g. agent calls, so events remain the complete attempt index); -// the stages themselves are step_executions, the authoritative record, -// not a fold over -// stage_start/stage_finish events. +// handleTaskAttempts returns a task's attempts from its events, each with the +// stages recorded as step executions. func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { t, ok := s.taskByPathID(w, r) if !ok { @@ -122,12 +114,8 @@ func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Tas return t, true } -// taskAttemptTarget resolves a per-attempt read: the task its {id} names and the -// attempt it asks for. An absent or zero "attempt" parameter selects the task's -// current attempt, which is what a human means by "why did this park?" -- the -// most recent run, not an arbitrary earlier retry. Zero is not an attempt: it is -// the value that means "unattributed" on an event, so reading "attempt zero" -// would read a bucket rather than a run. +// taskAttemptTarget resolves the task in {id} and the requested attempt, +// defaulting to the current one. func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) { t, ok := s.taskByPathID(w, r) if !ok { @@ -149,14 +137,8 @@ func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*tas return t, attempt, true } -// attemptsFromEvents folds a task's timeline into its rail: one entry per -// attempt the events attribute to, ordered by attempt, plus the number of events -// that carry no attempt at all. -// -// Events with attempt 0 are counted and then dropped, never grouped. Zero means -// unattributed -- every row written before the column existed and every -// deliberately task-agnostic producer carries it -- so grouping them would -// present unrelated activity as attempt zero's rail. +// attemptsFromEvents groups a task's events by attempt and counts events with +// no attempt. func attemptsFromEvents(evs []events.Event, steps []task.StepExecution, taskStatus string, currentAttempt int) ([]taskAttemptView, int) { grouped := make(map[int][]events.Event) numbers := make([]int, 0, 4) @@ -242,11 +224,7 @@ func attemptBounds(evs []events.Event) (first, last time.Time) { return first, last } -// stageViewsFromSteps builds an attempt's ordered stage occurrences directly -// from its recorded StepExecutions -- the authoritative record, -// not a fold over -// stage_start/stage_finish events. Only kind "stage" steps are shown: agent -// and call steps are the tree's own detail, not this rail's. +// stageViewsFromSteps returns an attempt's stage steps in order. func stageViewsFromSteps(steps []task.StepExecution, inFlight bool) []taskStageView { stages := []taskStageView{} for _, s := range steps { @@ -270,11 +248,8 @@ func stageViewsFromSteps(steps []task.StepExecution, inFlight bool) []taskStageV return stages } -// mapStepStatus reads the rail's status vocabulary off a step's own recorded -// status. A step still recorded running past this attempt -- the daemon -// crashed or restarted without marking it -- reads interrupted rather than -// running: RecoverStale is what corrects the row itself, and until it runs -// this is the honest read of a stale one. +// mapStepStatus maps a step status; a step still running after its attempt +// ended reads interrupted. func mapStepStatus(status taskstate.StepStatus, inFlight bool) string { switch status { case taskstate.StepSucceeded: @@ -293,12 +268,8 @@ func mapStepStatus(status taskstate.StepStatus, inFlight bool) string { } } -// attemptStatus reads one status off an attempt's stages. The task's own record -// outranks the events: an attempt the daemon is executing right now is running -// whatever its events have recorded so far -- including the ones that have -// recorded no stages at all. Otherwise no stage is left RUNNING to read: every -// stage still open when the daemon is not executing this attempt is folded as -// interrupted, which is what the next case reports. +// attemptStatus derives an attempt's status from its stages and whether it is +// running now. func attemptStatus(stages []taskStageView, inFlight bool) string { if inFlight { return attemptStatusRunning diff --git a/internal/webui/api_tasks_changes.go b/internal/webui/api_tasks_changes.go index 95e2fb32a..67de26fbe 100644 --- a/internal/webui/api_tasks_changes.go +++ b/internal/webui/api_tasks_changes.go @@ -60,11 +60,8 @@ type capturePayload struct { task.ChangeStats } -// capturePayloadKeys is the exact key set one capture carries, derived from -// capturePayload's own json tags rather than restated beside them: the reader -// and the key set cannot disagree. A payload that renamed, dropped or added a -// key is refused, because reading it leniently is how a lost truncation marker -// becomes "not truncated" and a dropped file list becomes "nothing changed". +// capturePayloadKeys is capturePayload's JSON key set; payloads with any other +// key set are refused. var capturePayloadKeys = structKeys(reflect.TypeFor[capturePayload]()) // structKeys collects the JSON key names a struct declares, recursing into the @@ -114,15 +111,8 @@ func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) { writeJSON(w, taskChangesView{TaskID: t.ID, Attempt: attempt, Found: recorded, Captures: captures}) } -// capturedChanges folds a task's events into the captures recorded for one -// attempt, oldest first (events are read in insert order, which is capture -// order). -// -// recorded reports that the attempt has at least one capture event even when its -// payload could not be read: a capture that happened is provenance whether or not -// this read can decode it, and answering "no capture was recorded" would be a -// false statement about it. A payload that is absent, in a schema this build does -// not read, or otherwise malformed is skipped rather than failing the read. +// capturedChanges returns one attempt's change captures, oldest first. +// recorded is true when a capture event exists even if unreadable. func capturedChanges(evs []events.Event, attempt int) (captures []changeCaptureView, recorded bool) { captures = []changeCaptureView{} for _, e := range evs { @@ -139,12 +129,8 @@ func capturedChanges(evs []events.Event, attempt int) (captures []changeCaptureV return captures, recorded } -// decodeCapture reads one capture event. It reports false when the event carries -// no data, when its payload is not in the schema this build reads, when its key -// set is not exactly the one this reader declares, or when the payload is -// malformed. The totals are passed through as recorded and never recomputed from -// the file entries, because the producer's totals cover the full change set even -// when the entries were capped. +// decodeCapture reads one capture event, or reports false for a missing, +// unknown or malformed payload. func decodeCapture(e events.Event) (changeCaptureView, bool) { if len(e.Data) == 0 { return changeCaptureView{}, false diff --git a/internal/webui/api_tasks_debug.go b/internal/webui/api_tasks_debug.go index 30dc08b22..bd68aecca 100644 --- a/internal/webui/api_tasks_debug.go +++ b/internal/webui/api_tasks_debug.go @@ -7,18 +7,8 @@ import ( "github.com/samcharles93/archie-core/internal/events" ) -// taskDebugView is GET /api/tasks/{id}/debug: the stored task record as it is, -// and every event recorded for the task. It is deliberately not a generic -// store-dump route -- the task list is capped at 100 rows, so a page that wanted -// to show an older task's raw provenance had no row to join against. Nothing -// here is projected, filtered or re-spelled: reading it is the point. -// -// Events are UNFILTERED. A debug view that silently hid the events of other -// attempts would be worse than useless; each event carries its own attempt, so -// the operator sees everything and can attribute it. Attempt reports only which -// attempt the page had selected. No log payload is included: the log tab already -// serves it, and embedding it would duplicate a large body for no new -// information. +// taskDebugView is GET /api/tasks/{id}/debug: the raw task record and all of +// its events. type taskDebugView struct { TaskID int64 `json:"task_id"` Attempt int `json:"attempt"` diff --git a/internal/webui/api_tasks_logs.go b/internal/webui/api_tasks_logs.go index 260e73972..aec2f2ffb 100644 --- a/internal/webui/api_tasks_logs.go +++ b/internal/webui/api_tasks_logs.go @@ -11,24 +11,8 @@ import ( "github.com/samcharles93/archie-core/internal/logging" ) -// handleTaskLogs serves one task attempt's persisted log history, the same -// way handleLogs serves the daemon-wide log -- transport only, parsing -// belongs to the logging package. -// -// A request with no "attempt" query param defaults to the task's current -// Attempt from the store, since that is what a human or Archie's own chat -// tool means by "why did task N park?" almost every time: the most recent -// run, not an arbitrary earlier retry. -// -// Two outcomes are kept apart on purpose, because only one of them is about -// the operator's configuration. A process with no task-log reader cannot say -// anything about an attempt, so it reports disabled and the page explains that -// this process cannot read logs. A process WITH a reader and an attempt with -// no log file reports found=false, which the page states as no log recorded -// for the attempt. Collapsing the second into the first is what made the -// dashboard claim "task logging is optional and was not enabled for this run" -// for every attempt of every task in a deployment where logging is -// unconditional. +// handleTaskLogs serves one attempt's log history, defaulting to the current +// attempt. No reader reports disabled; no log file reports found=false. func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { id, attempt, ok := s.taskLogTarget(w, r) if !ok { @@ -79,14 +63,8 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { }) } -// handleTaskLogDownload serves one task attempt's log verbatim as a file -// download -- the log itself rather than a decoded view of it, because an -// operator who asks for a download wants to read it in their own tooling or -// hand it to someone else. -// -// The conditions stay apart here too. A process with no reader answers 503, -// not 404: "there is no log for this attempt" is a claim only a process that -// can look is in a position to make. +// handleTaskLogDownload serves one attempt's raw log as a download. No reader +// answers 503. func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { id, attempt, ok := s.taskLogTarget(w, r) if !ok { @@ -98,15 +76,8 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { return } - // Headers are set before the read because the body streams straight from - // the reader into the response: a log file is unbounded input, so - // buffering it to size the response would defeat the reason the reader - // streams at all. The attempt's own name is known up front. - // - // Everything after this point must therefore CLEAR them before writing an - // error, never add to them: a 404 still carrying `Content-Disposition: - // attachment` is a browser download of the error text under a .log - // filename, and the NDJSON type would misdescribe it too. + // The body streams, so headers are set first and must be cleared before + // writing an error. w.Header().Set("Content-Type", "application/x-ndjson") w.Header().Set("Content-Disposition", `attachment; filename="`+taskLogFilename(id, attempt)+`"`) @@ -134,14 +105,8 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { } } -// taskLogTarget resolves the {id} path value and the task it names, returning -// the attempt to read: the "attempt" query parameter when the request names -// one, otherwise the task's current Attempt. It answers the request itself and -// reports false when either step fails. -// -// The resolution itself is taskAttemptTarget's, shared with the attempt rail, -// the changed-files read and the debug view, so every per-attempt read of one -// task selects the same attempt for the same request. +// taskLogTarget resolves the task and attempt for a log read, answering the +// request itself on failure. func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) { t, attempt, ok := s.taskAttemptTarget(w, r) if !ok { @@ -194,12 +159,7 @@ func taskLogFilename(taskID int64, attempt int) string { return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log" } -// taskLogReader is the task-log read capability this process has, or nil when -// it has none. The seam is a narrow interface rather than a concrete registry -// so the same handlers serve both processes: the daemon holds a registry over -// its own state directory, the dashboard holds the State Store client. A -// consumer-owned seam is the difference between the dashboard degrading -// honestly and the dashboard opening another process's files. +// taskLogReader returns this process's task-log reader, or nil. func (s *Server) taskLogReader() TaskLogSource { if s == nil { return nil diff --git a/internal/webui/api_version.go b/internal/webui/api_version.go index 8c1762769..f5f1151eb 100644 --- a/internal/webui/api_version.go +++ b/internal/webui/api_version.go @@ -41,13 +41,8 @@ type componentVersionStatus struct { Status string `json:"status"` } -// versionStatusFor decides one component's status from its check-command -// claim (installed) against the version actually observed running (running, -// ok). Order matters: drift is checked before update_available because a -// claim the running system actively contradicts is a more fundamental -// problem than a newer release merely existing -- an operator who only -// sees "update available" on a component that is silently not running what -// it claims would look in the wrong place. +// versionStatusFor compares a component's claimed version with the running +// one. Drift is reported before update_available. func versionStatusFor(component releaseupdate.Component, running string, ok bool) string { if ok && component.Installed != "" && running != component.Installed { return statusDrift diff --git a/internal/webui/api_workflows.go b/internal/webui/api_workflows.go index 5242195c2..bd26e3120 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/api_workflows.go @@ -116,11 +116,8 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"ok": true, "task_id": taskID}) } -// enabledWorkflowInterface returns the interface workflow id declares, and -// whether it is defined and enabled for the caller's org. The interface is what -// the work-request handler checks a request's inputs against, so a task whose -// workflow declaration the request cannot satisfy is refused before it is -// admitted. +// enabledWorkflowInterface returns a workflow's declared interface and whether +// it is defined and enabled for the caller's org. func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) { entry, found, err := s.workflowEntry(ctx, id) if err != nil || !found { diff --git a/internal/webui/auth.go b/internal/webui/auth.go index e41a76342..9bc4617a3 100644 --- a/internal/webui/auth.go +++ b/internal/webui/auth.go @@ -42,13 +42,7 @@ const ( ) // IsLoopback reports whether a listen address is reachable only from this -// machine. -// -// Loopback binds need no token. Archie's agent already runs shell, write and -// edit tools on the host, so anyone with local access has the capability -// regardless; a lock here would only obstruct the operator. What a token -// protects is *exposure* -- an instance reachable from a network -- so that is -// the only case where one is required. +// machine. Loopback binds need no token. func IsLoopback(listen string) bool { host, _, err := net.SplitHostPort(strings.TrimSpace(listen)) if err != nil { @@ -62,12 +56,8 @@ func IsLoopback(listen string) bool { return ip != nil && ip.IsLoopback() } -// DashboardURL renders a listen address as a URL a human can actually open. -// -// A wildcard bind ("0.0.0.0:8484", ":8484", "[::]:8484") is a valid thing to -// listen on but not a valid thing to visit, and printing it verbatim gives the -// operator a link that goes nowhere. The host is substituted for localhost, -// which is correct for the machine reading the log. +// DashboardURL renders a listen address as an openable URL, with localhost +// for wildcard hosts. func DashboardURL(listen, token string) string { host, port, err := net.SplitHostPort(strings.TrimSpace(listen)) if err != nil { @@ -112,18 +102,9 @@ func LoadOrCreateToken(path string) (string, error) { return tok, nil } -// requireToken wraps h with the credential check this process is configured for. -// -// With an identity provider configured, the check is a provider-issued bearer -// token that resolves to a named identity, and a request that cannot produce one -// is refused. With no provider, the shared token is the gate, which is the -// frictionless loopback behaviour a single-operator instance wants. -// -// The token may arrive as ?t=... once; it is then moved into a -// SameSite=Strict, HttpOnly cookie and the caller redirected to the clean URL. -// One click on the URL archied logs is the whole setup. -// The token is read per request rather than captured when the handler is -// built, so a Server whose Token is set after Handler() is still protected. +// requireToken checks the request's credential: a provider-issued bearer +// token when an identity provider is configured, else the shared token. A +// ?t= token is moved into a cookie and the request redirected. func (s *Server) requireToken(h http.Handler) http.Handler { if s.Authenticate != nil { return s.requireIdentity(h) @@ -179,14 +160,8 @@ func (s *Server) requireToken(h http.Handler) http.Handler { }) } -// requireIdentity authenticates a request from a provider-issued bearer token and -// attaches the identity that token resolved to. -// -// Nothing about the caller is read from the request body, a header or a query -// parameter: the subject comes from the credential the provider signed, and the -// identity is the record that subject is bound to. That is why an agent's action -// can be attributed at all -- a caller cannot assert who it is, it can only -// present what the provider gave it. +// requireIdentity authenticates a provider bearer token and attaches the +// identity it resolves to. func (s *Server) requireIdentity(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { credential, ok := bearerCredential(r) @@ -203,12 +178,7 @@ func (s *Server) requireIdentity(h http.Handler) http.Handler { }) } -// bearerCredential reads the credential a request presented. An empty token is -// reported as absent rather than as a rejected one: there is nothing to verify. -// -// A browser cannot set a header on a navigation, so after the sign-in flow the -// provider's token is read from its cookie. That cookie holds the provider's -// credential, not an archie session: it is verified here on every request. +// bearerCredential returns the request's bearer token or provider cookie. func bearerCredential(r *http.Request) (string, bool) { const prefix = "Bearer " header := r.Header.Get("Authorization") @@ -308,11 +278,8 @@ func randomToken() (string, error) { return base64.RawURLEncoding.EncodeToString(raw), nil } -// refuseUnidentified answers a request archie could not attribute to an identity. -// -// The status is HTTP's own distinction: absent or unverifiable credentials are -// 401 and name the scheme, while a credential that verified for an identity that -// may not act is 403 -- the caller proved who it is and is still not allowed. +// refuseUnidentified answers 401 for missing or invalid credentials and 403 +// for an identity that may not act. func (s *Server) refuseUnidentified(w http.ResponseWriter, r *http.Request, err error) { w.Header().Set("Cache-Control", "no-store") allowed := errors.Is(err, identity.ErrIdentityInactive) || errors.Is(err, identity.ErrSubjectUnbound) @@ -327,11 +294,7 @@ func (s *Server) refuseUnidentified(w http.ResponseWriter, r *http.Request, err w.Header().Set("WWW-Authenticate", `Bearer realm="archie"`) } if !allowed && wantsDocument(r) { - // A browser that cannot authenticate is sent to sign in, when this - // instance has a sign-in flow: re-presenting a credential is the only - // thing that helps, and a shared-token paste page would be meaningless - // here. A refusal the caller cannot fix by signing in again -- a - // suspended identity -- is answered rather than redirected. + // Send browsers to sign in, unless signing in again cannot help. if s.Login != nil { http.Redirect(w, r, loginPath, http.StatusSeeOther) return @@ -365,16 +328,7 @@ func wantsDocument(r *http.Request) bool { return strings.Contains(r.Header.Get("Accept"), "text/html") } -// authPage answers an unauthenticated or rejected browser navigation with a page -// a human can act on: the access token is pasted once, the existing ?t= -// exchange sets the cookie, and the redirect lands on the dashboard. -// -// The page is deliberately self-contained. index.html, the bundle and every -// other asset sit behind requireToken too, so a page that referenced anything -// would render unstyled for exactly the visitor who needs it. -// -// The status stays 401: a login page served as 200 is cached, and reads as -// success to anything that only checks the status. +// authPage serves a self-contained 401 page for pasting the access token. func (s *Server) authPage(w http.ResponseWriter, reason string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") @@ -424,13 +378,8 @@ button { margin-top: 1rem; width: 100%; padding: 0.6rem 0.7rem; border: 0; borde ` -// sameOriginPath rebuilds a redirect target from a request path and raw -// query, collapsing any leading "//" down to a single slash first. -// -// A path of "//evil.example/x" is a valid http.Redirect Location that -// browsers treat as protocol-relative, sending the client off-host. Since -// this path is echoed back from the incoming request URL, an attacker can -// choose it, so it must never reach http.Redirect verbatim. +// sameOriginPath rebuilds a redirect target, collapsing a leading "//" so it +// cannot redirect off-host. func sameOriginPath(path, rawQuery string) string { // URL.Path has already been decoded by net/http. Treat backslashes as // separators before checking for a protocol-relative path, because browsers diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go index f85de41b6..bab25bf68 100644 --- a/internal/webui/authorize.go +++ b/internal/webui/authorize.go @@ -1,12 +1,3 @@ -// The access chain at the dashboard and API request path: the second of the two -// places that call the Authorizer. A request that carries an identity is -// assembled into a principal; the action and resource kind are derived from the -// route; the chain decides; a denial is recorded with the level that decided it -// and reported as forbidden without the reason. -// -// The shared token is the single-operator install's owner of the default org: -// the token principal is -// assembled here, not looked up, until principal credentials exist. package webui import ( @@ -172,11 +163,7 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res case matchSegment(path, "/api/sources/", "/secret"): return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true case matchPrefix(path, "/api/harness/terminal"): - // Opening the setup terminal captures the binding's OAuth tokens, so - // it is the update action on the secret. - // The shipped - // org-owner and org-admin policies grant it; the terminal is - // admin-only. + // Opening the setup terminal updates the binding's secret. return access.ActionUpdate, access.KindSecret, "", true case matchPrefix(path, "/api/harness/bindings"): return access.ActionRead, access.KindSecret, "", true diff --git a/internal/webui/config_schema.go b/internal/webui/config_schema.go index 01b302e95..c3bb9bcb8 100644 --- a/internal/webui/config_schema.go +++ b/internal/webui/config_schema.go @@ -1,19 +1,5 @@ package webui -// Configuration schema contract: descriptor types and -// hand-authored field/section metadata for the Configuration page. -// -// This is deliberately NOT a reflection-based schema over config.Config. -// internal/config/config.go's own package doc marks it "scheduled for -// dissolution: its types and methods are to be reassigned to the domains -// whose behaviour they describe" -- a generic schema-from-struct-tags -// mechanism would be built on a foundation this repo has already decided to -// remove. Every field below is already a deliberate ConfigView allowlist -// entry (see api_config.go's own comment on why that allowlist exists); this -// attaches a label to a value that was already vetted as safe to show, -// rather than inventing a new safety boundary. -// - // ConfigFieldType is how the frontend's generic renderer decides what // control to show for a field. FieldStructured fields (repositories, // models, providers) opt out of the generic renderer entirely and keep @@ -45,13 +31,8 @@ type ConfigField struct { LockedReason string `json:"locked_reason,omitempty"` // Options lists the valid values for a FieldEnum field. Options []string `json:"options,omitempty"` - // RestartRequired reports that changing this field through the - // dashboard will not take effect until archied restarts. Sourced from - // internal/app/archied/reload.go's reloadableFields/reloadableSubFields - // allowlist -- webui does not import that app-layer package (dependency - // direction: app -> infrastructure, not the reverse), so the answer is - // copied by hand per field below and must be re-checked whenever - // reload.go's allowlist changes. + // RestartRequired reports that a change takes effect only after a restart. + // Kept in step with internal/app/archied/reload.go by hand. RestartRequired bool `json:"restart_required"` } @@ -64,23 +45,8 @@ type ConfigSection struct { Fields []ConfigField `json:"fields"` } -// configFieldDescriptors is the hand-authored catalog: one entry per field -// ConfigView exposes today, in the section grouping settings.js already -// renders. Values and LockedReason are attached separately -// against a live ConfigView; this list is the -// data-independent half of the contract -- key, label, type, and the -// safety-relevant property (restart_required) that must be decided -// deliberately rather than defaulted. -// -// RestartRequired is set from internal/app/archied/reload.go as of this -// writing: -// - reloadableFields lists BotUser, BotEmail, Label, DiffCapLines, Budgets, -// Models -- all reloadable. -// - reloadableSubFields["Forge"] allows only Host -- Forge.Type requires a -// restart. -// - Web is absent from both allowlists entirely, so it requires a restart. -// - WorkDir and DatabaseURL are locked (configuration.DeniedKeys), not merely -// restart-required -- the dashboard cannot change them at all. +// configFieldDescriptors lists every ConfigView field with its section, +// label, type and whether it needs a restart. func configFieldDescriptors() []ConfigSection { return []ConfigSection{ { @@ -149,12 +115,7 @@ func configFieldDescriptors() []ConfigSection { } } -// configFieldValues maps each descriptor key to its current value out of a -// live ConfigView. A plain switch, not reflection, for the same reason -// configFieldDescriptors is hand-authored: every value here already passed -// through ConfigView's own secret-safe allowlist, so this only has to -// answer "which already-safe field does this key mean," never "is this -// field safe to show." +// configFieldValues maps each descriptor key to its value in view. func configFieldValues(view ConfigView) map[string]any { return map[string]any{ "bot_user": view.Identity.BotUser, @@ -176,13 +137,8 @@ func configFieldValues(view ConfigView) map[string]any { } } -// buildConfigSchema attaches a live ConfigView's values and locked reasons to -// the static descriptor catalog, producing the -// sections handleConfig returns to the dashboard. The catalog -// (configFieldDescriptors) and the per-request state (configFieldValues, -// view.Locked) are kept as two separate functions deliberately: one is -// data-independent and safe to unit-test as a fixed catalog, the other is -// "what does this specific running config say." +// buildConfigSchema attaches view's values and locked reasons to the +// descriptor catalog. func buildConfigSchema(view ConfigView) []ConfigSection { values := configFieldValues(view) sections := configFieldDescriptors() diff --git a/internal/webui/server.go b/internal/webui/server.go index 7d4455b00..f241bf902 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -26,12 +26,7 @@ type Server struct { Store storecontract.TaskStore Log *slog.Logger - // Steps lists one execution's recorded StepExecutions: - // the run detail's - // authoritative source, GET /api/tasks/{id}/attempts. Nil degrades the - // route to reporting no steps rather than folding stage_start/ - // stage_finish events, which tasks.stage used to back and no longer - // exists to fall back to. + // Steps lists an execution's recorded steps. Nil reports none. Steps storecontract.StepReader // ConfigSource supplies the configuration projection GET /api/config @@ -46,15 +41,7 @@ type Server struct { // LogFeed is the daemon diagnostic stream. It is separate from Events, // which contains persisted task lifecycle activity only. LogFeed *logging.Feed - // TaskLogs reads each task's persisted log output. Composition gives this - // process whichever implementation it can use: the daemon (whose state - // directory holds the files) its own *logging.TaskRegistry, and the - // dashboard process, which owns no such directory, the State Store client - // -- the read crosses a contract rather than opening a file. - // Nil means this process has no - // task-log capability at all, which the handlers report as disabled rather - // than as "the attempt has no log": those are different claims and only one - // of them is about configuration. + // TaskLogs reads task logs. Nil means this process cannot read them. TaskLogs TaskLogSource // Channels reports actual adapter lifecycle, independently of configuration. @@ -104,26 +91,17 @@ type Server struct { // stay frictionless -- see IsLoopback. Token string - // Authenticate resolves a credential a request presented to the identity - // that may act, and is the whole of the provider integration: verification - // and binding both live behind it. Non-nil replaces the shared token, so - // every request resolves to a named identity or is refused; nil keeps the - // shared-token gate for an instance with no provider configured. + // Authenticate resolves a presented credential to an identity. Non-nil + // replaces the shared token. Authenticate func(context.Context, string) (identity.Identity, error) - // Login drives the provider's browser flow, so a person can sign in and the - // dashboard learns who they are. Nil removes the sign-in routes, which is what - // an instance with no provider configured gets. It is separate from - // Authenticate because a caller may present a token without ever signing in - // through a browser -- an agent does exactly that. + // Login drives the provider's browser sign-in. Nil removes the sign-in + // routes. Login identity.LoginFlow - // Access evaluates the policy chain for each request. - // Optional: nil keeps the credential - // check as the whole gate -- the documented behaviour of an install that - // has not built the chain. Principals assembles the request principal - // from the acting identity; Denials records refusals. All three are - // wired together at composition or not at all. + // Access evaluates the policy chain, Principals builds the request principal + // and Denials records refusals. All three or none; nil leaves the credential + // check as the only gate. Access access.Authorizer Principals access.PrincipalSource Denials access.DenialStore @@ -142,17 +120,8 @@ type Server struct { // used to bound captureByID's scan window (api_mapping.go). // CaptureIntake is the write half's mount. CaptureMaxEvents int - // CaptureIntake serves POST /webhooks/capture/{source} on the bypass - // mux, alongside /healthz: capture must accept unauthenticated - // senders, so it cannot sit behind requireToken. The handler is owned - // by internal/infrastructure/captureintake.Receiver; this package only - // mounts the route and reads the rows back. The UI process composes - // it from the cutover change -- it is the only - // dashboard listener left, and a capture POST answered by the - // token-gated mux would leave intake with no owner. Nil removes the - // route, which is what a store without the capture contract gets: - // two listeners with the same intake authority is what the boundary - // forbids. + // CaptureIntake serves unauthenticated POST /webhooks/capture/{source}. Nil + // removes the route. CaptureIntake http.Handler // Mappings persists payload field mappings. @@ -175,12 +144,8 @@ type Server struct { // /api/sources route answer 503 and marks no binding unsigned. Sources storecontract.SourceStore - // HarnessSecrets reads each credential binding's captured OAuth token - // set, so the harness page can report whether a binding is configured, - // when it expires and which scopes it carries. - // The token values - // themselves never reach the browser. Optional: nil answers - // /api/harness/bindings 503 rather than claiming the org has none. + // HarnessSecrets reports each credential binding's OAuth token status, never + // the values. Nil answers 503. HarnessSecrets storecontract.HarnessSecretStore // HarnessTerminal opens the setup terminal, a duplex PTY session in an @@ -189,21 +154,14 @@ type Server struct { // dashboard consumes it over a contract and never links one. HarnessTerminal HarnessTerminal - // TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard- - // initiated update use the same post-restart notification route as a - // Telegram-initiated update. The web UI has no durable chat identity, so - // composition supplies an authorized Telegram recipient when one exists. - // When either value is empty, UpdateReportPath remains in use. + // TelegramUpdateReportPath and TelegramUpdateChatID route a dashboard + // update's post-restart report to Telegram. Either empty uses + // UpdateReportPath. TelegramUpdateReportPath string TelegramUpdateChatID int64 - // UpdateReportPath is where the update watchdog leaves the phase-2 - // outcome of a dashboard-initiated install for this process to relay on - // its next boot -- the webui counterpart of - // channels/telegram.Gateway.UpdateReportPath. Empty (the default unless - // composition wires it) means dashboard-initiated updates get no - // phase-2 report: the operator only sees the - // synchronous install result, never restart/health/version outcome. + // UpdateReportPath is where the update watchdog leaves a dashboard-initiated + // update's outcome for relay on next boot. Empty disables it. UpdateReportPath string // RunningVersions reports, per component ID (see releaseupdate.Report.Verify), @@ -379,12 +337,8 @@ func (s *Server) Handler() http.Handler { return top } -// handleHealthz is a liveness probe for local, unauthenticated callers -- -// most notably the update watchdog script, which polls it after restarting -// archied to decide whether the new version came up or the update needs to -// be rolled back (see scripts/archie-update-watchdog). It deliberately -// bypasses requireToken: the token protects the dashboard from remote -// access, not this process's own local restart tooling. +// handleHealthz is the unauthenticated liveness probe the update watchdog +// polls. func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok")) diff --git a/internal/webui/sse.go b/internal/webui/sse.go index e562087ec..85685e1fe 100644 --- a/internal/webui/sse.go +++ b/internal/webui/sse.go @@ -15,14 +15,7 @@ import ( // sseBacklogPageSize bounds one EventsSince fetch during catch-up. const sseBacklogPageSize = 200 -// sseNoiseKinds are event kinds published for internal wiring rather than -// for a dashboard viewer: turn_completed fires on every chat turn so -// input-driven curators can wake on it (see events.KindTurnCompleted), and -// carries no task correlation (TaskID is always 0, Detail a raw session ID) -// -- on a dashboard where "Live activity" is otherwise almost entirely -// task lifecycle events, it drowned the signal it sits next to. Curators -// read the Bus directly and are unaffected by excluding a kind here, at the -// SSE boundary, rather than at publish. +// sseNoiseKinds are event kinds not sent to the dashboard stream. var sseNoiseKinds = map[string]bool{ events.KindTurnCompleted: true, } @@ -174,11 +167,8 @@ func (s *sseStream) writeLive(update liveUpdate, id string) bool { return true } -// writeErrorComment reports a backlog fetch failure as an SSE comment. -// Comments are invisible to EventSource's own event parsing, but writing -// one and flushing before the handler returns is what actually reaches the -// client: it ends the response, which is what drives EventSource's -// reconnect. +// writeErrorComment writes a backlog failure as an SSE comment and ends the +// response, so the client reconnects. func (s *sseStream) writeErrorComment(err error) { _, _ = s.w.Write([]byte(":error " + err.Error() + "\n\n")) s.fl.Flush() @@ -207,15 +197,8 @@ func (s *sseStream) catchUp(ctx context.Context, target string) bool { } } -// sendPage sends every event in backlog newer than s.since, advancing it as -// it goes. reachedTarget reports whether target was reached mid-page -- -// stopping there is correct, since nothing beyond it is needed yet -- and -// ok reports whether every send succeeded. -// -// since advances past a filtered-out event (sseVisible false) exactly as it -// would for a sent one: EventsSince only ever returns events after since, so -// leaving since behind a filtered event would make the next catchUp refetch -// it forever. +// sendPage sends backlog events newer than s.since, advancing it past sent +// and filtered events. It stops at target. func (s *sseStream) sendPage(backlog []events.Event, target string) (reachedTarget, ok bool) { for _, e := range backlog { cursor := storecontract.EventCursor(e.At, e.ID) @@ -233,11 +216,7 @@ func (s *sseStream) sendPage(backlog []events.Event, target string) (reachedTarg return false, true } -// drain relays broadcast events after the initial catch-up. A broadcast can -// reach the client before its event lands in the durable store, so each one -// first fills any persisted gap ahead of it, then is delivered directly if -// catch-up did not already cover it -- both paths go through the same -// since-based deduplication. +// drain relays broadcasts after catch-up, filling any persisted gap first. func (s *sseStream) drain(ctx context.Context, conn <-chan liveUpdate, stale <-chan struct{}, logs <-chan logging.Entry) { for { select {