> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cfosilvia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Scenario email optional implementation

# Scenario Email Optional Implementation

## Overview

This document describes the implementation that makes email notifications optional for scenarios based on their source (user-created vs radar-generated).

## Problem Statement

Previously, ALL completed scenarios would trigger email notifications to users. This was problematic for radar-generated scenarios, which are automated background processes that shouldn't spam users with emails.

## Solution Architecture

### Flow Diagram

```
User Creates Scenario (via UI)
    ↓ source: 'user'
    ↓
Radar Creates Scenario (automated)
    ↓ source: 'radar'
    ↓
    ├─→ Next.js API Tool (createScenario)
    │       ↓
    ├─→ Lambda API Handler
    │   - Accepts source parameter
    │   - Stores in DynamoDB
    │   - Passes through SQS
    │       ↓
    └─→ Lambda Agent Processor
        - Processes scenario
        - Checks source field
        - If source == 'user': ✅ Send email
        - If source == 'radar': ❌ Skip email
```

## Changes Made

### 1. Frontend - Chat Tools (`app/api/chat/tools.ts`)

**Change**: Added `source` parameter to createScenario tool

```typescript theme={null}
inputSchema: z.object({
  question: z.string().describe('...'),
  source: z
    .enum(['user', 'radar'])
    .optional()
    .default('user')
    .describe('Source of the scenario: "user" for user-created, "radar" for automated radar generation'),
}),
execute: async ({ question, source = 'user' }) => {
  // Pass source to API
  const response = await axios.post(
    `${apiUrl}/consultations`,
    { question, source },
    { headers: { 'X-User-Id': clerkId } }
  );
}
```

**Backward Compatibility**: Defaults to `'user'` if not specified

### 2. Radar Feed Directive (`app/api/radar/silvia-simulation/route.ts`)

**Change**: Updated system directive to instruct LLM to pass source

```typescript theme={null}
**CRITICAL FOR SCENARIO ANALYSIS:**
When using the createScenario tool, ALWAYS pass source: 'radar' to indicate this is an automated radar-generated scenario.
This prevents sending email notifications for automated scenarios.
Example: createScenario({ question: "...", source: "radar" })
```

### 3. Lambda API Handler (`aws/scenarios/lambdas/api/handler.py`)

**Changes**:

1. Accept source parameter from request body
2. Store in DynamoDB consultation item
3. Pass through SQS message

```python theme={null}
# Get optional source parameter (defaults to 'user' for backward compatibility)
source = body.get("source", "user")

consultation = {
    "userId": user_id,
    "consultationId": consultation_id,
    "title": title,
    "question": question,
    "source": source,  # NEW FIELD
    "status": "pending",
    "createdAt": now,
    "updatedAt": now,
}

# Pass to SQS
sqs.send_message(
    QueueUrl=queue_url,
    MessageBody=json.dumps({
        "consultationId": consultation_id,
        "userId": user_id,
        "question": question,
        "title": title,
        "source": source,  # PASS THROUGH
    })
)
```

**Backward Compatibility**: Defaults to `'user'` if not provided

### 4. Lambda Agent Processor (`aws/scenarios/lambdas/agent_processor/handler.py`)

**Change**: Conditionally send emails based on source

```python theme={null}
def process_consultation(message):
    consultation_id = message["consultationId"]
    user_id = message["userId"]
    question = message["question"]
    source = message.get("source", "user")  # Default to 'user'
    
    # ... process scenario ...
    
    # Only send email if NOT from radar
    if source != "radar":
        send_completion_email(
            user_id=user_id,
            consultation_id=consultation_id,
            title=message.get("title", "Your Research Report"),
            question=question,
            chart_count=len(all_charts)
        )
    else:
        print(f"[process_consultation] Skipping email notification for radar-generated scenario {consultation_id}")
```

**Backward Compatibility**: Defaults to `'user'` (sends email) if not specified

## Testing Checklist

### Manual Testing

* [ ] Create user scenario from UI → Should receive email
* [ ] Create user scenario from chat → Should receive email
* [ ] Radar generates scenario → Should NOT receive email
* [ ] Check DynamoDB to verify source field is stored
* [ ] Check CloudWatch logs for email skip message

### Edge Cases

* [ ] Scenario created before this change (no source field) → Should receive email (backward compatible)
* [ ] Scenario with invalid source value → Should receive email (defaults to 'user')
* [ ] Multiple radar scenarios generated → Should not receive multiple emails

## Deployment Notes

### Prerequisites

* No database migrations needed (DynamoDB is schemaless)
* No infrastructure changes needed
* Fully backward compatible

### Deployment Order

1. Deploy Lambda functions (API handler + Agent processor)
2. Deploy Next.js application (frontend changes)
3. No downtime required

### Rollback Plan

If issues occur:

1. Revert Lambda deployments
2. Revert Next.js deployment
3. All scenarios will default to sending emails (safe fallback)

## Monitoring

### Key Metrics

* Email send rate (should decrease after deployment)
* Radar scenario completion rate
* User scenario completion rate
* Email API success rate

### CloudWatch Logs

Search for:

* `"Skipping email notification for radar-generated scenario"` - Radar scenarios
* `"Sending email notification for consultation"` - User scenarios

## Benefits

1. **Better UX**: Users no longer receive spam emails from automated radar scenarios
2. **Cost Savings**: Fewer emails sent = lower email service costs
3. **Clean Separation**: Clear distinction between user-initiated and automated scenarios
4. **Extensible**: Easy to add more source types in the future (e.g., 'scheduled', 'webhook')
5. **Backward Compatible**: Existing scenarios and workflows unchanged

## Future Enhancements

Potential improvements:

* Add email preferences per source type in user settings
* Track source in analytics/metrics
* Add source filter in scenarios UI
* Support batch email digest for radar scenarios


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.