improvement(response): removed nested response block output, add docs for webhook block, styling improvements for subblocks (#2700)

* improvement(response): removed nested response block output, add docs for webhook block, styling improvements for subblocks

* remove outdated block docs

* updated docs

* remove outdated tests
This commit is contained in:
Waleed
2026-01-06 19:43:25 -08:00
committed by GitHub
parent e5bd5e4474
commit 5145ce1684
28 changed files with 792 additions and 1418 deletions

View File

@@ -1,231 +0,0 @@
---
title: Webhook
description: Empfangen Sie Webhooks von jedem Dienst durch Konfiguration eines
benutzerdefinierten Webhooks.
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
import { Image } from '@/components/ui/image'
<BlockInfoCard
type="generic_webhook"
color="#10B981"
/>
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Webhook-Block-Konfiguration"
width={500}
height={400}
className="my-6"
/>
</div>
## Übersicht
Der generische Webhook-Block ermöglicht den Empfang von Webhooks von jedem externen Dienst. Dies ist ein flexibler Trigger, der jede JSON-Nutzlast verarbeiten kann und sich daher ideal für die Integration mit Diensten eignet, die keinen dedizierten Sim-Block haben.
## Grundlegende Verwendung
### Einfacher Durchleitungsmodus
Ohne ein definiertes Eingabeformat leitet der Webhook den gesamten Anforderungstext unverändert weiter:
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Test webhook trigger",
"data": {
"key": "value"
}
}'
```
Greifen Sie in nachgelagerten Blöcken auf die Daten zu mit:
- `<webhook1.message>` → "Test webhook trigger"
- `<webhook1.data.key>` → "value"
### Strukturiertes Eingabeformat (optional)
Definieren Sie ein Eingabeschema, um typisierte Felder zu erhalten und erweiterte Funktionen wie Datei-Uploads zu aktivieren:
**Konfiguration des Eingabeformats:**
```json
[
{ "name": "message", "type": "string" },
{ "name": "priority", "type": "number" },
{ "name": "documents", "type": "files" }
]
```
**Webhook-Anfrage:**
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Invoice submission",
"priority": 1,
"documents": [
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "invoice.pdf",
"mime": "application/pdf"
}
]
}'
```
## Datei-Uploads
### Unterstützte Dateiformate
Der Webhook unterstützt zwei Dateieingabeformate:
#### 1. Base64-kodierte Dateien
Zum direkten Hochladen von Dateiinhalten:
```json
{
"documents": [
{
"type": "file",
"data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...",
"name": "screenshot.png",
"mime": "image/png"
}
]
}
```
- **Maximale Größe**: 20MB pro Datei
- **Format**: Standard-Daten-URL mit Base64-Kodierung
- **Speicherung**: Dateien werden in sicheren Ausführungsspeicher hochgeladen
#### 2. URL-Referenzen
Zum Übergeben vorhandener Datei-URLs:
```json
{
"documents": [
{
"type": "url",
"data": "https://example.com/files/document.pdf",
"name": "document.pdf",
"mime": "application/pdf"
}
]
}
```
### Zugriff auf Dateien in nachgelagerten Blöcken
Dateien werden in `UserFile`Objekte mit den folgenden Eigenschaften verarbeitet:
```typescript
{
id: string, // Unique file identifier
name: string, // Original filename
url: string, // Presigned URL (valid for 5 minutes)
size: number, // File size in bytes
type: string, // MIME type
key: string, // Storage key
uploadedAt: string, // ISO timestamp
expiresAt: string // ISO timestamp (5 minutes)
}
```
**Zugriff in Blöcken:**
- `<webhook1.documents[0].url>` → Download-URL
- `<webhook1.documents[0].name>` → "invoice.pdf"
- `<webhook1.documents[0].size>` → 524288
- `<webhook1.documents[0].type>` → "application/pdf"
### Vollständiges Datei-Upload-Beispiel
```bash
# Create a base64-encoded file
echo "Hello World" | base64
# SGVsbG8gV29ybGQK
# Send webhook with file
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"subject": "Document for review",
"attachments": [
{
"type": "file",
"data": "data:text/plain;base64,SGVsbG8gV29ybGQK",
"name": "sample.txt",
"mime": "text/plain"
}
]
}'
```
## Authentifizierung
### Authentifizierung konfigurieren (Optional)
In der Webhook-Konfiguration:
1. Aktiviere "Authentifizierung erforderlich"
2. Setze einen geheimen Token
3. Wähle den Header-Typ:
- **Benutzerdefinierter Header**: `X-Sim-Secret: your-token`
- **Authorization Bearer**: `Authorization: Bearer your-token`
### Verwendung der Authentifizierung
```bash
# With custom header
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret-token" \
-d '{"message": "Authenticated request"}'
# With bearer token
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-secret-token" \
-d '{"message": "Authenticated request"}'
```
## Best Practices
1. **Eingabeformat für Struktur verwenden**: Definiere ein Eingabeformat, wenn du das erwartete Schema kennst. Dies bietet:
- Typvalidierung
- Bessere Autovervollständigung im Editor
- Datei-Upload-Funktionen
2. **Authentifizierung**: Aktiviere immer die Authentifizierung für Produktions-Webhooks, um unbefugten Zugriff zu verhindern.
3. **Dateigrößenbeschränkungen**: Halte Dateien unter 20 MB. Verwende für größere Dateien URL-Referenzen.
4. **Dateiablauf**: Heruntergeladene Dateien haben URLs mit einer Gültigkeit von 5 Minuten. Verarbeite sie umgehend oder speichere sie an anderer Stelle, wenn sie länger benötigt werden.
5. **Fehlerbehandlung**: Die Webhook-Verarbeitung erfolgt asynchron. Überprüfe die Ausführungsprotokolle auf Fehler.
6. **Testen**: Verwende die Schaltfläche "Webhook testen" im Editor, um deine Konfiguration vor der Bereitstellung zu validieren.
## Anwendungsfälle
- **Formularübermittlungen**: Empfange Daten von benutzerdefinierten Formularen mit Datei-Uploads
- **Drittanbieter-Integrationen**: Verbinde mit Diensten, die Webhooks senden (Stripe, GitHub usw.)
- **Dokumentenverarbeitung**: Akzeptiere Dokumente von externen Systemen zur Verarbeitung
- **Ereignisbenachrichtigungen**: Empfange Ereignisdaten aus verschiedenen Quellen
- **Benutzerdefinierte APIs**: Erstelle benutzerdefinierte API-Endpunkte für deine Anwendungen
## Hinweise
- Kategorie: `triggers`
- Typ: `generic_webhook`
- **Dateiunterstützung**: Verfügbar über Eingabeformat-Konfiguration
- **Maximale Dateigröße**: 20 MB pro Datei

View File

@@ -15,7 +15,7 @@ Der generische Webhook-Block erstellt einen flexiblen Endpunkt, der beliebige Pa
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="Generische Webhook-Konfiguration"
width={500}
height={400}

View File

@@ -14,6 +14,7 @@
"router",
"variables",
"wait",
"webhook",
"workflow"
]
}

View File

@@ -0,0 +1,87 @@
---
title: Webhook
---
import { Callout } from 'fumadocs-ui/components/callout'
import { Image } from '@/components/ui/image'
The Webhook block sends HTTP POST requests to external webhook endpoints with automatic webhook headers and optional HMAC signing.
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Webhook Block"
width={500}
height={400}
className="my-6"
/>
</div>
## Configuration
### Webhook URL
The destination endpoint for your webhook request. Supports both static URLs and dynamic values from other blocks.
### Payload
JSON data to send in the request body. Use the AI wand to generate payloads or reference workflow variables:
```json
{
"event": "workflow.completed",
"data": {
"result": "<agent.content>",
"timestamp": "<function.result>"
}
}
```
### Signing Secret
Optional secret for HMAC-SHA256 payload signing. When provided, adds an `X-Webhook-Signature` header:
```
X-Webhook-Signature: t=1704067200000,v1=5d41402abc4b2a76b9719d911017c592...
```
To verify signatures, compute `HMAC-SHA256(secret, "${timestamp}.${body}")` and compare with the `v1` value.
### Additional Headers
Custom key-value headers to include with the request. These override any automatic headers with the same name.
## Automatic Headers
Every request includes these headers automatically:
| Header | Description |
|--------|-------------|
| `Content-Type` | `application/json` |
| `X-Webhook-Timestamp` | Unix timestamp in milliseconds |
| `X-Delivery-ID` | Unique UUID for this delivery |
| `Idempotency-Key` | Same as `X-Delivery-ID` for deduplication |
## Outputs
| Output | Type | Description |
|--------|------|-------------|
| `data` | json | Response body from the endpoint |
| `status` | number | HTTP status code |
| `headers` | object | Response headers |
## Example Use Cases
**Notify external services** - Send workflow results to Slack, Discord, or custom endpoints
```
Agent → Function (format) → Webhook (notify)
```
**Trigger external workflows** - Start processes in other systems when conditions are met
```
Condition (check) → Webhook (trigger) → Response
```
<Callout>
The Webhook block always uses POST. For other HTTP methods or more control, use the [API block](/blocks/api).
</Callout>

