oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "cmp"
5 "fmt"
6 "slices"
7 "strings"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/equipo/chat"
11 "amadan.net/oficina/equipo/internal/wire"
12)
13
14// The Connections page as Paul approved it (docs/mockups/connections.html,
15// 2026-11-08): what is answering and the preference, one row per
16// connection (its state in words with a dot, the provider's headroom only
17// when it reported one, the roles it serves and which are live, tokens
18// today, one recovery button when it needs the person and quiet actions
19// otherwise), and Add a connection with its chooser and the connecting
20// card.
21
22// connMachine is one machine's connections on the Connections page
23// (Mac runners slice F, task 11): its name, its rows, and on a Mac that
24// can take Claude the "Add Claude to <Mac>" its button says.
25type connMachine struct {
26 ID, Name string
27 Primary bool
28 Rows []connRow
29 AddClaude string
30}
31
32// groupByMachine groups v's rows by the machine each is on, the main
33// runner (primary) first, then each other machine in enrolment order
34// that holds a row or can take Claude (chat.TakesClaude). A row on a
35// machine no longer listed stays with the main runner's.
36func groupByMachine(v *modelsView, machines []chat.ConnectionMachine, primary string) {
37 listed := map[string]bool{}
38 for _, m := range machines {
39 listed[m.ID] = true
40 }
41 main := connMachine{ID: primary, Name: v.Runner, Primary: true}
42 byRunner := map[string][]connRow{}
43 for _, r := range v.Rows {
44 if r.Machine == "" || !listed[r.Machine] {
45 main.Rows = append(main.Rows, r)
46 } else {
47 byRunner[r.Machine] = append(byRunner[r.Machine], r)
48 }
49 }
50 v.Machines = []connMachine{main}
51 for _, m := range machines {
52 if m.ID == primary {
53 continue
54 }
55 g := connMachine{ID: m.ID, Name: cmp.Or(m.Label, m.ID), Rows: byRunner[m.ID]}
56 if chat.TakesClaude(m) {
57 g.AddClaude = fmt.Sprintf(copyText("chat.connections.add_to"), g.Name)
58 }
59 if len(g.Rows) > 0 || g.AddClaude != "" {
60 v.Machines = append(v.Machines, g)
61 }
62 }
63}
64
65// onPrimary: c is on the main runner (a row before slice F names no
66// runner, and is).
67func onPrimary(c wire.Connection, primary string) bool {
68 return c.RunnerID == "" || c.RunnerID == primary
69}
70
71// connKey is c's key for usage and live roles (chat.UsageKey).
72func connKey(c wire.Connection, primary string) string {
73 return chat.UsageKey(primary, c.RunnerID, c.LocalID)
74}
75
76// connRow is one connection the person holds (or held).
77type connRow struct {
78 // Label is the account the provider named (the success card's);
79 // Tag is the connection's label as every page says it.
80 ID, Provider, Name, Glyph, Label, Plan, Age string
81 Tag chat.ConnLabel
82 // Kind is the connection's (token: a pasted setup token); Expires
83 // says when its token expires, Renew asks for a new one near then.
84 Kind, Expires string
85 Renew bool
86 // State is the wire state; Words says it, WordsAt the reset it
87 // counts down to as a time (the hover title).
88 State, Words, WordsAt string
89 Meters []connMeter
90 Roles []connRole
91 // RolesNote stands where no role chip does.
92 RolesNote string
93 // Usage is today's tokens in words, "0" included; UsageTail the words
94 // after the figure.
95 Usage, UsageTail string
96 // PreferRevision is the preference's, for Make preferred.
97 PreferRevision int64
98 // Machine is the runner a row is on when that is not the main
99 // runner: its recovery starts there.
100 Machine string
101 // Needs is the one recovery action a row that needs the person shows
102 // (Sign in again, Connect again).
103 Needs string
104 Preferred, MakePreferred bool
105 SignOut, Forget bool
106 // CheckAgain: a token connection that needs signing in again can be
107 // checked again (one small request on the runner).
108 CheckAgain bool
109 // Note: an attempt that ended, said once.
110 Note string
111 // New: the row just added, highlighted once.
112 New bool
113 // Stated is the account email the person typed, shown as theirs
114 // where the provider named none. AskEmail offers the field for it;
115 // AskOpen opens it at once (a token sign-in that just finished).
116 Stated string
117 AskEmail, AskOpen bool
118 // UsageNote stands where a meter would, while none can show.
119 UsageNote string
120 // A metered connection (connectors spec S1): its model, spend line
121 // and its tail, why it is paused (Paused: the budget; Unknown: spend
122 // unknown, Resume with PauseRevision), a budget change Pending, and
123 // the budget form's figures at BudgetRevision.
124 Metered bool
125 Model, Spend, SpendTail string
126 Paused, Unknown, Pending string
127 PauseRevision, BudgetRevision int64
128 BudgetDay, BudgetMonth string
129 // Its allowed set (connectors spec rev 3.3 §16.1): "Models: 9 of 10",
130 // the list it opens (a form at ModelsRevision unless the runner is
131 // too old, which ModelsTooOld says), and the set pending until the
132 // runner applies it.
133 ModelsLine, ModelsPending, ModelsTooOld string
134 Models []connModel
135 ModelsRevision int64
136}
137
138// connModel is one model a metered connection's key listed: ticked when
139// allowed, greyed when it cannot be (No price yet), with a note when it
140// is not answering.
141type connModel struct {
142 ID, Tier, Note string
143 Allowed, Eligible bool
144}
145
146// connMeter is one provider-reported rate window. Resets counts down to
147// its reset; At is that reset as a time (the hover title).
148type connMeter struct {
149 Name, Level, Resets, At string
150 Used int
151}
152
153// connRole is one role a connection serves, Live while it runs one now.
154type connRole struct {
155 Name string
156 Live bool
157}
158
159// connAnswering is the card at the top: what answers now.
160type connAnswering struct {
161 Tone string
162 // Lead is LeadStart, LeadName in bold, LeadEnd.
163 LeadStart, LeadName, LeadEnd string
164 // LeadAt names the resets the lead counts down to as times (the
165 // hover title).
166 LeadAt string
167 Sub string
168 // SeeConversation adds the link to the conversation after Sub.
169 SeeConversation bool
170}
171
172// connPrefer is the Prefer control: Automatic ("") or a provider.
173type connPrefer struct {
174 Provider string
175 Revision int64
176 Options []connOption
177 Hint string
178}
179
180type connOption struct {
181 Value, Label string
182 On bool
183}
184
185// connectionsPage builds the page from the snapshot, today's usage per
186// connection and the preference.
187// stated is the email the person typed for a connection, by id.
188func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Preferences, runner string, stated map[string]string, now time.Time) modelsView {
189 v := modelsView{Offline: !snap.Runner.Online, Runner: runner, Cursor: snap.Cursor}
190 v.Prefer = preferControl(prefer)
191 primary := snap.Runner.ID
192 coordinating, serving := liveRoles(snap)
193 coord := coordinatorOn(snap)
194 var held []wire.Connection
195 for _, c := range snap.Connections {
196 switch {
197 case c.State == wire.ConnConnecting:
198 line := modelLine{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Kind: c.Kind, Connecting: true, Prompt: c.Prompt, RunnerID: c.RunnerID, Endpoint: wire.EndpointAnthropic}
199 if kp, ok := wire.APIKeyProviders[c.Provider]; ok && c.Kind == wire.KindAPIKey {
200 line.Endpoint = kp.Endpoint
201 line.Title, line.Sub = fmt.Sprintf(copyText("chat.connections.metered.title"), kp.Name), fmt.Sprintf(copyText("chat.connections.metered.key_sub"), kp.Name)
202 }
203 // The card seals to the key of the machine it is on.
204 if c.RunnerID == snap.Runner.ID {
205 line.SealKey = snap.Runner.SealKey
206 }
207 for _, r := range snap.Runners {
208 if r.ID == c.RunnerID && r.ID != primary {
209 line.SealKey, line.Machine = r.SealKey, r.ID
210 }
211 }
212 line.SignIn = c.Prompt != nil && c.Prompt.Kind == wire.PromptAuthorize && c.Kind != wire.KindToken
213 if line.SignIn {
214 line.Endpoint = wire.EndpointClaudeCode
215 }
216 // Loading: nothing from the runner yet (a sign-in with no link
217 // and no code sent is starting its CLI).
218 if c.Prompt == nil && c.Kind != wire.KindToken && c.Kind != wire.KindAPIKey || line.SignIn && c.Prompt.URL == "" && c.Prompt.Attempt == 0 {
219 line.Phrases = loadingPhrases(c.Provider)
220 }
221 v.Attempts = append(v.Attempts, line)
222 v.Connecting = true
223 case c.State == wire.ConnError && c.LocalID == "":
224 // An attempt that ended says why once, then the page moves on:
225 // after ten minutes, or once a newer attempt started.
226 if now.Sub(c.UpdatedAt) < 10*time.Minute && !newerThan(snap.Connections, c) {
227 note := copyText("chat.connections.reason." + c.Reason)
228 if c.Kind == wire.KindToken && c.Reason == "provider_refused" {
229 note = copyText("chat.connections.token_rejected")
230 }
231 if note == "" {
232 note = copyText("chat.connections.reason.provider_refused")
233 }
234 v.Ended = append(v.Ended, connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Note: note, Forget: true})
235 }
236 default:
237 held = append(held, c)
238 }
239 }
240 for i, c := range held {
241 held[i] = freshen(c, now)
242 }
243 labels := connLabels(snap.Connections, stated)
244 names := namesOf(held, labels)
245 // A metered connection never runs the coordinator (spec §0 decision
246 // 8): the answering line and the roles leave it out.
247 // Nor does one on another machine than the main runner.
248 answerable := slices.DeleteFunc(slices.Clone(held), func(c wire.Connection) bool { return c.Kind == wire.KindAPIKey || !onPrimary(c, primary) })
249 if coord == "" {
250 // Nothing answered yet: the first that can, the preferred first.
251 for _, c := range answerable {
252 if c.State == wire.ConnHealthy && (coord == "" || c.Provider == prefer.Provider) {
253 coord = c.LocalID
254 }
255 }
256 }
257 work := workOn(snap, answerable, coord)
258 for _, c := range held {
259 key := connKey(c, primary)
260 row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Tag: chat.LabelOf(labels, c), Plan: planLabel(c.Plan), Kind: c.Kind, State: c.State, Usage: tokensText(today[key]), PreferRevision: prefer.Revision}
261 if !onPrimary(c, primary) {
262 row.Machine = c.RunnerID
263 }
264 _, row.UsageTail, _ = strings.Cut(copyText("chat.connections.usage_today"), "%s")
265 if c.State == wire.ConnError {
266 row.State = wire.ConnSignInAgain
267 }
268 metered := false
269 if c.Headroom != nil && row.State != wire.ConnSignedOut && row.State != wire.ConnSignInAgain {
270 for _, w := range c.Headroom.Windows {
271 m := meterOf(w, now)
272 metered = metered || m.Resets != ""
273 row.Meters = append(row.Meters, m)
274 }
275 }
276 if len(row.Meters) > 0 {
277 row.Age = readingAge(c, now)
278 }
279 if c.Headroom != nil && c.Headroom.Unavailable {
280 row.UsageNote = copyText("usage.reading.unavailable")
281 }
282 // The status and a meter do not both say when: the meter does.
283 row.Words = connectionState(c, now, metered)
284 if c.State == wire.ConnLimited && !metered && c.Headroom != nil && c.Headroom.ResetsAt != nil {
285 row.WordsAt = resetText(*c.Headroom.ResetsAt, now.Location())
286 }
287 if c.Kind == wire.KindToken {
288 tokenFacts(&row, c, now)
289 }
290 if c.Kind == wire.KindAPIKey {
291 meteredFacts(&row, c, runner, now)
292 }
293 switch row.State {
294 case wire.ConnSignedOut:
295 row.Needs, row.Forget = copyText("chat.connections.connect_again"), true
296 case wire.ConnSignInAgain:
297 row.Needs, row.RolesNote = copyText("chat.connections.sign_in_again_action"), copyText("chat.connections.roles.sign_in_first")
298 row.CheckAgain = (c.Kind == wire.KindToken || c.Kind == wire.KindAPIKey) && c.LocalID != ""
299 case wire.ConnLimited:
300 row.RolesNote = copyText("chat.connections.roles.resting_none")
301 var to []string
302 for _, w := range work {
303 if w.LocalID != c.LocalID {
304 to = append(to, names.of(w))
305 }
306 }
307 if len(to) > 0 {
308 row.RolesNote = fmt.Sprintf(copyText("chat.connections.roles.resting_moved"), strings.Join(to, copyText("chat.connections.and")))
309 }
310 default:
311 if c.LocalID == coord && onPrimary(c, primary) {
312 row.Roles = append(row.Roles, connRole{Name: copyText("conversation.coordinator"), Live: coordinating[key]})
313 }
314 for _, name := range serving[key] {
315 row.Roles = append(row.Roles, connRole{Name: name, Live: true})
316 }
317 if len(row.Roles) == 0 {
318 row.RolesNote = copyText("chat.connections.roles.none")
319 }
320 }
321 if row.State != wire.ConnSignedOut {
322 row.SignOut = c.LocalID != ""
323 row.Preferred = prefer.Provider == c.Provider
324 row.MakePreferred = !row.Preferred && wire.PreferenceProviders[c.Provider]
325 }
326 v.Rows = append(v.Rows, row)
327 }
328 v.Answering = answering(answerable, coord, v.Attempts, names, prefer.Provider, now)
329 return v
330}
331
332// usageReportGrace is how long after an answered turn its provider's
333// usage has surely reached the row (hello every 30 s, headroom-only
334// changes at most once a minute), so a row with none can say none came.
335const usageReportGrace = 5 * time.Minute
336
337// rowFacts adds what the instance knows beside the runner's report: the
338// account email the person stated for a token connection the provider
339// named no account for, the field to state it in, and, on a ready row
340// with no meter, why there is none. A token connection is said to get
341// no usage only when a turn was answered on it long enough ago and it
342// never reported a window; otherwise the row says usage comes once the
343// provider reports it.
344func rowFacts(v *modelsView, snap wire.Snapshot, f chat.RowFacts) {
345 byID := map[string]wire.Connection{}
346 for _, c := range snap.Connections {
347 byID[c.ID] = c
348 }
349 for i := range v.Rows {
350 row := &v.Rows[i]
351 c := byID[row.ID]
352 if c.Kind == wire.KindToken && c.Label == "" && c.LocalID != "" && row.State != wire.ConnSignedOut {
353 row.Stated = f.Stated[c.ID]
354 row.AskEmail = true
355 row.AskOpen = row.New && row.Stated == ""
356 }
357 if row.State != wire.ConnHealthy || len(row.Meters) > 0 {
358 continue
359 }
360 if c.Kind == wire.KindToken && f.Served[connKey(c, snap.Runner.ID)] && (c.Headroom == nil || len(c.Headroom.Windows) == 0) {
361 row.UsageNote = copyText("chat.connections.usage_unreported")
362 } else {
363 row.UsageNote = fmt.Sprintf(copyText("chat.connections.usage_pending"), row.Name)
364 }
365 }
366}
367
368// newerThan: an attempt was started after c ended.
369func newerThan(conns []wire.Connection, c wire.Connection) bool {
370 for _, o := range conns {
371 if o.ID != c.ID && o.CreatedAt.After(c.UpdatedAt) {
372 return true
373 }
374 }
375 return false
376}
377
378// tokenFacts says when a token expires (about when, for an estimate),
379// asks for a sign-in again within TokenRenewal of then, and says a
380// rejected one was rejected. Both recoveries are the sign-in by a link
381// first, its card offering the paste second, as on the Add page.
382func tokenFacts(row *connRow, c wire.Connection, now time.Time) {
383 if row.State == wire.ConnSignInAgain {
384 row.Words = copyText("chat.connections.token_rejected_row")
385 return
386 }
387 if c.ExpiresAt == nil || row.State == wire.ConnSignedOut {
388 return
389 }
390 words := "chat.connections.token_expires"
391 if c.ExpiresEstimated {
392 // Neither the token nor the CLI says when: the date is a guess.
393 words = "chat.connections.token_expires_about"
394 }
395 row.Expires = fmt.Sprintf(copyText(words), c.ExpiresAt.UTC().Format("2 Jan 2006"))
396 row.Renew = c.ExpiresAt.Sub(now) < wire.TokenRenewal
397}
398
399// liveRoles are the roles each connection (by key) runs now: the
400// coordinator, for a turn of the person's running on it, and the names
401// of the specialists whose Engineering or Review steps run on it (a
402// maker by its own name: Design, not Engineering), Engineering then
403// Review then makers by name.
404func liveRoles(snap wire.Snapshot) (coordinating map[string]bool, serving map[string][]string) {
405 coordinating, serving = map[string]bool{}, map[string][]string{}
406 for _, t := range snap.Turns {
407 if t.State == wire.TurnRunning && t.Connection != "" {
408 coordinating[t.Connection] = true
409 }
410 }
411 for _, k := range snap.Tasks {
412 for _, s := range k.Steps {
413 if s.State != wire.StepRunning || s.Account == "" || s.Specialist != wire.SpecialistEngineering && s.Specialist != wire.SpecialistReview {
414 continue
415 }
416 key := chat.UsageKey(snap.Runner.ID, s.RunnerID, s.Account)
417 if name := stepName(s); !slices.Contains(serving[key], name) {
418 serving[key] = append(serving[key], name)
419 }
420 }
421 }
422 rank := func(name string) int {
423 if r, ok := map[string]int{specialistName(wire.SpecialistEngineering): 1, specialistName(wire.SpecialistReview): 2}[name]; ok {
424 return r
425 }
426 return 3
427 }
428 for _, names := range serving {
429 slices.SortFunc(names, func(a, b string) int { return cmp.Or(cmp.Compare(rank(a), rank(b)), strings.Compare(a, b)) })
430 }
431 return coordinating, serving
432}
433
434// coordinatorOn is the connection the person's coordinator answered on
435// last.
436func coordinatorOn(snap wire.Snapshot) string {
437 var at time.Time
438 on := ""
439 for _, t := range snap.Turns {
440 if t.Connection != "" && !t.UpdatedAt.Before(at) {
441 at, on = t.UpdatedAt, t.Connection
442 }
443 }
444 for _, c := range snap.Connections {
445 if c.LocalID == on && c.State == wire.ConnHealthy && onPrimary(c, snap.Runner.ID) {
446 return on
447 }
448 }
449 return ""
450}
451
452// answering says what answers now, or why nothing can. A connection is
453// named by its account when the person holds more than one of its
454// provider; what happens next is what the choice does, not a promise
455// (Paul, 2026-11-10): under Automatic work stays put until its next
456// message or step; with a preference it moves to the preferred one.
457// A rest counts down to its reset from now (Paul, 2026-11-11).
458func answering(held []wire.Connection, coord string, attempts []modelLine, names connNames, prefer string, now time.Time) connAnswering {
459 if len(held) == 0 {
460 return connAnswering{}
461 }
462 var on *wire.Connection
463 var resting []wire.Connection
464 for i, c := range held {
465 if c.LocalID == coord && c.State == wire.ConnHealthy {
466 on = &held[i]
467 }
468 if c.State == wire.ConnLimited {
469 resting = append(resting, c)
470 }
471 }
472 if on == nil {
473 var parts, at []string
474 for _, c := range held {
475 name := names.of(c)
476 switch c.State {
477 case wire.ConnLimited:
478 if c.Headroom != nil && c.Headroom.ResetsAt != nil {
479 parts = append(parts, fmt.Sprintf(copyText("chat.connections.answering.resets_in"), name, inText(c.Headroom.ResetsAt.Sub(now))))
480 at = append(at, resetAt(name, *c.Headroom.ResetsAt, now.Location()))
481 } else {
482 parts = append(parts, fmt.Sprintf(copyText("chat.connections.answering.no_reset"), name))
483 }
484 case wire.ConnSignedOut:
485 parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.signed_out"), name))
486 case wire.ConnSignInAgain, wire.ConnError:
487 parts = append(parts, fmt.Sprintf(copyText("chat.connections.answering.needs_sign_in"), name))
488 }
489 }
490 why := ""
491 if len(parts) > 0 {
492 why = " " + strings.Join(parts, "; ") + "."
493 }
494 return connAnswering{Tone: "attention", LeadName: copyText("chat.connections.answering.none"), LeadEnd: why, LeadAt: strings.Join(at, "; "), Sub: copyText("chat.connections.answering.kept"), SeeConversation: true}
495 }
496 a := connAnswering{}
497 a.LeadStart, a.LeadEnd, _ = strings.Cut(copyText("chat.connections.answering.on"), "%s")
498 a.LeadName = names.of(*on)
499 a.Sub = fmt.Sprintf(copyText("chat.connections.answering.too"), a.LeadName)
500 if len(resting) > 0 {
501 var rests, at []string
502 for _, c := range resting {
503 name := names.of(c)
504 if c.Provider == on.Provider && names.count[c.Provider] == 2 {
505 name = fmt.Sprintf(copyText("chat.connections.answering.other"), providerName(c.Provider))
506 }
507 if c.Headroom != nil && c.Headroom.ResetsAt != nil {
508 rests = append(rests, fmt.Sprintf(copyText("chat.connections.answering.back_in"), name, inText(c.Headroom.ResetsAt.Sub(now))))
509 at = append(at, resetAt(name, *c.Headroom.ResetsAt, now.Location()))
510 } else {
511 rests = append(rests, fmt.Sprintf(copyText("chat.connections.answering.rests"), name))
512 }
513 }
514 // "On X while Y rests." With a time it is a sentence of its own:
515 // "On X. Your other Codex account is back in 22 hours 5 minutes."
516 said := strings.Join(rests, copyText("chat.connections.and"))
517 if len(at) == 0 {
518 a.LeadEnd = fmt.Sprintf(copyText("chat.connections.answering.while"), said)
519 } else {
520 a.LeadEnd = fmt.Sprintf(copyText("chat.connections.answering.then"), sentenceCase(said))
521 }
522 a.LeadAt = strings.Join(at, "; ")
523 switch {
524 case prefer == "":
525 a.Sub += " " + copyText("chat.connections.answering.stays")
526 case prefer != on.Provider && names.count[prefer] > 0:
527 a.Sub += " " + fmt.Sprintf(copyText("chat.connections.answering.to_preferred"), providerName(prefer))
528 }
529 }
530 if len(attempts) > 0 {
531 a.Sub = fmt.Sprintf(copyText("chat.connections.answering.connecting"), attempts[0].Name)
532 }
533 return a
534}
535
536// resetAt is a reset as a time in the person's zone, for a hover title:
537// "Codex resets Thu 09:36".
538func resetAt(name string, t time.Time, loc *time.Location) string {
539 return sentenceCase(fmt.Sprintf(copyText("chat.connections.answering.resets_at"), name, resetText(t, loc)))
540}
541
542// connNames counts the person's connections by provider, to name each
543// in the answering card: the provider, and its shared label when the
544// person holds more than one of it (Paul, 2026-11-10).
545type connNames struct {
546 count map[string]int
547 labels map[string]chat.ConnLabel
548}
549
550func namesOf(held []wire.Connection, labels map[string]chat.ConnLabel) connNames {
551 n := connNames{count: map[string]int{}, labels: labels}
552 for _, c := range held {
553 n.count[c.Provider]++
554 }
555 return n
556}
557
558func (n connNames) of(c wire.Connection) string {
559 if n.count[c.Provider] > 1 {
560 return chat.LabelOf(n.labels, c).Text
561 }
562 return providerName(c.Provider)
563}
564
565// connLabels are the person's connections' shared labels, by id
566// (chat.ConnectionLabels in the instance's copy).
567func connLabels(conns []wire.Connection, stated map[string]string) map[string]chat.ConnLabel {
568 return chat.ConnectionLabels(conns, stated, copyText)
569}
570
571// workOn is where the person's work runs now: the coordinator's
572// connection, then those running a step, each once.
573func workOn(snap wire.Snapshot, held []wire.Connection, coord string) []wire.Connection {
574 ids := []string{coord}
575 for _, k := range snap.Tasks {
576 for _, s := range k.Steps {
577 if s.State == wire.StepRunning && s.Account != "" {
578 ids = append(ids, s.Account)
579 }
580 }
581 }
582 var out []wire.Connection
583 seen := map[string]bool{"": true}
584 for _, id := range ids {
585 for _, c := range held {
586 if c.LocalID == id && !seen[id] && c.State == wire.ConnHealthy {
587 seen[id] = true
588 out = append(out, c)
589 }
590 }
591 }
592 return out
593}
594
595// freshen drops what the provider reported that has gone stale: a
596// window or reset time already passed, and a full window on a
597// connection that answers (Paul, 2026-11-10: Ready with a full bar
598// after its reset). The meter stays away until fresh numbers come.
599func freshen(c wire.Connection, now time.Time) wire.Connection {
600 if c.Headroom == nil {
601 return c
602 }
603 h := *c.Headroom
604 if h.ResetsAt != nil && !h.ResetsAt.After(now) {
605 h.ResetsAt = nil
606 }
607 h.Windows = nil
608 for _, w := range c.Headroom.Windows {
609 if w.ResetsAt != nil && !w.ResetsAt.After(now) || c.State == wire.ConnHealthy && w.UsedPercent >= 99.5 {
610 continue
611 }
612 h.Windows = append(h.Windows, w)
613 }
614 c.Headroom = &h
615 return c
616}
617
618// meterOf is one reported window in words, its reset counted down from
619// now.
620func meterOf(w wire.Window, now time.Time) connMeter {
621 m := connMeter{Used: int(w.UsedPercent + 0.5), Level: "ok"}
622 switch {
623 case w.Minutes >= 7*24*60:
624 m.Name = copyText("chat.connections.window_week")
625 case w.Minutes > 0:
626 m.Name = fmt.Sprintf(copyText("chat.connections.window_hours"), (w.Minutes+30)/60)
627 default:
628 m.Name = copyText("chat.connections.window_used")
629 }
630 switch {
631 case m.Used >= 100:
632 m.Used, m.Level = 100, "full"
633 case m.Used >= 80:
634 m.Level = "high"
635 }
636 if w.ResetsAt != nil {
637 m.Resets = fmt.Sprintf(copyText("chat.connections.resets_in"), inText(w.ResetsAt.Sub(now)))
638 m.At = resetText(*w.ResetsAt, now.Location())
639 }
640 return m
641}
642
643// providerGlyph is a provider's monogram.
644func providerGlyph(p string) string {
645 switch p {
646 case wire.ProviderClaude:
647 return "Cl"
648 case wire.ProviderCodex:
649 return "Cx"
650 }
651 if len(p) >= 2 {
652 return strings.ToUpper(p[:1]) + p[1:2]
653 }
654 return p
655}
656
657// preferControl is the Prefer control: Automatic, Claude or Codex, the
658// person's on, with its hint (the Connections page and Settings).
659func preferControl(prefer wire.Preferences) connPrefer {
660 p := connPrefer{Provider: prefer.Provider, Revision: prefer.Revision, Hint: copyText("chat.connections.prefer_hint")}
661 if prefer.Provider == "" {
662 p.Hint = copyText("chat.connections.prefer_hint_auto")
663 }
664 for _, o := range []string{"", wire.ProviderClaude, wire.ProviderCodex} {
665 label := providerName(o)
666 if o == "" {
667 label = copyText("chat.connections.prefer_auto")
668 }
669 p.Options = append(p.Options, connOption{Value: o, Label: label, On: o == prefer.Provider})
670 }
671 return p
672}
673