Connect the Assistant to the Oficina apps behind a config switch
With EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID
set, the registry adds the oficina provider after Base's and the
team's, and the instance serves /oficina/connect/start (to connect's
consent), /oficina/connect/callback (the registered redirect) and POST
/oficina/connect/disconnect, all behind the member session. Unset,
nothing changes: no provider, no routes (TestContractAssistantOficina
OffByDefault).
A look for something the apps do, in a turn the person started, by a
person not connected, raises one Assistant connect card ("Connect your
Oficina apps", one link to start) while none is open; connecting
settles it. Migration 0089 adds oficina_connections (sealed refresh
token per person); saves check the roster in their transaction.
New copy is marked COPY REVIEW REQUIRED in copy.go and listed in the
Plan 3 inventory, with the API doc's sentence on connect cards.
Budgets re-measured: internal/equipo 20879, internal/equipo/chat 30101,
internal/thintest 30358 test lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+715
−11
.rastrillo/budgets.txt+3 −3docs/api/equipo-v1.md+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+11 −0internal/equipo/app.go+14 −0internal/equipo/chat/assistant_tools.go+1 −1internal/equipo/chat/connect.go+90 −0internal/equipo/chat/lane.go+3 −0internal/equipo/chat_wiring.go+25 −4internal/equipo/config.go+23 −0internal/equipo/copy.go+22 −0internal/equipo/migrations/0089_oficina_connections.sql+4 −0internal/equipo/migrations/schema.sql+1 −0internal/equipo/models.go+3 −1internal/equipo/oficina_connect.go+189 −0internal/equipo/staging_mail_test.go+26 −0internal/equipo/store.go+7 −0internal/thintest/assistant_oficina_contract_test.go+288 −0internal/thintest/instance.go+4 −1
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 6842c003..c2d6eb42 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,7 +14,7 @@ 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 20601 - Shared web rendering: project correction chips and destination forms beside Roster. Measured 20601 source lines. |
| +size internal/equipo 20879 - Shared web rendering: project correction chips and destination forms beside Roster; the Oficina connection routes and store. Measured 20879 source lines. |
| size internal/wire 6447 - Shared protocol types and Encode; 25 adds placement choices and notebook corrections. Measured 6447 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); |
| @@ -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 30008 - Transactional authority and dispatch stay together; project confirmation, fenced moves and notebook learning. Measured 30008 source lines. |
| +size internal/equipo/chat 30101 - Transactional authority and dispatch stay together; project confirmation, fenced moves, notebook learning and connect cards. Measured 30101 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. |
| @@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im |
| 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 - 30070 Shared instance harness: placement consent, restart proof, preserved context and responsive browser contracts. Measured 30070 test lines. |
| +size internal/thintest - 30358 Shared instance harness: placement consent, restart proof, preserved context, responsive browser and Oficina connection contracts. Measured 30358 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/api/equipo-v1.md b/docs/api/equipo-v1.md| index e0b28e40..bb64e111 100644 |
| --- a/docs/api/equipo-v1.md |
| +++ b/docs/api/equipo-v1.md |
| @@ -94,7 +94,7 @@ When a turn that answers you starts, a `glance` event may come first: one short |
| A message has `role` `person` or `assistant`. A turn's `kind` is empty when it answers you, and `team_update` when the Assistant tells you, on its own, what the team did with something you asked for. A `team_update` turn may end with no message: its state is `replied` and its `reply_id` is empty. Cancel a turn in flight with `POST /api/v1/assistant/turns/{id}/cancel` and an empty JSON object. The answer is `202` with the turn's `attempt`, or `409 turn_ended` once the turn has ended. |
| -A card has `id`, `revision`, `kind`, `state`, `question`, `options`, `links` and `result`. Its kind is `question`, `confirm`, `outcome`, `connect` or `job`. A `job` card has states of its own, below; any other card is `open`, `answered` or `resolved`. `options` and `links` are always arrays, never null. A link has `label` and `url`, and may have `rel`: `rel: "equipo"` marks a link to the job's page in Equipo. Answer an open card with `POST /api/v1/assistant/cards/{id}/answer`, one option's `value` and the card's revision: |
| +A card has `id`, `revision`, `kind`, `state`, `question`, `options`, `links` and `result`. Its kind is `question`, `confirm`, `outcome`, `connect` or `job`. A `job` card has states of its own, below; any other card is `open`, `answered` or `resolved`. `options` and `links` are always arrays, never null. A link has `label` and `url`, and may have `rel`: `rel: "equipo"` marks a link to the job's page in Equipo. 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. Answer an open card with `POST /api/v1/assistant/cards/{id}/answer`, one option's `value` and the card's revision: |
| ```json |
| {"choice":"Yes","revision":2} |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 53548822..fc4d1483 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6678,6 +6678,17 @@ records remain unchanged. |
| | `placement.observed` | Observed by Equipo | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| | `placement.forget` | Remove correction | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| | `placement.abandon_help` | You can abandon this move to keep the task here without restarting work. | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| +| `assistant.connect.oficina` | Connect your Oficina apps | Assistant connect card: its question, raised when the person asks for something the Oficina apps do before connecting them (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `assistant.connect.oficina_link` | Connect | Assistant connect card: the label of its one link, which starts connecting (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.title` | Oficina apps | the page after connecting or disconnecting the Oficina apps: its title (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.connected` | Your Oficina apps are connected. You can close this page and carry on in your conversation. | the page once the Oficina apps are connected (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.denied` | Your Oficina apps were not connected. You can connect them later from your conversation. | the page when the person did not allow the connection (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.expired` | This took too long or was already used. Use the card in your conversation to try again. | the page when the consent is too old, used, or not this person's (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.unavailable` | Oficina could not be reached. Try again in a minute. | the page when oficina-connect cannot be reached (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `oficina.connect.disconnected` | Your Oficina apps are disconnected. Your assistant can no longer use them. | the page after disconnecting the Oficina apps (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED | |
| +| `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 REVIEW REQUIRED | |
| +| `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 REVIEW REQUIRED | |
| +| `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. | API doc: the new sentence on connect cards in the card paragraph (oficina, 2026-11-16) | API; COPY REVIEW REQUIRED | |
| ## Task 21 |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 4a06d0bb..fe025645 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -3,6 +3,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/chat" |
| "amadan.net/oficina/equipo/internal/equipo/notifications" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| "context" |
| "encoding/json" |
| @@ -170,6 +171,14 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| store.chatExecution, store.chatTestPeople, store.chatOrigin, store.chatAssistantHosts = cfg.ExecutionEnabled, cfg.TestPeople, cfg.Origin, cfg.AssistantHosts |
| // What the Assistant's provider calls could not do, by call id only. |
| store.Chat().SetLogger(logger) |
| + if cfg.OficinaConnectOrigin != "" { |
| + // The Oficina apps, through oficina-connect. |
| + if store.oficina, err = oficina.New(cfg.oficinaConfig(), oficinaStore{store}, oficinaSealer{store}); err != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return nil, errors.New(copyOficinaConfig) |
| + } |
| + store.Chat().SetOperations(store.assistRegistry(logger)) |
| + } |
| if err := store.Bootstrap(context.Background(), cfg.Owners); err != nil { |
| return nil, err |
| } |
| @@ -306,6 +315,11 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/conversation/cards/{id}/visibility", a.chatCardVisibility) |
| r.Post("/conversation/cards/{id}/reply", a.chatCardReply) |
| r.Post("/conversation/turns/{id}/stop", a.chatTurnStop) |
| + if store.oficina != nil { |
| + r.Get(oficinaStartPath, a.oficinaStart) |
| + r.Get(oficinaCallbackPath, a.oficinaCallback) |
| + r.Post(oficinaDisconnectPath, a.oficinaDisconnect) |
| + } |
| r.Get("/jobs", a.jobsPage) |
| r.Get("/jobs/{id}", a.jobPage) |
| r.Post("/jobs/{id}/messages", a.jobSend) |
diff --git a/internal/equipo/chat/assistant_tools.go b/internal/equipo/chat/assistant_tools.go| index 01e49d2c..7fb66ae7 100644 |
| --- a/internal/equipo/chat/assistant_tools.go |
| +++ b/internal/equipo/chat/assistant_tools.go |
| @@ -594,7 +594,7 @@ func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.Too |
| } |
| switch row.Name { |
| case wire.ToolLook: |
| - text, err := ops.Look(ctx, row.Person, in.Query) |
| + text, err := ops.Look(withCall(ctx, row), row.Person, in.Query) |
| if err != nil { |
| return s.opFailed(ctx, row.Person, err), false |
| } |
diff --git a/internal/equipo/chat/connect.go b/internal/equipo/chat/connect.go| new file mode 100644 |
| index 00000000..df4d7cef |
| --- /dev/null |
| +++ b/internal/equipo/chat/connect.go |
| @@ -0,0 +1,90 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// ConnectCard is the Assistant card the instance raises when the person |
| +// asked for something a provider does and has not connected it: the |
| +// question and one link, to start connecting. Provider is kept on the |
| +// card (Name) so it is raised once and settled when they connect. |
| +type ConnectCard struct { |
| + Provider string |
| + Question string |
| + Link wire.CardLink |
| +} |
| + |
| +// RaiseConnect shows the person card in the Assistant lane, unless one |
| +// for the same provider is open. Raised from a call (look's), it belongs |
| +// to the call's turn, and only a turn the person started raises one. |
| +func (s *Store) RaiseConnect(ctx context.Context, person string, card ConnectCard) error { |
| + turn := "" |
| + if row, ok := callFrom(ctx); ok { |
| + turn = row.TurnID |
| + } |
| + return s.tx(ctx, func(t *txn) error { |
| + if _, err := t.s.authority.Me(t.db, person); err != nil { |
| + return err |
| + } |
| + if turn != "" { |
| + var kinds []string |
| + if err := t.db.Model(&turnRecord{}).Where("id = ? AND person = ?", turn, person).Pluck("coalesce(kind, '')", &kinds).Error; err != nil { |
| + return err |
| + } |
| + if len(kinds) != 1 || kinds[0] != wire.TurnPerson { |
| + return nil |
| + } |
| + } |
| + var open int64 |
| + if err := t.db.Model(&cardRecord{}).Where("person = ? AND lane = ? AND kind = ? AND name = ? AND state = ?", person, wire.LaneAssistant, wire.CardConnect, card.Provider, wire.CardOpen).Count(&open).Error; err != nil { |
| + return err |
| + } |
| + if open > 0 { |
| + return nil |
| + } |
| + links, err := json.Marshal([]wire.CardLink{card.Link}) |
| + if err != nil { |
| + return err |
| + } |
| + now := t.now() |
| + c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardConnect, State: wire.CardOpen, TurnID: turn, Question: card.Question, Options: "[]", Links: string(links), Name: card.Provider, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant} |
| + if err := t.db.Create(&c).Error; err != nil { |
| + return err |
| + } |
| + return t.cardEvent(c) |
| + }) |
| +} |
| + |
| +// SettleConnect resolves the person's open connect cards for provider: |
| +// they connected it. |
| +func (s *Store) SettleConnect(ctx context.Context, person, provider string) error { |
| + return s.tx(ctx, func(t *txn) error { |
| + var cards []cardRecord |
| + if err := t.db.Where("person = ? AND lane = ? AND kind = ? AND name = ? AND state = ?", person, wire.LaneAssistant, wire.CardConnect, provider, wire.CardOpen).Find(&cards).Error; err != nil { |
| + return err |
| + } |
| + for _, c := range cards { |
| + c.State = wire.CardResolved |
| + if err := t.saveCard(&c); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// connectCardView fills a connect card's link. |
| +func connectCardView(v *wire.AssistantCard, c cardRecord) error { |
| + if c.Links != "" { |
| + if err := json.Unmarshal([]byte(c.Links), &v.Links); err != nil { |
| + return err |
| + } |
| + } |
| + if v.Links == nil { |
| + v.Links = []wire.CardLink{} |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/chat/lane.go b/internal/equipo/chat/lane.go| index ac32cf89..2684ba23 100644 |
| --- a/internal/equipo/chat/lane.go |
| +++ b/internal/equipo/chat/lane.go |
| @@ -321,6 +321,9 @@ func (t *txn) assistantCardView(c cardRecord) (wire.AssistantCard, error) { |
| if c.Kind == wire.CardJob { |
| return v, t.jobCardView(&v, c) |
| } |
| + if c.Kind == wire.CardConnect { |
| + return v, connectCardView(&v, c) |
| + } |
| var options []string |
| if c.Options != "" { |
| if err := json.Unmarshal([]byte(c.Options), &options); err != nil { |
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go| index 4640e57a..e38b4645 100644 |
| --- a/internal/equipo/chat_wiring.go |
| +++ b/internal/equipo/chat_wiring.go |
| @@ -63,14 +63,35 @@ func (s *Store) Chat() *chat.Store { |
| return false |
| }, |
| }, nil) |
| - // The Assistant's operations: Base's, at the host each person |
| - // registered, then the team's (the hand-off). |
| - c := s.chat.store |
| - c.SetOperations(assist.NewRegistry(assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider())) |
| + s.chat.store.SetOperations(s.assistRegistry(slog.Default())) |
| }) |
| return s.chat.store |
| } |
| +// assistRegistry is the Assistant's operations: Base's, at the host each |
| +// person registered, then the team's (the hand-off), then, with |
| +// oficina-connect configured, the Oficina apps. A look for something |
| +// they do by a person not connected raises the connect card. |
| +func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry { |
| + c := s.chat.store |
| + providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()} |
| + if s.oficina != nil { |
| + providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil)) |
| + } |
| + r := assist.NewRegistry(providers...) |
| + r.OnUnconnected(func(ctx context.Context, person, provider string) { |
| + if provider != oficinaProvider { |
| + return |
| + } |
| + card := chat.ConnectCard{Provider: oficinaProvider, Question: copyText("assistant.connect.oficina"), Link: wire.CardLink{Label: copyText("assistant.connect.oficina_link"), URL: s.chatOrigin + oficinaStartPath}} |
| + if err := c.RaiseConnect(ctx, person, card); err != nil { |
| + logger.Warn(copyOficinaCardFailed, "err", err) |
| + } |
| + }) |
| + s.assist = r |
| + return r |
| +} |
| + |
| func lowered(in []string) []string { |
| out := make([]string, 0, len(in)) |
| for _, v := range in { |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index 2febd9db..3ce88767 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/home/connect" |
| "errors" |
| "net" |
| @@ -29,6 +30,14 @@ type Config struct { |
| // host (EQUIPO_ASSISTANT_HOSTS, comma-separated, lowercased): the |
| // Assistant calls no other address. |
| AssistantHosts []string |
| + // OficinaConnectOrigin is oficina-connect's origin |
| + // (EQUIPO_OFICINA_CONNECT_ORIGIN) and OficinaConnectClientID the |
| + // public client it registered for this instance |
| + // (EQUIPO_OFICINA_CONNECT_CLIENT_ID), whose redirect is |
| + // EQUIPO_ORIGIN/oficina/connect/callback. Unset, the Assistant has no |
| + // Oficina apps. |
| + OficinaConnectOrigin string |
| + OficinaConnectClientID string |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| @@ -57,6 +66,9 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| cfg.AssistantHosts = append(cfg.AssistantHosts, origin) |
| } |
| } |
| + if cfg.OficinaConnectOrigin = strings.TrimSpace(getenv("EQUIPO_OFICINA_CONNECT_ORIGIN")); cfg.OficinaConnectOrigin != "" { |
| + cfg.OficinaConnectClientID = strings.TrimSpace(getenv("EQUIPO_OFICINA_CONNECT_CLIENT_ID")) |
| + } |
| for _, suffix := range strings.Split(getenv("EQUIPO_TEST_PEOPLE"), ",") { |
| if suffix = strings.ToLower(strings.TrimSpace(suffix)); suffix != "" { |
| cfg.TestPeople = append(cfg.TestPeople, suffix) |
| @@ -117,9 +129,20 @@ func (cfg Config) validate() error { |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| return errors.New(copyLoggedMailPublic) |
| } |
| + if cfg.OficinaConnectOrigin != "" { |
| + if _, err := oficina.New(cfg.oficinaConfig(), oficinaStore{}, oficinaSealer{}); err != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return errors.New(copyOficinaConfig) |
| + } |
| + } |
| return nil |
| } |
| +// oficinaConfig is the oficina-connect client this configuration names. |
| +func (cfg Config) oficinaConfig() oficina.Config { |
| + return oficina.Config{Origin: cfg.OficinaConnectOrigin, ClientID: cfg.OficinaConnectClientID, Redirect: cfg.Origin + oficinaCallbackPath} |
| +} |
| + |
| // Logged sign-in mail is allowed off loopback only for Oficina's staging |
| // app, so the headless suite can sign in. Production origins never are. |
| var stagingMailOrigin = regexp.MustCompile(`^https://equipo-staging(-[a-f0-9]{16})?\.bds\.oncarlos\.com$`) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 5c77ecd6..c823248f 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -54,6 +54,13 @@ const ( |
| copyRetriageFailed = "Failed to triage open tasks." // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| ) |
| +// The Oficina apps through oficina-connect: a configuration refused at |
| +// boot, and a connect card that could not be raised (logged). |
| +const ( |
| + copyOficinaConfig = "EQUIPO_OFICINA_CONNECT_ORIGIN must be an HTTPS address, with EQUIPO_OFICINA_CONNECT_CLIENT_ID set." // COPY REVIEW REQUIRED |
| + copyOficinaCardFailed = "Could not show the card to connect Oficina apps." // COPY REVIEW REQUIRED |
| +) |
| + |
| // BootLog is the shared diagnostic used by the command entry point. |
| const BootLog = "Equipo could not start." |
| @@ -1644,6 +1651,21 @@ var pageCopy = map[string]string{ |
| "jobs.back": "Back to your conversation", // COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq, unchanged) |
| "jobs.all": "All work from Base", // COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq, unchanged) |
| + // The Assistant's connect card when the person asks for something |
| + // the Oficina apps do before connecting them: the question, and the |
| + // label of its one link, which starts connecting. |
| + "assistant.connect.oficina": "Connect your Oficina apps", // COPY REVIEW REQUIRED |
| + "assistant.connect.oficina_link": "Connect", // COPY REVIEW REQUIRED |
| + // The page after connecting the Oficina apps (/oficina/connect/...): |
| + // done, refused at the consent page, a consent too old or not this |
| + // person's, the connection service down; and after disconnecting. |
| + "oficina.connect.title": "Oficina apps", // COPY REVIEW REQUIRED |
| + "oficina.connect.connected": "Your Oficina apps are connected. You can close this page and carry on in your conversation.", // COPY REVIEW REQUIRED |
| + "oficina.connect.denied": "Your Oficina apps were not connected. You can connect them later from your conversation.", // COPY REVIEW REQUIRED |
| + "oficina.connect.expired": "This took too long or was already used. Use the card in your conversation to try again.", // COPY REVIEW REQUIRED |
| + "oficina.connect.unavailable": "Oficina could not be reached. Try again in a minute.", // COPY REVIEW REQUIRED |
| + "oficina.connect.disconnected": "Your Oficina apps are disconnected. Your assistant can no longer use them.", // COPY REVIEW REQUIRED |
| + |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.empty |
| "conversation.empty": "Say what you want done. Your coordinator picks the project and tells you, and you can change it.", |
| "conversation.age_minutes": "%d min", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0089_oficina_connections.sql b/internal/equipo/migrations/0089_oficina_connections.sql| new file mode 100644 |
| index 00000000..c6d66587 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0089_oficina_connections.sql |
| @@ -0,0 +1,4 @@ |
| +-- Each person's connection to oficina-connect, the Oficina apps' |
| +-- connection service: their rotating refresh token, sealed with the |
| +-- instance key. Access tokens are never stored. |
| +CREATE TABLE oficina_connections (person text PRIMARY KEY, refresh text, revision integer, created_at datetime, updated_at datetime); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index a76edb4e..29aacb0b 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -710,3 +710,4 @@ ALTER TABLE chat_turns ADD COLUMN create_repo text; |
| ALTER TABLE chat_notebooks ADD COLUMN corrections text; |
| CREATE INDEX chat_task_move ON chat_tasks(creator, move_project) WHERE move_project IS NOT NULL AND move_project <> ''; |
| UPDATE chat_notebooks SET entries = (SELECT json_group_array(json(value)) FROM json_each(chat_notebooks.entries) WHERE NOT (coalesce(json_extract(value, '$.source'), '') = 'own' AND substr(json_extract(value, '$.id'), 1, 2) = 'mv')) WHERE entries IS NOT NULL AND entries <> ''; |
| +CREATE TABLE oficina_connections (person text PRIMARY KEY, refresh text, revision integer, created_at datetime, updated_at datetime); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 2089e253..b9a643c8 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -55,4 +55,6 @@ type projectRequest = setup.ProjectRequest |
| type Specialist = library.Specialist |
| -func init() { Models = append(Models, oficinaid.Models...) } |
| +func init() { |
| + Models = append(append(Models, oficinaid.Models...), &oficinaConnectionRecord{}) |
| +} |
diff --git a/internal/equipo/oficina_connect.go b/internal/equipo/oficina_connect.go| new file mode 100644 |
| index 00000000..677fabfb |
| --- /dev/null |
| +++ b/internal/equipo/oficina_connect.go |
| @@ -0,0 +1,189 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/identity" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| +) |
| + |
| +// The Oficina apps, through oficina-connect (internal/equipo/oficina): |
| +// the provider's name in the Assistant's registry, and the routes a |
| +// person's browser takes to connect (the card's link, then connect's |
| +// redirect back) and to disconnect. |
| +const ( |
| + oficinaProvider = "oficina" |
| + oficinaStartPath = "/oficina/connect/start" |
| + oficinaCallbackPath = "/oficina/connect/callback" |
| + oficinaDisconnectPath = "/oficina/connect/disconnect" |
| +) |
| + |
| +// oficinaConnectionRecord is a person's connection to oficina-connect: |
| +// their refresh token, sealed with the instance key (domain |
| +// oficina.connect), replaced as connect rotates it. |
| +type oficinaConnectionRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + Refresh string |
| + Revision int64 |
| + CreatedAt time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (oficinaConnectionRecord) TableName() string { return "oficina_connections" } |
| + |
| +// oficinaStore keeps connections in the instance's database. A save |
| +// checks the roster in its transaction; each audit is a code, never a |
| +// token. |
| +type oficinaStore struct{ s *Store } |
| + |
| +func (o oficinaStore) Load(ctx context.Context, person string) (string, error) { |
| + var sealed []string |
| + err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Model(&oficinaConnectionRecord{}).Where("person = ?", normalizeAddress(person)).Pluck("refresh", &sealed).Error |
| + if err != nil || len(sealed) == 0 { |
| + return "", storeError(err) |
| + } |
| + return sealed[0], nil |
| +} |
| + |
| +func (o oficinaStore) Save(ctx context.Context, person, sealed, audit string) error { |
| + person = normalizeAddress(person) |
| + return o.tx(ctx, func(tx *gorm.DB) error { |
| + if _, err := currentRunnerMember(tx, person); err != nil { |
| + return err |
| + } |
| + var r oficinaConnectionRecord |
| + if err := tx.Where("person = ?", person).Limit(1).Find(&r).Error; err != nil { |
| + return err |
| + } |
| + now := time.Now().UTC() |
| + if r.Person == "" { |
| + r = oficinaConnectionRecord{Person: person, CreatedAt: now} |
| + } |
| + r.Refresh, r.Revision, r.UpdatedAt = sealed, r.Revision+1, now |
| + if err := tx.Save(&r).Error; err != nil { |
| + return err |
| + } |
| + if audit == "" { |
| + return nil |
| + } |
| + return appendAudit(tx, Actor{Address: person}, audit, "") |
| + }) |
| +} |
| + |
| +// Delete forgets a connection, a removed member's too. |
| +func (o oficinaStore) Delete(ctx context.Context, person, audit, detail string) error { |
| + person = normalizeAddress(person) |
| + return o.tx(ctx, func(tx *gorm.DB) error { |
| + if err := tx.Where("person = ?", person).Delete(&oficinaConnectionRecord{}).Error; err != nil { |
| + return err |
| + } |
| + return appendAudit(tx, Actor{Address: person}, audit, detail) |
| + }) |
| +} |
| + |
| +func (o oficinaStore) Audit(ctx context.Context, person, kind, detail string) error { |
| + return o.tx(ctx, func(tx *gorm.DB) error { return appendAudit(tx, Actor{Address: person}, kind, detail) }) |
| +} |
| + |
| +func (o oficinaStore) tx(ctx context.Context, fn func(*gorm.DB) error) error { |
| + err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| + if err == nil || errors.Is(err, ErrForbidden) { |
| + return err |
| + } |
| + return storeError(err) |
| +} |
| + |
| +// oficinaSealer seals with the instance key, as device results and |
| +// Base host tokens are (read when used: the key is set after the store). |
| +type oficinaSealer struct{ s *Store } |
| + |
| +func (o oficinaSealer) Seal(domain string, v any) (string, error) { |
| + return o.s.personDevices().Seal(domain, v) |
| +} |
| + |
| +func (o oficinaSealer) Open(domain, raw string, v any) error { |
| + return o.s.personDevices().Open(domain, raw, v) |
| +} |
| + |
| +// oficinaStart sends the signed-in person to connect's consent page. |
| +func (a *application) oficinaStart(w http.ResponseWriter, r *http.Request) { |
| + id, ok := identity.From(r) |
| + if !ok { |
| + ErrorPage(w, r, http.StatusForbidden, "") |
| + return |
| + } |
| + dest, err := a.store.oficina.Start(r.Context(), id.Address) |
| + if err != nil { |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| + return |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + http.Redirect(w, r, dest, http.StatusSeeOther) |
| +} |
| + |
| +// oficinaCallback is connect's redirect back: the same signed-in person |
| +// finishes the consent they started. Connected, their lists are read |
| +// afresh and their connect card is settled. |
| +func (a *application) oficinaCallback(w http.ResponseWriter, r *http.Request) { |
| + id, ok := identity.From(r) |
| + if !ok { |
| + ErrorPage(w, r, http.StatusForbidden, "") |
| + return |
| + } |
| + person := normalizeAddress(id.Address) |
| + switch err := a.store.oficina.Finish(r.Context(), person, r.URL.Query()); { |
| + case errors.Is(err, oficina.ErrDenied): |
| + a.oficinaPage(w, r, http.StatusOK, "oficina.connect.denied") |
| + return |
| + case errors.Is(err, oficina.ErrExpired): |
| + a.oficinaPage(w, r, http.StatusBadRequest, "oficina.connect.expired") |
| + return |
| + case errors.Is(err, ErrForbidden): |
| + ErrorPage(w, r, http.StatusForbidden, "") |
| + return |
| + case err != nil: |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| + return |
| + } |
| + a.store.assist.Forget(person) |
| + if err := a.store.Chat().SettleConnect(r.Context(), person, oficinaProvider); err != nil { |
| + a.logger.Warn(copyOficinaCardFailed, "err", err) |
| + } |
| + a.oficinaPage(w, r, http.StatusOK, "oficina.connect.connected") |
| +} |
| + |
| +// oficinaDisconnect revokes the signed-in person's connection at connect |
| +// and forgets it. |
| +func (a *application) oficinaDisconnect(w http.ResponseWriter, r *http.Request) { |
| + id, ok := identity.From(r) |
| + if !ok { |
| + ErrorPage(w, r, http.StatusForbidden, "") |
| + return |
| + } |
| + person := normalizeAddress(id.Address) |
| + if err := a.store.oficina.Disconnect(r.Context(), person); err != nil { |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| + return |
| + } |
| + a.store.assist.Forget(person) |
| + a.oficinaPage(w, r, http.StatusOK, "oficina.connect.disconnected") |
| +} |
| + |
| +// oficinaPage is a short page saying what happened, under the app's |
| +// chrome. |
| +func (a *application) oficinaPage(w http.ResponseWriter, r *http.Request, status int, key string) { |
| + data, err := a.page(r, "settings") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Title, data.EmptyKey = "oficina.connect.title", key |
| + w.Header().Set("Cache-Control", "no-store") |
| + renderStatus(w, status, "empty", data) |
| +} |
diff --git a/internal/equipo/staging_mail_test.go b/internal/equipo/staging_mail_test.go| index 01e5e347..54e173fb 100644 |
| --- a/internal/equipo/staging_mail_test.go |
| +++ b/internal/equipo/staging_mail_test.go |
| @@ -53,3 +53,29 @@ func TestDatabaseName(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// EQUIPO_OFICINA_CONNECT_ORIGIN is off by default; set, it needs an |
| +// https origin (http on loopback) and EQUIPO_OFICINA_CONNECT_CLIENT_ID, |
| +// and the client's redirect is this instance's callback. |
| +func TestOficinaConnectConfig(t *testing.T) { |
| + env := map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com", "EQUIPO_INSTANCE_KEY": "k", "CARLOS_SMTP_HOST": "smtp.example.com", "CARLOS_SMTP_FROM": "e@example.com", "EQUIPO_OFICINA_CONNECT_CLIENT_ID": "c"} |
| + get := func(k string) string { return env[k] } |
| + if cfg, err := LoadConfig(get); err != nil || cfg.OficinaConnectOrigin != "" || cfg.OficinaConnectClientID != "" { |
| + t.Fatalf("unset: %+v %v", cfg, err) |
| + } |
| + for origin, ok := range map[string]bool{"https://connect.oficina.works": true, "http://connect.oficina.works": false, "https://connect.oficina.works/x": false, "http://127.0.0.1:9": true} { |
| + env["EQUIPO_OFICINA_CONNECT_ORIGIN"] = origin |
| + if _, err := LoadConfig(get); (err == nil) != ok { |
| + t.Errorf("%s: %v", origin, err) |
| + } |
| + } |
| + env["EQUIPO_OFICINA_CONNECT_ORIGIN"], env["EQUIPO_OFICINA_CONNECT_CLIENT_ID"] = "https://connect.oficina.works", "" |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Error("no client id accepted") |
| + } |
| + env["EQUIPO_OFICINA_CONNECT_CLIENT_ID"] = " c " |
| + cfg, err := LoadConfig(get) |
| + if err != nil || cfg.OficinaConnectClientID != "c" || cfg.oficinaConfig().Redirect != "https://equipo.example.com/oficina/connect/callback" { |
| + t.Fatalf("set: %+v %v", cfg.oficinaConfig(), err) |
| + } |
| +} |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 220ec4ae..5c12729b 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -11,7 +11,9 @@ import ( |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| + "amadan.net/oficina/equipo/internal/equipo/assist" |
| "amadan.net/oficina/equipo/internal/equipo/library" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| @@ -79,6 +81,11 @@ type Store struct { |
| chatOrigin string |
| // chatAssistantHosts is EQUIPO_ASSISTANT_HOSTS. |
| chatAssistantHosts []string |
| + // oficina is the oficina-connect client, nil while |
| + // EQUIPO_OFICINA_CONNECT_ORIGIN is unset; assist the Assistant's |
| + // registry, kept to forget a person's lists when they connect. |
| + oficina *oficina.Connector |
| + assist *assist.Registry |
| } |
| type StoreOption func(*Store) |
diff --git a/internal/thintest/assistant_oficina_contract_test.go b/internal/thintest/assistant_oficina_contract_test.go| new file mode 100644 |
| index 00000000..0ed36232 |
| --- /dev/null |
| +++ b/internal/thintest/assistant_oficina_contract_test.go |
| @@ -0,0 +1,288 @@ |
| +package thintest |
| + |
| +import ( |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// oficinaRig is an Assistant rig whose instance has oficina-connect |
| +// configured: a fake connect that approves every consent itself. |
| +type oficinaRig struct { |
| + *opsRig |
| + fake *oficinatest.Connect |
| +} |
| + |
| +func newOficinaRig(t *testing.T) *oficinaRig { |
| + fake := oficinatest.Start(t) |
| + r := newRigWith(t, func(i *Instance) { |
| + i.OficinaConnect, i.OficinaClientID = fake.URL, fake.ClientID |
| + fake.Redirect = i.URL + "/oficina/connect/callback" |
| + }) |
| + runner := r.dialAt(wire.ProtocolAssistant) |
| + return &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: runner}, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} |
| +} |
| + |
| +// browse is one browser request with the owner's session, redirects not |
| +// followed: the status, Location and body. |
| +func (o *oficinaRig) browse(method, raw string) (int, string, string) { |
| + o.t.Helper() |
| + req, _ := http.NewRequest(method, raw, nil) |
| + if strings.HasPrefix(raw, o.inst.URL) { |
| + req.AddCookie(o.inst.Cookie()) |
| + if method == http.MethodPost { |
| + req.Header.Set("Origin", o.inst.URL) |
| + } |
| + } |
| + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + res, err := client.Do(req) |
| + if err != nil { |
| + o.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + body, _ := io.ReadAll(res.Body) |
| + return res.StatusCode, res.Header.Get("Location"), string(body) |
| +} |
| + |
| +// consent follows the connect card's link through connect's consent |
| +// and back, as the person's browser does; it returns the last page. |
| +func (o *oficinaRig) consent(start string) string { |
| + o.t.Helper() |
| + status, authorize, _ := o.browse(http.MethodGet, start) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") { |
| + o.t.Fatalf("start: %d %q", status, authorize) |
| + } |
| + status, callback, _ := o.browse(http.MethodGet, authorize) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(callback, o.inst.URL+"/oficina/connect/callback?") { |
| + o.t.Fatalf("consent: %d %q", status, callback) |
| + } |
| + status, _, page := o.browse(http.MethodGet, callback) |
| + if status != http.StatusOK { |
| + o.t.Fatalf("callback: %d %s", status, page) |
| + } |
| + return page |
| +} |
| + |
| +// connectCards are the person's connect cards in the Assistant lane. |
| +func (o *oficinaRig) connectCards() []wire.AssistantCard { |
| + o.t.Helper() |
| + snap, err := o.a.Snapshot(o.ctx) |
| + if err != nil { |
| + o.t.Fatal(err) |
| + } |
| + return slices.DeleteFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind != wire.CardConnect }) |
| +} |
| + |
| +// TestContractAssistantOficinaConnectCard: a look for something the |
| +// Oficina apps do, by a person who has not connected them, tells the |
| +// model so and raises one connect card, whose link starts connecting; a |
| +// look for anything else does neither. Connecting (PKCE, checked by the |
| +// fake) settles the card and the apps' operations are listed. |
| +func TestContractAssistantOficinaConnectCard(t *testing.T) { |
| + o := newOficinaRig(t) |
| + o.begin("Put lunch with Ana in my calendar on Friday.") |
| + for _, id := range []string{"l1", "l2"} { |
| + res := o.tool(id, wire.ToolLook, map[string]any{"query": "calendar"}) |
| + if res.IsError || !strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "(oficina)") { |
| + t.Fatalf("look %s: %+v", id, res) |
| + } |
| + } |
| + if res := o.tool("l3", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(res.Text, "oficina") { |
| + t.Errorf("weather: %+v", res) |
| + } |
| + cards := o.connectCards() |
| + if len(cards) != 1 { |
| + t.Fatalf("connect cards: %+v", cards) |
| + } |
| + c := cards[0] |
| + start := o.inst.URL + "/oficina/connect/start" |
| + if c.State != wire.CardOpen || c.Question != "Connect your Oficina apps" || len(c.Links) != 1 || c.Links[0].URL != start || c.Links[0].Label != "Connect" || c.Options == nil { |
| + t.Fatalf("card: %+v", c) |
| + } |
| + raw, _ := json.Marshal(c) |
| + var decoded any |
| + _ = json.Unmarshal(raw, &decoded) |
| + noMachinery(t, "k_none", []string{"/tasks/", "Equipo", "equipo"})("the connect card", decoded, false) |
| + |
| + page := o.consent(c.Links[0].URL) |
| + if !strings.Contains(page, "Your Oficina apps are connected.") { |
| + t.Errorf("page: %s", page) |
| + } |
| + if ex, _ := o.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| + cards = o.connectCards() |
| + if len(cards) != 1 || cards[0].State != wire.CardResolved || cards[0].Revision != c.Revision+1 { |
| + t.Errorf("after connecting: %+v", cards) |
| + } |
| + res := o.tool("l4", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + if strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "Calendar (oficina)") || !strings.Contains(res.Text, "calendar_create_event") { |
| + t.Errorf("connected look: %+v", res) |
| + } |
| + if n := len(o.connectCards()); n != 1 { |
| + t.Errorf("%d connect cards after connecting", n) |
| + } |
| + |
| + // A callback replayed, or one this person never started, connects |
| + // nothing. |
| + status, _, page := o.browse(http.MethodGet, o.inst.URL+"/oficina/connect/callback?state=nope&code=x&iss="+url.QueryEscape(o.fake.URL)) |
| + if status != http.StatusBadRequest || !strings.Contains(page, "try again") { |
| + t.Errorf("unknown state: %d %s", status, page) |
| + } |
| + if ex, _ := o.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaUse: through use, a read and a write |
| +// reach connect with a current bearer (refreshed, rotated, as each |
| +// expires) and the person's one team; the write's client_id is a UUIDv5 |
| +// of its ledger key, the same when a failed call is made again, and a |
| +// repeat is replayed. Destructive, external and unkeyed writes never |
| +// reach connect. Nothing stored or audited carries a token. |
| +func TestContractAssistantOficinaUse(t *testing.T) { |
| + o := newOficinaRig(t) |
| + o.fake.AccessTTL = time.Second |
| + o.begin("Book lunch.") |
| + o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + o.consent(o.connectCards()[0].Links[0].URL) |
| + |
| + d := o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "calendar_create_event"}) |
| + if d.IsError || strings.Contains(d.Text, "client_id") || strings.Contains(d.Text, `"teams"`) { |
| + t.Fatalf("describe: %+v", d) |
| + } |
| + if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "2026-11-20T00:00:00Z", "end": "2026-11-21T00:00:00Z"}); res.IsError || res.Code != "used" { |
| + t.Fatalf("read: %+v", res) |
| + } |
| + o.fake.FailNext = true |
| + lunch := map[string]any{"title": "Lunch with Ana", "start_local": "2026-11-20T13:00"} |
| + if res := o.use("w1", "calendar_create_event", lunch); !res.IsError || res.Code != "unavailable" { |
| + t.Fatalf("failed write: %+v", res) |
| + } |
| + if res := o.use("w2", "calendar_create_event", lunch); res.IsError || res.Code != "used" || res.Replayed { |
| + t.Fatalf("write: %+v", res) |
| + } |
| + if res := o.use("w3", "calendar_create_event", lunch); res.IsError || !res.Replayed { |
| + t.Fatalf("repeat: %+v", res) |
| + } |
| + for op, code := range map[string]string{"docs_delete": "not_yet", "calls_invite": "not_yet", "docs_append": "write_not_supported"} { |
| + if res := o.use("x-"+op, op, map[string]any{"id": "d1", "email": "guest@example.com", "text": "hi"}); !res.IsError || res.Code != code { |
| + t.Errorf("%s: %+v", op, res) |
| + } |
| + } |
| + |
| + calls := o.fake.Calls() |
| + if len(calls) != 3 || calls[0].Name != "calendar_free_busy" || calls[1].Name != "calendar_create_event" || calls[2].Name != "calendar_create_event" { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| + key, _ := calls[1].Input["client_id"].(string) |
| + if !uuidV5.MatchString(key) || calls[2].Input["client_id"] != key { |
| + t.Errorf("client_id %q then %v", key, calls[2].Input["client_id"]) |
| + } |
| + for _, c := range calls { |
| + if c.Input["team"] != "acme" || c.Bearer == "" { |
| + t.Errorf("call %s: %+v", c.Name, c) |
| + } |
| + } |
| + if _, refreshes := o.fake.Counts(); refreshes == 0 { |
| + t.Error("expired access tokens were not refreshed") |
| + } |
| + |
| + // The refresh token is stored sealed; neither it nor any access |
| + // token is in the audit or the logs. |
| + var sealed string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + if o.fake.Live(sealed) { |
| + t.Error("the refresh token is stored as it is") |
| + } |
| + logs := o.inst.Logs() |
| + for _, c := range calls { |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE record_id LIKE ?", "%"+c.Bearer+"%"); n != 0 || strings.Contains(logs, c.Bearer) { |
| + t.Error("an access token in the audit or the logs") |
| + } |
| + } |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.connect' AND actor = ? AND record_id = ''", Owner); n != 1 { |
| + t.Errorf("connect audits %d", n) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaDisconnect: the person's disconnect |
| +// revokes the connection at connect and forgets it; the next look for |
| +// the apps raises a connect card again. |
| +func TestContractAssistantOficinaDisconnect(t *testing.T) { |
| + o := newOficinaRig(t) |
| + o.begin("What is on Friday?") |
| + o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + o.consent(o.connectCards()[0].Links[0].URL) |
| + if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); res.IsError { |
| + t.Fatalf("read: %+v", res) |
| + } |
| + var sealed string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + status, _, page := o.browse(http.MethodPost, o.inst.URL+"/oficina/connect/disconnect") |
| + if status != http.StatusOK || !strings.Contains(page, "Your Oficina apps are disconnected.") { |
| + t.Fatalf("disconnect: %d %s", status, page) |
| + } |
| + if revoked := o.fake.Revoked(); len(revoked) != 1 || o.fake.Live(revoked[0]) { |
| + t.Errorf("revoked %v", revoked) |
| + } |
| + if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 { |
| + t.Errorf("%d connections kept", n) |
| + } |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.disconnect' AND actor = ?", Owner); n != 1 { |
| + t.Errorf("disconnect audits %d", n) |
| + } |
| + if res := o.tool("l2", wire.ToolLook, map[string]any{"query": "calendar"}); !strings.Contains(res.Text, "not connected") { |
| + t.Errorf("look after disconnecting: %+v", res) |
| + } |
| + if res := o.use("r2", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); !res.IsError { |
| + t.Errorf("use after disconnecting: %+v", res) |
| + } |
| + cards := o.connectCards() |
| + if len(cards) != 2 || cards[0].State == cards[1].State { |
| + t.Errorf("cards after disconnecting: %+v", cards) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaOffByDefault: without |
| +// EQUIPO_OFICINA_CONNECT_ORIGIN nothing changes: no hint, no card, no |
| +// routes. |
| +func TestContractAssistantOficinaOffByDefault(t *testing.T) { |
| + o := newOpsRig(t) |
| + o.begin("Put lunch in my calendar.") |
| + if res := o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}); strings.Contains(res.Text, "oficina") { |
| + t.Errorf("look: %+v", res) |
| + } |
| + snap, err := o.a.Snapshot(o.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardConnect }) { |
| + t.Errorf("a connect card: %+v", snap.Cards) |
| + } |
| + for _, path := range []string{"/oficina/connect/start", "/oficina/connect/callback"} { |
| + req, _ := http.NewRequest(http.MethodGet, o.inst.URL+path, nil) |
| + req.AddCookie(o.inst.Cookie()) |
| + res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res.Body.Close() |
| + if res.StatusCode != http.StatusNotFound { |
| + t.Errorf("%s: %d", path, res.StatusCode) |
| + } |
| + } |
| +} |
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go| index 3b29571a..134ceb6d 100644 |
| --- a/internal/thintest/instance.go |
| +++ b/internal/thintest/instance.go |
| @@ -58,6 +58,9 @@ type Instance struct { |
| // from the next start (StartInstanceWith, Restart). |
| AssistantHosts []string |
| Providers []assist.Provider |
| + // OficinaConnect and OficinaClientID are |
| + // EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID. |
| + OficinaConnect, OficinaClientID string |
| addr string |
| server *http.Server |
| @@ -126,7 +129,7 @@ func (i *Instance) serve(t testing.TB, l net.Listener) { |
| t.Fatal(err) |
| } |
| s := equipo.NewStore(d) |
| - router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts}, mail.Logged(i.logger), i.logger, s) |
| + router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts, OficinaConnectOrigin: i.OficinaConnect, OficinaConnectClientID: i.OficinaClientID}, mail.Logged(i.logger), i.logger, s) |
| if err != nil { |
| t.Fatal(err) |
| } |