From 1ce5285b386e120926f9c4f859b274575e5a95cc Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:06 +0800 Subject: [PATCH 1/8] fix(dgl): allow missing dependencies under configured model roots --- examples/server/async_jobs.cpp | 37 +++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index b521be536..19fd2817d 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -602,6 +602,23 @@ static json describe_dgl_result(const sd_dgl_result_t* result) { namespace { namespace fs = std::filesystem; + bool has_resolved_model_parent(const fs::path& path) { + std::error_code error; + for (auto part = path; !part.empty(); part = part.parent_path()) { + const auto status = fs::symlink_status(part, error); + if (status.type() != fs::file_type::not_found) { + if (error || !fs::is_directory(status)) + return false; + // A dangling link or junction must not be treated as a missing dependency. + const auto canonical = fs::canonical(part, error); + return !error && model_path_key(canonical) == model_path_key(part); + } + if (part == part.root_path()) + break; + } + return false; + } + bool allowed_dgl_path(const char* path, sd_dgl_file_access_t access, void* userdata) try { const auto& policy = *static_cast(userdata); std::error_code error; @@ -655,16 +672,18 @@ namespace { const bool readable = !error && (fs::is_regular_file(status) || fs::is_directory(status)); if (access == SD_DGL_FILE_READ) return readable; + if (!readable && status.type() != fs::file_type::not_found) + return false; + const auto key = model_path_key(resolved); - if (readable || status.type() == fs::file_type::not_found) { - if (policy.configured_files.count(key)) - return true; - if (std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { return model_path_inside(root, resolved); })) - return true; - } - return readable && std::any_of(policy.models.begin(), policy.models.end(), [&](const ModelRoot& root) { - return model_path_key(root.path) == key || model_path_inside(root.path, resolved); - }); + const bool allowed = policy.configured_files.count(key) || + std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { + return model_path_inside(root, resolved); + }) || + std::any_of(policy.models.begin(), policy.models.end(), [&](const ModelRoot& root) { + return model_path_key(root.path) == key || model_path_inside(root.path, resolved); + }); + return allowed && (readable || has_resolved_model_parent(resolved)); } catch (const std::exception&) { return false; } From 5d9083b13087537fe1d234b0ced73fd0af9374a5 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:06 +0800 Subject: [PATCH 2/8] feat(server): unify browser origin checks across routes --- examples/server/README.md | 24 +++++++---- examples/server/api.md | 4 +- examples/server/routes_dgl.cpp | 38 ++++-------------- examples/server/server_access.cpp | 66 ++++++++++++++++++++++++++++--- 4 files changed, 87 insertions(+), 45 deletions(-) diff --git a/examples/server/README.md b/examples/server/README.md index 3ab90012c..886df77f3 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -126,7 +126,10 @@ and are not parsed by the native server API. ### DGL editor -Open the Web UI using the local server address and select **DGL** in the header. +Open the Web UI and select **DGL** in the header. The workspace follows the +server's `--listen-ip` setting. The default `127.0.0.1` limits access to the +server machine. When the server listens on a LAN interface, open the Web UI +using the server's LAN IP and port to use the workspace from another device. Select a saved script or choose **New**. **Duplicate** saves a copy of the current editor text under a new name. Edit **File name** before saving to save under a different name. **Run** submits the editor text to the generation queue, @@ -433,29 +436,34 @@ configured defaults. | --- | --- | --- | | `--listen-ip ` | `127.0.0.1` | Server listen address | | `--listen-port ` | `1234` | Server listen port | -| `--dgl-dir ` | `dgl` | Script directory for the local DGL editor | +| `--dgl-dir ` | `dgl` | Script directory for the DGL editor | | `--max-pending-jobs ` | `64` | Maximum async jobs queued or generating | | `--completed-ttl-seconds ` | `600` | Retention time for completed async jobs | ### Access -By default any program on the machine, and any web page open in a browser on -it, can call the server. To limit that: +The default listener accepts connections from the server machine. A listener +bound to a LAN interface also accepts connections from devices that can reach +it. The Web UI and HTTP APIs use the same access rules. Browser requests are +same-origin by default. Use an IP address, `localhost`, or the hostname +configured as the listen address when connecting directly. | Option | Default | Purpose | | --- | --- | --- | | `--api-key ` | none | Key clients must send as `Authorization: Bearer ` or `X-Api-Key: `. Separate multiple keys with commas. | | `--api-key-file ` | none | The same, one key per line, so keys don't show in the process list | -| `--cors-origins ` | any | Web origins allowed to read the server's answers in a browser, comma-separated | +| `--cors-origins ` | none | Additional browser origins allowed to make cross-origin requests, comma-separated | With a key, the page at `/` still loads, but the bundled Web UI can't send the key, so its calls get `401`; it is meant for use without a key. Authentication failures return `401` with a `WWW-Authenticate` Bearer challenge. Protected responses include `Cache-Control: no-store`. -`--cors-origins` only decides which web pages may read the answers: other -pages get no CORS headers, but their requests still reach the server. To -refuse requests, set a key as well. +The server rejects requests from other browser origins with `403` unless their +origin is listed in `--cors-origins`. For a reverse proxy that preserves the +public Host header, include its full public origin in that list, such as +`https://sd.example.com`. The origin policy applies to DGL requests +as well as the generation APIs. Startup fails if an access option is missing its value, a list is empty (such as `--api-key ,`), or the key file contains no keys. diff --git a/examples/server/api.md b/examples/server/api.md index 51eddb102..89c89f99f 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -1829,8 +1829,8 @@ Example cancelled job: ## DGL editor API -These endpoints are available to the local, same-origin Web UI. The server uses -the working directory's ./dgl directory unless --dgl-dir is set. +These endpoints follow the server's access rules and `--listen-ip`. The server +uses `./dgl` in the working directory unless `--dgl-dir` is set. | Method and path | Request or response | | --- | --- | diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index 803a0b07a..a3cca682c 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -32,31 +32,9 @@ namespace { res.set_content(json({{"error", message}}).dump(-1, ' ', false, json::error_handler_t::replace), "application/json"); } - bool local_origin(const Request& req) { - if (req.remote_addr != "127.0.0.1" && req.remote_addr != "::1" && req.remote_addr != "::ffff:127.0.0.1") - return false; - const auto host = req.get_header_value("Host"); - const auto port = ":" + std::to_string(req.local_port); - const auto origin = req.get_header_value("Origin"); - const auto site = req.get_header_value("Sec-Fetch-Site"); - if ((!site.empty() && site != "same-origin" && site != "none") || - (!origin.empty() && origin != "http://" + host && origin != "https://" + host)) - return false; - for (const std::string address : {"localhost", "127.0.0.1", "[::1]"}) { - if (host == address || host == address + port) - return true; - } - return false; - } - - httplib::Server::Handler local_dgl_route(httplib::Server::Handler handler) { + httplib::Server::Handler with_dgl_errors(httplib::Server::Handler handler) { return [handler = std::move(handler)](const Request& req, Response& res) { res.set_header("Cache-Control", "no-store"); - res.set_header("Cross-Origin-Resource-Policy", "same-origin"); - if (!local_origin(req)) { - send_error(res, 403, "DGL is available from the local server's Web UI"); - return; - } if (req.method == "POST") { const auto content_type = req.get_header_value("Content-Type"); if (content_type.substr(0, content_type.find(';')) != "application/json") { @@ -172,7 +150,7 @@ namespace { void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { auto workspace = std::make_shared(runtime.svr_params->dgl_dir); - svr.Get("/sdcpp/v1/dgl/scripts", local_dgl_route([workspace](const Request&, Response& res) { + svr.Get("/sdcpp/v1/dgl/scripts", with_dgl_errors([workspace](const Request&, Response& res) { std::lock_guard lock(workspace->mutex); std::vector names; if (fs::exists(workspace->directory)) { @@ -186,7 +164,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_json(res, 200, {{"directory", workspace->directory.generic_u8string()}, {"scripts", names}}); })); - svr.Get("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) { + svr.Get("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) { const auto name = req.get_param_value("name"); if (!valid_script_name(name)) { send_error(res, 400, "Expected a .dgl file name"); @@ -201,7 +179,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_json(res, 200, {{"source", read_script(path)}}); })); - svr.Post("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) { + svr.Post("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) { const auto body = json::parse(req.body); const auto name = body.at("name").get(); const auto source = body.at("source").get(); @@ -227,7 +205,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_json(res, updating ? 200 : 201, {{"name", name}}); })); - svr.Post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) { + svr.Post("/sdcpp/v1/dgl/jobs", with_dgl_errors([&runtime](const Request& req, Response& res) { auto source = json::parse(req.body).at("source").get(); if (source.empty() || !valid_source(source)) { send_error(res, 400, "Expected non-empty UTF-8 source"); @@ -252,14 +230,14 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { manager.cv.notify_one(); })); - svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", local_dgl_route([&runtime](const Request& req, Response& res) { + svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", with_dgl_errors([&runtime](const Request& req, Response& res) { auto& manager = *runtime.async_job_manager; std::lock_guard lock(manager.mutex); if (auto job = find_dgl_job(manager, req.matches[1].str(), res)) send_json(res, 200, make_async_job_json(manager, *job)); })); - svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", local_dgl_route([&runtime](const Request& req, Response& res) { + svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", with_dgl_errors([&runtime](const Request& req, Response& res) { auto& manager = *runtime.async_job_manager; std::lock_guard lock(manager.mutex); auto job = find_dgl_job(manager, req.matches[1].str(), res); @@ -276,7 +254,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_json(res, 200, make_async_job_json(manager, *job)); })); - svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", local_dgl_route([&runtime](const Request& req, Response& res) { + svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", with_dgl_errors([&runtime](const Request& req, Response& res) { auto& manager = *runtime.async_job_manager; std::shared_ptr result; { diff --git a/examples/server/server_access.cpp b/examples/server/server_access.cpp index 1bd0aaf8b..9f7ce5b7c 100644 --- a/examples/server/server_access.cpp +++ b/examples/server/server_access.cpp @@ -59,7 +59,7 @@ void SDSvrParams::add_access_options(ArgOptions& options, const std::vector& allowed, std::string_view origin) { + return !origin.empty() && std::find(allowed.begin(), allowed.end(), origin) != allowed.end(); +} + static void set_cors_headers(const httplib::Request& req, httplib::Response& res, const std::vector& allowed) { const bool preflight = req.method == "OPTIONS"; - res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin"); + res.set_header("Vary", preflight ? "Origin, Sec-Fetch-Site, Access-Control-Request-Headers" : "Origin, Sec-Fetch-Site"); const auto origin = req.get_header_value("Origin"); - if (!allowed.empty() && std::find(allowed.begin(), allowed.end(), origin) == allowed.end()) { + if (!is_allowed_origin(allowed, origin)) { return; } - res.set_header("Access-Control-Allow-Origin", origin.empty() ? "*" : origin); + res.set_header("Access-Control-Allow-Origin", origin); res.set_header("Access-Control-Allow-Credentials", "true"); - res.set_header("Access-Control-Allow-Methods", "*"); + res.set_header("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"); const auto headers = preflight ? req.get_header_value("Access-Control-Request-Headers") : std::string{}; res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers); } +static bool is_server_host(std::string_view host, const std::string& listen_ip) { + if (host.empty()) + return false; + if (host.back() != ']') { + const auto port_separator = host.rfind(':'); + if (port_separator != std::string_view::npos) { + const auto port = host.substr(port_separator + 1); + if (port.empty() || port.find_first_not_of("0123456789") != std::string_view::npos) + return false; + host = host.substr(0, port_separator); + } + } + if (host == "localhost" || host == listen_ip) + return true; + if (host.size() > 2 && host.front() == '[' && host.back() == ']') { + const std::string ipv6(host.substr(1, host.size() - 2)); + in6_addr address{}; + return inet_pton(AF_INET6, ipv6.c_str(), &address) == 1; + } + const std::string ipv4(host); + in_addr address{}; + return inet_pton(AF_INET, ipv4.c_str(), &address) == 1; +} + +static bool is_allowed_request_origin(const httplib::Request& req, const SDSvrParams& params) { + if (req.get_header_value_count("Host") != 1 || + req.get_header_value_count("Origin") > 1 || req.get_header_value_count("Sec-Fetch-Site") > 1) + return false; + + // Same-origin browser headers alone do not distinguish a DNS-rebound hostname. + const auto host = req.get_header_value("Host"); + const auto http_origin = "http://" + host; + const auto https_origin = "https://" + host; + if (!is_server_host(host, params.listen_ip) && !is_allowed_origin(params.cors_origins, http_origin) && + !is_allowed_origin(params.cors_origins, https_origin)) + return false; + + const auto origin = req.get_header_value("Origin"); + if (is_allowed_origin(params.cors_origins, origin)) + return true; + const auto site = req.get_header_value("Sec-Fetch-Site"); + return (site.empty() || site == "same-origin" || site == "none") && + (origin.empty() || origin == http_origin); +} + SDHttpServer::SDHttpServer(const SDSvrParams& params) { set_pre_routing_handler([¶ms](const httplib::Request& req, httplib::Response& res) { + if (!is_allowed_request_origin(req, params)) { + res.status = 403; + res.set_content(R"({"error":"Request origin is not allowed"})", "application/json"); + close_after_response_ = true; + return HandlerResponse::Handled; + } if (req.method == "OPTIONS") { close_after_response_ = req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0; res.status = 204; @@ -168,6 +223,7 @@ SDHttpServer::SDHttpServer(const SDSvrParams& params) { res.headers.erase("Cache-Control"); res.set_header("Cache-Control", "no-store"); } + res.set_header("Cross-Origin-Resource-Policy", "same-origin"); set_cors_headers(req, res, params.cors_origins); }); } From dab02532553e15c31be46eb5902126889c6eafc7 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:07 +0800 Subject: [PATCH 3/8] refactor(server): unify DGL job polling and cancellation --- docs/dgl.md | 3 +- examples/server/README.md | 3 +- examples/server/api.md | 22 ++++---- examples/server/async_jobs.cpp | 9 ++-- examples/server/async_jobs.h | 2 - examples/server/routes_dgl.cpp | 91 ++------------------------------ examples/server/routes_sdcpp.cpp | 22 ++------ 7 files changed, 21 insertions(+), 131 deletions(-) diff --git a/docs/dgl.md b/docs/dgl.md index d7cb7f9f0..c4656c030 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -1163,8 +1163,7 @@ return {cover = cover, clip = clip, latent = latent} `media::save(path, media)` writes these exact bytes, with no re-encoding or metadata changes. It checks file-write permission and the extension against the MIME type. Omit the save calls for in-memory results only. The server's DGL -editor displays returned media from the existing job result; ordinary tensors -remain available for inspection. +editor displays returned media and ordinary tensor metadata in the job result. | Encoding | MIME type | Requirements | | --- | --- | --- | diff --git a/examples/server/README.md b/examples/server/README.md index 886df77f3..106a075a7 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -142,8 +142,7 @@ Use `image::encode` or `video::encode` and return their `{data, mime_type}` dicts, either directly or as named fields of the root dict. To save the same encoded output, call `media::save("output/cover.png", cover)` before returning it. Saving is optional. The job result contains the same encoded bytes, and -polling does not encode them again. Tensor frames can be inspected separately -with **Inspect tensor frames**; they are not fetched automatically. +polling returns them without re-encoding. DGL jobs share an execution context for the lifetime of the server. Compatible scripts can reuse loaded model components across runs. The context can release diff --git a/examples/server/api.md b/examples/server/api.md index 89c89f99f..41772e74f 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -1071,11 +1071,12 @@ Typical status codes: #### `POST /sdcpp/v1/jobs/{id}/cancel` -Cancels a queued job immediately, or requests interruption of a generating image or -video job. A generating job returns `200 OK` with `cancel_requested: true` and -remains `generating` until execution stops at a cancellation checkpoint. Continue -polling until its status becomes `cancelled`. Cancelled jobs have no result. -Repeated cancellation requests are safe; terminal jobs are returned unchanged. +Cancels a queued image, video, or DGL job immediately, or requests interruption +if it is already running. No request body is required. A running job returns +`200 OK` with `cancel_requested: true` and remains `generating` until it reaches +a cancellation checkpoint. Poll `GET /sdcpp/v1/jobs/{id}` for the final status. +Cancelled jobs have no result. Repeated cancellation requests are safe and +return the current status of terminal jobs. Typical status codes: @@ -1837,10 +1838,9 @@ uses `./dgl` in the working directory unless `--dgl-dir` is set. | GET /sdcpp/v1/dgl/scripts | Returns directory and a list of scripts | | GET /sdcpp/v1/dgl/script?name=example.dgl | Returns the script as source | | POST /sdcpp/v1/dgl/script | Saves UTF-8 source with the given name. Pass previous_source to update an existing script. A conflict returns HTTP 409. | -| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID with HTTP 202 | -| GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media | -| POST /sdcpp/v1/dgl/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job. Send `Content-Type: application/json`. | -| GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. | +| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID and `poll_url` with HTTP 202 | +| GET /sdcpp/v1/jobs/{id} | Returns job status and progress, plus any error or result with tensor descriptions and inline encoded media | +| POST /sdcpp/v1/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job | Failed jobs report `error.code` and `error.message`. When execution reports `out_of_memory`, the message includes the memory failure details available @@ -1878,9 +1878,7 @@ The name of a root media dict is `result`. The script encodes media once. After execution releases the generation lock, the server converts returned bytes to Base64 once, before publishing -`completed`. Polling returns the stored result; it does not encode a video, -convert Base64 again, or require frame requests. The frame endpoint remains -available for explicit tensor inspection. Native `/sdcpp/v1/vid_gen` is unchanged. +`completed`. Polling returns the stored metadata and inline Base64 media. Inline media share a 64 MiB raw-byte budget per job. An item that exceeds the remaining budget has no `b64_json`; it instead contains diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index 19fd2817d..a2d881bf2 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -503,7 +503,7 @@ bool execute_vid_gen_job(ServerRuntime& runtime, return true; } -int64_t dgl_image_frame_count(const sd_tensor_t* tensor) { +static int64_t dgl_image_frame_count(const sd_tensor_t* tensor) { if (!tensor || sd_tensor_type(tensor) != SD_TENSOR_U8) return 0; const auto rank = sd_tensor_rank(tensor); @@ -708,7 +708,6 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param static sd_status_t execute_dgl_job(ServerRuntime& runtime, AsyncGenerationJob& job, - std::shared_ptr& result, json& result_info, std::string& error_message) { try { @@ -728,7 +727,7 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime, return status; } } - result.reset(raw_result, sd_dgl_result_free); + std::unique_ptr result(raw_result, sd_dgl_result_free); result_info = describe_dgl_result(result.get()); return SD_STATUS_OK; } catch (const std::exception& error) { @@ -815,7 +814,6 @@ void async_job_worker(ServerRuntime& runtime) { std::string output_media_mime_type; int output_frame_count = 0; int output_fps = 0; - std::shared_ptr dgl_result; json dgl_result_info; std::string error_message; const char* error_code = "generation_failed"; @@ -833,7 +831,7 @@ void async_job_worker(ServerRuntime& runtime) { output_info, error_message); } else if (job->kind == AsyncJobKind::Dgl) { - const auto status = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message); + const auto status = execute_dgl_job(runtime, *job, dgl_result_info, error_message); ok = status == SD_STATUS_OK; if (status == SD_STATUS_OUT_OF_MEMORY) { error_code = "out_of_memory"; @@ -864,7 +862,6 @@ void async_job_worker(ServerRuntime& runtime) { job->result_media_mime_type = std::move(output_media_mime_type); job->result_frame_count = output_frame_count; job->result_fps = output_fps; - job->dgl_result = std::move(dgl_result); job->dgl_result_info = std::move(dgl_result_info); job->error_code.clear(); job->error_message.clear(); diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 283910a28..14c491deb 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -56,7 +56,6 @@ struct AsyncGenerationJob { ImgGenJobRequest img_gen; VidGenJobRequest vid_gen; std::string dgl_source; - std::shared_ptr dgl_result; json dgl_result_info; std::vector result_images_b64; json result_generation_info; @@ -99,7 +98,6 @@ size_t count_pending_jobs(const AsyncJobManager& manager); std::string make_async_job_id(AsyncJobManager& manager); bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job); json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job); -int64_t dgl_image_frame_count(const sd_tensor_t* tensor); bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index a3cca682c..bbbb0bcb6 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -1,14 +1,11 @@ #include "routes.h" #include -#include #include -#include #include #include #include "async_jobs.h" -#include "common/media_io.h" namespace { namespace fs = std::filesystem; @@ -103,49 +100,6 @@ namespace { std::error_code ignored; fs::remove(staging, ignored); } - - std::optional parse_index(std::string_view value) { - size_t index = 0; - const auto parsed = std::from_chars(value.data(), value.data() + value.size(), index); - if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size()) - return std::nullopt; - return index; - } - - std::shared_ptr find_dgl_job(AsyncJobManager& manager, const std::string& id, Response& res) { - purge_expired_jobs(manager); - auto it = manager.jobs.find(id); - if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl) - return it->second; - const bool expired = manager.expired_jobs.count(id) != 0; - send_error(res, expired ? 410 : 404, expired ? "Job expired" : "Job not found"); - return {}; - } - - void send_output_preview(const Request& req, Response& res, const sd_dgl_result_t* result) { - const auto output = parse_index(req.matches[2].str()); - if (!output || *output >= sd_dgl_result_count(result)) { - send_error(res, 404, "Output not found"); - return; - } - const auto* tensor = sd_dgl_result_tensor(result, sd_dgl_result_name(result, *output)); - const auto frames = dgl_image_frame_count(tensor); - const auto frame = req.has_param("frame") ? parse_index(req.get_param_value("frame")) : std::optional(0); - if (!frame || *frame >= static_cast(frames)) { - send_error(res, 404, "Frame not found"); - return; - } - const size_t stride = sd_tensor_byte_size(tensor) / static_cast(frames); - const auto* pixels = static_cast(sd_tensor_data(tensor)) + *frame * stride; - const auto png = encode_image_to_vector(EncodedImageFormat::PNG, pixels, - int(sd_tensor_dim(tensor, 1)), int(sd_tensor_dim(tensor, 2)), - int(sd_tensor_dim(tensor, 0))); - if (png.empty()) { - send_error(res, 500, "Could not encode preview"); - return; - } - res.set_content(reinterpret_cast(png.data()), png.size(), "image/png"); - } } void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { @@ -225,49 +179,10 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { job->id = make_async_job_id(manager); manager.jobs.emplace(job->id, job); manager.queue.push_back(job->id); - send_json(res, 202, make_async_job_json(manager, *job)); + auto response = make_async_job_json(manager, *job); + response["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + send_json(res, 202, response); } manager.cv.notify_one(); })); - - svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", with_dgl_errors([&runtime](const Request& req, Response& res) { - auto& manager = *runtime.async_job_manager; - std::lock_guard lock(manager.mutex); - if (auto job = find_dgl_job(manager, req.matches[1].str(), res)) - send_json(res, 200, make_async_job_json(manager, *job)); - })); - - svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", with_dgl_errors([&runtime](const Request& req, Response& res) { - auto& manager = *runtime.async_job_manager; - std::lock_guard lock(manager.mutex); - auto job = find_dgl_job(manager, req.matches[1].str(), res); - if (!job) - return; - if (job->status == AsyncJobStatus::Queued) { - if (!cancel_queued_job(manager, *job)) { - send_error(res, 409, "Job queue state changed before cancellation"); - return; - } - } else if (job->status == AsyncJobStatus::Generating) { - job->cancel_requested.store(true); - } - send_json(res, 200, make_async_job_json(manager, *job)); - })); - - svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", with_dgl_errors([&runtime](const Request& req, Response& res) { - auto& manager = *runtime.async_job_manager; - std::shared_ptr result; - { - std::lock_guard lock(manager.mutex); - const auto job = find_dgl_job(manager, req.matches[1].str(), res); - if (!job) - return; - result = job->dgl_result; - } - if (!result) { - send_error(res, 404, "Job has no result"); - return; - } - send_output_preview(req, res, result.get()); - })); } diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index 3d68e6076..8e12b1acf 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -549,17 +549,13 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { }); routes.get(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+))", [runtime](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); AsyncJobManager& manager = *runtime->async_job_manager; std::lock_guard lock(manager.mutex); purge_expired_jobs(manager); std::string job_id = req.matches[1]; auto it = manager.jobs.find(job_id); - if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl) { - res.status = 404; - res.set_content(R"({"error":"job not found"})", "application/json"); - return; - } if (it == manager.jobs.end()) { if (manager.expired_jobs.find(job_id) != manager.expired_jobs.end()) { res.status = 410; @@ -576,6 +572,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { }); routes.post(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+)/cancel)", [runtime](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); AsyncJobManager& manager = *runtime->async_job_manager; std::lock_guard lock(manager.mutex); purge_expired_jobs(manager); @@ -594,27 +591,14 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { } auto& job = *it->second; - if (job.kind == AsyncJobKind::Dgl) { - res.status = 404; - res.set_content(R"({"error":"job not found"})", "application/json"); - return; - } if (job.status == AsyncJobStatus::Queued) { if (!cancel_queued_job(manager, job)) { res.status = 409; res.set_content(R"({"error":"job queue state changed before cancellation"})", "application/json"); return; } - res.status = 200; - res.set_content(make_async_job_json(manager, job).dump(), "application/json"); - return; - } - - if (job.status == AsyncJobStatus::Generating) { + } else if (job.status == AsyncJobStatus::Generating) { job.cancel_requested.store(true); - res.status = 200; - res.set_content(make_async_job_json(manager, job).dump(), "application/json"); - return; } res.status = 200; From c7389f99a0204354022c0ee516c7efc001ce63b8 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:08 +0800 Subject: [PATCH 4/8] feat(server): serve workspace media files --- .gitignore | 1 + examples/server/CMakeLists.txt | 1 + examples/server/README.md | 3 +- examples/server/api.md | 13 ++ examples/server/main.cpp | 1 + examples/server/routes.h | 1 + examples/server/routes_media.cpp | 227 +++++++++++++++++++++++++++++++ examples/server/routes_sdcpp.cpp | 1 + examples/server/runtime.cpp | 2 + examples/server/runtime.h | 1 + 10 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 examples/server/routes_media.cpp diff --git a/.gitignore b/.gitignore index 101dd4155..4fe1a5097 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ tests/ /dgl/* !/dgl/.gitkeep logs/ +input/ output/ .vscode/ .idea/ diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index 5d2f928db..ccf290a11 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -78,6 +78,7 @@ add_executable(${TARGET} routes_sdapi.cpp routes_sdcpp.cpp routes_dgl.cpp + routes_media.cpp ) if(APPLE) sd_set_macos_rpaths(${TARGET}) diff --git a/examples/server/README.md b/examples/server/README.md index 106a075a7..6ef538ebd 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -436,6 +436,7 @@ configured defaults. | `--listen-ip ` | `127.0.0.1` | Server listen address | | `--listen-port ` | `1234` | Server listen port | | `--dgl-dir ` | `dgl` | Script directory for the DGL editor | +| `--no-media-view` | Off | Disable the media view endpoint | | `--max-pending-jobs ` | `64` | Maximum async jobs queued or generating | | `--completed-ttl-seconds ` | `600` | Retention time for completed async jobs | @@ -461,7 +462,7 @@ Protected responses include `Cache-Control: no-store`. The server rejects requests from other browser origins with `403` unless their origin is listed in `--cors-origins`. For a reverse proxy that preserves the public Host header, include its full public origin in that list, such as -`https://sd.example.com`. The origin policy applies to DGL requests +`https://sd.example.com`. The origin policy applies to DGL and media requests as well as the generation APIs. Startup fails if an access option is missing its value, a list is empty diff --git a/examples/server/api.md b/examples/server/api.md index 41772e74f..8c350d59e 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -858,6 +858,7 @@ Top-level fields: | `loras` | `array` | Available LoRA entries | | `upscalers` | `array` | Available highres upscalers, built-in and model-backed | | `preview_modes` | `array` | Available preview modes, e.g. `["none", "proj", "tae", "vae"]` | +| `media_view` | `boolean` | Whether the media view endpoint is enabled | | `limits` | `object` | Shared queue and size limits | `model` @@ -1828,6 +1829,18 @@ Example cancelled job: - `429 Too Many Requests` when the job queue is full - `500 Internal Server Error` for unexpected server exceptions during submission +## Media view + +`GET /sdcpp/v1/view?root=assets&path=reference.png` serves an image or video +over the configured listener. `root` selects `input`, `output`, or `assets` +in the server's working directory. `path` is a slash-separated relative path +within that directory. Supported formats are PNG, JPEG, GIF, WebP, WebM, MP4, +and AVI. The endpoint supports HTTP byte ranges and sends `Cache-Control: no-store`. + +The server returns `403` when access is denied or the server was started with +`--no-media-view`. Unavailable paths, links, and unsupported files return +`404`. + ## DGL editor API These endpoints follow the server's access rules and `--listen-ip`. The server diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 24a383321..2af2b9d08 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -151,6 +151,7 @@ int main(int argc, const char** argv) { index_html = "Stable Diffusion Server is running"; #endif register_index_endpoints(svr, svr_params, index_html); + register_media_view_endpoint(svr, svr_params); register_openai_api_endpoints(svr, runtime); register_sdapi_endpoints(svr, runtime); register_sdcpp_api_endpoints(svr, runtime); diff --git a/examples/server/routes.h b/examples/server/routes.h index a3093e476..656c56a0c 100644 --- a/examples/server/routes.h +++ b/examples/server/routes.h @@ -6,6 +6,7 @@ #include "runtime.h" void register_index_endpoints(httplib::Server& svr, const SDSvrParams& svr_params, const std::string& index_html); +void register_media_view_endpoint(httplib::Server& svr, const SDSvrParams& svr_params); void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt); void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt); void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt); diff --git a/examples/server/routes_media.cpp b/examples/server/routes_media.cpp new file mode 100644 index 000000000..a7eec4907 --- /dev/null +++ b/examples/server/routes_media.cpp @@ -0,0 +1,227 @@ +#include "routes.h" + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#endif + +namespace media_view { +#ifdef _WIN32 + class FileHandle { + HANDLE handle_; + + public: + explicit FileHandle(HANDLE handle = INVALID_HANDLE_VALUE) : handle_(handle) {} + ~FileHandle() { + if (*this) + CloseHandle(handle_); + } + FileHandle(FileHandle&& other) noexcept : handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE)) {} + FileHandle& operator=(FileHandle&& other) noexcept { + std::swap(handle_, other.handle_); + return *this; + } + explicit operator bool() const { return handle_ != INVALID_HANDLE_VALUE; } + HANDLE get() const { return handle_; } + }; + + static FileHandle working_directory() { + return FileHandle(CreateFileW(L".", FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + } + + static FileHandle open_child(const FileHandle& parent, const std::string& part, bool directory) { + static const auto open_file = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtOpenFile")); + if (!open_file) + return FileHandle(); + auto name = std::filesystem::u8path(part).native(); + const auto bytes = static_cast(name.size() * sizeof(wchar_t)); + UNICODE_STRING relative{bytes, bytes, name.data()}; + OBJECT_ATTRIBUTES object; + InitializeObjectAttributes(&object, &relative, OBJ_CASE_INSENSITIVE, parent.get(), nullptr); + IO_STATUS_BLOCK status{}; + HANDLE handle = INVALID_HANDLE_VALUE; + const auto access = (directory ? FILE_TRAVERSE : FILE_READ_DATA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE; + // A handle-relative open keeps every component under the directory already checked. + if (open_file(&handle, access, &object, &status, FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT) < 0) + return FileHandle(); + FileHandle file(handle); + BY_HANDLE_FILE_INFORMATION info{}; + if (GetFileType(handle) != FILE_TYPE_DISK || !GetFileInformationByHandle(handle, &info) || + (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || + static_cast(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != directory || + (!directory && info.nNumberOfLinks != 1)) + return FileHandle(); + return file; + } + + static uint64_t file_size(const FileHandle& file) { + LARGE_INTEGER size{}; + return GetFileSizeEx(file.get(), &size) && size.QuadPart > 0 ? static_cast(size.QuadPart) : 0; + } + + static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) { + LARGE_INTEGER position{}; + position.QuadPart = static_cast(offset); + DWORD count = 0; + if (!SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) || + !ReadFile(file.get(), buffer, static_cast(length), &count, nullptr)) + return 0; + return count; + } +#else + class FileHandle { + int fd_; + + public: + explicit FileHandle(int fd = -1) : fd_(fd) {} + ~FileHandle() { + if (*this) + close(fd_); + } + FileHandle(FileHandle&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {} + FileHandle& operator=(FileHandle&& other) noexcept { + std::swap(fd_, other.fd_); + return *this; + } + explicit operator bool() const { return fd_ >= 0; } + int get() const { return fd_; } + }; + + static FileHandle working_directory() { + return FileHandle(open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC)); + } + + static FileHandle open_child(const FileHandle& parent, const std::string& part, bool directory) { + const auto flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | (directory ? O_DIRECTORY : O_NONBLOCK); + return FileHandle(openat(parent.get(), part.c_str(), flags)); + } + + static uint64_t file_size(const FileHandle& file) { + struct stat info {}; + if (fstat(file.get(), &info) != 0 || !S_ISREG(info.st_mode) || info.st_nlink != 1 || info.st_size <= 0) + return 0; + return static_cast(info.st_size); + } + + static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) { + ssize_t count; + do { + count = pread(file.get(), buffer, length, static_cast(offset)); + } while (count < 0 && errno == EINTR); + return count > 0 ? static_cast(count) : 0; + } +#endif + + static bool valid_component(std::string_view part) { + return !part.empty() && part.size() <= 1020 && part != "." && part != ".." && + part.back() != '.' && part.back() != ' ' && part.find_first_of("\\:*?\"<>|") == std::string_view::npos && + std::none_of(part.begin(), part.end(), [](unsigned char c) { return c < 32 || c == 127; }); + } + + static FileHandle open_media(const std::string& root, std::string_view path) { + if (root != "input" && root != "output" && root != "assets") + return FileHandle(); + const auto cwd = working_directory(); + if (!cwd) + return FileHandle(); + auto parent = open_child(cwd, root, true); + while (parent) { + const auto slash = path.find('/'); + const auto part = path.substr(0, slash); + if (!valid_component(part)) + break; + const bool directory = slash != std::string_view::npos; + auto child = open_child(parent, std::string(part), directory); + if (!directory) + return child; + parent = std::move(child); + path.remove_prefix(slash + 1); + } + return FileHandle(); + } + + static const char* media_type(std::string extension, std::string_view header, uint64_t size) { + for (auto& ch : extension) { + if (ch >= 'A' && ch <= 'Z') + ch += 'a' - 'A'; + } + if (extension == ".png" && header.substr(0, 8) == "\x89PNG\r\n\x1a\n") + return "image/png"; + if ((extension == ".jpg" || extension == ".jpeg") && header.substr(0, 3) == "\xff\xd8\xff") + return "image/jpeg"; + if (extension == ".gif" && (header.substr(0, 6) == "GIF87a" || header.substr(0, 6) == "GIF89a")) + return "image/gif"; + if (extension == ".webp" && header.size() >= 16 && header.substr(0, 4) == "RIFF" && header.substr(8, 7) == "WEBPVP8" && + (header[15] == ' ' || header[15] == 'L' || header[15] == 'X')) + return "image/webp"; + if (extension == ".webm" && header.substr(0, 4) == "\x1a\x45\xdf\xa3" && + header.find("\x42\x82\x84webm", 4) != std::string_view::npos) + return "video/webm"; + if (extension == ".avi" && header.size() >= 12 && header.substr(0, 4) == "RIFF" && header.substr(8, 4) == "AVI ") + return "video/x-msvideo"; + if (extension == ".mp4" && header.size() >= 16 && header.substr(4, 4) == "ftyp") { + uint32_t box_size = 0; + for (size_t i = 0; i < 4; ++i) + box_size = (box_size << 8) | static_cast(header[i]); + if (box_size >= 16 && box_size <= size) + return "video/mp4"; + } + return nullptr; + } + + static bool set_media_content(const std::string& root, const std::string& path, httplib::Response& res) { + auto file = open_media(root, path); + if (!file) + return false; + const auto size = file_size(file); + if (size == 0 || size > std::numeric_limits::max()) + return false; + std::array header; + const auto count = read_at(file, 0, header.data(), header.size()); + const auto extension = path.find_last_of('.'); + if (extension == std::string::npos) + return false; + const auto* type = media_type(path.substr(extension), {header.data(), count}, size); + if (!type) + return false; + res.set_header("Accept-Ranges", "bytes"); + res.set_content_provider(static_cast(size), type, + [file = std::make_shared(std::move(file))](size_t offset, size_t length, httplib::DataSink& sink) { + std::array buffer; + const auto count = read_at(*file, offset, buffer.data(), std::min(length, buffer.size())); + return count != 0 && sink.write(buffer.data(), count); + }); + return true; + } +} + +void register_media_view_endpoint(httplib::Server& svr, const SDSvrParams& params) { + svr.Get("/sdcpp/v1/view", [enabled = params.media_view](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); + res.set_header("X-Content-Type-Options", "nosniff"); + if (!enabled) { + res.status = 403; + return; + } + try { + if (req.get_param_value_count("root") == 1 && req.get_param_value_count("path") == 1 && + media_view::set_media_content(req.get_param_value("root"), req.get_param_value("path"), res)) + return; + } catch (const std::system_error&) { + // Invalid path encodings are treated like unavailable files. + } + res.status = 404; + }); +} diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index 8e12b1acf..a17ea9613 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -341,6 +341,7 @@ static json make_capabilities_json(ServerRuntime& runtime) { }; result["generation_features"] = generation_features; result["generation_model_selection"] = true; + result["media_view"] = runtime.svr_params->media_view; result["runtime"] = model_status(runtime); result["current_mode"] = current_mode; result["supported_modes"] = supported_modes; diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 120b8de07..0a3497c18 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -318,6 +318,7 @@ ArgOptions SDSvrParams::get_options() { options.bool_options = { {"", "--color", "colors the logging tags according to level", true, &color}, + {"", "--no-media-view", "disable media file viewing", false, &media_view}, }; auto on_help_arg = [&](int, const char**, int, bool& valid) { @@ -400,6 +401,7 @@ std::string SDSvrParams::to_string() const { << " dgl_dir: \"" << dgl_dir << "\",\n" << " api_keys: " << api_keys.size() << ",\n" << " cors_origins: " << cors_origins.size() << ",\n" + << " media_view: " << std::boolalpha << media_view << ",\n" << "}"; return oss.str(); } diff --git a/examples/server/runtime.h b/examples/server/runtime.h index debf97cb9..50a5fb40a 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -28,6 +28,7 @@ struct SDSvrParams { int weight_residency_ttl = -1; std::string serve_html_path; std::string dgl_dir = "dgl"; + bool media_view = true; std::vector model_dirs; std::vector api_keys; std::string api_key_file; From 71a4ac8d21cf054c58f8884628f93f225c631f37 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:08 +0800 Subject: [PATCH 5/8] feat(server): show DGL progress in the UI and console --- docs/dgl.md | 3 ++- examples/server/api.md | 4 +-- examples/server/async_jobs.cpp | 47 +++++++++++++++++++++++++--------- examples/server/main.cpp | 3 +++ include/stable-diffusion.h | 3 ++- src/dgl/context.cpp | 3 +++ src/dgl/run_events.cpp | 19 +++++++++++--- src/dgl/run_events.h | 4 +++ 8 files changed, 67 insertions(+), 19 deletions(-) diff --git a/docs/dgl.md b/docs/dgl.md index c4656c030..99a801a41 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -1891,7 +1891,8 @@ clears the registration. The sampling pass counter starts at one on each run. Progress can report model loading in tensors, sampling in steps, video upscaling in frames, or a stage with no known total. Without a progress callback, the DGL execution layer displays sampling and -weight-loading progress bars. With a callback, the host controls their display. +weight-loading progress bars. Set `sd_dgl_ctx_set(ctx, "console_progress", "on")` +on an idle context to display those bars alongside a progress callback. The default observer handles previews. Preview mode `proj` uses latent projection. Modes `tae` and `vae` use the decoder supplied to `preview(decoder=...)`, falling back to projection. A positive interval diff --git a/examples/server/api.md b/examples/server/api.md index 8c350d59e..f2ebb5db4 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -768,8 +768,8 @@ Field types: the elapsed generation time in seconds, including output encoding and excluding queue time. -`progress` is available independently of the preview setting, for both image -and video jobs. Continue polling until `status` is terminal: a sampling pass +`progress` is available independently of the preview setting for image, video, +and local DGL jobs. Continue polling until `status` is terminal: a sampling pass can finish before decoding, ADetailer, or output encoding finishes. | Field | Type | Notes | diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index a2d881bf2..d01fbee80 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -126,22 +126,25 @@ static void finish_job_progress(AsyncGenerationJob& job) { job.progress.finished = std::chrono::steady_clock::now(); } -class JobCallbacksGuard { - sd_ctx_t* ctx_; - AsyncGenerationJob& job_; - - static void progress_callback(const sd_generation_progress_t* progress, void* data) { - auto& guard = *static_cast(data); - update_job_progress(guard.job_, progress->stage, progress->detail, +static void job_progress_callback(const sd_generation_progress_t* progress, void* data) noexcept { + try { + auto& job = *static_cast(data); + update_job_progress(job, progress->stage, progress->detail, progress->sample_pass, progress->completed, progress->total, progress->unit); + } catch (...) { + // Progress callbacks must not unwind into the generation context. } +} + +class JobCallbacksGuard { + sd_ctx_t* ctx_; public: JobCallbacksGuard(sd_ctx_t* ctx, AsyncGenerationJob& job) - : ctx_(ctx), job_(job) { + : ctx_(ctx) { clear_preview_callback(); set_preview_callback(job); - sd_set_generation_progress_callback(ctx_, progress_callback, this); + sd_set_generation_progress_callback(ctx_, job_progress_callback, &job); } ~JobCallbacksGuard() { @@ -153,6 +156,24 @@ class JobCallbacksGuard { JobCallbacksGuard& operator=(const JobCallbacksGuard&) = delete; }; +class DglJobProgressGuard { + sd_dgl_ctx_t* ctx_; + +public: + DglJobProgressGuard(sd_dgl_ctx_t* ctx, AsyncGenerationJob& job) : ctx_(ctx) { + if (sd_dgl_ctx_set_progress_callback(ctx_, job_progress_callback, &job) != SD_STATUS_OK) + throw std::runtime_error(sd_dgl_error()); + } + + ~DglJobProgressGuard() { + if (sd_dgl_ctx_set_progress_callback(ctx_, nullptr, nullptr) != SD_STATUS_OK) + LOG_WARN("could not clear DGL job progress callback: %s", sd_dgl_error()); + } + + DglJobProgressGuard(const DglJobProgressGuard&) = delete; + DglJobProgressGuard& operator=(const DglJobProgressGuard&) = delete; +}; + const char* async_job_kind_name(AsyncJobKind kind) { switch (kind) { case AsyncJobKind::ImgGen: @@ -717,11 +738,13 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime, std::lock_guard lock(*runtime.sd_ctx_mutex); if (job.cancel_requested.load()) return SD_STATUS_CANCELLED; - JobCancellationMonitor cancellation(job, [ctx = runtime.sd_ctx]() { - sd_dgl_ctx_cancel(sd_ctx_get_dgl_ctx(ctx)); + auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx); + DglJobProgressGuard progress(ctx, job); + JobCancellationMonitor cancellation(job, [ctx]() { + sd_dgl_ctx_cancel(ctx); }); update_job_progress(job, "executing", "dgl"); - const auto status = sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result); + const auto status = sd_dgl_run(ctx, source.c_str(), nullptr, 0, &raw_result); if (status != SD_STATUS_OK) { error_message = sd_dgl_error(); return status; diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 2af2b9d08..5c1737b40 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -103,6 +104,8 @@ int main(int argc, const char** argv) { } try { configure_server_file_access(models, svr_params, ctx_params); + if (!sd_dgl_ctx_set(sd_ctx_get_dgl_ctx(models.context.get()), "console_progress", "on")) + throw std::runtime_error(sd_dgl_error()); } catch (const std::exception& error) { LOG_ERROR("Context setup failed: %s", error.what()); return 1; diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 8760e5b02..c41818a58 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -360,7 +360,8 @@ SD_API sd_dgl_ctx_t* sd_dgl_ctx_create_once(void); SD_API void sd_dgl_ctx_free(sd_dgl_ctx_t* ctx); // Sets options on an idle context: max_vram, max_ram, conditioning_cache_size, batched_cfg, // n_threads, auto_fit, enable_mmap, eager_load, disable_prefetch, disable_segmented_compute, -// embed_metadata (default on; controls generation metadata in DGL image/video saves). +// embed_metadata (default on; controls generation metadata in DGL image/video saves), +// console_progress (default off; keeps built-in progress output alongside callbacks). // Threading, placement and weight-loading options invalidate cached models when changed. SD_API bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value); diff --git a/src/dgl/context.cpp b/src/dgl/context.cpp index 77eb42dc6..3ba0c5b48 100644 --- a/src/dgl/context.cpp +++ b/src/dgl/context.cpp @@ -132,6 +132,9 @@ namespace sd::dgl { if (!parse_strict_bool(value, enabled)) throw std::runtime_error("batched_cfg expects a boolean"); batched_cfg = enabled; + } else if (key == "console_progress") { + if (!parse_strict_bool(value, callbacks.console_progress)) + throw std::runtime_error("console_progress expects a boolean"); } else if (key == "max_vram") { ggml_graph_cut::MaxVramAssignment limit; std::string error; diff --git a/src/dgl/run_events.cpp b/src/dgl/run_events.cpp index f38cd1bf2..77a47e3ac 100644 --- a/src/dgl/run_events.cpp +++ b/src/dgl/run_events.cpp @@ -1,5 +1,7 @@ #include "run_events.h" +#include + #include "diagnostic.h" namespace sd::dgl { @@ -45,27 +47,37 @@ namespace sd::dgl { void RunEvents::begin_sample(int total_steps) { check_cancelled(); + finish_sample_line(); ++preview_info_.sample_pass; preview_info_.total_steps = total_steps; if (legacy_preview_) sd_begin_preview_pass(total_steps); last_progress_us_ = ggml_time_us(); - if (legacy_progress_ || !callbacks_.progress) + if (uses_console_progress()) pretty_progress(0, total_steps, 0.f); progress_.begin_sample(total_steps, ""); check_cancelled(); } void RunEvents::sample_step(int completed, int total_steps) { - if (legacy_progress_ || !callbacks_.progress) { + if (uses_console_progress()) { const auto now = ggml_time_us(); pretty_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f); last_progress_us_ = now; + sample_line_open_ = completed > 0 && completed < total_steps && !sd_get_progress_callback(); } progress_.report_sample(completed, total_steps); check_cancelled(); } + void RunEvents::finish_sample_line() { + if (sample_line_open_) { + std::fputc('\n', stdout); + std::fflush(stdout); + sample_line_open_ = false; + } + } + void RunEvents::preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata) { auto& run = *static_cast(userdata); if (run.cancelled()) @@ -79,10 +91,11 @@ namespace sd::dgl { RunEventsScope::RunEventsScope(RunEvents& events) : previous_(active_events), byte_progress_(events.uses_legacy_progress() ? nullptr : RunEvents::report_loading, &events), - console_progress_(events.uses_legacy_progress() || !events.callbacks().progress) { + console_progress_(events.uses_console_progress()) { active_events = &events; } RunEventsScope::~RunEventsScope() { + active_events->finish_sample_line(); active_events = previous_; } diff --git a/src/dgl/run_events.h b/src/dgl/run_events.h index c074a2ee3..7a2e1cb7b 100644 --- a/src/dgl/run_events.h +++ b/src/dgl/run_events.h @@ -17,6 +17,7 @@ namespace sd::dgl { int interval = 0; bool denoised = false; bool noisy = false; + bool console_progress = false; }; class RunEvents { @@ -28,6 +29,7 @@ namespace sd::dgl { void* legacy_preview_data_ = nullptr; bool legacy_progress_ = false; int64_t last_progress_us_ = 0; + bool sample_line_open_ = false; static void preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata); @@ -41,8 +43,10 @@ namespace sd::dgl { void report_frames(const char* stage, int completed, int total) const; static void report_loading(int completed, int total, void* data); bool uses_legacy_progress() const { return legacy_progress_; } + bool uses_console_progress() const { return legacy_progress_ || !callbacks_.progress || callbacks_.console_progress; } void begin_sample(int total_steps); void sample_step(int completed, int total_steps); + void finish_sample_line(); const RunCallbacks& callbacks() const { return callbacks_; } const sd_preview_info_t& preview_info() const { return preview_info_; } bool uses_legacy_preview() const { return legacy_preview_ != nullptr; } From 1e79b841f721ffd53796df761665a9669c3caa48 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 01:56:09 +0800 Subject: [PATCH 6/8] feat(server): update the bundled DGL workspace --- examples/server/README.md | 43 +++++++++++++++++++++++++++++++-------- examples/server/frontend | 2 +- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/examples/server/README.md b/examples/server/README.md index 6ef538ebd..a9a31d03e 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -130,13 +130,18 @@ Open the Web UI and select **DGL** in the header. The workspace follows the server's `--listen-ip` setting. The default `127.0.0.1` limits access to the server machine. When the server listens on a LAN interface, open the Web UI using the server's LAN IP and port to use the workspace from another device. -Select a saved script or choose **New**. **Duplicate** saves a copy of the -current editor text under a new name. Edit **File name** before saving to save -under a different name. **Run** submits the editor text to the generation queue, -so you can run unsaved edits. The results panel shows text, scalar and tensor -information and returned encoded media. PNG appears as an image, WebM as a -video player, and AVI as a download. WebM encoding is silent; use AVI for -a PCM16 soundtrack. +Use **Search scripts** to filter the script list, then select a saved script or +choose **New**. **Save** updates the current file or asks for a name for a new +script. Use **Save as…** to save a copy. The editor reopens the last saved script +used in that browser when it is still available. **Run** submits the current +editor text to the generation queue, including unsaved edits. The status bar +below the editor shows progress and keeps the final status and elapsed time. +The server terminal displays weight-loading throughput and sampling speed. + +When a script returns values, **View result** appears in the status bar. Open it +to inspect text, scalars, tensor metadata, and encoded media. PNG appears as an +image, WebM as a video player, and AVI as a download. WebM encoding is silent. +Use AVI for a PCM16 soundtrack. Use `image::encode` or `video::encode` and return their `{data, mime_type}` dicts, either directly or as named fields of the root dict. To save the same @@ -144,6 +149,24 @@ encoded output, call `media::save("output/cover.png", cover)` before returning it. Saving is optional. The job result contains the same encoded bytes, and polling returns them without re-encoding. +The editor underlines supported media paths and shows compact previews below +their lines. Previews align with the code indentation, and files on the same +line appear side by side when space permits. Media loads near the visible area +of the editor. An output path without a file stays collapsed, and a completed +run refreshes its preview when the file becomes available. Drag the handle in +a preview's lower-right corner to resize it, or double-click the handle to reset it. +Click an image or video preview to open it at a larger size. Expanded videos +open at the current playback position. Click the picture to play or pause, or +drag the timeline below it to seek. AVI path previews support MJPEG and +uncompressed 24-bit RGB video with up to 64 MiB of PCM or 32-bit float audio. +The speaker button mutes the preview. To adjust volume in an inline preview, +hover or focus the speaker button to open the volume slider. +Use a relative path under the server's working directory, such as +`assets/reference.png` or `output/clip.webm`. Turn off **Media view** in the +editor toolbar to hide the preview. The server previews files under `input/`, +`output/`, and `assets/`. Start the server +with `--no-media-view` to disable file previews at the server. + DGL jobs share an execution context for the lifetime of the server. Compatible scripts can reuse loaded model components across runs. The context can release idle weights under memory pressure. @@ -454,8 +477,10 @@ configured as the listen address when connecting directly. | `--api-key-file ` | none | The same, one key per line, so keys don't show in the process list | | `--cors-origins ` | none | Additional browser origins allowed to make cross-origin requests, comma-separated | -With a key, the page at `/` still loads, but the bundled Web UI can't send -the key, so its calls get `401`; it is meant for use without a key. +With a key, the page at `/` still loads. Enter the key in **Settings → Server API Key** +and select **Apply**. The Web UI saves it for that server in the current browser tab. +Leave **Base URL** blank when connecting to the server that serves the Web UI. +DGL scripts and media previews use the server that serves the Web UI. Authentication failures return `401` with a `WWW-Authenticate` Bearer challenge. Protected responses include `Cache-Control: no-store`. diff --git a/examples/server/frontend b/examples/server/frontend index d9fd4e6a9..e5929111f 160000 --- a/examples/server/frontend +++ b/examples/server/frontend @@ -1 +1 @@ -Subproject commit d9fd4e6a938b74ad97c7e464a8e689474b70c533 +Subproject commit e5929111fc43e5e492f30607a163e0859cdefb2c From 20368cdd64b155f05d68772763e4cdb3b1dd7fe7 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 02:24:05 +0800 Subject: [PATCH 7/8] fix: handle WebM headers, suffix ranges, UI navigation, and DGL console progress --- examples/server/README.md | 4 +-- examples/server/routes_media.cpp | 53 +++++++++++++++++++++++++++++-- examples/server/server_access.cpp | 18 +++++++++-- src/core/progress.h | 1 + src/core/util.cpp | 11 ++++--- src/dgl/run_events.cpp | 19 ++++++++--- src/dgl/run_events.h | 4 ++- thirdparty/httplib.h | 2 +- 8 files changed, 95 insertions(+), 17 deletions(-) diff --git a/examples/server/README.md b/examples/server/README.md index a9a31d03e..deea97408 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -467,8 +467,8 @@ configured defaults. The default listener accepts connections from the server machine. A listener bound to a LAN interface also accepts connections from devices that can reach -it. The Web UI and HTTP APIs use the same access rules. Browser requests are -same-origin by default. Use an IP address, `localhost`, or the hostname +it. You can open the Web UI from a link on another site. Browser API requests +are same-origin by default. Use an IP address, `localhost`, or the hostname configured as the listen address when connecting directly. | Option | Default | Purpose | diff --git a/examples/server/routes_media.cpp b/examples/server/routes_media.cpp index a7eec4907..91788e84f 100644 --- a/examples/server/routes_media.cpp +++ b/examples/server/routes_media.cpp @@ -152,6 +152,56 @@ namespace media_view { return FileHandle(); } + static size_t ebml_vint_width(std::string_view bytes, size_t max_width) { + if (bytes.empty()) + return 0; + const auto first = static_cast(bytes.front()); + for (size_t width = 1; width <= std::min(max_width, bytes.size()); ++width) { + if (first & (0x80u >> (width - 1))) + return width; + } + return 0; + } + + static bool read_ebml_size(std::string_view& bytes, uint64_t& size) { + const auto width = ebml_vint_width(bytes, 8); + if (width == 0) + return false; + size = static_cast(bytes.front()) & (0xffu >> width); + for (size_t i = 1; i < width; ++i) + size = (size << 8) | static_cast(bytes[i]); + bytes.remove_prefix(width); + return size != (uint64_t{1} << (7 * width)) - 1; + } + + static bool has_webm_doctype(std::string_view header, uint64_t file_size) { + constexpr std::string_view ebml_id = "\x1a\x45\xdf\xa3"; + if (header.substr(0, ebml_id.size()) != ebml_id) + return false; + const auto probe_size = header.size(); + header.remove_prefix(ebml_id.size()); + uint64_t size; + if (!read_ebml_size(header, size)) + return false; + const auto prefix_size = probe_size - header.size(); + if (prefix_size > file_size || size > file_size - prefix_size) + return false; + header = header.substr(0, static_cast(size)); + while (!header.empty()) { + const auto width = ebml_vint_width(header, 4); + if (width == 0) + return false; + const bool is_doctype = header.substr(0, width) == "\x42\x82"; + header.remove_prefix(width); + if (!read_ebml_size(header, size) || size > header.size()) + return false; + if (is_doctype) + return header.substr(0, static_cast(size)) == "webm"; + header.remove_prefix(static_cast(size)); + } + return false; + } + static const char* media_type(std::string extension, std::string_view header, uint64_t size) { for (auto& ch : extension) { if (ch >= 'A' && ch <= 'Z') @@ -166,8 +216,7 @@ namespace media_view { if (extension == ".webp" && header.size() >= 16 && header.substr(0, 4) == "RIFF" && header.substr(8, 7) == "WEBPVP8" && (header[15] == ' ' || header[15] == 'L' || header[15] == 'X')) return "image/webp"; - if (extension == ".webm" && header.substr(0, 4) == "\x1a\x45\xdf\xa3" && - header.find("\x42\x82\x84webm", 4) != std::string_view::npos) + if (extension == ".webm" && has_webm_doctype(header, size)) return "video/webm"; if (extension == ".avi" && header.size() >= 12 && header.substr(0, 4) == "RIFF" && header.substr(8, 4) == "AVI ") return "video/x-msvideo"; diff --git a/examples/server/server_access.cpp b/examples/server/server_access.cpp index 9f7ce5b7c..caa9e5c65 100644 --- a/examples/server/server_access.cpp +++ b/examples/server/server_access.cpp @@ -89,8 +89,12 @@ bool SDSvrParams::load_api_keys() { return true; } +static bool is_web_ui_request(const httplib::Request& req) { + return req.method == "GET" && req.path == "/"; +} + static bool requires_api_key(const SDSvrParams& params, const httplib::Request& req) { - return !params.api_keys.empty() && req.method != "OPTIONS" && !(req.method == "GET" && req.path == "/"); + return !params.api_keys.empty() && req.method != "OPTIONS" && !is_web_ui_request(req); } static bool api_key_matches(const std::vector& keys, std::string_view key) { @@ -131,7 +135,12 @@ static bool is_allowed_origin(const std::vector& allowed, std::stri static void set_cors_headers(const httplib::Request& req, httplib::Response& res, const std::vector& allowed) { const bool preflight = req.method == "OPTIONS"; - res.set_header("Vary", preflight ? "Origin, Sec-Fetch-Site, Access-Control-Request-Headers" : "Origin, Sec-Fetch-Site"); + std::string vary = "Origin, Sec-Fetch-Site"; + if (preflight) + vary += ", Access-Control-Request-Headers"; + else if (is_web_ui_request(req)) + vary += ", Sec-Fetch-Mode, Sec-Fetch-Dest"; + res.set_header("Vary", vary); const auto origin = req.get_header_value("Origin"); if (!is_allowed_origin(allowed, origin)) { @@ -181,6 +190,11 @@ static bool is_allowed_request_origin(const httplib::Request& req, const SDSvrPa !is_allowed_origin(params.cors_origins, https_origin)) return false; + if (is_web_ui_request(req) && req.get_header_value_count("Sec-Fetch-Mode") == 1 && + req.get_header_value_count("Sec-Fetch-Dest") == 1 && req.get_header_value("Sec-Fetch-Mode") == "navigate" && + req.get_header_value("Sec-Fetch-Dest") == "document") + return true; + const auto origin = req.get_header_value("Origin"); if (is_allowed_origin(params.cors_origins, origin)) return true; diff --git a/src/core/progress.h b/src/core/progress.h index ce1c6ddc2..61d2e3000 100644 --- a/src/core/progress.h +++ b/src/core/progress.h @@ -4,6 +4,7 @@ #include void pretty_progress(int step, int steps, float time); +void pretty_console_progress(int step, int steps, float time); void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds); namespace sd { diff --git a/src/core/util.cpp b/src/core/util.cpp index 00b0a3155..74c7a2ce7 100644 --- a/src/core/util.cpp +++ b/src/core/util.cpp @@ -592,14 +592,17 @@ static void print_progress_line(int step, int steps, const std::string& speed_te fflush(stdout); // for linux } -static int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show -static float passed_time = 0.f; - void pretty_progress(int step, int steps, float time) { if (sd_progress_cb) { sd_progress_cb(step, steps, time, sd_progress_cb_data); return; } + pretty_console_progress(step, steps, time); +} + +void pretty_console_progress(int step, int steps, float time) { + static thread_local int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show + static thread_local float passed_time = 0.f; if (step == 0) { show_eta = -1; // reinitialize for batch generations passed_time = 0.f; @@ -654,7 +657,7 @@ void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float if (!byte_progress_console) return; } - if (sd_progress_cb) { + if (!byte_progress_console && sd_progress_cb) { float time = elapsed_seconds / (step + 1e-6f); sd_progress_cb(step, steps, time, sd_progress_cb_data); return; diff --git a/src/dgl/run_events.cpp b/src/dgl/run_events.cpp index 77a47e3ac..38e380b3f 100644 --- a/src/dgl/run_events.cpp +++ b/src/dgl/run_events.cpp @@ -45,6 +45,16 @@ namespace sd::dgl { run.progress_.report("loading", "", completed, total, "tensors"); } + void RunEvents::render_sample_progress(int completed, int total_steps, float time) { + const bool console_only = forces_console_progress(); + const bool renders_line = console_only || !sd_get_progress_callback(); + if (console_only) + pretty_console_progress(completed, total_steps, time); + else + pretty_progress(completed, total_steps, time); + sample_line_open_ = renders_line && completed > 0 && completed < total_steps; + } + void RunEvents::begin_sample(int total_steps) { check_cancelled(); finish_sample_line(); @@ -54,7 +64,7 @@ namespace sd::dgl { sd_begin_preview_pass(total_steps); last_progress_us_ = ggml_time_us(); if (uses_console_progress()) - pretty_progress(0, total_steps, 0.f); + render_sample_progress(0, total_steps, 0.f); progress_.begin_sample(total_steps, ""); check_cancelled(); } @@ -62,9 +72,8 @@ namespace sd::dgl { void RunEvents::sample_step(int completed, int total_steps) { if (uses_console_progress()) { const auto now = ggml_time_us(); - pretty_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f); + render_sample_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f); last_progress_us_ = now; - sample_line_open_ = completed > 0 && completed < total_steps && !sd_get_progress_callback(); } progress_.report_sample(completed, total_steps); check_cancelled(); @@ -90,8 +99,8 @@ namespace sd::dgl { RunEventsScope::RunEventsScope(RunEvents& events) : previous_(active_events), - byte_progress_(events.uses_legacy_progress() ? nullptr : RunEvents::report_loading, &events), - console_progress_(events.uses_console_progress()) { + byte_progress_(!events.uses_legacy_progress() && events.callbacks().progress ? RunEvents::report_loading : nullptr, &events), + console_progress_(events.forces_console_progress()) { active_events = &events; } RunEventsScope::~RunEventsScope() { diff --git a/src/dgl/run_events.h b/src/dgl/run_events.h index 7a2e1cb7b..21bb5438e 100644 --- a/src/dgl/run_events.h +++ b/src/dgl/run_events.h @@ -32,6 +32,7 @@ namespace sd::dgl { bool sample_line_open_ = false; static void preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata); + void render_sample_progress(int completed, int total_steps, float time); public: RunEvents(const RunCallbacks& callbacks, bool legacy_callbacks); @@ -43,7 +44,8 @@ namespace sd::dgl { void report_frames(const char* stage, int completed, int total) const; static void report_loading(int completed, int total, void* data); bool uses_legacy_progress() const { return legacy_progress_; } - bool uses_console_progress() const { return legacy_progress_ || !callbacks_.progress || callbacks_.console_progress; } + bool forces_console_progress() const { return !legacy_progress_ && callbacks_.console_progress; } + bool uses_console_progress() const { return legacy_progress_ || !callbacks_.progress || forces_console_progress(); } void begin_sample(int total_steps); void sample_step(int completed, int total_steps); void finish_sample_line(); diff --git a/thirdparty/httplib.h b/thirdparty/httplib.h index 62be061cd..0ab87875e 100644 --- a/thirdparty/httplib.h +++ b/thirdparty/httplib.h @@ -6216,7 +6216,7 @@ inline bool range_error(Request &req, Response &res) { } if (first_pos == -1) { - first_pos = content_len - last_pos; + first_pos = content_len - (std::min)(content_len, last_pos); last_pos = content_len - 1; } From 18d07d0e94cc8536e2f75644c91c8c65d1190f97 Mon Sep 17 00:00:00 2001 From: leejet Date: Thu, 26 Nov 2026 02:25:26 +0800 Subject: [PATCH 8/8] format --- examples/server/async_jobs.cpp | 4 ++-- examples/server/routes_dgl.cpp | 2 +- examples/server/routes_media.cpp | 16 ++++++++-------- examples/server/routes_sdcpp.cpp | 2 +- src/core/execution_engine.cpp | 8 ++++---- src/dgl/models/vae.cpp | 4 ++-- src/model/diffusion/relay_vsr.hpp | 24 ++++++++++++------------ 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index d01fbee80..6a35a85f4 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -696,7 +696,7 @@ namespace { if (!readable && status.type() != fs::file_type::not_found) return false; - const auto key = model_path_key(resolved); + const auto key = model_path_key(resolved); const bool allowed = policy.configured_files.count(key) || std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { return model_path_inside(root, resolved); @@ -840,7 +840,7 @@ void async_job_worker(ServerRuntime& runtime) { json dgl_result_info; std::string error_message; const char* error_code = "generation_failed"; - bool ok = false; + bool ok = false; if (job->kind == AsyncJobKind::ImgGen) { ok = execute_img_gen_job(runtime, *job, output_images, output_info, error_message); diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index bbbb0bcb6..1b7e1d6f8 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -179,7 +179,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { job->id = make_async_job_id(manager); manager.jobs.emplace(job->id, job); manager.queue.push_back(job->id); - auto response = make_async_job_json(manager, *job); + auto response = make_async_job_json(manager, *job); response["poll_url"] = "/sdcpp/v1/jobs/" + job->id; send_json(res, 202, response); } diff --git a/examples/server/routes_media.cpp b/examples/server/routes_media.cpp index 91788e84f..ad390a36d 100644 --- a/examples/server/routes_media.cpp +++ b/examples/server/routes_media.cpp @@ -8,10 +8,10 @@ #ifdef _WIN32 #include #else -#include #include #include #include +#include #endif namespace media_view { @@ -44,13 +44,13 @@ namespace media_view { GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtOpenFile")); if (!open_file) return FileHandle(); - auto name = std::filesystem::u8path(part).native(); + auto name = std::filesystem::u8path(part).native(); const auto bytes = static_cast(name.size() * sizeof(wchar_t)); UNICODE_STRING relative{bytes, bytes, name.data()}; OBJECT_ATTRIBUTES object; InitializeObjectAttributes(&object, &relative, OBJ_CASE_INSENSITIVE, parent.get(), nullptr); IO_STATUS_BLOCK status{}; - HANDLE handle = INVALID_HANDLE_VALUE; + HANDLE handle = INVALID_HANDLE_VALUE; const auto access = (directory ? FILE_TRAVERSE : FILE_READ_DATA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE; // A handle-relative open keeps every component under the directory already checked. if (open_file(&handle, access, &object, &status, FILE_SHARE_READ | FILE_SHARE_WRITE, @@ -74,7 +74,7 @@ namespace media_view { static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) { LARGE_INTEGER position{}; position.QuadPart = static_cast(offset); - DWORD count = 0; + DWORD count = 0; if (!SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) || !ReadFile(file.get(), buffer, static_cast(length), &count, nullptr)) return 0; @@ -109,7 +109,7 @@ namespace media_view { } static uint64_t file_size(const FileHandle& file) { - struct stat info {}; + struct stat info{}; if (fstat(file.get(), &info) != 0 || !S_ISREG(info.st_mode) || info.st_nlink != 1 || info.st_size <= 0) return 0; return static_cast(info.st_size); @@ -139,11 +139,11 @@ namespace media_view { auto parent = open_child(cwd, root, true); while (parent) { const auto slash = path.find('/'); - const auto part = path.substr(0, slash); + const auto part = path.substr(0, slash); if (!valid_component(part)) break; const bool directory = slash != std::string_view::npos; - auto child = open_child(parent, std::string(part), directory); + auto child = open_child(parent, std::string(part), directory); if (!directory) return child; parent = std::move(child); @@ -238,7 +238,7 @@ namespace media_view { if (size == 0 || size > std::numeric_limits::max()) return false; std::array header; - const auto count = read_at(file, 0, header.data(), header.size()); + const auto count = read_at(file, 0, header.data(), header.size()); const auto extension = path.find_last_of('.'); if (extension == std::string::npos) return false; diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index a17ea9613..5e92df0ff 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -341,7 +341,7 @@ static json make_capabilities_json(ServerRuntime& runtime) { }; result["generation_features"] = generation_features; result["generation_model_selection"] = true; - result["media_view"] = runtime.svr_params->media_view; + result["media_view"] = runtime.svr_params->media_view; result["runtime"] = model_status(runtime); result["current_mode"] = current_mode; result["supported_modes"] = supported_modes; diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp index 4707d0f70..60cd989b8 100644 --- a/src/core/execution_engine.cpp +++ b/src/core/execution_engine.cpp @@ -978,10 +978,10 @@ namespace sd { const auto budget_bytes = available.available_budget_bytes == SIZE_MAX ? std::string("unlimited") : sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0)); - auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget", - ggml_backend_name(request.compute_backend), - available.required_device_bytes / (1024.0 * 1024.0), - available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str()); + auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget", + ggml_backend_name(request.compute_backend), + available.required_device_bytes / (1024.0 * 1024.0), + available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str()); LOG_WARN("%s", message.c_str()); if (device_memory_error != nullptr && available.valid) { *device_memory_error = std::move(message); diff --git a/src/dgl/models/vae.cpp b/src/dgl/models/vae.cpp index 74cd45c78..64c42a7df 100644 --- a/src/dgl/models/vae.cpp +++ b/src/dgl/models/vae.cpp @@ -202,8 +202,8 @@ namespace sd::dgl::models { return decoded; } if (!sd::backend_fit::prepare_vae_decode_retry_tiling(tiling_params, prefer_temporal_tiling, - first_stage_model->last_compute_status(), - tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) { + first_stage_model->last_compute_status(), + tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) { break; } } diff --git a/src/model/diffusion/relay_vsr.hpp b/src/model/diffusion/relay_vsr.hpp index f818c4fa3..f3bf9dfa8 100644 --- a/src/model/diffusion/relay_vsr.hpp +++ b/src/model/diffusion/relay_vsr.hpp @@ -87,19 +87,19 @@ namespace RelayVSR { } ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* context, ggml_tensor* query_rope, ggml_tensor* key_rope, const VSR::LocalAttention* local, const std::string& cut_group, const std::string& attention_name) { - auto to_q = std::dynamic_pointer_cast(blocks["to_q"]); - auto to_k = std::dynamic_pointer_cast(blocks["to_k"]); - auto to_v = std::dynamic_pointer_cast(blocks["to_v"]); - auto to_out_0 = std::dynamic_pointer_cast(blocks["to_out.0"]); - auto norm_q = std::dynamic_pointer_cast(blocks["norm_q"]); - auto norm_k = std::dynamic_pointer_cast(blocks["norm_k"]); - auto c = ctx->ggml_ctx; - auto q = norm_q->forward(ctx, to_q->forward(ctx, x)); + auto to_q = std::dynamic_pointer_cast(blocks["to_q"]); + auto to_k = std::dynamic_pointer_cast(blocks["to_k"]); + auto to_v = std::dynamic_pointer_cast(blocks["to_v"]); + auto to_out_0 = std::dynamic_pointer_cast(blocks["to_out.0"]); + auto norm_q = std::dynamic_pointer_cast(blocks["norm_q"]); + auto norm_k = std::dynamic_pointer_cast(blocks["norm_k"]); + auto c = ctx->ggml_ctx; + auto q = norm_q->forward(ctx, to_q->forward(ctx, x)); const auto cache_name = cut_group + "." + attention_name; - auto past_k = ctx->get_cache_tensor(cache_name + ".key"); - auto past_v = ctx->get_cache_tensor(cache_name + ".value"); - ggml_tensor* k = nullptr; - ggml_tensor* v = nullptr; + auto past_k = ctx->get_cache_tensor(cache_name + ".key"); + auto past_v = ctx->get_cache_tensor(cache_name + ".value"); + ggml_tensor* k = nullptr; + ggml_tensor* v = nullptr; if (context && past_k) { k = past_k; v = past_v;