akhaliq HF Staff commited on
Commit
a239a2c
·
1 Parent(s): 0796f2b

Fix JS client stream consumption by switching from .on() to async iterator

Browse files
Files changed (1) hide show
  1. index.html +20 -27
index.html CHANGED
@@ -1112,23 +1112,25 @@
1112
  max_tokens: tokens
1113
  });
1114
 
1115
- activeJob.on("data", (dataEvent) => {
1116
- const streamedText = dataEvent.data[0];
1117
- updateAssistantStream(currentMessageId, streamedText);
1118
- });
1119
-
1120
- activeJob.on("status", (statusEvent) => {
1121
- // Can monitor queue status here if needed
1122
- });
1123
-
1124
- activeJob.on("error", (err) => {
1125
- console.error("Job error:", err);
1126
- clearInterval(timerInterval);
1127
- updateMessageError(currentMessageId, "An error occurred during text generation.");
1128
- isGenerating = false;
1129
- resetSubmitButton();
1130
- updateStatus("ready", "Error");
1131
- });
 
 
1132
 
1133
  } catch (err) {
1134
  console.error("Submission failed:", err);
@@ -1428,16 +1430,7 @@
1428
  updateStatus("ready", "Server Ready");
1429
  };
1430
 
1431
- // Hook finalize generation on custom check if necessary
1432
- // We add an interval hook to check if activeJob has finished and set isGenerating = false
1433
- setInterval(() => {
1434
- if (isGenerating && activeJob) {
1435
- // If the job is resolved or cancelled
1436
- if (activeJob.status === "complete" || activeJob.status === "error") {
1437
- finalizeGeneration(currentMessageId);
1438
- }
1439
- }
1440
- }, 1000);
1441
  </script>
1442
  </body>
1443
  </html>
 
1112
  max_tokens: tokens
1113
  });
1114
 
1115
+ // Consume stream using async iterator
1116
+ (async () => {
1117
+ try {
1118
+ for await (const msg of activeJob) {
1119
+ if (msg && msg.data) {
1120
+ const streamedText = msg.data[0];
1121
+ updateAssistantStream(currentMessageId, streamedText);
1122
+ }
1123
+ }
1124
+ finalizeGeneration(currentMessageId);
1125
+ } catch (err) {
1126
+ console.error("Stream reading error:", err);
1127
+ clearInterval(timerInterval);
1128
+ updateMessageError(currentMessageId, "An error occurred during text generation.");
1129
+ isGenerating = false;
1130
+ resetSubmitButton();
1131
+ updateStatus("ready", "Error");
1132
+ }
1133
+ })();
1134
 
1135
  } catch (err) {
1136
  console.error("Submission failed:", err);
 
1430
  updateStatus("ready", "Server Ready");
1431
  };
1432
 
1433
+ // Stream state is now fully managed by the async iterator loop
 
 
 
 
 
 
 
 
 
1434
  </script>
1435
  </body>
1436
  </html>