> ## Documentation Index
> Fetch the complete documentation index at: https://desme.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Session Management

> Manually start, save, serve, and load debug sessions for full control over the session lifecycle.

The capture helpers (`capture`, `capture_to_file`, `capture_and_serve`) cover most use cases, but sometimes you need finer control — for example, interleaving multiple traced phases, conditionally saving only on failure, or loading a previously recorded session. The session management functions let you do all of this explicitly.

## When to use manual management

Use the manual API when you need to:

* Run instrumented code across multiple separate call sites and collect it all into one session
* Conditionally persist a session (e.g. only on error)
* Load a saved `.json` file or a directory of session files for programmatic inspection
* Combine session collection with custom error handling or structured logging

For simpler one-shot captures, the [Capture API](https://desme.mintlify.site/api/capture.md) is less code.

***

## `dbgflow::init_session`

```rust theme={null}
pub fn init_session(title: impl Into<String>)
```

Starts a fresh in-memory session. Any previously active session is discarded. Instrumented functions (`#[trace]`, `#[ui_debug]`) called after this point record their events into this new session.

**Parameters**

| Parameter | Type | Description |
| - | - | - |
| `title` | `impl Into<String>` | Display name for the session in the UI |

**Returns** nothing.

> [!NOTE]
>
> Calling `init_session` again at any point discards the previous session and starts a new one. If you need to preserve the existing session, call `save_current_session` first.

***

## `dbgflow::save_current_session`

```rust theme={null}
pub fn save_current_session(path: impl AsRef<Path>) -> std::io::Result<()>
```

Writes the current in-memory session to a JSON file at the given path. The session remains active in memory after saving; you can continue running instrumented code and call `save_current_session` again to overwrite or save to a different path.

**Parameters**

| Parameter | Type | Description |
| - | - | - |
| `path` | `impl AsRef<Path>` | Destination path for the JSON file |

**Returns** `std::io::Result<()>` — `Ok(())` on success, or an `Err` if the file cannot be written.

***

## `dbgflow::serve_current_session`

```rust theme={null}
pub fn serve_current_session(host: &str, port: u16) -> std::io::Result<()>
```

Serves the current in-memory session over the embedded HTTP server. Opens the interactive graph UI in your browser. This call **blocks** until the server is stopped.

**Parameters**

| Parameter | Type | Description |
| - | - | - |
| `host` | `&str` | Host address to bind (e.g. `"127.0.0.1"`) |
| `port` | `u16` | Port to listen on (e.g. `3000`) |

**Returns** `std::io::Result<()>` — `Ok(())` when the server shuts down, or an `Err` if it fails to start.

***

## `dbgflow::load_saved_session`

```rust theme={null}
pub fn load_saved_session(path: impl AsRef<Path>) -> std::io::Result<Session>
```

Reads a previously saved session from disk and returns it as a `Session` value. The path can point to either a single `.json` file or a directory containing multiple `.json` files.

**Parameters**

| Parameter | Type | Description |
| - | - | - |
| `path` | `impl AsRef<Path>` | Path to a `.json` file or a directory of `.json` files |

**Returns** `std::io::Result<Session>` — the loaded (or merged) session on success.

### Loading a single file

```rust theme={null}
let session = dbgflow::load_saved_session("artifacts/session.json")?;
println!("Loaded session: {}", session.title);
println!("Nodes: {}", session.nodes.len());
```

### Loading a directory

When the path is a directory, `load_saved_session` reads every `.json` file in it, sorts them by filename, and merges them into a single `Session`. Each individual session becomes a separate pipeline in the merged result.

```rust theme={null}
let merged = dbgflow::load_saved_session("artifacts/test-sessions/run-1234/")?;
// merged.title is derived from the directory name and the number of sessions,
// e.g. "run-1234 (5 sessions)"
```

Node IDs, event sequence numbers, and call IDs are all re-namespaced during the merge so there are no collisions between sessions.

> [!TIP]
>
> This is the same merging behaviour that `dbgflow serve <directory>` uses on the CLI. You can use `load_saved_session` to inspect merged sessions programmatically — for example, to assert on aggregate node counts in integration tests.

***

## Full manual flow example

```rust theme={null}
use dbgflow::prelude::*;

#[ui_debug]
struct Pipeline {
    stage: String,
    items: Vec<String>,
}

impl Pipeline {
    fn new() -> Self {
        Self { stage: "init".into(), items: vec![] }
    }
}

#[trace]
fn ingest(pipeline: &mut Pipeline, raw: &str) {
    pipeline.items = raw.split(',').map(str::trim).map(str::to_owned).collect();
    pipeline.stage = "ingested".into();
    pipeline.emit_snapshot("items loaded");
}

#[trace]
fn transform(pipeline: &mut Pipeline) {
    pipeline.items = pipeline.items.iter().map(|s| s.to_uppercase()).collect();
    pipeline.stage = "transformed".into();
    pipeline.emit_snapshot("items uppercased");
}

fn main() -> std::io::Result<()> {
    // 1. Start a fresh session.
    dbgflow::init_session("data pipeline");

    // 2. Run instrumented code. Events are collected automatically.
    let mut pipeline = Pipeline::new();
    ingest(&mut pipeline, "alpha, beta, gamma");
    transform(&mut pipeline);

    // 3. Save the session to disk.
    std::fs::create_dir_all("artifacts")?;
    dbgflow::save_current_session("artifacts/session.json")?;
    println!("Session saved to artifacts/session.json");

    // 4. Optionally serve it for interactive inspection.
    // dbgflow::serve_current_session("127.0.0.1", 3000)?;

    Ok(())
}
```

You can also save and then load back the session in the same process:

```rust theme={null}
dbgflow::save_current_session("artifacts/session.json")?;

let session = dbgflow::load_saved_session("artifacts/session.json")?;
assert_eq!(session.nodes.len(), 2); // ingest + transform
```

***

## Manual management vs. capture helpers

| | `capture` / `capture_to_file` / `capture_and_serve` | Manual (`init_session` + `save` / `serve`) |
| - | - | - |
| Code volume | Less — one call wraps everything | More — explicit start, run, save steps |
| Multiple traced phases | Not directly — closure must contain all code | Yes — call `init_session` once, trace freely |
| Conditional save | Not supported | Save only when needed (e.g. on error) |
| Re-use saved session | No | Yes — use `load_saved_session` |
| Async-friendly | Closure must be `FnOnce()` | Works wherever `init_session` is called |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.