Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

21.7 KB
Raw Blame
require 'rails_helper'

RSpec.describe 'Api::V1::Accounts::Captain::Assistants', type: :request do
  let(:account) { create(:account) }
  let(:admin) { create(:user, account: account, role: :administrator) }
  let(:agent) { create(:user, account: account, role: :agent) }

  def json_response
    JSON.parse(response.body, symbolize_names: true)
  end

  describe 'GET /api/v1/accounts/{account.id}/captain/assistants' do
    context 'when it is an un-authenticated user' do
      it 'does not fetch assistants' do
        get "/api/v1/accounts/#{account.id}/captain/assistants",
            as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an agent' do
      it 'fetches assistants for the account' do
        create_list(:captain_assistant, 3, account: account)
        get "/api/v1/accounts/#{account.id}/captain/assistants",
            headers: agent.create_new_auth_token,
            as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:payload].length).to eq(3)
        expect(json_response[:meta]).to eq(
          { total_count: 3, page: 1 }
        )
      end
    end
  end

  describe 'GET /api/v1/accounts/{account.id}/captain/assistants/{id}' do
    let(:assistant) { create(:captain_assistant, account: account) }

    context 'when it is an un-authenticated user' do
      it 'does not fetch the assistant' do
        get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
            as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an agent' do
      it 'fetches the assistant' do
        get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
            headers: agent.create_new_auth_token,
            as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:id]).to eq(assistant.id)
      end
    end
  end

  describe 'POST /api/v1/accounts/{account.id}/captain/assistants' do
    let(:valid_attributes) do
      {
        assistant: {
          name: 'New Assistant',
          description: 'Assistant Description',
          response_guidelines: ['Be helpful', 'Be concise'],
          guardrails: ['No harmful content', 'Stay on topic'],
          config: {
            product_name: 'Chatwoot',
            feature_faq: true,
            feature_memory: false,
            feature_citation: true
          }
        }
      }
    end

    context 'when it is an un-authenticated user' do
      it 'does not create an assistant' do
        post "/api/v1/accounts/#{account.id}/captain/assistants",
             params: valid_attributes,
             as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an agent' do
      it 'does not create an assistant' do
        post "/api/v1/accounts/#{account.id}/captain/assistants",
             params: valid_attributes,
             headers: agent.create_new_auth_token,
             as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an admin' do
      it 'creates a new assistant' do
        expect do
          post "/api/v1/accounts/#{account.id}/captain/assistants",
               params: valid_attributes,
               headers: admin.create_new_auth_token,
               as: :json
        end.to change(Captain::Assistant, :count).by(1)

        expect(json_response[:name]).to eq('New Assistant')
        expect(json_response[:response_guidelines]).to eq(['Be helpful', 'Be concise'])
        expect(json_response[:guardrails]).to eq(['No harmful content', 'Stay on topic'])
        expect(json_response[:config][:product_name]).to eq('Chatwoot')
        expect(json_response[:config][:feature_citation]).to be(true)
        expect(response).to have_http_status(:success)
      end

      it 'creates an assistant with feature_citation disabled' do
        attributes_with_disabled_citation = valid_attributes.deep_dup
        attributes_with_disabled_citation[:assistant][:config][:feature_citation] = false

        expect do
          post "/api/v1/accounts/#{account.id}/captain/assistants",
               params: attributes_with_disabled_citation,
               headers: admin.create_new_auth_token,
               as: :json
        end.to change(Captain::Assistant, :count).by(1)

        expect(json_response[:config][:feature_citation]).to be(false)
        expect(response).to have_http_status(:success)
      end

      it 'stores evaluated mode on the assistant when captain_tasks is enabled' do
        account.enable_features!('captain_tasks')

        post "/api/v1/accounts/#{account.id}/captain/assistants",
             params: valid_attributes,
             headers: admin.create_new_auth_token,
             as: :json

        assistant = Captain::Assistant.find(json_response[:id])
        expect(assistant.config['auto_resolve_mode']).to eq('evaluated')
        expect(account.reload.settings).not_to have_key('captain_auto_resolve_mode')
      end

      it 'stores legacy mode on the assistant when captain_tasks is disabled' do
        account.disable_features!('captain_tasks')

        post "/api/v1/accounts/#{account.id}/captain/assistants",
             params: valid_attributes,
             headers: admin.create_new_auth_token,
             as: :json

        assistant = Captain::Assistant.find(json_response[:id])
        expect(assistant.config['auto_resolve_mode']).to eq('legacy')
        expect(account.reload.settings).not_to have_key('captain_auto_resolve_mode')
      end
    end
  end

  describe 'PATCH /api/v1/accounts/{account.id}/captain/assistants/{id}' do
    let(:assistant) { create(:captain_assistant, account: account) }
    let(:update_attributes) do
      {
        assistant: {
          name: 'Updated Assistant',
          response_guidelines: ['Updated guideline'],
          guardrails: ['Updated guardrail'],
          config: {
            feature_citation: false
          }
        }
      }
    end

    context 'when it is an un-authenticated user' do
      it 'does not update the assistant' do
        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: update_attributes,
              as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an agent' do
      it 'does not update the assistant' do
        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: update_attributes,
              headers: agent.create_new_auth_token,
              as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an admin' do
      it 'updates the assistant' do
        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: update_attributes,
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:name]).to eq('Updated Assistant')
        expect(json_response[:response_guidelines]).to eq(['Updated guideline'])
        expect(json_response[:guardrails]).to eq(['Updated guardrail'])
      end

      it 'updates only response_guidelines when only that is provided' do
        assistant.update!(response_guidelines: ['Original guideline'], guardrails: ['Original guardrail'])
        original_name = assistant.name

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: { assistant: { response_guidelines: ['New guideline only'] } },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:name]).to eq(original_name)
        expect(json_response[:response_guidelines]).to eq(['New guideline only'])
        expect(json_response[:guardrails]).to eq(['Original guardrail'])
      end

      it 'updates only guardrails when only that is provided' do
        assistant.update!(response_guidelines: ['Original guideline'], guardrails: ['Original guardrail'])
        original_name = assistant.name

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: { assistant: { guardrails: ['New guardrail only'] } },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:name]).to eq(original_name)
        expect(json_response[:response_guidelines]).to eq(['Original guideline'])
        expect(json_response[:guardrails]).to eq(['New guardrail only'])
      end

      it 'updates feature_citation config' do
        assistant.update!(config: { 'feature_citation' => true, 'auto_resolve_mode' => 'disabled' })

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: { assistant: { config: { feature_citation: false } } },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(assistant.reload.config).to include('feature_citation' => false, 'auto_resolve_mode' => 'disabled')
      end

      it 'updates auto_resolve_mode without replacing other config' do
        assistant.update!(config: { 'product_name' => 'Chatwoot', 'auto_resolve_mode' => 'legacy' })

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: { assistant: { config: { auto_resolve_mode: 'disabled' } } },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(assistant.reload.config).to include('product_name' => 'Chatwoot', 'auto_resolve_mode' => 'disabled')
      end

      it 'updates inactive conversation settings for Captain v2' do
        account.enable_features!('captain_integration')

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: {
                assistant: {
                  config: {
                    auto_resolve_mode: 'evaluated',
                    auto_resolve_after: 61,
                    send_inactivity_resolution_message: false,
                    resolution_message: 'Saved closing message'
                  }
                }
              },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        expect(json_response[:config]).to include(
          auto_resolve_mode: 'evaluated',
          auto_resolve_after: 60,
          send_inactivity_resolution_message: false,
          resolution_message: 'Saved closing message'
        )
      end

      it 'persists the nested audience condition tree' do
        create(:custom_attribute_definition, account: account, attribute_model: :contact_attribute,
                                             attribute_display_type: :text, attribute_key: 'plan_tier')
        audience = {
          operator: 'and',
          conditions: [
            { attribute_key: 'country_code', filter_operator: 'equal_to', values: ['US'] },
            { operator: 'or', conditions: [
              { attribute_key: 'plan_tier', filter_operator: 'equal_to', values: ['paid'] }
            ] }
          ]
        }

        patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
              params: { assistant: { config: { audience: audience } } },
              headers: admin.create_new_auth_token,
              as: :json

        expect(response).to have_http_status(:success)
        stored = assistant.reload.config['audience']
        expect(stored['operator']).to eq('and')
        expect(stored['conditions'].first['attribute_key']).to eq('country_code')
        expect(stored['conditions'].last['conditions'].first['values']).to eq(['paid'])
      end

      it 'rejects invalid audience attributes and operators' do
        invalid_audiences = [
          { attribute_key: 'missing_attribute', filter_operator: 'not_equal_to', values: ['known'] },
          { attribute_key: 'blocked', filter_operator: 'is_not_present', values: [] }
        ]

        invalid_audiences.each do |audience|
          patch "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
                params: { assistant: { config: { audience: audience } } },
                headers: admin.create_new_auth_token,
                as: :json

          expect(response).to have_http_status(:unprocessable_content)
        end
      end
    end
  end

  describe 'DELETE /api/v1/accounts/{account.id}/captain/assistants/{id}' do
    let!(:assistant) { create(:captain_assistant, account: account) }

    context 'when it is an un-authenticated user' do
      it 'does not delete the assistant' do
        delete "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
               as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an agent' do
      it 'delete the assistant' do
        delete "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
               headers: agent.create_new_auth_token,
               as: :json
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an admin' do
      it 'deletes the assistant' do
        expect do
          delete "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}",
                 headers: admin.create_new_auth_token,
                 as: :json
        end.to change(Captain::Assistant, :count).by(-1)

        expect(response).to have_http_status(:no_content)
      end
    end
  end

  describe 'GET /api/v1/accounts/{account.id}/captain/assistants/{id}/faq_stats' do
    let(:assistant) { create(:captain_assistant, account: account) }

    it 'returns approved FAQ, open suggestion, document counts and coverage' do
      create_list(:captain_assistant_response, 3, assistant: assistant, account: account, status: :approved)
      assistant.faq_suggestions.create!(question: 'How do I enable the feature?', answer: 'Turn it on in settings.')
      create_list(:captain_document, 2, assistant: assistant, account: account)

      get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/faq_stats",
          headers: admin.create_new_auth_token,
          as: :json

      expect(response).to have_http_status(:success)
      expect(json_response).to eq(approved: 3, faqs: 3, suggestions: 1, documents: 2, coverage: 75)
    end

    it 'returns zero coverage when there are no FAQs or suggestions' do
      get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/faq_stats",
          headers: admin.create_new_auth_token,
          as: :json

      expect(response).to have_http_status(:success)
      expect(json_response).to include(approved: 0, faqs: 0, suggestions: 0, coverage: 0)
    end

    it 'counts only suggestions backed by conversations the agent can access' do
      accessible_inbox = create(:inbox, account: account)
      hidden_inbox = create(:inbox, account: account)
      create(:inbox_member, user: agent, inbox: accessible_inbox)
      create(:captain_assistant_response, assistant: assistant, account: account, status: :approved)

      accessible_suggestion = assistant.faq_suggestions.create!(question: 'Visible question', answer: 'Visible answer')
      accessible_suggestion.observations.create!(
        conversation: create(:conversation, account: account, inbox: accessible_inbox),
        generated_question: accessible_suggestion.question,
        generated_answer: accessible_suggestion.answer,
        language: accessible_suggestion.language
      )
      hidden_suggestion = assistant.faq_suggestions.create!(question: 'Hidden question', answer: 'Hidden answer')
      hidden_suggestion.observations.create!(
        conversation: create(:conversation, account: account, inbox: hidden_inbox),
        generated_question: hidden_suggestion.question,
        generated_answer: hidden_suggestion.answer,
        language: hidden_suggestion.language
      )

      get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/faq_stats",
          headers: agent.create_new_auth_token,
          as: :json

      expect(response).to have_http_status(:success)
      expect(json_response).to include(approved: 1, suggestions: 1, coverage: 50)
    end
  end

  describe 'GET /api/v1/accounts/{account.id}/captain/assistants/{id}/summary' do
    let(:assistant) { create(:captain_assistant, account: account) }
    let(:alice) { create(:user, account: account, role: :administrator, name: 'Alice Adams') }
    let(:bob) { create(:user, account: account, role: :administrator, name: 'Bob Brown') }
    let(:summary_service) { instance_double(Captain::OverviewSummaryService) }
    let(:summary_stats) do
      {
        conversations_handled: { current: 42 },
        hours_saved: { current: 12 },
        auto_resolution_rate: { current: 65.0, trend: 5.0 },
        handoff_rate: { current: 20.0, trend: -2.0 },
        reopen_rate: { current: 5.0, trend: -1.0 },
        knowledge: { coverage: 80, approved: 8, documents: 3 }
      }
    end

    def get_summary(user)
      get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/summary",
          params: { range: '30', stats: summary_stats },
          headers: user.create_new_auth_token,
          as: :json
    end

    before do
      # Test env uses a null store; swap in a real store so caching behaviour is observable.
      allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::MemoryStore.new)
      allow(Captain::OverviewSummaryService).to receive(:new).and_return(summary_service)
    end

    it 'caches the summary per viewer so one user never receives another user\'s greeting' do
      allow(summary_service).to receive(:perform).and_return({ message: 'Hi Alice' })
      expect(Captain::AssistantStatsBuilder).not_to receive(:new)

      get_summary(alice)
      get_summary(alice) # served from Alice's cache, no regeneration
      get_summary(bob)   # distinct cache key, regenerated for Bob

      expect(response).to have_http_status(:success)
      expect(Captain::OverviewSummaryService).to have_received(:new).twice
      expect(Captain::OverviewSummaryService).to have_received(:new).with(hash_including(stats: summary_stats)).twice
    end

    it 'does not cache failures so a transient error is retried' do
      allow(summary_service).to receive(:perform).and_return({ error: 'LLM unavailable' })

      get_summary(alice)
      get_summary(alice)

      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response[:error]).to eq('LLM unavailable')
      expect(Captain::OverviewSummaryService).to have_received(:new).twice
    end
  end

  describe 'POST /api/v1/accounts/{account.id}/captain/assistants/{id}/playground' do
    let(:assistant) { create(:captain_assistant, account: account) }
    let(:valid_params) do
      {
        request_id: 'playground-request-1',
        message_content: 'Hello assistant',
        message_history: [
          { role: 'user', content: 'Previous message' },
          { role: 'assistant', content: 'Previous response', agent_name: 'billing_scenario' }
        ]
      }
    end

    context 'when it is an un-authenticated user' do
      it 'returns unauthorized' do
        post "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/playground",
             params: valid_params,
             as: :json

        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when it is an authenticated user' do
      it 'queues the playground response and returns immediately' do
        expect do
          post "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/playground",
               params: valid_params,
               headers: agent.create_new_auth_token,
               as: :json
        end.to have_enqueued_job(Captain::Playground::ResponseJob).with(
          assistant: assistant,
          user: agent,
          request_id: valid_params[:request_id],
          request: {
            message_content: valid_params[:message_content],
            message_history: valid_params[:message_history],
            playground_config: nil,
            playground_config_supplied: false
          }
        )

        expect(response).to have_http_status(:accepted)
        expect(json_response[:request_id]).to eq(valid_params[:request_id])
      end

      it 'generates a request id when the client does not provide one' do
        post "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/playground",
             params: valid_params.except(:request_id),
             headers: agent.create_new_auth_token,
             as: :json

        expect(response).to have_http_status(:accepted)
        expect(json_response[:request_id]).to be_present
      end

      it 'passes the ephemeral playground configuration to the job' do
        enhanced_params = valid_params.merge(
          playground_config: {
            scenario_ids: [],
            temporary_scenarios: [],
            response_guidelines: ['Be concise'],
            guardrails: [],
            knowledge_text: 'Refunds take five days.',
            ignored: 'do not enqueue'
          }
        )

        expect do
          post "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/playground",
               params: enhanced_params,
               headers: agent.create_new_auth_token,
               as: :json
        end.to have_enqueued_job(Captain::Playground::ResponseJob).with(
          hash_including(
            request: hash_including(
              playground_config: enhanced_params[:playground_config].except(:ignored).stringify_keys,
              playground_config_supplied: true
            )
          )
        )
      end
    end
  end
end