From deb58619f02f470386b05c42c2194ba3018d722d Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 20:13:57 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20Owner-only=20Send=20to=20=20on=20model-owned=20stage-tracker=20rows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row of a model-bound repository whose state the model hands to an agent profile offers the owner Send to in its menu, backed by the owner-only POST /api/workflows/dispatch: the item is read fresh, the agent resolved (a profile disabled for automatic dispatch still resolves), the issue claimed first and the agent kicked; the hand-off is recorded once the kick lands so the automatic pass does not repeat it. Audited workflow_dispatch; openapi and api-reference updated. Part of the drafter hand-off for cncf/techdocs#395. Signed-off-by: Andy Anderson --- ...added-workflow-dispatch-send-to-profile.md | 1 + dashboard/openapi.json | 89 ++++++++++++ src/cmd/hive/main.go | 1 + src/cmd/hive/workflow_dispatch.go | 43 ++++++ src/docs/api-reference/configuration.md | 1 + src/docs/design/workflow-models.md | 8 ++ src/docs/workflows/techdocs-assessment.md | 16 ++- src/pkg/config/workflow_dispatch.go | 13 +- src/pkg/config/workflow_dispatch_test.go | 5 + src/pkg/dashboard/api_workflows.go | 1 + src/pkg/dashboard/api_workflows_dispatch.go | 134 ++++++++++++++++++ .../dashboard/api_workflows_dispatch_test.go | 98 +++++++++++++ src/pkg/dashboard/deps.go | 5 + src/pkg/dashboard/stage_tracker_workflows.go | 32 ++++- ...tage_tracker_workflows_dispatch_ui_test.go | 72 ++++++++++ .../static-src/js/tracker-actions.js | 16 ++- .../static-src/js/tracker-workflows.js | 26 ++++ src/pkg/dashboard/static/index.html | 42 +++++- src/pkg/github/workflow_dispatch.go | 32 +++++ src/pkg/scheduler/workflow_dispatch.go | 8 +- 20 files changed, 627 insertions(+), 16 deletions(-) create mode 100644 changelog.d/added-workflow-dispatch-send-to-profile.md create mode 100644 src/pkg/dashboard/api_workflows_dispatch.go create mode 100644 src/pkg/dashboard/api_workflows_dispatch_test.go create mode 100644 src/pkg/dashboard/stage_tracker_workflows_dispatch_ui_test.go diff --git a/changelog.d/added-workflow-dispatch-send-to-profile.md b/changelog.d/added-workflow-dispatch-send-to-profile.md new file mode 100644 index 0000000000..8a84175843 --- /dev/null +++ b/changelog.d/added-workflow-dispatch-send-to-profile.md @@ -0,0 +1 @@ +- The Activity Monitor offers owners **Send to *profile*** on a row of a model-bound repository whose state the model hands to an agent profile (Send to techdocs-drafter on an accepted TechDocs request, Send to techdocs-verifier on a draft PR), backed by the owner-only `POST /api/workflows/dispatch`, which claims the issue, kicks the agent and records the hand-off (audited `workflow_dispatch`). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index ed80a0500b..d88229cf6b 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -38776,6 +38776,95 @@ } } }, + "/api/workflows/dispatch": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Send a model-owned item to its agent profile", + "description": "Owner only. The stage tracker's \"Send to \" on a row of a repository bound to a workflow model whose current state the model hands to an agent profile (cncf/techdocs#395: Accepted -> techdocs-drafter, Drafting -> techdocs-verifier). Reads the item fresh, resolves its model state and the hive agent that fills the profile (workflow.dispatch.profiles..agent; a profile disabled for automatic dispatch still resolves), takes the agent claim on an issue first, and kicks the agent with the dispatch prompt. Once the kick lands the hand-off is recorded in the dispatch log, so the automatic pass does not repeat it. Audited as workflow_dispatch.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "repo", + "number" + ], + "properties": { + "repo": { + "type": "string", + "description": "owner/repo" + }, + "number": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Kick delivered", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "sent" + ] + }, + "ref": { + "type": "string" + }, + "model": { + "type": "string" + }, + "state": { + "type": "string" + }, + "profile": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "result": { + "type": "object", + "description": "Tracker toast: action dispatched, outcome, next" + } + } + } + } + } + }, + "400": { + "description": "Body is not {repo, number}" + }, + "403": { + "description": "Not an owner" + }, + "404": { + "description": "The bound model does not hand the item's current state to a profile (or workflow.enabled is off)" + }, + "409": { + "description": "No enabled agent fills the profile, someone else holds the issue's claim, or the agent is busy" + }, + "502": { + "description": "The item could not be read or the kick failed" + }, + "503": { + "description": "Dispatch is not wired on this hive" + } + } + } + }, "/api/workflows/enabled": { "put": { "tags": [ diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index ed7f538ac7..df2d86a404 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1125,6 +1125,7 @@ func (b *boot) wireBootClosures() { }, WorkflowRepoFile: workflowRepoFile(func() *github.Client { return b.ghClient }), WorkflowProvisionLabels: workflowProvisionLabels(b.cfg, func() *github.Client { return b.ghClient }, b.logger), + WorkflowDispatchPrepare: workflowDispatchPrepare(b.cfg, func() *github.Client { return b.ghClient }, b.logger), WorkflowEmitChecks: workflowEmitChecks(b.cfg, func() *github.Client { return b.ghClient }), WorkflowClusterRunner: workflowClusterRunner(), WorkflowSpecLLM: newWorkflowSpecRunner(func() *config.Config { return b.cfg }), diff --git a/src/cmd/hive/workflow_dispatch.go b/src/cmd/hive/workflow_dispatch.go index 0c52bfc4c4..acc7c386fa 100644 --- a/src/cmd/hive/workflow_dispatch.go +++ b/src/cmd/hive/workflow_dispatch.go @@ -2,6 +2,8 @@ package main import ( "context" + "errors" + "fmt" "log/slog" "path/filepath" "sync" @@ -9,6 +11,7 @@ import ( "github.com/hivecommons/hive/pkg/claims" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/dashboard" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/scheduler" "github.com/hivecommons/hive/pkg/workflowmodel" @@ -339,3 +342,43 @@ func releaseWorkflowDispatch(k workflowDispatchKick) { workflowDispatchRT.clearP func workflowDispatchKickKey(msg scheduler.KickMessage) string { return msg.Agent + "\x00" + msg.Message } + +// workflowDispatchPrepare is the dashboard's WorkflowDispatchPrepare: the +// owner's "Send to " through the same steps as the automatic +// pass (fresh item read, model state, agent, claim first, prompt). The +// handler kicks the agent and calls Record once the kick landed, so the +// automatic pass does not hand the same state off again. +func workflowDispatchPrepare(cfg *config.Config, client func() *github.Client, logger *slog.Logger) func(ctx context.Context, repo string, number int, by string, ledger *claims.Ledger) (dashboard.WorkflowDispatchPlan, error) { + return func(ctx context.Context, repo string, number int, by string, ledger *claims.Ledger) (dashboard.WorkflowDispatchPlan, error) { + gh := client() + if cfg == nil || gh == nil { + return dashboard.WorkflowDispatchPlan{}, errors.New("GitHub client unavailable") + } + if !cfg.Workflow.Enabled { + return dashboard.WorkflowDispatchPlan{}, fmt.Errorf("%w (workflow.enabled is off)", dashboard.ErrWorkflowDispatchNotOwned) + } + d, ok, err := gh.WorkflowDispatchForRef(ctx, qualifyClaimRepo(cfg.Project.Org, repo), number) + if err != nil { + return dashboard.WorkflowDispatchPlan{}, err + } + if !ok { + return dashboard.WorkflowDispatchPlan{}, dashboard.ErrWorkflowDispatchNotOwned + } + agent, ok := cfg.WorkflowDispatchAgentForManual(d.Target.Profile) + if !ok { + return dashboard.WorkflowDispatchPlan{}, fmt.Errorf("%w: %s", dashboard.ErrWorkflowDispatchNoAgent, d.Target.Profile) + } + c := scheduler.WorkflowDispatchCandidate{Dispatch: d, Agent: agent, Key: scheduler.WorkflowDispatchKey(d, nil), ManualBy: by} + if !claimForWorkflowDispatch(cfg, ledger, c, logger) { + return dashboard.WorkflowDispatchPlan{}, dashboard.ErrWorkflowDispatchHeld + } + entry := scheduler.WorkflowDispatchEntry{Key: c.Key, Ref: d.Ref(), Profile: d.Target.Profile, State: d.State, Agent: agent, By: by} + return dashboard.WorkflowDispatchPlan{ + Ref: d.Ref(), Model: d.Model, State: d.State, Profile: d.Target.Profile, Agent: agent, + Message: scheduler.BuildWorkflowDispatchPrompt(c, cfg.Workflow.Dispatch.Profile(d.Target.Profile).PromptTemplate), + Record: func(at time.Time) { + recordWorkflowDispatchDelivered(cfg, workflowDispatchKick{Entry: entry}, at, logger) + }, + }, nil + } +} diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 9cf22c7829..5d3650b6b7 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -128,3 +128,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:278` | | `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:279` | | `PUT` | `/api/workflows/enabled` | Owner only | Turn model-based stage derivation (`workflow.enabled`, [#17620](https://github.com/hivecommons/hive/issues/17620)) on or off from the dashboard, for hosted hives with no `hive.yaml` access. Body `{enabled: bool}`; persists `hive.yaml`; the stage engine and tracker read the live flag so it applies on the next derivation pass without a restart. Turning on also provisions every bound repository's model labels now (`warnings[]` lists repositories that could not be provisioned; the next sweep retries). Returns `{enabled, changed, bindings[], warnings?[]}`. Audited `workflow_enabled` / `workflow_disabled`; `400` on a non-boolean body | `pkg/dashboard/api_workflows.go:29` | +| `POST` | `/api/workflows/dispatch` | Owner only | Send a model-owned item to its agent profile: the stage tracker's **Send to *profile*** on a row whose bound model hands its current state to a profile ([cncf/techdocs#395](https://github.com/cncf/techdocs/issues/395): Accepted → `techdocs-drafter`, Drafting → `techdocs-verifier`). Body `{repo, number}`. Reads the item fresh, resolves the agent (`workflow.dispatch.profiles..agent`; a profile disabled for automatic dispatch still resolves), takes the agent claim on an issue first, kicks the agent, and records the hand-off once the kick lands so the automatic pass does not repeat it. Returns `{status: "sent", ref, model, state, profile, agent, result}`. Audited `workflow_dispatch`; `404` when the model does not hand the state to a profile, `409` when no agent fills it, someone else holds the claim, or the agent is busy | `pkg/dashboard/api_workflows.go:30` | diff --git a/src/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index 08dc200556..5e83daf79e 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -728,6 +728,14 @@ Every eval cycle, with `workflow.enabled` on: `workflow-dispatch` audit row is recorded; a failed or deferred kick frees the key for the next pass, and an in-flight mark lapses after 30 minutes. +**Send to a profile.** The tracker payload's `workflows.repos[repo].dispatch` maps a stage +number to `{profile, state, kinds, reply}`; a row in such a state offers the owner **Send to *profile*** in its ⋯ menu (`stageTrackerWorkflowDispatchAction`), which posts +`POST /api/workflows/dispatch {repo, number}`. cmd/hive's `WorkflowDispatchPrepare` reads the +item fresh (`github.WorkflowDispatchForRef`), resolves the agent with +`Config.WorkflowDispatchAgentForManual` (a profile `disabled` for automatic dispatch still +resolves), claims an issue first and renders the prompt; the handler kicks the agent and, once +the kick lands, records the hand-off under the automatic key, so the pass does not repeat it. + The built-in prompt names the item, model, state and trigger, the state's guidance (`dispatch.instructions`, waiting reasons, column hint), the tools and outputs the grant allows, and the deliverable: for a PR-producing profile a (draft) pull request labeled with diff --git a/src/docs/workflows/techdocs-assessment.md b/src/docs/workflows/techdocs-assessment.md index 4afe0c32e4..02e2a3532b 100644 --- a/src/docs/workflows/techdocs-assessment.md +++ b/src/docs/workflows/techdocs-assessment.md @@ -257,11 +257,21 @@ hand-off, and `workflow.dispatch.enabled: false` stops them all (owned items sta from the generic lanes either way). `prompt_template` replaces the built-in prompt; see the design doc for its `${VAR}` placeholders. +### Send to drafter (owner) + +On the Activity Monitor, the **⋯** menu of a `cncf/techdocs` row in a dispatched state offers +**Send to techdocs-drafter** (an Accepted issue) or **Send to techdocs-verifier** (a draft PR in +Drafting). It is owner-only and runs the same hand-off on demand: it reads the item fresh, +resolves the agent (a profile set `disabled` for automatic dispatch still resolves), takes the +claim, kicks the agent and records the hand-off (`POST /api/workflows/dispatch`, audited +`workflow_dispatch`). Use it to restart after a discarded draft (a hand-off happens once per +issue and state on its own: retries are a person's choice, spec §5) or to run the verifier +without a `/verify` comment. + ### Starting the drafter by hand (fallback) -When no agent fills the profile, dispatch is off, or a discarded draft should be restarted (a -hand-off happens once per issue and state: retries are a person's choice, spec §5), a hive -owner starts the draft by hand: +When no agent fills the profile or the hive predates automatic dispatch, a hive owner starts the +draft by hand: 1. Check the request is accepted: `triage/accepted` is on the issue, applied by a maintainer with write access to `cncf/techdocs`, and the hive's workflow column shows **Accepted**. diff --git a/src/pkg/config/workflow_dispatch.go b/src/pkg/config/workflow_dispatch.go index 5fb64e1941..4613df81fa 100644 --- a/src/pkg/config/workflow_dispatch.go +++ b/src/pkg/config/workflow_dispatch.go @@ -66,6 +66,17 @@ func (c WorkflowDispatchConfig) Profile(name string) WorkflowDispatchProfile { // profile is disabled, or a configured agent does not exist (a typo never // falls back to another agent). func (c *Config) WorkflowDispatchAgent(profile string) (agent string, ok bool) { + return c.workflowDispatchAgent(profile, true) +} + +// WorkflowDispatchAgentForManual is WorkflowDispatchAgent for the owner's +// "Send to ": a profile disabled for automatic dispatch still +// resolves, since a person chose to hand the item off. +func (c *Config) WorkflowDispatchAgentForManual(profile string) (agent string, ok bool) { + return c.workflowDispatchAgent(profile, false) +} + +func (c *Config) workflowDispatchAgent(profile string, honorDisabled bool) (agent string, ok bool) { if c == nil { return "", false } @@ -74,7 +85,7 @@ func (c *Config) WorkflowDispatchAgent(profile string) (agent string, ok bool) { return "", false } set := c.Workflow.Dispatch.Profile(profile) - if set.Disabled { + if set.Disabled && honorDisabled { return "", false } usable := func(name string) bool { diff --git a/src/pkg/config/workflow_dispatch_test.go b/src/pkg/config/workflow_dispatch_test.go index 72eb548279..dbc356ef45 100644 --- a/src/pkg/config/workflow_dispatch_test.go +++ b/src/pkg/config/workflow_dispatch_test.go @@ -53,6 +53,11 @@ func TestWorkflowDispatchAgent(t *testing.T) { } }) } + disabled := base() + disabled.Workflow.Dispatch.Profiles = map[string]WorkflowDispatchProfile{"techdocs-verifier": {Disabled: true}} + if got, ok := disabled.WorkflowDispatchAgentForManual("techdocs-verifier"); !ok || got != "alpha" { + t.Fatalf("manual send to a disabled profile = %q %v; want alpha", got, ok) + } var nilCfg *Config if _, ok := nilCfg.WorkflowDispatchAgent("x"); ok { t.Fatal("nil config resolved an agent") diff --git a/src/pkg/dashboard/api_workflows.go b/src/pkg/dashboard/api_workflows.go index 735301c989..cfe04965a7 100644 --- a/src/pkg/dashboard/api_workflows.go +++ b/src/pkg/dashboard/api_workflows.go @@ -27,6 +27,7 @@ func (s *Server) registerWorkflowRoutes() { s.mux.HandleFunc("GET /api/workflows/bindings", s.handleWorkflowBindingsGet) s.mux.HandleFunc("PUT /api/workflows/bindings", s.handleWorkflowBindingPut) s.mux.HandleFunc("PUT /api/workflows/enabled", s.handleWorkflowEnabledPut) + s.mux.HandleFunc("POST /api/workflows/dispatch", s.handleWorkflowDispatch) s.mux.HandleFunc("GET /api/workflows/{name}/{version}", s.handleWorkflowGet) s.mux.HandleFunc("PUT /api/workflows/{name}/{version}", s.handleWorkflowSave) s.mux.HandleFunc("DELETE /api/workflows/{name}/{version}", s.handleWorkflowDelete) diff --git a/src/pkg/dashboard/api_workflows_dispatch.go b/src/pkg/dashboard/api_workflows_dispatch.go new file mode 100644 index 0000000000..a834a77c54 --- /dev/null +++ b/src/pkg/dashboard/api_workflows_dispatch.go @@ -0,0 +1,134 @@ +package dashboard + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/claims" +) + +// POST /api/workflows/dispatch: the owner's "Send to " on a +// stage-tracker row of a model-bound repository (cncf/techdocs#395). +// +// The automatic pass (cmd/hive/workflow_dispatch.go) hands an item to its +// model profile once per state. This is the same hand-off on demand: the +// restart after a discarded draft, a verifier pass without a `/verify`, or a +// profile turned off for automatic dispatch. cmd/hive prepares it through +// Dependencies.WorkflowDispatchPrepare (fresh item read, model state, agent, +// the agent claim, the prompt); the handler kicks the agent and, once the +// kick lands, records it in the dispatch log so the automatic pass does not +// repeat it. + +// WorkflowDispatchPlan is one prepared hand-off. +type WorkflowDispatchPlan struct { + Ref string + Model string + State string + Profile string + Agent string + Message string + // Record writes the delivered hand-off to the dispatch log. + Record func(at time.Time) +} + +// Errors WorkflowDispatchPrepare reports; the handler maps them to status +// codes. +var ( + // ErrWorkflowDispatchNotOwned: the repository is not bound to a model + // that hands the item's current state to a profile. + ErrWorkflowDispatchNotOwned = errors.New("the bound workflow model does not hand this item's current state to an agent profile") + // ErrWorkflowDispatchNoAgent: no enabled hive agent fills the profile. + ErrWorkflowDispatchNoAgent = errors.New("no enabled agent fills the profile (workflow.dispatch.profiles..agent)") + // ErrWorkflowDispatchHeld: someone else holds the issue's claim. + ErrWorkflowDispatchHeld = errors.New("the issue is claimed by someone else") +) + +func (s *Server) handleWorkflowDispatch(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s.deps == nil || s.deps.WorkflowDispatchPrepare == nil || s.deps.AgentMgr == nil { + jsonError(w, "workflow dispatch is not available on this hive", http.StatusServiceUnavailable) + return + } + var body struct { + Repo string `json:"repo"` + Number int `json:"number"` + } + if err := decodeBody(r, &body); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + body.Repo = strings.TrimSpace(body.Repo) + if body.Repo == "" || body.Number <= 0 { + jsonError(w, "body must be {\"repo\": \"owner/repo\", \"number\": N}", http.StatusBadRequest) + return + } + by := requestUser(r) + plan, err := s.deps.WorkflowDispatchPrepare(r.Context(), body.Repo, body.Number, by, s.IssueClaims()) + if err != nil { + jsonError(w, err.Error(), workflowDispatchStatus(err)) + return + } + if err := s.deps.AgentMgr.SendKick(plan.Agent, plan.Message); err != nil { + status := http.StatusBadGateway + if errors.Is(err, crux.ErrAgentBusy) { + status = http.StatusConflict + } + jsonError(w, fmt.Sprintf("kick %s: %v", plan.Agent, err), status) + return + } + if s.deps.Governor != nil { + s.deps.Governor.RecordKick(plan.Agent) + } + if plan.Record != nil { + plan.Record(time.Now()) + } + s.auditFromRequest(r, "workflow_dispatch", fmt.Sprintf("%s profile=%s state=%s model=%s", plan.Ref, plan.Profile, plan.State, plan.Model), plan.Agent) + jsonResponse(w, map[string]interface{}{ + "status": "sent", + "ref": plan.Ref, + "model": plan.Model, + "state": plan.State, + "profile": plan.Profile, + "agent": plan.Agent, + // result is the tracker's toast: the hand-off is done when the kick + // lands, so the row does not wait for a state change (hours away). + "result": map[string]interface{}{ + "action": workflowDispatchResultAction, + "outcome": fmt.Sprintf("Sent to %s (%s).", plan.Agent, plan.Profile), + "next": workflowDispatchNext(plan), + }, + }) +} + +// workflowDispatchResultAction is the tracker result action of a sent +// hand-off. +const workflowDispatchResultAction = "dispatched" + +func workflowDispatchNext(plan WorkflowDispatchPlan) string { + if plan.Profile == "" { + return "" + } + return "The " + plan.Profile + " agent works the item now; the row moves when its deliverable lands." +} + +func workflowDispatchStatus(err error) int { + switch { + case errors.Is(err, ErrWorkflowDispatchNotOwned): + return http.StatusNotFound + case errors.Is(err, ErrWorkflowDispatchNoAgent), errors.Is(err, ErrWorkflowDispatchHeld): + return http.StatusConflict + case errors.Is(err, context.DeadlineExceeded): + return http.StatusGatewayTimeout + } + return http.StatusBadGateway +} + +// workflowDispatchPrepareFunc is Dependencies.WorkflowDispatchPrepare. +type workflowDispatchPrepareFunc = func(ctx context.Context, repo string, number int, by string, ledger *claims.Ledger) (WorkflowDispatchPlan, error) diff --git a/src/pkg/dashboard/api_workflows_dispatch_test.go b/src/pkg/dashboard/api_workflows_dispatch_test.go new file mode 100644 index 0000000000..400b31194f --- /dev/null +++ b/src/pkg/dashboard/api_workflows_dispatch_test.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/cruxtest" + "github.com/hivecommons/hive/pkg/claims" +) + +// POST /api/workflows/dispatch is the owner's "Send to ": owner +// only, it kicks the prepared agent, records the hand-off only once the +// kick landed, audits it, and maps the prepare errors to status codes. +func TestWorkflowDispatchEndpoint(t *testing.T) { + s := workflowTestServer(t, true) + rt := cruxtest.NewRecorder() + s.deps.AgentMgr = rt + recorded := 0 + var gotBy string + s.deps.WorkflowDispatchPrepare = func(_ context.Context, repo string, number int, by string, _ *claims.Ledger) (WorkflowDispatchPlan, error) { + gotBy = by + switch number { + case 1: + return WorkflowDispatchPlan{Ref: repo + "#1", Model: "m@1", State: "accepted", Profile: "techdocs-drafter", Agent: "writer", Message: "draft it", + Record: func(time.Time) { recorded++ }}, nil + case 2: + return WorkflowDispatchPlan{}, ErrWorkflowDispatchNotOwned + case 3: + return WorkflowDispatchPlan{}, fmt.Errorf("wrapped: %w", ErrWorkflowDispatchHeld) + case 4: + return WorkflowDispatchPlan{}, ErrWorkflowDispatchNoAgent + } + return WorkflowDispatchPlan{}, errors.New("github down") + } + + body := map[string]any{"repo": "cncf/techdocs", "number": 1} + if rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", body, false); rec.Code != http.StatusForbidden { + t.Fatalf("non-owner: %d %s", rec.Code, rec.Body) + } + if recorded != 0 || len(rt.Calls()) != 0 { + t.Fatal("a non-owner request reached the dispatcher") + } + for _, bad := range []any{"{", map[string]any{"repo": "cncf/techdocs"}, map[string]any{"number": 1}} { + if rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", bad, true); rec.Code != http.StatusBadRequest { + t.Fatalf("bad body %v: %d", bad, rec.Code) + } + } + + rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", body, true) + if rec.Code != http.StatusOK { + t.Fatalf("send: %d %s", rec.Code, rec.Body) + } + var resp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp["status"] != "sent" || resp["agent"] != "writer" || resp["profile"] != "techdocs-drafter" || resp["ref"] != "cncf/techdocs#1" { + t.Fatalf("response %v", resp) + } + if recorded != 1 || gotBy != "andy" { + t.Fatalf("recorded %d by %q", recorded, gotBy) + } + kicked := false + for _, c := range rt.Calls() { + if c.Method == "SendKick" && len(c.Args) == 2 && c.Args[0] == "writer" && c.Args[1] == "draft it" { + kicked = true + } + } + if !kicked { + t.Fatalf("no kick to writer: %v", rt.Calls()) + } + + for number, want := range map[int]int{2: http.StatusNotFound, 3: http.StatusConflict, 4: http.StatusConflict, 5: http.StatusBadGateway} { + if rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", map[string]any{"repo": "cncf/techdocs", "number": number}, true); rec.Code != want { + t.Errorf("number %d: %d want %d (%s)", number, rec.Code, want, rec.Body) + } + } + + // A busy agent is a 409 and records nothing: the hand-off stays open. + rt.KickErr = crux.ErrAgentBusy + if rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", body, true); rec.Code != http.StatusConflict { + t.Fatalf("busy agent: %d", rec.Code) + } + if recorded != 1 { + t.Fatalf("a refused kick was recorded (%d)", recorded) + } + + s.deps.WorkflowDispatchPrepare = nil + if rec := wfReq(s, http.MethodPost, "/api/workflows/dispatch", body, true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("unwired: %d", rec.Code) + } +} diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index 8dcf1c9174..c573e7ea44 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -62,6 +62,11 @@ type Dependencies struct { // stage and model labels now, for PUT /api/workflows/enabled turning // derivation on. Nil leaves provisioning to the next sweep pass. WorkflowProvisionLabels func(ctx context.Context, repo string) error + // WorkflowDispatchPrepare prepares the owner's "Send to " for + // POST /api/workflows/dispatch (cncf/techdocs#395): reads the item, + // resolves its model state, the agent and the agent claim, and renders + // the prompt. Nil answers 503. + WorkflowDispatchPrepare workflowDispatchPrepareFunc // WorkflowEmitChecks proposes a newly bound model's declared checks to // the repository as .hive/workflows/checks.yml through the checks PR // (hivecommons/hive#18355), for PUT /api/workflows/bindings. Nil leaves diff --git a/src/pkg/dashboard/stage_tracker_workflows.go b/src/pkg/dashboard/stage_tracker_workflows.go index 9b3b3fe83f..71cb3cafad 100644 --- a/src/pkg/dashboard/stage_tracker_workflows.go +++ b/src/pkg/dashboard/stage_tracker_workflows.go @@ -36,7 +36,21 @@ type StageTrackerWorkflow struct { // RFC phase 4). The gate pill offers them after the built-in verbs; // each posts `/hive `. Absent when the model declares none. Replies map[string][]string `json:"replies,omitempty"` - Error string `json:"error,omitempty"` + // Dispatch maps a stage number (string key, as Replies) to the agent + // profile the model hands an item in that state to (cncf/techdocs#395). + // The tracker offers an owner "Send to " on such rows (POST + // /api/workflows/dispatch). Absent when the model dispatches nothing. + Dispatch map[string]StageTrackerWorkflowDispatch `json:"dispatch,omitempty"` + Error string `json:"error,omitempty"` +} + +// StageTrackerWorkflowDispatch is one state the model hands to a profile. +type StageTrackerWorkflowDispatch struct { + Profile string `json:"profile"` + State string `json:"state"` + Kinds []string `json:"kinds,omitempty"` + // Reply is the reply that starts it automatically ("" = on entry). + Reply string `json:"reply,omitempty"` } // StageTrackerWorkflowColumn is a column with the stage numbers it anchors, @@ -81,6 +95,22 @@ func stageTrackerWorkflowBlock(p *workflowmodel.Profile) StageTrackerWorkflow { out.Replies[strconv.Itoa(n)] = append([]string{}, verbs...) } } + if p.Name != hivedefault.Name { + for sid, t := range p.Dispatch { + st := p.States[sid] + if st == nil || st.Lifecycle.Number <= 0 { + continue + } + kinds := make([]string, 0, len(t.Kinds)) + for _, k := range t.Kinds { + kinds = append(kinds, string(k)) + } + if out.Dispatch == nil { + out.Dispatch = map[string]StageTrackerWorkflowDispatch{} + } + out.Dispatch[strconv.Itoa(st.Lifecycle.Number)] = StageTrackerWorkflowDispatch{Profile: t.Profile, State: sid, Kinds: kinds, Reply: t.Reply} + } + } return out } diff --git a/src/pkg/dashboard/stage_tracker_workflows_dispatch_ui_test.go b/src/pkg/dashboard/stage_tracker_workflows_dispatch_ui_test.go new file mode 100644 index 0000000000..995045b3e7 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflows_dispatch_ui_test.go @@ -0,0 +1,72 @@ +package dashboard + +import ( + "os/exec" + "strings" + "testing" +) + +// TestStageTrackerWorkflowDispatchWiring pins the owner's "Send to +// " on a model-bound row (cncf/techdocs#395): the ⋯ menu offers it +// from the payload's workflows.repos[repo].dispatch block and it posts to +// POST /api/workflows/dispatch. +func TestStageTrackerWorkflowDispatchWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `function stageTrackerWorkflowDispatchOf(item, workflows)`, + `function stageTrackerWorkflowDispatchAction(item, workflows, ctx)`, + `stageTrackerWorkflowDispatchAction(item, _stageTracker.workflows, ctx)`, + `case 'wf-dispatch': return { url: '/api/workflows/dispatch', body: { repo: item.repo, number: n } };`, + `result.action === 'dispatched') stageTrackerClearPending(pend);`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing workflow-dispatch wiring %q", want) + } + } +} + +// The pure helpers under node: an Accepted issue of a bound repository +// offers Send to techdocs-drafter, enabled for an owner only; a draft PR in +// Drafting offers the verifier and names its /verify; an unbound +// repository, a state the model keeps for people, a row of the wrong kind +// and a PR drawn under its issue offer nothing. +func TestStageTrackerWorkflowDispatchNode(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed") + } + html := indexHTML(t) + script := `const assert = require('assert'); +` + jsFunc(t, html, "stageTrackerWorkflowOf") + jsFunc(t, html, "stageTrackerWorkflowDispatchOf") + jsFunc(t, html, "stageTrackerWorkflowDispatchAction") + ` +const td = { name: 'cncf-techdocs-assessment', version: 'curated-2026.11.2', + columns: [{ id: 'accepted', label: 'Accepted', states: ['accepted'], numbers: [20] }, { id: 'drafting', label: 'Drafting', states: ['drafting'], numbers: [70] }], + dispatch: { '20': { profile: 'techdocs-drafter', state: 'accepted', kinds: ['issue'] }, '70': { profile: 'techdocs-verifier', state: 'drafting', kinds: ['pr'], reply: '/verify' } } }; +const workflows = { default: { name: 'hive-default', version: '1', columns: [{ id: 'open', label: 'Open', states: ['open'], numbers: [] }] }, repos: { 'cncf/techdocs': td } }; + +const accepted = { repo: 'cncf/techdocs', kind: 'issue', number: 395, stage: 20 }; +assert.deepStrictEqual(stageTrackerWorkflowDispatchOf(accepted, workflows), { profile: 'techdocs-drafter', state: 'accepted', reply: '' }); +const owner = stageTrackerWorkflowDispatchAction(accepted, workflows, { owner: true }); +assert.strictEqual(owner.id, 'wf-dispatch'); +assert.strictEqual(owner.label, 'Send to techdocs-drafter'); +assert.strictEqual(owner.enabled, true); +assert.strictEqual(owner.hint, 'hand off now'); +const reader = stageTrackerWorkflowDispatchAction(accepted, workflows, { owner: false }); +assert.strictEqual(reader.enabled, false); +assert.strictEqual(reader.why, 'Needs the owner role'); + +const draft = { repo: 'cncf/techdocs', kind: 'pr', number: 400, stage: 70 }; +const v = stageTrackerWorkflowDispatchAction(draft, workflows, { owner: true }); +assert.strictEqual(v.label, 'Send to techdocs-verifier'); +assert.strictEqual(v.hint, 'also runs on /verify'); + +assert.strictEqual(stageTrackerWorkflowDispatchOf({ repo: 'cncf/other', kind: 'issue', number: 1, stage: 20 }, workflows), null, 'unbound repo'); +assert.strictEqual(stageTrackerWorkflowDispatchOf({ repo: 'cncf/techdocs', kind: 'issue', number: 2, stage: 10 }, workflows), null, 'a state kept for people'); +assert.strictEqual(stageTrackerWorkflowDispatchOf({ repo: 'cncf/techdocs', kind: 'pr', number: 3, stage: 20 }, workflows), null, 'wrong kind'); +assert.strictEqual(stageTrackerWorkflowDispatchOf(Object.assign({ via_pr: true }, draft), workflows), null, 'PR drawn under its issue'); +assert.strictEqual(stageTrackerWorkflowDispatchOf(accepted, null), null, 'no workflows block'); +assert.strictEqual(stageTrackerWorkflowDispatchAction(accepted, null, { owner: true }), null); +` + if out, err := runNodeStdin(node, script); err != nil { + t.Fatalf("node workflow dispatch fixture failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index a2694bd76f..a6ae96474a 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -36,6 +36,7 @@ 'decide:close-superseded': 'Close as superseded by', 'decide:close-wontfix': "Close as won't-fix", 'decide:close-read': 'Close now', 'decide:close-deferred': 'Close now', 'decide:close-issue': 'Close issue', + 'wf-dispatch': 'Send to agent', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', 'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker', @@ -207,13 +208,13 @@ // repaint showGHAuthState schedules settles the pills within the tick. function stageTrackerActionCtx(repo) { const governor = (window._lastStatus && window._lastStatus.governor) || null; - if (stageTrackerAuthPending()) return { user: true, canHold: null, canHuman: true, authPending: true, login: '', governor }; + if (stageTrackerAuthPending()) return { user: true, canHold: null, canHuman: true, owner: true, authPending: true, login: '', governor }; const role = window._hiveRole || 'read'; const owner = dashboardRoleAtLeast(role, 'owner'); const user = !!window._hiveUser || owner; if (typeof ensureRepoHoldPermission === 'function') ensureRepoHoldPermission(repo); const canHold = owner || (typeof repoHoldPermissionKnown === 'function' && repoHoldPermissionKnown(repo)) ? true : (user ? null : false); - return { user, canHold, canHuman: user && dashboardRoleAtLeast(role, 'merger'), login: String(window._hiveUser || ''), governor }; + return { user, canHold, canHuman: user && dashboardRoleAtLeast(role, 'merger'), owner, login: String(window._hiveUser || ''), governor }; } // Pure: the item a row's "Decide…" acts on. A PR parked at 085 (the // "Needs human decision" pill on the Merge queue column) decides itself; @@ -497,6 +498,10 @@ ? { id: 'release', label: 'Release hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, sep: triage && !target } : { id: 'hold', label: 'Hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, sep: triage && !target }); out.push({ id: 'retry', label: 'Re-evaluate now', hint: 'rescan', enabled: true, why: '' }); + // A model-bound row whose state the model hands to an agent profile + // (cncf/techdocs#395): the owner can send it now. + const wfDispatch = typeof stageTrackerWorkflowDispatchAction === 'function' && typeof _stageTracker !== 'undefined' && _stageTracker ? stageTrackerWorkflowDispatchAction(item, _stageTracker.workflows, ctx) : null; + if (wfDispatch) out.push(wfDispatch); if (!has('needs-human')) out.push({ id: 'needs-human', label: 'Mark needs-human…', enabled: !!ctx.canHuman, why: ctx.canHuman ? '' : STAGE_TRACKER_WHY_ROLE }); if (item.kind === 'issue' && String(item.state || '').toLowerCase() !== 'closed') out.push(Object.assign({ id: 'decide:close-issue', label: 'Close issue…', danger: true, hint: 'only this issue · completed' }, stageTrackerActionAllowed('decide:close-issue', ctx))); out.push({ id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link', sep: true }); @@ -1345,6 +1350,7 @@ case 'hold': return { url: '/api/repos/' + seg + '/items/' + n + '/hold', body: { held: true, type } }; case 'release': return { url: '/api/repos/' + seg + '/items/' + n + '/hold', body: { held: false, type } }; case 'retry': return { url: '/api/repos/rescan', body: {}, once: true }; + case 'wf-dispatch': return { url: '/api/workflows/dispatch', body: { repo: item.repo, number: n } }; case 'needs-human': return { url: '/api/review/pipeline/' + seg + '/' + n + '/send-to-human', body: { reason: payload.comment || ('flagged from the activity monitor for ' + stageTrackerRefOf(item)) } }; case 'accept-triage': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/accept-triage', body: {} }; case 'blocker:recheck': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/blocker/recheck', body: {} }; @@ -1560,7 +1566,7 @@ // the tracker's to show, so "Approving…" must not linger beside // the ✓ waiting for it (#15103). if (result.action === 'refused') stageTrackerNoteActionFailure(it, id, result.outcome || 'refused'); - if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT || result.action === 'refused' || result.action === 'approved') stageTrackerClearPending(pend); + if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT || result.action === 'refused' || result.action === 'approved' || result.action === 'dispatched') stageTrackerClearPending(pend); else { if (typeof stageTrackerDecidePending === 'function') stageTrackerDecidePending(pend, result, stageTrackerItemByKey(_stageTracker, stageTrackerTargetKey(result.target))); // Closed / merged: the terminal caption stays on the chevron @@ -2298,7 +2304,7 @@ function stageTrackerMergeBannerMs() { return stageTrackerToastMs('info') * STAGE_TRACKER_MERGE_BANNER_FACTOR; } const STAGE_TRACKER_ACTING_MAX_MS = 180000; const STAGE_TRACKER_ACTING_CAPTIONS = { - 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', + 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'wf-dispatch': 'Sending to the agent…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-deferred': 'Closing…', 'decide:close-issue': 'Closing…', 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', @@ -2306,7 +2312,7 @@ 'gate:decide': 'Sending your decision…', 'gate:request-changes': 'Requesting changes…', 'gate:confirm-sentinel': 'Confirming safe…', }; const STAGE_TRACKER_ACTION_WORDS = { - adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', + adopted: 'adopted', approved: 'approved', dispatched: 'sent to its agent', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', merged: 'merged', 'queued-for-merge': 'queued for merge — hive merges it on its next pass once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', held: 'held', released: 'hold released', 'sentinel-confirmed': 'sentinel confirmed safe', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: 'no effect yet', diff --git a/src/pkg/dashboard/static-src/js/tracker-workflows.js b/src/pkg/dashboard/static-src/js/tracker-workflows.js index 5004eac845..2e7fbf5e78 100644 --- a/src/pkg/dashboard/static-src/js/tracker-workflows.js +++ b/src/pkg/dashboard/static-src/js/tracker-workflows.js @@ -51,6 +51,32 @@ return Array.isArray(list) ? list.map(v => String(v || '').trim()).filter(Boolean) : []; } + // Pure: the agent profile the bound model hands the item's current + // state to (`workflows.repos[repo].dispatch` keyed by stage number, + // cncf/techdocs#395), or null: an unbound repository, a PR row drawn + // under its issue, a state the model keeps for people, or a state that + // does not apply to the row's kind. + function stageTrackerWorkflowDispatchOf(item, workflows) { + if (!item || item.via_pr) return null; + const wf = stageTrackerWorkflowOf({ workflows }, item.repo); + if (!wf || !wf.dispatch) return null; + const t = wf.dispatch[String(Number(item.stage) || 0)]; + if (!t || !t.profile) return null; + const kind = item.kind === 'pr' ? 'pr' : 'issue'; + if (Array.isArray(t.kinds) && t.kinds.length && t.kinds.indexOf(kind) < 0) return null; + return { profile: String(t.profile), state: String(t.state || ''), reply: String(t.reply || '') }; + } + + // Pure: the ⋯ menu entry for that hand-off — owner only, since it + // kicks an agent with a prompt. + function stageTrackerWorkflowDispatchAction(item, workflows, ctx) { + const t = stageTrackerWorkflowDispatchOf(item, workflows); + if (!t) return null; + const owner = !!(ctx && ctx.owner); + const hint = t.reply ? 'also runs on ' + t.reply : 'hand off now'; + return { id: 'wf-dispatch', label: 'Send to ' + t.profile, hint, profile: t.profile, enabled: owner, why: owner ? '' : 'Needs the owner role' }; + } + // Pure: a model verb as the pill prints it — "approve analysis" → // "Approve analysis". function stageTrackerWorkflowReplyLabel(verb) { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 9c3e2ce72b..935998360c 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -20507,6 +20507,32 @@

