wsb 0.222.4636

Workspace - A tool suite for file operations, version management, and development workflow automation
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
use crate::prelude::*;
pub mod github;
pub mod handlers;
pub mod notes;
pub mod ops;
pub mod parser;
pub mod pricing;
pub mod search_sources;
pub mod sse;
pub mod state;
pub mod sync;

use crate::fleet::config::gitmodules::validate_gitmodules_structure;
use anyhow::{bail, Context, Result};
use axum::{
    body::{boxed, Full},
    http::{header, StatusCode, Uri},
    response::{IntoResponse, Response},
    routing::{delete, get, patch, post, put},
    Router,
};
use rust_embed::RustEmbed;
use std::env;
use std::net::{SocketAddr, TcpListener};
use tower_http::cors::CorsLayer;

use crate::app::AppContext;
use crate::logging::{set_log_broadcast, LogLine, LogRingBuffer};
use state::WebState;

#[derive(RustEmbed)]
#[folder = "frontend/dist"]
struct FrontendAssets;

/// Start the web server on the given port.
pub async fn start_server(
    port: u16,
    debug: bool,
    parent_pid: Option<u32>,
    ctx: AppContext,
) -> Result<()> {
    let workspace_root = ctx.workspace_root.clone();
    validate_gitmodules_if_present(&workspace_root)?;
    env::set_current_dir(&workspace_root).with_context(|| {
        format!(
            "failed to switch process directory to workspace root {}",
            workspace_root.display()
        )
    })?;

    // Claim the port before doing any expensive setup (DB, threads, watchers).
    // If another wsb instance is already running on this port, bail out cleanly
    // rather than spawning duplicate background workers and hogging the CPU.
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let listener = TcpListener::bind(addr).with_context(|| {
        format!(
            "port {} is already in use — another wsb instance may be running. \
             Stop it first or choose a different port with --port.",
            port
        )
    })?;
    listener.set_nonblocking(true)?;

    if debug {
        eprintln!(
            "[wsb] starting web server on port {} from {}",
            port,
            workspace_root.display()
        );
    }

    let (log_tx, _) = tokio::sync::broadcast::channel::<LogLine>(1024);
    let log_ring = LogRingBuffer::new();
    set_log_broadcast(log_tx.clone(), log_ring.clone());

    let db = ctx.db.clone();
    let db_service = ctx.db_service.clone();
    let state = WebState::new(
        db,
        db_service,
        workspace_root.clone(),
        debug,
        port,
        log_tx,
        log_ring,
    )
    .await?;
    let app = create_router(state.clone());
    eprintln!("[wsb] listening on http://{}", addr);

    // Trigger initial sync through the actor — does not block server startup.
    let sync_handle = state.sync.clone();
    let ops_registry = state.ops.clone();
    tokio::spawn(async move {
        if let Err(e) = sync_handle
            .sync_incremental_tracked(Some(ops_registry))
            .await
        {
            eprintln!("[wsb] initial sync failed: {}", e);
        }
    });

    // Spawn the background git status watcher and the FS change detector.
    // The FS watcher nudges the scan loop on any .git dir change, so the
    // 3-second idle interval is only a fallback for missed events.
    handlers::fleet::spawn_git_watcher(state.clone());
    handlers::fleet::spawn_git_fs_watcher(state.clone());

    // Spawn workspace file watcher — emits file_changed events for any file
    // modified in the workspace so open editors can detect on-disk conflicts.
    spawn_workspace_file_watcher(state.clone());

    let watcher_state = state;
    tokio::spawn(async move {
        if let Err(e) = sync::start_watcher(watcher_state).await {
            eprintln!("[wsb] file watcher failed: {}", e);
        }
    });

    // If a parent PID was given, monitor it and exit as soon as it's gone.
    // This ensures wsb doesn't outlive the UI process that launched it.
    if let Some(pid) = parent_pid {
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_secs(2)).await;
                if !pid_is_alive(pid) {
                    eprintln!("[wsb] parent process {} exited — shutting down", pid);
                    std::process::exit(0);
                }
            }
        });
    }

    axum::Server::from_tcp(listener)?
        .serve(app.into_make_service())
        .await?;

    Ok(())
}

