| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "unicode" |
| 10 | "unicode/utf8" |
| 11 | |
| 12 | "gorm.io/gorm" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // What the inner screens show beyond the task itself: a step's newest |
| 18 | // activity lines, the task's people and source, a possible duplicate, |
| 19 | // the coordinator at work on it, and what Equipo knows of a project. |
| 20 | |
| 21 | // DisplayName is a member's name until people have profiles: the |
| 22 | // address's local part up to the first ".", "_", "-" or "+", capitalised; |
| 23 | // initials is its first letter. |
| 24 | func DisplayName(address string) (name, initials string) { |
| 25 | local, _, _ := strings.Cut(address, "@") |
| 26 | if i := strings.IndexAny(local, "._-+"); i > 0 { |
| 27 | local = local[:i] |
| 28 | } |
| 29 | r, n := utf8.DecodeRuneInString(local) |
| 30 | if n == 0 || r == utf8.RuneError { |
| 31 | return address, "" |
| 32 | } |
| 33 | first := string(unicode.ToUpper(r)) |
| 34 | return first + local[n:], first |
| 35 | } |
| 36 | |
| 37 | func personRef(address string) wire.PersonRef { |
| 38 | name, initials := DisplayName(address) |
| 39 | return wire.PersonRef{Address: address, Name: name, Initials: initials} |
| 40 | } |
| 41 | |
| 42 | func decodeActivity(raw string) []wire.ActivityLine { |
| 43 | out := []wire.ActivityLine{} |
| 44 | if raw != "" { |
| 45 | _ = json.Unmarshal([]byte(raw), &out) |
| 46 | } |
| 47 | return out |
| 48 | } |
| 49 | |
| 50 | var activityKinds = []string{wire.ActivityRead, wire.ActivitySearch, wire.ActivityEdit, wire.ActivityRun, wire.ActivityOther} |
| 51 | |
| 52 | // activitySubject is a line's subject made safe to show: one line, no |
| 53 | // control characters, the workspace prefix gone, bounded. |
| 54 | func activitySubject(s string) string { |
| 55 | if !utf8.ValidString(s) { |
| 56 | return "" |
| 57 | } |
| 58 | s, _, _ = strings.Cut(strings.TrimSpace(s), "\n") |
| 59 | s = strings.TrimPrefix(strings.TrimSpace(s), "/workspace/") |
| 60 | s = strings.Map(func(r rune) rune { |
| 61 | if unicode.IsControl(r) { |
| 62 | return -1 |
| 63 | } |
| 64 | return r |
| 65 | }, s) |
| 66 | if len(s) > wire.MaxActivitySubject { |
| 67 | s = s[:wire.MaxActivitySubject] |
| 68 | for !utf8.ValidString(s) { |
| 69 | s = s[:len(s)-1] |
| 70 | } |
| 71 | } |
| 72 | return strings.TrimSpace(s) |
| 73 | } |
| 74 | |
| 75 | // stepActivity keeps a running step's newest activity line and tells |
| 76 | // every member. Only the step person's primary runner, for the current |
| 77 | // attempt of a step that has not ended; anything else is dropped (the |
| 78 | // frame is not durable, so nothing waits on it). |
| 79 | func (t *txn) stepActivity(l Lease, v *wire.StepActivityReport) error { |
| 80 | var s stepRecord |
| 81 | if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 82 | return nil |
| 83 | } else if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | if s.Person != l.Runner.Person || v.Attempt != s.Attempt || wire.StepTerminal(s.State) { |
| 87 | return nil |
| 88 | } |
| 89 | primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | if primary != l.Runner.RunnerID { |
| 94 | return nil |
| 95 | } |
| 96 | kind := v.Kind |
| 97 | if !slices.Contains(activityKinds, kind) { |
| 98 | kind = wire.ActivityOther |
| 99 | } |
| 100 | lines := append(decodeActivity(s.Activity), wire.ActivityLine{Kind: kind, Subject: activitySubject(v.Subject), At: t.now()}) |
| 101 | if len(lines) > wire.MaxStepActivity { |
| 102 | lines = lines[len(lines)-wire.MaxStepActivity:] |
| 103 | } |
| 104 | raw, _ := json.Marshal(lines) |
| 105 | if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("activity", string(raw)).Error; err != nil { |
| 106 | return err |
| 107 | } |
| 108 | members, err := t.members() |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | data := wire.StepActivity{TaskID: s.TaskID, StepID: s.ID, Attempt: s.Attempt, Activity: lines} |
| 113 | for _, m := range members { |
| 114 | if err := t.event("", m, wire.EventActivity, wire.ResourceStep, s.ID, 0, "", "", s.Attempt, data); err != nil { |
| 115 | return err |
| 116 | } |
| 117 | } |
| 118 | return t.pushLine(s, lines[len(lines)-1]) |
| 119 | } |
| 120 | |
| 121 | // taskExtras fills what the screens show around a task: the creator's |
| 122 | // name, the message it was noted from, a possible duplicate and the |
| 123 | // coordinator at work on it. |
| 124 | func (t *txn) taskExtras(v *wire.Task, k taskRecord, steps []stepRecord) error { |
| 125 | v.CreatorName, _ = DisplayName(k.Creator) |
| 126 | if err := t.foldViews(v, k); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | if k.TurnID != "" { |
| 130 | var m messageRecord |
| 131 | err := t.db.Where("turn_id = ? AND person = ? AND role = ?", k.TurnID, k.Creator, wire.RolePerson).Order("seq").First(&m).Error |
| 132 | if err == nil { |
| 133 | at := m.CreatedAt |
| 134 | v.SourceMessageID, v.SourceAt = m.ID, &at |
| 135 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 136 | return err |
| 137 | } |
| 138 | } |
| 139 | if k.DuplicateOf != "" { |
| 140 | var d taskRecord |
| 141 | err := t.db.Select("id", "title", "stage", "creator").Where("id = ?", k.DuplicateOf).First(&d).Error |
| 142 | if err == nil { |
| 143 | v.DuplicateOf = &wire.TaskRef{ID: d.ID, Title: d.Title, Stage: d.Stage, Creator: d.Creator} |
| 144 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 145 | return err |
| 146 | } |
| 147 | } |
| 148 | switch k.Stage { |
| 149 | case wire.StageMerging: |
| 150 | since := k.UpdatedAt |
| 151 | for i := len(steps) - 1; i >= 0; i-- { |
| 152 | if steps[i].Specialist == wire.SpecialistMerge { |
| 153 | if steps[i].StartedAt != nil { |
| 154 | since = *steps[i].StartedAt |
| 155 | } |
| 156 | break |
| 157 | } |
| 158 | } |
| 159 | v.Coordinator = &wire.TaskActivity{Kind: wire.CoordinatorMerging, Since: since} |
| 160 | case wire.StageNoted, wire.StageInvestigated: |
| 161 | if k.TurnID == "" { |
| 162 | break |
| 163 | } |
| 164 | var r turnRecord |
| 165 | err := t.db.Select("id", "state", "created_at").Where("id = ?", k.TurnID).First(&r).Error |
| 166 | if err == nil && !wire.Terminal(r.State) { |
| 167 | v.Coordinator = &wire.TaskActivity{Kind: wire.CoordinatorLooking, Since: r.CreatedAt} |
| 168 | } else if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| 169 | return err |
| 170 | } |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 | |
| 175 | // MarkDuplicate folds a task into another open task of the same project: |
| 176 | // only its creator; the task is cancelled as Cancel does, and its title |
| 177 | // and brief go on the other task's thread as a report. |
| 178 | func (s *Store) MarkDuplicate(ctx context.Context, person, id string, in wire.MarkDuplicate) (out wire.Task, err error) { |
| 179 | err = s.tx(ctx, func(t *txn) error { |
| 180 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 181 | return err |
| 182 | } |
| 183 | k, err := t.loadTask(id) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | if k.Creator != person { |
| 188 | return ErrForbidden |
| 189 | } |
| 190 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 191 | return ErrTaskEnded |
| 192 | } |
| 193 | of := strings.TrimSpace(in.Of) |
| 194 | if of == "" || of == k.ID { |
| 195 | return ErrInvalid |
| 196 | } |
| 197 | target, err := t.loadTask(of) |
| 198 | if err != nil { |
| 199 | return err |
| 200 | } |
| 201 | // An exploration and a change are never duplicates. |
| 202 | if target.ProjectID != k.ProjectID || wire.FinalStage(target.Stage) || target.CancelRequested || wire.NormalKind(target.Kind) != wire.NormalKind(k.Kind) { |
| 203 | return ErrInvalid |
| 204 | } |
| 205 | // Never into another person's task: a fold appends to the target. |
| 206 | if target.Creator != k.Creator { |
| 207 | return ErrForbidden |
| 208 | } |
| 209 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("duplicate_of", target.ID).Error; err != nil { |
| 210 | return err |
| 211 | } |
| 212 | if _, err := t.cancelTask(person, k.ID); err != nil { |
| 213 | return err |
| 214 | } |
| 215 | var n int64 |
| 216 | if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind <> ?", target.ID, entryFinding).Count(&n).Error; err != nil { |
| 217 | return err |
| 218 | } |
| 219 | if n < wire.MaxThread { |
| 220 | text := k.Title |
| 221 | if k.Brief != "" { |
| 222 | text += "\n\n" + k.Brief |
| 223 | } |
| 224 | text = clip(text, wire.MaxThreadText) |
| 225 | e := entryRecord{ID: newID("e_"), TaskID: target.ID, IdempotencyKey: "duplicate:" + k.ID, Kind: entryReport, Author: person, Text: text, CreatedAt: t.now()} |
| 226 | if err := t.db.Create(&e).Error; err != nil { |
| 227 | return err |
| 228 | } |
| 229 | if err := t.saveTask(&target); err != nil { |
| 230 | return err |
| 231 | } |
| 232 | } |
| 233 | if k, err = t.loadTask(k.ID); err != nil { |
| 234 | return err |
| 235 | } |
| 236 | out, err = t.taskView(k) |
| 237 | return err |
| 238 | }) |
| 239 | return out, err |
| 240 | } |
| 241 | |
| 242 | func clip(s string, n int) string { |
| 243 | if len(s) <= n { |
| 244 | return s |
| 245 | } |
| 246 | s = s[:n] |
| 247 | for !utf8.ValidString(s) { |
| 248 | s = s[:len(s)-1] |
| 249 | } |
| 250 | return s |
| 251 | } |
| 252 | |
| 253 | // stackNames are the catalog's hints as people name them. |
| 254 | var stackNames = map[string]string{"go": "Go", "swift": "Swift", "swiftui": "SwiftUI", "javascript": "JavaScript", "react": "React", "vue": "Vue", "svelte": "Svelte", "next": "Next.js", "vite": "Vite", "rust": "Rust", "python": "Python", "android": "Android"} |
| 255 | |
| 256 | // catalogEntry is what a runner's index knows of repo: the viewer's |
| 257 | // primary runner first, else any active member's that lists it. |
| 258 | func (t *txn) catalogEntry(repo string) (wire.RepoInfo, bool, error) { |
| 259 | if t.catalogs == nil { |
| 260 | t.catalogs = map[string]wire.RepoInfo{} |
| 261 | members, err := t.members() |
| 262 | if err != nil { |
| 263 | return wire.RepoInfo{}, false, err |
| 264 | } |
| 265 | if t.viewer != "" { |
| 266 | members = append([]string{t.viewer}, members...) |
| 267 | } |
| 268 | for _, m := range members { |
| 269 | h, err := t.hello(m) |
| 270 | if err != nil { |
| 271 | return wire.RepoInfo{}, false, err |
| 272 | } |
| 273 | for _, e := range h.Catalog { |
| 274 | if _, ok := t.catalogs[e.Repo]; !ok { |
| 275 | t.catalogs[e.Repo] = e |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | e, ok := t.catalogs[repo] |
| 281 | return e, ok, nil |
| 282 | } |
| 283 | |
| 284 | // projectFacts adds what the index knows of the project's repositories |
| 285 | // and who is involved in it. |
| 286 | func (t *txn) projectFacts(v *wire.Project, p projectRecord) error { |
| 287 | v.Stack, v.People = []string{}, []wire.PersonRef{} |
| 288 | for i := range v.Attachments { |
| 289 | a := &v.Attachments[i] |
| 290 | if a.Kind != wire.AttachmentRepo { |
| 291 | continue |
| 292 | } |
| 293 | e, ok, err := t.catalogEntry(a.Ref) |
| 294 | if err != nil { |
| 295 | return err |
| 296 | } |
| 297 | if !ok { |
| 298 | continue |
| 299 | } |
| 300 | a.DefaultBranch, a.HeadSHA, a.HeadSubject = e.DefaultBranch, e.HeadSHA, e.HeadSubject |
| 301 | if !e.UpdatedAt.IsZero() { |
| 302 | at := e.UpdatedAt |
| 303 | a.HeadAt = &at |
| 304 | } |
| 305 | } |
| 306 | if e, ok, err := t.catalogEntry(p.Repo); err != nil { |
| 307 | return err |
| 308 | } else if ok { |
| 309 | v.Description = e.Summary |
| 310 | for _, h := range e.Hints { |
| 311 | if n := stackNames[h]; n != "" && !slices.Contains(v.Stack, n) { |
| 312 | v.Stack = append(v.Stack, n) |
| 313 | } |
| 314 | } |
| 315 | c := wire.ProjectChecks{Here: e.Gate != "" && e.ChecksReason == "", Gate: e.Gate, Reason: e.ChecksReason} |
| 316 | if c.Reason == "" && e.Gate == "" { |
| 317 | c.Reason = wire.ChecksNone |
| 318 | } |
| 319 | v.Checks = &c |
| 320 | } |
| 321 | var creators []string |
| 322 | if err := t.db.Raw("SELECT creator FROM chat_tasks WHERE project_id = ? GROUP BY creator ORDER BY MIN(created_at), creator", p.ID).Scan(&creators).Error; err != nil { |
| 323 | return err |
| 324 | } |
| 325 | for _, a := range append([]string{p.AddedBy}, creators...) { |
| 326 | if a != "" && !slices.ContainsFunc(v.People, func(r wire.PersonRef) bool { return r.Address == a }) { |
| 327 | v.People = append(v.People, personRef(a)) |
| 328 | } |
| 329 | } |
| 330 | return nil |
| 331 | } |
| 332 | |
| 333 | // OpenMergeCards are the person's open merge cards by task: the merge |
| 334 | // decisions the Needs you page and the task page answer in one tap. |
| 335 | func (s *Store) OpenMergeCards(ctx context.Context, person string) (out map[string]wire.Card, err error) { |
| 336 | out = map[string]wire.Card{} |
| 337 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 338 | var rows []cardRecord |
| 339 | if err := tx.Where("person = ? AND kind IN ? AND state = ?", person, []string{wire.CardMerge, wire.CardDirection, wire.CardHeld}, wire.CardOpen).Order("created_at, id").Find(&rows).Error; err != nil { |
| 340 | return err |
| 341 | } |
| 342 | t := &txn{s: s, db: tx} |
| 343 | for _, c := range rows { |
| 344 | v, err := t.cardView(c) |
| 345 | if err != nil { |
| 346 | return err |
| 347 | } |
| 348 | out[c.TaskID] = v |
| 349 | } |
| 350 | return nil |
| 351 | }) |
| 352 | return out, err |
| 353 | } |
| 354 | |