Where to get help

return Array.isArray(list) ? list.map(v => String(v || '').trim()).filter(Boolean) : []; } + // Pure: the agent profile the bound model hands the item's current + // state to (`workflows.repos[repo].dispatch` keyed by stage number, + // cncf/techdocs#395), or null: an unbound repository, a PR row drawn + // under its issue, a state the model keeps for people, or a state that + // does not apply to the row's kind. + function stageTrackerWorkflowDispatchOf(item, workflows) { + if (!item || item.via_pr) return null; + const wf = stageTrackerWorkflowOf({ workflows }, item.repo); + if (!wf || !wf.dispatch) return null; + const t = wf.dispatch[String(Number(item.stage) || 0)]; + if (!t || !t.profile) return null; + const kind = item.kind === 'pr' ? 'pr' : 'issue'; + if (Array.isArray(t.kinds) && t.kinds.length && t.kinds.indexOf(kind) < 0) return null; + return { profile: String(t.profile), state: String(t.state || ''), reply: String(t.reply || '') }; + } + + // Pure: the ⋯ menu entry for that hand-off — owner only, since it + // kicks an agent with a prompt. + function stageTrackerWorkflowDispatchAction(item, workflows, ctx) { + const t = stageTrackerWorkflowDispatchOf(item, workflows); + if (!t) return null; + const owner = !!(ctx && ctx.owner); + const hint = t.reply ? 'also runs on ' + t.reply : 'hand off now'; + return { id: 'wf-dispatch', label: 'Send to ' + t.profile, hint, profile: t.profile, enabled: owner, why: owner ? '' : 'Needs the owner role' }; + } + // Pure: a model verb as the pill prints it — "approve analysis" → // "Approve analysis". function stageTrackerWorkflowReplyLabel(verb) { @@ -24558,6 +24584,7 @@

