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

# Multi-App Workflow Example

> Complete shopping journey with context handoff between apps

# Multi-App Workflow: Shopping Journey with Context Handoff

This example demonstrates SuperModel's ability to create seamless user experiences across multiple specialized UI apps, with context flowing intelligently between each step of the journey.

## Scenario Overview

**User Goal**: "Buy the best wireless headphones for my home office setup"

**Journey**: Product Research → Bundle Building → Checkout

**Key Innovation**: Each app builds on context from previous interactions, creating a personalized, continuous experience.

## App 1: Product Research & Selection

### Step 1: Initial Request Routing

**User Input**: "Find me wireless headphones for working from home"

**Routing via MCP Sampling**:

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [{
      "role": "user",
      "content": {
        "type": "text",
        "text": "User wants wireless headphones for home office. Available apps:\n\n- product-search-ui: Product discovery with reviews and filters\n- comparison-ui: Side-by-side product comparison\n- bundle-builder-ui: Create product bundles and packages\n- data-viz-ui: Analytics and charts\n\nWhich app should handle this request? Consider the user's intent."
      }
    }],
    "systemPrompt": "You are a routing assistant. Return JSON: {\"app\": \"app-name\", \"context\": {...}}"
  }
}
```

**Client LLM Response**:

```json
{
  "role": "assistant",
  "content": {
    "type": "text",
    "text": "{\"app\": \"product-search-ui\", \"context\": {\"use_case\": \"home_office\", \"priority\": [\"comfort\", \"noise_canceling\"], \"environment\": \"work_from_home\"}}"
  }
}
```

### Step 2: Product Search UI Generation

**UI Generation via MCP Sampling**:

<CodeGroup>
  ```json Sampling Request
  {
    "method": "sampling/createMessage",
    "params": {
      "messages": [{
        "role": "user",
        "content": {
          "type": "text", 
          "text": "Create a product search interface for wireless headphones. Context:\n\n- Use case: home office/work from home\n- User priorities: comfort, noise canceling\n- Budget range: Under $300\n\nRequirements:\n- Product grid with images and key specs\n- Filters for comfort, noise canceling, price\n- Sort by ratings, price, comfort reviews\n- Quick compare functionality\n- 'Build Complete Setup' action for selected items\n\nProduct data: [\n  {\"id\": \"sony-wh1000xm5\", \"name\": \"Sony WH-1000XM5\", \"price\": 299, \"comfort_rating\": 4.8, \"noise_canceling\": 4.9},\n  {\"id\": \"bose-qc45\", \"name\": \"Bose QuietComfort 45\", \"price\": 279, \"comfort_rating\": 4.7, \"noise_canceling\": 4.8}\n]\n\nUse AG-UI event system for all interactions."
        }
      }],
      "systemPrompt": "Generate AG-UI React component optimized for the work-from-home use case. Include proper event handlers."
    }
  }
  ```

  ```jsx Generated Component
  function ProductSearchUI({ products, context, onEvent }) {
    const [selectedProducts, setSelectedProducts] = useState([]);
    const [filters, setFilters] = useState({
      maxPrice: context.budget || 300,
      minComfort: 4.0,
      minNoiseCanceling: 4.0
    });

    const handleAddToCompare = (product) => {
      setSelectedProducts([...selectedProducts, product]);
      
      // AG-UI event
      onEvent({
        type: 'TOOL_CALL',
        payload: {
          action: 'product_selected',
          product: product,
          context: {
            ...context,
            selected_products: [...selectedProducts, product],
            user_interaction: 'comparing_options'
          }
        }
      });
    };

    const handleBuildSetup = () => {
      // AG-UI event for app transition
      onEvent({
        type: 'INTENT',
        payload: {
          intent: 'build_complete_setup',
          context: {
            selected_products: selectedProducts,
            user_priorities: context.priority,
            use_case: context.use_case,
            budget_remaining: context.budget - selectedProducts.reduce((sum, p) => sum + p.price, 0)
          }
        }
      });
    };

    return (
      <div className="product-search">
        <div className="filters">
          <h3>Perfect for Work From Home</h3>
          {/* Comfort and noise canceling focused filters */}
        </div>
        
        <div className="product-grid">
          {filteredProducts.map(product => (
            <ProductCard 
              key={product.id}
              product={product}
              onAddToCompare={handleAddToCompare}
              highlighted={context.priority.includes('comfort') && product.comfort_rating > 4.5}
            />
          ))}
        </div>
        
        {selectedProducts.length > 0 && (
          <div className="selection-actions">
            <button onClick={handleBuildSetup} className="primary">
              Build Complete Office Setup ({selectedProducts.length} items)
            </button>
          </div>
        )}
      </div>
    );
  }
  ```
</CodeGroup>

### Step 3: User Interaction & Context Capture

**User Actions**:

1. Applies comfort filter (4.5+ rating)
2. Sorts by noise canceling performance
3. Selects Sony WH-1000XM5 and Bose QC45 for comparison
4. Clicks "Build Complete Office Setup"

**Captured Context**:

```json
{
  "selected_products": ["sony-wh1000xm5", "bose-qc45"],
  "user_priorities": ["comfort", "noise_canceling"], 
  "budget": 300,
  "use_case": "home_office",
  "interaction_pattern": "thorough_comparison",
  "preferences": {
    "values_comfort": true,
    "noise_sensitive": true,
    "budget_conscious": true
  }
}
```

## App 2: Bundle Building with Context

### Step 4: Context-Aware Routing

**Trigger**: User clicked "Build Complete Office Setup"

**Context-Aware Routing via MCP Sampling**:

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [{
      "role": "user", 
      "content": {
        "type": "text",
        "text": "User wants to build complete office setup. Previous context:\n\n{\"selected_products\": [\"sony-wh1000xm5\", \"bose-qc45\"], \"user_priorities\": [\"comfort\", \"noise_canceling\"], \"budget\": 300, \"use_case\": \"home_office\", \"preferences\": {\"values_comfort\": true}}\n\nUser action: 'Build Complete Office Setup'\n\nAvailable apps:\n- bundle-builder-ui: Create product bundles with accessories\n- comparison-ui: Detailed side-by-side comparison  \n- checkout-ui: Complete purchase process\n- recommendations-ui: AI-powered product suggestions\n\nWhich app should handle this next step? Consider the user journey."
      }
    }],
    "systemPrompt": "Consider user intent and context. Return optimal next app and enriched context."
  }
}
```

