wiki/appdoc/doc_statemachine_frontend.md

10 KiB

State Machine Documentation for Frontend Chat Workflow

Overview

Die Chat-Workflow-Frontend-Logik implementiert eine State Machine, die Benutzerinteraktionen, Datei-Uploads und die Kommunikation mit dem Backend orchestriert. Die State Machine steuert die UI, das Polling und die Statusübergänge und sorgt für eine robuste, reaktive Multi-Agent-Chat-Erfahrung.

Core Objects

Frontend Workflow State Object

{
  "status": "string", // null, "running", "completed", "failed", "stopped"
  "workflowId": "string", // null oder eindeutige Workflow-ID
  "logs": [], // Log-Einträge
  "chatMessages": [], // Chat-Nachrichten
  "lastPolledLogId": "string", // ID des letzten abgeholten Logs
  "lastPolledMessageId": "string", // ID der letzten abgeholten Nachricht
  "dataStats": {
    "bytesSent": int,
    "bytesReceived": int,
    "tokensUsed": float,
    "processingTime": float
  },
  "pollFailCount": int, // Zähler für Polling-Fehler
  "pollActive": boolean, // Steuert, ob Polling aktiv ist
  "sessionId": "string" // Session-Isolation
}

User Input State Object

{
  "promptText": "string", // Aktueller Benutzereingabetext
  "additionalFiles": [ /* File-Objekte, nicht nur IDs! */ ],
  "domElements": {}, // Referenzen auf UI-DOM-Elemente
  "sessionId": "string"
}

Log Entry Object

{
  "id": "log_timestamp",
  "message": "string",
  "progress": int, // Optional, 0-100
  "type": "string", // info, warning, error
  "timestamp": "ISO-datetime",
  "agentName": "string", // Name des Agents
  "waiting": boolean, // Zeigt Wartedots-Animation
  "highlighted": boolean // Für visuelles Highlighting
}

Chat Message Object

{
  "id": "msg_type_timestamp",
  "role": "string", // user, assistant  
  "agentName": "string",
  "content": "string",
  "documents": [], // Liste von File-Objekten
  "timestamp": "ISO-datetime",
  "status": "string" // first, step, last
}

File Object

{
  "id": "number|string", // numerisch oder UUID
  "name": "fileName.ext",
  "size": int,
  "mimeType": "string", // MIME-Type (z.B. application/pdf)
  "base64Encoded": boolean, // optional
  "content": "string", // optional, für Preview
  "isExtracted": boolean // optional, Parsing-Status
}

State Machine Workflow

1. Initial State

  • State: null (Kein Workflow aktiv)
  • UI: Leerer Chat, Eingabefeld aktiv, Start-Button aktiv, Stop-Button ausgeblendet, File-Upload aktiv, leeres Logpanel
  • Aktionen: Prompt eingeben, Dateien anhängen, Start klicken
  • API: Keine

2. Prompt Preparation

  • State: null (Übergang zu running)
  • Trigger: Eingabe im Promptfeld, Datei-Upload, Prompt-Auswahl
  • Prozess: Dateien werden via api.uploadFile hochgeladen, erscheinen als File-Objekte in userInputState.additionalFiles
  • API: POST /api/files/upload pro Datei

3. Workflow Initialization

  • State: running
  • Trigger: Start-Button oder Enter
  • Prozess: Validierung, UI-Ladezustand, Prompt und Files an Backend, Workflow-ID empfangen
  • State-Änderungen: statusrunning, workflowId gesetzt, Files und Prompt zurückgesetzt
  • API: POST /api/workflows/start (bzw. mit ID für Fortsetzung)

4. Polling for Updates

  • State: running
  • Prozess: Polling für Status, Logs, Messages (nur wenn pollActive true)
  • Polling-Details:
    • Status: alle 2000ms
    • Logs: alle 1000ms
    • Messages: alle 1000ms
    • Polling stoppt sofort bei failed oder stopped, bei completed erst nach Message mit status: last
    • Exponentielles Backoff bei Fehlern (pollFailCount)
  • API: GET /api/workflows/{workflowId}/status|logs|messages

5. Workflow Running

  • State: running
  • Prozess: Backend verarbeitet, Frontend pollt, Logs und Messages werden angezeigt
  • UI: Stop-Button sichtbar, Eingabe gesperrt, Logpanel zeigt Fortschritt, Chat zeigt Agenten-Antworten
  • Aktionen: Stop möglich, File-Previews, Downloads
  • API: wie oben, Stop: POST /api/workflows/{workflowId}/stop

6. Workflow Completion

  • State: completed
  • Trigger: Backend gibt Status "completed" oder Message mit status: last
  • Prozess: Finalmessage, Eingabe wieder aktiv, Polling stoppt
  • API: keine bis neue Eingabe

7. Workflow Failure

  • State: failed
  • Trigger: Backend gibt Status "failed"
  • Prozess: Fehlermeldung, Retry möglich, Polling stoppt
  • API: keine bis Retry

8. Workflow Stopped

  • State: stopped
  • Trigger: Stop-Button oder Backend gibt "stopped"
  • Prozess: Verarbeitung gestoppt, Polling stoppt
  • API: keine bis Fortsetzung oder Reset

