Five Default Assumptions of a Qt Desktop Workbench: From file:// to app://

🇨🇳 中文版

Project context: how Lume and lume-qt relate

Worth settling the name first, because otherwise the run of lume-prefixed symbols later makes it look as though the whole project were written in Lume.

Lume is a single-binary C11 backend framework: business logic lives in .lume scripts, and the artifact is a roughly 1.7 MB executable that serves static sites, JSON APIs, SSE, and native SQLite at once; no Node runtime, no separate frontend service process. It owns only the DSL layer — HTTP, sessions, and MCP come from a statically linked agent-httpd.

Writing it means a server declaration plus a route, with data going straight to SQLite:

server {
  port = medmon_port;
  workers = medmon_workers;
  bind = medmon_bind;
};

get "/api/medmon/health", (req) => {
  let r = try(() => sql_write(db, "DELETE FROM events WHERE id = -1"));
  if (r.err != null) {
    return { status: 503, body: { ok: false, err: r.err } };
  }
  return { body: { ok: true, write: true } };
};

Source: tools/lume-medmon/app.lume, once for the probe route declaration and once for its SQLite write transaction. That route is a "zero-row write" probe of the write path: it modifies no business data, yet it genuinely opens a SQLite write transaction, so it catches the "reads are fine, POST is stuck" state that a process-alive check misses.

In lume-qt, Lume plays exactly one role: the desktop shell hands audit uploads, alarm-threshold delivery, and the health probe to this reference service, and the shell needs a single environment variable, QTRS_LUME_URL=http://127.0.0.1:8090. The local JSONL ledger stays authoritative; the Lume mirror is optional and non-blocking, and it also exposes three read-only tools (medmon_summary, medmon_events, medmon_review) for engineering review. This reference implementation does not carry what production needs — per-case indexes, retention cleanup, write-side authentication — and the service itself has neither authentication nor TLS by default, so it belongs on loopback only.

So all five default assumptions in this article live on the Qt side: Lume is neither a runtime dependency of the C++ host nor a target of these replacements. lumesink.cpp, isAllowedLumeKey, and digestForLume name "the path that uploads to the Lume service"; that code is C++ from beginning to end and unrelated to DSL syntax.

Here is that boundary laid out, so the five replacements have somewhere to land:

React / TypeScript         workbench UI · 3D volume rendering · live dashboard · state
        ↕  QWebChannel (properties + signals; the JS side initiates, the host answers)
Qt / C++ host              window lifecycle · device I/O · DICOM parsing · scheme responses · index writes
        ↕  local files / local processes
local services             Lume reference service (audit upload, optional) · JSONL authoritative ledger

Each of the three edges has its own protocol: app:// governs how pages and assets are loaded, QWebChannel governs how host and page talk, and QTRS_LUME_URL governs how the shell uploads audit records to the mirror. The five replacements each touch one edge, not the architecture as a whole.

TL;DR

  • The default path — file:// loading static artifacts, QWebChannel injected into the page — holds for a single page with no routing and low-frequency bridging; once history routing, real-time data, and dirty data stack up, the failure points are not in the UI.
  • The page is served through a custom app:// scheme: host-answered means a fallback rule finally has a place to live, and the extension-less deep-link fallback now sits in resolveRequestPath; with no router dependency today it will not fire. The bridge is unaffected, since the official bridge only requires send and onmessage.
  • Frontend artifacts hook into the C++ build chain through two edges: ALL puts them in the default build, add_dependencies puts them ahead of the host target; without the second, make cpp leaves artifact consistency to a human who remembers.
  • Link health cannot be inferred from a single frame's age: SignalState / ChannelHealth / BatchSeries separate interruption, slowness, and batch queueing; DICOM marks missing values with hasZ instead of using 0 as a sentinel.
  • De-identification is not one regex: path rules must run before UID rules (the other order leaves half a path behind), and the outbound payload keeps only allowlisted fields, dropping unknown ones by default.

Source: https://github.com/erishen/lume-qt

The default path: the starter shape and the intersection where it holds

Most Qt WebEngine desktop projects start in the same shape: the frontend uses Vite or webpack to produce a build that lands in resources/web; the C++ side loads a file:// entry point with QWebEngineView; two-way communication injects a QObject through QWebChannel; and the build order is "frontend first, then C++, then package it all together".

