Auto-bind coordinators and explain unavailable turns
Co-Authored-By: Astra <noreply@openai.com>
27 files changed,
+734
−93
docs/superpowers/plans/CONTROLLER-REPORT-agent-setup.md+122 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+12 −2internal/agentsetuptest/autobind_test.go+202 −0internal/agentsetuptest/browser_test.go+21 −8internal/agentsetuptest/flow_test.go+35 −6internal/agentsetuptest/testdata/coordinator.py+6 −1internal/equipo/conversation/application.go+3 −0internal/equipo/conversation/coordinator_application.go+9 −0internal/equipo/conversation/coordinator_selection.go+51 −0internal/equipo/conversation/coordinator_setup.go+121 −0internal/equipo/conversation/coordinator_status.go+48 −0internal/equipo/conversation/live.go+2 −0internal/equipo/conversation/project_message.go+3 −0internal/equipo/conversation/store.go+6 −8internal/equipo/coordinator.go+9 −41internal/equipo/coordinator_setup.go+9 −0internal/equipo/copy.go+13 −4internal/equipo/static/chat-navigation.js+34 −0internal/equipo/static/equipo.css+3 −0internal/equipo/store.go+2 −0internal/equipo/templates/chrome.html+1 −1internal/equipo/templates/conversation_card.html+8 −8internal/plan3test/conversation_browser_test.go+1 −1internal/plan3test/conversation_test.go+9 −9internal/plan3test/notifications_migration_test.go+1 −1internal/plan3test/person_api_migration_test.go+2 −2internal/plan3test/preferences_migration_test.go+1 −1
Intent
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-agent-setup.md b/docs/superpowers/plans/CONTROLLER-REPORT-agent-setup.md| index 97b5faa0..a94072ee 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-agent-setup.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-agent-setup.md |
| @@ -1,5 +1,9 @@ |
| # Agent setup controller report |
| +Round 2 adds automatic coordinator binding, setup and failure notes, and chat |
| +focus/transition fixes. The round 2 evidence and handoff follow the original |
| +R1–R5 report below. |
| + |
| The coordinator can propose a repository project in the conversation. The |
| project is created only when its person taps **Set up**. **Not now** closes |
| the card without creating a project. This branch was rebased onto `main` |
| @@ -171,3 +175,121 @@ and push this commit. No merge, push or deployment was performed here. |
| All servers and browser processes started for the checks have stopped. Scratch |
| files created for this task were removed; default Go caches were retained. |
| The supplied worktree remains in place for the controller. |
| + |
| +## Round 2: automatic coordinator binding (2026-11-06) |
| + |
| +Merged local `main` first as `449715a`. The only conflict was in `copy.go`: |
| +kept the previous agent-setup empty state pending and retained main's approvals |
| +for unchanged chat strings. No fetch or push was attempted. |
| + |
| +A1: sending a main-conversation message now binds an unconfigured coordinator |
| +to the first eligible connection by ID. Candidates belong to the current |
| +person and an active runner in this instance. The release must certify the |
| +provider's coordinate action; reported provider, launcher, bubblewrap and |
| +policy versions must match. Existing freshness, availability, routing and |
| +isolation checks apply. The binding records current member and connection |
| +revisions. Message, binding, human-attributed audit, queued turn and system |
| +note commit together. A replay adds no note, binding or turn. Existing bindings |
| +are retained, including explicit project selection and the existing poll path. |
| + |
| +A2: missing runners, connections, certification or usable online connections |
| +produce a plain system note with the next action. Existing offline or changed |
| +bindings also explain the problem when sending. Interrupted, fenced, waiting |
| +connection and budget states are visible in the conversation. Lease and attempt |
| +deadlines produce a timeout note, with live refresh scheduled for both. Retry |
| +controls for uncertain turns remain hidden until containment is confirmed. |
| +Reads do not rewrite turn state or authorize a new attempt. |
| + |
| +A3: an app-owned script skips cross-document transitions when the source and |
| +destination have the same origin, path and query. Composer and answer forms |
| +restore focus to the composer after POST + 303; ordinary page navigation keeps |
| +its transition. Browser tests exercise actual composer and project-answer |
| +submissions at 1280 and 390. Vendored Rastrillo files remain byte-identical. |
| + |
| +Selection logic moved into the conversation package to stay within the existing |
| +source budget. No budget, migration, schema, policy constructor, policy inventory |
| +or certification file changed in round 2. The prior coordinator hashes above |
| +still apply. Its live certification is still required; the fake release injected |
| +by tests cannot authorize a real runner's policy or executable checks. |
| + |
| +### Round 2 verification |
| + |
| +Initial failing tests: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/agentsetuptest -run 'TestCoordinatorMissingSetupNote|TestCoordinatorFailureVisible' -count=1` |
| + failed with a missing setup note and silent uncertain, fenced, waiting |
| + connection and budget states. |
| +- `CGO_ENABLED=0 go test ./internal/agentsetuptest -run '^TestCoordinatorExistingOfflineNote$' -count=1` |
| + failed because an existing offline binding produced no note. |
| + |
| +The fake Python CLI now receives an authenticated first HTML message with no |
| +binding, runs through automatic binding and the real runner protocol, posts a |
| +reply with `post_message`, and reaches delivered state. A separate subprocess |
| +failure reaches an uncertain turn with a visible recovery action after |
| +containment. Existing project-proposal flows still pass. No live provider is |
| +used; containment and provider event transport are simulated. |
| + |
| +Eleven guard mutations each exited 1 with a test assertion, then were restored. |
| +Commands use `CGO_ENABLED=0 go test ./internal/agentsetuptest -run '<filter>' -count=1`: |
| + |
| +| Broken guard | Filter | Observed failure | |
| +|---|---|---| |
| +| coordinate certification | `^TestCoordinatorAutoBind/uncertified$` | ineligible binding accepted | |
| +| online freshness | `^TestCoordinatorAutoBind/offline$` | offline binding accepted | |
| +| certified provider version | `^TestCoordinatorAutoBind/wrong-version$` | wrong version accepted | |
| +| candidate person filter | `^TestCoordinatorAutoBind/eligible$` | eligible binding missing | |
| +| connection revocation | `^TestCoordinatorAutoBind/connection-revoked$` | revoked connection bound | |
| +| deterministic order | `^TestCoordinatorAutoBind/deterministic$` | wrong binding selected | |
| +| audit atomicity | `^TestCoordinatorAutoBind/audit$` | audit failure ignored | |
| +| setup replay | `^TestCoordinatorMissingSetupNote$` | replay attempted duplicate setup write | |
| +| failure visibility | `^TestCoordinatorFailureVisible/uncertain$` | silent turn | |
| +| timeout visibility | `^TestCoordinatorTimeoutVisible$` | timeout note missing | |
| +| same-page transition skip | `^TestAgentSetupBrowser/390$` with `-tags browser` | transition was not skipped | |
| + |
| +The certification and version fixtures were strengthened after independent |
| +version and isolation checks initially concealed those mutations. Restored |
| +checks cover current membership, foreign ownership, revoked runners and |
| +connections, unavailable reports, lookup/decode errors and audit rollback. |
| +Timeout tests also verify that live refresh is scheduled. Historical conversation |
| +and migration assertions now include the setup note beside the person's message. |
| + |
| +Eight new copy entries and the revised `coordinator.uncertain` and |
| +`coordinator.waiting_connection` are individually marked `COPY REVIEW PENDING`. |
| +The consolidated Plan 3 copy inventory contains their exact text. The controller |
| +applies Paul's acceptance before release. No copy-review server was started; |
| +README prose is unchanged. |
| + |
| +Targeted checks passed: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/agentsetuptest -count=1 |
| +CGO_ENABLED=0 go test -tags browser ./internal/agentsetuptest -run '^TestAgentSetupBrowser' -count=1 |
| +CGO_ENABLED=0 go test ./internal/agentsetuptest ./internal/plan3test -run 'TestCoordinatorAutoBind|TestCoordinatorExistingOfflineNote|TestPlan3ReleaseBoundaries/inventory' -count=1 |
| +``` |
| + |
| +The first full `make -k ci` exited 2 with one failing package: |
| +`internal/tryequipo`, test `TestAutomaticAnswerProcessChain`. Its captured |
| +terminal output showed the provider check passing and the shell printing |
| +`exit`; the Python driver then failed its one-shot, nonblocking child-exit |
| +check. A process-reaping race is the likely cause, not a proven diagnosis. |
| +`CGO_ENABLED=0 go test ./internal/tryequipo -run '^TestAutomaticAnswerProcessChain$' -count=3 -v` |
| +passed all three isolated runs. That unrelated fixture is unchanged. |
| + |
| +Every other gate passed on the first full run. Conversation median response was |
| +19.594 ms against 150 ms; cold boot was 110 ms against 500 ms. Existing local-only |
| +timing warnings: runner 5m54.874s/5m30s, provider 22.456s/15s, Claude |
| +53.751s/45s, Codex 43.872s/35s. No time limits were raised. |
| + |
| +The single full rerun exited 0. All 34 test packages ran uncached with zero |
| +failures. Reference scan, build, vet, formatting, static analysis, vulnerability |
| +and secret scans, size budgets, adapter and namespace checks, migration |
| +comparison and performance passed. Conversation median response was 20.991 ms; |
| +cold boot was 115 ms. The four local timing warnings remained: runner |
| +5m54.195s/5m30s, provider 21.528s/15s, Claude 47.469s/45s and Codex 39.94s/35s. |
| +Timing limits are enforced in CI environments; these existing warnings were not |
| +waived or changed. Two full runs total, one rerun; no third run. |
| + |
| +Controller: apply copy acceptance, rerun live coordinator certification and push |
| +the local commits. No push or deployment was performed. Test servers and browser |
| +processes have stopped, and task scratch was removed. Default Go caches and the |
| +controller-provided worktree remain in place. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index c6ae04d4..0a116014 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5028,13 +5028,21 @@ records remain unchanged. |
| | `coordinator.unavailable` | Your coordinator is unavailable. | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.budget_needed` | Ask a team owner to set coordinator limits. | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.queued` | Waiting for your coordinator | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| -| `coordinator.uncertain` | This turn was interrupted. Its result is unknown. | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `coordinator.uncertain` | Your coordinator stopped before finishing. Once the runner has stopped the turn, choose Try this turn again. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| | `coordinator.retry` | Try this turn again | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.reset` | Reset coordinator | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| -| `coordinator.waiting_connection` | Waiting for your connection | 5 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `coordinator.waiting_connection` | Your coordinator cannot reach your connection. Start your runner in Connections. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| | `coordinator.waiting_task` | Waiting for %s | 7 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.context_unavailable` | Your coordinator can no longer use a source for this request. Reset your coordinator or retry after access is restored. | 7 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.context_limit` | The required context is too long for this turn. Reset your coordinator or retry. | 7 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `coordinator.auto_bound` | Your coordinator uses %s. Change it in Your coordinator. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.setup_runner` | Your coordinator needs a runner. Add your machine in Connections. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.setup_connection` | Your coordinator needs a model connection. Connect an account in Connections. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.setup_certified` | None of your connections has a certified coordinator policy. Ask the team owner to enable a certified coordinator release. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.setup_offline` | Your coordinator cannot use your runner connection. Start or update your runner in Connections. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.fenced` | This coordinator turn stopped. Choose Try this turn again. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.timed_out` | Your coordinator took too long to reply. Restart your runner in Connections to finish stopping the turn. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| +| `coordinator.setup_binding` | Your coordinator connection changed. Choose your connection again in Your coordinator. | Agent setup round 2 | Runtime; COPY REVIEW REQUIRED | |
| | `tool.acceptance` | Submit acceptance tests for the requested behaviour. Encode file bytes as base64. Reuse the request ID only for an identical retry. | 4 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `tool.answer` | Submit an answer with references to the supplied source snapshots. Reuse the request ID only for an identical retry. | 4 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `tool.render` | Request a trusted render of the submitted candidate commit. Reuse the request ID only for an identical retry. | 4 | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| @@ -5182,6 +5190,8 @@ records remain unchanged. |
| | `CopyCalibrationFunding` | calibration funding is too low; rerun with JobInput=%d JobOutput=%d ProjectInputHeadroom=%d ProjectOutputHeadroom=%d TeamInputHeadroom=%d TeamOutputHeadroom=%d: %w | Direct isolation Round 3 | COPY ACCEPTED FOR NOW (Paul, 2026-11-05; iterate in context) | |
| + |
| + |
| ## Task 21 |
| Status: DONE_WITH_CONCERNS. Offline 3b acceptance, the complete person API contract |
diff --git a/internal/agentsetuptest/autobind_test.go b/internal/agentsetuptest/autobind_test.go| new file mode 100644 |
| index 00000000..8a250015 |
| --- /dev/null |
| +++ b/internal/agentsetuptest/autobind_test.go |
| @@ -0,0 +1,202 @@ |
| +package agentsetuptest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestCoordinatorMissingSetupNote(t *testing.T) { |
| + f := newFixture(t) |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "What can you work on?", equipo.Mutation{RequestID: "first"}) |
| + must(t, err) |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Messages) != 2 || page.Messages[1].AuthorKind != "system" || !strings.Contains(page.Messages[1].Body, "runner") { |
| + t.Fatal("missing setup note", page.Messages) |
| + } |
| + again, err := f.Store.SendMessage(ctx, owner, "", "What can you work on?", equipo.Mutation{RequestID: "first"}) |
| + must(t, err) |
| + if again.ID != msg.ID || f.count(t, "SELECT count(*) FROM conversation_messages") != 2 { |
| + t.Fatal("replay duplicated note") |
| + } |
| +} |
| + |
| +func TestCoordinatorFailureVisible(t *testing.T) { |
| + for _, state := range []string{"uncertain", "fenced", "waiting_connection", "budget_needed"} { |
| + t.Run(state, func(t *testing.T) { |
| + t.Parallel() |
| + f, _, _, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "Hello", "failure") |
| + f.exec(t, "UPDATE coordinator_turns SET state=? WHERE id=?", state, turn.ID) |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Cards) != 1 || page.Cards[0].CopyKey != "coordinator."+state { |
| + t.Fatal("silent turn", state, page.Cards) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCoordinatorAutoBind(t *testing.T) { |
| + for _, scenario := range []string{"eligible", "offline", "foreign", "revoked", "removed", "lookup", "audit", "uncertified", "wrong-version", "unavailable", "wrong-runner-owner", "deterministic", "connection-revoked", "decode"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + t.Parallel() |
| + f, _, _, _ := coordinatorFixture(t) |
| + f.exec(t, "DELETE FROM coordinator_bindings") |
| + certifyCoordinator(f) |
| + f.exec(t, "UPDATE connections SET label='My Claude' WHERE id='claude'") |
| + switch scenario { |
| + case "connection-revoked": |
| + f.exec(t, "UPDATE connections SET revoked_at=CURRENT_TIMESTAMP") |
| + case "decode": |
| + f.exec(t, "UPDATE connections SET reports_json='broken'") |
| + case "offline": |
| + f.exec(t, "UPDATE connections SET last_seen='2000-01-01'") |
| + case "foreign": |
| + f.exec(t, "UPDATE connections SET person=?", peer.Address) |
| + case "revoked": |
| + f.exec(t, "UPDATE runners SET revoked_at=CURRENT_TIMESTAMP") |
| + case "removed": |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + case "lookup": |
| + f.exec(t, "ALTER TABLE runners RENAME TO missing_runners") |
| + case "audit": |
| + f.exec(t, "CREATE TRIGGER reject_bind BEFORE INSERT ON audit_events WHEN NEW.kind='coordinator.auto_bind' BEGIN SELECT RAISE(ABORT,'audit failed'); END") |
| + case "uncertified": |
| + m := release.BuildManifest() |
| + m.LauncherVersion = "direct-v2" |
| + m.PolicyVersion = "policy-v2" |
| + equipo.WithCoordinatorRelease(m)(f.Store) |
| + case "wrong-version": |
| + m := certifyCoordinator(f) |
| + m.Claude = "old" |
| + m.DirectPolicies[0].ProviderVersion = "old" |
| + equipo.WithCoordinatorRelease(m)(f.Store) |
| + case "unavailable": |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false'))`) |
| + case "wrong-runner-owner": |
| + f.exec(t, "UPDATE runners SET person=?", peer.Address) |
| + case "deterministic": |
| + f.exec(t, `INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash,label) SELECT 'aaa',runner_id,person,'other',revision,last_seen,reports_json,security_hash,label FROM connections WHERE id='claude'`) |
| + } |
| + _, err := f.Store.SendMessage(ctx, owner, "", "What can you work on?", equipo.Mutation{RequestID: "auto"}) |
| + if scenario == "removed" || scenario == "lookup" || scenario == "audit" || scenario == "decode" { |
| + if err == nil { |
| + t.Fatal("guard accepted", scenario) |
| + } |
| + if f.count(t, "SELECT count(*) FROM coordinator_bindings") != 0 || f.count(t, "SELECT count(*) FROM conversation_messages") != 0 { |
| + t.Fatal("partial write") |
| + } |
| + return |
| + } |
| + must(t, err) |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Messages) != 2 || page.Messages[1].AuthorKind != "system" { |
| + t.Fatal("missing system note", page.Messages) |
| + } |
| + if scenario != "eligible" && scenario != "deterministic" { |
| + if f.count(t, "SELECT count(*) FROM coordinator_bindings") != 0 { |
| + t.Fatal("ineligible binding", scenario) |
| + } |
| + return |
| + } |
| + b, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + want := "claude" |
| + if scenario == "deterministic" { |
| + want = "aaa" |
| + } |
| + if b.ConnectionID != want || b.Person != owner.Address || b.Generation != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 1 { |
| + t.Fatal("wrong binding or turn", b) |
| + } |
| + if !strings.Contains(page.Messages[1].Body, "Your coordinator uses My Claude.") || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.auto_bind' AND actor=?", owner.Address) != 1 { |
| + t.Fatal("missing attribution") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func certifyCoordinator(f *fixture) release.Manifest { |
| + m := release.BuildManifest() |
| + m.LauncherVersion = "direct-v2" |
| + m.PolicyVersion = "policy-v2" |
| + m.UncertifiedPolicies = nil |
| + m.LiveGateCopyReviewed = true |
| + hash := strings.Repeat("c", 64) |
| + m.DirectPolicies = []release.PolicyCertificate{{Action: "coordinate", Provider: "claude", ProviderVersion: m.Claude, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: hash, NoRefreshReason: "fixture"}} |
| + m.Certifications = []release.Certification{{Provider: "claude", PolicyHash: hash, SHA256: hash}} |
| + equipo.WithCoordinatorRelease(m)(f.Store) |
| + return m |
| +} |
| + |
| +func TestCoordinatorTimeoutVisible(t *testing.T) { |
| + for _, deadline := range []string{"lease", "attempt"} { |
| + t.Run(deadline, func(t *testing.T) { |
| + t.Parallel() |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "Hello", "timeout") |
| + claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + raw, err := f.DB.Writer().BeginTx(ctx, nil) |
| + must(t, err) |
| + deadlines := map[string][]time.Time{} |
| + deadlineErr := conversation.ConversationDeadlines(ctx, raw, deadlines) |
| + must(t, raw.Rollback()) |
| + must(t, deadlineErr) |
| + found := false |
| + for _, times := range deadlines { |
| + for _, at := range times { |
| + if at.Equal(claim.AttemptDeadline) { |
| + found = true |
| + } |
| + } |
| + } |
| + if !found { |
| + t.Fatal("timeout not scheduled for live refresh") |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Cards) != 0 { |
| + t.Fatal("active turn marked timed out") |
| + } |
| + if deadline == "lease" { |
| + f.exec(t, "UPDATE attempts SET lease_deadline='2000-01-01T00:00:00Z' WHERE id=?", claim.Handle.Attempt) |
| + } else { |
| + f.exec(t, `UPDATE coordinator_turns SET claim=json_set(claim,'$.AttemptDeadline','2000-01-01T00:00:00Z') WHERE id=?`, turn.ID) |
| + } |
| + page, err = f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Cards) != 1 || page.Cards[0].CopyKey != "coordinator.timed_out" || len(page.Cards[0].ActionKeys) != 0 { |
| + t.Fatal("timeout missing or unsafe retry offered", page.Cards) |
| + } |
| + apiRouter(t, f, nil) |
| + w := f.get(t, owner, "/conversation") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "took too long") { |
| + t.Fatal("timeout absent from HTML") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCoordinatorExistingOfflineNote(t *testing.T) { |
| + f, _, _, b := coordinatorFixture(t) |
| + f.exec(t, "UPDATE connections SET last_seen='2000-01-01'") |
| + _, err := f.Store.SendMessage(ctx, owner, "", "Hello", equipo.Mutation{RequestID: "offline"}) |
| + must(t, err) |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Messages) != 2 || !strings.Contains(page.Messages[1].Body, "runner") { |
| + t.Fatal("existing offline binding stayed silent", page.Messages) |
| + } |
| + after, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if after != b { |
| + t.Fatal("existing binding changed") |
| + } |
| +} |
diff --git a/internal/agentsetuptest/browser_test.go b/internal/agentsetuptest/browser_test.go| index 06702dce..d17e213a 100644 |
| --- a/internal/agentsetuptest/browser_test.go |
| +++ b/internal/agentsetuptest/browser_test.go |
| @@ -56,11 +56,26 @@ func TestAgentSetupBrowser(t *testing.T) { |
| } |
| check(`document.querySelector('[data-empty-state="conversation.empty"]').textContent.includes('Say what you want fixed')`) |
| browsertest.Screenshot(t, rig, fmt.Sprintf("agent-setup-empty-%d", width)) |
| - turn := queueCoordinator(t, f, "Fix amadan.net/oficina/new-app", "browser") |
| + var turn equipo.CoordinatorTurn |
| + if noJS { |
| + turn = queueCoordinator(t, f, "Fix amadan.net/oficina/new-app", "browser") |
| + } else { |
| + check(`(()=>{ window.__skipCount=0; var original=ViewTransition.prototype.skipTransition; ViewTransition.prototype.skipTransition=function(){sessionStorage.setItem('test-skipped',String(Number(sessionStorage.getItem('test-skipped')||0)+1));return original.call(this)}; document.querySelector('#composer').removeAttribute('data-live-form');document.querySelector('#chat-body').value='Fix amadan.net/oficina/new-app';return true; })()`) |
| + rig.Run(browsertest.Click(`#composer button[type="submit"]`), browsertest.Wait(`document.activeElement.id==='chat-body' && document.querySelector('[equipo-feed]').textContent.includes('Fix amadan.net/oficina/new-app')`)) |
| + if width == 390 { |
| + check(`Number(sessionStorage.getItem('test-skipped'))>0`) |
| + } |
| + turns, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(turns) != 1 { |
| + t.Fatal("composer did not queue turn", turns) |
| + } |
| + turn = turns[0] |
| + } |
| c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| must(t, err) |
| f.exec(t, "UPDATE coordinator_turns SET provider_session_id='fixture-session' WHERE id=?", turn.ID) |
| - out := toolCall(t, x, p, c, "proposal", "propose_project", map[string]string{"repository": setupRepo, "why": "Set up this repository to work on your request."}) |
| + toolCall(t, x, p, c, "proposal", "propose_project", map[string]string{"repository": setupRepo, "why": "Set up this repository to work on your request."}) |
| if noJS { |
| rig.Run(chromedp.Navigate(rig.Origin + "/conversation")) |
| } else { |
| @@ -69,13 +84,11 @@ func TestAgentSetupBrowser(t *testing.T) { |
| check(`document.documentElement.scrollWidth<=innerWidth`) |
| check(`document.querySelectorAll('button[value="setup"]').length===1 && document.querySelectorAll('button[value="decline"]').length===1`) |
| browsertest.Screenshot(t, rig, fmt.Sprintf("agent-setup-card-%d", width)) |
| - if noJS { |
| - rig.Run(browsertest.Click(`button[value="setup"]`)) |
| - } else { |
| - // A tap in another tab must update this card through the conversation topic. |
| - must(t, f.Store.AnswerProjectProposal(ctx, owner, out.ResourceID, true, equipo.Mutation{RequestID: "browser-tap", Revision: 1})) |
| - rig.Run(browsertest.Wait(`document.querySelector('#conversation-feed').textContent.includes('Project set up') && !document.querySelector('button[value="setup"]')`)) |
| + rig.Run(browsertest.Click(`button[value="setup"]`)) |
| + if !noJS { |
| + rig.Run(browsertest.Wait(`document.activeElement.id==='chat-body' && document.querySelector('#conversation-feed').textContent.includes('Project set up')`)) |
| } |
| + |
| check(`document.querySelector('#conversation-feed').textContent.includes('Project set up')`) |
| if f.count(t, "SELECT count(*) FROM projects WHERE repository=?", setupRepo) != 1 { |
| t.Fatal("setup did not persist") |
diff --git a/internal/agentsetuptest/flow_test.go b/internal/agentsetuptest/flow_test.go| index b614c453..22c4a9c8 100644 |
| --- a/internal/agentsetuptest/flow_test.go |
| +++ b/internal/agentsetuptest/flow_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "context" |
| "encoding/json" |
| + "fmt" |
| "net/http" |
| "net/http/httptest" |
| "os/exec" |
| @@ -18,13 +19,17 @@ import ( |
| ) |
| func TestAgentSetupFakeCLI(t *testing.T) { |
| - for _, message := range []string{"Fix amadan.net/oficina/new-app", "Fix new-app", "What should I work on?"} { |
| + for _, message := range []string{"Fix amadan.net/oficina/new-app", "Fix new-app", "What should I work on?", "What can you work on?", "Simulate failure"} { |
| t.Run(message, func(t *testing.T) { |
| t.Parallel() |
| f, x, p, _ := coordinatorFixture(t) |
| - if message == "What should I work on?" { |
| + if message == "What should I work on?" || message == "What can you work on?" { |
| f.exec(t, "DELETE FROM projects") |
| } |
| + if message == "What can you work on?" || message == "Simulate failure" { |
| + f.exec(t, "DELETE FROM coordinator_bindings") |
| + certifyCoordinator(f) |
| + } |
| must(t, f.Store.ReportRepositories(ctx, p, []string{setupRepo})) |
| apiRouter(t, f, nil) |
| validators := runnerproto.ReportValidators(runnerproto.ReportErrors{Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict}, nil) |
| @@ -53,7 +58,7 @@ func TestAgentSetupFakeCLI(t *testing.T) { |
| command.Stdin = strings.NewReader(prompt) |
| raw, err := command.CombinedOutput() |
| if err != nil { |
| - t.Fatalf("fake CLI: %v: %s", err, raw) |
| + return runnerproto.CoordinatorToolCall{}, fmt.Errorf("fake CLI: %w: %s", err, raw) |
| } |
| var call runnerproto.CoordinatorToolCall |
| err = json.Unmarshal(raw, &call) |
| @@ -69,11 +74,35 @@ func TestAgentSetupFakeCLI(t *testing.T) { |
| v.Policy.ManifestHash = runnerproto.EventHash(v.Policy.Manifest) |
| return v, func() error { return nil }, j.RecordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: c.Turn.ID, ManifestHash: v.Policy.ManifestHash, PolicyHash: v.Policy.Hash}) |
| } |
| - turn := queueCoordinator(t, f, message, "request") |
| - must(t, service.Poll(ctx)) |
| + values := actionForm("request", 0) |
| + values.Set("body", message) |
| + expectHTTP(t, formPost(t, f, owner, "/conversation", values), 303) |
| + var turn equipo.CoordinatorTurn |
| + err = service.Poll(ctx) |
| + if message == "Simulate failure" { |
| + if err == nil { |
| + t.Fatal("fake CLI failure lost") |
| + } |
| + page, e := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, e) |
| + if len(page.Cards) != 1 || page.Cards[0].CopyKey != "coordinator.uncertain" || len(page.Cards[0].ActionKeys) == 0 { |
| + t.Fatal("failed CLI turn silent after containment", page.Cards) |
| + } |
| + return |
| + } |
| + must(t, err) |
| + must(t, f.DB.G.Table("coordinator_turns").Take(&turn).Error) |
| if l.starts != 1 || l.result.ResourceID == "" || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='delivered'", turn.ID) != 1 { |
| t.Fatal("proposal did not complete delivery") |
| } |
| + if message == "What can you work on?" { |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Messages) != 3 || page.Messages[1].AuthorKind != "system" || page.Messages[2].Body != "I can help with your repositories. Tell me what you want fixed." { |
| + t.Fatal("first message did not auto-bind and reply", page.Messages) |
| + } |
| + return |
| + } |
| if f.count(t, "SELECT count(*) FROM projects WHERE repository=?", setupRepo) != 0 { |
| t.Fatal("fake CLI created project without consent") |
| } |
| @@ -82,7 +111,7 @@ func TestAgentSetupFakeCLI(t *testing.T) { |
| if !strings.Contains(w.Body.String(), "Set up new-app ("+setupRepo+")?") { |
| t.Fatal("card missing", w.Body.String()) |
| } |
| - values := actionForm("tap", 1) |
| + values = actionForm("tap", 1) |
| values.Set("choice", "setup") |
| expectHTTP(t, formPost(t, f, owner, "/conversation/projects/"+l.result.ResourceID+"/answer", values), 303) |
| if f.count(t, "SELECT count(*) FROM projects WHERE repository=?", setupRepo) != 1 { |
diff --git a/internal/agentsetuptest/testdata/coordinator.py b/internal/agentsetuptest/testdata/coordinator.py| index 1c092adf..c3465fe5 100644 |
| --- a/internal/agentsetuptest/testdata/coordinator.py |
| +++ b/internal/agentsetuptest/testdata/coordinator.py |
| @@ -8,7 +8,12 @@ assert 'repository or app that is not a project yet' in prompt['Instructions'] |
| assert 'before the person taps Set up' in prompt['Instructions'] |
| context = prompt['Context'] |
| setup = next(json.loads(r['Text']) for r in context['Retrieved'] if r['Source']['kind'] == 'project_setup') |
| -message = context['Recent'][-1]['Body'] |
| +message = next(m['Body'] for m in reversed(context['Recent']) if m['AuthorKind'] == 'person') |
| +if message == 'Simulate failure': |
| + sys.exit(1) |
| +if message == 'What can you work on?': |
| + print(json.dumps({'request_id': 'reply', 'name': 'post_message', 'arguments': {'source_refs': [], 'body': 'I can help with your repositories. Tell me what you want fixed.'}})) |
| + sys.exit(0) |
| existing = {p['Repository'] for p in setup['ExistingProjects'] or []} |
| repos = [r for r in setup['ReportedRepositories'] if r not in existing] |
| repo = next((r for r in repos if r in message or r.split('/')[-1] in message), None) |
diff --git a/internal/equipo/conversation/application.go b/internal/equipo/conversation/application.go| index a6d28b67..fe7c7b1f 100644 |
| --- a/internal/equipo/conversation/application.go |
| +++ b/internal/equipo/conversation/application.go |
| @@ -25,6 +25,9 @@ func (s *Application) SendMessage(ctx context.Context, actor Actor, threadID, bo |
| err := s.Write(ctx, func(tx *gorm.DB) error { |
| var err error |
| msg, err = s.Conversation(tx).SendMessage(actor, threadID, body, m) |
| + if err == nil && msg.ConversationID != "" { |
| + err = s.setupMessage(tx, actor, msg) |
| + } |
| return err |
| }) |
| if err != nil { |
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go| index c3533cd7..31c21921 100644 |
| --- a/internal/equipo/conversation/coordinator_application.go |
| +++ b/internal/equipo/conversation/coordinator_application.go |
| @@ -2,8 +2,11 @@ package conversation |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "context" |
| "crypto/rand" |
| "errors" |
| @@ -15,6 +18,12 @@ import ( |
| type Actor = kernel.Actor |
| type Mutation = kernel.Mutation |
| type Application struct { |
| + BindingSelection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error) |
| + WaitingConnection error |
| + BindingRelease *release.Manifest |
| + Copy func(string) string |
| + DecodeConnection func(*planning.ConnectionRecord) error |
| + BindingEligible func(*gorm.DB, planning.ConnectionRecord, runnerproto.ConnectionReport) (bool, error) |
| Projects func(*gorm.DB) *setup.ProjectsStore |
| ProjectCreated, ProjectDeclined string |
| Read func(context.Context, func(*gorm.DB) error) error |
diff --git a/internal/equipo/conversation/coordinator_selection.go b/internal/equipo/conversation/coordinator_selection.go| new file mode 100644 |
| index 00000000..7decf967 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_selection.go |
| @@ -0,0 +1,51 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func SelectBinding(tx *gorm.DB, b BindingRecord, memberRevision func(*gorm.DB, string) (int64, error), decode func(*planning.ConnectionRecord) error, eligible func(*gorm.DB, planning.ConnectionRecord, runnerproto.ConnectionReport) (bool, error), snapshot func(*gorm.DB, planning.ConnectionRecord, runnerproto.ConnectionReport) (team.IsolationSnapshot, error), forbidden, waiting error, storeError func(error) error) (runnerproto.Selection, error) { |
| + m, err := memberRevision(tx, b.Person) |
| + if err != nil { |
| + return runnerproto.Selection{}, err |
| + } |
| + if m != b.MemberRevision { |
| + return runnerproto.Selection{}, forbidden |
| + } |
| + var c planning.ConnectionRecord |
| + if err = tx.First(&c, "id=?", b.ConnectionID).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return runnerproto.Selection{}, waiting |
| + } |
| + return runnerproto.Selection{}, storeError(err) |
| + } |
| + if c.Person != b.Person || c.RunnerID != b.RunnerID || c.Revision != b.ConnectionRevision { |
| + return runnerproto.Selection{}, forbidden |
| + } |
| + if err = decode(&c); err != nil { |
| + return runnerproto.Selection{}, err |
| + } |
| + for _, r := range c.Reports { |
| + ok, err := eligible(tx, c, r) |
| + if err != nil { |
| + return runnerproto.Selection{}, err |
| + } |
| + if !ok { |
| + continue |
| + } |
| + // Task 5 supports the subscription lane; metered calls need explicit prices. |
| + if r.Kind != "subscription" { |
| + continue |
| + } |
| + iso, err := snapshot(tx, c, r) |
| + if err != nil { |
| + return runnerproto.Selection{}, err |
| + } |
| + return runnerproto.Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: c.Person, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountID: r.Routing.AccountID, AccountLabel: r.AccountLabel, Revision: c.Revision, Isolation: iso}, nil |
| + } |
| + return runnerproto.Selection{}, waiting |
| +} |
diff --git a/internal/equipo/conversation/coordinator_setup.go b/internal/equipo/conversation/coordinator_setup.go| new file mode 100644 |
| index 00000000..27015f9b |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_setup.go |
| @@ -0,0 +1,121 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "crypto/rand" |
| + "errors" |
| + "fmt" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (s *Application) setupMessage(tx *gorm.DB, actor Actor, msg Message) error { |
| + cs := s.Conversation(tx) |
| + var done bool |
| + mutation := Mutation{RequestID: msg.ID} |
| + if ok, err := cs.CoordinatorReplay(actor, "coordinator.setup", msg.ID, mutation, msg.ID, &done); ok || err != nil { |
| + return err |
| + } |
| + b, err := cs.Binding(actor) |
| + note := "" |
| + exists := err == nil |
| + if exists { |
| + _, err = s.BindingSelection(tx, b) |
| + switch { |
| + case errors.Is(err, s.WaitingConnection): |
| + note = s.Copy("coordinator.setup_offline") |
| + err = nil |
| + case errors.Is(err, s.Forbidden): |
| + note = s.Copy("coordinator.setup_binding") |
| + err = nil |
| + } |
| + } |
| + if errors.Is(err, s.NotFound) { |
| + b, note, err = s.autoCoordinator(tx, actor) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if b.ID != "" && !exists { |
| + if _, err = cs.QueueCoordinator(actor, msg.ID, 0, Mutation{RequestID: "message:" + msg.ID}); err != nil { |
| + return err |
| + } |
| + } |
| + if note != "" { |
| + if err = cs.SystemNote(msg.ConversationID, note); err != nil { |
| + return err |
| + } |
| + } |
| + return cs.SaveCoordinatorResult(actor, "coordinator.setup", msg.ID, mutation, msg.ID, true) |
| +} |
| + |
| +func (s *Application) autoCoordinator(tx *gorm.DB, actor Actor) (BindingRecord, string, error) { |
| + var empty BindingRecord |
| + teamID, err := s.Conversation(tx).deps.Authorize(tx, actor) |
| + if err != nil { |
| + return empty, "", err |
| + } |
| + var runners int64 |
| + if err = tx.Table("runners").Where("person=? AND instance_id=? AND revoked_at IS NULL", actor.Address, teamID).Count(&runners).Error; err != nil { |
| + return empty, "", err |
| + } |
| + if runners == 0 { |
| + return empty, s.Copy("coordinator.setup_runner"), nil |
| + } |
| + var connections []planning.ConnectionRecord |
| + if err = tx.Where("person=? AND revoked_at IS NULL AND runner_id IN (SELECT id FROM runners WHERE person=? AND instance_id=? AND revoked_at IS NULL)", actor.Address, actor.Address, teamID).Order("id").Find(&connections).Error; err != nil { |
| + return empty, "", err |
| + } |
| + if len(connections) == 0 { |
| + return empty, s.Copy("coordinator.setup_connection"), nil |
| + } |
| + manifest := release.BuildManifest() |
| + if s.BindingRelease != nil { |
| + manifest = *s.BindingRelease |
| + } |
| + certified := false |
| + for _, c := range connections { |
| + if err = s.DecodeConnection(&c); err != nil { |
| + return empty, "", err |
| + } |
| + for _, r := range c.Reports { |
| + if !manifest.HasCertifiedAction(r.Provider, "coordinate") { |
| + continue |
| + } |
| + certified = true |
| + if r.ProviderVersion != map[string]string{"claude": manifest.Claude, "codex": manifest.Codex}[r.Provider] || r.LauncherVersion != manifest.LauncherVersion || r.BwrapVersion != manifest.BwrapVersion || r.PolicyVersion != manifest.PolicyVersion || r.Kind != "subscription" { |
| + continue |
| + } |
| + ok, err := s.BindingEligible(tx, c, r) |
| + if err != nil { |
| + return empty, "", err |
| + } |
| + if !ok { |
| + continue |
| + } |
| + memberRevision, connectionRevision, err := s.BindingIdentity(tx, actor, c.RunnerID, c.ID) |
| + if err != nil { |
| + return empty, "", err |
| + } |
| + b := BindingRecord{CoordinatorBinding: CoordinatorBinding{ID: rand.Text(), Person: actor.Address, RunnerID: c.RunnerID, ConnectionID: c.ID, Generation: 1, Revision: 1}, TeamID: teamID, PersonKey: actor.Address, MemberRevision: memberRevision, ConnectionRevision: connectionRevision} |
| + if err = tx.Create(&b).Error; err != nil { |
| + return empty, "", err |
| + } |
| + if err = s.Audit(tx, actor, "coordinator.auto_bind", b.ID); err != nil { |
| + return empty, "", err |
| + } |
| + label := c.Label |
| + if label == "" { |
| + label = r.AccountLabel |
| + } |
| + if label == "" { |
| + label = c.LocalID |
| + } |
| + return b, fmt.Sprintf(s.Copy("coordinator.auto_bound"), label), nil |
| + } |
| + } |
| + if !certified { |
| + return empty, s.Copy("coordinator.setup_certified"), nil |
| + } |
| + return empty, s.Copy("coordinator.setup_offline"), nil |
| +} |
diff --git a/internal/equipo/conversation/coordinator_status.go b/internal/equipo/conversation/coordinator_status.go| new file mode 100644 |
| index 00000000..7ad7e53c |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_status.go |
| @@ -0,0 +1,48 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "time" |
| +) |
| + |
| +func (s *Store) coordinatorStatus(page ConversationPage, b BindingRecord) (ConversationPage, error) { |
| + var turns []TurnRecord |
| + if err := s.tx.Where("binding_id=? AND generation=? AND state NOT IN ('delivered','superseded')", b.ID, b.Generation).Order("sequence DESC").Limit(50).Find(&turns).Error; err != nil { |
| + return page, err |
| + } |
| + for _, turn := range turns { |
| + state := turn.State |
| + if state == "running" { |
| + var attempt struct{ LeaseDeadline string } |
| + if err := s.tx.Table("attempts").Select("lease_deadline").Where("id=?", turn.AttemptID).Take(&attempt).Error; err != nil { |
| + return page, err |
| + } |
| + var claim CoordinatorClaim |
| + if err := decodeCoordinator(turn.Claim, &claim); err != nil { |
| + return page, err |
| + } |
| + now := time.Now().UTC() |
| + if !now.Before(kernel.ReadTime(attempt.LeaseDeadline)) || !claim.AttemptDeadline.IsZero() && !now.Before(claim.AttemptDeadline) { |
| + state = "timed_out" |
| + } |
| + } |
| + var actions []string |
| + switch state { |
| + case "context_limit", "context_unavailable", "fenced": |
| + actions = []string{"coordinator.reset", "coordinator.retry"} |
| + case "uncertain": |
| + var n int64 |
| + if err := s.tx.Table("attempts").Where("id=? AND containment='contained'", turn.AttemptID).Count(&n).Error; err != nil { |
| + return page, err |
| + } |
| + if n == 1 { |
| + actions = []string{"coordinator.reset", "coordinator.retry"} |
| + } |
| + case "waiting_connection", "budget_needed", "timed_out": |
| + default: |
| + continue |
| + } |
| + page.Cards = append(page.Cards, Card{ID: turn.ID, Kind: "coordinator", ResourceID: turn.ID, Revision: turn.Revision, CopyKey: "coordinator." + state, ActionKeys: actions}) |
| + } |
| + return page, nil |
| +} |
diff --git a/internal/equipo/conversation/live.go b/internal/equipo/conversation/live.go| index 625ab3ac..4ed28fba 100644 |
| --- a/internal/equipo/conversation/live.go |
| +++ b/internal/equipo/conversation/live.go |
| @@ -172,6 +172,8 @@ func ConversationDeadlines(ctx context.Context, tx *sql.Tx, deadlines map[string |
| sql string |
| clarification bool |
| }{ |
| + {`SELECT c.team_id,c.person,c.id,a.lease_deadline FROM coordinator_turns t JOIN attempts a ON a.id=t.attempt_id JOIN conversations c ON c.id=t.conversation_id WHERE t.state='running'`, false}, |
| + {`SELECT c.team_id,c.person,c.id,json_extract(t.claim,'$.AttemptDeadline') FROM coordinator_turns t JOIN conversations c ON c.id=t.conversation_id WHERE t.state='running' AND t.claim<>''`, false}, |
| {`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}, |
| } { |
diff --git a/internal/equipo/conversation/project_message.go b/internal/equipo/conversation/project_message.go| index 93c8f8fe..61af22ab 100644 |
| --- a/internal/equipo/conversation/project_message.go |
| +++ b/internal/equipo/conversation/project_message.go |
| @@ -28,6 +28,9 @@ func (s *Application) SendProjectMessage(ctx context.Context, actor Actor, body |
| return err |
| } |
| msg, err = cs.SendMessage(actor, "", project.Name+"\n\n"+body, m) |
| + if err == nil && msg.ConversationID != "" { |
| + err = s.setupMessage(tx, actor, msg) |
| + } |
| return err |
| }) |
| return msg, err |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index f0674bcd..4e093fd8 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -69,14 +69,7 @@ func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (Conv |
| if b.WaitingTaskID != "" { |
| page.Cards = append(page.Cards, Card{ID: b.ID, Kind: "coordinator", ResourceID: b.ID, Revision: page.Revision, CopyKey: "coordinator.waiting_task", WaitingTaskID: b.WaitingTaskID, WaitingTaskURL: b.WaitingTaskURL}) |
| } |
| - var limited []TurnRecord |
| - if err = s.tx.Where("binding_id=? AND generation=? AND state IN ('context_limit','context_unavailable')", b.ID, b.Generation).Order("sequence").Limit(1).Find(&limited).Error; err != nil { |
| - return page, err |
| - } |
| - for _, turn := range limited { |
| - page.Cards = append(page.Cards, Card{ID: turn.ID, Kind: "coordinator", ResourceID: turn.ID, Revision: turn.Revision, CopyKey: "coordinator." + turn.State, ActionKeys: []string{"coordinator.reset", "coordinator.retry"}}) |
| - } |
| - return page, nil |
| + return s.coordinatorStatus(page, b) |
| } |
| func (s *Store) SendMessage(actor kernel.Actor, threadID, body string, m kernel.Mutation) (Message, error) { |
| if !m.Valid() || !utf8.ValidString(body) || len(body) < 1 || len(body) > 16384 { |
| @@ -278,3 +271,8 @@ func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision i |
| } |
| return page, nil |
| } |
| + |
| +func (s *Store) SystemNote(conversationID, body string) error { |
| + _, err := s.appendMessage(conversationID, conversationID, "", "system", "", body, "system") |
| + return err |
| +} |
diff --git a/internal/equipo/coordinator.go b/internal/equipo/coordinator.go| index a267d3b1..541a20fd 100644 |
| --- a/internal/equipo/coordinator.go |
| +++ b/internal/equipo/coordinator.go |
| @@ -6,7 +6,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "context" |
| - "errors" |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| "slices" |
| @@ -25,52 +24,21 @@ func CoordinatorGrantRef(person string) string { |
| var errCoordinatorWaitingConnection = &refusal{copyText("coordinator.waiting_connection"), ErrUnavailable} |
| func (s *Store) coordinatorSelection(tx *gorm.DB, b conversation.BindingRecord) (Selection, error) { |
| - m, err := currentRunnerMember(tx, b.Person) |
| - if err != nil { |
| - return Selection{}, err |
| - } |
| - if m.Revision != b.MemberRevision { |
| - return Selection{}, ErrForbidden |
| - } |
| - var c connectionRecord |
| - if err = tx.First(&c, "id=?", b.ConnectionID).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return Selection{}, errCoordinatorWaitingConnection |
| - } |
| - return Selection{}, storeError(err) |
| - } |
| - if c.Person != b.Person || c.RunnerID != b.RunnerID || c.Revision != b.ConnectionRevision { |
| - return Selection{}, ErrForbidden |
| - } |
| - if err = decodeConnection(&c); err != nil { |
| - return Selection{}, err |
| - } |
| - for _, r := range c.Reports { |
| - ok, _, err := s.eligible(tx, c, r, s.runnerClock.Now().UTC()) |
| - if err != nil { |
| - return Selection{}, err |
| - } |
| - if !ok { |
| - continue |
| - } |
| - // Task 5 supports the subscription lane; metered calls need explicit prices. |
| - if r.Kind != "subscription" { |
| - continue |
| - } |
| - iso, err := s.isolationSnapshot(tx, c, r) |
| - if err != nil { |
| - return Selection{}, err |
| - } |
| - return Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: c.Person, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountID: r.Routing.AccountID, AccountLabel: r.AccountLabel, Revision: c.Revision, Isolation: iso}, nil |
| - } |
| - return Selection{}, errCoordinatorWaitingConnection |
| + return conversation.SelectBinding(tx, b, func(tx *gorm.DB, person string) (int64, error) { |
| + m, err := currentRunnerMember(tx, person) |
| + return m.Revision, err |
| + }, decodeConnection, s.coordinatorEligible, s.isolationSnapshot, ErrForbidden, errCoordinatorWaitingConnection, storeError) |
| +} |
| +func (s *Store) coordinatorEligible(tx *gorm.DB, c connectionRecord, r ConnectionReport) (bool, error) { |
| + ok, _, err := s.eligible(tx, c, r, s.runnerClock.Now().UTC()) |
| + return ok, err |
| } |
| func (s *Store) coordinatorApplication() *conversation.Application { |
| var core *team.Store |
| if s.execution != nil { |
| core = s.execution.Core |
| } |
| - return &conversation.Application{Projects: func(tx *gorm.DB) *setup.ProjectsStore { return s.projectsStore().At(tx) }, ProjectCreated: copyText("project_setup.created_message"), ProjectDeclined: copyText("project_setup.declined_message"), Now: s.runnerClock.Now, Core: core, Write: s.write, Read: func(ctx context.Context, fn func(*gorm.DB) error) error { |
| + return &conversation.Application{BindingSelection: s.coordinatorSelection, WaitingConnection: errCoordinatorWaitingConnection, Copy: copyText, BindingRelease: s.coordinatorRelease, DecodeConnection: decodeConnection, BindingEligible: s.coordinatorEligible, Projects: func(tx *gorm.DB) *setup.ProjectsStore { return s.projectsStore().At(tx) }, ProjectCreated: copyText("project_setup.created_message"), ProjectDeclined: copyText("project_setup.declined_message"), Now: s.runnerClock.Now, Core: core, Write: s.write, Read: func(ctx context.Context, fn func(*gorm.DB) error) error { |
| return s.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(fn) |
| }, 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) { |
diff --git a/internal/equipo/coordinator_setup.go b/internal/equipo/coordinator_setup.go| new file mode 100644 |
| index 00000000..f64c741c |
| --- /dev/null |
| +++ b/internal/equipo/coordinator_setup.go |
| @@ -0,0 +1,9 @@ |
| +package equipo |
| + |
| +import "amadan.net/oficina/equipo/internal/release" |
| + |
| +// WithCoordinatorRelease supplies the release used to choose an initial binding. |
| +// Runner admission still verifies its own exact policy and executable digests. |
| +func WithCoordinatorRelease(m release.Manifest) StoreOption { |
| + return func(s *Store) { s.coordinatorRelease = &m } |
| +} |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index d449c1cb..3ba7b000 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -46,6 +46,15 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + "coordinator.setup_binding": "Your coordinator connection changed. Choose your connection again in Your coordinator.", // COPY REVIEW PENDING |
| + "coordinator.auto_bound": "Your coordinator uses %s. Change it in Your coordinator.", // COPY REVIEW PENDING |
| + "coordinator.setup_runner": "Your coordinator needs a runner. Add your machine in Connections.", // COPY REVIEW PENDING |
| + "coordinator.setup_connection": "Your coordinator needs a model connection. Connect an account in Connections.", // COPY REVIEW PENDING |
| + "coordinator.setup_certified": "None of your connections has a certified coordinator policy. Ask the team owner to enable a certified coordinator release.", // COPY REVIEW PENDING |
| + "coordinator.setup_offline": "Your coordinator cannot use your runner connection. Start or update your runner in Connections.", // COPY REVIEW PENDING |
| + "coordinator.fenced": "This coordinator turn stopped. Choose Try this turn again.", // COPY REVIEW PENDING |
| + "coordinator.timed_out": "Your coordinator took too long to reply. Restart your runner in Connections to finish stopping the turn.", // COPY REVIEW PENDING |
| + |
| // COPY REVIEW PENDING: project_setup.heading |
| "project_setup.heading": "Set up %s (%s)?", |
| // COPY REVIEW PENDING: project_setup.accept |
| @@ -755,14 +764,14 @@ var runnerDraftCopy = map[string]string{ |
| "coordinator.budget_needed": "Ask a team owner to set coordinator limits.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.queued |
| "coordinator.queued": "Waiting for your coordinator", |
| - // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.uncertain |
| - "coordinator.uncertain": "This turn was interrupted. Its result is unknown.", |
| + // COPY REVIEW PENDING: coordinator.uncertain |
| + "coordinator.uncertain": "Your coordinator stopped before finishing. Once the runner has stopped the turn, choose Try this turn again.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.retry |
| "coordinator.retry": "Try this turn again", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.reset |
| "coordinator.reset": "Reset coordinator", |
| - // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.waiting_connection |
| - "coordinator.waiting_connection": "Waiting for your connection", |
| + // COPY REVIEW PENDING: coordinator.waiting_connection |
| + "coordinator.waiting_connection": "Your coordinator cannot reach your connection. Start your runner in Connections.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.waiting_task |
| "coordinator.waiting_task": "Waiting for %s", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.context_unavailable |
diff --git a/internal/equipo/static/chat-navigation.js b/internal/equipo/static/chat-navigation.js| new file mode 100644 |
| index 00000000..00ecffb8 |
| --- /dev/null |
| +++ b/internal/equipo/static/chat-navigation.js |
| @@ -0,0 +1,34 @@ |
| +(function () { |
| + "use strict"; |
| + var key = "equipo.chat.focus"; |
| + function place(raw) { |
| + if (!raw) return null; |
| + var url = new URL(raw, location.href); |
| + return url.origin + url.pathname + url.search; |
| + } |
| + function skip(event, from, to) { |
| + if (event.viewTransition && from && to && place(from) === place(to)) event.viewTransition.skipTransition(); |
| + } |
| + window.addEventListener("pageswap", function (event) { |
| + var activation = event.activation; |
| + skip(event, location.href, activation && activation.entry && activation.entry.url); |
| + }); |
| + window.addEventListener("pagereveal", function (event) { |
| + var activation = window.navigation && navigation.activation; |
| + skip(event, activation && activation.from && activation.from.url, location.href); |
| + }); |
| + function focus() { |
| + var input = document.getElementById("chat-body"); |
| + if (input) input.focus({ preventScroll: true }); |
| + } |
| + try { |
| + var destination = sessionStorage.getItem(key); |
| + sessionStorage.removeItem(key); |
| + if (destination === place(location.href)) window.addEventListener("pageshow", focus, { once: true }); |
| + } catch (_) { /* Focus still works for live submissions without storage. */ } |
| + document.addEventListener("submit", function (event) { |
| + if (!event.target.matches("[data-chat-submit]")) return; |
| + try { sessionStorage.setItem(key, place(location.href)); } catch (_) { /* Storage may be disabled. */ } |
| + focus(); |
| + }, true); |
| +})(); |
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css| index b5432886..38aa3777 100644 |
| --- a/internal/equipo/static/equipo.css |
| +++ b/internal/equipo/static/equipo.css |
| @@ -164,3 +164,6 @@ html:has([equipo-conversation]) { overflow: hidden; scrollbar-gutter: auto; } |
| [equipo-chat-task] [equipo-step] > span:first-of-type { overflow: hidden; text-overflow: ellipsis; } |
| [equipo-question] > h2 { margin-block-end: var(--rst-sp-2); } |
| [equipo-feed-card] > [equipo-card] > form { position: relative; z-index: 1; } |
| + |
| +[equipo-system-note] [equipo-bubble] { background: transparent; color: var(--rst-text-muted); font-size: var(--rst-fs-sm); } |
| +[equipo-system-note][equipo-card] { border: 0; background: transparent; color: var(--rst-text-muted); font-size: var(--rst-fs-sm); } |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index df7a9686..938ce8c4 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/release" |
| "context" |
| "errors" |
| "fmt" |
| @@ -53,6 +54,7 @@ type InvitationApplication = setup.Application |
| // against the current roster and append an AuditEvent in their transaction. |
| type Store struct { |
| + coordinatorRelease *release.Manifest |
| *NotificationApplication |
| *PlanApplication |
| *InvitationApplication |
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html| index da3fef98..91dcd60f 100644 |
| --- a/internal/equipo/templates/chrome.html |
| +++ b/internal/equipo/templates/chrome.html |
| @@ -1,6 +1,6 @@ |
| {{define "rail-brand"}}<span hidden></span>{{end}} |
| {{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}} |
| -{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}">{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat.js"}}"></script>{{end}}{{end}} |
| +{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}">{{if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script>{{end}}{{end}} |
| {{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}} |
| {{define "up-label"}}{{.TeamName}}{{end}} |
| {{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}} |
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html| index e42499d6..c45fb98a 100644 |
| --- a/internal/equipo/templates/conversation_card.html |
| +++ b/internal/equipo/templates/conversation_card.html |
| @@ -1,6 +1,6 @@ |
| {{define "region:chat-composer"}} |
| <div id="chat-composer" {{.Live.Attrs .Conversation.Topic}}> |
| -<form id="composer" data-live-form="conversation-feed" equipo-form method="post" action="{{if .Conversation.ThreadID}}/tasks/{{.Conversation.ThreadID}}/thread{{else}}/conversation{{end}}"> |
| +<form data-chat-submit id="composer" data-live-form="conversation-feed" 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"> |
| <textarea id="chat-body" rst-input name="body" required maxlength="16384" rows="1" aria-label="{{if .Conversation.ThreadID}}{{copy "conversation.thread_reply"}}{{else}}{{copy "conversation.composer"}}{{end}}" placeholder="{{copy "conversation.placeholder"}}"></textarea> |
| <div equipo-composer-tools>{{if and .Conversation.Projects (not .Conversation.ThreadID)}}<select rst-input name="project_id" aria-label="{{copy "plan.project"}}"><option value="">{{copy "conversation.any_project"}}</option>{{range .Conversation.Projects}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select>{{end}}<button rst-btn="primary" type="submit">{{copy "conversation.send_short"}}</button></div> |
| @@ -14,7 +14,7 @@ |
| {{$day := ""}}{{range .Conversation.Feed}} |
| {{if .Message}}{{$date := .Message.CreatedAt.Format "2006-01-02"}}{{if ne $date $day}}<li equipo-day><time datetime="{{$date}}">{{if eq $date $.Conversation.Today}}{{copy "conversation.today"}}{{else}}{{.Message.CreatedAt.Format "2 January 2006"}}{{end}}</time></li>{{$day = $date}}{{end}}{{end}} |
| {{if .Message}}{{with .Message}} |
| -<li equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}" data-sequence="{{.Sequence}}"> |
| +<li {{if eq .AuthorKind "system"}}equipo-system-note{{end}} equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}" data-sequence="{{.Sequence}}"> |
| <div equipo-message-meta><strong{{if .Own}} equipo-visually-hidden{{end}}>{{icon .AuthorIcon}}{{.AuthorName}}</strong><time datetime="{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.CreatedAt.Format "2006-01-02 15:04 MST"}}">{{.CreatedAt.Format "15:04"}}</time></div> |
| <div equipo-bubble><p equipo-message-body>{{.Body}}</p> |
| {{if .ThreadURL}}<a href="{{.ThreadURL}}">{{copy "conversation.thread_link"}}</a>{{end}} |
| @@ -28,10 +28,10 @@ |
| </section> |
| {{end}} |
| {{define "conversation-card"}} |
| -<article equipo-card data-card="{{.ID}}"{{if or .NativeQuestion .Question}} equipo-question{{end}}> |
| +<article {{if eq .Kind "coordinator"}}equipo-system-note{{end}} equipo-card data-card="{{.ID}}"{{if or .NativeQuestion .Question}} equipo-question{{end}}> |
| {{with .ProjectProposal}} |
| <h2>{{printf (copy "project_setup.heading") .Name .Repository}}</h2><p>{{.Why}}</p> |
| -{{if $.CanAnswer}}<form method="post" action="/conversation/projects/{{.ID}}/answer" equipo-actions><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="setup" type="submit">{{copy "project_setup.accept"}}</button><button rst-btn name="choice" value="decline" type="submit">{{copy "project_setup.decline"}}</button></form> |
| +{{if $.CanAnswer}}<form data-chat-submit method="post" action="/conversation/projects/{{.ID}}/answer" equipo-actions><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="setup" type="submit">{{copy "project_setup.accept"}}</button><button rst-btn name="choice" value="decline" type="submit">{{copy "project_setup.decline"}}</button></form> |
| {{else}}<p equipo-secondary>{{copy (printf "project_setup.%s" .State)}}</p>{{if .ProjectID}}<a href="/projects/{{.ProjectID}}">{{.Name}}</a>{{end}}{{end}} |
| {{end}} |
| {{if eq .Kind "task"}}{{with .Work}}{{template "chat-task" .}}{{end}} |
| @@ -39,16 +39,16 @@ |
| {{with .NativeQuestion}} |
| {{if not .Fields}}<pre>{{.Text}}</pre>{{else if eq (len .Fields) 1}}<h2>{{(index .Fields 0).Prompt}}</h2>{{end}} |
| {{if ne .State "pending"}}<small equipo-secondary>{{copy (printf "question.%s" .State)}}</small>{{end}} |
| -{{if and .CanAnswer (eq (len .Fields) 1)}}{{$q := .}}{{range (index .Fields 0).Options}}<form equipo-choice method="post" action="/tasks/{{$.Work.Task.ID}}/questions/{{$q.ID}}/answer"><input type="hidden" name="revision" value="{{$q.Revision}}"><input type="hidden" name="behavior" value="allow"><button rst-btn type="submit" name="answer_0" value="{{.}}">{{.}}</button></form>{{end}}{{end}} |
| -{{if .CanAnswer}}<form method="post" action="/tasks/{{$.Work.Task.ID}}/questions/{{.ID}}/answer" equipo-form> |
| +{{if and .CanAnswer (eq (len .Fields) 1)}}{{$q := .}}{{range (index .Fields 0).Options}}<form data-chat-submit equipo-choice method="post" action="/tasks/{{$.Work.Task.ID}}/questions/{{$q.ID}}/answer"><input type="hidden" name="revision" value="{{$q.Revision}}"><input type="hidden" name="behavior" value="allow"><button rst-btn type="submit" name="answer_0" value="{{.}}">{{.}}</button></form>{{end}}{{end}} |
| +{{if .CanAnswer}}<form data-chat-submit method="post" action="/tasks/{{$.Work.Task.ID}}/questions/{{.ID}}/answer" equipo-form> |
| <input type="hidden" name="revision" value="{{.Revision}}"> |
| {{range $i,$field:=.Fields}}<label>{{if ne (len $.NativeQuestion.Fields) 1}}{{$field.Prompt}}{{end}}<textarea rst-input aria-label="{{$field.Prompt}}" name="answer_{{$i}}" rows="1" placeholder="{{copy "question.reply"}}" maxlength="8192"></textarea></label>{{end}} |
| <div equipo-actions>{{if .Fields}}<button rst-btn="primary" type="submit" name="behavior" value="allow">{{copy "conversation.send_short"}}</button>{{else if .CanAllow}}<button rst-btn="primary" type="submit" name="behavior" value="allow">{{copy "question.allow_once"}}</button>{{end}}<button rst-btn type="submit" name="behavior" value="deny">{{copy "question.deny"}}</button></div></form>{{end}} |
| {{end}} |
| {{with .Question}} |
| <h2>{{.Prompt}}</h2>{{if ne .State "pending"}}<small equipo-secondary>{{copy (printf "question.%s" .State)}}</small>{{end}} |
| -{{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}}"><textarea rst-input name="text" rows="1" aria-label="{{copy "question.reply"}}" placeholder="{{copy "question.reply"}}" required maxlength="8192"></textarea><button rst-btn type="submit">{{copy "conversation.send_short"}}</button></form>{{end}} |
| +{{if $.CanAnswer}}<form data-chat-submit 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 data-chat-submit method="post" action="/conversation/questions/{{.ID}}/answer" equipo-form><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><textarea rst-input name="text" rows="1" aria-label="{{copy "question.reply"}}" placeholder="{{copy "question.reply"}}" required maxlength="8192"></textarea><button rst-btn type="submit">{{copy "conversation.send_short"}}</button></form>{{end}} |
| {{end}} |
| {{if eq .Kind "coordinator"}} |
diff --git a/internal/plan3test/conversation_browser_test.go b/internal/plan3test/conversation_browser_test.go| index d43f70e3..531fe3bd 100644 |
| --- a/internal/plan3test/conversation_browser_test.go |
| +++ b/internal/plan3test/conversation_browser_test.go |
| @@ -32,7 +32,7 @@ func TestConversationScriptless(t *testing.T) { |
| 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] |
| + msg := page.Messages[len(page.Messages)-2] |
| 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") |
diff --git a/internal/plan3test/conversation_test.go b/internal/plan3test/conversation_test.go| index 201e4fc0..6f28d5ac 100644 |
| --- a/internal/plan3test/conversation_test.go |
| +++ b/internal/plan3test/conversation_test.go |
| @@ -73,7 +73,7 @@ func TestConversationMessageReplay(t *testing.T) { |
| if !reflect.DeepEqual(m, again) || m.Sequence != 1 || m.Revision != 1 || m.AuthorKind != "person" || m.AuthorID != owner.Address || m.CreatedAt.Location().String() != "UTC" { |
| t.Fatal("unstable replay or attribution", m, again) |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 1 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 1 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 2 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 2 { |
| t.Fatal("duplicate send effects") |
| } |
| if _, e := f.Store.SendMessage(ctx, owner, "", "changed", equipo.Mutation{RequestID: "once"}); !errors.Is(e, equipo.ErrConflict) { |
| @@ -89,15 +89,15 @@ func TestConversationMessageReplay(t *testing.T) { |
| if _, e = f.Store.SendMessage(ctx, owner, "", "rollback", equipo.Mutation{RequestID: "rollback"}); e == nil { |
| t.Fatal("audit failure ignored") |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 2 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 2 || f.count(t, "SELECT count(*) FROM conversation_requests") != 2 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 4 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 4 || f.count(t, "SELECT count(*) FROM conversation_requests") != 4 { |
| t.Fatal("audit failure did not roll back") |
| } |
| f.exec(t, "DROP TRIGGER fail_conversation_audit") |
| - if m = send(t, f, owner, "", "rollback", "rollback"); m.Sequence != 3 { |
| + if m = send(t, f, owner, "", "rollback", "rollback"); m.Sequence != 5 { |
| t.Fatal("rollback consumed sequence") |
| } |
| send(t, f, peer, "", "different principal", "once") |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 4 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 8 { |
| t.Fatal("request keys not principal scoped") |
| } |
| f.createTask(t) |
| @@ -107,7 +107,7 @@ func TestConversationMessageReplay(t *testing.T) { |
| expectHTTP(t, formPost(t, f, owner, "/conversation", v), 303) |
| page, e = f.Store.Conversation(ctx, owner, "", 50) |
| must(t, e) |
| - if page.Messages[len(page.Messages)-1].Body != "fixture\n\nCheck the invoice" { |
| + if page.Messages[len(page.Messages)-2].Body != "fixture\n\nCheck the invoice" { |
| t.Fatal("selected project missing from message") |
| } |
| v.Set("request_id", "missing-project") |
| @@ -140,7 +140,7 @@ func TestConversationRouteOnce(t *testing.T) { |
| must(t, e) |
| shared, e := f.Store.TaskThread(ctx, peer, task.ID, "", 50) |
| must(t, e) |
| - if len(main.Messages) != 3 || main.Messages[2].AuthorKind != "system" || len(main.Cards) != 1 || main.Cards[0].ResourceID != task.ID || len(shared.Messages) != 1 || shared.Messages[0].Body != "selected reply" { |
| + if len(main.Messages) != 5 || main.Messages[4].AuthorKind != "system" || len(main.Cards) != 1 || main.Cards[0].ResourceID != task.ID || len(shared.Messages) != 1 || shared.Messages[0].Body != "selected reply" { |
| t.Fatal("route did not leave exactly one reply and notice", main, shared) |
| } |
| if shared.Messages[0].ConversationID != "" || shared.Messages[0].ID == secret.ID || len(shared.Cards) != 0 { |
| @@ -245,7 +245,7 @@ func TestConversationPageBounds(t *testing.T) { |
| for e := range errs { |
| must(t, e) |
| } |
| - if len(seen) != 105 { |
| + if len(seen) != 210 { |
| t.Fatal("inserts changed snapshot", len(seen)) |
| } |
| if _, e = f.Store.Conversation(ctx, owner, "guessed", 50); !errors.Is(e, equipo.ErrNotFound) { |
| @@ -326,7 +326,7 @@ func TestConversationConcurrentReplay(t *testing.T) { |
| wg.Wait() |
| page, e := f.Store.Conversation(ctx, owner, "", 50) |
| must(t, e) |
| - if len(page.Messages) != 1 { |
| + if len(page.Messages) != 2 { |
| t.Fatal("concurrent send duplicated") |
| } |
| for range 8 { |
| @@ -340,7 +340,7 @@ func TestConversationConcurrentReplay(t *testing.T) { |
| for e := range errs { |
| must(t, e) |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 3 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 3 || f.count(t, "SELECT count(*) FROM conversation_threads") != 1 || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 4 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 4 || f.count(t, "SELECT count(*) FROM conversation_threads") != 1 || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 { |
| t.Fatal("concurrent retry duplicated effects") |
| } |
| } |
diff --git a/internal/plan3test/notifications_migration_test.go b/internal/plan3test/notifications_migration_test.go| index 0dbef606..7bda5edb 100644 |
| --- a/internal/plan3test/notifications_migration_test.go |
| +++ b/internal/plan3test/notifications_migration_test.go |
| @@ -60,7 +60,7 @@ func TestNotificationMigrationUpgrade(t *testing.T) { |
| } |
| page, err := equipo.NewStore(d).Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 1 || page.Messages[0].ID != msg.ID { |
| + if len(page.Messages) != 2 || page.Messages[0].ID != msg.ID { |
| t.Fatal("upgrade lost historical conversation") |
| } |
| } |
diff --git a/internal/plan3test/person_api_migration_test.go b/internal/plan3test/person_api_migration_test.go| index 39ddd842..94c11709 100644 |
| --- a/internal/plan3test/person_api_migration_test.go |
| +++ b/internal/plan3test/person_api_migration_test.go |
| @@ -52,7 +52,7 @@ func TestPersonAPIMigrationUpgrade(t *testing.T) { |
| } |
| page, err := equipo.NewStore(d).Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 1 || page.Messages[0].ID != msg.ID { |
| + if len(page.Messages) != 2 || page.Messages[0].ID != msg.ID { |
| t.Fatal("historical message lost") |
| } |
| } |
| @@ -114,7 +114,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| } |
| page, err := equipo.NewStore(d).Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 1 || page.Messages[0].ID != msg.ID { |
| + if len(page.Messages) != 2 || page.Messages[0].ID != msg.ID { |
| t.Fatal("historical message lost") |
| } |
| } |
diff --git a/internal/plan3test/preferences_migration_test.go b/internal/plan3test/preferences_migration_test.go| index 5d12d539..725a9bb8 100644 |
| --- a/internal/plan3test/preferences_migration_test.go |
| +++ b/internal/plan3test/preferences_migration_test.go |
| @@ -59,7 +59,7 @@ func TestPreferencesMigrationUpgrade(t *testing.T) { |
| } |
| page, err := store.Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 1 || page.Messages[0].ID != msg.ID || page.Messages[0].Body != msg.Body { |
| + if len(page.Messages) != 2 || page.Messages[0].ID != msg.ID || page.Messages[0].Body != msg.Body { |
| t.Fatal("history changed") |
| } |
| fresh := newFixture(t) |