All labels

'decide:close-superseded': 'Close as superseded by', 'decide:close-wontfix': "Close as won't-fix", 'decide:close-read': 'Close now', 'decide:close-deferred': 'Close now', 'decide:close-issue': 'Close issue', + 'wf-dispatch': 'Send to agent', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', 'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker', @@ -24729,13 +24756,13 @@

All labels

// repaint showGHAuthState schedules settles the pills within the tick. function stageTrackerActionCtx(repo) { const governor = (window._lastStatus && window._lastStatus.governor) || null; - if (stageTrackerAuthPending()) return { user: true, canHold: null, canHuman: true, authPending: true, login: '', governor }; + if (stageTrackerAuthPending()) return { user: true, canHold: null, canHuman: true, owner: true, authPending: true, login: '', governor }; const role = window._hiveRole || 'read'; const owner = dashboardRoleAtLeast(role, 'owner'); const user = !!window._hiveUser || owner; if (typeof ensureRepoHoldPermission === 'function') ensureRepoHoldPermission(repo); const canHold = owner || (typeof repoHoldPermissionKnown === 'function' && repoHoldPermissionKnown(repo)) ? true : (user ? null : false); - return { user, canHold, canHuman: user && dashboardRoleAtLeast(role, 'merger'), login: String(window._hiveUser || ''), governor }; + return { user, canHold, canHuman: user && dashboardRoleAtLeast(role, 'merger'), owner, login: String(window._hiveUser || ''), governor }; } // Pure: the item a row's "Decide…" acts on. A PR parked at 085 (the // "Needs human decision" pill on the Merge queue column) decides itself; @@ -25019,6 +25046,10 @@

