Skip to content

Commit bb9291a

Browse files
committed
It works??
1 parent 5dc3ba3 commit bb9291a

File tree

6 files changed

+109
-28
lines changed

6 files changed

+109
-28
lines changed

apps/sim/app/api/workflows/[id]/route.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,16 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
110110
parallelsCount: Object.keys(normalizedData.parallels).length,
111111
loops: normalizedData.loops,
112112
})
113+
114+
// Debug: Log sample block data from normalized tables
115+
const sampleBlockId = Object.keys(normalizedData.blocks)[0]
116+
if (sampleBlockId) {
117+
logger.debug(`[${requestId}] Sample block from normalized tables:`, {
118+
blockId: sampleBlockId,
119+
block: normalizedData.blocks[sampleBlockId],
120+
subBlocks: normalizedData.blocks[sampleBlockId]?.subBlocks
121+
})
122+
}
113123
// Use normalized table data - reconstruct complete state object
114124
// First get any existing state properties, then override with normalized data
115125
const existingState =

apps/sim/app/api/workflows/[id]/state/route.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,19 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
8585
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
8686
}
8787

88-
// Save to normalized tables
88+
// Save to normalized tables
8989
logger.info(`[${requestId}] Saving workflow ${workflowId} state to normalized tables`)
90-
90+
91+
// Debug: Log sample block data being received
92+
const sampleBlockId = Object.keys(state.blocks)[0]
93+
if (sampleBlockId) {
94+
logger.debug(`[${requestId}] Sample block data received:`, {
95+
blockId: sampleBlockId,
96+
block: state.blocks[sampleBlockId],
97+
subBlocks: state.blocks[sampleBlockId]?.subBlocks
98+
})
99+
}
100+
91101
// Ensure all required fields are present for WorkflowState type
92102
const workflowState = {
93103
blocks: state.blocks,
@@ -101,7 +111,7 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
101111
hasActiveSchedule: state.hasActiveSchedule || false,
102112
hasActiveWebhook: state.hasActiveWebhook || false,
103113
}
104-
114+
105115
const saveResult = await saveWorkflowToNormalizedTables(workflowId, workflowState)
106116

107117
if (!saveResult.success) {

apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/control-bar/components/import-controls/import-controls.tsx

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,9 @@ export function ImportControls({ disabled = false }: ImportControlsProps) {
114114
workspaceId,
115115
})
116116

117-
// Navigate to the new workflow
118-
router.push(`/workspace/${workspaceId}/w/${newWorkflowId}`)
119-
120-
// Brief delay to ensure navigation completes
121-
await new Promise((resolve) => setTimeout(resolve, 100))
122-
123-
// Import the YAML into the new workflow (creates complete state and saves directly to DB)
117+
// Import the YAML into the new workflow BEFORE navigation (creates complete state and saves directly to DB)
118+
// This avoids timing issues with workflow reload during navigation
119+
logger.info('Importing YAML into new workflow before navigation')
124120
const result = await importWorkflowFromYaml(yamlContent, {
125121
addBlock: collaborativeAddBlock,
126122
addEdge: collaborativeAddEdge,
@@ -133,11 +129,16 @@ export function ImportControls({ disabled = false }: ImportControlsProps) {
133129
collaborativeSetSubblockValue(blockId, subBlockId, value)
134130
},
135131
getExistingBlocks: () => {
136-
// This will be called after navigation, so we need to get blocks from the store
137-
const { useWorkflowStore } = require('@/stores/workflows/workflow/store')
138-
return useWorkflowStore.getState().blocks
132+
// For a new workflow, we'll get the starter block from the server
133+
return {}
139134
},
140-
})
135+
}, newWorkflowId) // Pass the new workflow ID to import into
136+
137+
// Navigate to the new workflow AFTER import is complete
138+
if (result.success) {
139+
logger.info('Navigating to imported workflow')
140+
router.push(`/workspace/${workspaceId}/w/${newWorkflowId}`)
141+
}
141142

142143
setImportResult(result)
143144

apps/sim/lib/workflows/db-helpers.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,14 @@ export async function loadWorkflowFromNormalizedTables(
6969
parentId,
7070
extent,
7171
}
72+
73+
// Debug: Log sample block subBlocks from database
74+
if (block.type === 'agent') {
75+
logger.debug(`Loaded ${block.type} block from database:`, {
76+
blockId: block.id,
77+
subBlocks: block.subBlocks
78+
})
79+
}
7280
})
7381

7482
// Convert edges to the expected format
@@ -162,6 +170,15 @@ export async function saveWorkflowToNormalizedTables(
162170
extent: block.data?.extent || null,
163171
}))
164172

173+
// Debug: Log sample block insert data
174+
if (blockInserts.length > 0) {
175+
logger.debug(`Saving ${blockInserts.length} blocks. Sample block:`, {
176+
blockId: blockInserts[0].id,
177+
type: blockInserts[0].type,
178+
subBlocks: blockInserts[0].subBlocks
179+
})
180+
}
181+
165182
await tx.insert(workflowBlocks).values(blockInserts)
166183
}
167184

apps/sim/stores/workflows/registry/store.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,13 +474,20 @@ export const useWorkflowRegistry = create<WorkflowRegistry>()(
474474
})
475475
})
476476

