| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "mime" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | "github.com/go-chi/chi/v5" |
| 18 | "gorm.io/gorm" |
| 19 | ) |
| 20 | |
| 21 | // The person's connections page (Equipo Connections slice 1): the |
| 22 | // accounts their coordinator and specialists run on, how each stands, |
| 23 | // and adding one from the app. It follows the event stream |
| 24 | // (connections.js): an attempt's sign-in steps, approval and every change |
| 25 | // of state arrive in place, never by a reload; without scripts, Check |
| 26 | // again. |
| 27 | |
| 28 | // modelLine is a connecting card: an attempt the person started. |
| 29 | type modelLine struct { |
| 30 | ID, Provider, Name string |
| 31 | // Kind is the attempt's (token: a pasted setup token). |
| 32 | Kind string |
| 33 | Connecting bool |
| 34 | Prompt *wire.ConnectPrompt |
| 35 | // SignIn: Claude's sign-in by the runner's own setup-token, whose |
| 36 | // code the card seals (wire.PromptAuthorize). |
| 37 | SignIn bool |
| 38 | // A token or sign-in card seals to RunnerID's SealKey ("" when the |
| 39 | // runner has none to give) for Endpoint. Machine is RunnerID when it |
| 40 | // is not the main runner: switching the way of connecting stays there. |
| 41 | RunnerID, SealKey, Endpoint, Machine string |
| 42 | // Phrases are the loading line's rotating words while the runner has |
| 43 | // not yet shown the provider's sign-in. |
| 44 | Phrases string |
| 45 | // An API-key card (wire.KindAPIKey): the provider's name and how it |
| 46 | // bills, sealed for Endpoint like a token. |
| 47 | Title, Sub string |
| 48 | } |
| 49 | |
| 50 | type modelsView struct { |
| 51 | Rows []connRow |
| 52 | // Attempts are the connecting cards; Ended the attempts that ended, |
| 53 | // said once. |
| 54 | Attempts []modelLine |
| 55 | Ended []connRow |
| 56 | Answering connAnswering |
| 57 | Prefer connPrefer |
| 58 | Runner string |
| 59 | Offline bool |
| 60 | // Cursor is where the page's event stream resumes; Connecting says an |
| 61 | // attempt is open (without scripts the page offers Check again). |
| 62 | Cursor int64 |
| 63 | Connecting bool |
| 64 | // Adding is the Add a connection page: the chooser and the attempt's |
| 65 | // card (Paul, 2026-11-10: "Can 'Add a connection' go to a new |
| 66 | // screen?"). |
| 67 | Adding bool |
| 68 | // Metered are the API-key providers the chooser offers, each with |
| 69 | // its confirmation and budget form (connectors spec S1). |
| 70 | Metered []meteredAdd |
| 71 | // Machines are the rows grouped by machine, the main runner first |
| 72 | // (slice F task 11). |
| 73 | Machines []connMachine |
| 74 | } |
| 75 | |
| 76 | // loadingLine is the card an Add shows at once, before the server has |
| 77 | // the attempt (the page's template for connections.js). |
| 78 | func loadingLine(provider string) modelLine { |
| 79 | return modelLine{ID: "pending", Provider: provider, Name: providerName(provider), Connecting: true, Phrases: loadingPhrases(provider)} |
| 80 | } |
| 81 | |
| 82 | // loadingPhrases are the loading line's turning words, joined for the |
| 83 | // page's data attribute. |
| 84 | func loadingPhrases(provider string) string { |
| 85 | var out []string |
| 86 | for i := 1; i <= 3; i++ { |
| 87 | if p := copyText(fmt.Sprintf("chat.connections.loading_%s_%d", provider, i)); p != "" { |
| 88 | out = append(out, p) |
| 89 | } |
| 90 | } |
| 91 | return strings.Join(out, "|") |
| 92 | } |
| 93 | |
| 94 | // tokensText is a token count in words: 840, 12.4k, 3.1M. |
| 95 | func tokensText(n int64) string { |
| 96 | switch { |
| 97 | case n >= 1_000_000: |
| 98 | return fmt.Sprintf("%.1fM", float64(n)/1e6) |
| 99 | case n >= 10_000: |
| 100 | return fmt.Sprintf("%.0fk", float64(n)/1e3) |
| 101 | case n >= 1_000: |
| 102 | return fmt.Sprintf("%.1fk", float64(n)/1e3) |
| 103 | } |
| 104 | return fmt.Sprint(n) |
| 105 | } |
| 106 | |
| 107 | // providerName is how a provider is named to a person. |
| 108 | func providerName(p string) string { return chat.ProviderName(p) } |
| 109 | |
| 110 | // resetText renders a provider's reset time in the person's zone (paused |
| 111 | // work, decision 4), the day and the clock and nothing more: the |
| 112 | // conversation's lines keep it, history under old messages, where a |
| 113 | // relative "in 9 hours" would go stale. |
| 114 | func resetText(t time.Time, loc *time.Location) string { return t.In(loc).Format("Mon 15:04") } |
| 115 | |
| 116 | // inText is how long until something, in words (Paul, 2026-11-11: |
| 117 | // "Resets in Xdays Yhours"): days and hours from a day, hours and |
| 118 | // minutes under a day, minutes under an hour, then under a minute. A |
| 119 | // part that is zero is left out; what is left of a minute is dropped. |
| 120 | func inText(d time.Duration) string { |
| 121 | if d < time.Minute { |
| 122 | return copyText("chat.connections.in.under_minute") |
| 123 | } |
| 124 | days, hours, minutes := int(d/(24*time.Hour)), int(d/time.Hour)%24, int(d/time.Minute)%60 |
| 125 | var parts []string |
| 126 | part := func(n int, unit string) { |
| 127 | switch { |
| 128 | case n == 1: |
| 129 | parts = append(parts, fmt.Sprintf(copyText("chat.connections.in."+unit), n)) |
| 130 | case n > 1: |
| 131 | parts = append(parts, fmt.Sprintf(copyText("chat.connections.in."+unit+"s"), n)) |
| 132 | } |
| 133 | } |
| 134 | switch { |
| 135 | case days > 0: |
| 136 | part(days, "day") |
| 137 | part(hours, "hour") |
| 138 | case hours > 0: |
| 139 | part(hours, "hour") |
| 140 | part(minutes, "minute") |
| 141 | default: |
| 142 | part(minutes, "minute") |
| 143 | } |
| 144 | return strings.Join(parts, " ") |
| 145 | } |
| 146 | |
| 147 | // connectionState is a held connection's state in words on the |
| 148 | // Connections page. A limited one says when it resets, unless a meter |
| 149 | // beside it already does (metered). |
| 150 | func connectionState(c wire.Connection, now time.Time, metered bool) string { |
| 151 | switch c.State { |
| 152 | case wire.ConnHealthy: |
| 153 | return copyText("chat.connections.healthy") |
| 154 | case wire.ConnLimited: |
| 155 | switch { |
| 156 | case metered: |
| 157 | return copyText("chat.connections.limited_now") |
| 158 | case c.Headroom != nil && c.Headroom.ResetsAt != nil: |
| 159 | return fmt.Sprintf(copyText("chat.connections.limited_resets_in"), inText(c.Headroom.ResetsAt.Sub(now))) |
| 160 | } |
| 161 | return copyText("chat.connections.limited") |
| 162 | case wire.ConnSignedOut: |
| 163 | return copyText("chat.connections.signed_out") |
| 164 | case wire.ConnSignInAgain: |
| 165 | return copyText("chat.connections.sign_in_again") |
| 166 | case wire.ConnConnecting: |
| 167 | return fmt.Sprintf(copyText("chat.connections.connecting"), providerName(c.Provider)) |
| 168 | } |
| 169 | return copyText("chat.connections.error") |
| 170 | } |
| 171 | |
| 172 | // switchedText is the quiet line under a reply that moved connection. |
| 173 | func switchedText(s *wire.Switched, loc *time.Location) string { |
| 174 | if s == nil { |
| 175 | return "" |
| 176 | } |
| 177 | to := providerName(s.To) |
| 178 | if s.ResetsAt == nil { |
| 179 | return fmt.Sprintf(copyText("chat.switched"), to) |
| 180 | } |
| 181 | return fmt.Sprintf(copyText("chat.switched_reset"), to, providerName(s.From), resetText(*s.ResetsAt, loc)) |
| 182 | } |
| 183 | |
| 184 | // noConnectionText says why nothing can answer, from the connections. |
| 185 | func noConnectionText(lines []chat.NoConnectionLine, loc *time.Location) string { |
| 186 | var parts []string |
| 187 | for _, l := range lines { |
| 188 | name := providerName(l.Provider) |
| 189 | switch { |
| 190 | case l.State == wire.ConnLimited && l.ResetsAt != nil: |
| 191 | parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.resets"), name, resetText(*l.ResetsAt, loc))) |
| 192 | case l.State == wire.ConnLimited: |
| 193 | parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.limited"), name)) |
| 194 | case l.State == wire.ConnSignedOut || l.State == wire.ConnSignInAgain || l.State == wire.ConnError: |
| 195 | parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.signed_out"), name)) |
| 196 | } |
| 197 | } |
| 198 | why := strings.Join(parts, "; ") + "." |
| 199 | if len(parts) == 0 { |
| 200 | why = copyText("chat.no_connection.none") |
| 201 | } |
| 202 | return fmt.Sprintf(copyText("chat.no_connection"), why) |
| 203 | } |
| 204 | |
| 205 | func (a *application) runnerLabel(ctx context.Context, address, id string) string { |
| 206 | label := "" |
| 207 | _ = a.store.readTeam(ctx, Actor{Address: address}, func(tx *gorm.DB, _ Team) error { |
| 208 | return tx.Raw("SELECT coalesce(label, '') FROM runners WHERE id = ?", id).Scan(&label).Error |
| 209 | }) |
| 210 | return label |
| 211 | } |
| 212 | |
| 213 | func (a *application) connectionsView(w http.ResponseWriter, r *http.Request) { |
| 214 | a.connectionsPageFor(w, r, false) |
| 215 | } |
| 216 | |
| 217 | // connectionsAdd is the Add a connection page. Its attempt, once |
| 218 | // connected (?attempt= from the scriptless Check again), leads back to |
| 219 | // Connections with the new row marked; with scripts connections.js does. |
| 220 | func (a *application) connectionsAdd(w http.ResponseWriter, r *http.Request) { |
| 221 | a.connectionsPageFor(w, r, true) |
| 222 | } |
| 223 | |
| 224 | func (a *application) connectionsPageFor(w http.ResponseWriter, r *http.Request, adding bool) { |
| 225 | w.Header().Set("Cache-Control", "no-store") |
| 226 | ctx, address, ok := sessionContext(r) |
| 227 | if !ok { |
| 228 | a.failure(w, r, ErrForbidden) |
| 229 | return |
| 230 | } |
| 231 | snap, err := a.store.Chat().Snapshot(ctx, address) |
| 232 | if err != nil { |
| 233 | a.failure(w, r, chatError(err)) |
| 234 | return |
| 235 | } |
| 236 | if id := r.URL.Query().Get("attempt"); adding && id != "" { |
| 237 | for _, c := range snap.Connections { |
| 238 | if c.ID == id && c.State == wire.ConnHealthy { |
| 239 | http.Redirect(w, r, "/conversation/settings/connections?added="+url.QueryEscape(id), http.StatusSeeOther) |
| 240 | return |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | data, err := a.settingsPage(r, "connections", false) |
| 245 | if err != nil { |
| 246 | a.failure(w, r, err) |
| 247 | return |
| 248 | } |
| 249 | data.Title = "chat.connections.title" |
| 250 | if adding { |
| 251 | data.Title = "chat.connections.add" |
| 252 | } |
| 253 | runner := a.runnerLabel(ctx, address, snap.Runner.ID) |
| 254 | if runner == "" { |
| 255 | runner = copyText("chat.connections.your_runner") |
| 256 | } |
| 257 | today, err := a.store.Chat().UsageToday(ctx, address) |
| 258 | if err != nil { |
| 259 | a.failure(w, r, chatError(err)) |
| 260 | return |
| 261 | } |
| 262 | prefer, err := a.store.Chat().Preference(ctx, address) |
| 263 | if err != nil { |
| 264 | a.failure(w, r, chatError(err)) |
| 265 | return |
| 266 | } |
| 267 | facts, err := a.store.Chat().ConnectionRowFacts(ctx, address, usageReportGrace) |
| 268 | if err != nil { |
| 269 | a.failure(w, r, chatError(err)) |
| 270 | return |
| 271 | } |
| 272 | machines, err := a.store.Chat().ConnectionMachines(ctx, address) |
| 273 | if err != nil { |
| 274 | a.failure(w, r, chatError(err)) |
| 275 | return |
| 276 | } |
| 277 | v := connectionsPage(snap, today, prefer, runner, facts.Stated, time.Now().In(a.store.Chat().Zone(address))) |
| 278 | v.Adding = adding |
| 279 | v.Metered = meteredAdds(r.URL.Query().Get("refused")) |
| 280 | for i := range v.Rows { |
| 281 | v.Rows[i].New = !adding && v.Rows[i].ID == r.URL.Query().Get("added") |
| 282 | } |
| 283 | rowFacts(&v, snap, facts) |
| 284 | groupByMachine(&v, machines, snap.Runner.ID) |
| 285 | data.Models, data.ConnectionsStream = v, true |
| 286 | render(w, "models", data) |
| 287 | } |
| 288 | |
| 289 | // connectionsStart is Add Codex, Add Claude (the sign-in by a link, or |
| 290 | // a pasted token) and a row's Sign in again or Paste a new token. |
| 291 | func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) { |
| 292 | if r.PostFormValue("kind") == wire.KindAPIKey { |
| 293 | ctx, address, ok := sessionContext(r) |
| 294 | if !ok { |
| 295 | a.failure(w, r, ErrForbidden) |
| 296 | return |
| 297 | } |
| 298 | a.connectionsStartMetered(w, r, ctx, address, r.PostFormValue("provider")) |
| 299 | return |
| 300 | } |
| 301 | a.chatActionTo(w, r, "/conversation/settings/connections/add", func(ctx context.Context, address string) error { |
| 302 | provider, kind, machine := r.PostFormValue("provider"), wire.KindSubscription, r.PostFormValue("runner_id") |
| 303 | if r.PostFormValue("kind") == wire.KindToken { |
| 304 | kind = wire.KindToken |
| 305 | } |
| 306 | // The card open on the same machine gives way to the other way of |
| 307 | // connecting: the sign-in by a link, or a token. |
| 308 | conns, err := a.store.Chat().Connections(ctx, address) |
| 309 | if err != nil { |
| 310 | return err |
| 311 | } |
| 312 | snap, err := a.store.Chat().Snapshot(ctx, address) |
| 313 | if err != nil { |
| 314 | return err |
| 315 | } |
| 316 | there := func(c wire.Connection) bool { |
| 317 | if machine == "" || machine == snap.Runner.ID { |
| 318 | return onPrimary(c, snap.Runner.ID) |
| 319 | } |
| 320 | return c.RunnerID == machine |
| 321 | } |
| 322 | for _, c := range conns { |
| 323 | if c.State == wire.ConnConnecting && c.Provider == provider && c.Kind != kind && there(c) { |
| 324 | // Switching is not giving up: the ended card goes unsaid. |
| 325 | if _, err := a.store.Chat().CancelConnection(ctx, address, c.ID); err != nil { |
| 326 | return err |
| 327 | } |
| 328 | if err := a.store.Chat().Forget(ctx, address, c.ID); err != nil { |
| 329 | return err |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | _, err = a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: kind, RunnerID: machine}) |
| 334 | if errors.Is(err, chat.ErrRunnerOffline) { |
| 335 | return nil |
| 336 | } |
| 337 | return err |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | // connectionsSignOut is a connection's quiet Sign out. |
| 342 | func (a *application) connectionsSignOut(w http.ResponseWriter, r *http.Request) { |
| 343 | a.chatActionTo(w, r, "/conversation/settings/connections", func(ctx context.Context, address string) error { |
| 344 | _, err := a.store.Chat().SignOut(ctx, address, chi.URLParam(r, "id")) |
| 345 | return err |
| 346 | }) |
| 347 | } |
| 348 | |
| 349 | // connectionsPrefer is the Prefer control and a row's Make preferred. |
| 350 | func (a *application) connectionsPrefer(w http.ResponseWriter, r *http.Request) { |
| 351 | back := "/conversation/settings/connections" |
| 352 | if r.PostFormValue("from") == "settings" { |
| 353 | back = "/conversation/settings/connections" |
| 354 | } |
| 355 | a.chatActionTo(w, r, back, func(ctx context.Context, address string) error { |
| 356 | revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| 357 | _, err := a.store.Chat().SetPreference(ctx, address, wire.Preferences{Provider: r.PostFormValue("provider"), Revision: revision}) |
| 358 | if errors.Is(err, chat.ErrConflict) { |
| 359 | // Changed elsewhere meanwhile: the page shows it as it is now. |
| 360 | return nil |
| 361 | } |
| 362 | return err |
| 363 | }) |
| 364 | } |
| 365 | |
| 366 | // connectionsEmail keeps the account email the person typed for one of |
| 367 | // their own token connections, or clears it (display only). The sign-in |
| 368 | // card's code form posts it too, from the Add page, where it returns. |
| 369 | func (a *application) connectionsEmail(w http.ResponseWriter, r *http.Request) { |
| 370 | back := "/conversation/settings/connections" |
| 371 | if r.PostFormValue("from") == "add" { |
| 372 | back += "/add" |
| 373 | } |
| 374 | a.chatActionTo(w, r, back, func(ctx context.Context, address string) error { |
| 375 | return a.store.Chat().SetStatedEmail(ctx, address, chi.URLParam(r, "id"), r.PostFormValue("email")) |
| 376 | }) |
| 377 | } |
| 378 | |
| 379 | // connectionsCheck is a connection's Check again. |
| 380 | func (a *application) connectionsCheck(w http.ResponseWriter, r *http.Request) { |
| 381 | a.chatActionTo(w, r, "/conversation/connections", func(ctx context.Context, address string) error { |
| 382 | err := a.store.Chat().CheckConnection(ctx, address, chi.URLParam(r, "id")) |
| 383 | if errors.Is(err, chat.ErrConflict) { |
| 384 | return nil |
| 385 | } |
| 386 | return err |
| 387 | }) |
| 388 | } |
| 389 | |
| 390 | // connectionsForget removes a signed-out connection, or an ended |
| 391 | // attempt, from the list. |
| 392 | func (a *application) connectionsForget(w http.ResponseWriter, r *http.Request) { |
| 393 | back := "/conversation/settings/connections" |
| 394 | if r.PostFormValue("from") == "add" { |
| 395 | back += "/add" |
| 396 | } |
| 397 | a.chatActionTo(w, r, back, func(ctx context.Context, address string) error { |
| 398 | return a.store.Chat().Forget(ctx, address, chi.URLParam(r, "id")) |
| 399 | }) |
| 400 | } |
| 401 | |
| 402 | // connectionsSecret takes the token card's sealed box (JSON, sealed in |
| 403 | // the page by connections.js) for one of the person's token attempts. |
| 404 | // It answers 202 and nothing else: the box is never echoed. |
| 405 | func (a *application) connectionsSecret(w http.ResponseWriter, r *http.Request) { |
| 406 | w.Header().Set("Cache-Control", "no-store") |
| 407 | ctx, address, ok := sessionContext(r) |
| 408 | if !ok { |
| 409 | a.failure(w, r, ErrForbidden) |
| 410 | return |
| 411 | } |
| 412 | var in wire.Sealed |
| 413 | media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 414 | raw, err := io.ReadAll(io.LimitReader(r.Body, 2*wire.MaxSealedBytes)) |
| 415 | if media != "application/json" || err != nil || len(raw) >= 2*wire.MaxSealedBytes || wire.Strict(raw, &in) != nil { |
| 416 | a.failure(w, r, chatError(chat.ErrInvalid)) |
| 417 | return |
| 418 | } |
| 419 | if _, err := a.store.Chat().SendSecret(ctx, address, chi.URLParam(r, "id"), in); err != nil { |
| 420 | a.failure(w, r, chatError(err)) |
| 421 | return |
| 422 | } |
| 423 | runnerJSON(w, http.StatusAccepted, struct{}{}) |
| 424 | } |
| 425 | |
| 426 | func (a *application) connectionsCancel(w http.ResponseWriter, r *http.Request) { |
| 427 | a.chatActionTo(w, r, "/conversation/settings/connections/add", func(ctx context.Context, address string) error { |
| 428 | _, err := a.store.Chat().CancelConnection(ctx, address, chi.URLParam(r, "id")) |
| 429 | return err |
| 430 | }) |
| 431 | } |
| 432 | |