All labels

? { id: 'release', label: 'Release hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, sep: triage && !target } : { id: 'hold', label: 'Hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, sep: triage && !target }); out.push({ id: 'retry', label: 'Re-evaluate now', hint: 'rescan', enabled: true, why: '' }); + // A model-bound row whose state the model hands to an agent profile + // (cncf/techdocs#395): the owner can send it now. + const wfDispatch = typeof stageTrackerWorkflowDispatchAction === 'function' && typeof _stageTracker !== 'undefined' && _stageTracker ? stageTrackerWorkflowDispatchAction(item, _stageTracker.workflows, ctx) : null; + if (wfDispatch) out.push(wfDispatch); if (!has('needs-human')) out.push({ id: 'needs-human', label: 'Mark needs-human…', enabled: !!ctx.canHuman, why: ctx.canHuman ? '' : STAGE_TRACKER_WHY_ROLE }); if (item.kind === 'issue' && String(item.state || '').toLowerCase() !== 'closed') out.push(Object.assign({ id: 'decide:close-issue', label: 'Close issue…', danger: true, hint: 'only this issue · completed' }, stageTrackerActionAllowed('decide:close-issue', ctx))); out.push({ id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link', sep: true }); @@ -25867,6 +25898,7 @@

All labels

case 'hold': return { url: '/api/repos/' + seg + '/items/' + n + '/hold', body: { held: true, type } }; case 'release': return { url: '/api/repos/' + seg + '/items/' + n + '/hold', body: { held: false, type } }; case 'retry': return { url: '/api/repos/rescan', body: {}, once: true }; + case 'wf-dispatch': return { url: '/api/workflows/dispatch', body: { repo: item.repo, number: n } }; case 'needs-human': return { url: '/api/review/pipeline/' + seg + '/' + n + '/send-to-human', body: { reason: payload.comment || ('flagged from the activity monitor for ' + stageTrackerRefOf(item)) } }; case 'accept-triage': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/accept-triage', body: {} }; case 'blocker:recheck': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/blocker/recheck', body: {} }; @@ -26082,7 +26114,7 @@