477+
// Debug: Log what values are being extracted from the database
478+
logger.debug(`Extracted subblock values from database for workflow ${id}:`, subblockValues)
479+
477480
// Update subblock store for this workflow
478481
useSubBlockStore.setState((state) => ({
479482
workflowValues: {
480483
...state.workflowValues,
481484
[id]: subblockValues,
482485
},
483486
}))
487+
488+
// Debug: Verify SubBlockStore was updated
489+
const updatedValues = useSubBlockStore.getState().workflowValues[id]
490+
logger.debug(`SubBlockStore updated for workflow ${id}:`, updatedValues)
484491
} else {
485492
// If no state in DB, use empty state - server should have created start block
486493
workflowState = {

apps/sim/stores/workflows/yaml/importer.ts

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,8 @@ export async function importWorkflowFromYaml(
348348
applyAutoLayout: () => void
349349
setSubBlockValue: (blockId: string, subBlockId: string, value: any) => void
350350
getExistingBlocks: () => Record<string, any>
351-
}
351+
},
352+
targetWorkflowId?: string
352353
): Promise<{ success: boolean; errors: string[]; warnings: string[]; summary?: string }> {
353354
logger.info('Starting YAML workflow import (complete state creation)')
354355

@@ -376,7 +377,25 @@ export async function importWorkflowFromYaml(
376377
)
377378

378379
// Get the existing workflow state (to preserve starter blocks if they exist)
379-
const existingBlocks = workflowActions.getExistingBlocks()
380+
let existingBlocks: Record<string, any> = {}
381+
382+
if (targetWorkflowId) {
383+
// For target workflow, fetch from API
384+
try {
385+
const response = await fetch(`/api/workflows/${targetWorkflowId}`)
386+
if (response.ok) {
387+
const workflowData = await response.json()
388+
existingBlocks = workflowData.data?.state?.blocks || {}
389+
logger.debug(`Fetched existing blocks for target workflow ${targetWorkflowId}:`, Object.keys(existingBlocks))
390+
}
391+
} catch (error) {
392+
logger.warn(`Failed to fetch existing blocks for workflow ${targetWorkflowId}:`, error)
393+
}
394+
} else {
395+
// For active workflow, use from store
396+
existingBlocks = workflowActions.getExistingBlocks()
397+
}
398+
380399
const existingStarterBlocks = Object.values(existingBlocks).filter(
381400
(block: any) => block.type === 'starter'
382401
)
@@ -389,11 +408,13 @@ export async function importWorkflowFromYaml(
389408

390409
// Get current workflow state
391410
const currentWorkflowState = useWorkflowStore.getState()
392-
const activeWorkflowId = useWorkflowRegistry.getState().activeWorkflowId
411+
const activeWorkflowId = targetWorkflowId || useWorkflowRegistry.getState().activeWorkflowId
393412

394413
if (!activeWorkflowId) {
395414
return { success: false, errors: ['No active workflow'], warnings: [] }
396415
}
416+
417+
logger.info(`Importing YAML into workflow: ${activeWorkflowId} ${targetWorkflowId ? '(specified target)' : '(active workflow)'}`)
397418

398419
// Build complete blocks object
399420
const completeBlocks: Record<string, any> = {}
@@ -593,6 +614,12 @@ export async function importWorkflowFromYaml(
593614

594615
// Save directly to database via API
595616
logger.info('Saving complete workflow state directly to database...')
617+
logger.debug('Sample block being saved:', {
618+
firstBlockId: Object.keys(completeBlocks)[0],
619+
firstBlock: Object.values(completeBlocks)[0],
620+
firstBlockSubBlocks: Object.values(completeBlocks)[0]?.subBlocks
621+
})
622+
596623
const response = await fetch(`/api/workflows/${activeWorkflowId}/state`, {
597624
method: 'PUT',
598625
headers: {
@@ -614,17 +641,26 @@ export async function importWorkflowFromYaml(
614641
const saveResponse = await response.json()
615642
logger.info('Successfully saved to database:', saveResponse)
616643

617-
// Update local state for immediate UI display
618-
logger.info('Updating local state for immediate display...')
619-
useWorkflowStore.setState(completeWorkflowState)
620-
621-
// Set subblock values in local store
622-
useSubBlockStore.setState((state: any) => ({
623-
workflowValues: {
624-
...state.workflowValues,
625-
[activeWorkflowId]: completeSubBlockValues,
626-
},
627-
}))
644+
// Update local state for immediate UI display (only if importing into active workflow)
645+
if (!targetWorkflowId) {
646+
logger.info('Updating local state for immediate display (active workflow)...')
647+
useWorkflowStore.setState(completeWorkflowState)
648+
649+
// Set subblock values in local store
650+
logger.debug('Setting SubBlockStore with values:', completeSubBlockValues)
651+
useSubBlockStore.setState((state: any) => ({
652+
workflowValues: {
653+
...state.workflowValues,
654+
[activeWorkflowId]: completeSubBlockValues,
655+
},
656+
}))
657+
658+
// Verify SubBlockStore was updated
659+
const subBlockStoreValues = useSubBlockStore.getState().workflowValues[activeWorkflowId]
660+
logger.debug('SubBlockStore after update:', subBlockStoreValues)
661+
} else {
662+
logger.info('Skipping local state update (importing into non-active workflow)')
663+
}
628664

629665
// Brief delay for UI to update
630666
await new Promise((resolve) => setTimeout(resolve, 100))

0 commit comments

Comments
 (0)