/// Check whether a process with the given PID is still running.
#[cfg(unix)]
fn pid_is_alive(pid: u32) -> bool {
    // SAFETY: kill(2) is always safe to call; we only send signal 0.
    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
    result == 0
}

/// Check whether a process with the given PID is still running.
#[cfg(windows)]
fn pid_is_alive(pid: u32) -> bool {
    let output = std::process::Command::new("tasklist")
        .args(["/FI", &format!("PID eq {}", pid), "/FO", "CSV", "/NH"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output();

    match output {
        Ok(output) if output.status.success() => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            stdout
                .lines()
                .any(|line| !line.trim().is_empty() && !line.starts_with("INFO:"))
        }
        _ => false,
    }
}

/// Resolve and check the workspace `wsb serve` should run in.
///
/// Callers must run this before the generic workspace guard, so a misplaced
/// `serve` gets a diagnostic naming what is missing and how to fix it.
pub fn validate_server_workspace(workspace: Option<PathBuf>) -> Result<PathBuf> {
    let start_dir = match workspace {
        Some(p) => std::fs::canonicalize(&p)
            .with_context(|| format!("workspace path '{}' does not exist", p.display()))?,
        None => env::current_dir().context("failed to get current directory")?,
    };
    let workspace_root = crate::git_backend::repo_root(&start_dir)
        .map_err(|_| serve_workspace_error_not_git(&start_dir))?;

    let required_paths = [workspace_root.join(".wsb")];

    let missing: Vec<String> = required_paths
        .iter()
        .filter(|path| !path.exists())
        .map(|path| {
            path.strip_prefix(&workspace_root)
                .unwrap_or(path)
                .display()
                .to_string()
        })
        .collect();

    if !missing.is_empty() {
        bail!(
            "cannot start `wsb serve` from '{}': '{}' is not an initialized wsb workspace.\n\
required workspace files are missing: {}\n\
initialize this repository first:\n  wsb init\n\
or change into an existing initialized workspace and rerun `wsb serve`.",
            start_dir.display(),
            workspace_root.display(),
            missing.join(", ")
        );
    }

    Ok(workspace_root)
}

fn serve_workspace_error_not_git(cwd: &Path) -> anyhow::Error {
    anyhow::anyhow!(
        "cannot start `wsb serve` from '{}': not inside a git repository.\n\
`wsb serve` only works inside an initialized wsb workspace.\n\
initialize this directory first:\n  wsb init\n\
or change into an existing workspace and rerun `wsb serve`.",
        cwd.display()
    )
}

fn validate_gitmodules_if_present(workspace_root: &Path) -> Result<()> {
    let path = workspace_root.join(".gitmodules");
    if !path.exists() {
        return Ok(());
    }
    let bytes =
        std::fs::read(&path).with_context(|| format!("failed to read {}", path.display()))?;
    validate_gitmodules_structure(&bytes, &path).map_err(|e| anyhow::anyhow!("{}", e))
}

/// Spawn a lightweight file watcher over the workspace root that emits
/// `FileChangedEvent` on `state.file_changed_tx` whenever a non-hidden file
/// is created, modified, or deleted. The git watcher already handles `.git/`
/// changes; this watcher covers ordinary workspace files so open editors can
/// detect on-disk conflicts.
fn spawn_workspace_file_watcher(state: WebState) {
    use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode, DebouncedEvent};
    use std::time::Duration;

    let workspace_root = state.workspace_root.clone();
    let tx = state.file_changed_tx.clone();
    let runtime_handle = tokio::runtime::Handle::current();

    std::thread::spawn(move || {
        let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::<Vec<DebouncedEvent>>(256);
        let rt = runtime_handle.clone();

        let mut debouncer = match new_debouncer(
            Duration::from_millis(300),
            move |result: Result<Vec<DebouncedEvent>, notify::Error>| match result {
                Ok(events) => {
                    let etx = event_tx.clone();
                    rt.spawn(async move {
                        let _ = etx.send(events).await;
                    });
                }
                Err(e) => {
                    eprintln!("[wsb] workspace file watcher error: {}", e);
                }
            },
        ) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("[wsb] failed to create workspace file watcher: {}", e);
                return;
            }
        };

        if let Err(e) = debouncer
            .watcher()
            .watch(&workspace_root, RecursiveMode::Recursive)
        {
            eprintln!(
                "[wsb] failed to watch workspace root {}: {}",
                workspace_root.display(),
                e
            );
            return;
        }

        let root_clone = workspace_root.clone();
        runtime_handle.block_on(async move {
            while let Some(events) = event_rx.recv().await {
                for event in events {
                    let path = &event.path;

                    // Skip hidden files, .git directories, and build artifacts.
                    let rel = match path.strip_prefix(&root_clone) {
                        Ok(r) => r,
                        Err(_) => continue,
                    };
                    let rel_str = rel.to_string_lossy();
                    if rel_str.split('/').any(|seg| seg.starts_with('.')) {
                        continue;
                    }
                    if rel_str.starts_with("target/") {
                        continue;
                    }

                    let mtime_secs = std::fs::metadata(path)
                        .ok()
                        .and_then(|m| m.modified().ok())
                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                        .map(|d| d.as_secs());

                    let _ = tx.send(crate::web::state::FileChangedEvent {
                        path: rel_str.into_owned(),
                        mtime_secs,
                    });
                }
            }
        });
    });
}

