-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathAgentPanelRoot.vue
More file actions
1207 lines (1103 loc) · 35.5 KB
/
Copy pathAgentPanelRoot.vue
File metadata and controls
1207 lines (1103 loc) · 35.5 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
<script setup lang="ts">
import './agentPanel.css'
import { useClipboard } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import {
computed,
nextTick,
onBeforeUnmount,
provide,
readonly,
ref,
watch
} from 'vue'
import { useI18n } from 'vue-i18n'
import { useCurrentUser } from '@/composables/auth/useCurrentUser'
import { fitGraphToView } from '@/composables/canvas/fitGraphToView'
import { useFocusNode } from '@/composables/canvas/useFocusNode'
import { useTelemetry } from '@/platform/telemetry'
import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow'
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { validateComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema'
import type { LGraphCanvas, LGraphNode } from '@/lib/litegraph/src/litegraph'
import { useAppMode } from '@/composables/useAppMode'
import { MIME_ASSET_INFO } from '@/platform/assets/schemas/mediaAssetSchema'
import { assetService } from '@/platform/assets/services/assetService'
import {
fetchDroppedAsset,
getDroppedAsset,
hasImageType,
hasVideoType
} from '@/utils/eventUtils'
import { appendWorkflowJsonExt } from '@/utils/formatUtil'
import { getNodeByLocatorId } from '@/utils/graphTraversalUtil'
// eslint-disable-next-line import-x/no-restricted-paths
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
import { api } from '@/scripts/api'
import { app } from '@/scripts/app'
import { useAgentNodeSelectionStore } from '@/stores/agentNodeSelectionStore'
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore'
import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore'
import { isLGraphNode } from '@/utils/litegraphUtil'
import { useToastStore } from '@/platform/updates/common/toastStore'
import AgentPanel from './components/agent/AgentPanel.vue'
import OnboardingCoach from './components/agent/OnboardingCoach.vue'
import {
MAX_ATTACHMENT_BYTES,
useAttachment
} from './composables/agent/useAttachment'
import type { ActiveTab } from './types/activeTab'
import type { SelectedNode } from './composables/agent/useCanvasSelection'
import {
selectedNodeKey,
useCanvasSelection
} from './composables/agent/useCanvasSelection'
import type { CoachStep } from './composables/agent/useOnboarding'
import type { ComposerAttachment } from './composables/agent/useComposer'
import type {
AgentActiveTabData,
AgentDraftSnapshot,
AgentThreadSummary
} from './schemas/agentApiSchema'
import type { ChatSession } from './stores/agent/agentChatHistoryStore'
import type { ConversationEntry } from './stores/agent/agentConversationStore'
import type { WorkflowTurnContext } from './composables/agent/useAgentSession'
import { useAgentSession } from './composables/agent/useAgentSession'
import { useAgentDraftStore } from './stores/agent/agentDraftStore'
import { useAgentWorkflowTabBindingStore } from './stores/agent/agentWorkflowTabBindingStore'
import {
AgentApiError,
createAgentRestClient
} from './services/agent/agentRestClient'
import type {
DraftUpload,
OpenTabsSnapshot
} from './services/agent/agentRestClient'
import { createAgentEventSource } from './services/agent/agentEventSource'
import { useAgentChatHistoryStore } from './stores/agent/agentChatHistoryStore'
import { useAgentPanelStore } from './stores/agent/agentPanelStore'
const { t } = useI18n()
const toast = useToastStore()
const sidebarTabStore = useSidebarTabStore()
const { isBuilderMode } = useAppMode()
const { userDisplayName } = useCurrentUser()
const userName = computed(
() => userDisplayName.value?.trim().split(/\s+/)[0] || undefined
)
const rest = createAgentRestClient()
const events = createAgentEventSource(api)
const workflowStore = useWorkflowStore()
const workflowService = useWorkflowService()
const bindingStore = useAgentWorkflowTabBindingStore()
const draftStore = useAgentDraftStore()
const agentPanelStore = useAgentPanelStore()
const { dismissedSelectionSignature } = storeToRefs(agentPanelStore)
const agentNodeSelectionStore = useAgentNodeSelectionStore()
const tabActivity = useWorkflowTabActivityStore()
const CREATING_TAB_MIN_DURATION_MS = 500
const canvasStore = useCanvasStore()
const { focusNodeInstance } = useFocusNode()
function toSelectedNode(node: LGraphNode): SelectedNode {
return {
id: String(node.id),
locatorId: workflowStore.nodeToNodeLocatorId(node),
title: node.title || node.type
}
}
const selectedNodes = computed<SelectedNode[]>(() =>
canvasStore.selectedItems.filter(isLGraphNode).map(toSelectedNode)
)
const {
staged: selectionTags,
consume: consumeSelection,
remove: removeSelectionTag,
add: addSelectionTag,
replace: replaceSelectionTags
} = useCanvasSelection({
selection: selectedNodes,
isLive: () => agentPanelStore.isOpen,
isTracking: () => agentNodeSelectionStore.isActive,
isPaused: () => agentNodeSelectionStore.isLoadingWorkflow,
scope: () => workflowStore.activeWorkflow?.path ?? null,
dismissedSignature: dismissedSelectionSignature
})
function viewedGraphNodes() {
return app.canvas?.graph?.nodes ?? app.graph?.nodes ?? []
}
function mentionableNodes(): SelectedNode[] {
return viewedGraphNodes().map(toSelectedNode)
}
watch(
selectionTags,
(tags) => {
if (!agentPanelStore.isOpen || agentNodeSelectionStore.isLoadingWorkflow)
return
agentNodeSelectionStore.saveNodeIds(
workflowStore.activeWorkflow?.path,
tags.map(selectedNodeKey)
)
},
{ deep: true }
)
watch(
() => agentPanelStore.isOpen,
(open) => {
if (!open) return
const locatorIds = new Set(
agentNodeSelectionStore.nodeIds(workflowStore.activeWorkflow?.path)
)
replaceSelectionTags(
[...locatorIds]
.map((locatorId) => getNodeByLocatorId(app.rootGraph, locatorId))
.filter((node): node is LGraphNode => node !== null)
.map(toSelectedNode)
)
},
{ immediate: true }
)
function mentionableAssets() {
return assetService.getInputAssetsIncludingPublic()
}
let cloudIdsByName = new Map<string, string>()
async function refreshCloudWorkflowIds(): Promise<void> {
try {
const workflows = await rest.listCloudWorkflows()
const nameCounts = new Map<string, number>()
for (const { name } of workflows) {
if (name !== undefined)
nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1)
}
cloudIdsByName = new Map(
workflows.flatMap(({ id, name }) =>
name !== undefined && nameCounts.get(name) === 1
? [[name, id] as const]
: []
)
)
} catch (error) {
console.warn('[agent] could not refresh cloud workflow ids', error)
}
}
function openSavedTabsNamed(filename: string): ComfyWorkflow[] {
return workflowStore.openWorkflows.filter(
(tab) => !tab.isTemporary && tab.filename === filename
)
}
function cloudIdFor(tab: ComfyWorkflow): string | undefined {
const saved =
!tab.isTemporary && openSavedTabsNamed(tab.filename).length === 1
? cloudIdsByName.get(tab.filename)
: undefined
return saved ?? bindingStore.workflowIdFor(tab.path)
}
let lastKnownGraph: { serialized: string; workflowId: string } | null = null
function reclaimMovedBinding(activePath: string): string | undefined {
if (lastKnownGraph === null) return undefined
const graph = app.graph?.serialize()
if (
!graph?.nodes?.length ||
JSON.stringify(graph) !== lastKnownGraph.serialized
)
return undefined
const { workflowId } = lastKnownGraph
bindingStore.bind(workflowId, activePath)
lastKnownGraph = null
return workflowId
}
const workflowDetached = ref(false)
function activeWorkflowTurnContext(): WorkflowTurnContext | undefined {
if (workflowDetached.value) return undefined
const active = workflowStore.activeWorkflow
if (!active) return undefined
const bound = cloudIdFor(active) ?? reclaimMovedBinding(active.path)
return bound === undefined ? undefined : { id: bound, tabPath: active.path }
}
const activeTab = computed<ActiveTab | null>(() => {
const active = workflowStore.activeWorkflow
return active
? {
path: active.path,
name: active.filename,
isPersisted: active.isPersisted,
modified: active.isModified
}
: null
})
const workflowTabs = computed<ActiveTab[]>(() =>
workflowStore.openWorkflows.map((tab) => ({
path: tab.path,
name: tab.filename,
isPersisted: tab.isPersisted,
modified: tab.isModified
}))
)
async function onSelectTab(path: string): Promise<void> {
workflowDetached.value = false
const tab = workflowStore.getWorkflowByPath(path)
if (tab) await workflowService.openWorkflow(tab)
}
function onClearWorkflow(): void {
workflowDetached.value = true
}
let lastSentGraph: string | null = null
let snapshotTabPath: string | null = null
function takeWorkflowSnapshot(): DraftUpload | undefined {
if (workflowDetached.value) return undefined
const graph = app.graph?.serialize()
if (!graph) return undefined
const serialized = JSON.stringify(graph)
const active = workflowStore.activeWorkflow
const activePath = active?.path ?? null
const hasBoundWorkflow = active != null && cloudIdFor(active) !== undefined
if (
!graph.nodes?.length &&
!hasBoundWorkflow &&
(lastSentGraph === null || activePath !== snapshotTabPath)
)
return undefined
lastSentGraph = serialized
snapshotTabPath = activePath
return { content: graph, version: draftStore.version }
}
function resetSnapshotGuard(): void {
lastSentGraph = null
snapshotTabPath = null
lastKnownGraph = null
}
function openTabsSnapshot(): OpenTabsSnapshot | undefined {
const openTabs = workflowStore.openWorkflows.flatMap((tab) => {
const workflowId = cloudIdFor(tab)
return workflowId === undefined
? []
: [{ workflow_id: workflowId, name: tab.filename }]
})
if (openTabs.length === 0) return undefined
const active = workflowStore.activeWorkflow
return {
open_tabs: openTabs,
current_tab:
active && !workflowDetached.value ? cloudIdFor(active) : undefined
}
}
function onWorkflowAdopted(
workflowId: string,
sent: WorkflowTurnContext | undefined,
uploaded: boolean
): void {
if (uploaded && lastSentGraph !== null)
lastKnownGraph = { serialized: lastSentGraph, workflowId }
if (sent !== undefined && sent.id === workflowId) {
bindingStore.bind(workflowId, sent.tabPath)
tabActivity.setEditing(sent.tabPath)
return
}
if (uploaded && snapshotTabPath !== null) {
bindingStore.bind(workflowId, snapshotTabPath)
tabActivity.setEditing(snapshotTabPath)
}
}
const {
sendMessage,
stopTurn,
isSending,
newChat,
start,
stop,
entries,
editableTurnId,
isStreaming,
status,
notices,
threadId,
listThreads,
loadThread
} = useAgentSession({
rest,
events,
workflow: {
current: activeWorkflowTurnContext,
adopted: onWorkflowAdopted,
prepare: refreshCloudWorkflowIds,
snapshot: takeWorkflowSnapshot,
uploadSkipped: resetSnapshotGuard,
tabs: openTabsSnapshot,
activeTab: enqueueActiveTab
}
})
let autoFitPending = false
function fitDraftIntoView(): void {
const canvas = canvasStore.canvas
if (canvas) fitGraphToView(canvas)
}
// The agent's drafts often stack new nodes at one spot, so an added node
// triggers the layered arrange; running it after loadGraphData keeps the
// undo capture outside the loader's suppression window.
function arrangeAgentNodes(): void {
app.graph?.arrange()
workflowStore.activeWorkflow?.changeTracker?.captureCanvasState()
}
watch(isStreaming, (streaming) => {
if (streaming || !autoFitPending) return
autoFitPending = false
fitDraftIntoView()
})
// The resumed turn's own workflow outlives a panel remount (draftStore
// binds it at ack; only newChat/loadThread reset it), while the active tab
// may have changed since - prefer the bound tab over active-tab derivation.
function resumedTurnTabPath(): string | null {
if (workflowDetached.value) return null
const bound = draftStore.workflowId
if (bound === null) return activeWorkflowTurnContext()?.tabPath ?? null
const boundPath = bindingStore.tabPathFor(bound)
if (boundPath !== undefined) return boundPath
const context = activeWorkflowTurnContext()
return context?.id === bound ? context.tabPath : null
}
// Adoption (onWorkflowAdopted) and tab activation (onAgentActiveTab) are the
// primary spinner setters; the non-idle branch only re-arms it after the
// stash/resume flip of a panel remount, where those setters never run.
watch(status, (value) => {
if (value === 'idle') {
const completedPath = tabActivity.editingTabPath
tabActivity.setEditing(null)
if (completedPath !== null) tabActivity.markModified(completedPath)
} else if (tabActivity.editingTabPath === null)
tabActivity.setEditing(resumedTurnTabPath())
})
const executionErrorStore = useExecutionErrorStore()
function surfaceAgentError(
type: 'agent_api_failed' | 'agent_draft_apply_failed',
details: string
): void {
executionErrorStore.recordPromptError({
type,
message: t(`errorCatalog.promptErrors.${type}.desc`),
details
})
executionErrorStore.showErrorOverlay()
}
let noticesSeen = 0
watch(
() => notices.value.length,
(length) => {
for (const notice of notices.value.slice(noticesSeen))
surfaceAgentError('agent_api_failed', notice.text)
noticesSeen = length
}
)
let draftRejectionNotified = false
function surfaceDraftApplyFailure(details: string): void {
console.warn(details)
if (draftRejectionNotified) return
draftRejectionNotified = true
surfaceAgentError('agent_draft_apply_failed', details)
}
let lastApplied: { workflowId: string; version: number } | null = null
let applying = false
let reapplyQueued = false
function boundTabFor(workflowId: string): ComfyWorkflow | null {
const path = bindingStore.tabPathFor(workflowId)
const bound =
path === undefined ? null : workflowStore.getWorkflowByPath(path)
if (bound) return bound
for (const [name, id] of cloudIdsByName) {
if (id !== workflowId) continue
const matches = openSavedTabsNamed(name)
return matches.length === 1 ? matches[0] : null
}
return null
}
function unusedFilenameFor(tab: ComfyWorkflow): string {
const takenByOther = (filename: string) => {
const path =
tab.directory +
'/' +
appendWorkflowJsonExt(filename, tab.initialMode === 'app')
return path !== tab.path && workflowStore.getWorkflowByPath(path) !== null
}
if (!takenByOther(tab.filename)) return tab.filename
let counter = 2
while (takenByOther(`${tab.filename} (${counter})`)) counter++
return `${tab.filename} (${counter})`
}
async function autosaveAppliedDraft(
workflowId: string,
tab: ComfyWorkflow
): Promise<void> {
const preSavePath = tab.path
const wasEditing = tabActivity.editingTabPath === preSavePath
try {
const saved = tab.isTemporary
? await workflowService.saveWorkflowAs(tab, {
filename: unusedFilenameFor(tab)
})
: await workflowService.saveWorkflow(tab)
if (!saved) console.error(`Agent draft autosave failed for ${tab.path}`)
} catch (error) {
console.error(`Agent draft autosave failed for ${tab.path}:`, error)
} finally {
bindingStore.bind(workflowId, tab.path)
const editing = tabActivity.editingTabPath
if (
wasEditing &&
(editing === preSavePath || editing === null) &&
status.value !== 'idle'
)
tabActivity.setEditing(tab.path)
}
}
let activeTabGeneration = 0
let activeTabChain: Promise<void> = Promise.resolve()
const lastRenderedVersions = new Map<string, number>()
function enqueueActiveTab(data: AgentActiveTabData): void {
const generation = ++activeTabGeneration
activeTabChain = activeTabChain.then(() => onAgentActiveTab(data, generation))
}
function agentTabFilename(name: string | undefined): string | undefined {
const cleaned = [
...(name ?? '')
.replace(/[/\\\p{Cc}]/gu, '-')
.replace(/\.json$/i, '')
.trim()
.replace(/^\.+/, '')
]
.slice(0, 80)
.join('')
.replace(/^[\s.]+/u, '')
.trim()
return cleaned.length === 0 ? undefined : `${cleaned}.json`
}
async function fetchDraftSnapshot(
workflowId: string
): Promise<AgentDraftSnapshot | null> {
try {
return await rest.getDraft(workflowId)
} catch (error) {
if (error instanceof AgentApiError && error.status === 404) return null
throw error
}
}
function recordRenderedVersion(nextWorkflowId: string): void {
const leaving = draftStore.workflowId
if (leaving === null || leaving === nextWorkflowId) return
if (lastApplied?.workflowId === leaving)
lastRenderedVersions.set(leaving, lastApplied.version)
else lastRenderedVersions.delete(leaving)
}
async function adoptDraftBase(
workflowId: string,
snapshot: AgentDraftSnapshot,
armVersion: number = snapshot.version
): Promise<void> {
draftStore.bind(workflowId)
await nextTick()
if (
!(
lastApplied?.workflowId === workflowId && lastApplied.version > armVersion
)
)
lastApplied = { workflowId, version: armVersion }
draftStore.adoptSnapshot(snapshot)
}
async function onAgentActiveTab(
data: AgentActiveTabData,
generation: number
): Promise<void> {
const stale = () => generation !== activeTabGeneration
if (stale()) return
try {
recordRenderedVersion(data.workflow_id)
const bound = boundTabFor(data.workflow_id)
if (bound) {
const alreadyCurrent =
draftStore.workflowId === data.workflow_id &&
draftStore.version !== null
await workflowService.openWorkflow(bound)
if (stale()) return
// boundTabFor can resolve by cloud name, which leaves no binding behind
// for everything downstream that only reads tabPathFor.
bindingStore.bind(data.workflow_id, bound.path)
if (status.value !== 'idle') tabActivity.setEditing(bound.path)
draftStore.bind(data.workflow_id)
const snapshot = await fetchDraftSnapshot(data.workflow_id)
if (stale()) return
if (
snapshot !== null &&
!(alreadyCurrent && (draftStore.version ?? -1) >= snapshot.version)
)
await adoptDraftBase(
data.workflow_id,
snapshot,
lastRenderedVersions.get(data.workflow_id) ?? -1
)
useTelemetry()?.trackAgentWorkflowApplied({
workflow_id: data.workflow_id,
target: 'active_tab_switch'
})
return
}
const creatingStartedAt = Date.now()
tabActivity.setCreating(true)
const snapshot = await fetchDraftSnapshot(data.workflow_id)
if (stale()) return
let validationError = ''
const workflow =
snapshot === null
? null
: await validateComfyWorkflow(snapshot.content, (error) => {
validationError = error
})
if (stale()) return
if (snapshot !== null && !workflow) {
surfaceDraftApplyFailure(validationError)
draftStore.bind(data.workflow_id)
return
}
const remainingCreatingTime =
CREATING_TAB_MIN_DURATION_MS - (Date.now() - creatingStartedAt)
if (remainingCreatingTime > 0)
await new Promise((resolve) => setTimeout(resolve, remainingCreatingTime))
if (stale()) return
const tab = workflowStore.createTemporary(
agentTabFilename(data.name),
workflow ?? undefined
)
tabActivity.setCreating(false)
await workflowService.openWorkflow(tab)
if (stale()) return
if (status.value !== 'idle') tabActivity.setEditing(tab.path)
await autosaveAppliedDraft(data.workflow_id, tab)
if (stale()) return
if (snapshot === null) draftStore.bind(data.workflow_id)
else await adoptDraftBase(data.workflow_id, snapshot)
useTelemetry()?.trackAgentWorkflowApplied({
workflow_id: data.workflow_id,
target: 'active_tab_open'
})
} catch (error) {
if (stale()) return
draftStore.bind(data.workflow_id)
surfaceAgentError(
'agent_api_failed',
error instanceof Error ? error.message : String(error)
)
} finally {
tabActivity.setCreating(false)
}
}
async function loadDraft(
workflowId: string,
version: number,
content: Record<string, unknown>,
tab: ComfyWorkflow | null
): Promise<void> {
const workflow = await validateComfyWorkflow(content, (error) => {
surfaceDraftApplyFailure(error)
})
if (!workflow) return
const openBefore = new Set(workflowStore.openWorkflows.map((w) => w.path))
const knownIds =
tab === null
? new Set<string>()
: new Set((app.graph?.nodes ?? []).map((node) => String(node.id)))
try {
await app.loadGraphData(workflow, true, true, tab)
draftRejectionNotified = false
lastApplied = { workflowId, version }
if (workflow.nodes.some((node) => !knownIds.has(String(node.id))))
arrangeAgentNodes()
if (isStreaming.value) autoFitPending = true
else fitDraftIntoView()
const rendered = app.graph?.serialize()
if (rendered)
lastKnownGraph = { serialized: JSON.stringify(rendered), workflowId }
useTelemetry()?.trackAgentWorkflowApplied({
workflow_id: workflowId,
target: tab === null ? 'new_tab' : 'existing_tab'
})
if (tab === null) {
const opened = workflowStore.openWorkflows.find(
(w) => !openBefore.has(w.path)
)
if (opened) {
bindingStore.bind(workflowId, opened.path)
await autosaveAppliedDraft(workflowId, opened)
}
return
}
await autosaveAppliedDraft(workflowId, tab)
} catch (error) {
surfaceDraftApplyFailure(
error instanceof Error ? error.message : String(error)
)
}
}
async function applyDraft(): Promise<void> {
if (applying) {
reapplyQueued = true
return
}
applying = true
try {
const workflowId = draftStore.workflowId
const version = draftStore.version
const content = draftStore.content
if (workflowId === null || version === null || content === null) return
if (
lastApplied !== null &&
lastApplied.workflowId === workflowId &&
lastApplied.version >= version
)
return
const nodes = (content as { nodes?: unknown }).nodes
if (!Array.isArray(nodes) || nodes.length === 0) return
const boundTab = boundTabFor(workflowId)
if (boundTab) {
if (workflowStore.activeWorkflow?.path !== boundTab.path) {
tabActivity.markModified(boundTab.path)
return
}
await loadDraft(workflowId, version, content, boundTab)
return
}
await loadDraft(workflowId, version, content, null)
} finally {
applying = false
if (reapplyQueued) {
reapplyQueued = false
void applyDraft()
}
}
}
watch(
() => draftStore.version,
(version) => {
if (version === null || draftStore.content === null) return
void applyDraft()
}
)
watch(
() => workflowStore.activeWorkflow?.path,
() => void applyDraft()
)
watch(
() => draftStore.workflowId,
() => {
lastApplied = null
}
)
start()
void refreshCloudWorkflowIds()
onBeforeUnmount(() => {
exitNodeSelectionMode()
stop()
tabActivity.setEditing(null)
tabActivity.setCreating(false)
})
const history = useAgentChatHistoryStore()
const { copy } = useClipboard({ legacy: true })
function onFeedback(turnId: string, vote: 'up' | 'down' | null): void {
useTelemetry()?.trackAgentMessageFeedback({
message_id: turnId,
vote,
workflow_id: draftStore.workflowId
})
}
function toChatSession(thread: AgentThreadSummary): ChatSession {
const stamp = thread.last_message_at ?? thread.updated_at ?? thread.created_at
const updatedAt = stamp ? Date.parse(stamp) : Date.now()
return {
id: thread.id,
title: thread.title || thread.preview || t('agent.untitledChat'),
updatedAt: Number.isNaN(updatedAt) ? Date.now() : updatedAt
}
}
async function refreshHistory(): Promise<void> {
try {
history.replaceAll((await listThreads()).map(toChatSession))
} catch (error) {
surfaceAgentError(
'agent_api_failed',
error instanceof Error ? error.message : String(error)
)
}
}
watch(threadId, (id) => history.setActive(id), { immediate: true })
void refreshHistory()
async function onSelectHistory(id: string): Promise<void> {
exitNodeSelectionMode()
resetSnapshotGuard()
workflowDetached.value = false
await loadThread(id)
void refreshHistory()
}
function buildTranscriptMarkdown(entries: ConversationEntry[]): string {
return entries
.map((entry) => {
if (entry.role === 'user') return `**You:** ${entry.text}`
const text = entry.parts
.filter((part) => part.type === 'text')
.map((part) => part.text)
.join('')
return `**Agent:** ${text}`
})
.join('\n\n')
}
function onCopyMarkdown(id: string): void {
if (id === history.activeId) void copy(buildTranscriptMarkdown(entries.value))
else toast.add({ severity: 'info', summary: t('agent.copyUnavailable') })
}
const coachStep: CoachStep = {
target: '#agent-panel-root',
title: t('agent.coachTitle'),
body: t('agent.coachBody')
}
function onSend(text: string, attachments: ComposerAttachment[]): void {
exitNodeSelectionMode()
void applyDraft()
const nodeTags = consumeSelection()
useTelemetry()?.trackAgentMessageSent({
attachment_count: attachments.length,
node_tag_count: nodeTags.length
})
void sendMessage(text, attachments, nodeTags).then((ok) => {
if (!ok) resetSnapshotGuard()
})
}
function onStop(): void {
void stopTurn()
}
function onRenameChat(title: string): void {
if (threadId.value !== null) history.rename(threadId.value, title)
}
function onRenameHistory(id: string, title: string): void {
history.rename(id, title)
}
function onDeleteHistory(id: string): void {
history.remove(id)
// Deleting the open chat also ends it; a dead thread must not stay editable.
if (id === threadId.value) onNewChat()
}
function onNewChat(): void {
exitNodeSelectionMode()
resetSnapshotGuard()
workflowDetached.value = true
newChat()
}
const panelRef = ref<InstanceType<typeof AgentPanel>>()
const fileInput = ref<HTMLInputElement>()
const assetDragActive = ref(false)
let assetDragDepth = 0
provide('agentAssetDragActive', readonly(assetDragActive))
let selectingNodes = false
let nodeSelectionCanvas: LGraphCanvas | undefined
let selectedGraphNodes = new Map<string, LGraphNode>()
let restoreAllowDragNodes: boolean | undefined
let restoreSelectOnly: boolean | undefined
watch(
() => canvasStore.selectedItems,
(items) => {
const nodes = items.filter(isLGraphNode)
if (agentNodeSelectionStore.restoredNodeIds !== null) {
selectedGraphNodes = new Map(
nodes.map(
(node) => [workflowStore.nodeToNodeLocatorId(node), node] as const
)
)
replaceSelectionTags(nodes.map(toSelectedNode))
agentNodeSelectionStore.finishWorkflowLoad()
return
}
if (!selectingNodes || agentNodeSelectionStore.isLoadingWorkflow) return
const currentNodes = new Map<string, LGraphNode>(
nodes.map(
(node) => [workflowStore.nodeToNodeLocatorId(node), node] as const
)
)
selectedGraphNodes = currentNodes
},
{ immediate: true }
)
function exitNodeSelectionMode(): void {
const canvas = nodeSelectionCanvas
if (canvas) {
canvas.multi_select = false
canvas.allow_dragnodes = restoreAllowDragNodes ?? true
canvas.selectOnly = restoreSelectOnly ?? false
}
nodeSelectionCanvas = undefined
restoreAllowDragNodes = undefined
restoreSelectOnly = undefined
selectedGraphNodes.clear()
selectingNodes = false
if (agentNodeSelectionStore.isActive) agentNodeSelectionStore.exit()
if (canvas) {
canvas.deselectAll()
canvasStore.updateSelectedItems()
}
}
watch(
() => agentNodeSelectionStore.isActive,
(active) => {
if (!active) exitNodeSelectionMode()
}
)
watch(
() => agentNodeSelectionStore.restoredNodeIds,
(nodeIds) => {
if (nodeIds === null) return
selectedGraphNodes = new Map(
[...(app.canvas?.selectedItems ?? [])]
.filter(isLGraphNode)
.map((node) => [workflowStore.nodeToNodeLocatorId(node), node] as const)
)
}
)
watch(
[() => workflowStore.activeWorkflow?.path, () => canvasStore.currentGraph],
() => {
if (!agentNodeSelectionStore.isLoadingWorkflow) exitNodeSelectionMode()
}
)
function onSelectNodes(): void {
if (selectingNodes) return
const canvas = app.canvas
if (!canvas) return
const merged = new Map<string, LGraphNode>(
[...canvas.selectedItems]
.filter(isLGraphNode)
.map((node) => [workflowStore.nodeToNodeLocatorId(node), node] as const)
)
for (const tag of selectionTags.value) {
const key = selectedNodeKey(tag)
const node = getNodeByLocatorId(app.rootGraph, key)
if (node) merged.set(key, node)
}
selectedGraphNodes = merged
if (merged.size) {
canvas.selectItems([...merged.values()])
canvasStore.updateSelectedItems()
}
restoreAllowDragNodes = canvas.allow_dragnodes
restoreSelectOnly = canvas.selectOnly
canvas.allow_dragnodes = false
canvas.selectOnly = true
canvas.multi_select = true
nodeSelectionCanvas = canvas
selectingNodes = true
agentNodeSelectionStore.enter()
void nextTick(() => {
if (selectingNodes) canvas.canvas.focus()
})
}
const attachment = useAttachment({
upload: async (file) => ({
ref: (await rest.uploadImage(file, file.name)).name
}),
maxBytes: (file) => {
const serverLimit = api.getServerFeature(
'max_upload_size',
MAX_ATTACHMENT_BYTES
)
return hasVideoType(file)
? serverLimit
: Math.min(MAX_ATTACHMENT_BYTES, serverLimit)
},
// A rejected file is the user's problem to fix, not an agent failure, so it
// must not raise the server-error overlay.
onError: (message) =>
toast.add({ severity: 'warn', detail: message, life: 5000 }),
stage: (staged) => panelRef.value?.addAttachment(staged),
update: (id, patch) => panelRef.value?.updateAttachment(id, patch),
remove: (id) => panelRef.value?.removeAttachment(id)