| 1 | package slides |
| 2 | |
| 3 | // assist.go is the editor's assistant: POST /d/{sqid}/assist, mounted |
| 4 | // only with SLIDES_AI=on (config_ai.go). |
| 5 | // |
| 6 | // **The model proposes, the editor applies.** This handler never writes |
| 7 | // a document. It asks the model for operations, rebuilds them |
| 8 | // (assist_ops.go), applies them to a SCRATCH copy of the deck through |
| 9 | // the core — the same two checks every write gets, Handle.Check and |
| 10 | // deck.Parse — and answers the batch to the browser, which applies it |
| 11 | // through the editor's own commit(): font-gated, one undo step, saved |
| 12 | // through the queue as the person's own change, live to everybody else |
| 13 | // in the deck. So a proposal is never a second write path (AGENTS.md: |
| 14 | // applyOps and appendUpdate are the only two), the person sees it land |
| 15 | // before anyone could object, and Ctrl+Z takes it back. |
| 16 | // |
| 17 | // One repair round: a batch the checks refuse goes back to the model |
| 18 | // once with the reason, because a model's usual mistake is one wrong id |
| 19 | // and the second answer is usually right. Then it is refused in plain |
| 20 | // words. |
| 21 | // |
| 22 | // Nothing about a deck is logged — not the request, not the answer, |
| 23 | // not a refusal's message (it quotes ids the model chose). A line per |
| 24 | // request carries the deck, the model, the outcome, the op count and |
| 25 | // the time. |
| 26 | |
| 27 | import ( |
| 28 | "context" |
| 29 | "encoding/json" |
| 30 | "errors" |
| 31 | "mime" |
| 32 | "net/http" |
| 33 | "strings" |
| 34 | "sync" |
| 35 | "time" |
| 36 | "unicode/utf8" |
| 37 | |
| 38 | "amadan.net/oficina/slides/internal/slides/assist" |
| 39 | "amadan.net/oficina/slides/internal/slides/core" |
| 40 | "amadan.net/oficina/slides/internal/slides/deck" |
| 41 | ) |
| 42 | |
| 43 | const ( |
| 44 | // maxAssistPrompt is the longest request a person may type, in |
| 45 | // runes; the textarea says the same with maxlength. |
| 46 | maxAssistPrompt = 2000 |
| 47 | // maxAssistBody bounds the JSON body. |
| 48 | maxAssistBody = 16 << 10 |
| 49 | // assistWindow and assistPerWindow are the per-person rate: twenty |
| 50 | // requests in ten minutes is a person working fast, and a bound on |
| 51 | // what a stolen session can spend. |
| 52 | assistWindow = 10 * time.Minute |
| 53 | assistPerWindow = 20 |
| 54 | // assistAttempts is the first answer and one repair. |
| 55 | assistAttempts = 2 |
| 56 | ) |
| 57 | |
| 58 | // The answers' error words. Fixed English identifiers the bundle maps |
| 59 | // to catalog strings (fixtures/assist.mjs), never shown as they are. |
| 60 | const ( |
| 61 | assistErrInvalid = "invalid" |
| 62 | assistErrPrompt = "prompt" |
| 63 | assistErrBusy = "busy" |
| 64 | assistErrRate = "rate" |
| 65 | assistErrGone = "gone" |
| 66 | assistErrTooLarge = "too_large" |
| 67 | assistErrUnavailable = "unavailable" |
| 68 | assistErrTimeout = "timeout" |
| 69 | assistErrRefused = "refused" |
| 70 | assistErrInternal = "internal" |
| 71 | ) |
| 72 | |
| 73 | var errAssistTooLarge = errors.New("slides: the deck is too large to send") |
| 74 | |
| 75 | // assistant is the app's half of the feature: the client, the models |
| 76 | // on offer, and the limiter. |
| 77 | type assistant struct { |
| 78 | client interface { |
| 79 | Complete(ctx context.Context, model string, messages []assist.Message) (string, error) |
| 80 | } |
| 81 | models []string |
| 82 | |
| 83 | mu sync.Mutex |
| 84 | inFlight map[int64]bool |
| 85 | recent map[int64][]time.Time |
| 86 | now func() time.Time |
| 87 | } |
| 88 | |
| 89 | func newAssistant(client *assist.Client, models []string) *assistant { |
| 90 | return &assistant{client: client, models: models, inFlight: map[int64]bool{}, recent: map[int64][]time.Time{}, now: time.Now} |
| 91 | } |
| 92 | |
| 93 | // admit lets a person's request start, or says why not: one at a time |
| 94 | // (a second press while the first is out is a mistake, and two batches |
| 95 | // against the same deck would each be proposed against a deck the other |
| 96 | // is about to change), and assistPerWindow in assistWindow. |
| 97 | func (s *assistant) admit(user int64) (release func(), refusal string) { |
| 98 | s.mu.Lock() |
| 99 | defer s.mu.Unlock() |
| 100 | if s.inFlight[user] { |
| 101 | return nil, assistErrBusy |
| 102 | } |
| 103 | now := s.now() |
| 104 | kept := s.recent[user][:0] |
| 105 | for _, t := range s.recent[user] { |
| 106 | if now.Sub(t) < assistWindow { |
| 107 | kept = append(kept, t) |
| 108 | } |
| 109 | } |
| 110 | if len(kept) >= assistPerWindow { |
| 111 | s.recent[user] = kept |
| 112 | return nil, assistErrRate |
| 113 | } |
| 114 | s.recent[user] = append(kept, now) |
| 115 | s.inFlight[user] = true |
| 116 | return func() { |
| 117 | s.mu.Lock() |
| 118 | delete(s.inFlight, user) |
| 119 | s.mu.Unlock() |
| 120 | }, "" |
| 121 | } |
| 122 | |
| 123 | // offers reports whether model is one of the configured ids. |
| 124 | func (s *assistant) offers(model string) bool { |
| 125 | for _, m := range s.models { |
| 126 | if m == model { |
| 127 | return true |
| 128 | } |
| 129 | } |
| 130 | return false |
| 131 | } |
| 132 | |
| 133 | // assistRequest is the body the editor posts. |
| 134 | type assistRequest struct { |
| 135 | Prompt string `json:"prompt"` |
| 136 | Scope string `json:"scope"` |
| 137 | Slide string `json:"slide"` |
| 138 | Model string `json:"model"` |
| 139 | } |
| 140 | |
| 141 | // assistAnswer is a proposal that passed every check. |
| 142 | type assistAnswer struct { |
| 143 | Ops []map[string]json.RawMessage `json:"ops"` |
| 144 | Summary string `json:"summary"` |
| 145 | Focus string `json:"focus,omitempty"` |
| 146 | } |
| 147 | |
| 148 | func assistFail(w http.ResponseWriter, status int, word string) { |
| 149 | w.Header().Set("Cache-Control", "no-store") |
| 150 | apiFail(w, status, word) |
| 151 | } |
| 152 | |
| 153 | // assistDeck serves POST /d/{sqid}/assist. |
| 154 | func (a *app) assistDeck(w http.ResponseWriter, r *http.Request) { |
| 155 | if a.assist == nil { |
| 156 | a.routeNotFound(w, r) |
| 157 | return |
| 158 | } |
| 159 | u, ok := a.viewer(w, r) |
| 160 | if !ok { |
| 161 | return |
| 162 | } |
| 163 | d, ok := a.deckFor(w, r, u) |
| 164 | if !ok { |
| 165 | return |
| 166 | } |
| 167 | if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" { |
| 168 | assistFail(w, http.StatusUnsupportedMediaType, assistErrInvalid) |
| 169 | return |
| 170 | } |
| 171 | var in assistRequest |
| 172 | dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxAssistBody)) |
| 173 | dec.DisallowUnknownFields() |
| 174 | if err := dec.Decode(&in); err != nil { |
| 175 | assistFail(w, http.StatusBadRequest, assistErrInvalid) |
| 176 | return |
| 177 | } |
| 178 | in.Prompt = strings.TrimSpace(in.Prompt) |
| 179 | if in.Prompt == "" || utf8.RuneCountInString(in.Prompt) > maxAssistPrompt { |
| 180 | assistFail(w, http.StatusUnprocessableEntity, assistErrPrompt) |
| 181 | return |
| 182 | } |
| 183 | var scope assistScope |
| 184 | switch in.Scope { |
| 185 | case "deck": |
| 186 | case "slide": |
| 187 | if in.Slide == "" { |
| 188 | assistFail(w, http.StatusUnprocessableEntity, assistErrInvalid) |
| 189 | return |
| 190 | } |
| 191 | scope.slide = in.Slide |
| 192 | default: |
| 193 | assistFail(w, http.StatusUnprocessableEntity, assistErrInvalid) |
| 194 | return |
| 195 | } |
| 196 | model := in.Model |
| 197 | if model == "" { |
| 198 | model = a.assist.models[0] |
| 199 | } |
| 200 | if !a.assist.offers(model) { |
| 201 | assistFail(w, http.StatusUnprocessableEntity, assistErrInvalid) |
| 202 | return |
| 203 | } |
| 204 | |
| 205 | release, refusal := a.assist.admit(u.ID) |
| 206 | if refusal != "" { |
| 207 | assistFail(w, http.StatusTooManyRequests, refusal) |
| 208 | return |
| 209 | } |
| 210 | defer release() |
| 211 | |
| 212 | // Standing, before anything is spent: the write this proposal |
| 213 | // becomes is the browser's own POST, which the guard checks again |
| 214 | // in its transaction, but a lapsed member should not be sending a |
| 215 | // team's deck to a model in the meantime. |
| 216 | if err := a.deckGuard(r.Context(), u, d).run(func() error { return nil }); err != nil { |
| 217 | if guardRefusedJSON(w, err) { |
| 218 | return |
| 219 | } |
| 220 | a.logger.Error("slides: assistant standing", "deck", d.Sqid, "err", err) |
| 221 | assistFail(w, http.StatusInternalServerError, assistErrInternal) |
| 222 | return |
| 223 | } |
| 224 | |
| 225 | started := time.Now() |
| 226 | answer, outcome, attempts, err := a.propose(r.Context(), d, scope, model, in.Prompt) |
| 227 | ms := time.Since(started).Milliseconds() |
| 228 | logLine := []any{"deck", d.Sqid, "model", model, "scope", in.Scope, "outcome", outcome, "attempts", attempts, "ms", ms} |
| 229 | if err != nil { |
| 230 | // err is one of this file's fixed errors or the provider's, |
| 231 | // which carry no content (assist package comment). |
| 232 | a.logger.Info("slides: assistant", append(logLine, "err", err)...) |
| 233 | } else { |
| 234 | a.logger.Info("slides: assistant", append(logLine, "ops", len(answer.Ops))...) |
| 235 | } |
| 236 | switch outcome { |
| 237 | case "ok": |
| 238 | w.Header().Set("Cache-Control", "no-store") |
| 239 | a.writeJSON(w, http.StatusOK, answer) |
| 240 | case assistErrGone: |
| 241 | assistFail(w, http.StatusConflict, outcome) |
| 242 | case assistErrTooLarge: |
| 243 | assistFail(w, http.StatusRequestEntityTooLarge, outcome) |
| 244 | case assistErrUnavailable: |
| 245 | assistFail(w, http.StatusBadGateway, outcome) |
| 246 | case assistErrTimeout: |
| 247 | assistFail(w, http.StatusGatewayTimeout, outcome) |
| 248 | case assistErrRefused: |
| 249 | assistFail(w, http.StatusUnprocessableEntity, outcome) |
| 250 | default: |
| 251 | assistFail(w, http.StatusInternalServerError, assistErrInternal) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // propose is the conversation: the deck read, the model asked, its |
| 256 | // answer rebuilt and checked, and once more with the reason if that |
| 257 | // failed. It answers the proposal and an outcome word. |
| 258 | func (a *app) propose(ctx context.Context, d Deck, scope assistScope, model, prompt string) (assistAnswer, string, int, error) { |
| 259 | h, view, err := a.openDeck(ctx, d) |
| 260 | if err != nil { |
| 261 | return assistAnswer{}, assistErrInternal, 0, err |
| 262 | } |
| 263 | state, err := h.State(ctx) |
| 264 | h.Close(ctx) |
| 265 | if err != nil { |
| 266 | return assistAnswer{}, assistErrInternal, 0, err |
| 267 | } |
| 268 | if scope.slide != "" && !hasSlide(view, scope.slide) { |
| 269 | return assistAnswer{}, assistErrGone, 0, nil |
| 270 | } |
| 271 | deckJSON, err := assistContext(view, scope) |
| 272 | if errors.Is(err, errAssistTooLarge) { |
| 273 | return assistAnswer{}, assistErrTooLarge, 0, nil |
| 274 | } |
| 275 | if err != nil { |
| 276 | return assistAnswer{}, assistErrInternal, 0, err |
| 277 | } |
| 278 | |
| 279 | // The model call outlives nothing: it ends with the request, and |
| 280 | // with the process (a.draining, drain.go) rather than holding a |
| 281 | // shutdown for up to assist.Deadline. |
| 282 | ctx, cancel := context.WithCancel(ctx) |
| 283 | defer cancel() |
| 284 | go func() { |
| 285 | select { |
| 286 | case <-a.draining.done(): |
| 287 | cancel() |
| 288 | case <-ctx.Done(): |
| 289 | } |
| 290 | }() |
| 291 | |
| 292 | messages := []assist.Message{ |
| 293 | {Role: "system", Content: assistInstructions}, |
| 294 | {Role: "user", Content: assistUserMessage(scope, prompt, deckJSON)}, |
| 295 | } |
| 296 | var lastErr error |
| 297 | for attempt := 1; attempt <= assistAttempts; attempt++ { |
| 298 | content, err := a.assist.client.Complete(ctx, model, messages) |
| 299 | if err != nil { |
| 300 | if errors.Is(err, context.DeadlineExceeded) { |
| 301 | return assistAnswer{}, assistErrTimeout, attempt, err |
| 302 | } |
| 303 | return assistAnswer{}, assistErrUnavailable, attempt, err |
| 304 | } |
| 305 | answer, err := a.checkProposal(ctx, d, state, view, scope, content) |
| 306 | if err == nil { |
| 307 | return answer, "ok", attempt, nil |
| 308 | } |
| 309 | var refusal *assistRefusal |
| 310 | if !errors.As(err, &refusal) { |
| 311 | return assistAnswer{}, assistErrInternal, attempt, err |
| 312 | } |
| 313 | lastErr = errors.New("slides: the model's answer was refused") |
| 314 | messages = append(messages, |
| 315 | assist.Message{Role: "assistant", Content: content}, |
| 316 | assist.Message{Role: "user", Content: assistRepairMessage(refusal)}) |
| 317 | } |
| 318 | return assistAnswer{}, assistErrRefused, assistAttempts, lastErr |
| 319 | } |
| 320 | |
| 321 | // checkProposal is one answer through every check: parsed, rebuilt |
| 322 | // (assist_ops.go), then applied to a scratch document made from state — |
| 323 | // the deck as it was read — and read back through the core's shape |
| 324 | // check and deck.Parse, the two refusals every write passes. The scratch |
| 325 | // handle is discarded; nothing is written. Every refusal is an |
| 326 | // *assistRefusal whose message is for the model. |
| 327 | func (a *app) checkProposal(ctx context.Context, d Deck, state []byte, view *deck.Deck, scope assistScope, content string) (assistAnswer, error) { |
| 328 | reply, err := assist.ParseReply(content) |
| 329 | if err != nil { |
| 330 | return assistAnswer{}, refuse(`the answer was not one JSON object with "summary" and "ops"`) |
| 331 | } |
| 332 | norm, err := normalizeAssistOps(view, reply.Ops, scope, newID) |
| 333 | if err != nil { |
| 334 | return assistAnswer{}, err |
| 335 | } |
| 336 | answer := assistAnswer{Ops: norm.ops, Summary: reply.Summary, Focus: norm.focus} |
| 337 | if len(norm.ops) == 0 { |
| 338 | answer.Ops = []map[string]json.RawMessage{} |
| 339 | return answer, nil |
| 340 | } |
| 341 | encoded, err := json.Marshal(norm.ops) |
| 342 | if err != nil { |
| 343 | return assistAnswer{}, err |
| 344 | } |
| 345 | scratch, err := a.core.NewDoc(ctx, d.Sqid, serverClientID) |
| 346 | if err != nil { |
| 347 | return assistAnswer{}, err |
| 348 | } |
| 349 | defer scratch.Close(context.WithoutCancel(ctx)) |
| 350 | if err := scratch.Apply(ctx, state); err != nil { |
| 351 | return assistAnswer{}, err |
| 352 | } |
| 353 | if _, err := scratch.Ops(ctx, encoded); err != nil { |
| 354 | if rejected := (*core.RejectedError)(nil); errors.As(err, &rejected) { |
| 355 | return assistAnswer{}, refuse("%s", rejected.Error()) |
| 356 | } |
| 357 | return assistAnswer{}, err |
| 358 | } |
| 359 | if err := scratch.Check(ctx); err != nil { |
| 360 | if rejected := (*core.RejectedError)(nil); errors.As(err, &rejected) { |
| 361 | return assistAnswer{}, refuse("%s", rejected.Error()) |
| 362 | } |
| 363 | return assistAnswer{}, err |
| 364 | } |
| 365 | raw, err := scratch.JSON(ctx) |
| 366 | if err != nil { |
| 367 | return assistAnswer{}, err |
| 368 | } |
| 369 | after, err := deck.Parse(raw) |
| 370 | if err != nil { |
| 371 | return assistAnswer{}, refuse("those operations leave a deck that cannot be read") |
| 372 | } |
| 373 | if err := checkAssistResult(view, after); err != nil { |
| 374 | return assistAnswer{}, err |
| 375 | } |
| 376 | return answer, nil |
| 377 | } |
| 378 | |
| 379 | func hasSlide(view *deck.Deck, id string) bool { |
| 380 | for _, s := range view.Slides { |
| 381 | if s.ID == id { |
| 382 | return true |
| 383 | } |
| 384 | } |
| 385 | return false |
| 386 | } |
| 387 | |