All labels

// the tracker's to show, so "Approving…" must not linger beside // the ✓ waiting for it (#15103). if (result.action === 'refused') stageTrackerNoteActionFailure(it, id, result.outcome || 'refused'); - if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT || result.action === 'refused' || result.action === 'approved') stageTrackerClearPending(pend); + if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT || result.action === 'refused' || result.action === 'approved' || result.action === 'dispatched') stageTrackerClearPending(pend); else { if (typeof stageTrackerDecidePending === 'function') stageTrackerDecidePending(pend, result, stageTrackerItemByKey(_stageTracker, stageTrackerTargetKey(result.target))); // Closed / merged: the terminal caption stays on the chevron @@ -26820,7 +26852,7 @@

All labels

function stageTrackerMergeBannerMs() { return stageTrackerToastMs('info') * STAGE_TRACKER_MERGE_BANNER_FACTOR; } const STAGE_TRACKER_ACTING_MAX_MS = 180000; const STAGE_TRACKER_ACTING_CAPTIONS = { - 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', + 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'wf-dispatch': 'Sending to the agent…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-deferred': 'Closing…', 'decide:close-issue': 'Closing…', 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', @@ -26828,7 +26860,7 @@

All labels

'gate:decide': 'Sending your decision…', 'gate:request-changes': 'Requesting changes…', 'gate:confirm-sentinel': 'Confirming safe…', }; const STAGE_TRACKER_ACTION_WORDS = { - adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', + adopted: 'adopted', approved: 'approved', dispatched: 'sent to its agent', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', merged: 'merged', 'queued-for-merge': 'queued for merge — hive merges it on its next pass once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', held: 'held', released: 'hold released', 'sentinel-confirmed': 'sentinel confirmed safe', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: 'no effect yet', diff --git a/src/pkg/github/workflow_dispatch.go b/src/pkg/github/workflow_dispatch.go index 5e74aa2a91..53cca44778 100644 --- a/src/pkg/github/workflow_dispatch.go +++ b/src/pkg/github/workflow_dispatch.go @@ -229,3 +229,35 @@ func IsDispatchReply(body, reply string) bool { } return strings.EqualFold(strings.TrimRight(fields[0], ".:,;!"), strings.TrimSpace(reply)) } + +// WorkflowDispatchForRef reads repo#number fresh from the forge and reports +// whether its bound model hands the item's current state to a profile. It +// is the owner's "Send to " path: one GET, so the decision is made +// on the item as it is now rather than on the last enumeration. Issue +// coverage is not known from a single read; the issue's state is derived as +// if no pull request covered it. +func (c *Client) WorkflowDispatchForRef(ctx context.Context, repo string, number int) (WorkflowDispatch, bool, error) { + if c == nil || c.client == nil || number <= 0 { + return WorkflowDispatch{}, false, nil + } + if !c.WorkflowModelFor(repo).Dispatches() { + return WorkflowDispatch{}, false, nil + } + owner, name := c.splitRepo(repo) + it, _, err := c.client.Issues.Get(ctx, owner, name, number) + if err != nil { + return WorkflowDispatch{}, false, fmt.Errorf("reading %s/%s#%d: %w", owner, name, number, err) + } + if it.GetState() != "open" { + return WorkflowDispatch{}, false, nil + } + labels := issueLabelNames(it.Labels) + if it.IsPullRequest() { + d, ok := c.WorkflowDispatchForPR(PullRequest{Repo: repo, Number: number, Title: it.GetTitle(), Labels: labels, + Draft: it.GetDraft(), UpdatedAt: it.GetUpdatedAt().Time, URL: it.GetHTMLURL()}) + return d, ok, nil + } + d, ok := c.WorkflowDispatchForIssue(Issue{Repo: repo, Number: number, Title: it.GetTitle(), Labels: labels, + UpdatedAt: it.GetUpdatedAt().Time, URL: it.GetHTMLURL()}) + return d, ok, nil +} diff --git a/src/pkg/scheduler/workflow_dispatch.go b/src/pkg/scheduler/workflow_dispatch.go index a6191cca5d..2fc3076d08 100644 --- a/src/pkg/scheduler/workflow_dispatch.go +++ b/src/pkg/scheduler/workflow_dispatch.go @@ -103,6 +103,9 @@ type WorkflowDispatchCandidate struct { Agent string Key string Trigger *github.DispatchReply + // ManualBy names the person who sent the item from the dashboard + // ("Send to "); empty for an automatic hand-off. + ManualBy string } // WorkflowDispatchSkip is an item the plan did not hand off, and why. @@ -209,7 +212,10 @@ func BuildWorkflowDispatchPrompt(c WorkflowDispatchCandidate, template string) s func workflowPromptVars(c WorkflowDispatchCandidate) map[string]string { d := c.Dispatch trigger := "entering the state" - if c.Trigger != nil { + switch { + case c.ManualBy != "": + trigger = fmt.Sprintf("%s, a hive owner, from the dashboard (Send to %s)", c.ManualBy, d.Target.Profile) + case c.Trigger != nil: trigger = fmt.Sprintf("`%s` from %s (%s)", d.Target.Reply, c.Trigger.Author, c.Trigger.URL) } label := d.Target.StateLabel From ce914ff9f3f30763756dab69aab4ca7c5c8ed91b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 20:39:05 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20Register=20the=20kicked=20ag?= =?UTF-8?q?ent=20in=20the=20dispatch=20endpoint=20test=20runtime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/api_workflows_dispatch_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/pkg/dashboard/api_workflows_dispatch_test.go b/src/pkg/dashboard/api_workflows_dispatch_test.go index 400b31194f..04c5b30d27 100644 --- a/src/pkg/dashboard/api_workflows_dispatch_test.go +++ b/src/pkg/dashboard/api_workflows_dispatch_test.go @@ -20,6 +20,7 @@ import ( func TestWorkflowDispatchEndpoint(t *testing.T) { s := workflowTestServer(t, true) rt := cruxtest.NewRecorder() + rt.Add("writer", "writer", crux.StateIdle) s.deps.AgentMgr = rt recorded := 0 var gotBy string