@devvibex/aiflow 1.16.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -32
- package/package.json +1 -1
- package/src/index.d.ts +103 -7
- package/src/index.js +1484 -63
package/src/index.js
CHANGED
|
@@ -16,6 +16,11 @@ const JOB_WAIT_MS = 20_000;
|
|
|
16
16
|
const DEFAULT_JOB_TIMEOUT_MS = 30 * 60_000;
|
|
17
17
|
/** Times a dropped chat stream is re-attached to its job before giving up. */
|
|
18
18
|
const STREAM_RESUME_ATTEMPTS = 3;
|
|
19
|
+
/**
|
|
20
|
+
* Times a job cut off by a gateway restart (`code: 'interrupted'`) is
|
|
21
|
+
* submitted again. Such a job was never charged.
|
|
22
|
+
*/
|
|
23
|
+
const INTERRUPTED_RESUBMITS = 1;
|
|
19
24
|
|
|
20
25
|
/**
|
|
21
26
|
* Above this many seconds the gateway builds a video as independent SCENES in
|
|
@@ -77,6 +82,7 @@ export class AIFlowClient {
|
|
|
77
82
|
* @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
|
|
78
83
|
* @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
|
|
79
84
|
* @param {typeof fetch} [options.fetch] Custom fetch implementation.
|
|
85
|
+
* @param {boolean} [options.backgroundNotice] `false` turns off the background notice for the whole page (see {@link AIFlowClient.configureBackgroundNotice}).
|
|
80
86
|
*/
|
|
81
87
|
constructor({
|
|
82
88
|
appId,
|
|
@@ -93,6 +99,7 @@ export class AIFlowClient {
|
|
|
93
99
|
timeout = DEFAULT_TIMEOUT_MS,
|
|
94
100
|
maxRetries = DEFAULT_MAX_RETRIES,
|
|
95
101
|
fetch: customFetch,
|
|
102
|
+
backgroundNotice = true,
|
|
96
103
|
} = {}) {
|
|
97
104
|
if (!appId) throw new AIFlowError('appId is required');
|
|
98
105
|
if (!baseUrl) throw new AIFlowError('baseUrl is required');
|
|
@@ -167,12 +174,22 @@ export class AIFlowClient {
|
|
|
167
174
|
};
|
|
168
175
|
|
|
169
176
|
this._jobStore = new JobStore(this.appId);
|
|
177
|
+
// One registry for every client on the page: it knows which jobs a
|
|
178
|
+
// page is still waiting for, and shows the background notice for the
|
|
179
|
+
// ones whose page the user left.
|
|
180
|
+
const background = backgroundJobs();
|
|
181
|
+
this._jobStore.decorate = (entry) => background.decorate(entry);
|
|
182
|
+
this._jobStore.onChange = () => background.changed();
|
|
183
|
+
if (backgroundNotice === false) {
|
|
184
|
+
background.configure({ enabled: false });
|
|
185
|
+
}
|
|
170
186
|
/**
|
|
171
187
|
* Background jobs started from this browser, remembered for a day
|
|
172
188
|
* (localStorage; in memory where there is none) so a page can show a
|
|
173
189
|
* generation that finished, or is still running, after the user left
|
|
174
190
|
* and came back. Entries: `{ jobId, kind, tag, status, result?, error?,
|
|
175
|
-
* createdAt, updatedAt }`; `result` is what the call
|
|
191
|
+
* page?, label?, createdAt, updatedAt }`; `result` is what the call
|
|
192
|
+
* resolved with.
|
|
176
193
|
*/
|
|
177
194
|
this.jobs = {
|
|
178
195
|
/** Newest remembered job with this tag (any tag when omitted), or null. */
|
|
@@ -181,7 +198,33 @@ export class AIFlowClient {
|
|
|
181
198
|
list: ({ tag } = {}) => this._jobStore.list(tag),
|
|
182
199
|
/** Forget one job (by id) or every job with a tag. */
|
|
183
200
|
forget: (jobIdOrTag) => this._jobStore.forget(jobIdOrTag),
|
|
201
|
+
/**
|
|
202
|
+
* Pick a job up again on mount: the newest job with this tag (with no
|
|
203
|
+
* tag, the newest one started from the current page), or null.
|
|
204
|
+
* Returns `{ jobId, kind, tag, status, result?, error?, done }` —
|
|
205
|
+
* `done` resolves with what the starting call resolved with, also
|
|
206
|
+
* for a job still running after a page change or a reload. Reading
|
|
207
|
+
* `done` means the page shows the job, so the background notice
|
|
208
|
+
* hides it; a page that skips a failed job leaves its card up.
|
|
209
|
+
*/
|
|
210
|
+
attach: (tag) => this._attachJob(tag),
|
|
184
211
|
};
|
|
212
|
+
// A server-side client (holding the server key) never shows UI.
|
|
213
|
+
if (!this.appSecret) background.addClient(this);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Configure the background notice for the whole page — the small panel
|
|
218
|
+
* that tells a user who left a page mid-generation that it keeps going,
|
|
219
|
+
* and shows the result when it finishes. On by default in browsers.
|
|
220
|
+
* Also off when `window.__AIFLOW_BACKGROUND_NOTICE__ === false`.
|
|
221
|
+
* @param {object} options
|
|
222
|
+
* @param {boolean} [options.enabled]
|
|
223
|
+
* @param {'bottom-left'|'bottom-right'} [options.position] Default bottom-left.
|
|
224
|
+
* @param {string} [options.locale] 'en' | 'ko' | 'vi' | 'ja' | 'zh'; default from `<html lang>`, then the browser.
|
|
225
|
+
*/
|
|
226
|
+
static configureBackgroundNotice({ enabled, position, locale } = {}) {
|
|
227
|
+
backgroundJobs().configure({ enabled, position, locale });
|
|
185
228
|
}
|
|
186
229
|
|
|
187
230
|
/**
|
|
@@ -323,7 +366,9 @@ export class AIFlowClient {
|
|
|
323
366
|
* applies (on by default).
|
|
324
367
|
*
|
|
325
368
|
* Runs as a background job (see {@link waitForJob}): `onJob(jobId)` fires
|
|
326
|
-
* once the gateway has accepted it, `tag` labels it in `jobs.latest()
|
|
369
|
+
* once the gateway has accepted it, `tag` labels it in `jobs.latest()`,
|
|
370
|
+
* and `saveTo: { entity, id, field }` has the gateway write the answer
|
|
371
|
+
* into that row when the job ends (see {@link _generate}).
|
|
327
372
|
* @returns {Promise<{id:string, model:string, content:string, usage:{inputTokens:number,outputTokens:number,creditsUsed:number}}>}
|
|
328
373
|
*/
|
|
329
374
|
async chat({
|
|
@@ -338,11 +383,13 @@ export class AIFlowClient {
|
|
|
338
383
|
timeout,
|
|
339
384
|
onJob,
|
|
340
385
|
tag,
|
|
386
|
+
saveTo,
|
|
341
387
|
} = {}) {
|
|
342
388
|
if (!Array.isArray(messages) || messages.length === 0) {
|
|
343
389
|
throw new AIFlowError('messages must be a non-empty array');
|
|
344
390
|
}
|
|
345
391
|
assertNoTools(tools);
|
|
392
|
+
assertSaveTo(saveTo);
|
|
346
393
|
const resolvedModel = model || (await this._resolveDefaultModel('chat'));
|
|
347
394
|
const resolvedSystem = await this._resolveSystemPrompt(system);
|
|
348
395
|
return this._generate({
|
|
@@ -360,6 +407,8 @@ export class AIFlowClient {
|
|
|
360
407
|
timeout,
|
|
361
408
|
onJob,
|
|
362
409
|
tag,
|
|
410
|
+
saveTo,
|
|
411
|
+
label: lastUserText(messages),
|
|
363
412
|
});
|
|
364
413
|
}
|
|
365
414
|
|
|
@@ -374,7 +423,8 @@ export class AIFlowClient {
|
|
|
374
423
|
* written on the gateway — pick it up with {@link resumeChatStream} or
|
|
375
424
|
* {@link waitForJob}. `onJob(jobId)` fires as soon as the job id is known;
|
|
376
425
|
* a dropped connection is re-attached automatically. A server error frame
|
|
377
|
-
* (e.g. 402, out of credits) throws an AIFlowError.
|
|
426
|
+
* (e.g. 402, out of credits) throws an AIFlowError. With `saveTo`, the
|
|
427
|
+
* gateway writes the finished answer into that row itself.
|
|
378
428
|
*/
|
|
379
429
|
async *chatStream({
|
|
380
430
|
messages,
|
|
@@ -387,15 +437,17 @@ export class AIFlowClient {
|
|
|
387
437
|
signal,
|
|
388
438
|
onJob,
|
|
389
439
|
tag,
|
|
440
|
+
saveTo,
|
|
390
441
|
} = {}) {
|
|
391
442
|
if (!Array.isArray(messages) || messages.length === 0) {
|
|
392
443
|
throw new AIFlowError('messages must be a non-empty array');
|
|
393
444
|
}
|
|
394
445
|
assertNoTools(tools);
|
|
446
|
+
assertSaveTo(saveTo);
|
|
395
447
|
const resolvedModel = model || (await this._resolveDefaultModel('chat'));
|
|
396
448
|
const resolvedSystem = await this._resolveSystemPrompt(system);
|
|
397
449
|
const res = await this._request(
|
|
398
|
-
`/chat/stream${
|
|
450
|
+
`/chat/stream${await this._jobQuery({ tag, saveTo })}`,
|
|
399
451
|
{
|
|
400
452
|
model: resolvedModel,
|
|
401
453
|
system: resolvedSystem,
|
|
@@ -407,7 +459,12 @@ export class AIFlowClient {
|
|
|
407
459
|
},
|
|
408
460
|
{ signal, stream: true },
|
|
409
461
|
);
|
|
410
|
-
yield* this._streamChat(res, {
|
|
462
|
+
yield* this._streamChat(res, {
|
|
463
|
+
signal,
|
|
464
|
+
onJob,
|
|
465
|
+
tag,
|
|
466
|
+
label: lastUserText(messages),
|
|
467
|
+
});
|
|
411
468
|
}
|
|
412
469
|
|
|
413
470
|
/**
|
|
@@ -421,6 +478,8 @@ export class AIFlowClient {
|
|
|
421
478
|
if (!jobId || typeof jobId !== 'string') {
|
|
422
479
|
throw new AIFlowError('jobId is required');
|
|
423
480
|
}
|
|
481
|
+
// The page shows this answer again, so the notice need not.
|
|
482
|
+
backgroundJobs().claim(this, jobId);
|
|
424
483
|
const res = await this._openJobStream(jobId, from, signal);
|
|
425
484
|
yield* this._streamChat(res, { signal, jobId, from });
|
|
426
485
|
}
|
|
@@ -441,8 +500,41 @@ export class AIFlowClient {
|
|
|
441
500
|
* Read a chat SSE response as chunks. A server error frame throws. If the
|
|
442
501
|
* connection ends before the answer does, the stream is re-attached to its
|
|
443
502
|
* job from the last character received — the gateway kept writing.
|
|
503
|
+
*
|
|
504
|
+
* While it is being read, the background registry counts the answer as
|
|
505
|
+
* waited for, so it does not follow the job a second time.
|
|
444
506
|
*/
|
|
445
|
-
async *_streamChat(
|
|
507
|
+
async *_streamChat(
|
|
508
|
+
res,
|
|
509
|
+
{ signal, onJob, tag, label, jobId = null, from = 0 },
|
|
510
|
+
) {
|
|
511
|
+
const background = backgroundJobs();
|
|
512
|
+
let readingJob = null;
|
|
513
|
+
const markReading = (id) => {
|
|
514
|
+
if (readingJob || !id) return;
|
|
515
|
+
readingJob = id;
|
|
516
|
+
background.live(this, id, 1);
|
|
517
|
+
};
|
|
518
|
+
markReading(jobId);
|
|
519
|
+
try {
|
|
520
|
+
yield* this._readChatStream(res, {
|
|
521
|
+
signal,
|
|
522
|
+
onJob,
|
|
523
|
+
tag,
|
|
524
|
+
label,
|
|
525
|
+
jobId,
|
|
526
|
+
from,
|
|
527
|
+
markReading,
|
|
528
|
+
});
|
|
529
|
+
} finally {
|
|
530
|
+
if (readingJob) background.live(this, readingJob, -1);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
async *_readChatStream(
|
|
535
|
+
res,
|
|
536
|
+
{ signal, onJob, tag, label, jobId, from, markReading },
|
|
537
|
+
) {
|
|
446
538
|
let current = res;
|
|
447
539
|
let received = Math.max(0, Number(from) || 0);
|
|
448
540
|
let content = '';
|
|
@@ -459,7 +551,10 @@ export class AIFlowClient {
|
|
|
459
551
|
const match = /^aiflow-job\s+(\S+)/.exec(event.comment);
|
|
460
552
|
if (match && !jobId) {
|
|
461
553
|
jobId = match[1];
|
|
462
|
-
this._trackJob(jobId, 'chat_stream', tag, onJob
|
|
554
|
+
this._trackJob(jobId, 'chat_stream', tag, onJob, undefined, {
|
|
555
|
+
label,
|
|
556
|
+
});
|
|
557
|
+
markReading(jobId);
|
|
463
558
|
}
|
|
464
559
|
continue;
|
|
465
560
|
}
|
|
@@ -549,10 +644,12 @@ export class AIFlowClient {
|
|
|
549
644
|
timeout,
|
|
550
645
|
onJob,
|
|
551
646
|
tag,
|
|
647
|
+
saveTo,
|
|
552
648
|
} = {}) {
|
|
553
649
|
if (!prompt || typeof prompt !== 'string') {
|
|
554
650
|
throw new AIFlowError('prompt is required');
|
|
555
651
|
}
|
|
652
|
+
assertSaveTo(saveTo);
|
|
556
653
|
const resolvedModel =
|
|
557
654
|
model || (await this._resolveDefaultModel('image'));
|
|
558
655
|
// Resolve the system prompt: user-provided > server config > null,
|
|
@@ -586,6 +683,8 @@ export class AIFlowClient {
|
|
|
586
683
|
requestTimeout: 180_000,
|
|
587
684
|
onJob,
|
|
588
685
|
tag,
|
|
686
|
+
saveTo,
|
|
687
|
+
label: prompt,
|
|
589
688
|
});
|
|
590
689
|
}
|
|
591
690
|
|
|
@@ -613,10 +712,12 @@ export class AIFlowClient {
|
|
|
613
712
|
timeout,
|
|
614
713
|
onJob,
|
|
615
714
|
tag,
|
|
715
|
+
saveTo,
|
|
616
716
|
} = {}) {
|
|
617
717
|
if (!Array.isArray(pages) || pages.length === 0) {
|
|
618
718
|
throw new AIFlowError('pages must be a non-empty array');
|
|
619
719
|
}
|
|
720
|
+
assertSaveTo(saveTo);
|
|
620
721
|
const resolvedModel =
|
|
621
722
|
model || (await this._resolveDefaultModel('image'));
|
|
622
723
|
const resolvedSystem = await this._resolveSystemPrompt(system);
|
|
@@ -641,6 +742,8 @@ export class AIFlowClient {
|
|
|
641
742
|
requestTimeout: 600_000,
|
|
642
743
|
onJob,
|
|
643
744
|
tag,
|
|
745
|
+
saveTo,
|
|
746
|
+
label: prompt ?? pages[0]?.prompt,
|
|
644
747
|
});
|
|
645
748
|
}
|
|
646
749
|
|
|
@@ -654,7 +757,8 @@ export class AIFlowClient {
|
|
|
654
757
|
* unchanged from earlier SDK versions, so existing code keeps working.
|
|
655
758
|
*
|
|
656
759
|
* For finer control (e.g. your own polling UI) use {@link submitVideoJob}
|
|
657
|
-
* + {@link getVideoJob} directly.
|
|
760
|
+
* + {@link getVideoJob} directly. `saveTo: { entity, id, field }` has the
|
|
761
|
+
* gateway write the video URL into that row when the job ends.
|
|
658
762
|
*
|
|
659
763
|
* @returns {Promise<{videoUrl:string, thumbnailUrl?:string, prompt?:string, usage:{creditsUsed:number}}>}
|
|
660
764
|
*/
|
|
@@ -663,14 +767,19 @@ export class AIFlowClient {
|
|
|
663
767
|
throw new AIFlowError('prompt is required');
|
|
664
768
|
}
|
|
665
769
|
const { jobId } = await this.submitVideoJob(opts);
|
|
666
|
-
this._trackJob(jobId, 'video', opts.tag, opts.onJob
|
|
667
|
-
|
|
668
|
-
signal: opts.signal,
|
|
669
|
-
// Overall wait budget across all polls (default 10 min). Each
|
|
670
|
-
// individual poll is a short request, so the socket is never held.
|
|
671
|
-
timeout: opts.timeout ?? 600_000,
|
|
672
|
-
pollIntervalMs: opts.pollIntervalMs,
|
|
770
|
+
this._trackJob(jobId, 'video', opts.tag, opts.onJob, undefined, {
|
|
771
|
+
label: opts.prompt,
|
|
673
772
|
});
|
|
773
|
+
return this._followJob(
|
|
774
|
+
jobId,
|
|
775
|
+
this._pollVideoJob(jobId, {
|
|
776
|
+
signal: opts.signal,
|
|
777
|
+
// Overall wait budget across all polls (default 10 min). Each
|
|
778
|
+
// individual poll is a short request, so the socket is never held.
|
|
779
|
+
timeout: opts.timeout ?? 600_000,
|
|
780
|
+
pollIntervalMs: opts.pollIntervalMs,
|
|
781
|
+
}),
|
|
782
|
+
);
|
|
674
783
|
}
|
|
675
784
|
|
|
676
785
|
/**
|
|
@@ -694,10 +803,12 @@ export class AIFlowClient {
|
|
|
694
803
|
generateAudio,
|
|
695
804
|
signal,
|
|
696
805
|
timeout,
|
|
806
|
+
saveTo,
|
|
697
807
|
} = {}) {
|
|
698
808
|
if (!prompt || typeof prompt !== 'string') {
|
|
699
809
|
throw new AIFlowError('prompt is required');
|
|
700
810
|
}
|
|
811
|
+
assertSaveTo(saveTo);
|
|
701
812
|
if (lastFrame && !image) {
|
|
702
813
|
throw new AIFlowError('lastFrame requires image (the first frame)');
|
|
703
814
|
}
|
|
@@ -738,7 +849,7 @@ export class AIFlowClient {
|
|
|
738
849
|
const resolvedModel =
|
|
739
850
|
model || (await this._resolveDefaultModel('video'));
|
|
740
851
|
const res = await this._request(
|
|
741
|
-
|
|
852
|
+
`/video/jobs${await this._jobQuery({ saveTo })}`,
|
|
742
853
|
{
|
|
743
854
|
model: resolvedModel,
|
|
744
855
|
prompt,
|
|
@@ -884,14 +995,17 @@ export class AIFlowClient {
|
|
|
884
995
|
}
|
|
885
996
|
const { jobId } = await this.submitVideoMerge({ videos, signal });
|
|
886
997
|
this._trackJob(jobId, 'video', tag, onJob);
|
|
887
|
-
return this.
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
998
|
+
return this._followJob(
|
|
999
|
+
jobId,
|
|
1000
|
+
this._pollVideoJob(jobId, {
|
|
1001
|
+
signal,
|
|
1002
|
+
// Every clip is fetched and usually re-encoded on the gateway, so the
|
|
1003
|
+
// budget scales with how many were handed over.
|
|
1004
|
+
timeout: timeout ?? Math.max(600_000, videos.length * 120_000),
|
|
1005
|
+
pollIntervalMs: pollIntervalMs ?? 3_000,
|
|
1006
|
+
onProgress,
|
|
1007
|
+
}),
|
|
1008
|
+
);
|
|
895
1009
|
}
|
|
896
1010
|
|
|
897
1011
|
/**
|
|
@@ -953,18 +1067,20 @@ export class AIFlowClient {
|
|
|
953
1067
|
targetDurationSeconds,
|
|
954
1068
|
signal,
|
|
955
1069
|
timeout,
|
|
1070
|
+
saveTo,
|
|
956
1071
|
} = {}) {
|
|
957
1072
|
if (!prompt && !video) {
|
|
958
1073
|
throw new AIFlowError(
|
|
959
1074
|
'createVideoSession needs either a prompt (to generate the opening clip) or a video (to seed the timeline)',
|
|
960
1075
|
);
|
|
961
1076
|
}
|
|
1077
|
+
assertSaveTo(saveTo);
|
|
962
1078
|
// `model` is sent only when the caller chose one. Filling it from the
|
|
963
1079
|
// module default (as every other call does) would name `veo` on a module
|
|
964
1080
|
// pinned to Veo, and the gateway refuses a session on an explicitly
|
|
965
1081
|
// named non-Omni model; left out, it resolves to Omni itself.
|
|
966
1082
|
const res = await this._request(
|
|
967
|
-
|
|
1083
|
+
`/video/sessions${await this._jobQuery({ saveTo })}`,
|
|
968
1084
|
{
|
|
969
1085
|
model,
|
|
970
1086
|
prompt,
|
|
@@ -1037,6 +1153,7 @@ export class AIFlowClient {
|
|
|
1037
1153
|
pollIntervalMs,
|
|
1038
1154
|
onJob,
|
|
1039
1155
|
tag,
|
|
1156
|
+
saveTo,
|
|
1040
1157
|
} = {}) {
|
|
1041
1158
|
if (!prompt || typeof prompt !== 'string') {
|
|
1042
1159
|
throw new AIFlowError('prompt is required');
|
|
@@ -1055,18 +1172,22 @@ export class AIFlowClient {
|
|
|
1055
1172
|
description,
|
|
1056
1173
|
targetDurationSeconds: durationSeconds,
|
|
1057
1174
|
signal,
|
|
1175
|
+
saveTo,
|
|
1058
1176
|
});
|
|
1059
|
-
this._trackJob(jobId, 'video', tag, onJob, { sessionId });
|
|
1060
|
-
const result = await this.
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1177
|
+
this._trackJob(jobId, 'video', tag, onJob, { sessionId }, { label: prompt });
|
|
1178
|
+
const result = await this._followJob(
|
|
1179
|
+
jobId,
|
|
1180
|
+
this._pollVideoJob(jobId, {
|
|
1181
|
+
signal,
|
|
1182
|
+
timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
|
|
1183
|
+
// Minutes-long builds: a 5s poll on a 40-minute job is 480 pointless
|
|
1184
|
+
// requests. Progress is published per segment, not per second.
|
|
1185
|
+
pollIntervalMs:
|
|
1186
|
+
pollIntervalMs ??
|
|
1187
|
+
(durationSeconds > CONTINUOUS_MAX_SECONDS ? 15_000 : 5_000),
|
|
1188
|
+
onProgress,
|
|
1189
|
+
}),
|
|
1190
|
+
);
|
|
1070
1191
|
return { sessionId, ...result };
|
|
1071
1192
|
}
|
|
1072
1193
|
|
|
@@ -1110,12 +1231,15 @@ export class AIFlowClient {
|
|
|
1110
1231
|
} catch {
|
|
1111
1232
|
remaining = 600;
|
|
1112
1233
|
}
|
|
1113
|
-
return this.
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1234
|
+
return this._followJob(
|
|
1235
|
+
jobId,
|
|
1236
|
+
this._pollVideoJob(jobId, {
|
|
1237
|
+
signal,
|
|
1238
|
+
timeout: timeout ?? longVideoTimeoutMs(remaining),
|
|
1239
|
+
pollIntervalMs: pollIntervalMs ?? 15_000,
|
|
1240
|
+
onProgress,
|
|
1241
|
+
}),
|
|
1242
|
+
);
|
|
1119
1243
|
}
|
|
1120
1244
|
|
|
1121
1245
|
/**
|
|
@@ -1135,12 +1259,17 @@ export class AIFlowClient {
|
|
|
1135
1259
|
*/
|
|
1136
1260
|
async extendVideo(sessionId, opts = {}) {
|
|
1137
1261
|
const { jobId } = await this.submitVideoExtend(sessionId, opts);
|
|
1138
|
-
this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId }
|
|
1139
|
-
|
|
1140
|
-
signal: opts.signal,
|
|
1141
|
-
timeout: opts.timeout ?? 600_000,
|
|
1142
|
-
pollIntervalMs: opts.pollIntervalMs,
|
|
1262
|
+
this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId }, {
|
|
1263
|
+
label: opts.prompt,
|
|
1143
1264
|
});
|
|
1265
|
+
return this._followJob(
|
|
1266
|
+
jobId,
|
|
1267
|
+
this._pollVideoJob(jobId, {
|
|
1268
|
+
signal: opts.signal,
|
|
1269
|
+
timeout: opts.timeout ?? 600_000,
|
|
1270
|
+
pollIntervalMs: opts.pollIntervalMs,
|
|
1271
|
+
}),
|
|
1272
|
+
);
|
|
1144
1273
|
}
|
|
1145
1274
|
|
|
1146
1275
|
/**
|
|
@@ -1220,6 +1349,7 @@ export class AIFlowClient {
|
|
|
1220
1349
|
timeout,
|
|
1221
1350
|
onJob,
|
|
1222
1351
|
tag,
|
|
1352
|
+
saveTo,
|
|
1223
1353
|
} = {}) {
|
|
1224
1354
|
if (!prompt || typeof prompt !== 'string') {
|
|
1225
1355
|
throw new AIFlowError('prompt is required');
|
|
@@ -1227,6 +1357,7 @@ export class AIFlowClient {
|
|
|
1227
1357
|
if (images !== undefined && !Array.isArray(images)) {
|
|
1228
1358
|
throw new AIFlowError('images must be an array of URLs');
|
|
1229
1359
|
}
|
|
1360
|
+
assertSaveTo(saveTo);
|
|
1230
1361
|
const resolvedModel =
|
|
1231
1362
|
model || (await this._resolveDefaultModel('audio'));
|
|
1232
1363
|
return this._generate({
|
|
@@ -1249,6 +1380,8 @@ export class AIFlowClient {
|
|
|
1249
1380
|
requestTimeout: 180_000,
|
|
1250
1381
|
onJob,
|
|
1251
1382
|
tag,
|
|
1383
|
+
saveTo,
|
|
1384
|
+
label: prompt,
|
|
1252
1385
|
});
|
|
1253
1386
|
}
|
|
1254
1387
|
|
|
@@ -1266,10 +1399,12 @@ export class AIFlowClient {
|
|
|
1266
1399
|
timeout,
|
|
1267
1400
|
onJob,
|
|
1268
1401
|
tag,
|
|
1402
|
+
saveTo,
|
|
1269
1403
|
} = {}) {
|
|
1270
1404
|
if (!prompt || typeof prompt !== 'string') {
|
|
1271
1405
|
throw new AIFlowError('prompt is required');
|
|
1272
1406
|
}
|
|
1407
|
+
assertSaveTo(saveTo);
|
|
1273
1408
|
const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
|
|
1274
1409
|
return this._generate({
|
|
1275
1410
|
kind: 'sfx',
|
|
@@ -1286,6 +1421,8 @@ export class AIFlowClient {
|
|
|
1286
1421
|
requestTimeout: 120_000,
|
|
1287
1422
|
onJob,
|
|
1288
1423
|
tag,
|
|
1424
|
+
saveTo,
|
|
1425
|
+
label: prompt,
|
|
1289
1426
|
});
|
|
1290
1427
|
}
|
|
1291
1428
|
|
|
@@ -1364,12 +1501,27 @@ export class AIFlowClient {
|
|
|
1364
1501
|
* `jobs.latest()` / `jobs.list()` or {@link listJobs}, after a reload or on
|
|
1365
1502
|
* another page. Aborting `signal` or hitting `timeout` (default 30 min)
|
|
1366
1503
|
* stops only the waiting; the job carries on. Throws an AIFlowError with
|
|
1367
|
-
* the job's `status` / `code` when it failed.
|
|
1504
|
+
* the job's `status` / `code` when it failed. The page now shows the job,
|
|
1505
|
+
* so the background notice hides it.
|
|
1368
1506
|
*/
|
|
1369
1507
|
async waitForJob(jobId, { signal, timeout, onProgress } = {}) {
|
|
1370
1508
|
if (!jobId || typeof jobId !== 'string') {
|
|
1371
1509
|
throw new AIFlowError('jobId is required');
|
|
1372
1510
|
}
|
|
1511
|
+
const background = backgroundJobs();
|
|
1512
|
+
background.claim(this, jobId);
|
|
1513
|
+
return background.track(
|
|
1514
|
+
this,
|
|
1515
|
+
jobId,
|
|
1516
|
+
this._waitForJob(jobId, { signal, timeout, onProgress }),
|
|
1517
|
+
);
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/**
|
|
1521
|
+
* {@link waitForJob} without claiming the job for the page: what the
|
|
1522
|
+
* generation calls themselves and the background notice wait with.
|
|
1523
|
+
*/
|
|
1524
|
+
async _waitForJob(jobId, { signal, timeout, onProgress } = {}) {
|
|
1373
1525
|
const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
|
|
1374
1526
|
let lastProgress = -1;
|
|
1375
1527
|
// eslint-disable-next-line no-constant-condition
|
|
@@ -1487,17 +1639,71 @@ export class AIFlowClient {
|
|
|
1487
1639
|
* the job route and awaited, so it keeps running — and stays retrievable —
|
|
1488
1640
|
* if this page goes away; otherwise it is one request to the synchronous
|
|
1489
1641
|
* route. Both resolve with the same response body.
|
|
1642
|
+
*
|
|
1643
|
+
* `saveTo: { entity, id, field }` (gateways with `capabilities.saveTo`):
|
|
1644
|
+
* the gateway writes the outcome into that row itself, so it lands even
|
|
1645
|
+
* when the tab was closed — `job_id` on accept, then `{ [field]: value,
|
|
1646
|
+
* status: 'done' }` or `{ status: 'failed', error }`, each only where the
|
|
1647
|
+
* entity has the field. `value` is the answer text (chat), the image URL
|
|
1648
|
+
* (all URLs for an array field), the audio URL (music / SFX) or the video
|
|
1649
|
+
* URL. The submit is refused (400 / 403 / 404) when the row is missing or
|
|
1650
|
+
* the caller may not update it.
|
|
1490
1651
|
*/
|
|
1491
|
-
async _generate({
|
|
1652
|
+
async _generate({
|
|
1653
|
+
kind,
|
|
1654
|
+
path,
|
|
1655
|
+
body,
|
|
1656
|
+
signal,
|
|
1657
|
+
timeout,
|
|
1658
|
+
requestTimeout,
|
|
1659
|
+
onJob,
|
|
1660
|
+
tag,
|
|
1661
|
+
saveTo,
|
|
1662
|
+
label,
|
|
1663
|
+
}) {
|
|
1492
1664
|
if (await this._jobsEnabled()) {
|
|
1493
|
-
const
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1665
|
+
const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
|
|
1666
|
+
const query = await this._jobQuery({ tag, saveTo });
|
|
1667
|
+
// A re-run belongs to the page the first submit came from.
|
|
1668
|
+
const page = pageKey();
|
|
1669
|
+
let previous = null;
|
|
1670
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1671
|
+
const res = await this._request(`${path}/jobs${query}`, body, {
|
|
1672
|
+
signal,
|
|
1673
|
+
timeout: requestTimeout ?? DEFAULT_TIMEOUT_MS,
|
|
1674
|
+
});
|
|
1675
|
+
const { jobId } = await res.json();
|
|
1676
|
+
this._trackJob(jobId, kind, tag, onJob, undefined, {
|
|
1677
|
+
label,
|
|
1678
|
+
page,
|
|
1679
|
+
orphaned: previous?.orphaned,
|
|
1680
|
+
});
|
|
1681
|
+
try {
|
|
1682
|
+
return await this._followJob(
|
|
1683
|
+
jobId,
|
|
1684
|
+
this._waitForJob(jobId, {
|
|
1685
|
+
signal,
|
|
1686
|
+
timeout: Math.max(1, deadline - Date.now()),
|
|
1687
|
+
}),
|
|
1688
|
+
);
|
|
1689
|
+
} catch (err) {
|
|
1690
|
+
// The gateway pod running the job restarted (a deploy or a
|
|
1691
|
+
// scale-down) before it finished. Nothing was charged, so run
|
|
1692
|
+
// it once more — what the retry on a cut-off synchronous
|
|
1693
|
+
// request used to do. `onJob` fires again with the new id.
|
|
1694
|
+
const rerun =
|
|
1695
|
+
err?.code === 'interrupted' &&
|
|
1696
|
+
attempt < INTERRUPTED_RESUBMITS &&
|
|
1697
|
+
!signal?.aborted &&
|
|
1698
|
+
Date.now() < deadline;
|
|
1699
|
+
if (!rerun) throw err;
|
|
1700
|
+
// The re-run replaces it: its failure is not news.
|
|
1701
|
+
previous = this._jobStore.get(jobId);
|
|
1702
|
+
this._jobStore.patch(jobId, { hidden: true });
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1500
1705
|
}
|
|
1706
|
+
if (saveTo) this._warnSaveToUnsupported();
|
|
1501
1707
|
const res = await this._request(path, body, {
|
|
1502
1708
|
signal,
|
|
1503
1709
|
timeout: timeout ?? requestTimeout,
|
|
@@ -1514,10 +1720,67 @@ export class AIFlowClient {
|
|
|
1514
1720
|
}
|
|
1515
1721
|
}
|
|
1516
1722
|
|
|
1517
|
-
/**
|
|
1518
|
-
|
|
1723
|
+
/**
|
|
1724
|
+
* Query string for a job route: `tag`, and `saveTo` as
|
|
1725
|
+
* `saveEntity` / `saveId` / `saveField` when the gateway can write
|
|
1726
|
+
* results into rows (`config.capabilities.saveTo`).
|
|
1727
|
+
*/
|
|
1728
|
+
async _jobQuery({ tag, saveTo } = {}) {
|
|
1729
|
+
let save = null;
|
|
1730
|
+
if (saveTo) {
|
|
1731
|
+
let supported = false;
|
|
1732
|
+
try {
|
|
1733
|
+
const cfg = await this.getConfig();
|
|
1734
|
+
supported = cfg?.capabilities?.saveTo === true;
|
|
1735
|
+
} catch {
|
|
1736
|
+
supported = false;
|
|
1737
|
+
}
|
|
1738
|
+
if (supported) save = saveTo;
|
|
1739
|
+
else this._warnSaveToUnsupported();
|
|
1740
|
+
}
|
|
1741
|
+
return jobQuery({ tag, saveTo: save });
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
_warnSaveToUnsupported() {
|
|
1745
|
+
if (this._warnedSaveTo) return;
|
|
1746
|
+
this._warnedSaveTo = true;
|
|
1747
|
+
try {
|
|
1748
|
+
console.warn(
|
|
1749
|
+
'[AIFlow] saveTo is ignored: this gateway cannot write results into rows yet — save the result from the resolved value instead.',
|
|
1750
|
+
);
|
|
1751
|
+
} catch {
|
|
1752
|
+
/* no console */
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/**
|
|
1757
|
+
* Register `promise` as the page's wait for `jobId` (the starting call's
|
|
1758
|
+
* own wait), so `jobs.attach()` can share it and the background notice
|
|
1759
|
+
* does not follow the job twice. Returns `promise`.
|
|
1760
|
+
*/
|
|
1761
|
+
_followJob(jobId, promise) {
|
|
1762
|
+
return backgroundJobs().track(this, jobId, promise);
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/**
|
|
1766
|
+
* Remember a started job and hand its id to the caller's `onJob`. `meta`:
|
|
1767
|
+
* `label` (prompt shown by the notice), `page` (defaults to the current
|
|
1768
|
+
* one) and `orphaned` (carried over from a job this one re-runs).
|
|
1769
|
+
*/
|
|
1770
|
+
_trackJob(jobId, kind, tag, onJob, extra, meta = {}) {
|
|
1519
1771
|
if (!jobId) return;
|
|
1520
|
-
|
|
1772
|
+
const label = typeof meta.label === 'string' ? meta.label.trim() : '';
|
|
1773
|
+
this._jobStore.put({
|
|
1774
|
+
jobId,
|
|
1775
|
+
kind,
|
|
1776
|
+
tag,
|
|
1777
|
+
status: 'processing',
|
|
1778
|
+
bg: 1,
|
|
1779
|
+
page: meta.page ?? pageKey(),
|
|
1780
|
+
label: label ? label.slice(0, BG_LABEL_MAX_CHARS) : undefined,
|
|
1781
|
+
orphaned: meta.orphaned ? true : undefined,
|
|
1782
|
+
});
|
|
1783
|
+
backgroundJobs().started(this, jobId);
|
|
1521
1784
|
if (typeof onJob === 'function') {
|
|
1522
1785
|
try {
|
|
1523
1786
|
onJob(jobId, extra);
|
|
@@ -1528,6 +1791,49 @@ export class AIFlowClient {
|
|
|
1528
1791
|
}
|
|
1529
1792
|
}
|
|
1530
1793
|
|
|
1794
|
+
/** `jobs.attach(tag?)` — see the constructor. */
|
|
1795
|
+
_attachJob(tag) {
|
|
1796
|
+
const page = pageKey();
|
|
1797
|
+
const entries = this._jobStore.list(tag);
|
|
1798
|
+
const entry =
|
|
1799
|
+
tag === undefined || tag === null
|
|
1800
|
+
? entries.find((e) => (e.page ?? '') === page)
|
|
1801
|
+
: entries[0];
|
|
1802
|
+
if (!entry) return null;
|
|
1803
|
+
const background = backgroundJobs();
|
|
1804
|
+
const client = this;
|
|
1805
|
+
const status = entry.status === 'queued' ? 'processing' : entry.status;
|
|
1806
|
+
let done = null;
|
|
1807
|
+
return {
|
|
1808
|
+
jobId: entry.jobId,
|
|
1809
|
+
kind: entry.kind,
|
|
1810
|
+
tag: entry.tag,
|
|
1811
|
+
status,
|
|
1812
|
+
...(entry.result !== undefined ? { result: entry.result } : {}),
|
|
1813
|
+
...(entry.error ? { error: entry.error } : {}),
|
|
1814
|
+
// Created on first read, so an attached failure nobody asked about
|
|
1815
|
+
// never surfaces as an unhandled rejection. Reading it is what
|
|
1816
|
+
// claims the job for this page.
|
|
1817
|
+
get done() {
|
|
1818
|
+
if (!done) {
|
|
1819
|
+
background.claim(client, entry.jobId);
|
|
1820
|
+
if (status === 'succeeded' && entry.result !== undefined) {
|
|
1821
|
+
done = Promise.resolve(entry.result);
|
|
1822
|
+
} else if (status === 'failed') {
|
|
1823
|
+
done = Promise.reject(
|
|
1824
|
+
new AIFlowError(entry.error || 'Generation failed', {
|
|
1825
|
+
code: 'job_failed',
|
|
1826
|
+
}),
|
|
1827
|
+
);
|
|
1828
|
+
} else {
|
|
1829
|
+
done = background.wait(client, entry.jobId);
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
return done;
|
|
1833
|
+
},
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1531
1837
|
/**
|
|
1532
1838
|
* Open a real-time speech-translation session over WebSocket (Gemini Live
|
|
1533
1839
|
* via the platform gateway — no Google key in the browser). Stream 16 kHz
|
|
@@ -2121,6 +2427,18 @@ class JobStore {
|
|
|
2121
2427
|
constructor(appId) {
|
|
2122
2428
|
this._key = `aiflow:jobs:${appId}`;
|
|
2123
2429
|
this._memory = [];
|
|
2430
|
+
/** Set by the client: adds the notice flags to an entry as it settles. */
|
|
2431
|
+
this.decorate = null;
|
|
2432
|
+
/** Set by the client: called after every write. */
|
|
2433
|
+
this.onChange = null;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
_changed() {
|
|
2437
|
+
try {
|
|
2438
|
+
this.onChange?.();
|
|
2439
|
+
} catch {
|
|
2440
|
+
/* the notice never breaks bookkeeping */
|
|
2441
|
+
}
|
|
2124
2442
|
}
|
|
2125
2443
|
|
|
2126
2444
|
_storage() {
|
|
@@ -2187,6 +2505,22 @@ class JobStore {
|
|
|
2187
2505
|
if (i >= 0) list[i] = next;
|
|
2188
2506
|
else list.push(next);
|
|
2189
2507
|
this._write(list);
|
|
2508
|
+
this._changed();
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
get(jobId) {
|
|
2512
|
+
const entry = this._read().find((e) => e.jobId === jobId);
|
|
2513
|
+
return entry ? { ...entry } : null;
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
/** Set bookkeeping fields on a job this browser is tracking. */
|
|
2517
|
+
patch(jobId, fields) {
|
|
2518
|
+
const list = this._read();
|
|
2519
|
+
const i = list.findIndex((e) => e.jobId === jobId);
|
|
2520
|
+
if (i < 0) return;
|
|
2521
|
+
list[i] = { ...list[i], ...fields, updatedAt: Date.now() };
|
|
2522
|
+
this._write(list);
|
|
2523
|
+
this._changed();
|
|
2190
2524
|
}
|
|
2191
2525
|
|
|
2192
2526
|
/** Record an outcome — only for a job this browser is tracking. */
|
|
@@ -2210,8 +2544,19 @@ class JobStore {
|
|
|
2210
2544
|
delete next.resultOmitted;
|
|
2211
2545
|
}
|
|
2212
2546
|
}
|
|
2547
|
+
if (
|
|
2548
|
+
this.decorate &&
|
|
2549
|
+
(next.status === 'succeeded' || next.status === 'failed')
|
|
2550
|
+
) {
|
|
2551
|
+
try {
|
|
2552
|
+
this.decorate(next);
|
|
2553
|
+
} catch {
|
|
2554
|
+
/* the notice never breaks bookkeeping */
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2213
2557
|
list[i] = next;
|
|
2214
2558
|
this._write(list);
|
|
2559
|
+
this._changed();
|
|
2215
2560
|
}
|
|
2216
2561
|
|
|
2217
2562
|
list(tag) {
|
|
@@ -2232,13 +2577,56 @@ class JobStore {
|
|
|
2232
2577
|
(e) => e.jobId !== jobIdOrTag && e.tag !== jobIdOrTag,
|
|
2233
2578
|
),
|
|
2234
2579
|
);
|
|
2580
|
+
this._changed();
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
/**
|
|
2585
|
+
* Query string for a job route: `tag` (labels the job; capped like the
|
|
2586
|
+
* gateway caps it) and the `saveTo` target as `saveEntity` / `saveId` /
|
|
2587
|
+
* `saveField`.
|
|
2588
|
+
*/
|
|
2589
|
+
function jobQuery({ tag, saveTo } = {}) {
|
|
2590
|
+
const params = [];
|
|
2591
|
+
if (tag !== undefined && tag !== null && tag !== '') {
|
|
2592
|
+
params.push(`tag=${encodeURIComponent(String(tag).slice(0, 128))}`);
|
|
2593
|
+
}
|
|
2594
|
+
if (saveTo) {
|
|
2595
|
+
params.push(
|
|
2596
|
+
`saveEntity=${encodeURIComponent(String(saveTo.entity))}`,
|
|
2597
|
+
`saveId=${encodeURIComponent(String(saveTo.id))}`,
|
|
2598
|
+
`saveField=${encodeURIComponent(String(saveTo.field))}`,
|
|
2599
|
+
);
|
|
2235
2600
|
}
|
|
2601
|
+
return params.length ? `?${params.join('&')}` : '';
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
/** `saveTo` must name a row and one of its fields: `{ entity, id, field }`. */
|
|
2605
|
+
function assertSaveTo(saveTo) {
|
|
2606
|
+
if (saveTo === undefined || saveTo === null) return;
|
|
2607
|
+
const filled = (v) => typeof v === 'string' && v.trim() !== '';
|
|
2608
|
+
const ok =
|
|
2609
|
+
typeof saveTo === 'object' &&
|
|
2610
|
+
filled(saveTo.entity) &&
|
|
2611
|
+
filled(saveTo.field) &&
|
|
2612
|
+
(filled(saveTo.id) ||
|
|
2613
|
+
(typeof saveTo.id === 'number' && Number.isFinite(saveTo.id)));
|
|
2614
|
+
if (!ok) throw new AIFlowError('saveTo needs entity, id and field');
|
|
2236
2615
|
}
|
|
2237
2616
|
|
|
2238
|
-
/**
|
|
2239
|
-
function
|
|
2240
|
-
if (
|
|
2241
|
-
|
|
2617
|
+
/** Text of the last user message, to label a chat job. */
|
|
2618
|
+
function lastUserText(messages) {
|
|
2619
|
+
if (!Array.isArray(messages)) return undefined;
|
|
2620
|
+
const last = [...messages].reverse().find((m) => m?.role === 'user');
|
|
2621
|
+
if (!last) return undefined;
|
|
2622
|
+
if (typeof last.content === 'string') return last.content;
|
|
2623
|
+
if (Array.isArray(last.content)) {
|
|
2624
|
+
return last.content
|
|
2625
|
+
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
2626
|
+
.map((b) => b.text)
|
|
2627
|
+
.join(' ');
|
|
2628
|
+
}
|
|
2629
|
+
return undefined;
|
|
2242
2630
|
}
|
|
2243
2631
|
|
|
2244
2632
|
/** A finished video job as `generateVideo` has always resolved it. */
|
|
@@ -2371,4 +2759,1037 @@ async function safeJson(res) {
|
|
|
2371
2759
|
}
|
|
2372
2760
|
}
|
|
2373
2761
|
|
|
2762
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
2763
|
+
// Background notice
|
|
2764
|
+
//
|
|
2765
|
+
// A generation keeps running on the gateway when the user leaves the page that
|
|
2766
|
+
// started it, but that page's code is gone and nothing on screen says so. The
|
|
2767
|
+
// registry below — one per page, shared by every AIFlowClient — notices when a
|
|
2768
|
+
// job's page was left (or a previous page load started it), follows the job to
|
|
2769
|
+
// the end, and shows a small panel: "still generating", then the result with a
|
|
2770
|
+
// way back to the page. A page that picks the job up itself (`jobs.attach`,
|
|
2771
|
+
// `waitForJob`, `resumeChatStream`) claims it and the panel stays out of the way.
|
|
2772
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
2773
|
+
|
|
2774
|
+
/** How often the page is checked while a job of this page load is running. */
|
|
2775
|
+
const BG_PAGE_POLL_MS = 500;
|
|
2776
|
+
/** After load, how long a page has to claim a job a previous load started. */
|
|
2777
|
+
const BG_CLAIM_GRACE_MS = 1_500;
|
|
2778
|
+
/** Pause before following a job again after a failed wait. */
|
|
2779
|
+
const BG_FOLLOW_BACKOFF_MS = [5_000, 15_000, 60_000, 120_000];
|
|
2780
|
+
/** Longest the notice waits for a video (builds run for many minutes). */
|
|
2781
|
+
const BG_VIDEO_WAIT_MS = 2 * 60 * 60_000;
|
|
2782
|
+
const BG_LABEL_MAX_CHARS = 80;
|
|
2783
|
+
const BG_SNIPPET_MAX_CHARS = 280;
|
|
2784
|
+
const BG_MAX_CARDS = 3;
|
|
2785
|
+
|
|
2786
|
+
function isBrowser() {
|
|
2787
|
+
try {
|
|
2788
|
+
return (
|
|
2789
|
+
typeof window !== 'undefined' &&
|
|
2790
|
+
typeof document !== 'undefined' &&
|
|
2791
|
+
!!window.location
|
|
2792
|
+
);
|
|
2793
|
+
} catch {
|
|
2794
|
+
return false;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
/**
|
|
2799
|
+
* The page a job belongs to: the path, plus the route of a hash router
|
|
2800
|
+
* (`#/…`). Empty outside a browser.
|
|
2801
|
+
*/
|
|
2802
|
+
function pageKey() {
|
|
2803
|
+
if (!isBrowser()) return '';
|
|
2804
|
+
try {
|
|
2805
|
+
const { pathname, hash } = window.location;
|
|
2806
|
+
return hash && hash.startsWith('#/')
|
|
2807
|
+
? `${pathname}${hash}`
|
|
2808
|
+
: pathname || '';
|
|
2809
|
+
} catch {
|
|
2810
|
+
return '';
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
function isSettledEntry(entry) {
|
|
2815
|
+
return entry.status === 'succeeded' || entry.status === 'failed';
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
let backgroundSingleton = null;
|
|
2819
|
+
|
|
2820
|
+
/** The page-wide registry, created on first use (never at import). */
|
|
2821
|
+
function backgroundJobs() {
|
|
2822
|
+
if (!backgroundSingleton) backgroundSingleton = new BackgroundJobs();
|
|
2823
|
+
return backgroundSingleton;
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
/**
|
|
2827
|
+
* Per-page bookkeeping of background jobs. In memory (this page load):
|
|
2828
|
+
* who is waiting for each job and which page claimed it. In each client's
|
|
2829
|
+
* JobStore entry (survives reloads): `page`, `label`, `bg: 1` and the notice
|
|
2830
|
+
* flags `orphaned` (its page was left), `delivered` (it finished where a page
|
|
2831
|
+
* showed it), `dismissed` (the user closed its card) and `hidden`.
|
|
2832
|
+
*/
|
|
2833
|
+
class BackgroundJobs {
|
|
2834
|
+
constructor() {
|
|
2835
|
+
this._jobs = new Map();
|
|
2836
|
+
this._clients = new Map();
|
|
2837
|
+
this._scanned = new Set();
|
|
2838
|
+
this._config = { enabled: true, position: 'bottom-left', locale: null };
|
|
2839
|
+
this._timer = null;
|
|
2840
|
+
this._quietUntil = 0;
|
|
2841
|
+
this._listening = false;
|
|
2842
|
+
this._renderQueued = false;
|
|
2843
|
+
this._view = null;
|
|
2844
|
+
}
|
|
2845
|
+
|
|
2846
|
+
configure({ enabled, position, locale } = {}) {
|
|
2847
|
+
if (typeof enabled === 'boolean') this._config.enabled = enabled;
|
|
2848
|
+
if (position === 'bottom-left' || position === 'bottom-right') {
|
|
2849
|
+
this._config.position = position;
|
|
2850
|
+
}
|
|
2851
|
+
if (locale !== undefined) this._config.locale = locale || null;
|
|
2852
|
+
if (this._enabled()) this._ensureTimer();
|
|
2853
|
+
this.changed();
|
|
2854
|
+
}
|
|
2855
|
+
|
|
2856
|
+
_enabled() {
|
|
2857
|
+
if (!this._config.enabled || !isBrowser()) return false;
|
|
2858
|
+
try {
|
|
2859
|
+
return window.__AIFLOW_BACKGROUND_NOTICE__ !== false;
|
|
2860
|
+
} catch {
|
|
2861
|
+
return true;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
_state(client, jobId) {
|
|
2866
|
+
let state = this._jobs.get(jobId);
|
|
2867
|
+
if (!state) {
|
|
2868
|
+
state = {
|
|
2869
|
+
jobId,
|
|
2870
|
+
client,
|
|
2871
|
+
recovered: false,
|
|
2872
|
+
graceUntil: 0,
|
|
2873
|
+
claimedPage: null,
|
|
2874
|
+
waiting: new Set(),
|
|
2875
|
+
shared: null,
|
|
2876
|
+
live: 0,
|
|
2877
|
+
following: false,
|
|
2878
|
+
failures: 0,
|
|
2879
|
+
nextFollowAt: 0,
|
|
2880
|
+
};
|
|
2881
|
+
this._jobs.set(jobId, state);
|
|
2882
|
+
}
|
|
2883
|
+
return state;
|
|
2884
|
+
}
|
|
2885
|
+
|
|
2886
|
+
/**
|
|
2887
|
+
* A browser-side client: its jobs may show in the notice. The first time
|
|
2888
|
+
* an app id is seen in this page load, the jobs a previous load left
|
|
2889
|
+
* running are picked up — after a short grace in which the page can
|
|
2890
|
+
* claim them.
|
|
2891
|
+
*/
|
|
2892
|
+
addClient(client) {
|
|
2893
|
+
if (!isBrowser()) return;
|
|
2894
|
+
this._clients.set(client.appId, client);
|
|
2895
|
+
this._listen();
|
|
2896
|
+
if (this._scanned.has(client.appId)) return;
|
|
2897
|
+
this._scanned.add(client.appId);
|
|
2898
|
+
const now = Date.now();
|
|
2899
|
+
if (!this._quietUntil) {
|
|
2900
|
+
// Cards from a previous load wait for the grace too, so a page
|
|
2901
|
+
// that attaches on mount never sees them flash.
|
|
2902
|
+
this._quietUntil = now + BG_CLAIM_GRACE_MS;
|
|
2903
|
+
try {
|
|
2904
|
+
setTimeout(() => this.changed(), BG_CLAIM_GRACE_MS + 50);
|
|
2905
|
+
} catch {
|
|
2906
|
+
/* no timers */
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
let recovered = false;
|
|
2910
|
+
for (const entry of client._jobStore.list()) {
|
|
2911
|
+
if (!entry.bg || entry.hidden || isSettledEntry(entry)) continue;
|
|
2912
|
+
if (this._jobs.has(entry.jobId)) continue;
|
|
2913
|
+
const state = this._state(client, entry.jobId);
|
|
2914
|
+
state.recovered = true;
|
|
2915
|
+
state.graceUntil = now + BG_CLAIM_GRACE_MS;
|
|
2916
|
+
recovered = true;
|
|
2917
|
+
}
|
|
2918
|
+
if (recovered) this._ensureTimer();
|
|
2919
|
+
this.changed();
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
/** A job this page load just started. */
|
|
2923
|
+
started(client, jobId) {
|
|
2924
|
+
this._state(client, jobId);
|
|
2925
|
+
this._ensureTimer();
|
|
2926
|
+
this.changed();
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
/**
|
|
2930
|
+
* Count `promise` as a wait for `jobId`. The first one becomes the shared
|
|
2931
|
+
* wait `jobs.attach()` hands out. Returns `promise` unchanged.
|
|
2932
|
+
*/
|
|
2933
|
+
track(client, jobId, promise) {
|
|
2934
|
+
if (!jobId || !promise || typeof promise.then !== 'function') {
|
|
2935
|
+
return promise;
|
|
2936
|
+
}
|
|
2937
|
+
const state = this._state(client, jobId);
|
|
2938
|
+
state.waiting.add(promise);
|
|
2939
|
+
if (!state.shared) state.shared = promise;
|
|
2940
|
+
const release = () => {
|
|
2941
|
+
state.waiting.delete(promise);
|
|
2942
|
+
this._tickSoon();
|
|
2943
|
+
};
|
|
2944
|
+
promise.then(release, () => {
|
|
2945
|
+
// Stopped waiting (abort, timeout, network) without an outcome:
|
|
2946
|
+
// the next attach must wait afresh, not inherit that error.
|
|
2947
|
+
const entry = state.client._jobStore.get(jobId);
|
|
2948
|
+
if (state.shared === promise && entry?.status !== 'failed') {
|
|
2949
|
+
state.shared = null;
|
|
2950
|
+
}
|
|
2951
|
+
release();
|
|
2952
|
+
});
|
|
2953
|
+
return promise;
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2956
|
+
/** A wait for `jobId` that resolves like the call that started it. */
|
|
2957
|
+
wait(client, jobId) {
|
|
2958
|
+
const state = this._state(client, jobId);
|
|
2959
|
+
const shared = state.shared;
|
|
2960
|
+
if (shared) {
|
|
2961
|
+
return shared.catch((err) => {
|
|
2962
|
+
const entry = state.client._jobStore.get(jobId);
|
|
2963
|
+
if (entry?.status === 'failed' || state.shared === shared) {
|
|
2964
|
+
throw err;
|
|
2965
|
+
}
|
|
2966
|
+
return this.wait(client, jobId);
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
2969
|
+
const entry = client._jobStore.get(jobId);
|
|
2970
|
+
return this.track(
|
|
2971
|
+
client,
|
|
2972
|
+
jobId,
|
|
2973
|
+
client._waitForJob(jobId, {
|
|
2974
|
+
timeout: entry?.kind === 'video' ? BG_VIDEO_WAIT_MS : undefined,
|
|
2975
|
+
}),
|
|
2976
|
+
);
|
|
2977
|
+
}
|
|
2978
|
+
|
|
2979
|
+
/** A chat stream started (+1) or stopped (-1) reading `jobId`. */
|
|
2980
|
+
live(client, jobId, delta) {
|
|
2981
|
+
const state = this._state(client, jobId);
|
|
2982
|
+
state.live = Math.max(0, state.live + delta);
|
|
2983
|
+
if (delta < 0) this._tickSoon();
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
/** The current page shows `jobId` itself. */
|
|
2987
|
+
claim(client, jobId) {
|
|
2988
|
+
if (!jobId) return;
|
|
2989
|
+
const state = this._state(client, jobId);
|
|
2990
|
+
state.claimedPage = pageKey();
|
|
2991
|
+
const entry = client._jobStore.get(jobId);
|
|
2992
|
+
if (entry?.bg && isSettledEntry(entry) && !entry.delivered) {
|
|
2993
|
+
client._jobStore.patch(jobId, { delivered: true });
|
|
2994
|
+
} else {
|
|
2995
|
+
this.changed();
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2999
|
+
/** Called by JobStore.settle: was the result seen where it was asked for? */
|
|
3000
|
+
decorate(entry) {
|
|
3001
|
+
if (!entry.bg) return;
|
|
3002
|
+
const state = this._jobs.get(entry.jobId);
|
|
3003
|
+
const page = pageKey();
|
|
3004
|
+
const claimed = !!state && state.claimedPage !== null;
|
|
3005
|
+
const claimedHere = claimed && state.claimedPage === page;
|
|
3006
|
+
if (!entry.orphaned) {
|
|
3007
|
+
if (state?.recovered && !claimedHere) entry.orphaned = true;
|
|
3008
|
+
else if (claimed && !claimedHere) entry.orphaned = true;
|
|
3009
|
+
else if (!claimed && (entry.page ?? '') !== page) entry.orphaned = true;
|
|
3010
|
+
}
|
|
3011
|
+
if (!entry.orphaned || claimedHere) entry.delivered = true;
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
/** Something changed: re-render once, after the current task. */
|
|
3015
|
+
changed() {
|
|
3016
|
+
if (this._renderQueued) return;
|
|
3017
|
+
this._renderQueued = true;
|
|
3018
|
+
const run = () => {
|
|
3019
|
+
this._renderQueued = false;
|
|
3020
|
+
this._render();
|
|
3021
|
+
};
|
|
3022
|
+
try {
|
|
3023
|
+
if (typeof queueMicrotask === 'function') queueMicrotask(run);
|
|
3024
|
+
else Promise.resolve().then(run);
|
|
3025
|
+
} catch {
|
|
3026
|
+
this._renderQueued = false;
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
_listen() {
|
|
3031
|
+
if (this._listening || !isBrowser()) return;
|
|
3032
|
+
this._listening = true;
|
|
3033
|
+
try {
|
|
3034
|
+
const onNavigate = () => this._tick();
|
|
3035
|
+
window.addEventListener('popstate', onNavigate);
|
|
3036
|
+
window.addEventListener('hashchange', onNavigate);
|
|
3037
|
+
// Another tab finished or dismissed one of these jobs.
|
|
3038
|
+
window.addEventListener('storage', (event) => {
|
|
3039
|
+
if (!event.key || event.key.startsWith('aiflow:jobs:')) {
|
|
3040
|
+
this.changed();
|
|
3041
|
+
}
|
|
3042
|
+
});
|
|
3043
|
+
} catch {
|
|
3044
|
+
/* no events */
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
_ensureTimer() {
|
|
3049
|
+
if (this._timer || !this._enabled()) return;
|
|
3050
|
+
try {
|
|
3051
|
+
this._timer = setInterval(() => this._tick(), BG_PAGE_POLL_MS);
|
|
3052
|
+
} catch {
|
|
3053
|
+
this._timer = null;
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
_stopTimer() {
|
|
3058
|
+
if (!this._timer) return;
|
|
3059
|
+
try {
|
|
3060
|
+
clearInterval(this._timer);
|
|
3061
|
+
} catch {
|
|
3062
|
+
/* ignore */
|
|
3063
|
+
}
|
|
3064
|
+
this._timer = null;
|
|
3065
|
+
}
|
|
3066
|
+
|
|
3067
|
+
_tickSoon() {
|
|
3068
|
+
try {
|
|
3069
|
+
setTimeout(() => this._tick(), 0);
|
|
3070
|
+
} catch {
|
|
3071
|
+
/* no timers */
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
|
|
3075
|
+
/**
|
|
3076
|
+
* Mark jobs whose page was left, follow the ones nobody waits for, and
|
|
3077
|
+
* stop polling once no job of this page load is running.
|
|
3078
|
+
*/
|
|
3079
|
+
_tick() {
|
|
3080
|
+
try {
|
|
3081
|
+
if (!this._enabled()) {
|
|
3082
|
+
this._stopTimer();
|
|
3083
|
+
this._render();
|
|
3084
|
+
return;
|
|
3085
|
+
}
|
|
3086
|
+
const page = pageKey();
|
|
3087
|
+
const now = Date.now();
|
|
3088
|
+
let running = false;
|
|
3089
|
+
for (const state of this._jobs.values()) {
|
|
3090
|
+
const store = state.client._jobStore;
|
|
3091
|
+
const entry = store.get(state.jobId);
|
|
3092
|
+
if (!entry || !entry.bg || entry.hidden || isSettledEntry(entry)) {
|
|
3093
|
+
continue;
|
|
3094
|
+
}
|
|
3095
|
+
running = true;
|
|
3096
|
+
const claimed = state.claimedPage !== null;
|
|
3097
|
+
const claimedHere = claimed && state.claimedPage === page;
|
|
3098
|
+
let orphaned = !!entry.orphaned;
|
|
3099
|
+
if (!orphaned) {
|
|
3100
|
+
if (state.recovered) {
|
|
3101
|
+
orphaned = now >= state.graceUntil && !claimedHere;
|
|
3102
|
+
} else {
|
|
3103
|
+
orphaned = claimed ? !claimedHere : entry.page !== page;
|
|
3104
|
+
}
|
|
3105
|
+
if (orphaned) store.patch(state.jobId, { orphaned: true });
|
|
3106
|
+
}
|
|
3107
|
+
const waited = state.waiting.size > 0 || state.live > 0;
|
|
3108
|
+
if (orphaned && !waited && !state.following && now >= state.nextFollowAt) {
|
|
3109
|
+
this._follow(state, entry);
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
if (!running) this._stopTimer();
|
|
3113
|
+
this._render();
|
|
3114
|
+
} catch {
|
|
3115
|
+
/* never into app code */
|
|
3116
|
+
}
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
/** Wait for an orphaned job ourselves, so its card can show the result. */
|
|
3120
|
+
_follow(state, entry) {
|
|
3121
|
+
state.following = true;
|
|
3122
|
+
const promise = state.client._waitForJob(state.jobId, {
|
|
3123
|
+
timeout: entry.kind === 'video' ? BG_VIDEO_WAIT_MS : undefined,
|
|
3124
|
+
});
|
|
3125
|
+
this.track(state.client, state.jobId, promise);
|
|
3126
|
+
promise.then(
|
|
3127
|
+
() => {
|
|
3128
|
+
state.following = false;
|
|
3129
|
+
state.failures = 0;
|
|
3130
|
+
},
|
|
3131
|
+
(err) => {
|
|
3132
|
+
state.following = false;
|
|
3133
|
+
const now = state.client._jobStore.get(state.jobId);
|
|
3134
|
+
if (!now || isSettledEntry(now)) return;
|
|
3135
|
+
// Not this user's job any more (signed out / another account),
|
|
3136
|
+
// or gone from the gateway: nothing to show.
|
|
3137
|
+
if ([401, 403, 404].includes(err?.status)) {
|
|
3138
|
+
state.client._jobStore.patch(state.jobId, { hidden: true });
|
|
3139
|
+
return;
|
|
3140
|
+
}
|
|
3141
|
+
state.failures += 1;
|
|
3142
|
+
if (state.failures > BG_FOLLOW_BACKOFF_MS.length) {
|
|
3143
|
+
state.client._jobStore.patch(state.jobId, { hidden: true });
|
|
3144
|
+
return;
|
|
3145
|
+
}
|
|
3146
|
+
state.nextFollowAt =
|
|
3147
|
+
Date.now() + BG_FOLLOW_BACKOFF_MS[state.failures - 1];
|
|
3148
|
+
},
|
|
3149
|
+
);
|
|
3150
|
+
}
|
|
3151
|
+
|
|
3152
|
+
/** What the notice shows: running jobs and finished ones, newest first. */
|
|
3153
|
+
_visible() {
|
|
3154
|
+
const page = pageKey();
|
|
3155
|
+
const running = [];
|
|
3156
|
+
const cards = [];
|
|
3157
|
+
for (const client of this._clients.values()) {
|
|
3158
|
+
for (const entry of client._jobStore.list()) {
|
|
3159
|
+
if (!entry.bg || !entry.orphaned) continue;
|
|
3160
|
+
if (entry.dismissed || entry.delivered || entry.hidden) continue;
|
|
3161
|
+
const state = this._jobs.get(entry.jobId);
|
|
3162
|
+
if (state && state.claimedPage !== null && state.claimedPage === page) {
|
|
3163
|
+
continue;
|
|
3164
|
+
}
|
|
3165
|
+
(isSettledEntry(entry) ? cards : running).push({ client, entry });
|
|
3166
|
+
}
|
|
3167
|
+
}
|
|
3168
|
+
const newest = (a, b) => (b.entry.createdAt || 0) - (a.entry.createdAt || 0);
|
|
3169
|
+
return { running: running.sort(newest), cards: cards.sort(newest) };
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
_render() {
|
|
3173
|
+
try {
|
|
3174
|
+
if (!this._enabled()) {
|
|
3175
|
+
this._view?.remove();
|
|
3176
|
+
return;
|
|
3177
|
+
}
|
|
3178
|
+
if (Date.now() < this._quietUntil) return;
|
|
3179
|
+
const { running, cards } = this._visible();
|
|
3180
|
+
if (!running.length && !cards.length) {
|
|
3181
|
+
this._view?.remove();
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
3184
|
+
if (!this._view) this._view = new NoticeView();
|
|
3185
|
+
this._view.render({
|
|
3186
|
+
running,
|
|
3187
|
+
cards,
|
|
3188
|
+
strings: noticeStrings(this._config.locale),
|
|
3189
|
+
position: this._config.position,
|
|
3190
|
+
onDismiss: (client, jobId) =>
|
|
3191
|
+
client._jobStore.patch(jobId, { dismissed: true }),
|
|
3192
|
+
});
|
|
3193
|
+
} catch {
|
|
3194
|
+
/* never into app code */
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
|
|
3199
|
+
// ── Notice UI ──────────────────────────────────────────────────────────────
|
|
3200
|
+
|
|
3201
|
+
const NOTICE_STRINGS = {
|
|
3202
|
+
en: {
|
|
3203
|
+
region: 'Background generations',
|
|
3204
|
+
running: {
|
|
3205
|
+
image: 'Generating your image…',
|
|
3206
|
+
image_batch: 'Generating your images…',
|
|
3207
|
+
audio: 'Generating your music…',
|
|
3208
|
+
sfx: 'Generating your sound effect…',
|
|
3209
|
+
video: 'Generating your video…',
|
|
3210
|
+
chat: 'Writing your answer…',
|
|
3211
|
+
},
|
|
3212
|
+
runningMany: (n) => `Generating ${n} items…`,
|
|
3213
|
+
keepsGoing: 'It keeps going in the background.',
|
|
3214
|
+
ready: {
|
|
3215
|
+
image: 'Your image is ready',
|
|
3216
|
+
image_batch: 'Your images are ready',
|
|
3217
|
+
audio: 'Your music is ready',
|
|
3218
|
+
sfx: 'Your sound effect is ready',
|
|
3219
|
+
video: 'Your video is ready',
|
|
3220
|
+
chat: 'Your answer is ready',
|
|
3221
|
+
},
|
|
3222
|
+
failed: {
|
|
3223
|
+
image: 'Image failed',
|
|
3224
|
+
image_batch: 'Images failed',
|
|
3225
|
+
audio: 'Music failed',
|
|
3226
|
+
sfx: 'Sound effect failed',
|
|
3227
|
+
video: 'Video failed',
|
|
3228
|
+
chat: 'Answer failed',
|
|
3229
|
+
},
|
|
3230
|
+
failedFallback: 'The generation did not finish.',
|
|
3231
|
+
open: 'Open page',
|
|
3232
|
+
download: 'Download',
|
|
3233
|
+
copy: 'Copy',
|
|
3234
|
+
copied: 'Copied',
|
|
3235
|
+
dismiss: 'Dismiss',
|
|
3236
|
+
more: (n) => `+${n} more`,
|
|
3237
|
+
},
|
|
3238
|
+
ko: {
|
|
3239
|
+
region: '백그라운드 생성',
|
|
3240
|
+
running: {
|
|
3241
|
+
image: '이미지를 생성하는 중…',
|
|
3242
|
+
image_batch: '이미지를 생성하는 중…',
|
|
3243
|
+
audio: '음악을 생성하는 중…',
|
|
3244
|
+
sfx: '효과음을 생성하는 중…',
|
|
3245
|
+
video: '동영상을 생성하는 중…',
|
|
3246
|
+
chat: '답변을 작성하는 중…',
|
|
3247
|
+
},
|
|
3248
|
+
runningMany: (n) => `${n}개를 생성하는 중…`,
|
|
3249
|
+
keepsGoing: '페이지를 떠나도 백그라운드에서 계속 진행됩니다.',
|
|
3250
|
+
ready: {
|
|
3251
|
+
image: '이미지가 준비되었습니다',
|
|
3252
|
+
image_batch: '이미지가 준비되었습니다',
|
|
3253
|
+
audio: '음악이 준비되었습니다',
|
|
3254
|
+
sfx: '효과음이 준비되었습니다',
|
|
3255
|
+
video: '동영상이 준비되었습니다',
|
|
3256
|
+
chat: '답변이 준비되었습니다',
|
|
3257
|
+
},
|
|
3258
|
+
failed: {
|
|
3259
|
+
image: '이미지 생성 실패',
|
|
3260
|
+
image_batch: '이미지 생성 실패',
|
|
3261
|
+
audio: '음악 생성 실패',
|
|
3262
|
+
sfx: '효과음 생성 실패',
|
|
3263
|
+
video: '동영상 생성 실패',
|
|
3264
|
+
chat: '답변 생성 실패',
|
|
3265
|
+
},
|
|
3266
|
+
failedFallback: '생성을 완료하지 못했습니다.',
|
|
3267
|
+
open: '페이지 열기',
|
|
3268
|
+
download: '다운로드',
|
|
3269
|
+
copy: '복사',
|
|
3270
|
+
copied: '복사됨',
|
|
3271
|
+
dismiss: '닫기',
|
|
3272
|
+
more: (n) => `외 ${n}개`,
|
|
3273
|
+
},
|
|
3274
|
+
vi: {
|
|
3275
|
+
region: 'Đang tạo trong nền',
|
|
3276
|
+
running: {
|
|
3277
|
+
image: 'Đang tạo hình ảnh…',
|
|
3278
|
+
image_batch: 'Đang tạo các hình ảnh…',
|
|
3279
|
+
audio: 'Đang tạo nhạc…',
|
|
3280
|
+
sfx: 'Đang tạo hiệu ứng âm thanh…',
|
|
3281
|
+
video: 'Đang tạo video…',
|
|
3282
|
+
chat: 'Đang viết câu trả lời…',
|
|
3283
|
+
},
|
|
3284
|
+
runningMany: (n) => `Đang tạo ${n} mục…`,
|
|
3285
|
+
keepsGoing: 'Vẫn tiếp tục chạy trong nền.',
|
|
3286
|
+
ready: {
|
|
3287
|
+
image: 'Hình ảnh đã sẵn sàng',
|
|
3288
|
+
image_batch: 'Các hình ảnh đã sẵn sàng',
|
|
3289
|
+
audio: 'Bản nhạc đã sẵn sàng',
|
|
3290
|
+
sfx: 'Hiệu ứng âm thanh đã sẵn sàng',
|
|
3291
|
+
video: 'Video đã sẵn sàng',
|
|
3292
|
+
chat: 'Câu trả lời đã sẵn sàng',
|
|
3293
|
+
},
|
|
3294
|
+
failed: {
|
|
3295
|
+
image: 'Tạo hình ảnh thất bại',
|
|
3296
|
+
image_batch: 'Tạo hình ảnh thất bại',
|
|
3297
|
+
audio: 'Tạo nhạc thất bại',
|
|
3298
|
+
sfx: 'Tạo hiệu ứng âm thanh thất bại',
|
|
3299
|
+
video: 'Tạo video thất bại',
|
|
3300
|
+
chat: 'Tạo câu trả lời thất bại',
|
|
3301
|
+
},
|
|
3302
|
+
failedFallback: 'Quá trình tạo chưa hoàn tất.',
|
|
3303
|
+
open: 'Mở trang',
|
|
3304
|
+
download: 'Tải xuống',
|
|
3305
|
+
copy: 'Sao chép',
|
|
3306
|
+
copied: 'Đã sao chép',
|
|
3307
|
+
dismiss: 'Đóng',
|
|
3308
|
+
more: (n) => `+${n} mục khác`,
|
|
3309
|
+
},
|
|
3310
|
+
ja: {
|
|
3311
|
+
region: 'バックグラウンド生成',
|
|
3312
|
+
running: {
|
|
3313
|
+
image: '画像を生成しています…',
|
|
3314
|
+
image_batch: '画像を生成しています…',
|
|
3315
|
+
audio: '音楽を生成しています…',
|
|
3316
|
+
sfx: '効果音を生成しています…',
|
|
3317
|
+
video: '動画を生成しています…',
|
|
3318
|
+
chat: '回答を作成しています…',
|
|
3319
|
+
},
|
|
3320
|
+
runningMany: (n) => `${n}件を生成しています…`,
|
|
3321
|
+
keepsGoing: 'ページを離れてもバックグラウンドで続きます。',
|
|
3322
|
+
ready: {
|
|
3323
|
+
image: '画像ができました',
|
|
3324
|
+
image_batch: '画像ができました',
|
|
3325
|
+
audio: '音楽ができました',
|
|
3326
|
+
sfx: '効果音ができました',
|
|
3327
|
+
video: '動画ができました',
|
|
3328
|
+
chat: '回答ができました',
|
|
3329
|
+
},
|
|
3330
|
+
failed: {
|
|
3331
|
+
image: '画像の生成に失敗しました',
|
|
3332
|
+
image_batch: '画像の生成に失敗しました',
|
|
3333
|
+
audio: '音楽の生成に失敗しました',
|
|
3334
|
+
sfx: '効果音の生成に失敗しました',
|
|
3335
|
+
video: '動画の生成に失敗しました',
|
|
3336
|
+
chat: '回答の作成に失敗しました',
|
|
3337
|
+
},
|
|
3338
|
+
failedFallback: '生成は完了しませんでした。',
|
|
3339
|
+
open: 'ページを開く',
|
|
3340
|
+
download: 'ダウンロード',
|
|
3341
|
+
copy: 'コピー',
|
|
3342
|
+
copied: 'コピーしました',
|
|
3343
|
+
dismiss: '閉じる',
|
|
3344
|
+
more: (n) => `ほか${n}件`,
|
|
3345
|
+
},
|
|
3346
|
+
zh: {
|
|
3347
|
+
region: '后台生成',
|
|
3348
|
+
running: {
|
|
3349
|
+
image: '正在生成图片…',
|
|
3350
|
+
image_batch: '正在生成图片…',
|
|
3351
|
+
audio: '正在生成音乐…',
|
|
3352
|
+
sfx: '正在生成音效…',
|
|
3353
|
+
video: '正在生成视频…',
|
|
3354
|
+
chat: '正在生成回答…',
|
|
3355
|
+
},
|
|
3356
|
+
runningMany: (n) => `正在生成 ${n} 项…`,
|
|
3357
|
+
keepsGoing: '离开页面后仍会在后台继续。',
|
|
3358
|
+
ready: {
|
|
3359
|
+
image: '图片已生成',
|
|
3360
|
+
image_batch: '图片已生成',
|
|
3361
|
+
audio: '音乐已生成',
|
|
3362
|
+
sfx: '音效已生成',
|
|
3363
|
+
video: '视频已生成',
|
|
3364
|
+
chat: '回答已生成',
|
|
3365
|
+
},
|
|
3366
|
+
failed: {
|
|
3367
|
+
image: '图片生成失败',
|
|
3368
|
+
image_batch: '图片生成失败',
|
|
3369
|
+
audio: '音乐生成失败',
|
|
3370
|
+
sfx: '音效生成失败',
|
|
3371
|
+
video: '视频生成失败',
|
|
3372
|
+
chat: '回答生成失败',
|
|
3373
|
+
},
|
|
3374
|
+
failedFallback: '生成未完成。',
|
|
3375
|
+
open: '打开页面',
|
|
3376
|
+
download: '下载',
|
|
3377
|
+
copy: '复制',
|
|
3378
|
+
copied: '已复制',
|
|
3379
|
+
dismiss: '关闭',
|
|
3380
|
+
more: (n) => `还有 ${n} 项`,
|
|
3381
|
+
},
|
|
3382
|
+
};
|
|
3383
|
+
|
|
3384
|
+
/** Strings for the configured locale, else `<html lang>`, else the browser. */
|
|
3385
|
+
function noticeStrings(locale) {
|
|
3386
|
+
const candidates = [locale];
|
|
3387
|
+
try {
|
|
3388
|
+
candidates.push(document.documentElement.lang);
|
|
3389
|
+
} catch {
|
|
3390
|
+
/* no document */
|
|
3391
|
+
}
|
|
3392
|
+
try {
|
|
3393
|
+
candidates.push(navigator.language);
|
|
3394
|
+
} catch {
|
|
3395
|
+
/* no navigator */
|
|
3396
|
+
}
|
|
3397
|
+
for (const value of candidates) {
|
|
3398
|
+
const code = String(value || '')
|
|
3399
|
+
.slice(0, 2)
|
|
3400
|
+
.toLowerCase();
|
|
3401
|
+
if (NOTICE_STRINGS[code]) return NOTICE_STRINGS[code];
|
|
3402
|
+
}
|
|
3403
|
+
return NOTICE_STRINGS.en;
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
/** Job kind → the notice's wording key. */
|
|
3407
|
+
function noticeKind(kind) {
|
|
3408
|
+
if (kind === 'chat_stream') return 'chat';
|
|
3409
|
+
return NOTICE_STRINGS.en.running[kind] ? kind : 'chat';
|
|
3410
|
+
}
|
|
3411
|
+
|
|
3412
|
+
/** Only URLs that are safe as a media `src` / download `href`. */
|
|
3413
|
+
function safeMediaUrl(url) {
|
|
3414
|
+
if (typeof url !== 'string') return null;
|
|
3415
|
+
const value = url.trim();
|
|
3416
|
+
return /^(https?:|blob:|data:(image|audio|video)\/)/i.test(value)
|
|
3417
|
+
? value
|
|
3418
|
+
: null;
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
/** What a finished job's card previews. */
|
|
3422
|
+
function noticeMedia(entry) {
|
|
3423
|
+
const result = entry.result || {};
|
|
3424
|
+
const imageSrc = (img) =>
|
|
3425
|
+
safeMediaUrl(img?.url) ||
|
|
3426
|
+
(img?.b64
|
|
3427
|
+
? safeMediaUrl(`data:${img.mimeType || 'image/png'};base64,${img.b64}`)
|
|
3428
|
+
: null);
|
|
3429
|
+
let images = [];
|
|
3430
|
+
if (entry.kind === 'image') images = (result.images || []).map(imageSrc);
|
|
3431
|
+
if (entry.kind === 'image_batch') {
|
|
3432
|
+
images = (result.results || [])
|
|
3433
|
+
.flatMap((r) => r?.images || [])
|
|
3434
|
+
.map(imageSrc);
|
|
3435
|
+
}
|
|
3436
|
+
images = images.filter(Boolean);
|
|
3437
|
+
const audio =
|
|
3438
|
+
entry.kind === 'audio' || entry.kind === 'sfx'
|
|
3439
|
+
? safeMediaUrl(result.audioUrl)
|
|
3440
|
+
: null;
|
|
3441
|
+
const video = entry.kind === 'video' ? safeMediaUrl(result.videoUrl) : null;
|
|
3442
|
+
const text =
|
|
3443
|
+
(entry.kind === 'chat' || entry.kind === 'chat_stream') &&
|
|
3444
|
+
typeof result.content === 'string'
|
|
3445
|
+
? result.content
|
|
3446
|
+
: '';
|
|
3447
|
+
return {
|
|
3448
|
+
images,
|
|
3449
|
+
audio,
|
|
3450
|
+
video,
|
|
3451
|
+
poster: entry.kind === 'video' ? safeMediaUrl(result.thumbnailUrl) : null,
|
|
3452
|
+
text,
|
|
3453
|
+
download: images[0] || audio || video || null,
|
|
3454
|
+
};
|
|
3455
|
+
}
|
|
3456
|
+
|
|
3457
|
+
/** Navigate to a job's page the way a client-side router expects. */
|
|
3458
|
+
function openNoticePage(page) {
|
|
3459
|
+
try {
|
|
3460
|
+
if (!page || page === pageKey()) return;
|
|
3461
|
+
const hashAt = page.indexOf('#/');
|
|
3462
|
+
if (hashAt >= 0 && page.slice(0, hashAt) === window.location.pathname) {
|
|
3463
|
+
window.location.hash = page.slice(hashAt + 1);
|
|
3464
|
+
return;
|
|
3465
|
+
}
|
|
3466
|
+
// React Router keeps an index in history.state; continue it so its
|
|
3467
|
+
// POP handling sees an ordinary forward entry.
|
|
3468
|
+
const prev = window.history.state;
|
|
3469
|
+
const state =
|
|
3470
|
+
prev && typeof prev.idx === 'number'
|
|
3471
|
+
? {
|
|
3472
|
+
usr: null,
|
|
3473
|
+
key: Math.random().toString(36).slice(2, 10),
|
|
3474
|
+
idx: prev.idx + 1,
|
|
3475
|
+
}
|
|
3476
|
+
: null;
|
|
3477
|
+
window.history.pushState(state, '', page);
|
|
3478
|
+
window.dispatchEvent(new PopStateEvent('popstate', { state }));
|
|
3479
|
+
} catch {
|
|
3480
|
+
try {
|
|
3481
|
+
window.location.href = page;
|
|
3482
|
+
} catch {
|
|
3483
|
+
/* nothing else to try */
|
|
3484
|
+
}
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
|
|
3488
|
+
const NOTICE_CSS = `
|
|
3489
|
+
:host { all: initial; }
|
|
3490
|
+
.root {
|
|
3491
|
+
--bg: #ffffff; --fg: #17181c; --muted: #5d6068; --line: rgba(15, 17, 22, 0.12);
|
|
3492
|
+
--soft: #f2f3f5; --accent: #2457d6; --accent-fg: #ffffff; --danger: #b42318;
|
|
3493
|
+
--shadow: 0 4px 12px rgba(15, 17, 22, 0.14), 0 1px 3px rgba(15, 17, 22, 0.08);
|
|
3494
|
+
position: fixed; left: 16px; bottom: calc(16px + env(safe-area-inset-bottom, 0px));
|
|
3495
|
+
z-index: 2147483000; width: min(340px, calc(100vw - 32px)); box-sizing: border-box;
|
|
3496
|
+
max-height: calc(100vh - 32px); display: flex; flex-direction: column; gap: 8px;
|
|
3497
|
+
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial,
|
|
3498
|
+
"Apple SD Gothic Neo", "Malgun Gothic", "Hiragino Sans", "Noto Sans", sans-serif;
|
|
3499
|
+
color: var(--fg); -webkit-font-smoothing: antialiased; pointer-events: none;
|
|
3500
|
+
}
|
|
3501
|
+
.root.right { left: auto; right: 16px; }
|
|
3502
|
+
.root > * { pointer-events: auto; }
|
|
3503
|
+
@media (prefers-color-scheme: dark) {
|
|
3504
|
+
.root {
|
|
3505
|
+
--bg: #1f2026; --fg: #f1f2f4; --muted: #a6a9b1; --line: rgba(255, 255, 255, 0.14);
|
|
3506
|
+
--soft: #2c2e35; --accent: #8aa8ff; --accent-fg: #0f1115; --danger: #ff9b91;
|
|
3507
|
+
--shadow: 0 4px 12px rgba(0, 0, 0, 0.5), 0 1px 3px rgba(0, 0, 0, 0.35);
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
@media (max-width: 480px) {
|
|
3511
|
+
.root, .root.right {
|
|
3512
|
+
left: 12px; right: 12px; width: auto; max-height: 65vh;
|
|
3513
|
+
bottom: calc(12px + env(safe-area-inset-bottom, 0px));
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
/* The cards scroll when they do not fit; the padding keeps their shadows. */
|
|
3517
|
+
.root > .list {
|
|
3518
|
+
display: flex; flex-direction: column; gap: 8px; flex: 0 1 auto; min-height: 0;
|
|
3519
|
+
overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin;
|
|
3520
|
+
padding: 6px 16px 18px; margin: -6px -16px -18px; pointer-events: none;
|
|
3521
|
+
}
|
|
3522
|
+
.list > .card { pointer-events: auto; flex: none; }
|
|
3523
|
+
.list:empty, .more:empty { display: none; }
|
|
3524
|
+
.card, .pill {
|
|
3525
|
+
background: var(--bg); color: var(--fg); border: 1px solid var(--line);
|
|
3526
|
+
box-shadow: var(--shadow); box-sizing: border-box; min-width: 0;
|
|
3527
|
+
}
|
|
3528
|
+
.card { border-radius: 14px; padding: 10px 10px 12px 14px; display: flex; flex-direction: column; gap: 8px; }
|
|
3529
|
+
.head { display: flex; align-items: flex-start; gap: 6px; }
|
|
3530
|
+
.title { flex: 1; min-width: 0; font-weight: 600; padding-top: 6px; overflow-wrap: anywhere; }
|
|
3531
|
+
.failed .title { color: var(--danger); }
|
|
3532
|
+
.label {
|
|
3533
|
+
color: var(--muted); font-size: 13px; margin-top: -4px; padding-right: 4px;
|
|
3534
|
+
overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
|
|
3535
|
+
overflow-wrap: anywhere;
|
|
3536
|
+
}
|
|
3537
|
+
.error, .text {
|
|
3538
|
+
font-size: 13px; background: var(--soft); border-radius: 8px; padding: 8px 10px;
|
|
3539
|
+
margin-right: 4px; overflow-wrap: anywhere;
|
|
3540
|
+
}
|
|
3541
|
+
.text { white-space: pre-wrap; max-height: 92px; overflow: auto; }
|
|
3542
|
+
.thumbs { display: grid; gap: 6px; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-right: 4px; }
|
|
3543
|
+
.thumbs img {
|
|
3544
|
+
display: block; width: 100%; aspect-ratio: 1 / 1; object-fit: cover;
|
|
3545
|
+
border-radius: 8px; background: var(--soft);
|
|
3546
|
+
}
|
|
3547
|
+
.thumbs.one { display: block; }
|
|
3548
|
+
.thumbs.one img { width: auto; max-width: 100%; max-height: 150px; aspect-ratio: auto; }
|
|
3549
|
+
video { display: block; width: calc(100% - 4px); max-height: 150px; border-radius: 8px; background: #000; }
|
|
3550
|
+
audio { display: block; width: calc(100% - 4px); height: 40px; }
|
|
3551
|
+
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
3552
|
+
.btn {
|
|
3553
|
+
min-height: 32px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--line);
|
|
3554
|
+
background: var(--soft); color: var(--fg); font: inherit; font-size: 13px; font-weight: 600;
|
|
3555
|
+
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
|
3556
|
+
cursor: pointer; text-decoration: none; box-sizing: border-box; white-space: nowrap;
|
|
3557
|
+
}
|
|
3558
|
+
.btn.primary { background: var(--accent); color: var(--accent-fg); border-color: transparent; }
|
|
3559
|
+
.btn:hover { filter: brightness(0.97); }
|
|
3560
|
+
.icon {
|
|
3561
|
+
width: 32px; height: 32px; flex: none; border: 0; border-radius: 8px; padding: 0;
|
|
3562
|
+
background: transparent; color: var(--muted); font: inherit; font-size: 20px; line-height: 1;
|
|
3563
|
+
cursor: pointer; display: inline-flex; align-items: center; justify-content: center;
|
|
3564
|
+
}
|
|
3565
|
+
.icon:hover { background: var(--soft); color: var(--fg); }
|
|
3566
|
+
button:focus-visible, a:focus-visible, audio:focus-visible, video:focus-visible {
|
|
3567
|
+
outline: 2px solid var(--accent); outline-offset: 2px;
|
|
3568
|
+
}
|
|
3569
|
+
.more {
|
|
3570
|
+
align-self: flex-start; color: var(--muted); font-size: 12px; font-weight: 600;
|
|
3571
|
+
background: var(--bg); border: 1px solid var(--line); border-radius: 999px;
|
|
3572
|
+
padding: 2px 10px; box-shadow: var(--shadow);
|
|
3573
|
+
}
|
|
3574
|
+
.right .more { align-self: flex-end; }
|
|
3575
|
+
.pill {
|
|
3576
|
+
border-radius: 999px; padding: 8px 16px 8px 10px; display: flex; align-items: center;
|
|
3577
|
+
gap: 10px; align-self: flex-start; max-width: 100%;
|
|
3578
|
+
}
|
|
3579
|
+
.right .pill { align-self: flex-end; }
|
|
3580
|
+
.pill[hidden] { display: none; }
|
|
3581
|
+
.spinner {
|
|
3582
|
+
width: 18px; height: 18px; flex: none; border-radius: 50%; box-sizing: border-box;
|
|
3583
|
+
border: 2px solid var(--line); border-top-color: var(--accent);
|
|
3584
|
+
animation: aiflow-spin 0.9s linear infinite;
|
|
3585
|
+
}
|
|
3586
|
+
@keyframes aiflow-spin { to { transform: rotate(360deg); } }
|
|
3587
|
+
@media (prefers-reduced-motion: reduce) {
|
|
3588
|
+
.spinner { animation: none; border-color: var(--accent); opacity: 0.55; }
|
|
3589
|
+
}
|
|
3590
|
+
.pill-text { display: flex; flex-direction: column; min-width: 0; }
|
|
3591
|
+
.pill-title { font-weight: 600; font-size: 13px; overflow-wrap: anywhere; }
|
|
3592
|
+
.pill-sub { color: var(--muted); font-size: 12px; }
|
|
3593
|
+
`;
|
|
3594
|
+
|
|
3595
|
+
function noticeEl(tag, className, text) {
|
|
3596
|
+
const node = document.createElement(tag);
|
|
3597
|
+
if (className) node.className = className;
|
|
3598
|
+
if (text !== undefined) node.textContent = text;
|
|
3599
|
+
return node;
|
|
3600
|
+
}
|
|
3601
|
+
|
|
3602
|
+
/** The panel itself: a Shadow DOM host on <body>, created on first need. */
|
|
3603
|
+
class NoticeView {
|
|
3604
|
+
constructor() {
|
|
3605
|
+
this._host = null;
|
|
3606
|
+
this._root = null;
|
|
3607
|
+
this._list = null;
|
|
3608
|
+
this._more = null;
|
|
3609
|
+
this._pill = null;
|
|
3610
|
+
this._pillTitle = null;
|
|
3611
|
+
this._pillSub = null;
|
|
3612
|
+
this._cards = new Map();
|
|
3613
|
+
this._strings = null;
|
|
3614
|
+
}
|
|
3615
|
+
|
|
3616
|
+
_mount() {
|
|
3617
|
+
if (this._host && this._host.isConnected) return true;
|
|
3618
|
+
if (!document.body) return false;
|
|
3619
|
+
if (!this._host) {
|
|
3620
|
+
const host = document.createElement('div');
|
|
3621
|
+
if (typeof host.attachShadow !== 'function') return false;
|
|
3622
|
+
host.setAttribute('data-aiflow-background-notice', '');
|
|
3623
|
+
const shadow = host.attachShadow({ mode: 'open' });
|
|
3624
|
+
const style = document.createElement('style');
|
|
3625
|
+
style.textContent = NOTICE_CSS;
|
|
3626
|
+
const root = noticeEl('div', 'root');
|
|
3627
|
+
root.setAttribute('role', 'region');
|
|
3628
|
+
root.setAttribute('aria-live', 'polite');
|
|
3629
|
+
this._list = noticeEl('div', 'list');
|
|
3630
|
+
this._more = noticeEl('div', 'more');
|
|
3631
|
+
this._pill = noticeEl('div', 'pill');
|
|
3632
|
+
this._pill.hidden = true;
|
|
3633
|
+
const pillText = noticeEl('div', 'pill-text');
|
|
3634
|
+
this._pillTitle = noticeEl('span', 'pill-title');
|
|
3635
|
+
this._pillSub = noticeEl('span', 'pill-sub');
|
|
3636
|
+
pillText.append(this._pillTitle, this._pillSub);
|
|
3637
|
+
this._pill.append(noticeEl('span', 'spinner'), pillText);
|
|
3638
|
+
root.append(this._list, this._more, this._pill);
|
|
3639
|
+
shadow.append(style, root);
|
|
3640
|
+
this._host = host;
|
|
3641
|
+
this._root = root;
|
|
3642
|
+
}
|
|
3643
|
+
document.body.appendChild(this._host);
|
|
3644
|
+
return true;
|
|
3645
|
+
}
|
|
3646
|
+
|
|
3647
|
+
remove() {
|
|
3648
|
+
try {
|
|
3649
|
+
if (this._host?.isConnected) this._host.remove();
|
|
3650
|
+
} catch {
|
|
3651
|
+
/* ignore */
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
|
|
3655
|
+
render({ running, cards, strings: t, position, onDismiss }) {
|
|
3656
|
+
if (!this._mount()) return;
|
|
3657
|
+
if (this._strings !== t) {
|
|
3658
|
+
// Language changed: rebuild the cards in the new one.
|
|
3659
|
+
this._strings = t;
|
|
3660
|
+
for (const node of this._cards.values()) node.remove();
|
|
3661
|
+
this._cards.clear();
|
|
3662
|
+
}
|
|
3663
|
+
this._root.classList.toggle('right', position === 'bottom-right');
|
|
3664
|
+
this._root.setAttribute('aria-label', t.region);
|
|
3665
|
+
|
|
3666
|
+
if (running.length) {
|
|
3667
|
+
this._pillTitle.textContent =
|
|
3668
|
+
running.length === 1
|
|
3669
|
+
? t.running[noticeKind(running[0].entry.kind)]
|
|
3670
|
+
: t.runningMany(running.length);
|
|
3671
|
+
this._pillSub.textContent = t.keepsGoing;
|
|
3672
|
+
this._pill.hidden = false;
|
|
3673
|
+
} else {
|
|
3674
|
+
this._pill.hidden = true;
|
|
3675
|
+
}
|
|
3676
|
+
|
|
3677
|
+
const shown = cards.slice(0, BG_MAX_CARDS);
|
|
3678
|
+
const keep = new Set(shown.map((c) => c.entry.jobId));
|
|
3679
|
+
for (const [jobId, node] of this._cards) {
|
|
3680
|
+
if (!keep.has(jobId)) {
|
|
3681
|
+
node.remove();
|
|
3682
|
+
this._cards.delete(jobId);
|
|
3683
|
+
}
|
|
3684
|
+
}
|
|
3685
|
+
shown.forEach((card, i) => {
|
|
3686
|
+
let node = this._cards.get(card.entry.jobId);
|
|
3687
|
+
if (!node) {
|
|
3688
|
+
node = this._card(card, t, onDismiss);
|
|
3689
|
+
this._cards.set(card.entry.jobId, node);
|
|
3690
|
+
}
|
|
3691
|
+
// Move only what is out of place, so a playing video keeps playing.
|
|
3692
|
+
const at = this._list.children[i];
|
|
3693
|
+
if (at !== node) this._list.insertBefore(node, at || null);
|
|
3694
|
+
});
|
|
3695
|
+
this._more.textContent =
|
|
3696
|
+
cards.length > shown.length ? t.more(cards.length - shown.length) : '';
|
|
3697
|
+
}
|
|
3698
|
+
|
|
3699
|
+
_card({ client, entry }, t, onDismiss) {
|
|
3700
|
+
const kind = noticeKind(entry.kind);
|
|
3701
|
+
const failed = entry.status === 'failed';
|
|
3702
|
+
const card = noticeEl('div', failed ? 'card failed' : 'card');
|
|
3703
|
+
|
|
3704
|
+
const head = noticeEl('div', 'head');
|
|
3705
|
+
const close = noticeEl('button', 'icon', '×');
|
|
3706
|
+
close.type = 'button';
|
|
3707
|
+
close.title = t.dismiss;
|
|
3708
|
+
close.setAttribute('aria-label', t.dismiss);
|
|
3709
|
+
close.addEventListener('click', () => onDismiss(client, entry.jobId));
|
|
3710
|
+
head.append(
|
|
3711
|
+
noticeEl('div', 'title', failed ? t.failed[kind] : t.ready[kind]),
|
|
3712
|
+
close,
|
|
3713
|
+
);
|
|
3714
|
+
card.append(head);
|
|
3715
|
+
if (entry.label) card.append(noticeEl('div', 'label', entry.label));
|
|
3716
|
+
|
|
3717
|
+
const actions = noticeEl('div', 'actions');
|
|
3718
|
+
if (entry.page) {
|
|
3719
|
+
const open = noticeEl('button', 'btn primary', t.open);
|
|
3720
|
+
open.type = 'button';
|
|
3721
|
+
open.addEventListener('click', () => openNoticePage(entry.page));
|
|
3722
|
+
actions.append(open);
|
|
3723
|
+
}
|
|
3724
|
+
|
|
3725
|
+
if (failed) {
|
|
3726
|
+
card.append(noticeEl('div', 'error', entry.error || t.failedFallback));
|
|
3727
|
+
} else {
|
|
3728
|
+
const media = noticeMedia(entry);
|
|
3729
|
+
if (media.images.length) {
|
|
3730
|
+
const thumbs = noticeEl(
|
|
3731
|
+
'div',
|
|
3732
|
+
media.images.length === 1 ? 'thumbs one' : 'thumbs',
|
|
3733
|
+
);
|
|
3734
|
+
for (const src of media.images.slice(0, 4)) {
|
|
3735
|
+
const img = noticeEl('img');
|
|
3736
|
+
img.src = src;
|
|
3737
|
+
img.alt = entry.label || '';
|
|
3738
|
+
img.loading = 'lazy';
|
|
3739
|
+
thumbs.append(img);
|
|
3740
|
+
}
|
|
3741
|
+
card.append(thumbs);
|
|
3742
|
+
} else if (media.video) {
|
|
3743
|
+
const video = noticeEl('video');
|
|
3744
|
+
video.controls = true;
|
|
3745
|
+
video.playsInline = true;
|
|
3746
|
+
video.preload = 'metadata';
|
|
3747
|
+
if (media.poster) video.poster = media.poster;
|
|
3748
|
+
video.src = media.video;
|
|
3749
|
+
card.append(video);
|
|
3750
|
+
} else if (media.audio) {
|
|
3751
|
+
const audio = noticeEl('audio');
|
|
3752
|
+
audio.controls = true;
|
|
3753
|
+
audio.preload = 'none';
|
|
3754
|
+
audio.src = media.audio;
|
|
3755
|
+
card.append(audio);
|
|
3756
|
+
} else if (media.text) {
|
|
3757
|
+
const snippet =
|
|
3758
|
+
media.text.length > BG_SNIPPET_MAX_CHARS
|
|
3759
|
+
? `${media.text.slice(0, BG_SNIPPET_MAX_CHARS).trimEnd()}…`
|
|
3760
|
+
: media.text;
|
|
3761
|
+
card.append(noticeEl('div', 'text', snippet));
|
|
3762
|
+
}
|
|
3763
|
+
if (media.download) {
|
|
3764
|
+
const link = noticeEl('a', 'btn', t.download);
|
|
3765
|
+
link.href = media.download;
|
|
3766
|
+
link.setAttribute('download', '');
|
|
3767
|
+
link.target = '_blank';
|
|
3768
|
+
link.rel = 'noopener';
|
|
3769
|
+
actions.append(link);
|
|
3770
|
+
}
|
|
3771
|
+
if (media.text) {
|
|
3772
|
+
const copy = noticeEl('button', 'btn', t.copy);
|
|
3773
|
+
copy.type = 'button';
|
|
3774
|
+
copy.addEventListener('click', () => {
|
|
3775
|
+
try {
|
|
3776
|
+
navigator.clipboard
|
|
3777
|
+
.writeText(media.text)
|
|
3778
|
+
.then(() => {
|
|
3779
|
+
copy.textContent = t.copied;
|
|
3780
|
+
setTimeout(() => (copy.textContent = t.copy), 1_500);
|
|
3781
|
+
})
|
|
3782
|
+
.catch(() => {});
|
|
3783
|
+
} catch {
|
|
3784
|
+
/* no clipboard */
|
|
3785
|
+
}
|
|
3786
|
+
});
|
|
3787
|
+
actions.append(copy);
|
|
3788
|
+
}
|
|
3789
|
+
}
|
|
3790
|
+
if (actions.childNodes.length) card.append(actions);
|
|
3791
|
+
return card;
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
|
|
2374
3795
|
export default AIFlowClient;
|