From dd072e282f23ec29da4584607024724e8c7724ce Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 14:16:16 -0700 Subject: [PATCH 1/7] ODM: stop the UI from silently queueing duplicate tasks A user queued about a dozen identical reconstructions without meaning to, then saw only "Status: Queued, Progress: 0%" for two hours and reported it as a hang (MorphoCloud/Instances#139). The module made all of that easy: - The Run button was never disabled, so every click created another task on the node -- and each one overwrote self.webodmTask, so Slicer forgot the task it had just made while it kept running server-side. - create_task uploads every image on the UI thread with no progress_callback, freezing Slicer for minutes, while the button and its popup both claimed the operation was "(non-blocking)". - The status line never mentioned the node queue, so a task waiting behind eleven others was indistinguishable from a hang. - Nothing could cancel a task from inside Slicer; the only remedy was a browser pointed at a URL the module never showed. Changes: - Hold the Run button disabled for the whole of onRunWebODMTask (split into a guard + _runWebODMTask so an early return still re-enables it). - Query node.info() before creating: this is the first call that proves the node is reachable (Node.__init__ does no I/O), and it surfaces task_queue_count so we can ask before piling on. - Drive a progress dialog from pyodm's progress_callback during upload. - Report queue depth alongside a QUEUED status. - Add a Cancel Task button (Task.cancel()), and make Stop Monitoring say plainly that the task keeps running. - Add a clickable Node Dashboard link that tracks the IP/port fields. - Drop the false "(non-blocking)" from the button and popup. Also default matcher-type to flann, ODM's own default, which the tooltip already documented. bruteforce was preselected and, since turntable images carry no GPS EXIF, OpenSfM falls back to matching all pairs -- so every run was doing exhaustive descriptor matching over every pair. Separately, this file wrote "\\n" in 38 places, which renders as a literal "\n" in the dialog rather than a line break; the other 37 strings in the same file already used "\n". Repaired throughout. Co-Authored-By: Claude Opus 4.8 --- ODM/ODM.py | 230 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 195 insertions(+), 35 deletions(-) diff --git a/ODM/ODM.py b/ODM/ODM.py index 2458cf5..70de9a2 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -57,6 +57,8 @@ def __init__(self, parent=None): self.launchWebODMTaskButton = None self.webodmLogTextEdit = None self.stopMonitoringButton = None + self.cancelTaskButton = None + self.nodeDashboardLabel = None # NodeODM management self.launchWebODMButton = None @@ -86,7 +88,7 @@ def __init__(self, parent=None): "min-num-features": [50000, 10000, 20000], "pc-filter": [1, 2, 3, 4, 5], "depthmap-resolution": [3072, 2048, 4096, 8192], - "matcher-type": ["bruteforce", "bow", "flann"], + "matcher-type": ["flann", "bow", "bruteforce"], "feature-type": ["dspsift", "akaze", "hahog", "orb", "sift"], "feature-quality": ["ultra", "medium", "high"], "pc-quality": ["high", "medium", "ultra"], @@ -203,7 +205,18 @@ def setup(self): self.nodePortSpinBox.setValue(3002) self.nodePortSpinBox.setToolTip("Port number on which NodeODM is listening. Commonly 3001 or 3002.") webodmTaskFormLayout.addRow("Node Port:", self.nodePortSpinBox) - + + self.nodeDashboardLabel = qt.QLabel() + self.nodeDashboardLabel.setOpenExternalLinks(True) + self.nodeDashboardLabel.setToolTip( + "Opens the NodeODM dashboard in your browser.\n" + "Shows every task on this node (running, queued and finished) and lets you cancel them." + ) + webodmTaskFormLayout.addRow("Node Dashboard:", self.nodeDashboardLabel) + self.nodeIPLineEdit.connect('textChanged(QString)', self.onNodeAddressChanged) + self.nodePortSpinBox.connect('valueChanged(int)', self.onNodeAddressChanged) + self.updateNodeDashboardLink() + # WebODM parameter tooltips parameterTooltips = { "ignore-gsd": ( @@ -296,10 +309,14 @@ def setup(self): # TODO: Add WebODM parameter controls here (will be added in next step) self.datasetNameLineEdit = qt.QLineEdit("SlicerReconstruction") - self.datasetNameLineEdit.setToolTip("Name of the dataset in WebODM.\\nThis will be the reconstruction folder label.") + self.datasetNameLineEdit.setToolTip("Name of the dataset in WebODM.\nThis will be the reconstruction folder label.") webodmTaskFormLayout.addRow("name:", self.datasetNameLineEdit) - self.launchWebODMTaskButton = qt.QPushButton("Run NodeODM Task With Selected Parameters (non-blocking)") + self.launchWebODMTaskButton = qt.QPushButton("Run NodeODM Task With Selected Parameters") + self.launchWebODMTaskButton.setToolTip( + "Uploads the images and queues one reconstruction task on the node.\n" + "Uploading can take several minutes for large image sets." + ) webodmTaskFormLayout.addWidget(self.launchWebODMTaskButton) self.launchWebODMTaskButton.setEnabled(True) @@ -307,9 +324,20 @@ def setup(self): self.webodmLogTextEdit.setReadOnly(True) webodmTaskFormLayout.addRow("Console Log:", self.webodmLogTextEdit) + taskControlRow = qt.QHBoxLayout() self.stopMonitoringButton = qt.QPushButton("Stop Monitoring") self.stopMonitoringButton.setEnabled(False) - webodmTaskFormLayout.addWidget(self.stopMonitoringButton) + self.stopMonitoringButton.setToolTip( + "Stop updating this log. The task keeps running on the node.\n" + "Use 'Cancel Task' to actually stop it." + ) + taskControlRow.addWidget(self.stopMonitoringButton) + + self.cancelTaskButton = qt.QPushButton("Cancel Task") + self.cancelTaskButton.setEnabled(False) + self.cancelTaskButton.setToolTip("Cancel the monitored task on the node itself.") + taskControlRow.addWidget(self.cancelTaskButton) + webodmTaskFormLayout.addRow(taskControlRow) self.importModelButton = qt.QPushButton("Import Reconstructed Model") self.layout.addWidget(self.importModelButton) @@ -339,6 +367,7 @@ def setup(self): self.stopWebODMButton.connect('clicked(bool)', self.onStopNodeClicked) self.launchWebODMTaskButton.connect('clicked(bool)', self.onRunWebODMTask) self.stopMonitoringButton.connect('clicked(bool)', self.onStopMonitoring) + self.cancelTaskButton.connect('clicked(bool)', self.onCancelTaskClicked) self.importModelButton.connect('clicked(bool)', self.onImportModelClicked) # self.saveTaskButton.connect('clicked(bool)', self.onSaveTaskClicked) # self.restoreTaskButton.connect('clicked(bool)', self.onRestoreTaskClicked) @@ -365,7 +394,7 @@ def ensure_webodm_folder_permissions(self): os.chmod(self.webODMLocalFolder, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) logging.info(f"WebODM folder created and permissions set: {self.webODMLocalFolder}") except Exception as e: - slicer.util.errorDisplay(f"Failed to create or set permissions for WebODM folder:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to create or set permissions for WebODM folder:\n{str(e)}") def _ensurePyODMInstalled(self): """Check if pyodm is installed, and install it if missing.""" @@ -378,13 +407,13 @@ def _ensurePyODMInstalled(self): # Ask user to install if not slicer.util.confirmOkCancelDisplay( - "The ODM module requires the 'pyodm' Python package.\\n\\n" + "The ODM module requires the 'pyodm' Python package.\n\n" "Install it now?", "Install pyodm" ): slicer.util.warningDisplay( - "pyodm is required for this module to function.\\n" - "You can install it manually via:\\n" + "pyodm is required for this module to function.\n" + "You can install it manually via:\n" "pip install pyodm" ) return @@ -393,7 +422,7 @@ def _ensurePyODMInstalled(self): slicer.util.pip_install("pyodm") slicer.util.infoDisplay("pyodm installed successfully!") except Exception as e: - slicer.util.errorDisplay(f"Failed to install pyodm:\\n{e}\\n\\nPlease install manually:\\npip install pyodm") + slicer.util.errorDisplay(f"Failed to install pyodm:\n{e}\n\nPlease install manually:\npip install pyodm") def onLaunchWebODMClicked(self): """Launch NodeODM container with GPU support on port 3002""" @@ -410,7 +439,23 @@ def onRunWebODMTask(self): def onStopMonitoring(self): """Stop monitoring the current task""" self.webODMManager.onStopMonitoring() - + + def onCancelTaskClicked(self): + """Cancel the monitored task on the node""" + self.webODMManager.onCancelTaskClicked() + + def nodeDashboardUrl(self): + """URL of the NodeODM dashboard for the currently configured node.""" + return f"http://{self.nodeIPLineEdit.text.strip()}:{self.nodePortSpinBox.value}" + + def onNodeAddressChanged(self, unusedValue=None): + """Keep the dashboard link in sync with the IP/port fields.""" + self.updateNodeDashboardLink() + + def updateNodeDashboardLink(self): + url = self.nodeDashboardUrl() + self.nodeDashboardLabel.setText(f'{url}') + def onImportModelClicked(self): """Import the reconstructed 3D model into Slicer""" self.webODMManager.onImportModelClicked() @@ -601,7 +646,7 @@ def onLaunchWebODMClicked(self): """ proceed = slicer.util.confirmYesNoDisplay( "This action will ensure nodeodm:gpu is installed (pull if needed), " - "stop any running container on port 3002, and launch a new one.\\n\\n" + "stop any running container on port 3002, and launch a new one.\n\n" "Proceed?" ) if not proceed: @@ -612,7 +657,7 @@ def onLaunchWebODMClicked(self): try: subprocess.run(["docker", "--version"], check=True, capture_output=True) except Exception as e: - slicer.util.warningDisplay(f"Docker not found or not in PATH.\\nError: {str(e)}") + slicer.util.warningDisplay(f"Docker not found or not in PATH.\nError: {str(e)}") return # Check if image exists, pull if needed @@ -677,7 +722,7 @@ def onLaunchWebODMClicked(self): slicer.app.settings().setValue("ODM/WebODMIP", "127.0.0.1") slicer.app.settings().setValue("ODM/WebODMPort", "3002") except Exception as e: - slicer.util.errorDisplay(f"Failed to launch WebODM container:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to launch WebODM container:\n{str(e)}") def onStopNodeClicked(self): """ @@ -687,7 +732,7 @@ def onStopNodeClicked(self): if jobInProgress: proceed = slicer.util.confirmYesNoDisplay( - "A WebODM task appears to be in progress. Stopping the node now will cancel that task.\\n\\n" + "A WebODM task appears to be in progress. Stopping the node now will cancel that task.\n\n" "Do you want to continue?" ) if not proceed: @@ -710,12 +755,22 @@ def onStopNodeClicked(self): subprocess.run(["docker", "stop", cid], check=True) slicer.util.infoDisplay("NodeODM container stopped.") except Exception as e: - slicer.util.errorDisplay(f"Failed to stop container:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to stop container:\n{str(e)}") def onRunWebODMTask(self): """ - Create and execute a WebODM reconstruction task + Create and execute a WebODM reconstruction task. + + The button is held disabled for the whole call: the upload below runs on the UI + thread, and every click here queues a separate task on the node. """ + self.widget.launchWebODMTaskButton.setEnabled(False) + try: + self._runWebODMTask() + finally: + self.widget.launchWebODMTaskButton.setEnabled(True) + + def _runWebODMTask(self): try: from pyodm import Node except ImportError: @@ -727,7 +782,7 @@ def onRunWebODMTask(self): try: node = Node(node_ip, node_port) except Exception as e: - slicer.util.errorDisplay(f"Failed to connect to Node at {node_ip}:{node_port}\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to connect to Node at {node_ip}:{node_port}\n{str(e)}") return inputFolder = self.widget.inputFolderSelector.directory @@ -761,6 +816,30 @@ def onRunWebODMTask(self): else: slicer.util.infoDisplay("No combined_gcp_list.txt found. Proceeding without GCP...") + # Node.__init__ does not talk to the network, so this is the first call that + # actually proves the node is up -- and it tells us what is already queued. + dashboardUrl = self.widget.nodeDashboardUrl() + try: + nodeInfo = node.info() + except Exception as e: + slicer.util.errorDisplay( + f"Could not reach NodeODM at {dashboardUrl}\n\n{str(e)}\n\n" + "Is the node running? Use 'Launch NodeODM' above to start it." + ) + return + + queuedCount = nodeInfo.task_queue_count or 0 + if queuedCount > 0: + proceed = slicer.util.confirmYesNoDisplay( + f"This node already has {queuedCount} task(s) running or queued.\n\n" + "A new task waits in line behind them, and will just report " + "'Queued, Progress: 0%' until they finish.\n\n" + f"Review or cancel existing tasks at:\n{dashboardUrl}\n\n" + "Queue another task anyway?" + ) + if not proceed: + return + # Build parameters from baseline + UI selections params = dict(self.widget.baselineParams) @@ -785,21 +864,49 @@ def onRunWebODMTask(self): prefix = self.widget.datasetNameLineEdit.text.strip() or "SlicerReconstruction" shortTaskName = self.generateShortTaskName(prefix, params) - slicer.util.infoDisplay("Creating WebODM Task (non-blocking). Upload may take time...") + # create_task uploads every file on the UI thread, which for a few hundred images + # means minutes of frozen application. Drive a progress dialog from pyodm's + # callback so the upload is visibly alive. + fileCount = len(files_to_upload) + progressDialog = slicer.util.createProgressDialog( + windowTitle="Creating NodeODM Task", + labelText=f"Uploading {fileCount} file(s) to NodeODM...", + maximum=100 + ) + progressDialog.setCancelButton(None) + progressDialog.show() + slicer.app.processEvents() + + def onUploadProgress(percent): + progressDialog.labelText = f"Uploading {fileCount} file(s) to NodeODM... {percent:.0f}%" + progressDialog.setValue(int(percent)) + slicer.app.processEvents() try: - self.webodmTask = node.create_task(files=files_to_upload, options=params, name=shortTaskName) + self.webodmTask = node.create_task( + files=files_to_upload, + options=params, + name=shortTaskName, + progress_callback=onUploadProgress + ) except Exception as e: - slicer.util.errorDisplay(f"Task creation failed:\\n{str(e)}") + slicer.util.errorDisplay(f"Task creation failed:\n{str(e)}") return + finally: + progressDialog.close() - slicer.util.infoDisplay(f"Task '{shortTaskName}' created successfully. Monitoring progress...") + slicer.util.infoDisplay( + f"Task '{shortTaskName}' created successfully. Monitoring progress...", + autoCloseMsec=3000 + ) self.webodmOutDir = os.path.join(inputFolder, f"WebODM_{shortTaskName}") os.makedirs(self.webodmOutDir, exist_ok=True) self.widget.webodmLogTextEdit.clear() + self.widget.webodmLogTextEdit.append(f"Task '{shortTaskName}' queued on {dashboardUrl}") self.widget.stopMonitoringButton.setEnabled(True) + self.widget.cancelTaskButton.setEnabled(True) self.lastWebODMOutputLineIndex = 0 @@ -834,13 +941,61 @@ def onStopMonitoring(self): """ Stop monitoring the current task (task continues on server) """ + self._stopMonitoringTimer() + self.webodmTask = None + self.widget.stopMonitoringButton.setEnabled(False) + self.widget.cancelTaskButton.setEnabled(False) + self.widget.webodmLogTextEdit.append( + "Stopped monitoring. The task is still running on the node -- see " + f"{self.widget.nodeDashboardUrl()} to follow or cancel it." + ) + + def _stopMonitoringTimer(self): if self.webodmTimer: self.webodmTimer.stop() self.webodmTimer.deleteLater() self.webodmTimer = None + + def onCancelTaskClicked(self): + """ + Cancel the monitored task on the node itself (unlike Stop Monitoring, + which only stops Slicer from watching it). + """ + if not self.webodmTask: + slicer.util.infoDisplay("No task is currently being monitored.") + return + + if not slicer.util.confirmYesNoDisplay( + "Cancel the monitored task on the node?\n\nThis cannot be undone." + ): + return + + try: + self.webodmTask.cancel() + except Exception as e: + slicer.util.warningDisplay( + f"Failed to cancel the task:\n{str(e)}\n\n" + f"You can also cancel it at {self.widget.nodeDashboardUrl()}" + ) + return + + self.widget.webodmLogTextEdit.append("Task canceled on the node.") + self._stopMonitoringTimer() self.webodmTask = None self.widget.stopMonitoringButton.setEnabled(False) - self.widget.webodmLogTextEdit.append("Stopped monitoring.") + self.widget.cancelTaskButton.setEnabled(False) + + def queuedTaskCount(self): + """ + How many tasks are running or queued on the node, or None if it can't be asked. + Used to explain a task sitting at 'Queued, Progress: 0%'. + """ + try: + from pyodm import Node + node = Node(self.widget.nodeIPLineEdit.text.strip(), self.widget.nodePortSpinBox.value) + return node.info().task_queue_count + except Exception: + return None def checkWebODMTaskStatus(self): """ @@ -861,7 +1016,16 @@ def checkWebODMTaskStatus(self): self.widget.webodmLogTextEdit.append(line) self.lastWebODMOutputLineIndex += len(newLines) - self.widget.webodmLogTextEdit.append(f"Status: {info.status.name}, Progress: {info.progress}%") + statusLine = f"Status: {info.status.name}, Progress: {info.progress}%" + if info.status.name.lower() == "queued": + # "Queued, 0%" on its own reads as a hang. Say what it is waiting behind. + aheadCount = self.queuedTaskCount() + if aheadCount is not None and aheadCount > 1: + statusLine += ( + f" -- {aheadCount} task(s) running or queued on this node; " + f"yours is waiting its turn. See {self.widget.nodeDashboardUrl()}" + ) + self.widget.webodmLogTextEdit.append(statusLine) cursor = self.widget.webodmLogTextEdit.textCursor() cursor.movePosition(qt.QTextCursor.End) self.widget.webodmLogTextEdit.setTextCursor(cursor) @@ -873,25 +1037,21 @@ def checkWebODMTaskStatus(self): slicer.app.processEvents() try: self.webodmTask.download_assets(self.webodmOutDir) - slicer.util.infoDisplay(f"Results downloaded to:\\n{self.webodmOutDir}") + slicer.util.infoDisplay(f"Results downloaded to:\n{self.webodmOutDir}") except Exception as e: slicer.util.warningDisplay(f"Download failed: {str(e)}") - if self.webodmTimer: - self.webodmTimer.stop() - self.webodmTimer.deleteLater() - self.webodmTimer = None + self._stopMonitoringTimer() self.webodmTask = None self.widget.stopMonitoringButton.setEnabled(False) + self.widget.cancelTaskButton.setEnabled(False) elif info.status.name.lower() in ["failed", "canceled"]: self.widget.webodmLogTextEdit.append("Task failed or canceled. Stopping.") slicer.app.processEvents() - if self.webodmTimer: - self.webodmTimer.stop() - self.webodmTimer.deleteLater() - self.webodmTimer = None + self._stopMonitoringTimer() self.webodmTask = None self.widget.stopMonitoringButton.setEnabled(False) + self.widget.cancelTaskButton.setEnabled(False) def onImportModelClicked(self): """ @@ -922,7 +1082,7 @@ def onImportModelClicked(self): return obj_path = os.path.join(odm_texturing, obj_files[0]) - slicer.util.infoDisplay(f"Importing model from:\\n{obj_path}") + slicer.util.infoDisplay(f"Importing model from:\n{obj_path}") try: modelNode = slicer.util.loadModel(obj_path) @@ -932,7 +1092,7 @@ def onImportModelClicked(self): layoutManager.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) slicer.util.infoDisplay("Model imported successfully!") except Exception as e: - slicer.util.errorDisplay(f"Failed to import model:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to import model:\n{str(e)}") class ODMLogic(ScriptedLoadableModuleLogic): From ce3f2602727ee795e1ad8597c7838d2e83e4c7e8 Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 14:26:25 -0700 Subject: [PATCH 2/7] ODM: keep Run disabled while a task is still tracked Addresses the review on #84: the duplicate-task path was still reachable. Run was only held disabled for the duration of _runWebODMTask, so once a task was created and monitoring began the button came straight back -- and a second click would create another task on the node and overwrite self.webodmTask/self.webodmTimer, orphaning the first. That is exactly the behaviour the PR claimed to fix, and it is the likelier route to the dozen queued jobs in MorphoCloud/Instances#139: the user sees "Queued, 0%", concludes it is stuck, and clicks Run again. - Add _updateTaskButtons() as the single source of truth: Run is enabled only when no task is tracked; Stop Monitoring and Cancel only when one is. All four teardown paths (stop, cancel, completed, failed) go through it. - Add a hard guard at the top of _runWebODMTask: refuse to start when self.webodmTask is not None, rather than relying on the server-side queue-count prompt, which is dismissible and does not prevent the local overwrite. Also fix the off-by-one the review flagged in the queued status line. NodeODM's getQueueCount() counts QUEUED+RUNNING including this task (libs/TaskManager.js:305-316), so report count-1 as the number ahead. Co-Authored-By: Claude Opus 4.8 --- ODM/ODM.py | 57 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/ODM/ODM.py b/ODM/ODM.py index 70de9a2..f2f4ab6 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -757,20 +757,43 @@ def onStopNodeClicked(self): except Exception as e: slicer.util.errorDisplay(f"Failed to stop container:\n{str(e)}") + def _updateTaskButtons(self): + """ + Single source of truth for the task buttons: Run is available only when no task + is tracked, and the task controls only when one is. Re-enabling Run while a task + is still tracked is what let a second click orphan the first task. + """ + hasTask = self.webodmTask is not None + self.widget.launchWebODMTaskButton.setEnabled(not hasTask) + self.widget.stopMonitoringButton.setEnabled(hasTask) + self.widget.cancelTaskButton.setEnabled(hasTask) + def onRunWebODMTask(self): """ Create and execute a WebODM reconstruction task. - The button is held disabled for the whole call: the upload below runs on the UI - thread, and every click here queues a separate task on the node. + Run is disabled for the whole call (the upload runs on the UI thread, so clicks + would otherwise queue up behind it) and stays disabled afterwards for as long as + the created task is still being tracked. """ self.widget.launchWebODMTaskButton.setEnabled(False) try: self._runWebODMTask() finally: - self.widget.launchWebODMTaskButton.setEnabled(True) + self._updateTaskButtons() def _runWebODMTask(self): + # Slicer tracks exactly one task. Starting another would overwrite webodmTask and + # webodmTimer, leaving the previous one running on the node with no way to monitor + # or cancel it from here. + if self.webodmTask is not None: + slicer.util.warningDisplay( + "A task is already being monitored.\n\n" + "Use 'Cancel Task' to stop it, or 'Stop Monitoring' to leave it running on " + "the node, before starting another one." + ) + return + try: from pyodm import Node except ImportError: @@ -905,8 +928,6 @@ def onUploadProgress(percent): self.widget.webodmLogTextEdit.clear() self.widget.webodmLogTextEdit.append(f"Task '{shortTaskName}' queued on {dashboardUrl}") - self.widget.stopMonitoringButton.setEnabled(True) - self.widget.cancelTaskButton.setEnabled(True) self.lastWebODMOutputLineIndex = 0 @@ -943,8 +964,7 @@ def onStopMonitoring(self): """ self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) - self.widget.cancelTaskButton.setEnabled(False) + self._updateTaskButtons() self.widget.webodmLogTextEdit.append( "Stopped monitoring. The task is still running on the node -- see " f"{self.widget.nodeDashboardUrl()} to follow or cancel it." @@ -982,13 +1002,12 @@ def onCancelTaskClicked(self): self.widget.webodmLogTextEdit.append("Task canceled on the node.") self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) - self.widget.cancelTaskButton.setEnabled(False) + self._updateTaskButtons() def queuedTaskCount(self): """ - How many tasks are running or queued on the node, or None if it can't be asked. - Used to explain a task sitting at 'Queued, Progress: 0%'. + How many tasks are QUEUED or RUNNING on the node (this one included), or None if + it can't be asked. Used to explain a task sitting at 'Queued, Progress: 0%'. """ try: from pyodm import Node @@ -1019,11 +1038,13 @@ def checkWebODMTaskStatus(self): statusLine = f"Status: {info.status.name}, Progress: {info.progress}%" if info.status.name.lower() == "queued": # "Queued, 0%" on its own reads as a hang. Say what it is waiting behind. - aheadCount = self.queuedTaskCount() - if aheadCount is not None and aheadCount > 1: + # NodeODM counts QUEUED+RUNNING including this task, so drop it to get the + # number actually ahead. + totalCount = self.queuedTaskCount() + if totalCount is not None and totalCount > 1: statusLine += ( - f" -- {aheadCount} task(s) running or queued on this node; " - f"yours is waiting its turn. See {self.widget.nodeDashboardUrl()}" + f" -- {totalCount - 1} task(s) ahead of yours on this node. " + f"See {self.widget.nodeDashboardUrl()}" ) self.widget.webodmLogTextEdit.append(statusLine) cursor = self.widget.webodmLogTextEdit.textCursor() @@ -1043,15 +1064,13 @@ def checkWebODMTaskStatus(self): self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) - self.widget.cancelTaskButton.setEnabled(False) + self._updateTaskButtons() elif info.status.name.lower() in ["failed", "canceled"]: self.widget.webodmLogTextEdit.append("Task failed or canceled. Stopping.") slicer.app.processEvents() self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) - self.widget.cancelTaskButton.setEnabled(False) + self._updateTaskButtons() def onImportModelClicked(self): """ From 564c7b7a905f563f41d2f37adbd902aa596626f5 Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 14:49:27 -0700 Subject: [PATCH 3/7] ODM: close the upload dialog before reporting a creation failure Caught on a real node: when create_task fails, the "Creating NodeODM Task" progress dialog stays on screen behind the error. slicer.util.errorDisplay is modal, so raising it from the except block blocks before the finally that closes the progress dialog ever runs. Capture the exception, let the finally take the dialog down, then report. Found while testing against a NodeODM started with --test, which rejected feature-type=dspsift. That rejection is a test-mode artifact -- odmRunner's getJsonOptions returns a mock (tests/odm_options.json) instead of asking ODM, and that mock's feature-type enum predates dspsift -- but the stranded dialog it exposed is real and would show on any task-creation error. Co-Authored-By: Claude Opus 4.8 --- ODM/ODM.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ODM/ODM.py b/ODM/ODM.py index f2f4ab6..835a5f7 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -905,6 +905,9 @@ def onUploadProgress(percent): progressDialog.setValue(int(percent)) slicer.app.processEvents() + # Report the error only after the progress dialog is down: errorDisplay is modal, + # so raising it from the except block would strand the upload dialog behind it. + createError = None try: self.webodmTask = node.create_task( files=files_to_upload, @@ -913,10 +916,14 @@ def onUploadProgress(percent): progress_callback=onUploadProgress ) except Exception as e: - slicer.util.errorDisplay(f"Task creation failed:\n{str(e)}") - return + createError = e finally: progressDialog.close() + slicer.app.processEvents() + + if createError is not None: + slicer.util.errorDisplay(f"Task creation failed:\n{str(createError)}") + return slicer.util.infoDisplay( f"Task '{shortTaskName}' created successfully. Monitoring progress...", From 1ed363194ea9e93c7fb96e28ed393ccdea517efd Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 15:00:58 -0700 Subject: [PATCH 4/7] ODM: make each run identifiable on the node and on disk Observed on a real node: two tasks with different UUIDs both showed Name: SlicerReconstruction_15b1cf4b, and both mapped to one folder, WebODM_SlicerReconstruction_15b1cf4b. The suffix is not the UUID -- it is sha256(params)[:8], a pure function of the settings -- so any two runs with the same settings are indistinguishable on the dashboard and collide on disk, the second download landing on top of the first. - generateShortTaskName appends a YYYYMMDD-HHMMSS stamp. The node name and the WebODM_ folder are then 1:1 and unique per run. The params hash stays so settings remain readable at a glance. - Log the node task UUID and the download path when a task is created, so the console records the tie to the node's own identifier. - Create the output folder at download time, not at task creation. It was created up front, so any task that was never downloaded (Stop Monitoring, a failure, a restart) left an empty WebODM_ folder that looked like output and sent Import Reconstructed Model hunting for an odm_texturing that was never coming. - Sort the folder list in onImportModelClicked. os.listdir is in filesystem order, so `webodm_dirs[-1]` was an arbitrary folder despite being called latest_dir; with the timestamp suffix, sorting makes it genuinely the newest. Does not address re-attaching to an abandoned task (Stop Monitoring is still a one-way door). pyodm's Node.get_task(uuid) and NodeODM's GET /task/list make that feasible; it wants its own PR, and the module already carries commented-out Save/Restore Task buttons scoped for exactly that. Co-Authored-By: Claude Opus 4.8 --- ODM/ODM.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/ODM/ODM.py b/ODM/ODM.py index 835a5f7..d5671a6 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -930,11 +930,16 @@ def onUploadProgress(percent): autoCloseMsec=3000 ) + # Path only -- the folder is created at download time. Creating it here left an + # empty WebODM_ folder behind whenever a task was never downloaded (Stop + # Monitoring, a failure, a Slicer restart), which then looked like output and + # sent 'Import Reconstructed Model' hunting for an odm_texturing that never came. self.webodmOutDir = os.path.join(inputFolder, f"WebODM_{shortTaskName}") - os.makedirs(self.webodmOutDir, exist_ok=True) self.widget.webodmLogTextEdit.clear() self.widget.webodmLogTextEdit.append(f"Task '{shortTaskName}' queued on {dashboardUrl}") + self.widget.webodmLogTextEdit.append(f" node task UUID: {self.webodmTask.uuid}") + self.widget.webodmLogTextEdit.append(f" results will download to: {self.webodmOutDir}") self.lastWebODMOutputLineIndex = 0 @@ -953,17 +958,24 @@ def onUploadProgress(percent): def generateShortTaskName(self, basePrefix, paramsDict): """ - Generate a short task name based on prefix and parameter hash. - Similar to PhotoMasking's generateShortTaskName method. + Name a task uniquely: prefix, a hash of the parameters, and the start time. + + The hash alone is a pure function of the parameters, so re-running the same + settings produced the same name every time -- two tasks on the node sharing one + name, both pointing at one WebODM_ folder, the second download landing on + top of the first. The timestamp is what makes a run identifiable; the hash is + kept so the settings are still readable at a glance. """ import hashlib import json - + import datetime + # Convert params to a stable JSON string paramsStr = json.dumps(paramsDict, sort_keys=True) hashObj = hashlib.sha256(paramsStr.encode('utf-8')) shortHash = hashObj.hexdigest()[:8] - return f"{basePrefix}_{shortHash}" + stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + return f"{basePrefix}_{shortHash}_{stamp}" def onStopMonitoring(self): """ @@ -1064,6 +1076,7 @@ def checkWebODMTaskStatus(self): self.widget.webodmLogTextEdit.append(f"Task completed! Downloading results to {self.webodmOutDir} ...") slicer.app.processEvents() try: + os.makedirs(self.webodmOutDir, exist_ok=True) self.webodmTask.download_assets(self.webodmOutDir) slicer.util.infoDisplay(f"Results downloaded to:\n{self.webodmOutDir}") except Exception as e: @@ -1088,13 +1101,15 @@ def onImportModelClicked(self): slicer.util.errorDisplay("No input folder selected.") return - # Search for WebODM output folders - webodm_dirs = [d for d in os.listdir(inputFolder) if d.startswith("WebODM_")] + # Search for WebODM output folders. os.listdir is in filesystem order, so sort: + # task names end in a YYYYMMDD-HHMMSS stamp, which sorts chronologically, making + # the last entry genuinely the newest rather than whichever the OS happened to + # hand back last. + webodm_dirs = sorted(d for d in os.listdir(inputFolder) if d.startswith("WebODM_")) if not webodm_dirs: slicer.util.errorDisplay("No WebODM output folders found.") return - # For now, use the first one found (could add selection dialog) latest_dir = os.path.join(inputFolder, webodm_dirs[-1]) odm_texturing = os.path.join(latest_dir, "odm_texturing") From 7df2b2995fdba47da89c6dcc122089fef3888537 Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 15:04:28 -0700 Subject: [PATCH 5/7] ODM: add Reconnect to Task, so Stop Monitoring is no longer a one-way door Slicer held exactly one task in self.webodmTask, and nothing could ever get it back. Stop Monitoring, a Slicer restart, or a crash left the task running on the node with no code path anywhere in the module able to download its results -- the user's only recourse was the NodeODM dashboard. Naming the output folder well says where results would have gone; it cannot fetch them. The module already carried commented-out "Save Task"/"Restore Task" buttons and stub handlers: the original author scoped this and never built it. - "Reconnect to Task on Node..." lists what the node has (GET /task/list gives UUIDs only, so each is expanded via Task.info()), shows name/status/date/image count newest-first, and resumes monitoring the chosen one via Node.get_task(uuid). - Results route to WebODM_, matching the naming scheme, so a reconnected task lands exactly where it would have originally. Tasks created outside Slicer have no name; those fall back to WebODM_task_. - Reconnecting to an already-finished task downloads it immediately: the first poll is fired directly rather than waiting for the 5s tick. - Reconnect is the inverse of the task controls, so it shares _updateTaskButtons(): available only when no task is tracked. Tasks the node has forgotten are out of reach -- NodeODM's cleanup_tasks_after defaults to 2880 minutes (48h). Noted in the button tooltip. Co-Authored-By: Claude Opus 4.8 --- ODM/ODM.py | 125 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/ODM/ODM.py b/ODM/ODM.py index d5671a6..01d8407 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -58,6 +58,7 @@ def __init__(self, parent=None): self.webodmLogTextEdit = None self.stopMonitoringButton = None self.cancelTaskButton = None + self.reconnectTaskButton = None self.nodeDashboardLabel = None # NodeODM management @@ -338,6 +339,16 @@ def setup(self): self.cancelTaskButton.setToolTip("Cancel the monitored task on the node itself.") taskControlRow.addWidget(self.cancelTaskButton) webodmTaskFormLayout.addRow(taskControlRow) + + self.reconnectTaskButton = qt.QPushButton("Reconnect to Task on Node...") + self.reconnectTaskButton.setToolTip( + "Pick up a task that is already on the node - one left behind by 'Stop Monitoring',\n" + "or started in an earlier Slicer session - and resume watching it, downloading the\n" + "results when it finishes.\n\n" + "NodeODM deletes finished tasks after 48 hours by default, so this only reaches\n" + "tasks the node still remembers." + ) + webodmTaskFormLayout.addRow(self.reconnectTaskButton) self.importModelButton = qt.QPushButton("Import Reconstructed Model") self.layout.addWidget(self.importModelButton) @@ -368,6 +379,7 @@ def setup(self): self.launchWebODMTaskButton.connect('clicked(bool)', self.onRunWebODMTask) self.stopMonitoringButton.connect('clicked(bool)', self.onStopMonitoring) self.cancelTaskButton.connect('clicked(bool)', self.onCancelTaskClicked) + self.reconnectTaskButton.connect('clicked(bool)', self.onReconnectTaskClicked) self.importModelButton.connect('clicked(bool)', self.onImportModelClicked) # self.saveTaskButton.connect('clicked(bool)', self.onSaveTaskClicked) # self.restoreTaskButton.connect('clicked(bool)', self.onRestoreTaskClicked) @@ -444,6 +456,10 @@ def onCancelTaskClicked(self): """Cancel the monitored task on the node""" self.webODMManager.onCancelTaskClicked() + def onReconnectTaskClicked(self): + """Resume monitoring a task that is already on the node""" + self.webODMManager.onReconnectTaskClicked() + def nodeDashboardUrl(self): """URL of the NodeODM dashboard for the currently configured node.""" return f"http://{self.nodeIPLineEdit.text.strip()}:{self.nodePortSpinBox.value}" @@ -765,6 +781,7 @@ def _updateTaskButtons(self): """ hasTask = self.webodmTask is not None self.widget.launchWebODMTaskButton.setEnabled(not hasTask) + self.widget.reconnectTaskButton.setEnabled(not hasTask) self.widget.stopMonitoringButton.setEnabled(hasTask) self.widget.cancelTaskButton.setEnabled(hasTask) @@ -1023,6 +1040,114 @@ def onCancelTaskClicked(self): self.webodmTask = None self._updateTaskButtons() + def describeTask(self, info): + """One line per task for the reconnect picker.""" + stamp = info.date_created.strftime("%Y-%m-%d %H:%M") if info.date_created else "?" + return (f"{info.name or '(unnamed)'} | {info.status.name} | " + f"{stamp} UTC | {info.images_count} images") + + def onReconnectTaskClicked(self): + """ + Attach to a task that is already on the node -- left running by Stop Monitoring, + or started in an earlier Slicer session -- and resume monitoring it, so its + results can still be downloaded. + """ + if self.webodmTask is not None: + slicer.util.warningDisplay( + "A task is already being monitored.\n\nUse 'Stop Monitoring' first." + ) + return + + inputFolder = self.widget.inputFolderSelector.directory + if not inputFolder or not os.path.isdir(inputFolder): + slicer.util.errorDisplay( + "Select the masked images folder first - it is where the results are downloaded to." + ) + return + + try: + from pyodm import Node + except ImportError: + slicer.util.errorDisplay("pyodm module not found. Please install it via pip.") + return + + dashboardUrl = self.widget.nodeDashboardUrl() + node = Node(self.widget.nodeIPLineEdit.text.strip(), self.widget.nodePortSpinBox.value) + + try: + entries = node.get('/task/list') or [] + except Exception as e: + slicer.util.errorDisplay( + f"Could not reach NodeODM at {dashboardUrl}\n\n{str(e)}\n\n" + "Is the node running? Use 'Launch NodeODM' above to start it." + ) + return + + if not entries: + slicer.util.infoDisplay(f"The node at {dashboardUrl} has no tasks.") + return + + # /task/list returns UUIDs only, so ask each task for its name/status/date. + tasks = [] + for entry in entries: + uuid = entry.get('uuid') if isinstance(entry, dict) else None + if not uuid: + continue + try: + tasks.append(node.get_task(uuid).info()) + except Exception: + continue # vanished between listing and asking; skip it + + if not tasks: + slicer.util.warningDisplay( + f"The node at {dashboardUrl} listed tasks, but none of them could be read." + ) + return + + tasks.sort(key=lambda i: i.date_created, reverse=True) + labels = [self.describeTask(i) for i in tasks] + + # PythonQt's binding for QInputDialog.getItem returns just the selected string + # (empty on cancel), not the (value, ok) tuple the C++/PyQt API uses. + chosen = qt.QInputDialog.getItem( + slicer.util.mainWindow(), + "Reconnect to Task", + f"Tasks on {dashboardUrl}:", + labels, + 0, + False, + ) + if not chosen or chosen not in labels: + return + + self.attachToTask(node, tasks[labels.index(chosen)], inputFolder, dashboardUrl) + + def attachToTask(self, node, info, inputFolder, dashboardUrl): + """Resume monitoring an existing node task and route its results to disk.""" + self.webodmTask = node.get_task(info.uuid) + + # The task name is the folder key (WebODM_), which is why names carry a + # timestamp. A task created outside Slicer may be unnamed; fall back to its UUID. + folderKey = info.name or f"task_{info.uuid[:8]}" + self.webodmOutDir = os.path.join(inputFolder, f"WebODM_{folderKey}") + + self.widget.webodmLogTextEdit.clear() + self.widget.webodmLogTextEdit.append(f"Reconnected to '{folderKey}' on {dashboardUrl}") + self.widget.webodmLogTextEdit.append(f" node task UUID: {info.uuid}") + self.widget.webodmLogTextEdit.append(f" results will download to: {self.webodmOutDir}") + + self.lastWebODMOutputLineIndex = 0 + self._stopMonitoringTimer() + self.webodmTimer = qt.QTimer() + self.webodmTimer.setInterval(5000) + self.webodmTimer.timeout.connect(self.checkWebODMTaskStatus) + self.webodmTimer.start() + self._updateTaskButtons() + + # Poll once now rather than making the user wait for the first tick -- and if the + # task already finished, this downloads it immediately. + self.checkWebODMTaskStatus() + def queuedTaskCount(self): """ How many tasks are QUEUED or RUNNING on the node (this one included), or None if From 8eada1cb499af8dd9951f42cec3fd6af41db8e9d Mon Sep 17 00:00:00 2001 From: muratmaga Date: Wed, 15 Jul 2026 15:30:48 -0700 Subject: [PATCH 6/7] ODM: name tasks after the dataset, and record them on disk Every task was called SlicerReconstruction__