9. User Input Requested

  • State: variiert
  • Trigger: Message mit status: last oder Workflow nicht mehr running
  • Prozess: Log "Waiting for user input", Eingabe aktiv
  • API: keine bis neue Eingabe

10. Continuation Preparation

  • State: completed, failed, stopped (Übergang zu running)
  • Trigger: Neue Eingabe nach vorherigem Zyklus
  • Prozess: Fortsetzung mit bestehender Workflow-ID, Files können ergänzt werden
  • API: wie Prompt Preparation

11. Workflow Resumption

  • State: running
  • Trigger: Fortsetzung nach Stop/Fehler/Abschluss
  • Prozess: Neue Eingabe mit bestehender Workflow-ID, Polling startet erneut
  • API: POST /api/workflows/start?id={workflowId}

12. Workflow Reset

  • State: null
  • Trigger: Reset-Button
  • Prozess: Alle State-Daten gelöscht, UI zurückgesetzt
  • API: Optional DELETE /api/workflows/{workflowId}

API Interaction Details

Polling Implementation

  • Polling läuft nur, wenn pollActive true ist
  • Nach Statuswechsel zu failed oder stopped wird Polling sofort gestoppt
  • Bei completed läuft Polling weiter, bis eine Message mit status: last kommt
  • Exponentielles Backoff bei Fehlern (pollFailCount)
  • Events wie workflowStatusChanged, chatMessagesUpdated, etc. synchronisieren die UI

API Endpoints Used

Frontend Function Backend Endpoint Parameters Description
startWorkflow() POST /api/workflows/start { prompt: string, fileIds: [] } Startet neuen Workflow
continueWorkflow() POST /api/workflows/start?id={workflowId} { prompt: string, fileIds: [] } Setzt bestehenden Workflow fort
pollWorkflowStatus() GET /api/workflows/{workflowId}/status None Holt aktuellen Workflow-Status
pollWorkflowLogs() GET /api/workflows/{workflowId}/logs?id={lastLogId} Optional log ID Holt neue Logs
pollWorkflowMessages() GET /api/workflows/{workflowId}/messages?id={lastMessageId} Optional message ID Holt neue Nachrichten
stopWorkflow() POST /api/workflows/{workflowId}/stop None Stoppt laufenden Workflow
resetWorkflow() DELETE /api/workflows/{workflowId} None Löscht Workflow-Ressourcen
uploadFile() POST /api/files/upload FormData mit Datei Lädt Datei hoch und gibt File-Objekt zurück
deleteMessage() DELETE /api/workflows/{workflowId}/messages/{messageId} None Entfernt Nachricht aus Workflow
removeFileFromMessage() DELETE /api/workflows/{workflowId}/messages/{messageId}/files/{fileId} None Entfernt Datei aus Nachricht

Special Features

File Handling

  • File-Uploads liefern vollständige File-Objekte (siehe oben)
  • File-Previews, Download, Copy werden unterstützt
  • Jedes File kann einzeln entfernt werden

Chat Message Rendering

  • User- und Agenten-Nachrichten, Markdown, File-Attachments, Zeitstempel, Collapsible Content

Log Panel Features

  • Info/Warning/Error, Progress, Waiting-Animation, Highlighting, Collapsible Details, Timestamps

Waiting States

  • Dots-Animation in Logs, Spinner im Send-Button, Progress in Agent-Logs
  • State-Management über waiting-Flag, waitingDotsInterval, setLoadingState()

State Transitions

[null] → [running]               // Initial prompt submission
[running] → [running]            // Ongoing polling updates
[running] → [completed]          // Workflow completes successfully
[running] → [stopped]            // User manually stops workflow
[running] → [failed]             // Error occurs during workflow
[completed] → [running]          // User continues workflow with new input
[stopped] → [running]            // User continues after manual stop
[failed] → [running]             // User retries workflow despite error
[any] → [null]                   // User resets workflow

Error Handling

Client-side Errors

  • Retry-Mechanismus im Polling (pollFailCount)
  • Exponentielles Backoff
  • Fehlerlogs und Toasts

Backend Communication Errors

  • Fehlerlogging, User-Feedback, Retry-Option, Toasts

Data Inconsistencies

  • Fallbacks bei ID-Matching, File-Referenzen, Content Extraction

Implementation Notes

  1. Module Structure:

    • workflow.js: Main initialization and coordination
    • workflowCoordination.js: State management
    • workflowData.js: Backend communication
    • workflowUi.js: UI rendering
    • workflowUtils.js: Helper functions
  2. Key Functions:

    • initWorkflowModule(): Entry point for initialization
    • updateWorkflowStatus(): Core state transition function
    • pollWorkflowStatus(): Main update loop
    • sendUserResponse(): Handles user input submission
    • renderLogs() und renderChatMessages(): UI update functions
  3. Performance Optimizations:

    • Selektive DOM-Updates
    • Scroll-Position-Preservation
    • Datenmengen-Schätzung für Statistik
    • Bedingtes Re-Rendering