**Routing Response**:

```json
{
  "app": "bundle-builder-ui",
  "context": {
    "base_products": ["sony-wh1000xm5", "bose-qc45"],
    "theme": "home_office_productivity", 
    "budget_remaining": 200,
    "focus": "comfort_and_accessories",
    "next_likely_action": "checkout"
  }
}
```

### Step 5: Bundle Builder UI Generation

**Context-Aware UI Generation**:

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [{
      "role": "user",
      "content": {
        "type": "text",
        "text": "Generate bundle builder UI for home office productivity setup. User context:\n\n- Already selected: Sony WH-1000XM5 ($299), Bose QC45 ($279)\n- Priorities: comfort, noise canceling\n- Use case: work from home\n- Budget: $300 total\n- User values comfort and thorough comparison\n\nCreate interface to:\n1. Choose between the two selected headphones (with context-aware comparison)\n2. Suggest complementary office accessories: desk stand, premium cables, carrying case\n3. Show bundle pricing with discounts\n4. Highlight comfort-focused accessories based on user priorities\n5. Quick checkout flow\n\nPersonalization: Emphasize comfort and WFH productivity based on previous interactions."
      }
    }],
    "systemPrompt": "Generate AG-UI bundle builder that leverages user context for personalized recommendations."
  }
}
```

**Generated Bundle UI Features**:

<AccordionGroup>
  <Accordion title="Context-Aware Product Comparison">
    ```jsx
    function ContextualComparison({ products, userContext }) {
      return (
        <div className="comparison">
          <h3>Based on your comfort priority:</h3>
          <div className="recommendation">
            <ProductCard product={products.find(p => p.id === 'sony-wh1000xm5')}>
              <Badge variant="recommended">Best for Comfort</Badge>
              <p>Higher comfort rating (4.8) matches your priority</p>
            </ProductCard>
          </div>
        </div>
      );
    }
    ```
  </Accordion>

  <Accordion title="Personalized Accessory Suggestions">
    ```jsx
    function PersonalizedAccessories({ userContext }) {
      const suggestions = userContext.values_comfort ? [
        { name: "Ergonomic Headphone Stand", reason: "Matches your comfort focus" },
        { name: "Premium Memory Foam Ear Cushions", reason: "Extra comfort for long work sessions" }
      ] : defaultAccessories;
      
      return (
        <div className="accessories">
          <h3>Perfect for Your Home Office</h3>
          {suggestions.map(item => (
            <AccessoryCard key={item.name} item={item} highlighted={true} />
          ))}
        </div>
      );
    }
    ```
  </Accordion>

  <Accordion title="Bundle Optimization">
    ```jsx
    function BundleOptimizer({ selectedItems, budget, userContext }) {
      const optimizedBundle = useMemo(() => {
        // Context-aware bundle optimization
        if (userContext.budget_conscious) {
          return optimizeForValue(selectedItems, budget);
        }
        if (userContext.values_comfort) {
          return optimizeForComfort(selectedItems, budget);
        }
        return defaultOptimization(selectedItems, budget);
      }, [selectedItems, budget, userContext]);
      
      return <BundleDisplay bundle={optimizedBundle} />;
    }
    ```
  </Accordion>
</AccordionGroup>

### Step 6: User Completes Bundle

**User Actions**:

1. Selects Sony WH-1000XM5 (based on comfort recommendation)
2. Adds ergonomic desk stand (\$25)
3. Adds premium carrying case (\$35)
4. Reviews total: $359 (bundle discount applied: -$20)
5. Clicks "Proceed to Checkout"

**Final Context**:

```json
{
  "final_bundle": {
    "headphones": "sony-wh1000xm5",
    "accessories": ["ergonomic-stand", "premium-case"],
    "total": 339,
    "discount_applied": 20
  },
  "user_journey": {
    "started_with": "product_research",
    "decision_factors": ["comfort", "noise_canceling"],
    "bundle_theme": "home_office_productivity"
  },
  "next_action": "checkout",
  "personalization_data": {
    "comfort_focused": true,
    "thorough_researcher": true,
    "values_bundles": true
  }
}
```

## Benefits of Context Handoff

<CardGroup cols={2}>
  <Card title="Seamless Experience" icon="flow">
    User never restarts their journey. Each app builds on previous context, creating a natural flow.
  </Card>

  <Card title="Personalized Recommendations" icon="user-check">
    Bundle builder emphasizes comfort accessories because the user prioritized comfort in product search.
  </Card>

  <Card title="Intelligent Routing" icon="brain">
    System understands user intent and routes to bundle builder instead of direct checkout.
  </Card>

  <Card title="Zero Server Costs" icon="dollar-sign">
    Entire multi-app journey uses zero server inference. All decisions made via MCP sampling.
  </Card>
</CardGroup>

## Technical Implementation

### Context Flow Management

```typescript
class ContextManager {
  private context: UserContext = {};
  
