tuxevil-rotator 4.2.2 → 4.3.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/CHANGELOG.md +27 -1
- package/README.md +9 -4
- package/package.json +1 -1
- package/plugins/opencode-discovery/capabilities.d.mts +7 -0
- package/plugins/opencode-discovery/capabilities.mjs +54 -0
- package/plugins/opencode-discovery/index.d.mts +2 -1
- package/plugins/opencode-discovery/index.mjs +6 -1
- package/plugins/opencode-discovery/package.json +3 -1
- package/src/audio-transcription.ts +32 -6
- package/src/cli.ts +3 -3
- package/src/compat/model-specs.ts +4 -0
- package/src/compat.ts +30 -1
- package/src/dashboard-app.ts +1 -0
- package/src/install-agent.ts +211 -129
- package/src/install-opencode.ts +80 -18
- package/src/providers/google-antigravity/catalog.ts +14 -6
- package/src/providers/google-antigravity/dynamic-catalog.ts +79 -3
- package/src/providers/google-antigravity/forward.ts +4 -2
- package/src/providers/google-antigravity/quota.ts +4 -0
- package/src/providers/ollama/forward.ts +10 -0
- package/src/providers/openai-codex/catalog.ts +157 -18
- package/src/proxy.ts +35 -2
- package/src/rotator.ts +16 -2
- package/src/types.ts +78 -29
- package/src/web/app.tsx +4 -0
- package/src/web/lib/audio-recorder.ts +159 -0
- package/src/web/lib/colors.ts +4 -0
- package/src/web/lib/playground-storage.ts +261 -0
- package/src/web/lib/playground.ts +448 -0
- package/src/web/nav.ts +1 -0
- package/src/web/pages/Playground.tsx +1111 -0
- package/src/web/pages/Transcription.tsx +428 -0
- package/src/web/state/api.ts +3 -0
- package/src/web/state/playground-client.ts +136 -0
- package/src/web/state/playground.ts +69 -0
- package/src/web/state/router.ts +2 -2
- package/src/web/state/transcription-client.ts +93 -0
- package/src/web/styles/app.css +45 -0
- package/tools/telemetry-receiver/receiver.js +59 -46
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import type { JSX } from "preact";
|
|
2
|
+
import { useEffect, useRef, useState } from "preact/hooks";
|
|
3
|
+
import { Button, Panel, Pill } from "../components/ui.js";
|
|
4
|
+
import { copyText, downloadText } from "./shared.js";
|
|
5
|
+
import { toast } from "../state/actions.js";
|
|
6
|
+
import { masked, masker } from "../state/store.js";
|
|
7
|
+
import { transcribeAudio } from "../state/transcription-client.js";
|
|
8
|
+
import { newId, type TranscriptionState } from "../lib/playground.js";
|
|
9
|
+
import {
|
|
10
|
+
AUDIO_ACCEPT,
|
|
11
|
+
AudioRecorder,
|
|
12
|
+
audioFileLimit,
|
|
13
|
+
MAX_RECORDING_MS,
|
|
14
|
+
validateAudioFile,
|
|
15
|
+
type RecordingState,
|
|
16
|
+
} from "../lib/audio-recorder.js";
|
|
17
|
+
import { formatMs } from "../lib/format.js";
|
|
18
|
+
|
|
19
|
+
interface Props {
|
|
20
|
+
state: TranscriptionState;
|
|
21
|
+
models: string[];
|
|
22
|
+
maxBodyBytes: number;
|
|
23
|
+
disabled: boolean;
|
|
24
|
+
onChange: (update: (state: TranscriptionState) => TranscriptionState) => void;
|
|
25
|
+
onBusyChange: (busy: boolean) => void;
|
|
26
|
+
controllers: Map<string, AbortController>;
|
|
27
|
+
}
|
|
28
|
+
export function TranscriptionPage({
|
|
29
|
+
state,
|
|
30
|
+
models,
|
|
31
|
+
maxBodyBytes,
|
|
32
|
+
disabled,
|
|
33
|
+
onChange,
|
|
34
|
+
onBusyChange,
|
|
35
|
+
controllers,
|
|
36
|
+
}: Props): JSX.Element {
|
|
37
|
+
const [file, setFile] = useState<File | null>(null);
|
|
38
|
+
const [url, setUrl] = useState("");
|
|
39
|
+
const [recording, setRecording] = useState<RecordingState>("idle");
|
|
40
|
+
const [elapsed, setElapsed] = useState(0);
|
|
41
|
+
const [sending, setSending] = useState(false);
|
|
42
|
+
const [error, setError] = useState("");
|
|
43
|
+
const inputRef = useRef<HTMLInputElement>(null);
|
|
44
|
+
const capture = useRef<AudioRecorder | null>(null);
|
|
45
|
+
const request = useRef<AbortController | null>(null);
|
|
46
|
+
const mounted = useRef(true);
|
|
47
|
+
const maxBytes = audioFileLimit(maxBodyBytes);
|
|
48
|
+
const available = models.filter(
|
|
49
|
+
(id) =>
|
|
50
|
+
id === "whisper-1" || (/^gemini-/i.test(id) && !/image|tts/i.test(id)),
|
|
51
|
+
);
|
|
52
|
+
const selected =
|
|
53
|
+
state.model ||
|
|
54
|
+
(available.includes("whisper-1") ? "whisper-1" : available[0] || "");
|
|
55
|
+
const active = sending || recording !== "idle";
|
|
56
|
+
const locked = disabled || active;
|
|
57
|
+
const canRecord =
|
|
58
|
+
typeof MediaRecorder !== "undefined" &&
|
|
59
|
+
!!navigator.mediaDevices?.getUserMedia &&
|
|
60
|
+
window.isSecureContext;
|
|
61
|
+
|
|
62
|
+
useEffect(() => {
|
|
63
|
+
onBusyChange(active);
|
|
64
|
+
}, [active]);
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
mounted.current = true;
|
|
67
|
+
const recorder = new AudioRecorder({
|
|
68
|
+
maxBytes,
|
|
69
|
+
onState: (value) => {
|
|
70
|
+
if (mounted.current) setRecording(value);
|
|
71
|
+
if (value === "idle") controllers.delete("microphone");
|
|
72
|
+
},
|
|
73
|
+
onFile: (audio) => {
|
|
74
|
+
if (mounted.current) {
|
|
75
|
+
setFile(audio);
|
|
76
|
+
setError("");
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
onError: (message) => {
|
|
80
|
+
if (mounted.current) setError(message);
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
capture.current = recorder;
|
|
84
|
+
return () => {
|
|
85
|
+
mounted.current = false;
|
|
86
|
+
recorder.cancel();
|
|
87
|
+
request.current?.abort();
|
|
88
|
+
controllers.delete("microphone");
|
|
89
|
+
controllers.delete("transcription");
|
|
90
|
+
onBusyChange(false);
|
|
91
|
+
};
|
|
92
|
+
}, [maxBytes]);
|
|
93
|
+
useEffect(() => {
|
|
94
|
+
if (!file) {
|
|
95
|
+
setUrl("");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const next = URL.createObjectURL(file);
|
|
99
|
+
setUrl(next);
|
|
100
|
+
return () => URL.revokeObjectURL(next);
|
|
101
|
+
}, [file]);
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
if (recording !== "recording") return;
|
|
104
|
+
const started = Date.now();
|
|
105
|
+
setElapsed(0);
|
|
106
|
+
const timer = setInterval(() => setElapsed(Date.now() - started), 1000);
|
|
107
|
+
return () => clearInterval(timer);
|
|
108
|
+
}, [recording]);
|
|
109
|
+
|
|
110
|
+
function selectFile(next: File): void {
|
|
111
|
+
try {
|
|
112
|
+
validateAudioFile(next, maxBytes);
|
|
113
|
+
setFile(next);
|
|
114
|
+
setError("");
|
|
115
|
+
} catch (err) {
|
|
116
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function startRecording(): void {
|
|
120
|
+
if (!canRecord || locked) return;
|
|
121
|
+
setError("");
|
|
122
|
+
setFile(null);
|
|
123
|
+
const controller = new AbortController();
|
|
124
|
+
controller.signal.addEventListener(
|
|
125
|
+
"abort",
|
|
126
|
+
() => capture.current?.cancel(),
|
|
127
|
+
{ once: true },
|
|
128
|
+
);
|
|
129
|
+
controllers.set("microphone", controller);
|
|
130
|
+
void capture.current?.start();
|
|
131
|
+
}
|
|
132
|
+
async function transcribe(): Promise<void> {
|
|
133
|
+
if (!file || locked) return;
|
|
134
|
+
if (!available.includes(selected)) {
|
|
135
|
+
setError("Choose an enabled audio model.");
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const controller = new AbortController();
|
|
139
|
+
request.current = controller;
|
|
140
|
+
controllers.set("transcription", controller);
|
|
141
|
+
setSending(true);
|
|
142
|
+
setError("");
|
|
143
|
+
try {
|
|
144
|
+
const result = await transcribeAudio(
|
|
145
|
+
{
|
|
146
|
+
file,
|
|
147
|
+
model: selected,
|
|
148
|
+
language: state.language.trim(),
|
|
149
|
+
prompt: state.prompt,
|
|
150
|
+
maxBodyBytes,
|
|
151
|
+
},
|
|
152
|
+
controller.signal,
|
|
153
|
+
);
|
|
154
|
+
if (mounted.current)
|
|
155
|
+
onChange((current) => ({
|
|
156
|
+
...current,
|
|
157
|
+
model: selected,
|
|
158
|
+
results: [
|
|
159
|
+
{ ...result, id: newId(), createdAt: Date.now() },
|
|
160
|
+
...current.results,
|
|
161
|
+
],
|
|
162
|
+
}));
|
|
163
|
+
} catch (err) {
|
|
164
|
+
if (mounted.current)
|
|
165
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
166
|
+
} finally {
|
|
167
|
+
controllers.delete("transcription");
|
|
168
|
+
request.current = null;
|
|
169
|
+
if (mounted.current) setSending(false);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return (
|
|
174
|
+
<div class="pg-transcription">
|
|
175
|
+
<Panel
|
|
176
|
+
title="Transcription"
|
|
177
|
+
subtitle="Upload an audio file or record with this device's microphone, then preview and send it to the rotator."
|
|
178
|
+
>
|
|
179
|
+
<div class="form">
|
|
180
|
+
<div class="form-grid">
|
|
181
|
+
<label class="field">
|
|
182
|
+
<span class="field-label">Audio model</span>
|
|
183
|
+
<select
|
|
184
|
+
class="input"
|
|
185
|
+
aria-label="Audio model"
|
|
186
|
+
value={selected}
|
|
187
|
+
disabled={locked}
|
|
188
|
+
onChange={(e) =>
|
|
189
|
+
onChange((current) => ({
|
|
190
|
+
...current,
|
|
191
|
+
model: e.currentTarget.value,
|
|
192
|
+
}))
|
|
193
|
+
}
|
|
194
|
+
>
|
|
195
|
+
{!available.length && (
|
|
196
|
+
<option value="">No audio models enabled</option>
|
|
197
|
+
)}
|
|
198
|
+
{state.model && !available.includes(state.model) && (
|
|
199
|
+
<option value={state.model}>
|
|
200
|
+
{state.model} (unavailable)
|
|
201
|
+
</option>
|
|
202
|
+
)}
|
|
203
|
+
{available.map((model) => (
|
|
204
|
+
<option key={model} value={model}>
|
|
205
|
+
{model}
|
|
206
|
+
</option>
|
|
207
|
+
))}
|
|
208
|
+
</select>
|
|
209
|
+
<span class="field-hint">
|
|
210
|
+
Transcription uses Gemini. whisper-1 is a compatibility alias;
|
|
211
|
+
audio support depends on the selected model.
|
|
212
|
+
</span>
|
|
213
|
+
</label>
|
|
214
|
+
<label class="field">
|
|
215
|
+
<span class="field-label">Language (optional)</span>
|
|
216
|
+
<input
|
|
217
|
+
class="input"
|
|
218
|
+
value={state.language}
|
|
219
|
+
maxLength={12}
|
|
220
|
+
placeholder="Auto detect (e.g. es, en)"
|
|
221
|
+
disabled={locked}
|
|
222
|
+
onInput={(e) =>
|
|
223
|
+
onChange((current) => ({
|
|
224
|
+
...current,
|
|
225
|
+
language: e.currentTarget.value,
|
|
226
|
+
}))
|
|
227
|
+
}
|
|
228
|
+
/>
|
|
229
|
+
</label>
|
|
230
|
+
</div>
|
|
231
|
+
<label class="field">
|
|
232
|
+
<span class="field-label">Vocabulary context (optional)</span>
|
|
233
|
+
<textarea
|
|
234
|
+
class="input pg-audio-context"
|
|
235
|
+
rows={2}
|
|
236
|
+
maxLength={1000}
|
|
237
|
+
value={state.prompt}
|
|
238
|
+
disabled={locked}
|
|
239
|
+
placeholder="Names, technical terms or other vocabulary to help recognition."
|
|
240
|
+
onInput={(e) =>
|
|
241
|
+
onChange((current) => ({
|
|
242
|
+
...current,
|
|
243
|
+
prompt: e.currentTarget.value,
|
|
244
|
+
}))
|
|
245
|
+
}
|
|
246
|
+
/>
|
|
247
|
+
</label>
|
|
248
|
+
<div class="pg-toolbar">
|
|
249
|
+
<Button
|
|
250
|
+
icon="upload"
|
|
251
|
+
disabled={locked}
|
|
252
|
+
onClick={() => inputRef.current?.click()}
|
|
253
|
+
>
|
|
254
|
+
Upload audio
|
|
255
|
+
</Button>
|
|
256
|
+
<input
|
|
257
|
+
ref={inputRef}
|
|
258
|
+
class="sr-only"
|
|
259
|
+
type="file"
|
|
260
|
+
accept={AUDIO_ACCEPT}
|
|
261
|
+
aria-label="Audio file"
|
|
262
|
+
disabled={locked}
|
|
263
|
+
onChange={(e) => {
|
|
264
|
+
const next = e.currentTarget.files?.[0];
|
|
265
|
+
e.currentTarget.value = "";
|
|
266
|
+
if (next) selectFile(next);
|
|
267
|
+
}}
|
|
268
|
+
/>
|
|
269
|
+
<Button
|
|
270
|
+
icon="play"
|
|
271
|
+
disabled={locked || !canRecord}
|
|
272
|
+
onClick={startRecording}
|
|
273
|
+
>
|
|
274
|
+
Record microphone
|
|
275
|
+
</Button>
|
|
276
|
+
{recording === "recording" && (
|
|
277
|
+
<>
|
|
278
|
+
<Pill tone="bad">
|
|
279
|
+
Recording · {Math.floor(elapsed / 60_000)}:
|
|
280
|
+
{String(Math.floor(elapsed / 1000) % 60).padStart(2, "0")}
|
|
281
|
+
</Pill>
|
|
282
|
+
<Button
|
|
283
|
+
variant="primary"
|
|
284
|
+
onClick={() => capture.current?.stop()}
|
|
285
|
+
>
|
|
286
|
+
Stop recording
|
|
287
|
+
</Button>
|
|
288
|
+
</>
|
|
289
|
+
)}
|
|
290
|
+
{recording === "requesting" && (
|
|
291
|
+
<span role="status">Waiting for microphone permission…</span>
|
|
292
|
+
)}
|
|
293
|
+
{recording === "finalizing" && (
|
|
294
|
+
<span role="status">Preparing recording…</span>
|
|
295
|
+
)}
|
|
296
|
+
{recording !== "idle" && (
|
|
297
|
+
<Button
|
|
298
|
+
variant="danger"
|
|
299
|
+
onClick={() => capture.current?.cancel()}
|
|
300
|
+
>
|
|
301
|
+
Cancel recording
|
|
302
|
+
</Button>
|
|
303
|
+
)}
|
|
304
|
+
</div>
|
|
305
|
+
{!canRecord && (
|
|
306
|
+
<p class="field-hint">
|
|
307
|
+
Microphone recording requires HTTPS or localhost and a browser
|
|
308
|
+
with MediaRecorder support. You can still upload an audio file.
|
|
309
|
+
</p>
|
|
310
|
+
)}
|
|
311
|
+
<p class="field-hint">
|
|
312
|
+
WAV, MP3, M4A/MP4, WebM, OGG/OGA, FLAC or PCM. Up to{" "}
|
|
313
|
+
{(maxBytes / 1024 / 1024).toFixed(1)} MiB per file. Recording stops
|
|
314
|
+
automatically after {MAX_RECORDING_MS / 60_000} minutes.
|
|
315
|
+
</p>
|
|
316
|
+
{file && (
|
|
317
|
+
<div class="pg-audio-preview">
|
|
318
|
+
<div class="pg-toolbar">
|
|
319
|
+
<strong>{masked.value ? "Audio file" : file.name}</strong>
|
|
320
|
+
<span class="muted">{(file.size / 1024).toFixed(1)} KiB</span>
|
|
321
|
+
<Button
|
|
322
|
+
size="sm"
|
|
323
|
+
disabled={locked}
|
|
324
|
+
onClick={() => setFile(null)}
|
|
325
|
+
>
|
|
326
|
+
Remove audio
|
|
327
|
+
</Button>
|
|
328
|
+
</div>
|
|
329
|
+
{url && (
|
|
330
|
+
<audio
|
|
331
|
+
controls
|
|
332
|
+
preload="metadata"
|
|
333
|
+
src={url}
|
|
334
|
+
aria-label="Audio preview"
|
|
335
|
+
/>
|
|
336
|
+
)}
|
|
337
|
+
</div>
|
|
338
|
+
)}
|
|
339
|
+
{error && (
|
|
340
|
+
<p class="form-error" role="alert">
|
|
341
|
+
{masker.value.text(error)}
|
|
342
|
+
</p>
|
|
343
|
+
)}
|
|
344
|
+
<div class="pg-toolbar">
|
|
345
|
+
<Button
|
|
346
|
+
variant="primary"
|
|
347
|
+
disabled={locked || !file || !available.includes(selected)}
|
|
348
|
+
onClick={() => void transcribe()}
|
|
349
|
+
>
|
|
350
|
+
Transcribe
|
|
351
|
+
</Button>
|
|
352
|
+
{sending && (
|
|
353
|
+
<>
|
|
354
|
+
<span role="status">Transcribing…</span>
|
|
355
|
+
<Button
|
|
356
|
+
variant="danger"
|
|
357
|
+
onClick={() => request.current?.abort()}
|
|
358
|
+
>
|
|
359
|
+
Cancel transcription
|
|
360
|
+
</Button>
|
|
361
|
+
</>
|
|
362
|
+
)}
|
|
363
|
+
</div>
|
|
364
|
+
<p class="field-hint">
|
|
365
|
+
Audio is sent only when you press Transcribe. Only results and
|
|
366
|
+
settings are saved in local history; audio files and recordings stay
|
|
367
|
+
in this tab.
|
|
368
|
+
</p>
|
|
369
|
+
</div>
|
|
370
|
+
</Panel>
|
|
371
|
+
{state.results.map((result) => (
|
|
372
|
+
<Panel
|
|
373
|
+
key={result.id}
|
|
374
|
+
title={masked.value ? "Transcript" : result.filename}
|
|
375
|
+
subtitle={`${result.model} · ${new Date(result.createdAt).toLocaleString()} · ${formatMs(result.elapsedMs)}`}
|
|
376
|
+
actions={
|
|
377
|
+
<>
|
|
378
|
+
<Button
|
|
379
|
+
size="sm"
|
|
380
|
+
onClick={() =>
|
|
381
|
+
void copyText(result.text).then((ok) =>
|
|
382
|
+
toast(
|
|
383
|
+
ok ? "Transcript copied" : "Could not copy transcript",
|
|
384
|
+
ok ? "success" : "error",
|
|
385
|
+
),
|
|
386
|
+
)
|
|
387
|
+
}
|
|
388
|
+
>
|
|
389
|
+
Copy text
|
|
390
|
+
</Button>
|
|
391
|
+
<Button
|
|
392
|
+
size="sm"
|
|
393
|
+
icon="download"
|
|
394
|
+
onClick={() =>
|
|
395
|
+
downloadText(
|
|
396
|
+
`transcript-${result.id}.txt`,
|
|
397
|
+
result.text,
|
|
398
|
+
"text/plain;charset=utf-8",
|
|
399
|
+
)
|
|
400
|
+
}
|
|
401
|
+
>
|
|
402
|
+
Download text
|
|
403
|
+
</Button>
|
|
404
|
+
<Button
|
|
405
|
+
size="sm"
|
|
406
|
+
disabled={locked}
|
|
407
|
+
onClick={() =>
|
|
408
|
+
onChange((current) => ({
|
|
409
|
+
...current,
|
|
410
|
+
results: current.results.filter((r) => r.id !== result.id),
|
|
411
|
+
}))
|
|
412
|
+
}
|
|
413
|
+
>
|
|
414
|
+
Delete result
|
|
415
|
+
</Button>
|
|
416
|
+
</>
|
|
417
|
+
}
|
|
418
|
+
>
|
|
419
|
+
<pre class="pg-answer">
|
|
420
|
+
{result.text
|
|
421
|
+
? masker.value.text(result.text)
|
|
422
|
+
: "No clear speech detected."}
|
|
423
|
+
</pre>
|
|
424
|
+
</Panel>
|
|
425
|
+
))}
|
|
426
|
+
</div>
|
|
427
|
+
);
|
|
428
|
+
}
|
package/src/web/state/api.ts
CHANGED
|
@@ -33,6 +33,8 @@ export function setUnauthorizedHandler(handler: () => void): void {
|
|
|
33
33
|
onUnauthorized = handler;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
export function notifyUnauthorized(): void { onUnauthorized(); }
|
|
37
|
+
|
|
36
38
|
function messageFrom(body: unknown): string | null {
|
|
37
39
|
if (!body || typeof body !== "object") return null;
|
|
38
40
|
const record = body as Record<string, unknown>;
|
|
@@ -136,6 +138,7 @@ function query(params: Record<string, string | number | undefined>): string {
|
|
|
136
138
|
}
|
|
137
139
|
|
|
138
140
|
export const api = {
|
|
141
|
+
playgroundConfig: () => request<{ maxBodyBytes: number }>("GET", "/api/playground/config"),
|
|
139
142
|
session: () => request<SessionInfo>("GET", "/api/session", undefined, { ignoreUnauthorized: true }),
|
|
140
143
|
signIn: (token: string) =>
|
|
141
144
|
request<{ ok: true }>("POST", "/api/session", { token }, { ignoreUnauthorized: true }),
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { ApiError, notifyUnauthorized } from "./api.js";
|
|
2
|
+
import {
|
|
3
|
+
apiErrorMessage,
|
|
4
|
+
applyCompletion,
|
|
5
|
+
emptyResult,
|
|
6
|
+
SseDecoder,
|
|
7
|
+
type ChatRequest,
|
|
8
|
+
type ChatResult,
|
|
9
|
+
} from "../lib/playground.js";
|
|
10
|
+
|
|
11
|
+
export class PlaygroundError extends Error {
|
|
12
|
+
constructor(
|
|
13
|
+
message: string,
|
|
14
|
+
readonly result: ChatResult,
|
|
15
|
+
readonly cancelled = false,
|
|
16
|
+
) {
|
|
17
|
+
super(message);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One cancellable request, shared by Chat, Compare and Compliance. */
|
|
22
|
+
export async function runChat(
|
|
23
|
+
request: ChatRequest,
|
|
24
|
+
signal: AbortSignal,
|
|
25
|
+
onProgress: (result: ChatResult) => void = () => {},
|
|
26
|
+
fetcher: typeof fetch = fetch,
|
|
27
|
+
timeoutMs = 120_000,
|
|
28
|
+
): Promise<ChatResult> {
|
|
29
|
+
const started = performance.now();
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
const abort = () => controller.abort();
|
|
32
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
33
|
+
if (signal.aborted) abort();
|
|
34
|
+
let timedOut = false;
|
|
35
|
+
const timer = setTimeout(() => {
|
|
36
|
+
timedOut = true;
|
|
37
|
+
controller.abort();
|
|
38
|
+
}, timeoutMs);
|
|
39
|
+
const result = emptyResult();
|
|
40
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
41
|
+
try {
|
|
42
|
+
const response = await fetcher("/api/playground/chat/completions", {
|
|
43
|
+
method: "POST",
|
|
44
|
+
credentials: "same-origin",
|
|
45
|
+
signal: controller.signal,
|
|
46
|
+
headers: { "Content-Type": "application/json" },
|
|
47
|
+
body: JSON.stringify(request),
|
|
48
|
+
});
|
|
49
|
+
result.status = response.status;
|
|
50
|
+
response.headers.forEach((value, key) => {
|
|
51
|
+
if (key.startsWith("x-rotator-")) result.metadata[key] = value;
|
|
52
|
+
});
|
|
53
|
+
if (response.status === 401) {
|
|
54
|
+
notifyUnauthorized();
|
|
55
|
+
throw new ApiError(401, "Your session ended. Sign in again.");
|
|
56
|
+
}
|
|
57
|
+
if (!response.ok) {
|
|
58
|
+
let data: unknown;
|
|
59
|
+
try {
|
|
60
|
+
data = await response.json();
|
|
61
|
+
} catch {
|
|
62
|
+
data = null;
|
|
63
|
+
}
|
|
64
|
+
if (data) result.raw.push(data);
|
|
65
|
+
throw new Error(
|
|
66
|
+
apiErrorMessage(data) || `Request failed (HTTP ${response.status}).`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
if (request.stream) {
|
|
70
|
+
if (
|
|
71
|
+
!response.headers.get("content-type")?.includes("text/event-stream") ||
|
|
72
|
+
!response.body
|
|
73
|
+
)
|
|
74
|
+
throw new Error("Expected an SSE response.");
|
|
75
|
+
let terminated = false;
|
|
76
|
+
const parser = new SseDecoder((data) => {
|
|
77
|
+
if (terminated) throw new Error("Received data after [DONE].");
|
|
78
|
+
if (data === "[DONE]") {
|
|
79
|
+
terminated = true;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
applyCompletion(
|
|
83
|
+
result,
|
|
84
|
+
JSON.parse(data) as unknown,
|
|
85
|
+
true,
|
|
86
|
+
performance.now() - started,
|
|
87
|
+
);
|
|
88
|
+
result.durationMs = performance.now() - started;
|
|
89
|
+
onProgress(structuredClone(result));
|
|
90
|
+
});
|
|
91
|
+
reader = response.body.getReader();
|
|
92
|
+
const decoder = new TextDecoder();
|
|
93
|
+
for (;;) {
|
|
94
|
+
const { done, value } = await reader.read();
|
|
95
|
+
if (done) break;
|
|
96
|
+
parser.push(decoder.decode(value, { stream: true }));
|
|
97
|
+
}
|
|
98
|
+
parser.push(decoder.decode());
|
|
99
|
+
parser.finish();
|
|
100
|
+
if (!terminated || !result.finishReason)
|
|
101
|
+
throw new Error("Stream ended without a finish reason and [DONE].");
|
|
102
|
+
} else {
|
|
103
|
+
applyCompletion(
|
|
104
|
+
result,
|
|
105
|
+
await response.json(),
|
|
106
|
+
false,
|
|
107
|
+
performance.now() - started,
|
|
108
|
+
);
|
|
109
|
+
if (!result.finishReason)
|
|
110
|
+
throw new Error("Response is missing finish_reason.");
|
|
111
|
+
}
|
|
112
|
+
if (controller.signal.aborted) throw new Error("Request aborted.");
|
|
113
|
+
result.done = true;
|
|
114
|
+
return result;
|
|
115
|
+
} catch (err) {
|
|
116
|
+
const message = timedOut
|
|
117
|
+
? "Request timed out after 120 seconds."
|
|
118
|
+
: signal.aborted
|
|
119
|
+
? "Request cancelled."
|
|
120
|
+
: err instanceof Error
|
|
121
|
+
? err.message
|
|
122
|
+
: String(err);
|
|
123
|
+
throw new PlaygroundError(message, result, signal.aborted && !timedOut);
|
|
124
|
+
} finally {
|
|
125
|
+
result.durationMs = performance.now() - started;
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
signal.removeEventListener("abort", abort);
|
|
128
|
+
// Cancel a malformed or interrupted response so server capacity is released.
|
|
129
|
+
try {
|
|
130
|
+
await reader?.cancel();
|
|
131
|
+
} catch {
|
|
132
|
+
/* the transport may already be closed */
|
|
133
|
+
}
|
|
134
|
+
reader?.releaseLock();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { signal } from "@preact/signals";
|
|
2
|
+
import { newDocument, type PlaygroundDocument } from "../lib/playground.js";
|
|
3
|
+
import {
|
|
4
|
+
readWorkspace,
|
|
5
|
+
writeWorkspace,
|
|
6
|
+
type PlaygroundWorkspace,
|
|
7
|
+
} from "../lib/playground-storage.js";
|
|
8
|
+
|
|
9
|
+
export const workspace = signal<PlaygroundWorkspace | null>(null);
|
|
10
|
+
export const storageError = signal("");
|
|
11
|
+
let initialization: Promise<void> | undefined;
|
|
12
|
+
let saveTimer: ReturnType<typeof setTimeout> | undefined;
|
|
13
|
+
export function initializePlayground(): Promise<void> {
|
|
14
|
+
initialization ??= (async () => {
|
|
15
|
+
try {
|
|
16
|
+
workspace.value = await readWorkspace();
|
|
17
|
+
} catch (err) {
|
|
18
|
+
storageError.value = String(err);
|
|
19
|
+
}
|
|
20
|
+
if (!workspace.value || !workspace.value.documents.length) {
|
|
21
|
+
const doc = newDocument();
|
|
22
|
+
workspace.value = { version: 1, currentId: doc.id, documents: [doc] };
|
|
23
|
+
}
|
|
24
|
+
})();
|
|
25
|
+
return initialization;
|
|
26
|
+
}
|
|
27
|
+
export function currentDocument(): PlaygroundDocument | null {
|
|
28
|
+
const state = workspace.value;
|
|
29
|
+
return (
|
|
30
|
+
state?.documents.find((doc) => doc.id === state.currentId) ??
|
|
31
|
+
state?.documents[0] ??
|
|
32
|
+
null
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
export function saveWorkspace(
|
|
36
|
+
next: PlaygroundWorkspace,
|
|
37
|
+
immediate = false,
|
|
38
|
+
): void {
|
|
39
|
+
workspace.value = next;
|
|
40
|
+
clearTimeout(saveTimer);
|
|
41
|
+
const save = () => {
|
|
42
|
+
void writeWorkspace(workspace.value!)
|
|
43
|
+
.then(() => {
|
|
44
|
+
storageError.value = "";
|
|
45
|
+
})
|
|
46
|
+
.catch((err) => {
|
|
47
|
+
storageError.value = String(err);
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
if (immediate) save();
|
|
51
|
+
else saveTimer = setTimeout(save, 300);
|
|
52
|
+
}
|
|
53
|
+
export function updateDocument(
|
|
54
|
+
update: (doc: PlaygroundDocument) => PlaygroundDocument,
|
|
55
|
+
immediate = false,
|
|
56
|
+
): void {
|
|
57
|
+
const doc = currentDocument();
|
|
58
|
+
if (!doc || !workspace.value) return;
|
|
59
|
+
const next = { ...update(doc), updatedAt: Date.now() };
|
|
60
|
+
saveWorkspace(
|
|
61
|
+
{
|
|
62
|
+
...workspace.value,
|
|
63
|
+
documents: workspace.value.documents.map((d) =>
|
|
64
|
+
d.id === doc.id ? next : d,
|
|
65
|
+
),
|
|
66
|
+
},
|
|
67
|
+
immediate,
|
|
68
|
+
);
|
|
69
|
+
}
|
package/src/web/state/router.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { computed, signal } from "@preact/signals";
|
|
|
5
5
|
|
|
6
6
|
export const BASE = "/dashboard";
|
|
7
7
|
|
|
8
|
-
export type PageId = "overview" | "accounts" | "models" | "requests" | "usage" | "keys" | "settings";
|
|
8
|
+
export type PageId = "overview" | "accounts" | "models" | "requests" | "usage" | "keys" | "settings" | "playground";
|
|
9
9
|
|
|
10
10
|
export interface RouteMatch {
|
|
11
11
|
page: PageId | "not-found";
|
|
@@ -133,7 +133,7 @@ export function matchRoute(path: string): RouteMatch {
|
|
|
133
133
|
if (head === "accounts") return { ...none, page: "accounts", account: decodeSegment(second) };
|
|
134
134
|
if (head === "models" && second === "effort") return { ...none, page: "models", effort: { alias: decodeSegment(third) } };
|
|
135
135
|
if (head === "models") return { ...none, page: "models", provider: decodeSegment(second) };
|
|
136
|
-
if (head === "requests" || head === "usage" || head === "keys" || head === "settings") {
|
|
136
|
+
if (head === "playground" || head === "requests" || head === "usage" || head === "keys" || head === "settings") {
|
|
137
137
|
return { ...none, page: head };
|
|
138
138
|
}
|
|
139
139
|
return { ...none, page: "not-found" };
|