Documentation
¶
Overview ¶
Package dashboard will host the operator dashboard's HTTP server (G5.2, a different lane's work — replacing orchestrator/dashboard/server.py's FastAPI app). Today it only exposes the built web/ SPA as an fs.FS for that server to mount later.
The `go:embed` directive below cannot reach outside its own package directory, so web/vite.config.ts points build.outDir directly at internal/dashboard/dist/build — `pnpm build` in web/ writes straight here, with no go:generate copy step to keep in sync (the alternative considered and rejected; see docs/brainstorm/go-migration-notes/ sonnet-2.md). dist/README.md is the one file tracked directly under dist/: go:embed requires at least one matching file to compile at all, and vite's emptyOutDir is scoped to dist/build/ only, so it never touches dist/README.md across rebuilds.
Index ¶
- Constants
- Variables
- func HashToken(token string) string
- func SPA() (fs.FS, error)
- func SPAHandler(files fs.FS) http.Handler
- type Activity
- type Config
- type FindingsDesk
- type Options
- type Portfolio
- type PortfolioOptions
- type PortfolioProject
- type Profile
- type ProjectFlow
- type Server
- func (s *Server) BoundAddr() string
- func (s *Server) Handler() http.Handler
- func (s *Server) Ready() <-chan struct{}
- func (s *Server) Serve(ctx context.Context) error
- func (s *Server) StartTunnel(provider string) (tunnel.State, error)
- func (s *Server) StopTunnel() (tunnel.State, error)
- func (s *Server) TunnelLinks() (dashboard, portal string)
- type StateReader
- type TunnelOptions
- type UnavailableProject
- type Verdict
- type Welcome
- type WelcomeFlow
Constants ¶
const ( DefaultHost = "127.0.0.1" DefaultPort = 7420 )
Defaults for the listener, matching Python's.
const StakeholderPathPrefix = "/stakeholder"
StakeholderPathPrefix is where `both` mode switches into stakeholder rules.
Variables ¶
var DefaultStakeholderRoutes = []string{
"stakeholder_summary_json",
"stakeholder_snapshot_json",
"stakeholder_evidence_media",
"api_tunnel_capabilities",
"api_whoami",
"api_docs_list",
"api_docs_content",
"spa",
}
DefaultStakeholderRoutes is the allow-list a stakeholder session gets when config.yaml does not override it, by route name.
Ported from `DEFAULT_STAKEHOLDER_ROUTES`, with each entry's reason kept because every one of them is a decision about what a client may see:
- stakeholder_summary_json — the summary the whole profile exists for.
- api_tunnel_capabilities — the SPA has to know whether to draw the tunnel panel BEFORE it has a token, so this one also skips the token check.
- api_whoami — the SPA hides operator-only nav from the profile. The profile is not a secret; the token is.
- api_docs_list / api_docs_content — PRD and spec markdown are project artefacts a stakeholder is meant to read. No route has these names today (Python's /api/docs was not ported; #549): the list is policy, not inventory, so a docs route registered under them is the client's by design, and a name with no route opens nothing. Removing them is the owner's call, not a cleanup.
- stakeholder_evidence_media — the walk-through videos the portal shows (#520), served only when the operator opted in (evidence.publish.video).
- spa — the static shell and every client-side route under it.
var ErrPortfolioProfile = errors.New(
"dashboard: --portfolio is operator-only; a stakeholder profile has no " +
"portfolio view, and the per-project routes keep their own tokens")
ErrPortfolioProfile is what a non-operator profile gets.
Functions ¶
func HashToken ¶
HashToken returns the hex-encoded SHA-256 digest of a stakeholder token, or "" for an empty token — the one sentinel meaning "no token configured" everywhere in this package, so callers never need a second check for it.
Only the hash is ever persisted (state.Backend.SetStakeholderToken) or compared against (Config.decide): the plaintext exists only in the operator's hands and in the single moment `orch dashboard token rotate` prints it. This is also what a supplied token is hashed through before being compared to the stored/configured hash — see Server's request-time resolution in server.go.
func SPA ¶
SPA returns the built web/ SPA, rooted at its index.html, as an fs.FS ready for an HTTP file server to mount. Before `pnpm build` has run in web/ (or `make build`), dist/build/ doesn't exist yet — SPA itself still succeeds (fs.Sub does no I/O), but any read against the result fails; see TestSPARequiresABuild.
func SPAHandler ¶
SPAHandler serves the built SPA: the file when it exists, the shell when it does not.
The fallback is what makes client-side routing work. `/kanban` is not a file in the build — it is a route React resolves once the shell has loaded — so a plain file server answers 404 for every deep link and for every refresh on a page the user navigated to. Serving index.html instead hands the URL to the router, which is what a static host's "SPA mode" does.
Only GET and HEAD fall back. A POST to a path that does not exist is a caller doing something wrong, and answering it with a page of HTML would turn that into a confusing 200 instead of a 404.
This handler is deliberately NOT gated — see access.go for why the static surface is public by default and what bug that prevents.
Types ¶
type Activity ¶
type Activity struct {
// Offset is where the next read starts; pass it back as ?offset=.
Offset int64 `json:"offset"`
Steps []providers.Step `json:"steps"`
// Exists is false until the task's first dispatch writes its log.
Exists bool `json:"exists"`
}
Activity is one read of a dispatch log: the endpoint's payload, and what `orch tui` tails for the selected task, so both show the same steps.
type Config ¶
type Config struct {
Profile Profile
// Token is the shared secret from config.yaml/--token, in plaintext.
// Empty under the operator profile, where nothing is gated. Never
// itself compared against a supplied token — see TokenHash — and kept
// only as the source `orch dashboard` hashes when the database has no
// row for this project yet (see cli's newDashboardCmd).
Token string
// TokenHash is the resolved effective hash AT STARTUP: from the
// database (state.Backend.StakeholderToken) if this project has ever
// rotated one, else HashToken(Token). Consumed by Validate() and the
// startup banner, which both need an answer before a listener opens.
// NOT consulted by decide() at request time — Server resolves it fresh
// on every gated request instead (see server.go's expectedTokenHash),
// so a rotation takes effect on an already-running dashboard with no
// restart. This field would go stale the moment that happens, which is
// exactly why request handling does not read it.
TokenHash string
// TokenSource is "database" or "config.yaml" — which one produced
// TokenHash at startup. Empty when TokenHash is empty. Informational
// only: the startup banner and `orch dashboard token show` print it,
// nothing gates on it.
TokenSource string
// StakeholderRoutes is the allow-list, by route name or path prefix.
StakeholderRoutes []string
// ShowSpendToStakeholder gates every spend figure in
// `/stakeholder/summary` — the total, the daily series, and the spend
// sentence of the executive summary. Off by default ("spend is
// sensitive", per the key's own comment in Python). Bug 22 of this port
// was that the flag governed only `/api/budget/summary` while the page a
// client actually opens carried spend regardless.
ShowSpendToStakeholder bool
// SummaryLanguage picks the executive summary's wording, "es" or "en".
// Empty means "es", matching config's own default.
SummaryLanguage string
// Host and Port are where the server listens.
Host string
Port int
}
Config is what the dashboard needs to decide who sees what, and where to listen.
Built from config.yaml's `dashboard:` block. The stakeholder allow-list is the one field with no home in `internal/config` yet: it is a dashboard concern and nothing else reads it, so it is resolved here from the same block rather than widening the shared config struct for one consumer.
func FromConfig ¶
FromConfig builds a dashboard Config from a loaded project config.
An unknown profile is an error rather than a silent fallback to operator. Falling back would turn `profile: stakholder` — a typo in a file someone edited to *restrict* access — into a dashboard with no auth at all, and the symptom is a page that works, which is exactly the wrong feedback.
func (Config) Validate ¶
Validate reports a configuration that cannot serve what it claims to.
Separate from FromConfig because the two answer different questions: that one asks "is this file well-formed", this one asks "will this deployment work". A stakeholder profile with no token parses fine and then 401s every request including its own token form, which is a server nobody can use — and the operator finds out from a blank page rather than from startup.
type FindingsDesk ¶ added in v0.31.0
FindingsDesk is what the Findings page reads the queue from and sends through (#536): the project's state and the operator's gh. A nil Filer keeps the page read-only.
type Options ¶
type Options struct {
// Paths locates the project this dashboard reports on.
Paths config.Paths
// Static serves the built SPA. Required: a dashboard with no UI is a
// JSON API nobody asked for, and a nil handler here would 404 the shell
// while every API route worked — a failure that looks like a broken
// build rather than a missing argument.
Static http.Handler
// State is the backend the read endpoints query.
State StateReader
// Tunnel is optional: the zero value means "no tunnel configured", and
// `/api/tunnel/status` then answers 404 rather than pretending idle.
Tunnel TunnelOptions
// Logger defaults to slog.Default().
Logger *slog.Logger
// Portal is the client portal bundle (publish.Bundle), served at
// /stakeholder/. Optional: nil keeps /stakeholder/ a data prefix only.
Portal fs.FS
// Snapshot builds the document the portal reads at
// /stakeholder/data.json — the same builder `orch publish` uses, passed
// in so this package never assembles one of its own.
Snapshot func(ctx context.Context) (snapshot.Snapshot, error)
// EvidenceMedia finds the file behind an evidence video or poster the
// snapshot names (evidence/<hash>/<name>, #520); nil serves none.
EvidenceMedia func(sitePath string) (string, bool)
// Version is the running orch's; Releases lists orch's releases for the
// What's new page (update.Check behind the CLI). nil Releases: update
// checks are off.
Version string
Releases func(ctx context.Context) ([]update.Release, error)
// CLILatest reads an agent CLI's latest release for the Tools page
// (#448); nil leaves it out. update.check_clis: false also does.
CLILatest doctor.LatestFunc
// Steer is what the stop and note endpoints write through (#356). Nil
// turns them off. It is the one write the dashboard makes to the
// project's state, and it writes requests the run acts on — the same
// ones `orch task stop|note` write.
Steer *project.Steer
// Editor is what the task add and edit endpoints write tasks.json
// through (v0.22) — the same editor as `orch task add|edit|set`. Nil
// turns them off.
Editor *project.TaskEditor
// Knowledge is what the Knowledge page reads the lessons from and writes
// them through (#453) — the same editor as `orch knowledge add|rm`. Nil
// turns its endpoints off.
Knowledge *knowledge.Editor
// Curate is `orch knowledge curate` (#452), for the Knowledge page's
// Curate now: it writes what the curation would do and cost to out, then
// asks confirm with its task id; true dispatches it and Curate returns
// when that run ends. Nil turns its endpoints off.
Curate func(ctx context.Context, out io.Writer, confirm func(taskID string) bool) error
// Findings is the agents' reports about orch, for the Findings page to
// preview and send (#536). Nil shows an empty queue.
Findings *FindingsDesk
// Flow is the welcome page's plan and apply steps for this project, and
// a run of it (#548) — internal/cli's, the same ones `orch start` takes.
// Nil turns /api/flow off.
Flow ProjectFlow
}
Options are what New needs beyond the config.
type Portfolio ¶
type Portfolio struct {
// contains filtered or unexported fields
}
Portfolio serves N projects from one process (G8.5 / F3.6).
What it is, and what it is not ¶
It is a front door, not a second dashboard. Each project keeps its own *Server — its own Paths, its own state backend, its own profile and its own rotated token — and `/p/<project_id>/…` hands the request to that Server's handler with the prefix stripped. So a project configured as `stakeholder` still demands its own token on its own routes, resolved against its own row (G8.2/F3.3), and this type contains no second copy of the access model to drift from the first.
The only route it serves itself is `/api/portfolio`: the one question that cannot be answered by any single project.
Operator only, and what that does and does not mean ¶
NewPortfolio refuses a non-operator profile. The portfolio row for a project is NOT gated by that project's token — it is the operator's own view of their own machine, and the boundary is the same one a single-project operator dashboard has today: the listener, bound to 127.0.0.1 by default. "Operator only" here means "there is no stakeholder portfolio", not "authenticated". Worth stating because the asymmetry is real: a project whose per-project routes require a token still contributes counters to a row that does not.
func NewPortfolio ¶
func NewPortfolio(opts PortfolioOptions) (*Portfolio, error)
NewPortfolio wires the front door over already-opened projects.
func (*Portfolio) Handler ¶
Handler exposes the mux, for a test that wants the routes without a listener.
type PortfolioOptions ¶
type PortfolioOptions struct {
Config Config
Projects []PortfolioProject
// Static is the SPA, mounted at "/" and at every /p/<id>/ prefix's root.
Static http.Handler
Logger *slog.Logger
// Now defaults to time.Now.
Now func() time.Time
}
PortfolioOptions is everything NewPortfolio needs.
The caller opens the projects. This package does not glob directories or open databases for the same reason `New` takes a StateReader instead of a path: the filesystem and the driver belong to internal/cli, and a test here should not need either.
type PortfolioProject ¶
type PortfolioProject struct {
// ID is the project id, and the path segment under /p/. Must be unique
// across the set — NewPortfolio refuses a duplicate rather than letting
// the second registration silently shadow the first.
ID string
// Server serves this project's routes. Never Serve()d: only its
// Handler() is used, so it is a bundle of routes plus a gate rather than
// a listener.
Server *Server
}
PortfolioProject is one opened project: its identity and the server that owns its routes.
type Profile ¶
type Profile string
Profile decides how much of the dashboard a request may see.
const ( // ProfileOperator is the default: no auth, everything visible. The // operator is assumed to be on localhost. ProfileOperator Profile = "operator" // ProfileStakeholder gates every data route behind a token and an // allow-list. This is what a shared tunnel URL runs as. ProfileStakeholder Profile = "stakeholder" // ProfileBoth serves the operator surface unguarded and applies the // stakeholder rules only under /stakeholder/. Mixed-mode local use. ProfileBoth Profile = "both" )
type ProjectFlow ¶ added in v0.31.0
type ProjectFlow interface {
State() any
Plan(idea string) error
Apply(ctx context.Context) error
Run() error
}
ProjectFlow is the welcome page's plan and apply steps for the project this dashboard serves, and a run of its plan (#548). internal/cli implements it with the functions `orch start` and the welcome page use; this package only puts them on HTTP. Each step returns an error the page shows as is.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the dashboard's HTTP surface.
Ported from `create_app` in `orchestrator/dashboard/server.py`, minus FastAPI: the routes are plain handlers on a `http.ServeMux` and the access model is a decorator rather than middleware (see access.go for why).
What this file owns is the plumbing — listening, routing, shutting down. Which routes exist is routes.go; who may reach them is access.go; serving the SPA is spa.go, which this never wraps.
func (*Server) BoundAddr ¶
BoundAddr is the address the listener actually got, which is not cfg.Addr() when the configured port is 0.
func (*Server) Handler ¶
Handler exposes the mux, for a test that wants to drive the routes without a listener.
func (*Server) Ready ¶
func (s *Server) Ready() <-chan struct{}
Ready is closed once Serve has finished with the listener — bound, or failed to bind. A waiter is released either way: a channel that only closes on success is a deadlock the first time a port is taken.
After it closes, BoundAddr is the address, or "" if the listen failed.
func (*Server) Serve ¶
Serve listens and blocks until the context is cancelled, then shuts down gracefully.
The listener is opened before this returns control, so a caller that prints the URL prints one that already answers. Python's own runner prints it before uvicorn binds, which produces a URL that 404s for the first moment somebody is fast enough to click it.
func (*Server) StartTunnel ¶
StartTunnel raises a share of this server's bound port through provider ("" for the default, cloudflared) and mints fresh link tokens. The URL arrives asynchronously; TunnelLinks has it once the provider prints it.
func (*Server) StopTunnel ¶
StopTunnel stops the tunnel and invalidates its link tokens.
func (*Server) TunnelLinks ¶
TunnelLinks returns the full-dashboard and client-portal links, each with its own token, once the tunnel has a URL. Empty when there is no URL yet, or no tokens (a tunnel adopted from a previous process: restart it).
type StateReader ¶
type StateReader interface {
// StatusReader is the live status of every task, which every task-shaped
// view overlays on tasks.json (project.Hydrate). The dashboard asks it
// through project (Runtime, RuntimeOf, DoneRuntime) and filters in
// memory where it needs the unfiltered totals in the same response.
project.StatusReader
// AllEvents is the event log across every task, oldest first. n <= 0
// means all of it. The log view reads the tail; the per-task figures
// (hours spent, last updated) are derived from the whole thing.
AllEvents(ctx context.Context, n int) ([]project.Event, error)
// AllSpend is every spend row newer than `since`, across every backend.
// The metrics page asks for all of history; the budget summary asks for
// today.
AllSpend(ctx context.Context, since time.Time) ([]project.Spend, error)
// SpendSince is one provider's rolling window, and it is here because
// `budget.Gate` takes exactly this method: the dashboard reports the same
// numbers the dispatch guardrail enforces by asking the same gate, rather
// than by recomputing a window that could drift from it.
SpendSince(ctx context.Context, backend string, since time.Time) ([]project.Spend, error)
// CountDoneLastNDays is the numerator of velocity: tasks that finished
// inside the window.
CountDoneLastNDays(ctx context.Context, days int) (int, error)
// ProviderStates is which providers the operator turned off, for the
// Providers and quota page.
ProviderStates(ctx context.Context) ([]project.ProviderState, error)
// LastEventByTask is the newest event per task id, which is how a blocked
// task explains itself. The sprint panel asks only about the blocked ones.
LastEventByTask(ctx context.Context, taskIDs []string) (map[string]project.Event, error)
// LatestEventID is where a live tail starts, so it carries only what
// happens after the client connected.
LatestEventID(ctx context.Context) (int64, error)
// EventsSince is what that tail polls, keyed on the row id rather than on
// a timestamp — see state.EventsSince for why.
EventsSince(ctx context.Context, afterID int64, limit int) ([]project.Event, error)
// RunReader (LatestRun) and InFlightDispatches are what /api/now shows as
// the run and the agents working in it; project.LatestRun says whether
// the project ever ran.
project.RunReader
InFlightDispatches(ctx context.Context) ([]project.Dispatch, error)
// Attempts is every finished attempt, for /api/agent-metrics (#538).
Attempts(ctx context.Context) ([]project.Attempt, error)
// StakeholderToken is this project's rotated stakeholder token hash, if
// any (G8.2/F3.3) — resolved fresh on every gated request (see
// expectedTokenHash) rather than once at startup, so
// `orch dashboard token rotate` takes effect without a restart.
StakeholderToken(ctx context.Context) (tokenHash string, rotatedAt time.Time, ok bool, err error)
}
StateReader is the slice of the state backend the dashboard reads.
Narrow and read-only by construction: reads never go through a writer, and the profile guard rests on that. The local operator's edits (task edits, steering, review, config, knowledge, findings) are separate routes that go through the same functions as the CLI commands, never through this interface and never by driving the engine (CHECKLIST rule 13).
type TunnelOptions ¶
type TunnelOptions struct {
Enabled bool
// Command overrides the binary (tests); empty means cloudflared.
Command string
// URLParseTimeoutS is tunnel.url_parse_timeout_s.
URLParseTimeoutS int
Manager *tunnel.Manager
}
TunnelOptions is the tunnel half of Options, kept as its own type so a caller that has no tunnel says so by leaving one field alone.
type UnavailableProject ¶
type UnavailableProject struct {
}
UnavailableProject is a directory the caller could not open.
Reported rather than dropped: an operator whose glob matched a directory that is not an orch project needs to see which one and why, not a portfolio that is quietly one project short.
type Welcome ¶
type Welcome struct {
// contains filtered or unexported fields
}
Welcome is what `orch dashboard` serves outside a project: the SPA's /welcome page and the four steps behind it — pick a folder, plan, apply, run. The steps are internal/cli's (the same ones `orch start` takes); this type only puts them on HTTP, behind the gates every operator write has.
There is no token: no project holds one yet. The boundary is the loopback listener, which NewWelcome insists on, plus a Host and an Origin check, so neither another machine nor a web page in the operator's browser can drive it.
func NewWelcome ¶
NewWelcome wires the welcome routes over flow, the SPA at every other path.
func (*Welcome) Handler ¶
Handler exposes the routes, for a test that wants them without a listener.
type WelcomeFlow ¶
type WelcomeFlow interface {
State() any
Project(ctx context.Context, path string, gitInit bool) error
Plan(idea string) error
Apply(ctx context.Context) error
Run() error
}
WelcomeFlow is the welcome page's steps. Each mutating step returns an error the page shows as is; State is what the page polls.
Source Files
¶
- access.go
- activity.go
- bindgate.go
- budgetroutes.go
- ciroute.go
- config.go
- configroute.go
- estimateroutes.go
- events.go
- findingsroutes.go
- flowroutes.go
- knowledgeroutes.go
- metricroutes.go
- metrics.go
- notfound.go
- nowroutes.go
- portal.go
- portfolio.go
- portfolioserver.go
- providerroutes.go
- quotaroutes.go
- readroutes.go
- receiptroutes.go
- releases.go
- reviewroutes.go
- routersuggestroutes.go
- routes.go
- server.go
- settingsroutes.go
- skillsroutes.go
- spa.go
- spahandler.go
- sprint.go
- sprintroutes.go
- stakeholderroutes.go
- steerroutes.go
- stream.go
- taskeditroutes.go
- testsroutes.go
- tokenhash.go
- toolsroutes.go
- tunnelroutes.go
- usage.go
- usageroutes.go
- view.go
- welcome.go