  async routeWithContext(userAction: string, availableApps: App[]): Promise<RoutingDecision> {
    const routingResponse = await this.gateway.sample({
      messages: [{
        role: "user",
        content: {
          type: "text",
          text: `Previous context: ${JSON.stringify(this.context)}\n\nUser action: "${userAction}"\n\nAvailable apps: ${availableApps.map(a => a.description).join('\n')}\n\nWhich app should handle this next?`
        }
      }],
      systemPrompt: "Consider user journey and context. Return next app and enriched context."
    });
    
    const decision = JSON.parse(routingResponse.content.text);
    this.context = { ...this.context, ...decision.context };
    
    return decision;
  }
}
```

### App-to-App Context Enrichment

```typescript
interface AppContext {
  // Previous app context
  inherited: Record<string, any>;
  
  // Current app additions
  current: Record<string, any>;
  
  // Predictions for next apps
  predictions: {
    likely_next_app: string;
    suggested_context: Record<string, any>;
  };
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Context Handoff Deep Dive" icon="arrow-right-arrow-left" href="/examples/context-handoff">
    Learn the technical details of context preservation and enrichment.
  </Card>

  <Card title="Gateway Pattern" icon="route" href="/concepts/gateway-pattern">
    Understand how SuperModel orchestrates multi-app workflows.
  </Card>
</CardGroup>
