opensymphony 1.4.0

A Rust implementation of the OpenAI Symphony orchestration design
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! Runtime backend adapters for tracker, workspace, and worker orchestration.

use std::{
    collections::{HashMap, HashSet},
    path::PathBuf,
    sync::Arc,
    time::Duration,
};

use crate::opensymphony_domain::{
    ConversationMetadata, IssueId, IssueIdentifier, IssueState, IssueStateCategory,
    NormalizedIssue, TimestampMs, WorkerOutcomeKind, WorkerOutcomeRecord, WorkspaceKey,
};
use crate::opensymphony_linear::{LinearClient, LinearConfig, LinearError, WorkpadComment};
use crate::opensymphony_openhands::{
    IssueSessionError, IssueSessionObserver, IssueSessionResult, IssueSessionRunner,
    IssueSessionRunnerConfig, LocalServerSupervisor, LocalServerTooling, OpenHandsClient,
    OpenHandsError, SupervisedServerConfig, SupervisorConfig, TransportConfig,
    WorkpadComment as SessionWorkpadComment, WorkpadCommentSource,
};
use crate::opensymphony_orchestrator::{
    RecoveryRecord, TrackerBackend, WorkerAbortReason, WorkerBackend, WorkerLaunch,
    WorkerStartRequest, WorkerUpdate, WorkspaceBackend,
};
use crate::opensymphony_workflow::{ProcessEnvironment, ResolvedWorkflow};
use crate::opensymphony_workspace::{
    CleanupConfig, HookConfig, HookDefinition, IssueDescriptor, RunDescriptor, RunStatus,
    WorkspaceError, WorkspaceManager, WorkspaceManagerConfig,
};
use async_trait::async_trait;
use thiserror::Error;
use tokio::{
    fs,
    sync::{mpsc, oneshot},
    task::JoinHandle,
    time::timeout,
};
use url::Url;

use super::{
    RunCommandError, config::RunRuntimeConfig, datetime_to_timestamp_ms, now_timestamp,
    timestamp_to_datetime,
};

const DEFAULT_WORKER_LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);

