| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/base/internal/equipo" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | turnEvent = `{"cursor":41,"type":"turn","resource":"turn","id":"t_1","revision":2,"turn_id":"t_1","data":{"id":"t_1","revision":2,"kind":"","state":"running","reason":"","attempt":1,"message_ids":["m_1"],"reply_id":"","connection":"cn_secret","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z","timing":null}}` |
| 17 | msgEvent = `{"cursor":42,"type":"message","resource":"message","id":"m_2","revision":1,"turn_id":"t_1","message_id":"m_2","data":{"id":"m_2","revision":1,"role":"coordinator","text":"Hello","turn_id":"t_1","created_at":"2026-11-06T10:00:02Z","switched":null}}` |
| 18 | ) |
| 19 | |
| 20 | func frame(id, typ, data string) string { |
| 21 | return "id: " + id + "\nevent: " + typ + "\ndata: " + data + "\n\n" |
| 22 | } |
| 23 | |
| 24 | // relayTo runs relay over upstream and returns what reached the browser. |
| 25 | func relayTo(t *testing.T, upstream io.Reader, idle time.Duration, stop func()) string { |
| 26 | t.Helper() |
| 27 | return relaySeeded(t, turnsSeen{}, upstream, idle, stop) |
| 28 | } |
| 29 | |
| 30 | // relaySeeded is relayTo with what the stream knows of its turns as it |
| 31 | // starts. |
| 32 | func relaySeeded(t *testing.T, seen turnsSeen, upstream io.Reader, idle time.Duration, stop func()) string { |
| 33 | t.Helper() |
| 34 | rec := httptest.NewRecorder() |
| 35 | done := make(chan struct{}) |
| 36 | go func() { |
| 37 | relay(downstream{rec, http.NewResponseController(rec)}, upstream, idle, stop, seen) |
| 38 | close(done) |
| 39 | }() |
| 40 | select { |
| 41 | case <-done: |
| 42 | case <-time.After(3 * time.Second): |
| 43 | t.Fatal("the relay did not end") |
| 44 | } |
| 45 | return rec.Body.String() |
| 46 | } |
| 47 | |
| 48 | // An upstream that goes quiet (no event, no ping) ends the stream; the |
| 49 | // browser reconnects with its cursor. |
| 50 | func TestRelayEndsOnStalledUpstream(t *testing.T) { |
| 51 | pr, pw := io.Pipe() |
| 52 | go io.WriteString(pw, frame("42", "message", msgEvent)) |
| 53 | out := relayTo(t, pr, 100*time.Millisecond, func() { pr.CloseWithError(io.ErrClosedPipe) }) |
| 54 | if !strings.Contains(out, "id: 42\nevent: message\n") { |
| 55 | t.Fatalf("relayed:\n%q", out) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // An event past the size bound ends the stream and never reaches the browser. |
| 60 | func TestRelayEndsOnOversizedEvent(t *testing.T) { |
| 61 | big := `{"cursor":43,"type":"message","data":{"id":"m_3","role":"coordinator","text":"` + strings.Repeat("a", 2<<20) + `"}}` |
| 62 | many := strings.Repeat("data: 1\n", 5000) |
| 63 | for name, bad := range map[string]string{"bytes": frame("43", "message", big), "lines": "id: 43\nevent: message\n" + many + "\n"} { |
| 64 | upstream := frame("42", "message", msgEvent) + bad + frame("44", "message", strings.Replace(msgEvent, "m_2", "m_4", -1)) |
| 65 | out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 66 | if !strings.Contains(out, "id: 42\n") || strings.Contains(out, "id: 43") || strings.Contains(out, "id: 44") || len(out) > 4096 { |
| 67 | t.Errorf("%s: relayed %d bytes:\n%.300q", name, len(out), out) |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // A bare CR ends a line for the browser, so the relay must read it so too: |
| 73 | // here it turns a turn event into a runner event, which is not relayed, |
| 74 | // and no CR ever reaches the browser. |
| 75 | func TestRelayParsesBareCR(t *testing.T) { |
| 76 | upstream := "id: 41\nevent: turn\ndata: " + turnEvent + "\revent: runner\n\n" + |
| 77 | "id: 42\revent: message\rdata: " + msgEvent + "\r\r" |
| 78 | out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 79 | if strings.Contains(out, "\r") || strings.Contains(out, "runner") || strings.Contains(out, "id: 41") { |
| 80 | t.Fatalf("relayed:\n%q", out) |
| 81 | } |
| 82 | if !strings.Contains(out, "id: 42\nevent: message\ndata: ") { |
| 83 | t.Fatalf("lost the CR-framed message:\n%q", out) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // Frames are Base's own: known types only, data projected to the |
| 88 | // conversation's shape, bad JSON and bad ids dropped. |
| 89 | func TestRelayWritesItsOwnFrames(t *testing.T) { |
| 90 | project := `{"cursor":45,"type":"card","data":{"id":"c_1","revision":1,"kind":"project","state":"added","project_id":"p_1","name":"oficina/sample"}}` |
| 91 | question := `{"cursor":46,"type":"card","data":{"id":"c_2","revision":1,"kind":"question","state":"open","turn_id":"t_1","project_id":"p_9","question":"Which branch?","options":[{"value":"main","label":"main"}],"links":[],"result":"","task_id":"tk_9"}}` |
| 92 | upstream := frame("41", "turn", turnEvent) + frame("44", "message", `{"cursor":44,"data":{oops`) + |
| 93 | frame("x1", "message", msgEvent) + frame("45", "card", project) + frame("46", "card", question) + |
| 94 | "event: ping\ndata: {\"type\":\"ping\"}\n\n" + ": comment\nretry: 1\n\n" |
| 95 | out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 96 | for _, banned := range []string{"cn_secret", "oops", "x1", "p_1", "p_9", "tk_9", "oficina/sample", "retry: 1", "comment"} { |
| 97 | if strings.Contains(out, banned) { |
| 98 | t.Errorf("relayed %q:\n%s", banned, out) |
| 99 | } |
| 100 | } |
| 101 | for _, want := range []string{ |
| 102 | "id: 41\nevent: turn\ndata: {\"type\":\"turn\",\"data\":{\"id\":\"t_1\",\"kind\":\"\",\"state\":\"running\",\"reason\":\"\"}}\n\n", |
| 103 | "id: 46\nevent: card\ndata: {\"type\":\"card\",\"data\":{\"id\":\"c_2\",\"revision\":1,\"kind\":\"question\",\"state\":\"open\",\"question\":\"Which branch?\",\"options\":[{\"value\":\"main\",\"label\":\"main\"}],\"links\":[],\"result\":\"\"}}\n\n", |
| 104 | ": ping\n\n", |
| 105 | } { |
| 106 | if !strings.Contains(out, want) { |
| 107 | t.Errorf("relay lacks %q:\n%s", want, out) |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // The Assistant's cards pass as they are drawn: options as value and |
| 113 | // label, web links only, and nothing else Equipo puts on them. A card of a |
| 114 | // kind Base does not draw (a task card) is not passed on. |
| 115 | func TestRelayGenericCards(t *testing.T) { |
| 116 | outcome := `{"cursor":47,"type":"card","data":{"id":"c_3","revision":2,"kind":"outcome","state":"open","turn_id":"t_9","project_id":"p_9","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://preview.example.test/"},{"label":"Bad","url":"javascript:alert(1)"}],"result":"","task_id":"tk0001","secret_field":"s3cr3t"}}` |
| 117 | task := `{"cursor":48,"type":"card","data":{"id":"c_4","revision":1,"kind":"task","state":"open","question":"Merge tk0001?","options":[],"links":[],"result":""}}` |
| 118 | out := relayTo(t, strings.NewReader(frame("47", "card", outcome)+frame("48", "card", task)), time.Second, func() {}) |
| 119 | for _, banned := range []string{"p_9", "t_9", "tk0001", "s3cr3t", "javascript", "c_4", "id: 48"} { |
| 120 | if strings.Contains(out, banned) { |
| 121 | t.Errorf("relayed %q:\n%s", banned, out) |
| 122 | } |
| 123 | } |
| 124 | want := `data: {"type":"card","data":{"id":"c_3","revision":2,"kind":"outcome","state":"open","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://preview.example.test/"}],"result":""}}` |
| 125 | if !strings.Contains(out, want) { |
| 126 | t.Errorf("relay lacks %s:\n%s", want, out) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // A job card passes with its Equipo link's rel, its detail and its start |
| 131 | // time; a card attached to a job keeps the job's id. A job in a state |
| 132 | // Base does not know is not passed on, and Equipo's own fields still go. |
| 133 | func TestRelayJobCards(t *testing.T) { |
| 134 | job := `{"cursor":50,"type":"card","data":{"id":"c_5","revision":2,"kind":"job","state":"working","question":"Add a booking page","options":[],"links":[{"label":"Open in Equipo","url":"https://equipo.test/jobs/h_1","rel":"equipo"}],"result":"Building it","detail":"Putting the page together.","started_at":"2026-11-13T09:30:00Z","task_id":"tk0002"}}` |
| 135 | outcome := `{"cursor":51,"type":"card","data":{"id":"c_6","revision":1,"kind":"outcome","state":"open","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"}],"links":[],"result":"","job":"c_5","task_id":"tk0003"}}` |
| 136 | odd := `{"cursor":52,"type":"card","data":{"id":"c_7","revision":1,"kind":"job","state":"pending","question":"Odd","options":[],"links":[],"result":""}}` |
| 137 | out := relayTo(t, strings.NewReader(frame("50", "card", job)+frame("51", "card", outcome)+frame("52", "card", odd)), time.Second, func() {}) |
| 138 | for _, banned := range []string{"task_id", "tk0002", "tk0003", "c_7", "id: 52"} { |
| 139 | if strings.Contains(out, banned) { |
| 140 | t.Errorf("relayed %q:\n%s", banned, out) |
| 141 | } |
| 142 | } |
| 143 | for _, want := range []string{ |
| 144 | `data: {"type":"card","data":{"id":"c_5","revision":2,"kind":"job","state":"working","question":"Add a booking page","options":[],"links":[{"label":"Open in Equipo","url":"https://equipo.test/jobs/h_1","rel":"equipo"}],"result":"Building it","detail":"Putting the page together.","started_at":"2026-11-13T09:30:00Z"}}`, |
| 145 | `data: {"type":"card","data":{"id":"c_6","revision":1,"kind":"outcome","state":"open","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"}],"links":[],"result":"","job":"c_5"}}`, |
| 146 | } { |
| 147 | if !strings.Contains(out, want) { |
| 148 | t.Errorf("relay lacks %s:\n%s", want, out) |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | // glanceEvent is Equipo's glance for turn id saying text. It is live |
| 154 | // only: no id line, cursor 0. (cursor names it in these tests' text.) |
| 155 | func glanceEvent(cursor, id, text string) string { |
| 156 | raw, _ := json.Marshal(text) |
| 157 | return "event: glance\ndata: " + `{"cursor":0,"type":"glance","resource":"turn","id":"` + id + `","revision":0,"turn_id":"` + id + `","data":{"turn_id":"` + id + `","text":` + string(raw) + `},"n":"` + cursor + `"}` + "\n\n" |
| 158 | } |
| 159 | |
| 160 | // turnFrame is a turn event for turn id of kind in state, at cursor. |
| 161 | func turnFrame(cursor, id, kind, state string) string { |
| 162 | return frame(cursor, "turn", `{"cursor":`+cursor+`,"type":"turn","resource":"turn","id":"`+id+`","revision":2,"turn_id":"`+id+`","data":{"id":"`+id+`","kind":"`+kind+`","state":"`+state+`"}}`) |
| 163 | } |
| 164 | |
| 165 | // A glance, Equipo's one line on the turn in flight, passes for the |
| 166 | // person's turn before its first words, cleaned: one trimmed line of plain |
| 167 | // text, at most 60 characters, cut at a word. It is dropped for any other |
| 168 | // turn (a team_update turn, an ended one, one not known to be in flight), |
| 169 | // once the turn's words have started, and when nothing is left of it. |
| 170 | func TestRelayGlance(t *testing.T) { |
| 171 | long := "Looking through every one of your projects and the recent work in them" |
| 172 | delta := frame("60", "delta", `{"cursor":60,"type":"delta","resource":"turn","id":"t_1","revision":0,"turn_id":"t_1","data":{"turn_id":"t_1","offset":0,"text":"Here"}}`) |
| 173 | upstream := turnFrame("50", "t_1", "", "running") + |
| 174 | glanceEvent("51", "t_1", " Checking\n your **projects**\u0007\u202e ") + |
| 175 | glanceEvent("52", "t_1", long) + |
| 176 | glanceEvent("53", "t_1", " \n** ") + |
| 177 | glanceEvent("54", "t_9", "Another turn's glance") + |
| 178 | "event: glance\ndata: {\"cursor\":0,\"type\":\"glance\",\"resource\":\"turn\",\"id\":\"t_8\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Mismatched glance\"}}\n\n" + |
| 179 | turnFrame("56", "t_2", "team_update", "running") + |
| 180 | glanceEvent("57", "t_2", "Quiet turn's glance") + |
| 181 | turnFrame("58", "t_3", "", "replied") + |
| 182 | glanceEvent("59", "t_3", "Ended turn's glance") + |
| 183 | delta + |
| 184 | glanceEvent("61", "t_1", "After the first words") |
| 185 | out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 186 | // A glance has no id line, as it came: the page's cursor stays where |
| 187 | // the last conversation event put it. |
| 188 | for _, want := range []string{ |
| 189 | "\n\nevent: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Checking your projects\"}}\n\n", |
| 190 | "\n\nevent: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Looking through every one of your projects and the recent\"}}\n\n", |
| 191 | "id: 60\nevent: delta\n", |
| 192 | } { |
| 193 | if !strings.Contains(out, want) { |
| 194 | t.Errorf("relay lacks %q:\n%s", want, out) |
| 195 | } |
| 196 | } |
| 197 | if n := strings.Count(out, "event: glance"); n != 2 { |
| 198 | t.Errorf("relayed %d glances, want 2:\n%s", n, out) |
| 199 | } |
| 200 | if strings.Contains(out, "id: \n") || strings.Contains(out, "id: 0") { |
| 201 | t.Errorf("relayed an empty or zero id:\n%s", out) |
| 202 | } |
| 203 | // Any other event without an id is still not passed on. |
| 204 | out = relayTo(t, strings.NewReader(strings.Replace(frame("42", "message", msgEvent), "id: 42\n", "", 1)), time.Second, func() {}) |
| 205 | if strings.Contains(out, "message") { |
| 206 | t.Errorf("relayed a message without an id:\n%s", out) |
| 207 | } |
| 208 | out = relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 209 | for _, banned := range []string{"Another", "Mismatched", "Quiet", "Ended", "After the first", "\u0007", "\u202e", "**"} { |
| 210 | if strings.Contains(out, banned) { |
| 211 | t.Errorf("relayed %q:\n%s", banned, out) |
| 212 | } |
| 213 | } |
| 214 | // Once the turn has ended, a glance for a turn the stream has never |
| 215 | // seen is dropped too: nothing it knows of is in flight. |
| 216 | out = relayTo(t, strings.NewReader(turnFrame("50", "t_1", "", "running")+turnFrame("51", "t_1", "", "replied")+ |
| 217 | glanceEvent("52", "t_10", "Unseen turn's glance")), time.Second, func() {}) |
| 218 | if strings.Contains(out, "Unseen") { |
| 219 | t.Errorf("relayed a glance after the turn in flight ended:\n%s", out) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // A stream that begins after its turn started knows the turns from the |
| 224 | // conversation's snapshot: a glance passes for the person's turn in flight |
| 225 | // there, and for no other (an unknown turn, a team_update turn, an ended |
| 226 | // one, even when an older event replayed after the cursor has it running). |
| 227 | // Without a snapshot no glance passes for a turn the stream has not seen |
| 228 | // start. |
| 229 | func TestRelayGlanceFromSnapshot(t *testing.T) { |
| 230 | upstream := glanceEvent("70", "t_7", "Checking your projects") + glanceEvent("71", "t_6", "Unknown turn's glance") + |
| 231 | glanceEvent("72", "t_5", "Quiet turn's glance") + turnFrame("73", "t_4", "", "running") + |
| 232 | glanceEvent("74", "t_4", "Ended turn's glance") |
| 233 | out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| 234 | for _, banned := range []string{"Checking", "Unknown", "Quiet"} { |
| 235 | if strings.Contains(out, banned) { |
| 236 | t.Errorf("without a snapshot, relayed %q:\n%s", banned, out) |
| 237 | } |
| 238 | } |
| 239 | snap := equipo.Snapshot{Turns: []equipo.Turn{ |
| 240 | {ID: "t_4", State: equipo.TurnReplied}, {ID: "t_5", Kind: equipo.TurnTeamUpdate, State: equipo.TurnRunning}, |
| 241 | {ID: "t_7", State: equipo.TurnRunning}}} |
| 242 | out = relaySeeded(t, seedTurns(snap), strings.NewReader(upstream), time.Second, func() {}) |
| 243 | if !strings.HasPrefix(out, "event: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_7\",\"text\":\"Checking your projects\"}}\n\n") { |
| 244 | t.Errorf("with the turn in flight in the snapshot, the glance did not pass:\n%s", out) |
| 245 | } |
| 246 | for _, banned := range []string{"Unknown", "Quiet", "Ended"} { |
| 247 | if strings.Contains(out, banned) { |
| 248 | t.Errorf("relayed %q:\n%s", banned, out) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // A connect card passes with the turn that raised it, read from the |
| 254 | // event's own turn_id (never from the card's data), so the panel can hold |
| 255 | // it for that turn's reply. A turn id that is not one is dropped, and no |
| 256 | // other kind of card carries one. |
| 257 | func TestRelayConnectCardKeepsItsTurn(t *testing.T) { |
| 258 | connect := func(cursor, turn string) string { |
| 259 | return `{"cursor":` + cursor + `,"type":"card","resource":"card","id":"c_8","revision":1,"turn_id":"` + turn + `","data":{"id":"c_8","revision":1,"kind":"connect","state":"open","turn_id":"t_data","question":"Connect your Oficina apps","options":[],"links":[{"label":"Connect","url":"https://base.example.test/ask/oficina/connect","rel":"oficina_connect"}],"result":""}}` |
| 260 | } |
| 261 | outcome := `{"cursor":72,"type":"card","resource":"card","id":"c_9","revision":1,"turn_id":"t_7","data":{"id":"c_9","revision":1,"kind":"outcome","state":"open","question":"Go ahead?","options":[],"links":[],"result":""}}` |
| 262 | seen := turnsSeen{base: "https://base.example.test"} |
| 263 | out := relaySeeded(t, seen, strings.NewReader(frame("70", "card", connect("70", "t_7"))+frame("71", "card", connect("71", `t\"><x`))+frame("72", "card", outcome)), time.Second, func() {}) |
| 264 | for _, want := range []string{ |
| 265 | `id: 70` + "\nevent: card\n" + `data: {"type":"card","data":{"id":"c_8","revision":1,"kind":"connect","state":"open","question":"Connect your Oficina apps","options":[],"links":[{"label":"Connect","url":"https://base.example.test/ask/oficina/connect","rel":"oficina_connect"}],"result":"","turn_id":"t_7"}}`, |
| 266 | `id: 71` + "\nevent: card\n" + `data: {"type":"card","data":{"id":"c_8","revision":1,"kind":"connect","state":"open","question":"Connect your Oficina apps","options":[],"links":[{"label":"Connect","url":"https://base.example.test/ask/oficina/connect","rel":"oficina_connect"}],"result":""}}`, |
| 267 | `data: {"type":"card","data":{"id":"c_9","revision":1,"kind":"outcome","state":"open","question":"Go ahead?","options":[],"links":[],"result":""}}`, |
| 268 | } { |
| 269 | if !strings.Contains(out, want) { |
| 270 | t.Errorf("relay lacks %s:\n%s", want, out) |
| 271 | } |
| 272 | } |
| 273 | if strings.Contains(out, "t_data") { |
| 274 | t.Errorf("the card's own turn_id passed:\n%s", out) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // A message's files pass with the fields Base draws them from, and |
| 279 | // nothing else of Equipo's: no URL, no hash, no id Base would not call |
| 280 | // Equipo with; an unknown kind is a file. |
| 281 | func TestRelayMessageFiles(t *testing.T) { |
| 282 | files := `{"cursor":47,"type":"message","data":{"id":"m_3","revision":1,"role":"person","text":"","turn_id":"t_2","created_at":"2026-11-26T10:00:00Z",` + |
| 283 | `"attachments":[{"id":"at_abcdefgh12","revision":2,"kind":"image","name":"shot.png","media_type":"image/png","size":2048,"sha256":"feedface","width":640,"height":480,"message_id":"m_3","created_at":"2026-11-26T10:00:00Z","url":"https://equipo.example/api/v1/attachments/at_abcdefgh12"},` + |
| 284 | `{"id":"https://equipo.example/x","kind":"file","name":"bad.txt"},` + |
| 285 | `{"id":"at_zzzzzzzz99","kind":"video","name":"notes.md","media_type":"text/markdown","size":12,"width":0,"height":0}]}}` |
| 286 | out := relayTo(t, strings.NewReader(frame("47", "message", files)), time.Second, func() {}) |
| 287 | for _, banned := range []string{"equipo.example", "feedface", "message_id", "revision", "video", "bad.txt"} { |
| 288 | if strings.Contains(out, banned) { |
| 289 | t.Errorf("relayed %q:\n%s", banned, out) |
| 290 | } |
| 291 | } |
| 292 | want := `"attachments":[{"id":"at_abcdefgh12","kind":"image","name":"shot.png","media_type":"image/png","size":2048,"width":640,"height":480},` + |
| 293 | `{"id":"at_zzzzzzzz99","kind":"file","name":"notes.md","media_type":"text/markdown","size":12,"width":0,"height":0}]` |
| 294 | if !strings.Contains(out, want) { |
| 295 | t.Errorf("relay lacks %s:\n%s", want, out) |
| 296 | } |
| 297 | if out := relayTo(t, strings.NewReader(frame("42", "message", msgEvent)), time.Second, func() {}); strings.Contains(out, "attachments") { |
| 298 | t.Errorf("a message without files gained some:\n%s", out) |
| 299 | } |
| 300 | } |
| 301 | |