package codex import ( "context" "encoding/json" "fmt" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) func answerFixture(t *testing.T) (*Launcher, *sessionState, *rpcInput, chan provider.Frame) { t.Helper() f := fixtureFor(t) s, _ := openFixture(t, f) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) st := &sessionState{ session: s, launch: f.launch, lease: f.lease, ctx: ctx, cancel: cancel, events: make(chan provider.Event, 64), active: true, turn: provider.Turn{ID: "local-turn"}, providerTurn: "provider-turn", } w := &rpcInput{sent: make(chan []byte, 16)} frames := make(chan provider.Frame, 16) rpc := newFrameRPC(ctx, &provider.Capture{Input: w, Frames: frames, Done: make(chan error, 1)}, st.handle) st.rpc = rpc l := &Launcher{sessions: map[string]*sessionState{s.AttemptKey: st}} t.Cleanup(func() { rpc.close(); <-rpc.done }) return l, st, w, frames } func TestCodexApprovalResponse(t *testing.T) { for _, method := range []string{"item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request"} { t.Run(method, func(t *testing.T) { l, s, w, _ := answerFixture(t) ctx := context.Background() raw := []byte(fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","itemId":"item","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, method, s.session.ID)) raw = pinnedMCPRequest(t, s, raw) if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil { t.Fatal(e) } // IDs are JSON values, not their display form. if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: `"7"`, Behavior: "deny"}) == nil { t.Fatal("string ID answered numeric request") } for _, input := range []string{`{"decision":"acceptForSession"}`, `{"execpolicyAmendment":["curl"]}`, `{"permissions":{"network":true}}`} { if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow", Input: json.RawMessage(input)}) == nil { t.Fatal("policy amendment accepted", input) } } if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow"}) == nil { t.Fatal("approval without broker validation") } if e := l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "deny"}); e != nil { t.Fatal(e) } var reply struct { ID json.RawMessage Result map[string]any } if json.Unmarshal(<-w.sent, &reply) != nil || string(reply.ID) != "7" || reply.Result["decision"] != "decline" && reply.Result["action"] != "decline" { t.Fatal(reply) } }) } } func TestCodexAsyncQuestionAnswer(t *testing.T) { for _, mode := range []string{"async", "schema"} { t.Run(mode, func(t *testing.T) { l, s, w, frames := answerFixture(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() raw := fmt.Sprintf(`{"method":"item/completed","params":{"threadId":%q,"turnId":"provider-turn","item":{"id":"message","type":"agentMessage","delivery":"async","questions":[{"title":"Greeting","options":["hi","bye"]}]}}}`, s.session.ID) id := "async:message" if mode == "schema" { id = `"user-input"` raw = fmt.Sprintf(`{"id":"user-input","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"Greeting","header":"Greeting","question":"Which greeting?","options":[{"label":"hi"}]}]}}`, s.session.ID) } if e := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); e != nil { t.Fatal(e) } a := provider.Answer{RequestID: id, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"Greeting":"hi"}}`)} bad := a bad.TurnID = "replaced" if l.Respond(ctx, s.session, bad) == nil { t.Fatal("replaced turn answered") } result := make(chan error, 1) go func() { result <- l.Respond(ctx, s.session, a) }() var call struct { ID json.RawMessage Method string Params struct{ ThreadID, ExpectedTurnID string } Result struct { Answers map[string]struct{ Answers []string } } } var wire []byte select { case wire = <-w.sent: case e := <-result: t.Fatal("answer not transmitted", e) case <-ctx.Done(): t.Fatal("answer timeout") } if json.Unmarshal(wire, &call) != nil { t.Fatal("bad wire") } if mode == "async" { if call.Method != "turn/steer" || call.Params.ExpectedTurnID != "provider-turn" || call.Params.ThreadID != s.session.ID { t.Fatalf("wrong steer: %+v", call) } frames <- provider.Frame{Sequence: 100, Bytes: []byte(fmt.Sprintf(`{"id":%s,"result":{"turnId":"provider-turn"}}`, call.ID))} } else if string(call.ID) != id || len(call.Result.Answers["Greeting"].Answers) != 1 { t.Fatal("wrong schema answer", call) } if e := <-result; e != nil { t.Fatal(e) } if l.Respond(ctx, s.session, a) == nil { t.Fatal("answer replay") } s.mu.Lock() s.active = false s.mu.Unlock() if l.Respond(ctx, s.session, a) == nil { t.Fatal("completed turn follow-up without admission") } }) } } func TestCodexApprovalResponseValidatedMCP(t *testing.T) { l, s, w, _ := answerFixture(t) raw := []byte(fmt.Sprintf(`{"id":"mcp","method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID)) raw = pinnedMCPRequest(t, s, raw) if e := s.handle(provider.Frame{Sequence: 100, Bytes: raw}); e != nil { t.Fatal(e) } checked := 0 a := provider.Answer{TurnID: "local-turn", RequestID: `"mcp"`, Behavior: "allow", Authorize: func(_ context.Context, ev provider.Event) error { checked++ if string(ev.Payload) != string(raw) { t.Fatal("original request changed") } return nil }} if e := l.Respond(context.Background(), s.session, a); e != nil { t.Fatal(e) } var reply struct { ID string Result struct{ Decision, Action string } } if json.Unmarshal(<-w.sent, &reply) != nil || reply.ID != "mcp" || reply.Result.Action != "accept" || checked != 1 { t.Fatal(reply, checked) } } func TestCodexApprovalResponseFixedMCPPolicy(t *testing.T) { f := fixtureFor(t) var cfg map[string]json.RawMessage if json.Unmarshal(f.inputs.Settings, &cfg) != nil { t.Fatal("settings") } var servers map[string]struct { Command string Args []string } if json.Unmarshal(cfg["mcp_servers"], &servers) != nil || len(servers) != 1 || servers["equipo"].Command != "/opt/equipo-tool-proxy" || fmt.Sprint(servers["equipo"].Args) != "[--socket /tool/equipo.sock]" { t.Fatal("fixed MCP missing", string(cfg["mcp_servers"])) } } func pinnedMCPRequest(t *testing.T, s *sessionState, raw []byte) []byte { t.Helper() var v map[string]any if json.Unmarshal(raw, &v) != nil { t.Fatal("request") } if v["method"] != "mcpServer/elicitation/request" { return raw } p := v["params"].(map[string]any) item := map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "mcp-item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}} if e := s.handle(provider.Frame{Sequence: 98, Bytes: marshal(item)}); e != nil { t.Fatal(e) } v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "approval fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"], "persist": []string{"session", "always"}}} return marshal(v) } func TestCodexApprovalResponseResolvedRequest(t *testing.T) { l, s, _, _ := answerFixture(t) raw := []byte(fmt.Sprintf(`{"id":9,"method":"item/commandExecution/requestApproval","params":{"threadId":%q,"turnId":"provider-turn","itemId":"command"}}`, s.session.ID)) if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil { t.Fatal(e) } resolved := []byte(fmt.Sprintf(`{"method":"serverRequest/resolved","params":{"threadId":%q,"requestId":9}}`, s.session.ID)) if e := s.handle(provider.Frame{Sequence: 100, Bytes: resolved}); e != nil { t.Fatal(e) } if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "9", TurnID: "local-turn", Behavior: "deny"}) == nil { t.Fatal("resolved request answered") } } func TestCodexApprovalResponseMCPCorrelation(t *testing.T) { for _, change := range []string{"arguments", "server", "schema", "missing-item", "completed-item", "ambiguous"} { t.Run(change, func(t *testing.T) { l, s, _, _ := answerFixture(t) raw := []byte(fmt.Sprintf(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID)) raw = pinnedMCPRequest(t, s, raw) switch change { case "arguments": raw = []byte(strings.Replace(string(raw), "Which?", "Changed?", 1)) case "server": raw = []byte(strings.Replace(string(raw), `"serverName":"equipo"`, `"serverName":"other"`, 1)) case "schema": raw = []byte(strings.Replace(string(raw), `"properties":{}`, `"properties":{"permissions":{"type":"string"}}`, 1)) case "missing-item": s.mcpCalls = nil case "ambiguous": s.mcpCalls["other"] = s.mcpCalls["mcp-item"] } if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil { t.Fatal(e) } if change == "completed-item" { s.mu.Lock() delete(s.mcpCalls, "mcp-item") s.mu.Unlock() } if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "allow", Authorize: func(context.Context, provider.Event) error { return nil }}) == nil { t.Fatal("uncorrelated MCP approved", change) } }) } } func TestCodexApprovalResponseNoQuestionFallback(t *testing.T) { l, s, _, _ := answerFixture(t) raw := []byte(fmt.Sprintf(`{"id":"fallback","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"mcp_tool_call_approval_1","header":"Approve app tool call?","question":"Allow?","options":[{"label":"Always allow"}]}]}}`, s.session.ID)) if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil { t.Fatal(e) } if l.Respond(context.Background(), s.session, provider.Answer{RequestID: `"fallback"`, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"mcp_tool_call_approval_1":"Always allow"}}`)}) == nil { t.Fatal("permission amendment through question fallback") } } func TestCodexApprovalResponseInvalidAuthorizationWire(t *testing.T) { for _, reason := range []string{"fence", "attempt", "tool", "arguments", "changed-call", "completed-turn"} { t.Run(reason, func(t *testing.T) { l, s, w, _ := answerFixture(t) raw := []byte(fmt.Sprintf(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","server":"equipo","tool":"submit_candidate","arguments":{"request_id":"r","commit":"bad"}}}`, s.session.ID)) raw = pinnedMCPRequest(t, s, raw) if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil { t.Fatal(e) } e := l.Respond(context.Background(), s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow", Authorize: func(context.Context, provider.Event) error { s.mu.Lock() defer s.mu.Unlock() if reason == "changed-call" { clear(s.mcpCalls) } if reason == "completed-turn" { s.active = false } return provider.ErrPolicy }}) if reason == "completed-turn" { if e == nil { t.Fatal("completed turn answered") } select { case raw := <-w.sent: t.Fatalf("completed turn wire: %s", raw) default: } return } if e != nil { t.Fatalf("invalid %s authorization left request pending: %v", reason, e) } select { case raw := <-w.sent: var reply struct { ID json.RawMessage Result struct { Action string Content, Meta json.RawMessage } } if json.Unmarshal(raw, &reply) != nil || string(reply.ID) != "7" || reply.Result.Action != "decline" || string(reply.Result.Content) != "null" { t.Fatalf("expected decline on wire: %s", raw) } case <-time.After(time.Second): t.Fatal("no decline on wire") } }) } } func TestCodexRefusesUnsupportedRequests(t *testing.T) { for _, method := range []string{"item/permissions/requestApproval", "async/requestUserInput", "unlisted/request", "item/tool/requestUserInput"} { t.Run(method, func(t *testing.T) { l, s, w, _ := answerFixture(t) raw := fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","questions":[{"id":"q"}]}}`, method, s.session.ID) if err := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); err != nil { t.Fatal(err) } if supportedRequest(method) { if err := l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "deny"}); err != nil { t.Fatal("cannot refuse server request", err) } } select { case raw := <-w.sent: var reply struct { ID json.RawMessage Error json.RawMessage } if json.Unmarshal(raw, &reply) != nil || len(reply.Error) == 0 { t.Fatal("missing protocol refusal", string(raw)) } case <-time.After(time.Second): t.Fatal("request left hanging") } }) } } func TestCodexAsyncQuestionDenial(t *testing.T) { l, s, w, frames := answerFixture(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() raw := fmt.Sprintf(`{"method":"item/completed","params":{"threadId":%q,"turnId":"provider-turn","item":{"id":"message","type":"agentMessage","delivery":"async","questions":[{"title":"Greeting"}]}}}`, s.session.ID) if err := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); err != nil { t.Fatal(err) } done := make(chan error, 1) go func() { done <- l.Respond(ctx, s.session, provider.Answer{RequestID: "async:message", TurnID: "local-turn", Behavior: "deny"}) }() select { case err := <-done: t.Fatal("async denial was not sent", err) case raw := <-w.sent: var call struct { ID json.RawMessage Method string Params struct { ExpectedTurnID string `json:"expectedTurnId"` Input []struct{ Text string } } } if json.Unmarshal(raw, &call) != nil || call.Method != "turn/steer" || call.Params.ExpectedTurnID != "provider-turn" || len(call.Params.Input) != 1 || !strings.Contains(call.Params.Input[0].Text, provider.ErrPolicy.Error()) { t.Fatal("wrong async refusal", string(raw)) } frames <- provider.Frame{Sequence: 100, Bytes: marshal(map[string]any{"id": call.ID, "result": map[string]string{"turnId": "provider-turn"}})} case <-ctx.Done(): t.Fatal("async refusal left waiting") } if err := <-done; err != nil { t.Fatal(err) } }