View File

@@ -15,7 +15,7 @@ The Generic Webhook block creates a flexible endpoint that can receive any paylo
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="Generic Webhook Configuration"
width={500}
height={400}

View File

@@ -1,230 +0,0 @@
---
title: Webhook
description: Recibe webhooks de cualquier servicio configurando un webhook personalizado.
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
import { Image } from '@/components/ui/image'
<BlockInfoCard
type="generic_webhook"
color="#10B981"
/>
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Configuración del bloque Webhook"
width={500}
height={400}
className="my-6"
/>
</div>
## Descripción general
El bloque Webhook genérico te permite recibir webhooks desde cualquier servicio externo. Este es un disparador flexible que puede manejar cualquier carga útil JSON, lo que lo hace ideal para integrarse con servicios que no tienen un bloque Sim dedicado.
## Uso básico
### Modo de paso simple
Sin definir un formato de entrada, el webhook transmite todo el cuerpo de la solicitud tal como está:
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Test webhook trigger",
"data": {
"key": "value"
}
}'
```
Accede a los datos en bloques posteriores usando:
- `<webhook1.message>` → "Test webhook trigger"
- `<webhook1.data.key>` → "value"
### Formato de entrada estructurado (opcional)
Define un esquema de entrada para obtener campos tipados y habilitar funciones avanzadas como cargas de archivos:
**Configuración del formato de entrada:**
```json
[
{ "name": "message", "type": "string" },
{ "name": "priority", "type": "number" },
{ "name": "documents", "type": "files" }
]
```
**Solicitud de webhook:**
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Invoice submission",
"priority": 1,
"documents": [
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "invoice.pdf",
"mime": "application/pdf"
}
]
}'
```
## Cargas de archivos
### Formatos de archivo compatibles
El webhook admite dos formatos de entrada de archivos:
#### 1. Archivos codificados en Base64
Para cargar contenido de archivos directamente:
```json
{
"documents": [
{
"type": "file",
"data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...",
"name": "screenshot.png",
"mime": "image/png"
}
]
}
```
- **Tamaño máximo**: 20MB por archivo
- **Formato**: URL de datos estándar con codificación base64
- **Almacenamiento**: Los archivos se cargan en almacenamiento seguro de ejecución
#### 2. Referencias URL
Para pasar URLs de archivos existentes:
```json
{
"documents": [
{
"type": "url",
"data": "https://example.com/files/document.pdf",
"name": "document.pdf",
"mime": "application/pdf"
}
]
}
```
### Acceso a archivos en bloques posteriores
Los archivos se procesan en objetos `UserFile` con las siguientes propiedades:
```typescript
{
id: string, // Unique file identifier
name: string, // Original filename
url: string, // Presigned URL (valid for 5 minutes)
size: number, // File size in bytes
type: string, // MIME type
key: string, // Storage key
uploadedAt: string, // ISO timestamp
expiresAt: string // ISO timestamp (5 minutes)
}
```
**Acceso en bloques:**
- `<webhook1.documents[0].url>` → URL de descarga
- `<webhook1.documents[0].name>` → "invoice.pdf"
- `<webhook1.documents[0].size>` → 524288
- `<webhook1.documents[0].type>` → "application/pdf"
### Ejemplo completo de carga de archivos
```bash
# Create a base64-encoded file
echo "Hello World" | base64
# SGVsbG8gV29ybGQK
# Send webhook with file
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"subject": "Document for review",
"attachments": [
{
"type": "file",
"data": "data:text/plain;base64,SGVsbG8gV29ybGQK",
"name": "sample.txt",
"mime": "text/plain"
}
]
}'
```
## Autenticación
### Configurar autenticación (opcional)
En la configuración del webhook:
1. Habilitar "Requerir autenticación"
2. Establecer un token secreto
3. Elegir tipo de encabezado:
- **Encabezado personalizado**: `X-Sim-Secret: your-token`
- **Autorización Bearer**: `Authorization: Bearer your-token`
### Uso de la autenticación
```bash
# With custom header
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret-token" \
-d '{"message": "Authenticated request"}'
# With bearer token
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-secret-token" \
-d '{"message": "Authenticated request"}'
```
## Mejores prácticas
1. **Usar formato de entrada para estructura**: Define un formato de entrada cuando conozcas el esquema esperado. Esto proporciona:
- Validación de tipo
- Mejor autocompletado en el editor
- Capacidades de carga de archivos
2. **Autenticación**: Habilita siempre la autenticación para webhooks en producción para prevenir accesos no autorizados.
3. **Límites de tamaño de archivo**: Mantén los archivos por debajo de 20MB. Para archivos más grandes, usa referencias URL en su lugar.
4. **Caducidad de archivos**: Los archivos descargados tienen URLs con caducidad de 5 minutos. Procésalos rápidamente o almacénalos en otro lugar si los necesitas por más tiempo.
5. **Manejo de errores**: El procesamiento de webhooks es asíncrono. Revisa los registros de ejecución para detectar errores.
6. **Pruebas**: Usa el botón "Probar webhook" en el editor para validar tu configuración antes de implementarla.
## Casos de uso
- **Envíos de formularios**: Recibe datos de formularios personalizados con cargas de archivos
- **Integraciones con terceros**: Conéctate con servicios que envían webhooks (Stripe, GitHub, etc.)
- **Procesamiento de documentos**: Acepta documentos de sistemas externos para procesarlos
- **Notificaciones de eventos**: Recibe datos de eventos de varias fuentes
- **APIs personalizadas**: Construye endpoints de API personalizados para tus aplicaciones
## Notas
- Categoría: `triggers`
- Tipo: `generic_webhook`
- **Soporte de archivos**: disponible a través de la configuración del formato de entrada
- **Tamaño máximo de archivo**: 20MB por archivo

View File

@@ -15,7 +15,7 @@ El bloque de webhook genérico crea un punto de conexión flexible que puede rec
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="Configuración genérica de webhook"
width={500}
height={400}

View File