Why it is popular is plain: it mostly decouples build from runtime. What runs in a browser will largely run inside QWebEngineView; a frontend engineer does not need to understand CMake, and a host engineer does not need to understand Vite; static artifacts drop into any resource system. For a tool-like app of one page, a few buttons, and a handful of bridge calls, it costs almost nothing. The four comment lines at the top of Makefile are that idea in miniature: targets reachable on their own, frontend artifacts directed into resources/web, the C++ build consuming them.

The communication half is designed as "inject it and it works". The repository ships Qt's official qwebchannel.js as-is:

var QWebChannel = function(transport, initCallback, converters)
{
    if (typeof transport !== "object" || typeof transport.send !== "function") {
        console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
                      " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
        return;
    }

Source: the QWebChannel constructor in frontend/public/qwebchannel.js. The constructor checks only that transport has send and onmessage; the message-type table QWebChannelMessageTypes (same file) defines nothing but protocol semantics — signal, propertyUpdate, init, invokeMethod — and makes no assumption about which URL the page was loaded from. So "file:// + static artifacts + QWebChannel" becomes a self-consistent minimal loop.

The intersection where it holds is narrower than it looks: a single page, no history routing, packaged assets that do not depend on an absolute root path, a frontend built once at release time, low-frequency links, clean data, and a single instance held by agreement. Inside that intersection — tool-like shells, internal demos, read-only panels — the simplicity is a real advantage, and there is no reason to replace it just to look better architecturally.

What the approach does wave through, though, are two omissions treated as always true: "how the page loads has nothing to do with business logic", and "when the frontend is rebuilt is decided by a human, in the right order". Against real-time data, dirty data, and data egress, those two omissions produce five concrete failure points; each is paired with its replacement below.

The five replacements

Replacement one: the page no longer loads from file://

Failure: As soon as the page uses history routing, or packaged assets are referenced by an absolute root path, file:// has no server-side fallback, and a deep-link refresh lands on an empty path. That is not "inelegant" — it is "not working".

Replacement: Give the page its own scheme, answered by the host. But be precise about what that buys: a place where a fallback rule can be written, not the fallback itself. The file:// problem is not "a missing handler"; it is that there is nowhere to put a fallback at all. app:// creates that place; whether a rule goes into it, and which rule, stays the host's decision.

Evidence: This is not an announcement but a hard registration in the startup path, and it carries an ordering constraint:

    // 注册自定义 scheme 必须在 QApplication 构造之前,
    // 否则 Qt WebEngine 会拒绝使用未注册的 scheme。
    QWebEngineUrlScheme scheme("app");
    scheme.setSyntax(QWebEngineUrlScheme::Syntax::Host);

Source: the top of main() in src/main.cpp. Registration only stands the scheme up; the flags are what draw the security boundary, and all five are set together:

    scheme.setFlags(
        QWebEngineUrlScheme::Flag::SecureScheme
        | QWebEngineUrlScheme::Flag::LocalScheme
        | QWebEngineUrlScheme::Flag::LocalAccessAllowed
        | QWebEngineUrlScheme::Flag::CorsEnabled
        | QWebEngineUrlScheme::Flag::FetchApiAllowed);

Source: the setFlags call right after. The five flags are not equivalent; each governs a different permission. SecureScheme marks the scheme as potentially trustworthy: it only affects how the browser judges a secure context, and Qt intends it for schemes that can guarantee authenticity, confidentiality and integrity — it supplies no encryption, authentication or integrity guarantee itself. LocalScheme marks it as a local-resource scheme. LocalAccessAllowed opens its access to local resources. CorsEnabled permits cross-origin requests. FetchApiAllowed lets the page fetch from it. All five are on for concrete reasons — the page fetches the volume binary, assets share the page's origin, and the data layer is reached cross-origin — but turning all five on pushes this project's trust surface to its widest, and production setups should enable them one by one against real needs rather than copying the block.

The next question is who answers. AppSchemeHandler has exactly four branches:

Request Handling Source
app://app/ empty path normalised to index.html src/schemepath.cpp, empty-path branch
app://app/console (extension-less deep link) normalised to index.html as well src/schemepath.cpp, extension-less branch
app://app/__volume/current.bin bypasses the filesystem, served by the provider src/appschemehandler.cpp, __volume branch
app://app/assets/index-abc.js read from disk, MIME type by extension src/appschemehandler.cpp, disk branch
anything else that does not exist (including traversal attempts) UrlNotFound, no rewrite src/appschemehandler.cpp, fall-through

The fallback rule is short, but it has to exist as its own thing: scheme::resolveRequestPath (src/schemepath.cpp) strips the leading /, sends an empty path to the entry page, and treats any extension-less route-like path as index.html. The character set is limited to letters, digits and / _ -, so a path like /../etc/passwd is never quietly laundered into the front page — it still goes through the canonical check and 404s. All the handler does is one call, which separates "who answers" from "how it falls back".

That rule has unit tests behind it: tests/scheme_path_test.cpp covers the root, two deep-link shapes (/console, /review/7), asset pass-through, virtual-resource pass-through, and suspicious paths left unwritten, running as SchemePathUnitTests under ctest.

The bridge side is unaffected either way: the official bridge only requires a transport with send and onmessage (the QWebChannel constructor in frontend/public/qwebchannel.js), and protocol types are independent of the URL scheme (same file).

Boundary: Without history routing and without absolute-root assets, switching schemes is just one more handler to maintain. That is exactly this project's state — there is no router dependency (no react-router, no wouter in frontend/package.json), the fallback is written and will never fire, so what it bought is "no host-side change when routing arrives later", not "404s gone today".

Replacement two: when the frontend is built no longer rests with a human

Failure: Once the frontend and C++ share one data contract, "the human remembers to run them in the right order" does not hold. Forgetting the frontend, running a stale artifact, or having the C++ side see the previous resources/web all surface as "the code is right, the output is wrong", and nothing raises an error. That is not a defect of some build system; it is the price of decoupling the two builds under specific constraints.

Replacement: Hang the frontend build onto the C++ dependency chain — but be precise that it takes two edges: ALL puts it in the default build, add_dependencies puts it ahead of the host target. Without the second, "the frontend builds first" is still a coincidence of default ordering.

Evidence: The first edge is ALL on the custom target:

add_custom_target(frontend-build ALL
    COMMAND "${BASH_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/frontend-build.sh"
    COMMENT "Building React frontend (Vite) → resources/web (skipped if unchanged)"
    VERBATIM
)

Source: the frontend-build target definition in CMakeLists.txt.

The second edge is the host target's explicit dependency on it:

add_dependencies(lume-qt frontend-build)

Source: the add_dependencies(lume-qt frontend-build) line in CMakeLists.txt, plus its two comment lines. This is the one that gets missed: ALL only answers "does this target join the default build", not "who goes first" — ninja is free to compile the host and run the frontend build afterwards. With the edge in place, the first task of cmake --build build --target lume-qt is the frontend build ([1/6] Building React frontend (Vite) → resources/web), a direct observation of the ordering rather than an assurance in prose.

This is also a pit the first draft of this article fell into: it showed ALL alone and called it a predecessor. ALL governs membership and add_dependencies governs order; conflating them leaves readers with the same gap in their own project.

The script compares frontend sources and skips when nothing changed, so the dependency does not degrade incremental builds into full rebuilds; the configure target also skips CMake configuration when build.ninja already exists, leaving regeneration to ninja (Makefile, the configure target). Build variables are fixed at the top of the file and overridable from the environment (Makefile build variables at the top), so the chain does not collapse into one hard-coded path on another machine.

Boundary: When the Web page is only an optional debug panel and not part of the main interface, hanging the frontend onto the main build chain just slows compilation down.

Replacement three: link health is no longer inferred from a single frame's age

Failure: A working bridge only means messages can be sent and received. Arrival times shift wholesale when the render process is busy, the compositor queues, or the page is throttled while invisible; and worse, one callback is not one sample — real-time data such as ECG arrives as individual signals, while the receiving side folds several samples that land in the same microtask into one batch (pendingBatch and flushBatch, carrying startUs and per-channel counts). One frame's age therefore mistakes batch queueing for a slow link. Qt's own batching is a different layer: propertyUpdateInterval (50 ms by default) governs property updates only, and every property this project exposes is CONSTANT (the Q_PROPERTY block in src/bridge.h), so the real-time path never touches it — generalising property batching to all signals conflates two mechanisms. Then there is the clock source: the tsUs of a real-time sample is the acquisition instant, while the tsUs of a DICOM volume is the host-side parse-completion instant; subtracting offsets against one device clock yields an absurd age.

Replacement: Turn each channel's arrival times into a stateful statistical model — an explicit state set, per-channel thresholds, and batch delivery judged separately from real delay.

Evidence: Channel, SignalState, and ChannelHealth's ageMs and staleAfterMs (all in frontend/src/latency.ts) turn "interrupted" from a UI impression into a queryable value; BatchSeries's samples and gaps (same file) separate delay from backlog; volume is listed in HOST_STAMPED_CHANNELS and therefore takes no device-clock offset subtraction.

The time base deserves its own note: nowMicros uses performance.timeOrigin + performance.now() (in frontend/src/latency.ts, with the reasoning in the module comment). performance.now() is a monotonic clock, and timeOrigin anchors that monotonic reading to the wall-clock origin, so intervals are immune to NTP correction or a user changing the system clock; the volume channel's tsUs, by contrast, is wall-clock at parse completion. Different semantics — mixing them is simply wrong. One more limit: a batch records startUs and per-channel counts, with no per-sample sequence number, so you can see batches growing and gaps widening, but you cannot attribute one delayed delivery to one frame.

Boundary: The model holds only while the link is a continuous stream. alarm is an event channel that records only "how long this one took" and has no age/interruption semantics; volume is a one-shot parse on the order of seconds, and a 100 ms link budget would judge it slow forever, so it gets its own budget.

Replacement four: missing DICOM fields no longer fall back to defaults

Failure: DCMTK's findAndGetFloat64 writes 0 into the output when the tag is missing. So "read the rescale slope and use it" yields slope=0 on MR series that usually have no Rescale tag, and the whole volume turns all-zero and black; the sample brain T1 happened to carry an explicit 1/0, which is why the trap stayed hidden. The same class of problem shows up in bit depth: truncating 16-bit data with >> 8 erases the effective value.

Replacement: Fall back explicitly to the initial value the caller set; carry presence in a separate field instead of letting a number double as sentinel; store pixels at their original width.

Evidence: The trap and the fallback live in the same file — the comment explains DCMTK's behavior, and the code pins the fallback on two bad() branches:

    // rescale slope / intercept(CT 常非 1/0,MR 多为 1/0,但不可假定)
    //
    // 注意:DCMTK 的 findAndGetFloat64 在标签缺失时会把出参写成 0(不是保留
    // 原值)。之前直接 `findAndGetFloat64(DCM_RescaleSlope, slope)` 会让没有
    // Rescale 标签的序列(MR 很常见)变成 slope=0 → 整个体积全零 → 黑屏。
    // 样例脑部 T1 恰好显式写了 1/0,所以这个坑一直被掩盖。
    double slope = 1.0, intercept = 0.0;
    if (ds->findAndGetFloat64(DCM_RescaleSlope, slope).bad())
        slope = 1.0;
    if (ds->findAndGetFloat64(DCM_RescaleIntercept, intercept).bad())
        intercept = 0.0;

Source: the rescale fallback in src/dicomreader.cpp — the fallback has to be written out, or the 1.0 / 0.0 the caller set gets eaten by that 0.

The same idea is clearer in the structure: Slice splits "is there a Z" into a separate field, and raw keeps the original 16-bit width.

struct Slice {
    std::vector<uint16_t> raw; // rows × cols(行主序),8 位数据也统一存为 uint16
    int rows = 0;
    int cols = 0;
    double z = 0.0;      // 空间 Z(ImagePositionPatient 第 3 轴)
    bool hasZ = false;   // 是否真的读到了 Z —— 不能用 z==0.0 当哨兵

Source: the Slice definition in src/dicomreader.cpp. hasZ exists so that z == 0.0 need not double as a sentinel, and std::vector<uint16_t> preserves full bit depth — both reasons are in the comments rather than reconstructed after the fact.

That fallback has no unit test behind it: tests/ holds only bridge_test.cpp and volume_stats_test.cpp, with no DICOM parsing cases. The minimum matrix worth adding is four rows:

Case slope / intercept Expectation
CT with an explicit Rescale 2 / -1024 converted from the original values, no fallback
MR without the Rescale tag unreadable (DCMTK writes 0 into the out-params) falls back to 1 / 0, volume not black
Explicit zero values 0 / 0 treated as genuine zeros, not overwritten by the fallback
No ImagePositionPatient no Z hasZ=false, excluded from slice-spacing maths

The first three rows check that the fallback does not eat a legitimate zero; the fourth checks that absence is not impersonated by a value — which is what the Slice boolean is for.

The fallback also has a scope that must not be overread into "read one global slope/intercept and you are done for every DICOM": it covers top-level Rescale Slope/Intercept on conventional CT/MR. Enhanced Multi-frame puts some attributes in per-frame functional groups, so one global read does not apply to every frame; and when a Modality LUT is present, slope/intercept cannot be applied unconditionally — the precedence follows the standard. Extending to such datasets starts with confirming the actual read path, not assuming it is covered. One more thing worth pinning down: 1.0 / 0.0 is a fallback this application picks for a missing tag, not a default the standard prescribes.

Boundary: Only fields where zero is a legitimate value need that extra boolean. In a format where 0 naturally means "absent", the sentinel is the cheaper spelling.

Replacement five: from string regexes to layered data minimisation

Failure: Reduced to "run a regex before shipping", de-identification stands or falls on two things that are rarely written down — rule order, and whether there is an allowlist underneath. Paths often embed a DICOM UID (/data/1.2.840.113619…/slice.dcm), and running the UID rule first cuts the path in the middle, leaving a shorter but far more conspicuous bare path behind; a denylist also never catches up with new fields — a vendor adds one tag, a debug build logs one more field, and the data is out.

Replacement: Split it into three stages in a fixed order — path folding, UID folding, field allowlist. Be precise about the reach: this is minimisation at the string layer, not de-identification. PHI does not live only in paths and UIDs.

Evidence: In scrubText (src/lumesink.cpp) the path rule runs before the UID rule, with a character class that admits spaces so macOS directory names like Application Support are covered; the UID rule uses \d+(?:\.\d+){2,}, so three-segment forms such as 2.25.<integer> do not slip through, at the cost of folding IPv4-looking strings as well.

QString scrubText(const QString &text)
{
    QString out = text;
    // 路径先于 UID 折叠:路径里常带 DICOM UID,先吃掉整段才不会留下半截。
    // 字符类允许空格(macOS 的 "Application Support" 这类目录名很常见),
    // 到句子标点或换行停止;宁可连尾随描述一起折掉,也不能留下半截路径。
    static const QRegularExpression homePathRe(
        QStringLiteral("~/[^\\r\\n,;\"'。;,、]+"));
    static const QRegularExpression windowsPathRe(
        QStringLiteral("[A-Za-z]:[\\\\/][^\\r\\n,;\"'。;,、]+"));
    static const QRegularExpression unixPathRe(
        QStringLiteral("(?:/Users|/home|/private|/tmp|/var|/opt|/Library|/Applications|/System|/Volumes)"
                       "/[^\\r\\n,;\"'。;,、]+"));
    // DICOM UID 可以只有三段(2.25.<整数> 是 UUID 派生形式);旧正则要求五段,
    // 会把 2.25.* 与 1.2.840.10008 这类短 UID 原样放行。IPv4 与此同形,会一并
    // 折叠成 <uid>,属于可接受的过度脱敏:本地 JSONL 仍是完整权威记录。
    static const QRegularExpression uidRe(QStringLiteral("\\d+(?:\\.\\d+){2,}"));
    out.replace(homePathRe, QStringLiteral("<path>"));
    out.replace(windowsPathRe, QStringLiteral("<path>"));
    out.replace(unixPathRe, QStringLiteral("<path>"));
    out.replace(uidRe, QStringLiteral("<uid>"));
    return out;
}

Source: scrubText in src/lumesink.cpp.

Stabilizing identifier fields falls to digestForLume: the lume-qt| domain prefix, then SHA-256, truncated to 16 hex characters (the digestForLume function), yields a pseudonym stable inside this project's domain. The prefix buys domain separation, not secrecy: the same original value hashes differently here than in another system, so identifiers are not trivially reused across domains. But a prefix is not a key — anyone who knows the original value and the rule can recompute it and correlate, and known-input dictionary matching still works. Cross-system unlinkability would need HMAC-SHA-256 with a managed key, which this project has not implemented. Truncating to 64 bits is a trade-off between identifier length and storage cost, not a guarantee of cryptographic strength: once the identifier set grows, birthday collisions belong in the assessment — and a public prefix only separates namespaces that use different prefixes, nothing more.

Boundary: By layer, two of the three are done and the third is empty.

  • Layer one, string folding: covers "paths and UIDs that already made it into a string", nothing more.
  • Layer two, key allowlist: sanitizeValue recurses through objects and arrays (the sanitizeValue function), so nesting does not leak keys; but isAllowedLumeKey grants by key, not by path. The same key is a timing field (ageMs) in one place and free text in another, and a flat allowlist cannot tell them apart. A stronger version has to grant by path.
  • Layer three, at rest: the local JSONL is still sensitive data. Not leaving the machine is not the same as being safe — file permissions, retention, backup and cleanup are nobody's job among those three regexes; prunePacsStoreIfConfigured only keeps "delete nothing by default" true, which is not a retention policy.

One class of thing sits outside this mechanism altogether: PatientName, InstitutionName, private tags, free-text descriptions, exception and debug output. scrubText processes strings, not the data model, so it cannot see that the field itself is called patient name.

So the scope of this machinery has to be nailed down: this machinery minimises and pseudonymises the text that goes up to Lume. It is not a de-identification implementation in the DICOM PS3.15 sense, which requires working through an attribute list across the whole dataset, private tags and burned-in pixel data included. Reading scrubText as "clears PHI from the whole file" overrates it.

Which is why the section title had to change: "one regex to three fixed stages" reads as if three regexes were a de-identification scheme. The accurate description is a fixed order at the string layer plus a key allowlist at the structure layer — together, the first two layers of layered minimisation, no more.

Boundaries: outside the intersection, and the lines that must not be crossed

Read the five replacements backwards and you get the criteria for staying on the default path. That reads better as a table than as prose — left to right it says "when to switch", right to left "when to stay":

Project condition What to take Why
Single page, no routing, assets not tied to an absolute root file:// a scheme swap just adds one more handler
SPA with history routing app:// plus an explicit fallback rule the scheme only provides the place; the rule is yours to write
Frontend and backend share a data contract frontend build as a build-graph edge human ordering does not hold artefacts consistent
Continuous real-time stream per-channel health model one frame's age cannot separate backlog from delay
Zero can be a legitimate value explicit presence flag a value doubling as a sentinel swallows a real 0
Medical data going outbound string-layer folding plus key allowlist a denylist never catches up

Not a list of concessions, but the same thing read from both sides: where the left column does not hold, the right-hand machinery buys nothing but complexity.

A few lines should not be crossed even when the premises hold, because crossing them turns a trade-off into an error. First, the direction of de-identification: isAllowedLumeKey states that the outbound payload keeps only fields needed for audit and timing, and drops unknown ones rather than passing them by default — a missing field costs less than PHI leaving the machine, so "pass by default plus a denylist" swaps defense in depth for a single point. The same holds for rule order inside scrubText: reverse it and half a path survives. Second, clock sources stay separate: the volume channel's tsUs is host-side time, and merging it "for cleaner handling" turns the age on the dashboard into a fake number. Third, retention cleanup must not be treated as on by default: prunePacsStoreIfConfigured returns early when the environment variable is empty or non-positive (if (env.isEmpty()) return; and if (days <= 0) return;, the prunePacsStoreIfConfigured in src/bridge.cpp), and removing that check turns "deletes nothing by default" into "deletes by default".

Fourth, process uniqueness. The data directory and the volume-rendering preferences both assume a single writer; refusing a second instance is not fastidiousness but a guard against two processes overwriting the same files. QLockFile was not used casually here — its staleness test reads file age and process liveness together, and setting staleLockTime to 0 turns the liveness check off with it, so after a kill -9 the app can no longer start at all — and it did not adopt the more common "O_CREAT | O_EXCL lock plus a PID liveness check plus deleting the stale lock" path either — what follows is why that path was abandoned: testing staleness and deleting are two separate steps. When A and B both decide the old lock is dead, the fresh lock A has just taken can be swept away by B's delete, after which B takes the lock too and two instances each believe they own it (the reasoning sits in the file header of src/instancelock.h).

What it does now is hand ownership to the kernel:

    // O_CREAT 只负责「文件不存在就建」,不承担互斥;互斥由下面的 flock 完成。
    const int fd = ::open(path.toUtf8().constData(), O_CREAT | O_RDWR, 0644);
    if (fd < 0)
        return false;

    // LOCK_NB:拿不到立即返回,不阻塞启动(阻塞等锁在桌面应用里表现为卡在启动画面)。
    if (::flock(fd, LOCK_EX | LOCK_NB) != 0) {

Source: InstanceLock::acquire in src/instancelock.cpp. O_CREAT only creates the file and carries no mutual exclusion; flock does all of it. The lock travels with the file descriptor, so a kill -9 closes the fd in the kernel and releases the lock immediately — there is no stale-lock state to detect and no stale file to delete, and that race window is eliminated by the mechanism rather than patched with extra checks in our code. The pid is still written into the file, but only to render the "an instance is already running (pid=…)" message; it plays no part in deciding ownership.

The cost and the boundary are written down in the file header of src/instancelock.h: flock is only reliable on local filesystems, and NFS semantics depend on the server implementation (this application keeps its state directory on local disk and shares it across no machines, so the assumption holds). The lock file also survives exit, holding the last holder's pid — harmless, and deliberately not deleted: removing it opens a window between the path disappearing and the next process creating a fresh inode, in which a process still finishing its shutdown and a new starter could both believe they hold the lock. Four cases guard these properties (tests/instance_lock_test.cpp): first acquisition succeeds, a second fails and reports the holder, a release lets another acquire, and a leftover file does not stop a new process.

To check where those boundaries sit, the cheapest route is to run the replacements before and after with the repository's own targets:

make all          # full build (frontend + C++)
make bridge_test  # bridge layer only
make cpp          # configure + compile C++, frontend synced
make frontend     # frontend only (artifacts → resources/web)
make clean        # clean build and frontend artifacts

The difference is not line length on the command line: the former needs a human to guarantee order, the latter has the build graph guarantee it.

One last line: counterintuitive does not mean universally true. The default path is right inside its intersection, and this set of replacements is right inside its premises; engineering judgment is never about which road is more advanced, but about which intersection the project is standing in.

Source code navigation

Repository: https://github.com/erishen/lume-qt

The body names files and symbols only; line numbers are omitted because they drift with every commit — search by symbol or by the quoted snippet.

File What to look at
Makefile build targets and variables: all, frontend, configure, clean, bridge_test
CMakeLists.txt WEB_ROOT, the ALL on frontend-build, and add_dependencies
src/main.cpp scheme registration and the five flags
src/schemepath.cpp normalisation and fallback in scheme::resolveRequestPath
src/appschemehandler.cpp the four answer branches: __volume, disk, fall-through
src/instancelock.h the trade-offs behind InstanceLock
src/instancelock.cpp acquire and release
frontend/src/latency.ts nowMicros, ChannelHealth, BatchSeries
frontend/public/qwebchannel.js the bridge’s minimal contract (send / onmessage)
src/dicomreader.cpp field presence (hasZ) and the rescale fallback
src/lumesink.cpp scrubText, isAllowedLumeKey, digestForLume
src/bridge.h properties (all CONSTANT) and signals
src/bridge.cpp the default retention window
tools/lume-medmon/app.lume probe routes

[faq] Q: Why not load the packaged frontend directly from file://? A: It has no server-side fallback, so deep-link refreshes and absolute-root assets fail; once the host answers, a fallback rule finally has somewhere to live (see replacement one). [/faq]

[faq] Q: Why can't link health be judged from a single frame's age? A: One callback may stand for a batch of samples: ageMs / staleAfterMs detect interruption, while BatchSeries's samples and gaps separate delay from backlog (see replacement three). [/faq]

[faq] Q: What happens when a DICOM rescale slope cannot be read? A: when the Rescale tag is missing, DCMTK writes 0 into the out-param, so lume-qt judges by the status returned from findAndGetFloat64 and falls back to the application-level 1.0 / 0.0 — the MR series no longer renders black. That is a different matter from whether the structure carries a Z at all, which Slice::hasZ marks separately. Both keep zero from doubling as a missing-value sentinel, but they cover different fields. [/faq]

[faq] Q: When should the default path be kept? A: The criteria are the left column of the boundaries table; where those conditions do not hold, the replacements buy nothing but complexity. [/faq]

Comments (0)

    Comments require approval before appearing. Markdown supported.

    ← Back to list
    erishen

    Written by

    erishen

    Senior full-stack engineer focused on AI application engineering & delivery. Author of lume, lume-core and open-source AI engineering tooling.

    ⭐

    Enjoy this article?

    erishen/lume-qt

    Star on GitHub