#include "agvmapdocument.h" #include "agvmapeditorwidget.h" #include "agvmapviewwidget.h" #include "mainwindow.h" #include "robotclient.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { void require(bool condition, const char *message) { if (!condition) qFatal("AGV page smoke failed: %s", message); } void waitFor(const std::function &condition, const char *message) { QElapsedTimer timer; timer.start(); while (!condition() && timer.elapsed() < 7000) { QApplication::processEvents(); QThread::msleep(10); } require(condition(), message); } void fillNextDialog(const QString &kind, const std::function &fill) { auto *timer = new QTimer(qApp); timer->setInterval(10); QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() { auto *dialog = qobject_cast(QApplication::activeModalWidget()); if (!dialog || dialog->objectName() != kind) return; timer->stop(); fill(dialog); dialog->findChild()->button(QDialogButtonBox::Ok)->click(); QTimer::singleShot(100, qApp, [guard = QPointer(dialog)]() { if (guard && guard->isVisible()) { QStringList labels; for (const QLabel *label : guard->findChildren()) labels.append(label->text()); qFatal("AGV page smoke failed: dialog rejected fixture: %s", qPrintable(labels.join(" | "))); } }); timer->deleteLater(); }); timer->start(); QTimer::singleShot(7000, qApp, [guard = QPointer(timer), kind]() { if (guard && guard->isActive()) qFatal("AGV page smoke failed: expected dialog did not open: %s", qPrintable(kind)); }); } } int main(int argc, char *argv[]) { qInstallMessageHandler([](QtMsgType, const QMessageLogContext &, const QString &message) { const QByteArray text = message.toUtf8(); std::fprintf(stderr, "%s\n", text.constData()); std::fflush(stderr); }); QApplication app(argc, argv); Q_INIT_RESOURCE(resources); app.setOrganizationName("CMVR-Tests"); app.setApplicationName("AGV Page Smoke"); app.setStyle("Fusion"); QSettings::setDefaultFormat(QSettings::IniFormat); QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, app.applicationDirPath() + "/agv-page-test-settings"); const QString startupDevice = QStringLiteral("startup_agv_fixture"); const QString startupCamera = QStringLiteral("real_cam_startup_fixture"); constexpr int startupRefreshMs = 500; { QSettings startupSettings; // This application-specific test path is isolated from the user's // control-station settings. Restoring a camera selection invokes the // existing save callback before the AGV controls have been restored. startupSettings.clear(); startupSettings.setValue("agv/device", startupDevice); startupSettings.setValue("agv/mapRefreshIntervalMs", startupRefreshMs); startupSettings.setValue("agv/mapDirect", true); startupSettings.setValue("agv/mapDirectHost", "127.0.0.1"); startupSettings.setValue("camera/device", startupCamera); startupSettings.setValue("connection/demo", false); startupSettings.sync(); require(startupSettings.status() == QSettings::NoError, "isolated startup settings with saved AGV and camera devices are written"); } QFile style(QStringLiteral(":/styles.qss")); require(style.open(QIODevice::ReadOnly), "production stylesheet is available in test resources"); app.setStyleSheet(QString::fromUtf8(style.readAll())); MainWindow window; auto *client = window.findChild(); auto *editor = window.findChild(); auto *view = window.findChild(); auto *id = window.findChild("agvIdEdit"); auto *map = window.findChild("agvMapCombo"); auto *stations = window.findChild("agvStationCombo"); auto *demo = window.findChild("demoCheck"); auto *host = window.findChild("hostEdit"); auto *port = window.findChild("systemConnectionPort"); require(client && editor && view && id && map && stations && demo && host && port, "MainWindow exposes AGV controls"); auto *mapDirectMode = window.findChild("agvMapDirectMode"); auto *mapDirectHost = window.findChild("agvMapDirectHost"); require(mapDirectMode && mapDirectHost && mapDirectMode->currentData().toBool() && mapDirectHost->text() == QStringLiteral("127.0.0.1"), "startup restores the explicit map connection and vehicle address despite other settings callbacks"); // The remaining smoke scenarios exercise the original service and Demo // paths. Direct TCP and configuration discovery are tested on loopback. mapDirectMode->setCurrentIndex(0); auto *startupCameraCombo = window.findChild("cameraDeviceCombo"); auto *startupRefresh = window.findChild("agvMapRefreshCombo"); require(startupCameraCombo && startupCameraCombo->currentData().toString() == startupCamera, "construction restores a nonempty saved camera device through its normal selection callback"); require(id->text() == startupDevice && startupRefresh && startupRefresh->currentData().toInt() == startupRefreshMs, "camera restoration cannot erase the saved AGV device or map refresh interval during startup"); { QSettings restoredSettings; restoredSettings.sync(); require(restoredSettings.status() == QSettings::NoError && restoredSettings.value("agv/device").toString() == startupDevice && restoredSettings.value("agv/mapRefreshIntervalMs").toInt() == startupRefreshMs, "startup also preserves the persisted AGV device and refresh interval for the next launch"); } qInfo("PASS phase: startup preserves saved AGV device and refresh interval when saved camera selection also loads"); if (argc > 1 && QString::fromLocal8Bit(argv[1]) == QStringLiteral("--startup-settings-only")) return 0; // Keep the later frame-timing fixtures in their original automatic mode. startupRefresh->setCurrentIndex(startupRefresh->findData(0)); // An empty ID in live mode must stay empty; no backend connection is made. id->clear(); demo->setChecked(false); require(QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("test live UI"))), "live UI connection state injected"); require(id->text().isEmpty(), "live mode does not fill a Demo device ID"); QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, false), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("test disconnected"))); host->setText(QStringLiteral("127.0.0.1")); port->setValue(50052); const QString expectedDevice = argc > 2 ? QString::fromLocal8Bit(argv[2]) : QStringLiteral("demo_agv_1"); if (argc > 2) id->setText(expectedDevice); demo->setChecked(true); require(QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 3)), "AGV page selected"); window.showMaximized(); auto *coordinate = editor->findChild("agvCoordinateStationButton"); auto *route = editor->findChild("agvAddRouteButton"); auto *save = editor->findChild("agvSaveMapObjectsButton"); auto *undo = editor->findChild("agvUndoMapObjectsButton"); auto *manage = editor->findChild("agvManageMapObjectsButton"); auto *loadMap = window.findChild("switchMapButton"); auto *editorStatus = editor->findChild("agvMapEditorStatus"); auto *connectionValue = window.findChild("agvConnectionValue"); auto *modeValue = window.findChild("agvModeValue"); auto *mapValue = window.findChild("agvMapValue"); auto *errorValue = window.findChild("agvErrorValue"); require(coordinate && route && save && undo && manage && loadMap && editorStatus, "map editing and actual map loading controls exist"); require(connectionValue && modeValue && mapValue && errorValue, "AGV availability, mode, map and error fields are individually observable"); const auto contextFor = [&](const QString &device, bool demoMode) { return QVariantMap{{"deviceId", device}, {"endpoint", QStringLiteral("%1:%2") .arg(host->text().trimmed()).arg(port->value())}, {"demo", demoMode}, {"available", true}}; }; const auto emitFrame = [&](const QImage &image, QVariantMap metadata, const QString &detail) { // Local fixtures must follow the same generation contract as the // worker bridge. An explicit old generation is retained for rejection tests. if (!metadata.contains("streamGeneration")) metadata.insert("streamGeneration", QVariant::fromValue(client->agvMapStreamGeneration())); client->agvMapFrameReceived(image, metadata, detail); }; QVariantMap latestDemoState; QImage latestDemoImage; QVariantMap latestDemoMetadata; QObject::connect(client, &RobotClient::agvStateReceived, [&](const QVariantMap &state, const QVariantMap &) { if (state.value("available").toBool() && state.value("demo").toBool() && state.value("deviceId").toString() == expectedDevice) latestDemoState = state; }); QObject::connect(client, &RobotClient::agvMapFrameReceived, [&](const QImage &image, const QVariantMap &metadata, const QString &) { if (metadata.value("demo").toBool() && metadata.value("deviceId").toString() == expectedDevice) { latestDemoImage = image; latestDemoMetadata = metadata; } }); QHash mapReads; QHash expectedStationNames; quint64 verificationToken = 20000; quint64 completedToken = 0; QString downloaded; int switches = 0; bool observeDemoSwitches = true; QObject::connect(client, &RobotClient::agvMapContentReceived, [&](quint64 token, const QString &device, const QString &name, const QString &content, bool ok, const QString &) { if (device != expectedDevice) return; if (ok) ++mapReads[name]; if (token >= 20000) { require(ok, "map verification read succeeds"); completedToken = token; downloaded = content; } }); QObject::connect(client, &RobotClient::commandFinished, [&](const QString &command, bool ok, const QString &) { if (command == "AGV SwitchMap" && observeDemoSwitches) { require(ok, "actual map switch succeeds"); ++switches; } }); const auto readMap = [&](const QString &name) { const quint64 token = ++verificationToken; client->requestAgvMapContent(token, expectedDevice, name); waitFor([&]() { return completedToken == token; }, "complete map downloaded for verification"); AgvMapDocument result; QString error; require(result.load(downloaded, &error), "downloaded map remains editable SMAP"); return result; }; const auto hasRoute = [](const AgvMapDocument &document, const QString &name) { for (const QVariant &entry : document.routes()) if (entry.toMap().value("id").toString() == name) return true; return false; }; const auto stationIndex = [&](const QString &name) { return stations->findData(name); }; const auto stationName = [](const AgvMapDocument &document, const QString &id) { for (const QVariant &entry : document.stations()) { const QVariantMap station = entry.toMap(); if (station.value("id").toString() == id) return station.value("name").toString(); } return QString(); }; const auto loadPhysicalMap = [&](const QString &name) { require(map->findText(name) >= 0, "target map is listed"); const int previousSwitches = switches; map->setCurrentText(name); waitFor([&]() { return loadMap->isEnabled(); }, "actual map load button is ready"); loadMap->click(); const quint64 firstPreviewGeneration = client->agvMapStreamGeneration(); waitFor([&]() { return switches > previousSwitches && view->mapId() == name && coordinate->isEnabled() && id->isEnabled() && client->agvMapStreamGeneration() > firstPreviewGeneration; }, "selected map is confirmed and its fresh post-switch raster is ready"); }; const auto loadEditableMap = [&](const QString &name) { const int previousReads = mapReads.value(name); loadPhysicalMap(name); waitFor([&]() { return mapReads.value(name) > previousReads && editorStatus->text().contains(QStringLiteral("地图已读取")) && coordinate->isEnabled() && !save->isEnabled(); }, "selected map's complete station/route document loads automatically"); }; const auto inspectObjects = [&](const QStringList &requiredObjects, const QStringList &absentObjects) { waitFor([&]() { return manage->isEnabled(); }, "object manager is ready after confirmed-map refresh"); bool inspected = false; auto *timer = new QTimer(qApp); timer->setInterval(10); QObject::connect(timer, &QTimer::timeout, timer, [&, timer]() { auto *dialog = qobject_cast(QApplication::activeModalWidget()); if (!dialog || dialog->windowTitle() != QStringLiteral("AGV 站点与路线")) return; timer->stop(); auto *stationTable = dialog->findChild("agvMapStationsTable"); require(stationTable && stationTable->columnCount() >= 2, "manager exposes station ID and name columns"); QStringList cells; for (QTableWidget *table : dialog->findChildren()) for (int row = 0; row < table->rowCount(); ++row) for (int column = 0; column < table->columnCount(); ++column) if (table->item(row, column)) cells.append(table->item(row, column)->text()); for (const QString &object : requiredObjects) { require(cells.contains(object), "current map's saved/draft objects appear in editor manager"); if (!expectedStationNames.contains(object)) continue; bool pairedName = false; for (int row = 0; row < stationTable->rowCount(); ++row) if (stationTable->item(row, 0)->text() == object) pairedName = stationTable->item(row, 1)->text() == expectedStationNames.value(object); require(pairedName, "manager keeps the station's display name paired with its ID"); } for (const QString &object : absentObjects) require(!cells.contains(object), "other map's objects stay out of editor manager"); inspected = true; dialog->accept(); timer->deleteLater(); }); timer->start(); QTimer::singleShot(7000, qApp, [guard = QPointer(timer)]() { if (guard && guard->isActive()) qFatal("AGV page smoke failed: object manager did not open"); }); manage->click(); require(inspected, "editor object manager inspected"); }; const auto addStation = [&](const QString &stationId, const QString &stationName, double x, double y) { waitFor([&]() { return coordinate->isEnabled(); }, "coordinate action is ready after confirmed-map refresh"); fillNextDialog("agvStationDialog", [=](QDialog *dialog) { dialog->findChild("agvNewStationId")->setText(stationId); auto *name = dialog->findChild("agvNewStationName"); require(name != nullptr, "new station dialog exposes a display name field"); name->setText(stationName); dialog->findChild("agvNewStationX")->setValue(x); dialog->findChild("agvNewStationY")->setValue(y); }); coordinate->click(); waitFor([&]() { return save->isEnabled() && undo->isEnabled(); }, "station created in current map"); expectedStationNames.insert(stationId, stationName); }; const auto addBidirectionalRoute = [&](const QString &routeId, const QString &target) { waitFor([&]() { return route->isEnabled(); }, "route action is ready after confirmed-map refresh"); fillNextDialog("agvRouteDialog", [=](QDialog *dialog) { dialog->findChild("agvNewRouteId")->setText(routeId); dialog->findChild("agvNewRouteBidirectional")->setChecked(true); }); route->click(); view->stationSelected("HOME"); view->stationSelected(target); require(save->isEnabled(), "bidirectional route remains a current-map draft"); }; const auto renameStation = [&](const QString &stationId, const QString &newName) { waitFor([&]() { return manage->isEnabled(); }, "rename manager is ready after confirmed-map refresh"); fillNextDialog("agvStationNameDialog", [=](QDialog *dialog) { dialog->findChild("agvStationName")->setText(newName); }); bool renamed = false; auto *timer = new QTimer(qApp); timer->setInterval(10); QObject::connect(timer, &QTimer::timeout, timer, [&, timer]() { auto *dialog = qobject_cast(QApplication::activeModalWidget()); if (!dialog || dialog->objectName() != "agvMapObjectsDialog") return; timer->stop(); auto *table = dialog->findChild("agvMapStationsTable"); auto *rename = dialog->findChild("agvRenameStationButton"); require(table && rename, "manager exposes station rename controls"); int selected = -1; for (int row = 0; row < table->rowCount(); ++row) if (table->item(row, 0)->text() == stationId) selected = row; require(selected >= 0, "station to rename is present in current map manager"); table->selectRow(selected); rename->click(); renamed = true; dialog->accept(); timer->deleteLater(); }); timer->start(); QTimer::singleShot(7000, qApp, [guard = QPointer(timer)]() { if (guard && guard->isActive()) qFatal("AGV page smoke failed: rename manager did not open"); }); manage->click(); require(renamed && save->isEnabled() && undo->isEnabled(), "name change remains an undoable draft"); expectedStationNames.insert(stationId, newName); }; waitFor([&]() { return coordinate->isEnabled() && map->currentText() == "demo_map" && view->mapId() == "demo_map" && editorStatus && editorStatus->text().contains(QStringLiteral("地图已读取")); }, "map and existing stations/routes load automatically before editing"); require(id->text() == expectedDevice, "Demo fills only an empty device ID"); waitFor([&]() { return !latestDemoState.isEmpty() && connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() == QStringLiteral("空闲"); }, "available connected Demo state renders online and Idle consistently"); qInfo("AGV layout dimensions: window=%dx%d map=%dx%d", window.width(), window.height(), view->width(), view->height()); if (argc > 1) window.grab().save(QString::fromLocal8Bit(argv[1])); require(view->height() >= window.height() / 2, "map occupies the main workspace height"); auto *sidebar = window.findChild("agvControlSidebar"); auto *expand = window.findChild("agvExpandMapButton"); auto *tools = window.findChild("agvControlTools"); require(sidebar && expand && tools, "map expansion and sidebar tools exist"); auto *mapSelector = window.findChild("agvMapSelectorBar"); require(mapSelector != nullptr, "map selector has a persistent main-workspace row"); auto *mapListSummary = mapSelector->findChild("agvMapListSummary"); require(mapListSummary && mapListSummary->text().contains(QStringLiteral("演示")) && mapListSummary->text().contains(QStringLiteral("2 张地图")), "map selector reports actual Demo map count rather than a hidden library"); QPushButton *refreshMaps = nullptr; for (QPushButton *button : mapSelector->findChildren()) if (button->text() == QStringLiteral("刷新地图列表")) refreshMaps = button; require(refreshMaps && loadMap->text() == QStringLiteral("切换地图"), "map selector exposes clear refresh and switch actions"); bool mapSelectionLabel = false; for (QLabel *label : mapSelector->findChildren()) mapSelectionLabel |= label->text() == QStringLiteral("地图"); require(mapSelectionLabel, "map selector labels the pending map choice"); const auto verifyMapSelector = [&]() { require(mapSelector->isVisible() && mapSelector->parentWidget()->isAncestorOf(view) && !sidebar->isAncestorOf(mapSelector), "map selector belongs to the visible main map panel rather than sidebar"); for (QWidget *control : {static_cast(map), static_cast(refreshMaps), static_cast(loadMap)}) { require(mapSelector->isAncestorOf(control) && !sidebar->isAncestorOf(control) && control->isVisible(), "all map selection actions stay visible outside sidebar"); require(mapSelector->rect().contains(QRect(control->mapTo(mapSelector, QPoint()), control->size())), "map selection controls fit their workspace row without clipping"); } }; verifyMapSelector(); const int originalMapWidth = view->width(); expand->click(); waitFor([&]() { return !sidebar->isVisible() && view->width() > originalMapWidth; }, "map expands when sidebar is hidden"); verifyMapSelector(); expand->click(); waitFor([&]() { return sidebar->isVisible() && view->width() == originalMapWidth; }, "sidebar and map restore after expansion"); verifyMapSelector(); tools->setCurrentIndex(1); require(tools->tabText(1) == QStringLiteral("手动控制") && tools->currentWidget()->isVisible(), "manual controls remain available in sidebar"); verifyMapSelector(); waitFor([&]() { return sidebar->widget()->width() <= sidebar->viewport()->width(); }, "manual controls fit sidebar width without clipping"); tools->setCurrentIndex(0); waitFor([&]() { return sidebar->widget()->width() <= sidebar->viewport()->width(); }, "map controls fit sidebar after switching tabs"); verifyMapSelector(); // Inject inventory only: selecting mocked names must never issue SwitchMap. QStringList manyMaps{"demo_map", "warehouse"}; for (int index = 0; index < 62; ++index) manyMaps.append(QStringLiteral("map_%1_区域站点路线编辑示例").arg(index, 2, 10, QLatin1Char('0'))); const int switchesBeforeInventory = switches; client->agvInventoryReceivedForContext(contextFor(expectedDevice, true), manyMaps, {}); require(map->count() == manyMaps.size(), "all 64 inventory maps remain available in selector"); require(mapListSummary->text().contains(QStringLiteral("64 张地图")), "map count updates from complete inventory instead of a fixed Demo number"); for (int index = 0; index < manyMaps.size(); ++index) { require(map->itemText(index) == manyMaps.at(index), "inventory map names are retained without truncation"); map->setCurrentIndex(index); require(map->currentText() == manyMaps.at(index), "every listed map can be selected in full"); } map->showPopup(); const QModelIndex finalMap = map->model()->index(manyMaps.size() - 1, 0); map->view()->scrollTo(finalMap, QAbstractItemView::PositionAtBottom); waitFor([&]() { return map->view()->isVisible() && map->view()->viewport()->rect().contains(map->view()->visualRect(finalMap).center()); }, "last map in a long inventory is reachable in dropdown popup"); require(finalMap.data().toString() == manyMaps.last(), "last dropdown entry displays its complete map name"); map->hidePopup(); require(switches == switchesBeforeInventory && view->mapId() == "demo_map", "mock inventory and selection do not switch the actual displayed map"); map->setCurrentText("demo_map"); refreshMaps->click(); waitFor([&]() { return map->count() == 2 && map->findText("warehouse") >= 0 && map->currentText() == "demo_map" && stationIndex("HOME") >= 0 && mapListSummary->text().contains(QStringLiteral("2 张地图")); }, "refresh action restores actual Demo inventory after long-list verification"); require(switches == switchesBeforeInventory, "inventory refresh does not issue a mock switch command"); verifyMapSelector(); qInfo("PASS phase: map selector remains visible in expanded/manual views and retains all 64 inventory entries"); const int originalRouteCountA = readMap("demo_map").routes().size(); // A pending dropdown selection alone must not redirect A's editor/save. map->setCurrentText("warehouse"); QApplication::processEvents(); require(view->mapId() == "demo_map" && coordinate->isEnabled(), "selecting map B without loading leaves editing attached to displayed map A"); addStation("P101", QStringLiteral("起点A"), 2.0, 3.0); addBidirectionalRoute("A_HOME_P1", "P101"); int saves = 0; QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saves; }); save->click(); waitFor([&]() { return saves == 1 && stationIndex("P101") >= 0 && coordinate->isEnabled() && id->isEnabled() && view->mapId() == "demo_map"; }, "save refreshes navigation stations and restores controls"); require(!save->isEnabled(), "saved state survives inventory and stream refresh"); AgvMapDocument mapA = readMap("demo_map"); require(mapA.hasStation("P101") && hasRoute(mapA, "A_HOME_P1") && mapA.routes().size() == originalRouteCountA + 2 && stationName(mapA, "P101") == QStringLiteral("起点A") && stations->itemText(stationIndex("P101")).contains(QStringLiteral("起点A")), "map A stores station name and both route directions with navigation ID intact"); inspectObjects({"P101", "A_HOME_P1", QStringLiteral("起点A")}, {"P_B", "B_HOME_P_B", QStringLiteral("终点B")}); qInfo("PASS phase: pending map selection keeps named station/route save on map A"); loadEditableMap("warehouse"); AgvMapDocument mapB = readMap("warehouse"); const int originalRouteCountB = mapB.routes().size(); require(!mapB.hasStation("P101") && !hasRoute(mapB, "A_HOME_P1") && stationIndex("P101") < 0, "map A objects are absent from newly loaded map B"); addStation("UNDO_B", "undo B", 3.0, 3.0); inspectObjects({"UNDO_B"}, {"P101"}); undo->click(); require(!save->isEnabled() && !undo->isEnabled(), "map B station draft can be undone"); inspectObjects({}, {"UNDO_B", "P101"}); addStation("P_B", QStringLiteral("终点B"), -1.0, 1.0); addBidirectionalRoute("B_HOME_P_B", "P_B"); undo->click(); require(save->isEnabled() && undo->isEnabled(), "undoing map B route retains its station draft"); inspectObjects({"P_B"}, {"B_HOME_P_B", "P101"}); addBidirectionalRoute("B_HOME_P_B", "P_B"); save->click(); waitFor([&]() { return saves == 2 && stationIndex("P_B") >= 0 && coordinate->isEnabled() && !save->isEnabled(); }, "map B station and route saved and available in navigation inventory"); mapB = readMap("warehouse"); require(mapB.hasStation("P_B") && !mapB.hasStation("UNDO_B") && !mapB.hasStation("P101") && hasRoute(mapB, "B_HOME_P_B") && !hasRoute(mapB, "A_HOME_P1") && mapB.routes().size() == originalRouteCountB + 2 && stationName(mapB, "P_B") == QStringLiteral("终点B") && stations->itemText(stationIndex("P_B")).contains(QStringLiteral("终点B")), "map B stores its named station and routes with no undone/other-map objects"); renameStation("P_B", QStringLiteral("暂改名B")); inspectObjects({"P_B", QStringLiteral("暂改名B")}, {QStringLiteral("起点A")}); undo->click(); expectedStationNames.insert("P_B", QStringLiteral("终点B")); require(!save->isEnabled(), "undoing a name change restores the saved map"); inspectObjects({"P_B", QStringLiteral("终点B")}, {QStringLiteral("暂改名B")}); renameStation("P_B", QStringLiteral("终点B已命名")); save->click(); waitFor([&]() { return saves == 3 && !save->isEnabled() && stationIndex("P_B") >= 0 && stations->itemText(stationIndex("P_B")).contains(QStringLiteral("终点B已命名")); }, "renamed station saves and navigation label refreshes without changing ID"); mapB = readMap("warehouse"); require(stationName(mapB, "P_B") == QStringLiteral("终点B已命名") && mapB.routes().size() == originalRouteCountB + 2 && hasRoute(mapB, "B_HOME_P_B"), "saved rename retains station ID and route references"); qInfo("PASS phase: map B add/undo/save and name change/undo/save preserve route references"); loadEditableMap("demo_map"); mapA = readMap("demo_map"); require(mapA.hasStation("P101") && !mapA.hasStation("P_B") && hasRoute(mapA, "A_HOME_P1") && !hasRoute(mapA, "B_HOME_P_B") && stationIndex("P101") >= 0 && stationIndex("P_B") < 0 && stationName(mapA, "P101") == QStringLiteral("起点A"), "returning to map A restores its saved station/route without map B edits"); inspectObjects({"P101", "A_HOME_P1", QStringLiteral("起点A")}, {"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}); loadEditableMap("warehouse"); require(stationIndex("P_B") >= 0 && stationIndex("P101") < 0, "returning to map B restores its saved navigation station"); inspectObjects({"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}, {"P101", "A_HOME_P1", "UNDO_B", QStringLiteral("起点A")}); qInfo("PASS phase: both maps reload saved objects and display names without leakage"); // Keep A's draft while B can load/edit/undo independently, then save A. loadEditableMap("demo_map"); addStation("A_DRAFT", QStringLiteral("草稿A"), -2.0, 1.0); loadEditableMap("warehouse"); inspectObjects({"P_B", QStringLiteral("终点B已命名")}, {"A_DRAFT", QStringLiteral("草稿A")}); addStation("B_TEMP", QStringLiteral("临时B"), 4.0, 2.0); inspectObjects({"B_TEMP", "P_B"}, {"A_DRAFT", "P101"}); undo->click(); require(!save->isEnabled() && !undo->isEnabled(), "map B can undo while map A's draft is retained"); inspectObjects({"P_B"}, {"B_TEMP", "A_DRAFT"}); loadPhysicalMap("demo_map"); waitFor([&]() { return save->isEnabled() && undo->isEnabled(); }, "returning to A restores its unsaved draft"); inspectObjects({"A_DRAFT", "P101", "A_HOME_P1", QStringLiteral("草稿A")}, {"P_B", "B_HOME_P_B", "B_TEMP"}); require(!readMap("demo_map").hasStation("A_DRAFT") && !readMap("warehouse").hasStation("A_DRAFT"), "retained unsaved A draft has not been written into either map"); save->click(); waitFor([&]() { return saves == 4 && !save->isEnabled() && stationIndex("A_DRAFT") >= 0; }, "restored A draft can be saved to A and offered for navigation"); mapA = readMap("demo_map"); mapB = readMap("warehouse"); require(mapA.hasStation("A_DRAFT") && stationName(mapA, "A_DRAFT") == QStringLiteral("草稿A") && !mapA.hasStation("B_TEMP") && !mapA.hasStation("P_B") && !mapB.hasStation("A_DRAFT") && !mapB.hasStation("B_TEMP") && stationName(mapB, "P_B") == QStringLiteral("终点B已命名"), "saving restored A draft preserves map B's objects and names without leakage"); loadEditableMap("warehouse"); inspectObjects({"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}, {"A_DRAFT", "P101", QStringLiteral("草稿A"), QStringLiteral("起点A")}); loadEditableMap("demo_map"); inspectObjects({"P101", "A_DRAFT", "A_HOME_P1", QStringLiteral("起点A"), QStringLiteral("草稿A")}, {"P_B", "B_HOME_P_B", QStringLiteral("终点B已命名")}); qInfo("PASS phase: map A draft survives map B editing, returns and saves only to A"); // Process a periodic AGV state update to check the editor context remains stable. QElapsedTimer settle; settle.start(); while (settle.elapsed() < 900) { app.processEvents(); QThread::msleep(10); } require(coordinate->isEnabled() && !save->isEnabled(), "periodic refresh keeps editor ready"); require(view->visibleRegion().contains(view->rect()), "map view fits its parent without clipping"); for (QPushButton *button : sidebar->widget()->findChildren()) { if (!button->isVisible()) continue; const QPoint position = button->mapTo(sidebar->viewport(), QPoint()); require(position.x() >= 0 && position.x() + button->width() <= sidebar->viewport()->width(), "all visible sidebar actions fit horizontally"); } if (argc > 1) require(window.grab().save(QString::fromLocal8Bit(argv[1])), "AGV page screenshot saved"); const QVariantMap oldDemoState = latestDemoState; const QImage oldDemoImage = latestDemoImage; const QVariantMap oldDemoMetadata = latestDemoMetadata; require(!oldDemoState.isEmpty() && !oldDemoImage.isNull(), "Demo snapshots are available for late callback checks"); const auto requireEmptyMap = [&]() { QPointF point; require(view->mapId().isEmpty() && !view->widgetToWorld(QPointF(view->rect().center()), &point), "context reset clears map ID, image and projection metadata"); }; const auto requireUnavailable = [&]() { require(connectionValue->text().contains(QStringLiteral("状态不可用")) && !connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() != QStringLiteral("空闲"), "unavailable state is visibly unavailable rather than inherited online/Idle state"); requireEmptyMap(); }; const auto injectUnrelated = [&](QVariantMap context) { QVariantMap state = context; state.insert("connected", true); state.insert("mode", 2); state.insert("map", "FOREIGN_MAP"); state.insert("error", "FOREIGN_ERROR"); client->agvStateReceived(state, {}); client->agvInventoryReceivedForContext(context, {"FOREIGN_MAP"}, {QVariantMap{{"id", "FOREIGN_STATION"}, {"name", "foreign"}}}); QVariantMap metadata = oldDemoMetadata; for (auto it = context.cbegin(); it != context.cend(); ++it) metadata.insert(it.key(), it.value()); metadata.insert("mapId", "FOREIGN_MAP"); emitFrame(oldDemoImage, metadata, "FOREIGN_DEMO_FRAME"); }; // Changing only the device on this Demo connection immediately invalidates its UI. const QString otherDevice = expectedDevice + QStringLiteral("_other"); editorStatus->setText(QStringLiteral("旧 warehouse / demo_agv_1 读取失败")); editorStatus->setStyleSheet(QStringLiteral("color:#c63e3e")); id->setText(otherDevice); requireEmptyMap(); require(map->count() == 0 && stations->count() == 0 && !connectionValue->text().contains(QStringLiteral("在线")) && !editorStatus->text().contains(QStringLiteral("warehouse")) && !editorStatus->text().contains(QStringLiteral("demo_agv_1")) && !editorStatus->styleSheet().contains(QStringLiteral("#c63e3e")), "device change clears old online state, inventories and old editor error"); injectUnrelated(contextFor(expectedDevice, true)); injectUnrelated(contextFor(otherDevice, false)); QVariantMap otherEndpoint = contextFor(otherDevice, true); otherEndpoint.insert("endpoint", "127.0.0.1:59999"); injectUnrelated(otherEndpoint); requireEmptyMap(); require(map->count() == 0 && stations->count() == 0 && !mapValue->text().contains("FOREIGN") && !errorValue->text().contains("FOREIGN"), "late device/Demo/endpoint state, inventory and frames are all ignored"); require(QMetaObject::invokeMethod(id, "editingFinished", Qt::DirectConnection), "new Demo device edit completed"); waitFor([&]() { return view->mapId() == "demo_map" && coordinate->isEnabled() && map->count() == 2 && stations->findData("HOME") >= 0 && connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() == QStringLiteral("空闲"); }, "new device's successful state, inventory and first map restore usable UI"); require(stations->findData("P101") < 0 && stations->findData("A_DRAFT") < 0, "same-connection device switch does not reuse previous device's saved stations"); QVariantMap failedDemo = contextFor(otherDevice, true); failedDemo.insert("available", false); failedDemo.insert("connected", true); // A stale field must not override availability. failedDemo.insert("mode", 2); failedDemo.insert("error", "test unavailable runtime state"); client->agvStateReceived(failedDemo, {}); requireUnavailable(); require(errorValue->text().contains("test unavailable runtime state"), "current state failure displays its actual detail"); client->requestAgvRefresh(otherDevice); client->requestAgvInventory(otherDevice); waitFor([&]() { return connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() == QStringLiteral("空闲") && view->mapId() == "demo_map" && coordinate->isEnabled(); }, "successful Demo refresh restores availability after failure"); id->setText(expectedDevice); requireEmptyMap(); QMetaObject::invokeMethod(id, "editingFinished", Qt::DirectConnection); waitFor([&]() { return view->mapId() == "demo_map" && coordinate->isEnabled() && stationIndex("P101") >= 0 && stationIndex("A_DRAFT") >= 0; }, "returning to original device reloads only its saved objects"); inspectObjects({"P101", "A_DRAFT", QStringLiteral("起点A")}, {"FOREIGN_STATION"}); qInfo("PASS phase: device context reset, stale state/inventory/frame filtering and unavailable-state recovery"); client->disconnectFromServer(); waitFor([&]() { return !coordinate->isEnabled(); }, "disconnect disables map editing"); requireEmptyMap(); client->connectToServer(host->text().trimmed(), port->value(), true); waitFor([&]() { return coordinate->isEnabled() && view->mapId() == "demo_map"; }, "Demo reconnect restores AGV editing and map stream"); require(id->text() == expectedDevice, "Demo reconnect preserves device ID"); client->disconnectFromServer(); waitFor([&]() { return !coordinate->isEnabled(); }, "Demo disconnected after reconnect check"); requireEmptyMap(); // Final real-mode UI fixture: no real server is contacted. Typed raw-map // requests are answered locally after the worker has been disconnected. editorStatus->setText(QStringLiteral("旧 warehouse / demo_agv_1 红字")); demo->setChecked(false); port->setValue(50053); const QString liveDevice = QStringLiteral("src1100_test"); id->setText(liveDevice); require(QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic real UI only"))), "real-mode UI connection state injected without starting transport"); requireEmptyMap(); require(map->count() == 0 && stations->count() == 0 && !editorStatus->text().contains("warehouse") && !editorStatus->text().contains("demo_agv_1") && !editorStatus->styleSheet().contains(QStringLiteral("#c63e3e")), "Demo-to-real connection reset clears old raster, list and editor error"); const QVariantMap liveContext = contextFor(liveDevice, false); QVariantMap lateDemo = liveContext; lateDemo.insert("demo", true); injectUnrelated(lateDemo); requireEmptyMap(); require(map->count() == 0, "old Demo inventory cannot populate a real-mode connection"); const QString rawLive = QStringLiteral(R"({"header":{"map_type":"2D-Map","map_name":"real_map","resolution":0.05,"source":"test-real-context","min_pos":{"x":-5,"y":-2.5},"max_pos":{"x":5,"y":2.5}},"advanced_point_list":[{"class_name":"LandMark","instance_name":"REAL_HOME","description":"真实上下文测试点","pos":{"x":0,"y":0},"dir":0}],"advanced_curve_list":[]})"); QObject::disconnect(client, &RobotClient::agvMapContentRequested, nullptr, nullptr); QString rawPreviewB = rawLive; rawPreviewB.replace("\"map_name\":\"real_map\"", "\"map_name\":\"real_map_0\""); rawPreviewB.replace("REAL_HOME", "REAL_B"); rawPreviewB.replace("真实上下文测试点", "目标预览测试点"); rawPreviewB.replace("\"resolution\":0.05", "\"resolution\":0.1"); rawPreviewB.replace("\"x\":-5", "\"x\":-10"); rawPreviewB.replace("\"x\":5", "\"x\":10"); rawPreviewB.replace("\"y\":-2.5", "\"y\":-5"); rawPreviewB.replace("\"y\":2.5", "\"y\":5"); QHash localMapContents{{"real_map", rawLive}, {"real_map_0", rawPreviewB}}; QString fixtureDevice = liveDevice; QObject::connect(client, &RobotClient::agvMapContentRequested, client, [&](quint64 token, const QString &device, const QString &name) { if (device == fixtureDevice && localMapContents.contains(name)) { const QString content = localMapContents.value(name); QTimer::singleShot(0, client, [=]() { client->agvMapContentReceived(token, device, name, content, true, "local UI fixture"); }); } }); QStringList liveMaps{"real_map"}; for (int index = 0; index < 32; ++index) liveMaps.append(QStringLiteral("real_map_%1").arg(index)); const QVariantList liveStations{QVariantMap{{"id", "REAL_HOME"}, {"name", QStringLiteral("真实上下文测试点")}}}; QVariantMap liveState = liveContext; liveState.insert("connected", true); liveState.insert("mode", 2); liveState.insert("localized", true); liveState.insert("map", "real_map"); liveState.insert("station", "REAL_HOME"); client->agvStateReceived(liveState, {}); client->agvInventoryReceivedForContext(liveContext, liveMaps, liveStations); QImage liveImage(200, 100, QImage::Format_ARGB32_Premultiplied); liveImage.fill(QColor("#acbdce")); QVariantMap liveMetadata = liveContext; liveMetadata.insert("mapId", "real_map"); liveMetadata.insert("dimension", 2); liveMetadata.insert("resolution", 0.05); liveMetadata.insert("originX", -5.0); liveMetadata.insert("originY", -2.5); liveMetadata.insert("originTheta", 0.0); liveMetadata.insert("renderScale", 1.0); emitFrame(liveImage, liveMetadata, "local real-mode map fixture"); waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && editorStatus->text().contains(QStringLiteral("地图已读取")); }, "first current real-mode frame restores map projection and loads its editor document"); require(map->count() == 33 && stations->findData("REAL_HOME") >= 0 && map->findText("demo_map") < 0 && !mapListSummary->text().contains(QStringLiteral("演示")) && connectionValue->text().contains(QStringLiteral("在线")), "real inventory and online state replace Demo data without leftover badges"); const QPointF probe = QPointF(view->rect().center()) + QPointF(60, 20); QPointF beforeLateFrame; require(view->widgetToWorld(probe, &beforeLateFrame), "new real-mode frame has valid projection"); QVariantMap sameMapLateDemo = oldDemoMetadata; sameMapLateDemo.insert("deviceId", liveDevice); sameMapLateDemo.insert("endpoint", liveContext.value("endpoint")); sameMapLateDemo.insert("demo", true); sameMapLateDemo.insert("mapId", "real_map"); emitFrame(oldDemoImage, sameMapLateDemo, "late DEMO frame with matching map ID"); client->agvInventoryReceivedForContext(lateDemo, {"demo_map", "warehouse"}, {}); QVariantMap staleState = liveState; staleState.insert("demo", true); staleState.insert("connected", false); staleState.insert("mode", 1); client->agvStateReceived(staleState, {}); QPointF afterLateFrame; require(view->widgetToWorld(probe, &afterLateFrame) && (afterLateFrame - beforeLateFrame).manhattanLength() < 1e-9 && map->count() == 33 && connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() == QStringLiteral("空闲"), "late Demo payloads cannot overwrite real image metadata, inventory or online state"); QVariantMap liveOffline = liveState; liveOffline.insert("connected", false); liveOffline.insert("mode", 1); client->agvStateReceived(liveOffline, {}); require(connectionValue->text().contains(QStringLiteral("离线")) && !connectionValue->text().contains(QStringLiteral("在线")) && modeValue->text() == QStringLiteral("离线"), "current real controller's disconnected mode is shown faithfully instead of forced online"); client->agvStateReceived(liveState, {}); QVariantMap failedLive = liveState; failedLive.insert("available", false); failedLive.insert("error", "real fixture unavailable"); client->agvStateReceived(failedLive, {}); requireUnavailable(); client->agvStateReceived(liveState, {}); client->agvInventoryReceivedForContext(liveContext, liveMaps, liveStations); emitFrame(liveImage, liveMetadata, "recovered real-mode map fixture"); waitFor([&]() { return connectionValue->text().contains(QStringLiteral("在线")) && view->mapId() == "real_map" && coordinate->isEnabled(); }, "successful current real-mode payloads restore usable UI after unavailability"); qInfo("PASS phase: Demo-to-real clearing, first-frame recovery and same-map late Demo rejection without transport"); // Control ACK and runtime status independently: target preview must work // before the vehicle accepts or actually completes a map switch. observeDemoSwitches = false; QObject::disconnect(client, &RobotClient::agvSwitchMapRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvMapSaveRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvMapStreamStartRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvMapStreamStopRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvRefreshRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvInventoryRequested, nullptr, nullptr); int streamRequests = 0; QString streamTarget; bool streamPreview = false; QObject::connect(client, &RobotClient::agvMapStreamStartRequested, [&](const QString &device, const QString &target, int dimension, bool, bool, quint64 generation, bool preview) { require(device == fixtureDevice && dimension == 1 && generation == client->agvMapStreamGeneration(), "local stream request captures current device, 2D dimension and generation"); ++streamRequests; streamTarget = target; streamPreview = preview; }); int previewRequests = 0; QString requestedPreview; QStringList localSaveMaps; QObject::connect(client, &RobotClient::agvSwitchMapRequested, [&](const QString &device, const QString &target) { require(device == fixtureDevice, "synthetic switch targets the current fixture device"); ++previewRequests; requestedPreview = target; }); QObject::connect(client, &RobotClient::agvMapSaveRequested, client, [&](quint64 token, const QString &device, const QString &name, const QString &content) { require(device == fixtureDevice && localMapContents.contains(name), "synthetic save targets a known current-device map"); localSaveMaps.append(name); localMapContents.insert(name, content); QTimer::singleShot(0, client, [=]() { client->agvMapSaveFinished(token, device, name, true, "local fixture saved without transport"); }); }); auto *switchStatus = window.findChild("agvMapSwitchStatus"); require(switchStatus != nullptr, "map-switch acceptance and vehicle confirmation have an observable status label"); const auto robotPixels = [&]() { const QImage rendered = view->grab().toImage(); int count = 0; for (int y = 0; y < rendered.height(); ++y) { for (int x = 0; x < rendered.width(); ++x) { const QColor color = rendered.pixelColor(x, y); // These fixtures have no routes; saturated route-blue pixels // therefore belong only to the AGV marker/label. if (color.blue() > 200 && color.red() < 100 && color.green() < 160) ++count; } } return count; }; for (bool demoMode : {false, true}) { localMapContents.insert("real_map", rawLive); localMapContents.insert("real_map_0", rawPreviewB); localSaveMaps.clear(); fixtureDevice = demoMode ? liveDevice + "_preview_demo" : liveDevice; demo->setChecked(demoMode); id->setText(fixtureDevice); QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic switch fixture"))); const QVariantMap previewContext = contextFor(fixtureDevice, demoMode); QVariantMap runtimeA = previewContext; runtimeA.insert("connected", true); runtimeA.insert("localized", true); runtimeA.insert("mode", 2); runtimeA.insert("map", "real_map"); runtimeA.insert("station", "REAL_HOME"); QVariantMap runtimeB = runtimeA; runtimeB.insert("map", "real_map_0"); runtimeB.insert("station", "REAL_B"); QVariantMap metadataA = liveMetadata; QVariantMap metadataB = liveMetadata; for (auto it = previewContext.cbegin(); it != previewContext.cend(); ++it) { metadataA.insert(it.key(), it.value()); metadataB.insert(it.key(), it.value()); } metadataA.insert("mapId", "real_map"); metadataB.insert("mapId", "real_map_0"); metadataB.insert("resolution", 0.1); metadataB.insert("originX", -10.0); metadataB.insert("originY", -5.0); QImage previewImage = liveImage; previewImage.fill(QColor("#dcc9ad")); client->agvStateReceived(runtimeA, {}); client->agvInventoryReceivedForContext(previewContext, liveMaps, liveStations); emitFrame(liveImage, metadataA, "synthetic map A"); waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && !save->isEnabled(); }, "synthetic map A starts with a clean editable document"); const QString draft = demoMode ? "PREVIEW_A_DEMO" : "PREVIEW_A_REAL"; const QString failedDraft = demoMode ? "REJECT_A_DEMO" : "REJECT_A_REAL"; addStation(draft, QStringLiteral("切图前草稿A"), 1.0, 0.5); const auto beginPreview = [&](const QString &target) { const int previous = previewRequests; map->setCurrentText(target); waitFor([&]() { return loadMap->isEnabled(); }, "switch control is ready for explicit target preview"); loadMap->click(); require(previewRequests == previous + 1 && requestedPreview == target, "click dispatches one explicit target switch while withholding ACK"); requireEmptyMap(); require(!coordinate->isEnabled(), "old map editing is disabled immediately before the target frame"); }; beginPreview("real_map_0"); emitFrame(liveImage, metadataA, "late map A before target frame"); requireEmptyMap(); emitFrame(previewImage, metadataB, "target B before switch ACK"); waitFor([&]() { return view->mapId() == "real_map_0"; }, "target B is displayed before switch ACK arrives despite dirty map A"); require(!coordinate->isEnabled(), "pending vehicle ACK keeps editing locked while B preview is displayed"); QVariantMap unavailableDuringSwitch = runtimeA; unavailableDuringSwitch.insert("available", false); unavailableDuringSwitch.insert("error", "state refresh failed while switch pending"); client->agvStateReceived(unavailableDuringSwitch, {}); QPointF unavailableProjection; require(view->mapId() == "real_map_0" && view->widgetToWorld(probe, &unavailableProjection) && connectionValue->text().contains(QStringLiteral("状态不可用")) && !connectionValue->text().contains(QStringLiteral("在线")) && errorValue->text().contains("state refresh failed while switch pending"), "unavailable same-context state during a pending switch preserves target B image and reports unavailability"); client->agvStateReceived(runtimeA, {}); QApplication::processEvents(); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /"), "recovery to runtime A during a pending switch cannot restore map A over target B preview"); QPointF targetProjection; require(view->widgetToWorld(probe, &targetProjection), "target B projection is usable before ACK"); emitFrame(liveImage, metadataA, "late map A after target frame"); QPointF afterOldA; require(view->mapId() == "real_map_0" && view->widgetToWorld(probe, &afterOldA) && (targetProjection - afterOldA).manhattanLength() < 1e-9, "old A frames cannot replace target B projection before ACK"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); client->agvStateReceived(runtimeA, {}); emitFrame(liveImage, metadataA, "late map A after accepted request"); QApplication::processEvents(); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") && switchStatus->text().contains(QStringLiteral("等待")) && !switchStatus->text().contains(QStringLiteral("已确认")), "accepted ACK with runtime A keeps B preview and honestly waits for vehicle confirmation"); waitFor([&]() { return coordinate->isEnabled() && editorStatus->text().contains(QStringLiteral("地图已读取")); }, "after ACK target B is editable even while the vehicle still reports A"); inspectObjects({"REAL_B"}, {draft, "REAL_HOME"}); require(robotPixels() == 0, "vehicle A pose is hidden on a B preview while confirmation is pending"); QVariantMap offlineRuntimeB = runtimeB; offlineRuntimeB.insert("connected", false); const int switchesBeforeOfflineState = previewRequests; client->agvStateReceived(offlineRuntimeB, {}); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") && connectionValue->text().contains(QStringLiteral("离线")) && !connectionValue->text().contains(QStringLiteral("在线")) && switchStatus->text().contains(QStringLiteral("尚未确认")) && !switchStatus->text().contains(QStringLiteral("已确认")), "accepted ACK with an offline cached target map cannot confirm the current vehicle map"); require(robotPixels() == 0, "offline cached target pose is hidden on its matching map preview"); require(previewRequests == switchesBeforeOfflineState, "offline cached target state never automatically resends the switch command"); const int beforeConfirmedRefresh = streamRequests; client->agvStateReceived(runtimeB, {}); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") && switchStatus->text().contains(QStringLiteral("已确认")), "fresh matching runtime B confirms the vehicle map without changing its preview"); require(streamRequests == beforeConfirmedRefresh + 1, "vehicle confirmation re-reads the selected snapshot once after the initial pre-switch preview"); for (int repeat = 0; repeat < 3; ++repeat) client->agvStateReceived(runtimeB, {}); require(streamRequests == beforeConfirmedRefresh + 1 && previewRequests == switchesBeforeOfflineState, "repeated confirmed runtime cannot refresh repeatedly or send another switch command"); require(robotPixels() > 20, "matching runtime B makes its AGV marker visible on the B map"); beginPreview("real_map"); emitFrame(liveImage, metadataA, "returning to map A draft"); waitFor([&]() { return view->mapId() == "real_map"; }, "returning to A displays its preview before ACK"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); client->agvStateReceived(runtimeA, {}); waitFor([&]() { return coordinate->isEnabled() && save->isEnabled() && undo->isEnabled(); }, "returning to A restores its unsaved draft after pending ACK releases editing"); inspectObjects({draft, "REAL_HOME", QStringLiteral("切图前草稿A")}, {"REAL_B"}); save->click(); waitFor([&]() { return localSaveMaps.size() == 1 && !save->isEnabled(); }, "restored A draft can be saved through only the local A fixture"); AgvMapDocument savedA; AgvMapDocument savedB; QString error; require(localSaveMaps.first() == "real_map" && savedA.load(localMapContents.value("real_map"), &error) && savedA.hasStation(draft) && savedB.load(localMapContents.value("real_map_0"), &error) && !savedB.hasStation(draft), "A draft save retains map identity and never leaks into B content"); emitFrame(liveImage, metadataA, "map A refreshed after local save"); waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && !save->isEnabled(); }, "saved map A remains ready after its preview refresh"); addStation(failedDraft, QStringLiteral("拒绝后保留草稿A"), 2.0, 0.5); beginPreview("real_map_0"); emitFrame(previewImage, metadataB, "target B pending rejected switch"); waitFor([&]() { return view->mapId() == "real_map_0"; }, "B preview appears before a rejected switch ACK"); client->commandFinished("AGV SwitchMap", false, QStringLiteral("测试切换拒绝:请先定位")); client->agvStateReceived(runtimeA, {}); emitFrame(liveImage, metadataA, "late A after rejected switch"); QApplication::processEvents(); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") && switchStatus->text().contains(QStringLiteral("测试切换拒绝")), "rejected ACK preserves B preview, displays its reason and keeps the actual vehicle on A"); waitFor([&]() { return coordinate->isEnabled(); }, "rejected vehicle switch still releases B preview editing"); require(robotPixels() == 0, "rejected B switch cannot show vehicle A's marker on B"); inspectObjects({"REAL_B"}, {failedDraft, draft}); const int switchesBeforeMatchingFailedState = previewRequests; client->agvStateReceived(runtimeB, {}); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map_0 /") && switchStatus->text().contains(QStringLiteral("车端当前使用该地图")) && switchStatus->text().contains(QStringLiteral("此前切图请求失败")) && switchStatus->text().contains(QStringLiteral("测试切换拒绝")) && !switchStatus->text().contains(QStringLiteral("已确认")), "online matching map state reports current use without rewriting a failed switch request as success"); require(previewRequests == switchesBeforeMatchingFailedState, "matching map state after a failed request never automatically resends the switch command"); client->agvStateReceived(runtimeA, {}); require(view->mapId() == "real_map_0" && mapValue->text().startsWith("real_map /") && switchStatus->text().contains(QStringLiteral("测试切换拒绝")) && !switchStatus->text().contains(QStringLiteral("车端当前使用该地图")) && !switchStatus->text().contains(QStringLiteral("已确认")) && previewRequests == switchesBeforeMatchingFailedState, "later runtime A retains the original failed-request detail and the selected B preview without a retry"); require(robotPixels() == 0, "returning runtime A hides its marker from the retained B preview after a failed request"); beginPreview("real_map"); emitFrame(liveImage, metadataA, "A draft survives rejected B switch"); waitFor([&]() { return view->mapId() == "real_map"; }, "A preview returns after a rejected B switch"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); client->agvStateReceived(runtimeA, {}); waitFor([&]() { return coordinate->isEnabled() && save->isEnabled(); }, "A draft survives a rejected switch and restores after its return ACK"); inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); require(localSaveMaps.size() == 1 && !savedB.hasStation(failedDraft), "rejected switch never implicitly saves A draft or writes B"); qInfo("PASS phase: %s target preview before ACK, runtime confirmation, rejected-switch preview and retained A drafts", demoMode ? "synthetic Demo" : "synthetic real"); // The target has no first frame: a later fresh runtime state may // recover its preview once, but repeated failures must stay bounded. beginPreview("real_map_0"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); const quint64 firstAttempt = client->agvMapStreamGeneration(); const int firstRequestCount = streamRequests; const auto streamContext = [&](quint64 generation, const QString &error = QString()) { QVariantMap result = previewContext; result.insert("mapId", "real_map_0"); result.insert("streamGeneration", QVariant::fromValue(generation)); result.insert("preview", true); if (!error.isEmpty()) result.insert("error", error); return result; }; QVariantMap staleB = metadataB; staleB.insert("streamGeneration", QVariant::fromValue(firstAttempt - 1)); emitFrame(previewImage, staleB, "old generation of the same target B"); client->agvMapStreamStateChangedForContext( streamContext(firstAttempt - 1, "stale generation error"), false, "stale generation stop"); client->agvStateReceived(runtimeA, {}); requireEmptyMap(); require(streamRequests == firstRequestCount && !switchStatus->text().contains("stale generation error"), "same-map old generation frames and stop callbacks cannot display or restart the current preview"); client->agvMapStreamStateChanged(false, "legacy generic stop without context"); client->agvStateReceived(runtimeA, {}); require(streamRequests == firstRequestCount, "legacy generic stream state cannot initiate current UI recovery"); client->agvMapStreamStateChangedForContext( streamContext(firstAttempt, "fixture first preview read failed"), false, "fixture first preview read failed"); require(switchStatus->text().contains("fixture first preview read failed"), "current typed preview failure exposes its actual read error"); client->agvStateReceived(runtimeA, {}); require(streamRequests == firstRequestCount + 1 && streamTarget == "real_map_0" && streamPreview, "fresh runtime A automatically retries the selected B preview exactly once"); const quint64 retryAttempt = client->agvMapStreamGeneration(); require(retryAttempt > firstAttempt, "automatic recovery creates a new stream generation"); staleB.insert("streamGeneration", QVariant::fromValue(firstAttempt)); emitFrame(previewImage, staleB, "late first-attempt B during its retry"); requireEmptyMap(); client->agvMapStreamStateChangedForContext( streamContext(retryAttempt, "fixture retry preview read failed"), false, "fixture retry preview read failed"); for (int repeat = 0; repeat < 5; ++repeat) client->agvStateReceived(runtimeA, {}); require(streamRequests == firstRequestCount + 1 && switchStatus->text().contains("fixture retry preview read failed"), "repeated fresh state after the retry fails cannot create an automatic recovery loop"); QPushButton *refreshState = nullptr; auto *agvPage = window.findChild("agvPage"); require(agvPage != nullptr, "AGV page exists for its manual state refresh"); for (QPushButton *button : agvPage->findChildren()) if (button->text() == QStringLiteral("刷新状态")) refreshState = button; require(refreshState && refreshState->isEnabled(), "user can explicitly retry through the state refresh button"); refreshState->click(); client->agvStateReceived(runtimeA, {}); require(streamRequests == firstRequestCount + 2 && streamTarget == "real_map_0" && streamPreview, "manual refresh resets the retry budget and keeps the selected target B"); emitFrame(previewImage, metadataB, "target B recovered after manual refresh"); waitFor([&]() { return view->mapId() == "real_map_0" && coordinate->isEnabled(); }, "current-generation first frame restores selected B after manual recovery"); const int readyRequestCount = streamRequests; client->agvMapStreamStateChangedForContext( streamContext(client->agvMapStreamGeneration()), false, "static preview completed normally"); for (int repeat = 0; repeat < 3; ++repeat) client->agvStateReceived(runtimeA, {}); require(streamRequests == readyRequestCount && view->mapId() == "real_map_0", "a completed static preview with a valid frame does not restart on subsequent state refreshes"); beginPreview("real_map"); emitFrame(liveImage, metadataA, "A draft returns after bounded B recovery"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("请求已接受,等待车端确认")); client->agvStateReceived(runtimeA, {}); waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && save->isEnabled(); }, "bounded recovery retains A's unsaved draft across target retry and manual refresh"); inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); require(localSaveMaps.size() == 1, "preview recovery never implicitly uploads an unsaved draft"); qInfo("PASS phase: %s current-generation typed state, same-map stale callbacks and bounded target-preview recovery", demoMode ? "synthetic Demo" : "synthetic real"); QPushButton *startLiveStream = nullptr; QPushButton *stopLiveStream = nullptr; for (QPushButton *button : agvPage->findChildren()) { if (button->text() == QStringLiteral("启动地图流")) startLiveStream = button; if (button->text() == QStringLiteral("停止地图流")) stopLiveStream = button; } auto *mappingName = agvPage->findChild("mappingNameEdit"); require(startLiveStream && stopLiveStream && mappingName && startLiveStream->isEnabled() && stopLiveStream->isEnabled(), "live mapping stream controls remain available for explicit start and stop"); mappingName->setText("real_map"); const int beforeLiveStart = streamRequests; startLiveStream->click(); require(streamRequests == beforeLiveStart + 1 && streamTarget == "real_map" && !streamPreview, "manual live start retains the original stream API instead of the static preview API"); emitFrame(liveImage, metadataA, "manual live A first frame"); waitFor([&]() { return coordinate->isEnabled() && save->isEnabled(); }, "manual live start retains the current A draft"); stopLiveStream->click(); const int pausedRequestCount = streamRequests; QVariantMap unavailableAfterStop = runtimeA; unavailableAfterStop.insert("available", false); unavailableAfterStop.insert("error", "fixture unavailable after manual stop"); client->agvStateReceived(unavailableAfterStop, {}); requireUnavailable(); for (int repeat = 0; repeat < 3; ++repeat) client->agvStateReceived(runtimeA, {}); require(streamRequests == pausedRequestCount, "manual stop remains paused across unavailable state clearing and subsequent successful refreshes"); client->commandFinished("AGV StopMapping", true, "delayed stop-mapping ACK after manual stream stop"); require(streamRequests == pausedRequestCount, "a delayed successful StopMapping ACK cannot bypass manual stream pause"); QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 0)); client->commandFinished("AGV StopMapping", true, "delayed stop-mapping ACK outside the AGV page"); require(streamRequests == pausedRequestCount, "a successful StopMapping ACK outside AGV cannot start an invisible stream"); QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 3)); client->agvStateReceived(runtimeA, {}); require(streamRequests == pausedRequestCount, "leaving and reopening AGV cannot implicitly restart a manually stopped stream"); requireEmptyMap(); refreshState->click(); client->agvStateReceived(runtimeA, {}); require(streamRequests == pausedRequestCount + 1 && streamTarget == "real_map" && streamPreview, "explicit refresh releases manual pause and reloads the fresh current map once"); emitFrame(liveImage, metadataA, "A resumes only after explicit refresh"); waitFor([&]() { return view->mapId() == "real_map" && coordinate->isEnabled() && save->isEnabled(); }, "explicit refresh restores the A frame and its retained test-owned draft"); inspectObjects({failedDraft, draft, "REAL_HOME"}, {"REAL_B"}); require(localSaveMaps.size() == 1, "manual stop and explicit recovery do not upload a draft"); qInfo("PASS phase: %s manual stop survives failed/successful state, delayed StopMapping ACK and page changes until explicit refresh", demoMode ? "synthetic Demo" : "synthetic real"); // Refresh is tied to each explicit switch, including switching to the // same map. A target name in an old cache or before the ACK is no proof. QVariantMap timedA = runtimeA; timedA.insert("timestamp", 100.0); client->agvStateReceived(timedA, {}); const int sameMapSwitches = previewRequests; const int sameMapStreams = streamRequests; map->setCurrentText("real_map"); loadMap->click(); require(previewRequests == sameMapSwitches + 1 && streamRequests == sameMapStreams + 1, "same-map click sends one switch and one initial preview"); const quint64 beforeActivationGeneration = client->agvMapStreamGeneration(); QVariantMap freshA = timedA; freshA.insert("timestamp", 101.0); client->agvStateReceived(freshA, {}); require(streamRequests == sameMapStreams + 1, "matching target state before ACK cannot trigger activation refresh"); client->commandFinished("AGV SwitchMap", true, "same-map ACK"); client->agvStateReceived(timedA, {}); QVariantMap untypedA = freshA; untypedA.remove("deviceId"); untypedA.remove("endpoint"); untypedA.remove("demo"); client->agvStateReceived(untypedA, {}); QVariantMap oldGenerationA = freshA; oldGenerationA.insert("streamGeneration", QVariant::fromValue(beforeActivationGeneration - 1)); client->agvStateReceived(oldGenerationA, {}); require(streamRequests == sameMapStreams + 1 && !switchStatus->text().contains(QStringLiteral("已确认")), "same-map cached timestamp and untyped target state do not confirm the new request"); client->agvStateReceived(freshA, {}); require(streamRequests == sameMapStreams + 2 && client->agvMapStreamGeneration() > beforeActivationGeneration, "fresh post-ACK same-map state causes one new snapshot generation"); QVariantMap oldSameMap = metadataA; oldSameMap.insert("streamGeneration", QVariant::fromValue(beforeActivationGeneration)); emitFrame(liveImage, oldSameMap, "old pre-activation same-map frame"); for (int repeat = 0; repeat < 3; ++repeat) { client->agvStateReceived(freshA, {}); client->commandFinished("AGV SwitchMap", true, "duplicate old ACK"); } require(streamRequests == sameMapStreams + 2 && previewRequests == sameMapSwitches + 1, "old same-map frames, duplicate ACKs and repeated state cannot repeat the confirmed refresh"); loadMap->click(); const int nextSameMapStreams = streamRequests; client->commandFinished("AGV SwitchMap", false, "same-map rejected ACK"); freshA.insert("timestamp", 102.0); client->agvStateReceived(freshA, {}); require(streamRequests == nextSameMapStreams && previewRequests == sameMapSwitches + 2, "a failed same-map request cannot inherit the preceding request's confirmation"); qInfo("PASS phase: %s one activation refresh per explicit request, fresh timestamps, typed context, same-map switches and failed-request isolation", demoMode ? "synthetic Demo" : "synthetic real"); } // Exercise the direct-mode UI with synthetic signals only. Keep its TCP // implementation disabled in RobotClient; all relevant service signals // were disconnected above, and no direct operation reaches the worker. editor->setAutoLoadEnabled(false); QObject::disconnect(client, &RobotClient::agvActionRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvVelocityRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvNavigatePoseRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvNavigateStationRequested, nullptr, nullptr); QObject::disconnect(client, &RobotClient::agvFollowPathRequested, nullptr, nullptr); fixtureDevice = liveDevice + QStringLiteral("_direct_ui"); demo->setChecked(false); id->setText(fixtureDevice); mapDirectMode->setCurrentIndex(1); QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic direct UI only"))); const auto disableDirectTransport = [&]() { client->configureAgvMapDirect(false, QString(), host->text().trimmed(), 50053); }; disableDirectTransport(); const auto directContext = contextFor(fixtureDevice, false); QVariantMap directRuntimeA = directContext; directRuntimeA.insert("connected", true); directRuntimeA.insert("localized", true); directRuntimeA.insert("mode", 2); directRuntimeA.insert("map", "real_map"); directRuntimeA.insert("station", "REAL_HOME"); QVariantMap directRuntimeB = directRuntimeA; directRuntimeB.insert("map", "real_map_0"); directRuntimeB.insert("station", "REAL_B"); QVariantMap directMetadataA = liveMetadata; QVariantMap directMetadataB = liveMetadata; for (auto it = directContext.cbegin(); it != directContext.cend(); ++it) { directMetadataA.insert(it.key(), it.value()); directMetadataB.insert(it.key(), it.value()); } directMetadataA.insert("mapId", "real_map"); directMetadataB.insert("mapId", "real_map_0"); client->agvStateReceived(directRuntimeA, {}); client->agvInventoryReceivedForContext(directContext, liveMaps, liveStations); emitFrame(liveImage, directMetadataA, "synthetic direct map A"); waitFor([&]() { return view->mapId() == "real_map" && loadMap->isEnabled(); }, "synthetic direct UI starts with a usable local map and no TCP operation"); auto *directPage = window.findChild("agvPage"); require(directPage != nullptr, "direct UI controls belong to the AGV page"); const auto buttonWithText = [&](const QString &text) { for (QPushButton *button : directPage->findChildren()) if (button->text() == text) return button; return static_cast(nullptr); }; auto *directNavigate = buttonWithText(QStringLiteral("导航到目标位姿")); auto *directForward = buttonWithText(QStringLiteral("前进 (W)")); auto *directStop = buttonWithText(QStringLiteral("停止")); auto *directVelocityStop = buttonWithText(QStringLiteral("停止速度")); auto *directEmergency = buttonWithText(QStringLiteral("AGV 急停")); require(directNavigate && directForward && directStop && directVelocityStop && directEmergency, "direct UI exposes navigation, manual motion, stop and emergency controls"); require(directNavigate->isEnabled() && directForward->isEnabled() && mapDirectMode->isEnabled() && mapDirectHost->isEnabled(), "direct UI motion and connection controls are ready before a map operation"); QStringList syntheticStops; QObject::connect(client, &RobotClient::agvActionRequested, client, [&](const QString &device, const QString &action) { require(device == fixtureDevice, "synthetic stop retains the selected direct device"); syntheticStops.append(action); }); client->agvMapDirectBusyChanged(true); require(!directNavigate->isEnabled() && !directForward->isEnabled() && !mapDirectMode->isEnabled() && !mapDirectHost->isEnabled() && !loadMap->isEnabled() && directStop->isEnabled() && directVelocityStop->isEnabled() && directEmergency->isEnabled(), "direct busy disables navigation, manual motion, switching and connection options while retaining stop controls"); directStop->click(); directVelocityStop->click(); directEmergency->click(); require(syntheticStops.contains(QStringLiteral("StopVelocity")) && syntheticStops.contains(QStringLiteral("EmergencyStop")), "busy direct UI can dispatch stop and emergency through disconnected synthetic service signals"); client->agvMapDirectBusyChanged(false); require(directNavigate->isEnabled() && directForward->isEnabled() && mapDirectMode->isEnabled() && mapDirectHost->isEnabled() && loadMap->isEnabled(), "physical direct completion restores motion and connection controls"); map->setCurrentText("real_map_0"); const int directSwitchCount = previewRequests; loadMap->click(); require(previewRequests == directSwitchCount + 1 && switchStatus->text().contains(QStringLiteral("正在请求车辆切换")), "direct-mode presentation stays pending until a synthetic command acknowledgement arrives"); emitFrame(liveImage, directMetadataB, "synthetic direct target B"); waitFor([&]() { return view->mapId() == "real_map_0"; }, "direct target preview is independent of vehicle switch acknowledgement"); client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "old confirmation before this ACK"); require(!switchStatus->text().contains(QStringLiteral("已确认")), "a typed confirmation delivered before this request's ACK cannot confirm the new direct switch"); client->commandFinished("AGV SwitchMap", true, QStringLiteral("切图请求已接受,车辆当前地图待确认")); client->agvStateReceived(directRuntimeB, {}); require(switchStatus->text().contains(QStringLiteral("待确认")) && !switchStatus->text().contains(QStringLiteral("已确认")) && !switchStatus->styleSheet().contains(QStringLiteral("#16835e")), "matching connected service-cache map cannot promote an uncertain direct switch to confirmed green"); QVariantMap cachedOfflineTarget = directRuntimeB; cachedOfflineTarget.insert("connected", false); client->agvStateReceived(cachedOfflineTarget, {}); require(switchStatus->text().contains(QStringLiteral("待确认")) && !switchStatus->text().contains(QStringLiteral("已确认")), "matching offline service-cache map also leaves the direct request unconfirmed"); client->agvDirectMapSwitchConfirmed("wrong_direct_device", "real_map_0", "wrong-context fixture"); client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map", "wrong-map fixture"); require(!switchStatus->text().contains(QStringLiteral("已确认")), "typed direct confirmation rejects a different device or target map"); const int directBeforeConfirmedRefresh = streamRequests; client->agvMapDirectBusyChanged(true); client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "synthetic direct completion"); require(streamRequests == directBeforeConfirmedRefresh, "direct confirmation waits for the previous transport operation to physically finish before re-reading"); client->agvMapDirectBusyChanged(false); waitFor([&]() { return streamRequests == directBeforeConfirmedRefresh + 1; }, "direct transport completion releases one deferred snapshot refresh"); require(switchStatus->text().contains(QStringLiteral("车辆直连已确认本次切图完成")) && switchStatus->styleSheet().contains(QStringLiteral("#16835e")), "only matching typed direct confirmation marks this switch completed and green"); require(previewRequests == directSwitchCount + 1, "cache changes and typed confirmation never resend a direct switch request"); require(streamRequests == directBeforeConfirmedRefresh + 1, "matching typed direct completion refreshes the selected snapshot once"); client->agvDirectMapSwitchConfirmed(fixtureDevice, "real_map_0", "duplicate direct completion"); client->agvStateReceived(directRuntimeB, {}); require(streamRequests == directBeforeConfirmedRefresh + 1, "duplicate direct confirmation and service-cache state cannot repeat the snapshot refresh"); // A port-only source change must invalidate the prior typed confirmation, // even though the direct vehicle/configuration settings would be equal. port->setValue(port->value() == 50053 ? 50054 : 50053); disableDirectTransport(); require(switchStatus->isHidden() && mapDirectHost->text().isEmpty(), "source-port change clears the previous direct confirmation and vehicle override"); const QVariantMap changedDirectContext = contextFor(fixtureDevice, false); for (auto it = changedDirectContext.cbegin(); it != changedDirectContext.cend(); ++it) { directRuntimeB.insert(it.key(), it.value()); directMetadataB.insert(it.key(), it.value()); } directRuntimeB.insert("connected", true); client->agvStateReceived(directRuntimeB, {}); client->agvInventoryReceivedForContext(changedDirectContext, liveMaps, liveStations); emitFrame(liveImage, directMetadataB, "synthetic direct B after source change"); waitFor([&]() { return view->mapId() == "real_map_0" && loadMap->isEnabled(); }, "source-changed direct UI accepts only the new local map context"); map->setCurrentText("real_map_0"); loadMap->click(); client->commandFinished("AGV SwitchMap", true, QStringLiteral("切图请求已接受,新的连接仍待确认")); client->agvStateReceived(directRuntimeB, {}); require(switchStatus->text().contains(QStringLiteral("待确认")) && !switchStatus->text().contains(QStringLiteral("已确认")) && !switchStatus->styleSheet().contains(QStringLiteral("#16835e")), "a new source cannot reuse the previous map's typed direct confirmation"); qInfo("PASS phase: synthetic direct pending/uncertain/confirmed states, service-cache isolation, busy controls and source invalidation without TCP"); QMetaObject::invokeMethod(&window, "updateConnection", Qt::DirectConnection, Q_ARG(bool, false), Q_ARG(int, 0), Q_ARG(QString, QStringLiteral("synthetic test complete"))); if (argc > 1) { QFile log(QString::fromLocal8Bit(argv[1]) + ".log"); require(log.open(QIODevice::WriteOnly | QIODevice::Text), "test log opened"); log.write("PASS: AGV initialization/layout, 64-map inventory, two-map edits/names/drafts, device and Demo/real context reset, late callbacks, availability recovery, staged map-switch ACK and bounded generation-safe preview recovery\n"); } qInfo("PASS: AGV page layout/64 entries, two-map edits/names/drafts, device/Demo-real context reset, staged map-switch ACK and bounded generation-safe preview recovery"); return 0; }