codex-multi-workspace 0.3.3

Run Codex CLI in Docker across saved single-folder or multi-folder workspaces.
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
use std::ffi::OsStr;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, anyhow};

/// Saved workspace manifest entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceEntry {
    name: String,
    path: PathBuf,
}

impl WorkspaceEntry {
    /// Create a saved workspace manifest entry.
    ///
    /// # Arguments
    ///
    /// * `name` - Workspace name derived from the manifest file stem.
    /// * `path` - Manifest file path.
    ///
    /// # Returns
    ///
    /// A workspace entry.
    #[must_use]
    pub fn new(name: String, path: PathBuf) -> Self {
        Self { name, path }
    }

    /// Return the workspace name.
    ///
    /// # Returns
    ///
    /// Workspace name shown by `workspace ls`.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the manifest path.
    ///
    /// # Returns
    ///
    /// Path to the saved workspace manifest.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }
}

/// Return the saved workspace manifest directory.
///
/// # Arguments
///
/// * `sessions_root` - codex-ws state root.
///
/// # Returns
///
/// Directory containing saved workspace manifests.
#[must_use]
pub fn workspace_config_dir(sessions_root: &Path) -> PathBuf {
    sessions_root.join("config").join("workspace")
}

/// Return the manifest path for a saved workspace name.
///
/// # Arguments
///
/// * `sessions_root` - codex-ws state root.
/// * `workspace_name` - Saved workspace name.
///
/// # Returns
///
/// Path to the saved workspace manifest.
///
/// # Errors
///
/// Returns an error when the workspace name is empty or contains path separators.
pub fn workspace_manifest_path(sessions_root: &Path, workspace_name: &str) -> Result<PathBuf> {
    validate_workspace_name(workspace_name)?;
    Ok(workspace_config_dir(sessions_root).join(format!("{workspace_name}.yaml")))
}

/// Resolve a `run --workspace` value to a manifest path.
///
/// Path-like values are expanded and returned as paths. Bare workspace names resolve under
/// `~/.codex-ws/config/workspace` relative to the configured sessions root.
///
/// # Arguments
///
/// * `workspace` - User-provided workspace name or path.
/// * `sessions_root` - codex-ws state root.
///
/// # Returns
///
/// Manifest path to load.
///
/// # Errors
///
/// Returns an error when a bare workspace name is invalid.
pub fn resolve_workspace_path(workspace: PathBuf, sessions_root: &Path) -> Result<PathBuf> {
    if is_path_like(&workspace) {
        return Ok(expand_home_path(workspace));
    }

    let Some(workspace_name) = workspace.to_str() else {
        return Ok(workspace);
    };
    workspace_manifest_path(sessions_root, workspace_name)
}

/// List saved workspace manifests.
///
/// # Arguments
///
/// * `sessions_root` - codex-ws state root.
///
/// # Returns
///
/// Sorted workspace entries for `.yaml` files under the workspace config directory.
///
/// # Errors
///
/// Returns an error when the workspace config directory cannot be read.
pub fn list_workspaces(sessions_root: &Path) -> Result<Vec<WorkspaceEntry>> {
    let config_dir = workspace_config_dir(sessions_root);
    if !config_dir.exists() {
        return Ok(Vec::new());
    }

    let mut entries = Vec::new();
    for entry in fs::read_dir(&config_dir).with_context(|| {
        format!(
            "failed to read workspace config directory '{}'",
            config_dir.display()
        )
    })? {
        let entry = entry.with_context(|| {
            format!(
                "failed to read entry in workspace config directory '{}'",
                config_dir.display()
            )
        })?;
        let path = entry.path();
        if path.extension() != Some(OsStr::new("yaml")) {
            continue;
        }
        let Some(name) = path.file_stem().and_then(OsStr::to_str) else {
            continue;
        };
        entries.push(WorkspaceEntry::new(name.to_owned(), path));
    }

    entries.sort_by(|left, right| left.name().cmp(right.name()));
    Ok(entries)
}

