oficina / equipo Public

Resume approved access promptly and persist approval visits

Paul Campbell pushed by paul@keymail.dev 6c18a596ef1b615b8871a8eaf1e285cfcd2962e0 parent 98defec
24 files changed, +762 −29
  • .rastrillo/budgets.txt +6 −6
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +2 −0
  • internal/equipo/access_open.go +41 −0
  • internal/equipo/chat/access_request.go +14 −1
  • internal/equipo/chat/access_resume_test.go +127 −0
  • internal/equipo/chat/roster.go +15 −0
  • internal/equipo/chat/runner.go +3 −0
  • internal/equipo/chat_page.go +6 −2
  • internal/equipo/chat_roster.go +1 −1
  • internal/equipo/copy.go +2 −0
  • internal/equipo/static/chat-stream.js +17 −2
  • internal/equipo/static/equipo.css +9 −0
  • internal/equipo/templates/access_card.html +6 −3
  • internal/equipo/templates/chat.html +2 −2
  • internal/equipo/templates/placement_chip.html +1 −1
  • internal/equipo/work_views.go +2 −1
  • internal/headless/access_resume_test.go +127 −0
  • internal/runner/thin/access_resume.go +86 −0
  • internal/runner/thin/access_resume_test.go +162 −0
  • internal/runner/thin/movein.go +5 −0
  • internal/runner/thin/run.go +2 −2
  • internal/thintest/access_browser_test.go +39 −1
  • internal/thintest/access_resume_browser_test.go +79 −0
  • internal/wire/access.go +8 −7

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 2331581f..cd84f0e1 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 21076 - Shared web views and Roster access status copy. Measured 21076 source lines after final access-request fixes.
-size internal/wire 6543 - Shared protocol types; protocol 26 adds durable confirmed access commands and state reports. Limits match measured lines. Access review guards and contract tests; limit matches measured lines.
+size internal/equipo 21124 - Shared web views; persisted approval navigation and visible access continuations. Measured 21124 source lines.
+size internal/wire 6544 - Shared protocol types and the optional card approval-visit flag. Runner protocol stays 26; measured 6544 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 27080 19975 Shared runner state and forge integration. Measured 27080 source and 19975 test lines including disconnect, POST outcome and expiry guards.
+size internal/runner/thin 27171 20137 Shared runner state and forge integration, prompt verified access catalog and explore suppression. Measured 27171 source and 20137 test lines.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 30667 - Transactional authority and access confirmation; resume after provisional expiry. Measured 30667 source lines.
+size internal/equipo/chat 30698 - Transactional access visit, reconnect catch-up and continuation presentation. Measured 30698 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -70,8 +70,8 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only
perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
-size internal/headless - 11062 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11062 test lines.
-size internal/thintest - 30981 Shared instance/browser fixtures, including final access outcomes at two widths and themes. Measured 30981 test lines.
+size internal/headless - 11189 End-to-end scenarios, including approved access through the real runner and server while git is blocked. Measured 11189 test lines.
+size internal/thintest - 31098 Shared instance/browser fixtures, access reload and resume, live queue and emoji byline guards. Measured 31098 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index add25cb8..08e1144d 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6721,6 +6721,8 @@ records remain unchanged.
| `copyOficinaConfig` | EQUIPO_OFICINA_CONNECT_ORIGIN must be an HTTPS address, with EQUIPO_OFICINA_CONNECT_CLIENT_ID set. | boot error for a refused oficina-connect configuration (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| `copyOficinaCardFailed` | Could not show the card to connect Oficina apps. | log line when the connect card could not be raised (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| `docs/api/equipo-v1.md / Talk to the Assistant: connect cards` | A `connect` card asks you to connect something the Assistant needs, such as your Oficina apps: it has no options and one link, which you open in your browser to connect. It is answered by connecting, not through the API, and is `resolved` once you have. The Oficina apps' card link has `rel: "oficina_connect"`: call `POST /api/v1/assistant/oficina/connect` with `{"return_to":"<address on your origin>"}` and send the browser to the `url` it returns. The return address must be on an origin in `EQUIPO_ASSISTANT_HOSTS`, or the answer is `422 invalid_input`. After the consent page the browser comes back to it with `oficina_state` and `oficina_code`, which you pass to `POST /api/v1/assistant/oficina/connect/finish` as `{"state":"…","code":"…"}` with the same person's bearer, within two minutes. The answer is `200` with `status` `connected`, `denied`, `expired` or `unavailable`, or `403 forbidden` when the consent was started by someone else. When the consent fails, the browser comes back with `oficina` set to `denied`, `expired` or `unavailable` instead. | API doc: the new sentence on connect cards in the card paragraph (oficina, 2026-11-16) | API; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
+| `access.waiting` | Waiting for your approval on Amadan… | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
+| `access.reopen` | Open Amadan again | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
## Task 21
diff --git a/internal/equipo/access_open.go b/internal/equipo/access_open.go
new file mode 100644
index 00000000..546a8b86
--- /dev/null
+++ b/internal/equipo/access_open.go
@@ -0,0 +1,41 @@
+package equipo
+
+import (
+ "errors"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/go-chi/chi/v5"
+)
+
+// The scriptless form saves the visit before opening the trusted Amadan URL.
+func (a *application) openAccessApproval(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ ctx, address, ok := sessionContext(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
+ out, _, err := a.store.Chat().Answer(ctx, address, chi.URLParam(r, "id"), wire.AnswerCard{Choice: "open_access", Revision: revision})
+ if err != nil {
+ if errors.Is(err, chat.ErrCardConflict) && strings.Contains(r.Header.Get("Accept"), "application/json") {
+ runnerJSON(w, http.StatusConflict, struct{}{})
+ return
+ }
+ a.failure(w, r, chatError(err))
+ return
+ }
+ if strings.Contains(r.Header.Get("Accept"), "application/json") {
+ runnerJSON(w, http.StatusOK, struct{}{})
+ return
+ }
+ if out.Card.Access == nil || !wire.AccessURL(out.Card.Access.ApproveURL, out.Card.Access.RequestID) {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ http.Redirect(w, r, out.Card.Access.ApproveURL, http.StatusSeeOther)
+}
diff --git a/internal/equipo/chat/access_request.go b/internal/equipo/chat/access_request.go
index 9a8ed76a..5fe7295e 100644
--- a/internal/equipo/chat/access_request.go
+++ b/internal/equipo/chat/access_request.go
@@ -15,7 +15,7 @@ func (t *txn) requestAccess(r turnRecord, in wire.AccessRequest) (wire.ToolResul
in.Role = "agent"
}
reason, ok := cleanText(in.Reason, 1000)
- if !ok || !wire.ValidAccessReason(reason) || !wire.ValidAccessTarget(in.Target) || !wire.AccessRole(in.Role) || in.State != "" || in.RequestID != "" || in.ApproveURL != "" || in.Expires != 0 || r.Kind != wire.TurnPerson {
+ if !ok || !wire.ValidAccessReason(reason) || !wire.ValidAccessTarget(in.Target) || !wire.AccessRole(in.Role) || in.ApprovalOpened || in.State != "" || in.RequestID != "" || in.ApproveURL != "" || in.Expires != 0 || r.Kind != wire.TurnPerson {
return refused("invalid", toolBadInput), nil
}
id, err := t.s.authority.PrimaryRunner(t.db, r.Person)
@@ -109,6 +109,19 @@ func (t *txn) confirmAccess(person string, c cardRecord, in wire.AnswerCard) (wi
if err := json.Unmarshal([]byte(c.Access), &a); err != nil {
return wire.Card{}, current, err
}
+ if c.State == wire.CardOpen && c.Revision == in.Revision && a.State == "pending" && in.Choice == "open_access" && wire.AccessURL(a.ApproveURL, a.RequestID) {
+ a.ApprovalOpened = true
+ if err := t.s.authority.Audit(t.db, person, "access.approval_opened", c.ID); err != nil {
+ return wire.Card{}, current, err
+ }
+ raw, _ := json.Marshal(a)
+ c.Access = string(raw)
+ if err := t.saveCard(&c); err != nil {
+ return wire.Card{}, current, err
+ }
+ out, err := t.cardView(c)
+ return out, wire.Card{}, err
+ }
if c.State != wire.CardOpen || c.Revision != in.Revision || a.State != "confirmation" {
return wire.Card{}, current, ErrCardConflict
}
diff --git a/internal/equipo/chat/access_resume_test.go b/internal/equipo/chat/access_resume_test.go
new file mode 100644
index 00000000..708ccc0f
--- /dev/null
+++ b/internal/equipo/chat/access_resume_test.go
@@ -0,0 +1,127 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "gorm.io/gorm"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestAccessResumeOnCatalogConnection(t *testing.T) {
+ for _, target := range []string{"carlos/platform", "amadan.net/carlos/platform"} {
+ for _, reconnect := range []bool{false, true} {
+ t.Run(target+map[bool]string{false: "/heartbeat", true: "/reconnect"}[reconnect], func(t *testing.T) {
+ r, turn := accessRig(t, "Fix the build in carlos/platform")
+ accessRunnerAuthority(r)
+ r.s.authority.Copy = func(key string) string {
+ if key == "access.continue" {
+ return "Access to %s was approved. Continue: %s"
+ }
+ return key
+ }
+ c := proposeAccess(t, r, turn, target)
+ ctx := context.Background()
+ if _, _, err := r.s.Answer(ctx, hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.db.G.Model(&turnRecord{}).Where("id = ?", turn.ID).Update("state", wire.TurnReplied).Error; err != nil {
+ t.Fatal(err)
+ }
+ lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolCurrent}
+ report := wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: "approved", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"}
+ if err := r.s.Apply(ctx, lease, wire.Frame{ID: "approved", Type: wire.FrameAccess}, &report); err != nil {
+ t.Fatal(err)
+ }
+ var before cardRecord
+ r.s.db.G.First(&before, "id = ?", c.ID)
+ if before.State != wire.CardOpen {
+ t.Fatal("resumed without verified catalog")
+ }
+ h := wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{"amadan.net/carlos/platform"}, Catalog: []wire.RepoInfo{{Repo: "amadan.net/carlos/platform"}}}
+ var resolvedRevision int64
+ for i := 0; i < 2; i++ {
+ var err error
+ if reconnect {
+ lease, err = r.s.Connect(ctx, lease.Runner, "after-deploy", h, "")
+ } else {
+ err = r.s.Heartbeat(ctx, lease, h)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var resolved cardRecord
+ r.s.db.G.First(&resolved, "id = ?", c.ID)
+ if i == 0 {
+ resolvedRevision = resolved.Revision
+ } else if resolved.Revision != resolvedRevision {
+ t.Fatal("catch-up resolved twice")
+ }
+ }
+ var messages []messageRecord
+ r.s.db.G.Where("idempotency_key = ?", "access-approved:"+c.ID).Find(&messages)
+ if len(messages) != 1 || !strings.Contains(messages[0].Text, "Fix the build") {
+ t.Fatalf("continuations: %+v", messages)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if c.State != wire.CardResolved {
+ t.Fatal("approved card remains open")
+ }
+ ps, err := r.s.CardPresentations(ctx, hkOwner, []string{c.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ps[c.ID].Turns) != 0 || len(ps[c.ID].OwnMessages) != 1 {
+ t.Fatal("continuation hidden inside resolved card", ps[c.ID])
+ }
+ var commands int64
+ r.s.db.G.Model(&commandRecord{}).Where("kind = ?", wire.FrameMessage).Count(&commands)
+ if commands != 1 {
+ t.Fatal("resume dispatch count", commands)
+ }
+ })
+ }
+ }
+}
+
+func TestAccessApprovalOpenedPersists(t *testing.T) {
+ r, turn := accessRig(t, "Fix carlos/platform")
+ accessRunnerAuthority(r)
+ c := proposeAccess(t, r, turn, "carlos/platform")
+ ctx := context.Background()
+ if _, _, err := r.s.Answer(ctx, hkOwner, c.ID, wire.AnswerCard{Choice: "confirm", Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ lease := Lease{Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: hkOwner}, Protocol: wire.ProtocolCurrent}
+ report := wire.AccessReport{CardID: c.ID, Person: hkOwner, RequestID: "ar_one", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"}
+ if err := r.s.Apply(ctx, lease, wire.Frame{ID: "pending", Type: wire.FrameAccess}, &report); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.First(&c, "id = ?", c.ID)
+ if _, _, err := r.s.Answer(ctx, hkOwner, c.ID, wire.AnswerCard{Choice: "open_access", Revision: c.Revision}); err != nil {
+ t.Fatal("opening approval", err)
+ }
+ // A repeated runner poll must preserve the person's saved action.
+ if err := r.s.Apply(ctx, lease, wire.Frame{ID: "pending-again", Type: wire.FrameAccess}, &report); err != nil {
+ t.Fatal(err)
+ }
+ var saved cardRecord
+ r.s.db.G.First(&saved, "id = ?", c.ID)
+ var a map[string]any
+ json.Unmarshal([]byte(saved.Access), &a)
+ if a["approval_opened"] != true {
+ t.Fatal("busy state not persisted", a)
+ }
+ r.removed = true
+ if _, _, err := r.s.Answer(ctx, hkOwner, c.ID, wire.AnswerCard{Choice: "open_access", Revision: saved.Revision}); err == nil {
+ t.Fatal("removed person changed card")
+ }
+}
+
+func accessRunnerAuthority(r *meteredRig) {
+ r.s.db.G.Exec("CREATE TABLE runners (id text, person text, role text, label text, revoked_at datetime, removing_at datetime, tainted_at datetime)")
+ r.s.authority.CurrentRunner = func(*gorm.DB, RunnerPrincipal) error { return nil }
+ r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return wire.RolePrimary, nil }
+}
diff --git a/internal/equipo/chat/roster.go b/internal/equipo/chat/roster.go
index 5cdc96c0..2322c4f8 100644
--- a/internal/equipo/chat/roster.go
+++ b/internal/equipo/chat/roster.go
@@ -202,6 +202,21 @@ func (s *Store) CardPresentations(ctx context.Context, person string, ids []stri
}
}
for _, link := range links[c.ID] {
+ // Access resumes the main conversation. Hide only its generated
+ // prompt, never the coordinator's thinking or eventual reply.
+ continuation := false
+ if c.Kind == wire.CardAccess && c.Access != "" {
+ for _, m := range messagesByTurn[link.TurnID] {
+ if m.ID == link.MessageID && m.IdempotencyKey == "access-approved:"+c.ID {
+ p.OwnMessages = append(p.OwnMessages, m.ID)
+ continuation = true
+ }
+ }
+ }
+ if continuation {
+ continue
+ }
+
// A retained reply can outlive its execution record. Keep its
// text and clear pending state when that record is absent.
p.Waiting, p.TurnID, p.StepID, p.ThreadState = false, "", "", ""
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index e5f26560..28efbe83 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -93,6 +93,9 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil {
return err
} else if primary == p.RunnerID {
+ if err := t.resolveAccess(p.Person, hello); err != nil {
+ return err
+ }
if err := t.helloConnections(lease, hello.Connections); err != nil {
return err
}
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index ab38165b..2cfca15a 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -408,7 +408,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
// latest message instead of a line and timer of its own.
var ahead *wire.Turn
for i, t := range snap.Turns {
- if t.Kind == wire.TurnPerson && !wire.Terminal(t.State) && (ahead == nil || t.CreatedAt.Before(ahead.CreatedAt) || t.CreatedAt.Equal(ahead.CreatedAt) && t.ID < ahead.ID) {
+ if !wire.Terminal(t.State) && (ahead == nil || t.State != wire.TurnQueued && ahead.State == wire.TurnQueued || t.State == ahead.State && (t.CreatedAt.Before(ahead.CreatedAt) || t.CreatedAt.Equal(ahead.CreatedAt) && t.ID < ahead.ID)) {
ahead = &snap.Turns[i]
}
}
@@ -428,7 +428,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
}
continue
}
- if t.Kind == wire.TurnPerson && t.State == wire.TurnQueued && ahead != nil && ahead.ID != t.ID {
+ if t.State == wire.TurnQueued && ahead != nil && ahead.ID != t.ID {
queuedTurns[t.ID] = true
continue
}
@@ -685,6 +685,10 @@ func (a *application) workTaskFile(w http.ResponseWriter, r *http.Request) {
// repository; chatProjectRemove is the card's Remove. Both are the same
// store calls a device makes; a stale card just shows its current state.
func (a *application) chatCardAnswer(w http.ResponseWriter, r *http.Request) {
+ if r.PostFormValue("choice") == "open_access" {
+ a.openAccessApproval(w, r)
+ return
+ }
// A merge decision answered on Needs you or the task page returns there.
a.chatActionTo(w, r, workBack(r, r.PostFormValue("task")), func(ctx context.Context, address string) error {
revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
diff --git a/internal/equipo/chat_roster.go b/internal/equipo/chat_roster.go
index d065c3b1..cdcede6a 100644
--- a/internal/equipo/chat_roster.go
+++ b/internal/equipo/chat_roster.go
@@ -38,7 +38,7 @@ func (v *chatCard) rosterAuthor(tasks map[string]wire.Task) {
}
func (v chatCard) Interactive() bool {
- return v.Open && (!v.Receipt || v.Task != nil && (v.Task.CopyHold || v.Task.CopyCanSkip))
+ return v.Open && (v.Access == nil || !wire.AccessFinal(v.Access.State)) && (!v.Receipt || v.Task != nil && (v.Task.CopyHold || v.Task.CopyCanSkip))
}
func (v chatCard) SetAside() bool { return v.Interactive() && v.Presentation.Aside }
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index e05b60e5..863706e9 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -79,6 +79,8 @@ var pageCopy = map[string]string{
"access.title": "Ask for access", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
"access.confirm": "Ask Amadan for access to %s?", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
"access.ask": "Ask for access", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.waiting": "Waiting for your approval on Amadan…", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
+ "access.reopen": "Open Amadan again", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
"access.approve": "Approve on Amadan", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
"access.aside": "Not now", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
"access.reason": "Equipo’s own words", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17)
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index 4f2dff36..fc6ab1f4 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -483,6 +483,9 @@
// its line says so before any activity arrives.
function bubble(turn, kind, waited) {
if (!turn) return null;
+ if (!thread) feed.querySelectorAll("[equipo-thinking]").forEach(function (line) {
+ if (line.dataset.turn !== turn && ended[line.dataset.turn]) drop(line);
+ });
var el = lineFor(turn);
if (!el && !kind && pending.length) {
// The line shown since the send becomes this turn's, in place.
@@ -537,7 +540,7 @@
function behind(turn, sending) {
if (thread) return false;
if (sending && pending.length) return true;
- return Array.from(feed.querySelectorAll("[equipo-thinking]:not([data-kind]):not([data-optimistic])")).some(function (el) {
+ return Array.from(feed.querySelectorAll("[equipo-thinking]:not([data-optimistic])")).some(function (el) {
return el.dataset.turn && el.dataset.turn !== turn && !ended[el.dataset.turn];
});
}
@@ -982,7 +985,7 @@
drop(thinking);
ended[v.id] = true;
refreshSoon();
- } else if (v.state === "queued" && !v.kind && behind(v.id)) {
+ } else if (v.state === "queued" && behind(v.id)) {
// Behind the running turn: the note, and no line or timer.
delete ended[v.id];
queued[v.id] = true;
@@ -1089,6 +1092,13 @@
if (id && cardBusy.has(id)) return;
var body = new URLSearchParams(new FormData(f, button));
var previous = button && button.innerHTML;
+ var access = button && button.matches("[data-access-approve]");
+ if (access) {
+ window.open(button.dataset.approveUrl, "_blank", "noopener,noreferrer");
+ button.hidden = true;
+ card.querySelector("[data-access-waiting]").hidden = false;
+ card.querySelector("[data-access-reopen]").hidden = false;
+ }
var controls = card || f;
if (id) cardBusy.set(id, card);
controls.setAttribute("aria-busy", "true");
@@ -1124,6 +1134,11 @@
controls.removeAttribute("aria-busy");
controls.querySelectorAll("button").forEach(function (b) { b.disabled = false; });
if (button) { button.removeAttribute("aria-busy"); button.innerHTML = previous; }
+ if (access) {
+ button.hidden = false;
+ card.querySelector("[data-access-waiting]").hidden = true;
+ card.querySelector("[data-access-reopen]").hidden = true;
+ }
if (!error) { error = document.createElement("p"); error.setAttribute("equipo-card-error", ""); error.setAttribute("role", "alert"); controls.append(error); }
error.hidden = false;
error.textContent = e.message === "stale" ? root.dataset.cardStale : root.dataset.cardFailed;
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index ea0467d6..ec3e4b4a 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -2106,3 +2106,12 @@ label[equipo-sp-label] { cursor: pointer; }
[data-access-state] { display: contents; }
[data-access-aside] { min-block-size: 2.75rem; }
+
+[data-access-waiting]:not([hidden]) { display: flex; align-items: center; gap: .5rem; margin-block: .75rem; color: var(--rst-text-muted); }
+[equipo-access-spinner] { inline-size: 1rem; block-size: 1rem; flex: 0 0 auto; border: 2px solid var(--rst-line); border-block-start-color: currentColor; border-radius: 50%; animation: equipo-access-spin 1s linear infinite; }
+@keyframes equipo-access-spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { [equipo-access-spinner] { animation: none; } }
+
+[equipo-roster-author] { white-space: nowrap; }
+[equipo-roster-byline] > [equipo-roster-project] { flex: 1 1 6rem; max-inline-size: none; }
+[equipo-roster-byline] > time { flex: none; white-space: nowrap; }
diff --git a/internal/equipo/templates/access_card.html b/internal/equipo/templates/access_card.html
index 223e244c..400d670e 100644
--- a/internal/equipo/templates/access_card.html
+++ b/internal/equipo/templates/access_card.html
@@ -3,9 +3,12 @@
<h3 equipo-card-line>{{if eq .Access.State "confirmation"}}{{.Question}}{{else}}{{copy "access.title"}}: {{.AccessTarget}}{{end}}</h3>
<p equipo-card-note>{{copy "access.role"}}: {{.Access.Role}}</p>
<p equipo-card-note>{{copy "access.reason"}}</p><p>{{.Access.Reason}}</p>
-<p equipo-card-note role="status">{{.Line}}</p>
+{{if not (and (eq .Access.State "pending") .Access.ApprovalOpened)}}<p equipo-card-note role="status">{{.Line}}</p>{{end}}
{{if eq .Access.State "confirmation"}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn="primary" type="submit" name="choice" value="confirm" data-access-confirm>{{copy "access.ask"}}</button></form>{{end}}
-{{if and (eq .Access.State "pending") .Access.ApproveURL}}<p equipo-card-note>{{copy "access.operator"}}</p><div equipo-actions><a rst-btn="primary" href="{{.Access.ApproveURL}}" target="_blank" rel="noopener noreferrer" data-access-approve>{{copy "access.approve"}}</a></div>{{end}}
-{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/visibility" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="aside" value="true">{{template "card-job" .}}<button equipo-link type="submit" data-access-aside>{{copy "access.aside"}}</button></form>{{end}}
+{{if and (eq .Access.State "pending") .Access.ApproveURL}}<p equipo-card-note>{{copy "access.operator"}}</p>
+<div data-access-waiting{{if not .Access.ApprovalOpened}} hidden{{end}} role="status"><span equipo-access-spinner aria-hidden="true"></span><span>{{copy "access.waiting"}}</span></div>
+{{if not .Access.ApprovalOpened}}<form method="post" action="/conversation/cards/{{.ID}}/answer" target="_blank" rel="noopener noreferrer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn="primary" type="submit" name="choice" value="open_access" data-access-approve data-approve-url="{{.Access.ApproveURL}}" data-busy-label="{{copy "access.waiting"}}">{{copy "access.approve"}}</button></form>{{end}}
+<a equipo-link href="{{.Access.ApproveURL}}" target="_blank" rel="noopener noreferrer" data-access-reopen{{if not .Access.ApprovalOpened}} hidden{{end}}>{{copy "access.reopen"}}</a>{{end}}
+{{if and .Open (ne .Access.State "approved")}}<form method="post" action="/conversation/cards/{{.ID}}/visibility" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="aside" value="true">{{template "card-job" .}}<button equipo-link type="submit" data-access-aside>{{copy "access.aside"}}</button></form>{{end}}
</div>
{{end}}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 215b4bcf..c477b284 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -26,8 +26,8 @@
{{define "roster-copy-hold"}}<div equipo-copy-hold><span equipo-roster-stage>{{copy "roster.copy_waiting"}}</span><h3>{{.Line}}</h3><p>{{.HoldReason}}</p>{{with .Presentation.Coverage}}<div equipo-copy-meter>{{if .Known}}{{if .Total}}<meter min="0" max="{{.Total}}" value="{{.Reviewed}}" aria-label="{{printf (copy "roster.copy_count") .Reviewed .Total}}"></meter>{{end}}<span>{{printf (copy "roster.copy_count") .Reviewed .Total}}</span>{{else}}<span>{{copy "roster.copy_coverage"}}</span>{{end}}{{with .Since}}<small>{{printf (copy "roster.copy_since") (.Format "15:04")}}</small>{{end}}</div>{{end}}<div equipo-actions><a rst-btn="primary" href="/conversation?about={{.TaskID}}">{{copy "work.decide.ask_coordinator"}}</a>{{if .Task.CopyCanSkip}}<form method="post" action="/conversation/tasks/{{.TaskID}}/continue-without-copy" data-card-form><button rst-btn type="submit" data-copy-continue>{{copy "copy.continue"}}</button></form>{{end}}</div></div>{{end}}
{{define "roster-thread-turns"}}{{range .Presentation.Thread}}<div equipo-thread-turn{{if .Own}} data-own{{end}}>{{if not .Own}}<span equipo-thread-avatar{{if eq $.AuthorIcon "sparkles"}} equipo-coordinator-mark{{end}}>{{if eq $.AuthorIcon "sparkles"}}{{template "roster-mark" .}}{{else}}{{icon $.AuthorIcon}}{{end}}</span>{{end}}<div equipo-thread-bubble>{{if not .Own}}<div equipo-thread-who>{{$.Author}} <time datetime="{{.At.Format "2006-01-02T15:04:05Z07:00"}}">{{.At.Format "15:04"}}</time></div>{{end}}<div equipo-thread-text equipo-markdown>{{chatMarkdown .Text}}</div></div>{{if .Own}}<small equipo-thread-sent>{{copy "roster.sent"}}</small>{{end}}</div>{{end}}{{with .ThreadError}}<p equipo-thread-error role="alert">{{.}}</p>{{end}}{{if .Presentation.Waiting}}<div equipo-thread-wait role="status"><span equipo-reading-dots aria-hidden="true"><i></i><i></i><i></i></span><span>{{if .ThreadActivity}}{{.ThreadActivity}}{{else}}{{printf (copy "roster.waiting") .Author}}{{end}}</span><div equipo-thread-draft></div></div>{{end}}{{end}}
{{define "roster-undo"}}<form method="post" action="/conversation/cards/{{.ID}}/visibility" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="aside" value="false">{{template "card-job" .}}<button equipo-link type="submit" data-aside-undo data-busy-label="{{copy "roster.restoring"}}">{{copy "roster.undo"}}</button></form>{{end}}
-{{define "roster-byline"}}<div equipo-roster-byline><span equipo-roster-avatar{{if eq .AuthorIcon "sparkles"}} equipo-coordinator-mark{{end}}>{{if eq .AuthorIcon "sparkles"}}{{template "roster-mark" .}}{{else}}{{icon .AuthorIcon}}{{end}}</span>{{if eq .AuthorIcon "sparkles"}}<span equipo-visually-hidden>{{.Author}} {{.Verb}}</span>{{else}}<b>{{.Author}}</b><span>{{.Verb}}</span>{{end}}{{template "roster-project" .}}<time datetime="{{.BylineAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.BylineAt.Format "15:04"}}</time></div>{{end}}
-{{define "roster-project"}}{{if and .TaskID .Presentation.Context.ProjectTitle}}{{if .Task}}{{template "placement-chip" .Task}}{{else}}{{template "placement-chip" (dict "ID" .TaskID "Project" .Presentation.Context.ProjectTitle "Mono" .ProjectMono)}}{{end}}{{else if .Presentation.Context.ProjectTitle}}<span equipo-roster-project><span aria-hidden="true">·</span>{{template "mono-s" .ProjectMono}}<span equipo-project-name title="{{.Presentation.Context.ProjectTitle}}">{{.Presentation.Context.ProjectTitle}}</span></span>{{end}}{{end}}
+{{define "roster-byline"}}<div equipo-roster-byline><span equipo-roster-avatar{{if eq .AuthorIcon "sparkles"}} equipo-coordinator-mark{{end}}>{{if eq .AuthorIcon "sparkles"}}{{template "roster-mark" .}}{{else}}{{icon .AuthorIcon}}{{end}}</span>{{if eq .AuthorIcon "sparkles"}}<span equipo-visually-hidden>{{.Author}} {{.Verb}}</span>{{else}}<span equipo-roster-author><b>{{.Author}}</b> <span>{{.Verb}}</span></span>{{end}}{{template "roster-project" .}}<time datetime="{{.BylineAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.BylineAt.Format "15:04"}}</time></div>{{end}}
+{{define "roster-project"}}{{if and .TaskID .Presentation.Context.ProjectTitle}}{{if .Task}}{{template "placement-chip" .Task}}{{else}}{{template "placement-chip" (dict "ID" .TaskID "Project" .Presentation.Context.ProjectTitle "Mono" .ProjectMono)}}{{end}}{{else if .Presentation.Context.ProjectTitle}}<span equipo-roster-project><span aria-hidden="true">·</span>{{if not .ProjectMono.InTitle}}{{template "mono-s" .ProjectMono}}{{end}}<span equipo-project-name title="{{.Presentation.Context.ProjectTitle}}">{{.Presentation.Context.ProjectTitle}}</span></span>{{end}}{{end}}
{{define "roster-mark"}}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3c1.1 5.8 3.2 7.9 9 9-5.8 1.1-7.9 3.2-9 9-1.1-5.8-3.2-7.9-9-9 5.8-1.1 7.9-3.2 9-9Z"/></svg>{{end}}
{{define "work-task-receipt"}}{{$card := .}}{{with .Task}}<div equipo-roster-report{{if $card.SlimReport}} data-slim{{end}}{{if $card.Compact}} data-compact{{end}}>
<div equipo-roster-report-head><span equipo-roster-stage equipo-stage data-stage="{{.Stage}}" data-tone="{{.RosterTone}}">{{.Eyebrow}}</span>{{if .NeedsYou}}<span equipo-needs-chip>{{icon "hand"}}{{copy "nav.needs-you"}}</span>{{end}}<h3 equipo-card-line><a href="/tasks/{{.ID}}">{{.Title}}</a></h3>{{if not $card.Compact}}{{with .Why}}<p equipo-roster-why>{{.}}</p>{{end}}{{end}}</div>
diff --git a/internal/equipo/templates/placement_chip.html b/internal/equipo/templates/placement_chip.html
index c4b6d744..d8b84295 100644
--- a/internal/equipo/templates/placement_chip.html
+++ b/internal/equipo/templates/placement_chip.html
@@ -1,3 +1,3 @@
-{{define "placement-chip"}}<details equipo-placement equipo-roster-project data-placement-task="{{.ID}}"><summary aria-label="{{.Project}}: {{copy "placement.wrong"}}">{{template "mono-s" .Mono}}<span equipo-project-name>{{.Project}}</span>{{icon "chevron-down"}}</summary><div><strong>{{copy "placement.wrong"}}</strong>{{if .Stopping}}<p role="status">{{copy "roster.stopping"}}</p>{{else if .Moving}}{{template "placement-abandon" .}}{{else}}<a href="/tasks/{{.ID}}/move">{{copy "placement.move"}}</a><a href="/tasks/{{.ID}}/move?new=1">{{copy "placement.make_new"}}</a>{{end}}</div></details>{{end}}
+{{define "placement-chip"}}<details equipo-placement equipo-roster-project data-placement-task="{{.ID}}"><summary aria-label="{{.Project}}: {{copy "placement.wrong"}}">{{if not .Mono.InTitle}}{{template "mono-s" .Mono}}{{end}}<span equipo-project-name>{{.Project}}</span>{{icon "chevron-down"}}</summary><div><strong>{{copy "placement.wrong"}}</strong>{{if .Stopping}}<p role="status">{{copy "roster.stopping"}}</p>{{else if .Moving}}{{template "placement-abandon" .}}{{else}}<a href="/tasks/{{.ID}}/move">{{copy "placement.move"}}</a><a href="/tasks/{{.ID}}/move?new=1">{{copy "placement.make_new"}}</a>{{end}}</div></details>{{end}}
{{define "placement-abandon"}}<p equipo-placement-reason>{{if .MoveHoldReason}}{{copy (printf "placement.held_%s" .MoveHoldReason)}}{{else}}{{copy "placement.pending"}}{{end}}</p><p equipo-placement-help>{{copy "placement.abandon_help"}}</p><form method="post" action="/tasks/{{.ID}}/move"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn name="abandon" value="1" type="submit">{{copy "placement.abandon"}}</button></form>{{end}}
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go
index 9c14327c..ec9cd3fb 100644
--- a/internal/equipo/work_views.go
+++ b/internal/equipo/work_views.go
@@ -45,6 +45,7 @@ func hueOf(s string) int {
// monoLine is a project's letter monogram with a stable hue, until
// projects have icons.
type monoLine struct {
+ InTitle bool
Letter, Title string
Hue int
}
@@ -54,7 +55,7 @@ func monoOf(title, id string) monoLine {
if r == utf8.RuneError {
r = '?'
}
- return monoLine{Letter: string(unicode.ToUpper(r)), Title: title, Hue: hueOf(id)}
+ return monoLine{Letter: string(unicode.ToUpper(r)), Title: title, Hue: hueOf(id), InTitle: unicode.IsSymbol(r)}
}
// trackStages are the six stops of the stage track; merging sits on
diff --git a/internal/headless/access_resume_test.go b/internal/headless/access_resume_test.go
new file mode 100644
index 00000000..7136058b
--- /dev/null
+++ b/internal/headless/access_resume_test.go
@@ -0,0 +1,127 @@
+package headless
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/thin"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/thintest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The real runner polls approval, refreshes reach and sends a live hello while
+// git for the new repository is blocked. The real server resumes exactly once.
+func TestAccessResumeBeforeGit(t *testing.T) {
+ env, inst, r := localEnv(t)
+ ctx := context.Background()
+ sent, err := env.Client.Send(ctx, "Fix the build in carlos/platform", "original-access")
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ access := wire.AccessRequest{Target: "carlos/platform", Role: "agent", Reason: "Fix the build.", State: "pending", RequestID: "ar_live", ApproveURL: "https://amadan.net/settings/agents/requests/ar_live"}
+ raw, _ := json.Marshal(access)
+ if err := inst.DB.G.Exec("UPDATE chat_turns SET state='replied' WHERE id=?", sent.Turn.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := inst.DB.G.Exec("DELETE FROM runner_commands WHERE kind=?", wire.FrameMessage).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := inst.DB.G.Exec("INSERT INTO chat_cards(id,person,kind,state,turn_id,name,access,options,revision,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)", "c_live", thintest.Owner, wire.CardAccess, wire.CardOpen, sent.Turn.ID, "carlos/platform", string(raw), "[]", 1, now, now).Error; err != nil {
+ t.Fatal(err)
+ }
+ state, err := thin.OpenState(ctx, r.cfg.StateDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := wire.AccessCommand{CardID: "c_live", Person: thintest.Owner, Target: access.Target, Role: access.Role, Reason: access.Reason, Confirmed: true}
+ if err = state.AcceptAccess(ctx, "confirmed", cmd); err != nil {
+ t.Fatal(err)
+ }
+ state.Close()
+ db, err := sql.Open("sqlite", r.cfg.StateDir+"/thin.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ report := wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, RequestID: access.RequestID, State: "pending", ApproveURL: access.ApproveURL}
+ raw, _ = json.Marshal(report)
+ if _, err = db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)); err != nil {
+ db.Close()
+ t.Fatal(err)
+ }
+ db.Close()
+ f := &accessResumeForge{localForge: r.opts.Forge.(*localForge), report: report}
+ r.opts.Forge = f
+ r.start(t)
+ start := time.Now()
+ f.approved.Store(true)
+ for {
+ var state string
+ if err := inst.DB.G.Raw("SELECT state FROM chat_cards WHERE id='c_live'").Scan(&state).Error; err != nil {
+ t.Fatal(err)
+ }
+ if state == wire.CardResolved {
+ break
+ }
+ if time.Since(start) > 5*time.Second {
+ t.Fatal("approved request still waits for git")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ var messages []struct{ Text string }
+ if err := inst.DB.G.Raw("SELECT text FROM chat_messages WHERE idempotency_key='access-approved:c_live'").Scan(&messages).Error; err != nil {
+ t.Fatal(err)
+ }
+ if len(messages) != 1 || !strings.Contains(messages[0].Text, "Fix the build in carlos/platform") {
+ t.Fatal("original request not continued exactly once")
+ }
+ r.stop(t)
+ r.start(t)
+ var n int64
+ inst.DB.G.Table("chat_messages").Where("idempotency_key = ?", "access-approved:c_live").Count(&n)
+ if n != 1 {
+ t.Fatal("reconnect duplicated continuation", n)
+ }
+}
+
+type accessResumeForge struct {
+ *localForge
+ approved atomic.Bool
+ report wire.AccessReport
+}
+
+func (f *accessResumeForge) RequestAccess(context.Context, wire.AccessCommand) (wire.AccessReport, error) {
+ return f.report, nil
+}
+func (f *accessResumeForge) PollAccess(ctx context.Context, _ string, _ wire.AccessCommand) (wire.AccessReport, error) {
+ for !f.approved.Load() {
+ select {
+ case <-ctx.Done():
+ return wire.AccessReport{}, ctx.Err()
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+ v := f.report
+ v.State = "approved"
+ return v, nil
+}
+func (f *accessResumeForge) Reachable(ctx context.Context) []string {
+ out := f.localForge.Reachable(ctx)
+ if f.approved.Load() {
+ out = append(out, "amadan.net/carlos/platform")
+ }
+ return out
+}
+func (f *accessResumeForge) Remote(ctx context.Context, repo string) (workspace.Remote, error) {
+ if repo == "amadan.net/carlos/platform" {
+ <-ctx.Done()
+ return workspace.Remote{}, ctx.Err()
+ }
+ return f.localForge.Remote(ctx, repo)
+}
diff --git a/internal/runner/thin/access_resume.go b/internal/runner/thin/access_resume.go
new file mode 100644
index 00000000..fcfa7bed
--- /dev/null
+++ b/internal/runner/thin/access_resume.go
@@ -0,0 +1,86 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "path"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// AccessCatalog includes a verified grant immediately. Describing its clone
+// can finish later; access and the original request do not wait for git.
+func (x *Index) AccessCatalog(ctx context.Context, state *State) []wire.RepoInfo {
+ catalog := x.Catalog()
+ grants, err := state.approvedAccess(ctx)
+ if err != nil || len(grants) == 0 {
+ return catalog
+ }
+ reachable := x.Forge.Reachable(ctx)
+ for _, repo := range reachable {
+ if len(catalog) >= wire.MaxCatalog {
+ break
+ }
+ if slices.ContainsFunc(catalog, func(e wire.RepoInfo) bool { return e.Repo == repo }) {
+ continue
+ }
+ if slices.ContainsFunc(grants, func(c wire.AccessCommand) bool { return accessCovers(c.Target, repo) }) {
+ catalog = append(catalog, wire.RepoInfo{Repo: repo, Names: []string{path.Base(repo)}, Hints: []string{}})
+ }
+ }
+ return catalog
+}
+
+func accessCovers(target, repo string) bool {
+ repo = strings.TrimPrefix(repo, "amadan.net/")
+ return repo == target || !strings.Contains(target, "/") && strings.HasPrefix(repo, target+"/")
+}
+
+func (s *State) approvedAccess(ctx context.Context) ([]wire.AccessCommand, error) {
+ rows, err := s.db.QueryContext(ctx, "SELECT command FROM access_requests WHERE state = 'approved' ORDER BY rowid DESC LIMIT ?", wire.MaxCatalog)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []wire.AccessCommand
+ for rows.Next() {
+ var raw string
+ if err := rows.Scan(&raw); err != nil {
+ return nil, err
+ }
+ var c wire.AccessCommand
+ if err := json.Unmarshal([]byte(raw), &c); err != nil {
+ return nil, err
+ }
+ out = append(out, c)
+ }
+ return out, rows.Err()
+}
+
+// Grant-driven exploration belongs to the resumed request. Only new
+// namespaces fully covered by this person's approved requests are folded in.
+func (s *settler) foldAccess(ctx context.Context, person string, old, next []string) bool {
+ grants, err := s.State.approvedAccess(ctx)
+ if err != nil {
+ return false
+ }
+ for _, ns := range old {
+ if !slices.Contains(next, ns) {
+ return false
+ }
+ }
+ for _, ns := range next {
+ if slices.Contains(old, ns) {
+ continue
+ }
+ if !slices.ContainsFunc(grants, func(c wire.AccessCommand) bool {
+ target, _, _ := strings.Cut(c.Target, "/")
+ return c.Person == person && target == ns
+ }) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/runner/thin/access_resume_test.go b/internal/runner/thin/access_resume_test.go
new file mode 100644
index 00000000..3f34c03e
--- /dev/null
+++ b/internal/runner/thin/access_resume_test.go
@@ -0,0 +1,162 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestAccessGrantCatalogBeforeIndex(t *testing.T) {
+ for _, role := range []string{"agent", "reader"} {
+ t.Run(role, func(t *testing.T) {
+ ctx := context.Background()
+ var approved atomic.Bool
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/api/v1/repos":
+ if approved.Load() && role == "agent" {
+ fmt.Fprint(w, `{"repos":[{"ns":"carlos","name":"platform"}]}`)
+ } else {
+ fmt.Fprint(w, `{"repos":[]}`)
+ }
+ case r.URL.Path == "/api/v1/repos/carlos/platform":
+ if approved.Load() {
+ fmt.Fprint(w, `{"ns":"carlos","name":"platform","tier":"public"}`)
+ } else {
+ w.WriteHeader(404)
+ }
+ default:
+ v := accessResponse("ar_one", "approved")
+ v.Role = role
+ writeAccessInfo(w, v)
+ }
+ })
+ state, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ f.accessTargets = state.accessReadTargets
+ cmd := accessCommand()
+ cmd.Role = role
+ if err = state.AcceptAccess(ctx, "cmd", cmd); err != nil {
+ t.Fatal(err)
+ }
+ old := wire.AccessReport{CardID: cmd.CardID, Person: cmd.Person, RequestID: "ar_one", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one"}
+ raw, _ := json.Marshal(old)
+ state.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw))
+ index := &Index{Forge: f, catalog: []wire.RepoInfo{}} // No Clones: fetching cannot complete before the hello.
+ inst := newFakeInstance(t)
+ link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, func() wire.Hello {
+ return wire.Hello{Repos: f.Repos(), Catalog: index.AccessCatalog(ctx, state), CreateIn: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}}
+ })
+ c := <-inst.conns
+ read(t, c, wire.FrameHello)
+ welcome, _ := json.Marshal(wire.Frame{ID: "welcome", Type: wire.FrameWelcome, Data: json.RawMessage(fmt.Sprintf(`{"generation":3,"runner_id":"RUNNER1","protocol":%d,"role":"primary"}`, wire.ProtocolCurrent))})
+ write(t, c, welcome)
+ read(t, c, wire.FrameSync)
+ link.HelloSoon()
+ read(t, c, wire.FrameHello)
+ approved.Store(true)
+ // Exercise the production approval refresh, notification and live hello.
+ e := &AccessEngine{State: state, Forge: f, Refresh: func() { index.Kick(); link.HelloSoon() }}
+ start := time.Now()
+ if err = e.Step(ctx, cmd.CardID); err != nil {
+ t.Fatal(err)
+ }
+ frame, _ := read(t, c, wire.FrameHello)
+ var hello wire.Hello
+ if err = json.Unmarshal(frame.Data, &hello); err != nil {
+ t.Fatal(err)
+ }
+ if len(hello.Catalog) != 1 || hello.Catalog[0].Repo != "amadan.net/carlos/platform" {
+ t.Fatalf("grant held behind index: %+v", hello.Catalog)
+ }
+ if time.Since(start) > 2*time.Second {
+ t.Fatal("grant hello was not prompt")
+ }
+ if role == "reader" && len(hello.Repos) != 0 {
+ t.Fatal("read grant became writable")
+ }
+ approved.Store(false)
+ f.Recheck()
+ if got := index.AccessCatalog(ctx, state); len(got) != 0 {
+ t.Fatal("old approval supplied authority", got)
+ }
+ })
+ }
+}
+
+func TestAccessResumeFoldsExplore(t *testing.T) {
+ ctx := context.Background()
+ state, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ c := accessCommand()
+ if err = state.AcceptAccess(ctx, "grant", c); err != nil {
+ t.Fatal(err)
+ }
+ state.db.Exec("UPDATE access_requests SET state='approved'")
+ root := t.TempDir()
+ desk, err := OpenDesk(root, c.Person)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = desk.SaveEntries([]wire.NotebookEntry{{ID: "n1", Source: "own", Text: "A settled desk."}}); err != nil {
+ t.Fatal(err)
+ }
+ if err = desk.SaveState(deskState{MovedIn: true, Namespaces: []string{"oficina"}}); err != nil {
+ t.Fatal(err)
+ }
+ index := &Index{catalog: []wire.RepoInfo{{Repo: "amadan.net/oficina/equipo"}, {Repo: "amadan.net/carlos/platform"}}, settled: true}
+ s := &settler{State: state, Link: &Link{}, Index: index, SessionRoot: root, Persons: func() []string { return []string{c.Person} }}
+ for i := 0; i < 2; i++ {
+ s.Check(ctx)
+ }
+ frames, _, err := state.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if f.Type == wire.FrameMoveIn {
+ t.Fatal("grant also launched an explore turn")
+ }
+ }
+ again := &settler{State: state, Link: &Link{}, Index: index, SessionRoot: root, Persons: s.Persons}
+ again.Check(ctx)
+ frames, _, err = state.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range frames {
+ if f.Type == wire.FrameMoveIn {
+ t.Fatal("restart lost grant suppression")
+ }
+ }
+ if got := desk.State().Namespaces; len(got) != 1 {
+ t.Fatal("background refresh rewrote coordinator desk", got)
+ }
+ index.catalog = append(index.catalog, wire.RepoInfo{Repo: "amadan.net/other/new"})
+ s.Check(ctx)
+ frames, _, err = state.Unacked(ctx, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ for _, f := range frames {
+ if f.Type == wire.FrameMoveIn {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatal("unrelated access should still explore", n)
+ }
+}
diff --git a/internal/runner/thin/movein.go b/internal/runner/thin/movein.go
index 14c304ae..551b66eb 100644
--- a/internal/runner/thin/movein.go
+++ b/internal/runner/thin/movein.go
@@ -83,6 +83,11 @@ func (s *settler) Check(ctx context.Context) {
case !st.MovedIn || desk.Empty():
kind = wire.TurnMoveIn
case !slices.Equal(st.Namespaces, ns):
+ if s.foldAccess(ctx, person, st.Namespaces, ns) {
+ // The durable approvals suffice across restarts. Do not
+ // overwrite desk state while the resumed turn is taking notes.
+ continue
+ }
kind = wire.TurnExplore
}
s.mu.Lock()
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 56431c3b..50747d53 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -202,7 +202,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
clones := &Clones{Root: c.WorkspaceRoot, Git: c.GitPath, Forge: fg}
index := &Index{Forge: fg, Clones: clones, Path: filepath.Join(c.StateDir, "catalog.json"), Logger: o.Logger, Changed: link.HelloSoon, Pace: o.IndexPace}
tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity}
- o.Claude.Tools, o.Claude.Catalog = tools.Call, index.Catalog
+ o.Claude.Tools, o.Claude.Catalog = tools.Call, func() []wire.RepoInfo { return index.AccessCatalog(ctx, state) }
o.Claude.Protocol = link.LastProtocol
conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait}
conns.ClaudeUsage = o.Claude.Profile
@@ -326,7 +326,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if slices.Contains(in, o.Home) {
home = o.Home
}
- catalog := index.Catalog()
+ catalog := index.AccessCatalog(ctx, state)
if catalog == nil {
catalog = []wire.RepoInfo{}
}
diff --git a/internal/thintest/access_browser_test.go b/internal/thintest/access_browser_test.go
index 1b4ff0c6..c7a6ad3b 100644
--- a/internal/thintest/access_browser_test.go
+++ b/internal/thintest/access_browser_test.go
@@ -61,11 +61,49 @@ func TestBrowserAccessRequest(t *testing.T) {
}
p.wait(`document.querySelector('[data-access-state="`+state+`"]')`, state)
if state == "pending" {
- p.check(`(()=>{const a=document.querySelector('[data-access-approve]');return a.target==='_blank'&&a.rel.includes('noopener')&&a.href==='https://amadan.net/settings/agents/requests/ar_test'})()`, "approval link")
+ p.check(`(()=>{window.open=()=>null; document.querySelector('[data-access-approve]').click(); return !!document.querySelector('[data-access-waiting]:not([hidden])')})()`, "immediate approval busy state")
+ p.wait(`!document.querySelector('[data-access-approve]')`, "approval saved")
+ p.open("/conversation")
+ p.wait(`document.querySelector('[data-access-waiting]')`, "busy state after reload")
+ p.check(`document.querySelector('[data-access-waiting]').textContent.includes('Waiting for your approval on Amadan…') && document.querySelector('[equipo-access-spinner]') && getComputedStyle(document.querySelector('[equipo-access-spinner]')).borderTopStyle==='solid'`, "waiting copy and spinner")
+ p.check(`document.querySelector('[data-access-reopen]').href==='https://amadan.net/settings/agents/requests/ar_test'`, "reopen link")
+ p.shot(fmt.Sprintf("access-waiting-%d-%s", width, scheme))
+ }
+ if state != "pending" {
+ p.check(`!document.querySelector('[data-access-waiting]') && !document.querySelector('[data-access-approve]') && !document.querySelector('[data-access-reopen]') && !document.querySelector('[data-access-aside]') && !document.querySelector('[data-set-aside]')`, "final outcome replaces controls")
}
p.fits("access " + state)
p.shot(fmt.Sprintf("access-%s-%d-%s", state, width, scheme))
}
+ if outcome == "approved" {
+ hello := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent)
+ hello.Catalog = append(hello.Catalog, wire.RepoInfo{Repo: "amadan.net/carlos/platform", Names: []string{"platform"}, Hints: []string{}})
+ hello.Repos = append(hello.Repos, "amadan.net/carlos/platform")
+ for i := 0; i < 2; i++ {
+ if err := r.runner.Send(r.ctx, fmt.Sprintf("grant-catalog-%d", i), wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ }
+ p.wait(`document.querySelector('[equipo-card-done]')?.textContent.includes('Access granted to carlos/platform.')`, "compact granted note")
+ p.wait(`document.querySelectorAll('[equipo-thinking]').length===1`, "resumed thinking")
+ p.check(`!document.querySelector('[data-access-state]') && !document.querySelector('[data-access-aside]')`, "no stale card controls")
+ p.open("/conversation")
+ p.wait(`document.querySelectorAll('[equipo-thinking]').length===1`, "resumed thinking after reload")
+ var count int64
+ r.inst.DB.G.Table("chat_messages").Where("idempotency_key = ?", "access-approved:"+card.ID).Count(&count)
+ if count != 1 {
+ t.Fatal("continuation count", count)
+ }
+ p.shot(fmt.Sprintf("access-resumed-%d-%s", width, scheme))
+ var resumed string
+ r.inst.DB.G.Table("chat_messages").Select("turn_id").Where("idempotency_key = ?", "access-approved:"+card.ID).Scan(&resumed)
+ if err := r.runner.Send(r.ctx, "resumed-reply", wire.FrameReply, wire.Reply{TurnID: resumed, Attempt: 1, Text: "I can now read carlos/platform."}); err != nil {
+ t.Fatal(err)
+ }
+ p.wait(`document.querySelector('[equipo-message="incoming"] [equipo-message-body]') && document.querySelector('[data-chat-stream]').textContent.includes('I can now read carlos/platform.')`, "resumed reply visible")
+ p.open("/conversation")
+ p.check(`document.querySelector('[data-chat-stream]').textContent.includes('I can now read carlos/platform.')`, "reply survives reload")
+ }
})
}
}
diff --git a/internal/thintest/access_resume_browser_test.go b/internal/thintest/access_resume_browser_test.go
new file mode 100644
index 00000000..ff2745ea
--- /dev/null
+++ b/internal/thintest/access_resume_browser_test.go
@@ -0,0 +1,79 @@
+//go:build browser
+
+package thintest
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "fmt"
+ "testing"
+)
+
+func TestBrowserCoordinatorQueue(t *testing.T) {
+ for _, width := range []int64{1280, 390} {
+ for _, scheme := range []string{"light", "dark"} {
+ t.Run(fmt.Sprintf("%d-%s", width, scheme), func(t *testing.T) {
+ r := newToolRig(t)
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), width, 844, width == 390, scheme, "reduce")
+ defer p.stop()
+ p.open("/conversation")
+ p.wait(`document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-offline]').hidden`, "original thinking")
+ watch := `(()=>{window.thinkingPeak=document.querySelectorAll('[equipo-thinking]').length;new MutationObserver(()=>{window.thinkingPeak=Math.max(window.thinkingPeak,document.querySelectorAll('[equipo-thinking]').length)}).observe(document.querySelector('[data-chat-stream]'),{childList:true,subtree:true});return true})()`
+ p.check(watch, "observe live thinking count")
+ if err := r.runner.Send(r.ctx, "explore", wire.FrameMoveIn, wire.MoveIn{Person: Owner, Kind: wire.TurnExplore}); err != nil {
+ t.Fatal(err)
+ }
+ var explore string
+ r.wait("explore queued", func(c *Conversation) bool {
+ for id, v := range c.Turns {
+ if v.Kind == wire.TurnExplore {
+ explore = id
+ return true
+ }
+ }
+ return false
+ })
+ if err := r.runner.Send(r.ctx, "read-after-queue", wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile}); err != nil {
+ t.Fatal(err)
+ }
+ p.wait(`document.querySelector('[equipo-thinking] [equipo-activity]')?.textContent==='Reading the code…'`, "activity after queued turn reached browser")
+ p.check(`window.thinkingPeak===1 && document.querySelectorAll('[equipo-thinking]').length===1`, "one live thinking line")
+ p.open("/conversation")
+ p.check(`document.querySelectorAll('[equipo-thinking]').length===1`, "one thinking line after reload")
+ p.check(watch, "observe queue advance")
+ if err := r.runner.Send(r.ctx, "reply", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Done."}); err != nil {
+ t.Fatal(err)
+ }
+ r.runner.Expect(r.ctx, wire.FrameMessage)
+ if err := r.runner.Send(r.ctx, "explore-running", wire.FrameTurn, wire.TurnReport{TurnID: explore, Attempt: 1, State: wire.TurnRunning}); err != nil {
+ t.Fatal(err)
+ }
+ p.wait(`document.querySelector('[equipo-thinking][data-turn="`+explore+`"]')`, "queued explore starts")
+ p.check(`window.thinkingPeak===1 && document.querySelectorAll('[equipo-thinking]').length===1`, "one line when queue advances")
+ p.shot(fmt.Sprintf("access-queue-%d-%s", width, scheme))
+ })
+ }
+ }
+}
+
+func TestBrowserAccessEmojiByline(t *testing.T) {
+ r := newAlignRig(t)
+ if err := r.inst.DB.G.Exec("UPDATE chat_projects SET title = ?", "🤖 CARLOS platform").Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, width := range []int64{1280, 390} {
+ for _, scheme := range []string{"light", "dark"} {
+ t.Run(fmt.Sprintf("%d-%s", width, scheme), func(t *testing.T) {
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), width, 844, width == 390, scheme, "reduce")
+ defer p.stop()
+ p.open("/conversation")
+ p.wait(`document.querySelector('[equipo-roster-byline] [equipo-placement]')`, "project byline")
+ p.check(`Array.from(document.querySelectorAll('[equipo-roster-byline]')).filter(n=>n.querySelector('[equipo-placement]')).every(n=>(n.textContent.match(/🤖/gu)||[]).length===1)`, "project mark appears once")
+
+ p.check(`Array.from(document.querySelectorAll('[equipo-roster-byline]')).filter(n=>n.querySelector('[equipo-placement]')&&n.querySelector('b')).every(n=>{const a=n.querySelector('b').getBoundingClientRect(),b=n.querySelector('summary').getBoundingClientRect(),t=n.querySelector('time').getBoundingClientRect();return Math.abs((a.top+a.height/2)-(b.top+b.height/2))<3 && t.height<24})`, "author and project share a line; time wraps as a unit")
+ p.fits("emoji byline")
+ p.check(`(()=>{const n=Array.from(document.querySelectorAll('[equipo-roster-byline]')).find(n=>n.querySelector('[equipo-placement]')&&n.querySelector('b'));n.scrollIntoView({block:'center',behavior:'instant'});return true})()`, "show report byline")
+ p.shot(fmt.Sprintf("access-byline-%d-%s", width, scheme))
+ })
+ }
+ }
+}
diff --git a/internal/wire/access.go b/internal/wire/access.go
index 2cf61bcc..e5fd3391 100644
--- a/internal/wire/access.go
+++ b/internal/wire/access.go
@@ -16,13 +16,14 @@ const (
// AccessRequest is a proposal until the person confirms its exact fields.
type AccessRequest struct {
- Target string `json:"target"`
- Role string `json:"role,omitempty"`
- Reason string `json:"reason"`
- State string `json:"state,omitempty"`
- RequestID string `json:"request_id,omitempty"`
- ApproveURL string `json:"approve_url,omitempty"`
- Expires int64 `json:"expires,omitempty"`
+ ApprovalOpened bool `json:"approval_opened,omitempty"`
+ Target string `json:"target"`
+ Role string `json:"role,omitempty"`
+ Reason string `json:"reason"`
+ State string `json:"state,omitempty"`
+ RequestID string `json:"request_id,omitempty"`
+ ApproveURL string `json:"approve_url,omitempty"`
+ Expires int64 `json:"expires,omitempty"`
}
type AccessCommand struct {
CardID string `json:"card_id"`