// Actual gRPC transport against a loopback-only fake. No robot connection exists. #include "bioheadjointclient.h" #include "robotclient.h" #include "cmvr/api/biohead_service.grpc.pb.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { void check(bool value, const char *message) { if (!value) throw std::runtime_error(message); } bool waitFor(const std::function &ready, int timeout = 6000) { QElapsedTimer elapsed; elapsed.start(); while (!ready() && elapsed.elapsed() < timeout) { QCoreApplication::processEvents(); QThread::msleep(2); } return ready(); } void pump(int milliseconds = 80) { QElapsedTimer elapsed; elapsed.start(); while (elapsed.elapsed() < milliseconds) { QCoreApplication::processEvents(); QThread::msleep(2); } } const char *jointIds[] = {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}; const double minima[] = {-1., -.35, -1.5, -.65, -1.5}; const double maxima[] = {1., .55, 1., .70, .393}; const char *neutralId = "0de8a527543e423abab593484926dd1c"; const char *smileId = "ad8f669a78d54d30a2356512b0802c1d"; class FakeHead final : public cmvr::api::BioHeadService::Service { public: enum Result { Acknowledge, Reject, MissingSuccess, Timeout }; std::atomic states{0}, controls{0}, plays{0}, expressions{0}, cancels{0}; std::atomic holdState{false}, holdControl{false}, holdPlay{false}, holdExpression{false}; std::atomic playEntered{false}, playCanceled{false}; std::atomic expressionEntered{false}, expressionCanceled{false}, baseline{true}; std::atomic expressionDeadlineMs{0}; std::atomic nextControl{Acknowledge}, nextExpression{Acknowledge}; std::atomic nextStateOutcome{Acknowledge}; std::atomic nextStateDelayMs{0}, stateDeadlineMs{0}, stateValidityMs{0}; // Malformed metadata must invalidate a previously usable configuration. std::atomic nextStateFault{0}; grpc::Status GetHeadJointState(grpc::ServerContext *context, const cmvr::api::GetHeadJointStateCommand::Request *request, cmvr::api::GetHeadJointStateCommand::Feedback *response) override { ++states; { std::lock_guard guard(mutex); stateDevices.push_back(request->header().device_id()); statePeers.push_back(context->peer()); } stateValidityMs.store(static_cast(request->header().valid_for_ms())); stateDeadlineMs.store(static_cast(std::chrono::duration_cast( context->deadline() - std::chrono::system_clock::now()).count())); const auto ready = std::chrono::steady_clock::now() + std::chrono::milliseconds(nextStateDelayMs.exchange(0)); while (std::chrono::steady_clock::now() < ready && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); while (holdState.load() && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); if (context->IsCancelled()) return {grpc::StatusCode::CANCELLED, "fake state canceled"}; const Result outcome = nextStateOutcome.exchange(Acknowledge); if (outcome == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake state read deadline"}; if (outcome == Reject) { response->mutable_header()->set_success(false); response->mutable_header()->set_error_message("fixture state unavailable"); return grpc::Status::OK; } if (outcome == MissingSuccess) return grpc::Status::OK; response->mutable_header()->set_success(true); response->set_connected(true); response->set_position_feedback_available(false); response->set_hardware_emergency_stop_available(false); response->set_expression_baseline_ready(baseline.load()); response->set_last_command_outcome(cmvr::api::HEAD_JOINT_COMMAND_ACKNOWLEDGED); for (int index = 0; index < 5; ++index) { auto *info = response->add_joint_info(); info->set_id(jointIds[index]); info->set_min_position_rad(minima[index]); info->set_max_position_rad(maxima[index]); info->set_home_position_rad(index == 4 ? -1. : 0.); auto *target = response->add_targets(); target->set_id(jointIds[index]); target->set_target_position_rad(index == 4 ? -1. : 0.); target->set_target_valid(true); } for (int preset = 0; preset < 2; ++preset) { auto *expression = response->add_expressions(); expression->set_expression_id(preset ? smileId : neutralId); expression->set_expression_name(preset ? "微笑" : "中立"); for (int index = 0; index < 5; ++index) { auto *target = expression->add_targets(); target->set_id(jointIds[index]); target->set_position_rad(index == 4 ? -1. : (preset ? .2 : 0.)); } } switch (nextStateFault.exchange(0)) { case 1: response->mutable_joint_info(1)->set_id(jointIds[0]); break; case 2: response->mutable_joint_info(0)->set_max_position_rad(minima[0]); break; case 3: response->mutable_expressions(0)->mutable_targets()->RemoveLast(); break; default: break; } return grpc::Status::OK; } grpc::Status ControlHeadJoints(grpc::ServerContext *context, const cmvr::api::HeadJointCommand::Request *request, cmvr::api::HeadJointCommand::Feedback *response) override { ++controls; { std::lock_guard guard(mutex); controlRequests.push_back(*request); } if (request->has_cancel_expression()) { ++cancels; response->mutable_header()->set_success(true); return grpc::Status::OK; } const Result result = nextControl.exchange(Acknowledge); while (holdControl.load() && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); if (context->IsCancelled()) return {grpc::StatusCode::CANCELLED, "fake control canceled"}; if (result == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake write outcome unknown"}; if (result == Reject) { response->mutable_header()->set_success(false); response->mutable_header()->set_error_message("fixture firmware rejected command"); } else if (result == Acknowledge) response->mutable_header()->set_success(true); return grpc::Status::OK; } grpc::Status PlayHeadExpression(grpc::ServerContext *context, const cmvr::api::PlayHeadExpressionCommand::Request *request, cmvr::api::PlayHeadExpressionCommand::Feedback *response) override { ++plays; { std::lock_guard guard(mutex); playRequests.push_back(*request); } playEntered.store(true); while (holdPlay.load() && !context->IsCancelled() && cancels.load() == 0) std::this_thread::sleep_for(std::chrono::milliseconds(2)); if (context->IsCancelled()) { playCanceled.store(true); return {grpc::StatusCode::CANCELLED, "fake expression canceled"}; } response->mutable_header()->set_success(true); response->set_expression_id(request->expression_id()); response->set_expression_name("微笑"); return grpc::Status::OK; } grpc::Status SetHeadExpression(grpc::ServerContext *context, const cmvr::api::SetHeadExpressionCommand::Request *request, cmvr::api::SetHeadExpressionCommand::Feedback *response) override { ++expressions; { std::lock_guard guard(mutex); expressionRequests.push_back(*request); } expressionDeadlineMs.store(static_cast(std::chrono::duration_cast( context->deadline() - std::chrono::system_clock::now()).count())); expressionEntered.store(true); const Result result = nextExpression.exchange(Acknowledge); while (holdExpression.load() && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); if (context->IsCancelled()) { expressionCanceled.store(true); return {grpc::StatusCode::CANCELLED, "fake custom expression canceled"}; } if (result == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake custom expression outcome unknown"}; if (result == Reject) { response->mutable_header()->set_success(false); response->mutable_header()->set_error_message("fixture rejected custom expression"); } else if (result == Acknowledge) response->mutable_header()->set_success(true); return grpc::Status::OK; } cmvr::api::HeadJointCommand::Request control(int index = -1) { std::lock_guard guard(mutex); check(!controlRequests.empty(), "a control request was actually received"); return controlRequests.at(index < 0 ? controlRequests.size() - 1 : size_t(index)); } cmvr::api::PlayHeadExpressionCommand::Request play() { std::lock_guard guard(mutex); check(!playRequests.empty(), "a preset request was actually received"); return playRequests.back(); } cmvr::api::SetHeadExpressionCommand::Request expression() { std::lock_guard guard(mutex); check(!expressionRequests.empty(), "a custom expression request was actually received"); return expressionRequests.back(); } bool oneStatePeer() { std::lock_guard guard(mutex); if (statePeers.empty() || statePeers.front().empty()) return false; for (const auto &peer : statePeers) if (peer != statePeers.front()) return false; return true; } private: std::mutex mutex; std::vector stateDevices; std::vector statePeers; std::vector controlRequests; std::vector playRequests; std::vector expressionRequests; }; struct Reply { quint64 token; QString device, operation; quint64 generation; bool success; QVariantMap data; QString detail; }; class Harness { public: FakeHead fake; std::unique_ptr server; RobotClient robot; std::unique_ptr client; std::vector replies; int started = 0, port = 0; quint64 token = 0; Harness() { grpc::ServerBuilder builder; builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&fake); server = builder.BuildAndStart(); check(server && port > 0, "only an ephemeral loopback fake can be used"); // Detach the normal backend worker. These endpoint/lifecycle signals are // consumed only by the dedicated head client constructed afterwards. QObject::disconnect(&robot, nullptr, nullptr, nullptr); client.reset(new BioHeadJointClient(&robot)); QObject::connect(client.get(), &BioHeadJointClient::requestStarted, [&](quint64, const QString &, const QString &, const QVariantMap &, quint64) { ++started; }); QObject::connect(client.get(), &BioHeadJointClient::requestFinished, [&](quint64 id, const QString &device, const QString &operation, quint64 generation, bool success, const QVariantMap &data, const QString &detail) { replies.push_back({id, device, operation, generation, success, data, detail}); }); client->setDeviceId("usb_head"); robot.connectRequested("127.0.0.1", port, false); robot.connectionChanged(true, 0, {}); check(client->isConnected(), "head transport observes the current endpoint and connection"); } ~Harness() { client.reset(); server->Shutdown(); server->Wait(); } quint64 send(const QString &operation, const QVariantMap ¶meters = {}) { client->request(++token, operation, parameters); return token; } Reply await(quint64 id) { check(waitFor([&] { for (const auto &reply : replies) if (reply.token == id) return true; return false; }, 8000), "head RPC produced a bounded completion callback"); for (const auto &reply : replies) if (reply.token == id) return reply; throw std::runtime_error("unreachable callback lookup"); } Reply call(const QString &operation, const QVariantMap ¶meters = {}) { return await(send(operation, parameters)); } void state() { const Reply reply = call("state"); check(reply.success, "configured metadata read succeeds"); check(reply.data.value("jointInfo").toList().size() == 5 && reply.data.value("expressions").toList().size() == 2, "five real channel IDs and server-defined presets reach the UI data contract"); check(!reply.data.value("positionFeedbackAvailable").toBool() && !reply.data.value("hardwareEmergencyStopAvailable").toBool(), "cached targets must not be advertised as physical feedback or hardware emergency stop"); } }; void metadataAndExactWireValues() { Harness h; pump(); check(h.fake.controls == 0 && h.fake.plays == 0, "constructing/connecting never homes or moves the head"); h.state(); check(h.fake.controls == 0 && h.fake.plays == 0, "metadata reads never send positions"); const auto moved = h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.0}}); check(moved.success, "one explicit servo write is acknowledged"); const auto wire = h.fake.control(); check(wire.has_move() && wire.move().targets_size() == 1, "one slider sends exactly one target"); check(wire.move().targets(0).id() == "eye_l_up" && wire.move().targets(0).has_position_rad() && wire.move().targets(0).position_rad() == 0., "explicit zero survives the protobuf target oneof"); check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty(), "device routing and a unique command ID reach the actual gRPC server"); check(h.call("mode", {{"mode", 0}}).success, "explicit IMMEDIATE mode is accepted"); const auto mode = h.fake.control(); check(mode.has_mode() && mode.mode().has_mode() && mode.mode().mode() == cmvr::api::HEAD_JOINT_MOTION_IMMEDIATE, "explicit enum zero survives the protobuf mode oneof"); check(h.call("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}).success, "a configured preset is acknowledged"); const auto preset = h.fake.play(); check(preset.has_expression_id() && preset.expression_id() == smileId && std::abs(preset.transition_duration_s() - .7) < 1e-12, "the exact configured preset ID and transition duration reach the wire"); std::puts("PASS metadata/no automatic motion, single-target and explicit zero/mode/preset protobuf fields"); } void validationAndNegativeFeedback() { Harness h; check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success && h.fake.controls == 0, "motion is blocked until channel metadata is known"); h.state(); const int before = h.fake.controls; for (const auto ¶meters : {QVariantMap{{"id", "unknown_joint"}, {"positionRad", 0.}}, QVariantMap{{"id", "eye_l_up"}, {"positionRad", 1.1}}, QVariantMap{{"id", "eye_l_up"}, {"positionRad", std::numeric_limits::quiet_NaN()}}}) check(!h.call("move", parameters).success, "unknown/out-of-range/nonfinite local servo input is rejected"); check(h.fake.controls == before, "invalid inputs never reach the server"); check(!h.call("play", {{"expressionId", "not_configured"}, {"transitionDurationS", .7}}).success && !h.call("play", {{"expressionId", smileId}, {"transitionDurationS", 0.}}).success && h.fake.plays == 0, "unknown presets and invalid durations never reach the server"); for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { h.fake.nextControl.store(result); const auto reply = h.call("move", {{"id", "eye_l_up"}, {"positionRad", .2}}); check(!reply.success && !reply.detail.isEmpty(), "rejection/missing success/transport timeout cannot become an ACK"); } std::puts("PASS local limits and preset validation; business rejection, missing success and timeout are not ACKs"); } void busyCancellationAndGenerations() { Harness h; h.state(); h.fake.holdPlay.store(true); const quint64 playing = h.send("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}); check(waitFor([&] { return h.fake.playEntered.load() && h.client->isBusy(); }), "expression is active on the normal RPC lane"); const int started = h.started, controls = h.fake.controls; const auto busy = h.call("move", {{"id", "eye_l_up"}, {"positionRad", .2}}); check(!busy.success && h.fake.controls == controls && h.started == started, "busy normal lane rejects another write without enqueueing it"); const auto canceled = h.call("cancel"); check(canceled.success && h.fake.cancels == 1 && h.fake.control().has_cancel_expression(), "cancellation reaches the server through its own lane while a preset RPC is active"); h.fake.holdPlay.store(false); check(waitFor([&] { return !h.client->isBusy(); }), "cancellation releases normal admission"); for (const auto &reply : h.replies) check(reply.token != playing || !reply.success, "a canceled active expression cannot later report successful completion"); h.state(); h.fake.holdControl.store(true); const int controlCount = h.fake.controls; const quint64 old = h.send("move", {{"id", "eye_l_up"}, {"positionRad", .1}}); check(waitFor([&] { return h.fake.controls > controlCount; }), "old-device write entered the fake server"); const quint64 previousGeneration = h.client->generation(); h.client->setDeviceId("other_head"); h.fake.holdControl.store(false); check(h.client->generation() > previousGeneration, "changing device invalidates the old generation"); pump(); for (const auto &reply : h.replies) check(reply.token != old, "old-device reply is discarded after a generation change"); const int beforeNew = h.fake.controls; check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", .1}}).success && h.fake.controls == beforeNew, "changing device clears the previous device's metadata"); h.state(); check(h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success, "a fresh metadata read enables the newly selected device"); check(h.fake.control().header().device_id() == "other_head", "new writes route to the selected device only"); h.robot.connectionChanged(false, 0, {}); check(!h.client->isConnected() && !h.call("state").success, "disconnect prevents further RPC admission"); std::puts("PASS one normal in-flight RPC, independent cancellation lane, stale generations and disconnect"); } void malformedMetadataClearsAdmission() { Harness h; h.state(); for (int fault : {1, 2, 3}) { h.fake.nextStateFault.store(fault); const auto invalid = h.call("state"); check(!invalid.success && !invalid.detail.isEmpty(), "duplicate IDs, invalid limits and incomplete presets cannot be accepted as metadata"); const int before = h.fake.controls; check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success && h.fake.controls == before, "malformed metadata clears the previously admitted configuration before another servo write"); h.state(); } std::puts("PASS malformed joint IDs/limits/preset targets reject state and clear cached motion admission"); } QVariantList customTargets() { const double positions[]{0., .2, -.5, .1, -1.}; QVariantList targets; for (int i = 0; i < 5; ++i) targets.append(QVariantMap{{"id", jointIds[i]}, {"positionRad", positions[i]}}); return targets; } QVariantMap customParameters(double duration = .7) { return {{"targets", customTargets()}, {"transitionDurationS", duration}}; } void customExpressionWireAndValidation() { Harness h; check(!h.call("expression", customParameters()).success && h.fake.expressions == 0, "a custom expression requires a state read in this generation"); h.state(); check(h.call("expression", customParameters()).success, "a complete local custom expression receives an ACK"); const auto wire = h.fake.expression(); check(wire.targets_size() == 5 && std::abs(wire.transition_duration_s() - .7) < 1e-12, "custom expression transmits all five configured channels and exact duration"); const QVariantList expected = customTargets(); for (int i = 0; i < 5; ++i) check(wire.targets(i).id() == jointIds[i] && wire.targets(i).has_position_rad() && wire.targets(i).position_rad() == expected[i].toMap().value("positionRad").toDouble(), "each custom target, including explicit zero, survives the actual protobuf wire"); check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty() && wire.header().timestamp().seconds() > 0 && wire.header().valid_for_ms() == 2700, "custom execution preserves UUID, timestamp, device and duration-plus-two-seconds validity"); check(h.fake.expressionDeadlineMs > 1700 && h.fake.expressionDeadlineMs <= 2800, "custom expression deadline is bounded by its transition duration plus two seconds"); check(h.fake.plays == 0 && h.fake.controls == 0, "custom execution never substitutes a server preset or inserts automatic mode/home commands"); check(!h.call("play", {{"expressionId", "local-library-uuid"}, {"transitionDurationS", .7}}).success && h.fake.plays == 0, "a local library ID is never forwarded as a configured PlayHeadExpression selector"); const int before = h.fake.expressions; std::vector invalid; for (double duration : {.1, 5.1, std::numeric_limits::quiet_NaN()}) invalid.push_back(customParameters(duration)); QVariantList targets = customTargets(); targets.removeLast(); invalid.push_back({{"targets", targets}, {"transitionDurationS", .7}}); for (const QVariantMap &replacement : { QVariantMap{{"id", jointIds[0]}, {"positionRad", 0.}}, QVariantMap{{"id", "unknown_joint"}, {"positionRad", 0.}}, QVariantMap{{"id", jointIds[1]}, {"positionRad", 1.}}, QVariantMap{{"id", jointIds[1]}, {"positionRad", std::numeric_limits::infinity()}}, QVariantMap{{"id", jointIds[1]}}}) { targets = customTargets(); targets[1] = replacement; invalid.push_back({{"targets", targets}, {"transitionDurationS", .7}}); } QVariantMap withLocalId = customParameters(); withLocalId.insert("expressionId", "local-library-uuid"); invalid.push_back(withLocalId); for (const QVariantMap ¶meters : invalid) check(!h.call("expression", parameters).success, "invalid/incomplete/duplicate/nonfinite custom targets are rejected locally"); check(h.fake.expressions == before && h.fake.plays == 0, "invalid custom input never dispatches either expression RPC"); h.fake.baseline.store(false); h.state(); check(!h.call("expression", customParameters()).success && h.fake.expressions == before, "missing expression baseline blocks custom execution without automatic home"); h.fake.baseline.store(true); h.state(); for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { h.fake.nextExpression.store(result); const int count = h.fake.expressions; const auto reply = h.call("expression", customParameters()); check(!reply.success, "custom business rejection, missing success and unknown transport outcome cannot become ACK"); pump(); check(h.fake.expressions == count + 1, "a rejected or uncertain custom expression is never retried"); check(!h.call("expression", customParameters()).success && h.fake.expressions == count + 1, "an uncertain custom result invalidates its baseline until another explicit state read"); h.state(); } std::puts("PASS local custom expression uses SetHeadExpression: exact five targets/zero/header/deadline, validation and no retries"); } void customExpressionCancellationDeadlineAndGeneration() { Harness h; h.state(); h.fake.holdExpression.store(true); const quint64 active = h.send("expression", customParameters(5.)); check(waitFor([&] { return h.fake.expressionEntered.load(); }), "custom expression entered its independent transport worker"); const int controls = h.fake.controls; check(!h.call("home").success && h.fake.controls == controls, "another mutation cannot overlap the active custom expression"); check(h.call("cancel").success && h.fake.cancels == 1, "CancelExpression reaches its separate lane during a long custom expression"); check(waitFor([&] { return h.fake.expressionCanceled.load() && !h.client->isBusy(); }), "TryCancel interrupts the active custom-expression context"); for (const auto &reply : h.replies) check(reply.token != active || !reply.success, "an interrupted custom expression cannot report ACK later"); const int canceledCount = h.fake.expressions; check(!h.call("expression", customParameters()).success && h.fake.expressions == canceledCount, "successful cancellation invalidates the cached baseline before another custom expression"); h.fake.holdExpression.store(false); h.state(); h.fake.expressionEntered.store(false); h.fake.holdExpression.store(true); const quint64 stale = h.send("expression", customParameters(5.)); check(waitFor([&] { return h.fake.expressionEntered.load(); }), "another custom expression reached the fake"); h.client->setDeviceId("replacement_head"); check(waitFor([&] { return !h.client->isBusy(); }), "device change cancels and drains old custom transport"); for (const auto &reply : h.replies) check(reply.token != stale, "an old-device custom-expression callback is discarded"); const int before = h.fake.expressions; check(!h.call("expression", customParameters()).success && h.fake.expressions == before, "a new device cannot inherit custom-expression metadata or baseline"); h.state(); QElapsedTimer elapsed; elapsed.start(); const auto timedOut = h.call("expression", customParameters(.2)); check(!timedOut.success && elapsed.elapsed() >= 1800 && elapsed.elapsed() < 4500, "a hung custom-expression RPC obeys its actual duration-plus-two-seconds client deadline"); pump(); check(h.fake.expressions == before + 1, "actual client deadline expiry does not replay a custom expression"); h.fake.holdExpression.store(false); std::puts("PASS custom expression busy admission, independent cancel, stale generation and actual bounded deadline"); } void endpointIsolationAndDemoCustomTargets() { Harness h; const QString endpoint = QStringLiteral("grpc://127.0.0.1:%1").arg(h.port); check(h.client->endpointKey() == endpoint, "endpoint key includes the normalized real service endpoint"); h.client->setDeviceId("other_head"); check(h.client->endpointKey() == endpoint, "device identity is separate from the stable endpoint key"); h.robot.connectRequested("[0:0:0:0:0:0:0:1]", h.port, false); check(h.client->endpointKey() == QStringLiteral("grpc://[::1]:%1").arg(h.port), "IPv6 endpoint variants normalize to one bracketed key"); h.robot.connectRequested(" Demo.EXAMPLE ", h.port, true); h.robot.connectionChanged(true, 0, {}); check(h.client->endpointKey() == QStringLiteral("demo://demo.example:%1").arg(h.port), "demo and real endpoints have distinct normalized persistence keys"); const int states = h.fake.states, controls = h.fake.controls, expressions = h.fake.expressions; check(h.call("state").success && !h.call("expression", customParameters(.2)).success, "demo starts without a confirmed baseline and never homes automatically"); check(h.call("home").success && h.call("state").success, "explicit demo home establishes the baseline"); check(h.call("expression", customParameters(.2)).success, "demo custom expression acknowledges its bounded transition"); const auto state = h.call("state"); for (const QVariant &entry : state.data.value("targets").toList()) { const QVariantMap target = entry.toMap(); bool matched = false; for (const QVariant &expected : customTargets()) { const QVariantMap value = expected.toMap(); if (value.value("id") != target.value("id")) continue; matched = true; check(target.value("targetValid").toBool() && target.value("targetPositionRad") == value.value("positionRad"), "demo retains only acknowledged custom targets, never measured positions"); } check(matched, "demo state contains configured channels only"); } const quint64 playing = h.send("expression", customParameters(5.)); check(h.call("cancel").success, "demo long custom transition is locally cancelable"); check(waitFor([&] { return !h.client->isBusy(); }), "demo canceled transition drains promptly"); for (const auto &reply : h.replies) check(reply.token != playing || !reply.success, "canceled demo custom targets cannot overwrite the ACK cache"); check(h.fake.states == states && h.fake.controls == controls && h.fake.expressions == expressions, "all demo queries and explicit custom actions make zero network calls"); std::puts("PASS endpoint namespace isolation/normalization and cancelable demo custom-expression ACK cache"); } void sharedChannelSlowStateAndDiagnostics() { Harness h; const auto initial = h.call("state"); check(initial.success, "initial state read succeeds"); const QString channelId = initial.data.value("channelInstance").toString(); const QString endpoint = h.client->endpointKey(); check(!channelId.isEmpty() && initial.data.value("endpoint").toString() == endpoint && initial.data.contains("elapsedMs") && initial.data.value("elapsedMs").toLongLong() >= 0 && !initial.data.value("channelStateBefore").toString().isEmpty() && initial.data.value("channelStateAfter").toString() == "READY", "state reports its endpoint, bounded elapsed time and real channel connectivity diagnostics"); check(h.call("state").data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(), "sequential state reads keep the same explicit channel and HTTP2 peer alive"); int ticks = 0; QTimer heartbeat; heartbeat.setInterval(10); QObject::connect(&heartbeat, &QTimer::timeout, [&] { ++ticks; }); heartbeat.start(); h.fake.nextStateDelayMs.store(3200); const auto slow = h.call("state"); check(slow.success && slow.data.value("elapsedMs").toLongLong() >= 3100 && slow.data.value("elapsedMs").toLongLong() < 5800 && ticks > 100, "a 3.2-second read succeeds within the six-second budget while GUI events remain responsive"); check(h.fake.stateValidityMs == 6000 && h.fake.stateDeadlineMs > 5000 && h.fake.stateDeadlineMs <= 6100, "only the state read has a six-second header validity and RPC deadline"); check(slow.data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(), "the delayed read preserves the held channel instead of reconnecting"); const auto moved = h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}); check(moved.success && h.fake.control().header().valid_for_ms() == 3000 && moved.data.value("channelInstance").toString() == channelId, "a mutation still has its original three-second budget on the shared channel"); h.fake.holdPlay.store(true); h.send("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}); check(waitFor([&] { return h.fake.playEntered.load(); }), "preset begins on the shared channel"); const auto canceled = h.call("cancel"); check(canceled.success && canceled.data.value("channelInstance").toString() == channelId, "the independent cancel context can preempt an active preset on the same channel"); h.fake.holdPlay.store(false); check(waitFor([&] { return !h.client->isBusy(); }), "shared-channel cancellation drains both sessions"); std::puts("PASS held shared channel, readable diagnostics, slow state recovery/UI heartbeat and independent cancellation"); } void stateFailureBudgetAndRecovery() { Harness h; const auto initial = h.call("state"); check(initial.success, "initial state is known"); const QString channelId = initial.data.value("channelInstance").toString(); for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { h.fake.nextStateOutcome.store(result); const auto reply = h.call("state"); check(!reply.success && reply.detail.contains(QStringLiteral("状态读取")) && !reply.detail.contains(QStringLiteral("执行结果")) && reply.data.value("channelInstance").toString() == channelId, "read rejection/missing header/deadline never becomes ACK or implies an unknown motion"); h.state(); } const int before = h.fake.states; h.fake.holdState.store(true); int ticks = 0; QTimer heartbeat; heartbeat.setInterval(10); QObject::connect(&heartbeat, &QTimer::timeout, [&] { ++ticks; }); heartbeat.start(); const auto timeout = h.call("state"); check(!timeout.success && timeout.data.value("grpcCode").toInt() == grpc::StatusCode::DEADLINE_EXCEEDED && timeout.data.value("elapsedMs").toLongLong() >= 5500 && timeout.data.value("elapsedMs").toLongLong() < 7800 && ticks > 300, "a hung read has a bounded six-second deadline without blocking the GUI"); check(timeout.detail.contains(QStringLiteral("状态读取超时")) && !timeout.detail.contains(QStringLiteral("执行结果")), "a true read timeout is described as a read timeout, not uncertain execution"); h.fake.holdState.store(false); pump(); check(h.fake.states == before + 1 && h.fake.controls == 0 && h.fake.plays == 0 && h.fake.expressions == 0, "state failure performs no automatic read retries, reconnects or motion"); check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success && h.fake.controls == 0, "failed state invalidates cached motion admission until the next explicit successful read"); const auto recovered = h.call("state"); check(recovered.success && recovered.data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(), "explicit recovery reads succeed on the retained channel after a transient timeout"); std::puts("PASS read-only failure wording/business ACK checks, actual six-second timeout, no retry and explicit recovery"); } void sharedChannelProfileIsolation() { Harness h; const auto first = h.call("state"); check(first.success, "first endpoint state succeeds"); const QString oldChannel = first.data.value("channelInstance").toString(); FakeHead replacement; int replacementPort = 0; grpc::ServerBuilder builder; builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &replacementPort); builder.RegisterService(&replacement); auto server = builder.BuildAndStart(); check(server && replacementPort > 0, "replacement endpoint is another ephemeral loopback server"); h.fake.holdState.store(true); const int oldCount = h.fake.states; const quint64 stale = h.send("state"); check(waitFor([&] { return h.fake.states > oldCount; }), "old endpoint owns an in-flight state context"); const quint64 oldGeneration = h.client->generation(); h.robot.connectRequested("127.0.0.1", replacementPort, false); h.robot.connectionChanged(true, 0, {}); check(h.client->generation() > oldGeneration && waitFor([&] { return !h.client->isBusy(); }), "profile switch cancels the old session while its captured old channel remains lifetime-safe"); h.fake.holdState.store(false); for (const auto &reply : h.replies) check(reply.token != stale, "old-profile state cannot update the new context"); const auto current = h.call("state"); const QString newChannel = current.data.value("channelInstance").toString(); check(current.success && current.data.value("endpoint").toString() == h.client->endpointKey() && newChannel != oldChannel && replacement.states == 1 && h.fake.states == oldCount + 1, "a profile switch builds a new held channel and routes reads only to its endpoint"); h.client->setDeviceId("second_head"); check(h.call("state").data.value("channelInstance").toString() == newChannel, "device generation changes retain the same connection-profile channel"); h.client->cancelPending(); check(h.call("state").data.value("channelInstance").toString() == newChannel, "local cancellation generation does not discard a healthy connection"); h.robot.disconnectRequested(); h.robot.connectRequested("127.0.0.1", replacementPort, false); h.robot.connectionChanged(true, 0, {}); check(h.call("state").data.value("channelInstance").toString() != newChannel, "a new explicit connection lifetime replaces the profile's previous channel"); server->Shutdown(); server->Wait(); std::puts("PASS shared-channel endpoint/profile lifetime isolation, canceled old session and device generation reuse"); } } int main(int argc, char **argv) { QApplication app(argc, argv); app.setOrganizationName("CMVR-BioHead-Tests"); app.setApplicationName("Joint Transport Loopback"); try { metadataAndExactWireValues(); validationAndNegativeFeedback(); busyCancellationAndGenerations(); malformedMetadataClearsAdmission(); customExpressionWireAndValidation(); customExpressionCancellationDeadlineAndGeneration(); endpointIsolationAndDemoCustomTargets(); sharedChannelSlowStateAndDiagnostics(); stateFailureBudgetAndRecovery(); sharedChannelProfileIsolation(); std::puts("PASS BioHead joint transport regression; loopback only, no physical head operations"); return 0; } catch (const std::exception &error) { std::fprintf(stderr, "FAIL BioHead joint transport: %s\n", error.what()); return 1; } }