pub(crate) fn home_dir() -> Result<PathBuf> {
    if let Some(home) = env::var_os("HOME") {
        let path = PathBuf::from(home);
        if !path.as_os_str().is_empty() {
            return Ok(path);
        }
    }

    std::panic::catch_unwind(dirs::home_dir)
        .ok()
        .flatten()
        .context("cannot determine home directory")
}

fn create_router(state: WebState) -> Router {
    let api = Router::new()
        // Sessions
        .route("/sessions", get(handlers::sessions::list_sessions))
        .route("/sessions/:id", get(handlers::sessions::get_session))
        .route(
            "/sessions/:id/messages",
            get(handlers::sessions::get_messages),
        )
        .route(
            "/sessions/:id/children",
            get(handlers::sessions::get_children),
        )
        .route(
            "/sessions/:id/minimap",
            get(handlers::sessions::get_minimap),
        )
        .route(
            "/sessions/:id/search",
            get(handlers::sessions::search_session),
        )
        .route(
            "/sessions/:id/compact",
            get(handlers::sessions::get_compact_text),
        )
        .route(
            "/sessions/:id/export",
            get(handlers::sessions::export_session),
        )
        .route(
            "/sessions/:id/watch",
            get(handlers::sessions::watch_session),
        )
        .route(
            "/sessions/:id/rename",
            patch(handlers::sessions::rename_session),
        )
        .route("/sessions/:id", delete(handlers::sessions::delete_session))
        .route(
            "/sessions/:id/restore",
            post(handlers::sessions::restore_session),
        )
        .route(
            "/sessions/:id/permanent",
            delete(handlers::sessions::permanent_delete),
        )
        .route("/projects", get(handlers::sessions::list_projects))
        .route("/machines", get(handlers::sessions::list_machines))
        .route("/agents", get(handlers::sessions::list_agents))
        .route("/stats", get(handlers::sessions::get_stats))
        // Analytics
        .route("/analytics/summary", get(handlers::analytics::summary))
        .route("/analytics/activity", get(handlers::analytics::activity))
        .route("/analytics/heatmap", get(handlers::analytics::heatmap))
        .route("/analytics/projects", get(handlers::analytics::projects))
        .route(
            "/analytics/hour-of-week",
            get(handlers::analytics::hour_of_week),
        )
        .route(
            "/analytics/top-sessions",
            get(handlers::analytics::top_sessions),
        )
        // Usage
        .route("/usage/summary", get(handlers::analytics::usage_summary))
        .route("/usage/daily", get(handlers::analytics::usage_daily))
        .route("/usage/by-model", get(handlers::analytics::usage_by_model))
        .route(
            "/usage/by-project",
            get(handlers::analytics::usage_by_project),
        )
        .route(
            "/usage/sync-pricing",
            post(handlers::analytics::sync_pricing),
        )
        // Overview
        .route(
            "/overview/stats",
            get(handlers::overview::get_overview_stats),
        )
        .route(
            "/overview/stats/refresh",
            post(handlers::overview::refresh_overview_stats),
        )
        // Search
        .route("/search", get(handlers::search::global_search))
        // Sync
        .route("/sync", post(handlers::sync_handler::trigger_sync))
        .route("/resync", post(handlers::sync_handler::trigger_resync))
        .route("/sync/status", get(handlers::sync_handler::sync_status))
        // Starred
        .route("/starred", get(handlers::starred::list_starred))
        .route("/sessions/:id/star", put(handlers::starred::star_session))
        .route(
            "/sessions/:id/star",
            delete(handlers::starred::unstar_session),
        )
        .route("/starred/bulk", post(handlers::starred::bulk_star))
        // Path notes (markdown files across workspace, linked via ](path) targets)
        .route("/path-notes", get(handlers::path_notes::list_path_notes))
        .route("/path-notes", post(handlers::path_notes::create_path_note))
        // Pins
        .route("/pins", get(handlers::pins::list_all_pins))
        .route("/sessions/:id/pins", get(handlers::pins::list_session_pins))
        .route(
            "/sessions/:id/messages/:message_id/pin",
            post(handlers::pins::pin_message),
        )
        .route(
            "/sessions/:id/messages/:message_id/pin",
            delete(handlers::pins::unpin_message),
        )
        // Trash
        .route("/trash", get(handlers::trash::list_trash))
        .route("/trash", delete(handlers::trash::empty_trash))
        // Settings
        .route("/settings", get(handlers::settings::get_settings))
        .route("/settings", put(handlers::settings::update_settings))
        // Workspace
        .route("/workspace/tree", get(handlers::workspace::list_tree))
        .route(
            "/workspace/watch",
            get(handlers::workspace::workspace_watch),
        )
        .route("/workspace/file", get(handlers::workspace::read_file))
        .route("/workspace/file", post(handlers::workspace::save_file))
        .route("/workspace/update", post(handlers::workspace::run_update))
        .route(
            "/workspace/create-file",
            post(handlers::workspace::create_file),
        )
        .route(
            "/workspace/create-directory",
            post(handlers::workspace::create_directory),
        )
        .route("/workspace/delete", post(handlers::workspace::delete_entry))
        .route("/workspace/rename", post(handlers::workspace::rename_entry))
        .route("/workspace/copy", post(handlers::workspace::copy_entry))
        .route(
            "/workspace/workbench-model",
            get(handlers::extensions::get_workbench_model),
        )
        .route(
            "/workspace/extensions/execute",
            post(handlers::extensions::execute_extension_command),
        )
        .route(
            "/workspace/extensions/:extension_id/assets",
            get(handlers::extensions::get_extension_asset),
        )
        .route(
            "/workspace/extensions/:extension_id/readme",
            get(handlers::extensions::get_extension_readme),
        )
        // Marketplace
        .route(
            "/marketplace/search",
            get(handlers::marketplace::search_marketplace),
        )
        .route(
            "/marketplace/readme",
            get(handlers::marketplace::get_marketplace_readme),
        )
        .route(
            "/marketplace/install",
            post(handlers::marketplace::install_extension),
        )
        .route(
            "/marketplace/inspect",
            post(handlers::marketplace::inspect_marketplace_extension),
        )
        .route(
            "/marketplace/uninstall",
            post(handlers::marketplace::uninstall_extension),
        )
        .route(
            "/marketplace/disable",
            post(handlers::marketplace::disable_extension),
        )
        .route(
            "/marketplace/enable",
            post(handlers::marketplace::enable_extension),
        )
        // Workbench state
        .route(
            "/workbench/state",
            get(handlers::workbench_state::get_workbench_state),
        )
        .route(
            "/workbench/state",
            put(handlers::workbench_state::put_workbench_state),
        )
        // Plans
        .route("/plans/list", get(handlers::plans::list_plans))
        .route("/plans/content", get(handlers::plans::get_plan_content))
        // Version
        .route("/version", get(handlers::version::get_version))
        // Issues
        .route("/issues", get(handlers::issues::list_issues))
        .route("/issues/stream", get(handlers::issues::stream_issues))
        .route(
            "/issues/:owner/:repo",
            get(handlers::issues::list_repo_issues),
        )
        .route("/issues/:owner/:repo", post(handlers::issues::create_issue))
        .route(
            "/issues/:owner/:repo/:number",
            patch(handlers::issues::update_issue),
        )
        .route(
            "/issues/:owner/:repo/:number/comments",
            get(handlers::issues::list_comments),
        )
        .route(
            "/issues/:owner/:repo/:number/comments",
            post(handlers::issues::add_comment),
        )
        // Gists
        .route("/gists", get(handlers::gists::list_gists))
        .route("/gists", post(handlers::gists::create_gist))
        .route("/gists/:id", get(handlers::gists::get_gist))
        .route("/gists/:id", patch(handlers::gists::update_gist))
        // Fleet — read endpoints
        .route("/fleet/status", get(handlers::fleet::fleet_status))
        .route("/fleet/repos", get(handlers::fleet::fleet_repos))
        .route(
            "/fleet/detailed-status",
            get(handlers::fleet::fleet_detailed_status),
        )
        .route("/fleet/branches", get(handlers::fleet::fleet_branches))
        .route("/fleet/diff", get(handlers::fleet::fleet_diff))
        .route("/fleet/watch", get(handlers::fleet::fleet_watch))
        // Fleet — single-repo mutations
        .route("/fleet/focus", post(handlers::fleet::fleet_focus))
        .route("/fleet/stage", post(handlers::fleet::fleet_stage))
        .route("/fleet/commit", post(handlers::fleet::fleet_commit))
        .route("/fleet/push", post(handlers::fleet::fleet_push))
        .route("/fleet/pull", post(handlers::fleet::fleet_pull))
        .route("/fleet/checkout", post(handlers::fleet::fleet_checkout))
        .route(
            "/fleet/branch/create",
            post(handlers::fleet::fleet_create_branch),
        )
        // Fleet — fleet-wide mutations
        .route("/fleet/stage-all", post(handlers::fleet::fleet_stage_all))
        .route("/fleet/commit-all", post(handlers::fleet::fleet_commit_all))
        .route("/fleet/push-all", post(handlers::fleet::fleet_push_all))
        .route("/fleet/pull-all", post(handlers::fleet::fleet_pull_all))
        .route(
            "/fleet/checkout-all",
            post(handlers::fleet::fleet_checkout_all),
        )
        .route("/fleet/merge-back", post(handlers::fleet::fleet_merge_back))
        // Log stream
        .route("/logs", get(handlers::logs::stream_logs))
        // Background ops — snapshot and live stream
        .route("/ops", get(ops::ops_snapshot))
        .route("/ops/stream", get(ops::ops_stream));

    Router::new()
        .nest("/api/v1", api)
        .fallback(spa_handler)
        .layer(CorsLayer::permissive())
        .with_state(state)
}

/// Serve embedded frontend assets with SPA fallback to index.html
async fn spa_handler(uri: Uri) -> impl IntoResponse {
    let path = uri.path().trim_start_matches('/');

    // Try exact file match first
    if let Some(content) = FrontendAssets::get(path) {
        let mime = mime_guess::from_path(path).first_or_octet_stream();
        let cache_control = if path == "index.html" {
            "no-store"
        } else {
            "public, max-age=31536000, immutable"
        };
        return Response::builder()
            .header(header::CONTENT_TYPE, mime.as_ref())
            .header(header::CACHE_CONTROL, cache_control)
            .body(boxed(Full::from(content.data)))
            .unwrap();
    }

    // SPA fallback: serve index.html for all non-file routes
    match FrontendAssets::get("index.html") {
        Some(content) => Response::builder()
            .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .header(header::CACHE_CONTROL, "no-store")
            .body(boxed(Full::from(content.data)))
            .unwrap(),
        None => Response::builder()
            .status(StatusCode::NOT_FOUND)
            .body(boxed(Full::from("frontend not found")))
            .unwrap(),
    }
}