-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmodelseed.ts
More file actions
825 lines (754 loc) · 28 KB
/
modelseed.ts
File metadata and controls
825 lines (754 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// lib/api/modelseed.ts
/**
* Thin client for the new ModelSEED REST backend (modelseed-api).
*
* This module intentionally mirrors the patterns used in lib/api/workspace.ts
* and lib/api/auth.ts so that we can swap backends via configuration without
* touching the UI components again.
*/
import {
MODELSEED_API_URL,
MODELSEED_SUPPORT_URL,
USE_MODELSEED_API,
USE_NEW_PROXY,
WORKSPACE_URL,
} from './config';
import { getStoredAuthUsername, withRawTokenAuth } from './requestAuth';
export interface ModelseedModelSummary {
ref: string;
id: string;
name: string;
status?: string;
num_genes?: number;
num_reactions?: number;
num_compounds?: number;
fba_count?: number;
unintegrated_gapfills?: number;
integrated_gapfills?: number;
rundate?: string;
genome_id?: string;
organism_name?: string;
taxonomy?: string;
}
export interface ModelseedMediaSummary {
id: string;
name: string;
ref?: string;
isMinimal?: boolean | string;
isDefined?: boolean | string;
type?: string;
modDate?: string;
}
export interface ModelseedJobSummary {
id: string;
status?: string;
type?: string;
app?: string;
created_at?: string;
completed_at?: string;
[key: string]: unknown;
}
export interface RastGenomeJob {
id: string;
genome_id: string;
genome_name: string;
contig_count?: number;
mod_time?: string;
type: 'Genome';
}
export interface ModelDetailBundle {
ref: string;
data: Record<string, unknown>;
gapfills: Record<string, unknown>[];
fba: Record<string, unknown> | Record<string, unknown>[] | null;
}
function buildQueryString(params: Record<string, string | undefined>): string {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value != null && value !== '') query.set(key, value);
}
const encoded = query.toString();
return encoded ? `?${encoded}` : '';
}
function extractApiErrorMessage(payload: unknown): string | null {
if (!payload || typeof payload !== 'object') return null;
const rec = payload as Record<string, unknown>;
if (typeof rec.detail === 'string' && rec.detail) return rec.detail;
if (typeof rec.message === 'string' && rec.message) return rec.message;
const err = rec.error;
if (err && typeof err === 'object') {
const rpcErr = err as Record<string, unknown>;
if (typeof rpcErr.message === 'string' && rpcErr.message) return rpcErr.message;
if (typeof rpcErr.error === 'string' && rpcErr.error) return rpcErr.error;
}
return null;
}
async function parseJsonResponse(response: Response): Promise<{ payload: unknown; rawText: string }> {
const rawText = await response.text().catch(() => '');
if (!rawText) return { payload: null, rawText: '' };
try {
return { payload: JSON.parse(rawText) as unknown, rawText };
} catch {
return { payload: { raw: rawText }, rawText };
}
}
async function modelseedFetch<T>(path: string, init: RequestInit = {}, requireAuth = true): Promise<T> {
if (!USE_MODELSEED_API) {
throw new Error('modelseed-api client called but USE_MODELSEED_API is false');
}
const baseHeaders: Record<string, string> = {
Accept: 'application/json',
...(init.headers as Record<string, string> | undefined),
};
const headers = withRawTokenAuth(baseHeaders, requireAuth);
const response = await fetch(`${MODELSEED_API_URL}${path}`, {
...init,
headers,
});
const { payload, rawText } = await parseJsonResponse(response);
if (!response.ok) {
const detail = extractApiErrorMessage(payload);
throw new Error(
`modelseed-api ${path} failed (${response.status})${detail ? `: ${detail}` : rawText ? `: ${rawText}` : ''}`,
);
}
return payload as T;
}
/**
* Safely parse a value as a number, handling edge cases like "N/A", empty strings, or invalid values.
* Returns undefined if the value cannot be parsed as a finite number.
*/
function safeParseNumber(val: unknown): number | undefined {
if (val === null || val === undefined) return undefined;
if (typeof val === 'number' && Number.isFinite(val)) return val;
if (typeof val === 'string') {
const trimmed = val.trim();
if (trimmed === '' || trimmed.toLowerCase() === 'n/a') return undefined;
const parsed = Number(trimmed);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
}
/**
* Process model summary data with defensive number parsing.
*
* Handles edge cases like "N/A" values or invalid numbers in metadata
* to prevent crashes from malformed backend data.
*
* @param raw - Raw model data from API
* @returns Typed ModelseedModelSummary with safe defaults
*/
function processModelSummary(raw: Record<string, unknown>): ModelseedModelSummary {
return {
ref: String(raw.ref ?? ''),
id: String(raw.id ?? ''),
name: String(raw.name ?? ''),
status: raw.status != null ? String(raw.status) : undefined,
num_genes: safeParseNumber(raw.num_genes),
num_reactions: safeParseNumber(raw.num_reactions),
num_compounds: safeParseNumber(raw.num_compounds),
fba_count: safeParseNumber(raw.fba_count),
unintegrated_gapfills: safeParseNumber(raw.unintegrated_gapfills),
integrated_gapfills: safeParseNumber(raw.integrated_gapfills),
rundate: raw.rundate != null ? String(raw.rundate) : undefined,
genome_id: raw.genome_id != null ? String(raw.genome_id) : undefined,
organism_name: raw.organism_name != null ? String(raw.organism_name) : undefined,
taxonomy: raw.taxonomy != null ? String(raw.taxonomy) : undefined,
};
}
/**
* List all models owned by the authenticated user.
*
* Fetches model summaries from the modelseed-api backend with defensive
* parsing to handle malformed metadata gracefully.
*
* @returns Promise resolving to array of model summaries
* @throws {Error} When not authenticated or request fails
*
* @example
* ```typescript
* const models = await listUserModelsFromApi();
* models.forEach(model => {
* console.log(`${model.name}: ${model.num_reactions} reactions, ${model.num_genes} genes`);
* });
* ```
*/
export async function listUserModelsFromApi(): Promise<ModelseedModelSummary[]> {
const rawModels = await modelseedFetch<Record<string, unknown>[]>('/api/models');
// Process each model with defensive parsing to handle edge case metadata
return rawModels.map((raw, index) => {
try {
return processModelSummary(raw);
} catch (err) {
console.warn(`Failed to process model at index ${index}:`, err, raw);
// Return a minimal valid model object rather than crashing
return {
ref: String(raw.ref ?? ''),
id: String(raw.id ?? `unknown-${index}`),
name: String(raw.name ?? 'Unknown'),
};
}
});
}
/**
* Fetch full model data by workspace reference.
*
* @param ref - Workspace reference path (e.g., '/user@patricbrc.org/models/MyModel')
* @returns Promise resolving to model data object
* @throws {Error} When model not found or request fails
*
* @example
* ```typescript
* const modelData = await getModelDataFromApi('/user@patricbrc.org/models/EcoliModel');
* console.log('Model has', modelData.modelreactions.length, 'reactions');
* ```
*/
export async function getModelDataFromApi(ref: string): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>(
`/api/models/data${buildQueryString({ ref: safeDecodePath(ref) })}`,
);
}
export async function copyModelFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/models/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
export async function listModelGapfillsFromApi(ref: string): Promise<Record<string, unknown>[]> {
try {
return await modelseedFetch<Record<string, unknown>[]>(
`/api/models/gapfills${buildQueryString({ ref: safeDecodePath(ref) })}`,
);
} catch (err) {
// 404 means no gapfill data exists yet - this is expected for models without gapfill runs
if (err instanceof Error && err.message.includes('(404)')) {
return [];
}
throw err;
}
}
export async function manageModelGapfillsFromApi(
model: string,
commands: Record<string, string>,
selectedSolutions?: Record<string, number>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/models/gapfills/manage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, commands, selected_solutions: selectedSolutions }),
});
}
export async function getModelFbaFromApi(ref: string): Promise<Record<string, unknown>[] | null> {
try {
return await modelseedFetch<Record<string, unknown>[]>(
`/api/models/fba${buildQueryString({ ref: safeDecodePath(ref) })}`,
);
} catch (err) {
// 404 means no FBA data exists yet - this is expected for models without FBA runs
if (err instanceof Error && err.message.includes('(404)')) {
return null;
}
throw err;
}
}
export async function getModelFbaDataFromApi(
ref: string,
fbaId: string,
): Promise<Record<string, unknown> | null> {
try {
return await modelseedFetch<Record<string, unknown>>(
`/api/models/fba/data${buildQueryString({
ref: safeDecodePath(ref),
fba_id: safeDecodePath(fbaId),
})}`,
);
} catch (err) {
// 404 means no detail data exists yet for this FBA run
if (err instanceof Error && err.message.includes('(404)')) {
return null;
}
throw err;
}
}
export async function getModelDetailBundleFromApi(ref: string): Promise<ModelDetailBundle> {
const [data, gapfills, fba] = await Promise.all([
getModelDataFromApi(ref),
listModelGapfillsFromApi(ref).catch(() => []),
getModelFbaFromApi(ref).catch(() => null),
]);
return {
ref,
data,
gapfills,
fba,
};
}
/**
* Returns a Blob containing the exported model file.
* formats: 'sbml' | 'json' | 'tsv'
*/
export async function exportModelFromApi(ref: string, format: string): Promise<Blob> {
const response = await fetch(
`${MODELSEED_API_URL}/api/models/export?ref=${encodeURIComponent(safeDecodePath(ref))}&format=${format}`,
{
headers: {
...withRawTokenAuth({}, true),
},
},
);
if (!response.ok) {
throw new Error(`Export failed: ${response.statusText}`);
}
return response.blob();
}
/**
* Deletes a model from the workspace via the modelseed-api proxy.
*/
export async function deleteModelFromApi(ref: string): Promise<void> {
const response = await fetch(
`${MODELSEED_API_URL}/api/models?ref=${encodeURIComponent(safeDecodePath(ref))}`,
{
method: 'DELETE',
headers: withRawTokenAuth({}, true),
},
);
if (!response.ok) {
throw new Error(`Delete failed: ${response.statusText}`);
}
}
export async function getJobsFromApi(ids: string[]): Promise<ModelseedJobSummary[]> {
const query = ids.length > 0 ? { ids: ids.join(',') } : {};
const payload = await modelseedFetch<unknown>(`/api/jobs${buildQueryString(query)}`);
if (Array.isArray(payload)) {
return payload as ModelseedJobSummary[];
}
if (payload && typeof payload === 'object') {
return Object.values(payload as Record<string, ModelseedJobSummary>);
}
return [];
}
/**
* Submit a model reconstruction job.
*
* Submits a genome-to-model reconstruction job to the backend queue.
* Job completion can take minutes to hours depending on genome size.
*
* @param payload - Reconstruction parameters (genome, model_name, template, gapfill, etc.)
* @returns Promise resolving to job submission response (contains job ID)
* @throws {Error} When not authenticated or submission fails
*
* @example
* ```typescript
* const response = await submitReconstructJobFromApi({
* genome: '511145.12',
* model_name: 'EcoliModel',
* template: 'GramNegative',
* gapfill: true
* });
* const jobId = extractTrackedJobId(response);
* trackJob({ id: jobId, kind: 'reconstruct', label: 'E. coli reconstruction', ... });
* ```
*/
export async function submitReconstructJobFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/jobs/reconstruct', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
export async function submitGapfillJobFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/jobs/gapfill', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
export async function submitFbaJobFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/jobs/fba', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
export async function manageJobFromApi(
payload: { ids: string[]; action: string } | Record<string, unknown>,
): Promise<Record<string, unknown>> {
const body =
Array.isArray((payload as { ids?: unknown }).ids)
? { jobs: (payload as { ids: string[] }).ids, action: (payload as { action: string }).action }
: payload;
return modelseedFetch<Record<string, unknown>>('/api/jobs/manage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
}
export async function submitMergeJobFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
return modelseedFetch<Record<string, unknown>>('/api/jobs/merge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
interface RastJobsRpcResponse {
result?: unknown;
error?: {
code?: number;
message?: string;
error?: string;
};
}
type RawRastJob = {
id?: unknown;
genome_id?: unknown;
genome_name?: unknown;
contig_count?: unknown;
mod_time?: unknown;
type?: unknown;
};
/**
* List RAST genome annotation jobs for the authenticated user.
*
* Queries the modelseed_support backend for RAST genome jobs. Includes complex
* fallback logic to handle different backend RPC method names and deployment
* configurations. Returns empty array if backend is misconfigured rather than
* crashing the UI.
*
* @returns Promise resolving to array of RAST genome jobs
* @throws {Error} When authentication fails or all RPC methods fail
*
* @example
* ```typescript
* const genomes = await listRastGenomes();
* genomes.forEach(genome => {
* console.log(`${genome.genome_name} (${genome.genome_id}) - ${genome.contig_count} contigs`);
* });
* ```
*/
export async function listRastGenomes(): Promise<RastGenomeJob[]> {
const callRastList = async (method: string, params: Record<string, unknown>) => {
const response = await fetch(MODELSEED_SUPPORT_URL, {
method: 'POST',
headers: withRawTokenAuth(
{
'Content-Type': 'application/json',
Accept: 'application/json',
},
true,
),
body: JSON.stringify({
version: '1.1',
method,
id: 'list-rast-genomes',
params: [params],
}),
});
const { payload: rawPayload, rawText } = await parseJsonResponse(response);
const payload = rawPayload as RastJobsRpcResponse | null;
if (!response.ok) {
// Some deployments return RPC JSON error payloads with HTTP 500.
// Preserve payload so caller can apply compatibility fallbacks.
if (payload?.error) {
return payload;
}
throw new Error(
`RAST list jobs ${method} failed (${response.status})${rawText ? `: ${rawText}` : ''}`,
);
}
if (!payload) {
throw new Error('RAST list jobs returned an empty or non-JSON response');
}
return payload;
};
const candidateMethods = [
// Legacy ModelSEED UI used `service=msSupport` + `method=list_rast_jobs`,
// which resolved to `MSSeedSupportServer.list_rast_jobs`.
'MSSeedSupportServer.list_rast_jobs',
// Keep compatibility fallbacks for any non-standard deployments.
'msSupport.list_rast_jobs',
'ms_fba.list_rast_jobs',
];
const username = getStoredAuthUsername();
const candidateParams: Record<string, unknown>[] = username
? [{ owner: username }, {}]
: [{}];
let payload: RastJobsRpcResponse | null = null;
const methodErrors: string[] = [];
for (const method of candidateMethods) {
for (const params of candidateParams) {
const attempt = await callRastList(method, params);
if (attempt.error) {
const message = attempt.error.message || attempt.error.error || '';
const paramsLabel = 'owner' in params ? `owner=${String(params.owner)}` : 'owner=<none>';
methodErrors.push(
`${method} (${paramsLabel}): ${message || `error code ${attempt.error.code ?? 'unknown'}`}`,
);
// -32601 indicates "method not found" in most deployments. Some gateways also use it
// for "package not found". Either way, move to the next compatible method name.
if (attempt.error.code === -32601) {
break;
}
// This backend error appears when owner cannot be resolved internally.
// Try the alternate param payload before failing.
if ((attempt.error.message || '').includes('selectall_arrayref')) {
continue;
}
throw new Error(message || `RAST list jobs RPC error (${attempt.error.code})`);
}
payload = attempt;
break;
}
if (payload) {
break;
}
const lastForMethod = methodErrors[methodErrors.length - 1] ?? '';
if (lastForMethod.includes('error code -32601') || lastForMethod.includes('There is no method package')) {
continue;
}
}
if (!payload) {
// Preserve legacy behavior: if backend-side RAST listing is broken, avoid hard failure
// in the Build Model tab and return an empty list with a clear warning in the console.
if (methodErrors.some((entry) => entry.includes('selectall_arrayref'))) {
console.warn(
'RAST list jobs backend returned selectall_arrayref errors. '
+ 'Returning empty list to keep Build Model UI responsive.',
);
return [];
}
throw new Error(
`RAST list jobs method not available. Tried: ${candidateMethods.join(', ')}`
+ (methodErrors.length > 0 ? `. Errors: ${methodErrors.join(' | ')}` : ''),
);
}
const rawResult = payload.result;
const jobsArray = Array.isArray(rawResult)
? (Array.isArray(rawResult[0]) ? rawResult[0] : rawResult)
: [];
return jobsArray
.filter((item): item is RawRastJob => item != null && typeof item === 'object')
.filter((job) => String(job.type ?? '') === 'Genome')
.map((job) => {
const id = String(job.id ?? '');
const genomeId = String(job.genome_id ?? '');
return {
id,
genome_id: genomeId,
genome_name: String(job.genome_name ?? genomeId ?? id),
contig_count:
typeof job.contig_count === 'number'
? job.contig_count
: Number.isFinite(Number(job.contig_count))
? Number(job.contig_count)
: undefined,
mod_time: job.mod_time ? String(job.mod_time) : undefined,
type: 'Genome',
} satisfies RastGenomeJob;
})
.filter((job) => job.genome_id.length > 0 || job.id.length > 0);
}
/**
* List public media formulations.
*
* Retrieves the list of pre-defined public media available for FBA and gapfilling.
*
* @returns Promise resolving to array of public media summaries
*
* @example
* ```typescript
* const media = await listPublicMediaFromApi();
* const complete = media.find(m => m.id === 'Complete');
* ```
*/
export async function listPublicMediaFromApi(): Promise<ModelseedMediaSummary[]> {
return listMediaGeneric('/api/media/public');
}
/**
* List user's custom media formulations.
*
* Retrieves media created by the authenticated user. Includes fallback logic
* to search common workspace paths if primary endpoint returns empty results.
*
* @returns Promise resolving to array of user media summaries
*
* @example
* ```typescript
* const myMedia = await listMyMediaFromApi();
* console.log(`You have ${myMedia.length} custom media formulations`);
* ```
*/
export async function listMyMediaFromApi(): Promise<ModelseedMediaSummary[]> {
return listMediaGeneric('/api/media/mine');
}
/**
* Safely decode a path/ref string that might be URL-encoded.
* Handles double-encoding by decoding until no change occurs.
*/
function safeDecodePath(path: string): string {
try {
let decoded = path;
let prev = '';
// Decode until stable (handles double-encoding)
while (decoded !== prev) {
prev = decoded;
decoded = decodeURIComponent(decoded);
}
return decoded;
} catch {
return path; // If decoding fails, use original
}
}
export async function exportMediaFromApi(ref: string): Promise<Record<string, unknown>> {
// Decode ref to handle cases where it might already be URL-encoded
// This prevents double-encoding when buildQueryString uses URLSearchParams
const decodedRef = safeDecodePath(ref);
return modelseedFetch<Record<string, unknown>>(
`/api/media/export${buildQueryString({ ref: decodedRef })}`,
);
}
export async function listModelEditsFromApi(ref: string): Promise<Record<string, unknown>[]> {
try {
return await modelseedFetch<Record<string, unknown>[]>(
`/api/models/edits${buildQueryString({ ref: safeDecodePath(ref) })}`,
);
} catch (err) {
// 404 means no edits exist yet - this is expected for models without edits
if (err instanceof Error && err.message.includes('(404)')) {
return [];
}
throw err;
}
}
export async function editModelFromApi(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
// Route currently exists for forward-compatibility and may return 501 on some deployments.
return modelseedFetch<Record<string, unknown>>('/api/models/edit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
async function listMediaGeneric(path: string): Promise<ModelseedMediaSummary[]> {
// The Poplar deployment returns a dictionary of workspace paths to arrays of
// positional workspace tuples, rather than a flat list of objects. Each entry
// looks like:
//
// [
// name, // 0
// type, // 1
// path, // 2
// modDate, // 3
// id, // 4
// owner, // 5 (ignored here)
// wsIdOrSize, // 6 (ignored here)
// metadata, // 7 (optional object with flags)
// ...
// ]
//
// We flatten all arrays across all paths and map them into ModelseedMediaSummary.
type RawMediaEntry = [
name: string,
type: string,
path: string,
modDate: string,
id: string,
owner?: string,
wsIdOrSize?: number,
metadata?: Record<string, unknown>,
// allow trailing fields we do not currently use
...unknown[]
];
type RawMediaResponse = Record<string, RawMediaEntry[]>;
try {
const raw = await modelseedFetch<RawMediaResponse>(path);
return mapRawMediaResponse(raw);
} catch (err) {
// If the backend returns 404/500, it might mean the endpoint isn't implemented/enabled
// for this user or path. We log it and return an empty array to prevent a page crash.
console.warn(`modelseed-api: ${path} returned an error:`, err);
return [];
}
}
async function listMediaViaWorkspaceLs(path: string): Promise<ModelseedMediaSummary[]> {
const response = await fetch(`${WORKSPACE_URL}/ls`, {
method: 'POST',
headers: withRawTokenAuth(
{
'Content-Type': 'application/json',
Accept: 'application/json',
},
true,
),
body: JSON.stringify({ paths: [path] }),
});
const { payload, rawText } = await parseJsonResponse(response);
if (!response.ok) {
const detail = extractApiErrorMessage(payload);
throw new Error(
`workspace media ls failed (${response.status})${detail ? `: ${detail}` : rawText ? `: ${rawText}` : ''}`,
);
}
const unwrapped = (
payload &&
typeof payload === 'object' &&
'result' in (payload as Record<string, unknown>) &&
Array.isArray((payload as { result?: unknown[] }).result)
)
? (payload as { result: unknown[] }).result[0]
: payload;
if (!unwrapped || typeof unwrapped !== 'object') return [];
return mapRawMediaResponse(unwrapped as Record<string, unknown[]>);
}
function mapRawMediaResponse(raw: Record<string, unknown[]>): ModelseedMediaSummary[] {
const summaries: ModelseedMediaSummary[] = [];
for (const [folderPath, entries] of Object.entries(raw)) {
if (!Array.isArray(entries)) continue;
for (const entry of entries) {
if (!Array.isArray(entry)) continue;
const [name, type, path, modDate, id, , , metadata] = entry as [
unknown,
unknown,
unknown,
unknown,
unknown,
unknown?,
unknown?,
unknown?,
];
const meta = metadata && typeof metadata === 'object'
? (metadata as Record<string, unknown>)
: undefined;
// Construct the full path: prefer the tuple's path if it includes the name,
// otherwise construct from folder path + name
const nameStr = String(name ?? '');
let fullPath = path ? String(path) : '';
if (!fullPath || !fullPath.includes(nameStr)) {
// Path is missing or doesn't include the media name - construct it
const folder = folderPath.endsWith('/') ? folderPath.slice(0, -1) : folderPath;
fullPath = `${folder}/${nameStr}`;
}
summaries.push({
id: id ? String(id) : nameStr,
name: nameStr,
ref: fullPath,
type: type ? String(type) : undefined,
modDate: modDate ? String(modDate) : undefined,
isMinimal: (meta?.isMinimal ?? meta?.is_minimal) as boolean | string | undefined,
isDefined: (meta?.isDefined ?? meta?.is_defined) as boolean | string | undefined,
});
}
}
return summaries;
}