package web import ( "encoding/json" "io" "net/http" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/base/internal/equipo" ) const ( 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}}` 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}}` ) func frame(id, typ, data string) string { return "id: " + id + "\nevent: " + typ + "\ndata: " + data + "\n\n" } // relayTo runs relay over upstream and returns what reached the browser. func relayTo(t *testing.T, upstream io.Reader, idle time.Duration, stop func()) string { t.Helper() return relaySeeded(t, turnsSeen{}, upstream, idle, stop) } // relaySeeded is relayTo with what the stream knows of its turns as it // starts. func relaySeeded(t *testing.T, seen turnsSeen, upstream io.Reader, idle time.Duration, stop func()) string { t.Helper() rec := httptest.NewRecorder() done := make(chan struct{}) go func() { relay(downstream{rec, http.NewResponseController(rec)}, upstream, idle, stop, seen) close(done) }() select { case <-done: case <-time.After(3 * time.Second): t.Fatal("the relay did not end") } return rec.Body.String() } // An upstream that goes quiet (no event, no ping) ends the stream; the // browser reconnects with its cursor. func TestRelayEndsOnStalledUpstream(t *testing.T) { pr, pw := io.Pipe() go io.WriteString(pw, frame("42", "message", msgEvent)) out := relayTo(t, pr, 100*time.Millisecond, func() { pr.CloseWithError(io.ErrClosedPipe) }) if !strings.Contains(out, "id: 42\nevent: message\n") { t.Fatalf("relayed:\n%q", out) } } // An event past the size bound ends the stream and never reaches the browser. func TestRelayEndsOnOversizedEvent(t *testing.T) { big := `{"cursor":43,"type":"message","data":{"id":"m_3","role":"coordinator","text":"` + strings.Repeat("a", 2<<20) + `"}}` many := strings.Repeat("data: 1\n", 5000) for name, bad := range map[string]string{"bytes": frame("43", "message", big), "lines": "id: 43\nevent: message\n" + many + "\n"} { upstream := frame("42", "message", msgEvent) + bad + frame("44", "message", strings.Replace(msgEvent, "m_2", "m_4", -1)) out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) if !strings.Contains(out, "id: 42\n") || strings.Contains(out, "id: 43") || strings.Contains(out, "id: 44") || len(out) > 4096 { t.Errorf("%s: relayed %d bytes:\n%.300q", name, len(out), out) } } } // A bare CR ends a line for the browser, so the relay must read it so too: // here it turns a turn event into a runner event, which is not relayed, // and no CR ever reaches the browser. func TestRelayParsesBareCR(t *testing.T) { upstream := "id: 41\nevent: turn\ndata: " + turnEvent + "\revent: runner\n\n" + "id: 42\revent: message\rdata: " + msgEvent + "\r\r" out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) if strings.Contains(out, "\r") || strings.Contains(out, "runner") || strings.Contains(out, "id: 41") { t.Fatalf("relayed:\n%q", out) } if !strings.Contains(out, "id: 42\nevent: message\ndata: ") { t.Fatalf("lost the CR-framed message:\n%q", out) } } // Frames are Base's own: known types only, data projected to the // conversation's shape, bad JSON and bad ids dropped. func TestRelayWritesItsOwnFrames(t *testing.T) { project := `{"cursor":45,"type":"card","data":{"id":"c_1","revision":1,"kind":"project","state":"added","project_id":"p_1","name":"oficina/sample"}}` 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"}}` upstream := frame("41", "turn", turnEvent) + frame("44", "message", `{"cursor":44,"data":{oops`) + frame("x1", "message", msgEvent) + frame("45", "card", project) + frame("46", "card", question) + "event: ping\ndata: {\"type\":\"ping\"}\n\n" + ": comment\nretry: 1\n\n" out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) for _, banned := range []string{"cn_secret", "oops", "x1", "p_1", "p_9", "tk_9", "oficina/sample", "retry: 1", "comment"} { if strings.Contains(out, banned) { t.Errorf("relayed %q:\n%s", banned, out) } } for _, want := range []string{ "id: 41\nevent: turn\ndata: {\"type\":\"turn\",\"data\":{\"id\":\"t_1\",\"kind\":\"\",\"state\":\"running\",\"reason\":\"\"}}\n\n", "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", ": ping\n\n", } { if !strings.Contains(out, want) { t.Errorf("relay lacks %q:\n%s", want, out) } } } // The Assistant's cards pass as they are drawn: options as value and // label, web links only, and nothing else Equipo puts on them. A card of a // kind Base does not draw (a task card) is not passed on. func TestRelayGenericCards(t *testing.T) { 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"}}` task := `{"cursor":48,"type":"card","data":{"id":"c_4","revision":1,"kind":"task","state":"open","question":"Merge tk0001?","options":[],"links":[],"result":""}}` out := relayTo(t, strings.NewReader(frame("47", "card", outcome)+frame("48", "card", task)), time.Second, func() {}) for _, banned := range []string{"p_9", "t_9", "tk0001", "s3cr3t", "javascript", "c_4", "id: 48"} { if strings.Contains(out, banned) { t.Errorf("relayed %q:\n%s", banned, out) } } 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":""}}` if !strings.Contains(out, want) { t.Errorf("relay lacks %s:\n%s", want, out) } } // A job card passes with its Equipo link's rel, its detail and its start // time; a card attached to a job keeps the job's id. A job in a state // Base does not know is not passed on, and Equipo's own fields still go. func TestRelayJobCards(t *testing.T) { 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"}}` 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"}}` odd := `{"cursor":52,"type":"card","data":{"id":"c_7","revision":1,"kind":"job","state":"pending","question":"Odd","options":[],"links":[],"result":""}}` out := relayTo(t, strings.NewReader(frame("50", "card", job)+frame("51", "card", outcome)+frame("52", "card", odd)), time.Second, func() {}) for _, banned := range []string{"task_id", "tk0002", "tk0003", "c_7", "id: 52"} { if strings.Contains(out, banned) { t.Errorf("relayed %q:\n%s", banned, out) } } for _, want := range []string{ `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"}}`, `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"}}`, } { if !strings.Contains(out, want) { t.Errorf("relay lacks %s:\n%s", want, out) } } } // glanceEvent is Equipo's glance for turn id saying text. It is live // only: no id line, cursor 0. (cursor names it in these tests' text.) func glanceEvent(cursor, id, text string) string { raw, _ := json.Marshal(text) 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" } // turnFrame is a turn event for turn id of kind in state, at cursor. func turnFrame(cursor, id, kind, state string) string { return frame(cursor, "turn", `{"cursor":`+cursor+`,"type":"turn","resource":"turn","id":"`+id+`","revision":2,"turn_id":"`+id+`","data":{"id":"`+id+`","kind":"`+kind+`","state":"`+state+`"}}`) } // A glance, Equipo's one line on the turn in flight, passes for the // person's turn before its first words, cleaned: one trimmed line of plain // text, at most 60 characters, cut at a word. It is dropped for any other // turn (a team_update turn, an ended one, one not known to be in flight), // once the turn's words have started, and when nothing is left of it. func TestRelayGlance(t *testing.T) { long := "Looking through every one of your projects and the recent work in them" 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"}}`) upstream := turnFrame("50", "t_1", "", "running") + glanceEvent("51", "t_1", " Checking\n your **projects**\u0007\u202e ") + glanceEvent("52", "t_1", long) + glanceEvent("53", "t_1", " \n** ") + glanceEvent("54", "t_9", "Another turn's glance") + "event: glance\ndata: {\"cursor\":0,\"type\":\"glance\",\"resource\":\"turn\",\"id\":\"t_8\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Mismatched glance\"}}\n\n" + turnFrame("56", "t_2", "team_update", "running") + glanceEvent("57", "t_2", "Quiet turn's glance") + turnFrame("58", "t_3", "", "replied") + glanceEvent("59", "t_3", "Ended turn's glance") + delta + glanceEvent("61", "t_1", "After the first words") out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) // A glance has no id line, as it came: the page's cursor stays where // the last conversation event put it. for _, want := range []string{ "\n\nevent: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Checking your projects\"}}\n\n", "\n\nevent: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_1\",\"text\":\"Looking through every one of your projects and the recent\"}}\n\n", "id: 60\nevent: delta\n", } { if !strings.Contains(out, want) { t.Errorf("relay lacks %q:\n%s", want, out) } } if n := strings.Count(out, "event: glance"); n != 2 { t.Errorf("relayed %d glances, want 2:\n%s", n, out) } if strings.Contains(out, "id: \n") || strings.Contains(out, "id: 0") { t.Errorf("relayed an empty or zero id:\n%s", out) } // Any other event without an id is still not passed on. out = relayTo(t, strings.NewReader(strings.Replace(frame("42", "message", msgEvent), "id: 42\n", "", 1)), time.Second, func() {}) if strings.Contains(out, "message") { t.Errorf("relayed a message without an id:\n%s", out) } out = relayTo(t, strings.NewReader(upstream), time.Second, func() {}) for _, banned := range []string{"Another", "Mismatched", "Quiet", "Ended", "After the first", "\u0007", "\u202e", "**"} { if strings.Contains(out, banned) { t.Errorf("relayed %q:\n%s", banned, out) } } // Once the turn has ended, a glance for a turn the stream has never // seen is dropped too: nothing it knows of is in flight. out = relayTo(t, strings.NewReader(turnFrame("50", "t_1", "", "running")+turnFrame("51", "t_1", "", "replied")+ glanceEvent("52", "t_10", "Unseen turn's glance")), time.Second, func() {}) if strings.Contains(out, "Unseen") { t.Errorf("relayed a glance after the turn in flight ended:\n%s", out) } } // A stream that begins after its turn started knows the turns from the // conversation's snapshot: a glance passes for the person's turn in flight // there, and for no other (an unknown turn, a team_update turn, an ended // one, even when an older event replayed after the cursor has it running). // Without a snapshot no glance passes for a turn the stream has not seen // start. func TestRelayGlanceFromSnapshot(t *testing.T) { upstream := glanceEvent("70", "t_7", "Checking your projects") + glanceEvent("71", "t_6", "Unknown turn's glance") + glanceEvent("72", "t_5", "Quiet turn's glance") + turnFrame("73", "t_4", "", "running") + glanceEvent("74", "t_4", "Ended turn's glance") out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) for _, banned := range []string{"Checking", "Unknown", "Quiet"} { if strings.Contains(out, banned) { t.Errorf("without a snapshot, relayed %q:\n%s", banned, out) } } snap := equipo.Snapshot{Turns: []equipo.Turn{ {ID: "t_4", State: equipo.TurnReplied}, {ID: "t_5", Kind: equipo.TurnTeamUpdate, State: equipo.TurnRunning}, {ID: "t_7", State: equipo.TurnRunning}}} out = relaySeeded(t, seedTurns(snap), strings.NewReader(upstream), time.Second, func() {}) if !strings.HasPrefix(out, "event: glance\ndata: {\"type\":\"glance\",\"data\":{\"turn_id\":\"t_7\",\"text\":\"Checking your projects\"}}\n\n") { t.Errorf("with the turn in flight in the snapshot, the glance did not pass:\n%s", out) } for _, banned := range []string{"Unknown", "Quiet", "Ended"} { if strings.Contains(out, banned) { t.Errorf("relayed %q:\n%s", banned, out) } } } // A connect card passes with the turn that raised it, read from the // event's own turn_id (never from the card's data), so the panel can hold // it for that turn's reply. A turn id that is not one is dropped, and no // other kind of card carries one. func TestRelayConnectCardKeepsItsTurn(t *testing.T) { connect := func(cursor, turn string) string { 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":""}}` } 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":""}}` seen := turnsSeen{base: "https://base.example.test"} out := relaySeeded(t, seen, strings.NewReader(frame("70", "card", connect("70", "t_7"))+frame("71", "card", connect("71", `t\">