wsb 0.124.3689

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
pub mod db;
pub mod github;
pub mod handlers;
pub mod ops;
pub mod parser;
pub mod search_sources;
pub mod sse;
pub mod state;
pub mod sync;

use anyhow::{bail, Context, Result};
use crate::fleet::config::gitmodules::validate_gitmodules_structure;
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 std::path::{Path, PathBuf};
use tower_http::cors::CorsLayer;

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

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

/// Start the web server on the given port.
pub async fn start_server(port: u16, debug: bool, workspace: Option<PathBuf>, parent_pid: Option<u32>) -> Result<()> {
    let workspace_root = validate_server_workspace(workspace)?;
    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();
    // Register the sender and ring buffer with the global broadcast layer installed at startup.
    set_log_broadcast(log_tx.clone(), log_ring.clone());

    let state = WebState::new(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());

    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.
/// Uses POSIX kill(pid, 0) which returns success if the process exists
/// and we have permission to signal it, without actually sending a signal.
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
}

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))
}

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/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),
        )
        // 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
        .route("/path-notes", get(handlers::path_notes::list_path_notes))
        .route("/path-notes", post(handlers::path_notes::create_path_note))
        .route("/path-notes/:id", patch(handlers::path_notes::update_path_note))
        .route("/path-notes/:id", delete(handlers::path_notes::delete_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/file", get(handlers::workspace::read_file))
        .route("/workspace/update", post(handlers::workspace::run_update))
        .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(),
    }
}