feat: add live conversation cards and task discussions
38 files changed,
+2,412
−160
docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+128 −0internal/equipo/app.go+4 −2internal/equipo/conversation/cards.go+95 −0internal/equipo/conversation/coordinator_application.go+2 −0internal/equipo/conversation/handlers.go+103 −0internal/equipo/conversation/job_deadlines.go+75 −0internal/equipo/{live_changes.go => conversation/job_live.go}+2 −2internal/equipo/conversation/live.go+142 −0internal/equipo/conversation/models.go+1 −1internal/equipo/conversation/settings.go+144 −0internal/equipo/conversation/store.go+3 −1internal/equipo/conversation/tools.go+12 −1internal/equipo/conversation/views.go+166 −0internal/equipo/conversation_handlers.go+51 −0internal/equipo/coordinator.go+2 −5internal/equipo/copy.go+101 −1internal/equipo/handlers.go+5 −0internal/equipo/live.go+21 −68internal/equipo/planning/application.go+77 −0internal/equipo/planning/handlers.go+194 −0internal/equipo/planning/views.go+187 −0internal/equipo/plans.go+12 −59internal/equipo/render.go+2 −2internal/equipo/static/equipo.css+13 −0internal/equipo/task_views.go+40 −15internal/equipo/templates/conversation.html+9 −0internal/equipo/templates/conversation_card.html+44 −0internal/equipo/templates/coordinator.html+13 −0internal/equipo/templates/plan.html+41 −0internal/equipo/templates/settings.html+1 −0internal/equipo/templates/task.html+1 −1internal/equipo/templates/task_card.html+2 −2internal/equipo/templates/thread.html+10 −0internal/plan3test/conversation_browser_test.go+264 −0internal/plan3test/conversation_forms_test.go+218 −0internal/plan3test/conversation_layout_browser_test.go+99 −0internal/plan3test/conversation_layout_test.go+17 −0internal/plan3test/conversation_native_test.go+111 −0
CI failed — run details
Intent
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index d01c1282..f9ccb930 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -2987,3 +2987,131 @@ All nine entries are in `internal/equipo/copy.go`, individually marked `COPY REV |
| | `preferences.delete` | Delete | |
| | `preferences.team_rule` | Team rules take precedence. Preferences guide instructions but cannot grant approval, spending or account access. | |
| | `preferences.source_unavailable` | Source message unavailable | |
| + |
| + |
| +## Task 9 |
| + |
| +Status: DONE_WITH_CONCERNS. Live conversation cards, scriptless plan/discussion forms, question cards and coordinator settings are implemented. Pending copy and upstream live-use gates remain. |
| + |
| +Task 9 adds private live conversations, shared automatic task discussions, a scriptless plan editor, clarification cards and coordinator settings. HTML mutations use the same application operations as the Store facade. The composer remains outside the live region. |
| + |
| +The conversation has no project picker. Task cards name the selected project and link to correction. Ambiguous project questions now persist up to 32 choices from the coordinator's authorized project list, with the existing free-text reply available as well. Routing a message copies it to the task thread and leaves a short reference with a thread link. The latest 50 messages are shown by default, with scoped snapshot links for earlier messages; current cards remain visible independently of message pagination. |
| + |
| +Plan forms carry explicit request IDs and revisions. They support instruction and model edits, labeled connection choices, adding/removing eligible steps and numbered reordering. Started steps are visibly locked and remain guarded by Task 2's application operation. Project correction preserves the existing replacement-task behavior. Project approval settings and personal overrides have separate forms and revisions. Members can read shared plans and set their own overrides without receiving write authority over the plan. |
| + |
| +Cards show the current revision, project, playbook, selected model/account/reason, actual steps and approval state. Task, Journey and specialist pages link to discussion and use persisted plan steps. Empty, not-yet-selected outbox values are accepted as unset; malformed nonempty values remain errors. Completed recommendations/investigations use the answer-delivered state and expose no merge action. |
| + |
| +Coordinator settings expose the person's binding, reset, owner-only personal coordinator limits and the typed landing preference. Missing limits are shown as a setup state. Context-limit and filtered-context cards expose retry/reset actions; the waiting card names and links the blocking task. Clarifications retain their persisted expiry, generation, state and revision checks. Native questions keep their original routes, typed response shape and attempt/fence/expiry checks; conversation cards link to those native forms. |
| + |
| +Private live topics hash team, person and resource; shared thread topics hash team and thread. Authorization resolves persisted membership and associations on every check. Transactional triggers collect message, card, plan, step, question and coordinator changes; notifications run after commit. Clarification/native expiry notifications are restored on startup. Initial snapshots use the pinned live middleware and rendering APIs. The no-hub fallback renders usable pages and forms. |
| + |
| +The day theme/sidebar shell, tokens.css and theme.css are retained. App styling is confined to equipo.css. Values and badges do not wrap, secondary text truncates, and cards use a full hairline border with tint. Vendored assets and README prose are unchanged. |
| + |
| +### Test-first evidence |
| + |
| +Before implementation, the exact required command exited 1: |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversation(Scriptless|NoProject|Live|Question|Layout)' -count=1`. |
| +The meaningful missing interface was `conversation.ConversationTopic`. The initial test draft also tried to use browser-only harness functions without the browser tag; those fixtures were separated into a tagged file before implementation. An unused test import was removed. |
| + |
| +The first implementation run exposed an empty ambiguity-options list and a fixture that tried to create the same seed task twice. The fixture was corrected; the authorized project options were implemented. Expanded tests then found a live fragment/template-name mismatch, a read operation that incorrectly reused plan-write authority for personal settings, and the existing plan renderer's rejection of unset selections. Those were fixed. |
| + |
| +Additional focused red runs, all exit 1 before their fixes: |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversationLiveRecentAndCards$' -count=1`: “recent message or earlier live card missing”. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversationLiveQuestionExpiry$' -count=1`: “clarification expiry has no scheduled invalidation”. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversationScriptlessConnectionChoices$' -count=1`: “plan asks for an opaque connection identifier”. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversationScriptlessReadCompletion$' -count=1`: “read-only completion presented as publication”. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversation(QuestionRaceNative|ScriptlessSharedPlan)$' -count=1`: shared plan returned 503 before the persisted-step/unset-selection fix; the native question test already passed. |
| + |
| +Other test-development corrections: the established started-step operation returns 422 for an invalid edit, so the HTTP test follows that contract. Cancelled native questions can return the existing unavailable status; the native race test requires refusal and no persisted answer, rather than inventing a new status mapping. Native tests were moved into plan3test to retain equipotest's existing size ceiling. An early source-size check correctly rejected the first draft at 10,906 root source lines; existing live trigger/deadline code was extracted into conversation, and the root's existing test seam remains as a forwarding function. |
| + |
| +### Final verification |
| + |
| +All commands below exited 0: |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversation(Scriptless|NoProject|Live|Question|Layout)' -count=1`: 4.017s. Covers message replay/escaping, routing, thread replies, unstarted reordering, started-step rejection, project correction, clarification answers, waiting-task links, connection choices, coordinator settings/limits, approval settings, landing preference, shared plan rendering, recent messages/current cards, native answer correlation, privacy, expiry and rollback. |
| +- `CGO_ENABLED=0 go test -tags browser ./internal/plan3test -run '^TestConversationLayout$' -count=1 -v`: PASS, 1.663s. Chromium is installed at /usr/bin/chromium. The existing chromedp/harness pattern was used at 390px and 1280px, with 100% and 200% text. Checks cover overflow, single-column content, full borders, nonwrapping values/badges, truncated secondary text, no initials, keyboard focus, and a live message arriving while the composer retains its draft and focus. This browser run did not skip. Without the browser tag, the named test explains the tag requirement; machines without Chrome/Chromium skip with an explicit reason. |
| +- `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestVendoredAssetsMatchTheLibrary|TestLiveGateConfirmation|TestTaskLiveRefresh.*|TestTaskPagesQuestionRenewal|TestQuestion.*|TestLiveRejectsForeignJobAssociations)$' -count=1`: 27.560s. |
| +- `CGO_ENABLED=0 go test ./internal/equipo -run '^TestLiveChangesFailedInstallRollsBack$' -count=1`: 0.055s. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^(TestConversation|TestPlanApproval|TestPlanProjectCorrection|TestPlanEdit|TestCoordinatorProjectInference|TestCoordinatorToolClarification|TestPreferencesLivePrivacy)' -count=1`: 7.658s. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/conversation ./internal/equipo/planning ./internal/plan3test`. |
| +- `CGO_ENABLED=0 go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size`: all 30 directories within budget. No ceiling or exception was changed. |
| +- `gofmt -l internal/equipo/*.go internal/equipo/conversation/*.go internal/equipo/planning/*.go internal/plan3test/*.go`: no output. |
| +- `git diff --check`: no findings. |
| + |
| +No full test suite, make ci, migration or live release gate was run. There are no schema changes. All browser/HTTP tests use isolated fixture sessions and data; there were no live provider calls, sign-ins, enrolment, credential homes or external publication. |
| + |
| +### Independent guard mutations |
| + |
| +Each mutation below was applied alone, produced an assertion failure, and was restored byte-for-byte in a finally block. The required tests and browser test passed after restoration. The first privacy mutation draft failed to compile because its result variable became unused; it was corrected and rerun to the authorization assertion failure listed here. |
| + |
| +- **private-topic**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationLivePrivacy$ -count=1 -timeout=45s`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:199: private topic authorization failed. |
| +- **post-commit**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationLivePrivacy$`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:205: notification before commit. |
| +- **plan-revision**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationScriptless$`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:85: HTTP 422, want 409: [error page]. |
| +- **question-lifetime**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationQuestionRace$`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:251: HTTP 303, want 409:. |
| +- **question-once**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationQuestionRace/current$`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:234: HTTP 303, want 409:. |
| +- **owner-limits**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationScriptlessSettings$`. Exit 1; restored: yes. Assertion: conversation_forms_test.go:76: HTTP 303, want 403:. |
| +- **composer-region**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationLiveFragments$`. Exit 1; restored: yes. Assertion: conversation_forms_test.go:147: fragment replaced composer. |
| +- **no-project-picker**: `CGO_ENABLED=0 go test ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationNoProjectPicker$`. Exit 1; restored: yes. Assertion: conversation_browser_test.go:144: project picker in composer. |
| +- **nowrap**: `CGO_ENABLED=0 go test -tags browser ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationLayout$`. Exit 1; restored: yes. Assertion: conversation_layout_browser_test.go:53: wrapping values or badges. |
| +- **single-column**: `CGO_ENABLED=0 go test -tags browser ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationLayout$`. Exit 1; restored: yes. Assertion: conversation_layout_browser_test.go:50: conversation overflow or split screen. |
| +- **hairline-border**: `CGO_ENABLED=0 go test -tags browser ./internal/plan3test -count=1 -timeout=45s -run ^TestConversationLayout$`. Exit 1; restored: yes. Assertion: conversation_layout_browser_test.go:56: coloured left accent. |
| + |
| +The plan-revision mutation changed the expected stale-revision response from 409 to a downstream 422; the later edit validator still refused the stale plan. The question-once mutation removed the combined state/revision guard and was caught by the stale-answer assertion. Separate normal-path checks verify duplicate-answer replay and one continuation/native answer effect. |
| + |
| +### Pending copy inventory |
| + |
| +50 added or changed entries, all individually marked `COPY REVIEW REQUIRED` in internal/equipo/copy.go. No copy-review server or drafting/reviewer agent was started. Existing reviewed labels are reused unchanged; model/person messages, project names and account labels remain attributed data. |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| `plan.connection` | Connection | |
| +| `plan.current_selection` | Current selection | |
| +| `plan.unselected` | Choose later | |
| +| `plan.action.scope` | Define scope | |
| +| `conversation.title` | Conversation | |
| +| `conversation.empty` | Start a conversation with your coordinator. | |
| +| `conversation.composer` | Message your coordinator | |
| +| `conversation.send` | Send message | |
| +| `conversation.queued` | Message queued | |
| +| `conversation.offline` | Live updates are paused. Reload to see changes. | |
| +| `conversation.thread_link` | About this task | |
| +| `conversation.thread_reply` | Reply about this task | |
| +| `conversation.route_confirmation` | Add this reply to a task | |
| +| `conversation.private` | Only you can read this conversation. | |
| +| `conversation.shared_thread` | Everyone on the team can read this discussion. | |
| +| `conversation.coordinator` | Coordinator | |
| +| `conversation.more` | More messages | |
| +| `coordinator.settings` | Your coordinator | |
| +| `coordinator.limits` | Coordinator limits | |
| +| `coordinator.waiting_label` | Waiting for | |
| +| `plan.revision` | Revision | |
| +| `plan.approved` | Approved | |
| +| `plan.required_step` | Required step | |
| +| `plan.position` | Order | |
| +| `plan.instructions` | Instructions | |
| +| `plan.model` | Model | |
| +| `plan.reason` | Reason for this choice | |
| +| `plan.remove_step` | Remove step | |
| +| `plan.add_step` | Add a step | |
| +| `plan.step_key` | Step name | |
| +| `plan.specialist` | Specialist | |
| +| `plan.action` | Action | |
| +| `plan.approval_settings` | Plan approval | |
| +| `plan.personal_override` | Your approval setting | |
| +| `plan.custom` | Custom plan | |
| +| `question.choose` | Choose an answer | |
| +| `question.reply` | Your reply | |
| +| `question.superseded` | Replaced by a newer question | |
| +| `question.cancelled` | Cancelled | |
| +| `settings.landing` | Open this page when you sign in | |
| +| `plan.action.reproduce` | Reproduce | |
| +| `plan.action.implement` | Implement | |
| +| `plan.action.review` | Independent review | |
| +| `plan.action.checks` | Run checks | |
| +| `plan.action.publish` | Publish review branch | |
| +| `plan.action.person` | Person approval | |
| +| `plan.action.investigate` | Investigate | |
| +| `plan.action.recommend` | Recommend | |
| +| `plan.action.copy` | Write copy | |
| +| `plan.action.design` | Design | |
| + |
| +Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-9-report.md`. No agents, push, merge, deployment, live provider use or copy-review server. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 37f7185a..3ee33ef3 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -131,7 +131,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| } |
| a := &application{executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| if cfg.AlwaysOn { |
| - a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob, "personal": a.preferenceHandler().Allow}, Lifetime: 30 * time.Second}) |
| + a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob, "personal": a.preferenceHandler().Allow, "conversation": a.allowConversation}, Lifetime: 30 * time.Second}) |
| if err != nil { |
| return nil, err |
| } |
| @@ -174,8 +174,10 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/settings/recovery/release", a.releaseRecovery) |
| r.Get("/", a.preferenceHandler().Landing) |
| a.preferenceHandler().Routes(r) |
| + a.conversationHandler().Routes(r) |
| + a.planHandler().Routes(r) |
| r.Get("/work", a.index) |
| - for _, path := range []string{"/conversation", "/needs-you", "/journey", "/connections"} { |
| + for _, path := range []string{"/needs-you", "/journey", "/connections"} { |
| r.Get(path, a.taskList) |
| } |
| r.Get("/projects", a.projects) |
diff --git a/internal/equipo/conversation/cards.go b/internal/equipo/conversation/cards.go| new file mode 100644 |
| index 00000000..5da3d25d |
| --- /dev/null |
| +++ b/internal/equipo/conversation/cards.go |
| @@ -0,0 +1,95 @@ |
| +package conversation |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (s *Store) allCards(a Actor, main Main) ([]Card, error) { |
| + var rows []cardRecord |
| + if err := s.tx.Where("stream_id=?", main.ID).Order("sequence,id").Find(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + out := []Card{} |
| + for _, c := range rows { |
| + card := Card{ID: c.ID, Kind: c.Kind, ResourceID: c.ResourceID, Revision: c.Revision} |
| + switch c.Kind { |
| + case "task": |
| + t, err := s.deps.Task(s.tx, a, c.ResourceID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + card.Revision = t.Revision |
| + case "clarification": |
| + var q QuestionRecord |
| + if err := s.tx.Where("id=? AND person=?", c.ResourceID, a.Address).Take(&q).Error; err != nil { |
| + return nil, err |
| + } |
| + card.Revision = q.Revision |
| + case "suggest_preference", "suggest_specialist", "suggest_playbook": |
| + var m messageRecord |
| + if err := s.tx.Where("id=? AND conversation_id=?", c.ResourceID, main.ID).Take(&m).Error; err != nil { |
| + return nil, err |
| + } |
| + card.Revision = m.Revision |
| + default: |
| + return nil, s.deps.Invalid |
| + } |
| + out = append(out, card) |
| + } |
| + var native []struct { |
| + ID, TaskID string |
| + Revision int64 |
| + } |
| + if err := s.tx.Table("questions q").Select("q.id,q.task_id,q.revision").Joins("JOIN tasks t ON t.id=q.task_id").Where("t.team_id=? AND t.requester=? AND q.state='pending'", main.TeamID, a.Address).Order("q.id").Find(&native).Error; err != nil { |
| + return nil, err |
| + } |
| + for _, q := range native { |
| + out = append(out, Card{ID: "native:" + q.ID, Kind: "question", ResourceID: q.ID, TaskID: q.TaskID, Revision: q.Revision}) |
| + } |
| + return out, nil |
| +} |
| +func (s *Application) ConversationCards(ctx context.Context, a Actor) (out []Card, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + cs := s.Conversation(tx) |
| + main, e := cs.main(a) |
| + if e != nil { |
| + return e |
| + } |
| + out, e = cs.allCards(a, main) |
| + if e != nil { |
| + return e |
| + } |
| + page, e := cs.Conversation(a, "", 1) |
| + if e != nil { |
| + return e |
| + } |
| + for _, c := range page.Cards { |
| + if c.Kind == "coordinator" { |
| + out = append(out, c) |
| + } |
| + } |
| + return nil |
| + }) |
| + return |
| +} |
| +func (s *Store) recentPage(a Actor, stream string, through, revision int64) (ConversationPage, string, error) { |
| + after := through - 50 |
| + if after < 0 { |
| + after = 0 |
| + } |
| + page, err := s.pageAfter(a, stream, through, revision, "", 50, after) |
| + if err != nil { |
| + return page, "", err |
| + } |
| + if after == 0 { |
| + return page, "", nil |
| + } |
| + older := cursorRecord{ID: rand.Text(), Principal: a.Address, StreamID: stream, Through: after, Revision: revision, ExpiresAt: time.Now().UTC().Add(24 * time.Hour)} |
| + err = s.tx.Create(&older).Error |
| + return page, "?cursor=" + older.ID, err |
| +} |
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go| index b37c80db..86fe36e7 100644 |
| --- a/internal/equipo/conversation/coordinator_application.go |
| +++ b/internal/equipo/conversation/coordinator_application.go |
| @@ -8,11 +8,13 @@ import ( |
| "errors" |
| "gorm.io/gorm" |
| "math" |
| + "time" |
| ) |
| type Actor = kernel.Actor |
| type Mutation = kernel.Mutation |
| type Application struct { |
| + Now func() time.Time |
| Core *team.Store |
| Write func(context.Context, func(*gorm.DB) error) error |
| Conversation func(*gorm.DB) *Store |
diff --git a/internal/equipo/conversation/handlers.go b/internal/equipo/conversation/handlers.go| new file mode 100644 |
| index 00000000..3f9d8c26 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/handlers.go |
| @@ -0,0 +1,103 @@ |
| +package conversation |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/live" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +type Handler struct { |
| + Live *live.Hub |
| + App *Application |
| + Plans *planning.Application |
| + Failure func(http.ResponseWriter, *http.Request, error) |
| + Render func(http.ResponseWriter, *http.Request, Page) |
| + RenderSettings func(http.ResponseWriter, *http.Request, CoordinatorPage) |
| +} |
| + |
| +func (h *Handler) Routes(r chi.Router) { |
| + r.Get("/conversation", h.Page) |
| + r.Post("/conversation", h.Send) |
| + r.Get("/tasks/{id}/thread", h.Page) |
| + r.Post("/tasks/{id}/thread", h.Send) |
| + r.Post("/conversation/messages/{id}/route", h.Route) |
| + r.Post("/conversation/questions/{id}/answer", h.Answer) |
| + r.Get("/settings/coordinator", h.Settings) |
| + r.Post("/settings/coordinator", h.SaveSettings) |
| +} |
| +func (h *Handler) actor(w http.ResponseWriter, r *http.Request) (Actor, bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + id, ok := auth.From(r) |
| + if !ok { |
| + h.Failure(w, r, h.App.Forbidden) |
| + } |
| + return Actor{Address: id.Address}, ok |
| +} |
| +func (h *Handler) Page(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + snapshot := h.Live.View(r) |
| + out, err := h.App.View(r.Context(), a, chi.URLParam(r, "id"), r.URL.Query().Get("cursor"), h.Plans) |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + out.Live = snapshot |
| + h.Render(w, r, out) |
| +} |
| +func (h *Handler) Send(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := planning.ReadMutation(w, r, h.App.Invalid) |
| + task := chi.URLParam(r, "id") |
| + if err == nil { |
| + _, err = h.App.SendMessage(r.Context(), a, task, r.PostForm.Get("body"), m) |
| + } |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + path := "/conversation" |
| + if task != "" { |
| + path = "/tasks/" + url.PathEscape(task) + "/thread" |
| + } |
| + http.Redirect(w, r, path, 303) |
| +} |
| +func (h *Handler) Route(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := planning.ReadMutation(w, r, h.App.Invalid) |
| + if err == nil { |
| + _, err = h.App.RouteMessage(r.Context(), a, chi.URLParam(r, "id"), r.PostForm.Get("task_id"), m) |
| + } |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/conversation", 303) |
| +} |
| +func (h *Handler) Answer(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := planning.ReadMutation(w, r, h.App.Invalid) |
| + if err == nil { |
| + err = h.App.AnswerClarification(r.Context(), a, chi.URLParam(r, "id"), r.PostForm.Get("option_id"), r.PostForm.Get("text"), m) |
| + } |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/conversation", 303) |
| +} |
diff --git a/internal/equipo/conversation/job_deadlines.go b/internal/equipo/conversation/job_deadlines.go| new file mode 100644 |
| index 00000000..424cb716 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/job_deadlines.go |
| @@ -0,0 +1,75 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "database/sql" |
| + "time" |
| +) |
| + |
| +func JobDeadlines(ctx context.Context, tx *sql.Tx, deadlines map[string][]time.Time, teamID string, ids []team.JobID) error { |
| + if ids == nil { |
| + rows, err := tx.QueryContext(ctx, "SELECT id FROM jobs WHERE account=? AND state NOT IN ('succeeded','failed','cancelled')", teamID) |
| + if err != nil { |
| + return err |
| + } |
| + for rows.Next() { |
| + var id team.JobID |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + ids = append(ids, id) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + collection := kernel.JobTopic(teamID, 0) |
| + deadlines[collection] = append(deadlines[collection], kernel.WeekStart(time.Now()).AddDate(0, 0, 7)) |
| + for _, schedule := range []struct { |
| + query string |
| + shift time.Duration |
| + }{ |
| + {"SELECT t.job_id,q.expires_at FROM questions q JOIN tasks t ON t.id=q.task_id WHERE q.state='pending' AND t.team_id=?", 0}, |
| + {"SELECT 0,c.last_seen FROM connections c JOIN runners r ON r.id=c.runner_id WHERE r.instance_id=?", 90 * time.Second}, |
| + {"SELECT job_id,lease_deadline FROM runner_assignments WHERE state='claimed' AND team_id=?", 0}, |
| + {"SELECT a.job_id,a.lease_deadline FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE a.containment='pending' AND j.account=?", 0}, |
| + } { |
| + rows, err := tx.QueryContext(ctx, schedule.query, teamID) |
| + if err != nil { |
| + return err |
| + } |
| + for rows.Next() { |
| + var id team.JobID |
| + var raw any |
| + if err = rows.Scan(&id, &raw); err != nil { |
| + break |
| + } |
| + at := kernel.ReadTime(raw).Add(schedule.shift) |
| + deadlines[collection] = append(deadlines[collection], at) |
| + if id != 0 { |
| + deadlines[kernel.JobTopic(teamID, int64(id))] = append(deadlines[kernel.JobTopic(teamID, int64(id))], at) |
| + } else { |
| + for _, job := range ids { |
| + if job != 0 { |
| + topic := kernel.JobTopic(teamID, int64(job)) |
| + deadlines[topic] = append(deadlines[topic], at) |
| + } |
| + } |
| + } |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/live_changes.go b/internal/equipo/conversation/job_live.go| similarity index 98% |
| rename from internal/equipo/live_changes.go |
| rename to internal/equipo/conversation/job_live.go |
| index 7b69e0a2..2e00f6d3 100644 |
| --- a/internal/equipo/live_changes.go |
| +++ b/internal/equipo/conversation/job_live.go |
| @@ -1,4 +1,4 @@ |
| -package equipo |
| +package conversation |
| import ( |
| "context" |
| @@ -10,7 +10,7 @@ import ( |
| // Temporary triggers collect changed associations on the writer connection. |
| // They are transactional and never become part of the application schema. |
| -func installLiveChanges(ctx context.Context, tx *sql.Tx) (err error) { |
| +func InstallJobChanges(ctx context.Context, tx *sql.Tx) (err error) { |
| if _, err = tx.ExecContext(ctx, "SAVEPOINT equipo_live_install"); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/conversation/live.go b/internal/equipo/conversation/live.go| index c0ae4d1a..2820486f 100644 |
| --- a/internal/equipo/conversation/live.go |
| +++ b/internal/equipo/conversation/live.go |
| @@ -1,12 +1,14 @@ |
| package conversation |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| "context" |
| "crypto/sha256" |
| "database/sql" |
| "encoding/json" |
| "fmt" |
| "net/http" |
| + "time" |
| "amadan.net/rastrillo/rastrillo/auth" |
| "gorm.io/gorm" |
| @@ -61,3 +63,143 @@ func PersonalChanges(ctx context.Context, tx *sql.Tx) ([]string, error) { |
| } |
| return topics, rows.Err() |
| } |
| + |
| +func ConversationTopic(team, person, resource string) string { |
| + raw, _ := json.Marshal([]string{team, person, resource}) |
| + return fmt.Sprintf("conversation/%x", sha256.Sum256(raw)) |
| +} |
| +func (s *Application) AllowConversation(r *http.Request, key string) bool { |
| + id, ok := auth.From(r) |
| + if !ok { |
| + return false |
| + } |
| + allowed := false |
| + err := s.Write(r.Context(), func(tx *gorm.DB) error { |
| + a := Actor{Address: s.Normalize(id.Address)} |
| + team, err := s.Conversation(tx).deps.Authorize(tx, a) |
| + if err != nil { |
| + return err |
| + } |
| + var mains []Main |
| + if err = tx.Where("team_id=? AND person=?", team, a.Address).Find(&mains).Error; err != nil { |
| + return err |
| + } |
| + for _, main := range mains { |
| + if ConversationTopic(team, a.Address, main.ID) == "conversation/"+key { |
| + allowed = true |
| + } |
| + } |
| + var threads []Thread |
| + if err = tx.Table("conversation_threads").Select("conversation_threads.*").Joins("JOIN tasks ON tasks.id=conversation_threads.task_id AND tasks.team_id=conversation_threads.team_id").Where("conversation_threads.team_id=?", team).Find(&threads).Error; err != nil { |
| + return err |
| + } |
| + for _, thread := range threads { |
| + if ConversationTopic(team, "", thread.ID) == "conversation/"+key { |
| + allowed = true |
| + } |
| + } |
| + return nil |
| + }) |
| + return err == nil && allowed |
| +} |
| +func InstallConversationChanges(ctx context.Context, tx *sql.Tx) error { |
| + stmts := []string{ |
| + `CREATE TEMP TABLE IF NOT EXISTS equipo_conversation_changes(team TEXT,person TEXT,resource TEXT,PRIMARY KEY(team,person,resource))`, |
| + `DELETE FROM equipo_conversation_changes`, |
| + `CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_main AFTER UPDATE ON main.conversations WHEN OLD.revision IS NOT NEW.revision BEGIN INSERT OR IGNORE INTO equipo_conversation_changes VALUES(NEW.team_id,NEW.person,NEW.id); END`, |
| + `CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_thread AFTER UPDATE ON main.conversation_threads WHEN OLD.revision IS NOT NEW.revision BEGIN INSERT OR IGNORE INTO equipo_conversation_changes VALUES(NEW.team_id,'',NEW.id); END`, |
| + } |
| + for _, table := range []string{"conversation_cards", "coordinator_bindings", "coordinator_turns", "coordinator_questions", "tasks", "jobs", "steps", "attempts", "questions", "plan_approval_settings", "coordinator_limits"} { |
| + var match string |
| + switch table { |
| + case "conversation_cards": |
| + match = "c.id=NEW.stream_id" |
| + case "coordinator_bindings": |
| + match = "c.team_id=NEW.team_id AND c.person=NEW.person_key" |
| + case "coordinator_turns": |
| + match = "c.id=NEW.conversation_id" |
| + case "coordinator_questions": |
| + match = "c.person=NEW.person AND EXISTS(SELECT 1 FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND b.team_id=c.team_id)" |
| + case "tasks": |
| + match = "c.team_id=NEW.team_id AND c.person=NEW.requester" |
| + case "jobs": |
| + match = "EXISTS(SELECT 1 FROM tasks t WHERE t.job_id=NEW.id AND t.team_id=c.team_id AND t.requester=c.person)" |
| + case "steps", "attempts": |
| + match = "EXISTS(SELECT 1 FROM tasks t WHERE t.job_id=NEW.job_id AND t.team_id=c.team_id AND t.requester=c.person)" |
| + case "questions": |
| + match = "EXISTS(SELECT 1 FROM tasks t WHERE t.id=NEW.task_id AND t.team_id=c.team_id AND t.requester=c.person)" |
| + case "plan_approval_settings": |
| + match = "EXISTS(SELECT 1 FROM tasks t WHERE t.project_id=NEW.project_id AND t.team_id=c.team_id AND t.requester=c.person)" |
| + case "coordinator_limits": |
| + match = "c.team_id=NEW.account AND c.person=NEW.person" |
| + } |
| + for _, event := range []string{"INSERT", "UPDATE"} { |
| + stmts = append(stmts, fmt.Sprintf(`CREATE TEMP TRIGGER IF NOT EXISTS equipo_conversation_%s_%s AFTER %s ON main.%s BEGIN INSERT OR IGNORE INTO equipo_conversation_changes SELECT c.team_id,c.person,c.id FROM conversations c WHERE %s; END`, table, event, event, table, match)) |
| + } |
| + } |
| + for _, stmt := range stmts { |
| + if _, err := tx.ExecContext(ctx, stmt); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| +func ConversationChanges(ctx context.Context, tx *sql.Tx) ([]string, error) { |
| + rows, err := tx.QueryContext(ctx, `SELECT team,person,resource FROM equipo_conversation_changes`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var team, person, resource string |
| + if err = rows.Scan(&team, &person, &resource); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, ConversationTopic(team, person, resource)) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func ConversationDeadlines(ctx context.Context, tx *sql.Tx, deadlines map[string][]time.Time) error { |
| + for _, query := range []struct { |
| + sql string |
| + clarification bool |
| + }{ |
| + {`SELECT c.team_id,c.person,c.id,q.payload FROM coordinator_questions q JOIN coordinator_bindings b ON b.id=q.binding_id JOIN conversations c ON c.team_id=b.team_id AND c.person=q.person WHERE q.state='pending'`, true}, |
| + {`SELECT c.team_id,c.person,c.id,q.expires_at FROM questions q JOIN tasks t ON t.id=q.task_id JOIN conversations c ON c.team_id=t.team_id AND c.person=t.requester WHERE q.state='pending'`, false}, |
| + } { |
| + rows, err := tx.QueryContext(ctx, query.sql) |
| + if err != nil { |
| + return err |
| + } |
| + for rows.Next() { |
| + var team, person, id string |
| + var raw any |
| + if err = rows.Scan(&team, &person, &id, &raw); err != nil { |
| + break |
| + } |
| + var at time.Time |
| + if query.clarification { |
| + var q struct{ ExpiresAt time.Time } |
| + body := fmt.Sprint(raw) |
| + if err = json.Unmarshal([]byte(body), &q); err != nil { |
| + break |
| + } |
| + at = q.ExpiresAt |
| + } else { |
| + at = kernel.ReadTime(raw) |
| + } |
| + topic := ConversationTopic(team, person, id) |
| + deadlines[topic] = append(deadlines[topic], at) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/conversation/models.go b/internal/equipo/conversation/models.go| index 0d23a02b..a16bb400 100644 |
| --- a/internal/equipo/conversation/models.go |
| +++ b/internal/equipo/conversation/models.go |
| @@ -16,7 +16,7 @@ type Message struct { |
| type Card struct { |
| ActionKeys []string `json:",omitempty"` |
| CopyKey, WaitingTaskID, WaitingTaskURL string `json:",omitempty"` |
| - ID, Kind, ResourceID string |
| + ID, Kind, ResourceID, TaskID string |
| Revision int64 |
| } |
| type ConversationPage struct { |
diff --git a/internal/equipo/conversation/settings.go b/internal/equipo/conversation/settings.go| new file mode 100644 |
| index 00000000..43b0cbee |
| --- /dev/null |
| +++ b/internal/equipo/conversation/settings.go |
| @@ -0,0 +1,144 @@ |
| +package conversation |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type CoordinatorConnection struct{ ID, RunnerID, Label string } |
| +type CoordinatorPage struct { |
| + Binding CoordinatorBinding |
| + Connections []CoordinatorConnection |
| + Limits team.Limits |
| + LimitsRevision int64 |
| + BudgetMissing, Owner bool |
| + RequestID, ResetID, LimitsID, SettingsID string |
| + Settings PersonalSettings |
| +} |
| + |
| +func (s *Application) CoordinatorPage(ctx context.Context, a Actor) (out CoordinatorPage, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + out.RequestID, out.ResetID, out.LimitsID, out.SettingsID = rand.Text(), rand.Text(), rand.Text(), rand.Text() |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + cs := s.Conversation(tx) |
| + teamID, e := cs.deps.Authorize(tx, a) |
| + if e != nil { |
| + return e |
| + } |
| + b, e := cs.Binding(a) |
| + if e != nil && !errors.Is(e, s.NotFound) { |
| + return e |
| + } |
| + out.Binding = b.CoordinatorBinding |
| + out.Owner = s.LimitsAuthority(tx, a, a.Address) == nil |
| + var rows []struct{ ID, RunnerID, ReportsJSON string } |
| + if e = tx.Table("connections").Select("id,runner_id,reports_json").Where("person=?", a.Address).Order("id").Find(&rows).Error; e != nil { |
| + return e |
| + } |
| + for _, row := range rows { |
| + var reports []struct{ AccountLabel string } |
| + if e = json.Unmarshal([]byte(row.ReportsJSON), &reports); e != nil { |
| + return e |
| + } |
| + label := row.ID |
| + if len(reports) > 0 && reports[0].AccountLabel != "" { |
| + label = reports[0].AccountLabel |
| + } |
| + out.Connections = append(out.Connections, CoordinatorConnection{row.ID, row.RunnerID, label}) |
| + } |
| + var limits struct { |
| + Revision int64 |
| + Limits string |
| + } |
| + e = tx.Table("coordinator_limits").Where("account=? AND person=?", teamID, a.Address).Take(&limits).Error |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + out.BudgetMissing = true |
| + return nil |
| + } |
| + if e != nil { |
| + return e |
| + } |
| + out.LimitsRevision = limits.Revision |
| + return json.Unmarshal([]byte(limits.Limits), &out.Limits) |
| + }) |
| + if err == nil { |
| + out.Settings, err = s.PersonalSettings(ctx, a) |
| + } |
| + return |
| +} |
| +func (s *Application) AnswerClarification(ctx context.Context, a Actor, id, option, text string, m Mutation) error { |
| + a.Address = s.Normalize(a.Address) |
| + return s.Write(ctx, func(tx *gorm.DB) error { |
| + return s.Conversation(tx).AnswerClarification(a, id, option, text, m, s.Now().UTC()) |
| + }) |
| +} |
| +func (h *Handler) Settings(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + v, err := h.App.CoordinatorPage(r.Context(), a) |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + h.RenderSettings(w, r, v) |
| +} |
| +func (h *Handler) SaveSettings(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := planning.ReadMutation(w, r, h.App.Invalid) |
| + if err == nil { |
| + switch r.PostForm.Get("action") { |
| + case "bind": |
| + // The connection's runner is resolved from the person's safe projection. |
| + var page CoordinatorPage |
| + page, err = h.App.CoordinatorPage(r.Context(), a) |
| + if err == nil { |
| + err = h.App.Invalid |
| + for _, c := range page.Connections { |
| + if c.ID == r.PostForm.Get("connection_id") { |
| + _, err = h.App.SaveCoordinatorBinding(r.Context(), a, c.RunnerID, c.ID, m) |
| + break |
| + } |
| + } |
| + } |
| + case "reset": |
| + _, err = h.App.ResetCoordinator(r.Context(), a, m) |
| + case "retry": |
| + _, err = h.App.RetryCoordinatorTurn(r.Context(), a, r.PostForm.Get("turn_id"), m) |
| + case "limits": |
| + var limits team.Limits |
| + for key, target := range map[string]*int64{"calls": &limits.Calls, "input_tokens": &limits.InputTokens, "output_tokens": &limits.OutputTokens, "seconds": &limits.Seconds} { |
| + value, e := strconv.ParseInt(r.PostForm.Get(key), 10, 64) |
| + if e != nil || value <= 0 { |
| + err = h.App.Invalid |
| + break |
| + } |
| + *target = value |
| + } |
| + if err == nil { |
| + err = h.App.SetCoordinatorLimits(r.Context(), a, a.Address, limits, m) |
| + } |
| + case "landing": |
| + _, err = h.App.SavePersonalSettings(r.Context(), a, PersonalSettings{Landing: r.PostForm.Get("landing")}, m) |
| + default: |
| + err = h.App.Invalid |
| + } |
| + } |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/settings/coordinator", 303) |
| +} |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index c3c722a4..930d57e1 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -171,6 +171,9 @@ func (s *Store) appendMessage(stream, mainID, tid, kind, author, body, purpose s |
| return row.message(), nil |
| } |
| func (s *Store) page(actor kernel.Actor, stream string, through, revision int64, cursor string, limit int) (ConversationPage, error) { |
| + return s.pageAfter(actor, stream, through, revision, cursor, limit, 0) |
| +} |
| +func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision int64, cursor string, limit int, after int64) (ConversationPage, error) { |
| page := ConversationPage{Messages: []Message{}, Cards: []Card{}, Revision: revision} |
| if limit == 0 { |
| limit = 50 |
| @@ -178,7 +181,6 @@ func (s *Store) page(actor kernel.Actor, stream string, through, revision int64, |
| if limit < 1 || limit > 100 { |
| return page, s.deps.Invalid |
| } |
| - after := int64(0) |
| if cursor != "" { |
| var c cursorRecord |
| err := s.tx.Where("id=? AND principal=? AND stream_id=?", cursor, actor.Address, stream).First(&c).Error |
diff --git a/internal/equipo/conversation/tools.go b/internal/equipo/conversation/tools.go| index e9ccdf83..c7af54db 100644 |
| --- a/internal/equipo/conversation/tools.go |
| +++ b/internal/equipo/conversation/tools.go |
| @@ -99,7 +99,18 @@ func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c C |
| } |
| case *coordinator.ProposePlan: |
| if a.Plan.ProjectID == 0 { |
| - out, err = cs.ask(row, call.RequestID, coordinator.AskPerson{MessageID: a.MessageID, Question: e.Tools.AmbiguousProject, Options: []coordinator.QuestionOption{}}, e.Now()) |
| + projects, projectErr := e.projects(tx, p.Person, c.Brief.Selection) |
| + if projectErr != nil { |
| + return projectErr |
| + } |
| + options := []coordinator.QuestionOption{} |
| + for _, project := range projects { |
| + if len(options) == 32 { |
| + break |
| + } |
| + options = append(options, coordinator.QuestionOption{ID: strconv.FormatInt(project.ID, 10), Label: project.Label}) |
| + } |
| + out, err = cs.ask(row, call.RequestID, coordinator.AskPerson{MessageID: a.MessageID, Question: e.Tools.AmbiguousProject, Options: options}, e.Now()) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/conversation/views.go b/internal/equipo/conversation/views.go| new file mode 100644 |
| index 00000000..e61ffc26 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/views.go |
| @@ -0,0 +1,166 @@ |
| +package conversation |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "net/url" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/rastrillo/rastrillo/live" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type MessageView struct { |
| + Message |
| + RouteID, ThreadURL string |
| +} |
| +type CardView struct { |
| + Card |
| + Plan *planning.Page |
| + Question *runnerproto.ClarificationQuestion |
| + CanAnswer bool |
| + RequestID, ResetID string |
| + BindingRevision int64 |
| + WaitingLabel string |
| +} |
| +type Page struct { |
| + Live live.View |
| + Topic, ThreadID, RequestID, NextURL string |
| + Revision int64 |
| + Messages []MessageView |
| + Cards []CardView |
| + Tasks []planning.ProjectOption |
| + BindingRevision int64 |
| +} |
| + |
| +func (s *Application) View(ctx context.Context, a Actor, task, cursor string, plans *planning.Application) (out Page, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + out.ThreadID = task |
| + out.RequestID = rand.Text() |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + cs := s.Conversation(tx) |
| + var page ConversationPage |
| + if task == "" { |
| + main, e := cs.main(a) |
| + if e != nil { |
| + return e |
| + } |
| + out.Topic = ConversationTopic(main.TeamID, a.Address, main.ID) |
| + page, err = cs.Conversation(a, cursor, 50) |
| + if err != nil { |
| + return err |
| + } |
| + all, e := cs.allCards(a, main) |
| + if e != nil { |
| + return e |
| + } |
| + for _, c := range page.Cards { |
| + if c.Kind == "coordinator" { |
| + all = append(all, c) |
| + } |
| + } |
| + if cursor == "" { |
| + page, out.NextURL, err = cs.recentPage(a, main.ID, main.LastSequence, main.Revision) |
| + } |
| + page.Cards = all |
| + } else { |
| + thread, _, e := cs.thread(a, task) |
| + if e != nil { |
| + return e |
| + } |
| + out.Topic = ConversationTopic(thread.TeamID, "", thread.ID) |
| + page, err = cs.TaskThread(a, task, cursor, 50) |
| + if err == nil && cursor == "" { |
| + page, out.NextURL, err = cs.recentPage(a, thread.ID, thread.LastSequence, thread.Revision) |
| + } |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + out.Revision = page.Revision |
| + if page.NextCursor != "" { |
| + out.NextURL = "?cursor=" + url.QueryEscape(page.NextCursor) |
| + } |
| + for _, m := range page.Messages { |
| + mv := MessageView{Message: m, RouteID: rand.Text()} |
| + if task == "" { |
| + var route routeRecord |
| + e := tx.Where("notice_id=?", m.ID).Take(&route).Error |
| + if e == nil { |
| + mv.ThreadURL = "/tasks/" + url.PathEscape(route.TaskID) + "/thread" |
| + } else if !errors.Is(e, gorm.ErrRecordNotFound) { |
| + return e |
| + } |
| + } |
| + out.Messages = append(out.Messages, mv) |
| + } |
| + b, e := cs.Binding(a) |
| + if e != nil && !errors.Is(e, s.NotFound) { |
| + return e |
| + } |
| + out.BindingRevision = b.Revision |
| + for _, card := range page.Cards { |
| + v := CardView{Card: card, RequestID: rand.Text(), ResetID: rand.Text(), BindingRevision: b.Revision} |
| + switch card.Kind { |
| + case "task": |
| + p, e := plans.At(tx).Page(a, card.ResourceID) |
| + if e != nil { |
| + return e |
| + } |
| + v.Plan = &p |
| + case "clarification": |
| + q, can, e := cs.questionView(a, card.ResourceID, s.Now().UTC()) |
| + if e != nil { |
| + return e |
| + } |
| + v.Question = &q |
| + v.CanAnswer = can |
| + case "coordinator": |
| + if card.WaitingTaskID != "" { |
| + var row struct{ Description string } |
| + e := tx.Table("tasks").Where("id=? AND team_id=?", card.WaitingTaskID, b.TeamID).Select("description").Take(&row).Error |
| + if e != nil { |
| + return e |
| + } |
| + v.WaitingLabel = row.Description |
| + } |
| + } |
| + out.Cards = append(out.Cards, v) |
| + } |
| + return nil |
| + }) |
| + return |
| +} |
| +func (s *Store) questionView(a Actor, id string, now time.Time) (q runnerproto.ClarificationQuestion, can bool, err error) { |
| + b, err := s.Binding(a) |
| + if err != nil { |
| + return |
| + } |
| + var rec QuestionRecord |
| + if err = s.tx.Where("id=? AND binding_id=? AND person=?", id, b.ID, a.Address).Take(&rec).Error; err != nil { |
| + return |
| + } |
| + if err = json.Unmarshal([]byte(rec.Payload), &q); err != nil { |
| + return |
| + } |
| + var turn TurnRecord |
| + if err = s.tx.Where("id=? AND binding_id=?", rec.TurnID, b.ID).Take(&turn).Error; err != nil { |
| + return |
| + } |
| + q.State, q.Revision = rec.State, rec.Revision |
| + if q.State == "pending" { |
| + switch { |
| + case !now.Before(q.ExpiresAt): |
| + q.State = "expired" |
| + case rec.Generation != b.Generation || turn.Generation != b.Generation || (turn.State != "running" && turn.State != "delivered"): |
| + q.State = "superseded" |
| + default: |
| + can = true |
| + } |
| + } |
| + return |
| +} |
diff --git a/internal/equipo/conversation_handlers.go b/internal/equipo/conversation_handlers.go| new file mode 100644 |
| index 00000000..4595b80d |
| --- /dev/null |
| +++ b/internal/equipo/conversation_handlers.go |
| @@ -0,0 +1,51 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "context" |
| + "net/http" |
| +) |
| + |
| +func (s *Store) ConversationCards(ctx context.Context, a Actor) ([]Card, error) { |
| + return s.coordinatorApplication().ConversationCards(ctx, a) |
| +} |
| +func (a *application) allowConversation(r *http.Request, key string) bool { |
| + return a.store.coordinatorApplication().AllowConversation(r, key) |
| +} |
| +func (a *application) conversationHandler() *conversation.Handler { |
| + return &conversation.Handler{Live: a.live, App: a.store.coordinatorApplication(), Plans: a.store.planningApplication(), Failure: a.failure, |
| + Render: func(w http.ResponseWriter, r *http.Request, v conversation.Page) { |
| + data, err := a.page(r, "conversation") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Conversation = v |
| + data.Live = v.Live |
| + name := "conversation" |
| + if v.ThreadID != "" { |
| + name = "thread" |
| + } |
| + a.renderLive(w, r, name, data) |
| + }, RenderSettings: func(w http.ResponseWriter, r *http.Request, v conversation.CoordinatorPage) { |
| + data, err := a.page(r, "settings") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Coordinator = v |
| + a.renderLive(w, r, "coordinator", data) |
| + }} |
| +} |
| +func (a *application) planHandler() *planning.Handler { |
| + return &planning.Handler{App: a.store.planningApplication(), Invalid: ErrInvalid, Forbidden: ErrForbidden, Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, v planning.Page) { |
| + data, err := a.page(r, "conversation") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Plan = v |
| + a.renderLive(w, r, "plan", data) |
| + }} |
| +} |
diff --git a/internal/equipo/coordinator.go b/internal/equipo/coordinator.go| index 0b45217a..7f44cca7 100644 |
| --- a/internal/equipo/coordinator.go |
| +++ b/internal/equipo/coordinator.go |
| @@ -68,7 +68,7 @@ func (s *Store) coordinatorApplication() *conversation.Application { |
| if s.execution != nil { |
| core = s.execution.Core |
| } |
| - return &conversation.Application{Core: core, Write: s.write, Conversation: conversationAt, Normalize: normalizeAddress, Audit: appendAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, NotFound: ErrNotFound, |
| + return &conversation.Application{Now: s.runnerClock.Now, Core: core, Write: s.write, Conversation: conversationAt, Normalize: normalizeAddress, Audit: appendAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, NotFound: ErrNotFound, |
| BindingIdentity: func(tx *gorm.DB, actor Actor, runner, connection string) (int64, int64, error) { |
| member, err := currentRunnerMember(tx, actor.Address) |
| if err != nil { |
| @@ -146,10 +146,7 @@ func (e *Execution) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, |
| return e.coordinatorEngine().CallCoordinatorTool(ctx, p, c, call) |
| } |
| func (s *Store) AnswerClarification(ctx context.Context, a Actor, id, optionID, text string, m Mutation) error { |
| - a.Address = normalizeAddress(a.Address) |
| - return s.write(ctx, func(tx *gorm.DB) error { |
| - return conversationAt(tx).AnswerClarification(a, id, optionID, text, m, s.runnerClock.Now().UTC()) |
| - }) |
| + return s.coordinatorApplication().AnswerClarification(ctx, a, id, optionID, text, m) |
| } |
| func (e *Execution) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]CoordinatorTurn, error) { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 55f43dce..52ac7064 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -48,6 +48,107 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: plan.connection |
| + "plan.connection": "Connection", |
| + // COPY REVIEW REQUIRED: plan.current_selection |
| + "plan.current_selection": "Current selection", |
| + // COPY REVIEW REQUIRED: plan.unselected |
| + "plan.unselected": "Choose later", |
| + // COPY REVIEW REQUIRED: plan.action.scope |
| + "plan.action.scope": "Define scope", |
| + // COPY REVIEW REQUIRED: conversation.title |
| + "conversation.title": "Conversation", |
| + // COPY REVIEW REQUIRED: conversation.empty |
| + "conversation.empty": "Start a conversation with your coordinator.", |
| + // COPY REVIEW REQUIRED: conversation.composer |
| + "conversation.composer": "Message your coordinator", |
| + // COPY REVIEW REQUIRED: conversation.send |
| + "conversation.send": "Send message", |
| + // COPY REVIEW REQUIRED: conversation.queued |
| + "conversation.queued": "Message queued", |
| + // COPY REVIEW REQUIRED: conversation.offline |
| + "conversation.offline": "Live updates are paused. Reload to see changes.", |
| + // COPY REVIEW REQUIRED: conversation.thread_link |
| + "conversation.thread_link": "About this task", |
| + // COPY REVIEW REQUIRED: conversation.thread_reply |
| + "conversation.thread_reply": "Reply about this task", |
| + // COPY REVIEW REQUIRED: conversation.route_confirmation |
| + "conversation.route_confirmation": "Add this reply to a task", |
| + // COPY REVIEW REQUIRED: conversation.private |
| + "conversation.private": "Only you can read this conversation.", |
| + // COPY REVIEW REQUIRED: conversation.shared_thread |
| + "conversation.shared_thread": "Everyone on the team can read this discussion.", |
| + // COPY REVIEW REQUIRED: conversation.coordinator |
| + "conversation.coordinator": "Coordinator", |
| + // COPY REVIEW REQUIRED: conversation.more |
| + "conversation.more": "More messages", |
| + // COPY REVIEW REQUIRED: coordinator.settings |
| + "coordinator.settings": "Your coordinator", |
| + // COPY REVIEW REQUIRED: coordinator.limits |
| + "coordinator.limits": "Coordinator limits", |
| + // COPY REVIEW REQUIRED: coordinator.waiting_label |
| + "coordinator.waiting_label": "Waiting for", |
| + // COPY REVIEW REQUIRED: plan.revision |
| + "plan.revision": "Revision", |
| + // COPY REVIEW REQUIRED: plan.approved |
| + "plan.approved": "Approved", |
| + // COPY REVIEW REQUIRED: plan.required_step |
| + "plan.required_step": "Required step", |
| + // COPY REVIEW REQUIRED: plan.position |
| + "plan.position": "Order", |
| + // COPY REVIEW REQUIRED: plan.instructions |
| + "plan.instructions": "Instructions", |
| + // COPY REVIEW REQUIRED: plan.model |
| + "plan.model": "Model", |
| + // COPY REVIEW REQUIRED: plan.reason |
| + "plan.reason": "Reason for this choice", |
| + // COPY REVIEW REQUIRED: plan.remove_step |
| + "plan.remove_step": "Remove step", |
| + // COPY REVIEW REQUIRED: plan.add_step |
| + "plan.add_step": "Add a step", |
| + // COPY REVIEW REQUIRED: plan.step_key |
| + "plan.step_key": "Step name", |
| + // COPY REVIEW REQUIRED: plan.specialist |
| + "plan.specialist": "Specialist", |
| + // COPY REVIEW REQUIRED: plan.action |
| + "plan.action": "Action", |
| + // COPY REVIEW REQUIRED: plan.approval_settings |
| + "plan.approval_settings": "Plan approval", |
| + // COPY REVIEW REQUIRED: plan.personal_override |
| + "plan.personal_override": "Your approval setting", |
| + // COPY REVIEW REQUIRED: plan.custom |
| + "plan.custom": "Custom plan", |
| + // COPY REVIEW REQUIRED: question.choose |
| + "question.choose": "Choose an answer", |
| + // COPY REVIEW REQUIRED: question.reply |
| + "question.reply": "Your reply", |
| + // COPY REVIEW REQUIRED: question.superseded |
| + "question.superseded": "Replaced by a newer question", |
| + // COPY REVIEW REQUIRED: question.cancelled |
| + "question.cancelled": "Cancelled", |
| + // COPY REVIEW REQUIRED: settings.landing |
| + "settings.landing": "Open this page when you sign in", |
| + // COPY REVIEW REQUIRED: plan.action.reproduce |
| + "plan.action.reproduce": "Reproduce", |
| + // COPY REVIEW REQUIRED: plan.action.implement |
| + "plan.action.implement": "Implement", |
| + // COPY REVIEW REQUIRED: plan.action.review |
| + "plan.action.review": "Independent review", |
| + // COPY REVIEW REQUIRED: plan.action.checks |
| + "plan.action.checks": "Run checks", |
| + // COPY REVIEW REQUIRED: plan.action.publish |
| + "plan.action.publish": "Publish review branch", |
| + // COPY REVIEW REQUIRED: plan.action.person |
| + "plan.action.person": "Person approval", |
| + // COPY REVIEW REQUIRED: plan.action.investigate |
| + "plan.action.investigate": "Investigate", |
| + // COPY REVIEW REQUIRED: plan.action.recommend |
| + "plan.action.recommend": "Recommend", |
| + // COPY REVIEW REQUIRED: plan.action.copy |
| + "plan.action.copy": "Write copy", |
| + // COPY REVIEW REQUIRED: plan.action.design |
| + "plan.action.design": "Design", |
| + |
| // COPY REVIEW REQUIRED: preferences.title |
| "preferences.title": "Preferences", |
| // COPY REVIEW REQUIRED: preferences.confirmed |
| @@ -143,7 +244,6 @@ var pageCopy = map[string]string{ |
| "nav.work": "Work", |
| "nav.back": "Back to work", |
| "nav.signout": "Sign out", |
| - "conversation.empty": "No conversation yet. Work is not enabled yet.", |
| "needs-you.empty": "Nothing needs your decision yet.", |
| "journey.empty": "No work has started.", |
| "connections.empty": "Connections are not available yet.", |
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go| index 5a644597..a77ddaa3 100644 |
| --- a/internal/equipo/handlers.go |
| +++ b/internal/equipo/handlers.go |
| @@ -8,6 +8,8 @@ import ( |
| "strconv" |
| "strings" |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/live" |
| @@ -24,6 +26,9 @@ type budgetForm struct { |
| Fields []budgetField |
| } |
| type pageData struct { |
| + Conversation conversation.Page |
| + Coordinator conversation.CoordinatorPage |
| + Plan planning.Page |
| Rendered RenderedChangeView |
| Live live.View |
| Topic, CollectionTopic string |
diff --git a/internal/equipo/live.go b/internal/equipo/live.go| index c23f11b9..cbd8adbf 100644 |
| --- a/internal/equipo/live.go |
| +++ b/internal/equipo/live.go |
| @@ -67,10 +67,13 @@ func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserv |
| if s.notifier == nil { |
| return nil, nil |
| } |
| + if err := conversation.InstallConversationChanges(ctx, tx); err != nil { |
| + return nil, err |
| + } |
| if err := conversation.InstallPersonalChanges(ctx, tx); err != nil { |
| return nil, err |
| } |
| - if err := installLiveChanges(ctx, tx); err != nil { |
| + if err := conversation.InstallJobChanges(ctx, tx); err != nil { |
| return nil, err |
| } |
| return func(ctx context.Context, tx *sql.Tx) (func(), error) { |
| @@ -98,8 +101,11 @@ func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserv |
| return nil, err |
| } |
| st := liveState{deadlines: map[string][]time.Time{}} |
| + if err := conversation.ConversationDeadlines(ctx, tx, st.deadlines); err != nil { |
| + return nil, err |
| + } |
| for teamID, ids := range touched { |
| - if err := s.liveDeadlines(ctx, tx, &st, teamID, ids); err != nil { |
| + if err := conversation.JobDeadlines(ctx, tx, st.deadlines, teamID, ids); err != nil { |
| return nil, err |
| } |
| } |
| @@ -107,6 +113,11 @@ func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserv |
| if err != nil { |
| return nil, err |
| } |
| + conversations, err := conversation.ConversationChanges(ctx, tx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + private = append(private, conversations...) |
| for _, topic := range private { |
| topics[topic] = true |
| } |
| @@ -145,79 +156,21 @@ func (s *Store) restoreLiveSchedules(ctx context.Context) error { |
| return err |
| } |
| st := liveState{deadlines: map[string][]time.Time{}} |
| - if err := s.liveDeadlines(ctx, tx, &st, teamID, nil); err != nil { |
| + if err := conversation.ConversationDeadlines(ctx, tx, st.deadlines); err != nil { |
| + return err |
| + } |
| + if err := conversation.JobDeadlines(ctx, tx, st.deadlines, teamID, nil); err != nil { |
| return err |
| } |
| s.scheduleState(st) |
| return nil |
| }) |
| } |
| -func (s *Store) liveDeadlines(ctx context.Context, tx *sql.Tx, st *liveState, teamID string, ids []JobID) error { |
| - if ids == nil { |
| - rows, err := tx.QueryContext(ctx, "SELECT id FROM jobs WHERE account=? AND state NOT IN ('succeeded','failed','cancelled')", teamID) |
| - if err != nil { |
| - return err |
| - } |
| - for rows.Next() { |
| - var id JobID |
| - if err = rows.Scan(&id); err != nil { |
| - break |
| - } |
| - ids = append(ids, id) |
| - } |
| - if err == nil { |
| - err = rows.Err() |
| - } |
| - rows.Close() |
| - if err != nil { |
| - return err |
| - } |
| - } |
| - collection := jobTopic(teamID, 0) |
| - st.deadlines[collection] = append(st.deadlines[collection], weekStart(time.Now()).AddDate(0, 0, 7)) |
| - for _, schedule := range []struct { |
| - query string |
| - shift time.Duration |
| - }{ |
| - {"SELECT t.job_id,q.expires_at FROM questions q JOIN tasks t ON t.id=q.task_id WHERE q.state='pending' AND t.team_id=?", 0}, |
| - {"SELECT 0,c.last_seen FROM connections c JOIN runners r ON r.id=c.runner_id WHERE r.instance_id=?", 90 * time.Second}, |
| - {"SELECT job_id,lease_deadline FROM runner_assignments WHERE state='claimed' AND team_id=?", 0}, |
| - {"SELECT a.job_id,a.lease_deadline FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE a.containment='pending' AND j.account=?", 0}, |
| - } { |
| - rows, err := tx.QueryContext(ctx, schedule.query, teamID) |
| - if err != nil { |
| - return err |
| - } |
| - for rows.Next() { |
| - var id JobID |
| - var raw any |
| - if err = rows.Scan(&id, &raw); err != nil { |
| - break |
| - } |
| - at := readTime(raw).Add(schedule.shift) |
| - st.deadlines[collection] = append(st.deadlines[collection], at) |
| - if id != 0 { |
| - st.deadlines[jobTopic(teamID, id)] = append(st.deadlines[jobTopic(teamID, id)], at) |
| - } else { |
| - for _, job := range ids { |
| - if job != 0 { |
| - topic := jobTopic(teamID, job) |
| - st.deadlines[topic] = append(st.deadlines[topic], at) |
| - } |
| - } |
| - } |
| - } |
| - if err == nil { |
| - err = rows.Err() |
| - } |
| - rows.Close() |
| - if err != nil { |
| - return err |
| - } |
| - } |
| - return nil |
| -} |
| func readTime(v any) time.Time { return kernel.ReadTime(v) } |
| func weekStart(now time.Time) time.Time { return kernel.WeekStart(now) } |
| var _ JobNotifier = (*live.Hub)(nil) |
| + |
| +func installLiveChanges(ctx context.Context, tx *sql.Tx) error { |
| + return conversation.InstallJobChanges(ctx, tx) |
| +} |
diff --git a/internal/equipo/planning/application.go b/internal/equipo/planning/application.go| new file mode 100644 |
| index 00000000..cba987f8 |
| --- /dev/null |
| +++ b/internal/equipo/planning/application.go |
| @@ -0,0 +1,77 @@ |
| +package planning |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "context" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type Application struct { |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + At func(*gorm.DB) *Store |
| + Normalize func(string) string |
| +} |
| + |
| +func (s *Application) ProposePlan(ctx context.Context, a kernel.Actor, p taskplan.Plan, m kernel.Mutation) (out taskplan.Plan, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Propose(a, p, m); return err }) |
| + return |
| +} |
| +func (s *Application) EditPlan(ctx context.Context, a kernel.Actor, p taskplan.Plan, m kernel.Mutation) (out taskplan.Plan, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Edit(a, p, m); return err }) |
| + return |
| +} |
| +func (s *Application) ApprovePlan(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) (out Task, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Approve(a, id, m); return err }) |
| + return |
| +} |
| +func (s *Application) CorrectTaskProject(ctx context.Context, a kernel.Actor, id string, project int64, m kernel.Mutation) (out Task, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Correct(a, id, project, m); return err }) |
| + return |
| +} |
| +func (s *Application) SetProjectApproval(ctx context.Context, a kernel.Actor, project int64, mode ApprovalMode, m kernel.Mutation) error { |
| + a.Address = s.Normalize(a.Address) |
| + return s.Write(ctx, func(tx *gorm.DB) error { return s.At(tx).SetApproval(a, project, &mode, m, true) }) |
| +} |
| +func (s *Application) SetApprovalOverride(ctx context.Context, a kernel.Actor, project int64, mode *ApprovalMode, m kernel.Mutation) error { |
| + a.Address = s.Normalize(a.Address) |
| + return s.Write(ctx, func(tx *gorm.DB) error { return s.At(tx).SetApproval(a, project, mode, m, false) }) |
| +} |
| +func (s *Application) PlanApproval(ctx context.Context, a kernel.Actor, project int64) (out ApprovalMode, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + if err := st.deps.Member(tx, a, false); err != nil { |
| + return err |
| + } |
| + out, err = st.Approval(a.Address, project) |
| + return err |
| + }) |
| + return |
| +} |
| +func (s *Application) CheckPlanDispatch(ctx context.Context, a kernel.Actor, id string) error { |
| + a.Address = s.Normalize(a.Address) |
| + return s.Write(ctx, func(tx *gorm.DB) error { return s.At(tx).CheckDispatch(a, id) }) |
| +} |
| +func (s *Application) TaskPlan(ctx context.Context, a kernel.Actor, id string) (out taskplan.Plan, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + t, e := st.visibleTask(a, id) |
| + if e != nil { |
| + return e |
| + } |
| + out, err = st.Plan(t) |
| + return err |
| + }) |
| + return |
| +} |
| +func (s *Application) Page(ctx context.Context, a kernel.Actor, id string) (out Page, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Page(a, id); return err }) |
| + return |
| +} |
diff --git a/internal/equipo/planning/handlers.go b/internal/equipo/planning/handlers.go| new file mode 100644 |
| index 00000000..d314ac8c |
| --- /dev/null |
| +++ b/internal/equipo/planning/handlers.go |
| @@ -0,0 +1,194 @@ |
| +package planning |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +type Handler struct { |
| + App *Application |
| + Invalid, Forbidden error |
| + Failure func(http.ResponseWriter, *http.Request, error) |
| + Render func(http.ResponseWriter, *http.Request, Page) |
| +} |
| + |
| +func (h *Handler) Routes(r chi.Router) { |
| + r.Get("/tasks/{id}/plan", h.Page) |
| + r.Post("/tasks/{id}/plan", h.Edit) |
| + r.Post("/tasks/{id}/plan/approve", h.Approve) |
| + r.Post("/tasks/{id}/project", h.Correct) |
| + r.Post("/tasks/{id}/plan/settings", h.Settings) |
| +} |
| +func ReadMutation(w http.ResponseWriter, r *http.Request, invalid error) (kernel.Mutation, error) { |
| + r.Body = http.MaxBytesReader(w, r.Body, 64<<10) |
| + if r.ParseForm() != nil { |
| + return kernel.Mutation{}, invalid |
| + } |
| + for _, v := range r.PostForm { |
| + if len(v) != 1 { |
| + return kernel.Mutation{}, invalid |
| + } |
| + } |
| + revision, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64) |
| + m := kernel.Mutation{RequestID: r.PostForm.Get("request_id"), Revision: revision} |
| + if err != nil || !m.Valid() { |
| + return m, invalid |
| + } |
| + return m, nil |
| +} |
| +func (h *Handler) actor(w http.ResponseWriter, r *http.Request) (kernel.Actor, bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + id, ok := auth.From(r) |
| + if !ok { |
| + h.Failure(w, r, h.Forbidden) |
| + } |
| + return kernel.Actor{Address: id.Address}, ok |
| +} |
| +func (h *Handler) Page(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + v, err := h.App.Page(r.Context(), a, chi.URLParam(r, "id")) |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + h.Render(w, r, v) |
| +} |
| +func (h *Handler) finish(w http.ResponseWriter, r *http.Request, id string, err error) { |
| + if err != nil { |
| + h.Failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/tasks/"+url.PathEscape(id)+"/plan", 303) |
| +} |
| +func (h *Handler) Edit(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := ReadMutation(w, r, h.Invalid) |
| + if err == nil { |
| + var p taskplan.Plan |
| + p, err = decodePlan(r.PostForm, chi.URLParam(r, "id"), m, h.Invalid) |
| + if err == nil { |
| + _, err = h.App.EditPlan(r.Context(), a, p, m) |
| + } |
| + } |
| + h.finish(w, r, chi.URLParam(r, "id"), err) |
| +} |
| +func decodePlan(v url.Values, id string, m kernel.Mutation, invalid error) (taskplan.Plan, error) { |
| + p := taskplan.Plan{TaskID: id, Revision: m.Revision, Kind: taskplan.Kind(v.Get("kind")), PlaybookID: v.Get("playbook_id")} |
| + var err error |
| + p.ProjectID, err = strconv.ParseInt(v.Get("project_id"), 10, 64) |
| + if err != nil { |
| + return p, invalid |
| + } |
| + p.PlaybookRevision, err = strconv.ParseInt(v.Get("playbook_revision"), 10, 64) |
| + if err != nil { |
| + return p, invalid |
| + } |
| + count, err := strconv.Atoi(v.Get("step_count")) |
| + if err != nil || count < 1 || count > taskplan.MaxSteps { |
| + return p, invalid |
| + } |
| + type positioned struct { |
| + step taskplan.Step |
| + position int |
| + } |
| + var ordered []positioned |
| + used := map[int]bool{} |
| + for i := 0; i <= count; i++ { |
| + prefix := "step_" + strconv.Itoa(i) + "_" |
| + if i == count && v.Get(prefix+"key") == "" { |
| + break |
| + } |
| + if v.Get(prefix+"remove") == "1" { |
| + continue |
| + } |
| + pos, e := strconv.Atoi(v.Get(prefix + "position")) |
| + if e != nil || pos < 1 || pos > taskplan.MaxSteps || used[pos] { |
| + return p, invalid |
| + } |
| + used[pos] = true |
| + st := taskplan.Step{Key: v.Get(prefix + "key"), Specialist: v.Get(prefix + "specialist"), Action: v.Get(prefix + "action"), Instructions: v.Get(prefix + "instructions"), ConnectionID: v.Get(prefix + "connection"), Model: v.Get(prefix + "model"), SelectionReason: v.Get(prefix + "reason")} |
| + if dep := v.Get(prefix + "depends_on"); dep != "" { |
| + st.DependsOn = strings.Split(dep, ",") |
| + } |
| + ordered = append(ordered, positioned{st, pos}) |
| + } |
| + sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].position < ordered[j].position }) |
| + for _, st := range ordered { |
| + p.Steps = append(p.Steps, st.step) |
| + } |
| + return p, nil |
| +} |
| +func (h *Handler) Approve(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + m, err := ReadMutation(w, r, h.Invalid) |
| + if err == nil { |
| + _, err = h.App.ApprovePlan(r.Context(), a, chi.URLParam(r, "id"), m) |
| + } |
| + h.finish(w, r, chi.URLParam(r, "id"), err) |
| +} |
| +func (h *Handler) Correct(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + id := chi.URLParam(r, "id") |
| + m, err := ReadMutation(w, r, h.Invalid) |
| + if err == nil { |
| + project, e := strconv.ParseInt(r.PostForm.Get("project_id"), 10, 64) |
| + if e != nil { |
| + err = h.Invalid |
| + } else { |
| + var out Task |
| + out, err = h.App.CorrectTaskProject(r.Context(), a, id, project, m) |
| + if err == nil && out.ReplacementID != "" { |
| + id = out.ReplacementID |
| + } |
| + } |
| + } |
| + h.finish(w, r, id, err) |
| +} |
| +func (h *Handler) Settings(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.actor(w, r) |
| + if !ok { |
| + return |
| + } |
| + id := chi.URLParam(r, "id") |
| + m, err := ReadMutation(w, r, h.Invalid) |
| + if err == nil { |
| + var p taskplan.Plan |
| + p, err = h.App.TaskPlan(r.Context(), a, id) |
| + if err == nil { |
| + mode := ApprovalMode(r.PostForm.Get("mode")) |
| + switch r.PostForm.Get("scope") { |
| + case "project": |
| + err = h.App.SetProjectApproval(r.Context(), a, p.ProjectID, mode, m) |
| + case "personal": |
| + var value *ApprovalMode |
| + if mode != "" { |
| + value = &mode |
| + } |
| + err = h.App.SetApprovalOverride(r.Context(), a, p.ProjectID, value, m) |
| + default: |
| + err = h.Invalid |
| + } |
| + } |
| + } |
| + h.finish(w, r, id, err) |
| +} |
diff --git a/internal/equipo/planning/views.go b/internal/equipo/planning/views.go| new file mode 100644 |
| index 00000000..136e0cc3 |
| --- /dev/null |
| +++ b/internal/equipo/planning/views.go |
| @@ -0,0 +1,187 @@ |
| +package planning |
| + |
| +import ( |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type ProjectOption struct { |
| + ID int64 |
| + Name string |
| +} |
| +type StepView struct { |
| + taskplan.Step |
| + Index, Position int |
| + State, Account, Actual, Depends string |
| + Locked bool |
| +} |
| +type Page struct { |
| + Connections []ConnectionOption |
| + Task Task |
| + Plan taskplan.Plan |
| + Project string |
| + Projects []ProjectOption |
| + Steps []StepView |
| + ProjectSetting, PersonalSetting ApprovalSetting |
| + Effective ApprovalMode |
| + CanEdit, Owner bool |
| + RequestID, ApproveID, CorrectID, ProjectSettingID, PersonalSettingID string |
| +} |
| + |
| +func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) { |
| + out.Task, err = s.visibleTask(a, id) |
| + if err != nil { |
| + return |
| + } |
| + out.Plan, err = s.Plan(out.Task) |
| + if err != nil { |
| + return |
| + } |
| + _, accessErr := s.deps.Access(s.tx, a, out.Task.ProjectID) |
| + out.CanEdit = accessErr == nil |
| + out.Owner = s.deps.Member(s.tx, a, true) == nil |
| + out.RequestID, out.ApproveID, out.CorrectID = rand.Text(), rand.Text(), rand.Text() |
| + out.ProjectSettingID, out.PersonalSettingID = rand.Text(), rand.Text() |
| + if err = s.tx.Table("projects").Select("id,name").Order("name,id").Find(&out.Projects).Error; err != nil { |
| + return |
| + } |
| + for _, p := range out.Projects { |
| + if p.ID == out.Plan.ProjectID { |
| + out.Project = p.Name |
| + } |
| + } |
| + for _, setting := range []struct { |
| + person string |
| + out *ApprovalSetting |
| + }{{"", &out.ProjectSetting}, {a.Address, &out.PersonalSetting}} { |
| + err = s.tx.Where("project_id=? AND person=?", out.Plan.ProjectID, setting.person).Take(setting.out).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + err = nil |
| + } |
| + if err != nil { |
| + return |
| + } |
| + } |
| + out.Connections, err = s.connectionOptions(a, out.Plan.ProjectID) |
| + if err != nil { |
| + return |
| + } |
| + out.Effective, err = s.Approval(a.Address, out.Plan.ProjectID) |
| + if err != nil { |
| + return |
| + } |
| + var steps []struct { |
| + Key, State string |
| + ID int64 |
| + } |
| + if out.Task.JobID != 0 { |
| + err = s.tx.Table("steps").Select("id,key,state").Where("job_id=?", out.Task.JobID).Find(&steps).Error |
| + if err != nil { |
| + return |
| + } |
| + } |
| + for i, st := range out.Plan.Steps { |
| + v := StepView{Step: st, Index: i, Position: i + 1, State: "pending", Depends: strings.Join(st.DependsOn, ",")} |
| + for _, actual := range steps { |
| + if actual.Key == st.Key { |
| + v.State = actual.State |
| + var n int64 |
| + if err = s.tx.Table("attempts").Where("step_id=?", actual.ID).Count(&n).Error; err != nil { |
| + return |
| + } |
| + v.Locked = n > 0 || actual.State != "pending" |
| + var a struct{ Provider, Model string } |
| + e := s.tx.Table("attempts").Select("provider,model").Where("step_id=?", actual.ID).Order("id DESC").Take(&a).Error |
| + if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) { |
| + err = e |
| + return |
| + } |
| + if a.Provider != "" { |
| + v.Actual = a.Provider + " / " + a.Model |
| + } |
| + } |
| + } |
| + var n int64 |
| + if err = s.tx.Table("runner_assignments").Where("task_id=? AND step_key=? AND claim_request<>''", id, st.Key).Count(&n).Error; err != nil { |
| + return |
| + } |
| + v.Locked = v.Locked || n > 0 |
| + // Account labels are shown only to the account's person. IDs are opaque. |
| + if st.ConnectionID != "" { |
| + var row struct{ ReportsJSON string } |
| + e := s.tx.Table("connections").Select("reports_json").Where("id=? AND person=?", st.ConnectionID, a.Address).Take(&row).Error |
| + if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) { |
| + err = e |
| + return |
| + } |
| + v.Account = "" |
| + if v.Account == "" && row.ReportsJSON != "" { |
| + var reports []struct{ AccountLabel string } |
| + if err = json.Unmarshal([]byte(row.ReportsJSON), &reports); err != nil { |
| + return |
| + } |
| + if len(reports) > 0 { |
| + v.Account = reports[0].AccountLabel |
| + } |
| + } |
| + } |
| + out.Steps = append(out.Steps, v) |
| + } |
| + return |
| +} |
| + |
| +func (s *Store) visibleTask(a kernel.Actor, id string) (Task, error) { |
| + if err := s.deps.Member(s.tx, a, false); err != nil { |
| + return Task{}, err |
| + } |
| + var teamID string |
| + if err := s.tx.Table("teams").Select("id").Row().Scan(&teamID); err != nil { |
| + return Task{}, err |
| + } |
| + var t Task |
| + err := s.tx.Where("id=? AND team_id=?", id, teamID).First(&t).Error |
| + return t, err |
| +} |
| + |
| +type ConnectionOption struct{ ID, Label string } |
| + |
| +func (s *Store) connectionOptions(a kernel.Actor, project int64) ([]ConnectionOption, error) { |
| + var choice struct{ ConnectionIDsJSON string } |
| + err := s.tx.Table("connection_choices").Where("person=? AND project_id=?", a.Address, project).Take(&choice).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var ids []string |
| + if err = json.Unmarshal([]byte(choice.ConnectionIDsJSON), &ids); err != nil { |
| + return nil, err |
| + } |
| + var rows []struct{ ID, ReportsJSON string } |
| + if err = s.tx.Table("connections").Select("id,reports_json").Where("person=? AND id IN ?", a.Address, ids).Order("id").Find(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + var out []ConnectionOption |
| + for _, row := range rows { |
| + var reports []struct{ AccountLabel, Provider, Model string } |
| + if err = json.Unmarshal([]byte(row.ReportsJSON), &reports); err != nil { |
| + return nil, err |
| + } |
| + if len(reports) == 0 { |
| + continue |
| + } |
| + label := reports[0].AccountLabel |
| + if label == "" { |
| + label = reports[0].Provider + " / " + reports[0].Model |
| + } |
| + out = append(out, ConnectionOption{row.ID, label}) |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go| index 28ca139c..45961bbe 100644 |
| --- a/internal/equipo/plans.go |
| +++ b/internal/equipo/plans.go |
| @@ -97,82 +97,35 @@ func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error { |
| _, _, err = s.planPair(tx, t, p) |
| return err |
| } |
| +func (s *Store) planningApplication() *planning.Application { |
| + return &planning.Application{Write: s.write, At: s.planningAt, Normalize: normalizeAddress} |
| +} |
| func (s *Store) ProposePlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) { |
| - actor.Address = normalizeAddress(actor.Address) |
| - var result taskplan.Plan |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - var err error |
| - result, err = s.planningAt(tx).Propose(actor, p, m) |
| - return err |
| - }) |
| - return result, err |
| + return s.planningApplication().ProposePlan(ctx, actor, p, m) |
| } |
| func (s *Store) EditPlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) { |
| - actor.Address = normalizeAddress(actor.Address) |
| - var result taskplan.Plan |
| - err := s.write(ctx, func(tx *gorm.DB) error { var err error; result, err = s.planningAt(tx).Edit(actor, p, m); return err }) |
| - return result, err |
| + return s.planningApplication().EditPlan(ctx, actor, p, m) |
| } |
| func (s *Store) ApprovePlan(ctx context.Context, actor Actor, id string, m Mutation) (Task, error) { |
| - actor.Address = normalizeAddress(actor.Address) |
| - var result Task |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - var err error |
| - result, err = s.planningAt(tx).Approve(actor, id, m) |
| - return err |
| - }) |
| - return result, err |
| + return s.planningApplication().ApprovePlan(ctx, actor, id, m) |
| } |
| func (s *Store) CorrectTaskProject(ctx context.Context, actor Actor, id string, project int64, m Mutation) (Task, error) { |
| - actor.Address = normalizeAddress(actor.Address) |
| - var result Task |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - var err error |
| - result, err = s.planningAt(tx).Correct(actor, id, project, m) |
| - return err |
| - }) |
| - return result, err |
| + return s.planningApplication().CorrectTaskProject(ctx, actor, id, project, m) |
| } |
| func (s *Store) SetProjectApproval(ctx context.Context, actor Actor, project int64, mode ApprovalMode, m Mutation) error { |
| - actor.Address = normalizeAddress(actor.Address) |
| - return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).SetApproval(actor, project, &mode, m, true) }) |
| + return s.planningApplication().SetProjectApproval(ctx, actor, project, mode, m) |
| } |
| func (s *Store) SetApprovalOverride(ctx context.Context, actor Actor, project int64, mode *ApprovalMode, m Mutation) error { |
| - actor.Address = normalizeAddress(actor.Address) |
| - return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).SetApproval(actor, project, mode, m, false) }) |
| + return s.planningApplication().SetApprovalOverride(ctx, actor, project, mode, m) |
| } |
| func (s *Store) PlanApproval(ctx context.Context, actor Actor, project int64) (ApprovalMode, error) { |
| - actor.Address = normalizeAddress(actor.Address) |
| - var result ApprovalMode |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - if _, err := currentRunnerMember(tx, actor.Address); err != nil { |
| - return err |
| - } |
| - var err error |
| - result, err = s.planningAt(tx).Approval(actor.Address, project) |
| - return err |
| - }) |
| - return result, err |
| + return s.planningApplication().PlanApproval(ctx, actor, project) |
| } |
| func (s *Store) CheckPlanDispatch(ctx context.Context, actor Actor, id string) error { |
| - actor.Address = normalizeAddress(actor.Address) |
| - return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).CheckDispatch(actor, id) }) |
| + return s.planningApplication().CheckPlanDispatch(ctx, actor, id) |
| } |
| func (s *Store) TaskPlan(ctx context.Context, actor Actor, id string) (taskplan.Plan, error) { |
| - var result taskplan.Plan |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - if _, err := currentRunnerMember(tx, actor.Address); err != nil { |
| - return err |
| - } |
| - var t Task |
| - if err := tx.First(&t, "id=?", id).Error; err != nil { |
| - return storeError(err) |
| - } |
| - var err error |
| - result, err = s.planningAt(tx).Plan(t) |
| - return err |
| - }) |
| - return result, err |
| + return s.planningApplication().TaskPlan(ctx, actor, id) |
| } |
| func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 578cc70a..be8014fe 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -26,7 +26,7 @@ var assets = rastrillo.NewAssets(appFS) |
| var pages = map[string]*template.Template{} |
| func init() { |
| - for _, name := range []string{"preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| + for _, name := range []string{"conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| page := template.Must(template.New("layout"). |
| Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))). |
| Funcs(template.FuncMap{"asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} }, |
| @@ -44,7 +44,7 @@ func init() { |
| page = template.Must(page.ParseFS(appFS, "templates/layout.html")) |
| } |
| if name != "signin_page" && name != "errors" { |
| - page = template.Must(page.ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html")) |
| + page = template.Must(page.ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html", "templates/conversation_card.html")) |
| } |
| pages[name] = template.Must(page.ParseFS(appFS, "templates/"+name+".html")) |
| } |
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css| index 21f259a0..ffa5f87a 100644 |
| --- a/internal/equipo/static/equipo.css |
| +++ b/internal/equipo/static/equipo.css |
| @@ -28,3 +28,16 @@ |
| [equipo-preference-status] { display: inline-block; white-space: nowrap; border: 1px solid var(--rst-line); border-radius: var(--rst-radius); padding: var(--rst-sp-1) var(--rst-sp-2); background: var(--rst-surface-2); font-size: var(--rst-fs-sm); } |
| [equipo-preference-text] { white-space: pre-wrap; } |
| + |
| +[equipo-conversation], [equipo-plan] { display: block; max-width: 52rem; margin-inline: auto; min-width: 0; } |
| +[equipo-message] { margin-block: var(--rst-sp-5); min-width: 0; } |
| +[equipo-message-body] { white-space: pre-wrap; } |
| +[equipo-secondary] { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rst-text-muted); } |
| +[equipo-value], [equipo-badge] { display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } |
| +[equipo-badge] { border: 1px solid var(--rst-line); border-radius: var(--rst-radius); padding: var(--rst-sp-1) var(--rst-sp-2); background: var(--rst-surface-2); } |
| +[equipo-plan-steps] { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--rst-sp-3); list-style: none; padding: 0; } |
| +[equipo-plan-step] { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--rst-sp-2); border: 1px solid var(--rst-line); border-radius: var(--rst-radius); padding: var(--rst-sp-3); background: var(--rst-surface-2); min-width: 0; } |
| +[equipo-actions] { display: flex; gap: var(--rst-sp-2); flex-wrap: wrap; margin-block: var(--rst-sp-3); } |
| +[equipo-form] [equipo-checkbox] { display: flex; align-items: center; } |
| +[equipo-form] [equipo-checkbox] input { width: auto; } |
| +#composer { margin-block: var(--rst-sp-5); } |
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go| index 80cba9dd..15672e6d 100644 |
| --- a/internal/equipo/task_views.go |
| +++ b/internal/equipo/task_views.go |
| @@ -11,19 +11,20 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| ) |
| type StepCard struct { |
| - FinishedAt time.Time |
| - Key, Category, State, Model, Account, Actual, Person string |
| - Isolation team.IsolationSnapshot |
| - Unconfined bool |
| - UsageKnown bool |
| - AllowanceKnown bool |
| - AllowanceRemaining int64 |
| - CountedTurns, InputTokens, OutputTokens int64 |
| + FinishedAt time.Time |
| + Key, Category, State, Model, Account, Actual, Person, Action, Reason string |
| + Isolation team.IsolationSnapshot |
| + Unconfined bool |
| + UsageKnown bool |
| + AllowanceKnown bool |
| + AllowanceRemaining int64 |
| + CountedTurns, InputTokens, OutputTokens int64 |
| } |
| type QuestionField struct{ Key, Prompt string } |
| @@ -198,7 +199,7 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| return v, storeError(err) |
| } |
| var eng, review Selection |
| - if json.Unmarshal([]byte(outbox.Engineering), &eng) != nil || json.Unmarshal([]byte(outbox.Review), &review) != nil { |
| + if (outbox.Engineering != "" && json.Unmarshal([]byte(outbox.Engineering), &eng) != nil) || (outbox.Review != "" && json.Unmarshal([]byte(outbox.Review), &review) != nil) { |
| return v, ErrUnavailable |
| } |
| var steps []executionSteps |
| @@ -236,6 +237,11 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| v.StateKey = waitCopyKey(job.Wait) |
| } |
| } |
| + if job.State == "succeeded" && !taskplan.Publication(task.Kind) { |
| + v.StateKey, v.Group = "evidence.answer_delivered", "finished" |
| + v.CanMerge, v.NeedsYou = false, false |
| + v.FinishedAt = readTime(job.UpdatedAt) |
| + } |
| if task.WaitCode != "" { |
| v.StateKey = waitCopyKey(task.WaitCode) |
| } |
| @@ -279,23 +285,42 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| v.StateKey = "trial.reconnect" |
| v.NeedsYou = true |
| } |
| - for _, plan := range BugPlan(task) { |
| - card := StepCard{Key: plan.Key, Category: plan.Specialist, Person: plan.Person, State: "pending", UsageKnown: task.JobID != 0} |
| - if plan.RunnerOnly { |
| + persisted, err := s.planningAt(tx).Plan(task) |
| + if err != nil { |
| + return v, storeError(err) |
| + } |
| + for _, plan := range persisted.Steps { |
| + person := "" |
| + if plan.Action == "person" { |
| + person = task.MergeOwner |
| + } |
| + runnerOnly := plan.Action == "publish" || plan.Action == "checks" |
| + card := StepCard{Key: plan.Key, Action: plan.Action, Reason: plan.SelectionReason, Category: plan.Specialist, Person: person, State: "pending", UsageKnown: task.JobID != 0} |
| + if runnerOnly { |
| card.Category = "runner" |
| } |
| - if plan.Person != "" { |
| + if person != "" { |
| card.Category = "person" |
| } |
| sel := eng |
| if plan.Specialist == "review" { |
| sel = review |
| } |
| - if plan.Person == "" { |
| + for _, assignment := range assignments { |
| + if assignment.StepKey == plan.Key && assignment.Selection != "" { |
| + if err := json.Unmarshal([]byte(assignment.Selection), &sel); err != nil { |
| + return v, ErrUnavailable |
| + } |
| + } |
| + } |
| + if person == "" { |
| card.Model = sel.Model |
| + if plan.Model != "" { |
| + card.Model = plan.Model |
| + } |
| card.AllowanceKnown = sel.AllowanceKnown |
| card.AllowanceRemaining = sel.AllowanceRemaining |
| - if plan.RunnerOnly { |
| + if runnerOnly { |
| card.Model = "" |
| } |
| card.Account = sel.AccountLabel |
diff --git a/internal/equipo/templates/conversation.html b/internal/equipo/templates/conversation.html| new file mode 100644 |
| index 00000000..f94640c4 |
| --- /dev/null |
| +++ b/internal/equipo/templates/conversation.html |
| @@ -0,0 +1,9 @@ |
| +{{define "title"}}{{copy "conversation.title"}}{{end}} |
| +{{define "content"}} |
| +<div equipo-conversation> |
| +<h1>{{copy "conversation.title"}}</h1><p equipo-muted>{{copy "conversation.private"}}</p> |
| +<a href="/settings/coordinator">{{copy "coordinator.settings"}}</a> |
| +{{template "region:conversation-feed" .}} |
| +{{template "conversation-composer" .}} |
| +</div> |
| +{{end}} |
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html| new file mode 100644 |
| index 00000000..b75d4294 |
| --- /dev/null |
| +++ b/internal/equipo/templates/conversation_card.html |
| @@ -0,0 +1,44 @@ |
| +{{define "conversation-composer"}} |
| +<form id="composer" equipo-form method="post" action="{{if .Conversation.ThreadID}}/tasks/{{.Conversation.ThreadID}}/thread{{else}}/conversation{{end}}"> |
| +<input type="hidden" name="request_id" value="{{.Conversation.RequestID}}"><input type="hidden" name="revision" value="0"> |
| +<label>{{if .Conversation.ThreadID}}{{copy "conversation.thread_reply"}}{{else}}{{copy "conversation.composer"}}{{end}}<textarea rst-input name="body" required maxlength="16384" rows="4"></textarea></label> |
| +<button rst-btn="primary" type="submit">{{copy "conversation.send"}}</button> |
| +</form> |
| +{{end}} |
| +{{define "region:conversation-feed"}} |
| +<section id="conversation-feed" {{.Live.Attrs .Conversation.Topic}}> |
| +{{range .Conversation.Messages}} |
| +<article equipo-message data-message="{{.ID}}"><p equipo-secondary>{{if eq .AuthorKind "person"}}{{.AuthorID}}{{else if eq .AuthorKind "coordinator"}}{{copy "conversation.coordinator"}}{{else if eq .AuthorKind "specialist"}}{{.AuthorID}}{{else}}{{copy "brand"}}{{end}}</p><p equipo-message-body>{{.Body}}</p> |
| +{{if .ThreadURL}}<a href="{{.ThreadURL}}">{{copy "conversation.thread_link"}}</a>{{end}} |
| +{{if and (not $.Conversation.ThreadID) (eq .AuthorKind "person")}} |
| +{{if $.Conversation.Cards}}<details><summary>{{copy "conversation.route_confirmation"}}</summary><form method="post" action="/conversation/messages/{{.ID}}/route" equipo-form><input type="hidden" name="request_id" value="{{.RouteID}}"><input type="hidden" name="revision" value="{{.Revision}}"><label>{{copy "conversation.thread_link"}}<select rst-input name="task_id" required>{{range $.Conversation.Cards}}{{with .Plan}}<option value="{{.Task.ID}}">{{.Task.Description}}</option>{{end}}{{end}}</select></label><button rst-btn type="submit">{{copy "conversation.route_confirmation"}}</button></form></details>{{end}} |
| +{{end}} |
| +</article> |
| +{{else}}<p data-empty-state="conversation.empty">{{copy "conversation.empty"}}</p>{{end}} |
| +{{range .Conversation.Cards}}{{template "conversation-card" .}}{{end}} |
| +{{if .Conversation.NextURL}}<a href="{{.Conversation.NextURL}}">{{copy "conversation.more"}}</a>{{end}} |
| +</section> |
| +{{end}} |
| +{{define "conversation-card"}} |
| +<article equipo-card data-card="{{.ID}}"> |
| +{{with .Plan}} |
| +<h2><a href="/tasks/{{.Task.ID}}/plan">{{.Task.Description}}</a></h2> |
| +<p equipo-secondary>{{copy "plan.project"}}: {{.Project}}</p> |
| +<p><span equipo-badge>{{copy "plan.revision"}} {{.Plan.Revision}}</span> <span equipo-badge>{{if eq .Task.ApprovalRevision .Plan.Revision}}{{copy "plan.approved"}}{{else}}{{copy "plan.proposed"}}{{end}}</span></p> |
| +{{if .Plan.PlaybookID}}<p equipo-secondary>{{copy "plan.playbook"}}: {{.Plan.PlaybookID}} <span equipo-value>{{.Plan.PlaybookRevision}}</span></p>{{end}} |
| +<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step><strong>{{if .Specialist}}{{copy (printf "nav.%s" .Specialist)}}{{else}}{{copy (printf "plan.action.%s" .Action)}}{{end}}</strong><span equipo-secondary>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><span equipo-value>{{.Model}} {{.Account}}</span>{{if .SelectionReason}}<span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span>{{end}}{{if .Actual}}<span equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</span>{{end}}</li>{{end}}</ol> |
| +<a href="/tasks/{{.Task.ID}}/plan#project">{{copy "plan.correct_project"}}</a> <a href="/tasks/{{.Task.ID}}/plan">{{copy "plan.edit"}}</a> <a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a> |
| +{{end}} |
| +{{with .Question}} |
| +<h2>{{.Prompt}}</h2><span equipo-badge>{{copy (printf "question.%s" .State)}}</span> |
| +{{if $.CanAnswer}}<form method="post" action="/conversation/questions/{{.ID}}/answer" equipo-actions><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button rst-btn name="option_id" value="{{.ID}}" type="submit">{{.Label}}</button>{{end}}</form> |
| +<form method="post" action="/conversation/questions/{{.ID}}/answer" equipo-form><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><label>{{copy "question.reply"}}<textarea rst-input name="text" required maxlength="8192"></textarea></label><button rst-btn type="submit">{{copy "question.send_answer"}}</button></form>{{end}} |
| +{{end}} |
| +{{if eq .Kind "question"}}<a href="/tasks/{{.TaskID}}/questions/{{.ResourceID}}">{{copy "task.answer"}}</a>{{end}} |
| +{{if eq .Kind "coordinator"}} |
| +{{if .WaitingTaskURL}}<p>{{copy "coordinator.waiting_label"}} <a href="{{.WaitingTaskURL}}">{{.WaitingLabel}}</a></p>{{else}}<p>{{copy .CopyKey}}</p>{{end}} |
| +{{if .ActionKeys}}<div equipo-actions><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="retry"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="turn_id" value="{{.ResourceID}}"><button rst-btn type="submit">{{copy "coordinator.retry"}}</button></form><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="reset"><input type="hidden" name="request_id" value="{{.ResetID}}"><input type="hidden" name="revision" value="{{.BindingRevision}}"><button rst-btn type="submit">{{copy "coordinator.reset"}}</button></form></div>{{end}} |
| +{{end}} |
| +{{if eq .Kind "suggest_preference"}}<a href="/preferences">{{copy "preferences.title"}}</a>{{end}} |
| +</article> |
| +{{end}} |
diff --git a/internal/equipo/templates/coordinator.html b/internal/equipo/templates/coordinator.html| new file mode 100644 |
| index 00000000..3b858b12 |
| --- /dev/null |
| +++ b/internal/equipo/templates/coordinator.html |
| @@ -0,0 +1,13 @@ |
| +{{define "title"}}{{copy "coordinator.settings"}}{{end}} |
| +{{define "content"}} |
| +<h1>{{copy "coordinator.settings"}}</h1> |
| +{{with .Coordinator}} |
| +{{if .BudgetMissing}}<p equipo-note>{{copy "coordinator.budget_needed"}}</p>{{end}} |
| +{{if not .Binding.ID}}<p equipo-note>{{copy "coordinator.unavailable"}}</p>{{end}} |
| +{{if .Connections}}<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="bind"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Binding.Revision}}"><label>{{copy "coordinator.connection"}}<select rst-input name="connection_id">{{$current := .Binding.ConnectionID}}{{range .Connections}}<option value="{{.ID}}" {{if eq .ID $current}}selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{else}}<a href="/connections">{{copy "nav.connections"}}</a>{{end}} |
| +{{if .Binding.ID}}<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="reset"><input type="hidden" name="request_id" value="{{.ResetID}}"><input type="hidden" name="revision" value="{{.Binding.Revision}}"><button rst-btn type="submit">{{copy "coordinator.reset"}}</button></form>{{end}} |
| +{{if .Owner}}<section equipo-card><h2>{{copy "coordinator.limits"}}</h2><form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="limits"><input type="hidden" name="request_id" value="{{.LimitsID}}"><input type="hidden" name="revision" value="{{.LimitsRevision}}"> |
| +<label>{{copy "budget.calls"}}<input rst-input type="number" min="1" name="calls" value="{{if not .BudgetMissing}}{{.Limits.Calls}}{{end}}" required></label><label>{{copy "budget.input"}}<input rst-input type="number" min="1" name="input_tokens" value="{{if not .BudgetMissing}}{{.Limits.InputTokens}}{{end}}" required></label><label>{{copy "budget.output"}}<input rst-input type="number" min="1" name="output_tokens" value="{{if not .BudgetMissing}}{{.Limits.OutputTokens}}{{end}}" required></label><label>{{copy "budget.seconds"}}<input rst-input type="number" min="1" name="seconds" value="{{if not .BudgetMissing}}{{.Limits.Seconds}}{{end}}" required></label><button rst-btn type="submit">{{copy "form.save"}}</button></form></section>{{end}} |
| +<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="landing"><input type="hidden" name="request_id" value="{{.SettingsID}}"><input type="hidden" name="revision" value="{{.Settings.Revision}}"><label>{{copy "settings.landing"}}<select rst-input name="landing"><option value="conversation" {{if eq .Settings.Landing "conversation"}}selected{{end}}>{{copy "nav.conversation"}}</option><option value="work" {{if eq .Settings.Landing "work"}}selected{{end}}>{{copy "nav.work"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form> |
| +{{end}} |
| +{{end}} |
diff --git a/internal/equipo/templates/plan.html b/internal/equipo/templates/plan.html| new file mode 100644 |
| index 00000000..b9c19795 |
| --- /dev/null |
| +++ b/internal/equipo/templates/plan.html |
| @@ -0,0 +1,41 @@ |
| +{{define "title"}}{{copy "task.plan"}}{{end}} |
| +{{define "up"}}/tasks/{{.Plan.Task.ID}}{{end}} |
| +{{define "content"}} |
| +<div equipo-plan> |
| +{{with .Plan}} |
| +<h1>{{.Task.Description}}</h1><p><span equipo-badge>{{copy "plan.revision"}} {{.Plan.Revision}}</span> <span equipo-badge>{{if eq .Task.ApprovalRevision .Plan.Revision}}{{copy "plan.approved"}}{{else}}{{copy "plan.proposed"}}{{end}}</span></p> |
| +<a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a> |
| +{{if .Task.ReplacementID}}<a href="/tasks/{{.Task.ReplacementID}}/plan">{{copy "plan.replacement"}}</a>{{end}} |
| +{{if eq .Plan.Kind "investigation"}}<p equipo-note>{{copy "plan.investigation_checkpoint"}}</p>{{end}} |
| +<p equipo-secondary>{{copy "plan.playbook"}}: {{if .Plan.PlaybookID}}{{.Plan.PlaybookID}} <span equipo-value>{{.Plan.PlaybookRevision}}</span>{{else}}{{copy "plan.custom"}}{{end}}</p> |
| +{{if .CanEdit}} |
| +<form id="plan-editor" method="post" action="/tasks/{{.Task.ID}}/plan" equipo-form> |
| +<input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Plan.Revision}}"><input type="hidden" name="kind" value="{{.Plan.Kind}}"><input type="hidden" name="project_id" value="{{.Plan.ProjectID}}"><input type="hidden" name="playbook_id" value="{{.Plan.PlaybookID}}"><input type="hidden" name="playbook_revision" value="{{.Plan.PlaybookRevision}}"><input type="hidden" name="step_count" value="{{len .Steps}}"> |
| +{{range .Steps}} |
| +<fieldset data-plan-step="{{.Key}}"><legend>{{copy (printf "plan.action.%s" .Action)}}</legend><span equipo-badge>{{copy (printf "step.%s" .State)}}</span> |
| +{{if .Locked}}<p equipo-note>{{copy "plan.locked_step"}}</p>{{end}} |
| +{{if .Required}}<span equipo-badge>{{copy "plan.required_step"}}</span>{{end}} |
| +<input type="hidden" name="step_{{.Index}}_key" value="{{.Key}}"><input type="hidden" name="step_{{.Index}}_specialist" value="{{.Specialist}}"><input type="hidden" name="step_{{.Index}}_action" value="{{.Action}}"><input type="hidden" name="step_{{.Index}}_depends_on" value="{{.Depends}}"> |
| +<label>{{copy "plan.position"}}<input rst-input name="step_{{.Index}}_position" type="number" min="1" max="16" value="{{.Position}}" {{if .Locked}}readonly{{end}} required></label> |
| +<label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{.Index}}_instructions" rows="3" {{if .Locked}}readonly{{end}}>{{.Instructions}}</textarea></label> |
| +<label>{{copy "plan.model"}}<input rst-input name="step_{{.Index}}_model" value="{{.Model}}" {{if .Locked}}readonly{{end}}></label>{{if .Locked}}<input type="hidden" name="step_{{.Index}}_connection" value="{{.ConnectionID}}"><span equipo-value>{{.Account}}</span>{{else}}<label>{{copy "plan.connection"}}<select rst-input name="step_{{.Index}}_connection">{{$connection := .ConnectionID}}{{if .ConnectionID}}<option value="{{.ConnectionID}}" selected>{{if .Account}}{{.Account}}{{else}}{{copy "plan.current_selection"}}{{end}}</option>{{end}}<option value="">{{copy "plan.unselected"}}</option>{{range $.Plan.Connections}}{{if ne .ID $connection}}<option value="{{.ID}}">{{.Label}}</option>{{end}}{{end}}</select></label>{{end}}<label>{{copy "plan.reason"}}<input rst-input name="step_{{.Index}}_reason" value="{{.SelectionReason}}" {{if .Locked}}readonly{{end}}></label> |
| +{{if .Actual}}<p equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</p>{{end}} |
| +{{if and (not .Locked) (not .Required)}}<label equipo-checkbox><input type="checkbox" name="step_{{.Index}}_remove" value="1">{{copy "plan.remove_step"}}</label>{{end}} |
| +</fieldset> |
| +{{end}} |
| +{{if lt (len .Steps) 16}}<details><summary>{{copy "plan.add_step"}}</summary><fieldset>{{$i := len .Steps}} |
| +<label>{{copy "plan.step_key"}}<input rst-input name="step_{{$i}}_key"></label><label>{{copy "plan.specialist"}}<select rst-input name="step_{{$i}}_specialist"><option value=""></option>{{range .Steps}}{{if .Specialist}}<option value="{{.Specialist}}">{{copy (printf "nav.%s" .Specialist)}}</option>{{end}}{{end}}<option value="product">{{copy "nav.product"}}</option><option value="design">{{copy "nav.design"}}</option><option value="copy">{{copy "nav.copy"}}</option></select></label> |
| +<label>{{copy "plan.action"}}<select rst-input name="step_{{$i}}_action"><option value="investigate">{{copy "plan.action.investigate"}}</option><option value="recommend">{{copy "plan.action.recommend"}}</option><option value="implement">{{copy "plan.action.implement"}}</option><option value="copy">{{copy "plan.action.copy"}}</option><option value="design">{{copy "plan.action.design"}}</option></select></label> |
| +<label>{{copy "plan.position"}}<input rst-input name="step_{{$i}}_position" type="number" min="1" max="16"></label><label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{$i}}_instructions"></textarea></label> |
| +</fieldset></details>{{end}} |
| +<button rst-btn="primary" type="submit">{{copy "form.save"}}</button> |
| +</form> |
| +<form method="post" action="/tasks/{{.Task.ID}}/plan/approve" equipo-form><input type="hidden" name="request_id" value="{{.ApproveID}}"><input type="hidden" name="revision" value="{{.Plan.Revision}}"><button rst-btn type="submit">{{copy "plan.approve"}}</button></form> |
| +<section id="project" equipo-card><h2>{{copy "plan.project"}}</h2><form method="post" action="/tasks/{{.Task.ID}}/project" equipo-form><input type="hidden" name="request_id" value="{{.CorrectID}}"><input type="hidden" name="revision" value="{{.Task.Revision}}"><label>{{copy "plan.correct_project"}}<select rst-input name="project_id">{{$project := .Plan.ProjectID}}{{range .Projects}}<option value="{{.ID}}" {{if eq .ID $project}}selected{{end}}>{{.Name}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "plan.correct_project"}}</button></form></section> |
| +{{else}}<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step data-plan-step="{{.Key}}"><strong>{{copy (printf "plan.action.%s" .Action)}}</strong><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><p>{{.Instructions}}</p><span equipo-value>{{.Model}} {{.Account}}</span><span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span></li>{{end}}</ol>{{end}} |
| +<section equipo-card><h2>{{copy "plan.approval_settings"}}</h2><p>{{copy (printf "plan.%s" .Effective)}}</p> |
| +{{if .Owner}}<form method="post" action="/tasks/{{.Task.ID}}/plan/settings" equipo-form><input type="hidden" name="request_id" value="{{.ProjectSettingID}}"><input type="hidden" name="revision" value="{{.ProjectSetting.Revision}}"><input type="hidden" name="scope" value="project"><label>{{copy "plan.project"}}<select rst-input name="mode"><option value="immediate" {{if ne .ProjectSetting.Mode "required"}}selected{{end}}>{{copy "plan.immediate"}}</option><option value="required" {{if eq .ProjectSetting.Mode "required"}}selected{{end}}>{{copy "plan.required"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{end}} |
| +<form method="post" action="/tasks/{{.Task.ID}}/plan/settings" equipo-form><input type="hidden" name="request_id" value="{{.PersonalSettingID}}"><input type="hidden" name="revision" value="{{.PersonalSetting.Revision}}"><input type="hidden" name="scope" value="personal"><label>{{copy "plan.personal_override"}}<select rst-input name="mode"><option value="" {{if eq .PersonalSetting.Mode ""}}selected{{end}}>{{copy "plan.inherit"}}</option><option value="immediate" {{if eq .PersonalSetting.Mode "immediate"}}selected{{end}}>{{copy "plan.immediate"}}</option><option value="required" {{if eq .PersonalSetting.Mode "required"}}selected{{end}}>{{copy "plan.required"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form> |
| +</section> |
| +{{end}}</div> |
| +{{end}} |
diff --git a/internal/equipo/templates/settings.html b/internal/equipo/templates/settings.html| index c43e6203..15b66ecf 100644 |
| --- a/internal/equipo/templates/settings.html |
| +++ b/internal/equipo/templates/settings.html |
| @@ -1,4 +1,5 @@ |
| {{define "content"}} |
| +<a href="/settings/coordinator">{{copy "coordinator.settings"}}</a> |
| <a href="/preferences">{{copy "preferences.title"}}</a>{{if .Owner}}<a href="/settings/recovery">{{copy "recovery.title"}}</a>{{end}} |
| <h1>{{copy "nav.settings"}}</h1> |
| <p>{{copy "account.note"}}</p> |
diff --git a/internal/equipo/templates/task.html b/internal/equipo/templates/task.html| index 95208fe3..41ea15ea 100644 |
| --- a/internal/equipo/templates/task.html |
| +++ b/internal/equipo/templates/task.html |
| @@ -6,7 +6,7 @@ |
| {{if .CanCancel}}<form method="post" action="/tasks/{{.Task.ID}}/cancel"><button rst-btn type="submit">{{copy "task.cancel"}}</button></form>{{end}} |
| {{if .CanMerge}}<a rst-btn href="/tasks/{{.Task.ID}}/merge">{{copy "task.merge"}}</a>{{end}} |
| {{if eq .Task.Kind "rendered_change"}}<a rst-btn href="/tasks/{{.Task.ID}}/rendered-change">{{copy "evidence.render_approval"}}</a>{{end}} |
| -<h2>{{copy "task.selected"}}</h2>{{range .Steps}}<p>{{copy (printf "step.%s" .Key)}}: {{.Model}} {{.Account}}</p>{{if .Actual}}<p>{{copy "task.actual"}}: {{.Actual}}</p>{{end}}{{if .AllowanceKnown}}<p>{{copy "usage.allowance"}}: {{.AllowanceRemaining}}</p>{{else}}{{if .Model}}<p>{{copy "usage.allowance_unknown"}}</p>{{end}}{{end}}{{template "isolation-history" .Isolation}}{{end}} |
| +<h2>{{copy "task.selected"}}</h2>{{range .Steps}}<p>{{copy (printf "plan.action.%s" .Action)}}: {{.Model}} {{.Account}}</p>{{if .Actual}}<p>{{copy "task.actual"}}: {{.Actual}}</p>{{end}}{{if .AllowanceKnown}}<p>{{copy "usage.allowance"}}: {{.AllowanceRemaining}}</p>{{else}}{{if .Model}}<p>{{copy "usage.allowance_unknown"}}</p>{{end}}{{end}}{{template "isolation-history" .Isolation}}{{end}} |
| <h2>{{copy "budget.usage"}}</h2>{{if .UsageKnown}}<p>{{copy "usage.counted_turns"}}: {{.CountedTurns}}</p><p>{{copy "usage.tokens"}}: {{.InputTokens}} / {{.OutputTokens}}</p>{{else}}<p>{{copy "usage.unknown"}}</p>{{end}} |
| <h2>{{copy "task.questions"}}</h2>{{range .Questions}}<section equipo-card><pre>{{.Text}}</pre><p>{{copy (printf "question.%s" .State)}}</p>{{if .CanAnswer}}<a rst-btn href="/tasks/{{$.TaskView.Task.ID}}/questions/{{.ID}}">{{copy "task.answer"}}</a>{{end}}</section>{{end}} |
| <h2>{{copy "task.evidence"}}</h2>{{range .Evidence}}<section equipo-card><p>{{.Role}} {{.Hash}}</p>{{if .Unconfined}}<p>{{copy "isolation.unconfined"}}</p>{{end}}<p>{{.Actual}}</p>{{template "isolation-history" .Isolation}}<pre>{{.Detail}}</pre></section>{{end}} |
diff --git a/internal/equipo/templates/task_card.html b/internal/equipo/templates/task_card.html| index 624405c7..adcc5e78 100644 |
| --- a/internal/equipo/templates/task_card.html |
| +++ b/internal/equipo/templates/task_card.html |
| @@ -1,7 +1,7 @@ |
| {{define "task-card"}} |
| <article equipo-task data-task="{{.Task.ID}}"> |
| -<div equipo-card><h3><a href="/tasks/{{.Task.ID}}">{{.Task.Description}}</a></h3><p>{{.Project.Name}}</p><p>{{copy .StateKey}}</p>{{if .Unconfined}}<p equipo-isolation>{{copy "isolation.unconfined"}}</p>{{end}}{{template "trial-label" .Isolation}}</div> |
| -<ol equipo-steps>{{range .Steps}}<li equipo-step data-step="{{.Key}}"><strong>{{copy (printf "nav.%s" .Category)}}</strong><span>{{copy (printf "step.%s" .Key)}}</span><span>{{.Model}} {{.Account}}{{.Person}}</span><span>{{copy (printf "step.%s" .State)}}</span>{{if .Unconfined}}<span equipo-isolation>{{copy "isolation.unconfined"}}</span>{{end}}{{template "trial-label" .Isolation}}</li>{{end}}</ol> |
| +<div equipo-card><h3><a href="/tasks/{{.Task.ID}}">{{.Task.Description}}</a></h3><p equipo-secondary>{{.Project.Name}}</p><a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a> <a href="/tasks/{{.Task.ID}}/plan">{{copy "plan.edit"}}</a><p>{{copy .StateKey}}</p>{{if .Unconfined}}<p equipo-isolation>{{copy "isolation.unconfined"}}</p>{{end}}{{template "trial-label" .Isolation}}</div> |
| +<ol equipo-steps>{{range .Steps}}<li equipo-step data-step="{{.Key}}"><strong>{{copy (printf "nav.%s" .Category)}}</strong><span>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-value>{{.Model}} {{.Account}}{{.Person}}</span><span equipo-secondary title="{{.Reason}}">{{.Reason}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span>{{if .Unconfined}}<span equipo-isolation>{{copy "isolation.unconfined"}}</span>{{end}}{{template "trial-label" .Isolation}}</li>{{end}}</ol> |
| </article> |
| {{end}} |
| {{define "task-groups"}}{{range $group := taskGroups}}<section><h2>{{copy (printf "task.group.%s" $group)}}</h2>{{range $.Tasks}}{{if eq .Group $group}}{{template "task-card" .}}{{end}}{{end}}</section>{{end}}{{if not .Tasks}}<p data-empty-state="{{.Key}}.empty">{{copy "task.empty"}}</p>{{end}}{{end}} |
diff --git a/internal/equipo/templates/thread.html b/internal/equipo/templates/thread.html| new file mode 100644 |
| index 00000000..87fc7150 |
| --- /dev/null |
| +++ b/internal/equipo/templates/thread.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}{{copy "conversation.thread_link"}}{{end}} |
| +{{define "up"}}/tasks/{{.Conversation.ThreadID}}{{end}} |
| +{{define "content"}} |
| +<div equipo-conversation> |
| +<h1>{{copy "conversation.thread_link"}}</h1><p equipo-muted>{{copy "conversation.shared_thread"}}</p> |
| +<a href="/tasks/{{.Conversation.ThreadID}}/plan">{{copy "plan.edit"}}</a> |
| +{{template "region:conversation-feed" .}} |
| +{{template "conversation-composer" .}} |
| +</div> |
| +{{end}} |
diff --git a/internal/plan3test/conversation_browser_test.go b/internal/plan3test/conversation_browser_test.go| new file mode 100644 |
| index 00000000..dfd975db |
| --- /dev/null |
| +++ b/internal/plan3test/conversation_browser_test.go |
| @@ -0,0 +1,264 @@ |
| +package plan3test |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "gorm.io/plugin/dbresolver" |
| + "io" |
| + "log/slog" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| +) |
| + |
| +func formPost(t *testing.T, f *fixture, actor equipo.Actor, path string, v url.Values) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest("POST", path, strings.NewReader(v.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", origin) |
| + r.AddCookie(f.Cookies[actor.Address]) |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + return w |
| +} |
| +func actionForm(id string, revision int64) url.Values { |
| + return url.Values{"request_id": {id}, "revision": {fmt.Sprint(revision)}} |
| +} |
| +func expectHTTP(t *testing.T, w *httptest.ResponseRecorder, code int) { |
| + t.Helper() |
| + if w.Code != code { |
| + t.Fatalf("HTTP %d, want %d: %s", w.Code, code, w.Body.String()) |
| + } |
| +} |
| +func planForm(p taskplan.Plan, id string) url.Values { |
| + v := actionForm(id, p.Revision) |
| + v.Set("kind", string(p.Kind)) |
| + v.Set("project_id", fmt.Sprint(p.ProjectID)) |
| + v.Set("playbook_id", p.PlaybookID) |
| + v.Set("playbook_revision", fmt.Sprint(p.PlaybookRevision)) |
| + v.Set("step_count", fmt.Sprint(len(p.Steps))) |
| + for i, s := range p.Steps { |
| + prefix := fmt.Sprintf("step_%d_", i) |
| + for k, value := range map[string]string{"key": s.Key, "specialist": s.Specialist, "action": s.Action, "instructions": s.Instructions, "connection": s.ConnectionID, "model": s.Model, "reason": s.SelectionReason, "depends_on": strings.Join(s.DependsOn, ","), "position": fmt.Sprint(i + 1)} { |
| + v.Set(prefix+k, value) |
| + } |
| + } |
| + return v |
| +} |
| +func TestConversationScriptless(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `id="composer"`) { |
| + t.Fatal("conversation composer missing") |
| + } |
| + v := actionForm("send", 0) |
| + v.Set("body", "A <script>draft</script> for the team") |
| + expectHTTP(t, formPost(t, f, owner, "/conversation", v), 303) |
| + expectHTTP(t, formPost(t, f, owner, "/conversation", v), 303) |
| + page, err := f.Store.Conversation(ctx, owner, "", 100) |
| + must(t, err) |
| + msg := page.Messages[len(page.Messages)-1] |
| + w = f.get(t, owner, "/conversation") |
| + if strings.Contains(w.Body.String(), "<script>draft</script>") || !strings.Contains(w.Body.String(), "<script>") { |
| + t.Fatal("message not escaped") |
| + } |
| + route := actionForm("route", msg.Revision) |
| + route.Set("task_id", p.TaskID) |
| + expectHTTP(t, formPost(t, f, owner, "/conversation/messages/"+msg.ID+"/route", route), 303) |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/thread") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "<script>") { |
| + t.Fatal("routed reply missing") |
| + } |
| + p.Steps[1].Instructions = "Use the existing service" |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/plan", planForm(p, "edit")), 303) |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/plan", planForm(p, "stale")), 409) |
| + p, err = f.Store.TaskPlan(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if p.Steps[1].Instructions != "Use the existing service" { |
| + t.Fatal("plan edit lost") |
| + } |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `name="revision" value="2"`) { |
| + t.Fatal("plan revision missing") |
| + } |
| + target := equipo.Project{Name: "corrected project", Repository: "amadan.net/test/corrected", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&target).Error) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: target.ID, Decision: "merge", Address: owner.Address}).Error) |
| + task, err := f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + v = actionForm("correct", task.Revision) |
| + v.Set("project_id", fmt.Sprint(target.ID)) |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/project", v), 303) |
| + task, err = f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if task.ProjectID != target.ID { |
| + t.Fatal("project correction lost") |
| + } |
| + t.Run("waiting and questions", func(t *testing.T) { |
| + f, x, principal, c := claimTools(t) |
| + q := toolCall(t, x, principal, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a project", "options": []map[string]string{{"id": "one", "label": "First project"}}}) |
| + v := actionForm("answer", 1) |
| + v.Set("option_id", "one") |
| + expectHTTP(t, formPost(t, f, owner, "/conversation/questions/"+q.ResourceID+"/answer", v), 303) |
| + var waiting equipo.Task |
| + must(t, f.DB.G.First(&waiting).Error) |
| + raw, _ := json.Marshal(waiting.ID) |
| + f.exec(t, "INSERT INTO conversation_requests(principal,operation,resource,request_id,input_hash,result) VALUES(?,?,?,?,?,?)", owner.Address, "coordinator.waiting", c.Binding.ID, "current", "fixture", string(raw)) |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `href="/tasks/`+waiting.ID+`"`) || !strings.Contains(w.Body.String(), "Waiting for") { |
| + t.Fatal("waiting card lacks blocking task link") |
| + } |
| + }) |
| +} |
| +func TestConversationNoProjectPicker(t *testing.T) { |
| + f, x, principal, c := claimTools(t) |
| + q := toolCall(t, x, principal, c, "ambiguity", "propose_plan", proposalArgs(c.Turn.MessageID, 0)) |
| + var project int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| + proposal := toolCall(t, x, principal, c, "proposal", "propose_plan", proposalArgs(c.Turn.MessageID, project)) |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + body := w.Body.String() |
| + start := strings.Index(body, `id="composer"`) |
| + if start < 0 { |
| + t.Fatal("missing composer") |
| + } |
| + end := strings.Index(body[start:], "</form>") |
| + if end < 0 { |
| + t.Fatal("composer not a form") |
| + } |
| + if strings.Contains(body[start:start+end], "project_id") || strings.Contains(body[start:start+end], "<select") { |
| + t.Fatal("project picker in composer") |
| + } |
| + if !strings.Contains(body, `/tasks/`+proposal.ResourceID+`/plan#project`) || !strings.Contains(body, `/conversation/questions/`+q.ResourceID+`/answer`) || !strings.Contains(body, `name="option_id"`) { |
| + t.Fatal("chosen project or one-tap clarification missing", body) |
| + } |
| +} |
| +func liveFixture(t *testing.T, f *fixture) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + router, err := equipo.RouterWithStore(f.DB, equipo.Config{Origin: origin, InstanceKey: "plan3-fixture", AllowLoggedMail: true, AlwaysOn: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, f.Store) |
| + must(t, err) |
| + t.Cleanup(func() { equipo.CloseLive(router) }) |
| + f.Handler = equipo.Mux(router) |
| +} |
| +func watchConversation(t *testing.T, f *fixture, actor equipo.Actor, topic string) int { |
| + t.Helper() |
| + watchctx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + r := httptest.NewRequest("GET", "/live?t="+url.QueryEscape(topic+"@0"), nil).WithContext(watchctx) |
| + r.AddCookie(f.Cookies[actor.Address]) |
| + w := &preferenceStream{ResponseRecorder: httptest.NewRecorder(), cancel: cancel} |
| + f.Handler.ServeHTTP(w, r) |
| + return w.Code |
| +} |
| + |
| +type conversationNotifier struct { |
| + deadlines []string |
| + topics []string |
| + check func() |
| +} |
| + |
| +func (n *conversationNotifier) Notify(topics ...string) { |
| + if n.check != nil { |
| + n.check() |
| + } |
| + n.topics = append(n.topics, topics...) |
| +} |
| +func (n *conversationNotifier) NotifyAt(at time.Time, topics ...string) { |
| + for _, topic := range topics { |
| + if strings.HasPrefix(topic, "conversation/") { |
| + n.deadlines = append(n.deadlines, topic) |
| + } |
| + } |
| +} |
| +func TestConversationLivePrivacy(t *testing.T) { |
| + f := newFixture(t) |
| + liveFixture(t, f) |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + var resource string |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM conversations WHERE person=?", owner.Address).Scan(&resource)) |
| + topic := conversation.ConversationTopic(f.TeamID, owner.Address, resource) |
| + if !strings.Contains(w.Body.String(), `data-live="`+topic+"@") { |
| + t.Fatal("missing private live region") |
| + } |
| + if watchConversation(t, f, owner, topic) != 200 || watchConversation(t, f, peer, topic) != 403 { |
| + t.Fatal("private topic authorization failed") |
| + } |
| + n := &conversationNotifier{check: func() { |
| + var count int64 |
| + must(t, f.DB.G.Clauses(dbresolver.Read).Raw("SELECT count(*) FROM conversation_messages WHERE body='committed'").Scan(&count).Error) |
| + if count != 1 { |
| + t.Error("notification before commit") |
| + } |
| + }} |
| + f.Store.SetJobNotifier(n) |
| + _, err := f.Store.SendMessage(ctx, owner, "", "committed", equipo.Mutation{RequestID: "live"}) |
| + must(t, err) |
| + if !strings.Contains(strings.Join(n.topics, " "), topic) { |
| + t.Fatal("conversation change not invalidated") |
| + } |
| + n.topics = nil |
| + f.exec(t, "CREATE TRIGGER ui_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| + _, err = f.Store.SendMessage(ctx, owner, "", "rollback", equipo.Mutation{RequestID: "rollback"}) |
| + if err == nil || len(n.topics) != 0 { |
| + t.Fatal("rollback emitted notification") |
| + } |
| + f.exec(t, "DROP TRIGGER ui_audit_failure") |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + if watchConversation(t, f, owner, topic) == 200 { |
| + t.Fatal("removed member retained subscription") |
| + } |
| +} |
| +func TestConversationQuestionRace(t *testing.T) { |
| + for _, state := range []string{"current", "expired", "cancelled", "superseded"} { |
| + t.Run(state, func(t *testing.T) { |
| + f, x, principal, c := claimTools(t) |
| + q := toolCall(t, x, principal, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose", "options": []map[string]string{{"id": "one", "label": "One"}}}) |
| + path := "/conversation/questions/" + q.ResourceID + "/answer" |
| + v := actionForm("stale", 2) |
| + v.Set("option_id", "one") |
| + expectHTTP(t, formPost(t, f, owner, path, v), 409) |
| + v = actionForm("answer", 1) |
| + v.Set("option_id", "one") |
| + expectHTTP(t, formPost(t, f, peer, path, v), 404) |
| + if state == "expired" { |
| + f.exec(t, `UPDATE coordinator_questions SET payload=json_set(payload,'$.ExpiresAt','2000-01-01T00:00:00Z') WHERE id=?`, q.ResourceID) |
| + } |
| + if state == "cancelled" { |
| + f.exec(t, "UPDATE coordinator_turns SET state='cancelled' WHERE id=?", c.Turn.ID) |
| + } |
| + if state == "superseded" { |
| + f.exec(t, "UPDATE coordinator_questions SET state='superseded' WHERE id=?", q.ResourceID) |
| + } |
| + want := 409 |
| + if state == "current" { |
| + want = 303 |
| + } |
| + expectHTTP(t, formPost(t, f, owner, path, v), want) |
| + expectHTTP(t, formPost(t, f, owner, path, v), want) |
| + if state == "current" { |
| + v.Set("request_id", "second") |
| + expectHTTP(t, formPost(t, f, owner, path, v), 409) |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE request_id=?", "clarification:"+q.ResourceID) != 1 { |
| + t.Fatal("answer reached more than one continuation") |
| + } |
| + } else if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE request_id=?", "clarification:"+q.ResourceID) != 0 { |
| + t.Fatal("inactive question reached provider continuation") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/plan3test/conversation_forms_test.go b/internal/plan3test/conversation_forms_test.go| new file mode 100644 |
| index 00000000..e2644b58 |
| --- /dev/null |
| +++ b/internal/plan3test/conversation_forms_test.go |
| @@ -0,0 +1,218 @@ |
| +package plan3test |
| + |
| +import ( |
| + "fmt" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +func TestConversationScriptlessPlanGuards(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + // Read-only steps may be reordered until claimed. |
| + p.Steps = append([]taskplan.Step{{Key: "inspect", Specialist: "engineering", Action: "investigate", Instructions: "Read current code"}}, p.Steps...) |
| + v := planForm(p, "add") |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/plan", v), 303) |
| + p, err := f.Store.TaskPlan(ctx, owner, p.TaskID) |
| + must(t, err) |
| + p.Steps[0], p.Steps[1] = p.Steps[1], p.Steps[0] |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/plan", planForm(p, "reorder")), 303) |
| + got, err := f.Store.TaskPlan(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if got.Steps[0].Key != "reproduce" || got.Steps[1].Key != "inspect" { |
| + t.Fatal("unstarted reorder ignored") |
| + } |
| + // The server rejects submitted changes to a claimed step even if readonly is removed. |
| + f2 := newFixture(t) |
| + p = proposed(t, f2) |
| + x, _, scope := f2.planCore(t, p) |
| + _, err = x.Core.Claim(ctx, scope, "reproduce", "runner", "workspace") |
| + must(t, err) |
| + p.Steps[0].Instructions = "forged started instructions" |
| + expectHTTP(t, formPost(t, f2, owner, "/tasks/"+p.TaskID+"/plan", planForm(p, "locked")), 422) |
| + w := f2.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "This step has started") || !strings.Contains(w.Body.String(), "readonly") { |
| + t.Fatal("started step is not visibly locked") |
| + } |
| +} |
| +func TestConversationScriptlessSettings(t *testing.T) { |
| + f, x, _, b := coordinatorFixture(t) |
| + _ = x |
| + liveFixture(t, f) |
| + w := f.get(t, owner, "/settings/coordinator") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `value="claude" selected`) || !strings.Contains(w.Body.String(), `name="calls" value="24"`) { |
| + t.Fatal("coordinator settings missing", w.Body.String()) |
| + } |
| + v := actionForm("binding", b.Revision) |
| + v.Set("action", "bind") |
| + v.Set("connection_id", "codex") |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + got, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if got.ConnectionID != "codex" { |
| + t.Fatal("binding ignored") |
| + } |
| + v = actionForm("reset", got.Revision) |
| + v.Set("action", "reset") |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + v = actionForm("limits-ui", 1) |
| + v.Set("action", "limits") |
| + v.Set("calls", "12") |
| + v.Set("input_tokens", "100000") |
| + v.Set("output_tokens", "20000") |
| + v.Set("seconds", "5000") |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + v.Set("request_id", "stale-limit") |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 409) |
| + f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| + v.Set("revision", "0") |
| + expectHTTP(t, formPost(t, f, peer, "/settings/coordinator", v), 403) |
| + w = f.get(t, peer, "/settings/coordinator") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "Ask a team owner to set coordinator limits.") || strings.Contains(w.Body.String(), `name="calls"`) { |
| + t.Fatal("missing budget setup or owner gate") |
| + } |
| + settings, err := f.Store.PersonalSettings(ctx, owner) |
| + must(t, err) |
| + v = actionForm("landing", settings.Revision) |
| + v.Set("action", "landing") |
| + v.Set("landing", "work") |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + if w = f.get(t, owner, "/"); w.Header().Get("Location") != "/work" { |
| + t.Fatal("landing setting ignored") |
| + } |
| + var task equipo.Task |
| + must(t, f.DB.G.First(&task).Error) |
| + path := "/tasks/" + task.ID + "/plan/settings" |
| + v = actionForm("project-approval", 0) |
| + v.Set("scope", "project") |
| + v.Set("mode", "required") |
| + expectHTTP(t, formPost(t, f, owner, path, v), 303) |
| + v = actionForm("personal-approval", 0) |
| + v.Set("scope", "personal") |
| + v.Set("mode", "immediate") |
| + expectHTTP(t, formPost(t, f, peer, path, v), 303) |
| + mode, err := f.Store.PlanApproval(ctx, peer, task.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalImmediate { |
| + t.Fatal("personal override ignored") |
| + } |
| + v = actionForm("inherit", 1) |
| + v.Set("scope", "personal") |
| + v.Set("mode", "") |
| + expectHTTP(t, formPost(t, f, peer, path, v), 303) |
| + mode, err = f.Store.PlanApproval(ctx, peer, task.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalRequired { |
| + t.Fatal("inherit ignored") |
| + } |
| + v = actionForm("owner-only", 1) |
| + v.Set("scope", "project") |
| + v.Set("mode", "immediate") |
| + expectHTTP(t, formPost(t, f, peer, path, v), 403) |
| +} |
| +func TestConversationLiveFragments(t *testing.T) { |
| + for _, always := range []bool{false, true} { |
| + t.Run(fmt.Sprint(always), func(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + if always { |
| + liveFixture(t, f) |
| + } |
| + for _, path := range []string{"/conversation", "/tasks/" + p.TaskID + "/thread"} { |
| + w := f.get(t, owner, path) |
| + expectHTTP(t, w, 200) |
| + body := w.Body.String() |
| + start := strings.Index(body, `id="composer"`) |
| + if start < 0 { |
| + t.Fatal("missing composer") |
| + } |
| + if strings.Contains(body[start:], "data-live=") { |
| + t.Fatal("composer included in live region") |
| + } |
| + r := httptest.NewRequest("GET", path, nil) |
| + r.AddCookie(f.Cookies[owner.Address]) |
| + r.Header.Set("Rastrillo-Fragment", "conversation-feed") |
| + w = httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + expectHTTP(t, w, 200) |
| + if strings.Contains(w.Body.String(), `id="composer"`) || !strings.Contains(w.Body.String(), "conversation-feed") { |
| + t.Fatal("fragment replaced composer", w.Body.String()) |
| + } |
| + } |
| + // Current plan updates notify the private conversation after its card exists. |
| + n := &conversationNotifier{} |
| + f.Store.SetJobNotifier(n) |
| + p.Steps[1].Instructions = "new plan instructions" |
| + _, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "change", Revision: 1}) |
| + must(t, err) |
| + if !strings.Contains(strings.Join(n.topics, " "), "conversation/") { |
| + t.Fatal("plan card not invalidated") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestConversationLiveRecentAndCards(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + for i := 0; i < 55; i++ { |
| + _, err := f.Store.SendMessage(ctx, owner, "", fmt.Sprintf("message-%02d", i), equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| + must(t, err) |
| + } |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "message-54") || !strings.Contains(w.Body.String(), "/tasks/"+p.TaskID+"/plan") { |
| + t.Fatal("recent message or earlier live card missing") |
| + } |
| + cards, err := f.Store.ConversationCards(ctx, owner) |
| + must(t, err) |
| + if len(cards) != 1 || cards[0].ResourceID != p.TaskID { |
| + t.Fatal("current cards lost to message pagination") |
| + } |
| +} |
| + |
| +func TestConversationLiveQuestionExpiry(t *testing.T) { |
| + f, x, principal, c := claimTools(t) |
| + liveFixture(t, f) |
| + n := &conversationNotifier{} |
| + f.Store.SetJobNotifier(n) |
| + toolCall(t, x, principal, c, "expiry", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Expires later", "options": []any{}}) |
| + if len(n.deadlines) == 0 { |
| + t.Fatal("clarification expiry has no scheduled invalidation") |
| + } |
| + for _, topic := range n.deadlines { |
| + if !strings.HasPrefix(topic, "conversation/") { |
| + t.Fatal("question deadline lacks private topic") |
| + } |
| + } |
| +} |
| + |
| +func TestConversationScriptlessMissingPlan(t *testing.T) { |
| + f := newFixture(t) |
| + expectHTTP(t, f.get(t, owner, "/tasks/absent/plan"), 404) |
| +} |
| + |
| +func TestConversationScriptlessConnectionChoices(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + w := f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `select rst-input name="step_0_connection"`) || !strings.Contains(w.Body.String(), "claude / fixture-model") { |
| + t.Fatal("plan asks for an opaque connection identifier") |
| + } |
| + f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]' WHERE person=?`, owner.Address) |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if strings.Contains(w.Body.String(), `option value="claude"`) { |
| + t.Fatal("plan offered an excluded connection") |
| + } |
| +} |
diff --git a/internal/plan3test/conversation_layout_browser_test.go b/internal/plan3test/conversation_layout_browser_test.go| new file mode 100644 |
| index 00000000..85c126be |
| --- /dev/null |
| +++ b/internal/plan3test/conversation_layout_browser_test.go |
| @@ -0,0 +1,99 @@ |
| +//go:build browser |
| + |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "context" |
| + "fmt" |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| + "github.com/chromedp/chromedp/kb" |
| + "net/http" |
| + "os/exec" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestConversationLayout(t *testing.T) { |
| + found := false |
| + for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} { |
| + if _, err := exec.LookPath(name); err == nil { |
| + found = true |
| + break |
| + } |
| + } |
| + if !found { |
| + t.Skip("Chrome/Chromium is unavailable locally; conversation layout requires the existing chromedp browser fixture") |
| + } |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + p.Steps[1].SelectionReason = strings.Repeat("A long reason for this selection ", 30) |
| + var err error |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "browser-reason", Revision: p.Revision}) |
| + must(t, err) |
| + liveFixture(t, f) |
| + rig := harness.New(t, func(string) http.Handler { return f.Handler }, harness.WithScrollbars()) |
| + cookie := f.Cookies[owner.Address] |
| + rig.Run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: rig.Origin, Path: "/"}) |
| + return err |
| + })) |
| + for _, width := range []int64{390, 1280} { |
| + for _, scale := range []int{100, 200} { |
| + rig.Run(chromedp.EmulateViewport(width, 900), chromedp.Navigate(rig.Origin+"/conversation")) |
| + harness.Evaluate[bool](rig, fmt.Sprintf(`(document.documentElement.style.fontSize='%d%%',true)`, scale)) |
| + if !harness.Evaluate[bool](rig, `document.documentElement.scrollWidth<=innerWidth && getComputedStyle(document.querySelector('[equipo-conversation]')).display==='block'`) { |
| + t.Fatal("conversation overflow or split screen") |
| + } |
| + if !harness.Evaluate[bool](rig, `Array.from(document.querySelectorAll('[equipo-value],[equipo-badge]')).every(e=>getComputedStyle(e).whiteSpace==='nowrap')`) { |
| + t.Fatal("wrapping values or badges") |
| + } |
| + if !harness.Evaluate[bool](rig, `Array.from(document.querySelectorAll('[equipo-card],[equipo-note]')).every(e=>{let s=getComputedStyle(e);return s.borderLeftColor===s.borderRightColor && s.borderLeftWidth===s.borderRightWidth})`) { |
| + t.Fatal("coloured left accent") |
| + } |
| + rig.Run(chromedp.KeyEvent(kb.Tab)) |
| + if !harness.Evaluate[bool](rig, `document.activeElement.matches('[rst-skip]')`) { |
| + t.Fatal("lost keyboard focus") |
| + } |
| + if !harness.Evaluate[bool](rig, `Array.from(document.querySelectorAll('[equipo-secondary]')).every(e=>getComputedStyle(e).textOverflow==='ellipsis' && getComputedStyle(e).whiteSpace==='nowrap') && Array.from(document.querySelectorAll('[rst-person-av]')).every(e=>e.textContent.trim()==='')`) { |
| + t.Fatal("secondary text wraps or initials shown") |
| + } |
| + rig.Run(chromedp.Focus(chromedp.CSS(`#composer textarea`)), chromedp.SendKeys(chromedp.CSS(`#composer textarea`), "Keep this draft")) |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "live arrival", equipo.Mutation{RequestID: fmt.Sprintf("arrival-%d-%d", width, scale)}) |
| + must(t, err) |
| + rig.Run(conversationBrowserWait(fmt.Sprintf(`!!document.querySelector('[data-message="%s"]')`, msg.ID))) |
| + if !harness.Evaluate[bool](rig, `document.activeElement.matches('#composer textarea') && document.activeElement.value==='Keep this draft'`) { |
| + t.Fatal("live invalidation lost composer draft or focus") |
| + } |
| + rig.Run(chromedp.Navigate(rig.Origin + "/tasks/" + p.TaskID + "/plan")) |
| + harness.Evaluate[bool](rig, fmt.Sprintf(`(document.documentElement.style.fontSize='%d%%',true)`, scale)) |
| + if !harness.Evaluate[bool](rig, `document.documentElement.scrollWidth<=innerWidth`) { |
| + t.Fatal("plan overflow") |
| + } |
| + } |
| + } |
| +} |
| + |
| +func conversationBrowserWait(expression string) chromedp.Action[chromedp.Void] { |
| + return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + tick := time.NewTicker(20 * time.Millisecond) |
| + defer tick.Stop() |
| + for { |
| + ok, err := chromedp.Evaluate[bool](expression)(ctx, target) |
| + if err == nil && ok { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("waiting for %s: %w", expression, ctx.Err()) |
| + case <-tick.C: |
| + } |
| + } |
| + }) |
| +} |
diff --git a/internal/plan3test/conversation_layout_test.go b/internal/plan3test/conversation_layout_test.go| new file mode 100644 |
| index 00000000..94d8bb76 |
| --- /dev/null |
| +++ b/internal/plan3test/conversation_layout_test.go |
| @@ -0,0 +1,17 @@ |
| +//go:build !browser |
| + |
| +package plan3test |
| + |
| +import ( |
| + "os/exec" |
| + "testing" |
| +) |
| + |
| +func TestConversationLayout(t *testing.T) { |
| + for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} { |
| + if _, err := exec.LookPath(name); err == nil { |
| + t.Skip("Run with -tags browser to enable the existing chromedp fixtures") |
| + } |
| + } |
| + t.Skip("Chrome/Chromium is unavailable locally; conversation layout requires the existing chromedp browser fixture") |
| +} |
diff --git a/internal/plan3test/conversation_native_test.go b/internal/plan3test/conversation_native_test.go| new file mode 100644 |
| index 00000000..15fde075 |
| --- /dev/null |
| +++ b/internal/plan3test/conversation_native_test.go |
| @@ -0,0 +1,111 @@ |
| +package plan3test |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +func nativeConversationFixture(t *testing.T) (*fixture, *equipo.Execution, equipo.RunnerPrincipal, equipo.RunnerRequest, runnerproto.Question) { |
| + t.Helper() |
| + f, x, principal, _ := coordinatorFixture(t) |
| + var original equipo.Task |
| + must(t, f.DB.G.First(&original).Error) |
| + p, err := f.Store.ProposePlan(ctx, owner, taskplan.Plan{Kind: taskplan.Recommendation, ProjectID: original.ProjectID, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend", Instructions: "Read project material"}, {Key: "merge", Action: "person"}}}, equipo.Mutation{RequestID: "native-plan"}) |
| + must(t, err) |
| + // Retain just the read task for deterministic offline assignment. |
| + f.exec(t, "UPDATE tasks SET state='cancelled' WHERE id=?", original.ID) |
| + must(t, x.Sync(ctx)) |
| + var id string |
| + var revision int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &revision)) |
| + claim, err := x.Claim(ctx, principal, equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: revision, RequestID: "native-claim"}) |
| + must(t, err) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Question: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + q := runnerproto.Question{ID: "native-question", TaskID: p.TaskID, ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "permission", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"permission","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)} |
| + request := equipo.RunnerRequest{Version: 2, AssignmentID: id, Scope: claim.Scope, Handle: claim.Handle, RequestID: "native-question", Question: &q} |
| + _, err = x.Mutate(ctx, principal, "questions", request) |
| + must(t, err) |
| + request.Question = nil |
| + liveFixture(t, f) |
| + return f, x, principal, request, q |
| +} |
| +func TestConversationQuestionRaceNative(t *testing.T) { |
| + for _, state := range []string{"current", "stale", "expired", "cancelled"} { |
| + t.Run(state, func(t *testing.T) { |
| + f, x, principal, request, q := nativeConversationFixture(t) |
| + path := "/tasks/" + q.TaskID + "/questions/" + q.ID + "/answer" |
| + v := url.Values{"revision": {"1"}, "behavior": {"allow"}, "answer_0": {"Blue"}} |
| + switch state { |
| + case "stale": |
| + v.Set("revision", "2") |
| + case "expired": |
| + f.exec(t, "UPDATE runner_assignments SET lease_deadline='2000-01-01T00:00:00Z' WHERE id=?", request.AssignmentID) |
| + case "cancelled": |
| + _, err := x.Core.Cancel(ctx, request.Scope, "fixture", "cancel") |
| + must(t, err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + w := formPost(t, f, owner, path, v) |
| + if state == "current" { |
| + expectHTTP(t, w, 303) |
| + } else if w.Code < 400 { |
| + t.Fatal("inactive native answer accepted", state, w.Code) |
| + } |
| + } |
| + if state != "current" { |
| + if f.count(t, "SELECT count(*) FROM questions WHERE state='answered'") != 0 { |
| + t.Fatal("inactive native answer persisted") |
| + } |
| + return |
| + } |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='question.answer'") != 1 { |
| + t.Fatal("duplicate native answer effect") |
| + } |
| + request.RequestID = "poll-native" |
| + result, err := x.Mutate(ctx, principal, "answers", request) |
| + must(t, err) |
| + answers := result.([]runnerproto.Question) |
| + if len(answers) != 1 || answers[0].PermissionID != q.PermissionID || answers[0].SessionID != q.SessionID || answers[0].Revision != q.Revision { |
| + t.Fatal("answer lost original provider request", answers) |
| + } |
| + if !strings.Contains(string(answers[0].Answer.UpdatedInput), "Blue") { |
| + t.Fatal("native answer shape lost") |
| + } |
| + expectHTTP(t, formPost(t, f, owner, path, url.Values{"revision": {"1"}, "text": {"allow"}, "option_id": {"one"}}), 422) |
| + }) |
| + } |
| +} |
| +func TestConversationScriptlessSharedPlan(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + p.Kind = taskplan.Recommendation |
| + p.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend", Instructions: "Investigate the project"}, {Key: "merge", Action: "person"}} |
| + p, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "read-plan", Revision: p.Revision}) |
| + must(t, err) |
| + f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| + for _, path := range []string{"/tasks/" + p.TaskID, "/tasks/" + p.TaskID + "/plan", "/tasks/" + p.TaskID + "/thread", "/journey", "/specialists/product"} { |
| + w := f.get(t, peer, path) |
| + expectHTTP(t, w, 200) |
| + if path != "/tasks/"+p.TaskID+"/thread" && (!strings.Contains(w.Body.String(), "research") || !strings.Contains(w.Body.String(), "/tasks/"+p.TaskID+"/thread")) { |
| + t.Fatal("shared page lacks real planned steps or thread link", path) |
| + } |
| + } |
| +} |
| + |
| +func TestConversationScriptlessReadCompletion(t *testing.T) { |
| + f, _, _, request, q := nativeConversationFixture(t) |
| + f.exec(t, "UPDATE jobs SET state='succeeded' WHERE id=?", request.Scope.Job) |
| + f.exec(t, "UPDATE tasks SET state='succeeded' WHERE id=?", q.TaskID) |
| + w := f.get(t, owner, "/tasks/"+q.TaskID) |
| + expectHTTP(t, w, 200) |
| + if strings.Contains(w.Body.String(), `href="/tasks/`+q.TaskID+`/merge"`) || !strings.Contains(w.Body.String(), "Answer delivered") { |
| + t.Fatal("read-only completion presented as publication") |
| + } |
| +} |