/// Create a saved workspace manifest if needed and open it in an editor.
///
/// # Arguments
///
/// * `sessions_root` - codex-ws state root.
/// * `workspace_name` - Workspace name used for the manifest file.
///
/// # Returns
///
/// Path to the saved workspace manifest.
///
/// # Errors
///
/// Returns an error when the file cannot be created or the editor exits unsuccessfully.
pub fn add_workspace(sessions_root: &Path, workspace_name: &str) -> Result<PathBuf> {
    add_workspace_with_editor(sessions_root, workspace_name, selected_editor())
}

fn add_workspace_with_editor(
    sessions_root: &Path,
    workspace_name: &str,
    editor: String,
) -> Result<PathBuf> {
    let manifest_path = workspace_manifest_path(sessions_root, workspace_name)?;
    if let Some(parent) = manifest_path.parent() {
        fs::create_dir_all(parent).with_context(|| {
            format!(
                "failed to create workspace config directory '{}'",
                parent.display()
            )
        })?;
    }

    if !manifest_path.exists() {
        fs::write(&manifest_path, workspace_template(workspace_name)).with_context(|| {
            format!(
                "failed to write workspace manifest template '{}'",
                manifest_path.display()
            )
        })?;
    }

    open_editor(&editor, &manifest_path)?;
    Ok(manifest_path)
}

fn workspace_template(workspace_name: &str) -> String {
    format!(
        r#"# Workspace manifest for codex-ws.
# Replace the folder examples with absolute host paths.
name: {workspace_name}
folders:
  - /absolute/path/to/project

# The container has network access by default so Codex can reach the model provider.
# Advanced offline-only configuration:
# sandbox:
#   network: false

# Optional declarative runtime setup for the lightweight Ubuntu image.
# runtime:
#   python: "3.13"
#   node: "22"
#   go: "1.24"
#   rust: "1.86"
#   java: "21"
#   clang: "20"
#   c: "20"
#   cpp: "20"
#   ruby: "3.4"
#   php: "8.4"
#   deno: "2"
#   bun: "1"
#   zig: "0.14"
#   dotnet: "9"
#   apt:
#     - build-essential
#   setup:
#     - python -m pip install --user maturin
"#
    )
}

fn open_editor(editor: &str, path: &Path) -> Result<()> {
    let status = Command::new(editor)
        .arg(path)
        .status()
        .with_context(|| format!("failed to launch editor '{editor}'"))?;
    if status.success() {
        return Ok(());
    }

    Err(anyhow!(
        "editor '{editor}' exited unsuccessfully while editing '{}'",
        path.display()
    ))
}

fn selected_editor() -> String {
    std::env::var("VISUAL")
        .ok()
        .filter(|editor| !editor.trim().is_empty())
        .or_else(|| {
            std::env::var("EDITOR")
                .ok()
                .filter(|editor| !editor.trim().is_empty())
        })
        .unwrap_or_else(|| "vim".to_owned())
}

fn validate_workspace_name(workspace_name: &str) -> Result<()> {
    if workspace_name.trim().is_empty() {
        return Err(anyhow!("workspace name cannot be empty"));
    }
    if Path::new(workspace_name)
        .components()
        .any(|component| matches!(component, Component::ParentDir | Component::RootDir))
        || workspace_name.contains('/')
        || workspace_name.contains('\\')
    {
        return Err(anyhow!(
            "workspace name '{workspace_name}' cannot contain path separators"
        ));
    }
    Ok(())
}

fn is_path_like(path: &Path) -> bool {
    if path.is_absolute() {
        return true;
    }
    let Some(path_text) = path.to_str() else {
        return true;
    };
    path_text == "~"
        || path_text.starts_with("~/")
        || path_text.starts_with("./")
        || path_text.starts_with("../")
        || path_text.contains('/')
        || path_text.contains('\\')
        || path.extension().is_some()
}

