| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | |
| 8 | "gorm.io/gorm" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | // Try again: the person's latest turn in the conversation failed, and |
| 14 | // they ask for it to be answered again. A new turn takes over the failed |
| 15 | // turn's exchange: its messages, the cards it raised and their threads, |
| 16 | // the tasks it noted, its tool calls, its hand-off and the steps it asked |
| 17 | // for, and what it spent: a repository creation it used (CreateRepo). |
| 18 | // Every check that reads a turn's messages, cards or calls by its id |
| 19 | // (placement, consent, access, quote, dispatch) then reads them on the |
| 20 | // new turn as they were, and an instance that knows nothing of retries |
| 21 | // (a rollback) dispatches it as any queued turn. It is the failed turn's |
| 22 | // next attempt: what that turn already did is answered from the ledger, |
| 23 | // not done twice (earlierOp). Every member hears of a moved task, step or |
| 24 | // card at a new revision. The failed turn keeps its reason and usage, and |
| 25 | // has no messages left: the feed shows each once, and no note stays |
| 26 | // under it. RetryOf names it. A specialist it proposed keeps naming it: |
| 27 | // nothing reads that, and a specialist's grant holds at one revision. |
| 28 | |
| 29 | // notRetried are the reasons another try cannot mend: a file to attach |
| 30 | // again, room on the runner, a runner to update. |
| 31 | var notRetried = map[string]bool{ |
| 32 | wire.ReasonAttachmentUnavailable: true, |
| 33 | wire.ReasonStorageFull: true, |
| 34 | reasonRunnerTooOld: true, |
| 35 | } |
| 36 | |
| 37 | // Retryable reports whether a failed turn with this reason may be tried |
| 38 | // again. |
| 39 | func Retryable(reason string) bool { return !notRetried[reason] } |
| 40 | |
| 41 | // retryMoves are the rows of a turn's exchange no client sees, by table |
| 42 | // and turn column: they go with it to its retry as they are. Messages, |
| 43 | // cards, threads, tasks and steps move with their events (moveExchange). |
| 44 | var retryMoves = [][2]string{{"chat_tool_calls", "turn_id"}, {"chat_handoff_turns", "turn_id"}} |
| 45 | |
| 46 | // Retry queues a new turn for the exchange of id, the person's latest |
| 47 | // turn in the conversation, which failed. Asked again (a double tap, a |
| 48 | // second device, at once), it is the same turn: one is queued. It is |
| 49 | // refused (ErrNotRetryable) for a turn that did not fail, failed for a |
| 50 | // reason another try cannot mend, or that a newer turn of theirs |
| 51 | // followed. Authority is a message's: the current person, in their own |
| 52 | // lane. |
| 53 | func (s *Store) Retry(ctx context.Context, person, id string) (out wire.Turn, err error) { |
| 54 | err = s.tx(ctx, func(t *txn) error { |
| 55 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | var f turnRecord |
| 59 | if err := t.db.Where("id = ? AND person = ? AND coalesce(lane, '') = ? AND coalesce(kind, '') = ''", id, person, wire.LaneCoordinator).First(&f).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 60 | return ErrNotFound |
| 61 | } else if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | var newer turnRecord |
| 65 | if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND coalesce(kind, '') = '' AND (created_at > ? OR created_at = ? AND id > ?)", person, f.Lane, f.CreatedAt, f.CreatedAt, f.ID).Order("created_at, id").Limit(1).Find(&newer).Error; err != nil { |
| 66 | return err |
| 67 | } |
| 68 | if newer.ID != "" { |
| 69 | // Tried again already: that turn, whatever became of it. |
| 70 | if newer.RetryOf == f.ID { |
| 71 | out, err = t.turnView(newer) |
| 72 | return err |
| 73 | } |
| 74 | return ErrNotRetryable |
| 75 | } |
| 76 | if f.State != wire.TurnFailed || !Retryable(f.Reason) { |
| 77 | return ErrNotRetryable |
| 78 | } |
| 79 | var messages []messageRecord |
| 80 | if err := t.db.Where("turn_id = ? AND person = ?", f.ID, person).Order("seq").Find(&messages).Error; err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if !slices.ContainsFunc(messages, func(m messageRecord) bool { return m.Role == wire.RolePerson }) { |
| 84 | return ErrNotRetryable |
| 85 | } |
| 86 | now := t.now() |
| 87 | r := turnRecord{ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: f.Attempt + 1, CreatedAt: now, UpdatedAt: now, Lane: f.Lane, RetryOf: f.ID, CreateRepo: f.CreateRepo} |
| 88 | if err := t.db.Create(&r).Error; err != nil { |
| 89 | return err |
| 90 | } |
| 91 | if err := t.moveExchange(f, r, messages); err != nil { |
| 92 | return err |
| 93 | } |
| 94 | // As a message does: the person's tap ends quiet hours, and a |
| 95 | // move-in or explore turn in flight gives way. |
| 96 | if err := t.hkRelease(person, t.hkNow()); err != nil { |
| 97 | return err |
| 98 | } |
| 99 | busy, err := t.inFlight(person, r.Lane) |
| 100 | if err != nil { |
| 101 | return err |
| 102 | } |
| 103 | held, err := t.laneHeld(r.Lane) |
| 104 | if err != nil { |
| 105 | return err |
| 106 | } |
| 107 | if held { |
| 108 | // A held job's turn waits for the person's Carry on now. |
| 109 | } else if busy == 0 { |
| 110 | err = t.dispatch(&r) |
| 111 | } else { |
| 112 | err = t.yieldTurns(person) |
| 113 | } |
| 114 | if err != nil { |
| 115 | return err |
| 116 | } |
| 117 | if err := t.saveTurn(&r); err != nil { |
| 118 | return err |
| 119 | } |
| 120 | out, err = t.turnView(r) |
| 121 | return err |
| 122 | }) |
| 123 | return out, err |
| 124 | } |
| 125 | |
| 126 | // moveExchange gives f's exchange to r (see Retry), telling clients of |
| 127 | // each message, card, task and step that moved, and of f, which has none |
| 128 | // left. |
| 129 | func (t *txn) moveExchange(f, r turnRecord, messages []messageRecord) error { |
| 130 | for _, m := range messages { |
| 131 | m.TurnID = r.ID |
| 132 | m.Revision++ |
| 133 | if err := t.db.Model(&messageRecord{}).Where("seq = ?", m.Seq).Select("turn_id", "revision").Updates(&m).Error; err != nil { |
| 134 | return err |
| 135 | } |
| 136 | if err := t.messageEvent(m); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | } |
| 140 | // A card it raised, or one whose thread holds its words. |
| 141 | var cards []cardRecord |
| 142 | if err := t.db.Where("person = ? AND (turn_id = ? OR id IN (SELECT card_id FROM chat_card_threads WHERE turn_id = ?))", f.Person, f.ID, f.ID).Find(&cards).Error; err != nil { |
| 143 | return err |
| 144 | } |
| 145 | if err := t.db.Exec("UPDATE chat_card_threads SET turn_id = ? WHERE turn_id = ?", r.ID, f.ID).Error; err != nil { |
| 146 | return err |
| 147 | } |
| 148 | for _, c := range cards { |
| 149 | if c.TurnID == f.ID { |
| 150 | c.TurnID = r.ID |
| 151 | } |
| 152 | c.Revision, c.UpdatedAt = c.Revision+1, t.now() |
| 153 | if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("turn_id", "revision", "updated_at").Updates(&c).Error; err != nil { |
| 154 | return err |
| 155 | } |
| 156 | if err := t.cardEventPush(c, false); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | } |
| 160 | var tasks []taskRecord |
| 161 | if err := t.db.Where("turn_id = ?", f.ID).Find(&tasks).Error; err != nil { |
| 162 | return err |
| 163 | } |
| 164 | for _, k := range tasks { |
| 165 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("turn_id", r.ID).Error; err != nil { |
| 166 | return err |
| 167 | } |
| 168 | k.TurnID = r.ID |
| 169 | if err := t.saveTask(&k); err != nil { |
| 170 | return err |
| 171 | } |
| 172 | } |
| 173 | var steps []stepRecord |
| 174 | if err := t.db.Where("request_turn = ?", f.ID).Find(&steps).Error; err != nil { |
| 175 | return err |
| 176 | } |
| 177 | for _, st := range steps { |
| 178 | st.RequestTurn = r.ID |
| 179 | if err := t.writeStep(&st); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | } |
| 183 | for _, move := range retryMoves { |
| 184 | if err := t.db.Exec("UPDATE "+move[0]+" SET "+move[1]+" = ? WHERE "+move[1]+" = ?", r.ID, f.ID).Error; err != nil { |
| 185 | return err |
| 186 | } |
| 187 | } |
| 188 | f.Revision++ |
| 189 | f.UpdatedAt = t.now() |
| 190 | if err := t.db.Model(&turnRecord{}).Where("id = ?", f.ID).Select("revision", "updated_at").Updates(&f).Error; err != nil { |
| 191 | return err |
| 192 | } |
| 193 | return t.turnEvent(f) |
| 194 | } |
| 195 | |
| 196 | // TurnAccount is the account one of the person's turns last ran on, as |
| 197 | // its usage rows record it: the connection and its label. ok is false |
| 198 | // when no row names one of their connections: the turn ended before an |
| 199 | // account was chosen, or the connection is gone. |
| 200 | func (s *Store) TurnAccount(ctx context.Context, person, turn string) (conn wire.Connection, label ConnLabel, ok bool, err error) { |
| 201 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 202 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 203 | return err |
| 204 | } |
| 205 | var u usageRecord |
| 206 | if err := tx.Where("person = ? AND turn_id = ? AND coalesce(connection, '') <> ''", person, turn).Order("attempt DESC, id DESC").Limit(1).Find(&u).Error; err != nil || u.ID == 0 { |
| 207 | return err |
| 208 | } |
| 209 | t := &txn{s: s, db: tx} |
| 210 | recs, err := t.connections(person) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | // A usage row names the runner's local id (as the Usage page reads |
| 215 | // it): the first connection with it. |
| 216 | for _, r := range recs { |
| 217 | if r.LocalID == u.Connection { |
| 218 | conn, label, ok = connectionView(r), labelsOf(recs, t.copyOf)[r.ID], true |
| 219 | return nil |
| 220 | } |
| 221 | } |
| 222 | return nil |
| 223 | }) |
| 224 | return conn, label, ok, err |
| 225 | } |
| 226 | |