#[derive(Debug, Error)]
pub(super) enum CliWorkspaceError {
    #[error(transparent)]
    Workspace(#[from] WorkspaceError),
    #[error(transparent)]
    Identifier(#[from] crate::opensymphony_domain::IdentifierError),
    #[error("failed to remove workspace {path}: {source}")]
    RemoveWorkspace {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

#[derive(Debug, Error)]
pub(super) enum CliWorkerError {
    #[error(transparent)]
    Workspace(#[from] WorkspaceError),
    #[error("worker launch timed out after {0:?}")]
    LaunchTimeout(Duration),
    #[error("worker failed before reporting a conversation launch: {0}")]
    LaunchFailed(String),
    #[error("worker exited before reporting a conversation launch")]
    LaunchChannelClosed,
    #[error("worker task failed: {0}")]
    Join(#[from] tokio::task::JoinError),
}

#[derive(Debug)]
enum LaunchReport {
    Conversation(Box<ConversationMetadata>),
    Failed(String),
}

pub(super) struct RuntimeTrackerBackend {
    client: LinearClient,
}

pub(super) struct RuntimeWorkspaceBackend {
    manager: Arc<WorkspaceManager>,
    active_states: HashSet<String>,
    terminal_states: HashSet<String>,
}

pub(super) struct RuntimeWorkerBackend {
    client: OpenHandsClient,
    workflow: Arc<ResolvedWorkflow>,
    workspace_manager: Arc<WorkspaceManager>,
    runner_config: IssueSessionRunnerConfig,
    workpad_comment_source: Option<Arc<dyn WorkpadCommentSource>>,
    launch_timeout: Duration,
    updates_tx: mpsc::UnboundedSender<WorkerUpdate>,
    updates_rx: mpsc::UnboundedReceiver<WorkerUpdate>,
    tasks: HashMap<String, ActiveWorkerTask>,
}

struct ActiveWorkerTask {
    handle: JoinHandle<()>,
    run: crate::opensymphony_domain::RunAttempt,
}

struct PendingLaunch {
    worker_id: String,
    launch_rx: oneshot::Receiver<LaunchReport>,
}

struct SchedulerObserver {
    worker_id: String,
    launch_tx: Option<oneshot::Sender<LaunchReport>>,
    updates_tx: mpsc::UnboundedSender<WorkerUpdate>,
}

struct LinearWorkpadCommentSource {
    client: LinearClient,
}

#[async_trait]
impl WorkpadCommentSource for LinearWorkpadCommentSource {
    async fn fetch_workpad_comment(
        &self,
        issue_id: &str,
    ) -> Result<Option<SessionWorkpadComment>, String> {
        self.client
            .fetch_workpad_comment(issue_id)
            .await
            .map(|comment| comment.map(workpad_comment_from_linear))
            .map_err(|error| error.to_string())
    }
}

impl IssueSessionObserver for SchedulerObserver {
    fn on_launch(&mut self, conversation: &ConversationMetadata) {
        if let Some(sender) = self.launch_tx.take() {
            let _ = sender.send(LaunchReport::Conversation(Box::new(conversation.clone())));
        }
    }

    fn on_runtime_event(
        &mut self,
        observed_at: TimestampMs,
        event_id: Option<String>,
        event_kind: Option<String>,
        summary: Option<String>,
    ) {
        let worker_id = self.worker_id.clone();
        let _ = self.updates_tx.send(WorkerUpdate::RuntimeEvent {
            worker_id: crate::opensymphony_domain::WorkerId::new(worker_id)
                .expect("worker id should remain valid"),
            observed_at,
            event_id,
            event_kind,
            summary,
        });
    }

    fn on_conversation_update(&mut self, conversation: &ConversationMetadata) {
        let worker_id = self.worker_id.clone();
        let _ = self
            .updates_tx
            .send(WorkerUpdate::ConversationMetadataUpdate {
                worker_id: crate::opensymphony_domain::WorkerId::new(worker_id)
                    .expect("worker id should remain valid"),
                conversation: conversation.clone(),
            });
    }
}

fn build_linear_client(workflow: &ResolvedWorkflow) -> Result<LinearClient, LinearError> {
    let tracker = &workflow.config.tracker;
    let mut config = LinearConfig::new(tracker.api_key.clone(), tracker.project_slug.clone());
    config.base_url = tracker.endpoint.clone();
    config.active_states = tracker.active_states.clone();
    config.terminal_states = tracker.terminal_states.clone();
    LinearClient::new(config)
}

fn workpad_comment_from_linear(comment: WorkpadComment) -> SessionWorkpadComment {
    SessionWorkpadComment {
        id: comment.id,
        body: comment.body,
        updated_at: comment.updated_at,
    }
}

pub(super) fn build_tracker_backend(
    workflow: &ResolvedWorkflow,
) -> Result<RuntimeTrackerBackend, LinearError> {
    Ok(RuntimeTrackerBackend {
        client: build_linear_client(workflow)?,
    })
}

pub(super) fn build_workspace_manager_config(
    workflow: &ResolvedWorkflow,
) -> WorkspaceManagerConfig {
    let hooks = &workflow.config.hooks;
    WorkspaceManagerConfig {
        root: workflow.config.workspace.root.clone(),
        hooks: HookConfig {
            after_create: hooks.after_create.clone().map(HookDefinition::shell),
            before_run: hooks.before_run.clone().map(HookDefinition::shell),
            after_run: hooks.after_run.clone().map(HookDefinition::shell),
            before_remove: hooks.before_remove.clone().map(HookDefinition::shell),
            timeout: Duration::from_millis(hooks.timeout_ms),
        },
        cleanup: CleanupConfig {
            remove_terminal_workspaces: false,
        },
    }
}

pub(super) async fn build_runtime_transport(
    runtime: &RunRuntimeConfig,
) -> Result<(TransportConfig, Option<LocalServerSupervisor>), RunCommandError> {
    let transport = TransportConfig::from_workflow(&runtime.workflow, &ProcessEnvironment)?;
    let local_server = &runtime.workflow.extensions.openhands.local_server;
    let supervisor_base_url = transport.managed_local_server_base_url()?;
    let supervised = supervisor_base_url.is_some() && local_server.enabled;
    if local_server.command.is_some() && !supervised {
        return Err(OpenHandsError::InvalidConfiguration {
            detail:
                "`openhands.local_server.command` requires a managed local OpenHands target with `local_server.enabled: true`"
                    .to_string(),
        }
        .into());
    }

    if !supervised {
        return Ok((transport, None));
    }
    let Some(supervisor_base_url) = supervisor_base_url else {
        return Ok((transport, None));
    };

    let tool_dir = runtime
        .tool_dir
        .clone()
        .ok_or(RunCommandError::MissingToolDir)?;
    let tooling = LocalServerTooling::load(tool_dir.clone()).map_err(|error| {
        RunCommandError::ToolingSetupRequired {
            tool_dir,
            detail: error.to_string(),
        }
    })?;
    let url =
        Url::parse(&supervisor_base_url).expect("validated managed supervisor URL should parse");
    let mut config = SupervisedServerConfig::new(tooling);
    config.command = local_server.command.clone();
    config.extra_env = local_server.env.clone();
    config.startup_timeout = Duration::from_millis(local_server.startup_timeout_ms);
    config.probe.path = local_server.readiness_probe_path.clone();
    config.port_override = Some(transport_port_override(&url)?);

    let mut supervisor = LocalServerSupervisor::new(SupervisorConfig::Supervised(Box::new(config)));
    let status = supervisor.start()?;
    let transport = TransportConfig::new(status.base_url).with_auth(transport.auth().clone());
    Ok((transport, Some(supervisor)))
}

impl TrackerBackend for RuntimeTrackerBackend {
    type Error = LinearError;

    async fn candidate_issues(
        &mut self,
    ) -> Result<Vec<crate::opensymphony_domain::TrackerIssue>, Self::Error> {
        self.client.candidate_issues().await
    }

    async fn terminal_issues(
        &mut self,
    ) -> Result<Vec<crate::opensymphony_domain::TrackerIssue>, Self::Error> {
        self.client.terminal_issues().await
    }

    async fn issue_states_by_ids(
        &mut self,
        issue_ids: &[String],
    ) -> Result<Vec<crate::opensymphony_domain::TrackerIssueStateSnapshot>, Self::Error> {
        self.client.issue_states_by_ids(issue_ids).await
    }
}

impl RuntimeWorkspaceBackend {
    pub(super) fn new(manager: Arc<WorkspaceManager>, workflow: &ResolvedWorkflow) -> Self {
        Self {
            manager,
            active_states: workflow
                .config
                .tracker
                .active_states
                .iter()
                .map(|state| normalized_state_name(state))
                .collect(),
            terminal_states: workflow
                .config
                .tracker
                .terminal_states
                .iter()
                .map(|state| normalized_state_name(state))
                .collect(),
        }
    }
}

impl WorkspaceBackend for RuntimeWorkspaceBackend {
    type Error = CliWorkspaceError;

    async fn ensure_workspace(
        &mut self,
        issue: &NormalizedIssue,
        _observed_at: TimestampMs,
    ) -> Result<crate::opensymphony_domain::WorkspaceRecord, Self::Error> {
        let ensured = self.manager.ensure(&issue_descriptor(issue)).await?;
        Ok(crate::opensymphony_domain::WorkspaceRecord {
            path: ensured.handle.workspace_path().to_path_buf(),
            workspace_key: WorkspaceKey::new(ensured.handle.workspace_key().to_string())?,
            created_now: ensured.created,
            created_at: Some(datetime_to_timestamp_ms(ensured.issue_manifest.created_at)),
            updated_at: Some(datetime_to_timestamp_ms(ensured.issue_manifest.updated_at)),
            last_seen_tracker_refresh_at: ensured
                .issue_manifest
                .last_seen_tracker_refresh_at
                .map(datetime_to_timestamp_ms),
        })
    }

    async fn recover_workspaces(&mut self) -> Result<Vec<RecoveryRecord>, Self::Error> {
        let mut recoveries = Vec::new();
        for (handle, manifest) in self.manager.list_all_workspaces().await? {
            let run_manifest = self.manager.load_run_manifest(&handle).await?;
            let had_in_flight_run = run_manifest.as_ref().is_some_and(|run| {
                matches!(
                    run.status,
                    RunStatus::Preparing | RunStatus::Prepared | RunStatus::Running
                )
            });

            recoveries.push(RecoveryRecord {
                issue: normalized_issue_from_manifest(
                    &manifest,
                    &self.active_states,
                    &self.terminal_states,
                )?,
                workspace: crate::opensymphony_domain::WorkspaceRecord {
                    path: handle.workspace_path().to_path_buf(),
                    workspace_key: WorkspaceKey::new(handle.workspace_key().to_string())?,
                    created_now: false,
                    created_at: Some(datetime_to_timestamp_ms(manifest.created_at)),
                    updated_at: Some(datetime_to_timestamp_ms(manifest.updated_at)),
                    last_seen_tracker_refresh_at: manifest
                        .last_seen_tracker_refresh_at
                        .map(datetime_to_timestamp_ms),
                },
                had_in_flight_run,
            });
        }
        Ok(recoveries)
    }

    async fn cleanup_workspace(
        &mut self,
        workspace: &crate::opensymphony_domain::WorkspaceRecord,
        terminal: bool,
    ) -> Result<(), Self::Error> {
        if terminal {
            match fs::remove_dir_all(&workspace.path).await {
                Ok(()) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(source) => {
                    return Err(CliWorkspaceError::RemoveWorkspace {
                        path: workspace.path.clone(),
                        source,
                    });
                }
            }
        }
        Ok(())
    }
}

impl RuntimeWorkerBackend {
    pub(super) fn new(
        client: OpenHandsClient,
        workflow: Arc<ResolvedWorkflow>,
        workspace_manager: Arc<WorkspaceManager>,
    ) -> Self {
        let (updates_tx, updates_rx) = mpsc::unbounded_channel();
        let workpad_comment_source = match build_linear_client(&workflow) {
            Ok(client) => {
                Some(Arc::new(LinearWorkpadCommentSource { client })
                    as Arc<dyn WorkpadCommentSource>)
            }
            Err(error) => {
                tracing::warn!(
                    %error,
                    "failed to build the Linear workpad comment source; config-drift rehydrate prompts will fall back to workspace-only recovery"
                );
                None
            }
        };
        Self {
            client,
            workflow: workflow.clone(),
            workspace_manager,
            runner_config: IssueSessionRunnerConfig::from_workflow(&workflow),
            workpad_comment_source,
            launch_timeout: DEFAULT_WORKER_LAUNCH_TIMEOUT,
            updates_tx,
            updates_rx,
            tasks: HashMap::new(),
        }
    }

    fn abort_tracked_task(&mut self, worker_id: &str) {
        if let Some(task) = self.tasks.remove(worker_id) {
            task.handle.abort();
        }
    }

    fn abort_all_tracked_tasks(&mut self) {
        let active_count = self.tasks.len();
        if active_count == 0 {
            return;
        }

        tracing::info!(
            active_count,
            "aborting tracked worker tasks during backend shutdown"
        );
        for (_, task) in self.tasks.drain() {
            task.handle.abort();
        }
    }

    fn spawn_worker_task(&mut self, request: WorkerStartRequest) -> PendingLaunch {
        let mut runner = IssueSessionRunner::new(self.client.clone(), self.runner_config.clone());
        if let Some(source) = self.workpad_comment_source.clone() {
            runner = runner.with_workpad_comment_source(source);
        }
        let workspace_manager = self.workspace_manager.clone();
        let workflow = self.workflow.clone();
        let updates_tx = self.updates_tx.clone();
        let worker_id = request.run.worker_id.clone();
        let observer_worker_id = worker_id.clone();
        let finished_worker_id = worker_id.clone();
        let (launch_tx, launch_rx) = oneshot::channel();
        let run = request.run.clone();
        let issue = request.issue.clone();
        let launch_worker_id = worker_id.clone();
        let handle = tokio::spawn(async move {
            let mut launch_tx = Some(launch_tx);
            let ensured = match workspace_manager.ensure(&issue_descriptor(&issue)).await {
                Ok(ensured) => ensured,
                Err(error) => {
                    report_launch_failure(
                        &mut launch_tx,
                        format!("failed to ensure workspace: {error}"),
                    );
                    return;
                }
            };
            let attempt = run.attempt.map(|attempt| attempt.get()).unwrap_or(1);
            let run_descriptor = RunDescriptor::new(format!("run-{launch_worker_id}"), attempt);
            let mut run_manifest = match workspace_manager
                .start_run(&ensured.handle, &run_descriptor)
                .await
            {
                Ok(run_manifest) => run_manifest,
                Err(error) => {
                    report_launch_failure(
                        &mut launch_tx,
                        format!("failed to prepare workspace run: {error}"),
                    );
                    return;
                }
            };

            let mut observer = SchedulerObserver {
                worker_id: observer_worker_id.to_string(),
                launch_tx,
                updates_tx: updates_tx.clone(),
            };
            let result = runner
                .run_with_observer(
                    &workspace_manager,
                    &ensured.handle,
                    &mut run_manifest,
                    &issue,
                    &run,
                    &workflow,
                    &mut observer,
                )
                .await;

            if observer.launch_tx.is_some() {
                report_launch_failure(
                    &mut observer.launch_tx,
                    pending_launch_failure_detail(&result),
                );
                return;
            }

            let outcome = match result {
                Ok(result) => result.worker_outcome,
                Err(error) => WorkerOutcomeRecord::from_run(
                    &run,
                    WorkerOutcomeKind::Failed,
                    now_timestamp(),
                    Some("worker task failed before completing".to_string()),
                    Some(error.to_string()),
                ),
            };
            let _ = updates_tx.send(WorkerUpdate::Finished {
                worker_id: finished_worker_id.clone(),
                outcome,
            });
        });

        self.tasks.insert(
            worker_id.to_string(),
            ActiveWorkerTask {
                handle,
                run: request.run,
            },
        );

        PendingLaunch {
            worker_id: worker_id.to_string(),
            launch_rx,
        }
    }

    async fn resolve_launch_result(
        &mut self,
        worker_id: &str,
        result: Result<
            Result<LaunchReport, oneshot::error::RecvError>,
            tokio::time::error::Elapsed,
        >,
    ) -> Result<WorkerLaunch, CliWorkerError> {
        match result {
            Ok(Ok(LaunchReport::Conversation(conversation))) => Ok(WorkerLaunch {
                conversation: *conversation,
            }),
            Ok(Ok(LaunchReport::Failed(detail))) => {
                if let Some(task) = self.tasks.remove(worker_id) {
                    task.handle.await?;
                }
                Err(CliWorkerError::LaunchFailed(detail))
            }
            Ok(Err(_)) => {
                if let Some(task) = self.tasks.remove(worker_id) {
                    task.handle.await?;
                }
                Err(CliWorkerError::LaunchChannelClosed)
            }
            Err(_) => {
                self.abort_tracked_task(worker_id);
                Err(CliWorkerError::LaunchTimeout(self.launch_timeout))
            }
        }
    }
}

impl Drop for RuntimeWorkerBackend {
    fn drop(&mut self) {
        self.abort_all_tracked_tasks();
    }
}

fn transport_port_override(url: &Url) -> Result<u16, RunCommandError> {
    url.port_or_known_default()
        .ok_or_else(|| RunCommandError::MissingTransportPort {
            value: url.as_str().to_string(),
        })
}

fn report_launch_failure(
    launch_tx: &mut Option<oneshot::Sender<LaunchReport>>,
    detail: impl Into<String>,
) {
    if let Some(sender) = launch_tx.take() {
        let _ = sender.send(LaunchReport::Failed(detail.into()));
    }
}

fn pending_launch_failure_detail(result: &Result<IssueSessionResult, IssueSessionError>) -> String {
    match result {
        Ok(result) => {
            let detail = result
                .worker_outcome
                .error
                .clone()
                .or_else(|| result.worker_outcome.summary.clone())
                .unwrap_or_else(|| {
                    "worker finished before reporting a conversation launch".to_string()
                });
            format!("worker finished before reporting a conversation launch: {detail}")
        }
        Err(error) => format!("worker failed before reporting a conversation launch: {error}"),
    }
}

impl WorkerBackend for RuntimeWorkerBackend {
    type Error = CliWorkerError;

    async fn start_worker(
        &mut self,
        request: WorkerStartRequest,
    ) -> Result<WorkerLaunch, Self::Error> {
        let pending = self.spawn_worker_task(request);
        let worker_id = pending.worker_id.clone();
        self.resolve_launch_result(
            &worker_id,
            timeout(self.launch_timeout, pending.launch_rx).await,
        )
        .await
    }

    async fn start_workers(
        &mut self,
        requests: Vec<WorkerStartRequest>,
    ) -> Vec<Result<WorkerLaunch, Self::Error>> {
        let pending = requests
            .into_iter()
            .map(|request| self.spawn_worker_task(request))
            .collect::<Vec<_>>();
        let ordered_worker_ids = pending
            .iter()
            .map(|launch| launch.worker_id.clone())
            .collect::<Vec<_>>();

        let mut waiters = Vec::with_capacity(pending.len());
        for launch in pending {
            let worker_id = launch.worker_id;
            let timeout_duration = self.launch_timeout;
            let rx = launch.launch_rx;
            let worker_id_for_task = worker_id.clone();
            let handle =
                tokio::spawn(
                    async move { (worker_id_for_task, timeout(timeout_duration, rx).await) },
                );
            waiters.push((worker_id, handle));
        }

        let mut completed = HashMap::new();
        for (worker_id, handle) in waiters {
            match handle.await {
                Ok((worker_id, outcome)) => {
                    completed.insert(worker_id, outcome);
                }
                Err(join_error) => {
                    tracing::error!(error = %join_error, "worker launch waiter task failed");
                    completed.insert(
                        worker_id,
                        Ok(Ok(LaunchReport::Failed(format!(
                            "worker launch waiter task failed: {join_error}"
                        )))),
                    );
                }
            }
        }

        let mut launches = Vec::with_capacity(ordered_worker_ids.len());
        for worker_id in ordered_worker_ids {
            let outcome = completed
                .remove(&worker_id)
                .unwrap_or(Ok(Ok(LaunchReport::Failed(
                    "worker launch waiter finished without a result".to_string(),
                ))));
            launches.push(self.resolve_launch_result(&worker_id, outcome).await);
        }
        launches
    }

    async fn poll_updates(&mut self) -> Result<Vec<WorkerUpdate>, Self::Error> {
        let mut updates = Vec::new();
        while let Ok(update) = self.updates_rx.try_recv() {
            if let WorkerUpdate::Finished { worker_id, .. } = &update
                && let Some(task) = self.tasks.remove(worker_id.as_str())
            {
                let _ = task.handle.await;
            }
            updates.push(update);
        }

        let finished = self
            .tasks
            .iter()
            .filter_map(|(worker_id, task)| task.handle.is_finished().then_some(worker_id.clone()))
            .collect::<Vec<_>>();
        for worker_id in finished {
            let Some(task) = self.tasks.remove(worker_id.as_str()) else {
                continue;
            };
            if let Err(error) = task.handle.await {
                updates.push(WorkerUpdate::Finished {
                    worker_id: crate::opensymphony_domain::WorkerId::new(worker_id)
                        .expect("worker id should remain valid"),
                    outcome: WorkerOutcomeRecord::from_run(
                        &task.run,
                        WorkerOutcomeKind::Failed,
                        now_timestamp(),
                        Some("worker task terminated unexpectedly".to_string()),
                        Some(error.to_string()),
                    ),
                });
            }
        }

        Ok(updates)
    }

    async fn abort_worker(
        &mut self,
        worker_id: &crate::opensymphony_domain::WorkerId,
        _reason: WorkerAbortReason,
    ) -> Result<(), Self::Error> {
        self.abort_tracked_task(worker_id.as_str());
        Ok(())
    }
}

fn normalized_state_name(name: &str) -> String {
    name.trim().to_ascii_lowercase()
}

fn issue_state_category(
    name: &str,
    active_states: &HashSet<String>,
    terminal_states: &HashSet<String>,
) -> IssueStateCategory {
    let normalized = normalized_state_name(name);
    if terminal_states.contains(&normalized) {
        IssueStateCategory::Terminal
    } else if active_states.contains(&normalized) {
        IssueStateCategory::Active
    } else {
        IssueStateCategory::NonActive
    }
}

fn normalized_issue_from_manifest(
    manifest: &crate::opensymphony_workspace::IssueManifest,
    active_states: &HashSet<String>,
    terminal_states: &HashSet<String>,
) -> Result<NormalizedIssue, CliWorkspaceError> {
    Ok(NormalizedIssue {
        id: IssueId::new(manifest.issue_id.clone())?,
        identifier: IssueIdentifier::new(manifest.identifier.clone())?,
        title: manifest.title.clone(),
        description: None,
        priority: None,
        state: IssueState {
            id: None,
            name: manifest.current_state.clone(),
            category: issue_state_category(&manifest.current_state, active_states, terminal_states),
        },
        branch_name: None,
        url: None,
        labels: Vec::new(),
        parent_id: None,
        blocked_by: Vec::new(),
        sub_issues: Vec::new(),
        created_at: Some(datetime_to_timestamp_ms(manifest.created_at)),
        updated_at: Some(datetime_to_timestamp_ms(manifest.updated_at)),
    })
}

fn issue_descriptor(issue: &NormalizedIssue) -> IssueDescriptor {
    IssueDescriptor {
        issue_id: issue.id.to_string(),
        identifier: issue.identifier.to_string(),
        title: issue.title.clone(),
        current_state: issue.state.name.clone(),
        last_seen_tracker_refresh_at: issue.updated_at.map(timestamp_to_datetime),
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, future::pending, path::Path};

    use crate::opensymphony_domain::{
        IssueId, IssueIdentifier, IssueState, IssueStateCategory, RunAttempt, WorkerId,
        WorkspaceKey,
    };
    use crate::opensymphony_workflow::WorkflowDefinition;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn transport_port_override_reports_missing_port_separately() {
        let url = Url::parse("custom-scheme://openhands.local").expect("URL should parse");

        let error = transport_port_override(&url).expect_err("custom scheme should need a port");

        assert!(matches!(
            error,
            RunCommandError::MissingTransportPort { value }
                if value == "custom-scheme://openhands.local"
        ));
    }

    #[tokio::test]
    async fn start_worker_reports_workspace_setup_failures_before_launch() {
        let tempdir = TempDir::new().expect("tempdir should exist");
        let blocked_root = tempdir.path().join("workspace-root");
        fs::write(&blocked_root, "not a directory").expect("blocking file should be created");

        let workflow = Arc::new(sample_workflow(tempdir.path(), &blocked_root));
        let workspace_manager = Arc::new(
            WorkspaceManager::new(build_workspace_manager_config(&workflow))
                .expect("workspace manager should be constructed"),
        );
        let mut backend = RuntimeWorkerBackend::new(
            OpenHandsClient::new(TransportConfig::new("http://127.0.0.1:1")),
            workflow,
            workspace_manager,
        );

        let issue = sample_issue();
        let workspace = sample_workspace(&blocked_root);
        let run = RunAttempt::new(
            WorkerId::new("worker-1").expect("worker id should be valid"),
            issue.id.clone(),
            issue.identifier.clone(),
            workspace.path.clone(),
            TimestampMs::new(1),
            None,
            8,
        );

        let error = backend
            .start_worker(WorkerStartRequest {
                issue,
                workspace,
                run,
            })
            .await
            .expect_err("workspace setup failure should fail the launch immediately");

        assert!(matches!(
            error,
            CliWorkerError::LaunchFailed(detail)
                if detail.contains("failed to ensure workspace")
        ));
        assert!(
            backend.tasks.is_empty(),
            "failed launches should not leave worker tasks behind"
        );
        assert!(
            backend
                .poll_updates()
                .await
                .expect("poll_updates should succeed")
                .is_empty(),
            "launch failures should be surfaced through start_worker, not queued as runtime updates",
        );
    }

    #[tokio::test]
    async fn recover_workspaces_loads_managed_manifests_and_inflight_runs() {
        let tempdir = TempDir::new().expect("tempdir should exist");
        let workspace_root = tempdir.path().join("workspace-root");
        fs::create_dir_all(&workspace_root).expect("workspace root should be created");

        let workflow = sample_workflow(tempdir.path(), &workspace_root);
        let workspace_manager = Arc::new(
            WorkspaceManager::new(build_workspace_manager_config(&workflow))
                .expect("workspace manager should be constructed"),
        );
        let issue = sample_issue();
        let ensured = workspace_manager
            .ensure(&issue_descriptor(&issue))
            .await
            .expect("workspace should be created");
        workspace_manager
            .start_run(&ensured.handle, &RunDescriptor::new("run-recovery", 2))
            .await
            .expect("run manifest should be written");

        let mut backend = RuntimeWorkspaceBackend::new(workspace_manager, &workflow);
        let recoveries = backend
            .recover_workspaces()
            .await
            .expect("workspace recovery should succeed");

        assert_eq!(recoveries.len(), 1);
        let recovered = &recoveries[0];
        assert_eq!(
            recovered.issue.identifier.to_string(),
            issue.identifier.to_string()
        );
        assert_eq!(recovered.issue.state.category, IssueStateCategory::Active);
        assert!(recovered.had_in_flight_run);
        assert_eq!(recovered.workspace.path, ensured.handle.workspace_path());
    }

    #[tokio::test]
    async fn build_runtime_transport_rejects_launcher_overrides_for_external_targets() {
        let tempdir = TempDir::new().expect("tempdir should exist");
        let workflow = WorkflowDefinition::parse(
            r#"---
tracker:
  kind: linear
  endpoint: http://127.0.0.1:3001/graphql
  api_key: test-linear-key
  project_slug: sample-project
  active_states:
    - In Progress
  terminal_states:
    - Done
workspace:
  root: ./var/workspaces
openhands:
  transport:
    base_url: https://127.0.0.1:8000/runtime
  local_server:
    command:
      - bash
      - custom-run.sh
---

# Test Workflow

Run the scheduler.
"#,
        )
        .expect("workflow should parse")
        .resolve_with_process_env(tempdir.path())
        .expect("workflow should resolve");
        let runtime = RunRuntimeConfig {
            config_path: None,
            target_repo: tempdir.path().to_path_buf(),
            workflow_path: tempdir.path().join("WORKFLOW.md"),
            workflow,
            bind: "127.0.0.1:3000".parse().expect("bind should parse"),
            tool_dir: None,
        };

        let error = match build_runtime_transport(&runtime).await {
            Ok(_) => panic!("external targets should reject launcher overrides"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            RunCommandError::Transport(OpenHandsError::InvalidConfiguration { detail })
                if detail.contains("openhands.local_server.command")
        ));
    }

    #[tokio::test]
    async fn runtime_worker_backend_aborts_tracked_tasks_on_drop() {
        let tempdir = TempDir::new().expect("tempdir should exist");
        let workspace_root = tempdir.path().join("workspace-root");
        fs::create_dir_all(&workspace_root).expect("workspace root should be created");

        let workflow = Arc::new(sample_workflow(tempdir.path(), &workspace_root));
        let workspace_manager = Arc::new(
            WorkspaceManager::new(build_workspace_manager_config(&workflow))
                .expect("workspace manager should be constructed"),
        );
        let mut backend = RuntimeWorkerBackend::new(
            OpenHandsClient::new(TransportConfig::new("http://127.0.0.1:1")),
            workflow,
            workspace_manager,
        );

        let workspace = sample_workspace(&workspace_root);
        let run = RunAttempt::new(
            WorkerId::new("worker-drop").expect("worker id should be valid"),
            IssueId::new("issue-drop").expect("issue id should be valid"),
            IssueIdentifier::new("COE-286").expect("issue identifier should be valid"),
            workspace.path.clone(),
            TimestampMs::new(1),
            None,
            8,
        );
        let (aborted_tx, aborted_rx) = oneshot::channel();
        let handle = tokio::spawn(async move {
            let _notifier = AbortNotifier(Some(aborted_tx));
            pending::<()>().await;
        });
        backend
            .tasks
            .insert("worker-drop".to_string(), ActiveWorkerTask { handle, run });

        drop(backend);

        match timeout(Duration::from_millis(100), aborted_rx).await {
            Ok(Ok(())) | Ok(Err(_)) => {}
            Err(_) => panic!("dropping the backend should abort tracked tasks"),
        }
    }

    fn sample_workflow(base_dir: &Path, workspace_root: &Path) -> ResolvedWorkflow {
        let source = format!(
            "---\ntracker:\n  kind: linear\n  endpoint: http://127.0.0.1:3001/graphql\n  api_key: test-linear-key\n  project_slug: sample-project\n  active_states:\n    - In Progress\n  terminal_states:\n    - Done\nworkspace:\n  root: {}\nopenhands:\n  transport:\n    base_url: http://127.0.0.1:1\n    session_api_key_env: OPENHANDS_API_KEY\n---\n\n# Test Workflow\n\nRun the scheduler.\n",
            workspace_root.display()
        );
        WorkflowDefinition::parse(&source)
            .expect("workflow should parse")
            .resolve_with_process_env(base_dir)
            .expect("workflow should resolve")
    }

    fn sample_issue() -> NormalizedIssue {
        NormalizedIssue {
            id: IssueId::new("issue-1").expect("issue id should be valid"),
            identifier: IssueIdentifier::new("COE-284").expect("issue identifier should be valid"),
            title: "Test issue".to_string(),
            description: None,
            priority: None,
            state: IssueState {
                id: None,
                name: "In Progress".to_string(),
                category: IssueStateCategory::Active,
            },
            branch_name: None,
            url: None,
            labels: Vec::new(),
            parent_id: None,
            blocked_by: Vec::new(),
            sub_issues: Vec::new(),
            created_at: None,
            updated_at: None,
        }
    }

    fn sample_workspace(workspace_root: &Path) -> crate::opensymphony_domain::WorkspaceRecord {
        crate::opensymphony_domain::WorkspaceRecord {
            path: workspace_root.join("COE-284"),
            workspace_key: WorkspaceKey::new("COE-284").expect("workspace key should be valid"),
            created_now: false,
            created_at: None,
            updated_at: None,
            last_seen_tracker_refresh_at: None,
        }
    }

    struct AbortNotifier(Option<oneshot::Sender<()>>);

    impl Drop for AbortNotifier {
        fn drop(&mut self) {
            if let Some(sender) = self.0.take() {
                let _ = sender.send(());
            }
        }
    }
}