/// Expand a leading `~` in a path.
///
/// # Arguments
///
/// * `path` - Path that may start with `~` or `~/`.
///
/// # Returns
///
/// The path with a leading home-directory marker expanded when possible.
#[must_use]
pub fn expand_home_path(path: PathBuf) -> PathBuf {
    let Some(path_text) = path.to_str() else {
        return path;
    };

    if path_text == "~" {
        return home_dir().unwrap_or(path);
    }

    if let Some(rest) = path_text.strip_prefix("~/")
        && let Some(home) = home_dir()
    {
        return home.join(rest);
    }

    path
}

fn home_dir() -> Option<PathBuf> {
    directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf())
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    static TEMP_DIR_COUNTER: AtomicUsize = AtomicUsize::new(0);

    #[test]
    fn workspace_manifest_path_uses_config_workspace_directory() {
        let path = workspace_manifest_path(Path::new("/host/.codex-ws"), "backend")
            .expect("path should build");

        assert_eq!(
            path,
            PathBuf::from("/host/.codex-ws/config/workspace/backend.yaml")
        );
    }

    #[test]
    fn resolve_workspace_path_maps_names_to_saved_manifest_paths() {
        let path = resolve_workspace_path(PathBuf::from("backend"), Path::new("/host/.codex-ws"))
            .expect("path should resolve");

        assert_eq!(
            path,
            PathBuf::from("/host/.codex-ws/config/workspace/backend.yaml")
        );
    }

    #[test]
    fn resolve_workspace_path_keeps_path_like_values() {
        let path = resolve_workspace_path(
            PathBuf::from("/tmp/workspace.yaml"),
            Path::new("/host/.codex-ws"),
        )
        .expect("path should resolve");

        assert_eq!(path, PathBuf::from("/tmp/workspace.yaml"));
    }

    #[test]
    fn list_workspaces_returns_sorted_yaml_files() {
        let temp_dir = TestTempDir::create();
        let config_dir = workspace_config_dir(temp_dir.path());
        fs::create_dir_all(&config_dir).expect("config dir should be created");
        fs::write(config_dir.join("zeta.yaml"), "").expect("workspace should be written");
        fs::write(config_dir.join("alpha.yaml"), "").expect("workspace should be written");
        fs::write(config_dir.join("ignored.txt"), "").expect("ignored file should be written");

        let entries = list_workspaces(temp_dir.path()).expect("workspaces should list");

        assert_eq!(
            entries
                .iter()
                .map(|entry| entry.name().to_owned())
                .collect::<Vec<_>>(),
            vec!["alpha".to_owned(), "zeta".to_owned()]
        );
    }

    #[test]
    fn add_workspace_writes_template_without_overwriting_existing_file() {
        let temp_dir = TestTempDir::create();
        let editor = "true".to_owned();
        let path = add_workspace_with_editor(temp_dir.path(), "backend", editor.clone())
            .expect("workspace should be added");

        let first_content = fs::read_to_string(&path).expect("workspace should be readable");
        assert!(first_content.contains("name: backend"));

        fs::write(&path, "name: custom\n").expect("workspace should be overwritten for test");
        add_workspace_with_editor(temp_dir.path(), "backend", editor)
            .expect("existing workspace should open");

        assert_eq!(
            fs::read_to_string(&path).expect("workspace should be readable"),
            "name: custom\n"
        );
    }

    #[derive(Debug)]
    struct TestTempDir {
        path: PathBuf,
    }

    impl TestTempDir {
        fn create() -> Self {
            let counter = TEMP_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
            let timestamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system clock should be after Unix epoch")
                .as_nanos();
            let path = std::env::temp_dir().join(format!(
                "codex-ws-workspace-test-{}-{timestamp}-{counter}",
                std::process::id()
            ));
            fs::create_dir(&path).expect("temporary test directory should be created");
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TestTempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }
}