@@ -1,231 +0,0 @@
---
title: Webhook
description: Recevez des webhooks de n'importe quel service en configurant un
webhook personnalisé.
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
import { Image } from '@/components/ui/image'
<BlockInfoCard
type="generic_webhook"
color="#10B981"
/>
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Configuration du bloc Webhook"
width={500}
height={400}
className="my-6"
/>
</div>
## Aperçu
Le bloc Webhook générique vous permet de recevoir des webhooks depuis n'importe quel service externe. C'est un déclencheur flexible qui peut traiter n'importe quelle charge utile JSON, ce qui le rend idéal pour l'intégration avec des services qui n'ont pas de bloc Sim dédié.
## Utilisation de base
### Mode de transmission simple
Sans définir un format d'entrée, le webhook transmet l'intégralité du corps de la requête tel quel :
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Test webhook trigger",
"data": {
"key": "value"
}
}'
```
Accédez aux données dans les blocs en aval en utilisant :
- `<webhook1.message>` → "Test webhook trigger"
- `<webhook1.data.key>` → "value"
### Format d'entrée structuré (optionnel)
Définissez un schéma d'entrée pour obtenir des champs typés et activer des fonctionnalités avancées comme les téléchargements de fichiers :
**Configuration du format d'entrée :**
```json
[
{ "name": "message", "type": "string" },
{ "name": "priority", "type": "number" },
{ "name": "documents", "type": "files" }
]
```
**Requête Webhook :**
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Invoice submission",
"priority": 1,
"documents": [
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "invoice.pdf",
"mime": "application/pdf"
}
]
}'
```
## Téléchargements de fichiers
### Formats de fichiers pris en charge
Le webhook prend en charge deux formats d'entrée de fichiers :
#### 1. Fichiers encodés en Base64
Pour télécharger directement le contenu du fichier :
```json
{
"documents": [
{
"type": "file",
"data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...",
"name": "screenshot.png",
"mime": "image/png"
}
]
}
```
- **Taille maximale** : 20 Mo par fichier
- **Format** : URL de données standard avec encodage base64
- **Stockage** : Les fichiers sont téléchargés dans un stockage d'exécution sécurisé
#### 2. Références URL
Pour transmettre des URL de fichiers existants :
```json
{
"documents": [
{
"type": "url",
"data": "https://example.com/files/document.pdf",
"name": "document.pdf",
"mime": "application/pdf"
}
]
}
```
### Accès aux fichiers dans les blocs en aval
Les fichiers sont traités en objets `UserFile` avec les propriétés suivantes :
```typescript
{
id: string, // Unique file identifier
name: string, // Original filename
url: string, // Presigned URL (valid for 5 minutes)
size: number, // File size in bytes
type: string, // MIME type
key: string, // Storage key
uploadedAt: string, // ISO timestamp
expiresAt: string // ISO timestamp (5 minutes)
}
```
**Accès dans les blocs :**
- `<webhook1.documents[0].url>` → URL de téléchargement
- `<webhook1.documents[0].name>` → "invoice.pdf"
- `<webhook1.documents[0].size>` → 524288
- `<webhook1.documents[0].type>` → "application/pdf"
### Exemple complet de téléchargement de fichier
```bash
# Create a base64-encoded file
echo "Hello World" | base64
# SGVsbG8gV29ybGQK
# Send webhook with file
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"subject": "Document for review",
"attachments": [
{
"type": "file",
"data": "data:text/plain;base64,SGVsbG8gV29ybGQK",
"name": "sample.txt",
"mime": "text/plain"
}
]
}'
```
## Authentification
### Configurer l'authentification (optionnel)
Dans la configuration du webhook :
1. Activez "Exiger l'authentification"
2. Définissez un jeton secret
3. Choisissez le type d'en-tête :
- **En-tête personnalisé** : `X-Sim-Secret: your-token`
- **Autorisation Bearer** : `Authorization: Bearer your-token`
### Utilisation de l'authentification
```bash
# With custom header
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret-token" \
-d '{"message": "Authenticated request"}'
# With bearer token
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-secret-token" \
-d '{"message": "Authenticated request"}'
```
## Bonnes pratiques
1. **Utiliser le format d'entrée pour la structure** : définissez un format d'entrée lorsque vous connaissez le schéma attendu. Cela fournit :
- Validation de type
- Meilleure autocomplétion dans l'éditeur
- Capacités de téléchargement de fichiers
2. **Authentification** : activez toujours l'authentification pour les webhooks en production afin d'empêcher les accès non autorisés.
3. **Limites de taille de fichier** : gardez les fichiers en dessous de 20 Mo. Pour les fichiers plus volumineux, utilisez plutôt des références URL.
4. **Expiration des fichiers** : les fichiers téléchargés ont des URL d'expiration de 5 minutes. Traitez-les rapidement ou stockez-les ailleurs si vous en avez besoin plus longtemps.
5. **Gestion des erreurs** : le traitement des webhooks est asynchrone. Vérifiez les journaux d'exécution pour les erreurs.
6. **Tests** : utilisez le bouton "Tester le webhook" dans l'éditeur pour valider votre configuration avant le déploiement.
## Cas d'utilisation
- **Soumissions de formulaires** : recevez des données de formulaires personnalisés avec téléchargement de fichiers
- **Intégrations tierces** : connectez-vous avec des services qui envoient des webhooks (Stripe, GitHub, etc.)
- **Traitement de documents** : acceptez des documents de systèmes externes pour traitement
- **Notifications d'événements** : recevez des données d'événements de diverses sources
- **API personnalisées** : créez des points de terminaison API personnalisés pour vos applications
## Remarques
- Catégorie : `triggers`
- Type : `generic_webhook`
- **Support de fichiers** : disponible via la configuration du format d'entrée
- **Taille maximale de fichier** : 20 Mo par fichier

View File

@@ -15,7 +15,7 @@ Le bloc Webhook générique crée un point de terminaison flexible qui peut rece
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="Configuration de webhook générique"
width={500}
height={400}

View File

@@ -1,230 +0,0 @@
---
title: Webhook
description: カスタムウェブフックを設定して、任意のサービスからウェブフックを受信します。
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
import { Image } from '@/components/ui/image'
<BlockInfoCard
type="generic_webhook"
color="#10B981"
/>
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Webhookブロックの設定"
width={500}
height={400}
className="my-6"
/>
</div>
## 概要
汎用Webhookブロックを使用すると、任意の外部サービスからWebhookを受信できます。これは柔軟なトリガーであり、あらゆるJSONペイロードを処理できるため、専用のSimブロックがないサービスとの統合に最適です。
## 基本的な使用方法
### シンプルなパススルーモード
入力フォーマットを定義しない場合、Webhookはリクエスト本文全体をそのまま渡します
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Test webhook trigger",
"data": {
"key": "value"
}
}'
```
下流のブロックでデータにアクセスする方法:
- `<webhook1.message>` → "Test webhook trigger"
- `<webhook1.data.key>` → "value"
### 構造化入力フォーマット(オプション)
入力スキーマを定義して、型付きフィールドを取得し、ファイルアップロードなどの高度な機能を有効にします:
**入力フォーマット設定:**
```json
[
{ "name": "message", "type": "string" },
{ "name": "priority", "type": "number" },
{ "name": "documents", "type": "files" }
]
```
**Webhookリクエスト**
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Invoice submission",
"priority": 1,
"documents": [
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "invoice.pdf",
"mime": "application/pdf"
}
]
}'
```
## ファイルアップロード
### サポートされているファイル形式
Webhookは2つのファイル入力形式をサポートしています
#### 1. Base64エンコードファイル
ファイルコンテンツを直接アップロードする場合:
```json
{
"documents": [
{
"type": "file",
"data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...",
"name": "screenshot.png",
"mime": "image/png"
}
]
}
```
- **最大サイズ**: ファイルあたり20MB
- **フォーマット**: Base64エンコーディングを使用した標準データURL
- **ストレージ**: ファイルは安全な実行ストレージにアップロードされます
#### 2. URL参照
既存のファイルURLを渡す場合
```json
{
"documents": [
{
"type": "url",
"data": "https://example.com/files/document.pdf",
"name": "document.pdf",
"mime": "application/pdf"
}
]
}
```
### 下流のブロックでファイルにアクセスする
ファイルは以下のプロパティを持つ `UserFile` オブジェクトに処理されます:
```typescript
{
id: string, // Unique file identifier
name: string, // Original filename
url: string, // Presigned URL (valid for 5 minutes)
size: number, // File size in bytes
type: string, // MIME type
key: string, // Storage key
uploadedAt: string, // ISO timestamp
expiresAt: string // ISO timestamp (5 minutes)
}
```
**ブロック内でのアクセス:**
- `<webhook1.documents[0].url>` → ダウンロードURL
- `<webhook1.documents[0].name>` → "invoice.pdf"
- `<webhook1.documents[0].size>` → 524288
- `<webhook1.documents[0].type>` → "application/pdf"
### ファイルアップロードの完全な例
```bash
# Create a base64-encoded file
echo "Hello World" | base64
# SGVsbG8gV29ybGQK
# Send webhook with file
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"subject": "Document for review",
"attachments": [
{
"type": "file",
"data": "data:text/plain;base64,SGVsbG8gV29ybGQK",
"name": "sample.txt",
"mime": "text/plain"
}
]
}'
```
## 認証
### 認証の設定(オプション)
ウェブフック設定で:
1. 「認証を要求する」を有効にする
2. シークレットトークンを設定する
3. ヘッダータイプを選択する:
- **カスタムヘッダー**: `X-Sim-Secret: your-token`
- **認証ベアラー**: `Authorization: Bearer your-token`
### 認証の使用
```bash
# With custom header
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret-token" \
-d '{"message": "Authenticated request"}'
# With bearer token
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-secret-token" \
-d '{"message": "Authenticated request"}'
```
## ベストプラクティス
1. **構造化のための入力フォーマットの使用**: 予想されるスキーマがわかっている場合は入力フォーマットを定義してください。これにより以下が提供されます:
- 型の検証
- エディタでのより良いオートコンプリート
- ファイルアップロード機能
2. **認証**: 不正アクセスを防ぐため、本番環境のウェブフックには常に認証を有効にしてください。
3. **ファイルサイズの制限**: ファイルは20MB未満に保ってください。より大きなファイルの場合は、代わりにURL参照を使用してください。
4. **ファイルの有効期限**: ダウンロードされたファイルのURLは5分間有効です。すぐに処理するか、長期間必要な場合は別の場所に保存してください。
5. **エラー処理**: ウェブフック処理は非同期です。エラーについては実行ログを確認してください。
6. **テスト**: 設定をデプロイする前に、エディタの「ウェブフックをテスト」ボタンを使用して設定を検証してください。
## ユースケース
- **フォーム送信**: ファイルアップロード機能を持つカスタムフォームからデータを受け取る
- **サードパーティ連携**: ウェブフックを送信するサービスStripe、GitHubなどと接続する
- **ドキュメント処理**: 外部システムからドキュメントを受け取って処理する
- **イベント通知**: さまざまなソースからイベントデータを受け取る
- **カスタムAPI**: アプリケーション用のカスタムAPIエンドポイントを構築する
## 注意事項
- カテゴリ:`triggers`
- タイプ:`generic_webhook`
- **ファイルサポート**:入力フォーマット設定で利用可能
- **最大ファイルサイズ**ファイルあたり20MB

