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 "context"
5 "crypto/rand"
6 "errors"
7 "fmt"
8 "net/http"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/go-chi/chi/v5"
14
15 "amadan.net/oficina/equipo/internal/equipo/chat"
16 "amadan.net/oficina/equipo/internal/equipo/identity"
17 "amadan.net/oficina/equipo/internal/equipo/personapi"
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// chatView is the conversation page, rendered from the same snapshot a
22// person API v1 client reads; chat-stream.js then follows the event stream.
23type chatView struct {
24 // Draft is the composer's opening words: "Ask about this" on a task
25 // opens the conversation with the task referenced (?about=tk...).
26 Draft string
27 // Messages are today's; Days the earlier days, oldest first; Open what
28 // still needs the person from them, at the top of today.
29 Messages []chatLine
30 Days []chatDay
31 Open []chatLine
32 Waiting []wire.Turn
33 Ended *chatEnded
34 // NoConnection is the card for a turn held because nothing the person
35 // connected can answer; the message waits and goes on its own.
36 NoConnection *noConnectionCard
37 Offline bool
38 Cursor int64
39 // Job is the job thread the page shows instead of the person's own
40 // conversation (/jobs/{id}); FromBase links the conversation to the
41 // person's job threads, which Jobs lists (/jobs).
42 Job *jobHead
43 FromBase bool
44 Jobs []jobLine
45}
46
47// jobHead names the job thread a page shows.
48type jobHead struct{ ID, Label string }
49
50// jobLine is one job thread on /jobs: its label, its status and when it
51// last moved, in the person's zone.
52type jobLine struct {
53 ID, Label, Status, When string
54 At time.Time
55}
56
57type noConnectionCard struct{ TurnID, Line string }
58
59type chatLine struct {
60 // Switched is the quiet line under a reply that moved connection.
61 Switched string
62 // Waiting is the quiet status under a person's message whose turn
63 // waits for a connection (no thinking line, no timer).
64 Waiting string
65 // Queued is the quiet note under the latest message of a turn queued
66 // behind the running one (no thinking line, no timer).
67 Queued string
68 ID, Text, TurnID string
69 // Files are what the person attached to their message.
70 Files []wire.MessageAttachment
71 Own bool
72 CreatedAt time.Time
73 // Receipts (what the coordinator did during the turn) come before its
74 // reply; Cards (what needs the person) after the message.
75 Receipts, Cards []chatCard
76 // CardOnly is a card no turn produced (the merge card): it stands in
77 // the feed at its own time, with no message.
78 CardOnly bool
79}
80
81// chatCard is one card under the message that ends its turn. Line is the
82// card's sentence; the forms post to the page routes below.
83type chatCard struct {
84 ReportAction *reportAction
85 ProjectMono monoLine
86 ThreadActivity string
87 ThreadError string
88 ResearchReports []*researchView
89 HoldReason string
90 BylineAt time.Time
91 SlimReport bool
92 // Compact: the task's decision card is in the stream, so the report is
93 // one status line and the card carries the facts' action.
94 Compact bool
95 ExplorationSummary string
96 ReplyKey string
97 wire.Card
98 Line, Change, Agent, Namespace, Note string
99 AccessTarget string
100 Presentation chat.CardPresentation
101 Author, AuthorIcon, Verb string
102 // GrantHow introduces an access card's grant command.
103 GrantHow string
104 Open, Remove, Receipt bool
105 Choices []string
106 // ActLabel and DismissLabel are an advice card's two buttons.
107 ActLabel, DismissLabel string
108 // Job is the job thread whose page shows the card: its answer
109 // returns there.
110 Job string
111 // Task is a task card's task.
112 Task *taskLine
113 // PlaceChoices are a place card's candidates in the card's order, each
114 // labelled from code-derived console and account words.
115 PlaceChoices []placeChoice
116 // Gallery is an open direction card's kept Design captures, by
117 // option; with more than one, BuildNote: Build this takes a note.
118 Gallery *designGallery
119 BuildNote bool
120}
121
122// placeChoice is one button of a place card.
123type placeChoice struct{ ID, Label string }
124
125// notebookLine is one notebook entry on the Notebook page: the note, its
126// source and day, and whether it quotes the person.
127type notebookLine struct {
128 ID string
129 Correction bool
130 Who, Text, Day string
131 At time.Time
132 Said bool
133}
134
135func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCard {
136 v := chatCard{Card: c, Choices: choices, BylineAt: c.CreatedAt}
137 if c.PreviewURL != "" {
138 v.PreviewURL = "/tasks/" + c.TaskID + "/preview"
139 }
140 switch c.Kind {
141 case wire.CardProject:
142 v.Line = fmt.Sprintf(copyText("chat.card."+c.State), c.Name)
143 if c.State == wire.CardChanged {
144 v.Line = fmt.Sprintf(copyText("chat.card.changed"), c.Choice)
145 }
146 v.Open = c.State == wire.CardAdded || c.State == wire.CardWorking || c.State == wire.CardCreated
147 v.Remove = v.Open && c.State != wire.CardWorking
148 v.Change = copyText("chat.card.change")
149 if c.State == wire.CardCreated {
150 v.Change = copyText("chat.card.move")
151 }
152 case wire.CardQuestion:
153 v.Line, v.Open = c.Question, c.State == wire.CardOpen
154 case wire.CardHome:
155 v.Line = copyText("chat.card.home_cleared")
156 if c.Name != "" {
157 v.Line = fmt.Sprintf(copyText("chat.card.home"), c.Name)
158 }
159 if c.State == wire.CardHomeAsk {
160 v.Line = fmt.Sprintf(copyText("chat.card.home_ask_clear"), c.Question)
161 if c.Name != "" {
162 v.Line = fmt.Sprintf(copyText("chat.card.home_ask"), c.Name)
163 }
164 }
165 v.Open = c.State == wire.CardHomeSet || c.State == wire.CardHomeAsk
166 case wire.CardAccess:
167 if c.Access != nil {
168 v.Open = c.State == wire.CardOpen
169 v.Line = copyText("access." + c.Access.State)
170 if c.Access.State == "not_owned" {
171 ns, _, _ := strings.Cut(c.Access.Target, "/")
172 v.Line = fmt.Sprintf(v.Line, ns)
173 }
174 v.AccessTarget = c.Access.Target
175 if !strings.Contains(c.Access.Target, "/") {
176 v.AccessTarget = fmt.Sprintf(copyText("access.namespace"), c.Access.Target)
177 }
178 if c.Access.State == "approved" && c.State == wire.CardResolved {
179 v.Note = fmt.Sprintf(copyText("access.granted_note"), v.AccessTarget)
180 }
181 break
182 }
183 reach := strings.Join(c.Options, ", ")
184 // The command names a namespace only when the person gave one
185 // with a repository; otherwise it keeps the placeholder and says
186 // what goes there.
187 v.Agent, v.Namespace, v.GrantHow = c.Choice, "<namespace>", copyText("chat.card.grant_how_unknown")
188 if ns := chat.GrantNamespace(c.Name); ns != "" {
189 v.Namespace, v.GrantHow = ns, copyText("chat.card.grant_how")
190 }
191 v.Line = fmt.Sprintf(copyText("chat.card.access"), c.Question, reach)
192 if reach == "" {
193 // A new team whose agent reaches nothing yet (review R1).
194 v.Line = fmt.Sprintf(copyText("chat.card.access_first"), c.Question)
195 }
196 v.Open = c.State == wire.CardOpen
197 if c.State == wire.CardResolved {
198 v.Line = fmt.Sprintf(copyText("chat.card.access_resolved"), c.Question)
199 // Resolved by Equipo, not by a grant: the work found a
200 // repository the agent already reaches, or the card never
201 // named one (#48).
202 if c.Choice == wire.ChoiceNotNeeded {
203 v.Line = copyText("access.already")
204 }
205 }
206 case wire.CardMerge:
207 v.Line, v.Open = c.Question, c.State == wire.CardOpen
208 if t, ok := tasks[c.TaskID]; ok && t.Kind == wire.KindExplore {
209 // From before the task became an exploration: it never merges.
210 v.Open, v.Note = false, copyText("work.tl.merge_dropped")
211 break
212 }
213 switch {
214 case c.State == wire.CardAnswered:
215 v.Note = copyText("chat.card.merge_chose_" + c.Choice)
216 case c.State == wire.CardResolved:
217 v.Note = copyText("chat.card.merge_resolved")
218 }
219 case wire.CardPublish:
220 // Publishing a merged website: Publish or Not now, then the site.
221 v.Line, v.Open = c.Question, c.State == wire.CardOpen
222 switch c.State {
223 case wire.CardAnswered:
224 v.Note = copyText("chat.card.publish_chose_" + c.Choice)
225 case wire.CardResolved:
226 v.Note = copyText("chat.card.publish_stale")
227 }
228 case wire.CardPlace:
229 // Where a project's site goes: one button per candidate, Not now.
230 v.Line, v.Open = c.Question, c.State == wire.CardOpen
231 if c.Place != nil {
232 for _, cand := range c.Place.Candidates {
233 v.PlaceChoices = append(v.PlaceChoices, placeChoice{ID: cand.ID, Label: fmt.Sprintf(copyText("chat.card.place_option"), cand.ConsoleLabel, cand.Account)})
234 }
235 }
236 switch c.State {
237 case wire.CardAnswered:
238 v.Note = copyText("chat.card.place_chose_not_now")
239 if c.Choice != wire.ChoiceNotNow {
240 v.Note = copyText("chat.card.place_chose")
241 }
242 case wire.CardResolved:
243 // Superseded by a fresh card where the person asked.
244 v.Note = copyText("chat.card.merge_resolved")
245 }
246 case wire.CardMakerRemoved:
247 // A task's maker was removed: hand the task to Engineering.
248 v.Line, v.Open = c.Question, c.State == wire.CardOpen
249 switch c.State {
250 case wire.CardAnswered:
251 v.Note = copyText("chat.card.maker_removed_chose_" + c.Choice)
252 case wire.CardResolved:
253 v.Note = copyText("chat.card.merge_resolved")
254 }
255 case wire.CardDirection:
256 v.Line, v.Open = c.Question, c.State == wire.CardOpen
257 if t, ok := tasks[c.TaskID]; ok && v.Open && t.Direction != nil {
258 v.Gallery, v.BuildNote = galleryOf(c.TaskID, t.Direction.Options), t.Direction.NoteNeeded
259 }
260 switch {
261 case c.State == wire.CardAnswered:
262 v.Note = copyText("chat.card.direction_chose_" + c.Choice)
263 case c.State == wire.CardResolved:
264 v.Note = copyText("chat.card.merge_resolved")
265 }
266 case wire.CardSpecialist:
267 // Adding a specialist: what it can do and its brief, Add or Not now.
268 v.Line, v.Open = c.Question, c.State == wire.CardOpen
269 switch {
270 case c.Specialist != nil && c.Specialist.State == wire.SpecialistRevoked:
271 v.Note = copyText("chat.card.specialist_revoked")
272 case c.State == wire.CardAnswered:
273 v.Note = copyText("chat.card.specialist_chose_" + c.Choice)
274 }
275 case wire.CardInstanceInventory:
276 // The network the instance is on: its prefixes and the
277 // addresses it saw, as text, for an owner to Confirm.
278 v.Line, v.Open = c.Question, c.State == wire.CardOpen
279 case wire.CardResearchSources, wire.CardResearchInventory:
280 // Research: the pages it may read (Allow or Skip), or the
281 // addresses it reads from (Confirm); every URL and address as text.
282 v.Line, v.Open = c.Question, c.State == wire.CardOpen
283 switch c.State {
284 case wire.CardAnswered:
285 v.Note = decisionNote(c)
286 case wire.CardResolved:
287 v.Note = copyText("chat.card.research_withdrawn")
288 }
289 case wire.CardMergeShips, wire.CardMergePolicy, wire.CardMergeReceipt:
290 // Merge authority: the ships question, a proposed policy, and the
291 // receipt of Equipo's own merge (Undo when offered).
292 v.Line, v.Open = c.Question, c.State == wire.CardOpen && len(c.Options) > 0
293 switch {
294 case c.State == wire.CardAnswered && c.Kind == wire.CardMergeShips:
295 v.Note = copyText("chat.card.ships_chose_" + c.Choice)
296 case c.State == wire.CardAnswered && c.Kind == wire.CardMergePolicy:
297 v.Note = copyText("chat.card.policy_chose_" + c.Choice)
298 case c.State == wire.CardResolved:
299 v.Note = copyText("chat.card.merge_policy_stale")
300 }
301 case wire.CardCombined:
302 // Equipo combined two of the person's tasks: a quiet line, Undo.
303 v.Line, v.Open = c.Question, c.State == wire.CardOpen
304 if c.State == wire.CardAnswered {
305 v.Line = copyText("chat.card.combined_undone")
306 }
307 case wire.CardAdvice:
308 // Advice (connectors spec §9): one quiet card, its action and Not
309 // now; once answered, what was chosen; withdrawn, nothing.
310 v.Line, v.Open = c.Question, c.State == wire.CardOpen
311 if c.Advice != nil {
312 v.ActLabel, v.DismissLabel = c.Advice.Act, c.Advice.Dismiss
313 if c.State == wire.CardAnswered {
314 v.Note = c.Advice.Act
315 if c.Choice == wire.ChoiceDismiss {
316 v.Note = c.Advice.Dismiss
317 }
318 }
319 }
320 case wire.CardHousekeeping:
321 // The day's digest line: quiet, with the way to the Housekeeping view.
322 v.Line = c.Question
323 case wire.CardTask:
324 if t, ok := tasks[c.TaskID]; ok {
325 // A task card sits in its creator's own conversation.
326 pt, dropped := pageTask(t)
327 if wire.FinalStage(pt.Stage) {
328 pt.CopyHold, pt.CopyCanSkip = false, false
329 }
330 line := taskLineOf(pt, t.Creator)
331 line.MergeDropped = dropped
332 line.richOf(pt, t.Creator, nil, t.UpdatedAt)
333 line.Track = rosterTrack(pt)
334 v.BylineAt = t.UpdatedAt
335 v.SlimReport = t.NeedsYou == "" && (t.Stage == wire.StageReadyToMerge || t.Stage == wire.StageDone)
336 if t.Kind == wire.KindExplore {
337 for i := len(t.Steps) - 1; i >= 0; i-- {
338 if t.Steps[i].Specialist == wire.SpecialistEngineering {
339 v.ExplorationSummary = headline(t.Steps[i].Headline, t.Steps[i].Summary)
340 break
341 }
342 }
343 }
344 if t.CopyHold {
345 v.HoldReason = copyText("copy.round_budget")
346 }
347 if t.CopyCanSkip {
348 if s := lastStep(t); s != nil {
349 if s.Reason == "copy_budget" {
350 v.HoldReason = copyText("roster.copy_budget")
351 } else {
352 v.HoldReason = reasonLine(s.Reason, "work.reason.other")
353 }
354 }
355 }
356 v.Task, v.Line, v.Open = &line, t.Title, line.Retry || line.Cancel || line.Merge || line.Recover || line.CopyCanSkip || line.CopyHold
357 for _, step := range t.Steps {
358 if step.Specialist == wire.SpecialistResearch && step.Research != nil {
359 report := researchOf(t.ID, *step.Research)
360 report.StepID = step.ID
361 report.At = step.FinishedAt
362 v.ResearchReports = append(v.ResearchReports, report)
363 }
364 }
365 }
366 }
367 v.rosterAuthor(tasks)
368 return v
369}
370
371// sessionContext carries the browser session as the principal the chat
372// store re-checks inside each transaction.
373func sessionContext(r *http.Request) (context.Context, string, bool) {
374 id, ok := identity.From(r)
375 if !ok {
376 return r.Context(), "", false
377 }
378 p := personapi.PersonPrincipal{Address: normalizeAddress(id.Address), SessionEpoch: id.At.Unix()}
379 return personapi.WithVerifiedPrincipal(r.Context(), p), p.Address, true
380}
381
382func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
383 w.Header().Set("Cache-Control", "no-store")
384 ctx, address, ok := sessionContext(r)
385 if !ok {
386 a.failure(w, r, ErrForbidden)
387 return
388 }
389 snap, err := a.store.Chat().Snapshot(ctx, address)
390 if err != nil {
391 a.failure(w, r, chatError(err))
392 return
393 }
394 data, err := a.page(r, "conversation")
395 if err != nil {
396 a.failure(w, r, err)
397 return
398 }
399 view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor}
400 if id := r.URL.Query().Get("about"); taskIDPattern.MatchString(id) {
401 // A task the person cannot see, or none, leaves the composer empty.
402 if t, err := a.store.Chat().Task(ctx, address, id); err == nil {
403 // Named by its title, never its id (house rule: no ids in UI text).
404 view.Draft = fmt.Sprintf(copyText("work.ask_about.draft"), t.Title)
405 }
406 }
407 // A starter on the empty conversation, without script: the composer
408 // opens with its words (chat.html "starter").
409 if k := r.URL.Query().Get("start"); view.Draft == "" && (k == "bug" || k == "feature" || k == "project") {
410 view.Draft = copyText("conversation.start." + k + "_draft")
411 }
412 // Today, in the person's zone, is the conversation; each earlier day
413 // is a day box (chat_days.go), open when asked for (?day=) or when a
414 // task's "From your conversation" link names one of its messages.
415 chats := a.store.Chat()
416 loc := chats.Zone(address)
417 today := chat.DayStart(chats.Now(), loc)
418 expand := map[time.Time]bool{}
419 for _, key := range r.URL.Query()["day"] {
420 if d, ok := parseDay(key, loc); ok && d.Before(today) {
421 expand[d] = true
422 }
423 }
424 if id := r.URL.Query().Get("message"); id != "" {
425 if at, err := chats.MessageAt(ctx, address, id); err == nil && at.Before(today) {
426 expand[chat.DayStart(at, loc)] = true
427 }
428 }
429 win, err := chats.Window(ctx, address, today, time.Time{}, maxDayMessages)
430 if err != nil {
431 a.failure(w, r, chatError(err))
432 return
433 }
434 choices, err := chats.ProjectChoices(ctx, address)
435 if err != nil {
436 a.failure(w, r, chatError(err))
437 return
438 }
439 // The work Ask Base handed off has threads of its own: linked from
440 // here once there is one.
441 jobs, err := chats.Jobs(ctx, address)
442 if err != nil {
443 a.failure(w, r, chatError(err))
444 return
445 }
446 view.FromBase = len(jobs) > 0
447 tasks := map[string]wire.Task{}
448 for _, t := range snap.Tasks {
449 tasks[t.ID] = t
450 }
451 for _, t := range win.Tasks {
452 tasks[t.ID] = t
453 }
454 view.Days, view.Open, err = a.earlierDays(ctx, address, loc, today, expand, choices, tasks)
455 if err != nil {
456 a.failure(w, r, chatError(err))
457 return
458 }
459 view.Messages = feedLines(win.Messages, win.Cards, choices, tasks, loc)
460 // Nothing can answer: no turn shows the thinking line or a timer
461 // until an attempt starts on a connection. A turn waiting for one, and
462 // any queued behind it, get a quiet status under the person's message;
463 // one card stands after them for the conversation.
464 held := false
465 for _, t := range snap.Turns {
466 held = held || t.State == wire.TurnWaiting && t.Reason == wire.ReasonNoConnection
467 }
468 waitingTurns := map[string]bool{}
469 // The person's turns go one at a time: the oldest in flight has the
470 // thinking line, and one queued behind it a quiet note under its
471 // latest message instead of a line and timer of its own.
472 var ahead *wire.Turn
473 for i, t := range snap.Turns {
474 if !wire.Terminal(t.State) && (ahead == nil || t.State != wire.TurnQueued && ahead.State == wire.TurnQueued || t.State == ahead.State && (t.CreatedAt.Before(ahead.CreatedAt) || t.CreatedAt.Equal(ahead.CreatedAt) && t.ID < ahead.ID)) {
475 ahead = &snap.Turns[i]
476 }
477 }
478 queuedTurns := map[string]bool{}
479 var latest *wire.Turn
480 for i, t := range snap.Turns {
481 // The person's latest turn, whatever state it is in: one that ended
482 // unanswered has the note; one waiting or queued has none above it.
483 // Turns the coordinator takes on its own never end in a note.
484 if t.Kind == wire.TurnPerson && (latest == nil || t.CreatedAt.After(latest.CreatedAt)) {
485 latest = &snap.Turns[i]
486 }
487 if !wire.Terminal(t.State) {
488 if held && (t.State == wire.TurnWaiting && t.Reason == wire.ReasonNoConnection || t.State == wire.TurnQueued) {
489 waitingTurns[t.ID] = true
490 if view.NoConnection == nil {
491 lines, err := a.store.Chat().NoConnection(ctx, address)
492 if err != nil {
493 a.failure(w, r, chatError(err))
494 return
495 }
496 view.NoConnection = &noConnectionCard{TurnID: t.ID, Line: noConnectionText(lines, loc)}
497 }
498 continue
499 }
500 if t.State == wire.TurnQueued && ahead != nil && ahead.ID != t.ID {
501 queuedTurns[t.ID] = true
502 continue
503 }
504 view.Waiting = append(view.Waiting, t)
505 }
506 }
507 for i := range view.Messages {
508 if view.Messages[i].Own && waitingTurns[view.Messages[i].TurnID] {
509 view.Messages[i].Waiting = copyText("chat.waiting_connection")
510 }
511 }
512 // One note at most: under the person's latest waiting message.
513 for i := len(view.Messages) - 1; i >= 0; i-- {
514 if m := &view.Messages[i]; m.Own && queuedTurns[m.TurnID] {
515 m.Queued = copyText("chat.queued")
516 break
517 }
518 }
519 // A turn that ended unanswered on an earlier day is history there.
520 // Its note says why, and offers what to do (chat_failed.go).
521 if latest != nil && !latest.CreatedAt.Before(today) && (latest.State == wire.TurnFailed || latest.State == wire.TurnCancelled) {
522 if view.Ended, err = a.endedFor(ctx, address, *latest); err != nil {
523 a.failure(w, r, chatError(err))
524 return
525 }
526 }
527 if err := a.presentRoster(ctx, address, &view); err != nil {
528 a.failure(w, r, chatError(err))
529 return
530 }
531 data.Chat, data.ChatStream, data.RequestID = view, true, rand.Text()
532 data.ThinkingSet, data.ThinkingWords = a.thinkingFor(ctx, address)
533 render(w, "chat", data)
534}
535
536// chatSend is the scriptless composer: the same Send a device makes.
537func (a *application) chatSend(w http.ResponseWriter, r *http.Request) {
538 w.Header().Set("Cache-Control", "no-store")
539 ctx, address, ok := sessionContext(r)
540 if !ok {
541 a.failure(w, r, ErrForbidden)
542 return
543 }
544 in := wire.SendMessage{Text: r.PostFormValue("body"), IdempotencyKey: r.PostFormValue("request_id")}
545 if r.PostForm != nil {
546 in.Attachments = r.PostForm["attachment"]
547 }
548 sent, _, err := a.store.Chat().Send(ctx, address, in)
549 if err != nil {
550 a.failure(w, r, chatError(err))
551 return
552 }
553 // chat-stream.js sends in the background and reconciles by message id.
554 if strings.Contains(r.Header.Get("Accept"), "application/json") {
555 runnerJSON(w, http.StatusOK, sent)
556 return
557 }
558 http.Redirect(w, r, "/conversation", http.StatusSeeOther)
559}
560
561// jobsPage lists the person's job threads under "From Base": the work
562// Ask Base handed to their team, newest first.
563func (a *application) jobsPage(w http.ResponseWriter, r *http.Request) {
564 w.Header().Set("Cache-Control", "no-store")
565 ctx, address, ok := sessionContext(r)
566 if !ok {
567 a.failure(w, r, ErrForbidden)
568 return
569 }
570 chats := a.store.Chat()
571 jobs, err := chats.Jobs(ctx, address)
572 if err != nil {
573 a.failure(w, r, chatError(err))
574 return
575 }
576 data, err := a.page(r, "jobs")
577 if err != nil {
578 a.failure(w, r, err)
579 return
580 }
581 data.Title = "jobs.title"
582 loc := chats.Zone(address)
583 for _, j := range jobs {
584 data.Chat.Jobs = append(data.Chat.Jobs, jobLine{ID: j.ID, Label: j.Label, Status: j.Status, When: j.UpdatedAt.In(loc).Format("2 Jan 15:04"), At: j.UpdatedAt})
585 }
586 render(w, "jobs", data)
587}
588
589// jobPage is one job thread, drawn with the conversation's template: its
590// messages, the cards it raised, and a reply field. It is read as the
591// page loads (no stream: the person's own conversation is another lane).
592func (a *application) jobPage(w http.ResponseWriter, r *http.Request) {
593 w.Header().Set("Cache-Control", "no-store")
594 ctx, address, ok := sessionContext(r)
595 if !ok {
596 a.failure(w, r, ErrForbidden)
597 return
598 }
599 id := chi.URLParam(r, "id")
600 chats := a.store.Chat()
601 snap, err := chats.JobThread(ctx, address, id)
602 if err != nil {
603 a.failure(w, r, chatError(err))
604 return
605 }
606 jobs, err := chats.Jobs(ctx, address)
607 if err != nil {
608 a.failure(w, r, chatError(err))
609 return
610 }
611 head := &jobHead{ID: id}
612 for _, j := range jobs {
613 if j.ID == id {
614 head.Label = j.Label
615 }
616 }
617 choices, err := chats.ProjectChoices(ctx, address)
618 if err != nil {
619 a.failure(w, r, chatError(err))
620 return
621 }
622 data, err := a.page(r, "jobs")
623 if err != nil {
624 a.failure(w, r, err)
625 return
626 }
627 data.Title = "jobs.title"
628 tasks := map[string]wire.Task{}
629 for _, t := range snap.Tasks {
630 tasks[t.ID] = t
631 }
632 view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor, Job: head}
633 view.Messages = feedLines(snap.Messages, snap.Cards, choices, tasks, chats.Zone(address))
634 for i := range view.Messages {
635 for _, cards := range [][]chatCard{view.Messages[i].Cards, view.Messages[i].Receipts} {
636 for k := range cards {
637 cards[k].Job = id
638 }
639 }
640 }
641 for _, t := range snap.Turns {
642 if !wire.Terminal(t.State) {
643 view.Waiting = append(view.Waiting, t)
644 }
645 }
646 if err := a.presentRoster(ctx, address, &view); err != nil {
647 a.failure(w, r, chatError(err))
648 return
649 }
650 data.Chat, data.RequestID = view, rand.Text()
651 render(w, "chat", data)
652}
653
654// jobSend is a job thread's reply field: the person's message, into the
655// thread, then back to it.
656func (a *application) jobSend(w http.ResponseWriter, r *http.Request) {
657 w.Header().Set("Cache-Control", "no-store")
658 ctx, address, ok := sessionContext(r)
659 if !ok {
660 a.failure(w, r, ErrForbidden)
661 return
662 }
663 id := chi.URLParam(r, "id")
664 in := wire.SendMessage{Text: r.PostFormValue("body"), IdempotencyKey: r.PostFormValue("request_id")}
665 if _, _, err := a.store.Chat().SendJob(ctx, address, id, in); err != nil {
666 if errors.Is(err, chat.ErrNoRunner) || errors.Is(err, chat.ErrRunnerTooOld) {
667 // Nothing the person has can carry the thread's turn now.
668 err = ErrConflict
669 }
670 a.failure(w, r, chatError(err))
671 return
672 }
673 // SendJob found the thread, so id is a hand-off id ([a-z0-9_]).
674 http.Redirect(w, r, "/jobs/"+id, http.StatusSeeOther)
675}
676
677// chatUpload keeps one file the composer attached, before it is sent:
678// the same Upload a device makes, from this origin only (the page shows
679// the upload's progress, so it posts the bytes itself).
680func (a *application) chatUpload(w http.ResponseWriter, r *http.Request) {
681 w.Header().Set("Cache-Control", "no-store")
682 ctx, address, ok := sessionContext(r)
683 if !ok || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
684 a.failure(w, r, ErrForbidden)
685 return
686 }
687 name, declared, data, err := chat.ReadUpload(r)
688 if err == nil {
689 var out wire.MessageAttachment
690 if out, err = a.store.Chat().Upload(ctx, address, name, declared, data); err == nil {
691 runnerJSON(w, http.StatusCreated, out)
692 return
693 }
694 }
695 // The composer says what went wrong in words, by code.
696 code, status := uploadRefusal(err)
697 if code == "" {
698 a.failure(w, r, chatError(err))
699 return
700 }
701 runnerJSON(w, status, map[string]string{"code": code, "message": copyText("api." + code)})
702}
703
704// chatDeleteUpload deletes an upload the composer's Remove dropped before
705// it was sent, as a device's DELETE does, from this origin only, so it
706// stops counting against the unsent limit. Gone already, or sent in the
707// meantime, there is nothing left for the page to do: 204 too.
708func (a *application) chatDeleteUpload(w http.ResponseWriter, r *http.Request) {
709 w.Header().Set("Cache-Control", "no-store")
710 ctx, address, ok := sessionContext(r)
711 if !ok || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
712 a.failure(w, r, ErrForbidden)
713 return
714 }
715 switch err := a.store.Chat().DeleteUnsent(ctx, address, chi.URLParam(r, "id")); {
716 case err == nil, errors.Is(err, chat.ErrNotFound), errors.Is(err, chat.ErrAttachmentSent):
717 w.WriteHeader(http.StatusNoContent)
718 default:
719 a.failure(w, r, chatError(err))
720 }
721}
722
723func uploadRefusal(err error) (string, int) {
724 switch {
725 case errors.Is(err, chat.ErrAttachmentTooLarge):
726 return "attachment_too_large", http.StatusRequestEntityTooLarge
727 case errors.Is(err, chat.ErrAttachmentType):
728 return "attachment_type", http.StatusUnsupportedMediaType
729 case errors.Is(err, chat.ErrAttachmentHEIC):
730 return "attachment_heic", http.StatusUnsupportedMediaType
731 case errors.Is(err, chat.ErrAttachmentPixels):
732 return "attachment_pixels", http.StatusRequestEntityTooLarge
733 case errors.Is(err, chat.ErrAttachmentLimit):
734 return "attachment_limit", http.StatusConflict
735 }
736 return "", 0
737}
738
739// chatAttachment shows one of the person's attachments, or an image's
740// thumbnail.
741func (a *application) chatAttachment(preview bool) http.HandlerFunc {
742 return func(w http.ResponseWriter, r *http.Request) {
743 ctx, address, ok := sessionContext(r)
744 if !ok {
745 a.failure(w, r, ErrForbidden)
746 return
747 }
748 chat.ServeAttachment(w, r.WithContext(ctx), a.store.Chat(), address, chi.URLParam(r, "id"), preview, func(err error) { a.failure(w, r, chatError(err)) })
749 }
750}
751
752// workTaskFile is a task's kept Research image for the task page: the
753// person API's read check and headers, under the browser session.
754func (a *application) workTaskFile(w http.ResponseWriter, r *http.Request) {
755 ctx, address, ok := sessionContext(r)
756 if !ok {
757 a.failure(w, r, ErrForbidden)
758 return
759 }
760 chat.ServeTaskFile(w, r.WithContext(ctx), a.store.Chat(), address, chi.URLParam(r, "id"), chi.URLParam(r, "file"), func(err error) { a.failure(w, r, chatError(err)) })
761}
762
763// chatCardAnswer answers a question card or changes a project card's
764// repository; chatProjectRemove is the card's Remove. Both are the same
765// store calls a device makes; a stale card just shows its current state.
766func (a *application) chatCardAnswer(w http.ResponseWriter, r *http.Request) {
767 if r.PostFormValue("choice") == "open_access" {
768 a.openAccessApproval(w, r)
769 return
770 }
771 // A merge decision answered on Needs you or the task page returns there.
772 // On the conversation or a job thread the page opens at its bottom,
773 // where what follows the answer shows (Paul, 2026-11-27).
774 back := workBack(r, r.PostFormValue("task"))
775 if back == "/conversation" || strings.HasPrefix(back, "/jobs/") {
776 back += "#conversation-end"
777 }
778 a.chatActionTo(w, r, back, func(ctx context.Context, address string) error {
779 revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
780 var remember *string
781 if r.PostFormValue("remember_present") == "1" {
782 name := ""
783 if r.PostFormValue("remember") == "1" {
784 name = r.PostFormValue("remember_name")
785 }
786 remember = &name
787 }
788 _, _, err := a.store.Chat().Answer(ctx, address, chi.URLParam(r, "id"), wire.AnswerCard{Choice: r.PostFormValue("choice"), Revision: revision, Note: r.PostFormValue("note"), RememberName: remember})
789 return err
790 })
791}
792
793func (a *application) chatProjectRemove(w http.ResponseWriter, r *http.Request) {
794 a.chatAction(w, r, func(ctx context.Context, address string) error {
795 _, err := a.store.Chat().RemoveProject(ctx, address, chi.URLParam(r, "id"))
796 return err
797 })
798}
799
800func (a *application) chatAction(w http.ResponseWriter, r *http.Request, act func(context.Context, string) error) {
801 a.chatActionTo(w, r, "/conversation", act)
802}
803
804// chatActionTo runs a page action as the session's person and returns to
805// back (a fixed path the handler chose, never one from the form).
806func (a *application) chatActionTo(w http.ResponseWriter, r *http.Request, back string, act func(context.Context, string) error) {
807 w.Header().Set("Cache-Control", "no-store")
808 ctx, address, ok := sessionContext(r)
809 if !ok {
810 a.failure(w, r, ErrForbidden)
811 return
812 }
813 if err := act(ctx, address); err != nil {
814 if errors.Is(err, chat.ErrAbilityOff) {
815 // Building is off for the person: this job's work can't start.
816 data, perr := a.page(r, "jobs")
817 if perr != nil {
818 a.failure(w, r, perr)
819 return
820 }
821 data.Title, data.EmptyKey = "jobs.title", "chat.card.ability_off"
822 renderStatus(w, http.StatusForbidden, "empty", data)
823 return
824 }
825 if errors.Is(err, chat.ErrCardConflict) {
826 if strings.Contains(r.Header.Get("Accept"), "application/json") {
827 runnerJSON(w, http.StatusConflict, struct{}{})
828 return
829 }
830 http.Redirect(w, r, back, http.StatusSeeOther)
831 return
832 }
833 a.failure(w, r, chatError(err))
834 return
835 }
836 if strings.Contains(r.Header.Get("Accept"), "application/json") {
837 runnerJSON(w, http.StatusOK, struct{}{})
838 return
839 }
840 http.Redirect(w, r, back, http.StatusSeeOther)
841}
842
843// chatNotebook is what the person's coordinator noted, each entry with
844// where it came from, and Reset.
845func (a *application) chatNotebook(w http.ResponseWriter, r *http.Request) {
846 w.Header().Set("Cache-Control", "no-store")
847 ctx, address, ok := sessionContext(r)
848 if !ok {
849 a.failure(w, r, ErrForbidden)
850 return
851 }
852 n, err := a.store.Chat().Notebook(ctx, address)
853 if err != nil {
854 a.failure(w, r, chatError(err))
855 return
856 }
857 data, err := a.settingsPage(r, "notebook", false)
858 if err != nil {
859 a.failure(w, r, err)
860 return
861 }
862 data.Title = "chat.notebook.title"
863 for _, e := range n.Entries {
864 who := copyText("chat.notebook.own")
865 switch e.Source {
866 case wire.NoteSystem:
867 who = copyText("placement.observed")
868 case wire.NotePerson:
869 who = copyText("chat.notebook.person")
870 case wire.NoteRepo:
871 who = fmt.Sprintf(copyText("chat.notebook.repo"), e.Repo+"/"+e.Path)
872 }
873 data.Notebook = append(data.Notebook, notebookLine{ID: e.ID, Correction: e.Source == wire.NoteSystem, Who: who, Text: e.Text, Day: e.At.UTC().Format("2 Jan"), At: e.At, Said: e.Source == wire.NotePerson})
874 }
875 render(w, "notebook", data)
876}
877
878func (a *application) chatNotebookReset(w http.ResponseWriter, r *http.Request) {
879 a.chatActionTo(w, r, "/conversation/settings/notebook", func(ctx context.Context, address string) error {
880 _, err := a.store.Chat().ResetCoordinator(ctx, address)
881 return err
882 })
883}
884
885func chatError(err error) error {
886 for from, to := range map[error]error{chat.ErrBusy: ErrConflict, chat.ErrInvalid: ErrInvalid, chat.ErrConflict: ErrConflict, chat.ErrNotFound: ErrNotFound, chat.ErrForbidden: ErrForbidden, chat.ErrNotAllowed: ErrInvalid, chat.ErrTaskEnded: ErrConflict, chat.ErrNotRetryable: ErrConflict, chat.ErrMerging: ErrConflict, chat.ErrNotMergeable: ErrConflict, chat.ErrNotAskable: ErrConflict, chat.ErrRevision: ErrConflict, chat.ErrAlreadyReleased: ErrAlreadyRunning} {
887 if errors.Is(err, from) {
888 return to
889 }
890 }
891 return err
892}
893