-
Notifications
You must be signed in to change notification settings - Fork 647
Expand file tree
/
Copy pathBlueprintLandingPage.tsx
More file actions
1694 lines (1568 loc) · 63.2 KB
/
Copy pathBlueprintLandingPage.tsx
File metadata and controls
1694 lines (1568 loc) · 63.2 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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { logRpcFailure } from './rpcErrors'
import { useState, useEffect, useCallback, useMemo, useRef, type ReactNode } from 'react'
import { useNavigate, useParams, useRouter } from '@tanstack/react-router'
import { RpcStub, RpcTarget } from 'capnweb'
import { PublicApi, AuthenticatedApi, AdminApi, BlueprintPublicInfo, BlueprintBinding, BlueprintBindingAssignment, BlueprintUserSummary, AiChatAuthorInfo, ConnectedAccountsSubscriber } from '@gadgets/workshop-shared/api'
import { AccountDescription, SupportedResource, VendorDescription, ResourceConfiguratorFrame } from '@gadgets/workshop-shared/gatekeeper'
import { Button, Dialog, DropdownMenu, Select, Tooltip, useKumoToastManager } from '@cloudflare/kumo'
import { ArrowsOutSimple, ArrowLeft, ArrowSquareOut, DotsThree, DownloadSimple, Lightning, Plus, Robot, Sparkle, Star, Trash, X } from '@phosphor-icons/react'
import { useAuth } from './useAuth'
import LoginPage from './LoginPage'
import { normalizeResourceUrl } from './resourceMatching'
import {
BLUEPRINT_ARCHIVE_EXTENSION,
makeBlueprintFilename,
saveStreamToFile,
} from './fileTransfers'
import { AccountChooser, AccountOption } from './gatekeeper-modal/AccountChooser'
import ResourceConfiguratorHost from './ResourceConfiguratorHost'
import { WorkshopButton, WorkshopIconButton } from './components/WorkshopControls'
import { MENU_CONTENT, MENU_ITEM, MENU_ITEM_DANGER } from './components/menuStyles'
import { useDocumentTitle } from './useDocumentTitle'
interface Props {
rpcStub: RpcStub<PublicApi>
}
// Using `any` for form state to avoid complex discriminated union issues with spread.
type BindingFormState = Record<string, any>
const NO_AGENT_MODEL_ID = 'gadgets:sentinel:no-agent-model'
export default function BlueprintLandingPage({ rpcStub }: Props) {
const params = useParams({ strict: false }) as { id?: string }
const id = params.id ?? ''
const navigate = useNavigate()
const router = useRouter()
const { isAuthenticated, authenticatedApi, isLoading: authLoading, login } = useAuth(rpcStub)
const toasts = useKumoToastManager()
const [blueprint, setBlueprint] = useState<BlueprintPublicInfo | null>(null)
useDocumentTitle(blueprint?.metadata.title)
const [loading, setLoading] = useState(true)
const [notFound, setNotFound] = useState(false)
const [error, setError] = useState<string | null>(null)
const [activeBindingName, setActiveBindingName] = useState<string | null>(null)
const [bindingForm, setBindingForm] = useState<BindingFormState>({})
const [draftAssignments, setDraftAssignments] = useState<Record<string, BlueprintBindingAssignment>>({})
const [models, setModels] = useState<AiChatAuthorInfo[]>([])
const [creating, setCreating] = useState(false)
const [downloading, setDownloading] = useState(false)
const [showLogin, setShowLogin] = useState(false)
// Vendor catalog + connected accounts, shared by all gatekeeper bindings during configure.
const [vendors, setVendors] = useState<{id: string, description: VendorDescription, supportedResources: SupportedResource[]}[]>([])
const [accounts, setAccounts] = useState<AccountOption[]>([])
const [connectingVendor, setConnectingVendor] = useState<string | null>(null)
const [reconnectingAccountId, setReconnectingAccountId] = useState<number | null>(null)
// Per-binding readiness flags reported by configurator iframes. A gatekeeper binding can be
// submitted only when the iframe reports `setSelectionReady(true)` and an account is chosen.
const [gatekeeperReady, setGatekeeperReady] = useState<Record<string, boolean>>({})
// Per-binding URL collector functions exposed by each gatekeeper configurator iframe. We call
// these at submit time to capture the chosen resource URL.
const collectorsRef = useRef<Map<string, () => Promise<string>>>(new Map())
const selectPortalRef = useRef<HTMLDivElement>(null)
const [canManageFeatured, setCanManageFeatured] = useState(false)
const [isFeatured, setIsFeatured] = useState(false)
const [updatingFeatured, setUpdatingFeatured] = useState(false)
// Admin capability (null for non-admins), minted once and reused for the feature toggle. Wrapped
// in an object so the stub isn't mistaken for a state updater function. Disposed on cleanup.
const [admin, setAdmin] = useState<{ api: RpcStub<AdminApi> } | null>(null)
const [isInLibrary, setIsInLibrary] = useState(false)
const [isUploadedBlueprint, setIsUploadedBlueprint] = useState(false)
const [loadingLibraryState, setLoadingLibraryState] = useState(false)
const [isPinned, setIsPinned] = useState(false)
const [updatingPinned, setUpdatingPinned] = useState(false)
const [isOwnBlueprint, setIsOwnBlueprint] = useState(false)
const [ownBlueprintSummary, setOwnBlueprintSummary] = useState<BlueprintUserSummary | null>(null)
const [loadingOwnBlueprintState, setLoadingOwnBlueprintState] = useState(false)
const [addingToLibrary, setAddingToLibrary] = useState(false)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
const [removingFromLibrary, setRemovingFromLibrary] = useState(false)
const vendorById = useMemo(
() => new Map(vendors.map(v => [v.id.toLowerCase(), v])),
[vendors],
)
// Fetch blueprint metadata.
useEffect(() => {
if (!id) {
setLoading(false)
setNotFound(true)
return
}
setLoading(true)
setNotFound(false)
setError(null)
rpcStub.getBlueprint(id).then(result => {
if (result) {
setBlueprint(result)
} else {
setNotFound(true)
}
}).catch(err => {
setError(err.message || 'Failed to load blueprint.')
}).finally(() => {
setLoading(false)
})
}, [id, rpcStub])
useEffect(() => {
setActiveBindingName(null)
setBindingForm({})
setDraftAssignments({})
setGatekeeperReady({})
collectorsRef.current.clear()
}, [id])
// When authenticated, fetch models for binding assignment.
useEffect(() => {
if (isAuthenticated && authenticatedApi) {
authenticatedApi.listModels()
.then(setModels)
.catch(err => logRpcFailure('Failed to load models:', err))
} else {
setModels([])
}
}, [isAuthenticated, authenticatedApi])
// Load vendors (gatekeeper catalog) for both the summary cards and configure panel.
useEffect(() => {
if (!(isAuthenticated && authenticatedApi)) {
setVendors([])
return
}
let cancelled = false
authenticatedApi.listGatekeeperVendors().then(list => {
if (cancelled) return
setVendors(list)
}).catch(err => {
if (cancelled) return
console.error('Failed to load gatekeeper vendors:', err)
})
return () => { cancelled = true }
}, [isAuthenticated, authenticatedApi])
// Subscribe to connected accounts while authenticated. The same subscription serves all
// gatekeeper bindings; each binding filters down to the vendor + resource it requires.
useEffect(() => {
if (!(isAuthenticated && authenticatedApi)) {
setAccounts([])
return
}
let cancelled = false
const accountMap = new Map<number, AccountOption>()
let subStub: { [Symbol.dispose](): void } | null = null
class AccountsSubscriber extends RpcTarget implements ConnectedAccountsSubscriber {
add(
accountId: number,
description: AccountDescription,
vendor: VendorDescription,
supportedResources: SupportedResource[] = [],
credentialsValid: boolean = true,
vendorId: string = '',
) {
if (cancelled) return
accountMap.set(accountId, {
id: accountId, description, vendorId, vendorDescription: vendor,
supportedResources, credentialsValid,
})
setAccounts(Array.from(accountMap.values()))
if (credentialsValid) {
setReconnectingAccountId(prev => prev === accountId ? null : prev)
}
}
remove(accountId: number) {
if (cancelled) return
accountMap.delete(accountId)
setAccounts(Array.from(accountMap.values()))
}
ready() {}
}
authenticatedApi.subscribeConnectedAccounts(new AccountsSubscriber())
.then(stub => {
if (cancelled) {
stub[Symbol.dispose]()
} else {
subStub = stub
}
})
.catch(err => {
logRpcFailure('Failed to subscribe to connected accounts:', err)
})
return () => {
cancelled = true
subStub?.[Symbol.dispose]()
}
}, [isAuthenticated, authenticatedApi])
const handleConnectAccount = useCallback(async (vendorId: string) => {
if (!authenticatedApi) return
setConnectingVendor(vendorId)
try {
const result = await authenticatedApi.connectAccount(vendorId)
window.open(result.url, '_blank', 'noopener,noreferrer')
toasts.add({ title: 'Complete the account connection in the new tab.', variant: 'success' })
} catch (err) {
console.error('Failed to initiate connection:', err)
toasts.add({ title: 'Failed to start connection flow', variant: 'error' })
} finally {
setConnectingVendor(null)
}
}, [authenticatedApi, toasts])
const handleReconnectAccount = useCallback(async (accountId: number) => {
if (!authenticatedApi) return
setReconnectingAccountId(accountId)
try {
const result = await authenticatedApi.reconnectAccount(accountId)
window.open(result.url, '_blank', 'noopener,noreferrer')
toasts.add({ title: 'Complete the account reconnect in the new tab.', variant: 'success' })
} catch (err) {
console.error('Failed to initiate reconnect:', err)
toasts.add({ title: 'Failed to start reconnect flow', variant: 'error' })
setReconnectingAccountId(null)
}
}, [authenticatedApi, toasts])
const handleGatekeeperReadyChange = useCallback((bindingName: string, ready: boolean) => {
setGatekeeperReady(prev => {
if (prev[bindingName] === ready) return prev
return { ...prev, [bindingName]: ready }
})
}, [])
const handleCollectorChange = useCallback((bindingName: string, collect: (() => Promise<string>) | null) => {
if (collect) {
collectorsRef.current.set(bindingName, collect)
} else {
collectorsRef.current.delete(bindingName)
}
}, [])
useEffect(() => {
let cancelled = false
let stub: RpcStub<AdminApi> | null = null
if (!id || !authenticatedApi) {
setAdmin(null)
setCanManageFeatured(false)
setIsFeatured(false)
return () => {
cancelled = true
}
}
;(async () => {
try {
// Mint the admin capability once (the access check happens server-side); null = not admin.
const api = await authenticatedApi.getAdminApi()
if (cancelled) {
api?.[Symbol.dispose]?.()
return
}
if (!api) {
setCanManageFeatured(false)
setIsFeatured(false)
return
}
stub = api
setAdmin({ api })
const result = await api.isBlueprintFeatured(id)
if (cancelled) return
// null means the blueprint can't be featured; a boolean means it can.
if (result === null) {
setCanManageFeatured(false)
setIsFeatured(false)
} else {
setCanManageFeatured(true)
setIsFeatured(result)
}
} catch (err) {
if (cancelled) return
console.error('Failed to load admin featured state:', err)
setCanManageFeatured(false)
setIsFeatured(false)
}
})()
return () => {
cancelled = true
stub?.[Symbol.dispose]?.()
setAdmin(null)
}
}, [id, authenticatedApi])
useEffect(() => {
let cancelled = false
if (!id || !authenticatedApi) {
setIsInLibrary(false)
setLoadingLibraryState(false)
return () => {
cancelled = true
}
}
setLoadingLibraryState(true)
authenticatedApi.isBlueprintInLibrary(id).then(result => {
if (cancelled) return
setIsInLibrary(result !== null)
setIsUploadedBlueprint(result?.uploaded ?? false)
}).catch(err => {
if (cancelled) return
console.error('Failed to load library state:', err)
setIsInLibrary(false)
setIsUploadedBlueprint(false)
}).finally(() => {
if (!cancelled) {
setLoadingLibraryState(false)
}
})
return () => {
cancelled = true
}
}, [id, authenticatedApi])
useEffect(() => {
let cancelled = false
if (!id || !authenticatedApi) {
setIsPinned(false)
setIsOwnBlueprint(false)
setOwnBlueprintSummary(null)
setLoadingOwnBlueprintState(false)
return () => {
cancelled = true
}
}
setLoadingOwnBlueprintState(true)
Promise.all([
authenticatedApi.isBlueprintPinned(id),
authenticatedApi.getOwnBlueprint(id),
]).then(([pinned, ownBlueprint]) => {
if (cancelled) return
setIsPinned(pinned)
setOwnBlueprintSummary(ownBlueprint)
setIsOwnBlueprint(ownBlueprint !== null)
}).catch(err => {
if (cancelled) return
console.error('Failed to load blueprint user state:', err)
setIsPinned(false)
setOwnBlueprintSummary(null)
setIsOwnBlueprint(false)
}).finally(() => {
if (!cancelled) {
setLoadingOwnBlueprintState(false)
}
})
return () => {
cancelled = true
}
}, [id, authenticatedApi])
const findMatchingAccounts = useCallback((binding: Extract<BlueprintBinding, { type: 'gatekeeper' }>) => {
return accounts.filter(account =>
account.vendorId.toLowerCase() === binding.gatekeeperName.toLowerCase() &&
account.credentialsValid &&
account.supportedResources.some(resource => resource.urlPattern === binding.typeUrlPattern)
)
}, [accounts])
const findSuggestedModelId = useCallback((suggested: {provider: string, modelName: string}) => {
const provider = suggested.provider.trim().toLowerCase()
const modelName = suggested.modelName.trim().toLowerCase()
const exactMatches = models.filter(model =>
model.id.toLowerCase() === modelName ||
model.name.toLowerCase() === modelName ||
model.id.toLowerCase() === `${provider}/${modelName}` ||
model.id.toLowerCase() === `${provider}:${modelName}`
)
if (exactMatches.length === 1) return exactMatches[0].id
const providerScopedMatches = models.filter(model => {
const text = `${model.id} ${model.name}`.toLowerCase()
return text.includes(provider) && text.includes(modelName)
})
return providerScopedMatches.length === 1 ? providerScopedMatches[0].id : null
}, [models])
const getFirstUnresolvedBindingName = useCallback((assignments = draftAssignments) => {
if (!blueprint) return null
for (let name of Object.keys(blueprint.metadata.bindings)) {
if (!assignments[name]) return name
}
return null
}, [blueprint, draftAssignments])
const openBindingConfigurator = useCallback((name: string) => {
if (!blueprint) return
const binding = blueprint.metadata.bindings[name]
if (!binding) return
setGatekeeperReady(prev => ({ ...prev, [name]: false }))
collectorsRef.current.delete(name)
const existing = draftAssignments[name]
let initial: any = existing ? { ...existing } : { type: binding.type }
if (binding.type === 'gatekeeper') {
initial = {
type: 'gatekeeper',
accountId: existing?.type === 'gatekeeper' ? existing.accountId : undefined,
resourceUrl: existing?.type === 'gatekeeper' ? existing.resourceUrl : binding.resourceUrl || '',
}
} else if (binding.type === 'aiModel') {
initial = {
type: 'aiModel',
modelId: existing?.type === 'aiModel' ? existing.modelId : undefined,
}
} else if (binding.type === 'agentSpawner') {
initial = {
type: 'agentSpawner',
modelId: existing?.type === 'agentSpawner' ? existing.modelId : undefined,
}
}
setBindingForm(prev => ({ ...prev, [name]: initial }))
setActiveBindingName(name)
}, [blueprint, draftAssignments])
useEffect(() => {
if (!blueprint || !isAuthenticated) return
// Re-run when account/model data changes: findMatchingAccounts depends on accounts,
// and findSuggestedModelId depends on models.
setDraftAssignments(prev => {
let next = { ...prev }
let changed = false
for (let [name, binding] of Object.entries(blueprint.metadata.bindings)) {
if (next[name]) continue
if (binding.type === 'gatekeeper') {
if (!binding.resourceUrl) continue
const matches = findMatchingAccounts(binding)
if (matches.length === 1) {
next[name] = {
type: 'gatekeeper',
accountId: matches[0].id,
resourceUrl: normalizeResourceUrl(binding.resourceUrl),
}
changed = true
}
} else if (binding.type === 'aiModel') {
if (!binding.suggestedModel) continue
const modelId = findSuggestedModelId(binding.suggestedModel)
if (modelId) {
next[name] = { type: 'aiModel', modelId }
changed = true
}
} else if (binding.type === 'agentSpawner') {
if (binding.suggestedModel === null) {
next[name] = { type: 'agentSpawner', modelId: null }
changed = true
} else if (binding.suggestedModel) {
const modelId = findSuggestedModelId(binding.suggestedModel)
if (modelId) {
next[name] = { type: 'agentSpawner', modelId }
changed = true
}
}
}
}
return changed ? next : prev
})
}, [blueprint, isAuthenticated, findMatchingAccounts, findSuggestedModelId])
const handleStartConfigure = () => {
if (!isAuthenticated) {
setShowLogin(true)
return
}
let firstUnresolved = getFirstUnresolvedBindingName()
if (firstUnresolved) {
openBindingConfigurator(firstUnresolved)
return
}
handleCreate()
}
const handleLoginSuccess = () => {
const token = localStorage.getItem('authToken')
if (token) {
login(token)
setShowLogin(false)
}
}
const updateBinding = useCallback((name: string, updates: Partial<BlueprintBindingAssignment>) => {
setBindingForm(prev => ({
...prev,
[name]: { ...prev[name], ...updates },
}))
}, [])
const canSaveActiveBinding = useCallback(() => {
if (!activeBindingName || !blueprint) return false
const binding = blueprint.metadata.bindings[activeBindingName]
const assignment = bindingForm[activeBindingName]
if (!binding || !assignment) return false
if (binding.type === 'gatekeeper') {
let a = assignment as any
return a.accountId !== undefined && gatekeeperReady[activeBindingName] === true
} else if (binding.type === 'aiModel') {
return Boolean((assignment as any).modelId)
} else if (binding.type === 'agentSpawner') {
return (assignment as any).modelId !== undefined
}
return false
}, [activeBindingName, blueprint, bindingForm, gatekeeperReady])
const handleSaveActiveBinding = async () => {
if (!activeBindingName || !blueprint) return
const binding = blueprint.metadata.bindings[activeBindingName]
const form = bindingForm[activeBindingName]
if (!binding || !form) return
try {
let assignment: BlueprintBindingAssignment
if (binding.type === 'gatekeeper') {
const collect = collectorsRef.current.get(activeBindingName)
if (!collect) {
throw new Error(`Binding "${activeBindingName}" is not configured.`)
}
const resourceUrl = await collect()
assignment = {
type: 'gatekeeper',
accountId: (form as any).accountId,
resourceUrl: normalizeResourceUrl(resourceUrl),
}
} else if (binding.type === 'aiModel') {
assignment = {
type: 'aiModel',
modelId: (form as any).modelId,
}
} else {
assignment = {
type: 'agentSpawner',
modelId: (form as any).modelId ?? null,
}
}
setDraftAssignments(prev => ({ ...prev, [activeBindingName]: assignment }))
setActiveBindingName(null)
collectorsRef.current.delete(activeBindingName)
} catch (err: any) {
setError(err.message || 'Failed to save connection.')
}
}
const handleCreate = async () => {
if (!authenticatedApi || !blueprint || !id) return
let firstUnresolved = getFirstUnresolvedBindingName()
if (firstUnresolved) {
openBindingConfigurator(firstUnresolved)
return
}
setCreating(true)
setError(null)
const overseer = authenticatedApi.newGadgetFromBlueprint(id, draftAssignments)
try {
let metadata = await overseer.getMetadata()
window.location.href = `/workspace/${metadata.id}`
} catch (err: any) {
setError(err.message || 'Failed to create gadget from blueprint.')
} finally {
overseer.then(stub => stub[Symbol.dispose]()).catch(() => {})
setCreating(false)
}
}
const handleDownload = async () => {
if (!id || !blueprint) return
setDownloading(true)
setError(null)
try {
await saveStreamToFile(
() => rpcStub.downloadBlueprint(id),
makeBlueprintFilename(blueprint.metadata.title, blueprint.metadata.version),
{
description: 'Gadget Blueprint',
contentType: 'application/octet-stream',
extension: BLUEPRINT_ARCHIVE_EXTENSION,
},
)
} catch (err: any) {
setError(err.message || 'Failed to download blueprint.')
} finally {
setDownloading(false)
}
}
const handleToggleFeatured = async () => {
if (!admin || !id || !canManageFeatured) return
const nextFeatured = !isFeatured
setUpdatingFeatured(true)
try {
await admin.api.setBlueprintFeatured(id, nextFeatured)
setIsFeatured(nextFeatured)
} catch (err: any) {
console.error('Failed to update featured status:', err)
toasts.add({
title: nextFeatured ? 'Failed to feature blueprint' : 'Failed to unfeature blueprint',
variant: 'error',
})
} finally {
setUpdatingFeatured(false)
}
}
const handleTogglePinned = async () => {
if (!id) return
if (!isAuthenticated || !authenticatedApi) {
setShowLogin(true)
return
}
const nextPinned = !isPinned
setUpdatingPinned(true)
try {
await authenticatedApi.setBlueprintPinned(id, nextPinned)
setIsPinned(nextPinned)
if (nextPinned && !isOwnBlueprint) {
setIsInLibrary(true)
setIsUploadedBlueprint(false)
}
toasts.add({ title: nextPinned ? 'Blueprint favorited' : 'Blueprint unfavorited', variant: 'success' })
} catch (err) {
console.error('Failed to update blueprint pin:', err)
toasts.add({ title: 'Failed to update favorite status', variant: 'error' })
} finally {
setUpdatingPinned(false)
}
}
const handleAddToLibrary = async () => {
if (!id) return
if (!isAuthenticated || !authenticatedApi) {
setShowLogin(true)
return
}
if (isInLibrary) {
return
}
setAddingToLibrary(true)
try {
await authenticatedApi.addBlueprintToLibrary(id)
setIsInLibrary(true)
toasts.add({ title: 'Blueprint added to library', variant: 'success' })
} catch (err) {
console.error('Failed to add blueprint to library:', err)
toasts.add({ title: 'Failed to add blueprint to library', variant: 'error' })
} finally {
setAddingToLibrary(false)
}
}
const handleRemoveFromLibrary = async () => {
if (!id || !authenticatedApi) return
setRemovingFromLibrary(true)
try {
await authenticatedApi.removeBlueprintFromLibrary(id)
if (isUploadedBlueprint) {
setShowDeleteConfirm(false)
toasts.add({ title: 'Blueprint deleted', variant: 'success' })
navigate({ to: '/' })
} else {
setIsInLibrary(false)
setIsPinned(false)
toasts.add({ title: 'Blueprint removed from library', variant: 'success' })
}
} catch (err) {
console.error('Failed to remove blueprint from library:', err)
toasts.add({
title: isUploadedBlueprint ? 'Failed to delete blueprint' : 'Failed to remove blueprint from library',
variant: 'error',
})
} finally {
setRemovingFromLibrary(false)
}
}
const handleDeleteOwnedBlueprint = async () => {
if (!id || !authenticatedApi) return
setRemovingFromLibrary(true)
let overseer: ReturnType<typeof authenticatedApi.openGadget> | null = null
try {
// The source workspace owns its blueprints, so it must do the deleting. Once it is gone (or
// the blueprint was never published from one), the user record is all there is to clean up.
if (ownBlueprintSummary?.source.type === 'workspace') {
overseer = authenticatedApi.openGadget(ownBlueprintSummary.source.workspaceId)
await overseer.deleteBlueprint(id)
} else {
await authenticatedApi.deleteOrphanedBlueprint(id)
}
setShowDeleteConfirm(false)
toasts.add({ title: 'Blueprint deleted', variant: 'success' })
navigate({ to: '/' })
} catch (err) {
console.error('Failed to delete blueprint:', err)
toasts.add({ title: 'Failed to delete blueprint', variant: 'error' })
} finally {
overseer?.then(stub => stub[Symbol.dispose]()).catch(() => {})
setRemovingFromLibrary(false)
}
}
if (showLogin && !isAuthenticated) {
return <LoginPage rpcStub={rpcStub} onLoginSuccess={handleLoginSuccess} />
}
if (loading || authLoading) {
return <BlueprintStatePage title="Loading blueprint..." loading />
}
if (notFound) {
return (
<BlueprintStatePage
title="Blueprint not found"
message="This blueprint may have been removed or the link may be incorrect."
actionLabel="Back to Explore"
onAction={() => navigate({ to: '/explore' })}
/>
)
}
if (!blueprint) {
return (
<BlueprintStatePage
title="Couldn’t load blueprint"
message={error || 'Failed to load blueprint.'}
actionLabel="Back to Explore"
onAction={() => navigate({ to: '/explore' })}
/>
)
}
let meta = blueprint.metadata
let bindingEntries = Object.entries(meta.bindings)
let activeBinding = activeBindingName ? meta.bindings[activeBindingName] : undefined
let readyCount = bindingEntries.filter(([name]) => draftAssignments[name]).length
let unresolvedBindingName = getFirstUnresolvedBindingName()
let remainingCount = bindingEntries.length - readyCount
let primaryActionLabel: string
if (!isAuthenticated) {
primaryActionLabel = 'Log in to create a gadget'
} else if (unresolvedBindingName !== null) {
primaryActionLabel = remainingCount > 0
? `Configure ${remainingCount} remaining ${remainingCount === 1 ? 'connection' : 'connections'}`
: 'Configure connections'
} else {
primaryActionLabel = 'Create Gadget'
}
let createDisabled = creating
let canDeleteOwnedBlueprint = isOwnBlueprint && !loadingOwnBlueprintState
// Only set when the workspace this blueprint was published from is still around to open.
let sourceWorkspace =
ownBlueprintSummary?.source.type === 'workspace' ? ownBlueprintSummary.source : null
return (
<div className="min-h-full bg-kumo-base">
<div className="mx-auto w-full max-w-5xl px-6 pb-16 pt-10 sm:px-10">
<button
type="button"
onClick={() => {
if (router.history.canGoBack()) {
router.history.back()
} else {
navigate({ to: '/explore' })
}
}}
className="mb-8 inline-flex cursor-pointer items-center gap-2 px-1 py-1 text-[13px] leading-[18px] font-medium tracking-[-0.25px] text-kumo-subtle transition-[color,transform] duration-150 ease-out hover:text-kumo-default active:scale-[0.98]"
>
<ArrowLeft size={14} weight="bold" />
Back
</button>
<header className="mb-10 grid gap-7 lg:grid-cols-[minmax(0,1fr)_360px] lg:items-start">
<div className="min-w-0">
{isFeatured && (
<span className="mb-3 inline-flex items-center gap-1.5 rounded-full bg-[rgba(255,72,1,0.10)] px-2 py-1 text-[11px] leading-4 font-semibold tracking-[-0.1px] text-kumo-brand">
<Star size={12} weight="fill" />
Featured
</span>
)}
<h1 className="m-0 text-3xl font-semibold leading-tight tracking-tight text-kumo-default">
{meta.title}
</h1>
{meta.description && (
<p className="mt-3 max-w-[640px] text-[15px] leading-[22px] font-normal tracking-[-0.25px] text-kumo-subtle">
{meta.description}
</p>
)}
<div className="mt-5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] leading-[18px] font-normal tracking-[-0.25px] text-kumo-subtle">
<span>By {meta.author.name}</span>
<span className="text-kumo-inactive">•</span>
<span>v{meta.version}</span>
<span className="text-kumo-inactive">•</span>
<span>Updated {new Date(meta.lastUpdated).toLocaleDateString()}</span>
</div>
</div>
<aside className="space-y-3 lg:w-[360px] lg:justify-self-end lg:pt-1">
{blueprint.screenshotUrl && (
<BlueprintScreenshotHero
title={meta.title}
screenshotUrl={blueprint.screenshotUrl}
/>
)}
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1">
<button
type="button"
onClick={handleStartConfigure}
disabled={createDisabled}
className="press inline-flex h-10 w-full cursor-pointer items-center justify-center rounded-lg bg-kumo-brand px-4 text-[14px] leading-5 font-semibold tracking-[-0.25px] text-white transition-colors duration-150 ease-out hover:bg-kumo-brand-hover disabled:cursor-not-allowed disabled:opacity-60"
>
{creating ? 'Creating...' : primaryActionLabel}
</button>
</span>
{!isOwnBlueprint && !loadingOwnBlueprintState && !isInLibrary && (
<Tooltip content={isAuthenticated ? 'Add to library' : 'Log in to add to library'} asChild>
<button
type="button"
aria-label={isAuthenticated ? 'Add blueprint to library' : 'Log in to add blueprint to library'}
onClick={handleAddToLibrary}
disabled={addingToLibrary || loadingLibraryState}
className="press inline-flex h-10 w-10 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-kumo-line bg-kumo-base p-0 text-kumo-subtle transition-colors duration-150 ease-out hover:border-kumo-fill hover:bg-kumo-tint hover:text-kumo-default disabled:cursor-not-allowed disabled:opacity-60"
>
<Plus size={17} weight="bold" />
</button>
</Tooltip>
)}
<DropdownMenu>
<DropdownMenu.Trigger
render={(
<WorkshopIconButton
aria-label="More blueprint actions"
className="!h-10 !w-10 shrink-0 rounded-lg border border-kumo-line bg-kumo-base text-kumo-subtle hover:border-kumo-fill hover:bg-kumo-tint hover:text-kumo-default data-[popup-open]:border-kumo-fill data-[popup-open]:bg-kumo-tint data-[popup-open]:text-kumo-default"
>
<DotsThree size={18} weight="bold" />
</WorkshopIconButton>
)}
/>
<DropdownMenu.Content className={MENU_CONTENT}>
<DropdownMenu.Item
icon={<DownloadSimple size={13} className="mr-2" />}
onClick={handleDownload}
disabled={downloading}
className={MENU_ITEM}
>
{downloading ? 'Downloading...' : 'Download archive'}
</DropdownMenu.Item>
<DropdownMenu.Item
icon={<Star size={13} className="mr-2" weight={isPinned ? 'fill' : 'regular'} />}
onClick={handleTogglePinned}
disabled={updatingPinned}
className={MENU_ITEM}
>
{updatingPinned ? 'Updating...' : (isPinned ? 'Unfavorite' : 'Favorite')}
</DropdownMenu.Item>
{sourceWorkspace && (
<DropdownMenu.Item
icon={<ArrowSquareOut size={13} className="mr-2" />}
onClick={() => window.open(`/workspace/${sourceWorkspace.workspaceId}`, '_blank', 'noopener,noreferrer')}
className={MENU_ITEM}
>
Go to workspace
</DropdownMenu.Item>
)}
{canDeleteOwnedBlueprint && (
<>
<DropdownMenu.Separator />
<DropdownMenu.Item
icon={<Trash size={13} className="mr-2" />}
variant="danger"
onClick={() => setShowDeleteConfirm(true)}
className={MENU_ITEM_DANGER}
>
Delete blueprint
</DropdownMenu.Item>
</>
)}
{!isOwnBlueprint && !loadingOwnBlueprintState && isInLibrary && (
<>
<DropdownMenu.Separator />
{isUploadedBlueprint ? (
<DropdownMenu.Item
icon={<Trash size={13} className="mr-2" />}
variant="danger"
onClick={() => setShowDeleteConfirm(true)}
className={MENU_ITEM_DANGER}
>
Delete blueprint
</DropdownMenu.Item>
) : (
<DropdownMenu.Item
icon={<Trash size={13} className="mr-2" />}
variant="danger"
onClick={handleRemoveFromLibrary}
disabled={removingFromLibrary}
className={MENU_ITEM_DANGER}
>
{removingFromLibrary ? 'Removing...' : 'Remove from library'}
</DropdownMenu.Item>
)}
</>
)}
{canManageFeatured && (
<>
<DropdownMenu.Separator />
<DropdownMenu.Item
icon={<Sparkle size={13} className="mr-2" weight={isFeatured ? 'fill' : 'regular'} />}
onClick={handleToggleFeatured}
disabled={updatingFeatured}
className={MENU_ITEM}
>
{updatingFeatured ? 'Updating...' : (isFeatured ? 'Unfeature blueprint' : 'Feature blueprint')}
</DropdownMenu.Item>
</>
)}
</DropdownMenu.Content>
</DropdownMenu>
</div>
</aside>
</header>
<main className="space-y-6">
{bindingEntries.length > 0 ? (
<section>
<div className="mb-2 flex items-center gap-2 px-1">
<h2 className="text-[12px] font-medium uppercase tracking-[0.08em] text-kumo-inactive">
Required connections
</h2>
<span className="text-[12px] font-medium tracking-[-0.1px] text-kumo-inactive">
{bindingEntries.length}
</span>
</div>
<div className="mb-3 px-1 text-[13px] leading-[18px] font-normal tracking-[-0.25px] text-kumo-subtle">
{readyCount === bindingEntries.length
? 'Everything is ready. You can change any connection before creating the Gadget.'
: `${readyCount} of ${bindingEntries.length} ready. Suggestions are used automatically when they match one of your connected accounts.`}
</div>
<div className="overflow-hidden rounded-2xl border border-kumo-line bg-kumo-base">
{bindingEntries.map(([name, binding]) => (
<BlueprintBindingSummaryCard
key={name}
name={name}
binding={binding}
assignment={draftAssignments[name]}
vendor={binding.type === 'gatekeeper' ? vendorById.get(binding.gatekeeperName.toLowerCase()) : undefined}
models={models}
onConfigure={() => isAuthenticated ? openBindingConfigurator(name) : setShowLogin(true)}
/>
))}
</div>
</section>
) : (
<section className="rounded-2xl border border-kumo-line bg-kumo-base px-5 py-5">
<p className="m-0 text-[15px] leading-5 font-medium tracking-[-0.25px] text-kumo-default">
No connections required
</p>
<p className="mt-1 text-[13px] leading-[18px] font-normal tracking-[-0.25px] text-kumo-subtle">