View File

@@ -15,7 +15,7 @@ Webhookを使用すると、外部サービスがHTTPリクエストを送信し
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="汎用Webhook設定"
width={500}
height={400}

View File

@@ -1,230 +0,0 @@
---
title: Webhook
description: 通过配置自定义 webhook从任何服务接收 webhook。
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
import { Image } from '@/components/ui/image'
<BlockInfoCard
type="generic_webhook"
color="#10B981"
/>
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
alt="Webhook Block Configuration"
width={500}
height={400}
className="my-6"
/>
</div>
## 概述
通用 Webhook 模块允许您接收来自任何外部服务的 webhook。这是一个灵活的触发器可以处理任何 JSON 负载,非常适合与没有专用 Sim 模块的服务集成。
## 基本用法
### 简单直通模式
在未定义输入格式的情况下webhook 会按原样传递整个请求正文:
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Test webhook trigger",
"data": {
"key": "value"
}
}'
```
在下游模块中使用以下方式访问数据:
- `<webhook1.message>` → "测试 webhook 触发器"
- `<webhook1.data.key>` → "值"
### 结构化输入格式(可选)
定义输入模式以获取类型化字段,并启用高级功能,例如文件上传:
**输入格式配置:**
```json
[
{ "name": "message", "type": "string" },
{ "name": "priority", "type": "number" },
{ "name": "documents", "type": "files" }
]
```
**Webhook 请求:**
```bash
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"message": "Invoice submission",
"priority": 1,
"documents": [
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQK...",
"name": "invoice.pdf",
"mime": "application/pdf"
}
]
}'
```
## 文件上传
### 支持的文件格式
webhook 支持两种文件输入格式:
#### 1. Base64 编码文件
用于直接上传文件内容:
```json
{
"documents": [
{
"type": "file",
"data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...",
"name": "screenshot.png",
"mime": "image/png"
}
]
}
```
- **最大大小**:每个文件 20MB
- **格式**:带有 base64 编码的标准数据 URL
- **存储**:文件上传到安全的执行存储
#### 2. URL 引用
用于传递现有文件 URL
```json
{
"documents": [
{
"type": "url",
"data": "https://example.com/files/document.pdf",
"name": "document.pdf",
"mime": "application/pdf"
}
]
}
```
### 在下游模块中访问文件
文件被处理为具有以下属性的 `UserFile` 对象:
```typescript
{
id: string, // Unique file identifier
name: string, // Original filename
url: string, // Presigned URL (valid for 5 minutes)
size: number, // File size in bytes
type: string, // MIME type
key: string, // Storage key
uploadedAt: string, // ISO timestamp
expiresAt: string // ISO timestamp (5 minutes)
}
```
**分块访问:**
- `<webhook1.documents[0].url>` → 下载 URL
- `<webhook1.documents[0].name>` → "invoice.pdf"
- `<webhook1.documents[0].size>` → 524288
- `<webhook1.documents[0].type>` → "application/pdf"
### 完整文件上传示例
```bash
# Create a base64-encoded file
echo "Hello World" | base64
# SGVsbG8gV29ybGQK
# Send webhook with file
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret" \
-d '{
"subject": "Document for review",
"attachments": [
{
"type": "file",
"data": "data:text/plain;base64,SGVsbG8gV29ybGQK",
"name": "sample.txt",
"mime": "text/plain"
}
]
}'
```
## 身份验证
### 配置身份验证(可选)
在 webhook 配置中:
1. 启用“需要身份验证”
2. 设置一个密钥令牌
3. 选择头类型:
- **自定义头**: `X-Sim-Secret: your-token`
- **授权 Bearer**: `Authorization: Bearer your-token`
### 使用身份验证
```bash
# With custom header
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "X-Sim-Secret: your-secret-token" \
-d '{"message": "Authenticated request"}'
# With bearer token
curl -X POST https://sim.ai/api/webhooks/trigger/{webhook-path} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-secret-token" \
-d '{"message": "Authenticated request"}'
```
## 最佳实践
1. **使用输入格式定义结构**:当您知道预期的模式时,定义输入格式。这提供:
- 类型验证
- 编辑器中的更好自动完成
- 文件上传功能
2. **身份验证**:在生产环境的 webhook 中始终启用身份验证,以防止未经授权的访问。
3. **文件大小限制**:将文件保持在 20MB 以下。对于更大的文件,请使用 URL 引用。
4. **文件过期**:下载的文件具有 5 分钟的 URL 过期时间。请及时处理,或如果需要更长时间,请将其存储在其他地方。
5. **错误处理**Webhook 处理是异步的。请检查执行日志以获取错误信息。
6. **测试**:在部署前,使用编辑器中的“测试 Webhook”按钮验证您的配置。
## 使用场景
- **表单提交**:接收带有文件上传的自定义表单数据
- **第三方集成**:与发送 webhook 的服务(如 Stripe、GitHub 等)连接
- **文档处理**:接受来自外部系统的文档进行处理
- **事件通知**:接收来自各种来源的事件数据
- **自定义 API**:为您的应用程序构建自定义 API 端点
## 注意事项
- 类别:`triggers`
- 类型:`generic_webhook`
- **文件支持**:通过输入格式配置可用
- **最大文件大小**:每个文件 20MB

View File

@@ -15,7 +15,7 @@ Webhook 允许外部服务通过向您的工作流发送 HTTP 请求来触发工
<div className="flex justify-center">
<Image
src="/static/blocks/webhook.png"
src="/static/blocks/webhook-trigger.png"
alt="通用 Webhook 配置"
width={500}
height={400}

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

@@ -256,24 +256,13 @@ export function InputMapping({
if (!selectedWorkflowId) {
return (
<div className='flex flex-col items-center justify-center rounded-[4px] border border-[var(--border-1)] bg-[var(--surface-3)] p-8 text-center dark:bg-[#1F1F1F]'>
<svg
className='mb-3 h-10 w-10 text-[var(--text-tertiary)]'
fill='none'
viewBox='0 0 24 24'
stroke='currentColor'
>
<path
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth={1.5}
d='M13 10V3L4 14h7v7l9-11h-7z'
/>
</svg>
<p className='font-medium text-[var(--text-tertiary)] text-sm'>No workflow selected</p>
<p className='mt-1 text-[var(--text-tertiary)]/80 text-xs'>
Select a workflow above to configure inputs
</p>
<div className='flex h-32 items-center justify-center rounded-[4px] border border-[var(--border-1)] border-dashed bg-[var(--surface-3)] dark:bg-[#1F1F1F]'>
<div className='text-center'>
<p className='font-medium text-[var(--text-secondary)] text-sm'>No workflow selected</p>
<p className='mt-1 text-[var(--text-muted)] text-xs'>
Select a workflow above to configure inputs
</p>
</div>
</div>
)
}

View File

@@ -95,7 +95,9 @@ export function FieldFormat({
}: FieldFormatProps) {
const [storeValue, setStoreValue] = useSubBlockValue<Field[]>(blockId, subBlockId)
const valueInputRefs = useRef<Record<string, HTMLInputElement | HTMLTextAreaElement>>({})
const nameInputRefs = useRef<Record<string, HTMLInputElement>>({})
const overlayRefs = useRef<Record<string, HTMLDivElement>>({})
const nameOverlayRefs = useRef<Record<string, HTMLDivElement>>({})
const accessiblePrefixes = useAccessibleReferencePrefixes(blockId)
const inputController = useSubBlockInput({
@@ -158,6 +160,97 @@ export function FieldFormat({
if (overlay) overlay.scrollLeft = scrollLeft
}
/**
* Syncs scroll position between name input and overlay for text highlighting
*/
const syncNameOverlayScroll = (fieldId: string, scrollLeft: number) => {
const overlay = nameOverlayRefs.current[fieldId]
if (overlay) overlay.scrollLeft = scrollLeft
}
/**
* Generates a unique field key for name inputs to avoid collision with value inputs
*/
const getNameFieldKey = (fieldId: string) => `name-${fieldId}`
/**
* Renders the name input field with tag dropdown support
*/
const renderNameInput = (field: Field) => {
const nameFieldKey = getNameFieldKey(field.id)
const fieldValue = field.name ?? ''
const fieldState = inputController.fieldHelpers.getFieldState(nameFieldKey)
const handlers = inputController.fieldHelpers.createFieldHandlers(
nameFieldKey,
fieldValue,
(newValue) => updateField(field.id, 'name', newValue)
)
const tagSelectHandler = inputController.fieldHelpers.createTagSelectHandler(
nameFieldKey,
fieldValue,
(newValue) => updateField(field.id, 'name', newValue)
)
const inputClassName = cn('text-transparent caret-foreground')
return (
<>
<Input
ref={(el) => {
if (el) nameInputRefs.current[field.id] = el
}}
name='name'
value={fieldValue}
onChange={handlers.onChange}
onKeyDown={handlers.onKeyDown}
onDrop={handlers.onDrop}
onDragOver={handlers.onDragOver}
onScroll={(e) => syncNameOverlayScroll(field.id, e.currentTarget.scrollLeft)}
onPaste={() =>
setTimeout(() => {
const input = nameInputRefs.current[field.id]
input && syncNameOverlayScroll(field.id, input.scrollLeft)
}, 0)
}
placeholder={placeholder}
disabled={isReadOnly}
autoComplete='off'
className={cn('allow-scroll w-full overflow-auto', inputClassName)}
style={{ overflowX: 'auto' }}
/>
<div
ref={(el) => {
if (el) nameOverlayRefs.current[field.id] = el
}}
className='pointer-events-none absolute inset-0 flex items-center overflow-x-auto bg-transparent px-[8px] py-[6px] font-medium font-sans text-sm'
style={{ overflowX: 'auto' }}
>
<div
className='w-full whitespace-pre'
style={{ scrollbarWidth: 'none', minWidth: 'fit-content' }}
>
{formatDisplayText(
fieldValue,
accessiblePrefixes ? { accessiblePrefixes } : { highlightAll: true }
)}
</div>
</div>
{fieldState.showTags && (
<TagDropdown
visible={fieldState.showTags}
onSelect={tagSelectHandler}
blockId={blockId}
activeSourceBlockId={fieldState.activeSourceBlockId}
inputValue={fieldValue}
cursorPosition={fieldState.cursorPosition}
onClose={() => inputController.fieldHelpers.hideFieldDropdowns(nameFieldKey)}
inputRef={{ current: nameInputRefs.current[field.id] || null }}
/>
)}
</>
)
}
/**
* Renders the field header with name, type badge, and action buttons
*/
@@ -417,14 +510,7 @@ export function FieldFormat({
<div className='flex flex-col gap-[8px] border-[var(--border-1)] border-t px-[10px] pt-[6px] pb-[10px]'>
<div className='flex flex-col gap-[6px]'>
<Label className='text-[13px]'>Name</Label>
<Input
name='name'
value={field.name}
onChange={(e) => updateField(field.id, 'name', e.target.value)}
placeholder={placeholder}
disabled={isReadOnly}
autoComplete='off'
/>
<div className='relative'>{renderNameInput(field)}</div>
</div>
{showType && (

View File

@@ -352,53 +352,6 @@ describe('Blocks Module', () => {
expect(typeof block?.tools.config?.tool).toBe('function')
})
})
describe('WebhookBlock', () => {
const block = getBlock('webhook')
it('should have correct metadata', () => {
expect(block?.type).toBe('webhook')
expect(block?.name).toBe('Webhook')
expect(block?.category).toBe('triggers')
expect(block?.authMode).toBe(AuthMode.OAuth)
expect(block?.triggerAllowed).toBe(true)
expect(block?.hideFromToolbar).toBe(true)
})
it('should have webhookProvider dropdown with multiple providers', () => {
const providerSubBlock = block?.subBlocks.find((sb) => sb.id === 'webhookProvider')
expect(providerSubBlock).toBeDefined()
expect(providerSubBlock?.type).toBe('dropdown')
const options = providerSubBlock?.options as Array<{ label: string; id: string }>
expect(options?.map((o) => o.id)).toContain('slack')
expect(options?.map((o) => o.id)).toContain('generic')
expect(options?.map((o) => o.id)).toContain('github')
})
it('should have conditional OAuth inputs', () => {
const gmailCredentialSubBlock = block?.subBlocks.find((sb) => sb.id === 'gmailCredential')
expect(gmailCredentialSubBlock).toBeDefined()
expect(gmailCredentialSubBlock?.type).toBe('oauth-input')
expect(gmailCredentialSubBlock?.condition).toEqual({
field: 'webhookProvider',
value: 'gmail',
})
const outlookCredentialSubBlock = block?.subBlocks.find(
(sb) => sb.id === 'outlookCredential'
)
expect(outlookCredentialSubBlock).toBeDefined()
expect(outlookCredentialSubBlock?.type).toBe('oauth-input')
expect(outlookCredentialSubBlock?.condition).toEqual({
field: 'webhookProvider',
value: 'outlook',
})
})
it('should have empty tools access', () => {
expect(block?.tools.access).toEqual([])
})
})
})
describe('SubBlock Validation', () => {
@@ -545,8 +498,8 @@ describe('Blocks Module', () => {
})
it('should handle blocks with triggerAllowed flag', () => {
const webhookBlock = getBlock('webhook')
expect(webhookBlock?.triggerAllowed).toBe(true)
const gmailBlock = getBlock('gmail')
expect(gmailBlock?.triggerAllowed).toBe(true)
const functionBlock = getBlock('function')
expect(functionBlock?.triggerAllowed).toBeUndefined()
@@ -663,16 +616,6 @@ describe('Blocks Module', () => {
expect(temperatureSubBlock?.min).toBe(0)
expect(temperatureSubBlock?.max).toBe(2)
})
it('should have required scopes on OAuth inputs', () => {
const webhookBlock = getBlock('webhook')
const gmailCredentialSubBlock = webhookBlock?.subBlocks.find(
(sb) => sb.id === 'gmailCredential'
)
expect(gmailCredentialSubBlock?.requiredScopes).toBeDefined()
expect(Array.isArray(gmailCredentialSubBlock?.requiredScopes)).toBe(true)
expect((gmailCredentialSubBlock?.requiredScopes?.length ?? 0) > 0).toBe(true)
})
})
describe('Block Consistency', () => {

View File

@@ -10,6 +10,7 @@ export const HumanInTheLoopBlock: BlockConfig<ResponseBlockOutput> = {
'Combines response and start functionality. Sends structured responses and allows workflow to resume from this point.',
category: 'blocks',
bgColor: '#10B981',
docsLink: 'https://docs.sim.ai/blocks/human-in-the-loop',
icon: HumanInTheLoopIcon,
subBlocks: [
// Operation dropdown hidden - block defaults to human approval mode

View File

@@ -9,7 +9,7 @@ export const TtsBlock: BlockConfig<TtsBlockResponse> = {
authMode: AuthMode.ApiKey,
longDescription:
'Generate natural-sounding speech from text using state-of-the-art AI voices from OpenAI, Deepgram, ElevenLabs, Cartesia, Google Cloud, Azure, and PlayHT. Supports multiple voices, languages, and audio formats.',
docsLink: 'https://docs.sim.ai/blocks/tts',
docsLink: 'https://docs.sim.ai/tools/tts',
category: 'tools',
bgColor: '#181C1E',
icon: TTSIcon,

View File

@@ -1,132 +0,0 @@
import {
AirtableIcon,
DiscordIcon,
GithubIcon,
GmailIcon,
MicrosoftTeamsIcon,
OutlookIcon,
SignalIcon,
SlackIcon,
StripeIcon,
TelegramIcon,
WebhookIcon,
WhatsAppIcon,
} from '@/components/icons'
import type { BlockConfig } from '@/blocks/types'
import { AuthMode } from '@/blocks/types'
const getWebhookProviderIcon = (provider: string) => {
const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
slack: SlackIcon,
gmail: GmailIcon,
outlook: OutlookIcon,
airtable: AirtableIcon,
telegram: TelegramIcon,
generic: SignalIcon,
whatsapp: WhatsAppIcon,
github: GithubIcon,
discord: DiscordIcon,
stripe: StripeIcon,
microsoftteams: MicrosoftTeamsIcon,
}
return iconMap[provider.toLowerCase()]
}
export const WebhookBlock: BlockConfig = {
type: 'webhook',
name: 'Webhook',
description: 'Trigger workflow execution from external webhooks',
authMode: AuthMode.OAuth,
category: 'triggers',
icon: WebhookIcon,
bgColor: '#10B981', // Green color for triggers
docsLink: 'https://docs.sim.ai/triggers/webhook',
triggerAllowed: true,
hideFromToolbar: true, // Hidden for backwards compatibility - use generic webhook trigger instead
subBlocks: [
{
id: 'webhookProvider',
title: 'Webhook Provider',
type: 'dropdown',
options: [
'slack',
'gmail',
'outlook',
'airtable',
'telegram',
'generic',
'whatsapp',
'github',
'discord',
'stripe',
'microsoftteams',
].map((provider) => {
const providerLabels = {
slack: 'Slack',
gmail: 'Gmail',
outlook: 'Outlook',
airtable: 'Airtable',
telegram: 'Telegram',
generic: 'Generic',
whatsapp: 'WhatsApp',
github: 'GitHub',
discord: 'Discord',
stripe: 'Stripe',
microsoftteams: 'Microsoft Teams',
}
const icon = getWebhookProviderIcon(provider)
return {
label: providerLabels[provider as keyof typeof providerLabels],
id: provider,
...(icon && { icon }),
}
}),
value: () => 'generic',
},
{
id: 'gmailCredential',
title: 'Gmail Account',
type: 'oauth-input',
serviceId: 'gmail',
requiredScopes: [
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.labels',
],
placeholder: 'Select Gmail account',
condition: { field: 'webhookProvider', value: 'gmail' },
required: true,
},
{
id: 'outlookCredential',
title: 'Microsoft Account',
type: 'oauth-input',
serviceId: 'outlook',
requiredScopes: [
'Mail.ReadWrite',
'Mail.ReadBasic',
'Mail.Read',
'Mail.Send',
'offline_access',
],
placeholder: 'Select Microsoft account',
condition: { field: 'webhookProvider', value: 'outlook' },
required: true,
},
{
id: 'webhookConfig',
title: 'Webhook Configuration',
type: 'webhook-config',
},
],
tools: {
access: [], // No external tools needed
},
inputs: {}, // No inputs - webhook triggers receive data externally
outputs: {}, // No outputs - webhook data is injected directly into workflow context
}

View File

@@ -2,7 +2,6 @@ import { WorkflowIcon } from '@/components/icons'
import type { BlockConfig } from '@/blocks/types'
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
// Helper: list workflows excluding self
const getAvailableWorkflows = (): Array<{ label: string; id: string }> => {
try {
const { workflows, activeWorkflowId } = useWorkflowRegistry.getState()
@@ -15,7 +14,6 @@ const getAvailableWorkflows = (): Array<{ label: string; id: string }> => {
}
}
// New workflow block variant that visualizes child Input Trigger schema for mapping
export const WorkflowInputBlock: BlockConfig = {
type: 'workflow_input',
name: 'Workflow',
@@ -26,6 +24,7 @@ export const WorkflowInputBlock: BlockConfig = {
- Remember, that the start point of the child workflow is the Start block.
`,
category: 'blocks',
docsLink: 'https://docs.sim.ai/blocks/workflow',
bgColor: '#6366F1', // Indigo - modern and professional
icon: WorkflowIcon,
subBlocks: [

View File

@@ -130,7 +130,6 @@ import { VisionBlock } from '@/blocks/blocks/vision'
import { WaitBlock } from '@/blocks/blocks/wait'
import { WealthboxBlock } from '@/blocks/blocks/wealthbox'
import { WebflowBlock } from '@/blocks/blocks/webflow'
import { WebhookBlock } from '@/blocks/blocks/webhook'
import { WebhookRequestBlock } from '@/blocks/blocks/webhook_request'
import { WhatsAppBlock } from '@/blocks/blocks/whatsapp'
import { WikipediaBlock } from '@/blocks/blocks/wikipedia'
@@ -281,7 +280,6 @@ export const registry: Record<string, BlockConfig> = {
wait: WaitBlock,
wealthbox: WealthboxBlock,
webflow: WebflowBlock,
webhook: WebhookBlock,
webhook_request: WebhookRequestBlock,
whatsapp: WhatsAppBlock,
wikipedia: WikipediaBlock,
@@ -296,11 +294,9 @@ export const registry: Record<string, BlockConfig> = {
}
export const getBlock = (type: string): BlockConfig | undefined => {
// Direct lookup first
if (registry[type]) {
return registry[type]
}
// Fallback: normalize hyphens to underscores (e.g., 'microsoft-teams' -> 'microsoft_teams')
const normalized = type.replace(/-/g, '_')
return registry[normalized]
}

View File

@@ -1,7 +1,6 @@
import { createLogger } from '@sim/logger'
import type { BlockOutput } from '@/blocks/types'
import { BlockType, HTTP, REFERENCE } from '@/executor/constants'
import type { BlockHandler, ExecutionContext } from '@/executor/types'
import type { BlockHandler, ExecutionContext, NormalizedBlockOutput } from '@/executor/types'
import type { SerializedBlock } from '@/serializer/types'
const logger = createLogger('ResponseBlockHandler')
@@ -23,7 +22,7 @@ export class ResponseBlockHandler implements BlockHandler {
ctx: ExecutionContext,
block: SerializedBlock,
inputs: Record<string, any>
): Promise<BlockOutput> {
): Promise<NormalizedBlockOutput> {
logger.info(`Executing response block: ${block.id}`)
try {
@@ -38,23 +37,19 @@ export class ResponseBlockHandler implements BlockHandler {
})
return {
response: {
data: responseData,
status: statusCode,
headers: responseHeaders,
},
data: responseData,
status: statusCode,
headers: responseHeaders,
}
} catch (error: any) {
logger.error('Response block execution failed:', error)
return {
response: {
data: {
error: 'Response block execution failed',
message: error.message || 'Unknown error',
},
status: HTTP.STATUS.SERVER_ERROR,
headers: { 'Content-Type': HTTP.CONTENT_TYPE.JSON },
data: {
error: 'Response block execution failed',
message: error.message || 'Unknown error',
},
status: HTTP.STATUS.SERVER_ERROR,
headers: { 'Content-Type': HTTP.CONTENT_TYPE.JSON },
}
}
}

View File

@@ -293,6 +293,532 @@ describe('BlockResolver', () => {
})
})
describe('Response block backwards compatibility', () => {
it.concurrent('should resolve new format: <responseBlock.data>', () => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: { message: 'hello', userId: 123 },
status: 200,
headers: { 'Content-Type': 'application/json' },
},
})
expect(resolver.resolve('<response.data>', ctx)).toEqual({ message: 'hello', userId: 123 })
expect(resolver.resolve('<response.data.message>', ctx)).toBe('hello')
expect(resolver.resolve('<response.data.userId>', ctx)).toBe(123)
})
it.concurrent('should resolve new format: <responseBlock.status>', () => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: { message: 'hello' },
status: 201,
headers: {},
},
})
expect(resolver.resolve('<response.status>', ctx)).toBe(201)
})
it.concurrent('should resolve new format: <responseBlock.headers>', () => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: {},
status: 200,
headers: { 'X-Custom-Header': 'custom-value', 'Content-Type': 'application/json' },
},
})
expect(resolver.resolve('<response.headers>', ctx)).toEqual({
'X-Custom-Header': 'custom-value',
'Content-Type': 'application/json',
})
})
it.concurrent(
'should resolve old format (backwards compat): <responseBlock.response.data>',
() => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: { message: 'hello', userId: 123 },
status: 200,
headers: { 'Content-Type': 'application/json' },
},
})
// Old format: <responseBlock.response.data> should strip 'response.' and resolve to data
expect(resolver.resolve('<response.response.data>', ctx)).toEqual({
message: 'hello',
userId: 123,
})
expect(resolver.resolve('<response.response.data.message>', ctx)).toBe('hello')
expect(resolver.resolve('<response.response.data.userId>', ctx)).toBe(123)
}
)
it.concurrent(
'should resolve old format (backwards compat): <responseBlock.response.status>',
() => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: { message: 'hello' },
status: 404,
headers: {},
},
})
// Old format: <responseBlock.response.status> should strip 'response.' and resolve to status
expect(resolver.resolve('<response.response.status>', ctx)).toBe(404)
}
)
it.concurrent(
'should resolve old format (backwards compat): <responseBlock.response.headers>',
() => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'response-block': {
data: {},
status: 200,
headers: { 'X-Request-Id': 'abc-123' },
},
})
// Old format: <responseBlock.response.headers> should strip 'response.' and resolve to headers
expect(resolver.resolve('<response.response.headers>', ctx)).toEqual({
'X-Request-Id': 'abc-123',
})
}
)
it.concurrent('should resolve entire Response block output with new format', () => {
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'My Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
const fullOutput = {
data: { result: 'success' },
status: 200,
headers: { 'Content-Type': 'application/json' },
}
const ctx = createTestContext('current', { 'response-block': fullOutput })
expect(resolver.resolve('<myresponse>', ctx)).toEqual(fullOutput)
})
it.concurrent(
'should only strip response prefix for response block type, not other blocks',
() => {
// For non-response blocks, 'response' is a valid property name that should NOT be stripped
const workflow = createTestWorkflow([{ id: 'agent-block', name: 'Agent', type: 'agent' }])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'agent-block': {
response: { content: 'AI generated text' },
tokens: { input: 100, output: 50 },
},
})
// For agent blocks, 'response' is a valid property and should be accessed normally
expect(resolver.resolve('<agent.response.content>', ctx)).toBe('AI generated text')
}
)
it.concurrent(
'should NOT strip response prefix if output actually has response key (edge case)',
() => {
// Edge case: What if a Response block somehow has a 'response' key in its output?
// This shouldn't happen in practice, but if it does, we should respect it.
const workflow = createTestWorkflow([
{ id: 'response-block', name: 'Response', type: 'response' },
])
const resolver = new BlockResolver(workflow)
// Hypothetical edge case where output has an actual 'response' property
const ctx = createTestContext('current', {
'response-block': {
response: { legacyData: 'some value' },
data: { newData: 'other value' },
},
})
// Since output.response exists, we should NOT strip it - access the actual 'response' property
expect(resolver.resolve('<response.response.legacyData>', ctx)).toBe('some value')
expect(resolver.resolve('<response.data.newData>', ctx)).toBe('other value')
}
)
})
describe('Workflow block with child Response block backwards compatibility', () => {
it.concurrent('should resolve new format: <workflowBlock.result.data>', () => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
// After our change, child workflow with Response block returns { data, status, headers }
// Workflow block wraps it in { success, result: { data, status, headers }, ... }
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: { userId: 456, name: 'Test User' },
status: 200,
headers: { 'Content-Type': 'application/json' },
},
},
})
expect(resolver.resolve('<myworkflow.result.data>', ctx)).toEqual({
userId: 456,
name: 'Test User',
})
expect(resolver.resolve('<myworkflow.result.data.userId>', ctx)).toBe(456)
expect(resolver.resolve('<myworkflow.result.data.name>', ctx)).toBe('Test User')
})
it.concurrent('should resolve new format: <workflowBlock.result.status>', () => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: { message: 'created' },
status: 201,
headers: {},
},
},
})
expect(resolver.resolve('<myworkflow.result.status>', ctx)).toBe(201)
})
it.concurrent('should resolve new format: <workflowBlock.result.headers>', () => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: {},
status: 200,
headers: { 'X-Trace-Id': 'trace-abc-123' },
},
},
})
expect(resolver.resolve('<myworkflow.result.headers>', ctx)).toEqual({
'X-Trace-Id': 'trace-abc-123',
})
})
it.concurrent(
'should resolve old format (backwards compat): <workflowBlock.result.response.data>',
() => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: { userId: 456, name: 'Test User' },
status: 200,
headers: { 'Content-Type': 'application/json' },
},
},
})
// Old format: <workflowBlock.result.response.data> should strip 'response.' and resolve to result.data
expect(resolver.resolve('<myworkflow.result.response.data>', ctx)).toEqual({
userId: 456,
name: 'Test User',
})
expect(resolver.resolve('<myworkflow.result.response.data.userId>', ctx)).toBe(456)
expect(resolver.resolve('<myworkflow.result.response.data.name>', ctx)).toBe('Test User')
}
)
it.concurrent(
'should resolve old format (backwards compat): <workflowBlock.result.response.status>',
() => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: { message: 'error' },
status: 500,
headers: {},
},
},
})
// Old format: <workflowBlock.result.response.status> should strip 'response.' and resolve to result.status
expect(resolver.resolve('<myworkflow.result.response.status>', ctx)).toBe(500)
}
)
it.concurrent(
'should resolve old format (backwards compat): <workflowBlock.result.response.headers>',
() => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
data: {},
status: 200,
headers: { 'Cache-Control': 'no-cache' },
},
},
})
// Old format: <workflowBlock.result.response.headers> should strip 'response.' and resolve to result.headers
expect(resolver.resolve('<myworkflow.result.response.headers>', ctx)).toEqual({
'Cache-Control': 'no-cache',
})
}
)
it.concurrent('should resolve workflow block success and other properties', () => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: { data: {}, status: 200, headers: {} },
},
})
expect(resolver.resolve('<myworkflow.success>', ctx)).toBe(true)
expect(resolver.resolve('<myworkflow.childWorkflowName>', ctx)).toBe('Child Workflow')
})
it.concurrent('should handle workflow block with failed child workflow', () => {
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: false,
childWorkflowName: 'Child Workflow',
result: {},
error: 'Child workflow execution failed',
},
})
expect(resolver.resolve('<myworkflow.success>', ctx)).toBe(false)
expect(resolver.resolve('<myworkflow.error>', ctx)).toBe('Child workflow execution failed')
})
it.concurrent('should handle workflow block where child has non-Response final block', () => {
// When child workflow does NOT have a Response block as final block,
// the result structure will be different (not data/status/headers)
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
content: 'AI generated response',
tokens: { input: 100, output: 50 },
},
},
})
// No backwards compat needed here since child didn't have Response block
expect(resolver.resolve('<myworkflow.result.content>', ctx)).toBe('AI generated response')
expect(resolver.resolve('<myworkflow.result.tokens.input>', ctx)).toBe(100)
})
it.concurrent('should not apply workflow backwards compat for non-workflow blocks', () => {
// For non-workflow blocks, 'result.response' is a valid path that should NOT be modified
const workflow = createTestWorkflow([
{ id: 'function-block', name: 'Function', type: 'function' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'function-block': {
result: {
response: { apiData: 'test' },
other: 'value',
},
},
})
// For function blocks, 'result.response' is a valid nested property
expect(resolver.resolve('<function.result.response.apiData>', ctx)).toBe('test')
})
it.concurrent(
'should NOT strip result.response if child actually has response property (edge case)',
() => {
// Edge case: Child workflow's final output legitimately has a 'response' property
// (e.g., child ended with an Agent block that outputs response data)
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'Child Workflow',
result: {
// Child workflow ended with Agent block, not Response block
content: 'AI generated text',
response: { apiCallData: 'from external API' }, // legitimate 'response' property
},
},
})
// Since output.result.response exists, we should NOT strip it - access the actual property
expect(resolver.resolve('<myworkflow.result.response.apiCallData>', ctx)).toBe(
'from external API'
)
expect(resolver.resolve('<myworkflow.result.content>', ctx)).toBe('AI generated text')
}
)
it.concurrent('should handle mixed scenarios correctly', () => {
// Test that new format works when child workflow had Response block
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'My Workflow', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
// Scenario 1: Child had Response block (new format - no 'response' key in result)
const ctx1 = createTestContext('current', {
'workflow-block': {
success: true,
result: { data: { id: 1 }, status: 200, headers: {} },
},
})
// New format works
expect(resolver.resolve('<myworkflow.result.data.id>', ctx1)).toBe(1)
// Old format also works (backwards compat kicks in because result.response is undefined)
expect(resolver.resolve('<myworkflow.result.response.data.id>', ctx1)).toBe(1)
// Scenario 2: Child had Agent block with 'response' property
const ctx2 = createTestContext('current', {
'workflow-block': {
success: true,
result: {
content: 'text',
response: { external: 'data' }, // actual 'response' property
},
},
})
// Access the actual 'response' property - no stripping
expect(resolver.resolve('<myworkflow.result.response.external>', ctx2)).toBe('data')
})
it.concurrent(
'real-world scenario: parent workflow referencing child Response block via <workflow1.result.response.data>',
() => {
/**
* This test simulates the exact scenario from user workflows:
*
* Child workflow (vibrant-cliff):
* Start → Function 1 (returns "fuck") → Response 1
* Response 1 outputs: { data: { hi: "fuck" }, status: 200, headers: {...} }
*
* Parent workflow (flying-glacier):
* Start → Workflow 1 (calls vibrant-cliff) → Function 1
* Function 1 code: return <workflow1.result.response.data>
*
* After our changes:
* - Child Response block outputs { data, status, headers } (no wrapper)
* - Workflow block wraps it in { success, result: { data, status, headers }, ... }
* - Parent uses OLD reference <workflow1.result.response.data>
* - Backwards compat should strip 'response.' and resolve to result.data
*/
const workflow = createTestWorkflow([
{ id: 'workflow-block', name: 'Workflow 1', type: 'workflow' },
])
const resolver = new BlockResolver(workflow)
// Simulate the workflow block output after child (vibrant-cliff) executes
// Child's Response block now outputs { data, status, headers } directly (no wrapper)
// Workflow block wraps it in { success, result: <child_output>, ... }
const ctx = createTestContext('current', {
'workflow-block': {
success: true,
childWorkflowName: 'vibrant-cliff',
result: {
// This is what Response block outputs after our changes (no 'response' wrapper)
data: { hi: 'fuck' },
status: 200,
headers: { 'Content-Type': 'application/json' },
},
},
})
// OLD reference pattern: <workflow1.result.response.data>
// Should work via backwards compatibility (strips 'response.')
expect(resolver.resolve('<workflow1.result.response.data>', ctx)).toEqual({ hi: 'fuck' })
expect(resolver.resolve('<workflow1.result.response.data.hi>', ctx)).toBe('fuck')
expect(resolver.resolve('<workflow1.result.response.status>', ctx)).toBe(200)
// NEW reference pattern: <workflow1.result.data>
// Should work directly
expect(resolver.resolve('<workflow1.result.data>', ctx)).toEqual({ hi: 'fuck' })
expect(resolver.resolve('<workflow1.result.data.hi>', ctx)).toBe('fuck')
expect(resolver.resolve('<workflow1.result.status>', ctx)).toBe(200)
// Other workflow block properties should still work
expect(resolver.resolve('<workflow1.success>', ctx)).toBe(true)
expect(resolver.resolve('<workflow1.childWorkflowName>', ctx)).toBe('vibrant-cliff')
}
)
})
describe('edge cases', () => {
it.concurrent('should handle case-insensitive block name matching', () => {
const workflow = createTestWorkflow([{ id: 'block-1', name: 'My Block' }])

View File

@@ -48,7 +48,6 @@ export class BlockResolver implements Resolver {
}
const output = this.getBlockOutput(blockId, context)
if (output === undefined) {
return undefined
}
@@ -56,16 +55,62 @@ export class BlockResolver implements Resolver {
return output
}
const result = navigatePath(output, pathParts)
// Try the original path first
let result = navigatePath(output, pathParts)
if (result === undefined) {
const availableKeys = output && typeof output === 'object' ? Object.keys(output) : []
throw new Error(
`No value found at path "${pathParts.join('.')}" in block "${blockName}". Available fields: ${availableKeys.join(', ')}`
)
// If successful, return it immediately
if (result !== undefined) {
return result
}
return result
// If failed, check if we should try backwards compatibility fallback
const block = this.workflow.blocks.find((b) => b.id === blockId)
// Response block backwards compatibility:
// Old: <responseBlock.response.data> -> New: <responseBlock.data>
// Only apply fallback if:
// 1. Block type is 'response'
// 2. Path starts with 'response.'
// 3. Output doesn't have a 'response' key (confirming it's the new format)
if (
block?.metadata?.id === 'response' &&
pathParts[0] === 'response' &&
output?.response === undefined
) {
const adjustedPathParts = pathParts.slice(1)
if (adjustedPathParts.length === 0) {
return output
}
result = navigatePath(output, adjustedPathParts)
if (result !== undefined) {
return result
}
}
// Workflow block backwards compatibility:
// Old: <workflowBlock.result.response.data> -> New: <workflowBlock.result.data>
// Only apply fallback if:
// 1. Block type is 'workflow'
// 2. Path starts with 'result.response.'
// 3. output.result.response doesn't exist (confirming child used new format)
if (
block?.metadata?.id === 'workflow' &&
pathParts[0] === 'result' &&
pathParts[1] === 'response' &&
output?.result?.response === undefined
) {
const adjustedPathParts = ['result', ...pathParts.slice(2)]
result = navigatePath(output, adjustedPathParts)
if (result !== undefined) {
return result
}
}
// If still undefined, throw error with original path
const availableKeys = output && typeof output === 'object' ? Object.keys(output) : []
throw new Error(
`No value found at path "${pathParts.join('.')}" in block "${blockName}". Available fields: ${availableKeys.join(', ')}`
)
}
private getBlockOutput(blockId: string, context: ResolutionContext): any {

View File

@@ -42,11 +42,7 @@ interface StreamingState {
}
function extractOutputValue(output: any, path: string): any {
let value = traverseObjectPath(output, path)
if (value === undefined && output?.response) {
value = traverseObjectPath(output.response, path)
}
return value
return traverseObjectPath(output, path)
}
function isDangerousKey(key: string): boolean {

View File

@@ -136,12 +136,7 @@ export async function updateWorkflowRunCounts(workflowId: string, runs = 1) {
}
export const workflowHasResponseBlock = (executionResult: ExecutionResult): boolean => {
if (
!executionResult?.logs ||
!Array.isArray(executionResult.logs) ||
!executionResult.success ||
!executionResult.output.response
) {
if (!executionResult?.logs || !Array.isArray(executionResult.logs) || !executionResult.success) {
return false
}
@@ -154,8 +149,7 @@ export const workflowHasResponseBlock = (executionResult: ExecutionResult): bool
// Create a HTTP response from response block
export const createHttpResponseFromBlock = (executionResult: ExecutionResult): NextResponse => {
const output = executionResult.output.response
const { data = {}, status = 200, headers = {} } = output
const { data = {}, status = 200, headers = {} } = executionResult.output
const responseHeaders = new Headers({
'Content-Type': 'application/json',