From 040d6b993855ebffc10eed682f6cb14560cfbe62 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:01:40 +0100 Subject: [PATCH 1/9] Avoid GCC 14 optional payload warnings without changing projection behavior --- src/codex/ShellWidget.cpp | 5503 ++++++++--------- src/codex/middle/ConversationItemModel.cpp | 3073 +++++----- src/codex/ui/NodeGraphUiAdapter.cpp | 6166 +++++++++----------- 3 files changed, 6915 insertions(+), 7827 deletions(-) diff --git a/src/codex/ShellWidget.cpp b/src/codex/ShellWidget.cpp index ef54d29..8352048 100644 --- a/src/codex/ShellWidget.cpp +++ b/src/codex/ShellWidget.cpp @@ -66,3022 +66,2657 @@ #include namespace codexui::codex { -namespace { - -using nodegraph::boolFromValue; -using nodegraph::exactStringFromValue; -using nodegraph::signedIntegerFromValue; -using nodegraph::valueMember; - -constexpr auto DraftThreadId = "draft:new-thread"; -constexpr int GraphRetryDelayMilliseconds = 8; -constexpr qint64 PaneCommitBudgetMilliseconds = 8; -constexpr std::size_t ConversationPresentationRowsPerPass = 8; -constexpr int ConversationProjectionQuietMilliseconds = 500; - -bool containsKind(const nodegraph::GraphChanged &change, - std::initializer_list kinds) { - const auto matches = [kinds](const nodegraph::NodeRef &node) { - return node && std::ranges::find(kinds, node->id().kind) != kinds.end(); - }; - return std::ranges::any_of(change.affected, matches) || - std::ranges::any_of(change.removed, matches); -} - -QString text(std::string_view value) { - return QString::fromUtf8(value.data(), static_cast(value.size())); -} - -std::string utf8(const QString &value) { return value.toUtf8().toStdString(); } - -QString lastActivityText(std::int64_t timestamp) { - const QDateTime activity = - QDateTime::fromSecsSinceEpoch(timestamp).toLocalTime(); - const QDateTime now = QDateTime::currentDateTime(); - const QString formatted = - activity.date() == now.date() - ? activity.toString(QStringLiteral("HH:mm:ss")) - : activity.toString(QStringLiteral("yyyy-MM-dd HH:mm:ss")); - return QStringLiteral("Last activity: %1").arg(formatted); -} - -void collectThreadTitles(const std::vector &rows, - std::vector &titles) { - for (const ui::ThreadListRow &row : rows) { - titles.push_back(row.title); - collectThreadTitles(row.children, titles); - } -} - -bool fieldChanged(const nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &node, std::string_view field, - std::uint64_t revision) { - return node && read.contains(node) && - read.fieldChangedRevision(node, field) == revision; -} - -struct ThreadPaneRoute { - bool affected = false; - bool structural = false; - std::vector rows; - std::uint64_t graphRevision = 0; -}; - -enum class ThreadSelectionOrigin { Graph, User }; - -ThreadPaneRoute -threadPaneRoute(const nodegraph::GraphChanged &change, - const nodegraph::NodeGraph::ReadAccess &access, - middle::ThreadPane::SortCriterion sortCriterion, - ui::ThreadGrouping grouping, - std::uint64_t lastRoutedRevision) { - if (lastRoutedRevision != 0 && change.revision != 0 && - change.revision <= lastRoutedRevision) - return {}; - if (change.rescanRequired) - return {true, true, {}, access.revision()}; - if (containsKind(change, {nodegraph::NodeKind::Project, - nodegraph::NodeKind::ThreadSection}) || - std::ranges::any_of(change.affected, [](const auto &node) { - return node && node->id().kind == nodegraph::NodeKind::Catalog && - node->id().canonical.starts_with("thread-browser:"); - })) - return {true, true, {}, access.revision()}; - if (containsKind(change, {nodegraph::NodeKind::Connection, - nodegraph::NodeKind::Interaction}) || - std::ranges::any_of(change.removed, [](const auto &node) { - return node && (node->id().kind == nodegraph::NodeKind::Runtime || - node->id().kind == nodegraph::NodeKind::Connection || - node->id().kind == nodegraph::NodeKind::Thread); - })) - return {true, true, {}}; - const auto *read = &access; - constexpr std::array Fields{"projectId", - "section", - "sectionEnteredAt", - "name", - "localNameOverlay", - "title", - "preview", - "cwd", - "workspace", - "status", - "createdAt", - "updatedAt", - "recencyAt", - "lastActivityAt", - "localActivityAt", - "localPromptActivityAt", - "confirmedLocalPromptActivityAt", - "hydrationState", - "uninspectedResult", - "archived"}; - ThreadPaneRoute route; - route.graphRevision = change.revision; - for (const nodegraph::NodeRef &node : change.affected) { - if (!node || !read->contains(node)) - continue; - if (node->id().kind == nodegraph::NodeKind::Runtime) { - if (read->structureChangedRevision(node) == change.revision) - return {true, true, {}}; - continue; - } - if (node->id().kind == nodegraph::NodeKind::Item) { - const auto state = read->state(node); - if (!state || - exactStringFromValue(valueMember(*state, "type")) != "localPrompt") - continue; - nodegraph::NodeRef owner = read->parent(node); - while (owner && owner->id().kind != nodegraph::NodeKind::Thread) - owner = read->parent(owner); - if (owner && std::ranges::find(route.rows, owner) == route.rows.end()) { - route.affected = true; - route.rows.push_back(std::move(owner)); - } - continue; - } - if (node->id().kind != nodegraph::NodeKind::Thread) - continue; - const bool presentationChanged = - read->statusChangedRevision(node) == change.revision || - std::ranges::any_of(Fields, [&](std::string_view field) { - return fieldChanged(*read, node, field, change.revision); + namespace { + + using nodegraph::boolFromValue; + using nodegraph::exactStringFromValue; + using nodegraph::signedIntegerFromValue; + using nodegraph::valueMember; + + constexpr auto DraftThreadId = "draft:new-thread"; + constexpr int GraphRetryDelayMilliseconds = 8; + constexpr qint64 PaneCommitBudgetMilliseconds = 8; + constexpr std::size_t ConversationPresentationRowsPerPass = 8; + constexpr int ConversationProjectionQuietMilliseconds = 500; + + bool containsKind(const nodegraph::GraphChanged& change, std::initializer_list kinds) { + const auto matches = [kinds](const nodegraph::NodeRef& node) { + return node && std::ranges::find(kinds, node->id().kind) != kinds.end(); + }; + return std::ranges::any_of(change.affected, matches) || std::ranges::any_of(change.removed, matches); + } + + QString text(std::string_view value) { + return QString::fromUtf8(value.data(), static_cast(value.size())); + } + + std::string utf8(const QString& value) { + return value.toUtf8().toStdString(); + } + + QString lastActivityText(std::int64_t timestamp) { + const QDateTime activity = QDateTime::fromSecsSinceEpoch(timestamp).toLocalTime(); + const QDateTime now = QDateTime::currentDateTime(); + const QString formatted = activity.date() == now.date() ? activity.toString(QStringLiteral("HH:mm:ss")) + : activity.toString(QStringLiteral("yyyy-MM-dd HH:mm:ss")); + return QStringLiteral("Last activity: %1").arg(formatted); + } + + void collectThreadTitles(const std::vector& rows, std::vector& titles) { + for (const ui::ThreadListRow& row : rows) { + titles.push_back(row.title); + collectThreadTitles(row.children, titles); + } + } + + bool fieldChanged(const nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& node, + std::string_view field, + std::uint64_t revision) { + return node && read.contains(node) && read.fieldChangedRevision(node, field) == revision; + } + + struct ThreadPaneRoute { + bool affected = false; + bool structural = false; + std::vector rows; + std::uint64_t graphRevision = 0; + }; + + enum class ThreadSelectionOrigin { Graph, User }; + + ThreadPaneRoute threadPaneRoute(const nodegraph::GraphChanged& change, + const nodegraph::NodeGraph::ReadAccess& access, + middle::ThreadPane::SortCriterion sortCriterion, + ui::ThreadGrouping grouping, + std::uint64_t lastRoutedRevision) { + if (lastRoutedRevision != 0 && change.revision != 0 && change.revision <= lastRoutedRevision) + return {}; + if (change.rescanRequired) + return {true, true, {}, access.revision()}; + if (containsKind(change, {nodegraph::NodeKind::Project, nodegraph::NodeKind::ThreadSection}) || + std::ranges::any_of(change.affected, [](const auto& node) { + return node && node->id().kind == nodegraph::NodeKind::Catalog && node->id().canonical.starts_with("thread-browser:"); + })) + return {true, true, {}, access.revision()}; + if (containsKind(change, {nodegraph::NodeKind::Connection, nodegraph::NodeKind::Interaction}) || + std::ranges::any_of(change.removed, [](const auto& node) { + return node && (node->id().kind == nodegraph::NodeKind::Runtime || node->id().kind == nodegraph::NodeKind::Connection || + node->id().kind == nodegraph::NodeKind::Thread); + })) + return {true, true, {}}; + const auto* read = &access; + constexpr std::array Fields{"projectId", + "section", + "sectionEnteredAt", + "name", + "localNameOverlay", + "title", + "preview", + "cwd", + "workspace", + "status", + "createdAt", + "updatedAt", + "recencyAt", + "lastActivityAt", + "localActivityAt", + "localPromptActivityAt", + "confirmedLocalPromptActivityAt", + "hydrationState", + "uninspectedResult", + "archived"}; + ThreadPaneRoute route; + route.graphRevision = change.revision; + for (const nodegraph::NodeRef& node : change.affected) { + if (!node || !read->contains(node)) + continue; + if (node->id().kind == nodegraph::NodeKind::Runtime) { + if (read->structureChangedRevision(node) == change.revision) + return {true, true, {}}; + continue; + } + if (node->id().kind == nodegraph::NodeKind::Item) { + const auto state = read->state(node); + if (!state || exactStringFromValue(valueMember(*state, "type")) != "localPrompt") + continue; + nodegraph::NodeRef owner = read->parent(node); + while (owner && owner->id().kind != nodegraph::NodeKind::Thread) + owner = read->parent(owner); + if (owner && std::ranges::find(route.rows, owner) == route.rows.end()) { + route.affected = true; + route.rows.push_back(std::move(owner)); + } + continue; + } + if (node->id().kind != nodegraph::NodeKind::Thread) + continue; + const bool presentationChanged = + read->statusChangedRevision(node) == change.revision || std::ranges::any_of(Fields, [&](std::string_view field) { + return fieldChanged(*read, node, field, change.revision); + }); + if (!presentationChanged && read->structureChangedRevision(node) != change.revision) + continue; + const bool sortChanged = + (sortCriterion == middle::ThreadPane::SortCriterion::Alphanumeric && + (fieldChanged(*read, node, "name", change.revision) || + fieldChanged(*read, node, "localNameOverlay", change.revision) || + fieldChanged(*read, node, "title", change.revision) || fieldChanged(*read, node, "preview", change.revision))) || + (sortCriterion == middle::ThreadPane::SortCriterion::Created && + fieldChanged(*read, node, "createdAt", change.revision)) || + (sortCriterion == middle::ThreadPane::SortCriterion::Recency && + (fieldChanged(*read, node, "recencyAt", change.revision) || + fieldChanged(*read, node, "localPromptActivityAt", change.revision) || + fieldChanged(*read, node, "confirmedLocalPromptActivityAt", change.revision))); + if (read->structureChangedRevision(node) == change.revision || + (grouping != ui::ThreadGrouping::Ungrouped && read->statusChangedRevision(node) == change.revision) || sortChanged || + fieldChanged(*read, node, "uninspectedResult", change.revision) || + fieldChanged(*read, node, "archived", change.revision)) { + return {true, true, {}}; + } + route.affected = true; + if (std::ranges::find(route.rows, node) == route.rows.end()) + route.rows.push_back(node); + } + // Family activity requires a complete presentation refresh, not action rejection. + route.structural = std::ranges::any_of(route.rows, [&](const auto& node) { + return std::ranges::any_of(std::array{nodegraph::RelationKind::StructuralChildThread, + nodegraph::RelationKind::AgentChildThread, + nodegraph::RelationKind::ForkChildThread}, + [&](auto kind) { + return read->relatedCount(node, kind) != 0 || read->hasIncomingRelation(node, kind); + }); + }); + return route; + } + + std::vector graphAttachmentDrafts(const nodegraph::NodeState& state) { + std::vector result; + const nodegraph::Value* attachments = valueMember(state, "attachments"); + const nodegraph::Value::Array* array = attachments ? attachments->asArray() : nullptr; + if (!array) + return result; + result.reserve(array->size()); + for (const nodegraph::Value& entry : *array) { + const nodegraph::Value::Object* object = entry.asObject(); + if (!object) + continue; + AttachmentDraft attachment; + attachment.path = exactStringFromValue(valueMember(*object, "path")); + attachment.name = exactStringFromValue(valueMember(*object, "displayName")); + attachment.mimeType = exactStringFromValue(valueMember(*object, "mimeType")); + if (!attachment.path.empty()) + result.emplace_back(std::move(attachment)); + } + return result; + } + + bool shellChromeAffected(const nodegraph::GraphChanged& change, + const nodegraph::NodeGraph::ReadAccess& access, + const nodegraph::NodeRef& selectedThread) { + if (change.rescanRequired) + return true; + constexpr std::size_t MaximumFilteredNodes = 64; + if (change.affected.size() + change.removed.size() > MaximumFilteredNodes) + return true; + + const auto* read = &access; + const auto directlyAffectsChrome = [&](const auto& node) { + if (!node) + return false; + if (!read->contains(node)) + return true; + switch (node->id().kind) { + case nodegraph::NodeKind::Connection: + return true; + case nodegraph::NodeKind::Account: + return node->id().canonical == "account/usage/read"; + case nodegraph::NodeKind::Catalog: + return node->id().canonical == "model" || node->id().canonical == "permissionProfile"; + case nodegraph::NodeKind::Thread: { + if (fieldChanged(*read, node, "tokenUsage", change.revision) || + read->structureChangedRevision(node) == change.revision) + return true; + if (!selectedThread || node != selectedThread) + return false; + constexpr std::array Fields{"name", + "title", + "cwd", + "workspace", + "status", + "hydrationState", + "recoveryOnly", + "lastActivityAt", + "recencyAt", + "updatedAt", + "localActivityAt", + "localPromptActivityAt", + "settingsRevision", + "settings", + "settingsAcknowledgements"}; + return read->statusChangedRevision(node) == change.revision || + read->structureChangedRevision(node) == change.revision || + std::ranges::any_of(Fields, [&](std::string_view field) { + return fieldChanged(*read, node, field, change.revision); + }); + } + default: + return false; + } + }; + if (std::ranges::any_of(change.affected, directlyAffectsChrome) || std::ranges::any_of(change.removed, directlyAffectsChrome)) + return true; + if (!selectedThread) + return false; + + const auto turnBelongsToSelection = [&](const auto& node) { + if (!node || node->id().kind != nodegraph::NodeKind::Turn) + return false; + if (read->statusChangedRevision(node) != change.revision && read->structureChangedRevision(node) != change.revision) + return false; + if (read->parent(node) == selectedThread) + return true; + return exactStringFromValue(valueMember(*read->state(node), "protocolThreadId")) == selectedThread->id().canonical; + }; + return std::ranges::any_of(change.affected, turnBelongsToSelection) || + std::ranges::any_of(change.removed, turnBelongsToSelection); + } + + bool graphUiFallbackAffected(const nodegraph::GraphChanged& change, const nodegraph::NodeGraph::ReadAccess& access) { + if (change.rescanRequired || containsKind(change, {nodegraph::NodeKind::Notice})) + return true; + const auto* read = &access; + return std::ranges::any_of(change.affected, [&](const auto& node) { + return node && read->contains(node) && node->id().kind == nodegraph::NodeKind::Runtime && + (read->structureChangedRevision(node) == change.revision || + fieldChanged(*read, node, "uiSelectionSerial", change.revision)); + }); + } + + bool connectionSettingsContainSelection(const nlohmann::json& settings, const nlohmann::json& selection) { + if (!settings.is_object() || !selection.is_object()) + return false; + const std::string transport = selection.value("transport", std::string{}); + if (transport.empty() || settings.value("selected", std::string{}) != transport) + return false; + const nlohmann::json available = settings.value("available", nlohmann::json::array()); + for (const auto& entry : available) { + if (!entry.is_object() || entry.value("key", std::string{}) != transport) + continue; + for (auto field = selection.cbegin(); field != selection.cend(); ++field) { + if (field.key() != "transport" && (!entry.contains(field.key()) || entry[field.key()] != field.value())) + return false; + } + return true; + } + return false; + } + + void applyConnectionSelection(nlohmann::json& settings, const nlohmann::json& selection) { + if (!settings.is_object() || !selection.is_object()) + return; + const std::string transport = selection.value("transport", std::string{}); + if (transport.empty()) + return; + settings["selected"] = transport; + auto available = settings.find("available"); + if (available == settings.end() || !available->is_array()) + return; + for (auto& entry : *available) { + if (!entry.is_object() || entry.value("key", std::string{}) != transport) + continue; + for (auto field = selection.cbegin(); field != selection.cend(); ++field) + if (field.key() != "transport") + entry[field.key()] = field.value(); + return; + } + } + + struct ShellChromeValues final { + bool connected = false; + bool retrying = false; + bool canControl = false; + bool activeTurn = false; + bool threadAdmissionReady = true; + bool conversationReadyForDisplay = true; + bool hydrationFailed = false; + bool recoveryOnly = false; + std::string role; + std::string providerState; + std::string selectedTransport; + std::string workspace; + std::string workspaceChangeUnavailable; + std::string title; + ui::TokenUsageSnapshot tokenUsage; + UiStatus status; + std::optional lastActivityAt; + std::size_t totalPending = 0; + std::optional attention; + + bool operator==(const ShellChromeValues&) const = default; + }; + + struct LocalPendingRequest final { + PendingRequestSubmission submission; + std::optional awaitingResponseAfter; + }; + + using UiStyle::makeLabel; + + QLabel* makeStatusLabel(QString value, QString objectName, int maximumWidth, const char* kind = "meta") { + auto* label = makeLabel({}, kind); + label->setObjectName(std::move(objectName)); + label->setWordWrap(false); + label->setMaximumWidth(maximumWidth); + label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + label->setToolTip(value); + label->setText(label->fontMetrics().elidedText(value, Qt::ElideMiddle, label->maximumWidth())); + return label; + } + + void setStatusLabelText(QLabel* label, QString value) { + const QString displayed = label->fontMetrics().elidedText(value, Qt::ElideMiddle, label->maximumWidth()); + if (label->toolTip() != value) + label->setToolTip(value); + if (label->text() != displayed) + label->setText(displayed); + } + + void setStatusTone(QFrame* dot, const QString& tone, QLabel* label = nullptr) { + for (QWidget* target : {static_cast(dot), static_cast(label)}) { + if (!target || target->property("tone").toString() == tone) + continue; + target->setProperty("tone", tone); + target->style()->unpolish(target); + target->style()->polish(target); + target->update(); + } + } + + } // namespace + + struct ShellWidget::Impl final { + Impl(ShellWidget* owner, FrontendSession& session) + : owner(owner) + , session(session) + , uiAdapter(session.nodeGraph()) + , alive(std::make_shared(true)) { + owner->setProperty("conversationPresentationRowsPerPassBudget", static_cast(ConversationPresentationRowsPerPass)); + buildUi(); + connectUi(); + const auto token = alive; + session.setGraphChangedHandler([this, token](const nodegraph::GraphChanged& change) { + if (token->load(std::memory_order_acquire)) + return handleGraphChanged(change); + return true; + }); + session.setProtocolDiagnosticHandler([this, token](const nodegraph::ProtocolDiagnostic& diagnostic) { + if (token->load(std::memory_order_acquire)) + handleProtocolDiagnostic(diagnostic); + }); + bindGraphPanes({}); + observedProviderAuthorityRevision = middleRegion->composer().turnSettings().context().providerAuthorityRevision; + } + + ~Impl() { + alive->store(false, std::memory_order_release); + projectionPool.waitForDone(); + session.setGraphChangedHandler({}); + session.setProtocolDiagnosticHandler({}); + if (!pendingUiDetachments.empty()) { + std::vector detached; + detached.reserve(pendingUiDetachments.size()); + for (auto& [node, reference] : pendingUiDetachments) { + static_cast(node); + detached.push_back(std::move(reference)); + } + session.acknowledgeUiDetached(detached); + } + if (qApp) + qApp->removeEventFilter(owner); + } + + void buildUi(); + void connectUi(); + void scheduleGraphBinding(bool immediate = true); + void runGraphBinding(); + void bindGraphPanes(nodegraph::NodeRef selectedThread); + [[nodiscard]] bool refreshConversation(); + void requestConversationSnapshot(); + void requestConversationRescan(); + void requestConversationProjection(bool fullSnapshot); + void startConversationSnapshot(); + [[nodiscard]] bool refreshInspector(); + void requestInspectorProjection(nodegraph::NodeRef thread, ui::InspectorProjection projection, ui::InspectorRowRequest request); + void startInspectorProjection(); + void queueConversationRoute(const ui::NodeGraphUiAdapter::ConversationRoute& route); + void clearPendingConversationItems(); + void popPendingConversationItem(); + [[nodiscard]] bool uiRetainsTarget(const nodegraph::NodeRef& target) const noexcept; + void acknowledgeDetachedTargets(); + void schedulePaneCommit(bool immediate = false); + void commitPendingPanes(); + [[nodiscard]] bool handleGraphChanged(const nodegraph::GraphChanged& change); + void handleProtocolDiagnostic(const nodegraph::ProtocolDiagnostic& diagnostic); + void reconcileGraphUiFallback(); + void selectGraphThread(nodegraph::NodeRef thread, ThreadSelectionOrigin origin, std::uint64_t graphSerial = 0); + void render(const ui::PendingRequestsSummary* requests = nullptr); + void renderStatus(const ShellChromeValues& values); + void showNotice(QString message, bool error = true); + [[nodiscard]] bool sendNodeAction(nodegraph::NodeAction action, QString rejection); + [[nodiscard]] bool sendRuntimeAction(nodegraph::RuntimeAction action, QString rejection); + [[nodiscard]] nodegraph::NodeRef activeTurn() const; + [[nodiscard]] std::optional pendingRequestSummary(bool* busy = nullptr); + [[nodiscard]] std::optional pendingRequestPage(const ui::InspectorRowRequest& request, + bool* busy = nullptr); + [[nodiscard]] std::optional pendingRequest(const nodegraph::NodeRef& target); + void applyLocalPending(PendingRequestDescriptor& request); + [[nodiscard]] bool submitPending(const PendingRequestDescriptor& request, PendingRequestSubmission submission); + void hydrateSelectedThreadIfNeeded(nodegraph::NodeRef thread); + [[nodiscard]] std::optional threadSnapshot(std::uint64_t* revision = nullptr); + [[nodiscard]] QStringList projectWorkspaceRoots(const std::string& project); + void beginThreadDraft(NewThreadDraft draft); + void beginNewThreadDialog(std::string project = {}, std::string section = {}); + [[nodiscard]] std::optional suggestedForkDraft(const nodegraph::NodeRef& thread) const; + void forkThread(const nodegraph::NodeRef& thread, NewThreadDraft draft, bool includeOptions, const nodegraph::NodeRef& turn = {}); + void beginForkThreadDialog(nodegraph::NodeRef thread, nodegraph::NodeRef turn = {}); + void renameThreadDialog(const nodegraph::NodeRef& thread); + void changeWorkspaceDialog(const nodegraph::NodeRef& thread); + void confirmDeleteThread(const nodegraph::NodeRef& thread); + void showTurnMenu(nodegraph::NodeRef item, QPoint position); + [[nodiscard]] bool submitPrompt(QString prompt, std::vector attachments); + void recoverPrompt(const nodegraph::NodeRef& prompt); + void presentPending(PendingRequestDescriptor request); + void reviewPending(const nodegraph::NodeRef& target); + void acceptPending(const nodegraph::NodeRef& target); + void rejectPending(const nodegraph::NodeRef& target); + void respondToRenderedPending(void (Impl::*respond)(const nodegraph::NodeRef&)); + + ShellWidget* owner = nullptr; + FrontendSession& session; + ui::NodeGraphUiAdapter uiAdapter; + std::shared_ptr alive; + QThreadPool projectionPool; + std::optional newThreadDraft; + std::string creationDraftCorrelation; + std::uint64_t nextCreationDraftSerial = 1; + std::uint64_t observedProviderAuthorityRevision = 0; + std::uint64_t routedThreadRevision = 0; + std::uint64_t routedConversationRevision = 0; + std::string selectedGraphThreadId; + nodegraph::NodeRef boundGraphThread; + std::map> retainedRenames; + std::map> localPendingRequests; + nodegraph::NodeRef reviewedRequest; + QPointer reviewSubmit; + std::optional retainedConnectionSelection; + bool graphPanesBound = false; + bool graphBindingScheduled = false; + bool paneCommitScheduled = false; + bool pendingThreadPane = false; + std::deque pendingThreadRows; + bool pendingConversation = false; + bool pendingConversationAuthorityReplacement = false; + bool conversationProjectionInFlight = false; + bool conversationFullProjectionInFlight = false; + bool conversationProjectionRequested = false; + bool conversationFullProjectionRequested = false; + bool conversationProjectionStartScheduled = false; + std::uint64_t conversationProjectionScheduleGeneration = 0; + std::optional pendingStructuralConversationDelta; + std::deque pendingConversationItems; + std::unordered_set pendingConversationItemKeys; + std::unordered_map pendingUiDetachments; + bool pendingInspector = false; + bool inspectorProjectionInFlight = false; + bool inspectorProjectionRequested = false; + std::uint64_t inspectorProjectionGeneration = 0; + nodegraph::NodeRef requestedInspectorThread; + ui::InspectorProjection requestedInspectorProjection = ui::InspectorProjection::Plan; + ui::InspectorRowRequest requestedInspectorRows; + bool pendingChrome = false; + bool graphFallbackScheduled = false; + std::uint64_t lastNoticeSerial = 0; + std::uint64_t lastSelectionSerial = 0; + std::optional renderedChrome; + std::uint64_t shellRenderCommits = 0; + std::uint64_t threadPaneRoutes = 0; + std::uint64_t conversationRoutes = 0; + std::uint64_t inspectorRoutes = 0; + + middle::MiddleRegionWidget* middleRegion = nullptr; + QPushButton* restoreSidebarButton = nullptr; + QPushButton* restoreInspectorButton = nullptr; + QPushButton* requestButton = nullptr; + QToolButton* connectionButton = nullptr; + QAction* connectAction = nullptr; + QAction* disconnectAction = nullptr; + QAction* reconnectAction = nullptr; + QPushButton* controllerButton = nullptr; + QFrame* globalStatusDot = nullptr; + QLabel* globalStatusLabel = nullptr; + UiStyle::TokenUsageLabel* overallTokens = nullptr; + }; + + void ShellWidget::Impl::buildUi() { + owner->setObjectName(QStringLiteral("applicationShell")); + auto* root = new QVBoxLayout(owner); + root->setContentsMargins(0, 0, 0, 0); + root->setSpacing(0); + + auto* top = new QFrame; + top->setObjectName(QStringLiteral("topBar")); + top->setMinimumHeight(64); + auto* topLayout = new QHBoxLayout(top); + topLayout->setContentsMargins(18, 0, 18, 0); + topLayout->setSpacing(12); + topLayout->addWidget(codexui::BrandMark::createLockup()); + + restoreSidebarButton = new QPushButton(QStringLiteral("Show threads")); + restoreSidebarButton->setProperty("kind", "subtle"); + restoreSidebarButton->setMinimumHeight(32); + restoreSidebarButton->hide(); + topLayout->addSpacing(12); + topLayout->addWidget(restoreSidebarButton); + topLayout->addStretch(); + + restoreInspectorButton = new QPushButton(QStringLiteral("Show inspector")); + restoreInspectorButton->setProperty("kind", "subtle"); + restoreInspectorButton->setMinimumHeight(32); + restoreInspectorButton->hide(); + requestButton = new QPushButton; + requestButton->setProperty("kind", "request"); + requestButton->setMinimumHeight(32); + requestButton->hide(); + controllerButton = new QPushButton(QStringLiteral("Claim control")); + controllerButton->setMinimumHeight(32); + topLayout->addWidget(restoreInspectorButton); + topLayout->addWidget(requestButton); + topLayout->addWidget(controllerButton); + + connectionButton = new UiStyle::ChevronToolButton; + connectionButton->setObjectName(QStringLiteral("transportButton")); + connectionButton->setText(QStringLiteral("Connection")); + connectionButton->setProperty("kind", "subtle"); + connectionButton->setProperty("codexChevron", true); + connectionButton->setPopupMode(QToolButton::InstantPopup); + connectionButton->setMinimumHeight(32); + auto* connectionMenu = new QMenu(connectionButton); + connectionMenu->addAction(QStringLiteral("Configure..."), owner, [this] { + nlohmann::json settings = nlohmann::json::object(); + { + auto read = session.nodeGraph().tryRead(); + if (!read) { + showNotice(QStringLiteral("Connection state is busy; try again.")); + return; + } + const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"}); + if (connection) { + const auto state = read->state(connection); + if (const nodegraph::Value* value = valueMember(*state, "settings")) + settings = jsonFromValue(*value); + } + } + if (!settings.is_object() || settings.empty()) { + showNotice(QStringLiteral("Connection settings are not available yet.")); + return; + } + if (retainedConnectionSelection && connectionSettingsContainSelection(settings, *retainedConnectionSelection)) + retainedConnectionSelection.reset(); + if (retainedConnectionSelection) + applyConnectionSelection(settings, *retainedConnectionSelection); + ConnectionDialog dialog(std::move(settings), owner); + if (dialog.exec() != QDialog::Accepted) + return; + retainedConnectionSelection = dialog.selection(); + nodegraph::RuntimeAction action; + action.kind = nodegraph::RuntimeActionKind::ConfigureConnection; + action.payload = objectFromJson(*retainedConnectionSelection); + static_cast(sendRuntimeAction(std::move(action), QStringLiteral("Connection settings were not sent; try again."))); }); - if (!presentationChanged && - read->structureChangedRevision(node) != change.revision) - continue; - const bool sortChanged = - (sortCriterion == middle::ThreadPane::SortCriterion::Alphanumeric && - (fieldChanged(*read, node, "name", change.revision) || - fieldChanged(*read, node, "localNameOverlay", change.revision) || - fieldChanged(*read, node, "title", change.revision) || - fieldChanged(*read, node, "preview", change.revision))) || - (sortCriterion == middle::ThreadPane::SortCriterion::Created && - fieldChanged(*read, node, "createdAt", change.revision)) || - (sortCriterion == middle::ThreadPane::SortCriterion::Recency && - (fieldChanged(*read, node, "recencyAt", change.revision) || - fieldChanged(*read, node, "localPromptActivityAt", change.revision) || - fieldChanged(*read, node, "confirmedLocalPromptActivityAt", - change.revision))); - if (read->structureChangedRevision(node) == change.revision || - (grouping != ui::ThreadGrouping::Ungrouped && read->statusChangedRevision(node) == change.revision) || sortChanged || - fieldChanged(*read, node, "uninspectedResult", change.revision) || fieldChanged(*read, node, "archived", change.revision)) { - return {true, true, {}}; - } - route.affected = true; - if (std::ranges::find(route.rows, node) == route.rows.end()) - route.rows.push_back(node); - } - // Family activity requires a complete presentation refresh, not action rejection. - route.structural = std::ranges::any_of(route.rows, [&](const auto& node) { - return std::ranges::any_of(std::array{nodegraph::RelationKind::StructuralChildThread, - nodegraph::RelationKind::AgentChildThread, - nodegraph::RelationKind::ForkChildThread}, - [&](auto kind) { - return read->relatedCount(node, kind) != 0 || read->hasIncomingRelation(node, kind); - }); - }); - return route; -} - -std::vector -graphAttachmentDrafts(const nodegraph::NodeState &state) { - std::vector result; - const nodegraph::Value *attachments = valueMember(state, "attachments"); - const nodegraph::Value::Array *array = - attachments ? attachments->asArray() : nullptr; - if (!array) - return result; - result.reserve(array->size()); - for (const nodegraph::Value &entry : *array) { - const nodegraph::Value::Object *object = entry.asObject(); - if (!object) - continue; - AttachmentDraft attachment; - attachment.path = exactStringFromValue(valueMember(*object, "path")); - attachment.name = exactStringFromValue(valueMember(*object, "displayName")); - attachment.mimeType = - exactStringFromValue(valueMember(*object, "mimeType")); - if (!attachment.path.empty()) - result.emplace_back(std::move(attachment)); - } - return result; -} - -bool shellChromeAffected(const nodegraph::GraphChanged &change, - const nodegraph::NodeGraph::ReadAccess &access, - const nodegraph::NodeRef &selectedThread) { - if (change.rescanRequired) - return true; - constexpr std::size_t MaximumFilteredNodes = 64; - if (change.affected.size() + change.removed.size() > MaximumFilteredNodes) - return true; - - const auto *read = &access; - const auto directlyAffectsChrome = [&](const auto &node) { - if (!node) - return false; - if (!read->contains(node)) - return true; - switch (node->id().kind) { - case nodegraph::NodeKind::Connection: - return true; - case nodegraph::NodeKind::Account: - return node->id().canonical == "account/usage/read"; - case nodegraph::NodeKind::Catalog: - return node->id().canonical == "model" || - node->id().canonical == "permissionProfile"; - case nodegraph::NodeKind::Thread: { - if (fieldChanged(*read, node, "tokenUsage", change.revision) || - read->structureChangedRevision(node) == change.revision) - return true; - if (!selectedThread || node != selectedThread) - return false; - constexpr std::array Fields{ - "name", - "title", - "cwd", - "workspace", - "status", - "hydrationState", - "recoveryOnly", - "lastActivityAt", - "recencyAt", - "updatedAt", - "localActivityAt", - "localPromptActivityAt", - "settingsRevision", - "settings", - "settingsAcknowledgements"}; - return read->statusChangedRevision(node) == change.revision || - read->structureChangedRevision(node) == change.revision || - std::ranges::any_of(Fields, [&](std::string_view field) { - return fieldChanged(*read, node, field, change.revision); - }); - } - default: - return false; - } - }; - if (std::ranges::any_of(change.affected, directlyAffectsChrome) || - std::ranges::any_of(change.removed, directlyAffectsChrome)) - return true; - if (!selectedThread) - return false; - - const auto turnBelongsToSelection = [&](const auto &node) { - if (!node || node->id().kind != nodegraph::NodeKind::Turn) - return false; - if (read->statusChangedRevision(node) != change.revision && - read->structureChangedRevision(node) != change.revision) - return false; - if (read->parent(node) == selectedThread) - return true; - return exactStringFromValue( - valueMember(*read->state(node), "protocolThreadId")) == - selectedThread->id().canonical; - }; - return std::ranges::any_of(change.affected, turnBelongsToSelection) || - std::ranges::any_of(change.removed, turnBelongsToSelection); -} - -bool graphUiFallbackAffected(const nodegraph::GraphChanged &change, - const nodegraph::NodeGraph::ReadAccess &access) { - if (change.rescanRequired || - containsKind(change, {nodegraph::NodeKind::Notice})) - return true; - const auto *read = &access; - return std::ranges::any_of(change.affected, [&](const auto &node) { - return node && read->contains(node) && - node->id().kind == nodegraph::NodeKind::Runtime && - (read->structureChangedRevision(node) == change.revision || - fieldChanged(*read, node, "uiSelectionSerial", change.revision)); - }); -} - -bool connectionSettingsContainSelection(const nlohmann::json &settings, - const nlohmann::json &selection) { - if (!settings.is_object() || !selection.is_object()) - return false; - const std::string transport = selection.value("transport", std::string{}); - if (transport.empty() || - settings.value("selected", std::string{}) != transport) - return false; - const nlohmann::json available = - settings.value("available", nlohmann::json::array()); - for (const auto &entry : available) { - if (!entry.is_object() || entry.value("key", std::string{}) != transport) - continue; - for (auto field = selection.cbegin(); field != selection.cend(); ++field) { - if (field.key() != "transport" && - (!entry.contains(field.key()) || entry[field.key()] != field.value())) - return false; - } - return true; - } - return false; -} - -void applyConnectionSelection(nlohmann::json &settings, - const nlohmann::json &selection) { - if (!settings.is_object() || !selection.is_object()) - return; - const std::string transport = selection.value("transport", std::string{}); - if (transport.empty()) - return; - settings["selected"] = transport; - auto available = settings.find("available"); - if (available == settings.end() || !available->is_array()) - return; - for (auto &entry : *available) { - if (!entry.is_object() || entry.value("key", std::string{}) != transport) - continue; - for (auto field = selection.cbegin(); field != selection.cend(); ++field) - if (field.key() != "transport") - entry[field.key()] = field.value(); - return; - } -} - -struct ShellChromeValues final { - bool connected = false; - bool retrying = false; - bool canControl = false; - bool activeTurn = false; - bool threadAdmissionReady = true; - bool conversationReadyForDisplay = true; - bool hydrationFailed = false; - bool recoveryOnly = false; - std::string role; - std::string providerState; - std::string selectedTransport; - std::string workspace; - std::string workspaceChangeUnavailable; - std::string title; - ui::TokenUsageSnapshot tokenUsage; - UiStatus status; - std::optional lastActivityAt; - std::size_t totalPending = 0; - std::optional attention; - - bool operator==(const ShellChromeValues &) const = default; -}; - -struct LocalPendingRequest final { - PendingRequestSubmission submission; - std::optional awaitingResponseAfter; -}; - -using UiStyle::makeLabel; - -QLabel *makeStatusLabel(QString value, QString objectName, int maximumWidth, - const char *kind = "meta") { - auto *label = makeLabel({}, kind); - label->setObjectName(std::move(objectName)); - label->setWordWrap(false); - label->setMaximumWidth(maximumWidth); - label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - label->setToolTip(value); - label->setText(label->fontMetrics().elidedText(value, Qt::ElideMiddle, - label->maximumWidth())); - return label; -} - -void setStatusLabelText(QLabel *label, QString value) { - const QString displayed = label->fontMetrics().elidedText( - value, Qt::ElideMiddle, label->maximumWidth()); - if (label->toolTip() != value) - label->setToolTip(value); - if (label->text() != displayed) - label->setText(displayed); -} - -void setStatusTone(QFrame *dot, const QString &tone, QLabel *label = nullptr) { - for (QWidget *target : - {static_cast(dot), static_cast(label)}) { - if (!target || target->property("tone").toString() == tone) - continue; - target->setProperty("tone", tone); - target->style()->unpolish(target); - target->style()->polish(target); - target->update(); - } -} - - -} // namespace - -struct ShellWidget::Impl final { - Impl(ShellWidget *owner, FrontendSession &session) - : owner(owner), session(session), uiAdapter(session.nodeGraph()), - alive(std::make_shared(true)) { - owner->setProperty( - "conversationPresentationRowsPerPassBudget", - static_cast(ConversationPresentationRowsPerPass)); - buildUi(); - connectUi(); - const auto token = alive; - session.setGraphChangedHandler( - [this, token](const nodegraph::GraphChanged &change) { - if (token->load(std::memory_order_acquire)) - return handleGraphChanged(change); - return true; + connectionMenu->addSeparator(); + connectAction = connectionMenu->addAction(QStringLiteral("Connect"), owner, [this] { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::Connect, {}, {}, {}, {}}, + QStringLiteral("Connect request was not admitted; try again."))); }); - session.setProtocolDiagnosticHandler( - [this, token](const nodegraph::ProtocolDiagnostic &diagnostic) { - if (token->load(std::memory_order_acquire)) - handleProtocolDiagnostic(diagnostic); + disconnectAction = connectionMenu->addAction(QStringLiteral("Disconnect"), owner, [this] { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::Disconnect, {}, {}, {}, {}}, + QStringLiteral("Disconnect request was not admitted; try again."))); }); - bindGraphPanes({}); - observedProviderAuthorityRevision = middleRegion->composer() - .turnSettings() - .context() - .providerAuthorityRevision; - } - - ~Impl() { - alive->store(false, std::memory_order_release); - projectionPool.waitForDone(); - session.setGraphChangedHandler({}); - session.setProtocolDiagnosticHandler({}); - if (!pendingUiDetachments.empty()) { - std::vector detached; - detached.reserve(pendingUiDetachments.size()); - for (auto &[node, reference] : pendingUiDetachments) { - static_cast(node); - detached.push_back(std::move(reference)); - } - session.acknowledgeUiDetached(detached); - } - if (qApp) - qApp->removeEventFilter(owner); - } - - void buildUi(); - void connectUi(); - void scheduleGraphBinding(bool immediate = true); - void runGraphBinding(); - void bindGraphPanes(nodegraph::NodeRef selectedThread); - [[nodiscard]] bool refreshConversation(); - void requestConversationSnapshot(); - void requestConversationRescan(); - void requestConversationProjection(bool fullSnapshot); - void startConversationSnapshot(); - [[nodiscard]] bool refreshInspector(); - void requestInspectorProjection( - nodegraph::NodeRef thread, ui::InspectorProjection projection, - ui::InspectorRowRequest request); - void startInspectorProjection(); - void queueConversationRoute( - const ui::NodeGraphUiAdapter::ConversationRoute &route); - void clearPendingConversationItems(); - void popPendingConversationItem(); - [[nodiscard]] bool - uiRetainsTarget(const nodegraph::NodeRef &target) const noexcept; - void acknowledgeDetachedTargets(); - void schedulePaneCommit(bool immediate = false); - void commitPendingPanes(); - [[nodiscard]] bool - handleGraphChanged(const nodegraph::GraphChanged &change); - void handleProtocolDiagnostic( - const nodegraph::ProtocolDiagnostic &diagnostic); - void reconcileGraphUiFallback(); - void selectGraphThread(nodegraph::NodeRef thread, - ThreadSelectionOrigin origin, - std::uint64_t graphSerial = 0); - void render(const ui::PendingRequestsSummary *requests = nullptr); - void renderStatus(const ShellChromeValues& values); - void showNotice(QString message, bool error = true); - [[nodiscard]] bool sendNodeAction(nodegraph::NodeAction action, - QString rejection); - [[nodiscard]] bool sendRuntimeAction(nodegraph::RuntimeAction action, - QString rejection); - [[nodiscard]] nodegraph::NodeRef activeTurn() const; - [[nodiscard]] std::optional - pendingRequestSummary(bool *busy = nullptr); - [[nodiscard]] std::optional - pendingRequestPage(const ui::InspectorRowRequest &request, - bool *busy = nullptr); - [[nodiscard]] std::optional - pendingRequest(const nodegraph::NodeRef &target); - void applyLocalPending(PendingRequestDescriptor &request); - [[nodiscard]] bool submitPending(const PendingRequestDescriptor &request, - PendingRequestSubmission submission); - void hydrateSelectedThreadIfNeeded(nodegraph::NodeRef thread); - [[nodiscard]] std::optional - threadSnapshot(std::uint64_t *revision = nullptr); - [[nodiscard]] QStringList projectWorkspaceRoots(const std::string& project); - void beginThreadDraft(NewThreadDraft draft); - void beginNewThreadDialog(std::string project = {}, std::string section = {}); - [[nodiscard]] std::optional - suggestedForkDraft(const nodegraph::NodeRef &thread) const; - void forkThread(const nodegraph::NodeRef& thread, NewThreadDraft draft, bool includeOptions, const nodegraph::NodeRef& turn = {}); - void beginForkThreadDialog(nodegraph::NodeRef thread, nodegraph::NodeRef turn = {}); - void renameThreadDialog(const nodegraph::NodeRef &thread); - void changeWorkspaceDialog(const nodegraph::NodeRef& thread); - void confirmDeleteThread(const nodegraph::NodeRef &thread); - void showTurnMenu(nodegraph::NodeRef item, QPoint position); - [[nodiscard]] bool submitPrompt(QString prompt, - std::vector attachments); - void recoverPrompt(const nodegraph::NodeRef &prompt); - void presentPending(PendingRequestDescriptor request); - void reviewPending(const nodegraph::NodeRef &target); - void acceptPending(const nodegraph::NodeRef &target); - void rejectPending(const nodegraph::NodeRef &target); - void - respondToRenderedPending(void (Impl::*respond)(const nodegraph::NodeRef &)); - - ShellWidget *owner = nullptr; - FrontendSession &session; - ui::NodeGraphUiAdapter uiAdapter; - std::shared_ptr alive; - QThreadPool projectionPool; - std::optional newThreadDraft; - std::string creationDraftCorrelation; - std::uint64_t nextCreationDraftSerial = 1; - std::uint64_t observedProviderAuthorityRevision = 0; - std::uint64_t routedThreadRevision = 0; - std::uint64_t routedConversationRevision = 0; - std::string selectedGraphThreadId; - nodegraph::NodeRef boundGraphThread; - std::map> - retainedRenames; - std::map> - localPendingRequests; - nodegraph::NodeRef reviewedRequest; - QPointer reviewSubmit; - std::optional retainedConnectionSelection; - bool graphPanesBound = false; - bool graphBindingScheduled = false; - bool paneCommitScheduled = false; - bool pendingThreadPane = false; - std::deque pendingThreadRows; - bool pendingConversation = false; - bool pendingConversationAuthorityReplacement = false; - bool conversationProjectionInFlight = false; - bool conversationFullProjectionInFlight = false; - bool conversationProjectionRequested = false; - bool conversationFullProjectionRequested = false; - bool conversationProjectionStartScheduled = false; - std::uint64_t conversationProjectionScheduleGeneration = 0; - std::optional pendingStructuralConversationDelta; - std::deque pendingConversationItems; - std::unordered_set pendingConversationItemKeys; - std::unordered_map - pendingUiDetachments; - bool pendingInspector = false; - bool inspectorProjectionInFlight = false; - bool inspectorProjectionRequested = false; - std::uint64_t inspectorProjectionGeneration = 0; - nodegraph::NodeRef requestedInspectorThread; - ui::InspectorProjection requestedInspectorProjection = - ui::InspectorProjection::Plan; - ui::InspectorRowRequest requestedInspectorRows; - bool pendingChrome = false; - bool graphFallbackScheduled = false; - std::uint64_t lastNoticeSerial = 0; - std::uint64_t lastSelectionSerial = 0; - std::optional renderedChrome; - std::uint64_t shellRenderCommits = 0; - std::uint64_t threadPaneRoutes = 0; - std::uint64_t conversationRoutes = 0; - std::uint64_t inspectorRoutes = 0; - - middle::MiddleRegionWidget *middleRegion = nullptr; - QPushButton *restoreSidebarButton = nullptr; - QPushButton *restoreInspectorButton = nullptr; - QPushButton* requestButton = nullptr; - QToolButton *connectionButton = nullptr; - QAction *connectAction = nullptr; - QAction *disconnectAction = nullptr; - QAction *reconnectAction = nullptr; - QPushButton *controllerButton = nullptr; - QFrame *globalStatusDot = nullptr; - QLabel *globalStatusLabel = nullptr; - UiStyle::TokenUsageLabel *overallTokens = nullptr; -}; - -void ShellWidget::Impl::buildUi() { - owner->setObjectName(QStringLiteral("applicationShell")); - auto *root = new QVBoxLayout(owner); - root->setContentsMargins(0, 0, 0, 0); - root->setSpacing(0); - - auto *top = new QFrame; - top->setObjectName(QStringLiteral("topBar")); - top->setMinimumHeight(64); - auto *topLayout = new QHBoxLayout(top); - topLayout->setContentsMargins(18, 0, 18, 0); - topLayout->setSpacing(12); - topLayout->addWidget(codexui::BrandMark::createLockup()); - - restoreSidebarButton = new QPushButton(QStringLiteral("Show threads")); - restoreSidebarButton->setProperty("kind", "subtle"); - restoreSidebarButton->setMinimumHeight(32); - restoreSidebarButton->hide(); - topLayout->addSpacing(12); - topLayout->addWidget(restoreSidebarButton); - topLayout->addStretch(); - - restoreInspectorButton = new QPushButton(QStringLiteral("Show inspector")); - restoreInspectorButton->setProperty("kind", "subtle"); - restoreInspectorButton->setMinimumHeight(32); - restoreInspectorButton->hide(); - requestButton = new QPushButton; - requestButton->setProperty("kind", "request"); - requestButton->setMinimumHeight(32); - requestButton->hide(); - controllerButton = new QPushButton(QStringLiteral("Claim control")); - controllerButton->setMinimumHeight(32); - topLayout->addWidget(restoreInspectorButton); - topLayout->addWidget(requestButton); - topLayout->addWidget(controllerButton); - - connectionButton = new UiStyle::ChevronToolButton; - connectionButton->setObjectName(QStringLiteral("transportButton")); - connectionButton->setText(QStringLiteral("Connection")); - connectionButton->setProperty("kind", "subtle"); - connectionButton->setProperty("codexChevron", true); - connectionButton->setPopupMode(QToolButton::InstantPopup); - connectionButton->setMinimumHeight(32); - auto *connectionMenu = new QMenu(connectionButton); - connectionMenu->addAction(QStringLiteral("Configure..."), owner, [this] { - nlohmann::json settings = nlohmann::json::object(); - { - auto read = session.nodeGraph().tryRead(); - if (!read) { - showNotice(QStringLiteral("Connection state is busy; try again.")); - return; - } - const nodegraph::NodeRef connection = - read->find({nodegraph::NodeKind::Connection, "connection"}); - if (connection) { - const auto state = read->state(connection); - if (const nodegraph::Value *value = valueMember(*state, "settings")) - settings = jsonFromValue(*value); - } - } - if (!settings.is_object() || settings.empty()) { - showNotice(QStringLiteral("Connection settings are not available yet.")); - return; - } - if (retainedConnectionSelection && - connectionSettingsContainSelection(settings, - *retainedConnectionSelection)) - retainedConnectionSelection.reset(); - if (retainedConnectionSelection) - applyConnectionSelection(settings, *retainedConnectionSelection); - ConnectionDialog dialog(std::move(settings), owner); - if (dialog.exec() != QDialog::Accepted) - return; - retainedConnectionSelection = dialog.selection(); - nodegraph::RuntimeAction action; - action.kind = nodegraph::RuntimeActionKind::ConfigureConnection; - action.payload = objectFromJson(*retainedConnectionSelection); - static_cast(sendRuntimeAction( - std::move(action), - QStringLiteral("Connection settings were not sent; try again."))); - }); - connectionMenu->addSeparator(); - connectAction = - connectionMenu->addAction(QStringLiteral("Connect"), owner, [this] { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::Connect, {}, {}, {}, {}}, - QStringLiteral("Connect request was not admitted; try again."))); - }); - disconnectAction = - connectionMenu->addAction(QStringLiteral("Disconnect"), owner, [this] { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::Disconnect, {}, {}, {}, {}}, - QStringLiteral("Disconnect request was not admitted; try again."))); - }); - reconnectAction = - connectionMenu->addAction(QStringLiteral("Reconnect"), owner, [this] { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::Reconnect, {}, {}, {}, {}}, - QStringLiteral("Reconnect request was not admitted; try again."))); - }); - connectionButton->setMenu(connectionMenu); - topLayout->addWidget(connectionButton); - root->addWidget(top); - - middleRegion = new middle::MiddleRegionWidget; - root->addWidget(middleRegion, 1); - - auto *statusBar = new QFrame; - statusBar->setObjectName(QStringLiteral("customStatusBar")); - statusBar->setMinimumHeight(40); - auto *statusLayout = new QHBoxLayout(statusBar); - statusLayout->setContentsMargins(18, 0, 24, 0); - auto *attribution = new QLabel( - QStringLiteral( - "" - "© Volker Christian" - " & Codex | " - "CodexUI • " - "AISuite • " - "Powered by " - "SNode.C") - .arg(QString::fromLatin1(UiStyle::strongText), - QString::fromLatin1(UiStyle::placeholder))); - attribution->setObjectName(QStringLiteral("statusAttribution")); - attribution->setProperty("kind", "meta"); - attribution->setTextFormat(Qt::RichText); - attribution->setOpenExternalLinks(true); - attribution->setTextInteractionFlags(Qt::LinksAccessibleByMouse | - Qt::LinksAccessibleByKeyboard); - attribution->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - statusLayout->addWidget(attribution); - statusLayout->addStretch(); - overallTokens = new UiStyle::TokenUsageLabel; - overallTokens->setObjectName(QStringLiteral("overallTokenUsage")); - statusLayout->addWidget(overallTokens); - overallTokens->ensurePolished(); - statusLayout->setSpacing(overallTokens->fontMetrics().horizontalAdvance(QLatin1Char(' '))); - auto *statusCaption = makeLabel(QStringLiteral("| Status"), "meta"); - statusCaption->setObjectName(QStringLiteral("globalStatusCaption")); - statusCaption->setWordWrap(false); - statusCaption->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - statusLayout->addWidget(statusCaption); - globalStatusDot = new QFrame; - globalStatusDot->setFixedSize(10, 10); - globalStatusDot->setProperty("kind", "statusDot"); - globalStatusDot->setObjectName(QStringLiteral("shellGlobalStatusDot")); - statusLayout->addWidget(globalStatusDot); - globalStatusLabel = - makeStatusLabel(QStringLiteral("Offline"), - QStringLiteral("globalStatusLabel"), 160, "settingLabel"); - statusLayout->addWidget(globalStatusLabel); - root->addWidget(statusBar); -} - -void ShellWidget::Impl::connectUi() { - middle::ThreadPane::Actions threadActions; - threadActions.newThread = [this] { beginNewThreadDialog(); }; - threadActions.newGroupedThread = [this](std::string project, std::string section) { - beginNewThreadDialog(std::move(project), std::move(section)); - }; - threadActions.browserChanged = [this] { - pendingThreadPane = true; - schedulePaneCommit(); - }; - threadActions.refreshGroups = [this] { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::RefreshThreadGroups, {}, {}, {}, {}}, - QStringLiteral("Groups could not be refreshed; try again."))); - }; - threadActions.browse = [this](nlohmann::json parameters) { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::LoadThreadGroup, - objectFromJson(parameters), - {}, - {}, - {}}, - QStringLiteral("The thread page could not be requested; try again."))); - }; - threadActions.manage = [this](nodegraph::RuntimeActionKind kind, - nlohmann::json parameters) { - static_cast(sendRuntimeAction( - {kind, objectFromJson(parameters), {}, {}, {}}, - QStringLiteral("The group change was not admitted; try again."))); - }; - threadActions.loadMore = [this] { - static_cast(sendRuntimeAction( - {nodegraph::RuntimeActionKind::LoadMoreThreads, {}, {}, {}, {}}, - QStringLiteral("More threads could not be requested; try again."))); - }; - threadActions.hide = [this] { middleRegion->showSidebar(false); }; - const auto showTiming = [this](nodegraph::NodeRef target) { - middleRegion->showInspector(true); - middleRegion->inspector().showTiming(std::move(target)); - }; - threadActions.timing = showTiming; - middleRegion->conversation().setTimingAction(showTiming); - middleRegion->conversation().setAnswerAction([this](nodegraph::NodeRef item) { - PendingRequestDescriptor request; - request.kind = PendingRequestKind::UserInput; - request.method = "agentMessage"; - std::string sourceId; - const auto source = [&] { - nlohmann::json questions = nullptr; - auto read = session.nodeGraph().tryRead(); - if (read && read->live(item) && read->parent(read->parent(item)) == boundGraphThread) { - const auto state = read->state(item); - if (exactStringFromValue(valueMember(*state, "type")) == "agentMessage" && - exactStringFromValue(valueMember(*state, "delivery")) == "async" && valueMember(*state, "questions")) { - questions = PendingRequestPolicy::asyncQuestionRequest(jsonFromValue(*valueMember(*state, "questions"))); - sourceId = nodegraph::protocolCanonicalId(*state, item); - } - } - return questions; - }; - request.raw = source(); - const auto thread = boundGraphThread; - if (!request.raw.is_null()) { - request.availability = PendingRequestAvailability::Actionable; - static_cast(PendingRequestDialog::present(request, owner, nullptr, {}, [&](const PendingRequestSubmission& submission) { - const auto answer = PendingRequestPolicy::asyncQuestionAnswer(request.raw, submission, sourceId); - const bool current = thread == boundGraphThread && source() == request.raw; - const bool admitted = current && renderedChrome && renderedChrome->canControl && answer && submitPrompt(text(*answer), {}); - return admitted; - })); - acknowledgeDetachedTargets(); - } - }); - middleRegion->conversation().setTurnMenuAction([this](nodegraph::NodeRef item, QPoint position) { - showTurnMenu(std::move(item), position); - }); - threadActions.select = [this](const nodegraph::NodeRef &thread) { - selectGraphThread(thread, ThreadSelectionOrigin::User); - }; - threadActions.reload = [this](const nodegraph::NodeRef& thread) { - if (!thread) - return; - nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Reload, {}, {}, {}, {}}; - static_cast(sendNodeAction(std::move(action), QStringLiteral("Thread reload was not admitted; try again."))); - }; - threadActions.changeWorkspace = [this](const nodegraph::NodeRef& thread) { - changeWorkspaceDialog(thread); - }; - threadActions.rename = [this](const nodegraph::NodeRef &thread) { - if (thread) - renameThreadDialog(thread); - }; - threadActions.fork = [this](const nodegraph::NodeRef &thread) { - if (!thread) - return; - const std::optional draft = suggestedForkDraft(thread); - if (!draft) { - showNotice(QStringLiteral("Thread state is busy; try Quick fork again.")); - return; - } - forkThread(thread, *draft, false); - }; - threadActions.forkWithOptions = [this](const nodegraph::NodeRef &thread) { - if (thread) - beginForkThreadDialog(thread); - }; - threadActions.toggleArchive = [this](const nodegraph::NodeRef &thread) { - if (!thread) - return; - bool archived = false; - if (auto read = session.nodeGraph().tryRead(); read && read->live(thread)) - archived = boolFromValue(valueMember(*read->state(thread), "archived")); - else { - showNotice( - QStringLiteral("Thread state is busy; no archive action was sent.")); - return; - } - nodegraph::NodeAction action{thread, - archived ? nodegraph::NodeActionKind::Unarchive - : nodegraph::NodeActionKind::Archive, - {}, {}, {}, {}}; - static_cast(sendNodeAction( - std::move(action), - QStringLiteral("Archive request was not admitted; try again."))); - }; - threadActions.remove = [this](const nodegraph::NodeRef &thread) { - if (thread) - confirmDeleteThread(thread); - }; - const FileSelectionDialog::Access filesystem = [this] { - return session.filesystemAccess(); - }; - threadActions.filesystem = filesystem; - middleRegion->threads().setActions(std::move(threadActions)); - - middle::ComposerPane::Actions composerActions; - composerActions.filesystem = filesystem; - composerActions.workspace = [this] { - const auto row = uiAdapter.threadRow(boundGraphThread); - return row ? text(row->cwd) : newThreadDraft ? newThreadDraft->workspace : QString{}; - }; - composerActions.submit = [this](QString prompt, - std::vector attachments) { - return submitPrompt(std::move(prompt), std::move(attachments)); - }; - composerActions.stop = [this] { - nodegraph::NodeRef turn = activeTurn(); - if (!turn) { - showNotice(QStringLiteral("No active turn is available to stop.")); - return; - } - nodegraph::NodeAction action{turn, - nodegraph::NodeActionKind::InterruptTurn, - {}, {}, {}, {}}; - static_cast(sendNodeAction( - std::move(action), - QStringLiteral("Stop request was not admitted; try again."))); - }; - composerActions.attachmentError = [this](QString error) { - showNotice(std::move(error)); - }; - composerActions.accept = [this] { - respondToRenderedPending(&Impl::acceptPending); - }; - composerActions.review = [this] { - respondToRenderedPending(&Impl::reviewPending); - }; - composerActions.deny = [this] { - respondToRenderedPending(&Impl::rejectPending); - }; - middleRegion->composer().setActions(std::move(composerActions)); - - middleRegion->conversation().setLoadMoreAction([this](bool throughFirst) { - if (boundGraphThread && !pendingConversation && !middleRegion->conversation().structuralStagingActive()) { - const auto info = uiAdapter.conversationInfo(boundGraphThread); - if (!info) { - showNotice(QStringLiteral("Conversation state is busy; no history request was sent.")); - } else if (!info->historyRequestPending && info->providerHasMore) { - nodegraph::NodeAction action{ - boundGraphThread, nodegraph::NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", throughFirst}}, {}}; - static_cast(sendNodeAction(std::move(action), QStringLiteral("History request was not admitted; try again."))); - } - } - }); - middleRegion->conversation().setPromptMaterializedAction( - [this](nodegraph::NodeRef localPrompt) { - nodegraph::NodeAction action{ - std::move(localPrompt), - nodegraph::NodeActionKind::PromptMaterialized, - {}, {}, {}, {}}; - return sendNodeAction(std::move(action), {}); - }); - middleRegion->conversation().setPromptRecoveryAction( - [this](nodegraph::NodeRef prompt) { recoverPrompt(prompt); }); - middleRegion->conversation().setReconciliationFinishedAction( - [this](const std::string &threadId, - middle::ConversationView::ReconciliationResult result, - bool selectionCommitted) { - if (!boundGraphThread || boundGraphThread->id().canonical != threadId) - return; - if (result == - middle::ConversationView::ReconciliationResult::Rejected) { - showNotice(QStringLiteral( - "Conversation data could not be presented; select Reload to " - "retry.")); - if (pendingConversation || !pendingConversationItems.empty()) - schedulePaneCommit(true); - return; - } - if (pendingConversation || !pendingConversationItems.empty()) - schedulePaneCommit(true); - if (!selectionCommitted) - return; - renderedChrome.reset(); - pendingInspector = true; - pendingChrome = true; - schedulePaneCommit(); - }); - middleRegion->inspector().setRequestActions( - [this](const nodegraph::NodeRef &target) { reviewPending(target); }, - [this](const nodegraph::NodeRef &target) { acceptPending(target); }, - [this](const nodegraph::NodeRef &target) { rejectPending(target); }); - middleRegion->inspector().setRefreshRequestedAction([this] { - pendingInspector = true; - schedulePaneCommit(); - }); - middleRegion->setPaneVisibilityAction( - [this](bool sidebarVisible, bool inspectorVisible) { - restoreSidebarButton->setVisible(!sidebarVisible); - restoreInspectorButton->setVisible(!inspectorVisible); - }); - - connect(restoreSidebarButton, &QPushButton::clicked, owner, - [this] { middleRegion->showSidebar(true); }); - connect(restoreInspectorButton, &QPushButton::clicked, owner, [this] { - middleRegion->showInspector(true); - pendingInspector = true; - schedulePaneCommit(); - }); - connect(requestButton, &QPushButton::clicked, owner, [this] { - middleRegion->showInspector(true); - middleRegion->inspector().tabs()->setCurrentIndex(3); - pendingInspector = true; - schedulePaneCommit(); - }); - connect(controllerButton, &QPushButton::clicked, owner, [this] { - bool controller = false; - auto read = session.nodeGraph().tryRead(); - if (!read) { - showNotice(QStringLiteral( - "Connection state is busy; no controller request was sent.")); - return; + reconnectAction = connectionMenu->addAction(QStringLiteral("Reconnect"), owner, [this] { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::Reconnect, {}, {}, {}, {}}, + QStringLiteral("Reconnect request was not admitted; try again."))); + }); + connectionButton->setMenu(connectionMenu); + topLayout->addWidget(connectionButton); + root->addWidget(top); + + middleRegion = new middle::MiddleRegionWidget; + root->addWidget(middleRegion, 1); + + auto* statusBar = new QFrame; + statusBar->setObjectName(QStringLiteral("customStatusBar")); + statusBar->setMinimumHeight(40); + auto* statusLayout = new QHBoxLayout(statusBar); + statusLayout->setContentsMargins(18, 0, 24, 0); + auto* attribution = new QLabel(QStringLiteral("" + "© Volker Christian" + " & Codex | " + "CodexUI • " + "AISuite • " + "Powered by " + "SNode.C") + .arg(QString::fromLatin1(UiStyle::strongText), QString::fromLatin1(UiStyle::placeholder))); + attribution->setObjectName(QStringLiteral("statusAttribution")); + attribution->setProperty("kind", "meta"); + attribution->setTextFormat(Qt::RichText); + attribution->setOpenExternalLinks(true); + attribution->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + attribution->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + statusLayout->addWidget(attribution); + statusLayout->addStretch(); + overallTokens = new UiStyle::TokenUsageLabel; + overallTokens->setObjectName(QStringLiteral("overallTokenUsage")); + statusLayout->addWidget(overallTokens); + overallTokens->ensurePolished(); + statusLayout->setSpacing(overallTokens->fontMetrics().horizontalAdvance(QLatin1Char(' '))); + auto* statusCaption = makeLabel(QStringLiteral("| Status"), "meta"); + statusCaption->setObjectName(QStringLiteral("globalStatusCaption")); + statusCaption->setWordWrap(false); + statusCaption->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + statusLayout->addWidget(statusCaption); + globalStatusDot = new QFrame; + globalStatusDot->setFixedSize(10, 10); + globalStatusDot->setProperty("kind", "statusDot"); + globalStatusDot->setObjectName(QStringLiteral("shellGlobalStatusDot")); + statusLayout->addWidget(globalStatusDot); + globalStatusLabel = makeStatusLabel(QStringLiteral("Offline"), QStringLiteral("globalStatusLabel"), 160, "settingLabel"); + statusLayout->addWidget(globalStatusLabel); + root->addWidget(statusBar); } - const nodegraph::NodeRef connection = - read->find({nodegraph::NodeKind::Connection, "connection"}); - if (connection) - controller = exactStringFromValue(valueMember(*read->state(connection), - "role")) == "controller"; - read.reset(); - static_cast(sendRuntimeAction( - {controller ? nodegraph::RuntimeActionKind::ReleaseController - : nodegraph::RuntimeActionKind::ClaimController, - {}, {}, {}, {}}, - QStringLiteral("Controller request was not admitted; try again."))); - }); - qApp->installEventFilter(owner); -} - -void ShellWidget::Impl::showNotice(QString message, bool error) { - middleRegion->showNotice(std::move(message), error); -} - -void ShellWidget::Impl::scheduleGraphBinding(bool immediate) { - if (graphBindingScheduled) - return; - graphBindingScheduled = true; - const auto token = alive; - const int delay = immediate ? 0 : GraphRetryDelayMilliseconds; - QTimer::singleShot(delay, owner, [this, token] { - if (!token->load(std::memory_order_acquire)) - return; - graphBindingScheduled = false; - runGraphBinding(); - }); -} - -void ShellWidget::Impl::runGraphBinding() { - if (!selectedGraphThreadId.empty()) { - auto read = session.nodeGraph().tryRead(); - if (!read) { - scheduleGraphBinding(false); - } else { - const auto selectedThread = read->find({nodegraph::NodeKind::Thread, selectedGraphThreadId}); - read.reset(); - if (selectedThread && selectedThread != boundGraphThread) { - bindGraphPanes(selectedThread); - nodegraph::NodeAction action{selectedThread, nodegraph::NodeActionKind::Hydrate, {}, {}, {}, {}}; + + void ShellWidget::Impl::connectUi() { + middle::ThreadPane::Actions threadActions; + threadActions.newThread = [this] { + beginNewThreadDialog(); + }; + threadActions.newGroupedThread = [this](std::string project, std::string section) { + beginNewThreadDialog(std::move(project), std::move(section)); + }; + threadActions.browserChanged = [this] { + pendingThreadPane = true; + schedulePaneCommit(); + }; + threadActions.refreshGroups = [this] { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::RefreshThreadGroups, {}, {}, {}, {}}, + QStringLiteral("Groups could not be refreshed; try again."))); + }; + threadActions.browse = [this](nlohmann::json parameters) { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::LoadThreadGroup, objectFromJson(parameters), {}, {}, {}}, + QStringLiteral("The thread page could not be requested; try again."))); + }; + threadActions.manage = [this](nodegraph::RuntimeActionKind kind, nlohmann::json parameters) { + static_cast(sendRuntimeAction({kind, objectFromJson(parameters), {}, {}, {}}, + QStringLiteral("The group change was not admitted; try again."))); + }; + threadActions.loadMore = [this] { + static_cast(sendRuntimeAction({nodegraph::RuntimeActionKind::LoadMoreThreads, {}, {}, {}, {}}, + QStringLiteral("More threads could not be requested; try again."))); + }; + threadActions.hide = [this] { + middleRegion->showSidebar(false); + }; + const auto showTiming = [this](nodegraph::NodeRef target) { + middleRegion->showInspector(true); + middleRegion->inspector().showTiming(std::move(target)); + }; + threadActions.timing = showTiming; + middleRegion->conversation().setTimingAction(showTiming); + middleRegion->conversation().setAnswerAction([this](nodegraph::NodeRef item) { + PendingRequestDescriptor request; + request.kind = PendingRequestKind::UserInput; + request.method = "agentMessage"; + std::string sourceId; + const auto source = [&] { + nlohmann::json questions = nullptr; + auto read = session.nodeGraph().tryRead(); + if (read && read->live(item) && read->parent(read->parent(item)) == boundGraphThread) { + const auto state = read->state(item); + if (exactStringFromValue(valueMember(*state, "type")) == "agentMessage" && + exactStringFromValue(valueMember(*state, "delivery")) == "async" && valueMember(*state, "questions")) { + questions = PendingRequestPolicy::asyncQuestionRequest(jsonFromValue(*valueMember(*state, "questions"))); + sourceId = nodegraph::protocolCanonicalId(*state, item); + } + } + return questions; + }; + request.raw = source(); + const auto thread = boundGraphThread; + if (!request.raw.is_null()) { + request.availability = PendingRequestAvailability::Actionable; static_cast( - sendNodeAction(std::move(action), QStringLiteral("Thread loading was not admitted; select Reload to retry."))); + PendingRequestDialog::present(request, owner, nullptr, {}, [&](const PendingRequestSubmission& submission) { + const auto answer = PendingRequestPolicy::asyncQuestionAnswer(request.raw, submission, sourceId); + const bool current = thread == boundGraphThread && source() == request.raw; + const bool admitted = + current && renderedChrome && renderedChrome->canControl && answer && submitPrompt(text(*answer), {}); + return admitted; + })); + acknowledgeDetachedTargets(); } - } - } -} - -void ShellWidget::Impl::bindGraphPanes(nodegraph::NodeRef selectedThread) { - if (graphPanesBound && boundGraphThread == selectedThread) { - render(); - return; - } - if (selectedThread && boundGraphThread != selectedThread) - middleRegion->conversation().beginThreadSelection( - selectedThread->id().canonical, selectedThread->incarnation()); - pendingConversationAuthorityReplacement = false; - pendingStructuralConversationDelta.reset(); - if (boundGraphThread != selectedThread) { - session.acknowledgeInspection(selectedThread); - } - boundGraphThread = std::move(selectedThread); - middleRegion->inspector().clearTimingTarget(); - routedThreadRevision = 0; - routedConversationRevision = 0; - graphPanesBound = true; - pendingConversation = false; - clearPendingConversationItems(); - std::uint64_t threadRevision = 0; - if (auto threads = threadSnapshot(&threadRevision)) { - middleRegion->threads().refresh(*threads); - routedThreadRevision = threadRevision; - } - const bool conversationReady = refreshConversation(); - pendingInspector = false; - const bool inspectorReady = refreshInspector(); - std::optional requests = pendingRequestSummary(); - pendingChrome = !requests; - if (requests) - render(&*requests); - // The immediate atomic bind already represents the newest graph state. - // Any frame-coalesced work queued for the previous selection is obsolete. - pendingThreadPane = false; - pendingThreadRows.clear(); - if (!conversationReady) { - pendingConversation = true; - pendingConversationAuthorityReplacement = true; - } - pendingInspector |= !inspectorReady; - if (pendingConversation || pendingInspector || pendingChrome) - schedulePaneCommit(); -} - -bool ShellWidget::Impl::refreshConversation() { - if (!boundGraphThread) { - static_cast(middleRegion->conversation().reconcile({})); - routedConversationRevision = 0; - return true; - } - - const auto info = uiAdapter.conversationInfo(boundGraphThread); - if (!info) - return false; - const std::string &threadId = boundGraphThread->id().canonical; - middleRegion->conversation().setHistoryRequestPending( - threadId, info->historyRequestPending); - - if (!info->readyForDisplay) { - if (!info->hydrationFailed) { - middleRegion->conversation().beginThreadSelection( - threadId, boundGraphThread->incarnation()); - return true; - } - middleRegion->conversation().setEmptyMessage( - QStringLiteral("Thread loading failed. Select Reload to retry.")); - middle::ConversationSnapshot failed; - failed.threadId = threadId; - static_cast(middleRegion->conversation().reconcile(failed)); - return true; - } - - middleRegion->conversation().setEmptyMessage( - QStringLiteral("No materialized activity.")); - requestConversationSnapshot(); - return true; -} - -void ShellWidget::Impl::requestConversationSnapshot() { - requestConversationProjection(true); -} - -void ShellWidget::Impl::requestConversationRescan() { - const bool needsSnapshot = - !boundGraphThread || - middleRegion->conversation().presentedThreadId() != - boundGraphThread->id().canonical || - routedConversationRevision == 0; - requestConversationProjection(needsSnapshot); -} - -void ShellWidget::Impl::requestConversationProjection(bool fullSnapshot) { - conversationProjectionRequested = true; - conversationFullProjectionRequested |= fullSnapshot; - ++conversationProjectionScheduleGeneration; - if (conversationProjectionInFlight) - return; - conversationProjectionStartScheduled = true; - const auto token = alive; - const std::uint64_t generation = conversationProjectionScheduleGeneration; - QTimer::singleShot(fullSnapshot ? 0 : ConversationProjectionQuietMilliseconds, - Qt::PreciseTimer, owner, [this, token, generation] { - if (!token->load(std::memory_order_acquire)) - return; - if (generation != conversationProjectionScheduleGeneration) - return; - conversationProjectionStartScheduled = false; - startConversationSnapshot(); - }); -} - -void ShellWidget::Impl::startConversationSnapshot() { - if (!boundGraphThread) - return; - if (conversationProjectionInFlight) { - conversationProjectionRequested = true; - return; - } - const auto info = uiAdapter.conversationInfo(boundGraphThread); - if (!info || (info->historyRequestPending && !info->readyForDisplay)) { - if (info) - middleRegion->conversation().setHistoryRequestPending(boundGraphThread->id().canonical, info->historyRequestPending); - // A failed tryRead has no completion event to wake the pending projection. - requestConversationProjection(false); - return; - } - middleRegion->conversation().setHistoryRequestPending(boundGraphThread->id().canonical, info->historyRequestPending); - middleRegion->conversation().setProviderHasMore( - boundGraphThread->id().canonical, info->providerHasMore); - conversationProjectionInFlight = true; - conversationProjectionRequested = false; - const bool fullSnapshot = conversationFullProjectionRequested; - conversationFullProjectionRequested = false; - conversationFullProjectionInFlight = fullSnapshot; - const std::uint64_t afterRevision = routedConversationRevision; - const nodegraph::NodeRef requestedThread = boundGraphThread; - const ui::NodeGraphUiAdapter adapter = uiAdapter; - const auto token = alive; - projectionPool.start( - [this, requestedThread, adapter, token, fullSnapshot, afterRevision] { - std::uint64_t graphRevision = 0; - auto snapshot = - fullSnapshot - ? adapter.conversation(requestedThread, &graphRevision) - : std::optional{}; - auto delta = - fullSnapshot - ? std::optional{} - : adapter.conversationDeltaSince( - requestedThread, afterRevision, &graphRevision); - QMetaObject::invokeMethod( - qApp, - [this, requestedThread, graphRevision, - snapshot = std::move(snapshot), delta = std::move(delta), - fullSnapshot, token]() mutable { - if (!token->load(std::memory_order_acquire)) + }); + middleRegion->conversation().setTurnMenuAction([this](nodegraph::NodeRef item, QPoint position) { + showTurnMenu(std::move(item), position); + }); + threadActions.select = [this](const nodegraph::NodeRef& thread) { + selectGraphThread(thread, ThreadSelectionOrigin::User); + }; + threadActions.reload = [this](const nodegraph::NodeRef& thread) { + if (!thread) return; - conversationProjectionInFlight = false; - conversationFullProjectionInFlight = false; - if (requestedThread != boundGraphThread) { - if (conversationProjectionRequested) - requestConversationSnapshot(); + nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Reload, {}, {}, {}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("Thread reload was not admitted; try again."))); + }; + threadActions.changeWorkspace = [this](const nodegraph::NodeRef& thread) { + changeWorkspaceDialog(thread); + }; + threadActions.rename = [this](const nodegraph::NodeRef& thread) { + if (thread) + renameThreadDialog(thread); + }; + threadActions.fork = [this](const nodegraph::NodeRef& thread) { + if (!thread) return; - } - const auto currentInfo = - uiAdapter.conversationInfo(requestedThread); - if ((fullSnapshot && !snapshot) || (!fullSnapshot && !delta) || !currentInfo || - (currentInfo->historyRequestPending && !currentInfo->readyForDisplay)) { - conversationProjectionRequested = true; - conversationFullProjectionRequested |= fullSnapshot; - QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this] { - requestConversationProjection(false); - }); - return; - } - if (conversationProjectionRequested) { - requestConversationProjection(fullSnapshot); - return; - } - - // A complete snapshot initializes or replaces authority. A - // rescan uses graph revision stamps to project only changed - // rows, keeping the full graph scan off the QWidget thread. - pendingConversation = false; - pendingConversationAuthorityReplacement = false; - pendingStructuralConversationDelta.reset(); - clearPendingConversationItems(); - if (fullSnapshot) { - const auto disposition = - middleRegion->conversation().reconcileStaged( - std::move(*snapshot)); - if (disposition != middle::ConversationView:: - SnapshotDisposition::Retryable) { - routedConversationRevision = graphRevision; - } else { - conversationProjectionRequested = true; - conversationFullProjectionRequested = true; + const std::optional draft = suggestedForkDraft(thread); + if (!draft) { + showNotice(QStringLiteral("Thread state is busy; try Quick fork again.")); + return; + } + forkThread(thread, *draft, false); + }; + threadActions.forkWithOptions = [this](const nodegraph::NodeRef& thread) { + if (thread) + beginForkThreadDialog(thread); + }; + threadActions.toggleArchive = [this](const nodegraph::NodeRef& thread) { + if (!thread) + return; + bool archived = false; + if (auto read = session.nodeGraph().tryRead(); read && read->live(thread)) + archived = boolFromValue(valueMember(*read->state(thread), "archived")); + else { + showNotice(QStringLiteral("Thread state is busy; no archive action was sent.")); + return; + } + nodegraph::NodeAction action{ + thread, archived ? nodegraph::NodeActionKind::Unarchive : nodegraph::NodeActionKind::Archive, {}, {}, {}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("Archive request was not admitted; try again."))); + }; + threadActions.remove = [this](const nodegraph::NodeRef& thread) { + if (thread) + confirmDeleteThread(thread); + }; + const FileSelectionDialog::Access filesystem = [this] { + return session.filesystemAccess(); + }; + threadActions.filesystem = filesystem; + middleRegion->threads().setActions(std::move(threadActions)); + + middle::ComposerPane::Actions composerActions; + composerActions.filesystem = filesystem; + composerActions.workspace = [this] { + const auto row = uiAdapter.threadRow(boundGraphThread); + return row ? text(row->cwd) : newThreadDraft ? newThreadDraft->workspace : QString{}; + }; + composerActions.submit = [this](QString prompt, std::vector attachments) { + return submitPrompt(std::move(prompt), std::move(attachments)); + }; + composerActions.stop = [this] { + nodegraph::NodeRef turn = activeTurn(); + if (!turn) { + showNotice(QStringLiteral("No active turn is available to stop.")); + return; + } + nodegraph::NodeAction action{turn, nodegraph::NodeActionKind::InterruptTurn, {}, {}, {}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("Stop request was not admitted; try again."))); + }; + composerActions.attachmentError = [this](QString error) { + showNotice(std::move(error)); + }; + composerActions.accept = [this] { + respondToRenderedPending(&Impl::acceptPending); + }; + composerActions.review = [this] { + respondToRenderedPending(&Impl::reviewPending); + }; + composerActions.deny = [this] { + respondToRenderedPending(&Impl::rejectPending); + }; + middleRegion->composer().setActions(std::move(composerActions)); + + middleRegion->conversation().setLoadMoreAction([this](bool throughFirst) { + if (boundGraphThread && !pendingConversation && !middleRegion->conversation().structuralStagingActive()) { + const auto info = uiAdapter.conversationInfo(boundGraphThread); + if (!info) { + showNotice(QStringLiteral("Conversation state is busy; no history request was sent.")); + } else if (!info->historyRequestPending && info->providerHasMore) { + nodegraph::NodeAction action{ + boundGraphThread, nodegraph::NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", throughFirst}}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("History request was not admitted; try again."))); } - } else { - middleRegion->conversation().setProviderHasMore( - requestedThread->id().canonical, delta->providerHasMore); - if (!delta->rows.empty() || !delta->removals.empty()) { - pendingStructuralConversationDelta = std::move(*delta); - pendingConversation = true; - schedulePaneCommit(); + } + }); + middleRegion->conversation().setPromptMaterializedAction([this](nodegraph::NodeRef localPrompt) { + nodegraph::NodeAction action{std::move(localPrompt), nodegraph::NodeActionKind::PromptMaterialized, {}, {}, {}, {}}; + return sendNodeAction(std::move(action), {}); + }); + middleRegion->conversation().setPromptRecoveryAction([this](nodegraph::NodeRef prompt) { + recoverPrompt(prompt); + }); + middleRegion->conversation().setReconciliationFinishedAction( + [this](const std::string& threadId, middle::ConversationView::ReconciliationResult result, bool selectionCommitted) { + if (!boundGraphThread || boundGraphThread->id().canonical != threadId) + return; + if (result == middle::ConversationView::ReconciliationResult::Rejected) { + showNotice(QStringLiteral("Conversation data could not be presented; select Reload to " + "retry.")); + if (pendingConversation || !pendingConversationItems.empty()) + schedulePaneCommit(true); + return; } - } - if (conversationProjectionRequested) - requestConversationProjection(false); + if (pendingConversation || !pendingConversationItems.empty()) + schedulePaneCommit(true); + if (!selectionCommitted) + return; + renderedChrome.reset(); + pendingInspector = true; + pendingChrome = true; + schedulePaneCommit(); + }); + middleRegion->inspector().setRequestActions( + [this](const nodegraph::NodeRef& target) { + reviewPending(target); }, - Qt::QueuedConnection); - }); -} - -bool ShellWidget::Impl::refreshInspector() { - middle::InspectorPane &pane = middleRegion->inspector(); - const std::optional projection = - pane.currentProjection(); - if (!projection) - return true; - if (*projection == ui::InspectorProjection::Requests) { - ui::InspectorSnapshot snapshot; - snapshot.threadIncarnation = - boundGraphThread ? boundGraphThread->incarnation() : 0; - auto requests = pendingRequestPage(pane.rowRequest(*projection)); - if (!requests) - return false; - snapshot.requests = std::move(*requests); - pane.refresh(snapshot, *projection); - return true; - } - nodegraph::NodeRef inspectorThread = boundGraphThread; - if (inspectorThread) { - const auto info = uiAdapter.conversationInfo(inspectorThread); - if (!info) - return false; - const std::string &presentedThreadId = - middleRegion->conversation().presentedThreadId(); - if (!presentedThreadId.empty() && - presentedThreadId != inspectorThread->id().canonical && - !info->hydrationFailed) - return true; - if (!info->readyForDisplay) - inspectorThread.reset(); - } - requestInspectorProjection(inspectorThread, *projection, - pane.rowRequest(*projection)); - return true; -} - -void ShellWidget::Impl::requestInspectorProjection( - nodegraph::NodeRef thread, ui::InspectorProjection projection, - ui::InspectorRowRequest request) { - requestedInspectorThread = std::move(thread); - requestedInspectorProjection = projection; - requestedInspectorRows = std::move(request); - inspectorProjectionRequested = true; - ++inspectorProjectionGeneration; - if (!inspectorProjectionInFlight) - startInspectorProjection(); -} - -void ShellWidget::Impl::startInspectorProjection() { - if (!inspectorProjectionRequested || inspectorProjectionInFlight) - return; - inspectorProjectionRequested = false; - inspectorProjectionInFlight = true; - const std::uint64_t generation = inspectorProjectionGeneration; - const nodegraph::NodeRef thread = requestedInspectorThread; - const ui::InspectorProjection projection = requestedInspectorProjection; - const ui::InspectorRowRequest request = requestedInspectorRows; - const ui::NodeGraphUiAdapter adapter = uiAdapter; - const auto token = alive; - projectionPool.start( - [this, thread, projection, request, adapter, token, generation] { - auto snapshot = adapter.inspector(thread, projection, request); - if (snapshot) - middle::InspectorPane::prepareMarkdown(*snapshot); - QMetaObject::invokeMethod( - qApp, - [this, thread, projection, snapshot = std::move(snapshot), token, - generation]() mutable { - if (!token->load(std::memory_order_acquire)) - return; - inspectorProjectionInFlight = false; - middle::InspectorPane &pane = middleRegion->inspector(); - const std::optional currentProjection = pane.currentProjection(); - const bool current = generation == inspectorProjectionGeneration && - thread == boundGraphThread && - currentProjection && - *currentProjection == projection; - if (current && snapshot) { - pane.refresh(*snapshot, projection); - } else if (current && !snapshot) { - inspectorProjectionRequested = true; - } - if (inspectorProjectionRequested) - startInspectorProjection(); + [this](const nodegraph::NodeRef& target) { + acceptPending(target); }, - Qt::QueuedConnection); - }); -} - -void ShellWidget::Impl::queueConversationRoute( - const ui::NodeGraphUiAdapter::ConversationRoute &route) { - if (route.historyRequestPending && boundGraphThread) - middleRegion->conversation().setHistoryRequestPending( - boundGraphThread->id().canonical, *route.historyRequestPending); - if (route.providerHasMore && boundGraphThread) - middleRegion->conversation().setProviderHasMore( - boundGraphThread->id().canonical, *route.providerHasMore); - if (route.historyRequestPending && !*route.historyRequestPending && - conversationProjectionRequested) - requestConversationSnapshot(); - if (route.authorityReplacement) { - pendingConversation = false; - pendingConversationAuthorityReplacement = false; - pendingStructuralConversationDelta.reset(); - clearPendingConversationItems(); - requestConversationSnapshot(); - return; - } - const bool snapshotNeedsFull = - boundGraphThread && - (middleRegion->conversation().presentedThreadId() != - boundGraphThread->id().canonical || - middleRegion->conversation().structuralStagingActive() || - conversationFullProjectionInFlight || - conversationFullProjectionRequested); - const bool snapshotOwnsStructure = - boundGraphThread && - (snapshotNeedsFull || - conversationProjectionRequested || conversationProjectionInFlight || - conversationProjectionStartScheduled); - if (snapshotOwnsStructure && route.affected && route.structural) { - pendingStructuralConversationDelta.reset(); - clearPendingConversationItems(); - requestConversationProjection(snapshotNeedsFull); - return; - } - routedConversationRevision = - std::max(routedConversationRevision, route.graphRevision); - if (route.structural && !route.items.empty()) { - pendingConversation = true; - pendingConversationAuthorityReplacement = false; - } - if (route.affected && !pendingConversationAuthorityReplacement) { - for (const nodegraph::NodeRef &item : route.items) { - if (item && pendingConversationItemKeys.insert(item.get()).second) - pendingConversationItems.push_back(item); + [this](const nodegraph::NodeRef& target) { + rejectPending(target); + }); + middleRegion->inspector().setRefreshRequestedAction([this] { + pendingInspector = true; + schedulePaneCommit(); + }); + middleRegion->setPaneVisibilityAction([this](bool sidebarVisible, bool inspectorVisible) { + restoreSidebarButton->setVisible(!sidebarVisible); + restoreInspectorButton->setVisible(!inspectorVisible); + }); + + connect(restoreSidebarButton, &QPushButton::clicked, owner, [this] { + middleRegion->showSidebar(true); + }); + connect(restoreInspectorButton, &QPushButton::clicked, owner, [this] { + middleRegion->showInspector(true); + pendingInspector = true; + schedulePaneCommit(); + }); + connect(requestButton, &QPushButton::clicked, owner, [this] { + middleRegion->showInspector(true); + middleRegion->inspector().tabs()->setCurrentIndex(3); + pendingInspector = true; + schedulePaneCommit(); + }); + connect(controllerButton, &QPushButton::clicked, owner, [this] { + bool controller = false; + auto read = session.nodeGraph().tryRead(); + if (!read) { + showNotice(QStringLiteral("Connection state is busy; no controller request was sent.")); + return; + } + const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"}); + if (connection) + controller = exactStringFromValue(valueMember(*read->state(connection), "role")) == "controller"; + read.reset(); + static_cast(sendRuntimeAction( + {controller ? nodegraph::RuntimeActionKind::ReleaseController : nodegraph::RuntimeActionKind::ClaimController, + {}, + {}, + {}, + {}}, + QStringLiteral("Controller request was not admitted; try again."))); + }); + qApp->installEventFilter(owner); + } + + void ShellWidget::Impl::showNotice(QString message, bool error) { + middleRegion->showNotice(std::move(message), error); + } + + void ShellWidget::Impl::scheduleGraphBinding(bool immediate) { + if (graphBindingScheduled) + return; + graphBindingScheduled = true; + const auto token = alive; + const int delay = immediate ? 0 : GraphRetryDelayMilliseconds; + QTimer::singleShot(delay, owner, [this, token] { + if (!token->load(std::memory_order_acquire)) + return; + graphBindingScheduled = false; + runGraphBinding(); + }); + } + + void ShellWidget::Impl::runGraphBinding() { + if (!selectedGraphThreadId.empty()) { + auto read = session.nodeGraph().tryRead(); + if (!read) { + scheduleGraphBinding(false); + } else { + const auto selectedThread = read->find({nodegraph::NodeKind::Thread, selectedGraphThreadId}); + read.reset(); + if (selectedThread && selectedThread != boundGraphThread) { + bindGraphPanes(selectedThread); + nodegraph::NodeAction action{selectedThread, nodegraph::NodeActionKind::Hydrate, {}, {}, {}, {}}; + static_cast( + sendNodeAction(std::move(action), QStringLiteral("Thread loading was not admitted; select Reload to retry."))); + } + } + } } - } -} - -void ShellWidget::Impl::clearPendingConversationItems() { - pendingConversationItems.clear(); - pendingConversationItemKeys.clear(); -} - -void ShellWidget::Impl::popPendingConversationItem() { - pendingConversationItemKeys.erase(pendingConversationItems.front().get()); - pendingConversationItems.pop_front(); -} - -bool ShellWidget::Impl::uiRetainsTarget( - const nodegraph::NodeRef &target) const noexcept { - if (!target) - return false; - if (boundGraphThread == target || reviewedRequest == target || - retainedRenames.contains(target.get()) || - localPendingRequests.contains(target)) - return true; - if (std::ranges::find(pendingThreadRows, target) != pendingThreadRows.end() || - pendingConversationItemKeys.contains(target.get())) - return true; - if (pendingStructuralConversationDelta) { - const middle::ConversationDelta &delta = *pendingStructuralConversationDelta; - if (std::ranges::any_of(delta.presentations, [&target](const auto &card) { - return card.target == target; - }) || - std::ranges::any_of(delta.rows, [&target](const auto &row) { - return row.placement.card.target == target; - }) || - std::ranges::find(delta.removals, target) != delta.removals.end() || - std::ranges::any_of(delta.materializedPrompts, - [&target](const auto &prompt) { - return prompt.prompt == target; - })) - return true; - } - return middleRegion->threads().retainsTarget(target) || - middleRegion->conversation().retainsTarget(target) || - middleRegion->inspector().retainsTarget(target); -} - -void ShellWidget::Impl::acknowledgeDetachedTargets() { - std::vector detached; - for (auto iterator = pendingUiDetachments.begin(); - iterator != pendingUiDetachments.end();) { - if (uiRetainsTarget(iterator->second)) { - ++iterator; - continue; + + void ShellWidget::Impl::bindGraphPanes(nodegraph::NodeRef selectedThread) { + if (graphPanesBound && boundGraphThread == selectedThread) { + render(); + return; + } + if (selectedThread && boundGraphThread != selectedThread) + middleRegion->conversation().beginThreadSelection(selectedThread->id().canonical, selectedThread->incarnation()); + pendingConversationAuthorityReplacement = false; + pendingStructuralConversationDelta.reset(); + if (boundGraphThread != selectedThread) { + session.acknowledgeInspection(selectedThread); + } + boundGraphThread = std::move(selectedThread); + middleRegion->inspector().clearTimingTarget(); + routedThreadRevision = 0; + routedConversationRevision = 0; + graphPanesBound = true; + pendingConversation = false; + clearPendingConversationItems(); + std::uint64_t threadRevision = 0; + if (auto threads = threadSnapshot(&threadRevision)) { + middleRegion->threads().refresh(*threads); + routedThreadRevision = threadRevision; + } + const bool conversationReady = refreshConversation(); + pendingInspector = false; + const bool inspectorReady = refreshInspector(); + std::optional requests = pendingRequestSummary(); + pendingChrome = !requests; + if (requests) + render(&*requests); + // The immediate atomic bind already represents the newest graph state. + // Any frame-coalesced work queued for the previous selection is obsolete. + pendingThreadPane = false; + pendingThreadRows.clear(); + if (!conversationReady) { + pendingConversation = true; + pendingConversationAuthorityReplacement = true; + } + pendingInspector |= !inspectorReady; + if (pendingConversation || pendingInspector || pendingChrome) + schedulePaneCommit(); } - detached.push_back(std::move(iterator->second)); - iterator = pendingUiDetachments.erase(iterator); - } - if (!detached.empty()) - session.acknowledgeUiDetached(detached); -} - -void ShellWidget::Impl::schedulePaneCommit(bool immediate) { - if (paneCommitScheduled) - return; - paneCommitScheduled = true; - const auto token = alive; - QTimer::singleShot(immediate ? 0 : 16, Qt::PreciseTimer, owner, - [this, token] { - if (!token->load(std::memory_order_acquire)) - return; - paneCommitScheduled = false; - commitPendingPanes(); - }); -} - -void ShellWidget::Impl::commitPendingPanes() { - QElapsedTimer commitTiming; - commitTiming.start(); - const auto hasFrameBudget = [&] { - return commitTiming.elapsed() < PaneCommitBudgetMilliseconds; - }; - owner->setProperty("paneCommitInvocations", - owner->property("paneCommitInvocations").toULongLong() + - 1); - owner->setProperty("conversationPresentationRowsInLastPass", qulonglong{0}); - bool retry = false; - bool waitingForConversationStage = false; - middleRegion->inspector().flushProtocolPresentation(); - if (hasFrameBudget() && !pendingThreadPane && - !pendingThreadRows.empty()) { - while (!pendingThreadRows.empty() && hasFrameBudget()) { - const auto row = uiAdapter.threadRow(pendingThreadRows.front()); - if (!row || !middleRegion->threads().applyRowPresentation(*row)) { - pendingThreadPane = true; - break; - } - pendingThreadRows.pop_front(); + + bool ShellWidget::Impl::refreshConversation() { + if (!boundGraphThread) { + static_cast(middleRegion->conversation().reconcile({})); + routedConversationRevision = 0; + return true; + } + + const auto info = uiAdapter.conversationInfo(boundGraphThread); + if (!info) + return false; + const std::string& threadId = boundGraphThread->id().canonical; + middleRegion->conversation().setHistoryRequestPending(threadId, info->historyRequestPending); + + if (!info->readyForDisplay) { + if (!info->hydrationFailed) { + middleRegion->conversation().beginThreadSelection(threadId, boundGraphThread->incarnation()); + return true; + } + middleRegion->conversation().setEmptyMessage(QStringLiteral("Thread loading failed. Select Reload to retry.")); + middle::ConversationSnapshot failed; + failed.threadId = threadId; + static_cast(middleRegion->conversation().reconcile(failed)); + return true; + } + + middleRegion->conversation().setEmptyMessage(QStringLiteral("No materialized activity.")); + requestConversationSnapshot(); + return true; } - if (!pendingThreadPane) { - ++threadPaneRoutes; - owner->setProperty("threadPaneRoutes", - static_cast(threadPaneRoutes)); - owner->setProperty( - "targetedThreadPaneRoutes", - owner->property("targetedThreadPaneRoutes").toULongLong() + 1); + + void ShellWidget::Impl::requestConversationSnapshot() { + requestConversationProjection(true); } - } - if (hasFrameBudget() && pendingThreadPane) { - std::uint64_t graphRevision = 0; - if (auto threads = threadSnapshot(&graphRevision)) { - pendingThreadPane = false; - pendingThreadRows.clear(); - routedThreadRevision = graphRevision; - ++threadPaneRoutes; - owner->setProperty("threadPaneRoutes", - static_cast(threadPaneRoutes)); - middleRegion->threads().refresh(*threads); - } else { - retry = true; + + void ShellWidget::Impl::requestConversationRescan() { + const bool needsSnapshot = !boundGraphThread || + middleRegion->conversation().presentedThreadId() != boundGraphThread->id().canonical || + routedConversationRevision == 0; + requestConversationProjection(needsSnapshot); } - } - if (hasFrameBudget() && !pendingConversation && - !pendingConversationItems.empty() && - boundGraphThread) { - const std::size_t requestedRows = std::min( - ConversationPresentationRowsPerPass, pendingConversationItems.size()); - std::vector items; - items.reserve(requestedRows); - auto pending = pendingConversationItems.begin(); - for (std::size_t index = 0; index < requestedRows; ++index, ++pending) - items.push_back(*pending); - auto delta = uiAdapter.conversationDelta(boundGraphThread, items, false); - std::size_t appliedRows = delta ? delta->presentations.size() : 0; - const bool projected = delta.has_value(); - const bool applied = - delta && - middleRegion->conversation().applyConversationDelta(std::move(*delta)); - if (!applied) - appliedRows = 0; - if (applied) { - for (std::size_t index = 0; index < requestedRows; ++index) - popPendingConversationItem(); - } else if (projected) { - pendingConversation = true; - } else { - retry = true; + + void ShellWidget::Impl::requestConversationProjection(bool fullSnapshot) { + conversationProjectionRequested = true; + conversationFullProjectionRequested |= fullSnapshot; + ++conversationProjectionScheduleGeneration; + if (conversationProjectionInFlight) + return; + conversationProjectionStartScheduled = true; + const auto token = alive; + const std::uint64_t generation = conversationProjectionScheduleGeneration; + QTimer::singleShot(fullSnapshot ? 0 : ConversationProjectionQuietMilliseconds, Qt::PreciseTimer, owner, [this, token, generation] { + if (!token->load(std::memory_order_acquire)) + return; + if (generation != conversationProjectionScheduleGeneration) + return; + conversationProjectionStartScheduled = false; + startConversationSnapshot(); + }); } - owner->setProperty("conversationPresentationRowsInLastPass", - static_cast(appliedRows)); - owner->setProperty( - "conversationPresentationRowsProcessed", - owner->property("conversationPresentationRowsProcessed").toULongLong() + - static_cast(appliedRows)); - owner->setProperty( - "conversationPresentationMaxRowsPerPass", - std::max(owner->property("conversationPresentationMaxRowsPerPass") - .toULongLong(), - static_cast(appliedRows))); - if (appliedRows != 0) { - ++conversationRoutes; - owner->setProperty("conversationRoutes", - static_cast(conversationRoutes)); - owner->setProperty( - "targetedConversationRoutes", - owner->property("targetedConversationRoutes").toULongLong() + 1); + + void ShellWidget::Impl::startConversationSnapshot() { + if (!boundGraphThread) + return; + if (conversationProjectionInFlight) { + conversationProjectionRequested = true; + return; + } + const auto info = uiAdapter.conversationInfo(boundGraphThread); + if (!info || (info->historyRequestPending && !info->readyForDisplay)) { + if (info) + middleRegion->conversation().setHistoryRequestPending(boundGraphThread->id().canonical, info->historyRequestPending); + // A failed tryRead has no completion event to wake the pending projection. + requestConversationProjection(false); + return; + } + middleRegion->conversation().setHistoryRequestPending(boundGraphThread->id().canonical, info->historyRequestPending); + middleRegion->conversation().setProviderHasMore(boundGraphThread->id().canonical, info->providerHasMore); + conversationProjectionInFlight = true; + conversationProjectionRequested = false; + const bool fullSnapshot = conversationFullProjectionRequested; + conversationFullProjectionRequested = false; + conversationFullProjectionInFlight = fullSnapshot; + const std::uint64_t afterRevision = routedConversationRevision; + const nodegraph::NodeRef requestedThread = boundGraphThread; + const ui::NodeGraphUiAdapter adapter = uiAdapter; + const auto token = alive; + projectionPool.start([this, requestedThread, adapter, token, fullSnapshot, afterRevision] { + std::uint64_t graphRevision = 0; + auto snapshot = + fullSnapshot ? adapter.conversation(requestedThread, &graphRevision) : std::optional{}; + auto delta = fullSnapshot ? std::optional{} + : adapter.conversationDeltaSince(requestedThread, afterRevision, &graphRevision); + QMetaObject::invokeMethod( + qApp, + [this, + requestedThread, + graphRevision, + snapshot = std::move(snapshot), + delta = std::move(delta), + fullSnapshot, + token]() mutable { + if (!token->load(std::memory_order_acquire)) + return; + conversationProjectionInFlight = false; + conversationFullProjectionInFlight = false; + if (requestedThread != boundGraphThread) { + if (conversationProjectionRequested) + requestConversationSnapshot(); + return; + } + const auto currentInfo = uiAdapter.conversationInfo(requestedThread); + if ((fullSnapshot && !snapshot) || (!fullSnapshot && !delta) || !currentInfo || + (currentInfo->historyRequestPending && !currentInfo->readyForDisplay)) { + conversationProjectionRequested = true; + conversationFullProjectionRequested |= fullSnapshot; + QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this] { + requestConversationProjection(false); + }); + return; + } + if (conversationProjectionRequested) { + requestConversationProjection(fullSnapshot); + return; + } + + // A complete snapshot initializes or replaces authority. A + // rescan uses graph revision stamps to project only changed + // rows, keeping the full graph scan off the QWidget thread. + pendingConversation = false; + pendingConversationAuthorityReplacement = false; + pendingStructuralConversationDelta.reset(); + clearPendingConversationItems(); + if (fullSnapshot) { + const auto disposition = middleRegion->conversation().reconcileStaged(std::move(*snapshot)); + if (disposition != middle::ConversationView::SnapshotDisposition::Retryable) { + routedConversationRevision = graphRevision; + } else { + conversationProjectionRequested = true; + conversationFullProjectionRequested = true; + } + } else { + middleRegion->conversation().setProviderHasMore(requestedThread->id().canonical, delta->providerHasMore); + if (!delta->rows.empty() || !delta->removals.empty()) { + pendingStructuralConversationDelta = std::move(*delta); + pendingConversation = true; + schedulePaneCommit(); + } + } + if (conversationProjectionRequested) + requestConversationProjection(false); + }, + Qt::QueuedConnection); + }); } - if (applied && !pendingConversationItems.empty()) - owner->setProperty( - "conversationPresentationDeferredPasses", - owner->property("conversationPresentationDeferredPasses") - .toULongLong() + - 1); - } - if (hasFrameBudget() && pendingStructuralConversationDelta && - !middleRegion->conversation().structuralStagingActive()) { - middle::ConversationDelta delta = - std::move(*pendingStructuralConversationDelta); - pendingStructuralConversationDelta.reset(); - if (middleRegion->conversation().applyConversationDelta(std::move(delta))) { - pendingConversation = !pendingConversationItems.empty(); - pendingConversationAuthorityReplacement = false; - ++conversationRoutes; - owner->setProperty("conversationRoutes", - static_cast(conversationRoutes)); - owner->setProperty( - "targetedConversationRoutes", - owner->property("targetedConversationRoutes").toULongLong() + 1); - } else { - pendingConversation = true; - pendingConversationAuthorityReplacement = true; - clearPendingConversationItems(); + + bool ShellWidget::Impl::refreshInspector() { + middle::InspectorPane& pane = middleRegion->inspector(); + const std::optional projection = pane.currentProjection(); + if (!projection) + return true; + if (*projection == ui::InspectorProjection::Requests) { + ui::InspectorSnapshot snapshot; + snapshot.threadIncarnation = boundGraphThread ? boundGraphThread->incarnation() : 0; + auto requests = pendingRequestPage(pane.rowRequest(*projection)); + if (!requests) + return false; + snapshot.requests = std::move(*requests); + pane.refresh(snapshot, *projection); + return true; + } + nodegraph::NodeRef inspectorThread = boundGraphThread; + if (inspectorThread) { + const auto info = uiAdapter.conversationInfo(inspectorThread); + if (!info) + return false; + const std::string& presentedThreadId = middleRegion->conversation().presentedThreadId(); + if (!presentedThreadId.empty() && presentedThreadId != inspectorThread->id().canonical && !info->hydrationFailed) + return true; + if (!info->readyForDisplay) + inspectorThread.reset(); + } + requestInspectorProjection(inspectorThread, *projection, pane.rowRequest(*projection)); + return true; } - } - if (hasFrameBudget() && pendingConversation && - !pendingConversationAuthorityReplacement && - !pendingStructuralConversationDelta && - !pendingConversationItems.empty() && boundGraphThread && - !middleRegion->conversation().structuralStagingActive()) { - const std::size_t requestedRows = std::min( - ConversationPresentationRowsPerPass, pendingConversationItems.size()); - std::vector items; - items.reserve(requestedRows); - auto pending = pendingConversationItems.begin(); - for (std::size_t index = 0; index < requestedRows; ++index, ++pending) - items.push_back(*pending); - auto delta = uiAdapter.conversationDelta(boundGraphThread, items, true); - if (delta) { - pendingStructuralConversationDelta = std::move(*delta); - for (std::size_t index = 0; index < requestedRows; ++index) - popPendingConversationItem(); - } else { - retry = true; + + void ShellWidget::Impl::requestInspectorProjection(nodegraph::NodeRef thread, + ui::InspectorProjection projection, + ui::InspectorRowRequest request) { + requestedInspectorThread = std::move(thread); + requestedInspectorProjection = projection; + requestedInspectorRows = std::move(request); + inspectorProjectionRequested = true; + ++inspectorProjectionGeneration; + if (!inspectorProjectionInFlight) + startInspectorProjection(); } - } - if (hasFrameBudget() && pendingConversation && - pendingConversationAuthorityReplacement && - !middleRegion->conversation().structuralStagingActive()) { - const bool authorityReplacement = pendingConversationAuthorityReplacement; - pendingConversation = false; - pendingConversationAuthorityReplacement = false; - pendingStructuralConversationDelta.reset(); - clearPendingConversationItems(); - if (refreshConversation()) { - ++conversationRoutes; - owner->setProperty("conversationRoutes", - static_cast(conversationRoutes)); - } else { - pendingConversation = true; - pendingConversationAuthorityReplacement = authorityReplacement; - retry = true; + + void ShellWidget::Impl::startInspectorProjection() { + if (!inspectorProjectionRequested || inspectorProjectionInFlight) + return; + inspectorProjectionRequested = false; + inspectorProjectionInFlight = true; + const std::uint64_t generation = inspectorProjectionGeneration; + const nodegraph::NodeRef thread = requestedInspectorThread; + const ui::InspectorProjection projection = requestedInspectorProjection; + const ui::InspectorRowRequest request = requestedInspectorRows; + const ui::NodeGraphUiAdapter adapter = uiAdapter; + const auto token = alive; + projectionPool.start([this, thread, projection, request, adapter, token, generation] { + auto snapshot = adapter.inspector(thread, projection, request); + if (snapshot) + middle::InspectorPane::prepareMarkdown(*snapshot); + QMetaObject::invokeMethod( + qApp, + [this, thread, projection, snapshot = std::move(snapshot), token, generation]() mutable { + if (!token->load(std::memory_order_acquire)) + return; + inspectorProjectionInFlight = false; + middle::InspectorPane& pane = middleRegion->inspector(); + const std::optional currentProjection = pane.currentProjection(); + const bool current = generation == inspectorProjectionGeneration && thread == boundGraphThread && currentProjection && + *currentProjection == projection; + if (current && snapshot) { + pane.refresh(*snapshot, projection); + } else if (current && !snapshot) { + inspectorProjectionRequested = true; + } + if (inspectorProjectionRequested) + startInspectorProjection(); + }, + Qt::QueuedConnection); + }); } - } - waitingForConversationStage = - middleRegion->conversation().structuralStagingActive() && - (pendingConversation || pendingStructuralConversationDelta || - !pendingConversationItems.empty()); - if (hasFrameBudget() && pendingInspector) { - pendingInspector = false; - if (refreshInspector()) { - ++inspectorRoutes; - owner->setProperty("inspectorRoutes", - static_cast(inspectorRoutes)); - } else { - pendingInspector = true; - retry = true; + + void ShellWidget::Impl::queueConversationRoute(const ui::NodeGraphUiAdapter::ConversationRoute& route) { + if (route.historyRequestPending && boundGraphThread) + middleRegion->conversation().setHistoryRequestPending(boundGraphThread->id().canonical, *route.historyRequestPending); + if (route.providerHasMore && boundGraphThread) + middleRegion->conversation().setProviderHasMore(boundGraphThread->id().canonical, *route.providerHasMore); + if (route.historyRequestPending && !*route.historyRequestPending && conversationProjectionRequested) + requestConversationSnapshot(); + if (route.authorityReplacement) { + pendingConversation = false; + pendingConversationAuthorityReplacement = false; + pendingStructuralConversationDelta.reset(); + clearPendingConversationItems(); + requestConversationSnapshot(); + return; + } + const bool snapshotNeedsFull = + boundGraphThread && (middleRegion->conversation().presentedThreadId() != boundGraphThread->id().canonical || + middleRegion->conversation().structuralStagingActive() || conversationFullProjectionInFlight || + conversationFullProjectionRequested); + const bool snapshotOwnsStructure = boundGraphThread && (snapshotNeedsFull || conversationProjectionRequested || + conversationProjectionInFlight || conversationProjectionStartScheduled); + if (snapshotOwnsStructure && route.affected && route.structural) { + pendingStructuralConversationDelta.reset(); + clearPendingConversationItems(); + requestConversationProjection(snapshotNeedsFull); + return; + } + routedConversationRevision = std::max(routedConversationRevision, route.graphRevision); + if (route.structural && !route.items.empty()) { + pendingConversation = true; + pendingConversationAuthorityReplacement = false; + } + if (route.affected && !pendingConversationAuthorityReplacement) { + for (const nodegraph::NodeRef& item : route.items) { + if (item && pendingConversationItemKeys.insert(item.get()).second) + pendingConversationItems.push_back(item); + } + } } - } - if (hasFrameBudget() && pendingChrome) { - const std::optional projectedRequests = - pendingRequestSummary(); - if (projectedRequests) { - pendingChrome = false; - render(&*projectedRequests); - } else { - retry = true; + + void ShellWidget::Impl::clearPendingConversationItems() { + pendingConversationItems.clear(); + pendingConversationItemKeys.clear(); } - } - acknowledgeDetachedTargets(); - if (retry || pendingThreadPane || !pendingThreadRows.empty() || - (!waitingForConversationStage && - (pendingConversation || pendingStructuralConversationDelta || - !pendingConversationItems.empty())) || - pendingInspector || pendingChrome) - schedulePaneCommit(); -} - -bool ShellWidget::Impl::handleGraphChanged( - const nodegraph::GraphChanged &change) { - auto read = session.nodeGraph().tryRead(); - if (!read) - return false; - const bool requestsChanged = - uiAdapter.inspectorAffected(change, boundGraphThread, - ui::InspectorProjection::Requests, *read); - const bool updateChrome = - requestsChanged || shellChromeAffected(change, *read, boundGraphThread); - const bool providerReset = change.providerAuthorityRevision != 0; - const bool authorityAdvanced = - change.providerAuthorityRevision > observedProviderAuthorityRevision; - if (authorityAdvanced) - observedProviderAuthorityRevision = change.providerAuthorityRevision; - for (const nodegraph::NodeRef &removed : change.removed) { - if (!removed) - continue; - pendingUiDetachments.insert_or_assign(removed.get(), removed); - if (removed->id().kind == nodegraph::NodeKind::Thread) { - middleRegion->conversation().forgetThreadPresentation( - removed->id().canonical, removed->incarnation()); - middleRegion->composer().turnSettings().forget(removed->id().canonical, - removed->incarnation()); + + void ShellWidget::Impl::popPendingConversationItem() { + pendingConversationItemKeys.erase(pendingConversationItems.front().get()); + pendingConversationItems.pop_front(); } - if (removed->id().kind == nodegraph::NodeKind::Interaction) - localPendingRequests.erase(removed); - retainedRenames.erase(removed.get()); - } - bool staleBoundThread = false; - if (authorityAdvanced && change.rescanRequired && boundGraphThread) { - staleBoundThread = read->find(boundGraphThread->id()) != boundGraphThread; - } - const nodegraph::NodeRef removedBoundThread = - boundGraphThread && - (staleBoundThread || - std::ranges::find(change.removed, boundGraphThread) != - change.removed.end()) - ? boundGraphThread - : nodegraph::NodeRef{}; - if (change.rescanRequired) { - if (boundGraphThread) { - requestConversationRescan(); + + bool ShellWidget::Impl::uiRetainsTarget(const nodegraph::NodeRef& target) const noexcept { + if (!target) + return false; + if (boundGraphThread == target || reviewedRequest == target || retainedRenames.contains(target.get()) || + localPendingRequests.contains(target)) + return true; + if (std::ranges::find(pendingThreadRows, target) != pendingThreadRows.end() || pendingConversationItemKeys.contains(target.get())) + return true; + if (pendingStructuralConversationDelta) { + const middle::ConversationDelta& delta = *pendingStructuralConversationDelta; + if (std::ranges::any_of(delta.presentations, + [&target](const auto& card) { + return card.target == target; + }) || + std::ranges::any_of(delta.rows, + [&target](const auto& row) { + return row.placement.card.target == target; + }) || + std::ranges::find(delta.removals, target) != delta.removals.end() || + std::ranges::any_of(delta.materializedPrompts, [&target](const auto& prompt) { + return prompt.prompt == target; + })) + return true; + } + return middleRegion->threads().retainsTarget(target) || middleRegion->conversation().retainsTarget(target) || + middleRegion->inspector().retainsTarget(target); } - } else { - ui::NodeGraphUiAdapter::ConversationRoute conversationRoute = - uiAdapter.conversationRoute(change, boundGraphThread, *read); - for (const nodegraph::NodeRef &removed : change.removed) { - if (!removed || - !middleRegion->conversation().retainsTarget(removed) || - std::ranges::find(conversationRoute.items, removed) != - conversationRoute.items.end()) - continue; - conversationRoute.affected = true; - conversationRoute.structural = true; - conversationRoute.items.push_back(removed); + + void ShellWidget::Impl::acknowledgeDetachedTargets() { + std::vector detached; + for (auto iterator = pendingUiDetachments.begin(); iterator != pendingUiDetachments.end();) { + if (uiRetainsTarget(iterator->second)) { + ++iterator; + continue; + } + detached.push_back(std::move(iterator->second)); + iterator = pendingUiDetachments.erase(iterator); + } + if (!detached.empty()) + session.acknowledgeUiDetached(detached); } - queueConversationRoute(conversationRoute); - } - middle::InspectorPane &inspectorPane = middleRegion->inspector(); - const std::optional inspectorProjection = - inspectorPane.isVisible() ? inspectorPane.currentProjection() - : std::nullopt; - const ThreadPaneRoute threads = - requestsChanged && !change.childListsChanged.empty() - ? ThreadPaneRoute{true, true, {}} - : threadPaneRoute(change, *read, - middleRegion->threads().currentSortCriterion(), - middleRegion->threads().browserOptions().grouping, - routedThreadRevision); - if (threads.structural) { - pendingThreadPane = true; - pendingThreadRows.clear(); - } else if (threads.affected && !pendingThreadPane) { - for (const nodegraph::NodeRef &thread : threads.rows) - if (std::ranges::find(pendingThreadRows, thread) == - pendingThreadRows.end()) - pendingThreadRows.push_back(thread); - } - if (!threads.structural) - routedThreadRevision = - std::max(routedThreadRevision, threads.graphRevision); - pendingInspector = - pendingInspector || - (inspectorProjection && - (*inspectorProjection == ui::InspectorProjection::Requests - ? requestsChanged - : uiAdapter.inspectorAffected( - change, boundGraphThread, *inspectorProjection, *read))); - pendingChrome = pendingChrome || updateChrome; - const bool fallbackAffected = graphUiFallbackAffected(change, *read); - read.reset(); - if (fallbackAffected) - reconcileGraphUiFallback(); - - // Promotion may already have rebound a removed optimistic thread. Otherwise - // clear all pane-held references synchronously before FrontendSession can - // acknowledge retirement. Preserve the canonical selection only across a - // provider generation reset so recreation can trigger one fresh hydration. - if (removedBoundThread && boundGraphThread == removedBoundThread) { - if (!providerReset) - selectedGraphThreadId.clear(); - bindGraphPanes({}); - } - - acknowledgeDetachedTargets(); - - // The graph retains removed identities until commitPendingPanes has - // detached every presentation reference and acknowledges that lifetime. - // Visible reconciliation therefore remains frame-coalesced for removals as - // well as ordinary state traffic. - if (pendingThreadPane || !pendingThreadRows.empty() || pendingConversation || - !pendingConversationItems.empty() || pendingInspector || pendingChrome || - !pendingUiDetachments.empty()) - schedulePaneCommit(); - if (authorityAdvanced) - observedProviderAuthorityRevision = std::max( - observedProviderAuthorityRevision, middleRegion->composer() - .turnSettings() - .context() - .providerAuthorityRevision); - - const bool selectedChanged = - !graphPanesBound || change.rescanRequired || - (!boundGraphThread && !selectedGraphThreadId.empty() && - std::ranges::any_of( - change.affected, - [this](const auto &node) { - return node && node->id().kind == nodegraph::NodeKind::Thread && - node->id().canonical == selectedGraphThreadId; - })) || - std::ranges::any_of(change.removed, [this](const auto &node) { - return node && node->id().kind == nodegraph::NodeKind::Thread && - node->id().canonical == selectedGraphThreadId; - }); - if (selectedChanged) - scheduleGraphBinding(); - return true; -} - -void ShellWidget::Impl::reconcileGraphUiFallback() { - std::string notice; - bool noticeError = true; - std::uint64_t noticeSerial = lastNoticeSerial; - nodegraph::NodeRef selection; - std::uint64_t selectionSerial = lastSelectionSerial; - if (auto read = session.nodeGraph().tryRead()) { - const auto considerNotice = [&](std::string_view id) { - if (const nodegraph::NodeRef node = - read->find({nodegraph::NodeKind::Notice, std::string(id)})) { - const auto state = read->state(node); - const std::int64_t rawSerial = - signedIntegerFromValue(valueMember(*state, "noticeSerial")) - .value_or(0); - if (rawSerial > 0 && - static_cast(rawSerial) > noticeSerial) { - noticeSerial = static_cast(rawSerial); - notice = exactStringFromValue(valueMember(*state, "noticeText")); - if (notice.empty()) - notice = exactStringFromValue(valueMember(*state, "message")); - noticeError = exactStringFromValue(valueMember(*state, "severity")) != - "warning"; - } - } - }; - considerNotice("local-worker-notice"); - considerNotice("provider-notice"); - if (const nodegraph::NodeRef runtime = - read->find({nodegraph::NodeKind::Runtime, "runtime"})) { - const auto state = read->state(runtime); - const std::int64_t rawSerial = - signedIntegerFromValue(valueMember(*state, "uiSelectionSerial")) - .value_or(0); - if (rawSerial > 0 && - static_cast(rawSerial) > lastSelectionSerial) { - const std::vector targets = - read->related(runtime, nodegraph::RelationKind::UiSelectionTarget); - if (!targets.empty() && read->live(targets.front())) { - selectionSerial = static_cast(rawSerial); - selection = targets.front(); - } - } + + void ShellWidget::Impl::schedulePaneCommit(bool immediate) { + if (paneCommitScheduled) + return; + paneCommitScheduled = true; + const auto token = alive; + QTimer::singleShot(immediate ? 0 : 16, Qt::PreciseTimer, owner, [this, token] { + if (!token->load(std::memory_order_acquire)) + return; + paneCommitScheduled = false; + commitPendingPanes(); + }); } - } else { - if (!graphFallbackScheduled) { - graphFallbackScheduled = true; - const auto token = alive; - QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this, token] { - if (!token->load(std::memory_order_acquire)) - return; - graphFallbackScheduled = false; - reconcileGraphUiFallback(); - }); + + void ShellWidget::Impl::commitPendingPanes() { + QElapsedTimer commitTiming; + commitTiming.start(); + const auto hasFrameBudget = [&] { + return commitTiming.elapsed() < PaneCommitBudgetMilliseconds; + }; + owner->setProperty("paneCommitInvocations", owner->property("paneCommitInvocations").toULongLong() + 1); + owner->setProperty("conversationPresentationRowsInLastPass", qulonglong{0}); + bool retry = false; + bool waitingForConversationStage = false; + middleRegion->inspector().flushProtocolPresentation(); + if (hasFrameBudget() && !pendingThreadPane && !pendingThreadRows.empty()) { + while (!pendingThreadRows.empty() && hasFrameBudget()) { + const auto row = uiAdapter.threadRow(pendingThreadRows.front()); + if (!row || !middleRegion->threads().applyRowPresentation(*row)) { + pendingThreadPane = true; + break; + } + pendingThreadRows.pop_front(); + } + if (!pendingThreadPane) { + ++threadPaneRoutes; + owner->setProperty("threadPaneRoutes", static_cast(threadPaneRoutes)); + owner->setProperty("targetedThreadPaneRoutes", owner->property("targetedThreadPaneRoutes").toULongLong() + 1); + } + } + if (hasFrameBudget() && pendingThreadPane) { + std::uint64_t graphRevision = 0; + if (auto threads = threadSnapshot(&graphRevision)) { + pendingThreadPane = false; + pendingThreadRows.clear(); + routedThreadRevision = graphRevision; + ++threadPaneRoutes; + owner->setProperty("threadPaneRoutes", static_cast(threadPaneRoutes)); + middleRegion->threads().refresh(*threads); + } else { + retry = true; + } + } + if (hasFrameBudget() && !pendingConversation && !pendingConversationItems.empty() && boundGraphThread) { + const std::size_t requestedRows = std::min(ConversationPresentationRowsPerPass, pendingConversationItems.size()); + std::vector items; + items.reserve(requestedRows); + auto pending = pendingConversationItems.begin(); + for (std::size_t index = 0; index < requestedRows; ++index, ++pending) + items.push_back(*pending); + auto delta = uiAdapter.conversationDelta(boundGraphThread, items, false); + std::size_t appliedRows = delta ? delta->presentations.size() : 0; + const bool projected = delta.has_value(); + const bool applied = delta && middleRegion->conversation().applyConversationDelta(std::move(*delta)); + if (!applied) + appliedRows = 0; + if (applied) { + for (std::size_t index = 0; index < requestedRows; ++index) + popPendingConversationItem(); + } else if (projected) { + pendingConversation = true; + } else { + retry = true; + } + owner->setProperty("conversationPresentationRowsInLastPass", static_cast(appliedRows)); + owner->setProperty("conversationPresentationRowsProcessed", + owner->property("conversationPresentationRowsProcessed").toULongLong() + + static_cast(appliedRows)); + owner->setProperty( + "conversationPresentationMaxRowsPerPass", + std::max(owner->property("conversationPresentationMaxRowsPerPass").toULongLong(), static_cast(appliedRows))); + if (appliedRows != 0) { + ++conversationRoutes; + owner->setProperty("conversationRoutes", static_cast(conversationRoutes)); + owner->setProperty("targetedConversationRoutes", owner->property("targetedConversationRoutes").toULongLong() + 1); + } + if (applied && !pendingConversationItems.empty()) + owner->setProperty("conversationPresentationDeferredPasses", + owner->property("conversationPresentationDeferredPasses").toULongLong() + 1); + } + if (hasFrameBudget() && pendingStructuralConversationDelta && !middleRegion->conversation().structuralStagingActive()) { + middle::ConversationDelta delta = std::move(*pendingStructuralConversationDelta); + pendingStructuralConversationDelta.reset(); + if (middleRegion->conversation().applyConversationDelta(std::move(delta))) { + pendingConversation = !pendingConversationItems.empty(); + pendingConversationAuthorityReplacement = false; + ++conversationRoutes; + owner->setProperty("conversationRoutes", static_cast(conversationRoutes)); + owner->setProperty("targetedConversationRoutes", owner->property("targetedConversationRoutes").toULongLong() + 1); + } else { + pendingConversation = true; + pendingConversationAuthorityReplacement = true; + clearPendingConversationItems(); + } + } + if (hasFrameBudget() && pendingConversation && !pendingConversationAuthorityReplacement && !pendingStructuralConversationDelta && + !pendingConversationItems.empty() && boundGraphThread && !middleRegion->conversation().structuralStagingActive()) { + const std::size_t requestedRows = std::min(ConversationPresentationRowsPerPass, pendingConversationItems.size()); + std::vector items; + items.reserve(requestedRows); + auto pending = pendingConversationItems.begin(); + for (std::size_t index = 0; index < requestedRows; ++index, ++pending) + items.push_back(*pending); + auto delta = uiAdapter.conversationDelta(boundGraphThread, items, true); + if (delta) { + pendingStructuralConversationDelta = std::move(*delta); + for (std::size_t index = 0; index < requestedRows; ++index) + popPendingConversationItem(); + } else { + retry = true; + } + } + if (hasFrameBudget() && pendingConversation && pendingConversationAuthorityReplacement && + !middleRegion->conversation().structuralStagingActive()) { + const bool authorityReplacement = pendingConversationAuthorityReplacement; + pendingConversation = false; + pendingConversationAuthorityReplacement = false; + pendingStructuralConversationDelta.reset(); + clearPendingConversationItems(); + if (refreshConversation()) { + ++conversationRoutes; + owner->setProperty("conversationRoutes", static_cast(conversationRoutes)); + } else { + pendingConversation = true; + pendingConversationAuthorityReplacement = authorityReplacement; + retry = true; + } + } + waitingForConversationStage = middleRegion->conversation().structuralStagingActive() && + (pendingConversation || pendingStructuralConversationDelta || !pendingConversationItems.empty()); + if (hasFrameBudget() && pendingInspector) { + pendingInspector = false; + if (refreshInspector()) { + ++inspectorRoutes; + owner->setProperty("inspectorRoutes", static_cast(inspectorRoutes)); + } else { + pendingInspector = true; + retry = true; + } + } + if (hasFrameBudget() && pendingChrome) { + const std::optional projectedRequests = pendingRequestSummary(); + if (projectedRequests) { + pendingChrome = false; + render(&*projectedRequests); + } else { + retry = true; + } + } + acknowledgeDetachedTargets(); + if (retry || pendingThreadPane || !pendingThreadRows.empty() || + (!waitingForConversationStage && + (pendingConversation || pendingStructuralConversationDelta || !pendingConversationItems.empty())) || + pendingInspector || pendingChrome) + schedulePaneCommit(); } - return; - } - - if (noticeSerial > lastNoticeSerial) { - lastNoticeSerial = noticeSerial; - if (!notice.empty()) - showNotice(text(notice), noticeError); - } - if (selection && selectionSerial > lastSelectionSerial) { - lastSelectionSerial = selectionSerial; - selectGraphThread(std::move(selection), ThreadSelectionOrigin::Graph, - selectionSerial); - } -} - -void ShellWidget::Impl::selectGraphThread(nodegraph::NodeRef thread, - ThreadSelectionOrigin origin, - std::uint64_t graphSerial) { - if (thread && thread->id().kind == nodegraph::NodeKind::Thread) { + + bool ShellWidget::Impl::handleGraphChanged(const nodegraph::GraphChanged& change) { auto read = session.nodeGraph().tryRead(); - if (!read) { - QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this, thread = std::move(thread), origin, graphSerial]() mutable { - selectGraphThread(std::move(thread), origin, graphSerial); + if (!read) + return false; + const bool requestsChanged = uiAdapter.inspectorAffected(change, boundGraphThread, ui::InspectorProjection::Requests, *read); + const bool updateChrome = requestsChanged || shellChromeAffected(change, *read, boundGraphThread); + const bool providerReset = change.providerAuthorityRevision != 0; + const bool authorityAdvanced = change.providerAuthorityRevision > observedProviderAuthorityRevision; + if (authorityAdvanced) + observedProviderAuthorityRevision = change.providerAuthorityRevision; + for (const nodegraph::NodeRef& removed : change.removed) { + if (!removed) + continue; + pendingUiDetachments.insert_or_assign(removed.get(), removed); + if (removed->id().kind == nodegraph::NodeKind::Thread) { + middleRegion->conversation().forgetThreadPresentation(removed->id().canonical, removed->incarnation()); + middleRegion->composer().turnSettings().forget(removed->id().canonical, removed->incarnation()); + } + if (removed->id().kind == nodegraph::NodeKind::Interaction) + localPendingRequests.erase(removed); + retainedRenames.erase(removed.get()); + } + bool staleBoundThread = false; + if (authorityAdvanced && change.rescanRequired && boundGraphThread) { + staleBoundThread = read->find(boundGraphThread->id()) != boundGraphThread; + } + const nodegraph::NodeRef removedBoundThread = + boundGraphThread && (staleBoundThread || std::ranges::find(change.removed, boundGraphThread) != change.removed.end()) + ? boundGraphThread + : nodegraph::NodeRef{}; + if (change.rescanRequired) { + if (boundGraphThread) { + requestConversationRescan(); + } + } else { + ui::NodeGraphUiAdapter::ConversationRoute conversationRoute = uiAdapter.conversationRoute(change, boundGraphThread, *read); + for (const nodegraph::NodeRef& removed : change.removed) { + if (!removed || !middleRegion->conversation().retainsTarget(removed) || + std::ranges::find(conversationRoute.items, removed) != conversationRoute.items.end()) + continue; + conversationRoute.affected = true; + conversationRoute.structural = true; + conversationRoute.items.push_back(removed); + } + queueConversationRoute(conversationRoute); + } + middle::InspectorPane& inspectorPane = middleRegion->inspector(); + const std::optional inspectorProjection = inspectorPane.currentProjection(); + const ThreadPaneRoute threads = requestsChanged && !change.childListsChanged.empty() + ? ThreadPaneRoute{true, true, {}} + : threadPaneRoute(change, + *read, + middleRegion->threads().currentSortCriterion(), + middleRegion->threads().browserOptions().grouping, + routedThreadRevision); + if (threads.structural) { + pendingThreadPane = true; + pendingThreadRows.clear(); + } else if (threads.affected && !pendingThreadPane) { + for (const nodegraph::NodeRef& thread : threads.rows) + if (std::ranges::find(pendingThreadRows, thread) == pendingThreadRows.end()) + pendingThreadRows.push_back(thread); + } + if (!threads.structural) + routedThreadRevision = std::max(routedThreadRevision, threads.graphRevision); + pendingInspector = pendingInspector || (inspectorPane.isVisible() && inspectorProjection && + (*inspectorProjection == ui::InspectorProjection::Requests + ? requestsChanged + : uiAdapter.inspectorAffected(change, boundGraphThread, *inspectorProjection, *read))); + pendingChrome = pendingChrome || updateChrome; + const bool fallbackAffected = graphUiFallbackAffected(change, *read); + read.reset(); + if (fallbackAffected) + reconcileGraphUiFallback(); + + // Promotion may already have rebound a removed optimistic thread. Otherwise + // clear all pane-held references synchronously before FrontendSession can + // acknowledge retirement. Preserve the canonical selection only across a + // provider generation reset so recreation can trigger one fresh hydration. + if (removedBoundThread && boundGraphThread == removedBoundThread) { + if (!providerReset) + selectedGraphThreadId.clear(); + bindGraphPanes({}); + } + + acknowledgeDetachedTargets(); + + // The graph retains removed identities until commitPendingPanes has + // detached every presentation reference and acknowledges that lifetime. + // Visible reconciliation therefore remains frame-coalesced for removals as + // well as ordinary state traffic. + if (pendingThreadPane || !pendingThreadRows.empty() || pendingConversation || !pendingConversationItems.empty() || + pendingInspector || pendingChrome || !pendingUiDetachments.empty()) + schedulePaneCommit(); + if (authorityAdvanced) + observedProviderAuthorityRevision = + std::max(observedProviderAuthorityRevision, middleRegion->composer().turnSettings().context().providerAuthorityRevision); + + const bool selectedChanged = + !graphPanesBound || change.rescanRequired || + (!boundGraphThread && !selectedGraphThreadId.empty() && + std::ranges::any_of(change.affected, + [this](const auto& node) { + return node && node->id().kind == nodegraph::NodeKind::Thread && + node->id().canonical == selectedGraphThreadId; + })) || + std::ranges::any_of(change.removed, [this](const auto& node) { + return node && node->id().kind == nodegraph::NodeKind::Thread && node->id().canonical == selectedGraphThreadId; }); - } else if (read->live(thread)) { - const auto state = read->state(thread); - const std::string creationCorrelation = exactStringFromValue(valueMember(*state, "creationCorrelation")); - const bool local = boolFromValue(valueMember(*state, "local")); - const bool selectedCreation = - !creationCorrelation.empty() && boundGraphThread && read->contains(boundGraphThread) && - exactStringFromValue(valueMember(*read->state(boundGraphThread), "creationCorrelation")) == creationCorrelation; - read.reset(); - const auto visible = middleRegion->threads().visiblySelectedThread(); - bool selected = origin == ThreadSelectionOrigin::User ? visible && visible->target == thread - : graphSerial == 0 || graphSerial == lastSelectionSerial; - if (selected) { - const std::string targetId = thread->id().canonical; - const bool ownsCreation = !creationCorrelation.empty() && creationCorrelation == creationDraftCorrelation; - if (!local && !creationCorrelation.empty()) { - middleRegion->composer().turnSettings().promote( - ui::threadPresentationKey(targetId, creationCorrelation), targetId, thread->incarnation()); + if (selectedChanged) + scheduleGraphBinding(); + return true; + } + + void ShellWidget::Impl::reconcileGraphUiFallback() { + std::string notice; + bool noticeError = true; + std::uint64_t noticeSerial = lastNoticeSerial; + nodegraph::NodeRef selection; + std::uint64_t selectionSerial = lastSelectionSerial; + if (auto read = session.nodeGraph().tryRead()) { + const auto considerNotice = [&](std::string_view id) { + if (const nodegraph::NodeRef node = read->find({nodegraph::NodeKind::Notice, std::string(id)})) { + const auto state = read->state(node); + const std::int64_t rawSerial = signedIntegerFromValue(valueMember(*state, "noticeSerial")).value_or(0); + if (rawSerial > 0 && static_cast(rawSerial) > noticeSerial) { + noticeSerial = static_cast(rawSerial); + notice = exactStringFromValue(valueMember(*state, "noticeText")); + if (notice.empty()) + notice = exactStringFromValue(valueMember(*state, "message")); + noticeError = exactStringFromValue(valueMember(*state, "severity")) != "warning"; + } } - if (origin == ThreadSelectionOrigin::Graph && !creationCorrelation.empty()) { - selected = ownsCreation ? selectedGraphThreadId.empty() || selectedGraphThreadId == targetId || selectedCreation - : creationDraftCorrelation.empty(); - if (ownsCreation && !local) { - creationDraftCorrelation.clear(); + }; + considerNotice("local-worker-notice"); + considerNotice("provider-notice"); + if (const nodegraph::NodeRef runtime = read->find({nodegraph::NodeKind::Runtime, "runtime"})) { + const auto state = read->state(runtime); + const std::int64_t rawSerial = signedIntegerFromValue(valueMember(*state, "uiSelectionSerial")).value_or(0); + if (rawSerial > 0 && static_cast(rawSerial) > lastSelectionSerial) { + const std::vector targets = read->related(runtime, nodegraph::RelationKind::UiSelectionTarget); + if (!targets.empty() && read->live(targets.front())) { + selectionSerial = static_cast(rawSerial); + selection = targets.front(); } } + } + } else { + if (!graphFallbackScheduled) { + graphFallbackScheduled = true; + const auto token = alive; + QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this, token] { + if (!token->load(std::memory_order_acquire)) + return; + graphFallbackScheduled = false; + reconcileGraphUiFallback(); + }); + } + return; + } + + if (noticeSerial > lastNoticeSerial) { + lastNoticeSerial = noticeSerial; + if (!notice.empty()) + showNotice(text(notice), noticeError); + } + if (selection && selectionSerial > lastSelectionSerial) { + lastSelectionSerial = selectionSerial; + selectGraphThread(std::move(selection), ThreadSelectionOrigin::Graph, selectionSerial); + } + } + + void ShellWidget::Impl::selectGraphThread(nodegraph::NodeRef thread, ThreadSelectionOrigin origin, std::uint64_t graphSerial) { + if (thread && thread->id().kind == nodegraph::NodeKind::Thread) { + auto read = session.nodeGraph().tryRead(); + if (!read) { + QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this, thread = std::move(thread), origin, graphSerial]() mutable { + selectGraphThread(std::move(thread), origin, graphSerial); + }); + } else if (read->live(thread)) { + const auto state = read->state(thread); + const std::string creationCorrelation = exactStringFromValue(valueMember(*state, "creationCorrelation")); + const bool local = boolFromValue(valueMember(*state, "local")); + const bool selectedCreation = + !creationCorrelation.empty() && boundGraphThread && read->contains(boundGraphThread) && + exactStringFromValue(valueMember(*read->state(boundGraphThread), "creationCorrelation")) == creationCorrelation; + read.reset(); + const auto visible = middleRegion->threads().visiblySelectedThread(); + bool selected = origin == ThreadSelectionOrigin::User ? visible && visible->target == thread + : graphSerial == 0 || graphSerial == lastSelectionSerial; if (selected) { - if (origin == ThreadSelectionOrigin::User && newThreadDraft) { - middleRegion->composer().turnSettings().forget(ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation)); - middleRegion->threads().discardOptimisticThread(DraftThreadId); - creationDraftCorrelation.clear(); + const std::string targetId = thread->id().canonical; + const bool ownsCreation = !creationCorrelation.empty() && creationCorrelation == creationDraftCorrelation; + if (!local && !creationCorrelation.empty()) { + middleRegion->composer().turnSettings().promote( + ui::threadPresentationKey(targetId, creationCorrelation), targetId, thread->incarnation()); } - newThreadDraft.reset(); - selectedGraphThreadId = targetId; - bindGraphPanes(thread); - if (origin == ThreadSelectionOrigin::User) { - hydrateSelectedThreadIfNeeded(std::move(thread)); + if (origin == ThreadSelectionOrigin::Graph && !creationCorrelation.empty()) { + selected = ownsCreation ? selectedGraphThreadId.empty() || selectedGraphThreadId == targetId || selectedCreation + : creationDraftCorrelation.empty(); + if (ownsCreation && !local) { + creationDraftCorrelation.clear(); + } + } + if (selected) { + if (origin == ThreadSelectionOrigin::User && newThreadDraft) { + middleRegion->composer().turnSettings().forget( + ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation)); + middleRegion->threads().discardOptimisticThread(DraftThreadId); + creationDraftCorrelation.clear(); + } + newThreadDraft.reset(); + selectedGraphThreadId = targetId; + bindGraphPanes(thread); + if (origin == ThreadSelectionOrigin::User) { + hydrateSelectedThreadIfNeeded(std::move(thread)); + } } } } } } -} - -void ShellWidget::Impl::handleProtocolDiagnostic( - const nodegraph::ProtocolDiagnostic &diagnostic) { - if (middleRegion->inspector().appendProtocolDiagnostic(diagnostic)) - schedulePaneCommit(); -} - -bool ShellWidget::Impl::sendNodeAction(nodegraph::NodeAction action, - QString rejection) { - const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); - if (!nodegraph::deliveryGuaranteed(status)) { - if (!rejection.isEmpty()) - showNotice(std::move(rejection)); - return false; - } - if (nodegraph::wakeFailed(status)) - showNotice(QStringLiteral( - "The action was admitted after a worker wake-up failure; bounded " - "fallback delivery is active.")); - return true; -} - -bool ShellWidget::Impl::sendRuntimeAction(nodegraph::RuntimeAction action, - QString rejection) { - const nodegraph::ChannelSendStatus status = session.sendRuntimeAction(action); - if (!nodegraph::deliveryGuaranteed(status)) { - if (!rejection.isEmpty()) - showNotice(std::move(rejection)); - return false; - } - if (nodegraph::wakeFailed(status)) - showNotice(QStringLiteral( - "The action was admitted after a worker wake-up failure; bounded " - "fallback delivery is active.")); - return true; -} - -void ShellWidget::Impl::hydrateSelectedThreadIfNeeded( - nodegraph::NodeRef thread) { - if (!thread || boundGraphThread != thread) - return; - auto read = session.nodeGraph().tryRead(); - if (!read) { - QTimer::singleShot(GraphRetryDelayMilliseconds, owner, - [this, thread = std::move(thread)]() mutable { - hydrateSelectedThreadIfNeeded(std::move(thread)); - }); - return; - } - if (!read->live(thread)) - return; - const bool recoveryOnly = - boolFromValue(valueMember(*read->state(thread), "recoveryOnly")); - read.reset(); - if (recoveryOnly) - return; - nodegraph::NodeAction action{std::move(thread), - nodegraph::NodeActionKind::Hydrate, - {}, {}, {}, {}}; - static_cast(sendNodeAction( - std::move(action), - QStringLiteral( - "Thread loading was not admitted; select Reload to retry."))); -} - -nodegraph::NodeRef ShellWidget::Impl::activeTurn() const { - if (!boundGraphThread) - return {}; - auto read = session.nodeGraph().tryRead(); - if (!read || !read->live(boundGraphThread)) - return {}; - nodegraph::NodeRef indexed = - read->relatedAt(boundGraphThread, nodegraph::RelationKind::ActiveTurn, 0); - if (indexed && indexed->id().kind == nodegraph::NodeKind::Turn) - return indexed; - return {}; -} - -void ShellWidget::Impl::applyLocalPending(PendingRequestDescriptor &request) { - const auto local = localPendingRequests.find(request.target); - if (local == localPendingRequests.end()) - return; - if (local->second.awaitingResponseAfter && - request.responseRevision > *local->second.awaitingResponseAfter) { - localPendingRequests.erase(local); - return; - } - request.retainedSubmission = local->second.submission; - if (local->second.awaitingResponseAfter) - request.availability = PendingRequestAvailability::Submitting; -} - -std::optional -ShellWidget::Impl::pendingRequestSummary(bool *busy) { - if (busy) - *busy = false; - std::vector localTargets; - localTargets.reserve(localPendingRequests.size()); - for (const auto &[target, local] : localPendingRequests) { - static_cast(local); - localTargets.push_back(target); - } - if (reviewedRequest) - localTargets.push_back(reviewedRequest); - auto summary = uiAdapter.pendingRequestSummary( - boundGraphThread ? std::string_view(boundGraphThread->id().canonical) - : std::string_view{}, - localTargets); - if (!summary) { - if (busy) - *busy = true; - return std::nullopt; - } - for (PendingRequestDescriptor &request : summary->candidates) - applyLocalPending(request); - std::erase_if(localPendingRequests, [&](const auto &local) { - return std::ranges::none_of(summary->candidates, [&](const auto &request) { - return request.target == local.first; - }); - }); - return summary; -} - -std::optional -ShellWidget::Impl::pendingRequestPage(const ui::InspectorRowRequest &request, - bool *busy) { - if (busy) - *busy = false; - auto page = uiAdapter.pendingRequests(request); - if (!page) { - if (busy) - *busy = true; - return std::nullopt; - } - const auto apply = [this](ui::InspectorRow &row) { - if (auto *pending = std::get_if(&row.value)) - applyLocalPending(*pending); - }; - for (ui::InspectorRow &row : page->rows) - apply(row); - if (page->focused) - apply(*page->focused); - return page; -} - -std::optional -ShellWidget::Impl::pendingRequest(const nodegraph::NodeRef &target) { - bool busy = false; - auto request = uiAdapter.pendingRequest(target, &busy); - if (!request) { - showNotice( - busy ? QStringLiteral("Request state is busy; no response was sent.") - : QStringLiteral("The pending request is no longer actionable.")); - return std::nullopt; - } - applyLocalPending(*request); - return request; -} - -void ShellWidget::Impl::render( - const ui::PendingRequestsSummary *projectedRequests) { - ShellChromeValues values; - values.title = "Select a thread"; - values.workspace = "No workspace"; - - { - auto read = session.nodeGraph().tryRead(); - if (!read) { - pendingChrome = true; - schedulePaneCommit(); - return; + + void ShellWidget::Impl::handleProtocolDiagnostic(const nodegraph::ProtocolDiagnostic& diagnostic) { + if (middleRegion->inspector().appendProtocolDiagnostic(diagnostic)) + schedulePaneCommit(); } - if (const nodegraph::NodeRef connection = - read->find({nodegraph::NodeKind::Connection, "connection"})) { - const auto state = read->state(connection); - const std::string transport = - exactStringFromValue(valueMember(*state, "transportState")); - values.connected = state->status == nodegraph::NodeStatus::Connected; - values.retrying = transport == "retrying" || transport == "connecting"; - values.role = exactStringFromValue(valueMember(*state, "role")); - values.providerState = - exactStringFromValue(valueMember(*state, "providerState")); - values.canControl = values.connected && values.providerState == "ready" && - values.role == "controller"; - if (const nodegraph::Value *settings = valueMember(*state, "settings")) { - if (const auto *object = settings->asObject()) { - const std::string selected = - exactStringFromValue(valueMember(*object, "selected")); - const nodegraph::Value *available = valueMember(*object, "available"); - if (available && available->asArray()) { - for (const nodegraph::Value &entry : *available->asArray()) { - const auto *transportEntry = entry.asObject(); - if (transportEntry && exactStringFromValue(valueMember( - *transportEntry, "key")) == selected) { - values.selectedTransport = - exactStringFromValue(valueMember(*transportEntry, "label")); - break; - } - } - } + + bool ShellWidget::Impl::sendNodeAction(nodegraph::NodeAction action, QString rejection) { + const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); + if (!nodegraph::deliveryGuaranteed(status)) { + if (!rejection.isEmpty()) + showNotice(std::move(rejection)); + return false; } - } + if (nodegraph::wakeFailed(status)) + showNotice(QStringLiteral("The action was admitted after a worker wake-up failure; bounded " + "fallback delivery is active.")); + return true; } - nodegraph::NodeRef selected = boundGraphThread; - if (selected && !read->live(selected)) - selected.reset(); - values.tokenUsage = uiAdapter.tokenUsage(selected, *read); - if (selected) { - const auto state = read->state(selected); - values.title = exactStringFromValue(valueMember(*state, "name")); - if (values.title.empty()) - values.title = exactStringFromValue(valueMember(*state, "title")); - if (values.title.empty()) - values.title = "Untitled thread"; - values.workspace = exactStringFromValue(valueMember(*state, "cwd")); - values.workspaceChangeUnavailable = nodegraph::threadWorkspaceChangeUnavailable(*read, selected); - values.status = statusFromState(*state); - values.recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); - const std::string hydrationState = - exactStringFromValue(valueMember(*state, "hydrationState")); - const bool local = boolFromValue(valueMember(*state, "local")); - values.conversationReadyForDisplay = - hydrationState == "ready" || local || values.recoveryOnly; - values.hydrationFailed = hydrationState == "failed"; - values.threadAdmissionReady = - !values.recoveryOnly && hydrationState != "loading" && - hydrationState != "failed" && - (state->status != nodegraph::NodeStatus::NotLoaded || - hydrationState == "ready"); - for (const auto& operation : read->related(selected, nodegraph::RelationKind::PendingOperation)) { - if (exactStringFromValue(valueMember(*read->state(operation), "method")) == "thread/revert") { - values.threadAdmissionReady = false; - } - } - values.lastActivityAt = - signedIntegerFromValue(valueMember(*state, "lastActivityAt")); - for (const std::string_view field : - {std::string_view("recencyAt"), std::string_view("updatedAt"), - std::string_view("localActivityAt"), - std::string_view("localPromptActivityAt")}) { - const std::optional timestamp = - signedIntegerFromValue(valueMember(*state, field)); - if (timestamp && - (!values.lastActivityAt || *timestamp > *values.lastActivityAt)) - values.lastActivityAt = timestamp; - } - nodegraph::NodeRef turn = - read->relatedAt(selected, nodegraph::RelationKind::ActiveTurn, 0); - values.activeTurn = turn && turn->id().kind == nodegraph::NodeKind::Turn; - } else if (newThreadDraft) { - values.title = newThreadDraft->name.trimmed().isEmpty() - ? "New thread" - : utf8(newThreadDraft->name.trimmed()); - values.workspace = utf8(newThreadDraft->workspace); - } - } - - std::optional ownedRequests; - if (!projectedRequests) { - ownedRequests = pendingRequestSummary(); - if (!ownedRequests) { - pendingChrome = true; - schedulePaneCommit(); - return; - } - projectedRequests = &*ownedRequests; - } - values.totalPending = projectedRequests->total; - if (reviewSubmit) { - const auto request = std::ranges::find(projectedRequests->candidates, - reviewedRequest, - &PendingRequestDescriptor::target); - const bool live = request != projectedRequests->candidates.end(); - reviewSubmit->setEnabled(live && request->availability == - PendingRequestAvailability::Actionable); - reviewSubmit->setToolTip(live ? text(PendingRequestPolicy::status(*request)) - : QStringLiteral("This request has ended.")); - reviewSubmit->setText(live ? QStringLiteral("Submit") - : QStringLiteral("Resolved")); - } - const std::optional attention = - PendingRequestPolicy::attentionIndex( - projectedRequests->candidates, - boundGraphThread ? std::string_view(boundGraphThread->id().canonical) - : std::string_view{}); - if (attention && *attention < projectedRequests->candidates.size()) - values.attention = projectedRequests->candidates[*attention]; - const std::string &presentedThreadId = - middleRegion->conversation().presentedThreadId(); - const bool replacementHydrating = - boundGraphThread && !presentedThreadId.empty() && - boundGraphThread->id().canonical != presentedThreadId && - !values.hydrationFailed; - - if (!replacementHydrating) { - const std::string draftIdentity = - newThreadDraft || !creationDraftCorrelation.empty() - ? ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation) - : std::string{}; - auto settingsContext = uiAdapter.turnSettings(boundGraphThread, draftIdentity); - if (!settingsContext) { - pendingChrome = true; - schedulePaneCommit(); - return; + bool ShellWidget::Impl::sendRuntimeAction(nodegraph::RuntimeAction action, QString rejection) { + const nodegraph::ChannelSendStatus status = session.sendRuntimeAction(action); + if (!nodegraph::deliveryGuaranteed(status)) { + if (!rejection.isEmpty()) + showNotice(std::move(rejection)); + return false; + } + if (nodegraph::wakeFailed(status)) + showNotice(QStringLiteral("The action was admitted after a worker wake-up failure; bounded " + "fallback delivery is active.")); + return true; } - middleRegion->composer().setTurnSettingsContext( - std::move(*settingsContext)); - } - - if (values.canControl && renderedChrome && !renderedChrome->canControl && boundGraphThread && !values.recoveryOnly) { - hydrateSelectedThreadIfNeeded(boundGraphThread); - } - const bool chromeChanged = !renderedChrome || *renderedChrome != values; - if (!chromeChanged) - return; - - if (!replacementHydrating) { - middleRegion->conversation().setEmptyMessage( - values.recoveryOnly - ? QStringLiteral( - "This thread preserves an unsent prompt. Restore it from " - "the failed prompt card before continuing.") - : boundGraphThread && values.hydrationFailed - ? QStringLiteral("Thread loading failed. Select Reload to retry.") - : boundGraphThread && !values.conversationReadyForDisplay - ? QStringLiteral("Loading conversation…") - : boundGraphThread - ? QStringLiteral("Conversation activity appears here.") - : (newThreadDraft - ? QStringLiteral("Send a message to create this thread.") - : QStringLiteral("Conversation activity appears here."))); - if (boundGraphThread) { - const QString activity = values.lastActivityAt - ? lastActivityText(*values.lastActivityAt) - : QString{}; - const QString status = text(displayStatus(values.status)); - const std::string_view statusToneValue = statusTone(values.status); - const QString tone = - QString::fromLatin1(statusToneValue.data(), statusToneValue.size()); - middleRegion->setThreadHeading(text(values.title), values.tokenUsage.thread, - activity, status, tone); - middleRegion->setThreadWorkspace(text(values.workspace), text(values.workspaceChangeUnavailable), [this, target = boundGraphThread] { - changeWorkspaceDialog(target); - }); - } else { - middleRegion->setThreadHeading(text(values.title), values.tokenUsage.thread); - middleRegion->setThreadWorkspace(text(values.workspace), QStringLiteral("Create a thread before changing its workspace."), {}); + + void ShellWidget::Impl::hydrateSelectedThreadIfNeeded(nodegraph::NodeRef thread) { + if (!thread || boundGraphThread != thread) + return; + auto read = session.nodeGraph().tryRead(); + if (!read) { + QTimer::singleShot(GraphRetryDelayMilliseconds, owner, [this, thread = std::move(thread)]() mutable { + hydrateSelectedThreadIfNeeded(std::move(thread)); + }); + return; + } + if (!read->live(thread)) + return; + const bool recoveryOnly = boolFromValue(valueMember(*read->state(thread), "recoveryOnly")); + read.reset(); + if (recoveryOnly) + return; + nodegraph::NodeAction action{std::move(thread), nodegraph::NodeActionKind::Hydrate, {}, {}, {}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("Thread loading was not admitted; select Reload to retry."))); } - } - renderStatus(values); - overallTokens->setUsage(text(values.tokenUsage.overall.summary), - text(values.tokenUsage.overall.details)); - renderedChrome = values; - ++shellRenderCommits; - owner->setProperty("shellRenderCommits", - static_cast(shellRenderCommits)); -} - -void ShellWidget::Impl::renderStatus(const ShellChromeValues& status) { - const QString connectionText = status.selectedTransport.empty() ? QStringLiteral("Connection") : text(status.selectedTransport); - if (connectionButton->text() != connectionText) - connectionButton->setText(connectionText); - const QString connectionTip = status.retrying ? QStringLiteral("Disconnected, retrying") - : status.connected ? QStringLiteral("Connected bridge transport") - : QStringLiteral("Disconnected bridge transport"); - if (connectionButton->toolTip() != connectionTip) - connectionButton->setToolTip(connectionTip); - connectAction->setEnabled(!status.connected); - disconnectAction->setEnabled(status.connected); - reconnectAction->setEnabled(status.connected); - const QString controllerText = status.role == "controller" ? QStringLiteral("Release control") : QStringLiteral("Claim control"); - if (controllerButton->text() != controllerText) - controllerButton->setText(controllerText); - controllerButton->setEnabled(status.connected); - - const QString requestText = QStringLiteral("Requests (%1)").arg(static_cast(status.totalPending)); - if (requestButton->text() != requestText) - requestButton->setText(requestText); - requestButton->setVisible(status.totalPending != 0); - PendingRequestControls controls; - if (status.attention) { - const PendingRequestDescriptor& request = *status.attention; - const bool replacesTarget = !renderedChrome || !renderedChrome->attention || renderedChrome->attention->target != request.target; - controls = PendingRequestPolicy::controls(request); - QString requestDetail = text(PendingRequestPolicy::detail(request)); - const QString requestStatus = text(PendingRequestPolicy::status(request)); - if (!requestStatus.isEmpty()) - requestDetail += QStringLiteral(" | ") + requestStatus; - middleRegion->composer().setAttentionRequest(text(PendingRequestPolicy::title(request.kind)), - std::move(requestDetail), - controls.positive.has_value(), - controls.positive ? text(controls.positive->label) : QString{}, - controls.negative.has_value(), - controls.negative ? text(controls.negative->label) : QString{}, - replacesTarget); + + nodegraph::NodeRef ShellWidget::Impl::activeTurn() const { + if (!boundGraphThread) + return {}; + auto read = session.nodeGraph().tryRead(); + if (!read || !read->live(boundGraphThread)) + return {}; + nodegraph::NodeRef indexed = read->relatedAt(boundGraphThread, nodegraph::RelationKind::ActiveTurn, 0); + if (indexed && indexed->id().kind == nodegraph::NodeKind::Turn) + return indexed; + return {}; } - middleRegion->composer().setAttentionVisible(status.attention.has_value()); - middleRegion->composer().setAttentionActionEnabled( - controls.directEnabled && controls.positive, controls.directEnabled && controls.negative, controls.reviewEnabled); - - QString globalStatus = QStringLiteral("Ready"); - QString globalTone = QStringLiteral("success"); - if (status.retrying) { - globalStatus = QStringLiteral("Reconnecting"); - globalTone = QStringLiteral("warning"); - } else if (!status.connected) { - globalStatus = QStringLiteral("Offline"); - globalTone = QStringLiteral("danger"); - } else if (status.providerState != "ready") { - globalStatus = status.providerState.empty() ? QStringLiteral("Waiting for provider") : QStringLiteral("Provider unavailable"); - globalTone = status.providerState.empty() ? QStringLiteral("warning") : QStringLiteral("danger"); - } else if (status.totalPending != 0) { - globalStatus = QStringLiteral("Attention required"); - globalTone = QStringLiteral("warning"); + + void ShellWidget::Impl::applyLocalPending(PendingRequestDescriptor& request) { + const auto local = localPendingRequests.find(request.target); + if (local == localPendingRequests.end()) + return; + if (local->second.awaitingResponseAfter && request.responseRevision > *local->second.awaitingResponseAfter) { + localPendingRequests.erase(local); + return; + } + request.retainedSubmission = local->second.submission; + if (local->second.awaitingResponseAfter) + request.availability = PendingRequestAvailability::Submitting; } - setStatusTone(globalStatusDot, globalTone, globalStatusLabel); - setStatusLabelText(globalStatusLabel, globalStatus); - globalStatusLabel->setToolTip(connectionText + QStringLiteral(": ") + connectionTip); - globalStatusDot->setToolTip(globalStatusLabel->toolTip()); - - middleRegion->composer().setActiveTurn(status.activeTurn); - middleRegion->composer().setCanSubmit(status.canControl && (boundGraphThread || newThreadDraft) && - (status.activeTurn || status.threadAdmissionReady)); - middleRegion->composer().setSettingsEnabled(status.canControl && status.threadAdmissionReady && (boundGraphThread || newThreadDraft) && - !status.activeTurn); -} - -std::optional -ShellWidget::Impl::threadSnapshot(std::uint64_t *revision) { - const auto draft = middleRegion->threads().optimisticThread(); - return uiAdapter.threads(boundGraphThread, revision, - &middleRegion->threads().browserOptions(), - draft ? &*draft : nullptr); -} - -void ShellWidget::Impl::beginThreadDraft(NewThreadDraft draft) { - newThreadDraft = draft; - creationDraftCorrelation = - "qt-draft:" + std::to_string(nextCreationDraftSerial++); - selectedGraphThreadId.clear(); - bindGraphPanes({}); - ui::ThreadListRow row; - row.id = DraftThreadId; - row.presentationKey = - ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation); - row.title = draft.name.isEmpty() ? "New thread" : utf8(draft.name); - row.cwd = utf8(draft.workspace); - row.projectId = draft.projectId; - row.sectionId = draft.sectionId; - middleRegion->threads().beginOptimisticThread(row); - if (auto threads = threadSnapshot()) - middleRegion->threads().refresh(*threads); -} - -QStringList ShellWidget::Impl::projectWorkspaceRoots(const std::string& project) { - QStringList choices; - if (!project.empty()) { - if (const auto snapshot = threadSnapshot()) { - const auto found = std::ranges::find(snapshot->projects, project, &ui::ThreadGroup::id); - if (found != snapshot->projects.end()) { - for (const auto& root : found->fields.value("roots", nlohmann::json::array())) { - if (root.is_object() && root.contains("path") && root["path"].is_string()) { - choices.push_back(text(root["path"].get())); - } - } - } + + std::optional ShellWidget::Impl::pendingRequestSummary(bool* busy) { + if (busy) + *busy = false; + std::vector localTargets; + localTargets.reserve(localPendingRequests.size()); + for (const auto& [target, local] : localPendingRequests) { + static_cast(local); + localTargets.push_back(target); + } + if (reviewedRequest) + localTargets.push_back(reviewedRequest); + auto summary = uiAdapter.pendingRequestSummary( + boundGraphThread ? std::string_view(boundGraphThread->id().canonical) : std::string_view{}, localTargets); + if (!summary) { + if (busy) + *busy = true; + return std::nullopt; } + for (PendingRequestDescriptor& request : summary->candidates) + applyLocalPending(request); + std::erase_if(localPendingRequests, [&](const auto& local) { + return std::ranges::none_of(summary->candidates, [&](const auto& request) { + return request.target == local.first; + }); + }); + return summary; } - return choices; -} - -void ShellWidget::Impl::changeWorkspaceDialog(const nodegraph::NodeRef& thread) { - const auto row = uiAdapter.threadRow(thread); - if (!row || !row->workspaceChangeUnavailable.empty()) { - showNotice(row ? text(row->workspaceChangeUnavailable) : QStringLiteral("Thread state is unavailable.")); - } else { - FileSelectionDialog dialog( - text(row->cwd), owner, text(row->title), projectWorkspaceRoots(row->projectId), session.filesystemAccess()); - if (dialog.exec() == QDialog::Accepted && dialog.selectedDirectory() != text(row->cwd)) { - nodegraph::NodeAction action{ - thread, nodegraph::NodeActionKind::ChangeWorkspace, {}, {}, {{"cwd", utf8(dialog.selectedDirectory())}}, {}}; - static_cast(sendNodeAction(std::move(action), QStringLiteral("Workspace change was not admitted; try again."))); + + std::optional ShellWidget::Impl::pendingRequestPage(const ui::InspectorRowRequest& request, bool* busy) { + if (busy) + *busy = false; + auto page = uiAdapter.pendingRequests(request); + if (!page) { + if (busy) + *busy = true; + return std::nullopt; } + const auto apply = [this](ui::InspectorRow& row) { + if (auto* pending = std::get_if(&row.value)) + applyLocalPending(*pending); + }; + for (ui::InspectorRow& row : page->rows) + apply(row); + if (page->focused) + apply(*page->focused); + return page; } -} - -void ShellWidget::Impl::beginNewThreadDialog(std::string project, std::string section) { - if (!creationDraftCorrelation.empty()) { - showNotice(QStringLiteral("A new-thread draft is already active. Select another thread to abandon it before starting another."), - false); - } else { - const auto choices = projectWorkspaceRoots(project); - NewThreadDraft initial; - initial.workspace = choices.size() == 1 ? choices.front() : QString{}; - NewThreadDialog dialog(initial, NewThreadDialog::Purpose::Create, owner, choices, [this] { - return session.filesystemAccess(); - }); - if (dialog.exec() == QDialog::Accepted) { - NewThreadDraft draft = dialog.draft(); - draft.projectId = std::move(project); - draft.sectionId = std::move(section); - beginThreadDraft(std::move(draft)); - middleRegion->composer().clearDraft(); - middleRegion->composer().promptEditor()->setFocus(); + + std::optional ShellWidget::Impl::pendingRequest(const nodegraph::NodeRef& target) { + bool busy = false; + auto request = uiAdapter.pendingRequest(target, &busy); + if (!request) { + showNotice(busy ? QStringLiteral("Request state is busy; no response was sent.") + : QStringLiteral("The pending request is no longer actionable.")); + return std::nullopt; } + applyLocalPending(*request); + return request; } -} - -std::optional -ShellWidget::Impl::suggestedForkDraft(const nodegraph::NodeRef &thread) const { - if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - const std::optional source = uiAdapter.threadRow(thread); - if (!source) - return std::nullopt; - const std::optional snapshot = uiAdapter.threads({}); - if (!snapshot) - return std::nullopt; - - std::vector titles; - collectThreadTitles(snapshot->roots, titles); - NewThreadDraft draft; - draft.workspace = text(source->cwd); - draft.name = text(suggestForkName(source->title, titles)); - - if (auto read = session.nodeGraph().tryRead(); read && read->live(thread)) { - const std::shared_ptr state = - read->state(thread); - draft.baseInstructions = - text(exactStringFromValue(valueMember(*state, "baseInstructions"))); - draft.developerInstructions = text( - exactStringFromValue(valueMember(*state, "developerInstructions"))); - draft.ephemeral = boolFromValue(valueMember(*state, "ephemeral")); - } - return draft; -} - -void ShellWidget::Impl::forkThread(const nodegraph::NodeRef& thread, - NewThreadDraft draft, - bool includeOptions, - const nodegraph::NodeRef& turn) { - if (!thread || thread->id().kind != nodegraph::NodeKind::Thread || !uiAdapter.threadRow(thread)) { - showNotice(QStringLiteral("The source thread is no longer available; no fork was sent.")); - } else { - nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Fork, {}, {}, {}, {}}; - if (turn) { + + void ShellWidget::Impl::render(const ui::PendingRequestsSummary* projectedRequests) { + ShellChromeValues values; + values.title = "Select a thread"; + values.workspace = "No workspace"; + + { auto read = session.nodeGraph().tryRead(); - if (!read || !read->live(turn) || read->parent(turn) != thread) { - showNotice(QStringLiteral("The selected turn is no longer available; no fork was sent.")); - } else { - action.payload.emplace("lastTurnId", nodegraph::protocolCanonicalId(*read->state(turn), turn)); + if (!read) { + pendingChrome = true; + schedulePaneCommit(); + return; + } + if (const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"})) { + const auto state = read->state(connection); + const std::string transport = exactStringFromValue(valueMember(*state, "transportState")); + values.connected = state->status == nodegraph::NodeStatus::Connected; + values.retrying = transport == "retrying" || transport == "connecting"; + values.role = exactStringFromValue(valueMember(*state, "role")); + values.providerState = exactStringFromValue(valueMember(*state, "providerState")); + values.canControl = values.connected && values.providerState == "ready" && values.role == "controller"; + if (const nodegraph::Value* settings = valueMember(*state, "settings")) { + if (const auto* object = settings->asObject()) { + const std::string selected = exactStringFromValue(valueMember(*object, "selected")); + const nodegraph::Value* available = valueMember(*object, "available"); + if (available && available->asArray()) { + for (const nodegraph::Value& entry : *available->asArray()) { + const auto* transportEntry = entry.asObject(); + if (transportEntry && exactStringFromValue(valueMember(*transportEntry, "key")) == selected) { + values.selectedTransport = exactStringFromValue(valueMember(*transportEntry, "label")); + break; + } + } + } + } + } + } + + nodegraph::NodeRef selected = boundGraphThread; + if (selected && !read->live(selected)) + selected.reset(); + values.tokenUsage = uiAdapter.tokenUsage(selected, *read); + if (selected) { + const auto state = read->state(selected); + values.title = exactStringFromValue(valueMember(*state, "name")); + if (values.title.empty()) + values.title = exactStringFromValue(valueMember(*state, "title")); + if (values.title.empty()) + values.title = "Untitled thread"; + values.workspace = exactStringFromValue(valueMember(*state, "cwd")); + values.workspaceChangeUnavailable = nodegraph::threadWorkspaceChangeUnavailable(*read, selected); + values.status = statusFromState(*state); + values.recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); + const std::string hydrationState = exactStringFromValue(valueMember(*state, "hydrationState")); + const bool local = boolFromValue(valueMember(*state, "local")); + values.conversationReadyForDisplay = hydrationState == "ready" || local || values.recoveryOnly; + values.hydrationFailed = hydrationState == "failed"; + values.threadAdmissionReady = !values.recoveryOnly && hydrationState != "loading" && hydrationState != "failed" && + (state->status != nodegraph::NodeStatus::NotLoaded || hydrationState == "ready"); + for (const auto& operation : read->related(selected, nodegraph::RelationKind::PendingOperation)) { + if (exactStringFromValue(valueMember(*read->state(operation), "method")) == "thread/revert") { + values.threadAdmissionReady = false; + } + } + values.lastActivityAt = signedIntegerFromValue(valueMember(*state, "lastActivityAt")); + for (const std::string_view field : {std::string_view("recencyAt"), + std::string_view("updatedAt"), + std::string_view("localActivityAt"), + std::string_view("localPromptActivityAt")}) { + const std::optional timestamp = signedIntegerFromValue(valueMember(*state, field)); + if (timestamp && (!values.lastActivityAt || *timestamp > *values.lastActivityAt)) + values.lastActivityAt = timestamp; + } + nodegraph::NodeRef turn = read->relatedAt(selected, nodegraph::RelationKind::ActiveTurn, 0); + values.activeTurn = turn && turn->id().kind == nodegraph::NodeKind::Turn; + } else if (newThreadDraft) { + values.title = newThreadDraft->name.trimmed().isEmpty() ? "New thread" : utf8(newThreadDraft->name.trimmed()); + values.workspace = utf8(newThreadDraft->workspace); } } - const QString requestedName = draft.name.trimmed(); - if (!draft.ephemeral && !requestedName.isEmpty()) { - action.payload.emplace("requestedName", utf8(requestedName)); - } - if (includeOptions) { - const QString workspace = draft.workspace.trimmed(); - if (!workspace.isEmpty()) { - action.payload.emplace("cwd", utf8(workspace)); + + std::optional ownedRequests; + if (!projectedRequests) { + ownedRequests = pendingRequestSummary(); + if (!ownedRequests) { + pendingChrome = true; + schedulePaneCommit(); + return; } - const QString baseInstructions = draft.baseInstructions.trimmed(); - if (!baseInstructions.isEmpty()) { - action.payload.emplace("baseInstructions", utf8(baseInstructions)); + projectedRequests = &*ownedRequests; + } + values.totalPending = projectedRequests->total; + if (reviewSubmit) { + const auto request = std::ranges::find(projectedRequests->candidates, reviewedRequest, &PendingRequestDescriptor::target); + const bool live = request != projectedRequests->candidates.end(); + reviewSubmit->setEnabled(live && request->availability == PendingRequestAvailability::Actionable); + reviewSubmit->setToolTip(live ? text(PendingRequestPolicy::status(*request)) : QStringLiteral("This request has ended.")); + reviewSubmit->setText(live ? QStringLiteral("Submit") : QStringLiteral("Resolved")); + } + const std::optional attention = PendingRequestPolicy::attentionIndex( + projectedRequests->candidates, boundGraphThread ? std::string_view(boundGraphThread->id().canonical) : std::string_view{}); + if (attention && *attention < projectedRequests->candidates.size()) + values.attention = projectedRequests->candidates[*attention]; + const std::string& presentedThreadId = middleRegion->conversation().presentedThreadId(); + const bool replacementHydrating = boundGraphThread && !presentedThreadId.empty() && + boundGraphThread->id().canonical != presentedThreadId && !values.hydrationFailed; + + if (!replacementHydrating) { + const std::string draftIdentity = newThreadDraft || !creationDraftCorrelation.empty() + ? ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation) + : std::string{}; + auto settingsContext = uiAdapter.turnSettings(boundGraphThread, draftIdentity); + if (!settingsContext) { + pendingChrome = true; + schedulePaneCommit(); + return; } - const QString developerInstructions = draft.developerInstructions.trimmed(); - if (!developerInstructions.isEmpty()) { - action.payload.emplace("developerInstructions", utf8(developerInstructions)); + middleRegion->composer().setTurnSettingsContext(std::move(*settingsContext)); + } + + if (values.canControl && renderedChrome && !renderedChrome->canControl && boundGraphThread && !values.recoveryOnly) { + hydrateSelectedThreadIfNeeded(boundGraphThread); + } + const bool chromeChanged = !renderedChrome || *renderedChrome != values; + if (!chromeChanged) + return; + + if (!replacementHydrating) { + middleRegion->conversation().setEmptyMessage( + values.recoveryOnly ? QStringLiteral("This thread preserves an unsent prompt. Restore it from " + "the failed prompt card before continuing.") + : boundGraphThread && values.hydrationFailed ? QStringLiteral("Thread loading failed. Select Reload to retry.") + : boundGraphThread && !values.conversationReadyForDisplay ? QStringLiteral("Loading conversation…") + : boundGraphThread ? QStringLiteral("Conversation activity appears here.") + : (newThreadDraft ? QStringLiteral("Send a message to create this thread.") + : QStringLiteral("Conversation activity appears here."))); + if (boundGraphThread) { + const QString activity = values.lastActivityAt ? lastActivityText(*values.lastActivityAt) : QString{}; + const QString status = text(displayStatus(values.status)); + const std::string_view statusToneValue = statusTone(values.status); + const QString tone = QString::fromLatin1(statusToneValue.data(), statusToneValue.size()); + middleRegion->setThreadHeading(text(values.title), values.tokenUsage.thread, activity, status, tone); + middleRegion->setThreadWorkspace( + text(values.workspace), text(values.workspaceChangeUnavailable), [this, target = boundGraphThread] { + changeWorkspaceDialog(target); + }); + } else { + middleRegion->setThreadHeading(text(values.title), values.tokenUsage.thread); + middleRegion->setThreadWorkspace( + text(values.workspace), QStringLiteral("Create a thread before changing its workspace."), {}); } - action.payload.emplace("ephemeral", draft.ephemeral); } - if (!turn || action.payload.contains("lastTurnId")) { - static_cast(sendNodeAction(std::move(action), QStringLiteral("Thread fork was not admitted; try again."))); + renderStatus(values); + overallTokens->setUsage(text(values.tokenUsage.overall.summary), text(values.tokenUsage.overall.details)); + renderedChrome = values; + ++shellRenderCommits; + owner->setProperty("shellRenderCommits", static_cast(shellRenderCommits)); + } + + void ShellWidget::Impl::renderStatus(const ShellChromeValues& status) { + const QString connectionText = status.selectedTransport.empty() ? QStringLiteral("Connection") : text(status.selectedTransport); + if (connectionButton->text() != connectionText) + connectionButton->setText(connectionText); + const QString connectionTip = status.retrying ? QStringLiteral("Disconnected, retrying") + : status.connected ? QStringLiteral("Connected bridge transport") + : QStringLiteral("Disconnected bridge transport"); + if (connectionButton->toolTip() != connectionTip) + connectionButton->setToolTip(connectionTip); + connectAction->setEnabled(!status.connected); + disconnectAction->setEnabled(status.connected); + reconnectAction->setEnabled(status.connected); + const QString controllerText = status.role == "controller" ? QStringLiteral("Release control") : QStringLiteral("Claim control"); + if (controllerButton->text() != controllerText) + controllerButton->setText(controllerText); + controllerButton->setEnabled(status.connected); + + const QString requestText = QStringLiteral("Requests (%1)").arg(static_cast(status.totalPending)); + if (requestButton->text() != requestText) + requestButton->setText(requestText); + requestButton->setVisible(status.totalPending != 0); + PendingRequestControls controls; + if (status.attention) { + const PendingRequestDescriptor& request = *status.attention; + const bool replacesTarget = + !renderedChrome || !renderedChrome->attention || renderedChrome->attention->target != request.target; + controls = PendingRequestPolicy::controls(request); + QString requestDetail = text(PendingRequestPolicy::detail(request)); + const QString requestStatus = text(PendingRequestPolicy::status(request)); + if (!requestStatus.isEmpty()) + requestDetail += QStringLiteral(" | ") + requestStatus; + middleRegion->composer().setAttentionRequest(text(PendingRequestPolicy::title(request.kind)), + std::move(requestDetail), + controls.positive.has_value(), + controls.positive ? text(controls.positive->label) : QString{}, + controls.negative.has_value(), + controls.negative ? text(controls.negative->label) : QString{}, + replacesTarget); + } + middleRegion->composer().setAttentionVisible(status.attention.has_value()); + middleRegion->composer().setAttentionActionEnabled( + controls.directEnabled && controls.positive, controls.directEnabled && controls.negative, controls.reviewEnabled); + + QString globalStatus = QStringLiteral("Ready"); + QString globalTone = QStringLiteral("success"); + if (status.retrying) { + globalStatus = QStringLiteral("Reconnecting"); + globalTone = QStringLiteral("warning"); + } else if (!status.connected) { + globalStatus = QStringLiteral("Offline"); + globalTone = QStringLiteral("danger"); + } else if (status.providerState != "ready") { + globalStatus = status.providerState.empty() ? QStringLiteral("Waiting for provider") : QStringLiteral("Provider unavailable"); + globalTone = status.providerState.empty() ? QStringLiteral("warning") : QStringLiteral("danger"); + } else if (status.totalPending != 0) { + globalStatus = QStringLiteral("Attention required"); + globalTone = QStringLiteral("warning"); } + setStatusTone(globalStatusDot, globalTone, globalStatusLabel); + setStatusLabelText(globalStatusLabel, globalStatus); + globalStatusLabel->setToolTip(connectionText + QStringLiteral(": ") + connectionTip); + globalStatusDot->setToolTip(globalStatusLabel->toolTip()); + + middleRegion->composer().setActiveTurn(status.activeTurn); + middleRegion->composer().setCanSubmit(status.canControl && (boundGraphThread || newThreadDraft) && + (status.activeTurn || status.threadAdmissionReady)); + middleRegion->composer().setSettingsEnabled(status.canControl && status.threadAdmissionReady && + (boundGraphThread || newThreadDraft) && !status.activeTurn); + } + + std::optional ShellWidget::Impl::threadSnapshot(std::uint64_t* revision) { + const auto draft = middleRegion->threads().optimisticThread(); + return uiAdapter.threads(boundGraphThread, revision, &middleRegion->threads().browserOptions(), draft ? &*draft : nullptr); } -} -void ShellWidget::Impl::beginForkThreadDialog(nodegraph::NodeRef thread, nodegraph::NodeRef turn) { - const auto draft = suggestedForkDraft(thread); - if (!draft) { - showNotice(QStringLiteral("Thread state is busy; try Fork with options again.")); - } else { + void ShellWidget::Impl::beginThreadDraft(NewThreadDraft draft) { + newThreadDraft = draft; + creationDraftCorrelation = "qt-draft:" + std::to_string(nextCreationDraftSerial++); + selectedGraphThreadId.clear(); + bindGraphPanes({}); + ui::ThreadListRow row; + row.id = DraftThreadId; + row.presentationKey = ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation); + row.title = draft.name.isEmpty() ? "New thread" : utf8(draft.name); + row.cwd = utf8(draft.workspace); + row.projectId = draft.projectId; + row.sectionId = draft.sectionId; + middleRegion->threads().beginOptimisticThread(row); + if (auto threads = threadSnapshot()) + middleRegion->threads().refresh(*threads); + } + + QStringList ShellWidget::Impl::projectWorkspaceRoots(const std::string& project) { + QStringList choices; + if (!project.empty()) { + if (const auto snapshot = threadSnapshot()) { + const auto found = std::ranges::find(snapshot->projects, project, &ui::ThreadGroup::id); + if (found != snapshot->projects.end()) { + for (const auto& root : found->fields.value("roots", nlohmann::json::array())) { + if (root.is_object() && root.contains("path") && root["path"].is_string()) { + choices.push_back(text(root["path"].get())); + } + } + } + } + } + return choices; + } + + void ShellWidget::Impl::changeWorkspaceDialog(const nodegraph::NodeRef& thread) { const auto row = uiAdapter.threadRow(thread); - NewThreadDialog dialog( - *draft, NewThreadDialog::Purpose::Fork, owner, projectWorkspaceRoots(row ? row->projectId : std::string{}), [this] { + if (!row || !row->workspaceChangeUnavailable.empty()) { + showNotice(row ? text(row->workspaceChangeUnavailable) : QStringLiteral("Thread state is unavailable.")); + } else { + FileSelectionDialog dialog( + text(row->cwd), owner, text(row->title), projectWorkspaceRoots(row->projectId), session.filesystemAccess()); + if (dialog.exec() == QDialog::Accepted && dialog.selectedDirectory() != text(row->cwd)) { + nodegraph::NodeAction action{ + thread, nodegraph::NodeActionKind::ChangeWorkspace, {}, {}, {{"cwd", utf8(dialog.selectedDirectory())}}, {}}; + static_cast(sendNodeAction(std::move(action), QStringLiteral("Workspace change was not admitted; try again."))); + } + } + } + + void ShellWidget::Impl::beginNewThreadDialog(std::string project, std::string section) { + if (!creationDraftCorrelation.empty()) { + showNotice(QStringLiteral("A new-thread draft is already active. Select another thread to abandon it before starting another."), + false); + } else { + const auto choices = projectWorkspaceRoots(project); + NewThreadDraft initial; + initial.workspace = choices.size() == 1 ? choices.front() : QString{}; + NewThreadDialog dialog(initial, NewThreadDialog::Purpose::Create, owner, choices, [this] { return session.filesystemAccess(); }); - if (dialog.exec() == QDialog::Accepted) { - auto selected = dialog.draft(); - if (selected.name.trimmed().isEmpty()) { - selected.name = draft->name; + if (dialog.exec() == QDialog::Accepted) { + NewThreadDraft draft = dialog.draft(); + draft.projectId = std::move(project); + draft.sectionId = std::move(section); + beginThreadDraft(std::move(draft)); + middleRegion->composer().clearDraft(); + middleRegion->composer().promptEditor()->setFocus(); } - forkThread(thread, std::move(selected), true, turn); } } -} - -void ShellWidget::Impl::renameThreadDialog(const nodegraph::NodeRef &thread) { - if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) - return; - std::string currentName; - if (auto read = session.nodeGraph().tryRead()) { - if (!read->live(thread)) - return; - const auto state = read->state(thread); - currentName = exactStringFromValue(valueMember(*state, "name")); - if (currentName.empty()) - currentName = exactStringFromValue(valueMember(*state, "title")); - } else { - showNotice(QStringLiteral("Thread state is busy; try again.")); - return; - } - const auto retained = retainedRenames.find(thread.get()); - const QString initialName = retained == retainedRenames.end() - ? text(currentName) - : retained->second.second; - bool accepted = false; - const QString name = - QInputDialog::getText(owner, QStringLiteral("Rename thread"), - QStringLiteral("Name"), QLineEdit::Normal, - initialName, &accepted) - .trimmed(); - if (!accepted || name.isEmpty()) - return; - { - auto read = session.nodeGraph().tryRead(); - if (!read) { - showNotice( - QStringLiteral("Thread state is busy; the rename was not sent.")); - return; - } - if (!read->live(thread)) { - retainedRenames.erase(thread.get()); - showNotice(QStringLiteral( - "The thread was removed while Rename was open; no rename was sent.")); - return; - } - } - nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Rename, - {}, {}, {}, {}}; - action.payload.emplace("name", utf8(name)); - const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); - if (!nodegraph::deliveryGuaranteed(status)) { - retainedRenames.insert_or_assign(thread.get(), std::pair{thread, name}); - showNotice(QStringLiteral( - "Rename request was not admitted. Reopen Rename to recover the " - "name you entered.")); - return; - } - retainedRenames.erase(thread.get()); - if (nodegraph::wakeFailed(status)) - showNotice(QStringLiteral( - "The rename was admitted after a worker wake-up failure; bounded " - "fallback delivery is active.")); -} - -void ShellWidget::Impl::showTurnMenu(nodegraph::NodeRef item, QPoint position) { - nodegraph::NodeRef turn, thread; - std::string reason = "Conversation state is busy; try again."; - if (auto read = session.nodeGraph().tryRead()) { - if (item && read->live(item)) { - turn = read->parent(item); - thread = turn ? read->parent(turn) : nodegraph::NodeRef{}; - } - reason = nodegraph::threadRevertUnavailable(*read, turn); + + std::optional ShellWidget::Impl::suggestedForkDraft(const nodegraph::NodeRef& thread) const { + if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + const std::optional source = uiAdapter.threadRow(thread); + if (!source) + return std::nullopt; + const std::optional snapshot = uiAdapter.threads({}); + if (!snapshot) + return std::nullopt; + + std::vector titles; + collectThreadTitles(snapshot->roots, titles); + NewThreadDraft draft; + draft.workspace = text(source->cwd); + draft.name = text(suggestForkName(source->title, titles)); + + if (auto read = session.nodeGraph().tryRead(); read && read->live(thread)) { + const std::shared_ptr state = read->state(thread); + draft.baseInstructions = text(exactStringFromValue(valueMember(*state, "baseInstructions"))); + draft.developerInstructions = text(exactStringFromValue(valueMember(*state, "developerInstructions"))); + draft.ephemeral = boolFromValue(valueMember(*state, "ephemeral")); + } + return draft; } - QMenu menu(owner); - menu.setToolTipsVisible(true); - auto* quick = menu.addAction(QStringLiteral("Quick fork from here")); - auto* options = menu.addAction(QStringLiteral("Fork from here with options…")); - for (auto* action : {quick, options}) { - action->setEnabled(thread && renderedChrome && renderedChrome->canControl); + + void ShellWidget::Impl::forkThread(const nodegraph::NodeRef& thread, + NewThreadDraft draft, + bool includeOptions, + const nodegraph::NodeRef& turn) { + if (!thread || thread->id().kind != nodegraph::NodeKind::Thread || !uiAdapter.threadRow(thread)) { + showNotice(QStringLiteral("The source thread is no longer available; no fork was sent.")); + } else { + nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Fork, {}, {}, {}, {}}; + if (turn) { + auto read = session.nodeGraph().tryRead(); + if (!read || !read->live(turn) || read->parent(turn) != thread) { + showNotice(QStringLiteral("The selected turn is no longer available; no fork was sent.")); + } else { + action.payload.emplace("lastTurnId", nodegraph::protocolCanonicalId(*read->state(turn), turn)); + } + } + const QString requestedName = draft.name.trimmed(); + if (!draft.ephemeral && !requestedName.isEmpty()) { + action.payload.emplace("requestedName", utf8(requestedName)); + } + if (includeOptions) { + const QString workspace = draft.workspace.trimmed(); + if (!workspace.isEmpty()) { + action.payload.emplace("cwd", utf8(workspace)); + } + const QString baseInstructions = draft.baseInstructions.trimmed(); + if (!baseInstructions.isEmpty()) { + action.payload.emplace("baseInstructions", utf8(baseInstructions)); + } + const QString developerInstructions = draft.developerInstructions.trimmed(); + if (!developerInstructions.isEmpty()) { + action.payload.emplace("developerInstructions", utf8(developerInstructions)); + } + action.payload.emplace("ephemeral", draft.ephemeral); + } + if (!turn || action.payload.contains("lastTurnId")) { + static_cast(sendNodeAction(std::move(action), QStringLiteral("Thread fork was not admitted; try again."))); + } + } } - menu.addSeparator(); - QAction* remove = menu.addAction(QStringLiteral("Remove this turn and all later turns…")); - remove->setEnabled(reason.empty()); - remove->setToolTip(text(reason)); - const auto* selected = menu.exec(position); - if (selected == options) { - beginForkThreadDialog(thread, turn); - } else if (selected == quick) { + + void ShellWidget::Impl::beginForkThreadDialog(nodegraph::NodeRef thread, nodegraph::NodeRef turn) { const auto draft = suggestedForkDraft(thread); - if (draft) { - forkThread(thread, *draft, false, turn); + if (!draft) { + showNotice(QStringLiteral("Thread state is busy; try Fork with options again.")); } else { - showNotice(QStringLiteral("Thread state is busy; try Quick fork again.")); - } - } else if (selected == remove && reason.empty()) { - QMessageBox confirmation( - QMessageBox::Warning, - QStringLiteral("Remove conversation history?"), - QStringLiteral("This will permanently remove the selected turn and every later turn from this conversation. Earlier turns will " - "remain. File changes and commands already performed will not be undone."), - QMessageBox::NoButton, - owner); - auto* cancel = confirmation.addButton(QStringLiteral("Cancel"), QMessageBox::RejectRole); - auto* accepted = confirmation.addButton(QStringLiteral("Remove turns"), QMessageBox::DestructiveRole); - confirmation.setDefaultButton(cancel); - confirmation.setEscapeButton(cancel); - confirmation.exec(); - if (confirmation.clickedButton() == accepted) { - reason = "Conversation state is busy; try again."; - if (auto read = session.nodeGraph().tryRead()) { - reason = nodegraph::threadRevertUnavailable(*read, turn); + const auto row = uiAdapter.threadRow(thread); + NewThreadDialog dialog( + *draft, NewThreadDialog::Purpose::Fork, owner, projectWorkspaceRoots(row ? row->projectId : std::string{}), [this] { + return session.filesystemAccess(); + }); + if (dialog.exec() == QDialog::Accepted) { + auto selected = dialog.draft(); + if (selected.name.trimmed().isEmpty()) { + selected.name = draft->name; + } + forkThread(thread, std::move(selected), true, turn); + } + } + } + + void ShellWidget::Impl::renameThreadDialog(const nodegraph::NodeRef& thread) { + if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) + return; + std::string currentName; + if (auto read = session.nodeGraph().tryRead()) { + if (!read->live(thread)) + return; + const auto state = read->state(thread); + currentName = exactStringFromValue(valueMember(*state, "name")); + if (currentName.empty()) + currentName = exactStringFromValue(valueMember(*state, "title")); + } else { + showNotice(QStringLiteral("Thread state is busy; try again.")); + return; + } + const auto retained = retainedRenames.find(thread.get()); + const QString initialName = retained == retainedRenames.end() ? text(currentName) : retained->second.second; + bool accepted = false; + const QString name = + QInputDialog::getText(owner, QStringLiteral("Rename thread"), QStringLiteral("Name"), QLineEdit::Normal, initialName, &accepted) + .trimmed(); + if (!accepted || name.isEmpty()) + return; + { + auto read = session.nodeGraph().tryRead(); + if (!read) { + showNotice(QStringLiteral("Thread state is busy; the rename was not sent.")); + return; + } + if (!read->live(thread)) { + retainedRenames.erase(thread.get()); + showNotice(QStringLiteral("The thread was removed while Rename was open; no rename was sent.")); + return; + } + } + nodegraph::NodeAction action{thread, nodegraph::NodeActionKind::Rename, {}, {}, {}, {}}; + action.payload.emplace("name", utf8(name)); + const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); + if (!nodegraph::deliveryGuaranteed(status)) { + retainedRenames.insert_or_assign(thread.get(), std::pair{thread, name}); + showNotice(QStringLiteral("Rename request was not admitted. Reopen Rename to recover the " + "name you entered.")); + return; + } + retainedRenames.erase(thread.get()); + if (nodegraph::wakeFailed(status)) + showNotice(QStringLiteral("The rename was admitted after a worker wake-up failure; bounded " + "fallback delivery is active.")); + } + + void ShellWidget::Impl::showTurnMenu(nodegraph::NodeRef item, QPoint position) { + nodegraph::NodeRef turn, thread; + std::string reason = "Conversation state is busy; try again."; + if (auto read = session.nodeGraph().tryRead()) { + if (item && read->live(item)) { + turn = read->parent(item); + thread = turn ? read->parent(turn) : nodegraph::NodeRef{}; } - if (reason.empty()) { - static_cast(sendNodeAction({turn, nodegraph::NodeActionKind::RevertTurn, {}, {}, {}, {}}, - QStringLiteral("History removal was not admitted; try again."))); + reason = nodegraph::threadRevertUnavailable(*read, turn); + } + QMenu menu(owner); + menu.setToolTipsVisible(true); + auto* quick = menu.addAction(QStringLiteral("Quick fork from here")); + auto* options = menu.addAction(QStringLiteral("Fork from here with options…")); + for (auto* action : {quick, options}) { + action->setEnabled(thread && renderedChrome && renderedChrome->canControl); + } + menu.addSeparator(); + QAction* remove = menu.addAction(QStringLiteral("Remove this turn and all later turns…")); + remove->setEnabled(reason.empty()); + remove->setToolTip(text(reason)); + const auto* selected = menu.exec(position); + if (selected == options) { + beginForkThreadDialog(thread, turn); + } else if (selected == quick) { + const auto draft = suggestedForkDraft(thread); + if (draft) { + forkThread(thread, *draft, false, turn); + } else { + showNotice(QStringLiteral("Thread state is busy; try Quick fork again.")); + } + } else if (selected == remove && reason.empty()) { + QMessageBox confirmation( + QMessageBox::Warning, + QStringLiteral("Remove conversation history?"), + QStringLiteral( + "This will permanently remove the selected turn and every later turn from this conversation. Earlier turns will " + "remain. File changes and commands already performed will not be undone."), + QMessageBox::NoButton, + owner); + auto* cancel = confirmation.addButton(QStringLiteral("Cancel"), QMessageBox::RejectRole); + auto* accepted = confirmation.addButton(QStringLiteral("Remove turns"), QMessageBox::DestructiveRole); + confirmation.setDefaultButton(cancel); + confirmation.setEscapeButton(cancel); + confirmation.exec(); + if (confirmation.clickedButton() == accepted) { + reason = "Conversation state is busy; try again."; + if (auto read = session.nodeGraph().tryRead()) { + reason = nodegraph::threadRevertUnavailable(*read, turn); + } + if (reason.empty()) { + static_cast(sendNodeAction({turn, nodegraph::NodeActionKind::RevertTurn, {}, {}, {}, {}}, + QStringLiteral("History removal was not admitted; try again."))); + } else { + showNotice(text(reason)); + } + } + } + } + + void ShellWidget::Impl::confirmDeleteThread(const nodegraph::NodeRef& thread) { + if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) + return; + if (QMessageBox::question(owner, + QStringLiteral("Delete thread"), + QStringLiteral("Delete the selected thread?"), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel) != QMessageBox::Yes) + return; + if (!uiAdapter.threadRow(thread)) { + showNotice(QStringLiteral("The thread is no longer available; no delete was sent.")); + return; + } + static_cast(sendNodeAction({thread, nodegraph::NodeActionKind::Delete, {}, {}, {}, {}}, + QStringLiteral("Delete request was not admitted; try again."))); + } + + bool ShellWidget::Impl::submitPrompt(QString prompt, std::vector attachments) { + if (prompt.trimmed().isEmpty() && attachments.empty()) + return false; + TurnSettingsPolicy& settings = middleRegion->composer().turnSettings(); + std::vector ownedAttachments; + ownedAttachments.reserve(attachments.size()); + for (AttachmentDraft& attachment : attachments) { + ownedAttachments.push_back( + {std::move(attachment.path), std::move(attachment.name), std::move(attachment.mimeType), std::nullopt}); + } + + bool admitted = false; + const std::optional visible = middleRegion->threads().visiblySelectedThread(); + nodegraph::NodeRef target = visible && visible->target == boundGraphThread ? visible->target : nodegraph::NodeRef{}; + const bool visibleDraft = visible && !visible->target && visible->id == DraftThreadId && + visible->presentationKey == ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation); + if (target) { + QString graphRejection; + if (auto read = session.nodeGraph().tryRead()) { + if (!read->live(target)) { + graphRejection = QStringLiteral("The selected thread is no longer available. Your " + "message was not sent."); + } else { + const auto state = read->state(target); + const std::string hydration = exactStringFromValue(valueMember(*state, "hydrationState")); + const nodegraph::NodeRef turn = read->relatedAt(target, nodegraph::RelationKind::ActiveTurn, 0); + const bool steeringKnownActiveTurn = turn && turn->id().kind == nodegraph::NodeKind::Turn; + if (!steeringKnownActiveTurn && (hydration == "loading" || hydration == "failed" || + (state->status == nodegraph::NodeStatus::NotLoaded && hydration != "ready"))) { + const std::string detail = exactStringFromValue(valueMember(*state, "hydrationError")); + graphRejection = text(detail.empty() ? "This thread must finish loading before sending. Your " + "draft is still available." + : detail + ". Reload the thread; your draft is still available."); + } + } } else { - showNotice(text(reason)); + graphRejection = QStringLiteral("Thread state is busy. Your draft is still available; try again."); + } + // The graph read guard above is gone before any QWidget is touched. + if (!graphRejection.isEmpty()) { + showNotice(std::move(graphRejection)); + return false; + } + auto settingsContext = uiAdapter.turnSettings(target); + if (!settingsContext) { + showNotice(QStringLiteral("Thread settings are busy. Your message was not sent; try again.")); + return false; } + middleRegion->composer().setTurnSettingsContext(std::move(*settingsContext)); + nodegraph::NodeAction action{target, nodegraph::NodeActionKind::SubmitPrompt, {}, {}, {}, {}}; + action.promptText = utf8(prompt); + action.attachments = std::move(ownedAttachments); + action.payload = objectFromJson(settings.startOptions(TurnSettingsScope::Turn)); + admitted = sendNodeAction(std::move(action), QStringLiteral("Your message was not sent; the worker queue is full.")); + } else if (visibleDraft && newThreadDraft) { + auto settingsContext = uiAdapter.turnSettings({}, ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation)); + if (!settingsContext) { + showNotice(QStringLiteral("Thread settings are busy. Your message was not sent; try again.")); + return false; + } + middleRegion->composer().setTurnSettingsContext(std::move(*settingsContext)); + nodegraph::RuntimeAction action; + action.kind = nodegraph::RuntimeActionKind::CreateThread; + action.correlation = creationDraftCorrelation; + action.promptText = utf8(prompt); + action.attachments = std::move(ownedAttachments); + nodegraph::Value::Object threadStart = objectFromJson(settings.startOptions(TurnSettingsScope::Thread)); + threadStart.insert_or_assign("cwd", utf8(newThreadDraft->workspace)); + if (!newThreadDraft->projectId.empty()) + threadStart.insert_or_assign("projectId", newThreadDraft->projectId); + if (!newThreadDraft->sectionId.empty()) + action.payload.insert_or_assign("sectionId", newThreadDraft->sectionId); + if (!newThreadDraft->ephemeral && !newThreadDraft->name.trimmed().isEmpty()) + action.payload.insert_or_assign("requestedName", utf8(newThreadDraft->name)); + if (!newThreadDraft->baseInstructions.isEmpty()) + threadStart.insert_or_assign("baseInstructions", utf8(newThreadDraft->baseInstructions)); + if (!newThreadDraft->developerInstructions.isEmpty()) + threadStart.insert_or_assign("developerInstructions", utf8(newThreadDraft->developerInstructions)); + if (newThreadDraft->ephemeral) + threadStart.insert_or_assign("ephemeral", true); + action.payload.insert_or_assign("threadStart", nodegraph::Value(std::move(threadStart))); + action.payload.insert_or_assign("turnStart", nodegraph::Value(objectFromJson(settings.startOptions(TurnSettingsScope::Turn)))); + admitted = sendRuntimeAction(std::move(action), QStringLiteral("Your message was not sent; the worker queue is full.")); + if (admitted) + newThreadDraft.reset(); + } else { + showNotice(QStringLiteral("No destination thread is selected. Your message was not sent.")); + } + return admitted; + } + + void ShellWidget::Impl::recoverPrompt(const nodegraph::NodeRef& prompt) { + if (!prompt || prompt->id().kind != nodegraph::NodeKind::Item) + return; + + std::shared_ptr state; + if (auto read = session.nodeGraph().tryRead()) { + if (!read->live(prompt)) + return; + state = read->state(prompt); + if (!boolFromValue(valueMember(*state, "requiresExplicitRecovery"))) + return; + } else { + showNotice(QStringLiteral("Prompt state is busy; the preserved prompt was not changed.")); + return; + } + std::string authoredText = exactStringFromValue(valueMember(*state, "authoredText")); + if (authoredText.empty()) + authoredText = exactStringFromValue(valueMember(*state, "text")); + std::vector attachments = graphAttachmentDrafts(*state); + + if (!middleRegion->composer().promptEditor()->toPlainText().isEmpty() || !middleRegion->composer().attachments().empty()) { + showNotice(QStringLiteral("Clear or send the current draft before restoring this prompt. The " + "preserved prompt was not changed.")); + return; + } + + NewThreadDraft draft; + const nodegraph::Value::Object* threadStart = nullptr; + if (const nodegraph::Value* value = valueMember(*state, "threadStartOptions")) + threadStart = value->asObject(); + const std::string recoveredWorkspace = threadStart ? exactStringFromValue(valueMember(*threadStart, "cwd")) : std::string{}; + draft.workspace = text(recoveredWorkspace); + const std::string requestedName = exactStringFromValue(valueMember(*state, "requestedName")); + draft.name = requestedName.empty() ? QStringLiteral("Recovered prompt") : text(requestedName); + draft.sectionId = exactStringFromValue(valueMember(*state, "sectionId")); + if (threadStart) { + draft.projectId = exactStringFromValue(valueMember(*threadStart, "projectId")); + draft.baseInstructions = text(exactStringFromValue(valueMember(*threadStart, "baseInstructions"))); + draft.developerInstructions = text(exactStringFromValue(valueMember(*threadStart, "developerInstructions"))); + draft.ephemeral = boolFromValue(valueMember(*threadStart, "ephemeral")); + } + beginThreadDraft(std::move(draft)); + middleRegion->composer().promptEditor()->setPlainText(text(authoredText)); + middleRegion->composer().setAttachments(std::move(attachments)); + middleRegion->composer().promptEditor()->setFocus(); + showNotice(QStringLiteral("The unsent prompt was restored to a new-thread draft."), false); + } + + void ShellWidget::Impl::respondToRenderedPending(void (Impl::*respond)(const nodegraph::NodeRef&)) { + if (!renderedChrome || !renderedChrome->attention) { + showNotice(QStringLiteral("The pending request is no longer actionable.")); + return; + } + (this->*respond)(renderedChrome->attention->target); + } + + bool ShellWidget::Impl::submitPending(const PendingRequestDescriptor& request, PendingRequestSubmission submission) { + if (request.availability == PendingRequestAvailability::Submitting) { + showNotice(QStringLiteral("This request response is already submitting."), false); + return false; + } + if (request.availability != PendingRequestAvailability::Actionable) { + localPendingRequests.insert_or_assign(request.target, LocalPendingRequest{std::move(submission), std::nullopt}); + pendingChrome = true; + pendingInspector = true; + schedulePaneCommit(); + showNotice(request.availability == PendingRequestAvailability::RecoveryOnly + ? QStringLiteral("The original request ended when the provider " + "changed. Your authored response remains preserved " + "for review, but was not sent.") + : QStringLiteral("Controller access is unavailable. Your response " + "remains preserved for review.")); + return false; + } + + nodegraph::NodeAction action{request.target, nodegraph::NodeActionKind::ResolveInteraction, {}, {}, {}, {}}; + action.payload.emplace("choice", nodegraph::Value(submission.choice)); + if (!submission.input.is_null()) + action.payload.emplace("input", valueFromJson(submission.input)); + if (!submission.metadata.is_null()) + action.payload.emplace("metadata", valueFromJson(submission.metadata)); + auto [local, inserted] = + localPendingRequests.insert_or_assign(request.target, LocalPendingRequest{std::move(submission), request.responseRevision}); + static_cast(inserted); + const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); + if (!nodegraph::deliveryGuaranteed(status)) { + local->second.awaitingResponseAfter.reset(); + showNotice(QStringLiteral("Your response was not admitted. Reopen Review to recover the input " + "you entered; the request remains pending.")); + } else if (nodegraph::wakeFailed(status)) { + showNotice(QStringLiteral("The response was admitted after a worker wake-up failure; bounded " + "fallback delivery is active.")); + } + pendingChrome = true; + pendingInspector = true; + schedulePaneCommit(); + return nodegraph::deliveryGuaranteed(status); + } + + void ShellWidget::Impl::presentPending(PendingRequestDescriptor request) { + if (request.availability == PendingRequestAvailability::Submitting) { + showNotice(QStringLiteral("This request response is already submitting."), false); + return; + } + if (request.availability != PendingRequestAvailability::Actionable && !request.retainedSubmission) { + showNotice(QStringLiteral("Controller access is unavailable; no response was sent.")); + return; + } + const auto submission = [&] { + // Reuse the shell's request projection while this exact dialog is alive. + const QScopedValueRollback targetScope(reviewedRequest, request.target); + const QScopedValueRollback submitScope(reviewSubmit); + return PendingRequestDialog::present( + request, owner, request.retainedSubmission ? &*request.retainedSubmission : nullptr, [this](QPushButton* button) { + reviewSubmit = button; + pendingChrome = true; + schedulePaneCommit(); + }); + }(); + acknowledgeDetachedTargets(); + if (!submission) + return; + const auto current = pendingRequest(request.target); + if (current) + static_cast(submitPending(*current, *submission)); + } + + void ShellWidget::Impl::reviewPending(const nodegraph::NodeRef& target) { + const auto request = pendingRequest(target); + if (request) + presentPending(*request); + } + + void ShellWidget::Impl::acceptPending(const nodegraph::NodeRef& target) { + const auto request = pendingRequest(target); + if (!request) + return; + if (request->availability != PendingRequestAvailability::Actionable) { + showNotice(QStringLiteral("Controller access is unavailable; no response was sent.")); + return; } + const auto positive = PendingRequestPolicy::controls(*request).positive; + if (!positive) { + presentPending(*request); + return; + } + static_cast(submitPending(*request, PendingRequestSubmission{positive->value, nullptr, nullptr})); } -} - -void ShellWidget::Impl::confirmDeleteThread(const nodegraph::NodeRef &thread) { - if (!thread || thread->id().kind != nodegraph::NodeKind::Thread) - return; - if (QMessageBox::question(owner, QStringLiteral("Delete thread"), - QStringLiteral("Delete the selected thread?"), - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel) != QMessageBox::Yes) - return; - if (!uiAdapter.threadRow(thread)) { - showNotice(QStringLiteral( - "The thread is no longer available; no delete was sent.")); - return; - } - static_cast(sendNodeAction( - {thread, nodegraph::NodeActionKind::Delete, {}, {}, {}, {}}, - QStringLiteral("Delete request was not admitted; try again."))); -} - -bool ShellWidget::Impl::submitPrompt(QString prompt, - std::vector attachments) { - if (prompt.trimmed().isEmpty() && attachments.empty()) - return false; - TurnSettingsPolicy &settings = middleRegion->composer().turnSettings(); - std::vector ownedAttachments; - ownedAttachments.reserve(attachments.size()); - for (AttachmentDraft &attachment : attachments) { - ownedAttachments.push_back({std::move(attachment.path), - std::move(attachment.name), - std::move(attachment.mimeType), std::nullopt}); - } - - bool admitted = false; - const std::optional visible = - middleRegion->threads().visiblySelectedThread(); - nodegraph::NodeRef target = visible && visible->target == boundGraphThread - ? visible->target - : nodegraph::NodeRef{}; - const bool visibleDraft = - visible && !visible->target && visible->id == DraftThreadId && - visible->presentationKey == - ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation); - if (target) { - QString graphRejection; - if (auto read = session.nodeGraph().tryRead()) { - if (!read->live(target)) { - graphRejection = - QStringLiteral("The selected thread is no longer available. Your " - "message was not sent."); - } else { - const auto state = read->state(target); - const std::string hydration = - exactStringFromValue(valueMember(*state, "hydrationState")); - const nodegraph::NodeRef turn = - read->relatedAt(target, nodegraph::RelationKind::ActiveTurn, 0); - const bool steeringKnownActiveTurn = - turn && turn->id().kind == nodegraph::NodeKind::Turn; - if (!steeringKnownActiveTurn && - (hydration == "loading" || hydration == "failed" || - (state->status == nodegraph::NodeStatus::NotLoaded && - hydration != "ready"))) { - const std::string detail = - exactStringFromValue(valueMember(*state, "hydrationError")); - graphRejection = text( - detail.empty() - ? "This thread must finish loading before sending. Your " - "draft is still available." - : detail + - ". Reload the thread; your draft is still available."); - } - } - } else { - graphRejection = QStringLiteral( - "Thread state is busy. Your draft is still available; try again."); + + void ShellWidget::Impl::rejectPending(const nodegraph::NodeRef& target) { + const auto request = pendingRequest(target); + if (!request) + return; + if (request->availability != PendingRequestAvailability::Actionable) { + showNotice(QStringLiteral("Controller access is unavailable; no response was sent.")); + return; + } + const auto negative = PendingRequestPolicy::controls(*request).negative; + if (!negative) { + presentPending(*request); + return; + } + static_cast(submitPending(*request, PendingRequestSubmission{negative->value, nullptr, nullptr})); } - // The graph read guard above is gone before any QWidget is touched. - if (!graphRejection.isEmpty()) { - showNotice(std::move(graphRejection)); - return false; + + ShellWidget::ShellWidget(FrontendSession& session, QWidget* parent) + : QWidget(parent) + , impl(nullptr) { + // Impl installs this widget as the application event filter. Keep the + // member in a defined null state while Impl builds child widgets: their + // construction can synchronously pass events through that filter. + impl = std::make_unique(this, session); } - auto settingsContext = uiAdapter.turnSettings(target); - if (!settingsContext) { - showNotice(QStringLiteral( - "Thread settings are busy. Your message was not sent; try again.")); - return false; + + ShellWidget::~ShellWidget() = default; + + bool ShellWidget::eventFilter(QObject* watched, QEvent* event) { + if (watched == qApp && event && event->type() == QEvent::ApplicationFontChange) { + const QString styleSheet = UiStyle::applicationStyleSheet(); + if (qApp->styleSheet() != styleSheet) + qApp->setStyleSheet(styleSheet); + } + if (impl && impl->middleRegion->routeScrollEvent(watched, event)) + return true; + return QWidget::eventFilter(watched, event); } - middleRegion->composer().setTurnSettingsContext( - std::move(*settingsContext)); - nodegraph::NodeAction action{target, - nodegraph::NodeActionKind::SubmitPrompt, - {}, {}, {}, {}}; - action.promptText = utf8(prompt); - action.attachments = std::move(ownedAttachments); - action.payload = - objectFromJson(settings.startOptions(TurnSettingsScope::Turn)); - admitted = sendNodeAction( - std::move(action), - QStringLiteral("Your message was not sent; the worker queue is full.")); - } else if (visibleDraft && newThreadDraft) { - auto settingsContext = uiAdapter.turnSettings({}, ui::threadPresentationKey(DraftThreadId, creationDraftCorrelation)); - if (!settingsContext) { - showNotice(QStringLiteral("Thread settings are busy. Your message was not sent; try again.")); - return false; - } - middleRegion->composer().setTurnSettingsContext( - std::move(*settingsContext)); - nodegraph::RuntimeAction action; - action.kind = nodegraph::RuntimeActionKind::CreateThread; - action.correlation = creationDraftCorrelation; - action.promptText = utf8(prompt); - action.attachments = std::move(ownedAttachments); - nodegraph::Value::Object threadStart = - objectFromJson(settings.startOptions(TurnSettingsScope::Thread)); - threadStart.insert_or_assign("cwd", utf8(newThreadDraft->workspace)); - if (!newThreadDraft->projectId.empty()) - threadStart.insert_or_assign("projectId", newThreadDraft->projectId); - if (!newThreadDraft->sectionId.empty()) - action.payload.insert_or_assign("sectionId", newThreadDraft->sectionId); - if (!newThreadDraft->ephemeral && !newThreadDraft->name.trimmed().isEmpty()) - action.payload.insert_or_assign("requestedName", - utf8(newThreadDraft->name)); - if (!newThreadDraft->baseInstructions.isEmpty()) - threadStart.insert_or_assign("baseInstructions", - utf8(newThreadDraft->baseInstructions)); - if (!newThreadDraft->developerInstructions.isEmpty()) - threadStart.insert_or_assign("developerInstructions", - utf8(newThreadDraft->developerInstructions)); - if (newThreadDraft->ephemeral) - threadStart.insert_or_assign("ephemeral", true); - action.payload.insert_or_assign("threadStart", - nodegraph::Value(std::move(threadStart))); - action.payload.insert_or_assign( - "turnStart", nodegraph::Value(objectFromJson( - settings.startOptions(TurnSettingsScope::Turn)))); - admitted = sendRuntimeAction( - std::move(action), - QStringLiteral("Your message was not sent; the worker queue is full.")); - if (admitted) - newThreadDraft.reset(); - } else { - showNotice(QStringLiteral( - "No destination thread is selected. Your message was not sent.")); - } - return admitted; -} - -void ShellWidget::Impl::recoverPrompt(const nodegraph::NodeRef &prompt) { - if (!prompt || prompt->id().kind != nodegraph::NodeKind::Item) - return; - - std::shared_ptr state; - if (auto read = session.nodeGraph().tryRead()) { - if (!read->live(prompt)) - return; - state = read->state(prompt); - if (!boolFromValue(valueMember(*state, "requiresExplicitRecovery"))) - return; - } else { - showNotice(QStringLiteral( - "Prompt state is busy; the preserved prompt was not changed.")); - return; - } - std::string authoredText = - exactStringFromValue(valueMember(*state, "authoredText")); - if (authoredText.empty()) - authoredText = exactStringFromValue(valueMember(*state, "text")); - std::vector attachments = graphAttachmentDrafts(*state); - - if (!middleRegion->composer().promptEditor()->toPlainText().isEmpty() || - !middleRegion->composer().attachments().empty()) { - showNotice(QStringLiteral( - "Clear or send the current draft before restoring this prompt. The " - "preserved prompt was not changed.")); - return; - } - - NewThreadDraft draft; - const nodegraph::Value::Object *threadStart = nullptr; - if (const nodegraph::Value *value = valueMember(*state, "threadStartOptions")) - threadStart = value->asObject(); - const std::string recoveredWorkspace = - threadStart ? exactStringFromValue(valueMember(*threadStart, "cwd")) - : std::string{}; - draft.workspace = text(recoveredWorkspace); - const std::string requestedName = - exactStringFromValue(valueMember(*state, "requestedName")); - draft.name = requestedName.empty() ? QStringLiteral("Recovered prompt") - : text(requestedName); - draft.sectionId = exactStringFromValue(valueMember(*state, "sectionId")); - if (threadStart) { - draft.projectId = - exactStringFromValue(valueMember(*threadStart, "projectId")); - draft.baseInstructions = text( - exactStringFromValue(valueMember(*threadStart, "baseInstructions"))); - draft.developerInstructions = text(exactStringFromValue( - valueMember(*threadStart, "developerInstructions"))); - draft.ephemeral = boolFromValue(valueMember(*threadStart, "ephemeral")); - } - beginThreadDraft(std::move(draft)); - middleRegion->composer().promptEditor()->setPlainText(text(authoredText)); - middleRegion->composer().setAttachments(std::move(attachments)); - middleRegion->composer().promptEditor()->setFocus(); - showNotice( - QStringLiteral("The unsent prompt was restored to a new-thread draft."), - false); -} - -void ShellWidget::Impl::respondToRenderedPending( - void (Impl::*respond)(const nodegraph::NodeRef &)) { - if (!renderedChrome || !renderedChrome->attention) { - showNotice(QStringLiteral("The pending request is no longer actionable.")); - return; - } - (this->*respond)(renderedChrome->attention->target); -} - -bool ShellWidget::Impl::submitPending(const PendingRequestDescriptor &request, - PendingRequestSubmission submission) { - if (request.availability == PendingRequestAvailability::Submitting) { - showNotice(QStringLiteral("This request response is already submitting."), - false); - return false; - } - if (request.availability != PendingRequestAvailability::Actionable) { - localPendingRequests.insert_or_assign( - request.target, - LocalPendingRequest{std::move(submission), std::nullopt}); - pendingChrome = true; - pendingInspector = true; - schedulePaneCommit(); - showNotice( - request.availability == PendingRequestAvailability::RecoveryOnly - ? QStringLiteral( - "The original request ended when the provider " - "changed. Your authored response remains preserved " - "for review, but was not sent.") - : QStringLiteral("Controller access is unavailable. Your response " - "remains preserved for review.")); - return false; - } - - nodegraph::NodeAction action{request.target, - nodegraph::NodeActionKind::ResolveInteraction, - {}, {}, {}, {}}; - action.payload.emplace("choice", nodegraph::Value(submission.choice)); - if (!submission.input.is_null()) - action.payload.emplace("input", valueFromJson(submission.input)); - if (!submission.metadata.is_null()) - action.payload.emplace("metadata", valueFromJson(submission.metadata)); - auto [local, inserted] = localPendingRequests.insert_or_assign( - request.target, - LocalPendingRequest{std::move(submission), request.responseRevision}); - static_cast(inserted); - const nodegraph::ChannelSendStatus status = session.sendNodeAction(action); - if (!nodegraph::deliveryGuaranteed(status)) { - local->second.awaitingResponseAfter.reset(); - showNotice(QStringLiteral( - "Your response was not admitted. Reopen Review to recover the input " - "you entered; the request remains pending.")); - } else if (nodegraph::wakeFailed(status)) { - showNotice(QStringLiteral( - "The response was admitted after a worker wake-up failure; bounded " - "fallback delivery is active.")); - } - pendingChrome = true; - pendingInspector = true; - schedulePaneCommit(); - return nodegraph::deliveryGuaranteed(status); -} - -void ShellWidget::Impl::presentPending(PendingRequestDescriptor request) { - if (request.availability == PendingRequestAvailability::Submitting) { - showNotice(QStringLiteral("This request response is already submitting."), - false); - return; - } - if (request.availability != PendingRequestAvailability::Actionable && - !request.retainedSubmission) { - showNotice(QStringLiteral( - "Controller access is unavailable; no response was sent.")); - return; - } - const auto submission = [&] { - // Reuse the shell's request projection while this exact dialog is alive. - const QScopedValueRollback targetScope(reviewedRequest, request.target); - const QScopedValueRollback submitScope(reviewSubmit); - return PendingRequestDialog::present( - request, owner, - request.retainedSubmission ? &*request.retainedSubmission : nullptr, - [this](QPushButton *button) { - reviewSubmit = button; - pendingChrome = true; - schedulePaneCommit(); - }); - }(); - acknowledgeDetachedTargets(); - if (!submission) - return; - const auto current = pendingRequest(request.target); - if (current) - static_cast(submitPending(*current, *submission)); -} - -void ShellWidget::Impl::reviewPending(const nodegraph::NodeRef &target) { - const auto request = pendingRequest(target); - if (request) - presentPending(*request); -} - -void ShellWidget::Impl::acceptPending(const nodegraph::NodeRef &target) { - const auto request = pendingRequest(target); - if (!request) - return; - if (request->availability != PendingRequestAvailability::Actionable) { - showNotice(QStringLiteral( - "Controller access is unavailable; no response was sent.")); - return; - } - const auto positive = PendingRequestPolicy::controls(*request).positive; - if (!positive) { - presentPending(*request); - return; - } - static_cast(submitPending( - *request, PendingRequestSubmission{positive->value, nullptr, nullptr})); -} - -void ShellWidget::Impl::rejectPending(const nodegraph::NodeRef &target) { - const auto request = pendingRequest(target); - if (!request) - return; - if (request->availability != PendingRequestAvailability::Actionable) { - showNotice(QStringLiteral( - "Controller access is unavailable; no response was sent.")); - return; - } - const auto negative = PendingRequestPolicy::controls(*request).negative; - if (!negative) { - presentPending(*request); - return; - } - static_cast(submitPending( - *request, PendingRequestSubmission{negative->value, nullptr, nullptr})); -} - -ShellWidget::ShellWidget(FrontendSession &session, QWidget *parent) - : QWidget(parent), impl(nullptr) { - // Impl installs this widget as the application event filter. Keep the - // member in a defined null state while Impl builds child widgets: their - // construction can synchronously pass events through that filter. - impl = std::make_unique(this, session); -} - -ShellWidget::~ShellWidget() = default; - -bool ShellWidget::eventFilter(QObject *watched, QEvent *event) { - if (watched == qApp && event && - event->type() == QEvent::ApplicationFontChange) { - const QString styleSheet = UiStyle::applicationStyleSheet(); - if (qApp->styleSheet() != styleSheet) - qApp->setStyleSheet(styleSheet); - } - if (impl && impl->middleRegion->routeScrollEvent(watched, event)) - return true; - return QWidget::eventFilter(watched, event); -} } // namespace codexui::codex diff --git a/src/codex/middle/ConversationItemModel.cpp b/src/codex/middle/ConversationItemModel.cpp index a384422..dfcc95c 100644 --- a/src/codex/middle/ConversationItemModel.cpp +++ b/src/codex/middle/ConversationItemModel.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-or-later OR MIT #include "codex/middle/ConversationItemModel.h" + #include "codex/ui/TimingPresentation.h" #include @@ -12,1672 +13,1528 @@ #include namespace codexui::codex::middle { -namespace { - -QString cardLabel(CardKind kind) { - switch (kind) { - case CardKind::UserMessage: - return QStringLiteral("You"); - case CardKind::AgentMessage: - return QStringLiteral("Codex"); - case CardKind::CommandExecution: - return QStringLiteral("Command execution"); - case CardKind::AgentActivity: - return QStringLiteral("Agent activity"); - case CardKind::Reasoning: - return QStringLiteral("Reasoning"); - case CardKind::FileChanges: - return QStringLiteral("File changes"); - case CardKind::ImageGeneration: - return QStringLiteral("Generated image"); - case CardKind::Plan: - return QStringLiteral("Plan"); - case CardKind::GenericActivity: - return QStringLiteral("Activity"); - case CardKind::LocalPrompt: - return QStringLiteral("You"); - } - return QStringLiteral("Activity"); -} - -QString boundedAccessibleText(std::string_view value) { - constexpr std::size_t MaximumAccessibleBytes = 8192; - const std::size_t length = std::min(value.size(), MaximumAccessibleBytes); - QString result = - QString::fromUtf8(value.data(), static_cast(length)); - if (length != value.size()) - result += QStringLiteral("…"); - return result; -} - -constexpr qsizetype MaximumAccessibleCharacters = 8192; - -bool appendAccessibleLine(QString &destination, std::string_view value, - bool prependNewline) { - qsizetype remaining = MaximumAccessibleCharacters - destination.size(); - if (prependNewline) { - if (remaining <= 0) - return false; - destination += QLatin1Char('\n'); - --remaining; - } - if (remaining <= 0) - return value.empty(); - - const std::size_t byteCount = - std::min(value.size(), static_cast(remaining) * 4); - QString rendered = - QString::fromUtf8(value.data(), static_cast(byteCount)); - if (rendered.size() > remaining) - rendered.truncate(remaining); - destination += rendered; - return byteCount == value.size(); -} - -void markAccessibleTextTruncated(QString &value) { - value.truncate(MaximumAccessibleCharacters); - value += QStringLiteral("…"); -} - -QString accessibleCardText(const VisibleCardData &card) { - QString detail = std::visit( - [](const auto &payload) -> QString { - using Payload = std::decay_t; - if constexpr (std::is_same_v) - return boundedAccessibleText(payload.text); - if constexpr (std::is_same_v) - return boundedAccessibleText(payload.text); - if constexpr (std::is_same_v) - return QStringLiteral("%1\n%2").arg( - boundedAccessibleText(payload.command), - boundedAccessibleText(payload.output)); - if constexpr (std::is_same_v) - return QStringLiteral("%1\n%2").arg( - boundedAccessibleText(payload.prompt), - boundedAccessibleText(payload.resultText)); - if constexpr (std::is_same_v) - return boundedAccessibleText(payload.summary); - if constexpr (std::is_same_v) { - QString paths; - bool first = true; - for (const FileChangeData &change : payload.changes) { - if (!appendAccessibleLine(paths, change.path, !first)) { - markAccessibleTextTruncated(paths); - break; + namespace { + + QString cardLabel(CardKind kind) { + switch (kind) { + case CardKind::UserMessage: + return QStringLiteral("You"); + case CardKind::AgentMessage: + return QStringLiteral("Codex"); + case CardKind::CommandExecution: + return QStringLiteral("Command execution"); + case CardKind::AgentActivity: + return QStringLiteral("Agent activity"); + case CardKind::Reasoning: + return QStringLiteral("Reasoning"); + case CardKind::FileChanges: + return QStringLiteral("File changes"); + case CardKind::ImageGeneration: + return QStringLiteral("Generated image"); + case CardKind::Plan: + return QStringLiteral("Plan"); + case CardKind::GenericActivity: + return QStringLiteral("Activity"); + case CardKind::LocalPrompt: + return QStringLiteral("You"); + } + return QStringLiteral("Activity"); + } + + QString boundedAccessibleText(std::string_view value) { + constexpr std::size_t MaximumAccessibleBytes = 8192; + const std::size_t length = std::min(value.size(), MaximumAccessibleBytes); + QString result = QString::fromUtf8(value.data(), static_cast(length)); + if (length != value.size()) + result += QStringLiteral("…"); + return result; + } + + constexpr qsizetype MaximumAccessibleCharacters = 8192; + + bool appendAccessibleLine(QString& destination, std::string_view value, bool prependNewline) { + qsizetype remaining = MaximumAccessibleCharacters - destination.size(); + if (prependNewline) { + if (remaining <= 0) + return false; + destination += QLatin1Char('\n'); + --remaining; } - first = false; - } - return paths; + if (remaining <= 0) + return value.empty(); + + const std::size_t byteCount = std::min(value.size(), static_cast(remaining) * 4); + QString rendered = QString::fromUtf8(value.data(), static_cast(byteCount)); + if (rendered.size() > remaining) + rendered.truncate(remaining); + destination += rendered; + return byteCount == value.size(); } - if constexpr (std::is_same_v) - return QStringLiteral("%1\n%2").arg( - boundedAccessibleText(payload.revisedPrompt), - boundedAccessibleText(payload.path)); - if constexpr (std::is_same_v) { - QString lines; - bool complete = - appendAccessibleLine(lines, payload.explanation, false); - for (const PlanStepData &step : payload.steps) { - if (!complete || - !appendAccessibleLine(lines, displayStatus(step.status), - true) || - !appendAccessibleLine(lines, ": ", false) || - !appendAccessibleLine(lines, step.text, false)) { - complete = false; - break; + + void markAccessibleTextTruncated(QString& value) { + value.truncate(MaximumAccessibleCharacters); + value += QStringLiteral("…"); + } + + QString accessibleCardText(const VisibleCardData& card) { + QString detail = std::visit( + [](const auto& payload) -> QString { + using Payload = std::decay_t; + if constexpr (std::is_same_v) + return boundedAccessibleText(payload.text); + if constexpr (std::is_same_v) + return boundedAccessibleText(payload.text); + if constexpr (std::is_same_v) + return QStringLiteral("%1\n%2").arg(boundedAccessibleText(payload.command), boundedAccessibleText(payload.output)); + if constexpr (std::is_same_v) + return QStringLiteral("%1\n%2").arg(boundedAccessibleText(payload.prompt), + boundedAccessibleText(payload.resultText)); + if constexpr (std::is_same_v) + return boundedAccessibleText(payload.summary); + if constexpr (std::is_same_v) { + QString paths; + bool first = true; + for (const FileChangeData& change : payload.changes) { + if (!appendAccessibleLine(paths, change.path, !first)) { + markAccessibleTextTruncated(paths); + break; + } + first = false; + } + return paths; + } + if constexpr (std::is_same_v) + return QStringLiteral("%1\n%2").arg(boundedAccessibleText(payload.revisedPrompt), + boundedAccessibleText(payload.path)); + if constexpr (std::is_same_v) { + QString lines; + bool complete = appendAccessibleLine(lines, payload.explanation, false); + for (const PlanStepData& step : payload.steps) { + if (!complete || !appendAccessibleLine(lines, displayStatus(step.status), true) || + !appendAccessibleLine(lines, ": ", false) || !appendAccessibleLine(lines, step.text, false)) { + complete = false; + break; + } + } + if (complete && !payload.legacyText.empty()) + complete = appendAccessibleLine(lines, payload.legacyText, true); + if (!complete) + markAccessibleTextTruncated(lines); + return lines; + } + if constexpr (std::is_same_v) + return boundedAccessibleText(payload.displayDetail); + if constexpr (std::is_same_v) + return boundedAccessibleText(payload.prompt); + return {}; + }, + card.payload); + if (detail.size() > MaximumAccessibleCharacters) { + markAccessibleTextTruncated(detail); } - } - if (complete && !payload.legacyText.empty()) - complete = appendAccessibleLine(lines, payload.legacyText, true); - if (!complete) - markAccessibleTextTruncated(lines); - return lines; + const QString label = cardLabel(card.kind); + const QString timing = ui::timingSummary(card.timing); + const QString heading = timing.isEmpty() ? label : label + QStringLiteral(" · ") + timing; + return detail.isEmpty() ? heading : heading + QStringLiteral("\n") + detail; + } + + bool structurallyCompatible(const CardKey& beforeKey, + CardKind beforeKind, + const nodegraph::NodeRef& beforeTarget, + const VisibleCardData& after) noexcept { + return beforeKey == after.key && ((beforeKind == after.kind && beforeTarget == after.target) || + (beforeKind == CardKind::LocalPrompt && after.kind == CardKind::UserMessage)); + } + + bool validSectionPlacement(bool turnRoot, + bool nested, + std::size_t remainingSectionRows, + bool remainingRoot, + bool previousInSection, + bool nextInSection) noexcept { + if (turnRoot && nested) + return false; + if (remainingSectionRows != 0 && !previousInSection && !nextInSection) + return false; + if (turnRoot) + return !remainingRoot; + return true; + } + + } // namespace + + ConversationItemModel::ConversationItemModel(QObject* parent) + : QAbstractListModel(parent) { + } + + ConversationItemModel::~ConversationItemModel() = default; + + int ConversationItemModel::rowCount(const QModelIndex& parent) const { + return parent.isValid() ? 0 : static_cast(nodeCount(rows_)); + } + + QVariant ConversationItemModel::data(const QModelIndex& index, int role) const { + const Row* value = row(index.row()); + if (!value || index.column() != 0) + return {}; + switch (role) { + case Qt::DisplayRole: + return cardLabel(value->card.kind); + case Qt::AccessibleTextRole: + return accessibleCardText(value->card); + case StableKeyRole: + return QString::fromStdString(value->stableKey); + case ThreadIdRole: + return QString::fromStdString(value->card.threadId); + case TurnIdRole: + return QString::fromStdString(value->card.turnId); + case ItemIdRole: + return QString::fromStdString(value->card.itemId); + case CardKindRole: + return static_cast(value->card.kind); + case TargetIdentityRole: + return value->card.target ? QString::fromStdString(value->card.target->id().canonical) : QString{}; + case TurnSectionRole: + return QString::fromStdString(value->sectionKey); + case TurnRootRole: + return value->turnRoot; + case NestedCardRole: + return value->nested; + case FirstInTurnRole: + return value->firstInTurn; + case LastInTurnRole: + return value->lastInTurn; + case PresentedRole: + return value->presented; + case ActiveTurnRole: + return value->activeTurn; + case PresentationRole: + // Large card values intentionally remain available only through card(). + // Returning them through QVariant would copy streamed text. + return {}; + default: + return {}; } - if constexpr (std::is_same_v) - return boundedAccessibleText(payload.displayDetail); - if constexpr (std::is_same_v) - return boundedAccessibleText(payload.prompt); - return {}; - }, - card.payload); - if (detail.size() > MaximumAccessibleCharacters) { - markAccessibleTextTruncated(detail); - } - const QString label = cardLabel(card.kind); - const QString timing = ui::timingSummary(card.timing); - const QString heading = - timing.isEmpty() ? label : label + QStringLiteral(" · ") + timing; - return detail.isEmpty() ? heading : heading + QStringLiteral("\n") + detail; -} - -bool structurallyCompatible(const CardKey &beforeKey, CardKind beforeKind, - const nodegraph::NodeRef &beforeTarget, - const VisibleCardData &after) noexcept { - return beforeKey == after.key && - ((beforeKind == after.kind && beforeTarget == after.target) || - (beforeKind == CardKind::LocalPrompt && - after.kind == CardKind::UserMessage)); -} - -bool validSectionPlacement(bool turnRoot, bool nested, - std::size_t remainingSectionRows, bool remainingRoot, - bool previousInSection, - bool nextInSection) noexcept { - if (turnRoot && nested) - return false; - if (remainingSectionRows != 0 && !previousInSection && !nextInSection) - return false; - if (turnRoot) - return !remainingRoot; - return true; -} - -} // namespace - -ConversationItemModel::ConversationItemModel(QObject *parent) - : QAbstractListModel(parent) {} - -ConversationItemModel::~ConversationItemModel() = default; - -int ConversationItemModel::rowCount(const QModelIndex &parent) const { - return parent.isValid() ? 0 : static_cast(nodeCount(rows_)); -} - -QVariant ConversationItemModel::data(const QModelIndex &index, int role) const { - const Row *value = row(index.row()); - if (!value || index.column() != 0) - return {}; - switch (role) { - case Qt::DisplayRole: - return cardLabel(value->card.kind); - case Qt::AccessibleTextRole: - return accessibleCardText(value->card); - case StableKeyRole: - return QString::fromStdString(value->stableKey); - case ThreadIdRole: - return QString::fromStdString(value->card.threadId); - case TurnIdRole: - return QString::fromStdString(value->card.turnId); - case ItemIdRole: - return QString::fromStdString(value->card.itemId); - case CardKindRole: - return static_cast(value->card.kind); - case TargetIdentityRole: - return value->card.target - ? QString::fromStdString(value->card.target->id().canonical) - : QString{}; - case TurnSectionRole: - return QString::fromStdString(value->sectionKey); - case TurnRootRole: - return value->turnRoot; - case NestedCardRole: - return value->nested; - case FirstInTurnRole: - return value->firstInTurn; - case LastInTurnRole: - return value->lastInTurn; - case PresentedRole: - return value->presented; - case ActiveTurnRole: - return value->activeTurn; - case PresentationRole: - // Large card values intentionally remain available only through card(). - // Returning them through QVariant would copy streamed text. - return {}; - default: - return {}; - } -} - -Qt::ItemFlags ConversationItemModel::flags(const QModelIndex &index) const { - const Row *value = row(index.row()); - if (!value || !value->presented) - return Qt::NoItemFlags; - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; -} - -QHash ConversationItemModel::roleNames() const { - return { - {StableKeyRole, "stableKey"}, {ThreadIdRole, "threadId"}, - {TurnIdRole, "turnId"}, {ItemIdRole, "itemId"}, - {CardKindRole, "cardKind"}, {TargetIdentityRole, "targetIdentity"}, - {TurnSectionRole, "turnSection"}, {TurnRootRole, "turnRoot"}, - {NestedCardRole, "nestedCard"}, {FirstInTurnRole, "firstInTurn"}, - {LastInTurnRole, "lastInTurn"}, {PresentedRole, "presented"}, - {ActiveTurnRole, "activeTurn"}, {PresentationRole, "presentation"}}; -} - -ConversationItemModel::StructuralChangeResult -ConversationItemModel::replaceConversation(ConversationSnapshot snapshot) { - const std::string nextThreadId = snapshot.threadId; - const bool nextHasMore = snapshot.hasMore; - std::vector desired = flatten(std::move(snapshot)); - if (!rowsAreUnique(desired)) - return StructuralChangeResult::Rejected; - - bool identical = nextThreadId == threadId_ && nextHasMore == hasMore_ && - desired.size() == nodeCount(rows_); - for (std::size_t position = 0; identical && position < desired.size(); - ++position) { - const RowNode *current = nodeAt(position); - identical = current && current->value == desired[position]; - } - if (identical) - return StructuralChangeResult::Unchanged; - - beginResetModel(); - clearRows(); - rows_ = buildRows(desired, 0, desired.size()); - threadId_ = nextThreadId; - hasMore_ = nextHasMore; - rebuildIndexes(); - endResetModel(); - incrementProperty("modelResetCount"); - incrementProperty("modelReplacementCount"); - return StructuralChangeResult::Changed; -} - -ConversationItemModel::StructuralChangeResult -ConversationItemModel::reconcile(ConversationSnapshot snapshot) { - if (snapshot.threadId != threadId_) - return replaceConversation(std::move(snapshot)); - const bool nextHasMore = snapshot.hasMore; - std::vector desired = flatten(std::move(snapshot)); - if (!rowsAreUnique(desired)) - return StructuralChangeResult::Rejected; - - const bool chromeChanged = nextHasMore != hasMore_; - hasMore_ = nextHasMore; - const std::size_t currentCount = nodeCount(rows_); - if (currentCount != 0 && desired.size() >= currentCount) { - struct InsertionRun { - std::size_t first = 0; - std::size_t count = 0; - }; - std::vector insertions; - std::vector retainedNodes; - std::vector retainedPositions; - retainedNodes.reserve(currentCount); - retainedPositions.reserve(currentCount); - RowNode *current = nodeAt(0); - std::size_t desiredPosition = 0; - bool insertionOnly = true; - while (current && insertionOnly) { - const std::size_t insertionFirst = desiredPosition; - while (desiredPosition < desired.size() && - desired[desiredPosition].stableKey != current->value.stableKey) - ++desiredPosition; - if (desiredPosition == desired.size()) { - insertionOnly = false; - break; - } - if (desiredPosition != insertionFirst) - insertions.push_back( - {insertionFirst, desiredPosition - insertionFirst}); - const Row &replacement = desired[desiredPosition]; - insertionOnly = - structurallyCompatible(current->value.card.key, - current->value.card.kind, - current->value.card.target, replacement.card); - retainedNodes.push_back(current); - retainedPositions.push_back(desiredPosition); - ++desiredPosition; - current = nextNode(current); } - if (insertionOnly && retainedPositions.size() == currentCount) { - if (desiredPosition != desired.size()) - insertions.push_back( - {desiredPosition, desired.size() - desiredPosition}); - for (const InsertionRun &insertion : insertions) { - const int firstRow = static_cast(insertion.first); - beginInsertRows({}, firstRow, - firstRow + static_cast(insertion.count) - 1); - auto [before, after] = - splitRows(std::move(rows_), insertion.first); - rows_ = mergeRows( - mergeRows(std::move(before), - buildRows(desired, insertion.first, - insertion.first + insertion.count)), - std::move(after)); + + Qt::ItemFlags ConversationItemModel::flags(const QModelIndex& index) const { + const Row* value = row(index.row()); + if (!value || !value->presented) + return Qt::NoItemFlags; + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } + + QHash ConversationItemModel::roleNames() const { + return {{StableKeyRole, "stableKey"}, + {ThreadIdRole, "threadId"}, + {TurnIdRole, "turnId"}, + {ItemIdRole, "itemId"}, + {CardKindRole, "cardKind"}, + {TargetIdentityRole, "targetIdentity"}, + {TurnSectionRole, "turnSection"}, + {TurnRootRole, "turnRoot"}, + {NestedCardRole, "nestedCard"}, + {FirstInTurnRole, "firstInTurn"}, + {LastInTurnRole, "lastInTurn"}, + {PresentedRole, "presented"}, + {ActiveTurnRole, "activeTurn"}, + {PresentationRole, "presentation"}}; + } + + ConversationItemModel::StructuralChangeResult ConversationItemModel::replaceConversation(ConversationSnapshot snapshot) { + const std::string nextThreadId = snapshot.threadId; + const bool nextHasMore = snapshot.hasMore; + std::vector desired = flatten(std::move(snapshot)); + if (!rowsAreUnique(desired)) + return StructuralChangeResult::Rejected; + + bool identical = nextThreadId == threadId_ && nextHasMore == hasMore_ && desired.size() == nodeCount(rows_); + for (std::size_t position = 0; identical && position < desired.size(); ++position) { + const RowNode* current = nodeAt(position); + identical = current && current->value == desired[position]; + } + if (identical) + return StructuralChangeResult::Unchanged; + + beginResetModel(); + clearRows(); + rows_ = buildRows(desired, 0, desired.size()); + threadId_ = nextThreadId; + hasMore_ = nextHasMore; rebuildIndexes(); - endInsertRows(); - incrementProperty("modelInsertCount"); - } - bool rowsUpdated = false; - for (std::size_t index = 0; index < currentCount; ++index) { - const std::size_t position = retainedPositions[index]; - RowNode *retained = retainedNodes[index]; - if (retained->value == desired[position]) - continue; - updateRow(retained, static_cast(position), - std::move(desired[position])); - rowsUpdated = true; - } - return !insertions.empty() || rowsUpdated || chromeChanged - ? StructuralChangeResult::Changed - : StructuralChangeResult::Unchanged; + endResetModel(); + incrementProperty("modelResetCount"); + incrementProperty("modelReplacementCount"); + return StructuralChangeResult::Changed; } - } - std::unordered_set desiredKeys; - desiredKeys.reserve(desired.size()); - for (const Row &row : desired) - desiredKeys.insert(row.stableKey); - - bool changed = chromeChanged; - for (std::size_t offset = nodeCount(rows_); offset > 0;) { - std::size_t last = offset - 1; - const RowNode *lastNode = nodeAt(last); - if (lastNode && desiredKeys.contains(lastNode->value.stableKey)) { - offset = last; - continue; + + ConversationItemModel::StructuralChangeResult ConversationItemModel::reconcile(ConversationSnapshot snapshot) { + if (snapshot.threadId != threadId_) + return replaceConversation(std::move(snapshot)); + const bool nextHasMore = snapshot.hasMore; + std::vector desired = flatten(std::move(snapshot)); + if (!rowsAreUnique(desired)) + return StructuralChangeResult::Rejected; + + const bool chromeChanged = nextHasMore != hasMore_; + hasMore_ = nextHasMore; + const std::size_t currentCount = nodeCount(rows_); + if (currentCount != 0 && desired.size() >= currentCount) { + struct InsertionRun { + std::size_t first = 0; + std::size_t count = 0; + }; + std::vector insertions; + std::vector retainedNodes; + std::vector retainedPositions; + retainedNodes.reserve(currentCount); + retainedPositions.reserve(currentCount); + RowNode* current = nodeAt(0); + std::size_t desiredPosition = 0; + bool insertionOnly = true; + while (current && insertionOnly) { + const std::size_t insertionFirst = desiredPosition; + while (desiredPosition < desired.size() && desired[desiredPosition].stableKey != current->value.stableKey) + ++desiredPosition; + if (desiredPosition == desired.size()) { + insertionOnly = false; + break; + } + if (desiredPosition != insertionFirst) + insertions.push_back({insertionFirst, desiredPosition - insertionFirst}); + const Row& replacement = desired[desiredPosition]; + insertionOnly = + structurallyCompatible(current->value.card.key, current->value.card.kind, current->value.card.target, replacement.card); + retainedNodes.push_back(current); + retainedPositions.push_back(desiredPosition); + ++desiredPosition; + current = nextNode(current); + } + if (insertionOnly && retainedPositions.size() == currentCount) { + if (desiredPosition != desired.size()) + insertions.push_back({desiredPosition, desired.size() - desiredPosition}); + for (const InsertionRun& insertion : insertions) { + const int firstRow = static_cast(insertion.first); + beginInsertRows({}, firstRow, firstRow + static_cast(insertion.count) - 1); + auto [before, after] = splitRows(std::move(rows_), insertion.first); + rows_ = mergeRows(mergeRows(std::move(before), buildRows(desired, insertion.first, insertion.first + insertion.count)), + std::move(after)); + rebuildIndexes(); + endInsertRows(); + incrementProperty("modelInsertCount"); + } + bool rowsUpdated = false; + for (std::size_t index = 0; index < currentCount; ++index) { + const std::size_t position = retainedPositions[index]; + RowNode* retained = retainedNodes[index]; + if (retained->value == desired[position]) + continue; + updateRow(retained, static_cast(position), std::move(desired[position])); + rowsUpdated = true; + } + return !insertions.empty() || rowsUpdated || chromeChanged ? StructuralChangeResult::Changed + : StructuralChangeResult::Unchanged; + } + } + std::unordered_set desiredKeys; + desiredKeys.reserve(desired.size()); + for (const Row& row : desired) + desiredKeys.insert(row.stableKey); + + bool changed = chromeChanged; + for (std::size_t offset = nodeCount(rows_); offset > 0;) { + std::size_t last = offset - 1; + const RowNode* lastNode = nodeAt(last); + if (lastNode && desiredKeys.contains(lastNode->value.stableKey)) { + offset = last; + continue; + } + std::size_t first = last; + while (first > 0 && !desiredKeys.contains(nodeAt(first - 1)->value.stableKey)) + --first; + beginRemoveRows({}, static_cast(first), static_cast(last)); + for (std::size_t position = last + 1; position > first; --position) + (void) takeRow(position - 1); + endRemoveRows(); + incrementProperty("modelRemoveCount"); + changed = true; + offset = first; + } + + std::vector inserted(desired.size(), false); + for (std::size_t position = 0; position < desired.size(); ++position) { + const RowNode* current = nodeAt(position); + if (current && current->value.stableKey == desired[position].stableKey) + continue; + const auto found = stableRows_.find(desired[position].stableKey); + const std::optional source = found == stableRows_.end() ? std::nullopt : rowOf(found->second); + if (!source) { + std::size_t count = 1; + while (position + count < desired.size() && !stableRows_.contains(desired[position + count].stableKey)) + ++count; + beginInsertRows({}, static_cast(position), static_cast(position + count - 1)); + for (std::size_t inserted = 0; inserted < count; ++inserted) + insertRow(position + inserted, std::move(desired[position + inserted])); + endInsertRows(); + std::fill(inserted.begin() + static_cast(position), + inserted.begin() + static_cast(position + count), + true); + incrementProperty("modelInsertCount"); + changed = true; + position += count - 1; + continue; + } + + beginMoveRows({}, *source, *source, {}, static_cast(position)); + std::unique_ptr moved = takeRow(static_cast(*source)); + insertRow(position, std::move(moved->value)); + endMoveRows(); + incrementProperty("modelMoveCount"); + changed = true; + } + + for (std::size_t position = 0; position < desired.size(); ++position) { + if (inserted[position]) + continue; + const RowNode* current = nodeAt(position); + if (current && current->value == desired[position]) + continue; + updateRow(static_cast(position), std::move(desired[position])); + changed = true; + } + return changed ? StructuralChangeResult::Changed : StructuralChangeResult::Unchanged; } - std::size_t first = last; - while (first > 0 && - !desiredKeys.contains(nodeAt(first - 1)->value.stableKey)) - --first; - beginRemoveRows({}, static_cast(first), static_cast(last)); - for (std::size_t position = last + 1; position > first; --position) - (void)takeRow(position - 1); - endRemoveRows(); - incrementProperty("modelRemoveCount"); - changed = true; - offset = first; - } - - std::vector inserted(desired.size(), false); - for (std::size_t position = 0; position < desired.size(); ++position) { - const RowNode *current = nodeAt(position); - if (current && current->value.stableKey == desired[position].stableKey) - continue; - const auto found = stableRows_.find(desired[position].stableKey); - const std::optional source = - found == stableRows_.end() ? std::nullopt : rowOf(found->second); - if (!source) { - std::size_t count = 1; - while (position + count < desired.size() && - !stableRows_.contains(desired[position + count].stableKey)) - ++count; - beginInsertRows({}, static_cast(position), - static_cast(position + count - 1)); - for (std::size_t inserted = 0; inserted < count; ++inserted) - insertRow(position + inserted, std::move(desired[position + inserted])); - endInsertRows(); - std::fill(inserted.begin() + static_cast(position), - inserted.begin() + - static_cast(position + count), - true); - incrementProperty("modelInsertCount"); - changed = true; - position += count - 1; - continue; + + ConversationItemModel::CardUpdateResult ConversationItemModel::cardUpdateResult(const VisibleCardData& card) const { + const std::string key = stableKey(card.key); + const auto found = stableRows_.find(key); + if (found == stableRows_.end()) + return CardUpdateResult::Missing; + const std::optional modelRow = rowOf(found->second); + if (!modelRow) + return CardUpdateResult::Missing; + const Row& current = found->second->value; + if (current.card.key != card.key || current.card.kind != card.kind || current.card.target != card.target) + return CardUpdateResult::Incompatible; + if (current.card == card) + return CardUpdateResult::Unchanged; + return CardUpdateResult::Changed; } - beginMoveRows({}, *source, *source, {}, static_cast(position)); - std::unique_ptr moved = takeRow(static_cast(*source)); - insertRow(position, std::move(moved->value)); - endMoveRows(); - incrementProperty("modelMoveCount"); - changed = true; - } - - for (std::size_t position = 0; position < desired.size(); ++position) { - if (inserted[position]) - continue; - const RowNode *current = nodeAt(position); - if (current && current->value == desired[position]) - continue; - updateRow(static_cast(position), std::move(desired[position])); - changed = true; - } - return changed ? StructuralChangeResult::Changed - : StructuralChangeResult::Unchanged; -} - -ConversationItemModel::CardUpdateResult -ConversationItemModel::cardUpdateResult(const VisibleCardData &card) const { - const std::string key = stableKey(card.key); - const auto found = stableRows_.find(key); - if (found == stableRows_.end()) - return CardUpdateResult::Missing; - const std::optional modelRow = rowOf(found->second); - if (!modelRow) - return CardUpdateResult::Missing; - const Row ¤t = found->second->value; - if (current.card.key != card.key || current.card.kind != card.kind || - current.card.target != card.target) - return CardUpdateResult::Incompatible; - if (current.card == card) - return CardUpdateResult::Unchanged; - return CardUpdateResult::Changed; -} - -ConversationItemModel::CardUpdateResult -ConversationItemModel::updateCard(VisibleCardData card) { - const CardUpdateResult admission = cardUpdateResult(card); - if (admission != CardUpdateResult::Changed) - return admission; - - const std::string key = stableKey(card.key); - const auto found = stableRows_.find(key); - const std::optional modelRow = rowOf(found->second); - Row ¤t = found->second->value; - const bool wasPresented = current.presented; - current.card = std::move(card); - current.presented = isPresented(current.card); - QList roles{PresentationRole, Qt::AccessibleTextRole}; - if (wasPresented != current.presented) - roles.push_back(PresentedRole); - emit dataChanged(index(*modelRow), index(*modelRow), roles); - incrementProperty("modelDataChangeCount"); - return CardUpdateResult::Changed; -} - -std::optional -ConversationItemModel::planStructuralDelta( - std::span rows, - std::span removals) const { - const auto reject = [&](const char *) -> std::optional { - return std::nullopt; - }; - struct VirtualRow { - CardKey key; - CardKind kind = CardKind::GenericActivity; - nodegraph::NodeRef target; - std::string stableKey; - std::string sectionKey; - bool turnRoot = false; - bool nested = false; - }; - struct VirtualSequence { - struct Segment { - std::size_t originalFirst = 0; - std::size_t originalCount = 0; - std::optional value; - - [[nodiscard]] std::size_t size() const noexcept { - return value ? 1 : originalCount; - } - }; - - explicit VirtualSequence(const ConversationItemModel &source) - : source(source) { - if (source.rowCount() != 0) - segments.push_back( - {0, static_cast(source.rowCount()), std::nullopt}); + ConversationItemModel::CardUpdateResult ConversationItemModel::updateCard(VisibleCardData card) { + const CardUpdateResult admission = cardUpdateResult(card); + if (admission != CardUpdateResult::Changed) + return admission; + + const std::string key = stableKey(card.key); + const auto found = stableRows_.find(key); + const std::optional modelRow = rowOf(found->second); + Row& current = found->second->value; + const bool wasPresented = current.presented; + current.card = std::move(card); + current.presented = isPresented(current.card); + QList roles{PresentationRole, Qt::AccessibleTextRole}; + if (wasPresented != current.presented) + roles.push_back(PresentedRole); + emit dataChanged(index(*modelRow), index(*modelRow), roles); + incrementProperty("modelDataChangeCount"); + return CardUpdateResult::Changed; } - [[nodiscard]] static VirtualRow project(const Row &row) { - return {row.card.key, row.card.kind, row.card.target, row.stableKey, - row.sectionKey, row.turnRoot, row.nested}; + std::optional + ConversationItemModel::planStructuralDelta(std::span rows, + std::span removals) const { + const auto reject = [&](const char*) -> std::optional { + return std::nullopt; + }; + struct VirtualRow { + CardKey key; + CardKind kind = CardKind::GenericActivity; + nodegraph::NodeRef target; + std::string stableKey; + std::string sectionKey; + bool turnRoot = false; + bool nested = false; + }; + struct VirtualSequence { + struct Segment { + std::size_t originalFirst = 0; + std::size_t originalCount = 0; + std::optional value; + + [[nodiscard]] std::size_t size() const noexcept { + return value ? 1 : originalCount; + } + }; + + explicit VirtualSequence(const ConversationItemModel& source) + : source(source) { + if (source.rowCount() != 0) + segments.push_back({0, static_cast(source.rowCount()), std::nullopt}); + } + + [[nodiscard]] static VirtualRow project(const Row& row) { + return {row.card.key, row.card.kind, row.card.target, row.stableKey, row.sectionKey, row.turnRoot, row.nested}; + } + + [[nodiscard]] int size() const noexcept { + std::size_t result = 0; + for (const Segment& segment : segments) + result += segment.size(); + return static_cast(result); + } + + [[nodiscard]] std::optional at(int position) const { + if (position < 0) + return std::nullopt; + std::size_t offset = static_cast(position); + for (const Segment& segment : segments) { + if (offset >= segment.size()) { + offset -= segment.size(); + continue; + } + if (segment.value) + return *segment.value; + const Row* row = source.row(static_cast(segment.originalFirst + offset)); + return row ? std::optional(project(*row)) : std::nullopt; + } + return std::nullopt; + } + + [[nodiscard]] std::optional locateStable(const std::string& key) const { + int position = 0; + for (const Segment& segment : segments) { + if (segment.value && segment.value->stableKey == key) + return position; + position += static_cast(segment.size()); + } + const QModelIndex original = source.indexForStableKey(key); + return original.isValid() ? locateOriginal(original.row()) : std::nullopt; + } + + [[nodiscard]] std::optional locateTarget(const nodegraph::NodeRef& target) const { + if (!target) + return std::nullopt; + int position = 0; + for (const Segment& segment : segments) { + if (segment.value && segment.value->target == target) + return position; + position += static_cast(segment.size()); + } + const QModelIndex original = source.indexForTarget(target); + return original.isValid() ? locateOriginal(original.row()) : std::nullopt; + } + + [[nodiscard]] std::optional erase(int position) { + const std::optional removed = at(position); + if (!removed) + return std::nullopt; + const std::size_t first = splitAt(static_cast(position)); + const std::size_t after = splitAt(static_cast(position + 1)); + segments.erase(segments.begin() + static_cast(first), + segments.begin() + static_cast(after)); + return removed; + } + + void insert(int position, VirtualRow row) { + const std::size_t at = splitAt(static_cast(position)); + segments.insert(segments.begin() + static_cast(at), Segment{0, 0, std::move(row)}); + } + + private: + [[nodiscard]] std::optional locateOriginal(int original) const { + int position = 0; + for (const Segment& segment : segments) { + if (!segment.value && original >= static_cast(segment.originalFirst) && + original < static_cast(segment.originalFirst + segment.originalCount)) + return position + original - static_cast(segment.originalFirst); + position += static_cast(segment.size()); + } + return std::nullopt; + } + + std::size_t splitAt(std::size_t position) { + std::size_t offset = 0; + for (std::size_t index = 0; index < segments.size(); ++index) { + Segment& segment = segments[index]; + if (position == offset) + return index; + if (position < offset + segment.size()) { + const std::size_t leftCount = position - offset; + Segment right{segment.originalFirst + leftCount, segment.originalCount - leftCount, std::nullopt}; + segment.originalCount = leftCount; + segments.insert(segments.begin() + static_cast(index + 1), std::move(right)); + return index + 1; + } + offset += segment.size(); + } + return segments.size(); + } + + const ConversationItemModel& source; + std::vector segments; + } sequence(*this); + + struct VirtualSection { + std::size_t count = 0; + bool hasRoot = false; + std::string firstKey; + }; + std::unordered_map sections; + const auto section = [&](const std::string& key) -> VirtualSection& { + if (const auto found = sections.find(key); found != sections.end()) + return found->second; + VirtualSection value; + if (const auto found = sectionRows_.find(key); found != sectionRows_.end()) { + value.count = found->second.count; + value.hasRoot = found->second.root != nullptr; + if (found->second.first) + value.firstKey = found->second.first->value.stableKey; + } + return sections.emplace(key, value).first->second; + }; + const auto removeVirtual = [&](int position) { + const std::optional removed = sequence.erase(position); + if (!removed) + return false; + VirtualSection& owner = section(removed->sectionKey); + if (owner.count == 0) + return false; + --owner.count; + if (removed->turnRoot) + owner.hasRoot = false; + if (owner.firstKey == removed->stableKey) { + const std::optional next = sequence.at(position); + owner.firstKey = next && next->sectionKey == removed->sectionKey ? next->stableKey : std::string{}; + } + return true; + }; + const auto insertVirtual = [&](int position, VirtualRow row) { + VirtualSection& owner = section(row.sectionKey); + const std::optional first = sequence.locateStable(owner.firstKey); + if (owner.count == 0 || (first && position <= *first)) + owner.firstKey = row.stableKey; + ++owner.count; + owner.hasRoot = owner.hasRoot || row.turnRoot; + sequence.insert(position, std::move(row)); + }; + + std::unordered_map desiredRows; + std::unordered_set desiredTargets; + std::unordered_set removedTargets; + desiredRows.reserve(rows.size()); + desiredTargets.reserve(rows.size()); + removedTargets.reserve(removals.size()); + for (std::size_t index = 0; index < rows.size(); ++index) { + const ConversationRowChange& change = rows[index]; + const VisibleCardData& card = change.placement.card; + const std::string key = stableKey(card.key); + if (key.empty() || card.threadId != threadId_ || change.placement.sectionKey.empty() || + !desiredRows.emplace(key, index).second || (card.target && !desiredTargets.insert(card.target.get()).second)) + return std::nullopt; + } + for (const nodegraph::NodeRef& target : removals) { + if (!target || !removedTargets.insert(target.get()).second || desiredTargets.contains(target.get())) + return std::nullopt; + } + + StructuralDeltaPlan result; + std::vector settled(rows.size(), false); + std::vector replacedRoots(removals.size(), false); + for (std::size_t removalIndex = 0; removalIndex < removals.size(); ++removalIndex) { + const std::optional position = sequence.locateTarget(removals[removalIndex]); + const std::optional current = position ? sequence.at(*position) : std::nullopt; + if (!current || !current->turnRoot || section(current->sectionKey).count < 2) + continue; + + std::optional replacementIndex; + for (std::size_t index = 0; index < rows.size(); ++index) { + const ConversationRowPlacement& placement = rows[index].placement; + const std::string key = stableKey(placement.card.key); + if (settled[index] || !placement.turnRoot || placement.nested || placement.sectionKey != current->sectionKey || + key == current->stableKey || sequence.locateStable(key) || sequence.locateTarget(placement.card.target)) + continue; + if (replacementIndex) { + replacementIndex.reset(); + break; + } + replacementIndex = index; + } + if (!replacementIndex) + continue; + + const ConversationRowPlacement& placement = rows[*replacementIndex].placement; + VirtualRow replacement{placement.card.key, + placement.card.kind, + placement.card.target, + stableKey(placement.card.key), + placement.sectionKey, + true, + false}; + if (!removeVirtual(*position)) + return std::nullopt; + insertVirtual(*position, std::move(replacement)); + + StructuralDeltaPlan::Operation operation; + operation.kind = StructuralDeltaPlan::Operation::Kind::ReplaceRoot; + operation.deltaIndex = *replacementIndex; + operation.removalIndex = removalIndex; + operation.source = *position; + operation.destination = *position; + operation.oldStableKey = current->stableKey; + operation.stableKey = stableKey(placement.card.key); + operation.oldSection = current->sectionKey; + operation.section = placement.sectionKey; + result.operations.push_back(std::move(operation)); + settled[*replacementIndex] = true; + replacedRoots[removalIndex] = true; + } + + for (std::size_t index = 0; index < removals.size(); ++index) { + if (replacedRoots[index]) + continue; + const std::optional position = sequence.locateTarget(removals[index]); + const std::optional current = position ? sequence.at(*position) : std::nullopt; + if (!current) + continue; + const auto desired = desiredRows.find(current->stableKey); + const bool replaced = desired != desiredRows.end() && rows[desired->second].placement.card.target != removals[index]; + if (replaced) + continue; + if (!removeVirtual(*position)) + return std::nullopt; + StructuralDeltaPlan::Operation operation; + operation.kind = StructuralDeltaPlan::Operation::Kind::Remove; + operation.removalIndex = index; + operation.source = *position; + operation.oldStableKey = current->stableKey; + operation.oldSection = current->sectionKey; + result.operations.push_back(std::move(operation)); + } + + for (std::size_t attempt = 0; attempt < 2 * rows.size(); ++attempt) { + const std::size_t index = attempt < rows.size() ? attempt : 2 * rows.size() - attempt - 1; + if (settled[index]) + continue; + const ConversationRowChange& change = rows[index]; + const VisibleCardData& card = change.placement.card; + const std::string key = stableKey(card.key); + const std::optional stable = sequence.locateStable(key); + const std::optional target = sequence.locateTarget(card.target); + if (stable && target && *stable != *target) + return reject("stable-target-disagree"); + if (!stable && target) + return reject("target-without-stable"); + + const int source = stable ? *stable : -1; + const std::optional current = source >= 0 ? sequence.at(source) : std::nullopt; + if (current && (!current->target || !structurallyCompatible(current->key, current->kind, current->target, card))) + return reject("incompatible-current"); + const bool materializesLocalPrompt = current && current->kind == CardKind::LocalPrompt && card.kind == CardKind::UserMessage; + const bool rehomesLocalPrompt = + current && current->kind == CardKind::LocalPrompt && card.kind == CardKind::LocalPrompt && current->target == card.target; + if (current && !materializesLocalPrompt && !rehomesLocalPrompt && + (current->turnRoot != change.placement.turnRoot || + (current->turnRoot && current->sectionKey != change.placement.sectionKey))) + return reject("section-change"); + + const auto pending = [&](const std::optional& neighbor) { + if (!neighbor) + return false; + const auto found = desiredRows.find(stableKey(*neighbor)); + return found != desiredRows.end() && !settled[found->second]; + }; + const int previous = change.previousCardKey && !pending(change.previousCardKey) + ? sequence.locateStable(stableKey(*change.previousCardKey)).value_or(-1) + : -1; + const int next = change.nextCardKey && !pending(change.nextCardKey) + ? sequence.locateStable(stableKey(*change.nextCardKey)).value_or(-1) + : -1; + const bool connected = source >= 0 || previous >= 0 || next >= 0 || !change.nextCardKey || sequence.size() == 0; + if (!connected) + continue; + + int destination = -1; + if (!change.previousCardKey) { + destination = 0; + } else if (!change.nextCardKey) { + destination = sequence.size() - static_cast(source >= 0); + } else if (previous >= 0 && previous != source) { + destination = previous + 1; + if (source >= 0 && source < destination) + --destination; + } else if (next >= 0 && next != source) { + destination = next; + if (source >= 0 && source < destination) + --destination; + } + if (destination < 0) { + if (sequence.size() == 0) + destination = 0; + else + continue; + } + + if (source >= 0 && !removeVirtual(source)) + return reject("invalid-destination"); + if (destination < 0 || destination > sequence.size() || sequence.locateStable(key) || sequence.locateTarget(card.target)) + return reject("invalid-current-placement"); + + VirtualRow replacement{ + card.key, card.kind, card.target, key, change.placement.sectionKey, change.placement.turnRoot, change.placement.nested}; + const std::optional previousRow = sequence.at(destination - 1); + const std::optional nextRow = sequence.at(destination); + const VirtualSection& owner = section(replacement.sectionKey); + const bool previousInSection = previousRow && previousRow->sectionKey == replacement.sectionKey; + const bool nextInSection = nextRow && nextRow->sectionKey == replacement.sectionKey; + const bool exactTail = source < 0 && !change.nextCardKey && destination == sequence.size(); + const bool valid = validSectionPlacement( + replacement.turnRoot, replacement.nested, owner.count, owner.hasRoot, previousInSection, nextInSection); + if (!valid) + return std::nullopt; + if (current && current->turnRoot && source != destination) + return std::nullopt; + insertVirtual(destination, std::move(replacement)); + StructuralDeltaPlan::Operation operation; + operation.kind = StructuralDeltaPlan::Operation::Kind::Place; + operation.deltaIndex = index; + operation.source = source; + operation.destination = destination; + operation.tailAppend = exactTail; + operation.oldStableKey = current ? current->stableKey : std::string{}; + operation.stableKey = key; + operation.oldSection = current ? current->sectionKey : std::string{}; + operation.section = change.placement.sectionKey; + result.operations.push_back(std::move(operation)); + settled[index] = true; + } + + for (std::size_t index = 0; index < rows.size(); ++index) { + if (!settled[index]) { + return reject("unsettled"); + } + } + + for (const StructuralDeltaPlan::Operation& operation : result.operations) { + if (operation.kind == StructuralDeltaPlan::Operation::Kind::Remove) + continue; + const ConversationRowChange& change = rows[operation.deltaIndex]; + const std::optional position = sequence.locateStable(stableKey(change.placement.card.key)); + if (!position) + return reject("missing-after-plan"); + if ((!change.previousCardKey && *position != 0) || (!change.nextCardKey && *position != sequence.size() - 1)) + return reject("edge-mismatch"); + const auto adjacent = [&](const std::optional& neighbor, int offset) { + if (!neighbor) + return true; + const std::string neighborKey = stableKey(*neighbor); + const std::optional neighborPosition = sequence.locateStable(neighborKey); + return neighborPosition && *neighborPosition + offset == *position; + }; + if (!adjacent(change.previousCardKey, 1) || !adjacent(change.nextCardKey, -1)) { + return reject("adjacency-mismatch"); + } + } + + return result; } - [[nodiscard]] int size() const noexcept { - std::size_t result = 0; - for (const Segment &segment : segments) - result += segment.size(); - return static_cast(result); + std::optional + ConversationItemModel::applyStructuralDelta(std::vector& rows, std::span removals) { + std::optional plan = planStructuralDelta(rows, removals); + if (!plan) + return std::nullopt; + commitStructuralDelta(*plan, rows, removals); + return plan; } - [[nodiscard]] std::optional at(int position) const { - if (position < 0) - return std::nullopt; - std::size_t offset = static_cast(position); - for (const Segment &segment : segments) { - if (offset >= segment.size()) { - offset -= segment.size(); - continue; + void ConversationItemModel::commitStructuralDelta(StructuralDeltaPlan& plan, + std::vector& rows, + std::span removals) { + struct SectionChange { + SectionStructure before; + std::vector changedKeys; + }; + std::unordered_map changedSections; + const auto touch = [this, &changedSections](const std::string& section, const std::string& key) { + if (section.empty()) + return; + auto [found, inserted] = changedSections.try_emplace(section); + if (inserted) + found->second.before = sectionStructure(section); + if (!key.empty() && std::ranges::find(found->second.changedKeys, key) == found->second.changedKeys.end()) + found->second.changedKeys.push_back(key); + }; + + for (StructuralDeltaPlan::Operation& operation : plan.operations) { + if (operation.kind == StructuralDeltaPlan::Operation::Kind::ReplaceRoot) { + const QModelIndex sourceIndex = indexForTarget(removals[operation.removalIndex]); + Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); + const Row* current = row(sourceIndex.row()); + Q_ASSERT(current && current->turnRoot && current->sectionKey == operation.oldSection); + touch(operation.oldSection, operation.oldStableKey); + touch(operation.section, operation.stableKey); + + Row replacement = rowFromPlacement(std::move(rows[operation.deltaIndex].placement)); + const bool finalFirstInTurn = current->firstInTurn; + replacement.lastInTurn = current->lastInTurn; + const bool finalActive = replacement.activeTurn; + replacement.turnRoot = false; + replacement.nested = true; + replacement.firstInTurn = false; + replacement.activeTurn = false; + + const int insertedRow = sourceIndex.row() + 1; + beginInsertRows({}, insertedRow, insertedRow); + insertRow(static_cast(insertedRow), std::move(replacement)); + endInsertRows(); + incrementProperty("modelInsertCount"); + incrementProperty("modelExactInsertCount"); + + beginRemoveRows({}, sourceIndex.row(), sourceIndex.row()); + (void) takeRow(static_cast(sourceIndex.row())); + RowNode* promoted = nodeAt(static_cast(sourceIndex.row())); + Q_ASSERT(promoted && promoted->value.stableKey == operation.stableKey); + removeSectionIdentity(promoted); + promoted->value.turnRoot = true; + promoted->value.nested = false; + promoted->value.firstInTurn = finalFirstInTurn; + promoted->value.activeTurn = finalActive; + addSectionIdentity(promoted); + endRemoveRows(); + incrementProperty("modelRemoveCount"); + incrementProperty("modelExactRemoveCount"); + emit dataChanged( + index(sourceIndex.row()), index(sourceIndex.row()), {TurnRootRole, NestedCardRole, FirstInTurnRole, ActiveTurnRole}); + incrementProperty("modelDataChangeCount"); + continue; + } + + if (operation.kind == StructuralDeltaPlan::Operation::Kind::Remove) { + const QModelIndex sourceIndex = indexForTarget(removals[operation.removalIndex]); + Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); + touch(operation.oldSection, operation.oldStableKey); + beginRemoveRows({}, sourceIndex.row(), sourceIndex.row()); + (void) takeRow(static_cast(sourceIndex.row())); + endRemoveRows(); + incrementProperty("modelRemoveCount"); + incrementProperty("modelExactRemoveCount"); + continue; + } + + Row replacement = rowFromPlacement(std::move(rows[operation.deltaIndex].placement)); + if (operation.source < 0) { + touch(operation.section, operation.stableKey); + const Row* previous = row(operation.destination - 1); + const Row* next = row(operation.destination); + replacement.firstInTurn = !previous || previous->sectionKey != replacement.sectionKey; + replacement.lastInTurn = !next || next->sectionKey != replacement.sectionKey; + beginInsertRows({}, operation.destination, operation.destination); + insertRow(static_cast(operation.destination), std::move(replacement)); + endInsertRows(); + incrementProperty("modelInsertCount"); + incrementProperty(operation.tailAppend ? "modelTailAppendCount" : "modelExactInsertCount"); + continue; + } + + const QModelIndex sourceIndex = indexForStableKey(operation.oldStableKey); + Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); + const Row* current = row(sourceIndex.row()); + Q_ASSERT(current); + replacement.firstInTurn = current->firstInTurn; + replacement.lastInTurn = current->lastInTurn; + const bool movedRows = operation.source != operation.destination; + const bool presentationChanged = *current != replacement; + operation.changed = movedRows || presentationChanged; + if (!operation.changed) + continue; + touch(operation.oldSection, operation.oldStableKey); + touch(operation.section, operation.stableKey); + if (movedRows) { + const int destinationChild = operation.destination > operation.source ? operation.destination + 1 : operation.destination; + beginMoveRows({}, operation.source, operation.source, {}, destinationChild); + std::unique_ptr moved = takeRow(static_cast(operation.source)); + insertRow(static_cast(operation.destination), std::move(moved->value)); + endMoveRows(); + incrementProperty("modelMoveCount"); + } + + Row& moved = nodeAt(static_cast(operation.destination))->value; + replacement.firstInTurn = moved.firstInTurn; + replacement.lastInTurn = moved.lastInTurn; + if (presentationChanged || movedRows) + updateRow(operation.destination, std::move(replacement)); + incrementProperty(movedRows ? "modelExactMoveCount" : "modelExactPlacementUpdateCount"); } - if (segment.value) - return *segment.value; - const Row *row = - source.row(static_cast(segment.originalFirst + offset)); - return row ? std::optional(project(*row)) : std::nullopt; - } - return std::nullopt; + + for (auto& [section, change] : changedSections) + refreshSectionStructure(section, change.before, change.changedKeys); + } + + bool ConversationItemModel::setProviderHasMore(bool providerHasMore) noexcept { + if (hasMore_ == providerHasMore) + return false; + hasMore_ = providerHasMore; + return true; } - [[nodiscard]] std::optional - locateStable(const std::string &key) const { - int position = 0; - for (const Segment &segment : segments) { - if (segment.value && segment.value->stableKey == key) - return position; - position += static_cast(segment.size()); - } - const QModelIndex original = source.indexForStableKey(key); - return original.isValid() ? locateOriginal(original.row()) : std::nullopt; + bool ConversationItemModel::setVisibility(Visibility visibility) { + if (visibility_ == visibility) + return false; + visibility_ = visibility; + int first = -1; + bool changed = false; + for (int position = 0; position < rowCount(); ++position) { + Row& current = nodeAt(static_cast(position))->value; + const bool presented = isPresented(current.card); + if (presented == current.presented) { + if (first >= 0) { + emit dataChanged(index(first), index(position - 1), {PresentedRole}); + incrementProperty("modelDataChangeCount"); + first = -1; + } + continue; + } + current.presented = presented; + changed = true; + if (first < 0) + first = position; + } + if (first < 0) + return changed; + emit dataChanged(index(first), index(rowCount() - 1), {PresentedRole}); + incrementProperty("modelDataChangeCount"); + return true; } - [[nodiscard]] std::optional - locateTarget(const nodegraph::NodeRef &target) const { - if (!target) - return std::nullopt; - int position = 0; - for (const Segment &segment : segments) { - if (segment.value && segment.value->target == target) - return position; - position += static_cast(segment.size()); - } - const QModelIndex original = source.indexForTarget(target); - return original.isValid() ? locateOriginal(original.row()) : std::nullopt; + const ConversationItemModel::Row* ConversationItemModel::row(int rowIndex) const noexcept { + const RowNode* node = rowIndex >= 0 ? nodeAt(static_cast(rowIndex)) : nullptr; + return node ? &node->value : nullptr; } - [[nodiscard]] std::optional erase(int position) { - const std::optional removed = at(position); - if (!removed) - return std::nullopt; - const std::size_t first = splitAt(static_cast(position)); - const std::size_t after = splitAt(static_cast(position + 1)); - segments.erase(segments.begin() + static_cast(first), - segments.begin() + static_cast(after)); - return removed; + const VisibleCardData* ConversationItemModel::card(int rowIndex) const noexcept { + const Row* value = row(rowIndex); + return value ? &value->card : nullptr; } - void insert(int position, VirtualRow row) { - const std::size_t at = splitAt(static_cast(position)); - segments.insert(segments.begin() + static_cast(at), - Segment{0, 0, std::move(row)}); + QModelIndex ConversationItemModel::indexForStableKey(const std::string& key) const { + const auto found = stableRows_.find(key); + if (found == stableRows_.end()) + return {}; + const std::optional row = rowOf(found->second); + return row ? index(*row) : QModelIndex{}; } - private: - [[nodiscard]] std::optional locateOriginal(int original) const { - int position = 0; - for (const Segment &segment : segments) { - if (!segment.value && - original >= static_cast(segment.originalFirst) && - original < - static_cast(segment.originalFirst + segment.originalCount)) - return position + original - static_cast(segment.originalFirst); - position += static_cast(segment.size()); - } - return std::nullopt; + QModelIndex ConversationItemModel::indexForTarget(const nodegraph::NodeRef& target) const { + if (!target) + return {}; + const auto found = targetRows_.find(target.get()); + if (found == targetRows_.end()) + return {}; + const std::optional modelRow = rowOf(found->second); + const Row* candidate = modelRow ? row(*modelRow) : nullptr; + return candidate && candidate->card.target == target ? index(*modelRow) : QModelIndex{}; } - std::size_t splitAt(std::size_t position) { - std::size_t offset = 0; - for (std::size_t index = 0; index < segments.size(); ++index) { - Segment &segment = segments[index]; - if (position == offset) - return index; - if (position < offset + segment.size()) { - const std::size_t leftCount = position - offset; - Segment right{segment.originalFirst + leftCount, - segment.originalCount - leftCount, std::nullopt}; - segment.originalCount = leftCount; - segments.insert(segments.begin() + - static_cast(index + 1), - std::move(right)); - return index + 1; + std::vector ConversationItemModel::flatten(ConversationSnapshot&& snapshot) const { + std::size_t count = 0; + for (const TurnSection& section : snapshot.sections) + count += section.cards.size(); + std::vector result; + result.reserve(count); + for (TurnSection& section : snapshot.sections) { + std::optional root; + if (section.rootCardKey) + root = stableKey(*section.rootCardKey); + const auto representedRoot = root ? std::ranges::find_if(section.cards, + [&](const auto& card) { + return stableKey(card.key) == *root; + }) + : section.cards.end(); + const std::optional rootPosition = + representedRoot == section.cards.end() + ? std::nullopt + : std::optional{static_cast(std::distance(section.cards.begin(), representedRoot))}; + for (std::size_t position = 0; position < section.cards.size(); ++position) { + VisibleCardData card = std::move(section.cards[position]); + const std::string key = stableKey(card.key); + const bool turnRoot = rootPosition && position == *rootPosition; + result.push_back(Row{std::move(card), + key, + section.key, + turnRoot, + isNestedTurnCard(rootPosition, position), + position == 0, + position + 1 == section.cards.size(), + false, + false}); + Row& row = result.back(); + row.presented = isPresented(row.card); + row.activeTurn = turnRoot && snapshot.activeTurnId && row.card.turnId == *snapshot.activeTurnId; + } } - offset += segment.size(); - } - return segments.size(); + return result; } - const ConversationItemModel &source; - std::vector segments; - } sequence(*this); - - struct VirtualSection { - std::size_t count = 0; - bool hasRoot = false; - std::string firstKey; - }; - std::unordered_map sections; - const auto section = [&](const std::string &key) -> VirtualSection & { - if (const auto found = sections.find(key); found != sections.end()) - return found->second; - VirtualSection value; - if (const auto found = sectionRows_.find(key); - found != sectionRows_.end()) { - value.count = found->second.count; - value.hasRoot = found->second.root != nullptr; - if (found->second.first) - value.firstKey = found->second.first->value.stableKey; + bool ConversationItemModel::rowsAreUnique(const std::vector& rows) const { + std::unordered_set stableKeys; + std::unordered_set targets; + stableKeys.reserve(rows.size()); + targets.reserve(rows.size()); + for (const Row& row : rows) { + if (row.stableKey.empty() || !stableKeys.insert(row.stableKey).second) + return false; + if (row.card.target && !targets.insert(row.card.target.get()).second) + return false; + } + return true; } - return sections.emplace(key, value).first->second; - }; - const auto removeVirtual = [&](int position) { - const std::optional removed = sequence.erase(position); - if (!removed) - return false; - VirtualSection &owner = section(removed->sectionKey); - if (owner.count == 0) - return false; - --owner.count; - if (removed->turnRoot) - owner.hasRoot = false; - if (owner.firstKey == removed->stableKey) { - const std::optional next = sequence.at(position); - owner.firstKey = next && next->sectionKey == removed->sectionKey - ? next->stableKey - : std::string{}; + + ConversationItemModel::Row ConversationItemModel::rowFromPlacement(ConversationRowPlacement placement) const { + Row result; + result.card = std::move(placement.card); + result.stableKey = stableKey(result.card.key); + result.sectionKey = std::move(placement.sectionKey); + result.turnRoot = placement.turnRoot; + result.nested = placement.nested; + result.presented = isPresented(result.card); + result.activeTurn = placement.turnRoot && placement.activeTurn; + return result; } - return true; - }; - const auto insertVirtual = [&](int position, VirtualRow row) { - VirtualSection &owner = section(row.sectionKey); - const std::optional first = sequence.locateStable(owner.firstKey); - if (owner.count == 0 || (first && position <= *first)) - owner.firstKey = row.stableKey; - ++owner.count; - owner.hasRoot = owner.hasRoot || row.turnRoot; - sequence.insert(position, std::move(row)); - }; - - std::unordered_map desiredRows; - std::unordered_set desiredTargets; - std::unordered_set removedTargets; - desiredRows.reserve(rows.size()); - desiredTargets.reserve(rows.size()); - removedTargets.reserve(removals.size()); - for (std::size_t index = 0; index < rows.size(); ++index) { - const ConversationRowChange &change = rows[index]; - const VisibleCardData &card = change.placement.card; - const std::string key = stableKey(card.key); - if (key.empty() || card.threadId != threadId_ || - change.placement.sectionKey.empty() || - !desiredRows.emplace(key, index).second || - (card.target && !desiredTargets.insert(card.target.get()).second)) - return std::nullopt; - } - for (const nodegraph::NodeRef &target : removals) { - if (!target || !removedTargets.insert(target.get()).second || - desiredTargets.contains(target.get())) - return std::nullopt; - } - - StructuralDeltaPlan result; - std::vector settled(rows.size(), false); - std::vector replacedRoots(removals.size(), false); - for (std::size_t removalIndex = 0; removalIndex < removals.size(); - ++removalIndex) { - const std::optional position = - sequence.locateTarget(removals[removalIndex]); - const std::optional current = - position ? sequence.at(*position) : std::nullopt; - if (!current || !current->turnRoot || - section(current->sectionKey).count < 2) - continue; - - std::optional replacementIndex; - for (std::size_t index = 0; index < rows.size(); ++index) { - const ConversationRowPlacement &placement = rows[index].placement; - const std::string key = stableKey(placement.card.key); - if (settled[index] || !placement.turnRoot || placement.nested || - placement.sectionKey != current->sectionKey || - key == current->stableKey || sequence.locateStable(key) || - sequence.locateTarget(placement.card.target)) - continue; - if (replacementIndex) { - replacementIndex.reset(); - break; - } - replacementIndex = index; + + ConversationItemModel::SectionStructure ConversationItemModel::sectionStructure(const std::string& sectionKey) const { + SectionStructure result; + const auto found = sectionRows_.find(sectionKey); + if (found == sectionRows_.end()) + return result; + if (found->second.first) + result.first = found->second.first->value.stableKey; + if (found->second.last) + result.last = found->second.last->value.stableKey; + if (found->second.root) + result.root = found->second.root->value.stableKey; + return result; } - if (!replacementIndex) - continue; - - const ConversationRowPlacement &placement = - rows[*replacementIndex].placement; - VirtualRow replacement{placement.card.key, - placement.card.kind, - placement.card.target, - stableKey(placement.card.key), - placement.sectionKey, - true, - false}; - if (!removeVirtual(*position)) - return std::nullopt; - insertVirtual(*position, std::move(replacement)); - - StructuralDeltaPlan::Operation operation; - operation.kind = StructuralDeltaPlan::Operation::Kind::ReplaceRoot; - operation.deltaIndex = *replacementIndex; - operation.removalIndex = removalIndex; - operation.source = *position; - operation.destination = *position; - operation.oldStableKey = current->stableKey; - operation.stableKey = stableKey(placement.card.key); - operation.oldSection = current->sectionKey; - operation.section = placement.sectionKey; - result.operations.push_back(std::move(operation)); - settled[*replacementIndex] = true; - replacedRoots[removalIndex] = true; - } - - for (std::size_t index = 0; index < removals.size(); ++index) { - if (replacedRoots[index]) - continue; - const std::optional position = sequence.locateTarget(removals[index]); - const std::optional current = - position ? sequence.at(*position) : std::nullopt; - if (!current) - continue; - const auto desired = desiredRows.find(current->stableKey); - const bool replaced = - desired != desiredRows.end() && - rows[desired->second].placement.card.target != removals[index]; - if (replaced) - continue; - if (!removeVirtual(*position)) - return std::nullopt; - StructuralDeltaPlan::Operation operation; - operation.kind = StructuralDeltaPlan::Operation::Kind::Remove; - operation.removalIndex = index; - operation.source = *position; - operation.oldStableKey = current->stableKey; - operation.oldSection = current->sectionKey; - result.operations.push_back(std::move(operation)); - } - - for (std::size_t attempt = 0; attempt < 2 * rows.size(); ++attempt) { - const std::size_t index = - attempt < rows.size() ? attempt : 2 * rows.size() - attempt - 1; - if (settled[index]) - continue; - const ConversationRowChange &change = rows[index]; - const VisibleCardData &card = change.placement.card; - const std::string key = stableKey(card.key); - const std::optional stable = sequence.locateStable(key); - const std::optional target = sequence.locateTarget(card.target); - if (stable && target && *stable != *target) - return reject("stable-target-disagree"); - if (!stable && target) - return reject("target-without-stable"); - - const int source = stable ? *stable : -1; - const std::optional current = - source >= 0 ? sequence.at(source) : std::nullopt; - if (current && (!current->target || - !structurallyCompatible(current->key, current->kind, - current->target, card))) - return reject("incompatible-current"); - const bool materializesLocalPrompt = - current && current->kind == CardKind::LocalPrompt && - card.kind == CardKind::UserMessage; - const bool rehomesLocalPrompt = - current && current->kind == CardKind::LocalPrompt && - card.kind == CardKind::LocalPrompt && current->target == card.target; - if (current && !materializesLocalPrompt && !rehomesLocalPrompt && - (current->turnRoot != change.placement.turnRoot || - (current->turnRoot && - current->sectionKey != change.placement.sectionKey))) - return reject("section-change"); - - const auto pending = [&](const std::optional &neighbor) { - if (!neighbor) - return false; - const auto found = desiredRows.find(stableKey(*neighbor)); - return found != desiredRows.end() && !settled[found->second]; - }; - const std::optional previous = - change.previousCardKey && !pending(change.previousCardKey) - ? sequence.locateStable(stableKey(*change.previousCardKey)) - : std::nullopt; - const std::optional next = - change.nextCardKey && !pending(change.nextCardKey) - ? sequence.locateStable(stableKey(*change.nextCardKey)) - : std::nullopt; - const bool connected = source >= 0 || previous || next || - !change.nextCardKey || sequence.size() == 0; - if (!connected) - continue; - - int destination = -1; - if (!change.previousCardKey) { - destination = 0; - } else if (!change.nextCardKey) { - destination = sequence.size() - static_cast(source >= 0); - } else if (previous && *previous != source) { - destination = *previous + 1; - if (source >= 0 && source < destination) - --destination; - } else if (next && *next != source) { - destination = *next; - if (source >= 0 && source < destination) - --destination; + + void ConversationItemModel::refreshSectionStructure(const std::string& sectionKey, + const SectionStructure& before, + std::span changedKeys) { + if (sectionKey.empty()) + return; + const auto found = sectionRows_.find(sectionKey); + if (found == sectionRows_.end()) + return; + + const SectionStructure after = sectionStructure(sectionKey); + const std::optional rootPosition = found->second.root ? rowOf(found->second.root) : std::nullopt; + std::vector affected; + affected.reserve(7); + const auto retain = [this, &affected](const std::string& key) { + if (key.empty()) + return; + const auto found = stableRows_.find(key); + if (found != stableRows_.end() && std::ranges::find(affected, found->second) == affected.end()) + affected.push_back(found->second); + }; + retain(before.first); + retain(before.last); + retain(before.root); + retain(after.first); + retain(after.last); + retain(after.root); + for (const std::string& key : changedKeys) + retain(key); + + if (before.root.empty() != after.root.empty()) { + affected.clear(); + RowNode* node = found->second.first; + while (node && node->value.sectionKey == sectionKey) { + affected.push_back(node); + node = nextNode(node); + } + } + + for (RowNode* node : affected) { + incrementProperty("modelSectionStructureRowsTouched"); + const std::optional rowPosition = rowOf(node); + if (!rowPosition || node->value.sectionKey != sectionKey) + continue; + Row& current = node->value; + QList roles; + const bool firstInTurn = node == found->second.first; + const bool lastInTurn = node == found->second.last; + const bool nested = + rootPosition && isNestedTurnCard(static_cast(*rootPosition), static_cast(*rowPosition)); + if (current.firstInTurn != firstInTurn) { + current.firstInTurn = firstInTurn; + roles.push_back(FirstInTurnRole); + } + if (current.lastInTurn != lastInTurn) { + current.lastInTurn = lastInTurn; + roles.push_back(LastInTurnRole); + } + if (current.nested != nested) { + current.nested = nested; + roles.push_back(NestedCardRole); + } + if (current.activeTurn && !current.turnRoot) { + current.activeTurn = false; + roles.push_back(ActiveTurnRole); + } + if (roles.empty()) + continue; + emit dataChanged(index(*rowPosition), index(*rowPosition), roles); + incrementProperty("modelDataChangeCount"); + } } - if (destination < 0) { - if (sequence.size() == 0) - destination = 0; - else - continue; + + bool ConversationItemModel::isPresented(const VisibleCardData& card) const noexcept { + const auto* message = card.kind == CardKind::AgentMessage ? std::get_if(&card.payload) : nullptr; + return card.kind == CardKind::Reasoning ? visibility_.showReasoning + : !message || !message->questionRequest.is_null() || message->phase == "final_answer" || + message->phase == "partial_answer" || visibility_.showCodexUpdates; } - if (source >= 0 && !removeVirtual(source)) - return reject("invalid-destination"); - if (destination < 0 || destination > sequence.size() || - sequence.locateStable(key) || sequence.locateTarget(card.target)) - return reject("invalid-current-placement"); - - VirtualRow replacement{card.key, - card.kind, - card.target, - key, - change.placement.sectionKey, - change.placement.turnRoot, - change.placement.nested}; - const std::optional previousRow = sequence.at(destination - 1); - const std::optional nextRow = sequence.at(destination); - const VirtualSection &owner = section(replacement.sectionKey); - const bool previousInSection = - previousRow && previousRow->sectionKey == replacement.sectionKey; - const bool nextInSection = - nextRow && nextRow->sectionKey == replacement.sectionKey; - const bool exactTail = - source < 0 && !change.nextCardKey && destination == sequence.size(); - const bool valid = - validSectionPlacement(replacement.turnRoot, replacement.nested, - owner.count, owner.hasRoot, previousInSection, - nextInSection); - if (!valid) - return std::nullopt; - if (current && current->turnRoot && source != destination) - return std::nullopt; - insertVirtual(destination, std::move(replacement)); - StructuralDeltaPlan::Operation operation; - operation.kind = StructuralDeltaPlan::Operation::Kind::Place; - operation.deltaIndex = index; - operation.source = source; - operation.destination = destination; - operation.tailAppend = exactTail; - operation.oldStableKey = current ? current->stableKey : std::string{}; - operation.stableKey = key; - operation.oldSection = current ? current->sectionKey : std::string{}; - operation.section = change.placement.sectionKey; - result.operations.push_back(std::move(operation)); - settled[index] = true; - } - - for (std::size_t index = 0; index < rows.size(); ++index) { - if (!settled[index]) { - return reject("unsettled"); + void ConversationItemModel::rebuildIndexes() { + stableRows_.clear(); + targetRows_.clear(); + sectionRows_.clear(); + stableRows_.reserve(nodeCount(rows_)); + targetRows_.reserve(nodeCount(rows_)); + std::vector pending; + RowNode* current = rows_.get(); + while (current || !pending.empty()) { + while (current) { + pending.push_back(current); + current = current->left.get(); + } + current = pending.back(); + pending.pop_back(); + stableRows_.emplace(current->value.stableKey, current); + if (current->value.card.target) + targetRows_.emplace(current->value.card.target.get(), current); + addSectionIdentity(current); + current = current->right.get(); + } + incrementProperty("modelIndexRebuildCount"); } - } - - for (const StructuralDeltaPlan::Operation &operation : result.operations) { - if (operation.kind == StructuralDeltaPlan::Operation::Kind::Remove) - continue; - const ConversationRowChange &change = rows[operation.deltaIndex]; - const std::optional position = - sequence.locateStable(stableKey(change.placement.card.key)); - if (!position) - return reject("missing-after-plan"); - if ((!change.previousCardKey && *position != 0) || - (!change.nextCardKey && *position != sequence.size() - 1)) - return reject("edge-mismatch"); - const auto adjacent = [&](const std::optional &neighbor, - int offset) { - if (!neighbor) - return true; - const std::string neighborKey = stableKey(*neighbor); - const std::optional neighborPosition = - sequence.locateStable(neighborKey); - return neighborPosition && - *neighborPosition + offset == *position; - }; - if (!adjacent(change.previousCardKey, 1) || - !adjacent(change.nextCardKey, -1)) { - return reject("adjacency-mismatch"); + + std::unique_ptr + ConversationItemModel::buildRows(std::vector& rows, std::size_t first, std::size_t last, std::uint64_t depth) { + if (first >= last) + return {}; + const std::size_t middle = first + (last - first) / 2; + auto node = std::make_unique(std::move(rows[middle]), std::numeric_limits::max() - depth); + node->left = buildRows(rows, first, middle, depth + 1); + node->right = buildRows(rows, middle + 1, last, depth + 1); + updateNode(node.get()); + node->parent = nullptr; + return node; } - } - - return result; -} - -std::optional -ConversationItemModel::applyStructuralDelta( - std::vector &rows, - std::span removals) { - std::optional plan = planStructuralDelta(rows, removals); - if (!plan) - return std::nullopt; - commitStructuralDelta(*plan, rows, removals); - return plan; -} - -void ConversationItemModel::commitStructuralDelta( - StructuralDeltaPlan &plan, std::vector &rows, - std::span removals) { - struct SectionChange { - SectionStructure before; - std::vector changedKeys; - }; - std::unordered_map changedSections; - const auto touch = [this, &changedSections](const std::string §ion, - const std::string &key) { - if (section.empty()) - return; - auto [found, inserted] = changedSections.try_emplace(section); - if (inserted) - found->second.before = sectionStructure(section); - if (!key.empty() && std::ranges::find(found->second.changedKeys, key) == - found->second.changedKeys.end()) - found->second.changedKeys.push_back(key); - }; - - for (StructuralDeltaPlan::Operation &operation : plan.operations) { - if (operation.kind == StructuralDeltaPlan::Operation::Kind::ReplaceRoot) { - const QModelIndex sourceIndex = - indexForTarget(removals[operation.removalIndex]); - Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); - const Row *current = row(sourceIndex.row()); - Q_ASSERT(current && current->turnRoot && - current->sectionKey == operation.oldSection); - touch(operation.oldSection, operation.oldStableKey); - touch(operation.section, operation.stableKey); - - Row replacement = - rowFromPlacement(std::move(rows[operation.deltaIndex].placement)); - const bool finalFirstInTurn = current->firstInTurn; - replacement.lastInTurn = current->lastInTurn; - const bool finalActive = replacement.activeTurn; - replacement.turnRoot = false; - replacement.nested = true; - replacement.firstInTurn = false; - replacement.activeTurn = false; - - const int insertedRow = sourceIndex.row() + 1; - beginInsertRows({}, insertedRow, insertedRow); - insertRow(static_cast(insertedRow), std::move(replacement)); - endInsertRows(); - incrementProperty("modelInsertCount"); - incrementProperty("modelExactInsertCount"); - - beginRemoveRows({}, sourceIndex.row(), sourceIndex.row()); - (void)takeRow(static_cast(sourceIndex.row())); - RowNode *promoted = nodeAt(static_cast(sourceIndex.row())); - Q_ASSERT(promoted && promoted->value.stableKey == operation.stableKey); - removeSectionIdentity(promoted); - promoted->value.turnRoot = true; - promoted->value.nested = false; - promoted->value.firstInTurn = finalFirstInTurn; - promoted->value.activeTurn = finalActive; - addSectionIdentity(promoted); - endRemoveRows(); - incrementProperty("modelRemoveCount"); - incrementProperty("modelExactRemoveCount"); - emit dataChanged( - index(sourceIndex.row()), index(sourceIndex.row()), - {TurnRootRole, NestedCardRole, FirstInTurnRole, ActiveTurnRole}); - incrementProperty("modelDataChangeCount"); - continue; + + ConversationItemModel::RowNode* ConversationItemModel::nodeAt(std::size_t row) const noexcept { + RowNode* current = rows_.get(); + while (current) { + const std::size_t leftCount = nodeCount(current->left); + if (row < leftCount) { + current = current->left.get(); + continue; + } + if (row == leftCount) + return current; + row -= leftCount + 1; + current = current->right.get(); + } + return nullptr; } - if (operation.kind == StructuralDeltaPlan::Operation::Kind::Remove) { - const QModelIndex sourceIndex = - indexForTarget(removals[operation.removalIndex]); - Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); - touch(operation.oldSection, operation.oldStableKey); - beginRemoveRows({}, sourceIndex.row(), sourceIndex.row()); - (void)takeRow(static_cast(sourceIndex.row())); - endRemoveRows(); - incrementProperty("modelRemoveCount"); - incrementProperty("modelExactRemoveCount"); - continue; + std::optional ConversationItemModel::rowOf(const RowNode* node) const noexcept { + if (!node) + return std::nullopt; + std::size_t result = nodeCount(node->left); + while (node->parent) { + if (node == node->parent->right.get()) + result += nodeCount(node->parent->left) + 1; + node = node->parent; + } + if (node != rows_.get() || result > static_cast(std::numeric_limits::max())) + return std::nullopt; + return static_cast(result); } - Row replacement = - rowFromPlacement(std::move(rows[operation.deltaIndex].placement)); - if (operation.source < 0) { - touch(operation.section, operation.stableKey); - const Row *previous = row(operation.destination - 1); - const Row *next = row(operation.destination); - replacement.firstInTurn = - !previous || previous->sectionKey != replacement.sectionKey; - replacement.lastInTurn = - !next || next->sectionKey != replacement.sectionKey; - beginInsertRows({}, operation.destination, operation.destination); - insertRow(static_cast(operation.destination), - std::move(replacement)); - endInsertRows(); - incrementProperty("modelInsertCount"); - incrementProperty(operation.tailAppend ? "modelTailAppendCount" - : "modelExactInsertCount"); - continue; + ConversationItemModel::RowNode* ConversationItemModel::insertRow(std::size_t row, Row value) { + auto inserted = std::make_unique(std::move(value), nextPriority()); + RowNode* result = inserted.get(); + auto [left, right] = splitRows(std::move(rows_), row); + rows_ = mergeRows(mergeRows(std::move(left), std::move(inserted)), std::move(right)); + stableRows_.insert_or_assign(result->value.stableKey, result); + if (result->value.card.target) + targetRows_.insert_or_assign(result->value.card.target.get(), result); + addSectionIdentity(result); + return result; } - const QModelIndex sourceIndex = indexForStableKey(operation.oldStableKey); - Q_ASSERT(sourceIndex.isValid() && sourceIndex.row() == operation.source); - const Row *current = row(sourceIndex.row()); - Q_ASSERT(current); - replacement.firstInTurn = current->firstInTurn; - replacement.lastInTurn = current->lastInTurn; - const bool movedRows = operation.source != operation.destination; - const bool presentationChanged = *current != replacement; - operation.changed = movedRows || presentationChanged; - if (!operation.changed) - continue; - touch(operation.oldSection, operation.oldStableKey); - touch(operation.section, operation.stableKey); - if (movedRows) { - const int destinationChild = operation.destination > operation.source - ? operation.destination + 1 - : operation.destination; - beginMoveRows({}, operation.source, operation.source, {}, - destinationChild); - std::unique_ptr moved = - takeRow(static_cast(operation.source)); - insertRow(static_cast(operation.destination), - std::move(moved->value)); - endMoveRows(); - incrementProperty("modelMoveCount"); + std::unique_ptr ConversationItemModel::takeRow(std::size_t row) { + RowNode* candidate = nodeAt(row); + if (!candidate) + return {}; + removeSectionIdentity(candidate); + auto [left, suffix] = splitRows(std::move(rows_), row); + auto [removed, right] = splitRows(std::move(suffix), 1); + rows_ = mergeRows(std::move(left), std::move(right)); + if (!removed) + return {}; + eraseRowIdentity(removed->value); + removed->parent = nullptr; + return std::move(removed); } - Row &moved = nodeAt(static_cast(operation.destination))->value; - replacement.firstInTurn = moved.firstInTurn; - replacement.lastInTurn = moved.lastInTurn; - if (presentationChanged || movedRows) - updateRow(operation.destination, std::move(replacement)); - incrementProperty(movedRows ? "modelExactMoveCount" - : "modelExactPlacementUpdateCount"); - } - - for (auto &[section, change] : changedSections) - refreshSectionStructure(section, change.before, change.changedKeys); -} - -bool ConversationItemModel::setProviderHasMore(bool providerHasMore) noexcept { - if (hasMore_ == providerHasMore) - return false; - hasMore_ = providerHasMore; - return true; -} - -bool ConversationItemModel::setVisibility(Visibility visibility) { - if (visibility_ == visibility) - return false; - visibility_ = visibility; - int first = -1; - bool changed = false; - for (int position = 0; position < rowCount(); ++position) { - Row ¤t = nodeAt(static_cast(position))->value; - const bool presented = isPresented(current.card); - if (presented == current.presented) { - if (first >= 0) { - emit dataChanged(index(first), index(position - 1), {PresentedRole}); - incrementProperty("modelDataChangeCount"); - first = -1; - } - continue; + void ConversationItemModel::clearRows() noexcept { + stableRows_.clear(); + targetRows_.clear(); + sectionRows_.clear(); + rows_.reset(); } - current.presented = presented; - changed = true; - if (first < 0) - first = position; - } - if (first < 0) - return changed; - emit dataChanged(index(first), index(rowCount() - 1), {PresentedRole}); - incrementProperty("modelDataChangeCount"); - return true; -} - -const ConversationItemModel::Row * -ConversationItemModel::row(int rowIndex) const noexcept { - const RowNode *node = - rowIndex >= 0 ? nodeAt(static_cast(rowIndex)) : nullptr; - return node ? &node->value : nullptr; -} - -const VisibleCardData * -ConversationItemModel::card(int rowIndex) const noexcept { - const Row *value = row(rowIndex); - return value ? &value->card : nullptr; -} - -QModelIndex -ConversationItemModel::indexForStableKey(const std::string &key) const { - const auto found = stableRows_.find(key); - if (found == stableRows_.end()) - return {}; - const std::optional row = rowOf(found->second); - return row ? index(*row) : QModelIndex{}; -} - -QModelIndex -ConversationItemModel::indexForTarget(const nodegraph::NodeRef &target) const { - if (!target) - return {}; - const auto found = targetRows_.find(target.get()); - if (found == targetRows_.end()) - return {}; - const std::optional modelRow = rowOf(found->second); - const Row *candidate = modelRow ? row(*modelRow) : nullptr; - return candidate && candidate->card.target == target ? index(*modelRow) - : QModelIndex{}; -} - -std::vector -ConversationItemModel::flatten(ConversationSnapshot &&snapshot) const { - std::size_t count = 0; - for (const TurnSection §ion : snapshot.sections) - count += section.cards.size(); - std::vector result; - result.reserve(count); - for (TurnSection §ion : snapshot.sections) { - std::optional root; - if (section.rootCardKey) - root = stableKey(*section.rootCardKey); - const auto representedRoot = - root ? std::ranges::find_if(section.cards, [&](const auto &card) { - return stableKey(card.key) == *root; - }) : section.cards.end(); - const std::optional rootPosition = - representedRoot == section.cards.end() - ? std::nullopt - : std::optional{static_cast( - std::distance(section.cards.begin(), representedRoot))}; - for (std::size_t position = 0; position < section.cards.size(); - ++position) { - VisibleCardData card = std::move(section.cards[position]); - const std::string key = stableKey(card.key); - const bool turnRoot = rootPosition && position == *rootPosition; - result.push_back(Row{std::move(card), key, section.key, turnRoot, - isNestedTurnCard(rootPosition, position), - position == 0, - position + 1 == section.cards.size(), false, false}); - Row &row = result.back(); - row.presented = isPresented(row.card); - row.activeTurn = turnRoot && snapshot.activeTurnId && - row.card.turnId == *snapshot.activeTurnId; + + std::uint64_t ConversationItemModel::nextPriority() noexcept { + priorityState_ ^= priorityState_ >> 12; + priorityState_ ^= priorityState_ << 25; + priorityState_ ^= priorityState_ >> 27; + return priorityState_ * 0x2545f4914f6cdd1dULL; } - } - return result; -} - -bool ConversationItemModel::rowsAreUnique(const std::vector &rows) const { - std::unordered_set stableKeys; - std::unordered_set targets; - stableKeys.reserve(rows.size()); - targets.reserve(rows.size()); - for (const Row &row : rows) { - if (row.stableKey.empty() || !stableKeys.insert(row.stableKey).second) - return false; - if (row.card.target && !targets.insert(row.card.target.get()).second) - return false; - } - return true; -} - -ConversationItemModel::Row ConversationItemModel::rowFromPlacement( - ConversationRowPlacement placement) const { - Row result; - result.card = std::move(placement.card); - result.stableKey = stableKey(result.card.key); - result.sectionKey = std::move(placement.sectionKey); - result.turnRoot = placement.turnRoot; - result.nested = placement.nested; - result.presented = isPresented(result.card); - result.activeTurn = placement.turnRoot && placement.activeTurn; - return result; -} - -ConversationItemModel::SectionStructure -ConversationItemModel::sectionStructure(const std::string §ionKey) const { - SectionStructure result; - const auto found = sectionRows_.find(sectionKey); - if (found == sectionRows_.end()) - return result; - if (found->second.first) - result.first = found->second.first->value.stableKey; - if (found->second.last) - result.last = found->second.last->value.stableKey; - if (found->second.root) - result.root = found->second.root->value.stableKey; - return result; -} - -void ConversationItemModel::refreshSectionStructure( - const std::string §ionKey, const SectionStructure &before, - std::span changedKeys) { - if (sectionKey.empty()) - return; - const auto found = sectionRows_.find(sectionKey); - if (found == sectionRows_.end()) - return; - - const SectionStructure after = sectionStructure(sectionKey); - const std::optional rootPosition = - found->second.root ? rowOf(found->second.root) : std::nullopt; - std::vector affected; - affected.reserve(7); - const auto retain = [this, &affected](const std::string &key) { - if (key.empty()) - return; - const auto found = stableRows_.find(key); - if (found != stableRows_.end() && - std::ranges::find(affected, found->second) == affected.end()) - affected.push_back(found->second); - }; - retain(before.first); - retain(before.last); - retain(before.root); - retain(after.first); - retain(after.last); - retain(after.root); - for (const std::string &key : changedKeys) - retain(key); - - if (before.root.empty() != after.root.empty()) { - affected.clear(); - RowNode *node = found->second.first; - while (node && node->value.sectionKey == sectionKey) { - affected.push_back(node); - node = nextNode(node); + + std::size_t ConversationItemModel::nodeCount(const std::unique_ptr& node) noexcept { + return node ? node->count : 0; } - } - - for (RowNode *node : affected) { - incrementProperty("modelSectionStructureRowsTouched"); - const std::optional rowPosition = rowOf(node); - if (!rowPosition || node->value.sectionKey != sectionKey) - continue; - Row ¤t = node->value; - QList roles; - const bool firstInTurn = node == found->second.first; - const bool lastInTurn = node == found->second.last; - const bool nested = - rootPosition && isNestedTurnCard( - static_cast(*rootPosition), - static_cast(*rowPosition)); - if (current.firstInTurn != firstInTurn) { - current.firstInTurn = firstInTurn; - roles.push_back(FirstInTurnRole); + + void ConversationItemModel::updateNode(RowNode* node) noexcept { + if (!node) + return; + node->count = nodeCount(node->left) + 1 + nodeCount(node->right); + if (node->left) + node->left->parent = node; + if (node->right) + node->right->parent = node; } - if (current.lastInTurn != lastInTurn) { - current.lastInTurn = lastInTurn; - roles.push_back(LastInTurnRole); + + std::pair, std::unique_ptr> + ConversationItemModel::splitRows(std::unique_ptr root, std::size_t leftCount) { + if (!root) + return {}; + if (nodeCount(root->left) >= leftCount) { + auto [left, middle] = splitRows(std::move(root->left), leftCount); + root->left = std::move(middle); + updateNode(root.get()); + root->parent = nullptr; + if (left) + left->parent = nullptr; + return {std::move(left), std::move(root)}; + } + const std::size_t remaining = leftCount - nodeCount(root->left) - 1; + auto [middle, right] = splitRows(std::move(root->right), remaining); + root->right = std::move(middle); + updateNode(root.get()); + root->parent = nullptr; + if (right) + right->parent = nullptr; + return {std::move(root), std::move(right)}; } - if (current.nested != nested) { - current.nested = nested; - roles.push_back(NestedCardRole); + + std::unique_ptr ConversationItemModel::mergeRows(std::unique_ptr left, + std::unique_ptr right) { + if (!left) { + if (right) + right->parent = nullptr; + return right; + } + if (!right) { + left->parent = nullptr; + return left; + } + if (left->priority >= right->priority) { + left->right = mergeRows(std::move(left->right), std::move(right)); + updateNode(left.get()); + left->parent = nullptr; + return left; + } + right->left = mergeRows(std::move(left), std::move(right->left)); + updateNode(right.get()); + right->parent = nullptr; + return right; } - if (current.activeTurn && !current.turnRoot) { - current.activeTurn = false; - roles.push_back(ActiveTurnRole); + + ConversationItemModel::RowNode* ConversationItemModel::previousNode(RowNode* node) noexcept { + if (!node) + return nullptr; + if (node->left) { + node = node->left.get(); + while (node->right) + node = node->right.get(); + return node; + } + while (node->parent && node == node->parent->left.get()) + node = node->parent; + return node->parent; } - if (roles.empty()) - continue; - emit dataChanged(index(*rowPosition), index(*rowPosition), roles); - incrementProperty("modelDataChangeCount"); - } -} - -bool ConversationItemModel::isPresented( - const VisibleCardData &card) const noexcept { - const auto* message = card.kind == CardKind::AgentMessage ? std::get_if(&card.payload) : nullptr; - return card.kind == CardKind::Reasoning ? visibility_.showReasoning - : !message || !message->questionRequest.is_null() || message->phase == "final_answer" || - message->phase == "partial_answer" || visibility_.showCodexUpdates; -} - -void ConversationItemModel::rebuildIndexes() { - stableRows_.clear(); - targetRows_.clear(); - sectionRows_.clear(); - stableRows_.reserve(nodeCount(rows_)); - targetRows_.reserve(nodeCount(rows_)); - std::vector pending; - RowNode *current = rows_.get(); - while (current || !pending.empty()) { - while (current) { - pending.push_back(current); - current = current->left.get(); + + ConversationItemModel::RowNode* ConversationItemModel::nextNode(RowNode* node) noexcept { + if (!node) + return nullptr; + if (node->right) { + node = node->right.get(); + while (node->left) + node = node->left.get(); + return node; + } + while (node->parent && node == node->parent->right.get()) + node = node->parent; + return node->parent; } - current = pending.back(); - pending.pop_back(); - stableRows_.emplace(current->value.stableKey, current); - if (current->value.card.target) - targetRows_.emplace(current->value.card.target.get(), current); - addSectionIdentity(current); - current = current->right.get(); - } - incrementProperty("modelIndexRebuildCount"); -} - -std::unique_ptr -ConversationItemModel::buildRows(std::vector &rows, std::size_t first, - std::size_t last, std::uint64_t depth) { - if (first >= last) - return {}; - const std::size_t middle = first + (last - first) / 2; - auto node = std::make_unique( - std::move(rows[middle]), - std::numeric_limits::max() - depth); - node->left = buildRows(rows, first, middle, depth + 1); - node->right = buildRows(rows, middle + 1, last, depth + 1); - updateNode(node.get()); - node->parent = nullptr; - return node; -} - -ConversationItemModel::RowNode * -ConversationItemModel::nodeAt(std::size_t row) const noexcept { - RowNode *current = rows_.get(); - while (current) { - const std::size_t leftCount = nodeCount(current->left); - if (row < leftCount) { - current = current->left.get(); - continue; + + void ConversationItemModel::addSectionIdentity(RowNode* node) { + if (!node || node->value.sectionKey.empty()) + return; + SectionIndex& section = sectionRows_[node->value.sectionKey]; + const std::optional position = rowOf(node); + if (!section.member) { + section.member = node; + section.first = node; + section.last = node; + } else if (position) { + const std::optional first = rowOf(section.first); + const std::optional last = rowOf(section.last); + if (!first || *position < *first) + section.first = node; + if (!last || *position > *last) + section.last = node; + } + if (node->value.turnRoot) + section.root = node; + ++section.count; } - if (row == leftCount) - return current; - row -= leftCount + 1; - current = current->right.get(); - } - return nullptr; -} - -std::optional -ConversationItemModel::rowOf(const RowNode *node) const noexcept { - if (!node) - return std::nullopt; - std::size_t result = nodeCount(node->left); - while (node->parent) { - if (node == node->parent->right.get()) - result += nodeCount(node->parent->left) + 1; - node = node->parent; - } - if (node != rows_.get() || - result > static_cast(std::numeric_limits::max())) - return std::nullopt; - return static_cast(result); -} - -ConversationItemModel::RowNode * -ConversationItemModel::insertRow(std::size_t row, Row value) { - auto inserted = std::make_unique(std::move(value), nextPriority()); - RowNode *result = inserted.get(); - auto [left, right] = splitRows(std::move(rows_), row); - rows_ = mergeRows(mergeRows(std::move(left), std::move(inserted)), - std::move(right)); - stableRows_.insert_or_assign(result->value.stableKey, result); - if (result->value.card.target) - targetRows_.insert_or_assign(result->value.card.target.get(), result); - addSectionIdentity(result); - return result; -} - -std::unique_ptr -ConversationItemModel::takeRow(std::size_t row) { - RowNode *candidate = nodeAt(row); - if (!candidate) - return {}; - removeSectionIdentity(candidate); - auto [left, suffix] = splitRows(std::move(rows_), row); - auto [removed, right] = splitRows(std::move(suffix), 1); - rows_ = mergeRows(std::move(left), std::move(right)); - if (!removed) - return {}; - eraseRowIdentity(removed->value); - removed->parent = nullptr; - return std::move(removed); -} - -void ConversationItemModel::clearRows() noexcept { - stableRows_.clear(); - targetRows_.clear(); - sectionRows_.clear(); - rows_.reset(); -} - -std::uint64_t ConversationItemModel::nextPriority() noexcept { - priorityState_ ^= priorityState_ >> 12; - priorityState_ ^= priorityState_ << 25; - priorityState_ ^= priorityState_ >> 27; - return priorityState_ * 0x2545f4914f6cdd1dULL; -} - -std::size_t ConversationItemModel::nodeCount( - const std::unique_ptr &node) noexcept { - return node ? node->count : 0; -} - -void ConversationItemModel::updateNode(RowNode *node) noexcept { - if (!node) - return; - node->count = nodeCount(node->left) + 1 + nodeCount(node->right); - if (node->left) - node->left->parent = node; - if (node->right) - node->right->parent = node; -} - -std::pair, - std::unique_ptr> -ConversationItemModel::splitRows(std::unique_ptr root, - std::size_t leftCount) { - if (!root) - return {}; - if (nodeCount(root->left) >= leftCount) { - auto [left, middle] = splitRows(std::move(root->left), leftCount); - root->left = std::move(middle); - updateNode(root.get()); - root->parent = nullptr; - if (left) - left->parent = nullptr; - return {std::move(left), std::move(root)}; - } - const std::size_t remaining = leftCount - nodeCount(root->left) - 1; - auto [middle, right] = splitRows(std::move(root->right), remaining); - root->right = std::move(middle); - updateNode(root.get()); - root->parent = nullptr; - if (right) - right->parent = nullptr; - return {std::move(root), std::move(right)}; -} - -std::unique_ptr -ConversationItemModel::mergeRows(std::unique_ptr left, - std::unique_ptr right) { - if (!left) { - if (right) - right->parent = nullptr; - return right; - } - if (!right) { - left->parent = nullptr; - return left; - } - if (left->priority >= right->priority) { - left->right = mergeRows(std::move(left->right), std::move(right)); - updateNode(left.get()); - left->parent = nullptr; - return left; - } - right->left = mergeRows(std::move(left), std::move(right->left)); - updateNode(right.get()); - right->parent = nullptr; - return right; -} - -ConversationItemModel::RowNode * -ConversationItemModel::previousNode(RowNode *node) noexcept { - if (!node) - return nullptr; - if (node->left) { - node = node->left.get(); - while (node->right) - node = node->right.get(); - return node; - } - while (node->parent && node == node->parent->left.get()) - node = node->parent; - return node->parent; -} - -ConversationItemModel::RowNode * -ConversationItemModel::nextNode(RowNode *node) noexcept { - if (!node) - return nullptr; - if (node->right) { - node = node->right.get(); - while (node->left) - node = node->left.get(); - return node; - } - while (node->parent && node == node->parent->right.get()) - node = node->parent; - return node->parent; -} - -void ConversationItemModel::addSectionIdentity(RowNode *node) { - if (!node || node->value.sectionKey.empty()) - return; - SectionIndex §ion = sectionRows_[node->value.sectionKey]; - const std::optional position = rowOf(node); - if (!section.member) { - section.member = node; - section.first = node; - section.last = node; - } else if (position) { - const std::optional first = rowOf(section.first); - const std::optional last = rowOf(section.last); - if (!first || *position < *first) - section.first = node; - if (!last || *position > *last) - section.last = node; - } - if (node->value.turnRoot) - section.root = node; - ++section.count; -} - -void ConversationItemModel::removeSectionIdentity(RowNode *node) { - if (!node || node->value.sectionKey.empty()) - return; - const auto found = sectionRows_.find(node->value.sectionKey); - if (found == sectionRows_.end()) - return; - SectionIndex §ion = found->second; - RowNode *previous = previousNode(node); - RowNode *next = nextNode(node); - if (section.root == node) - section.root = nullptr; - if (section.first == node) - section.first = next && next->value.sectionKey == node->value.sectionKey - ? next - : nullptr; - if (section.last == node) - section.last = - previous && previous->value.sectionKey == node->value.sectionKey - ? previous - : nullptr; - if (section.count > 0) - --section.count; - if (section.count == 0) { - sectionRows_.erase(found); - return; - } - if (section.member == node) { - RowNode *replacement = previous; - if (!replacement || replacement->value.sectionKey != node->value.sectionKey) - replacement = next; - section.member = replacement; - } - if (!section.first && section.member) { - section.first = section.member; - while (RowNode *candidate = previousNode(section.first)) { - if (candidate->value.sectionKey != node->value.sectionKey) - break; - section.first = candidate; + + void ConversationItemModel::removeSectionIdentity(RowNode* node) { + if (!node || node->value.sectionKey.empty()) + return; + const auto found = sectionRows_.find(node->value.sectionKey); + if (found == sectionRows_.end()) + return; + SectionIndex& section = found->second; + RowNode* previous = previousNode(node); + RowNode* next = nextNode(node); + if (section.root == node) + section.root = nullptr; + if (section.first == node) + section.first = next && next->value.sectionKey == node->value.sectionKey ? next : nullptr; + if (section.last == node) + section.last = previous && previous->value.sectionKey == node->value.sectionKey ? previous : nullptr; + if (section.count > 0) + --section.count; + if (section.count == 0) { + sectionRows_.erase(found); + return; + } + if (section.member == node) { + RowNode* replacement = previous; + if (!replacement || replacement->value.sectionKey != node->value.sectionKey) + replacement = next; + section.member = replacement; + } + if (!section.first && section.member) { + section.first = section.member; + while (RowNode* candidate = previousNode(section.first)) { + if (candidate->value.sectionKey != node->value.sectionKey) + break; + section.first = candidate; + } + } + if (!section.last && section.member) { + section.last = section.member; + while (RowNode* candidate = nextNode(section.last)) { + if (candidate->value.sectionKey != node->value.sectionKey) + break; + section.last = candidate; + } + } } - } - if (!section.last && section.member) { - section.last = section.member; - while (RowNode *candidate = nextNode(section.last)) { - if (candidate->value.sectionKey != node->value.sectionKey) - break; - section.last = candidate; + + void ConversationItemModel::eraseRowIdentity(const Row& row) { + stableRows_.erase(row.stableKey); + if (row.card.target) + targetRows_.erase(row.card.target.get()); + } + + void ConversationItemModel::incrementProperty(const char* name) { + setProperty(name, property(name).toULongLong() + 1); + } + + void ConversationItemModel::updateRow(int rowIndex, Row replacement) { + RowNode* node = nodeAt(static_cast(rowIndex)); + if (!node) + return; + updateRow(node, rowIndex, std::move(replacement)); + } + + void ConversationItemModel::updateRow(RowNode* node, int rowIndex, Row replacement) { + Row& before = node->value; + QList roles; + if (before.card.threadId != replacement.card.threadId) + roles.push_back(ThreadIdRole); + if (before.card.turnId != replacement.card.turnId) + roles.push_back(TurnIdRole); + if (before.card.itemId != replacement.card.itemId) + roles.push_back(ItemIdRole); + if (before.card.kind != replacement.card.kind) { + roles.push_back(CardKindRole); + roles.push_back(Qt::DisplayRole); + roles.push_back(Qt::AccessibleTextRole); + } + if (before.card.target != replacement.card.target) + roles.push_back(TargetIdentityRole); + if (before.sectionKey != replacement.sectionKey) + roles.push_back(TurnSectionRole); + if (before.turnRoot != replacement.turnRoot) + roles.push_back(TurnRootRole); + if (before.nested != replacement.nested) + roles.push_back(NestedCardRole); + if (before.firstInTurn != replacement.firstInTurn) + roles.push_back(FirstInTurnRole); + if (before.lastInTurn != replacement.lastInTurn) + roles.push_back(LastInTurnRole); + if (before.presented != replacement.presented) + roles.push_back(PresentedRole); + if (before.activeTurn != replacement.activeTurn) + roles.push_back(ActiveTurnRole); + if (before.card.payload != replacement.card.payload || before.card.status != replacement.card.status || + before.card.timing != replacement.card.timing) { + roles.push_back(PresentationRole); + roles.push_back(Qt::AccessibleTextRole); + } + const std::string oldStableKey = before.stableKey; + const std::string oldSectionKey = before.sectionKey; + const bool oldTurnRoot = before.turnRoot; + const nodegraph::Node* oldTarget = before.card.target ? before.card.target.get() : nullptr; + if (oldSectionKey != replacement.sectionKey || oldTurnRoot != replacement.turnRoot) + removeSectionIdentity(node); + before = std::move(replacement); + if (oldSectionKey != before.sectionKey || oldTurnRoot != before.turnRoot) + addSectionIdentity(node); + if (oldStableKey != before.stableKey) { + stableRows_.erase(oldStableKey); + stableRows_.insert_or_assign(before.stableKey, node); + } + const nodegraph::Node* newTarget = before.card.target ? before.card.target.get() : nullptr; + if (oldTarget != newTarget) { + const auto old = targetRows_.find(oldTarget); + if (old != targetRows_.end() && old->second == node) + targetRows_.erase(old); + if (newTarget) + targetRows_.insert_or_assign(newTarget, node); + } + if (roles.empty()) + return; + emit dataChanged(index(rowIndex), index(rowIndex), roles); + incrementProperty("modelDataChangeCount"); } - } -} - -void ConversationItemModel::eraseRowIdentity(const Row &row) { - stableRows_.erase(row.stableKey); - if (row.card.target) - targetRows_.erase(row.card.target.get()); -} - -void ConversationItemModel::incrementProperty(const char *name) { - setProperty(name, property(name).toULongLong() + 1); -} - -void ConversationItemModel::updateRow(int rowIndex, Row replacement) { - RowNode *node = nodeAt(static_cast(rowIndex)); - if (!node) - return; - updateRow(node, rowIndex, std::move(replacement)); -} - -void ConversationItemModel::updateRow(RowNode *node, int rowIndex, - Row replacement) { - Row &before = node->value; - QList roles; - if (before.card.threadId != replacement.card.threadId) - roles.push_back(ThreadIdRole); - if (before.card.turnId != replacement.card.turnId) - roles.push_back(TurnIdRole); - if (before.card.itemId != replacement.card.itemId) - roles.push_back(ItemIdRole); - if (before.card.kind != replacement.card.kind) { - roles.push_back(CardKindRole); - roles.push_back(Qt::DisplayRole); - roles.push_back(Qt::AccessibleTextRole); - } - if (before.card.target != replacement.card.target) - roles.push_back(TargetIdentityRole); - if (before.sectionKey != replacement.sectionKey) - roles.push_back(TurnSectionRole); - if (before.turnRoot != replacement.turnRoot) - roles.push_back(TurnRootRole); - if (before.nested != replacement.nested) - roles.push_back(NestedCardRole); - if (before.firstInTurn != replacement.firstInTurn) - roles.push_back(FirstInTurnRole); - if (before.lastInTurn != replacement.lastInTurn) - roles.push_back(LastInTurnRole); - if (before.presented != replacement.presented) - roles.push_back(PresentedRole); - if (before.activeTurn != replacement.activeTurn) - roles.push_back(ActiveTurnRole); - if (before.card.payload != replacement.card.payload || - before.card.status != replacement.card.status || - before.card.timing != replacement.card.timing) { - roles.push_back(PresentationRole); - roles.push_back(Qt::AccessibleTextRole); - } - const std::string oldStableKey = before.stableKey; - const std::string oldSectionKey = before.sectionKey; - const bool oldTurnRoot = before.turnRoot; - const nodegraph::Node *oldTarget = - before.card.target ? before.card.target.get() : nullptr; - if (oldSectionKey != replacement.sectionKey || - oldTurnRoot != replacement.turnRoot) - removeSectionIdentity(node); - before = std::move(replacement); - if (oldSectionKey != before.sectionKey || oldTurnRoot != before.turnRoot) - addSectionIdentity(node); - if (oldStableKey != before.stableKey) { - stableRows_.erase(oldStableKey); - stableRows_.insert_or_assign(before.stableKey, node); - } - const nodegraph::Node *newTarget = - before.card.target ? before.card.target.get() : nullptr; - if (oldTarget != newTarget) { - const auto old = targetRows_.find(oldTarget); - if (old != targetRows_.end() && old->second == node) - targetRows_.erase(old); - if (newTarget) - targetRows_.insert_or_assign(newTarget, node); - } - if (roles.empty()) - return; - emit dataChanged(index(rowIndex), index(rowIndex), roles); - incrementProperty("modelDataChangeCount"); -} } // namespace codexui::codex::middle diff --git a/src/codex/ui/NodeGraphUiAdapter.cpp b/src/codex/ui/NodeGraphUiAdapter.cpp index 0285539..5cdf98b 100644 --- a/src/codex/ui/NodeGraphUiAdapter.cpp +++ b/src/codex/ui/NodeGraphUiAdapter.cpp @@ -28,3326 +28,2922 @@ #include namespace codexui::codex::ui { -namespace { -using namespace middle; -using nodegraph::boolFromValue; -using nodegraph::exactStringFromValue; -using nodegraph::scalarTextFromValue; -using nodegraph::signedIntegerFromValue; -using nodegraph::valueMember; - -// Labels are a projection of the complete loaded catalog, never stored names. -// Compare paths only within colliding names, not across every project pair. -void labelThreadGroups(std::vector &groups) { - std::map> names; - for (auto &group : groups) - names[group.label].push_back(&group); - for (auto &[name, matches] : names) { - if (matches.size() < 2) - continue; - std::vector> paths(matches.size()); - qsizetype maxDepth = 1; - for (std::size_t i = 0; i < matches.size(); ++i) { - const auto roots = matches[i]->fields.find("roots"); - if (roots == matches[i]->fields.end() || !roots->is_array()) - continue; - for (const auto &root : *roots) { - const auto path = root.find("path"); - if (path == root.end() || !path->is_string()) - continue; - auto parts = QString::fromStdString(path->get()) - .replace('\\', '/') - .split('/', Qt::SkipEmptyParts); - if (parts.isEmpty()) - parts.push_back(QStringLiteral("/")); - maxDepth = std::max(maxDepth, parts.size()); - paths[i].push_back(std::move(parts)); - } - } - const auto suffix = [&](std::size_t index, qsizetype depth) { - QStringList roots; - for (const auto &parts : paths[index]) - roots.push_back( - parts.mid(std::max(qsizetype{0}, parts.size() - depth)).join('/')); - return roots.join(QStringLiteral(", ")).toStdString(); - }; - for (std::size_t i = 0; i < matches.size(); ++i) { - qsizetype depth = 1; - for (; depth < maxDepth; ++depth) { - bool ambiguous = false; - for (std::size_t j = 0; j < matches.size(); ++j) - ambiguous |= i != j && suffix(i, depth) == suffix(j, depth) && - suffix(i, maxDepth) != suffix(j, maxDepth); - if (!ambiguous) - break; - } - const auto context = suffix(i, depth); - if (!context.empty()) - matches[i]->label = name + " — " + context; - } - } - // A literal name can also equal a generated path label. Resolve collisions - // across the final catalog, extending ID suffixes only as far as necessary. - for (;;) { - std::map> labels; - for (auto &group : groups) - labels[group.label].push_back(&group); - bool ambiguous = false; - for (const auto &[label, matches] : labels) { - if (matches.size() < 2) - continue; - ambiguous = true; - for (auto *group : matches) { - std::size_t length = std::min(std::size_t{6}, group->id.size()); - for (; length < group->id.size(); ++length) { - const auto suffix = group->id.substr(group->id.size() - length); - if (std::ranges::none_of(matches, [&](const auto *other) { - return other != group && other->id.ends_with(suffix); - })) - break; - } - group->label = - label + " · " + group->id.substr(group->id.size() - length); - } - } - if (!ambiguous) - break; - } -} - -UiStatus uiStatus(nodegraph::NodeStatusView status) { - return statusFromNode(status.semantic, status.unknownText); -} - -constexpr std::array TokenFields{ - "totalTokens", "inputTokens", "outputTokens", "cachedInputTokens", - "cacheWriteInputTokens", "reasoningOutputTokens"}; -using TokenCounts = std::array, TokenFields.size()>; - -TokenCounts tokenCounts(const nodegraph::Value *value) { - TokenCounts counts; - const auto *object = value ? value->asObject() : nullptr; - for (std::size_t i = 0; i < counts.size(); ++i) { - counts[i] = object ? signedIntegerFromValue(valueMember(*object, TokenFields[i])) - : std::nullopt; - if (counts[i] && *counts[i] < 0) - counts[i].reset(); - } - return counts; -} - -std::string tokenNumber(std::optional count, bool compact) { - if (!count) - return "—"; - if (compact && *count >= 1000) { - const bool millions = *count >= 1000000; - return (QLocale::c().toString(static_cast(*count) / - (millions ? 1000000.0 : 1000.0), 'f', 1) + - (millions ? "M" : "k")).toStdString(); - } - return QLocale(QLocale::English, QLocale::UnitedStates) - .toString(static_cast(*count)).toStdString(); -} - -TokenUsageText tokenText(const TokenCounts &counts, std::string prefix) { - TokenUsageText text; - text.summary = std::move(prefix) + " " + tokenNumber(counts[0], true) + - " | In " + tokenNumber(counts[1], true) + - " | Out " + tokenNumber(counts[2], true); - constexpr std::array labels{"Total", "Input", "Output", "Cached input", - "Cache-write input", "Reasoning output"}; - for (std::size_t i = 0; i < counts.size(); ++i) - text.details += std::string(labels[i]) + ": " + tokenNumber(counts[i], false) + "\n"; - text.details += "Cached input and reasoning are breakdowns, not additional totals.\n"; - return text; -} - -UiStatus uiStatusFromValue(const nodegraph::Value *value) { - return uiStatus(nodegraph::nodeStatusView(value)); -} - -bool graphProviderHasMoreHistory(const nodegraph::NodeState &state) { - return boolFromValue(valueMember(state, "historyHasMore")); -} - -bool isConversationSnapshotMethod(std::string_view method) noexcept { - return method == "thread/read" || method == "thread/turns/list" || - method == "thread/items/list"; -} - -bool hasPendingHistoryRequest(const nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread) { - for (const nodegraph::NodeRef &operation : - read.related(thread, nodegraph::RelationKind::PendingOperation)) { - const auto state = read.state(operation); - if (state && state->status == nodegraph::NodeStatus::Pending && - isConversationSnapshotMethod( - scalarTextFromValue(valueMember(*state, "method")))) - return true; - } - return false; -} - -bool fieldChanged(const nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &node, std::string_view field, - std::uint64_t revision) { - return node && read.contains(node) && - read.fieldChangedRevision(node, field) == revision; -} - -UiStatus agentUiStatus(const nodegraph::NodeState &state); - -struct PendingPromptPresentation { - bool awaitingConversation = false; - std::optional admittedAtMs; - nodegraph::NodeRef provisionalTurn; -}; - -PendingPromptPresentation -pendingPromptPresentation(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread) { - PendingPromptPresentation result; - for (const nodegraph::NodeRef &prompt : - read.related(thread, nodegraph::RelationKind::PendingPrompt)) { - if (prompt->id().kind != nodegraph::NodeKind::Item) - continue; - const auto state = read.state(prompt); - if (!state || - scalarTextFromValue(valueMember(*state, "type")) != "localPrompt") - continue; - const std::string dispatch = - scalarTextFromValue(valueMember(*state, "dispatchState")); - const bool awaiting = dispatch == "queued" || dispatch == "dispatching" || - dispatch == "inFlight" || - dispatch == "awaitingMaterialization"; - if (!awaiting || - read.hasIncomingRelation( - prompt, nodegraph::RelationKind::PromptMaterialization)) - continue; - result.awaitingConversation = true; - const auto admittedAt = - signedIntegerFromValue(valueMember(*state, "admittedAtMs")); - if (admittedAt && - (!result.admittedAtMs || *admittedAt < *result.admittedAtMs)) - result.admittedAtMs = admittedAt; - if (!result.provisionalTurn && - boolFromValue(valueMember(*state, "startsTurn")) && - (dispatch == "dispatching" || dispatch == "inFlight") && - (state->status == nodegraph::NodeStatus::Pending || - state->status == nodegraph::NodeStatus::Running)) { - const nodegraph::NodeRef turn = read.parent(prompt); - if (turn && turn->id().kind == nodegraph::NodeKind::Turn && - read.parent(turn) == thread) - result.provisionalTurn = turn; - } - } - return result; -} - -std::vector graphStrings(const nodegraph::Value *value) { - std::vector result; - const auto *array = value ? value->asArray() : nullptr; - if (!array) - return result; - result.reserve(array->size()); - for (const nodegraph::Value &entry : *array) - if (const auto *text = entry.asString(); text && !text->empty()) - result.push_back(*text); - return result; -} - -std::uint64_t graphOmittedTextBytes(const nodegraph::NodeState &state, - std::string_view field) { - const nodegraph::Value *retention = valueMember(state, "textRetention"); - const auto *retentionObject = retention ? retention->asObject() : nullptr; - const nodegraph::Value *entry = - retentionObject ? valueMember(*retentionObject, field) : nullptr; - const auto *entryObject = entry ? entry->asObject() : nullptr; - const nodegraph::Value *discarded = - entryObject ? valueMember(*entryObject, "discardedBytes") : nullptr; - return nodegraph::unsignedIntegerFromValue(discarded).value_or(0); -} - -std::string withTruncationNotice(std::string value, std::uint64_t omitted, - std::string_view subject, bool markdown) { - if (omitted == 0) - return value; - const std::string notice = "Earlier " + std::string(subject) + - " was truncated (" + std::to_string(omitted) + - " bytes omitted)."; - return markdown ? "> " + notice + "\n\n" + value - : '[' + notice + "]\n" + value; -} - -std::vector graphImagePaths(const nodegraph::NodeState &state) { - std::vector result; - const auto *content = valueMember(state, "content"); - const auto *array = content ? content->asArray() : nullptr; - if (!array) - return result; - for (const nodegraph::Value &entry : *array) { - const auto *object = entry.asObject(); - if (!object || - scalarTextFromValue(valueMember(*object, "type")) != "localImage") - continue; - if (std::string path = scalarTextFromValue(valueMember(*object, "path")); - !path.empty()) - result.push_back(std::move(path)); - } - return result; -} - -std::vector -graphLocalPromptImagePaths(const nodegraph::NodeState &state) { - std::vector result; - const nodegraph::Value *attachments = valueMember(state, "attachments"); - const auto *array = attachments ? attachments->asArray() : nullptr; - if (!array) - return result; - for (const nodegraph::Value &entry : *array) { - const auto *object = entry.asObject(); - if (!object || !scalarTextFromValue(valueMember(*object, "mimeType")) - .starts_with("image/")) - continue; - if (std::string path = scalarTextFromValue(valueMember(*object, "path")); - !path.empty()) - result.emplace_back(std::move(path)); - } - return result; -} - -std::string graphJoinedText(const nodegraph::Value *value) { - const auto *array = value ? value->asArray() : nullptr; - if (!array) - return scalarTextFromValue(value); - std::string result; - for (const nodegraph::Value &entry : *array) { - std::string text = scalarTextFromValue(&entry); - if (text.empty()) - if (const auto *object = entry.asObject()) - text = scalarTextFromValue(valueMember(*object, "text")); - if (text.empty()) - continue; - if (!result.empty()) - result += ", "; - result += text; - } - return result; -} - -std::pair graphDiffCounts(std::string_view diff) { - int additions = 0; - int deletions = 0; - for (std::size_t offset = 0; offset <= diff.size();) { - const std::size_t end = diff.find('\n', offset); - const std::string_view line = - diff.substr(offset, end == std::string_view::npos ? diff.size() - offset - : end - offset); - if (!line.starts_with("+++ ") && !line.starts_with("--- ")) { - if (line.starts_with('+')) - ++additions; - else if (line.starts_with('-')) - ++deletions; - } - if (end == std::string_view::npos) - break; - offset = end + 1; - } - return {additions, deletions}; -} - -constexpr std::size_t MaximumGraphActivityDetailBytes = 4000; - -class GraphDetailBuilder final { -public: - void append(std::string_view text) { - if (text.empty() || truncated_) - return; - std::size_t count = - std::min(text.size(), MaximumGraphActivityDetailBytes - value_.size()); - truncated_ = count < text.size(); - while (count > 0 && count < text.size() && - (static_cast(text[count]) & 0xc0U) == 0x80U) - --count; - value_.append(text.substr(0, count)); - } - - void indent(int depth) { - for (int index = 0; index < depth; ++index) - append(" "); - } - - [[nodiscard]] bool truncated() const noexcept { return truncated_; } - - [[nodiscard]] std::string finish() && { - if (truncated_) - value_ += "\n\n[Activity details truncated]"; - return std::move(value_); - } - -private: - std::string value_; - bool truncated_ = false; -}; - -// Use shortest round-trip numbers, with the browser's decimal/exponent range. -// Integer Value alternatives retain their exact protocol representation. -std::string graphDetailNumber(double value) { - if (value == 0) - return "0"; - char buffer[64]; - const auto converted = std::to_chars(std::begin(buffer), std::end(buffer), - value, std::chars_format::scientific); - std::string result(buffer, converted.ptr); - const auto exponentAt = result.find('e'); - if (exponentAt == std::string::npos) - return result; - int exponent = 0; - const char *digits = result.data() + exponentAt + 1; - if (*digits == '+') - ++digits; - std::from_chars(digits, result.data() + result.size(), exponent); - result.resize(exponentAt); - if (exponent < -6 || exponent >= 21) - return result + "e" + (exponent >= 0 ? "+" : "") + std::to_string(exponent); - const std::size_t sign = result.front() == '-' ? 1 : 0; - const auto point = result.find('.'); - if (point != std::string::npos) - result.erase(point, 1); - if (exponent < 0) - result.insert(sign, "0." + std::string(-exponent - 1, '0')); - else if (const auto position = sign + static_cast(exponent) + 1; - position < result.size()) - result.insert(position, "."); - else - result.append(position - result.size(), '0'); - return result; -} - -void appendGraphDetail(GraphDetailBuilder &builder, - const nodegraph::Value &value, int depth) { - if (builder.truncated()) - return; - if (value.isNull()) { - builder.append("none"); - return; - } - if (const auto *boolean = value.asBool()) { - builder.append(*boolean ? "true" : "false"); - return; - } - if (const auto *number = value.asInt64()) { - builder.append(std::to_string(*number)); - return; - } - if (const auto *number = value.asUInt64()) { - builder.append(std::to_string(*number)); - return; - } - if (const auto *number = value.asDouble()) { - builder.append(graphDetailNumber(*number)); - return; - } - if (const auto *text = value.asString()) { - builder.append(*text); - return; - } - if (depth >= 4) { - builder.append("nested detail omitted"); - return; - } - if (const auto *array = value.asArray()) { - if (array->empty()) { - builder.append("none"); - return; - } - for (const nodegraph::Value &entry : *array) { - builder.append("\n"); - builder.indent(depth + 1); - builder.append("- "); - appendGraphDetail(builder, entry, depth + 1); - if (builder.truncated()) - return; - } - return; - } - const auto *object = value.asObject(); - if (!object || object->empty()) { - builder.append("none"); - return; - } - for (const auto &[key, entry] : *object) { - builder.append("\n"); - builder.indent(depth + 1); - builder.append(key); - builder.append(": "); - appendGraphDetail(builder, entry, depth + 1); - if (builder.truncated()) - return; - } -} - -std::string graphDisplayDetail(const nodegraph::NodeState &state) { - GraphDetailBuilder builder; - for (const auto &[key, value] : state.fields) { - // Graph identity/retention metadata is not part of the activity payload. - if (key == "protocolId" || key == "protocolThreadId" || - key == "protocolTurnId" || key == "textRetention") - continue; - builder.append(key); - builder.append(": "); - appendGraphDetail(builder, value, 0); - if (builder.truncated()) - break; - builder.append("\n"); - } - return std::move(builder).finish(); -} - -CardKind graphCardKind(const nodegraph::NodeState &state) { - const std::string type = scalarTextFromValue(valueMember(state, "type")); - if (type == "localPrompt") - return CardKind::LocalPrompt; - if (type == "userMessage") - return CardKind::UserMessage; - if (type == "agentMessage") - return CardKind::AgentMessage; - if (type == "commandExecution") - return CardKind::CommandExecution; - if (type == "collabAgentToolCall" || type == "subAgentActivity") - return CardKind::AgentActivity; - if (type == "reasoning") - return CardKind::Reasoning; - if (type == "fileChange") - return CardKind::FileChanges; - if (type == "imageGeneration" || type == "imageView") - return CardKind::ImageGeneration; - if (type == "plan" && !nodegraph::messageText(state).empty()) { - return CardKind::Plan; - } - return CardKind::GenericActivity; -} - -VisibleCardData graphCardData(const nodegraph::NodeRef &item, - std::string threadId, std::string turnId, - const nodegraph::NodeState &state, - std::string_view threadCwd = {}) { - const std::string itemId = - item ? nodegraph::protocolCanonicalId(state, item) : std::string{}; - const std::string type = scalarTextFromValue(valueMember(state, "type")); - const CardKind kind = graphCardKind(state); - VisibleCardData result{AuthoritativeItemKey{threadId, turnId, itemId}, - kind, - std::move(threadId), - std::move(turnId), - itemId, - GenericActivityData{}, - {}, - {}}; - - result.status = statusFromState(state); - result.timing = protocolTimes(state.fields, "ItemLifecycle"); - if (result.kind == CardKind::AgentActivity) - result.status = agentUiStatus(state); - else if (result.kind == CardKind::ImageGeneration && type == "imageView") - result.status = nodegraph::NodeStatus::Completed; - else if (result.kind == CardKind::UserMessage || - result.kind == CardKind::AgentMessage || - result.kind == CardKind::LocalPrompt) - result.status = {}; - switch (result.kind) { - case CardKind::UserMessage: { - result.payload = UserMessageData{nodegraph::messageText(state), graphImagePaths(state)}; - break; - } - case CardKind::AgentMessage: - result.payload = AgentMessageData{ - withTruncationNotice(nodegraph::messageText(state), graphOmittedTextBytes(state, "text"), "Codex response", true), - scalarTextFromValue(valueMember(state, "phase")), - scalarTextFromValue(valueMember(state, "delivery")) == "async" && valueMember(state, "questions") - ? PendingRequestPolicy::asyncQuestionRequest(jsonFromValue(*valueMember(state, "questions"))) - : nlohmann::json(nullptr)}; - break; - case CardKind::CommandExecution: { - std::string outputField = "aggregatedOutput"; - std::string output = - scalarTextFromValue(valueMember(state, "aggregatedOutput")); - if (output.empty()) { - outputField = "output"; - output = scalarTextFromValue(valueMember(state, "output")); - } - output = withTruncationNotice(std::move(output), - graphOmittedTextBytes(state, outputField), - "command output", false); - if (!terminalOutputHasVisibleText(output)) - output.clear(); - const auto exit = signedIntegerFromValue(valueMember(state, "exitCode")); - auto duration = signedIntegerFromValue(valueMember(state, "durationMs")); - if (!duration) - duration = signedIntegerFromValue(valueMember(state, "duration_ms")); - result.payload = CommandExecutionData{ - scalarTextFromValue(valueMember(state, "command")), std::move(output), - scalarTextFromValue(valueMember(state, "cwd")), - exit ? std::optional(static_cast(*exit)) : std::nullopt, - duration}; - break; - } - case CardKind::AgentActivity: - result.payload = AgentActivityData{ - scalarTextFromValue(valueMember(state, "tool")), - scalarTextFromValue(valueMember(state, "kind")), - scalarTextFromValue(valueMember(state, "prompt")), - scalarTextFromValue(valueMember(state, "resultText")), - graphStrings(valueMember(state, "receiverThreadIds")), - scalarTextFromValue(valueMember(state, "model")), - scalarTextFromValue(valueMember(state, "reasoningEffort")), - scalarTextFromValue(valueMember(state, "agentThreadId")), - scalarTextFromValue(valueMember(state, "agentPath")), - scalarTextFromValue(valueMember(state, "senderThreadId"))}; - break; - case CardKind::Reasoning: - result.payload = ReasoningData{withTruncationNotice( - graphJoinedText(valueMember(state, "summary")), - graphOmittedTextBytes(state, "summary"), "reasoning", true)}; - break; - case CardKind::FileChanges: { - std::string cwd = scalarTextFromValue(valueMember(state, "cwd")); - if (cwd.empty()) - cwd = threadCwd; - FileChangesData projected{{}, std::move(cwd)}; - const auto *changes = valueMember(state, "changes"); - const auto *array = changes ? changes->asArray() : nullptr; - if (array) { - projected.changes.reserve(array->size()); - for (const nodegraph::Value &value : *array) { - const auto *change = value.asObject(); - if (!change) - continue; - FileChangeData entry{scalarTextFromValue(valueMember(*change, "path")), - scalarTextFromValue(valueMember(*change, "kind")), - std::nullopt, std::nullopt}; - const auto additions = - signedIntegerFromValue(valueMember(*change, "additions")); - const auto deletions = - signedIntegerFromValue(valueMember(*change, "deletions")); - if (additions && deletions && *additions >= 0 && *deletions >= 0) { - entry.additions = static_cast(std::min( - *additions, std::numeric_limits::max())); - entry.deletions = static_cast(std::min( - *deletions, std::numeric_limits::max())); - } else if (const nodegraph::Value *diffValue = - valueMember(*change, "diff"); - diffValue && diffValue->asString() && - !diffValue->asString()->empty()) { - const std::string &diff = *diffValue->asString(); - const auto [additions, deletions] = graphDiffCounts(diff); - entry.additions = additions; - entry.deletions = deletions; - } - projected.changes.push_back(std::move(entry)); - } - } - result.payload = std::move(projected); - break; - } - case CardKind::ImageGeneration: { - std::string path = scalarTextFromValue(valueMember(state, "path")); - if (path.empty()) - path = scalarTextFromValue(valueMember(state, "savedPath")); - if (path.empty()) - path = scalarTextFromValue(valueMember(state, "saved_path")); - std::string prompt = - scalarTextFromValue(valueMember(state, "revisedPrompt")); - if (prompt.empty()) - prompt = scalarTextFromValue(valueMember(state, "revised_prompt")); - result.payload = ImageGenerationData{std::move(path), std::move(prompt)}; - break; - } - case CardKind::Plan: - result.payload = - PlanData{{}, {}, withTruncationNotice(nodegraph::messageText(state), graphOmittedTextBytes(state, "text"), "plan text", true)}; - break; - case CardKind::GenericActivity: - result.payload = GenericActivityData{type, graphDisplayDetail(state)}; - break; - case CardKind::LocalPrompt: { - const std::string dispatch = - scalarTextFromValue(valueMember(state, "dispatchState")); - PromptState promptState = PromptState::Queued; - if (dispatch == "dispatching" || dispatch == "inFlight") - promptState = PromptState::InFlight; - else if (dispatch == "awaitingMaterialization") - promptState = PromptState::Accepted; - else if (dispatch == "failed" || dispatch == "uncertain") - promptState = PromptState::Failed; - const std::int64_t rawId = - signedIntegerFromValue(valueMember(state, "submissionId")).value_or(0); - const std::uint64_t submissionId = - rawId < 0 ? 0 : static_cast(rawId); - result.key = LocalPromptKey{submissionId}; - result.itemId.clear(); - result.payload = LocalPromptData{ - submissionId, - scalarTextFromValue(valueMember(state, "text")), - promptState, - scalarTextFromValue(valueMember(state, "error")), - graphLocalPromptImagePaths(state), - signedIntegerFromValue(valueMember(state, "admittedAtMs")), - boolFromValue(valueMember(state, "requiresExplicitRecovery"))}; - break; - } - } - result.target = item; - return result; -} - -struct MaterializedPrompt { - nodegraph::NodeRef prompt; - std::optional submissionId; -}; - -std::optional -materializedPrompt(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &item) { - if (!item) - return std::nullopt; - std::optional fallback; - for (const nodegraph::NodeRef &prompt : - read.related(item, nodegraph::RelationKind::PromptMaterialization)) { - if (prompt->id().kind != nodegraph::NodeKind::Item) - continue; - const auto state = read.state(prompt); - if (!state || - scalarTextFromValue(valueMember(*state, "type")) != "localPrompt") - continue; - const auto rawSubmission = - signedIntegerFromValue(valueMember(*state, "submissionId")); - MaterializedPrompt candidate{ - prompt, rawSubmission && *rawSubmission >= 0 - ? std::optional{static_cast( - *rawSubmission)} - : std::nullopt}; - if (candidate.submissionId) - return candidate; - if (!fallback) - fallback = std::move(candidate); - } - return fallback; -} - -std::optional -conversationCardKey(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &item, std::string_view threadId, - std::string_view turnId, bool hiddenPrompt = false) { - if (!read.live(item) || - item->id().kind != nodegraph::NodeKind::Item) - return std::nullopt; - const auto state = read.state(item); - if (!state) - return std::nullopt; - const std::string type = scalarTextFromValue(valueMember(*state, "type")); - if (type == "localPrompt") { - if (hiddenPrompt) - return std::nullopt; - const std::int64_t rawId = - signedIntegerFromValue(valueMember(*state, "submissionId")).value_or(0); - return LocalPromptKey{rawId < 0 ? 0 : static_cast(rawId)}; - } - if (graphCardKind(*state) == CardKind::UserMessage) { - if (const auto materialized = materializedPrompt(read, item); - materialized && materialized->submissionId) - return LocalPromptKey{*materialized->submissionId}; - const auto submission = - signedIntegerFromValue(valueMember(*state, "localSubmissionId")); - if (submission && *submission >= 0) - return LocalPromptKey{static_cast(*submission)}; - } - return AuthoritativeItemKey{std::string(threadId), std::string(turnId), - nodegraph::protocolCanonicalId(*state, item)}; -} - -bool isHiddenMaterializedPrompt(const nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &prompt) { - if (!read.live(prompt)) - return false; - const auto state = read.state(prompt); - return state && - scalarTextFromValue(valueMember(*state, "type")) == "localPrompt" && - read.hasIncomingRelation( - prompt, nodegraph::RelationKind::PromptMaterialization); -} - -nodegraph::NodeRef conversationTurnRoot( - const nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &turn) { - const auto roots = read.related(turn, nodegraph::RelationKind::TurnRootItem); - return roots.empty() ? nodegraph::NodeRef{} : roots.front(); -} - -bool conversationItemsComplete(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& turn) { - const auto state = turn ? read.state(turn) : nullptr; - return state && valueMember(*state, "itemsHistoryHasMore") && !boolFromValue(valueMember(*state, "itemsHistoryHasMore")); -} - -nodegraph::NodeRef conversationOpeningItem(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& turn) { - const auto root = conversationTurnRoot(read, turn); - return root ? root : conversationItemsComplete(read, turn) ? read.childAt(turn, 0) : nodegraph::NodeRef{}; -} - -nodegraph::NodeRef -conversationActiveTurn(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread) { - for (const nodegraph::NodeRef &turn : - read.related(thread, nodegraph::RelationKind::ActiveTurn)) - if (turn->id().kind == nodegraph::NodeKind::Turn && - read.parent(turn) == thread) - return turn; - return pendingPromptPresentation(read, thread).provisionalTurn; -} - -VisibleCardData conversationCardData(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &item, - std::string threadId, std::string turnId, - const nodegraph::NodeState &state, - std::string_view threadCwd = {}) { - const std::optional key = - conversationCardKey(read, item, threadId, turnId); - VisibleCardData result = graphCardData(item, std::move(threadId), - std::move(turnId), state, threadCwd); - if (auto* message = std::get_if(&result.payload); message && !message->questionRequest.is_null()) { - const auto& questions = message->questionRequest["questions"]; - message->answers.resize(questions.size()); - std::map keys; - for (std::size_t i = 0; i < questions.size(); ++i) { - keys.emplace(nodegraph::questionReplyKey(result.itemId, i), i); - } - bool sending = false; - for (const auto& source : read.questionReplies(item)) { - const auto state = read.state(source); - const auto dispatch = isHiddenMaterializedPrompt(read, source) ? "" : scalarTextFromValue(valueMember(*state, "dispatchState")); - const bool accepted = scalarTextFromValue(valueMember(*state, "type")) == "userMessage" || dispatch == "awaitingMaterialization"; - for (const auto& reply : nodegraph::questionReplies(nodegraph::messageText(*state))) { - const auto found = keys.find(reply.questionItemId); - if (found != keys.end() && reply.question == questions[found->second]["question"].get() && - !reply.answer.empty()) { - if (accepted) { - message->answers[found->second] = reply.answer; - } - sending |= dispatch == "queued" || dispatch == "dispatching" || dispatch == "inFlight"; - } - } - } - const std::size_t count = std::ranges::count_if(message->answers, [](const auto& answer) { - return !answer.empty(); - }); - message->questionStatus = sending ? "Sending…" - : count == questions.size() ? "✓ Answer sent" - : count ? std::to_string(count) + "/" + std::to_string(questions.size()) + " answers sent" - : ""; - if (count) { - std::vector replies; - for (std::size_t i = 0; i < questions.size(); ++i) { - replies.push_back({{}, questions[i]["question"], message->answers[i]}); - } - message->text = nodegraph::questionReplyMarkdown(replies); - } - } - if (key) - result.key = *key; - const auto turn = read.parent(item); - result.turnOpening = - turn && result.kind != CardKind::LocalPrompt && conversationItemsComplete(read, turn) && conversationOpeningItem(read, turn) == item; - if (turn && - read.isRelated(turn, nodegraph::RelationKind::TurnRootItem, item)) { - auto timing = protocolTimes(read.state(turn)->fields, "Turn"); - for (auto &time : timing) - time.field = "turn/" + time.field; - result.timing.insert(result.timing.end(), timing.begin(), timing.end()); - } - return result; -} - -void updateAgentStatus(UiStatus ¤t, UiStatus candidate) { - if (candidate.empty() || - (isTerminalTurnStatus(current) && isActiveStatus(candidate))) - return; - current = std::move(candidate); -} - -UiStatus agentUiStatus(const nodegraph::NodeState &state) { - return uiStatus(nodegraph::agentActivityStatus(state)); -} - -std::string threadRowPresentationKey(const nodegraph::NodeRef &thread, - const nodegraph::NodeState &state) { - const std::string correlation = - exactStringFromValue(valueMember(state, "creationCorrelation")); - return correlation.empty() - ? "thread:" + std::to_string(thread->incarnation()) - : ui::threadPresentationKey(thread->id().canonical, correlation); -} - -std::string settingString(const nodegraph::Value *value, - std::string_view fallback = {}) { - const std::string result = exactStringFromValue(value); - return result.empty() ? std::string(fallback) : result; -} - -std::string settingSandbox(const nodegraph::Value *value) { - std::string type = settingString(value); - if (const auto *object = value ? value->asObject() : nullptr) - type = settingString(valueMember(*object, "type")); - if (type == "readOnly") - return "read-only"; - if (type == "workspaceWrite") - return "workspace-write"; - if (type == "dangerFullAccess") - return "danger-full-access"; - if (type == "externalSandbox") - return "external"; - if (type == "read-only" || type == "workspace-write" || - type == "danger-full-access" || type == "external") - return type; - return std::string(DefaultTurnSetting); -} - -std::vector -settingModels(nodegraph::NodeGraph::ReadAccess &read) { - std::vector result; - const nodegraph::NodeRef catalog = - read.find({nodegraph::NodeKind::Catalog, "model"}); - if (!catalog) - return result; - for (const nodegraph::NodeRef &entry : read.children(catalog)) { - const auto state = read.state(entry); - const nodegraph::Value *hidden = valueMember(*state, "hidden"); - if (hidden && hidden->asBool() && *hidden->asBool()) - continue; - std::string id = settingString(valueMember(*state, "model")); - if (id.empty()) - id = settingString(valueMember(*state, "id")); - if (id.empty()) - continue; - TurnSettingModel model; - model.choice.value = id; - model.choice.label = settingString(valueMember(*state, "displayName")); - if (model.choice.label.empty()) - model.choice.label = id; - model.choice.description = - settingString(valueMember(*state, "description")); - model.isDefault = boolFromValue(valueMember(*state, "isDefault")); - model.defaultReasoningEffort = - settingString(valueMember(*state, "defaultReasoningEffort")); - model.defaultServiceTier = - settingString(valueMember(*state, "defaultServiceTier")); - std::unordered_set effortIds; - if (const nodegraph::Value *supported = - valueMember(*state, "supportedReasoningEfforts"); - supported && supported->asArray()) { - for (const nodegraph::Value &option : *supported->asArray()) { - const auto *fields = option.asObject(); - const std::string effort = - fields ? settingString(valueMember(*fields, "reasoningEffort")) - : std::string{}; - if (!effort.empty() && effortIds.insert(effort).second) - model.reasoningEfforts.push_back(effort); - } - } - std::unordered_set tierIds; - if (const nodegraph::Value *tiers = valueMember(*state, "serviceTiers"); - tiers && tiers->asArray()) { - for (const nodegraph::Value &tier : *tiers->asArray()) { - const auto *fields = tier.asObject(); - const std::string tierId = - fields ? settingString(valueMember(*fields, "id")) : std::string{}; - if (tierId.empty() || !tierIds.insert(tierId).second) - continue; - std::string label = settingString(valueMember(*fields, "name")); - model.serviceTiers.push_back( - {tierId, label.empty() ? tierId : std::move(label), - settingString(valueMember(*fields, "description"))}); - } - } - if (const nodegraph::Value *tiers = - valueMember(*state, "additionalSpeedTiers"); - tiers && tiers->asArray()) { - for (const nodegraph::Value &tier : *tiers->asArray()) { - const std::string value = settingString(&tier); - if (!value.empty() && tierIds.insert(value).second) - model.serviceTiers.push_back({value, {}, {}}); - } - } - if (const nodegraph::Value *personality = - valueMember(*state, "supportsPersonality"); - personality && personality->asBool()) - model.supportsPersonality = *personality->asBool(); - result.push_back(std::move(model)); - } - return result; -} - -std::vector -settingPermissionProfiles(nodegraph::NodeGraph::ReadAccess &read) { - std::vector result; - const nodegraph::NodeRef catalog = - read.find({nodegraph::NodeKind::Catalog, "permissionProfile"}); - if (!catalog) - return result; - for (const nodegraph::NodeRef &entry : read.children(catalog)) { - const auto state = read.state(entry); - const nodegraph::Value *allowed = valueMember(*state, "allowed"); - if (allowed && allowed->asBool() && !*allowed->asBool()) - continue; - const std::string id = settingString(valueMember(*state, "id")); - if (!id.empty()) - result.push_back( - {id, {}, settingString(valueMember(*state, "description"))}); - } - return result; -} - -bool canControlRequests(nodegraph::NodeGraph::ReadAccess &read) { - const nodegraph::NodeRef connection = - read.find({nodegraph::NodeKind::Connection, "connection"}); - if (!connection) - return false; - const auto state = read.state(connection); - return state && state->status == nodegraph::NodeStatus::Connected && - scalarTextFromValue(valueMember(*state, "providerState")) == "ready" && - scalarTextFromValue(valueMember(*state, "role")) == "controller"; -} - -nodegraph::NodeRef -interactionThread(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &interaction) { - const std::size_t targetCount = read.relatedCount( - interaction, nodegraph::RelationKind::InteractionTarget); - for (std::size_t index = 0; index < targetCount; ++index) - for (nodegraph::NodeRef target = read.relatedAt( - interaction, nodegraph::RelationKind::InteractionTarget, index); - target; target = read.parent(target)) - if (target->id().kind == nodegraph::NodeKind::Thread) - return target; - return {}; -} - -std::string requestThreadId(const nodegraph::NodeState &state, - const nodegraph::NodeRef &exactThread) { - if (exactThread) - return exactThread->id().canonical; - const nodegraph::Value *payload = valueMember(state, "payload"); - const auto *object = payload ? payload->asObject() : nullptr; - return object ? scalarTextFromValue(valueMember(*object, "threadId")) - : std::string{}; -} - -PendingRequestDescriptor -projectPendingRequest(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &interaction, bool canControl) { - const auto state = read.state(interaction); - PendingRequestDescriptor request; - request.target = interaction; - request.method = scalarTextFromValue(valueMember(*state, "method")); - request.kind = PendingRequestPolicy::kindForMethod(request.method); - request.error = scalarTextFromValue(valueMember(*state, "error")); - request.responseRevision = nodegraph::unsignedIntegerFromValue( - valueMember(*state, "responseRevision")) - .value_or(0); - - const nodegraph::Value *payload = valueMember(*state, "payload"); - if (payload) - request.raw = jsonFromValue(*payload); - - const nodegraph::NodeRef thread = interactionThread(read, interaction); - request.threadId = requestThreadId(*state, thread); - if (thread) { - const auto threadState = read.state(thread); - request.threadTitle = - scalarTextFromValue(valueMember(*threadState, "name")); - if (request.threadTitle.empty()) - request.threadTitle = - scalarTextFromValue(valueMember(*threadState, "title")); - } - - const nodegraph::Value *retained = - valueMember(*state, "retainedResponsePayload"); - if (const auto *object = retained ? retained->asObject() : nullptr) { - PendingRequestSubmission submission; - submission.choice = scalarTextFromValue(valueMember(*object, "choice")); - if (const nodegraph::Value *input = valueMember(*object, "input")) - submission.input = jsonFromValue(*input); - if (const nodegraph::Value *metadata = valueMember(*object, "metadata")) - submission.metadata = jsonFromValue(*metadata); - if (!submission.choice.empty()) - request.retainedSubmission = std::move(submission); - } - - const bool recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); - request.availability = recoveryOnly ? PendingRequestAvailability::RecoveryOnly - : canControl ? PendingRequestAvailability::Actionable - : PendingRequestAvailability::Unavailable; - return request; -} - -template -std::optional numericSuffix(std::string_view key, - std::string_view prefix) { - if (!key.starts_with(prefix)) - return std::nullopt; - Integer result = 0; - const char *first = key.data() + prefix.size(); - const char *last = key.data() + key.size(); - const auto parsed = std::from_chars(first, last, result); - return parsed.ec == std::errc{} && parsed.ptr == last - ? std::optional{result} : std::nullopt; -} - -std::optional -requestPosition(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &runtime, std::string_view key) { - const auto incarnation = numericSuffix(key, "request:"); - if (!incarnation) - return std::nullopt; - std::size_t first = 0; - std::size_t last = read.relatedCount( - runtime, nodegraph::RelationKind::PendingInteraction); - while (first < last) { - const std::size_t middle = first + (last - first) / 2; - const nodegraph::NodeRef candidate = read.relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, middle); - if (candidate->incarnation() < *incarnation) - first = middle + 1; - else - last = middle; - } - const nodegraph::NodeRef found = read.relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, first); - return found && found->incarnation() == *incarnation - ? std::optional{first} - : std::nullopt; -} - -bool requestTargetsThread(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &interaction, - const nodegraph::NodeState &state, - std::string_view selectedThreadId) { - return requestThreadId(state, interactionThread(read, interaction)) == - selectedThreadId; -} - -template -void forEachPendingRequestThread(nodegraph::NodeGraph::ReadAccess &read, - Visitor &&visit) { - const nodegraph::NodeRef runtime = - read.find({nodegraph::NodeKind::Runtime, "runtime"}); - if (!runtime) - return; - const std::size_t count = read.relatedCount( - runtime, nodegraph::RelationKind::PendingInteraction); - for (std::size_t index = 0; index < count; ++index) { - const nodegraph::NodeRef interaction = read.relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, index); - if (const nodegraph::NodeRef thread = - interactionThread(read, interaction)) - visit(thread); - } -} - -std::unordered_map -pendingRequestCounts(nodegraph::NodeGraph::ReadAccess &read) { - std::unordered_map result; - forEachPendingRequestThread( - read, [&](const nodegraph::NodeRef &thread) { ++result[thread.get()]; }); - return result; -} - -int pendingRequestRank(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &interaction, - const nodegraph::NodeState &state, bool canControl, - std::string_view selectedThreadId) { - const nodegraph::Value *retained = - valueMember(state, "retainedResponsePayload"); - const auto *object = retained ? retained->asObject() : nullptr; - const bool hasRetained = - object && !scalarTextFromValue(valueMember(*object, "choice")).empty(); - const PendingRequestAvailability availability = - boolFromValue(valueMember(state, "recoveryOnly")) - ? PendingRequestAvailability::RecoveryOnly - : canControl ? PendingRequestAvailability::Actionable - : PendingRequestAvailability::Unavailable; - return PendingRequestPolicy::attentionRank( - availability, hasRetained, - requestTargetsThread(read, interaction, state, selectedThreadId)); -} - -void boundInspectorWindow(InspectorPageSnapshot &page, std::size_t count) { - page.first = std::min(page.first, page.total); - if (page.total == 0 || count == 0) - return; - count = std::min(count, page.total); - if (page.first == page.total) - page.first = page.total - count; - if (!page.anchorIndex) - return; - if (*page.anchorIndex < page.first) - page.first = *page.anchorIndex; - else if (*page.anchorIndex - page.first >= count) - page.first = *page.anchorIndex - count + 1; -} - -template -void projectInspectorWindow(InspectorPageSnapshot &page, - const InspectorRowRequest &request, - Project &&project) { - page.first = request.first; - const std::size_t count = std::min(request.count, MaximumInspectorRows); - boundInspectorWindow(page, count); - const std::size_t end = - page.first + std::min(count, page.total - page.first); - page.rows.reserve(end - page.first); - for (std::size_t row = page.first; row < end; ++row) - page.rows.push_back(project(row)); - if (page.focusedIndex && - (*page.focusedIndex < page.first || *page.focusedIndex >= end)) - page.focused = project(*page.focusedIndex); -} - -InspectorPageSnapshot projectPendingRequests( - nodegraph::NodeGraph::ReadAccess &read, bool canControl, - const InspectorRowRequest &window) { - InspectorPageSnapshot result; - const nodegraph::NodeRef runtime = - read.find({nodegraph::NodeKind::Runtime, "runtime"}); - if (!runtime) { - result.emptyMessage = "No pending requests."; - return result; - } - result.orderRevision = read.pendingInteractionOrderRevision(); - result.total = read.relatedCount( - runtime, nodegraph::RelationKind::PendingInteraction); - result.anchorIndex = requestPosition(read, runtime, window.anchorKey); - result.focusedIndex = requestPosition(read, runtime, window.focusedKey); - projectInspectorWindow(result, window, [&](std::size_t index) { - const nodegraph::NodeRef interaction = read.relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, index); - return InspectorRow{"request:" + std::to_string(interaction->incarnation()), - projectPendingRequest(read, interaction, canControl)}; - }); - if (result.total == 0) - result.emptyMessage = "No pending requests."; - return result; -} - -PendingRequestsSummary projectPendingRequestSummary( - nodegraph::NodeGraph::ReadAccess &read, bool canControl, - std::string_view selectedThreadId, - std::span localTargets) { - PendingRequestsSummary result; - const nodegraph::NodeRef runtime = - read.find({nodegraph::NodeKind::Runtime, "runtime"}); - if (!runtime) - return result; - std::unordered_set local; - local.reserve(localTargets.size()); - for (const nodegraph::NodeRef &target : localTargets) - if (target) - local.insert(target.get()); - int bestRank = std::numeric_limits::max(); - nodegraph::NodeRef best; - std::size_t bestInsertion = 0; - for (std::size_t index = 0; - index < read.relatedCount(runtime, - nodegraph::RelationKind::PendingInteraction); - ++index) { - const nodegraph::NodeRef interaction = read.relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, index); - ++result.total; - if (local.contains(interaction.get())) { - result.candidates.push_back( - projectPendingRequest(read, interaction, canControl)); - continue; - } - const auto state = read.state(interaction); - const int rank = pendingRequestRank(read, interaction, *state, canControl, - selectedThreadId); - if (rank < bestRank) { - bestRank = rank; - best = interaction; - bestInsertion = result.candidates.size(); - } - } - if (best) - result.candidates.insert( - result.candidates.begin() + static_cast(bestInsertion), - projectPendingRequest(read, best, canControl)); - return result; -} - -void appendUniqueBounded(std::vector &values, std::string value, - std::size_t maximum) { - if (value.empty() || std::ranges::find(values, value) != values.end()) - return; - if (values.size() == maximum) - values.erase(values.begin()); - values.emplace_back(std::move(value)); -} - -std::string_view nodeKindName(nodegraph::NodeKind kind) { - using nodegraph::NodeKind; - switch (kind) { - case NodeKind::Runtime: - return "Runtime"; - case NodeKind::Connection: - return "Connection"; - case NodeKind::Thread: - return "Thread"; - case NodeKind::Turn: - return "Turn"; - case NodeKind::Item: - return "Item"; - case NodeKind::Interaction: - return "Interaction"; - case NodeKind::Operation: - return "Operation"; - case NodeKind::Catalog: - return "Catalog"; - case NodeKind::CatalogEntry: - return "CatalogEntry"; - case NodeKind::Account: - return "Account"; - case NodeKind::Configuration: - return "Configuration"; - case NodeKind::PermissionProfile: - return "PermissionProfile"; - case NodeKind::Skill: - return "Skill"; - case NodeKind::Hook: - return "Hook"; - case NodeKind::Plugin: - return "Plugin"; - case NodeKind::App: - return "App"; - case NodeKind::McpServer: - return "McpServer"; - case NodeKind::Project: - return "Project"; - case NodeKind::ThreadSection: - return "ThreadSection"; - case NodeKind::Process: - return "Process"; - case NodeKind::RealtimeSession: - return "RealtimeSession"; - case NodeKind::FilesystemWatch: - return "FilesystemWatch"; - case NodeKind::ExternalAgentImport: - return "ExternalAgentImport"; - case NodeKind::FuzzyFileSearchSession: - return "FuzzyFileSearchSession"; - case NodeKind::LoginAttempt: - return "LoginAttempt"; - case NodeKind::Notice: - return "Notice"; - case NodeKind::UnknownProtocol: - return "UnknownProtocol"; - } - return "Unknown"; -} - -bool sensitiveStateField(std::string_view key) { - std::string normalized; - normalized.reserve(key.size()); - for (const unsigned char character : key) - if (std::isalnum(character)) - normalized.push_back(static_cast(std::tolower(character))); - return normalized == "payload" || normalized == "requestpayload" || - normalized == "responsepayload" || - normalized == "retainedresponsepayload" || normalized == "raw" || - normalized == "private" || normalized == "bytes" || - normalized == "command" || normalized == "prompt" || - normalized == "input" || normalized == "output" || - normalized == "delta" || normalized == "error" || - normalized == "message" || normalized == "token" || - normalized.ends_with("token") || - normalized.find("password") != std::string::npos || - normalized.find("secret") != std::string::npos || - normalized.find("credential") != std::string::npos || - normalized.find("authorization") != std::string::npos || - normalized.find("cookie") != std::string::npos || - normalized.find("apikey") != std::string::npos || - normalized.find("privatekey") != std::string::npos; -} - -nlohmann::json safeStateValue(const nodegraph::Value &value, int depth = 0) { - if (depth > 8) - return ""; - if (value.isNull()) - return nullptr; - if (const auto *boolean = value.asBool()) - return *boolean; - if (const auto *number = value.asInt64()) - return *number; - if (const auto *number = value.asUInt64()) - return *number; - if (const auto *number = value.asDouble()) - return *number; - if (const auto *string = value.asString()) { - if (string->size() > 1024) - return string->substr(0, 1024) + "..."; - return *string; - } - if (const auto *array = value.asArray()) { - nlohmann::json result = nlohmann::json::array(); - const std::size_t retained = std::min(array->size(), 32); - for (std::size_t index = 0; index < retained; ++index) - result.push_back(safeStateValue(array->at(index), depth + 1)); - if (array->size() > retained) - result.push_back(""); - return result; - } - nlohmann::json result = nlohmann::json::object(); - const auto *object = value.asObject(); - std::size_t retained = 0; - for (const auto &[key, entry] : *object) { - if (retained++ == 64) { - result[""] = "omitted"; - break; - } - result[key] = sensitiveStateField(key) ? nlohmann::json("") - : safeStateValue(entry, depth + 1); - } - return result; -} - -nlohmann::json safeStateObject(const nodegraph::Value::Object &fields) { - return safeStateValue(nodegraph::Value(fields)); -} - -std::string sectionComponent(std::string_view prefix, std::string_view threadId, - std::string_view suffix) { - std::string result(prefix); - result += std::to_string(threadId.size()); - result.push_back(':'); - result.append(threadId); - result += std::to_string(suffix.size()); - result.push_back(':'); - result.append(suffix); - return result; -} - -std::optional -projectThreadRow(nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread, std::size_t pending) { - if (!read.live(thread) || - thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - const auto state = read.state(thread); - if (!state) - return std::nullopt; - const auto timestamp = [&state](std::string_view field) { - return signedIntegerFromValue(valueMember(*state, field)); - }; - ThreadListRow row; - row.id = thread->id().canonical; - row.presentationKey = threadRowPresentationKey(thread, *state); - row.target = thread; - row.timing = protocolTimes(state->fields, "Thread"); - row.title = scalarTextFromValue(valueMember(*state, "localNameOverlay")); - if (row.title.empty()) - row.title = scalarTextFromValue(valueMember(*state, "name")); - if (row.title.empty()) - row.title = scalarTextFromValue(valueMember(*state, "preview")); - if (row.title.empty()) - row.title = row.id.substr(0, std::min(12, row.id.size())); - row.cwd = scalarTextFromValue(valueMember(*state, "cwd")); - row.workspaceChangeUnavailable = nodegraph::threadWorkspaceChangeUnavailable(read, thread); - row.status = statusFromState(*state); - row.uninspectedResult = boolFromValue(valueMember(*state, "uninspectedResult")); - row.createdAt = timestamp("createdAt"); - row.updatedAt = timestamp("updatedAt"); - row.recencyAt = timestamp("recencyAt"); - if (const auto local = timestamp("localPromptActivityAt"); - local && (!row.recencyAt || *local > *row.recencyAt)) - row.recencyAt = local; - for (const std::string_view field : - {std::string_view("lastActivityAt"), std::string_view("updatedAt"), - std::string_view("recencyAt"), std::string_view("localActivityAt"), - std::string_view("localPromptActivityAt")}) { - const std::optional candidate = timestamp(field); - if (candidate && (!row.lastActivityAt || *candidate > *row.lastActivityAt)) - row.lastActivityAt = candidate; - } - row.pending = pending; - const PendingPromptPresentation prompt = - pendingPromptPresentation(read, thread); - row.awaitingPromptConversation = prompt.awaitingConversation; - row.pendingPromptAdmittedAtMs = prompt.admittedAtMs; - row.archived = boolFromValue(valueMember(*state, "archived")); - if (read.relatedCount(thread, nodegraph::RelationKind::ProjectMembership)) - row.projectId = - read.relatedAt(thread, nodegraph::RelationKind::ProjectMembership, 0) - ->id() - .canonical; - if (read.relatedCount(thread, nodegraph::RelationKind::SectionMembership)) - row.sectionId = - read.relatedAt(thread, nodegraph::RelationKind::SectionMembership, 0) - ->id() - .canonical; - return row; -} - -InspectorPageSnapshot projectPlan( - nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread, - const nodegraph::InspectorThreadIndex *index, - const InspectorRowRequest &request) { - InspectorPageSnapshot result; - if (!thread || !index || !index->planSource) { - result.emptyMessage = thread ? "No plan for this thread." - : "No selected thread."; - return result; - } - const bool legacy = - index->planSource->id().kind == nodegraph::NodeKind::Item; - const std::string sourceId = - std::to_string(index->planSource->incarnation()); - const std::string explanationKey = "plan:" + sourceId + ":explanation"; - const std::string stepPrefix = "plan:step:" + sourceId + ':'; - const auto keyFor = [&](std::size_t row) { - if (legacy) - return "plan:" + sourceId + ":legacy"; - if (index->planHasExplanation && row == 0) - return explanationKey; - return stepPrefix + - std::to_string(row - (index->planHasExplanation ? 1 : 0)); - }; - result.total = index->planRowCount; - result.orderRevision = index->planOrderRevision; - if (result.total == 0 && legacy) - result.emptyMessage = "Plan is being prepared."; - const auto find = [&](const std::string &key) -> std::optional { - if (key.empty()) - return std::nullopt; - if (legacy || key == explanationKey) - return result.total != 0 && key == keyFor(0) - ? std::optional{0} - : std::nullopt; - const auto sourceIndex = numericSuffix(key, stepPrefix); - const std::size_t offset = index->planHasExplanation ? 1 : 0; - if (!sourceIndex || *sourceIndex >= result.total - offset) - return std::nullopt; - return *sourceIndex + offset; - }; - result.anchorIndex = find(request.anchorKey); - result.focusedIndex = find(request.focusedKey); - const auto source = read.state(index->planSource); - const nodegraph::InspectorPlanView plan = - nodegraph::inspectorPlanView(*source); - const UiStatus turnStatus = statusFromState( - *read.state(legacy ? read.parent(index->planSource) : index->planSource)); - const UiStatus threadStatus = statusFromState(*read.state(thread)); - const auto project = [&](std::size_t row) -> InspectorRow { - const std::string key = keyFor(row); - if (!legacy && index->planHasExplanation && row == 0) { - return InspectorRow{ - key, - InspectorMarkdownRow{scalarTextFromValue(plan.explanation), - "Plan explanation", {}}}; - } - if (legacy) - return InspectorRow{ - key, - InspectorMarkdownRow{scalarTextFromValue(valueMember(*source, "text")), - "Plan", {}}}; - const auto *steps = plan.steps->asArray(); - const std::size_t sourceIndex = - row - (index->planHasExplanation ? 1 : 0); - const auto *step = steps->at(sourceIndex).asObject(); - if (!step) - return InspectorRow{key, PlanStepData{}}; - std::string stepText = scalarTextFromValue(valueMember(*step, "step")); - if (stepText.empty()) - stepText = scalarTextFromValue(valueMember(*step, "text")); - return InspectorRow{ - key, - PlanStepData{ - std::move(stepText), - effectivePlanStepStatus( - uiStatusFromValue(valueMember(*step, "status")), turnStatus, - threadStatus)}}; - }; - projectInspectorWindow(result, request, project); - return result; -} - -InspectorPageSnapshot projectAgents( - nodegraph::NodeGraph::ReadAccess &read, - const nodegraph::NodeRef &thread, - const nodegraph::InspectorThreadIndex *index, - const InspectorRowRequest &request) { - InspectorPageSnapshot result; - result.validRetainedKeys.emplace(); - if (!thread || !index || index->agents.empty()) { - result.emptyMessage = thread ? "No agent activity for this thread." - : "No selected thread."; - return result; - } - result.total = index->agents.size(); - result.orderRevision = index->agentOrderRevision; - const auto logicalKey = [](std::string_view key) { - constexpr std::string_view prefix = "agent:"; - return key.starts_with(prefix) ? key.substr(prefix.size()) : key; - }; - const auto find = [&](const std::string &key) -> std::optional { - if (key.empty()) - return std::nullopt; - const auto found = index->agentPositions.find(std::string(logicalKey(key))); - return found == index->agentPositions.end() - ? std::nullopt - : std::optional{found->second}; - }; - const std::size_t retainedCount = - std::min(request.retainedKeys.size(), MaximumInspectorRows); - result.validRetainedKeys->reserve(retainedCount); - for (std::size_t index = 0; index < retainedCount; ++index) { - const std::string &key = request.retainedKeys[index]; - if (find(key) && - std::ranges::find(*result.validRetainedKeys, key) == - result.validRetainedKeys->end()) - result.validRetainedKeys->push_back(key); - } - result.anchorIndex = find(request.anchorKey); - result.focusedIndex = find(request.focusedKey); - const auto project = [&](std::size_t row) -> InspectorRow { - const nodegraph::InspectorAgentSelector &selector = index->agents[row]; - InspectorAgentRow logical; - if (selector.childIdVisible) - logical.childThreadId = selector.childId; - const auto sourceFor = [&](std::size_t field) { - const auto &candidates = selector.candidates[field]; - return candidates.empty() - ? nodegraph::NodeRef{} - : selector.contributors[*candidates.rbegin() / 2]; - }; - const std::array targets{&logical.agentPath, &logical.tool, &logical.model, - &logical.reasoningEffort, &logical.prompt, - &logical.senderThreadId}; - for (std::size_t index = 0; - index < nodegraph::InspectorAgentDetailFields.size(); ++index) - if (const nodegraph::NodeRef source = sourceFor(index)) - *targets[index] = scalarTextFromValue( - valueMember(*read.state(source), - nodegraph::InspectorAgentDetailFields[index])); - const nodegraph::NodeRef receiver = sourceFor(6); - if (receiver) - logical.receiverThreadIds = - graphStrings(valueMember(*read.state(receiver), "receiverThreadIds")); - - const auto status = [&](std::size_t token) { - const nodegraph::NodeRef &source = selector.contributors[token / 2]; - const auto sourceState = read.state(source); - const auto *child = - nodegraph::reportedAgentState(*sourceState, selector.childId); - const nodegraph::NodeStatusView childStatus = - child ? nodegraph::nodeStatusView(valueMember(*child, "status")) - : nodegraph::NodeStatusView{}; - if (token % 2 != 0) - return uiStatus(childStatus); - const auto turnState = read.state(read.parent(source)); - return uiStatus(nodegraph::inspectorAgentActivityStatus( - *sourceState, turnState.get(), childStatus, - selector.childIdVisible)); - }; - if (!selector.candidates[8].empty()) { - logical.status = status(*selector.candidates[8].rbegin()); - if (isActiveStatus(logical.status) && - !selector.candidates[9].empty()) { - const std::size_t nonRunning = *selector.candidates[9].rbegin(); - const UiStatus previous = status(nonRunning); - if (isTerminalTurnStatus(previous)) - logical.status = previous; - } - } - if (!selector.candidates[7].empty()) { - const std::size_t token = *selector.candidates[7].rbegin(); - const nodegraph::NodeRef &source = selector.contributors[token / 2]; - const auto sourceState = read.state(source); - if (token % 2 == 0) - logical.resultText = - scalarTextFromValue(valueMember(*sourceState, "resultText")); - else if (const auto *child = - nodegraph::reportedAgentState(*sourceState, - selector.childId)) - logical.resultText = - scalarTextFromValue(valueMember(*child, "message")); - } - const nodegraph::NodeRef &childThread = selector.exactChild; - if (childThread) { - updateAgentStatus(logical.status, - statusFromState(*read.state(childThread))); - if (logical.resultText.empty()) - if (const nodegraph::InspectorThreadIndex *childIndex = - read.inspectorIndex(childThread); - childIndex) - if (const nodegraph::NodeRef latest = - childIndex->latestAgentMessage()) - logical.resultText = scalarTextFromValue( - valueMember(*read.state(latest), "text")); - } - return InspectorRow{"agent:" + selector.key, std::move(logical)}; - }; - projectInspectorWindow(result, request, project); - return result; -} - -} // namespace - -using namespace middle; - -NodeGraphUiAdapter::NodeGraphUiAdapter( - const nodegraph::NodeGraph &graph) noexcept - : graph_(&graph) {} - -TokenUsageSnapshot NodeGraphUiAdapter::tokenUsage( - const nodegraph::NodeRef &selectedThread, - const nodegraph::NodeGraph::ReadAccess &read) const { - TokenUsageSnapshot result; - TokenCounts total; - total.fill(0); - std::array reported{}; - result.thread = tokenText(total, "Tokens"); - result.thread.details += "No retained usage reported; counters initialized to zero."; - const auto &threads = read.orderedNodes(nodegraph::NodeKind::Thread); - for (const auto &thread : threads) { - const auto snapshot = read.state(thread); - const auto *entry = valueMember(*snapshot, "tokenUsage"); - const auto *usage = entry ? entry->asObject() : nullptr; - const auto values = tokenCounts(usage ? valueMember(*usage, "total") : nullptr); - for (std::size_t i = 0; i < values.size(); ++i) { - if (!values[i]) continue; - ++reported[i]; - if (total[i] && *values[i] <= std::numeric_limits::max() - *total[i]) - *total[i] += *values[i]; - else - total[i].reset(); - } - if (thread != selectedThread || !usage) continue; - result.thread = tokenText(values, "Tokens"); - const auto last = tokenCounts(valueMember(*usage, "last")); - const auto window = signedIntegerFromValue(valueMember(*usage, "modelContextWindow")); - result.thread.details += "\nLatest reported usage\n" + tokenText(last, "").details + - "\nContext capacity: " + tokenNumber(window && *window > 0 ? window : std::nullopt, false); - if (window && *window > 0 && last[0]) { - const auto remaining = *window - std::clamp(*last[0], std::int64_t{0}, *window); - result.thread.summary += " | Left ≈" + tokenNumber(remaining, true); - result.thread.details += "\nEstimated remaining: " + tokenNumber(remaining, false) + - "\nBased on the latest report, not cumulative thread consumption."; - } - } - const auto account = read.find({nodegraph::NodeKind::Account, "account/usage/read"}); - const auto accountState = account ? read.state(account) : nullptr; - const auto *summaryValue = accountState ? valueMember(*accountState, "summary") : nullptr; - const auto *summary = summaryValue ? summaryValue->asObject() : nullptr; - auto lifetime = summary ? signedIntegerFromValue(valueMember(*summary, "lifetimeTokens")) - : std::nullopt; - if (lifetime && *lifetime < 0) - lifetime.reset(); - for (std::size_t i = 0; i < total.size(); ++i) - if (!reported[i]) total[i].reset(); - result.overall = tokenText(total, "Overall tokens"); - result.overall.details += "\nScope: available thread snapshots, including archived threads.\n"; - for (std::size_t i = 0; i < reported.size(); ++i) - result.overall.details += std::string(TokenFields[i]) + " coverage: " + - std::to_string(reported[i]) + "/" + std::to_string(threads.size()) + " threads\n"; - result.overall.details += "\nAccount lifetime tokens: " + tokenNumber(lifetime, false) + - "\nSeparate account scope; input/output breakdowns are not provided."; - if (accountState && accountState->status == nodegraph::NodeStatus::Pending) - result.overall.details += "\nRefreshing account usage…"; - if (accountState && accountState->status == nodegraph::NodeStatus::Failed) - result.overall.details += "\nAccount usage refresh unavailable; any account value is the last successful snapshot."; - - return result; -} - -std::optional NodeGraphUiAdapter::threadRow(const nodegraph::NodeRef& thread) const { - std::optional result; - auto read = graph_ && thread ? graph_->tryRead() : std::nullopt; - if (read && read->live(thread)) { - std::size_t pending = 0; - forEachPendingRequestThread(*read, [&](const nodegraph::NodeRef& owner) { - pending += owner == thread; - }); - result = projectThreadRow(*read, thread, pending); - } - return result; -} - -std::optional -NodeGraphUiAdapter::threads(const nodegraph::NodeRef &selectedThread, - std::uint64_t *graphRevision, - const ThreadBrowserOptions *browser, - const ThreadListRow *draft) const { - if (!graph_) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) - return std::nullopt; - if (graphRevision) - *graphRevision = read->revision(); - - const auto pendingCounts = pendingRequestCounts(*read); - - ThreadListSnapshot result; - if (read->live(selectedThread)) - result.selectedThreadId = selectedThread->id().canonical; - - const nodegraph::NodeRef connection = - read->find({nodegraph::NodeKind::Connection, "connection"}); - if (connection) { - const auto state = read->state(connection); - if (state) { - const std::string provider = - scalarTextFromValue(valueMember(*state, "providerState")); - const bool connected = state->status == nodegraph::NodeStatus::Connected; - result.providerReady = connected && provider == "ready"; - result.canControl = - result.providerReady && - scalarTextFromValue(valueMember(*state, "role")) == "controller"; - } - } - - const auto allThreads = read->orderedNodes(nodegraph::NodeKind::Thread); - std::unordered_set childThreads; - for (const nodegraph::NodeRef& node : allThreads) { - for (const nodegraph::RelationKind kind : {nodegraph::RelationKind::StructuralChildThread, - nodegraph::RelationKind::AgentChildThread, - nodegraph::RelationKind::ForkChildThread}) - for (std::size_t index = 0; index < read->relatedCount(node, kind); ++index) { - const nodegraph::NodeRef child = read->relatedAt(node, kind, index); - if (child->id().kind == nodegraph::NodeKind::Thread) { - childThreads.insert(child.get()); - } - } - } - - std::unordered_set emitted; - const auto buildRow = [&](const auto &self, - const nodegraph::NodeRef &node) -> ThreadListRow { - if (!node || !emitted.insert(node.get()).second) - return {}; - const auto pending = pendingCounts.find(node.get()); - std::optional projected = projectThreadRow( - *read, node, pending == pendingCounts.end() ? 0 : pending->second); - if (!projected) - return {}; - ThreadListRow row = std::move(*projected); - if (draft && row.presentationKey == draft->presentationKey) - draft = nullptr; - std::unordered_set localChildren; - for (const nodegraph::RelationKind kind : - {nodegraph::RelationKind::StructuralChildThread, - nodegraph::RelationKind::AgentChildThread, - nodegraph::RelationKind::ForkChildThread}) { - for (std::size_t index = 0; index < read->relatedCount(node, kind); - ++index) { - const nodegraph::NodeRef child = read->relatedAt(node, kind, index); - if (!child || child->id().kind != nodegraph::NodeKind::Thread || - !localChildren.insert(child.get()).second) - continue; - ThreadListRow projected = self(self, child); - if (!projected.id.empty()) { - row.uninspectedResult |= projected.uninspectedResult; - row.children.push_back(std::move(projected)); - } - } - } - row.indirectActive = !isActiveStatus(row.status) && std::ranges::any_of(row.children, [](const auto& child) { - return isActiveStatus(child.status) || child.indirectActive; - }); - return row; - }; - - std::vector roots; - const nodegraph::NodeRef runtime = - read->find({nodegraph::NodeKind::Runtime, "runtime"}); - if (runtime) - roots = read->related(runtime, nodegraph::RelationKind::RootThread); - roots.insert(roots.end(), allThreads.begin(), allThreads.end()); - for (const nodegraph::NodeRef& root : roots) { - if (!childThreads.contains(root.get())) { - ThreadListRow row = buildRow(buildRow, root); - if (!row.id.empty()) { - result.roots.push_back(std::move(row)); - } - } - } - // Malformed or partially paged ownership must not make a canonical thread - // disappear. Keep any still-unreachable thread as a root until its owner is - // available. - for (const nodegraph::NodeRef &thread : allThreads) { - if (emitted.contains(thread.get())) - continue; - ThreadListRow row = buildRow(buildRow, thread); - if (!row.id.empty()) - result.roots.push_back(std::move(row)); - } - // A graph-owned correlated row supersedes the renderer-local draft above. - // Any remaining UI draft participates in the same membership projection. - if (draft) - result.roots.push_back(*draft); - if (browser) { - const auto catalogState = [&](std::string_view method, - const nlohmann::json ¶meters) { - const auto node = read->find( - {nodegraph::NodeKind::Catalog, threadBrowserKey(method, parameters)}); - return node ? read->state(node) - : std::shared_ptr{}; - }; - const auto projects = - catalogState("project/list", nlohmann::json::object()); - const auto sections = - catalogState("threadSection/list", nlohmann::json::object()); - result.groupingAvailable = - projects && sections && - !boolFromValue(valueMember(*projects, "unsupported")) && - !boolFromValue(valueMember(*sections, "unsupported")); - if (connection) { - const auto state = read->state(connection); - if (const auto *settings = valueMember(*state, "settings")) - result.serverIdentity = jsonFromValue(*settings).dump(); + namespace { + using namespace middle; + using nodegraph::boolFromValue; + using nodegraph::exactStringFromValue; + using nodegraph::scalarTextFromValue; + using nodegraph::signedIntegerFromValue; + using nodegraph::valueMember; + + // Labels are a projection of the complete loaded catalog, never stored names. + // Compare paths only within colliding names, not across every project pair. + void labelThreadGroups(std::vector& groups) { + std::map> names; + for (auto& group : groups) + names[group.label].push_back(&group); + for (auto& [name, matches] : names) { + if (matches.size() < 2) + continue; + std::vector> paths(matches.size()); + qsizetype maxDepth = 1; + for (std::size_t i = 0; i < matches.size(); ++i) { + const auto roots = matches[i]->fields.find("roots"); + if (roots == matches[i]->fields.end() || !roots->is_array()) + continue; + for (const auto& root : *roots) { + const auto path = root.find("path"); + if (path == root.end() || !path->is_string()) + continue; + auto parts = QString::fromStdString(path->get()).replace('\\', '/').split('/', Qt::SkipEmptyParts); + if (parts.isEmpty()) + parts.push_back(QStringLiteral("/")); + maxDepth = std::max(maxDepth, parts.size()); + paths[i].push_back(std::move(parts)); + } + } + const auto suffix = [&](std::size_t index, qsizetype depth) { + QStringList roots; + for (const auto& parts : paths[index]) + roots.push_back(parts.mid(std::max(qsizetype{0}, parts.size() - depth)).join('/')); + return roots.join(QStringLiteral(", ")).toStdString(); + }; + for (std::size_t i = 0; i < matches.size(); ++i) { + qsizetype depth = 1; + for (; depth < maxDepth; ++depth) { + bool ambiguous = false; + for (std::size_t j = 0; j < matches.size(); ++j) + ambiguous |= i != j && suffix(i, depth) == suffix(j, depth) && suffix(i, maxDepth) != suffix(j, maxDepth); + if (!ambiguous) + break; + } + const auto context = suffix(i, depth); + if (!context.empty()) + matches[i]->label = name + " — " + context; + } + } + // A literal name can also equal a generated path label. Resolve collisions + // across the final catalog, extending ID suffixes only as far as necessary. + for (;;) { + std::map> labels; + for (auto& group : groups) + labels[group.label].push_back(&group); + bool ambiguous = false; + for (const auto& [label, matches] : labels) { + if (matches.size() < 2) + continue; + ambiguous = true; + for (auto* group : matches) { + std::size_t length = std::min(std::size_t{6}, group->id.size()); + for (; length < group->id.size(); ++length) { + const auto suffix = group->id.substr(group->id.size() - length); + if (std::ranges::none_of(matches, [&](const auto* other) { + return other != group && other->id.ends_with(suffix); + })) + break; + } + group->label = label + " · " + group->id.substr(group->id.size() - length); + } + } + if (!ambiguous) + break; + } + } + + UiStatus uiStatus(nodegraph::NodeStatusView status) { + return statusFromNode(status.semantic, status.unknownText); + } + + constexpr std::array TokenFields{ + "totalTokens", "inputTokens", "outputTokens", "cachedInputTokens", "cacheWriteInputTokens", "reasoningOutputTokens"}; + using TokenCounts = std::array, TokenFields.size()>; + + TokenCounts tokenCounts(const nodegraph::Value* value) { + TokenCounts counts; + const auto* object = value ? value->asObject() : nullptr; + for (std::size_t i = 0; i < counts.size(); ++i) { + counts[i] = object ? signedIntegerFromValue(valueMember(*object, TokenFields[i])) : std::nullopt; + if (counts[i] && *counts[i] < 0) + counts[i].reset(); + } + return counts; + } + + std::string tokenNumber(std::optional count, bool compact) { + if (!count) + return "—"; + if (compact && *count >= 1000) { + const bool millions = *count >= 1000000; + return (QLocale::c().toString(static_cast(*count) / (millions ? 1000000.0 : 1000.0), 'f', 1) + + (millions ? "M" : "k")) + .toStdString(); + } + return QLocale(QLocale::English, QLocale::UnitedStates).toString(static_cast(*count)).toStdString(); + } + + TokenUsageText tokenText(const TokenCounts& counts, std::string prefix) { + TokenUsageText text; + text.summary = std::move(prefix) + " " + tokenNumber(counts[0], true) + " | In " + tokenNumber(counts[1], true) + " | Out " + + tokenNumber(counts[2], true); + constexpr std::array labels{"Total", "Input", "Output", "Cached input", "Cache-write input", "Reasoning output"}; + for (std::size_t i = 0; i < counts.size(); ++i) + text.details += std::string(labels[i]) + ": " + tokenNumber(counts[i], false) + "\n"; + text.details += "Cached input and reasoning are breakdowns, not additional totals.\n"; + return text; + } + + UiStatus uiStatusFromValue(const nodegraph::Value* value) { + return uiStatus(nodegraph::nodeStatusView(value)); + } + + bool graphProviderHasMoreHistory(const nodegraph::NodeState& state) { + return boolFromValue(valueMember(state, "historyHasMore")); + } + + bool isConversationSnapshotMethod(std::string_view method) noexcept { + return method == "thread/read" || method == "thread/turns/list" || method == "thread/items/list"; + } + + bool hasPendingHistoryRequest(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& thread) { + for (const nodegraph::NodeRef& operation : read.related(thread, nodegraph::RelationKind::PendingOperation)) { + const auto state = read.state(operation); + if (state && state->status == nodegraph::NodeStatus::Pending && + isConversationSnapshotMethod(scalarTextFromValue(valueMember(*state, "method")))) + return true; + } + return false; + } + + bool fieldChanged(const nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& node, + std::string_view field, + std::uint64_t revision) { + return node && read.contains(node) && read.fieldChangedRevision(node, field) == revision; + } + + UiStatus agentUiStatus(const nodegraph::NodeState& state); + + struct PendingPromptPresentation { + bool awaitingConversation = false; + std::optional admittedAtMs; + nodegraph::NodeRef provisionalTurn; + }; + + PendingPromptPresentation pendingPromptPresentation(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& thread) { + PendingPromptPresentation result; + for (const nodegraph::NodeRef& prompt : read.related(thread, nodegraph::RelationKind::PendingPrompt)) { + if (prompt->id().kind != nodegraph::NodeKind::Item) + continue; + const auto state = read.state(prompt); + if (!state || scalarTextFromValue(valueMember(*state, "type")) != "localPrompt") + continue; + const std::string dispatch = scalarTextFromValue(valueMember(*state, "dispatchState")); + const bool awaiting = + dispatch == "queued" || dispatch == "dispatching" || dispatch == "inFlight" || dispatch == "awaitingMaterialization"; + if (!awaiting || read.hasIncomingRelation(prompt, nodegraph::RelationKind::PromptMaterialization)) + continue; + result.awaitingConversation = true; + const auto admittedAt = signedIntegerFromValue(valueMember(*state, "admittedAtMs")); + if (admittedAt && (!result.admittedAtMs || *admittedAt < *result.admittedAtMs)) + result.admittedAtMs = admittedAt; + if (!result.provisionalTurn && boolFromValue(valueMember(*state, "startsTurn")) && + (dispatch == "dispatching" || dispatch == "inFlight") && + (state->status == nodegraph::NodeStatus::Pending || state->status == nodegraph::NodeStatus::Running)) { + const nodegraph::NodeRef turn = read.parent(prompt); + if (turn && turn->id().kind == nodegraph::NodeKind::Turn && read.parent(turn) == thread) + result.provisionalTurn = turn; + } + } + return result; + } + + std::vector graphStrings(const nodegraph::Value* value) { + std::vector result; + const auto* array = value ? value->asArray() : nullptr; + if (!array) + return result; + result.reserve(array->size()); + for (const nodegraph::Value& entry : *array) + if (const auto* text = entry.asString(); text && !text->empty()) + result.push_back(*text); + return result; + } + + std::uint64_t graphOmittedTextBytes(const nodegraph::NodeState& state, std::string_view field) { + const nodegraph::Value* retention = valueMember(state, "textRetention"); + const auto* retentionObject = retention ? retention->asObject() : nullptr; + const nodegraph::Value* entry = retentionObject ? valueMember(*retentionObject, field) : nullptr; + const auto* entryObject = entry ? entry->asObject() : nullptr; + const nodegraph::Value* discarded = entryObject ? valueMember(*entryObject, "discardedBytes") : nullptr; + return nodegraph::unsignedIntegerFromValue(discarded).value_or(0); + } + + std::string withTruncationNotice(std::string value, std::uint64_t omitted, std::string_view subject, bool markdown) { + if (omitted == 0) + return value; + const std::string notice = + "Earlier " + std::string(subject) + " was truncated (" + std::to_string(omitted) + " bytes omitted)."; + return markdown ? "> " + notice + "\n\n" + value : '[' + notice + "]\n" + value; + } + + std::vector graphImagePaths(const nodegraph::NodeState& state) { + std::vector result; + const auto* content = valueMember(state, "content"); + const auto* array = content ? content->asArray() : nullptr; + if (!array) + return result; + for (const nodegraph::Value& entry : *array) { + const auto* object = entry.asObject(); + if (!object || scalarTextFromValue(valueMember(*object, "type")) != "localImage") + continue; + if (std::string path = scalarTextFromValue(valueMember(*object, "path")); !path.empty()) + result.push_back(std::move(path)); + } + return result; + } + + std::vector graphLocalPromptImagePaths(const nodegraph::NodeState& state) { + std::vector result; + const nodegraph::Value* attachments = valueMember(state, "attachments"); + const auto* array = attachments ? attachments->asArray() : nullptr; + if (!array) + return result; + for (const nodegraph::Value& entry : *array) { + const auto* object = entry.asObject(); + if (!object || !scalarTextFromValue(valueMember(*object, "mimeType")).starts_with("image/")) + continue; + if (std::string path = scalarTextFromValue(valueMember(*object, "path")); !path.empty()) + result.emplace_back(std::move(path)); + } + return result; + } + + std::string graphJoinedText(const nodegraph::Value* value) { + const auto* array = value ? value->asArray() : nullptr; + if (!array) + return scalarTextFromValue(value); + std::string result; + for (const nodegraph::Value& entry : *array) { + std::string text = scalarTextFromValue(&entry); + if (text.empty()) + if (const auto* object = entry.asObject()) + text = scalarTextFromValue(valueMember(*object, "text")); + if (text.empty()) + continue; + if (!result.empty()) + result += ", "; + result += text; + } + return result; + } + + std::pair graphDiffCounts(std::string_view diff) { + int additions = 0; + int deletions = 0; + for (std::size_t offset = 0; offset <= diff.size();) { + const std::size_t end = diff.find('\n', offset); + const std::string_view line = diff.substr(offset, end == std::string_view::npos ? diff.size() - offset : end - offset); + if (!line.starts_with("+++ ") && !line.starts_with("--- ")) { + if (line.starts_with('+')) + ++additions; + else if (line.starts_with('-')) + ++deletions; + } + if (end == std::string_view::npos) + break; + offset = end + 1; + } + return {additions, deletions}; + } + + constexpr std::size_t MaximumGraphActivityDetailBytes = 4000; + + class GraphDetailBuilder final { + public: + void append(std::string_view text) { + if (text.empty() || truncated_) + return; + std::size_t count = std::min(text.size(), MaximumGraphActivityDetailBytes - value_.size()); + truncated_ = count < text.size(); + while (count > 0 && count < text.size() && (static_cast(text[count]) & 0xc0U) == 0x80U) + --count; + value_.append(text.substr(0, count)); + } + + void indent(int depth) { + for (int index = 0; index < depth; ++index) + append(" "); + } + + [[nodiscard]] bool truncated() const noexcept { + return truncated_; + } + + [[nodiscard]] std::string finish() && { + if (truncated_) + value_ += "\n\n[Activity details truncated]"; + return std::move(value_); + } + + private: + std::string value_; + bool truncated_ = false; + }; + + // Use shortest round-trip numbers, with the browser's decimal/exponent range. + // Integer Value alternatives retain their exact protocol representation. + std::string graphDetailNumber(double value) { + if (value == 0) + return "0"; + char buffer[64]; + const auto converted = std::to_chars(std::begin(buffer), std::end(buffer), value, std::chars_format::scientific); + std::string result(buffer, converted.ptr); + const auto exponentAt = result.find('e'); + if (exponentAt == std::string::npos) + return result; + int exponent = 0; + const char* digits = result.data() + exponentAt + 1; + if (*digits == '+') + ++digits; + std::from_chars(digits, result.data() + result.size(), exponent); + result.resize(exponentAt); + if (exponent < -6 || exponent >= 21) + return result + "e" + (exponent >= 0 ? "+" : "") + std::to_string(exponent); + const std::size_t sign = result.front() == '-' ? 1 : 0; + const auto point = result.find('.'); + if (point != std::string::npos) + result.erase(point, 1); + if (exponent < 0) + result.insert(sign, "0." + std::string(-exponent - 1, '0')); + else if (const auto position = sign + static_cast(exponent) + 1; position < result.size()) + result.insert(position, "."); + else + result.append(position - result.size(), '0'); + return result; + } + + void appendGraphDetail(GraphDetailBuilder& builder, const nodegraph::Value& value, int depth) { + if (builder.truncated()) + return; + if (value.isNull()) { + builder.append("none"); + return; + } + if (const auto* boolean = value.asBool()) { + builder.append(*boolean ? "true" : "false"); + return; + } + if (const auto* number = value.asInt64()) { + builder.append(std::to_string(*number)); + return; + } + if (const auto* number = value.asUInt64()) { + builder.append(std::to_string(*number)); + return; + } + if (const auto* number = value.asDouble()) { + builder.append(graphDetailNumber(*number)); + return; + } + if (const auto* text = value.asString()) { + builder.append(*text); + return; + } + if (depth >= 4) { + builder.append("nested detail omitted"); + return; + } + if (const auto* array = value.asArray()) { + if (array->empty()) { + builder.append("none"); + return; + } + for (const nodegraph::Value& entry : *array) { + builder.append("\n"); + builder.indent(depth + 1); + builder.append("- "); + appendGraphDetail(builder, entry, depth + 1); + if (builder.truncated()) + return; + } + return; + } + const auto* object = value.asObject(); + if (!object || object->empty()) { + builder.append("none"); + return; + } + for (const auto& [key, entry] : *object) { + builder.append("\n"); + builder.indent(depth + 1); + builder.append(key); + builder.append(": "); + appendGraphDetail(builder, entry, depth + 1); + if (builder.truncated()) + return; + } + } + + std::string graphDisplayDetail(const nodegraph::NodeState& state) { + GraphDetailBuilder builder; + for (const auto& [key, value] : state.fields) { + // Graph identity/retention metadata is not part of the activity payload. + if (key == "protocolId" || key == "protocolThreadId" || key == "protocolTurnId" || key == "textRetention") + continue; + builder.append(key); + builder.append(": "); + appendGraphDetail(builder, value, 0); + if (builder.truncated()) + break; + builder.append("\n"); + } + return std::move(builder).finish(); + } + + CardKind graphCardKind(const nodegraph::NodeState& state) { + const std::string type = scalarTextFromValue(valueMember(state, "type")); + if (type == "localPrompt") + return CardKind::LocalPrompt; + if (type == "userMessage") + return CardKind::UserMessage; + if (type == "agentMessage") + return CardKind::AgentMessage; + if (type == "commandExecution") + return CardKind::CommandExecution; + if (type == "collabAgentToolCall" || type == "subAgentActivity") + return CardKind::AgentActivity; + if (type == "reasoning") + return CardKind::Reasoning; + if (type == "fileChange") + return CardKind::FileChanges; + if (type == "imageGeneration" || type == "imageView") + return CardKind::ImageGeneration; + if (type == "plan" && !nodegraph::messageText(state).empty()) { + return CardKind::Plan; + } + return CardKind::GenericActivity; + } + + VisibleCardData graphCardData(const nodegraph::NodeRef& item, + std::string threadId, + std::string turnId, + const nodegraph::NodeState& state, + std::string_view threadCwd = {}) { + const std::string itemId = item ? nodegraph::protocolCanonicalId(state, item) : std::string{}; + const std::string type = scalarTextFromValue(valueMember(state, "type")); + const CardKind kind = graphCardKind(state); + VisibleCardData result{AuthoritativeItemKey{threadId, turnId, itemId}, + kind, + std::move(threadId), + std::move(turnId), + itemId, + GenericActivityData{}, + {}, + {}}; + + result.status = statusFromState(state); + result.timing = protocolTimes(state.fields, "ItemLifecycle"); + if (result.kind == CardKind::AgentActivity) + result.status = agentUiStatus(state); + else if (result.kind == CardKind::ImageGeneration && type == "imageView") + result.status = nodegraph::NodeStatus::Completed; + else if (result.kind == CardKind::UserMessage || result.kind == CardKind::AgentMessage || result.kind == CardKind::LocalPrompt) + result.status = {}; + switch (result.kind) { + case CardKind::UserMessage: { + result.payload = UserMessageData{nodegraph::messageText(state), graphImagePaths(state)}; + break; + } + case CardKind::AgentMessage: + result.payload = AgentMessageData{ + withTruncationNotice(nodegraph::messageText(state), graphOmittedTextBytes(state, "text"), "Codex response", true), + scalarTextFromValue(valueMember(state, "phase")), + scalarTextFromValue(valueMember(state, "delivery")) == "async" && valueMember(state, "questions") + ? PendingRequestPolicy::asyncQuestionRequest(jsonFromValue(*valueMember(state, "questions"))) + : nlohmann::json(nullptr)}; + break; + case CardKind::CommandExecution: { + std::string outputField = "aggregatedOutput"; + std::string output = scalarTextFromValue(valueMember(state, "aggregatedOutput")); + if (output.empty()) { + outputField = "output"; + output = scalarTextFromValue(valueMember(state, "output")); + } + output = withTruncationNotice(std::move(output), graphOmittedTextBytes(state, outputField), "command output", false); + if (!terminalOutputHasVisibleText(output)) + output.clear(); + const auto exit = signedIntegerFromValue(valueMember(state, "exitCode")); + auto duration = signedIntegerFromValue(valueMember(state, "durationMs")); + if (!duration) + duration = signedIntegerFromValue(valueMember(state, "duration_ms")); + result.payload = CommandExecutionData{scalarTextFromValue(valueMember(state, "command")), + std::move(output), + scalarTextFromValue(valueMember(state, "cwd")), + exit ? std::optional(static_cast(*exit)) : std::nullopt, + duration}; + break; + } + case CardKind::AgentActivity: + result.payload = AgentActivityData{scalarTextFromValue(valueMember(state, "tool")), + scalarTextFromValue(valueMember(state, "kind")), + scalarTextFromValue(valueMember(state, "prompt")), + scalarTextFromValue(valueMember(state, "resultText")), + graphStrings(valueMember(state, "receiverThreadIds")), + scalarTextFromValue(valueMember(state, "model")), + scalarTextFromValue(valueMember(state, "reasoningEffort")), + scalarTextFromValue(valueMember(state, "agentThreadId")), + scalarTextFromValue(valueMember(state, "agentPath")), + scalarTextFromValue(valueMember(state, "senderThreadId"))}; + break; + case CardKind::Reasoning: + result.payload = ReasoningData{withTruncationNotice( + graphJoinedText(valueMember(state, "summary")), graphOmittedTextBytes(state, "summary"), "reasoning", true)}; + break; + case CardKind::FileChanges: { + std::string cwd = scalarTextFromValue(valueMember(state, "cwd")); + if (cwd.empty()) + cwd = threadCwd; + FileChangesData projected{{}, std::move(cwd)}; + const auto* changes = valueMember(state, "changes"); + const auto* array = changes ? changes->asArray() : nullptr; + if (array) { + projected.changes.reserve(array->size()); + for (const nodegraph::Value& value : *array) { + const auto* change = value.asObject(); + if (!change) + continue; + FileChangeData entry{scalarTextFromValue(valueMember(*change, "path")), + scalarTextFromValue(valueMember(*change, "kind")), + std::nullopt, + std::nullopt}; + const auto additions = signedIntegerFromValue(valueMember(*change, "additions")); + const auto deletions = signedIntegerFromValue(valueMember(*change, "deletions")); + if (additions && deletions && *additions >= 0 && *deletions >= 0) { + entry.additions = static_cast(std::min(*additions, std::numeric_limits::max())); + entry.deletions = static_cast(std::min(*deletions, std::numeric_limits::max())); + } else if (const nodegraph::Value* diffValue = valueMember(*change, "diff"); + diffValue && diffValue->asString() && !diffValue->asString()->empty()) { + const std::string& diff = *diffValue->asString(); + const auto [additions, deletions] = graphDiffCounts(diff); + entry.additions = additions; + entry.deletions = deletions; + } + projected.changes.push_back(std::move(entry)); + } + } + result.payload = std::move(projected); + break; + } + case CardKind::ImageGeneration: { + std::string path = scalarTextFromValue(valueMember(state, "path")); + if (path.empty()) + path = scalarTextFromValue(valueMember(state, "savedPath")); + if (path.empty()) + path = scalarTextFromValue(valueMember(state, "saved_path")); + std::string prompt = scalarTextFromValue(valueMember(state, "revisedPrompt")); + if (prompt.empty()) + prompt = scalarTextFromValue(valueMember(state, "revised_prompt")); + result.payload = ImageGenerationData{std::move(path), std::move(prompt)}; + break; + } + case CardKind::Plan: + result.payload = PlanData{ + {}, + {}, + withTruncationNotice(nodegraph::messageText(state), graphOmittedTextBytes(state, "text"), "plan text", true)}; + break; + case CardKind::GenericActivity: + result.payload = GenericActivityData{type, graphDisplayDetail(state)}; + break; + case CardKind::LocalPrompt: { + const std::string dispatch = scalarTextFromValue(valueMember(state, "dispatchState")); + PromptState promptState = PromptState::Queued; + if (dispatch == "dispatching" || dispatch == "inFlight") + promptState = PromptState::InFlight; + else if (dispatch == "awaitingMaterialization") + promptState = PromptState::Accepted; + else if (dispatch == "failed" || dispatch == "uncertain") + promptState = PromptState::Failed; + const std::int64_t rawId = signedIntegerFromValue(valueMember(state, "submissionId")).value_or(0); + const std::uint64_t submissionId = rawId < 0 ? 0 : static_cast(rawId); + result.key = LocalPromptKey{submissionId}; + result.itemId.clear(); + result.payload = LocalPromptData{submissionId, + scalarTextFromValue(valueMember(state, "text")), + promptState, + scalarTextFromValue(valueMember(state, "error")), + graphLocalPromptImagePaths(state), + signedIntegerFromValue(valueMember(state, "admittedAtMs")), + boolFromValue(valueMember(state, "requiresExplicitRecovery"))}; + break; + } + } + result.target = item; + return result; + } + + struct MaterializedPrompt { + nodegraph::NodeRef prompt; + std::optional submissionId; + }; + + std::optional materializedPrompt(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& item) { + if (!item) + return std::nullopt; + std::optional fallback; + for (const nodegraph::NodeRef& prompt : read.related(item, nodegraph::RelationKind::PromptMaterialization)) { + if (prompt->id().kind != nodegraph::NodeKind::Item) + continue; + const auto state = read.state(prompt); + if (!state || scalarTextFromValue(valueMember(*state, "type")) != "localPrompt") + continue; + const auto rawSubmission = signedIntegerFromValue(valueMember(*state, "submissionId")); + MaterializedPrompt candidate{prompt, + rawSubmission && *rawSubmission >= 0 + ? std::optional{static_cast(*rawSubmission)} + : std::nullopt}; + if (candidate.submissionId) + return candidate; + if (!fallback) + fallback = std::move(candidate); + } + return fallback; + } + + std::optional conversationCardKey(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& item, + std::string_view threadId, + std::string_view turnId, + bool hiddenPrompt = false) { + if (!read.live(item) || item->id().kind != nodegraph::NodeKind::Item) + return std::nullopt; + const auto state = read.state(item); + if (!state) + return std::nullopt; + const std::string type = scalarTextFromValue(valueMember(*state, "type")); + if (type == "localPrompt") { + if (hiddenPrompt) + return std::nullopt; + const std::int64_t rawId = signedIntegerFromValue(valueMember(*state, "submissionId")).value_or(0); + return LocalPromptKey{rawId < 0 ? 0 : static_cast(rawId)}; + } + if (graphCardKind(*state) == CardKind::UserMessage) { + if (const auto materialized = materializedPrompt(read, item); materialized && materialized->submissionId) + return LocalPromptKey{*materialized->submissionId}; + const auto submission = signedIntegerFromValue(valueMember(*state, "localSubmissionId")); + if (submission && *submission >= 0) + return LocalPromptKey{static_cast(*submission)}; + } + return AuthoritativeItemKey{std::string(threadId), std::string(turnId), nodegraph::protocolCanonicalId(*state, item)}; + } + + bool isHiddenMaterializedPrompt(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& prompt) { + if (!read.live(prompt)) + return false; + const auto state = read.state(prompt); + return state && scalarTextFromValue(valueMember(*state, "type")) == "localPrompt" && + read.hasIncomingRelation(prompt, nodegraph::RelationKind::PromptMaterialization); + } + + nodegraph::NodeRef conversationTurnRoot(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& turn) { + const auto roots = read.related(turn, nodegraph::RelationKind::TurnRootItem); + return roots.empty() ? nodegraph::NodeRef{} : roots.front(); + } + + bool conversationItemsComplete(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& turn) { + const auto state = turn ? read.state(turn) : nullptr; + return state && valueMember(*state, "itemsHistoryHasMore") && !boolFromValue(valueMember(*state, "itemsHistoryHasMore")); + } + + nodegraph::NodeRef conversationOpeningItem(const nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& turn) { + const auto root = conversationTurnRoot(read, turn); + return root ? root : conversationItemsComplete(read, turn) ? read.childAt(turn, 0) : nodegraph::NodeRef{}; + } + + nodegraph::NodeRef conversationActiveTurn(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& thread) { + for (const nodegraph::NodeRef& turn : read.related(thread, nodegraph::RelationKind::ActiveTurn)) + if (turn->id().kind == nodegraph::NodeKind::Turn && read.parent(turn) == thread) + return turn; + return pendingPromptPresentation(read, thread).provisionalTurn; + } + + VisibleCardData conversationCardData(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& item, + std::string threadId, + std::string turnId, + const nodegraph::NodeState& state, + std::string_view threadCwd = {}) { + const std::optional key = conversationCardKey(read, item, threadId, turnId); + VisibleCardData result = graphCardData(item, std::move(threadId), std::move(turnId), state, threadCwd); + if (auto* message = std::get_if(&result.payload); message && !message->questionRequest.is_null()) { + const auto& questions = message->questionRequest["questions"]; + message->answers.resize(questions.size()); + std::map keys; + for (std::size_t i = 0; i < questions.size(); ++i) { + keys.emplace(nodegraph::questionReplyKey(result.itemId, i), i); + } + bool sending = false; + for (const auto& source : read.questionReplies(item)) { + const auto state = read.state(source); + const auto dispatch = + isHiddenMaterializedPrompt(read, source) ? "" : scalarTextFromValue(valueMember(*state, "dispatchState")); + const bool accepted = + scalarTextFromValue(valueMember(*state, "type")) == "userMessage" || dispatch == "awaitingMaterialization"; + for (const auto& reply : nodegraph::questionReplies(nodegraph::messageText(*state))) { + const auto found = keys.find(reply.questionItemId); + if (found != keys.end() && reply.question == questions[found->second]["question"].get() && + !reply.answer.empty()) { + if (accepted) { + message->answers[found->second] = reply.answer; + } + sending |= dispatch == "queued" || dispatch == "dispatching" || dispatch == "inFlight"; + } + } + } + const std::size_t count = std::ranges::count_if(message->answers, [](const auto& answer) { + return !answer.empty(); + }); + message->questionStatus = sending ? "Sending…" + : count == questions.size() ? "✓ Answer sent" + : count ? std::to_string(count) + "/" + std::to_string(questions.size()) + " answers sent" + : ""; + if (count) { + std::vector replies; + for (std::size_t i = 0; i < questions.size(); ++i) { + replies.push_back({{}, questions[i]["question"], message->answers[i]}); + } + message->text = nodegraph::questionReplyMarkdown(replies); + } + } + if (key) + result.key = *key; + const auto turn = read.parent(item); + result.turnOpening = turn && result.kind != CardKind::LocalPrompt && conversationItemsComplete(read, turn) && + conversationOpeningItem(read, turn) == item; + if (turn && read.isRelated(turn, nodegraph::RelationKind::TurnRootItem, item)) { + auto timing = protocolTimes(read.state(turn)->fields, "Turn"); + for (auto& time : timing) + time.field = "turn/" + time.field; + result.timing.insert(result.timing.end(), timing.begin(), timing.end()); + } + return result; + } + + void updateAgentStatus(UiStatus& current, UiStatus candidate) { + if (candidate.empty() || (isTerminalTurnStatus(current) && isActiveStatus(candidate))) + return; + current = std::move(candidate); + } + + UiStatus agentUiStatus(const nodegraph::NodeState& state) { + return uiStatus(nodegraph::agentActivityStatus(state)); + } + + std::string threadRowPresentationKey(const nodegraph::NodeRef& thread, const nodegraph::NodeState& state) { + const std::string correlation = exactStringFromValue(valueMember(state, "creationCorrelation")); + return correlation.empty() ? "thread:" + std::to_string(thread->incarnation()) + : ui::threadPresentationKey(thread->id().canonical, correlation); + } + + std::string settingString(const nodegraph::Value* value, std::string_view fallback = {}) { + const std::string result = exactStringFromValue(value); + return result.empty() ? std::string(fallback) : result; + } + + std::string settingSandbox(const nodegraph::Value* value) { + std::string type = settingString(value); + if (const auto* object = value ? value->asObject() : nullptr) + type = settingString(valueMember(*object, "type")); + if (type == "readOnly") + return "read-only"; + if (type == "workspaceWrite") + return "workspace-write"; + if (type == "dangerFullAccess") + return "danger-full-access"; + if (type == "externalSandbox") + return "external"; + if (type == "read-only" || type == "workspace-write" || type == "danger-full-access" || type == "external") + return type; + return std::string(DefaultTurnSetting); + } + + std::vector settingModels(nodegraph::NodeGraph::ReadAccess& read) { + std::vector result; + const nodegraph::NodeRef catalog = read.find({nodegraph::NodeKind::Catalog, "model"}); + if (!catalog) + return result; + for (const nodegraph::NodeRef& entry : read.children(catalog)) { + const auto state = read.state(entry); + const nodegraph::Value* hidden = valueMember(*state, "hidden"); + if (hidden && hidden->asBool() && *hidden->asBool()) + continue; + std::string id = settingString(valueMember(*state, "model")); + if (id.empty()) + id = settingString(valueMember(*state, "id")); + if (id.empty()) + continue; + TurnSettingModel model; + model.choice.value = id; + model.choice.label = settingString(valueMember(*state, "displayName")); + if (model.choice.label.empty()) + model.choice.label = id; + model.choice.description = settingString(valueMember(*state, "description")); + model.isDefault = boolFromValue(valueMember(*state, "isDefault")); + model.defaultReasoningEffort = settingString(valueMember(*state, "defaultReasoningEffort")); + model.defaultServiceTier = settingString(valueMember(*state, "defaultServiceTier")); + std::unordered_set effortIds; + if (const nodegraph::Value* supported = valueMember(*state, "supportedReasoningEfforts"); + supported && supported->asArray()) { + for (const nodegraph::Value& option : *supported->asArray()) { + const auto* fields = option.asObject(); + const std::string effort = fields ? settingString(valueMember(*fields, "reasoningEffort")) : std::string{}; + if (!effort.empty() && effortIds.insert(effort).second) + model.reasoningEfforts.push_back(effort); + } + } + std::unordered_set tierIds; + if (const nodegraph::Value* tiers = valueMember(*state, "serviceTiers"); tiers && tiers->asArray()) { + for (const nodegraph::Value& tier : *tiers->asArray()) { + const auto* fields = tier.asObject(); + const std::string tierId = fields ? settingString(valueMember(*fields, "id")) : std::string{}; + if (tierId.empty() || !tierIds.insert(tierId).second) + continue; + std::string label = settingString(valueMember(*fields, "name")); + model.serviceTiers.push_back( + {tierId, label.empty() ? tierId : std::move(label), settingString(valueMember(*fields, "description"))}); + } + } + if (const nodegraph::Value* tiers = valueMember(*state, "additionalSpeedTiers"); tiers && tiers->asArray()) { + for (const nodegraph::Value& tier : *tiers->asArray()) { + const std::string value = settingString(&tier); + if (!value.empty() && tierIds.insert(value).second) + model.serviceTiers.push_back({value, {}, {}}); + } + } + if (const nodegraph::Value* personality = valueMember(*state, "supportsPersonality"); personality && personality->asBool()) + model.supportsPersonality = *personality->asBool(); + result.push_back(std::move(model)); + } + return result; + } + + std::vector settingPermissionProfiles(nodegraph::NodeGraph::ReadAccess& read) { + std::vector result; + const nodegraph::NodeRef catalog = read.find({nodegraph::NodeKind::Catalog, "permissionProfile"}); + if (!catalog) + return result; + for (const nodegraph::NodeRef& entry : read.children(catalog)) { + const auto state = read.state(entry); + const nodegraph::Value* allowed = valueMember(*state, "allowed"); + if (allowed && allowed->asBool() && !*allowed->asBool()) + continue; + const std::string id = settingString(valueMember(*state, "id")); + if (!id.empty()) + result.push_back({id, {}, settingString(valueMember(*state, "description"))}); + } + return result; + } + + bool canControlRequests(nodegraph::NodeGraph::ReadAccess& read) { + const nodegraph::NodeRef connection = read.find({nodegraph::NodeKind::Connection, "connection"}); + if (!connection) + return false; + const auto state = read.state(connection); + return state && state->status == nodegraph::NodeStatus::Connected && + scalarTextFromValue(valueMember(*state, "providerState")) == "ready" && + scalarTextFromValue(valueMember(*state, "role")) == "controller"; + } + + nodegraph::NodeRef interactionThread(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& interaction) { + const std::size_t targetCount = read.relatedCount(interaction, nodegraph::RelationKind::InteractionTarget); + for (std::size_t index = 0; index < targetCount; ++index) + for (nodegraph::NodeRef target = read.relatedAt(interaction, nodegraph::RelationKind::InteractionTarget, index); target; + target = read.parent(target)) + if (target->id().kind == nodegraph::NodeKind::Thread) + return target; + return {}; + } + + std::string requestThreadId(const nodegraph::NodeState& state, const nodegraph::NodeRef& exactThread) { + if (exactThread) + return exactThread->id().canonical; + const nodegraph::Value* payload = valueMember(state, "payload"); + const auto* object = payload ? payload->asObject() : nullptr; + return object ? scalarTextFromValue(valueMember(*object, "threadId")) : std::string{}; + } + + PendingRequestDescriptor + projectPendingRequest(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& interaction, bool canControl) { + const auto state = read.state(interaction); + PendingRequestDescriptor request; + request.target = interaction; + request.method = scalarTextFromValue(valueMember(*state, "method")); + request.kind = PendingRequestPolicy::kindForMethod(request.method); + request.error = scalarTextFromValue(valueMember(*state, "error")); + request.responseRevision = nodegraph::unsignedIntegerFromValue(valueMember(*state, "responseRevision")).value_or(0); + + const nodegraph::Value* payload = valueMember(*state, "payload"); + if (payload) + request.raw = jsonFromValue(*payload); + + const nodegraph::NodeRef thread = interactionThread(read, interaction); + request.threadId = requestThreadId(*state, thread); + if (thread) { + const auto threadState = read.state(thread); + request.threadTitle = scalarTextFromValue(valueMember(*threadState, "name")); + if (request.threadTitle.empty()) + request.threadTitle = scalarTextFromValue(valueMember(*threadState, "title")); + } + + const nodegraph::Value* retained = valueMember(*state, "retainedResponsePayload"); + if (const auto* object = retained ? retained->asObject() : nullptr) { + PendingRequestSubmission submission; + submission.choice = scalarTextFromValue(valueMember(*object, "choice")); + if (const nodegraph::Value* input = valueMember(*object, "input")) + submission.input = jsonFromValue(*input); + if (const nodegraph::Value* metadata = valueMember(*object, "metadata")) + submission.metadata = jsonFromValue(*metadata); + if (!submission.choice.empty()) + request.retainedSubmission = std::move(submission); + } + + const bool recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); + request.availability = recoveryOnly ? PendingRequestAvailability::RecoveryOnly + : canControl ? PendingRequestAvailability::Actionable + : PendingRequestAvailability::Unavailable; + return request; + } + + template + std::optional numericSuffix(std::string_view key, std::string_view prefix) { + if (!key.starts_with(prefix)) + return std::nullopt; + Integer result = 0; + const char* first = key.data() + prefix.size(); + const char* last = key.data() + key.size(); + const auto parsed = std::from_chars(first, last, result); + return parsed.ec == std::errc{} && parsed.ptr == last ? std::optional{result} : std::nullopt; + } + + std::optional + requestPosition(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& runtime, std::string_view key) { + const auto incarnation = numericSuffix(key, "request:"); + if (!incarnation) + return std::nullopt; + std::size_t first = 0; + std::size_t last = read.relatedCount(runtime, nodegraph::RelationKind::PendingInteraction); + while (first < last) { + const std::size_t middle = first + (last - first) / 2; + const nodegraph::NodeRef candidate = read.relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, middle); + if (candidate->incarnation() < *incarnation) + first = middle + 1; + else + last = middle; + } + const nodegraph::NodeRef found = read.relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, first); + return found && found->incarnation() == *incarnation ? std::optional{first} : std::nullopt; + } + + bool requestTargetsThread(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& interaction, + const nodegraph::NodeState& state, + std::string_view selectedThreadId) { + return requestThreadId(state, interactionThread(read, interaction)) == selectedThreadId; + } + + template + void forEachPendingRequestThread(nodegraph::NodeGraph::ReadAccess& read, Visitor&& visit) { + const nodegraph::NodeRef runtime = read.find({nodegraph::NodeKind::Runtime, "runtime"}); + if (!runtime) + return; + const std::size_t count = read.relatedCount(runtime, nodegraph::RelationKind::PendingInteraction); + for (std::size_t index = 0; index < count; ++index) { + const nodegraph::NodeRef interaction = read.relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, index); + if (const nodegraph::NodeRef thread = interactionThread(read, interaction)) + visit(thread); + } + } + + std::unordered_map pendingRequestCounts(nodegraph::NodeGraph::ReadAccess& read) { + std::unordered_map result; + forEachPendingRequestThread(read, [&](const nodegraph::NodeRef& thread) { + ++result[thread.get()]; + }); + return result; + } + + int pendingRequestRank(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& interaction, + const nodegraph::NodeState& state, + bool canControl, + std::string_view selectedThreadId) { + const nodegraph::Value* retained = valueMember(state, "retainedResponsePayload"); + const auto* object = retained ? retained->asObject() : nullptr; + const bool hasRetained = object && !scalarTextFromValue(valueMember(*object, "choice")).empty(); + const PendingRequestAvailability availability = boolFromValue(valueMember(state, "recoveryOnly")) + ? PendingRequestAvailability::RecoveryOnly + : canControl ? PendingRequestAvailability::Actionable + : PendingRequestAvailability::Unavailable; + return PendingRequestPolicy::attentionRank( + availability, hasRetained, requestTargetsThread(read, interaction, state, selectedThreadId)); + } + + void boundInspectorWindow(InspectorPageSnapshot& page, std::size_t count) { + page.first = std::min(page.first, page.total); + if (page.total == 0 || count == 0) + return; + count = std::min(count, page.total); + if (page.first == page.total) + page.first = page.total - count; + if (!page.anchorIndex) + return; + if (*page.anchorIndex < page.first) + page.first = *page.anchorIndex; + else if (*page.anchorIndex - page.first >= count) + page.first = *page.anchorIndex - count + 1; + } + + template + void projectInspectorWindow(InspectorPageSnapshot& page, const InspectorRowRequest& request, Project&& project) { + page.first = request.first; + const std::size_t count = std::min(request.count, MaximumInspectorRows); + boundInspectorWindow(page, count); + const std::size_t end = page.first + std::min(count, page.total - page.first); + page.rows.reserve(end - page.first); + for (std::size_t row = page.first; row < end; ++row) + page.rows.push_back(project(row)); + if (page.focusedIndex && (*page.focusedIndex < page.first || *page.focusedIndex >= end)) + page.focused = project(*page.focusedIndex); + } + + InspectorPageSnapshot + projectPendingRequests(nodegraph::NodeGraph::ReadAccess& read, bool canControl, const InspectorRowRequest& window) { + InspectorPageSnapshot result; + const nodegraph::NodeRef runtime = read.find({nodegraph::NodeKind::Runtime, "runtime"}); + if (!runtime) { + result.emptyMessage = "No pending requests."; + return result; + } + result.orderRevision = read.pendingInteractionOrderRevision(); + result.total = read.relatedCount(runtime, nodegraph::RelationKind::PendingInteraction); + result.anchorIndex = requestPosition(read, runtime, window.anchorKey); + result.focusedIndex = requestPosition(read, runtime, window.focusedKey); + projectInspectorWindow(result, window, [&](std::size_t index) { + const nodegraph::NodeRef interaction = read.relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, index); + return InspectorRow{"request:" + std::to_string(interaction->incarnation()), + projectPendingRequest(read, interaction, canControl)}; + }); + if (result.total == 0) + result.emptyMessage = "No pending requests."; + return result; + } + + PendingRequestsSummary projectPendingRequestSummary(nodegraph::NodeGraph::ReadAccess& read, + bool canControl, + std::string_view selectedThreadId, + std::span localTargets) { + PendingRequestsSummary result; + const nodegraph::NodeRef runtime = read.find({nodegraph::NodeKind::Runtime, "runtime"}); + if (!runtime) + return result; + std::unordered_set local; + local.reserve(localTargets.size()); + for (const nodegraph::NodeRef& target : localTargets) + if (target) + local.insert(target.get()); + int bestRank = std::numeric_limits::max(); + nodegraph::NodeRef best; + std::size_t bestInsertion = 0; + for (std::size_t index = 0; index < read.relatedCount(runtime, nodegraph::RelationKind::PendingInteraction); ++index) { + const nodegraph::NodeRef interaction = read.relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, index); + ++result.total; + if (local.contains(interaction.get())) { + result.candidates.push_back(projectPendingRequest(read, interaction, canControl)); + continue; + } + const auto state = read.state(interaction); + const int rank = pendingRequestRank(read, interaction, *state, canControl, selectedThreadId); + if (rank < bestRank) { + bestRank = rank; + best = interaction; + bestInsertion = result.candidates.size(); + } + } + if (best) + result.candidates.insert(result.candidates.begin() + static_cast(bestInsertion), + projectPendingRequest(read, best, canControl)); + return result; + } + + void appendUniqueBounded(std::vector& values, std::string value, std::size_t maximum) { + if (value.empty() || std::ranges::find(values, value) != values.end()) + return; + if (values.size() == maximum) + values.erase(values.begin()); + values.emplace_back(std::move(value)); + } + + std::string_view nodeKindName(nodegraph::NodeKind kind) { + using nodegraph::NodeKind; + switch (kind) { + case NodeKind::Runtime: + return "Runtime"; + case NodeKind::Connection: + return "Connection"; + case NodeKind::Thread: + return "Thread"; + case NodeKind::Turn: + return "Turn"; + case NodeKind::Item: + return "Item"; + case NodeKind::Interaction: + return "Interaction"; + case NodeKind::Operation: + return "Operation"; + case NodeKind::Catalog: + return "Catalog"; + case NodeKind::CatalogEntry: + return "CatalogEntry"; + case NodeKind::Account: + return "Account"; + case NodeKind::Configuration: + return "Configuration"; + case NodeKind::PermissionProfile: + return "PermissionProfile"; + case NodeKind::Skill: + return "Skill"; + case NodeKind::Hook: + return "Hook"; + case NodeKind::Plugin: + return "Plugin"; + case NodeKind::App: + return "App"; + case NodeKind::McpServer: + return "McpServer"; + case NodeKind::Project: + return "Project"; + case NodeKind::ThreadSection: + return "ThreadSection"; + case NodeKind::Process: + return "Process"; + case NodeKind::RealtimeSession: + return "RealtimeSession"; + case NodeKind::FilesystemWatch: + return "FilesystemWatch"; + case NodeKind::ExternalAgentImport: + return "ExternalAgentImport"; + case NodeKind::FuzzyFileSearchSession: + return "FuzzyFileSearchSession"; + case NodeKind::LoginAttempt: + return "LoginAttempt"; + case NodeKind::Notice: + return "Notice"; + case NodeKind::UnknownProtocol: + return "UnknownProtocol"; + } + return "Unknown"; + } + + bool sensitiveStateField(std::string_view key) { + std::string normalized; + normalized.reserve(key.size()); + for (const unsigned char character : key) + if (std::isalnum(character)) + normalized.push_back(static_cast(std::tolower(character))); + return normalized == "payload" || normalized == "requestpayload" || normalized == "responsepayload" || + normalized == "retainedresponsepayload" || normalized == "raw" || normalized == "private" || normalized == "bytes" || + normalized == "command" || normalized == "prompt" || normalized == "input" || normalized == "output" || + normalized == "delta" || normalized == "error" || normalized == "message" || normalized == "token" || + normalized.ends_with("token") || normalized.find("password") != std::string::npos || + normalized.find("secret") != std::string::npos || normalized.find("credential") != std::string::npos || + normalized.find("authorization") != std::string::npos || normalized.find("cookie") != std::string::npos || + normalized.find("apikey") != std::string::npos || normalized.find("privatekey") != std::string::npos; + } + + nlohmann::json safeStateValue(const nodegraph::Value& value, int depth = 0) { + if (depth > 8) + return ""; + if (value.isNull()) + return nullptr; + if (const auto* boolean = value.asBool()) + return *boolean; + if (const auto* number = value.asInt64()) + return *number; + if (const auto* number = value.asUInt64()) + return *number; + if (const auto* number = value.asDouble()) + return *number; + if (const auto* string = value.asString()) { + if (string->size() > 1024) + return string->substr(0, 1024) + "..."; + return *string; + } + if (const auto* array = value.asArray()) { + nlohmann::json result = nlohmann::json::array(); + const std::size_t retained = std::min(array->size(), 32); + for (std::size_t index = 0; index < retained; ++index) + result.push_back(safeStateValue(array->at(index), depth + 1)); + if (array->size() > retained) + result.push_back(""); + return result; + } + nlohmann::json result = nlohmann::json::object(); + const auto* object = value.asObject(); + std::size_t retained = 0; + for (const auto& [key, entry] : *object) { + if (retained++ == 64) { + result[""] = "omitted"; + break; + } + result[key] = sensitiveStateField(key) ? nlohmann::json("") : safeStateValue(entry, depth + 1); + } + return result; + } + + nlohmann::json safeStateObject(const nodegraph::Value::Object& fields) { + return safeStateValue(nodegraph::Value(fields)); + } + + std::string sectionComponent(std::string_view prefix, std::string_view threadId, std::string_view suffix) { + std::string result(prefix); + result += std::to_string(threadId.size()); + result.push_back(':'); + result.append(threadId); + result += std::to_string(suffix.size()); + result.push_back(':'); + result.append(suffix); + return result; + } + + std::optional + projectThreadRow(nodegraph::NodeGraph::ReadAccess& read, const nodegraph::NodeRef& thread, std::size_t pending) { + if (!read.live(thread) || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + const auto state = read.state(thread); + if (!state) + return std::nullopt; + const auto timestamp = [&state](std::string_view field) { + return signedIntegerFromValue(valueMember(*state, field)); + }; + ThreadListRow row; + row.id = thread->id().canonical; + row.presentationKey = threadRowPresentationKey(thread, *state); + row.target = thread; + row.timing = protocolTimes(state->fields, "Thread"); + row.title = scalarTextFromValue(valueMember(*state, "localNameOverlay")); + if (row.title.empty()) + row.title = scalarTextFromValue(valueMember(*state, "name")); + if (row.title.empty()) + row.title = scalarTextFromValue(valueMember(*state, "preview")); + if (row.title.empty()) + row.title = row.id.substr(0, std::min(12, row.id.size())); + row.cwd = scalarTextFromValue(valueMember(*state, "cwd")); + row.workspaceChangeUnavailable = nodegraph::threadWorkspaceChangeUnavailable(read, thread); + row.status = statusFromState(*state); + row.uninspectedResult = boolFromValue(valueMember(*state, "uninspectedResult")); + row.createdAt = timestamp("createdAt"); + row.updatedAt = timestamp("updatedAt"); + row.recencyAt = timestamp("recencyAt"); + if (const auto local = timestamp("localPromptActivityAt"); local && (!row.recencyAt || *local > *row.recencyAt)) + row.recencyAt = local; + for (const std::string_view field : {std::string_view("lastActivityAt"), + std::string_view("updatedAt"), + std::string_view("recencyAt"), + std::string_view("localActivityAt"), + std::string_view("localPromptActivityAt")}) { + const std::optional candidate = timestamp(field); + if (candidate && (!row.lastActivityAt || *candidate > *row.lastActivityAt)) + row.lastActivityAt = candidate; + } + row.pending = pending; + const PendingPromptPresentation prompt = pendingPromptPresentation(read, thread); + row.awaitingPromptConversation = prompt.awaitingConversation; + row.pendingPromptAdmittedAtMs = prompt.admittedAtMs; + row.archived = boolFromValue(valueMember(*state, "archived")); + if (read.relatedCount(thread, nodegraph::RelationKind::ProjectMembership)) + row.projectId = read.relatedAt(thread, nodegraph::RelationKind::ProjectMembership, 0)->id().canonical; + if (read.relatedCount(thread, nodegraph::RelationKind::SectionMembership)) + row.sectionId = read.relatedAt(thread, nodegraph::RelationKind::SectionMembership, 0)->id().canonical; + return row; + } + + InspectorPageSnapshot projectPlan(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& thread, + const nodegraph::InspectorThreadIndex* index, + const InspectorRowRequest& request) { + InspectorPageSnapshot result; + if (!thread || !index || !index->planSource) { + result.emptyMessage = thread ? "No plan for this thread." : "No selected thread."; + return result; + } + const bool legacy = index->planSource->id().kind == nodegraph::NodeKind::Item; + const std::string sourceId = std::to_string(index->planSource->incarnation()); + const std::string explanationKey = "plan:" + sourceId + ":explanation"; + const std::string stepPrefix = "plan:step:" + sourceId + ':'; + const auto keyFor = [&](std::size_t row) { + if (legacy) + return "plan:" + sourceId + ":legacy"; + if (index->planHasExplanation && row == 0) + return explanationKey; + return stepPrefix + std::to_string(row - (index->planHasExplanation ? 1 : 0)); + }; + result.total = index->planRowCount; + result.orderRevision = index->planOrderRevision; + if (result.total == 0 && legacy) + result.emptyMessage = "Plan is being prepared."; + const auto find = [&](const std::string& key) -> std::optional { + if (key.empty()) + return std::nullopt; + if (legacy || key == explanationKey) + return result.total != 0 && key == keyFor(0) ? std::optional{0} : std::nullopt; + const auto sourceIndex = numericSuffix(key, stepPrefix); + const std::size_t offset = index->planHasExplanation ? 1 : 0; + if (!sourceIndex || *sourceIndex >= result.total - offset) + return std::nullopt; + return *sourceIndex + offset; + }; + result.anchorIndex = find(request.anchorKey); + result.focusedIndex = find(request.focusedKey); + const auto source = read.state(index->planSource); + const nodegraph::InspectorPlanView plan = nodegraph::inspectorPlanView(*source); + const UiStatus turnStatus = statusFromState(*read.state(legacy ? read.parent(index->planSource) : index->planSource)); + const UiStatus threadStatus = statusFromState(*read.state(thread)); + const auto project = [&](std::size_t row) -> InspectorRow { + const std::string key = keyFor(row); + if (!legacy && index->planHasExplanation && row == 0) { + return InspectorRow{key, InspectorMarkdownRow{scalarTextFromValue(plan.explanation), "Plan explanation", {}}}; + } + if (legacy) + return InspectorRow{key, InspectorMarkdownRow{scalarTextFromValue(valueMember(*source, "text")), "Plan", {}}}; + const auto* steps = plan.steps->asArray(); + const std::size_t sourceIndex = row - (index->planHasExplanation ? 1 : 0); + const auto* step = steps->at(sourceIndex).asObject(); + if (!step) + return InspectorRow{key, PlanStepData{}}; + std::string stepText = scalarTextFromValue(valueMember(*step, "step")); + if (stepText.empty()) + stepText = scalarTextFromValue(valueMember(*step, "text")); + return InspectorRow{ + key, + PlanStepData{std::move(stepText), + effectivePlanStepStatus(uiStatusFromValue(valueMember(*step, "status")), turnStatus, threadStatus)}}; + }; + projectInspectorWindow(result, request, project); + return result; + } + + InspectorPageSnapshot projectAgents(nodegraph::NodeGraph::ReadAccess& read, + const nodegraph::NodeRef& thread, + const nodegraph::InspectorThreadIndex* index, + const InspectorRowRequest& request) { + InspectorPageSnapshot result; + result.validRetainedKeys.emplace(); + if (!thread || !index || index->agents.empty()) { + result.emptyMessage = thread ? "No agent activity for this thread." : "No selected thread."; + return result; + } + result.total = index->agents.size(); + result.orderRevision = index->agentOrderRevision; + const auto logicalKey = [](std::string_view key) { + constexpr std::string_view prefix = "agent:"; + return key.starts_with(prefix) ? key.substr(prefix.size()) : key; + }; + const auto find = [&](const std::string& key) -> std::optional { + if (key.empty()) + return std::nullopt; + const auto found = index->agentPositions.find(std::string(logicalKey(key))); + return found == index->agentPositions.end() ? std::nullopt : std::optional{found->second}; + }; + const std::size_t retainedCount = std::min(request.retainedKeys.size(), MaximumInspectorRows); + result.validRetainedKeys->reserve(retainedCount); + for (std::size_t index = 0; index < retainedCount; ++index) { + const std::string& key = request.retainedKeys[index]; + if (find(key) && std::ranges::find(*result.validRetainedKeys, key) == result.validRetainedKeys->end()) + result.validRetainedKeys->push_back(key); + } + result.anchorIndex = find(request.anchorKey); + result.focusedIndex = find(request.focusedKey); + const auto project = [&](std::size_t row) -> InspectorRow { + const nodegraph::InspectorAgentSelector& selector = index->agents[row]; + InspectorAgentRow logical; + if (selector.childIdVisible) + logical.childThreadId = selector.childId; + const auto sourceFor = [&](std::size_t field) { + const auto& candidates = selector.candidates[field]; + return candidates.empty() ? nodegraph::NodeRef{} : selector.contributors[*candidates.rbegin() / 2]; + }; + const std::array targets{ + &logical.agentPath, &logical.tool, &logical.model, &logical.reasoningEffort, &logical.prompt, &logical.senderThreadId}; + for (std::size_t index = 0; index < nodegraph::InspectorAgentDetailFields.size(); ++index) + if (const nodegraph::NodeRef source = sourceFor(index)) + *targets[index] = + scalarTextFromValue(valueMember(*read.state(source), nodegraph::InspectorAgentDetailFields[index])); + const nodegraph::NodeRef receiver = sourceFor(6); + if (receiver) + logical.receiverThreadIds = graphStrings(valueMember(*read.state(receiver), "receiverThreadIds")); + + const auto status = [&](std::size_t token) { + const nodegraph::NodeRef& source = selector.contributors[token / 2]; + const auto sourceState = read.state(source); + const auto* child = nodegraph::reportedAgentState(*sourceState, selector.childId); + const nodegraph::NodeStatusView childStatus = + child ? nodegraph::nodeStatusView(valueMember(*child, "status")) : nodegraph::NodeStatusView{}; + if (token % 2 != 0) + return uiStatus(childStatus); + const auto turnState = read.state(read.parent(source)); + return uiStatus( + nodegraph::inspectorAgentActivityStatus(*sourceState, turnState.get(), childStatus, selector.childIdVisible)); + }; + if (!selector.candidates[8].empty()) { + logical.status = status(*selector.candidates[8].rbegin()); + if (isActiveStatus(logical.status) && !selector.candidates[9].empty()) { + const std::size_t nonRunning = *selector.candidates[9].rbegin(); + const UiStatus previous = status(nonRunning); + if (isTerminalTurnStatus(previous)) + logical.status = previous; + } + } + if (!selector.candidates[7].empty()) { + const std::size_t token = *selector.candidates[7].rbegin(); + const nodegraph::NodeRef& source = selector.contributors[token / 2]; + const auto sourceState = read.state(source); + if (token % 2 == 0) + logical.resultText = scalarTextFromValue(valueMember(*sourceState, "resultText")); + else if (const auto* child = nodegraph::reportedAgentState(*sourceState, selector.childId)) + logical.resultText = scalarTextFromValue(valueMember(*child, "message")); + } + const nodegraph::NodeRef& childThread = selector.exactChild; + if (childThread) { + updateAgentStatus(logical.status, statusFromState(*read.state(childThread))); + if (logical.resultText.empty()) + if (const nodegraph::InspectorThreadIndex* childIndex = read.inspectorIndex(childThread); childIndex) + if (const nodegraph::NodeRef latest = childIndex->latestAgentMessage()) + logical.resultText = scalarTextFromValue(valueMember(*read.state(latest), "text")); + } + return InspectorRow{"agent:" + selector.key, std::move(logical)}; + }; + projectInspectorWindow(result, request, project); + return result; + } + + } // namespace + + using namespace middle; + + NodeGraphUiAdapter::NodeGraphUiAdapter(const nodegraph::NodeGraph& graph) noexcept + : graph_(&graph) { } - const auto groups = [&](nodegraph::NodeKind kind, - std::vector &destination) { - for (const auto &node : read->orderedNodes(kind)) { - const auto state = read->state(node); - const auto name = QString::fromStdString( - exactStringFromValue(valueMember(*state, "name"))) - .simplified() - .toStdString(); - destination.push_back({node->id().canonical, - name.empty() ? "Unnamed" : name, node, - jsonFromValue(nodegraph::Value(state->fields))}); - } - labelThreadGroups(destination); - }; - groups(nodegraph::NodeKind::Project, result.projects); - groups(nodegraph::NodeKind::ThreadSection, result.sections); - const auto groupName = [](const auto &groups, const std::string &id, - std::string fallback) { - const auto found = std::ranges::find(groups, id, &ThreadGroup::id); - return found == groups.end() ? (id.empty() ? fallback : id) - : found->label; - }; - nlohmann::json filter = nlohmann::json::object(); - if (browser->archived != 2) - filter["archived"] = browser->archived == 1; - if (!browser->title.empty()) - filter["searchTerm"] = browser->title; - const auto pageRow = [&](std::string method, nlohmann::json parameters) { - ThreadListRow row; - row.kind = ThreadRowKind::Page; - row.presentationKey = threadBrowserKey(method, parameters); - row.query = {{"method", method}, {"parameters", parameters}}; - const auto state = catalogState(method, parameters); - const bool loaded = state && boolFromValue(valueMember(*state, "loaded")); - row.pendingPage = state && boolFromValue(valueMember(*state, "pending")); - const std::string error = - state ? exactStringFromValue(valueMember(*state, "error")) : ""; - const bool more = state && boolFromValue(valueMember(*state, "hasMore")); - const bool unsupported = - state && boolFromValue(valueMember(*state, "unsupported")); - row.title = row.pendingPage ? "Loading…" - : !error.empty() ? "Retry loading…" - : !loaded ? "Load threads…" - : more ? "Load more…" - : ""; - if (unsupported) { - row.title = "Not supported by this server"; - row.query = nullptr; - } - row.details = error; - row.order = std::numeric_limits::max(); - return row; - }; - const auto appendPages = [&](std::vector &rows, - std::string method, - nlohmann::json parameters) { - const int count = - method == "thread/list" && browser->archived == 2 ? 2 : 1; - for (int page = 0; page < count; ++page) { - if (count == 2) - parameters["archived"] = page != 0; - auto row = pageRow(method, parameters); - if (row.title.empty()) - continue; - if (count == 2) - row.title += page ? " (archived)" : " (active)"; - rows.push_back(std::move(row)); - } - }; - const bool grouped = browser->grouping != ThreadGrouping::Ungrouped && - result.groupingAvailable; - // Flatten once, retaining the original parent identity. Membership decides - // placement; graph ancestry remains unchanged and accessible by navigation. - std::vector flat; - flat.reserve(allThreads.size()); - const auto flatten = [&](const auto &self, std::vector rows, - nodegraph::NodeRef parent) -> void { - for (auto &row : rows) { - auto children = std::move(row.children); - row.children.clear(); - row.parentThread = parent; - const auto target = row.target; - if (!row.target || ((browser->archived == 2 || - row.archived == (browser->archived == 1)) && - (browser->title.empty() || - QString::fromStdString(row.title).contains( - QString::fromStdString(browser->title), Qt::CaseInsensitive)))) - flat.push_back(std::move(row)); - self(self, std::move(children), target); - } - }; - flatten(flatten, std::move(result.roots), {}); - result.roots.clear(); - const auto familyKey = [&](const ThreadListRow &row) { - if (!grouped) - return std::string{}; - return browser->grouping == ThreadGrouping::Sections - ? row.sectionId - : nlohmann::json::array({row.projectId, row.sectionId}).dump(); - }; - std::unordered_map positions; - positions.reserve(flat.size()); - for (std::size_t i = 0; i < flat.size(); ++i) - positions.emplace(flat[i].target.get(), i); - std::vector> descendants(flat.size()); - std::vector roots; - for (std::size_t i = 0; i < flat.size(); ++i) { - const auto parent = positions.find(flat[i].parentThread.get()); - if (flat[i].parentThread && parent != positions.end() && - familyKey(flat[i]) == familyKey(flat[parent->second])) - descendants[parent->second].push_back(i); - else - roots.push_back(i); + + TokenUsageSnapshot NodeGraphUiAdapter::tokenUsage(const nodegraph::NodeRef& selectedThread, + const nodegraph::NodeGraph::ReadAccess& read) const { + TokenUsageSnapshot result; + TokenCounts total; + total.fill(0); + std::array reported{}; + result.thread = tokenText(total, "Tokens"); + result.thread.details += "No retained usage reported; counters initialized to zero."; + const auto& threads = read.orderedNodes(nodegraph::NodeKind::Thread); + for (const auto& thread : threads) { + const auto snapshot = read.state(thread); + const auto* entry = valueMember(*snapshot, "tokenUsage"); + const auto* usage = entry ? entry->asObject() : nullptr; + const auto values = tokenCounts(usage ? valueMember(*usage, "total") : nullptr); + for (std::size_t i = 0; i < values.size(); ++i) { + if (!values[i]) + continue; + ++reported[i]; + if (total[i] && *values[i] <= std::numeric_limits::max() - *total[i]) + *total[i] += *values[i]; + else + total[i].reset(); + } + if (thread != selectedThread || !usage) + continue; + result.thread = tokenText(values, "Tokens"); + const auto last = tokenCounts(valueMember(*usage, "last")); + const auto window = signedIntegerFromValue(valueMember(*usage, "modelContextWindow")); + result.thread.details += "\nLatest reported usage\n" + tokenText(last, "").details + + "\nContext capacity: " + tokenNumber(window && *window > 0 ? window : std::nullopt, false); + if (window && *window > 0 && last[0]) { + const auto remaining = *window - std::clamp(*last[0], std::int64_t{0}, *window); + result.thread.summary += " | Left ≈" + tokenNumber(remaining, true); + result.thread.details += "\nEstimated remaining: " + tokenNumber(remaining, false) + + "\nBased on the latest report, not cumulative thread consumption."; + } + } + const auto account = read.find({nodegraph::NodeKind::Account, "account/usage/read"}); + const auto accountState = account ? read.state(account) : nullptr; + const auto* summaryValue = accountState ? valueMember(*accountState, "summary") : nullptr; + const auto* summary = summaryValue ? summaryValue->asObject() : nullptr; + const auto lifetime = signedIntegerFromValue(summary ? valueMember(*summary, "lifetimeTokens") : nullptr).value_or(-1); + for (std::size_t i = 0; i < total.size(); ++i) + if (!reported[i]) + total[i].reset(); + result.overall = tokenText(total, "Overall tokens"); + result.overall.details += "\nScope: available thread snapshots, including archived threads.\n"; + for (std::size_t i = 0; i < reported.size(); ++i) + result.overall.details += std::string(TokenFields[i]) + " coverage: " + std::to_string(reported[i]) + "/" + + std::to_string(threads.size()) + " threads\n"; + result.overall.details += + "\nAccount lifetime tokens: " + tokenNumber(lifetime >= 0 ? std::optional{lifetime} : std::nullopt, false) + + "\nSeparate account scope; input/output breakdowns are not provided."; + if (accountState && accountState->status == nodegraph::NodeStatus::Pending) + result.overall.details += "\nRefreshing account usage…"; + if (accountState && accountState->status == nodegraph::NodeStatus::Failed) + result.overall.details += "\nAccount usage refresh unavailable; any account value is the last successful snapshot."; + + return result; } - const auto family = [&](const auto &self, - std::size_t index) -> ThreadListRow { - ThreadListRow row = std::move(flat[index]); - for (auto child : descendants[index]) - row.children.push_back(self(self, child)); - return row; - }; - std::map grouping; - const auto ensureGroup = [&](const std::string &id, - bool project) -> ThreadListRow & { - auto [entry, inserted] = grouping.try_emplace(id); - auto &row = entry->second; - if (inserted) { - row.id = id; - row.kind = project ? ThreadRowKind::Project : ThreadRowKind::Section; - row.presentationKey = - std::string(project ? "project:" : "section:") + id; - row.projectId = project ? id : std::string{}; - row.sectionId = project ? std::string{} : id; - row.title = groupName(project ? result.projects : result.sections, id, - project ? "No project" : "Unsectioned"); - auto parameters = filter; - parameters[project ? "projectId" : "sectionId"] = - id.empty() ? nlohmann::json(nullptr) : nlohmann::json(id); - if (!project && browser->manualSections && !id.empty()) { - parameters["sortKey"] = "section_position"; - parameters["sortDirection"] = "asc"; - } - row.query = {{"method", "thread/list"}, {"parameters", parameters}}; - const auto &source = project ? result.projects : result.sections; - const auto found = std::ranges::find(source, id, &ThreadGroup::id); - if (found != source.end()) { - row.target = found->target; - const auto &fields = found->fields; - if (fields.contains("recencyAt") && - fields["recencyAt"].is_number_integer()) - row.recencyAt = fields["recencyAt"].get(); - row.order = fields.value("position", std::int64_t{0}); - for (const auto &root : - fields.value("roots", nlohmann::json::array())) { - if (!row.details.empty()) - row.details += '\n'; - row.details += root.value("path", std::string{}); - } - if (!project) { - row.details = "Shared section across projects"; - } - } - } - return row; - }; - if (grouped) { - const bool project = browser->grouping == ThreadGrouping::Projects; - for (const auto &group : project ? result.projects : result.sections) - ensureGroup(group.id, project); - ensureGroup({}, project); - for (const auto index : roots) { - auto row = family(family, index); - auto &parent = - ensureGroup(project ? row.projectId : row.sectionId, project); - if (row.recencyAt > parent.recencyAt) - parent.recencyAt = row.recencyAt; - parent.children.push_back(std::move(row)); - } - for (auto &[id, group] : grouping) { - if (project) { - std::map subsections; - const auto ensureSection = - [&](const std::string §ionId) -> ThreadListRow & { - auto [entry, inserted] = subsections.try_emplace(sectionId); - auto §ion = entry->second; - if (inserted) { - section.kind = ThreadRowKind::Section; - section.id = sectionId; - section.sectionId = sectionId; - section.projectId = id; - section.presentationKey = - "project-section:" + - nlohmann::json::array({id, sectionId}).dump(); - section.title = - groupName(result.sections, sectionId, "Unsectioned"); - const auto found = std::ranges::find(result.sections, sectionId, - &ThreadGroup::id); - if (found != result.sections.end()) { - section.target = found->target; - section.details = "Shared section across projects"; - } - auto parameters = group.query.at("parameters"); - parameters["sectionId"] = sectionId; - if (browser->manualSections) { - parameters["sortKey"] = "section_position"; - parameters["sortDirection"] = "asc"; - } - section.query = {{"method", "thread/list"}, - {"parameters", parameters}}; - } - return section; - }; - if (id.empty()) - for (const auto §ion : result.sections) - if (!read->hasIncomingRelation( - section.target, - nodegraph::RelationKind::SectionMembership)) - ensureSection(section.id); - std::vector children; - for (auto &row : group.children) { - if (row.sectionId.empty()) - children.push_back(std::move(row)); - else - ensureSection(row.sectionId).children.push_back(std::move(row)); - } - for (auto &[sectionId, section] : subsections) - children.push_back(std::move(section)); - group.children = std::move(children); - } - result.roots.push_back(std::move(group)); - } - } else { - for (const auto index : roots) - result.roots.push_back(family(family, index)); + + std::optional NodeGraphUiAdapter::threadRow(const nodegraph::NodeRef& thread) const { + std::optional result; + auto read = graph_ && thread ? graph_->tryRead() : std::nullopt; + if (read && read->live(thread)) { + std::size_t pending = 0; + forEachPendingRequestThread(*read, [&](const nodegraph::NodeRef& owner) { + pending += owner == thread; + }); + result = projectThreadRow(*read, thread, pending); + } + return result; } - const auto finalizeRows = [&](const auto& self, std::vector& rows) -> UiStatus { - UiStatus aggregate{nodegraph::NodeStatus::NotLoaded}; - for (auto& row : rows) { - const UiStatus descendants = self(self, row.children); - if (row.kind == ThreadRowKind::Project || row.kind == ThreadRowKind::Section) { - row.status = descendants; - row.indirectActive = isActiveStatus(descendants); - row.uninspectedResult = std::ranges::any_of(row.children, [](const auto& child) { - return child.uninspectedResult; - }); + + std::optional NodeGraphUiAdapter::threads(const nodegraph::NodeRef& selectedThread, + std::uint64_t* graphRevision, + const ThreadBrowserOptions* browser, + const ThreadListRow* draft) const { + if (!graph_) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) + return std::nullopt; + if (graphRevision) + *graphRevision = read->revision(); + + const auto pendingCounts = pendingRequestCounts(*read); + + ThreadListSnapshot result; + if (read->live(selectedThread)) + result.selectedThreadId = selectedThread->id().canonical; + + const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"}); + if (connection) { + const auto state = read->state(connection); + if (state) { + const std::string provider = scalarTextFromValue(valueMember(*state, "providerState")); + const bool connected = state->status == nodegraph::NodeStatus::Connected; + result.providerReady = connected && provider == "ready"; + result.canControl = result.providerReady && scalarTextFromValue(valueMember(*state, "role")) == "controller"; } - // Fold descendants without changing an individual thread's own status. - for (const auto& status : {row.status, descendants}) { - if (isActiveStatus(status) || row.indirectActive) { - aggregate = nodegraph::NodeStatus::Running; - } else if (!isActiveStatus(aggregate) && !statusTone(status).empty()) { - aggregate = nodegraph::NodeStatus::Completed; + } + + const auto allThreads = read->orderedNodes(nodegraph::NodeKind::Thread); + std::unordered_set childThreads; + for (const nodegraph::NodeRef& node : allThreads) { + for (const nodegraph::RelationKind kind : {nodegraph::RelationKind::StructuralChildThread, + nodegraph::RelationKind::AgentChildThread, + nodegraph::RelationKind::ForkChildThread}) + for (std::size_t index = 0; index < read->relatedCount(node, kind); ++index) { + const nodegraph::NodeRef child = read->relatedAt(node, kind, index); + if (child->id().kind == nodegraph::NodeKind::Thread) { + childThreads.insert(child.get()); + } } + } + + std::unordered_set emitted; + const auto buildRow = [&](const auto& self, const nodegraph::NodeRef& node) -> ThreadListRow { + if (!node || !emitted.insert(node.get()).second) + return {}; + const auto pending = pendingCounts.find(node.get()); + std::optional projected = projectThreadRow(*read, node, pending == pendingCounts.end() ? 0 : pending->second); + if (!projected) + return {}; + ThreadListRow row = std::move(*projected); + if (draft && row.presentationKey == draft->presentationKey) + draft = nullptr; + std::unordered_set localChildren; + for (const nodegraph::RelationKind kind : {nodegraph::RelationKind::StructuralChildThread, + nodegraph::RelationKind::AgentChildThread, + nodegraph::RelationKind::ForkChildThread}) { + for (std::size_t index = 0; index < read->relatedCount(node, kind); ++index) { + const nodegraph::NodeRef child = read->relatedAt(node, kind, index); + if (!child || child->id().kind != nodegraph::NodeKind::Thread || !localChildren.insert(child.get()).second) + continue; + ThreadListRow projected = self(self, child); + if (!projected.id.empty()) { + row.uninspectedResult |= projected.uninspectedResult; + row.children.push_back(std::move(projected)); + } + } + } + row.indirectActive = !isActiveStatus(row.status) && std::ranges::any_of(row.children, [](const auto& child) { + return isActiveStatus(child.status) || child.indirectActive; + }); + return row; + }; + + std::vector roots; + const nodegraph::NodeRef runtime = read->find({nodegraph::NodeKind::Runtime, "runtime"}); + if (runtime) + roots = read->related(runtime, nodegraph::RelationKind::RootThread); + roots.insert(roots.end(), allThreads.begin(), allThreads.end()); + for (const nodegraph::NodeRef& root : roots) { + if (!childThreads.contains(root.get())) { + ThreadListRow row = buildRow(buildRow, root); + if (!row.id.empty()) { + result.roots.push_back(std::move(row)); + } + } + } + // Malformed or partially paged ownership must not make a canonical thread + // disappear. Keep any still-unreachable thread as a root until its owner is + // available. + for (const nodegraph::NodeRef& thread : allThreads) { + if (emitted.contains(thread.get())) + continue; + ThreadListRow row = buildRow(buildRow, thread); + if (!row.id.empty()) + result.roots.push_back(std::move(row)); + } + // A graph-owned correlated row supersedes the renderer-local draft above. + // Any remaining UI draft participates in the same membership projection. + if (draft) + result.roots.push_back(*draft); + if (browser) { + const auto catalogState = [&](std::string_view method, const nlohmann::json& parameters) { + const auto node = read->find({nodegraph::NodeKind::Catalog, threadBrowserKey(method, parameters)}); + return node ? read->state(node) : std::shared_ptr{}; + }; + const auto projects = catalogState("project/list", nlohmann::json::object()); + const auto sections = catalogState("threadSection/list", nlohmann::json::object()); + result.groupingAvailable = projects && sections && !boolFromValue(valueMember(*projects, "unsupported")) && + !boolFromValue(valueMember(*sections, "unsupported")); + if (connection) { + const auto state = read->state(connection); + if (const auto* settings = valueMember(*state, "settings")) + result.serverIdentity = jsonFromValue(*settings).dump(); + } + const auto groups = [&](nodegraph::NodeKind kind, std::vector& destination) { + for (const auto& node : read->orderedNodes(kind)) { + const auto state = read->state(node); + const auto name = QString::fromStdString(exactStringFromValue(valueMember(*state, "name"))).simplified().toStdString(); + destination.push_back( + {node->id().canonical, name.empty() ? "Unnamed" : name, node, jsonFromValue(nodegraph::Value(state->fields))}); + } + labelThreadGroups(destination); + }; + groups(nodegraph::NodeKind::Project, result.projects); + groups(nodegraph::NodeKind::ThreadSection, result.sections); + const auto groupName = [](const auto& groups, const std::string& id, std::string fallback) { + const auto found = std::ranges::find(groups, id, &ThreadGroup::id); + return found == groups.end() ? (id.empty() ? fallback : id) : found->label; + }; + nlohmann::json filter = nlohmann::json::object(); + if (browser->archived != 2) + filter["archived"] = browser->archived == 1; + if (!browser->title.empty()) + filter["searchTerm"] = browser->title; + const auto pageRow = [&](std::string method, nlohmann::json parameters) { + ThreadListRow row; + row.kind = ThreadRowKind::Page; + row.presentationKey = threadBrowserKey(method, parameters); + row.query = {{"method", method}, {"parameters", parameters}}; + const auto state = catalogState(method, parameters); + const bool loaded = state && boolFromValue(valueMember(*state, "loaded")); + row.pendingPage = state && boolFromValue(valueMember(*state, "pending")); + const std::string error = state ? exactStringFromValue(valueMember(*state, "error")) : ""; + const bool more = state && boolFromValue(valueMember(*state, "hasMore")); + const bool unsupported = state && boolFromValue(valueMember(*state, "unsupported")); + row.title = row.pendingPage ? "Loading…" + : !error.empty() ? "Retry loading…" + : !loaded ? "Load threads…" + : more ? "Load more…" + : ""; + if (unsupported) { + row.title = "Not supported by this server"; + row.query = nullptr; + } + row.details = error; + row.order = std::numeric_limits::max(); + return row; + }; + const auto appendPages = [&](std::vector& rows, std::string method, nlohmann::json parameters) { + const int count = method == "thread/list" && browser->archived == 2 ? 2 : 1; + for (int page = 0; page < count; ++page) { + if (count == 2) + parameters["archived"] = page != 0; + auto row = pageRow(method, parameters); + if (row.title.empty()) + continue; + if (count == 2) + row.title += page ? " (archived)" : " (active)"; + rows.push_back(std::move(row)); + } + }; + const bool grouped = browser->grouping != ThreadGrouping::Ungrouped && result.groupingAvailable; + // Flatten once, retaining the original parent identity. Membership decides + // placement; graph ancestry remains unchanged and accessible by navigation. + std::vector flat; + flat.reserve(allThreads.size()); + const auto flatten = [&](const auto& self, std::vector rows, nodegraph::NodeRef parent) -> void { + for (auto& row : rows) { + auto children = std::move(row.children); + row.children.clear(); + row.parentThread = parent; + const auto target = row.target; + if (!row.target || ((browser->archived == 2 || row.archived == (browser->archived == 1)) && + (browser->title.empty() || QString::fromStdString(row.title).contains( + QString::fromStdString(browser->title), Qt::CaseInsensitive)))) + flat.push_back(std::move(row)); + self(self, std::move(children), target); + } + }; + flatten(flatten, std::move(result.roots), {}); + result.roots.clear(); + const auto familyKey = [&](const ThreadListRow& row) { + if (!grouped) + return std::string{}; + return browser->grouping == ThreadGrouping::Sections ? row.sectionId + : nlohmann::json::array({row.projectId, row.sectionId}).dump(); + }; + std::unordered_map positions; + positions.reserve(flat.size()); + for (std::size_t i = 0; i < flat.size(); ++i) + positions.emplace(flat[i].target.get(), i); + std::vector> descendants(flat.size()); + std::vector roots; + for (std::size_t i = 0; i < flat.size(); ++i) { + const auto parent = positions.find(flat[i].parentThread.get()); + if (flat[i].parentThread && parent != positions.end() && familyKey(flat[i]) == familyKey(flat[parent->second])) + descendants[parent->second].push_back(i); + else + roots.push_back(i); + } + const auto family = [&](const auto& self, std::size_t index) -> ThreadListRow { + ThreadListRow row = std::move(flat[index]); + for (auto child : descendants[index]) + row.children.push_back(self(self, child)); + return row; + }; + std::map grouping; + const auto ensureGroup = [&](const std::string& id, bool project) -> ThreadListRow& { + auto [entry, inserted] = grouping.try_emplace(id); + auto& row = entry->second; + if (inserted) { + row.id = id; + row.kind = project ? ThreadRowKind::Project : ThreadRowKind::Section; + row.presentationKey = std::string(project ? "project:" : "section:") + id; + row.projectId = project ? id : std::string{}; + row.sectionId = project ? std::string{} : id; + row.title = groupName(project ? result.projects : result.sections, id, project ? "No project" : "Unsectioned"); + auto parameters = filter; + parameters[project ? "projectId" : "sectionId"] = id.empty() ? nlohmann::json(nullptr) : nlohmann::json(id); + if (!project && browser->manualSections && !id.empty()) { + parameters["sortKey"] = "section_position"; + parameters["sortDirection"] = "asc"; + } + row.query = {{"method", "thread/list"}, {"parameters", parameters}}; + const auto& source = project ? result.projects : result.sections; + const auto found = std::ranges::find(source, id, &ThreadGroup::id); + if (found != source.end()) { + row.target = found->target; + const auto& fields = found->fields; + if (fields.contains("recencyAt") && fields["recencyAt"].is_number_integer()) + row.recencyAt = fields["recencyAt"].get(); + row.order = fields.value("position", std::int64_t{0}); + for (const auto& root : fields.value("roots", nlohmann::json::array())) { + if (!row.details.empty()) + row.details += '\n'; + row.details += root.value("path", std::string{}); + } + if (!project) { + row.details = "Shared section across projects"; + } + } + } + return row; + }; + if (grouped) { + const bool project = browser->grouping == ThreadGrouping::Projects; + for (const auto& group : project ? result.projects : result.sections) + ensureGroup(group.id, project); + ensureGroup({}, project); + for (const auto index : roots) { + auto row = family(family, index); + auto& parent = ensureGroup(project ? row.projectId : row.sectionId, project); + if (row.recencyAt > parent.recencyAt) + parent.recencyAt = row.recencyAt; + parent.children.push_back(std::move(row)); + } + for (auto& [id, group] : grouping) { + if (project) { + std::map subsections; + const auto ensureSection = [&](const std::string& sectionId) -> ThreadListRow& { + auto [entry, inserted] = subsections.try_emplace(sectionId); + auto& section = entry->second; + if (inserted) { + section.kind = ThreadRowKind::Section; + section.id = sectionId; + section.sectionId = sectionId; + section.projectId = id; + section.presentationKey = "project-section:" + nlohmann::json::array({id, sectionId}).dump(); + section.title = groupName(result.sections, sectionId, "Unsectioned"); + const auto found = std::ranges::find(result.sections, sectionId, &ThreadGroup::id); + if (found != result.sections.end()) { + section.target = found->target; + section.details = "Shared section across projects"; + } + auto parameters = group.query.at("parameters"); + parameters["sectionId"] = sectionId; + if (browser->manualSections) { + parameters["sortKey"] = "section_position"; + parameters["sortDirection"] = "asc"; + } + section.query = {{"method", "thread/list"}, {"parameters", parameters}}; + } + return section; + }; + if (id.empty()) + for (const auto& section : result.sections) + if (!read->hasIncomingRelation(section.target, nodegraph::RelationKind::SectionMembership)) + ensureSection(section.id); + std::vector children; + for (auto& row : group.children) { + if (row.sectionId.empty()) + children.push_back(std::move(row)); + else + ensureSection(row.sectionId).children.push_back(std::move(row)); + } + for (auto& [sectionId, section] : subsections) + children.push_back(std::move(section)); + group.children = std::move(children); + } + result.roots.push_back(std::move(group)); + } + } else { + for (const auto index : roots) + result.roots.push_back(family(family, index)); } - if (!row.query.is_null()) { - const auto parameters = row.query.at("parameters"); - if (browser->manualSections && row.kind == ThreadRowKind::Section) { - std::unordered_map rank; - // The API sorts active and archived pages independently; in All, - // preserve each server order and place active threads first. - for (int page = 0; page < (browser->archived == 2 ? 2 : 1); ++page) { - auto query = parameters; - if (browser->archived == 2) { - query["archived"] = page != 0; + const auto finalizeRows = [&](const auto& self, std::vector& rows) -> UiStatus { + UiStatus aggregate{nodegraph::NodeStatus::NotLoaded}; + for (auto& row : rows) { + const UiStatus descendants = self(self, row.children); + if (row.kind == ThreadRowKind::Project || row.kind == ThreadRowKind::Section) { + row.status = descendants; + row.indirectActive = isActiveStatus(descendants); + row.uninspectedResult = std::ranges::any_of(row.children, [](const auto& child) { + return child.uninspectedResult; + }); + } + // Fold descendants without changing an individual thread's own status. + for (const auto& status : {row.status, descendants}) { + if (isActiveStatus(status) || row.indirectActive) { + aggregate = nodegraph::NodeStatus::Running; + } else if (!isActiveStatus(aggregate) && !statusTone(status).empty()) { + aggregate = nodegraph::NodeStatus::Completed; } - const auto state = catalogState("thread/list", query); - const auto* ids = state ? valueMember(*state, "ids") : nullptr; - if (ids && ids->asArray()) { - for (const auto& id : *ids->asArray()) { - rank.emplace(exactStringFromValue(&id), rank.size()); + } + if (!row.query.is_null()) { + const auto parameters = row.query.at("parameters"); + if (browser->manualSections && row.kind == ThreadRowKind::Section) { + std::unordered_map rank; + // The API sorts active and archived pages independently; in All, + // preserve each server order and place active threads first. + for (int page = 0; page < (browser->archived == 2 ? 2 : 1); ++page) { + auto query = parameters; + if (browser->archived == 2) { + query["archived"] = page != 0; + } + const auto state = catalogState("thread/list", query); + const auto* ids = state ? valueMember(*state, "ids") : nullptr; + if (ids && ids->asArray()) { + for (const auto& id : *ids->asArray()) { + rank.emplace(exactStringFromValue(&id), rank.size()); + } + } + } + for (auto& child : row.children) { + const auto position = rank.find(child.id); + child.order = position == rank.end() ? std::numeric_limits::max() - 1 : position->second; } } + appendPages(row.children, "thread/list", parameters); + } + } + return aggregate; + }; + finalizeRows(finalizeRows, result.roots); + // Absence of membership is not another enclosing group. Standalone + // sections and wholly ungrouped threads are peers of project cards. + if (grouped) { + std::vector outer; + for (auto& row : result.roots) { + if (!row.id.empty()) { + outer.push_back(std::move(row)); + continue; } for (auto& child : row.children) { - const auto position = rank.find(child.id); - child.order = position == rank.end() ? std::numeric_limits::max() - 1 : position->second; + if (child.kind == ThreadRowKind::Page) + child.title = "Unassigned · " + child.title; + outer.push_back(std::move(child)); } } - appendPages(row.children, "thread/list", parameters); - } - } - return aggregate; - }; - finalizeRows(finalizeRows, result.roots); - // Absence of membership is not another enclosing group. Standalone - // sections and wholly ungrouped threads are peers of project cards. - if (grouped) { - std::vector outer; - for (auto &row : result.roots) { - if (!row.id.empty()) { - outer.push_back(std::move(row)); - continue; - } - for (auto &child : row.children) { - if (child.kind == ThreadRowKind::Page) - child.title = "Unassigned · " + child.title; - outer.push_back(std::move(child)); - } - } - result.roots = std::move(outer); - } - appendPages(result.roots, - grouped ? (browser->grouping == ThreadGrouping::Projects - ? "project/list" - : "threadSection/list") - : "thread/list", - grouped ? nlohmann::json::object() : filter); - } - return result; -} - -std::optional -NodeGraphUiAdapter::conversationInfo(const nodegraph::NodeRef &thread) const { - if (!graph_ || !thread) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read || !read->live(thread) || - thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - const auto state = read->state(thread); - if (!state) - return std::nullopt; - - ConversationInfo result; - const std::string hydration = - scalarTextFromValue(valueMember(*state, "hydrationState")); - const bool local = boolFromValue(valueMember(*state, "local")); - const bool recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); - result.readyForDisplay = hydration == "ready" || local || recoveryOnly; - result.hydrationFailed = hydration == "failed"; - result.providerHasMore = graphProviderHasMoreHistory(*state); - result.historyRequestPending = hasPendingHistoryRequest(*read, thread); - return result; -} - -std::optional -NodeGraphUiAdapter::pendingRequests(const InspectorRowRequest &request) const { - if (!graph_) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) - return std::nullopt; - return projectPendingRequests(*read, canControlRequests(*read), request); -} - -std::optional NodeGraphUiAdapter::pendingRequestSummary( - std::string_view selectedThreadId, - std::span localTargets) const { - if (!graph_) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) - return std::nullopt; - return projectPendingRequestSummary(*read, canControlRequests(*read), - selectedThreadId, localTargets); -} - -std::optional -NodeGraphUiAdapter::pendingRequest(const nodegraph::NodeRef &target, - bool *busy) const { - if (busy) - *busy = false; - if (!graph_ || !target) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) { - if (busy) - *busy = true; - return std::nullopt; - } - if (!read->live(target)) - return std::nullopt; - const nodegraph::NodeRef runtime = - read->find({nodegraph::NodeKind::Runtime, "runtime"}); - if (!runtime || - !read->isRelated(runtime, nodegraph::RelationKind::PendingInteraction, - target)) - return std::nullopt; - return projectPendingRequest(*read, target, canControlRequests(*read)); -} - -std::optional NodeGraphUiAdapter::turnSettings(const nodegraph::NodeRef& thread, - std::string_view draftIdentity) const { - if (!graph_) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) - return std::nullopt; - - TurnSettingsContext result; - result.models = settingModels(*read); - result.permissionProfiles = settingPermissionProfiles(*read); - if (const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"})) - result.providerAuthorityRevision = - nodegraph::unsignedIntegerFromValue(valueMember(*read->state(connection), "providerAuthorityRevision")).value_or(0); - if (!thread) { - result.identity = std::string(draftIdentity); + result.roots = std::move(outer); + } + appendPages(result.roots, + grouped ? (browser->grouping == ThreadGrouping::Projects ? "project/list" : "threadSection/list") : "thread/list", + grouped ? nlohmann::json::object() : filter); + } return result; } - if (thread->id().kind != nodegraph::NodeKind::Thread || !read->live(thread)) - return std::nullopt; - const auto state = read->state(thread); - - result.threadIncarnation = thread->incarnation(); - result.identity = boolFromValue(valueMember(*state, "local")) ? threadRowPresentationKey(thread, *state) : thread->id().canonical; - const nodegraph::Value* acknowledgements = valueMember(*state, "settingsAcknowledgements"); - const auto* acknowledged = acknowledgements ? acknowledgements->asObject() : nullptr; - const auto acknowledge = [&result, acknowledged](TurnSettingField field, std::string_view name) { - result.acknowledged[static_cast(field)] = - acknowledged ? nodegraph::unsignedIntegerFromValue(valueMember(*acknowledged, name)).value_or(0) : 0; - }; - const auto assign = [&result, &state, &acknowledge](TurnSettingField field, std::string_view name, std::string_view authority = {}) { - result.canonical[field] = settingString(valueMember(*state, name), DefaultTurnSetting); - acknowledge(field, authority.empty() ? name : authority); - }; - assign(TurnSettingField::Model, "model"); - result.canonical[TurnSettingField::Effort] = settingString(valueMember(*state, "reasoningEffort"), DefaultTurnSetting); - if (result.canonical[TurnSettingField::Effort] == DefaultTurnSetting) - result.canonical[TurnSettingField::Effort] = settingString(valueMember(*state, "effort"), DefaultTurnSetting); - acknowledge(TurnSettingField::Effort, "effort"); - assign(TurnSettingField::Personality, "personality"); - assign(TurnSettingField::Approval, "approvalPolicy", "approval"); - assign(TurnSettingField::Reviewer, "approvalsReviewer", "reviewer"); - assign(TurnSettingField::ServiceTier, "serviceTier"); - assign(TurnSettingField::Summary, "summary"); - - const nodegraph::Value* sandbox = valueMember(*state, "sandboxPolicy"); - if (!sandbox) - sandbox = valueMember(*state, "sandbox"); - result.canonical[TurnSettingField::Sandbox] = settingSandbox(sandbox); - const auto* sandboxObject = sandbox ? sandbox->asObject() : nullptr; - const nodegraph::Value* network = sandboxObject ? valueMember(*sandboxObject, "networkAccess") : nullptr; - const bool networkEnabled = network && ((network->asBool() && *network->asBool()) || scalarTextFromValue(network) == "enabled"); - const std::string& access = result.canonical[TurnSettingField::Sandbox]; - result.canonical[TurnSettingField::Network] = access == DefaultTurnSetting ? std::string(DefaultTurnSetting) - : access == "danger-full-access" || networkEnabled ? "enabled" - : "restricted"; - acknowledge(TurnSettingField::Sandbox, "sandbox"); - acknowledge(TurnSettingField::Network, "sandbox"); - - if (const nodegraph::Value* profile = valueMember(*state, "activePermissionProfile")) { - const std::string id = profile->asObject() ? settingString(valueMember(*profile->asObject(), "id")) : settingString(profile); - if (!id.empty()) - result.canonical[TurnSettingField::PermissionProfile] = id; + + std::optional NodeGraphUiAdapter::conversationInfo(const nodegraph::NodeRef& thread) const { + if (!graph_ || !thread) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read || !read->live(thread) || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + const auto state = read->state(thread); + if (!state) + return std::nullopt; + + ConversationInfo result; + const std::string hydration = scalarTextFromValue(valueMember(*state, "hydrationState")); + const bool local = boolFromValue(valueMember(*state, "local")); + const bool recoveryOnly = boolFromValue(valueMember(*state, "recoveryOnly")); + result.readyForDisplay = hydration == "ready" || local || recoveryOnly; + result.hydrationFailed = hydration == "failed"; + result.providerHasMore = graphProviderHasMoreHistory(*state); + result.historyRequestPending = hasPendingHistoryRequest(*read, thread); + return result; } - acknowledge(TurnSettingField::PermissionProfile, "permissionProfile"); - if (const nodegraph::Value* collaboration = valueMember(*state, "collaborationMode"); collaboration && collaboration->asObject()) { - const std::string mode = settingString(valueMember(*collaboration->asObject(), "mode")); - if (!mode.empty()) - result.canonical[TurnSettingField::Collaboration] = mode; + + std::optional NodeGraphUiAdapter::pendingRequests(const InspectorRowRequest& request) const { + if (!graph_) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) + return std::nullopt; + return projectPendingRequests(*read, canControlRequests(*read), request); } - acknowledge(TurnSettingField::Collaboration, "collaboration"); - return result; -} - -std::optional -NodeGraphUiAdapter::inspector(const nodegraph::NodeRef &selectedThread, - InspectorProjection projection, - const InspectorRowRequest &request) const { - if (!graph_) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read) - return std::nullopt; - - nodegraph::NodeRef thread; - if (selectedThread && - selectedThread->id().kind == nodegraph::NodeKind::Thread && - read->live(selectedThread)) - thread = selectedThread; - - InspectorSnapshot result; - const bool wantPlan = projection == InspectorProjection::Plan; - const bool wantAgents = projection == InspectorProjection::Agents; - const bool wantChanges = projection == InspectorProjection::Changes; - const bool wantRequests = projection == InspectorProjection::Requests; - const bool wantState = projection == InspectorProjection::State; - result.threadIncarnation = thread ? thread->incarnation() : 0; - result.changes.threadId = thread ? thread->id().canonical : std::string{}; - if (projection == InspectorProjection::Timing) { - auto target = request.timingTarget ? request.timingTarget : thread; - result.timingTitle = "No object selected"; - if (target && !read->live(target)) { - result.timingTitle = "Object is no longer available"; - return result; + + std::optional + NodeGraphUiAdapter::pendingRequestSummary(std::string_view selectedThreadId, std::span localTargets) const { + if (!graph_) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) + return std::nullopt; + return projectPendingRequestSummary(*read, canControlRequests(*read), selectedThreadId, localTargets); } - if (target) - result.timingTitle = - std::string(nodeKindName(target->id().kind)) + ": " + - nodegraph::protocolCanonicalId(*read->state(target), target); - const auto appendTimes = [&](const nodegraph::Value::Object &fields, - std::string_view type, - const std::string &scope) { - for (auto &time : protocolTimes(fields, type)) { - if (result.timing.size() >= 128) - break; - time.field = scope + "/" + time.field; - result.timing.push_back(std::move(time)); - } - }; - for (; target;) { - const auto kind = target->id().kind; - const std::string_view type = - kind == nodegraph::NodeKind::Item ? "ItemLifecycle" - : kind == nodegraph::NodeKind::Turn ? "Turn" - : kind == nodegraph::NodeKind::Thread ? "Thread" - : kind == nodegraph::NodeKind::Project ? "Project" - : ""; - if (type.empty()) - break; - const auto state = read->state(target); - appendTimes(state->fields, type, std::string(type)); - if (kind == nodegraph::NodeKind::Thread) { - if (const auto *goal = valueMember(*state, "goal"); - goal && goal->asObject()) - appendTimes(*goal->asObject(), "ThreadGoal", "Goal"); - target = read->relatedAt(target, - nodegraph::RelationKind::ProjectMembership, 0); - } else { - target = read->parent(target); - } + + std::optional NodeGraphUiAdapter::pendingRequest(const nodegraph::NodeRef& target, bool* busy) const { + if (busy) + *busy = false; + if (!graph_ || !target) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) { + if (busy) + *busy = true; + return std::nullopt; + } + if (!read->live(target)) + return std::nullopt; + const nodegraph::NodeRef runtime = read->find({nodegraph::NodeKind::Runtime, "runtime"}); + if (!runtime || !read->isRelated(runtime, nodegraph::RelationKind::PendingInteraction, target)) + return std::nullopt; + return projectPendingRequest(*read, target, canControlRequests(*read)); } - // Current peripheral facts, not a second history database. Use kind indexes - // and a bounded page; do no conversation-wide or arbitrary-payload scan. - using Kind = nodegraph::NodeKind; - const std::pair domains[]{ - {Kind::Account, "GetAccountRateLimitsResponse"}, - {Kind::Account, "GetWorkspaceMessagesResponse"}, - {Kind::Hook, "HookRunSummary"}, - {Kind::Plugin, "PluginSummary"}, - {Kind::Catalog, "ModelListResponse"}, - {Kind::ExternalAgentImport, "ExternalAgentConfigImportHistory"}}; - std::size_t visited = 0; - for (const auto &[kind, type] : domains) { - for (const auto &node : read->orderedNodes(kind)) { - if (++visited > 64 || result.timing.size() >= 128) - break; - const auto state = read->state(node); - const auto id = nodegraph::protocolCanonicalId(*state, node); - auto end = std::min(id.size(), std::size_t{192}); - while (end && end < id.size() && - (static_cast(id[end]) & 0xc0U) == 0x80U) - --end; - const std::string scope = - std::string(nodeKindName(kind)) + ":" + id.substr(0, end); - appendTimes(state->fields, type, scope); - } + + std::optional NodeGraphUiAdapter::turnSettings(const nodegraph::NodeRef& thread, + std::string_view draftIdentity) const { + if (!graph_) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) + return std::nullopt; + + TurnSettingsContext result; + result.models = settingModels(*read); + result.permissionProfiles = settingPermissionProfiles(*read); + if (const nodegraph::NodeRef connection = read->find({nodegraph::NodeKind::Connection, "connection"})) + result.providerAuthorityRevision = + nodegraph::unsignedIntegerFromValue(valueMember(*read->state(connection), "providerAuthorityRevision")).value_or(0); + if (!thread) { + result.identity = std::string(draftIdentity); + return result; + } + if (thread->id().kind != nodegraph::NodeKind::Thread || !read->live(thread)) + return std::nullopt; + const auto state = read->state(thread); + + result.threadIncarnation = thread->incarnation(); + result.identity = boolFromValue(valueMember(*state, "local")) ? threadRowPresentationKey(thread, *state) : thread->id().canonical; + const nodegraph::Value* acknowledgements = valueMember(*state, "settingsAcknowledgements"); + const auto* acknowledged = acknowledgements ? acknowledgements->asObject() : nullptr; + const auto acknowledge = [&result, acknowledged](TurnSettingField field, std::string_view name) { + result.acknowledged[static_cast(field)] = + acknowledged ? nodegraph::unsignedIntegerFromValue(valueMember(*acknowledged, name)).value_or(0) : 0; + }; + const auto assign = + [&result, &state, &acknowledge](TurnSettingField field, std::string_view name, std::string_view authority = {}) { + result.canonical[field] = settingString(valueMember(*state, name), DefaultTurnSetting); + acknowledge(field, authority.empty() ? name : authority); + }; + assign(TurnSettingField::Model, "model"); + result.canonical[TurnSettingField::Effort] = settingString(valueMember(*state, "reasoningEffort"), DefaultTurnSetting); + if (result.canonical[TurnSettingField::Effort] == DefaultTurnSetting) + result.canonical[TurnSettingField::Effort] = settingString(valueMember(*state, "effort"), DefaultTurnSetting); + acknowledge(TurnSettingField::Effort, "effort"); + assign(TurnSettingField::Personality, "personality"); + assign(TurnSettingField::Approval, "approvalPolicy", "approval"); + assign(TurnSettingField::Reviewer, "approvalsReviewer", "reviewer"); + assign(TurnSettingField::ServiceTier, "serviceTier"); + assign(TurnSettingField::Summary, "summary"); + + const nodegraph::Value* sandbox = valueMember(*state, "sandboxPolicy"); + if (!sandbox) + sandbox = valueMember(*state, "sandbox"); + result.canonical[TurnSettingField::Sandbox] = settingSandbox(sandbox); + const auto* sandboxObject = sandbox ? sandbox->asObject() : nullptr; + const nodegraph::Value* network = sandboxObject ? valueMember(*sandboxObject, "networkAccess") : nullptr; + const bool networkEnabled = network && ((network->asBool() && *network->asBool()) || scalarTextFromValue(network) == "enabled"); + const std::string& access = result.canonical[TurnSettingField::Sandbox]; + result.canonical[TurnSettingField::Network] = access == DefaultTurnSetting ? std::string(DefaultTurnSetting) + : access == "danger-full-access" || networkEnabled ? "enabled" + : "restricted"; + acknowledge(TurnSettingField::Sandbox, "sandbox"); + acknowledge(TurnSettingField::Network, "sandbox"); + + if (const nodegraph::Value* profile = valueMember(*state, "activePermissionProfile")) { + const std::string id = profile->asObject() ? settingString(valueMember(*profile->asObject(), "id")) : settingString(profile); + if (!id.empty()) + result.canonical[TurnSettingField::PermissionProfile] = id; + } + acknowledge(TurnSettingField::PermissionProfile, "permissionProfile"); + if (const nodegraph::Value* collaboration = valueMember(*state, "collaborationMode"); collaboration && collaboration->asObject()) { + const std::string mode = settingString(valueMember(*collaboration->asObject(), "mode")); + if (!mode.empty()) + result.canonical[TurnSettingField::Collaboration] = mode; + } + acknowledge(TurnSettingField::Collaboration, "collaboration"); + return result; } - if (visited > 64 || result.timing.size() >= 128) - result.timing.push_back(protocolTime( - "Timestamp display limit reached; further entries omitted", {})); - return result; - } - - std::map> kindCounts; - nlohmann::json domains = nlohmann::json::array(); - std::size_t omittedDomains = 0; - if (wantState) { - for (int rawKind = static_cast(nodegraph::NodeKind::Runtime); - rawKind <= static_cast(nodegraph::NodeKind::UnknownProtocol); - ++rawKind) { - const auto kind = static_cast(rawKind); - const auto &nodes = read->orderedNodes(kind); - if (!nodes.empty()) - kindCounts.emplace(std::string(nodeKindName(kind)), nodes.size()); - if (kind == nodegraph::NodeKind::Thread) - result.state.threadCount = nodes.size(); - else if (kind == nodegraph::NodeKind::UnknownProtocol) - result.state.telemetryCount = nodes.size(); - if (kind == nodegraph::NodeKind::Catalog) - for (const nodegraph::NodeRef &node : nodes) - if (node->id().canonical == "model") { - const auto state = read->state(node); - const nodegraph::Value *data = valueMember(*state, "data"); - if (const auto *models = data ? data->asArray() : nullptr) - result.state.modelCount = models->size(); - break; - } - - const bool domain = kind != nodegraph::NodeKind::Thread && - kind != nodegraph::NodeKind::Turn && - kind != nodegraph::NodeKind::Item && - kind != nodegraph::NodeKind::Interaction && - kind != nodegraph::NodeKind::Operation && - kind != nodegraph::NodeKind::UnknownProtocol; - if (!domain) - continue; - for (const nodegraph::NodeRef &node : nodes) { - if (domains.size() >= 96) { - ++omittedDomains; - continue; - } - const auto state = read->state(node); - domains.push_back( - {{"kind", nodeKindName(kind)}, - {"id", node->id().canonical}, - {"status", std::string(statusToken(statusFromState(*state)))}, - {"changedRevision", read->changedRevision(node)}, - {"fields", safeStateObject(state->fields)}}); - } + + std::optional NodeGraphUiAdapter::inspector(const nodegraph::NodeRef& selectedThread, + InspectorProjection projection, + const InspectorRowRequest& request) const { + if (!graph_) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read) + return std::nullopt; + + nodegraph::NodeRef thread; + if (selectedThread && selectedThread->id().kind == nodegraph::NodeKind::Thread && read->live(selectedThread)) + thread = selectedThread; + + InspectorSnapshot result; + const bool wantPlan = projection == InspectorProjection::Plan; + const bool wantAgents = projection == InspectorProjection::Agents; + const bool wantChanges = projection == InspectorProjection::Changes; + const bool wantRequests = projection == InspectorProjection::Requests; + const bool wantState = projection == InspectorProjection::State; + result.threadIncarnation = thread ? thread->incarnation() : 0; + result.changes.threadId = thread ? thread->id().canonical : std::string{}; + if (projection == InspectorProjection::Timing) { + auto target = request.timingTarget ? request.timingTarget : thread; + result.timingTitle = "No object selected"; + if (target && !read->live(target)) { + result.timingTitle = "Object is no longer available"; + return result; + } + if (target) + result.timingTitle = + std::string(nodeKindName(target->id().kind)) + ": " + nodegraph::protocolCanonicalId(*read->state(target), target); + const auto appendTimes = [&](const nodegraph::Value::Object& fields, std::string_view type, const std::string& scope) { + for (auto& time : protocolTimes(fields, type)) { + if (result.timing.size() >= 128) + break; + time.field = scope + "/" + time.field; + result.timing.push_back(std::move(time)); + } + }; + for (; target;) { + const auto kind = target->id().kind; + const std::string_view type = kind == nodegraph::NodeKind::Item ? "ItemLifecycle" + : kind == nodegraph::NodeKind::Turn ? "Turn" + : kind == nodegraph::NodeKind::Thread ? "Thread" + : kind == nodegraph::NodeKind::Project ? "Project" + : ""; + if (type.empty()) + break; + const auto state = read->state(target); + appendTimes(state->fields, type, std::string(type)); + if (kind == nodegraph::NodeKind::Thread) { + if (const auto* goal = valueMember(*state, "goal"); goal && goal->asObject()) + appendTimes(*goal->asObject(), "ThreadGoal", "Goal"); + target = read->relatedAt(target, nodegraph::RelationKind::ProjectMembership, 0); + } else { + target = read->parent(target); + } + } + // Current peripheral facts, not a second history database. Use kind indexes + // and a bounded page; do no conversation-wide or arbitrary-payload scan. + using Kind = nodegraph::NodeKind; + const std::pair domains[]{{Kind::Account, "GetAccountRateLimitsResponse"}, + {Kind::Account, "GetWorkspaceMessagesResponse"}, + {Kind::Hook, "HookRunSummary"}, + {Kind::Plugin, "PluginSummary"}, + {Kind::Catalog, "ModelListResponse"}, + {Kind::ExternalAgentImport, "ExternalAgentConfigImportHistory"}}; + std::size_t visited = 0; + for (const auto& [kind, type] : domains) { + for (const auto& node : read->orderedNodes(kind)) { + if (++visited > 64 || result.timing.size() >= 128) + break; + const auto state = read->state(node); + const auto id = nodegraph::protocolCanonicalId(*state, node); + auto end = std::min(id.size(), std::size_t{192}); + while (end && end < id.size() && (static_cast(id[end]) & 0xc0U) == 0x80U) + --end; + const std::string scope = std::string(nodeKindName(kind)) + ":" + id.substr(0, end); + appendTimes(state->fields, type, scope); + } + } + if (visited > 64 || result.timing.size() >= 128) + result.timing.push_back(protocolTime("Timestamp display limit reached; further entries omitted", {})); + return result; + } + + std::map> kindCounts; + nlohmann::json domains = nlohmann::json::array(); + std::size_t omittedDomains = 0; + if (wantState) { + for (int rawKind = static_cast(nodegraph::NodeKind::Runtime); + rawKind <= static_cast(nodegraph::NodeKind::UnknownProtocol); + ++rawKind) { + const auto kind = static_cast(rawKind); + const auto& nodes = read->orderedNodes(kind); + if (!nodes.empty()) + kindCounts.emplace(std::string(nodeKindName(kind)), nodes.size()); + if (kind == nodegraph::NodeKind::Thread) + result.state.threadCount = nodes.size(); + else if (kind == nodegraph::NodeKind::UnknownProtocol) + result.state.telemetryCount = nodes.size(); + if (kind == nodegraph::NodeKind::Catalog) + for (const nodegraph::NodeRef& node : nodes) + if (node->id().canonical == "model") { + const auto state = read->state(node); + const nodegraph::Value* data = valueMember(*state, "data"); + if (const auto* models = data ? data->asArray() : nullptr) + result.state.modelCount = models->size(); + break; + } + + const bool domain = kind != nodegraph::NodeKind::Thread && kind != nodegraph::NodeKind::Turn && + kind != nodegraph::NodeKind::Item && kind != nodegraph::NodeKind::Interaction && + kind != nodegraph::NodeKind::Operation && kind != nodegraph::NodeKind::UnknownProtocol; + if (!domain) + continue; + for (const nodegraph::NodeRef& node : nodes) { + if (domains.size() >= 96) { + ++omittedDomains; + continue; + } + const auto state = read->state(node); + domains.push_back({{"kind", nodeKindName(kind)}, + {"id", node->id().canonical}, + {"status", std::string(statusToken(statusFromState(*state)))}, + {"changedRevision", read->changedRevision(node)}, + {"fields", safeStateObject(state->fields)}}); + } + } + } + + nlohmann::json pendingMetadata = nlohmann::json::array(); + if (wantRequests || wantState) { + InspectorRowRequest metadataRequest; + metadataRequest.count = MaximumInspectorRows; + InspectorPageSnapshot requests = + projectPendingRequests(*read, canControlRequests(*read), wantRequests ? request : metadataRequest); + result.state.pendingRequestCount = requests.total; + if (wantState) + for (const InspectorRow& row : requests.rows) { + const auto* pending = std::get_if(&row.value); + if (!pending) + continue; + pendingMetadata.push_back({{"id", pending->target->id().canonical}, + {"method", pending->method}, + {"category", std::string(PendingRequestPolicy::kindToken(pending->kind))}, + {"thread", pending->threadTitle.empty() ? pending->threadId : pending->threadTitle}, + {"status", std::string(statusToken(statusFromState(*read->state(pending->target))))}}); + } + if (wantRequests) + result.requests = std::move(requests); + } + + const nodegraph::InspectorThreadIndex* inspectorIndex = thread ? read->inspectorIndex(thread) : nullptr; + if (wantPlan) + result.plan = projectPlan(*read, thread, inspectorIndex, request); + if (wantAgents) + result.agents = projectAgents(*read, thread, inspectorIndex, request); + + if (thread) { + const auto threadState = read->state(thread); + if (wantChanges) + result.changes.cwd = scalarTextFromValue(valueMember(*threadState, "cwd")); + if (wantState) + result.state.selectedThreadTurnCount = read->childCount(thread); + if (wantChanges || wantState) + for (std::size_t turnIndex = 0; turnIndex < read->childCount(thread); ++turnIndex) { + const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); + if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) + continue; + if (wantState) + result.state.selectedThreadItemCount += read->childCount(turn); + for (std::size_t itemIndex = 0; itemIndex < read->childCount(turn); ++itemIndex) { + const nodegraph::NodeRef item = read->childAt(turn, itemIndex); + if (!item || item->id().kind != nodegraph::NodeKind::Item) + continue; + const auto state = read->state(item); + const std::string type = scalarTextFromValue(valueMember(*state, "type")); + if (wantChanges && type == "commandExecution") { + appendUniqueBounded(result.changes.commandCwds, scalarTextFromValue(valueMember(*state, "cwd")), 64); + } else if (wantChanges && type == "fileChange") { + appendUniqueBounded(result.changes.commandCwds, scalarTextFromValue(valueMember(*state, "cwd")), 64); + const nodegraph::Value* changes = valueMember(*state, "changes"); + if (const auto* array = changes ? changes->asArray() : nullptr) + for (const nodegraph::Value& change : *array) + if (const auto* object = change.asObject()) + appendUniqueBounded( + result.changes.changedPaths, scalarTextFromValue(valueMember(*object, "path")), 512); + } + } + } + } + + nlohmann::json selected = nullptr; + if (wantState && thread) { + const auto state = read->state(thread); + selected = {{"id", thread->id().canonical}, + {"status", std::string(statusToken(statusFromState(*state)))}, + {"changedRevision", read->changedRevision(thread)}, + {"turns", result.state.selectedThreadTurnCount}, + {"items", result.state.selectedThreadItemCount}, + {"fields", safeStateObject(state->fields)}}; + if (const nodegraph::NodeRef parent = read->parent(thread)) + selected["parent"] = parent->id().canonical; + } + if (wantState) { + nlohmann::json counts = nlohmann::json::object(); + for (const auto& [kind, count] : kindCounts) + counts[kind] = count; + result.state.state = {{"sharedNodeGraph", + {{"revision", read->revision()}, + {"nodes", read->orderedNodes().size()}, + {"nodeKinds", std::move(counts)}, + {"selectedThread", std::move(selected)}, + {"currentDomains", std::move(domains)}, + {"omittedDomainCount", omittedDomains}, + {"pendingInteractions", std::move(pendingMetadata)}}}}; + } + return result; } - } - - nlohmann::json pendingMetadata = nlohmann::json::array(); - if (wantRequests || wantState) { - InspectorRowRequest metadataRequest; - metadataRequest.count = MaximumInspectorRows; - InspectorPageSnapshot requests = projectPendingRequests( - *read, canControlRequests(*read), - wantRequests ? request : metadataRequest); - result.state.pendingRequestCount = requests.total; - if (wantState) - for (const InspectorRow &row : requests.rows) { - const auto *pending = std::get_if(&row.value); - if (!pending) - continue; - pendingMetadata.push_back( - {{"id", pending->target->id().canonical}, - {"method", pending->method}, - {"category", - std::string(PendingRequestPolicy::kindToken(pending->kind))}, - {"thread", pending->threadTitle.empty() ? pending->threadId - : pending->threadTitle}, - {"status", std::string(statusToken( - statusFromState(*read->state(pending->target))))}}); - } - if (wantRequests) - result.requests = std::move(requests); - } - - const nodegraph::InspectorThreadIndex *inspectorIndex = - thread ? read->inspectorIndex(thread) : nullptr; - if (wantPlan) - result.plan = projectPlan(*read, thread, inspectorIndex, request); - if (wantAgents) - result.agents = projectAgents(*read, thread, inspectorIndex, request); - - if (thread) { - const auto threadState = read->state(thread); - if (wantChanges) - result.changes.cwd = - scalarTextFromValue(valueMember(*threadState, "cwd")); - if (wantState) - result.state.selectedThreadTurnCount = read->childCount(thread); - if (wantChanges || wantState) - for (std::size_t turnIndex = 0; turnIndex < read->childCount(thread); - ++turnIndex) { - const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); - if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) - continue; - if (wantState) - result.state.selectedThreadItemCount += read->childCount(turn); - for (std::size_t itemIndex = 0; itemIndex < read->childCount(turn); - ++itemIndex) { - const nodegraph::NodeRef item = read->childAt(turn, itemIndex); - if (!item || item->id().kind != nodegraph::NodeKind::Item) - continue; - const auto state = read->state(item); - const std::string type = - scalarTextFromValue(valueMember(*state, "type")); - if (wantChanges && type == "commandExecution") { - appendUniqueBounded(result.changes.commandCwds, - scalarTextFromValue(valueMember(*state, "cwd")), - 64); - } else if (wantChanges && type == "fileChange") { - appendUniqueBounded(result.changes.commandCwds, - scalarTextFromValue(valueMember(*state, "cwd")), - 64); - const nodegraph::Value *changes = valueMember(*state, "changes"); - if (const auto *array = changes ? changes->asArray() : nullptr) - for (const nodegraph::Value &change : *array) - if (const auto *object = change.asObject()) - appendUniqueBounded( - result.changes.changedPaths, - scalarTextFromValue(valueMember(*object, "path")), 512); - } - } - } - - } - - nlohmann::json selected = nullptr; - if (wantState && thread) { - const auto state = read->state(thread); - selected = {{"id", thread->id().canonical}, - {"status", std::string(statusToken(statusFromState(*state)))}, - {"changedRevision", read->changedRevision(thread)}, - {"turns", result.state.selectedThreadTurnCount}, - {"items", result.state.selectedThreadItemCount}, - {"fields", safeStateObject(state->fields)}}; - if (const nodegraph::NodeRef parent = read->parent(thread)) - selected["parent"] = parent->id().canonical; - } - if (wantState) { - nlohmann::json counts = nlohmann::json::object(); - for (const auto &[kind, count] : kindCounts) - counts[kind] = count; - result.state.state = { - {"sharedNodeGraph", - {{"revision", read->revision()}, - {"nodes", read->orderedNodes().size()}, - {"nodeKinds", std::move(counts)}, - {"selectedThread", std::move(selected)}, - {"currentDomains", std::move(domains)}, - {"omittedDomainCount", omittedDomains}, - {"pendingInteractions", std::move(pendingMetadata)}}}}; - } - return result; -} - -bool NodeGraphUiAdapter::inspectorAffected( - const nodegraph::GraphChanged &change, - const nodegraph::NodeRef &selectedThread, - InspectorProjection projection) const { - if (!graph_) - return false; - auto read = graph_->tryRead(); - return read ? inspectorAffected(change, selectedThread, projection, *read) - : true; -} - -bool NodeGraphUiAdapter::inspectorAffected( - const nodegraph::GraphChanged &change, - const nodegraph::NodeRef &selectedThread, - InspectorProjection projection, - const nodegraph::NodeGraph::ReadAccess &access) const { - if (projection == InspectorProjection::Protocol) - return false; - if (projection == InspectorProjection::Timing) - return change.rescanRequired || !change.removed.empty() || - std::ranges::any_of(change.affected, [&](const auto &node) { - return node && access.live(node) && - std::ranges::any_of( - std::array{"startedAt", "completedAt", "durationMs", - "startedAtMs", "completedAtMs", "createdAt", - "updatedAt", "recencyAt", "sectionEnteredAt", - "goal", "projectId", "data", "messages", - "rateLimits", "rateLimitsByLimitId", - "rateLimitResetCredits", "installedAt", - "failure"}, - [&](const char *field) { - return fieldChanged(access, node, field, - change.revision); - }); - }); - if (change.rescanRequired) - return true; - if (projection == InspectorProjection::State) { - if (!change.childListsChanged.empty()) - return true; - const auto changesSummary = [&](const nodegraph::NodeRef &node) { - if (!node) - return false; - if (node == selectedThread) - return true; - return node->id().kind != nodegraph::NodeKind::Turn && - node->id().kind != nodegraph::NodeKind::Item && - node->id().kind != nodegraph::NodeKind::Operation; - }; - return std::ranges::any_of(change.affected, changesSummary) || - std::ranges::any_of(change.removed, changesSummary); - } - if (change.affected.size() + change.removed.size() > 64 || - change.childListsChanged.size() > 64) - return true; - const auto *read = &access; - - if (projection == InspectorProjection::Requests) { - if (read->pendingInteractionOrderRevision() == change.revision) - return true; - const auto connectionChanged = [&](const nodegraph::NodeRef &node) { - if (!node || node->id().kind != nodegraph::NodeKind::Connection) - return false; - return !read->live(node) || - read->statusChangedRevision(node) == change.revision || - fieldChanged(*read, node, "role", change.revision) || - fieldChanged(*read, node, "providerState", change.revision); - }; - if (std::ranges::any_of(change.affected, connectionChanged) || - std::ranges::any_of(change.removed, connectionChanged)) - return true; - const nodegraph::NodeRef runtime = - read->find({nodegraph::NodeKind::Runtime, "runtime"}); - if (!runtime) - return false; - constexpr std::array RequestFields{ - "method", "payload", "error", "responseRevision", - "retainedResponsePayload", "recoveryOnly"}; - for (const nodegraph::NodeRef &node : change.affected) { - if (!node || node->id().kind != nodegraph::NodeKind::Interaction || - !read->live(node) || - !read->isRelated(runtime, - nodegraph::RelationKind::PendingInteraction, node)) - continue; - if (read->structureChangedRevision(node) == change.revision || - std::ranges::any_of(RequestFields, [&](std::string_view field) { - return fieldChanged(*read, node, field, change.revision); - })) - return true; + + bool NodeGraphUiAdapter::inspectorAffected(const nodegraph::GraphChanged& change, + const nodegraph::NodeRef& selectedThread, + InspectorProjection projection) const { + if (!graph_) + return false; + auto read = graph_->tryRead(); + return read ? inspectorAffected(change, selectedThread, projection, *read) : true; } - std::vector renamedThreads; - for (const nodegraph::NodeRef &node : change.affected) - if (node && node->id().kind == nodegraph::NodeKind::Thread && - read->live(node) && - (fieldChanged(*read, node, "name", change.revision) || - fieldChanged(*read, node, "title", change.revision))) - renamedThreads.push_back(node); - if (renamedThreads.empty() && change.childListsChanged.empty()) - return false; - const std::size_t count = read->relatedCount( - runtime, nodegraph::RelationKind::PendingInteraction); - for (std::size_t index = 0; index < count; ++index) { - const nodegraph::NodeRef interaction = read->relatedAt( - runtime, nodegraph::RelationKind::PendingInteraction, index); - const std::size_t targetCount = read->relatedCount( - interaction, nodegraph::RelationKind::InteractionTarget); - bool resolved = false; - for (std::size_t targetIndex = 0; - targetIndex < targetCount && !resolved; ++targetIndex) { - for (nodegraph::NodeRef node = read->relatedAt( - interaction, nodegraph::RelationKind::InteractionTarget, - targetIndex); - node; node = read->parent(node)) { - if (node->id().kind == nodegraph::NodeKind::Thread) { - resolved = true; - if (std::ranges::find(renamedThreads, node) != - renamedThreads.end()) - return true; - break; - } - if (read->structureChangedRevision(node) != change.revision) - continue; - const nodegraph::NodeRef parent = read->parent(node); - if (std::ranges::any_of( - change.childListsChanged, - [&](const nodegraph::ChildListChange &entry) { - return entry.childKind == node->id().kind && - (!parent || entry.owner == parent); - })) + + bool NodeGraphUiAdapter::inspectorAffected(const nodegraph::GraphChanged& change, + const nodegraph::NodeRef& selectedThread, + InspectorProjection projection, + const nodegraph::NodeGraph::ReadAccess& access) const { + if (projection == InspectorProjection::Protocol) + return false; + if (projection == InspectorProjection::Timing) + return change.rescanRequired || !change.removed.empty() || std::ranges::any_of(change.affected, [&](const auto& node) { + return node && access.live(node) && + std::ranges::any_of(std::array{"startedAt", + "completedAt", + "durationMs", + "startedAtMs", + "completedAtMs", + "createdAt", + "updatedAt", + "recencyAt", + "sectionEnteredAt", + "goal", + "projectId", + "data", + "messages", + "rateLimits", + "rateLimitsByLimitId", + "rateLimitResetCredits", + "installedAt", + "failure"}, + [&](const char* field) { + return fieldChanged(access, node, field, change.revision); + }); + }); + if (change.rescanRequired) return true; + if (projection == InspectorProjection::State) { + if (!change.childListsChanged.empty()) + return true; + const auto changesSummary = [&](const nodegraph::NodeRef& node) { + if (!node) + return false; + if (node == selectedThread) + return true; + return node->id().kind != nodegraph::NodeKind::Turn && node->id().kind != nodegraph::NodeKind::Item && + node->id().kind != nodegraph::NodeKind::Operation; + }; + return std::ranges::any_of(change.affected, changesSummary) || std::ranges::any_of(change.removed, changesSummary); + } + if (change.affected.size() + change.removed.size() > 64 || change.childListsChanged.size() > 64) + return true; + const auto* read = &access; + + if (projection == InspectorProjection::Requests) { + if (read->pendingInteractionOrderRevision() == change.revision) + return true; + const auto connectionChanged = [&](const nodegraph::NodeRef& node) { + if (!node || node->id().kind != nodegraph::NodeKind::Connection) + return false; + return !read->live(node) || read->statusChangedRevision(node) == change.revision || + fieldChanged(*read, node, "role", change.revision) || fieldChanged(*read, node, "providerState", change.revision); + }; + if (std::ranges::any_of(change.affected, connectionChanged) || std::ranges::any_of(change.removed, connectionChanged)) + return true; + const nodegraph::NodeRef runtime = read->find({nodegraph::NodeKind::Runtime, "runtime"}); + if (!runtime) + return false; + constexpr std::array RequestFields{ + "method", "payload", "error", "responseRevision", "retainedResponsePayload", "recoveryOnly"}; + for (const nodegraph::NodeRef& node : change.affected) { + if (!node || node->id().kind != nodegraph::NodeKind::Interaction || !read->live(node) || + !read->isRelated(runtime, nodegraph::RelationKind::PendingInteraction, node)) + continue; + if (read->structureChangedRevision(node) == change.revision || + std::ranges::any_of(RequestFields, [&](std::string_view field) { + return fieldChanged(*read, node, field, change.revision); + })) + return true; + } + std::vector renamedThreads; + for (const nodegraph::NodeRef& node : change.affected) + if (node && node->id().kind == nodegraph::NodeKind::Thread && read->live(node) && + (fieldChanged(*read, node, "name", change.revision) || fieldChanged(*read, node, "title", change.revision))) + renamedThreads.push_back(node); + if (renamedThreads.empty() && change.childListsChanged.empty()) + return false; + const std::size_t count = read->relatedCount(runtime, nodegraph::RelationKind::PendingInteraction); + for (std::size_t index = 0; index < count; ++index) { + const nodegraph::NodeRef interaction = read->relatedAt(runtime, nodegraph::RelationKind::PendingInteraction, index); + const std::size_t targetCount = read->relatedCount(interaction, nodegraph::RelationKind::InteractionTarget); + bool resolved = false; + for (std::size_t targetIndex = 0; targetIndex < targetCount && !resolved; ++targetIndex) { + for (nodegraph::NodeRef node = read->relatedAt(interaction, nodegraph::RelationKind::InteractionTarget, targetIndex); + node; + node = read->parent(node)) { + if (node->id().kind == nodegraph::NodeKind::Thread) { + resolved = true; + if (std::ranges::find(renamedThreads, node) != renamedThreads.end()) + return true; + break; + } + if (read->structureChangedRevision(node) != change.revision) + continue; + const nodegraph::NodeRef parent = read->parent(node); + if (std::ranges::any_of(change.childListsChanged, [&](const nodegraph::ChildListChange& entry) { + return entry.childKind == node->id().kind && (!parent || entry.owner == parent); + })) + return true; + } + } + } + return false; + } + + if (!selectedThread) + return false; + if (!read->live(selectedThread)) + return true; + if (projection == InspectorProjection::Plan || projection == InspectorProjection::Agents) { + const nodegraph::InspectorThreadIndex* index = read->inspectorIndex(selectedThread); + if (!index) + return true; + return (projection == InspectorProjection::Plan ? index->planChangedRevision : index->agentChangedRevision) == change.revision; + } + + const auto belongsToSelection = [&](nodegraph::NodeRef node) { + while (node && node != selectedThread && read->live(node)) + node = read->parent(node); + return node == selectedThread; + }; + if (std::ranges::any_of(change.childListsChanged, [&](const auto& entry) { + return entry.owner && belongsToSelection(entry.owner) && + ((entry.owner == selectedThread && entry.childKind == nodegraph::NodeKind::Turn) || + (entry.owner->id().kind == nodegraph::NodeKind::Turn && entry.childKind == nodegraph::NodeKind::Item)); + })) + return true; + for (const nodegraph::NodeRef& node : change.affected) { + if (!node || !read->contains(node)) + continue; + if (node == selectedThread) { + if (fieldChanged(*read, node, "cwd", change.revision) || fieldChanged(*read, node, "workspace", change.revision) || + fieldChanged(*read, node, "hydrationState", change.revision)) + return true; + continue; + } + if (node->id().kind != nodegraph::NodeKind::Item || !belongsToSelection(node)) + continue; + const auto state = read->state(node); + const std::string type = scalarTextFromValue(valueMember(*state, "type")); + if (type == "fileChange" || type == "commandExecution" || fieldChanged(*read, node, "type", change.revision)) + return true; } - } - } - return false; - } - - if (!selectedThread) - return false; - if (!read->live(selectedThread)) - return true; - if (projection == InspectorProjection::Plan || - projection == InspectorProjection::Agents) { - const nodegraph::InspectorThreadIndex *index = - read->inspectorIndex(selectedThread); - if (!index) - return true; - return (projection == InspectorProjection::Plan - ? index->planChangedRevision - : index->agentChangedRevision) == change.revision; - } - - const auto belongsToSelection = [&](nodegraph::NodeRef node) { - while (node && node != selectedThread && read->live(node)) - node = read->parent(node); - return node == selectedThread; - }; - if (std::ranges::any_of(change.childListsChanged, [&](const auto &entry) { - return entry.owner && belongsToSelection(entry.owner) && - ((entry.owner == selectedThread && - entry.childKind == nodegraph::NodeKind::Turn) || - (entry.owner->id().kind == nodegraph::NodeKind::Turn && - entry.childKind == nodegraph::NodeKind::Item)); - })) - return true; - for (const nodegraph::NodeRef &node : change.affected) { - if (!node || !read->contains(node)) - continue; - if (node == selectedThread) { - if (fieldChanged(*read, node, "cwd", change.revision) || - fieldChanged(*read, node, "workspace", change.revision) || - fieldChanged(*read, node, "hydrationState", change.revision)) - return true; - continue; - } - if (node->id().kind != nodegraph::NodeKind::Item || - !belongsToSelection(node)) - continue; - const auto state = read->state(node); - const std::string type = - scalarTextFromValue(valueMember(*state, "type")); - if (type == "fileChange" || type == "commandExecution" || - fieldChanged(*read, node, "type", change.revision)) - return true; - } - return false; -} - -NodeGraphUiAdapter::ConversationRoute -NodeGraphUiAdapter::conversationRoute(const nodegraph::GraphChanged &change, - const nodegraph::NodeRef &thread) const { - if (!graph_ || !thread) - return {}; - auto read = graph_->tryRead(); - return read ? conversationRoute(change, thread, *read) - : ConversationRoute{true, true, true, {}, {}, {}, 0}; -} - -NodeGraphUiAdapter::ConversationRoute NodeGraphUiAdapter::conversationRoute( - const nodegraph::GraphChanged &change, const nodegraph::NodeRef &thread, - const nodegraph::NodeGraph::ReadAccess &access) const { - ConversationRoute route; - route.graphRevision = access.revision(); - if (!thread) - return route; - if (change.rescanRequired) { - route.affected = true; - route.structural = true; - route.authorityReplacement = true; - return route; - } - - const auto *read = &access; - - const std::string &threadId = thread->id().canonical; - route.graphRevision = change.revision; - const auto isHistoryOperationForThread = [&](const nodegraph::NodeRef &node) { - if (!node || node->id().kind != nodegraph::NodeKind::Operation || - !read->contains(node)) - return false; - const auto state = read->state(node); - if (!state || !isConversationSnapshotMethod( - scalarTextFromValue(valueMember(*state, "method")))) - return false; - const nodegraph::Value *payload = valueMember(*state, "requestPayload"); - const auto *object = payload ? payload->asObject() : nullptr; - if (object && - scalarTextFromValue(valueMember(*object, "threadId")) == threadId) - return true; - if (!read->live(node) || !read->live(thread)) - return false; - const std::vector pendingOperations = - read->related(thread, nodegraph::RelationKind::PendingOperation); - return std::ranges::find(pendingOperations, node) != - pendingOperations.end(); - }; - const bool historyOperationChanged = - std::ranges::any_of(change.affected, isHistoryOperationForThread) || - std::ranges::any_of(change.removed, isHistoryOperationForThread); - if (historyOperationChanged && read->live(thread)) - route.historyRequestPending = hasPendingHistoryRequest(*read, thread); - const bool threadTurnsChanged = - std::ranges::any_of(change.childListsChanged, [&](const auto &changed) { - return changed.owner == thread && - changed.childKind == nodegraph::NodeKind::Turn; - }); - const bool turnInsertedIntoThread = - threadTurnsChanged && - std::ranges::any_of(change.affected, [&](const auto &node) { - return node && node->id().kind == nodegraph::NodeKind::Turn && - read->structureChangedRevision(node) == change.revision && - read->parent(node) == thread; - }); - if (threadTurnsChanged && !turnInsertedIntoThread) { - route.affected = true; - route.structural = true; - route.authorityReplacement = true; - return route; - } - const auto belongsToThread = [&](const nodegraph::NodeRef &node) { - if (!node) - return false; - nodegraph::NodeRef ancestor = node; - while ((ancestor = read->parent(ancestor))) { - if (ancestor == thread) - return true; - if (ancestor->id().kind == nodegraph::NodeKind::Thread) return false; } - const auto state = read->state(node); - if (!state) - return false; - constexpr std::array ThreadFields{ - "protocolThreadId", "threadId"}; - return std::ranges::any_of( - ThreadFields, [&](std::string_view field) { - return scalarTextFromValue(valueMember(*state, field)) == threadId; - }); - }; - const auto addItem = [&](const nodegraph::NodeRef &item) { - if (!item || route.authorityReplacement || - std::ranges::find(route.items, item) != route.items.end()) - return; - route.items.push_back(item); - }; - const auto routeNode = [&](const nodegraph::NodeRef &node) { - if (!node) - return; - if (node == thread) { - if (!read->contains(node)) { - route = {true, true, true, {}, {}, {}, route.graphRevision}; - return; - } - if (fieldChanged(*read, node, "historyHasMore", change.revision)) { - route.affected = true; - route.providerHasMore = graphProviderHasMoreHistory(*read->state(node)); - } - if (fieldChanged(*read, node, "hydrationState", change.revision)) { - route.affected = true; - route.structural = true; - route.authorityReplacement = true; - route.items.clear(); - return; - } - if (read->structureChangedRevision(node) == change.revision) { - for (const nodegraph::NodeRef &candidate : change.affected) { - if (!candidate || - candidate->id().kind != nodegraph::NodeKind::Turn || - !belongsToThread(candidate)) - continue; - route.affected = true; - route.structural = true; - addItem(conversationOpeningItem(*read, candidate)); - } - } - return; - } - if (node->id().kind == nodegraph::NodeKind::Thread || - (node->id().kind != nodegraph::NodeKind::Turn && - node->id().kind != nodegraph::NodeKind::Item)) - return; - - if (!read->live(node)) { - if (node->id().kind == nodegraph::NodeKind::Item && - belongsToThread(node)) { - route.affected = true; - route.structural = true; - addItem(node); - } - return; - } - if (!belongsToThread(node)) { - if (node->id().kind == nodegraph::NodeKind::Item && - read->structureChangedRevision(node) == change.revision && - !read->parent(node)) { - route.affected = true; - route.structural = true; - route.authorityReplacement = true; - } - return; + NodeGraphUiAdapter::ConversationRoute NodeGraphUiAdapter::conversationRoute(const nodegraph::GraphChanged& change, + const nodegraph::NodeRef& thread) const { + if (!graph_ || !thread) + return {}; + auto read = graph_->tryRead(); + return read ? conversationRoute(change, thread, *read) : ConversationRoute{true, true, true, {}, {}, {}, 0}; } - if (node->id().kind == nodegraph::NodeKind::Turn) { - const bool structureChanged = - read->structureChangedRevision(node) == change.revision; - const bool statusChanged = - read->statusChangedRevision(node) == change.revision; - const bool timingChanged = std::ranges::any_of( - std::array{"startedAt", "completedAt", "durationMs"}, - [&](const char *field) { - return fieldChanged(*read, node, field, change.revision); - }); - if (!structureChanged && !statusChanged && !timingChanged) - return; - route.affected = true; - route.structural = route.structural || structureChanged || statusChanged; - addItem(conversationOpeningItem(*read, node)); - return; - } - route.affected = true; - if (read->structureChangedRevision(node) == change.revision) - route.structural = true; - addItem(node); - }; - - for (const nodegraph::NodeRef &node : change.affected) - routeNode(node); - for (const nodegraph::NodeRef &node : change.removed) { - if (!node) - continue; - if (node == thread) - return {true, true, true, {}, {}, {}, route.graphRevision}; - if (node->id().kind == nodegraph::NodeKind::Item && - belongsToThread(node)) { - route.affected = true; - route.structural = true; - addItem(node); - } else if (node->id().kind == nodegraph::NodeKind::Turn && - belongsToThread(node)) { - route.affected = true; - route.structural = true; - route.authorityReplacement = true; - route.items.clear(); - } - } - - return route; -} - -std::optional -NodeGraphUiAdapter::conversationDelta(const nodegraph::NodeRef &thread, - std::span items, - bool structural) const { - if (!graph_ || !thread) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read || !read->live(thread) || - thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - const auto threadState = read->state(thread); - if (!threadState) - return std::nullopt; - - ConversationDelta result; - result.threadId = thread->id().canonical; - result.providerHasMore = graphProviderHasMoreHistory(*threadState); - const std::string threadCwd = - scalarTextFromValue(valueMember(*threadState, "cwd")); - const nodegraph::NodeRef activeTurn = - structural ? conversationActiveTurn(*read, thread) : nodegraph::NodeRef{}; - - std::vector transactionItems; - transactionItems.reserve(items.size()); - for (const nodegraph::NodeRef &target : items) { - if (structural && target && read->live(target) && - target->id().kind == nodegraph::NodeKind::Turn) - transactionItems.push_back(conversationTurnRoot(*read, target)); - else - transactionItems.push_back(target); - } - - std::unordered_set seen; - seen.reserve(transactionItems.size()); - std::unordered_set materializedPrompts; - materializedPrompts.reserve(items.size()); - std::unordered_map changedRows; - changedRows.reserve(items.size()); - for (const nodegraph::NodeRef &item : transactionItems) { - if (!item || !seen.insert(item.get()).second) - continue; - if (!structural) { - if (!read->live(item) || - item->id().kind != nodegraph::NodeKind::Item) - continue; - const nodegraph::NodeRef turn = read->parent(item); - if (!turn || turn->id().kind != nodegraph::NodeKind::Turn || - read->parent(turn) != thread) - continue; - const auto state = read->state(item); - const auto turnState = read->state(turn); - if (!state || !turnState) - continue; - - if (!isHiddenMaterializedPrompt(*read, item)) - result.presentations.push_back(conversationCardData( - *read, item, result.threadId, - nodegraph::protocolCanonicalId(*turnState, turn), *state, - threadCwd)); - continue; - } + NodeGraphUiAdapter::ConversationRoute NodeGraphUiAdapter::conversationRoute(const nodegraph::GraphChanged& change, + const nodegraph::NodeRef& thread, + const nodegraph::NodeGraph::ReadAccess& access) const { + ConversationRoute route; + route.graphRevision = access.revision(); + if (!thread) + return route; + if (change.rescanRequired) { + route.affected = true; + route.structural = true; + route.authorityReplacement = true; + return route; + } - std::optional row = - projectRowChange(read, thread, item, threadCwd, activeTurn); - if (!row) { - result.removals.push_back(item); - continue; - } - if (const auto prompt = materializedPrompt(*read, item); - prompt && materializedPrompts.insert(prompt->prompt.get()).second) - result.materializedPrompts.push_back( - {row->placement.card.key, prompt->prompt}); - const std::string key = stableKey(row->placement.card.key); - if (const auto duplicate = changedRows.find(key); - duplicate != changedRows.end()) { - result.rows[duplicate->second] = std::move(*row); - } else { - changedRows.emplace(key, result.rows.size()); - result.rows.push_back(std::move(*row)); - } - } - - read.reset(); - if (!structural || result.rows.size() < 2) - return result; - - std::vector> following(result.rows.size()); - std::vector predecessors(result.rows.size(), 0); - const auto relate = [&](std::size_t before, std::size_t after) { - if (before == after || - std::ranges::find(following[before], after) != following[before].end()) - return; - following[before].push_back(after); - ++predecessors[after]; - }; - for (std::size_t index = 0; index < result.rows.size(); ++index) { - if (result.rows[index].previousCardKey) { - const auto previous = - changedRows.find(stableKey(*result.rows[index].previousCardKey)); - if (previous != changedRows.end()) - relate(previous->second, index); - } - if (result.rows[index].nextCardKey) { - const auto next = - changedRows.find(stableKey(*result.rows[index].nextCardKey)); - if (next != changedRows.end()) - relate(index, next->second); + const auto* read = &access; + + const std::string& threadId = thread->id().canonical; + route.graphRevision = change.revision; + const auto isHistoryOperationForThread = [&](const nodegraph::NodeRef& node) { + if (!node || node->id().kind != nodegraph::NodeKind::Operation || !read->contains(node)) + return false; + const auto state = read->state(node); + if (!state || !isConversationSnapshotMethod(scalarTextFromValue(valueMember(*state, "method")))) + return false; + const nodegraph::Value* payload = valueMember(*state, "requestPayload"); + const auto* object = payload ? payload->asObject() : nullptr; + if (object && scalarTextFromValue(valueMember(*object, "threadId")) == threadId) + return true; + if (!read->live(node) || !read->live(thread)) + return false; + const std::vector pendingOperations = read->related(thread, nodegraph::RelationKind::PendingOperation); + return std::ranges::find(pendingOperations, node) != pendingOperations.end(); + }; + const bool historyOperationChanged = std::ranges::any_of(change.affected, isHistoryOperationForThread) || + std::ranges::any_of(change.removed, isHistoryOperationForThread); + if (historyOperationChanged && read->live(thread)) + route.historyRequestPending = hasPendingHistoryRequest(*read, thread); + const bool threadTurnsChanged = std::ranges::any_of(change.childListsChanged, [&](const auto& changed) { + return changed.owner == thread && changed.childKind == nodegraph::NodeKind::Turn; + }); + const bool turnInsertedIntoThread = threadTurnsChanged && std::ranges::any_of(change.affected, [&](const auto& node) { + return node && node->id().kind == nodegraph::NodeKind::Turn && + read->structureChangedRevision(node) == change.revision && + read->parent(node) == thread; + }); + if (threadTurnsChanged && !turnInsertedIntoThread) { + route.affected = true; + route.structural = true; + route.authorityReplacement = true; + return route; + } + const auto belongsToThread = [&](const nodegraph::NodeRef& node) { + if (!node) + return false; + nodegraph::NodeRef ancestor = node; + while ((ancestor = read->parent(ancestor))) { + if (ancestor == thread) + return true; + if (ancestor->id().kind == nodegraph::NodeKind::Thread) + return false; + } + const auto state = read->state(node); + if (!state) + return false; + constexpr std::array ThreadFields{"protocolThreadId", "threadId"}; + return std::ranges::any_of(ThreadFields, [&](std::string_view field) { + return scalarTextFromValue(valueMember(*state, field)) == threadId; + }); + }; + const auto addItem = [&](const nodegraph::NodeRef& item) { + if (!item || route.authorityReplacement || std::ranges::find(route.items, item) != route.items.end()) + return; + route.items.push_back(item); + }; + const auto routeNode = [&](const nodegraph::NodeRef& node) { + if (!node) + return; + if (node == thread) { + if (!read->contains(node)) { + route = {true, true, true, {}, {}, {}, route.graphRevision}; + return; + } + if (fieldChanged(*read, node, "historyHasMore", change.revision)) { + route.affected = true; + route.providerHasMore = graphProviderHasMoreHistory(*read->state(node)); + } + if (fieldChanged(*read, node, "hydrationState", change.revision)) { + route.affected = true; + route.structural = true; + route.authorityReplacement = true; + route.items.clear(); + return; + } + if (read->structureChangedRevision(node) == change.revision) { + for (const nodegraph::NodeRef& candidate : change.affected) { + if (!candidate || candidate->id().kind != nodegraph::NodeKind::Turn || !belongsToThread(candidate)) + continue; + route.affected = true; + route.structural = true; + addItem(conversationOpeningItem(*read, candidate)); + } + } + return; + } + if (node->id().kind == nodegraph::NodeKind::Thread || + (node->id().kind != nodegraph::NodeKind::Turn && node->id().kind != nodegraph::NodeKind::Item)) + return; + + if (!read->live(node)) { + if (node->id().kind == nodegraph::NodeKind::Item && belongsToThread(node)) { + route.affected = true; + route.structural = true; + addItem(node); + } + return; + } + + if (!belongsToThread(node)) { + if (node->id().kind == nodegraph::NodeKind::Item && read->structureChangedRevision(node) == change.revision && + !read->parent(node)) { + route.affected = true; + route.structural = true; + route.authorityReplacement = true; + } + return; + } + + if (node->id().kind == nodegraph::NodeKind::Turn) { + const bool structureChanged = read->structureChangedRevision(node) == change.revision; + const bool statusChanged = read->statusChangedRevision(node) == change.revision; + const bool timingChanged = + std::ranges::any_of(std::array{"startedAt", "completedAt", "durationMs"}, [&](const char* field) { + return fieldChanged(*read, node, field, change.revision); + }); + if (!structureChanged && !statusChanged && !timingChanged) + return; + route.affected = true; + route.structural = route.structural || structureChanged || statusChanged; + addItem(conversationOpeningItem(*read, node)); + return; + } + route.affected = true; + if (read->structureChangedRevision(node) == change.revision) + route.structural = true; + addItem(node); + }; + + for (const nodegraph::NodeRef& node : change.affected) + routeNode(node); + for (const nodegraph::NodeRef& node : change.removed) { + if (!node) + continue; + if (node == thread) + return {true, true, true, {}, {}, {}, route.graphRevision}; + if (node->id().kind == nodegraph::NodeKind::Item && belongsToThread(node)) { + route.affected = true; + route.structural = true; + addItem(node); + } else if (node->id().kind == nodegraph::NodeKind::Turn && belongsToThread(node)) { + route.affected = true; + route.structural = true; + route.authorityReplacement = true; + route.items.clear(); + } + } + + return route; } - } - - std::vector ordered; - ordered.reserve(result.rows.size()); - std::vector emitted(result.rows.size(), false); - while (ordered.size() != result.rows.size()) { - bool progress = false; - for (std::size_t index = 0; index < result.rows.size(); ++index) { - if (emitted[index] || predecessors[index] != 0) - continue; - emitted[index] = true; - progress = true; - ordered.push_back(std::move(result.rows[index])); - for (const std::size_t next : following[index]) - --predecessors[next]; + + std::optional NodeGraphUiAdapter::conversationDelta(const nodegraph::NodeRef& thread, + std::span items, + bool structural) const { + if (!graph_ || !thread) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read || !read->live(thread) || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + const auto threadState = read->state(thread); + if (!threadState) + return std::nullopt; + + ConversationDelta result; + result.threadId = thread->id().canonical; + result.providerHasMore = graphProviderHasMoreHistory(*threadState); + const std::string threadCwd = scalarTextFromValue(valueMember(*threadState, "cwd")); + const nodegraph::NodeRef activeTurn = structural ? conversationActiveTurn(*read, thread) : nodegraph::NodeRef{}; + + std::vector transactionItems; + transactionItems.reserve(items.size()); + for (const nodegraph::NodeRef& target : items) { + if (structural && target && read->live(target) && target->id().kind == nodegraph::NodeKind::Turn) + transactionItems.push_back(conversationTurnRoot(*read, target)); + else + transactionItems.push_back(target); + } + + std::unordered_set seen; + seen.reserve(transactionItems.size()); + std::unordered_set materializedPrompts; + materializedPrompts.reserve(items.size()); + std::unordered_map changedRows; + changedRows.reserve(items.size()); + for (const nodegraph::NodeRef& item : transactionItems) { + if (!item || !seen.insert(item.get()).second) + continue; + if (!structural) { + if (!read->live(item) || item->id().kind != nodegraph::NodeKind::Item) + continue; + const nodegraph::NodeRef turn = read->parent(item); + if (!turn || turn->id().kind != nodegraph::NodeKind::Turn || read->parent(turn) != thread) + continue; + const auto state = read->state(item); + const auto turnState = read->state(turn); + if (!state || !turnState) + continue; + + if (!isHiddenMaterializedPrompt(*read, item)) + result.presentations.push_back(conversationCardData( + *read, item, result.threadId, nodegraph::protocolCanonicalId(*turnState, turn), *state, threadCwd)); + continue; + } + + std::optional row = projectRowChange(read, thread, item, threadCwd, activeTurn); + if (!row) { + result.removals.push_back(item); + continue; + } + if (const auto prompt = materializedPrompt(*read, item); prompt && materializedPrompts.insert(prompt->prompt.get()).second) + result.materializedPrompts.push_back({row->placement.card.key, prompt->prompt}); + const std::string key = stableKey(row->placement.card.key); + if (const auto duplicate = changedRows.find(key); duplicate != changedRows.end()) { + result.rows[duplicate->second] = std::move(*row); + } else { + changedRows.emplace(key, result.rows.size()); + result.rows.push_back(std::move(*row)); + } + } + + read.reset(); + if (!structural || result.rows.size() < 2) + return result; + + std::vector> following(result.rows.size()); + std::vector predecessors(result.rows.size(), 0); + const auto relate = [&](std::size_t before, std::size_t after) { + if (before == after || std::ranges::find(following[before], after) != following[before].end()) + return; + following[before].push_back(after); + ++predecessors[after]; + }; + for (std::size_t index = 0; index < result.rows.size(); ++index) { + if (result.rows[index].previousCardKey) { + const auto previous = changedRows.find(stableKey(*result.rows[index].previousCardKey)); + if (previous != changedRows.end()) + relate(previous->second, index); + } + if (result.rows[index].nextCardKey) { + const auto next = changedRows.find(stableKey(*result.rows[index].nextCardKey)); + if (next != changedRows.end()) + relate(index, next->second); + } + } + + std::vector ordered; + ordered.reserve(result.rows.size()); + std::vector emitted(result.rows.size(), false); + while (ordered.size() != result.rows.size()) { + bool progress = false; + for (std::size_t index = 0; index < result.rows.size(); ++index) { + if (emitted[index] || predecessors[index] != 0) + continue; + emitted[index] = true; + progress = true; + ordered.push_back(std::move(result.rows[index])); + for (const std::size_t next : following[index]) + --predecessors[next]; + } + if (!progress) + return std::nullopt; + } + result.rows = std::move(ordered); + return result; } - if (!progress) - return std::nullopt; - } - result.rows = std::move(ordered); - return result; -} - -std::optional -NodeGraphUiAdapter::conversationDeltaSince( - const nodegraph::NodeRef &thread, std::uint64_t afterRevision, - std::uint64_t *graphRevision) const { - if (!graph_ || !thread || afterRevision == 0) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read || !read->live(thread) || - thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - - std::vector changed; - const std::size_t turnCount = read->childCount(thread); - changed.reserve(turnCount); - for (std::size_t turnIndex = 0; turnIndex < turnCount; ++turnIndex) { - const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); - if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) - continue; - const auto turnState = read->state(turn); - if (!turnState) - continue; - if (read->changedRevision(turn) > afterRevision || - read->structureChangedRevision(turn) > afterRevision) - changed.push_back(conversationOpeningItem(*read, turn)); - const std::size_t itemCount = read->childCount(turn); - for (std::size_t itemIndex = 0; itemIndex < itemCount; ++itemIndex) { - const nodegraph::NodeRef item = read->childAt(turn, itemIndex); - if (item && item->id().kind == nodegraph::NodeKind::Item && - (read->changedRevision(item) > afterRevision || - read->structureChangedRevision(item) > afterRevision)) - changed.push_back(item); + + std::optional NodeGraphUiAdapter::conversationDeltaSince(const nodegraph::NodeRef& thread, + std::uint64_t afterRevision, + std::uint64_t* graphRevision) const { + if (!graph_ || !thread || afterRevision == 0) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read || !read->live(thread) || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + + std::vector changed; + const std::size_t turnCount = read->childCount(thread); + changed.reserve(turnCount); + for (std::size_t turnIndex = 0; turnIndex < turnCount; ++turnIndex) { + const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); + if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) + continue; + const auto turnState = read->state(turn); + if (!turnState) + continue; + if (read->changedRevision(turn) > afterRevision || read->structureChangedRevision(turn) > afterRevision) + changed.push_back(conversationOpeningItem(*read, turn)); + const std::size_t itemCount = read->childCount(turn); + for (std::size_t itemIndex = 0; itemIndex < itemCount; ++itemIndex) { + const nodegraph::NodeRef item = read->childAt(turn, itemIndex); + if (item && item->id().kind == nodegraph::NodeKind::Item && + (read->changedRevision(item) > afterRevision || read->structureChangedRevision(item) > afterRevision)) + changed.push_back(item); + } + } + if (graphRevision) + *graphRevision = read->revision(); + read.reset(); + return conversationDelta(thread, changed, true); } - } - if (graphRevision) - *graphRevision = read->revision(); - read.reset(); - return conversationDelta(thread, changed, true); -} - -std::optional NodeGraphUiAdapter::projectRowChange( - std::optional &read, - const nodegraph::NodeRef &thread, const nodegraph::NodeRef &item, - std::string_view threadCwd, const nodegraph::NodeRef &activeTurn) { - if (!read) - return std::nullopt; - if (!read->live(thread) || !read->live(item) || - thread->id().kind != nodegraph::NodeKind::Thread || - item->id().kind != nodegraph::NodeKind::Item) - return {}; - - const nodegraph::NodeRef turn = read->parent(item); - if (!turn || turn->id().kind != nodegraph::NodeKind::Turn || - read->parent(turn) != thread) - return {}; - const auto itemState = read->state(item); - const auto turnState = read->state(turn); - if (!itemState || !turnState) - return {}; - - const std::string threadId = thread->id().canonical; - const auto canonicalTurnId = [&](const nodegraph::NodeRef &owner) { - const auto state = owner ? read->state(owner) : nullptr; - return state ? nodegraph::protocolCanonicalId(*state, owner) - : std::string{}; - }; - const auto projectedKeyAt = [&](const nodegraph::NodeRef &owner, - std::size_t index) -> std::optional { - const nodegraph::NodeRef candidate = read->childAt(owner, index); - return conversationCardKey( - *read, candidate, threadId, canonicalTurnId(owner), - isHiddenMaterializedPrompt(*read, candidate)); - }; - - const std::size_t itemCount = read->childCount(turn); - const std::optional itemIndex = read->childIndex(item); - if (!itemIndex || *itemIndex >= itemCount) - return {}; - const std::optional itemKey = projectedKeyAt(turn, *itemIndex); - if (!itemKey) - return {}; - - std::optional previous; - std::optional next; - for (std::size_t offset = *itemIndex; offset > 0 && !previous; --offset) - previous = projectedKeyAt(turn, offset - 1); - for (std::size_t index = *itemIndex + 1; index < itemCount && !next; ++index) - next = projectedKeyAt(turn, index); - - const std::size_t turnCount = read->childCount(thread); - const std::optional turnIndex = read->childIndex(turn); - if (!turnIndex || *turnIndex >= turnCount) - return {}; - for (std::size_t offset = *turnIndex; offset > 0 && !previous; --offset) { - const nodegraph::NodeRef owner = read->childAt(thread, offset - 1); - if (!owner || owner->id().kind != nodegraph::NodeKind::Turn) - continue; - for (std::size_t child = read->childCount(owner); child > 0 && !previous; - --child) - previous = projectedKeyAt(owner, child - 1); - } - for (std::size_t ownerIndex = *turnIndex + 1; ownerIndex < turnCount && !next; - ++ownerIndex) { - const nodegraph::NodeRef owner = read->childAt(thread, ownerIndex); - if (!owner || owner->id().kind != nodegraph::NodeKind::Turn) - continue; - for (std::size_t child = 0; child < read->childCount(owner) && !next; - ++child) - next = projectedKeyAt(owner, child); - } - - const nodegraph::NodeRef root = conversationTurnRoot(*read, turn); - const std::optional rootIndex = - root && read->parent(root) == turn ? read->childIndex(root) - : std::nullopt; - const std::string turnId = canonicalTurnId(turn); - - ConversationRowChange result; - result.placement.card = conversationCardData(*read, item, threadId, turnId, - *itemState, threadCwd); - result.placement.card.key = *itemKey; - result.placement.sectionKey = sectionComponent("turn:", threadId, turnId); - result.placement.turnRoot = root == item; - result.placement.nested = isNestedTurnCard(rootIndex, *itemIndex); - result.placement.activeTurn = activeTurn == turn; - result.previousCardKey = std::move(previous); - result.nextCardKey = std::move(next); - return result; -} - -std::optional -NodeGraphUiAdapter::conversation(const nodegraph::NodeRef &thread, - std::uint64_t *graphRevision) const { - if (!graph_ || !thread) - return std::nullopt; - auto read = graph_->tryRead(); - if (!read || !read->live(thread) || - thread->id().kind != nodegraph::NodeKind::Thread) - return std::nullopt; - - const auto threadState = read->state(thread); - if (!threadState) - return std::nullopt; - if (graphRevision) - *graphRevision = read->revision(); - const std::string threadCwd = - scalarTextFromValue(valueMember(*threadState, "cwd")); - const nodegraph::NodeRef activeTurn = conversationActiveTurn(*read, thread); - - ConversationSnapshot result; - result.threadId = thread->id().canonical; - result.hasMore = graphProviderHasMoreHistory(*threadState); - - if (activeTurn) { - const auto state = read->state(activeTurn); - if (state) - result.activeTurnId = nodegraph::protocolCanonicalId(*state, activeTurn); - } - - std::unordered_set materializedPrompts; - const std::size_t turnCount = read->childCount(thread); - result.sections.reserve(turnCount); - for (std::size_t turnIndex = 0; turnIndex < turnCount; ++turnIndex) { - const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); - if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) - continue; - const auto turnState = read->state(turn); - if (!turnState) - continue; - const std::string turnId = - nodegraph::protocolCanonicalId(*turnState, turn); - const nodegraph::NodeRef root = conversationTurnRoot(*read, turn); - TurnSection section; - section.key = sectionComponent("turn:", result.threadId, turnId); - section.turnId = turnId; - const std::size_t childCount = read->childCount(turn); - section.cards.reserve(childCount); - for (std::size_t itemIndex = 0; itemIndex < childCount; ++itemIndex) { - const nodegraph::NodeRef item = read->childAt(turn, itemIndex); - if (!item || item->id().kind != nodegraph::NodeKind::Item || - !read->live(item)) - continue; - const auto itemState = read->state(item); - if (!itemState || - (scalarTextFromValue(valueMember(*itemState, "type")) == - "localPrompt" && - isHiddenMaterializedPrompt(*read, item))) - continue; - VisibleCardData card = conversationCardData(*read, item, result.threadId, - turnId, *itemState, - threadCwd); - if (const auto prompt = materializedPrompt(*read, item); - prompt && materializedPrompts.insert(prompt->prompt.get()).second) - result.materializedPrompts.push_back({card.key, prompt->prompt}); - if (item == root) - section.rootCardKey = card.key; - section.cards.push_back(std::move(card)); + + std::optional NodeGraphUiAdapter::projectRowChange(std::optional& read, + const nodegraph::NodeRef& thread, + const nodegraph::NodeRef& item, + std::string_view threadCwd, + const nodegraph::NodeRef& activeTurn) { + if (!read) + return std::nullopt; + if (!read->live(thread) || !read->live(item) || thread->id().kind != nodegraph::NodeKind::Thread || + item->id().kind != nodegraph::NodeKind::Item) + return {}; + + const nodegraph::NodeRef turn = read->parent(item); + if (!turn || turn->id().kind != nodegraph::NodeKind::Turn || read->parent(turn) != thread) + return {}; + const auto itemState = read->state(item); + const auto turnState = read->state(turn); + if (!itemState || !turnState) + return {}; + + const std::string threadId = thread->id().canonical; + const auto canonicalTurnId = [&](const nodegraph::NodeRef& owner) { + const auto state = owner ? read->state(owner) : nullptr; + return state ? nodegraph::protocolCanonicalId(*state, owner) : std::string{}; + }; + const auto projectedKeyAt = [&](const nodegraph::NodeRef& owner, std::size_t index) -> std::optional { + const nodegraph::NodeRef candidate = read->childAt(owner, index); + return conversationCardKey(*read, candidate, threadId, canonicalTurnId(owner), isHiddenMaterializedPrompt(*read, candidate)); + }; + + const std::size_t itemCount = read->childCount(turn); + const std::optional itemIndex = read->childIndex(item); + if (!itemIndex || *itemIndex >= itemCount) + return {}; + const std::optional itemKey = projectedKeyAt(turn, *itemIndex); + if (!itemKey) + return {}; + + std::optional previous; + std::optional next; + for (std::size_t offset = *itemIndex; offset > 0 && !previous; --offset) + previous = projectedKeyAt(turn, offset - 1); + for (std::size_t index = *itemIndex + 1; index < itemCount && !next; ++index) + next = projectedKeyAt(turn, index); + + const std::size_t turnCount = read->childCount(thread); + const std::optional turnIndex = read->childIndex(turn); + if (!turnIndex || *turnIndex >= turnCount) + return {}; + for (std::size_t offset = *turnIndex; offset > 0 && !previous; --offset) { + const nodegraph::NodeRef owner = read->childAt(thread, offset - 1); + if (!owner || owner->id().kind != nodegraph::NodeKind::Turn) + continue; + for (std::size_t child = read->childCount(owner); child > 0 && !previous; --child) + previous = projectedKeyAt(owner, child - 1); + } + for (std::size_t ownerIndex = *turnIndex + 1; ownerIndex < turnCount && !next; ++ownerIndex) { + const nodegraph::NodeRef owner = read->childAt(thread, ownerIndex); + if (!owner || owner->id().kind != nodegraph::NodeKind::Turn) + continue; + for (std::size_t child = 0; child < read->childCount(owner) && !next; ++child) + next = projectedKeyAt(owner, child); + } + + const nodegraph::NodeRef root = conversationTurnRoot(*read, turn); + const std::optional rootIndex = root && read->parent(root) == turn ? read->childIndex(root) : std::nullopt; + const std::string turnId = canonicalTurnId(turn); + + ConversationRowChange result; + result.placement.card = conversationCardData(*read, item, threadId, turnId, *itemState, threadCwd); + result.placement.card.key = *itemKey; + result.placement.sectionKey = sectionComponent("turn:", threadId, turnId); + result.placement.turnRoot = root == item; + result.placement.nested = isNestedTurnCard(rootIndex, *itemIndex); + result.placement.activeTurn = activeTurn == turn; + result.previousCardKey = std::move(previous); + result.nextCardKey = std::move(next); + return result; } - if (!section.cards.empty()) - result.sections.push_back(std::move(section)); - } + std::optional NodeGraphUiAdapter::conversation(const nodegraph::NodeRef& thread, + std::uint64_t* graphRevision) const { + if (!graph_ || !thread) + return std::nullopt; + auto read = graph_->tryRead(); + if (!read || !read->live(thread) || thread->id().kind != nodegraph::NodeKind::Thread) + return std::nullopt; + + const auto threadState = read->state(thread); + if (!threadState) + return std::nullopt; + if (graphRevision) + *graphRevision = read->revision(); + const std::string threadCwd = scalarTextFromValue(valueMember(*threadState, "cwd")); + const nodegraph::NodeRef activeTurn = conversationActiveTurn(*read, thread); + + ConversationSnapshot result; + result.threadId = thread->id().canonical; + result.hasMore = graphProviderHasMoreHistory(*threadState); + + if (activeTurn) { + const auto state = read->state(activeTurn); + if (state) + result.activeTurnId = nodegraph::protocolCanonicalId(*state, activeTurn); + } - return result; -} + std::unordered_set materializedPrompts; + const std::size_t turnCount = read->childCount(thread); + result.sections.reserve(turnCount); + for (std::size_t turnIndex = 0; turnIndex < turnCount; ++turnIndex) { + const nodegraph::NodeRef turn = read->childAt(thread, turnIndex); + if (!turn || turn->id().kind != nodegraph::NodeKind::Turn) + continue; + const auto turnState = read->state(turn); + if (!turnState) + continue; + const std::string turnId = nodegraph::protocolCanonicalId(*turnState, turn); + const nodegraph::NodeRef root = conversationTurnRoot(*read, turn); + TurnSection section; + section.key = sectionComponent("turn:", result.threadId, turnId); + section.turnId = turnId; + const std::size_t childCount = read->childCount(turn); + section.cards.reserve(childCount); + for (std::size_t itemIndex = 0; itemIndex < childCount; ++itemIndex) { + const nodegraph::NodeRef item = read->childAt(turn, itemIndex); + if (!item || item->id().kind != nodegraph::NodeKind::Item || !read->live(item)) + continue; + const auto itemState = read->state(item); + if (!itemState || + (scalarTextFromValue(valueMember(*itemState, "type")) == "localPrompt" && isHiddenMaterializedPrompt(*read, item))) + continue; + VisibleCardData card = conversationCardData(*read, item, result.threadId, turnId, *itemState, threadCwd); + if (const auto prompt = materializedPrompt(*read, item); prompt && materializedPrompts.insert(prompt->prompt.get()).second) + result.materializedPrompts.push_back({card.key, prompt->prompt}); + if (item == root) + section.rootCardKey = card.key; + section.cards.push_back(std::move(card)); + } + + if (!section.cards.empty()) + result.sections.push_back(std::move(section)); + } + + return result; + } } // namespace codexui::codex::ui From b19a54a41a3fe9a0cd4ff51cfb79c27447824e7d Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:02:48 +0100 Subject: [PATCH 2/9] Enroll CodexUI for the 21 Linux targets with required desktop dependencies --- .github/workflows/build-and-qualify.yml | 14 +- .snodec/repo.yml | 4 +- AGENTS.md | 4 + CMakeLists.txt | 682 ++++++++++++------------ VERSION | 1 + ci/package/native.sh | 21 + ci/packages.json | 118 ++++ cmake/PackageConfig.cmake | 4 + cmake/Packing.cmake | 25 + cmake/Version.cmake | 12 + docs/qualification/README.md | 1 + docs/qualification/package-targets.md | 60 +++ 12 files changed, 587 insertions(+), 359 deletions(-) create mode 100644 VERSION create mode 100644 ci/package/native.sh create mode 100644 ci/packages.json create mode 100644 cmake/PackageConfig.cmake create mode 100644 cmake/Packing.cmake create mode 100644 cmake/Version.cmake create mode 100644 docs/qualification/package-targets.md diff --git a/.github/workflows/build-and-qualify.yml b/.github/workflows/build-and-qualify.yml index aaf54de..f2bcffe 100644 --- a/.github/workflows/build-and-qualify.yml +++ b/.github/workflows/build-and-qualify.yml @@ -1,6 +1,6 @@ name: Build and qualify CodexUI desktop and web # Verify the native UI, web SDK, browser performance and production artifacts. -on: [workflow_dispatch] +on: [pull_request, workflow_dispatch] permissions: { contents: read } concurrency: group: codexui-ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -19,7 +19,7 @@ jobs: steps: - name: Check out exact CodexUI head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7 with: fetch-depth: 0 ref: >- @@ -28,13 +28,13 @@ jobs: path: CodexUI - name: Check out AISuite default-branch frontend SDK - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7 with: repository: SNodeC/AISuite path: AISuite - name: Set up Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + uses: actions/setup-node@v7 with: node-version: 22 cache: npm @@ -68,7 +68,7 @@ jobs: npm test - name: Select the qualified performance runtime - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + uses: actions/setup-node@v7 with: node-version: 24.20.0 @@ -123,7 +123,7 @@ jobs: - name: Upload failed web timing diagnostics if: ${{ !cancelled() && (steps.web-model-profile.outcome == 'failure' || steps.web-browser.outcome == 'failure') }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: actions/upload-artifact@v7 with: name: web-timing-diagnostics path: CodexUI/_build/frontend/web/_build/web-profiles @@ -141,7 +141,7 @@ jobs: test -n "$(find _stage/web/share/codexui/web/assets -type f -print -quit)" - name: Upload CodexWebUI production artifact - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: actions/upload-artifact@v7 with: name: codexui-web path: CodexUI/_build/frontend/web/_stage/web/share/codexui/web diff --git a/.snodec/repo.yml b/.snodec/repo.yml index 46d19e0..946c07b 100644 --- a/.snodec/repo.yml +++ b/.snodec/repo.yml @@ -21,9 +21,9 @@ ci: - --output-on-failure - --verbose - --parallel - - '4' + - '14' ipv6: true runtime_dirs: true - parallel: 4 + parallel: 14 env: {CODEXUI_TIMING_POLICY: report} ctest_launcher: [xvfb-run, -a, env, QT_QPA_PLATFORM=offscreen] diff --git a/AGENTS.md b/AGENTS.md index 4b85f77..e3fc08e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,10 @@ For profile-manager planning or implementation, follow [Codex Profile Manager re This canonical checkout uses the nested layout: approved persistent checkouts belong in `/checkouts/` and persistent builds in `/build/codex/`. Temporary build/check output belongs in `/tmp/codex/build/CodexUI/`. Do not reuse the historical `build-qualification` directory for new work. The repository copies the shared formatting and analysis baseline; use explicit formatting targets or format only files changed by the current task. +## Native packages + +`VERSION` supplies the CMake project version. `ci/packages.json` declares only the full Linux targets qualified in `docs/qualification/package-targets.md`, depends on `aisuite`, and uses the existing install rules for both desktop applications, icons, desktop files and manager web assets. The package hook follows the native CI configuration with `CODEXUI_INSTALL_WEB=OFF`; the separate CodexWebUI production artifact retains its existing build/release workflow. GUI checks use Xvfb with `QT_QPA_PLATFORM=offscreen`. CPack DEB/RPM configuration is under `cmake/`; never install verification packages on this host. + ## Markdown formatting - Write each prose paragraph on one physical source line. Do not manually wrap prose to a fixed column width; let the renderer wrap to the available width. diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ec74c2..c8ee638 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,13 @@ # SPDX-License-Identifier: LGPL-3.0-or-later OR MIT cmake_minimum_required(VERSION 3.20) +include(cmake/Version.cmake) -project(CodexUI VERSION 1.0.0 LANGUAGES CXX) +project( + CodexUI + VERSION ${RELEASE_VERSION} + LANGUAGES CXX +) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include(format) @@ -11,10 +16,8 @@ include(GNUInstallDirs) include(CTest) find_package(Threads REQUIRED) -option( - CODEXUI_NODEGRAPH_ONLY - "Configure only the standalone codexui-nodegraph library and tests" - OFF +option(CODEXUI_NODEGRAPH_ONLY + "Configure only the standalone codexui-nodegraph library and tests" OFF ) add_subdirectory(src/codex/nodegraph) @@ -34,12 +37,10 @@ find_package( COMPONENTS net-un-stream-legacy net-in-stream-legacy net-in6-stream-legacy ) find_package( - snodec 2.0 CONFIG QUIET - COMPONENTS net-in-stream-tls net-in6-stream-tls + snodec 2.0 CONFIG QUIET COMPONENTS net-in-stream-tls net-in6-stream-tls ) find_package( - snodec 2.0 CONFIG QUIET - COMPONENTS net-rc-stream-legacy net-rc-stream-tls + snodec 2.0 CONFIG QUIET COMPONENTS net-rc-stream-legacy net-rc-stream-tls ) find_package(Qt6 6.6 REQUIRED COMPONENTS Widgets Network) find_package(KF6Sonnet 6.13 REQUIRED) @@ -53,15 +54,21 @@ pkg_check_modules(LIBGIT2 REQUIRED IMPORTED_TARGET libgit2) function(configure_codexui_transports target) if(TARGET snodec::net-in-stream-tls AND TARGET snodec::net-in6-stream-tls) - target_compile_definitions(${target} PRIVATE CODEXUI_CODEX_FRONTEND_TLS=1) + target_compile_definitions( + ${target} PRIVATE CODEXUI_CODEX_FRONTEND_TLS=1 + ) target_link_libraries( - ${target} PRIVATE snodec::net-in-stream-tls snodec::net-in6-stream-tls + ${target} PRIVATE snodec::net-in-stream-tls + snodec::net-in6-stream-tls ) endif() if(TARGET snodec::net-rc-stream-legacy AND TARGET snodec::net-rc-stream-tls) - target_compile_definitions(${target} PRIVATE CODEXUI_CODEX_FRONTEND_RFCOMM=1) + target_compile_definitions( + ${target} PRIVATE CODEXUI_CODEX_FRONTEND_RFCOMM=1 + ) target_link_libraries( - ${target} PRIVATE snodec::net-rc-stream-legacy snodec::net-rc-stream-tls + ${target} PRIVATE snodec::net-rc-stream-legacy + snodec::net-rc-stream-tls ) endif() if(TARGET snodec::http-client AND TARGET snodec::websocket-client) @@ -78,7 +85,9 @@ add_library(codexui-build-options INTERFACE) if(MSVC) target_compile_options(codexui-build-options INTERFACE /W4 /WX) else() - target_compile_options(codexui-build-options INTERFACE -Wall -Wextra -Werror) + target_compile_options( + codexui-build-options INTERFACE -Wall -Wextra -Werror + ) endif() add_library( @@ -95,14 +104,13 @@ target_compile_features(codexui-client-runtime PUBLIC cxx_std_20) target_include_directories(codexui-client-runtime PUBLIC src) target_link_libraries( codexui-client-runtime - PUBLIC - AISuite::OpenAICodex - codexui-nodegraph - Qt6::Core - Threads::Threads - snodec::net-un-stream-legacy - snodec::net-in-stream-legacy - snodec::net-in6-stream-legacy + PUBLIC AISuite::OpenAICodex + codexui-nodegraph + Qt6::Core + Threads::Threads + snodec::net-un-stream-legacy + snodec::net-in-stream-legacy + snodec::net-in6-stream-legacy PRIVATE codexui-build-options ) configure_codexui_transports(codexui-client-runtime) @@ -118,42 +126,37 @@ target_link_libraries(codexui-conversation-height-index PUBLIC Qt6::Core) add_library( codexui-nodegraph-json STATIC - src/codex/NodeGraphJson.cpp - src/codex/NodeGraphJson.h - src/codex/ProtocolTiming.cpp - src/codex/ProtocolTiming.h + src/codex/NodeGraphJson.cpp src/codex/NodeGraphJson.h + src/codex/ProtocolTiming.cpp src/codex/ProtocolTiming.h ) target_compile_features(codexui-nodegraph-json PUBLIC cxx_std_20) target_include_directories(codexui-nodegraph-json PUBLIC src) add_library( - codexui-pending-request-policy STATIC - src/codex/PendingRequestPolicy.cpp - src/codex/PendingRequestPolicy.h + codexui-pending-request-policy STATIC src/codex/PendingRequestPolicy.cpp + src/codex/PendingRequestPolicy.h ) target_compile_features(codexui-pending-request-policy PUBLIC cxx_std_20) target_include_directories(codexui-pending-request-policy PUBLIC src) target_link_libraries(codexui-pending-request-policy PUBLIC codexui-nodegraph) add_library( - codexui-turn-settings-policy STATIC - src/codex/TurnSettingsPolicy.cpp - src/codex/TurnSettingsPolicy.h + codexui-turn-settings-policy STATIC src/codex/TurnSettingsPolicy.cpp + src/codex/TurnSettingsPolicy.h ) target_compile_features(codexui-turn-settings-policy PUBLIC cxx_std_20) target_include_directories(codexui-turn-settings-policy PUBLIC src) add_library( codexui-ui-style STATIC - src/codex/ui/UiStyle.cpp - src/codex/ui/UiStyle.h - src/codex/ui/TimingPresentation.cpp - src/codex/ui/TimingPresentation.h + src/codex/ui/UiStyle.cpp src/codex/ui/UiStyle.h + src/codex/ui/TimingPresentation.cpp src/codex/ui/TimingPresentation.h ) target_compile_features(codexui-ui-style PUBLIC cxx_std_20) target_include_directories(codexui-ui-style PUBLIC src) target_link_libraries( - codexui-ui-style PUBLIC Qt6::Widgets codexui-nodegraph-json codexui-nodegraph + codexui-ui-style PUBLIC Qt6::Widgets codexui-nodegraph-json + codexui-nodegraph ) target_link_libraries(codexui-ui-style PRIVATE codexui-build-options) @@ -174,39 +177,29 @@ target_compile_features(codexui-conversation-ui PUBLIC cxx_std_20) target_include_directories(codexui-conversation-ui PUBLIC src) target_link_libraries( codexui-conversation-ui - PUBLIC - codexui-conversation-height-index - codexui-nodegraph - codexui-ui-style - Qt6::Widgets + PUBLIC codexui-conversation-height-index codexui-nodegraph codexui-ui-style + Qt6::Widgets PRIVATE codexui-build-options ) add_library( codexui-ui-adapter STATIC - src/codex/ui/NodeGraphUiAdapter.cpp - src/codex/ui/NodeGraphUiAdapter.h + src/codex/ui/NodeGraphUiAdapter.cpp src/codex/ui/NodeGraphUiAdapter.h src/codex/ui/UiViewState.h ) target_compile_features(codexui-ui-adapter PUBLIC cxx_std_20) target_include_directories(codexui-ui-adapter PUBLIC src) target_link_libraries( codexui-ui-adapter - PUBLIC - codexui-conversation-ui - codexui-nodegraph-json - codexui-nodegraph - codexui-pending-request-policy - codexui-turn-settings-policy + PUBLIC codexui-conversation-ui codexui-nodegraph-json codexui-nodegraph + codexui-pending-request-policy codexui-turn-settings-policy PRIVATE codexui-build-options ) add_library( codexui-diff-viewer STATIC - src/codex/DiffViewer.cpp - src/codex/DiffViewer.h - src/codex/GitDiffProvider.cpp - src/codex/GitDiffProvider.h + src/codex/DiffViewer.cpp src/codex/DiffViewer.h + src/codex/GitDiffProvider.cpp src/codex/GitDiffProvider.h ) target_compile_features(codexui-diff-viewer PUBLIC cxx_std_20) target_include_directories(codexui-diff-viewer PUBLIC src) @@ -239,22 +232,22 @@ target_compile_features(codexui-middle-ui PUBLIC cxx_std_20) target_include_directories(codexui-middle-ui PUBLIC src) target_link_libraries( codexui-middle-ui - PUBLIC - AISuite::OpenAICodex - codexui-conversation-ui - codexui-diff-viewer - codexui-pending-request-policy - codexui-turn-settings-policy - codexui-ui-adapter - codexui-ui-style - Qt6::Widgets + PUBLIC AISuite::OpenAICodex + codexui-conversation-ui + codexui-diff-viewer + codexui-pending-request-policy + codexui-turn-settings-policy + codexui-ui-adapter + codexui-ui-style + Qt6::Widgets PRIVATE codexui-build-options KF6::SonnetCore ) add_library( codexui-shell-ui STATIC src/codex/AttachmentDraft.h - src/codex/ConnectionDialog.cpp src/codex/ConnectionDialog.h + src/codex/ConnectionDialog.cpp + src/codex/ConnectionDialog.h src/codex/FrontendSession.cpp src/codex/FrontendSession.h src/codex/ForkNaming.h @@ -272,59 +265,56 @@ target_compile_features(codexui-shell-ui PUBLIC cxx_std_20) target_include_directories(codexui-shell-ui PUBLIC src) target_link_libraries( codexui-shell-ui - PUBLIC - AISuite::OpenAICodex - codexui-client-runtime - codexui-middle-ui - codexui-nodegraph-json - codexui-nodegraph - codexui-pending-request-policy - codexui-turn-settings-policy - codexui-ui-adapter - codexui-ui-style - Qt6::Widgets - Threads::Threads + PUBLIC AISuite::OpenAICodex + codexui-client-runtime + codexui-middle-ui + codexui-nodegraph-json + codexui-nodegraph + codexui-pending-request-policy + codexui-turn-settings-policy + codexui-ui-adapter + codexui-ui-style + Qt6::Widgets + Threads::Threads PRIVATE codexui-build-options ) qt_add_executable( - codex-ui - src/codex/MainWindow.cpp - src/codex/MainWindow.h - src/codex/main.cpp + codex-ui src/codex/MainWindow.cpp src/codex/MainWindow.h src/codex/main.cpp ) function(configure_codexui_target target) target_compile_features(${target} PRIVATE cxx_std_20) target_include_directories(${target} PRIVATE src) target_link_libraries( ${target} - PRIVATE - AISuite::OpenAICodex - codexui-client-runtime - codexui-diff-viewer - codexui-middle-ui - codexui-conversation-ui - codexui-conversation-height-index - codexui-nodegraph-json - codexui-nodegraph - codexui-pending-request-policy - codexui-shell-ui - codexui-turn-settings-policy - codexui-ui-adapter - codexui-ui-style - PkgConfig::LIBGIT2 - Qt6::Widgets - Threads::Threads - snodec::net-un-stream-legacy - snodec::net-in-stream-legacy - snodec::net-in6-stream-legacy + PRIVATE AISuite::OpenAICodex + codexui-client-runtime + codexui-diff-viewer + codexui-middle-ui + codexui-conversation-ui + codexui-conversation-height-index + codexui-nodegraph-json + codexui-nodegraph + codexui-pending-request-policy + codexui-shell-ui + codexui-turn-settings-policy + codexui-ui-adapter + codexui-ui-style + PkgConfig::LIBGIT2 + Qt6::Widgets + Threads::Threads + snodec::net-un-stream-legacy + snodec::net-in-stream-legacy + snodec::net-in6-stream-legacy ) endfunction() configure_codexui_target(codex-ui) target_link_libraries(codex-ui PRIVATE codexui-build-options) -option(CODEXUI_INSTALL_WEB "Require and install the CodexWebUI production artifact" ON) +option(CODEXUI_INSTALL_WEB + "Require and install the CodexWebUI production artifact" ON +) if(CODEXUI_INSTALL_WEB) add_subdirectory(web) else() @@ -344,25 +334,19 @@ if(BUILD_TESTING) target_compile_features( codexui-nodegraph-ui-adapter-test PRIVATE cxx_std_20 ) - target_include_directories( - codexui-nodegraph-ui-adapter-test PRIVATE src - ) + target_include_directories(codexui-nodegraph-ui-adapter-test PRIVATE src) target_compile_definitions( - codexui-nodegraph-ui-adapter-test PRIVATE - CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json" - ) - target_link_libraries( codexui-nodegraph-ui-adapter-test PRIVATE - codexui-ui-adapter + CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json" ) - add_test( - NAME codexui-nodegraph-ui-adapter - COMMAND codexui-nodegraph-ui-adapter-test + target_link_libraries( + codexui-nodegraph-ui-adapter-test PRIVATE codexui-ui-adapter ) - set_tests_properties( - codexui-nodegraph-ui-adapter PROPERTIES TIMEOUT 10 + add_test(NAME codexui-nodegraph-ui-adapter + COMMAND codexui-nodegraph-ui-adapter-test ) + set_tests_properties(codexui-nodegraph-ui-adapter PROPERTIES TIMEOUT 10) qt_add_executable( codexui-nodegraph-conversation-ui-test @@ -376,14 +360,11 @@ if(BUILD_TESTING) ) target_link_libraries( codexui-nodegraph-conversation-ui-test - PRIVATE - codexui-ui-adapter - codexui-conversation-height-index - Qt6::Widgets + PRIVATE codexui-ui-adapter codexui-conversation-height-index + Qt6::Widgets ) - add_test( - NAME codexui-nodegraph-conversation-ui - COMMAND codexui-nodegraph-conversation-ui-test + add_test(NAME codexui-nodegraph-conversation-ui + COMMAND codexui-nodegraph-conversation-ui-test ) set_tests_properties( codexui-nodegraph-conversation-ui @@ -402,40 +383,44 @@ if(BUILD_TESTING) ) target_link_libraries( codexui-nodegraph-thread-pane-ui-test - PRIVATE - codexui-middle-ui - codexui-ui-adapter - codexui-nodegraph-json - codexui-nodegraph - codexui-pending-request-policy - codexui-conversation-ui - Qt6::Widgets - ) - add_test( - NAME codexui-nodegraph-thread-pane-ui - COMMAND codexui-nodegraph-thread-pane-ui-test + PRIVATE codexui-middle-ui + codexui-ui-adapter + codexui-nodegraph-json + codexui-nodegraph + codexui-pending-request-policy + codexui-conversation-ui + Qt6::Widgets + ) + add_test(NAME codexui-nodegraph-thread-pane-ui + COMMAND codexui-nodegraph-thread-pane-ui-test ) set_tests_properties( codexui-nodegraph-thread-pane-ui PROPERTIES - TIMEOUT 15 - LABELS "geometry;qt;thread-pane" + TIMEOUT + 15 + LABELS + "geometry;qt;thread-pane" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=1;QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_EXPECTED_DPR=1" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=1;QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_EXPECTED_DPR=1" ) foreach(thread_dpr IN ITEMS 1.25 1.5 2) string(REPLACE "." "_" thread_dpr_name "${thread_dpr}") set(thread_geometry_name "codexui-nodegraph-thread-pane-ui-dpr-${thread_dpr_name}" ) - add_test(NAME ${thread_geometry_name} COMMAND codexui-nodegraph-thread-pane-ui-test) + add_test(NAME ${thread_geometry_name} + COMMAND codexui-nodegraph-thread-pane-ui-test + ) set_tests_properties( ${thread_geometry_name} PROPERTIES - TIMEOUT 15 - LABELS "geometry;qt;thread-pane" + TIMEOUT + 15 + LABELS + "geometry;qt;thread-pane" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_EXPECTED_DPR=${thread_dpr}" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_EXPECTED_DPR=${thread_dpr}" ) endforeach() foreach(thread_rows IN ITEMS 320 1280 10000) @@ -444,45 +429,56 @@ if(BUILD_TESTING) set(thread_benchmark_name "codexui-thread-pane-performance-${thread_rows}-dpr-${thread_dpr_name}" ) - add_test( - NAME ${thread_benchmark_name} - COMMAND codexui-nodegraph-thread-pane-ui-test - ${thread_rows} ${thread_dpr} + add_test(NAME ${thread_benchmark_name} + COMMAND codexui-nodegraph-thread-pane-ui-test + ${thread_rows} ${thread_dpr} ) set_tests_properties( ${thread_benchmark_name} PROPERTIES - TIMEOUT 45 - RUN_SERIAL TRUE - LABELS "performance;qt;thread-pane" + TIMEOUT + 45 + RUN_SERIAL + TRUE + LABELS + "performance;qt;thread-pane" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() endforeach() foreach(thread_dpr IN ITEMS 1 1.25 1.5 2) string(REPLACE "." "_" thread_dpr_name "${thread_dpr}") - set(group_benchmark "codexui-thread-groups-performance-10000-dpr-${thread_dpr_name}") + set(group_benchmark + "codexui-thread-groups-performance-10000-dpr-${thread_dpr_name}" + ) add_test(NAME ${group_benchmark} - COMMAND codexui-nodegraph-thread-pane-ui-test 10000 ${thread_dpr} gates grouped) - set_tests_properties(${group_benchmark} PROPERTIES - TIMEOUT 45 RUN_SERIAL TRUE LABELS "performance;qt;thread-pane" - ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough") + COMMAND codexui-nodegraph-thread-pane-ui-test 10000 + ${thread_dpr} gates grouped + ) + set_tests_properties( + ${group_benchmark} + PROPERTIES + TIMEOUT + 45 + RUN_SERIAL + TRUE + LABELS + "performance;qt;thread-pane" + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${thread_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + ) endforeach() add_executable( - codexui-nodegraph-json-test - tests/codex/nodegraph/NodeGraphJsonTest.cpp + codexui-nodegraph-json-test tests/codex/nodegraph/NodeGraphJsonTest.cpp ) target_compile_features(codexui-nodegraph-json-test PRIVATE cxx_std_20) target_include_directories(codexui-nodegraph-json-test PRIVATE src) target_link_libraries( codexui-nodegraph-json-test - PRIVATE - AISuite::OpenAICodex - codexui-nodegraph-json - codexui-nodegraph + PRIVATE AISuite::OpenAICodex codexui-nodegraph-json codexui-nodegraph ) add_test(NAME codexui-nodegraph-json COMMAND codexui-nodegraph-json-test) set_tests_properties(codexui-nodegraph-json PROPERTIES TIMEOUT 10) @@ -492,23 +488,16 @@ if(BUILD_TESTING) tests/codex/nodegraph/ProtocolBindingsTest.cpp src/codex/InternalProtocolOperations.h ) - target_compile_features( - codexui-protocol-bindings-test PRIVATE cxx_std_20 - ) - target_include_directories( - codexui-protocol-bindings-test PRIVATE src - ) + target_compile_features(codexui-protocol-bindings-test PRIVATE cxx_std_20) + target_include_directories(codexui-protocol-bindings-test PRIVATE src) target_link_libraries( - codexui-protocol-bindings-test - PRIVATE AISuite::OpenAICodex codexui-nodegraph + codexui-protocol-bindings-test PRIVATE AISuite::OpenAICodex + codexui-nodegraph ) - add_test( - NAME codexui-protocol-bindings - COMMAND codexui-protocol-bindings-test - ) - set_tests_properties( - codexui-protocol-bindings PROPERTIES TIMEOUT 10 + add_test(NAME codexui-protocol-bindings + COMMAND codexui-protocol-bindings-test ) + set_tests_properties(codexui-protocol-bindings PROPERTIES TIMEOUT 10) add_executable( codexui-client-runtime-dispatch-test @@ -516,14 +505,10 @@ if(BUILD_TESTING) ) configure_codexui_target(codexui-client-runtime-dispatch-test) configure_codexui_transports(codexui-client-runtime-dispatch-test) - add_test( - NAME codexui-client-runtime-dispatch - COMMAND codexui-client-runtime-dispatch-test - ) - set_tests_properties( - codexui-client-runtime-dispatch - PROPERTIES TIMEOUT 20 + add_test(NAME codexui-client-runtime-dispatch + COMMAND codexui-client-runtime-dispatch-test ) + set_tests_properties(codexui-client-runtime-dispatch PROPERTIES TIMEOUT 20) add_executable( codexui-pending-request-policy-test @@ -532,71 +517,73 @@ if(BUILD_TESTING) target_compile_features( codexui-pending-request-policy-test PRIVATE cxx_std_20 ) - target_include_directories( - codexui-pending-request-policy-test PRIVATE src - ) + target_include_directories(codexui-pending-request-policy-test PRIVATE src) target_link_libraries( codexui-pending-request-policy-test PRIVATE codexui-pending-request-policy ) - add_test( - NAME codexui-pending-request-policy - COMMAND codexui-pending-request-policy-test - ) - set_tests_properties( - codexui-pending-request-policy PROPERTIES TIMEOUT 10 + add_test(NAME codexui-pending-request-policy + COMMAND codexui-pending-request-policy-test ) + set_tests_properties(codexui-pending-request-policy PROPERTIES TIMEOUT 10) qt_add_executable( - codexui-conversation-cards-test - tests/codex/ConversationCardsTest.cpp - ) - target_compile_features( - codexui-conversation-cards-test PRIVATE cxx_std_20 + codexui-conversation-cards-test tests/codex/ConversationCardsTest.cpp ) + target_compile_features(codexui-conversation-cards-test PRIVATE cxx_std_20) target_include_directories(codexui-conversation-cards-test PRIVATE src) - target_compile_definitions(codexui-conversation-cards-test PRIVATE - CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json") - target_link_libraries( + target_compile_definitions( codexui-conversation-cards-test - PRIVATE codexui-conversation-ui codexui-ui-adapter + PRIVATE + CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json" + ) + target_link_libraries( + codexui-conversation-cards-test PRIVATE codexui-conversation-ui + codexui-ui-adapter ) - add_test( - NAME codexui-conversation-cards - COMMAND codexui-conversation-cards-test + add_test(NAME codexui-conversation-cards + COMMAND codexui-conversation-cards-test ) set_tests_properties( - codexui-conversation-cards - PROPERTIES TIMEOUT 35 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexui-conversation-cards PROPERTIES TIMEOUT 35 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) foreach(markdown_dpr IN ITEMS 1 1.25 1.5 2) string(REPLACE "." "_" markdown_dpr_name "${markdown_dpr}") set(markdown_test "codexui-markdown-selection-dpr-${markdown_dpr_name}") add_test(NAME ${markdown_test} COMMAND codexui-conversation-cards-test) - set_tests_properties(${markdown_test} PROPERTIES - TIMEOUT 15 LABELS "conversation;dpr;geometry;qt" - ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${markdown_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_MARKDOWN_SELECTION_TESTS=1") + set_tests_properties( + ${markdown_test} + PROPERTIES + TIMEOUT + 15 + LABELS + "conversation;dpr;geometry;qt" + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${markdown_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_MARKDOWN_SELECTION_TESTS=1" + ) endforeach() foreach(command_output_style IN ITEMS Fusion Breeze) string(TOLOWER "${command_output_style}" command_output_style_name) foreach(command_output_dpr IN ITEMS 1 1.25 1.5 2) - string( - REPLACE "." "_" command_output_dpr_name "${command_output_dpr}" + string(REPLACE "." "_" command_output_dpr_name + "${command_output_dpr}" ) set(command_output_test "codexui-command-output-geometry-${command_output_style_name}-dpr-${command_output_dpr_name}" ) - add_test( - NAME ${command_output_test} - COMMAND codexui-conversation-cards-test + add_test(NAME ${command_output_test} + COMMAND codexui-conversation-cards-test ) set_tests_properties( ${command_output_test} PROPERTIES - TIMEOUT 15 - LABELS "conversation;dpr;geometry;qt" + TIMEOUT + 15 + LABELS + "conversation;dpr;geometry;qt" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_STYLE_OVERRIDE=${command_output_style};QT_SCALE_FACTOR=${command_output_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_SETTLEMENT_TESTS=1" + "QT_QPA_PLATFORM=offscreen;QT_STYLE_OVERRIDE=${command_output_style};QT_SCALE_FACTOR=${command_output_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough;CODEXUI_SETTLEMENT_TESTS=1" ) endforeach() endforeach() @@ -608,21 +595,14 @@ if(BUILD_TESTING) target_compile_features( codexui-conversation-item-model-test PRIVATE cxx_std_20 ) - target_include_directories( - codexui-conversation-item-model-test PRIVATE src - ) + target_include_directories(codexui-conversation-item-model-test PRIVATE src) target_link_libraries( - codexui-conversation-item-model-test - PRIVATE codexui-conversation-ui - ) - add_test( - NAME codexui-conversation-item-model - COMMAND codexui-conversation-item-model-test + codexui-conversation-item-model-test PRIVATE codexui-conversation-ui ) - set_tests_properties( - codexui-conversation-item-model - PROPERTIES TIMEOUT 15 + add_test(NAME codexui-conversation-item-model + COMMAND codexui-conversation-item-model-test ) + set_tests_properties(codexui-conversation-item-model PROPERTIES TIMEOUT 15) qt_add_executable( codexui-conversation-virtualization-test @@ -638,9 +618,8 @@ if(BUILD_TESTING) codexui-conversation-virtualization-test PRIVATE codexui-conversation-ui ) - add_test( - NAME codexui-conversation-virtualization - COMMAND codexui-conversation-virtualization-test + add_test(NAME codexui-conversation-virtualization + COMMAND codexui-conversation-virtualization-test ) set_tests_properties( codexui-conversation-virtualization @@ -653,19 +632,21 @@ if(BUILD_TESTING) set(selection_test "codexui-conversation-selection-focus-${selection_style_name}-dpr-${selection_dpr_name}" ) - add_test( - NAME ${selection_test} - COMMAND codexui-conversation-virtualization-test - --selection-focus + add_test(NAME ${selection_test} + COMMAND codexui-conversation-virtualization-test + --selection-focus ) set_tests_properties( ${selection_test} PROPERTIES - TIMEOUT 10 - SKIP_RETURN_CODE 77 - LABELS "qt;conversation;dpr;accessibility;geometry" + TIMEOUT + 10 + SKIP_RETURN_CODE + 77 + LABELS + "qt;conversation;dpr;accessibility;geometry" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_STYLE_OVERRIDE=${selection_style};QT_SCALE_FACTOR=${selection_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + "QT_QPA_PLATFORM=offscreen;QT_STYLE_OVERRIDE=${selection_style};QT_SCALE_FACTOR=${selection_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() endforeach() @@ -677,12 +658,9 @@ if(BUILD_TESTING) target_compile_features( codexui-conversation-view-benchmark PRIVATE cxx_std_20 ) - target_include_directories( - codexui-conversation-view-benchmark PRIVATE src - ) + target_include_directories(codexui-conversation-view-benchmark PRIVATE src) target_link_libraries( - codexui-conversation-view-benchmark - PRIVATE codexui-conversation-ui + codexui-conversation-view-benchmark PRIVATE codexui-conversation-ui ) foreach(benchmark_rows IN ITEMS 320 1280 10000) foreach(benchmark_dpr IN ITEMS 1 1.25 1.5 2) @@ -690,19 +668,21 @@ if(BUILD_TESTING) set(benchmark_name "codexui-conversation-performance-${benchmark_rows}-dpr-${benchmark_dpr_name}" ) - add_test( - NAME ${benchmark_name} - COMMAND codexui-conversation-view-benchmark - ${benchmark_rows} ${benchmark_dpr} + add_test(NAME ${benchmark_name} + COMMAND codexui-conversation-view-benchmark + ${benchmark_rows} ${benchmark_dpr} ) set_tests_properties( ${benchmark_name} PROPERTIES - TIMEOUT 45 - RUN_SERIAL TRUE - LABELS "performance;qt;conversation" + TIMEOUT + 45 + RUN_SERIAL + TRUE + LABELS + "performance;qt;conversation" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${benchmark_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${benchmark_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() endforeach() @@ -721,26 +701,27 @@ if(BUILD_TESTING) ) set_tests_properties( codexui-prompt-spelling-dpr-${spelling_dpr_name} - PROPERTIES TIMEOUT 30 ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${spelling_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + PROPERTIES + TIMEOUT + 30 + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${spelling_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() foreach(spelling_state IN ITEMS unavailable missing-language) add_test(NAME codexui-prompt-spelling-${spelling_state} COMMAND codexui-prompt-spelling-test --${spelling_state} ) - set_tests_properties(codexui-prompt-spelling-${spelling_state} - PROPERTIES TIMEOUT 30 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + set_tests_properties( + codexui-prompt-spelling-${spelling_state} + PROPERTIES TIMEOUT 30 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" ) endforeach() qt_add_executable( - codexui-application-layout-test - tests/codex/EstablishedUiUxTest.cpp - ) - target_compile_features( - codexui-application-layout-test PRIVATE cxx_std_20 + codexui-application-layout-test tests/codex/EstablishedUiUxTest.cpp ) + target_compile_features(codexui-application-layout-test PRIVATE cxx_std_20) target_compile_definitions( codexui-application-layout-test PRIVATE @@ -749,141 +730,145 @@ if(BUILD_TESTING) target_include_directories(codexui-application-layout-test PRIVATE src) target_link_libraries( codexui-application-layout-test - PRIVATE - AISuite::OpenAICodex - codexui-conversation-ui - codexui-diff-viewer - codexui-middle-ui - codexui-shell-ui - codexui-conversation-height-index - codexui-nodegraph - codexui-pending-request-policy - codexui-turn-settings-policy - PkgConfig::LIBGIT2 - Qt6::Widgets - Qt6::Network - ) - add_test( - NAME codexui-application-layout - COMMAND codexui-application-layout-test + PRIVATE AISuite::OpenAICodex + codexui-conversation-ui + codexui-diff-viewer + codexui-middle-ui + codexui-shell-ui + codexui-conversation-height-index + codexui-nodegraph + codexui-pending-request-policy + codexui-turn-settings-policy + PkgConfig::LIBGIT2 + Qt6::Widgets + Qt6::Network + ) + add_test(NAME codexui-application-layout + COMMAND codexui-application-layout-test ) set_tests_properties( - codexui-application-layout - PROPERTIES TIMEOUT 15 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexui-application-layout PROPERTIES TIMEOUT 15 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) - add_test( - NAME codexui-middle-region-wheel-performance - COMMAND codexui-application-layout-test --wheel-routing-performance + add_test(NAME codexui-middle-region-wheel-performance + COMMAND codexui-application-layout-test + --wheel-routing-performance ) set_tests_properties( codexui-middle-region-wheel-performance - PROPERTIES - TIMEOUT 15 - RUN_SERIAL TRUE - LABELS "performance;qt;middle-region" - ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + PROPERTIES TIMEOUT + 15 + RUN_SERIAL + TRUE + LABELS + "performance;qt;middle-region" + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) qt_add_executable( - codexui-inspector-graph-test - tests/codex/NodeGraphInspectorUiTest.cpp + codexui-inspector-graph-test tests/codex/NodeGraphInspectorUiTest.cpp ) qt_add_executable( - codexui-timestamp-presentation-test tests/codex/TimestampPresentationTest.cpp + codexui-timestamp-presentation-test + tests/codex/TimestampPresentationTest.cpp ) target_link_libraries( codexui-timestamp-presentation-test PRIVATE codexui-middle-ui ) - target_compile_definitions(codexui-timestamp-presentation-test PRIVATE - CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json") + target_compile_definitions( + codexui-timestamp-presentation-test + PRIVATE + CODEXUI_PRESENTATION_CONTRACT_PATH="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/frontend-presentation.json" + ) foreach(timing_dpr IN ITEMS 1 1.25 1.5 2) string(REPLACE "." "_" timing_dpr_name "${timing_dpr}") - add_test( - NAME codexui-timestamps-dpr-${timing_dpr_name} - COMMAND codexui-timestamp-presentation-test + add_test(NAME codexui-timestamps-dpr-${timing_dpr_name} + COMMAND codexui-timestamp-presentation-test ) set_tests_properties( - codexui-timestamps-dpr-${timing_dpr_name} PROPERTIES TIMEOUT 30 - ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${timing_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + codexui-timestamps-dpr-${timing_dpr_name} + PROPERTIES + TIMEOUT + 30 + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${timing_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() target_compile_features(codexui-inspector-graph-test PRIVATE cxx_std_20) target_include_directories(codexui-inspector-graph-test PRIVATE src) target_link_libraries( codexui-inspector-graph-test - PRIVATE - codexui-ui-adapter - codexui-diff-viewer - codexui-middle-ui - codexui-nodegraph-json - codexui-conversation-ui - codexui-conversation-height-index - codexui-nodegraph - codexui-pending-request-policy - PkgConfig::LIBGIT2 - Qt6::Widgets - ) - add_test( - NAME codexui-inspector-graph - COMMAND codexui-inspector-graph-test - ) + PRIVATE codexui-ui-adapter + codexui-diff-viewer + codexui-middle-ui + codexui-nodegraph-json + codexui-conversation-ui + codexui-conversation-height-index + codexui-nodegraph + codexui-pending-request-policy + PkgConfig::LIBGIT2 + Qt6::Widgets + ) + add_test(NAME codexui-inspector-graph COMMAND codexui-inspector-graph-test) set_tests_properties( - codexui-inspector-graph - PROPERTIES TIMEOUT 15 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexui-inspector-graph PROPERTIES TIMEOUT 15 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) foreach(inspector_dpr IN ITEMS 1 1.25 1.5 2) string(REPLACE "." "_" inspector_dpr_name "${inspector_dpr}") set(inspector_benchmark_name "codexui-inspector-performance-10000-dpr-${inspector_dpr_name}" ) - add_test( - NAME ${inspector_benchmark_name} - COMMAND codexui-inspector-graph-test --performance 10000 - ${inspector_dpr} + add_test(NAME ${inspector_benchmark_name} + COMMAND codexui-inspector-graph-test --performance 10000 + ${inspector_dpr} ) set_tests_properties( ${inspector_benchmark_name} PROPERTIES - TIMEOUT 60 - RUN_SERIAL TRUE - LABELS "performance;qt;inspector" + TIMEOUT + 60 + RUN_SERIAL + TRUE + LABELS + "performance;qt;inspector" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${inspector_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${inspector_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) set(inspector_geometry_name "codexui-inspector-geometry-dpr-${inspector_dpr_name}" ) - add_test( - NAME ${inspector_geometry_name} - COMMAND codexui-inspector-graph-test --geometry ${inspector_dpr} + add_test(NAME ${inspector_geometry_name} + COMMAND codexui-inspector-graph-test --geometry + ${inspector_dpr} ) set_tests_properties( ${inspector_geometry_name} PROPERTIES - TIMEOUT 15 - LABELS "geometry;qt;inspector" + TIMEOUT + 15 + LABELS + "geometry;qt;inspector" ENVIRONMENT - "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${inspector_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" + "QT_QPA_PLATFORM=offscreen;QT_SCALE_FACTOR=${inspector_dpr};QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough" ) endforeach() qt_add_executable( - codexui-git-changes-live-test - tests/codex/GitChangesLiveTest.cpp + codexui-git-changes-live-test tests/codex/GitChangesLiveTest.cpp ) target_compile_features(codexui-git-changes-live-test PRIVATE cxx_std_20) target_include_directories(codexui-git-changes-live-test PRIVATE src) target_link_libraries( - codexui-git-changes-live-test - PRIVATE codexui-diff-viewer + codexui-git-changes-live-test PRIVATE codexui-diff-viewer ) - add_test( - NAME codexui-git-changes-live - COMMAND codexui-git-changes-live-test + add_test(NAME codexui-git-changes-live + COMMAND codexui-git-changes-live-test ) set_tests_properties( - codexui-git-changes-live - PROPERTIES TIMEOUT 30 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexui-git-changes-live PROPERTIES TIMEOUT 30 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) qt_add_executable( @@ -911,18 +896,16 @@ if(BUILD_TESTING) endforeach() qt_add_executable( - codexui-shell-integration-test - tests/codex/ShellIntegrationTest.cpp + codexui-shell-integration-test tests/codex/ShellIntegrationTest.cpp ) configure_codexui_target(codexui-shell-integration-test) configure_codexui_transports(codexui-shell-integration-test) - add_test( - NAME codexui-shell-integration - COMMAND codexui-shell-integration-test + add_test(NAME codexui-shell-integration + COMMAND codexui-shell-integration-test ) set_tests_properties( - codexui-shell-integration - PROPERTIES TIMEOUT 45 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexui-shell-integration PROPERTIES TIMEOUT 45 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen" ) endif() @@ -932,11 +915,10 @@ install( RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} BUNDLE DESTINATION . ) -install( - FILES resources/icons/codex-ui.svg - DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/apps +install(FILES resources/icons/codex-ui.svg + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/apps ) -install( - FILES resources/applications/codex-ui.desktop - DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications +install(FILES resources/applications/codex-ui.desktop + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications ) +include(Packing) diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/ci/package/native.sh b/ci/package/native.sh new file mode 100644 index 0000000..b2ac01c --- /dev/null +++ b/ci/package/native.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Dependency installation belongs to trusted preparation. +set -eu +: "${SOURCE_DIR:?}" "${TARGET_JSON:?}" "${OUTPUT_DIR:?}" +format=$(python3 -c 'import json,os; print(json.load(open(os.environ["TARGET_JSON"]))["build"]["format"])') +if [ "$format" = deb ]; then + libdir="lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)" +else + libdir=lib64 + if [ -f /opt/rh/gcc-toolset-14/enable ]; then + . /opt/rh/gcc-toolset-14/enable + fi +fi +build=/work/build-product +cmake -S "$SOURCE_DIR" -B "$build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr \ + -DCMAKE_INSTALL_LIBDIR="$libdir" -DBUILD_TESTING=ON -DCODEXUI_INSTALL_WEB=OFF +cmake --build "$build" --parallel "$(nproc)" +xvfb-run -a env QT_QPA_PLATFORM=offscreen CODEXUI_TIMING_POLICY=report ctest --test-dir "$build" \ + --parallel "$(nproc)" --output-on-failure --output-junit core-ci-tests.xml +python3 /tool/native_container.py --package "$build" diff --git a/ci/packages.json b/ci/packages.json new file mode 100644 index 0000000..ea814cb --- /dev/null +++ b/ci/packages.json @@ -0,0 +1,118 @@ +{ + "schema": 1, + "title": "CodexUI", + "package": "codexui", + "depends_on": [ + "aisuite" + ], + "build": { + "native": "ci/package/native.sh" + }, + "matrix": [ + { + "id": "debian-trixie-amd64" + }, + { + "id": "debian-trixie-arm64" + }, + { + "id": "debian-trixie-armhf" + }, + { + "id": "debian-trixie-riscv64" + }, + { + "id": "debian-forky-amd64" + }, + { + "id": "debian-forky-arm64" + }, + { + "id": "debian-forky-armhf" + }, + { + "id": "debian-forky-riscv64" + }, + { + "id": "debian-sid-amd64" + }, + { + "id": "debian-sid-arm64" + }, + { + "id": "debian-sid-armhf" + }, + { + "id": "debian-sid-riscv64" + }, + { + "id": "ubuntu-resolute-amd64" + }, + { + "id": "ubuntu-resolute-arm64" + }, + { + "id": "rocky-10-x86_64" + }, + { + "id": "rocky-10-aarch64" + }, + { + "id": "fedora-43-x86_64" + }, + { + "id": "fedora-43-aarch64" + }, + { + "id": "fedora-44-x86_64" + }, + { + "id": "fedora-44-aarch64" + }, + { + "id": "raspberrypios-trixie-arm64" + } + ], + "build_dependencies": { + "deb": [ + "cmake", + "ninja-build", + "libbluetooth-dev", + "libmagic-dev", + "libmariadb-dev", + "libssl-dev", + "openssl", + "libncurses-dev", + "nlohmann-json3-dev", + "libsqlite3-dev", + "qt6-base-dev", + "libkf6sonnet-dev", + "sonnet6-plugins", + "hunspell-en-us", + "hunspell-de-at", + "libgit2-dev", + "xvfb", + "xauth" + ], + "rpm": [ + "cmake", + "ninja-build", + "bluez-libs-devel", + "file-devel", + "mariadb-connector-c-devel", + "openssl-devel", + "openssl", + "ncurses-devel", + "json-devel", + "sqlite-devel", + "qt6-qtbase-devel", + "kf6-sonnet-devel", + "kf6-sonnet-hunspell", + "hunspell-en-US", + "hunspell-de", + "libgit2-devel", + "xorg-x11-server-Xvfb", + "xorg-x11-xauth" + ] + } +} diff --git a/cmake/PackageConfig.cmake b/cmake/PackageConfig.cmake new file mode 100644 index 0000000..43ffa4d --- /dev/null +++ b/cmake/PackageConfig.cmake @@ -0,0 +1,4 @@ +file(MAKE_DIRECTORY "${CPACK_OUTPUT_FILE_PREFIX}") +file(WRITE "${CPACK_OUTPUT_FILE_PREFIX}/codexui.packages" + "${CPACK_PACKAGE_NAME}\n" +) diff --git a/cmake/Packing.cmake b/cmake/Packing.cmake new file mode 100644 index 0000000..1b7cb12 --- /dev/null +++ b/cmake/Packing.cmake @@ -0,0 +1,25 @@ +set(CPACK_PACKAGE_NAME "codexui") +set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") +set(CPACK_PACKAGE_VENDOR "SNodeC") +set(CPACK_PACKAGE_CONTACT "Volker Christian ") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY + "Native Codex desktop and profile manager" +) +set(CPACK_VERBATIM_VARIABLES YES) +set(CPACK_STRIP_FILES YES) +set(CPACK_OUTPUT_FILE_PREFIX "${CMAKE_BINARY_DIR}/_packages") +set(CPACK_PACKAGING_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") +set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) +set(CPACK_RPM_FILE_NAME RPM-DEFAULT) +set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) +set(CPACK_DEBIAN_PACKAGE_DEPENDS "aisuite, sonnet6-plugins") +set(CPACK_RPM_PACKAGE_REQUIRES "aisuite, kf6-sonnet-hunspell") +set(CPACK_RPM_PACKAGE_LICENSE "MIT AND LGPL-3.0-or-later") +set(CPACK_RPM_PACKAGE_RELEASE 1) +set(CPACK_RPM_PACKAGE_RELEASE_DIST OFF) +set(CPACK_RPM_PACKAGE_RELOCATABLE OFF) +set(CPACK_SOURCE_IGNORE_FILES + "/build[^/]*/;/checkouts/;/.git/;/.qtcreator/;/.local-credentials/;/secrets/;/web/(node_modules|dist|app-dist)/;~$" +) +set(CPACK_PROJECT_CONFIG_FILE "${CMAKE_CURRENT_LIST_DIR}/PackageConfig.cmake") +include(CPack) diff --git a/cmake/Version.cmake b/cmake/Version.cmake new file mode 100644 index 0000000..9517a0f --- /dev/null +++ b/cmake/Version.cmake @@ -0,0 +1,12 @@ +set_property( + DIRECTORY + APPEND + PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/../VERSION" +) +file(READ "${CMAKE_CURRENT_LIST_DIR}/../VERSION" RELEASE_VERSION) +string(STRIP "${RELEASE_VERSION}" RELEASE_VERSION) +if(NOT RELEASE_VERSION MATCHES + "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$" +) + message(FATAL_ERROR "VERSION must contain MAJOR.MINOR.PATCH") +endif() diff --git a/docs/qualification/README.md b/docs/qualification/README.md index 648b062..8040d2e 100644 --- a/docs/qualification/README.md +++ b/docs/qualification/README.md @@ -11,6 +11,7 @@ The native interactive test suite and its recorded execution results. ## Sections +- [Native package target availability](package-targets.md#banner) - [Native qualification execution record — 2026-09-27](native-results-2026-09-27.md#banner) - [CodexUI canonical interactive Xvfb test suite](native-test-suite.md#banner) - [CodexManager implementation qualification](codexmanager-2026-10-16.md) diff --git a/docs/qualification/package-targets.md b/docs/qualification/package-targets.md new file mode 100644 index 0000000..62236e0 --- /dev/null +++ b/docs/qualification/package-targets.md @@ -0,0 +1,60 @@ + + +

CodexUI — Qualification

+

Up to QualificationVolker Christian accountSNode.C organizationCodexUI repository

+ + +# Native package targets + +Index audit: 2026-11-11. The allowed starting set is exactly the 26 native targets from SNodeC/snode.c-idp at `f0cb4d44a8da33f68ab56f2fedf24bdb0ecef4c8`. Requirements are Qt6 Widgets and Network ≥6.6, KF6Sonnet ≥6.13, and libgit2. Versions below identify available upstream versions; distribution revisions and security suffixes are omitted. + +| Target | Qt6 | KF6Sonnet | libgit2 | Included | +| --- | --- | --- | --- | --- | +| debian-trixie-amd64 | 6.8.2 | 6.13.0 | 1.9.0 | yes | +| debian-trixie-arm64 | 6.8.2 | 6.13.0 | 1.9.0 | yes | +| debian-trixie-armhf | 6.8.2 | 6.13.0 | 1.9.0 | yes | +| debian-trixie-riscv64 | 6.8.2 | 6.13.0 | 1.9.0 | yes | +| debian-forky-amd64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-forky-arm64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-forky-armhf | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-forky-riscv64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-sid-amd64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-sid-arm64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-sid-armhf | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| debian-sid-riscv64 | 6.11.2 | 6.30.0 | 1.9.7 | yes | +| ubuntu-noble-amd64 | 6.4.2 (<6.6) | unavailable | 1.7.2 | no | +| ubuntu-noble-arm64 | 6.4.2 (<6.6) | unavailable | 1.7.2 | no | +| ubuntu-resolute-amd64 | 6.10.2 | 6.24.0 | 1.9.1 | yes | +| ubuntu-resolute-arm64 | 6.10.2 | 6.24.0 | 1.9.1 | yes | +| rocky-9-x86_64 | 6.10.3 (EPEL) | unavailable | 1.7.2 (EPEL) | no | +| rocky-9-aarch64 | 6.10.3 (EPEL) | unavailable | 1.7.2 (EPEL) | no | +| rocky-10-x86_64 | 6.10.1 | 6.30.0 (EPEL) | 1.7.2 (EPEL) | yes | +| rocky-10-aarch64 | 6.10.1 | 6.30.0 (EPEL) | 1.7.2 (EPEL) | yes | +| fedora-43-x86_64 | 6.10.3 | 6.30.0 | 1.9.7 | yes | +| fedora-43-aarch64 | 6.10.3 | 6.30.0 | 1.9.7 | yes | +| fedora-44-x86_64 | 6.11.2 | 6.31.0 | 1.9.7 | yes | +| fedora-44-aarch64 | 6.11.2 | 6.31.0 | 1.9.7 | yes | +| raspberrypios-bookworm-arm64 | 6.4.2 (<6.6) | unavailable | 1.5.1 | no | +| raspberrypios-trixie-arm64 | 6.8.2 | 6.13.0 | 1.9.0 | yes | + +Decision: include the 21 qualifying targets and exclude both Ubuntu noble targets, both Rocky 9 targets and Raspberry Pi OS bookworm arm64 because required distribution packages do not meet the stated minimums. No OpenWrt target is declared. A failed target does not block enrollment of the others. + +The existing trusted preparation in DistributionPackages `coreci/build.py` already installs `epel-release` and enables CRB for Rocky. This audit uses only those existing repositories, plus each distribution's normally enabled repositories and updates. It adds no repository or dependency bootstrap to the product hook. + +## Official index evidence + +- Debian publishes architecture lists and versions for [Qt6](https://packages.debian.org/search?keywords=qt6-base-dev&searchon=names&suite=all§ion=all), [KF6 Sonnet](https://packages.debian.org/search?keywords=libkf6sonnet-dev&searchon=names&suite=all§ion=all), and [libgit2](https://packages.debian.org/search?keywords=libgit2-dev&searchon=names&suite=all§ion=all). The four declared architectures are listed for trixie, forky and sid. A direct trixie `apt-cache policy` check confirmed Qt 6.8.2, Sonnet 6.13.0 and libgit2 1.9.0. +- Ubuntu's official indexes list [Qt6](https://packages.ubuntu.com/search?keywords=qt6-base-dev&searchon=names&suite=all§ion=all), [KF6 Sonnet](https://packages.ubuntu.com/search?keywords=libkf6sonnet-dev&searchon=names&suite=all§ion=all), and [libgit2](https://packages.ubuntu.com/search?keywords=libgit2-dev&searchon=names&suite=all§ion=all). Noble has Qt 6.4.2 and no KF6 Sonnet package; resolute lists qualifying amd64 and arm64 packages. +- Fedora's official package indexes list [Qt6](https://packages.fedoraproject.org/pkgs/qt6-qtbase/qt6-qtbase-devel/), [Sonnet](https://packages.fedoraproject.org/pkgs/kf6-sonnet/kf6-sonnet-devel/) and [libgit2](https://packages.fedoraproject.org/pkgs/libgit2/libgit2-devel/). Direct `dnf repoquery` checks for releases 43 and 44 confirmed the table for x86_64 and aarch64. +- Rocky base repositories are at [Rocky 9](https://dl.rockylinux.org/pub/rocky/9/) and [Rocky 10](https://dl.rockylinux.org/pub/rocky/10/). The same EPEL package indexes above document supplemental packages. Direct `dnf repoquery` checks after the existing EPEL/CRB preparation confirmed both architectures: Rocky 9 provides Qt/libgit2 but no `kf6-sonnet-devel`; Rocky 10 provides all three. +- Raspberry Pi OS arm64 uses Debian packages plus the official Raspberry Pi archive. The [bookworm arm64 index](https://archive.raspberrypi.com/debian/dists/bookworm/main/binary-arm64/Packages.gz) and [trixie arm64 index](https://archive.raspberrypi.com/debian/dists/trixie/main/binary-arm64/Packages.gz) contain no overrides for these three development packages; the Debian suite versions therefore govern this selection. + +The RPM checks used the official image's repository configuration and `repoquery --latest-limit 1`; `--forcearch=aarch64` selected ARM metadata without running ARM binaries. Availability is an index audit, not a claim that all 21 targets have completed package builds. + +## Package scope + +Decision: the package follows the established native verification configuration with `CODEXUI_INSTALL_WEB=OFF`. It includes `codex-ui`, `codex-manager`, both desktop files and icons, and the manager's installed web assets. The separate CodexWebUI production artifact retains its existing release workflow; it is not silently rebuilt with distribution Node versions below that artifact's declared Node ≥22 requirement. + +Decision: `VERSION` supplies the requested 0.1.0 CMake version directly, rather than deriving it from old release tags. No tags are created, moved or deleted. + +GUI package-hook tests run under Xvfb with `QT_QPA_PLATFORM=offscreen`. Packaging adds no alternate UI renderer, state owner or application configuration store. From 23a835a4f970213ae14d72c943d5eab1d89dde12 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:06:34 +0100 Subject: [PATCH 3/9] Install the styles required by the declared GUI qualification matrix --- .snodec/repo.yml | 1 + ci/packages.json | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.snodec/repo.yml b/.snodec/repo.yml index 946c07b..65e4d8e 100644 --- a/.snodec/repo.yml +++ b/.snodec/repo.yml @@ -6,6 +6,7 @@ ci: - qt6-base-dev - libkf6sonnet-dev - sonnet6-plugins + - kde-style-breeze - hunspell-en-us - hunspell-de-at - xvfb diff --git a/ci/packages.json b/ci/packages.json index ea814cb..abe83e2 100644 --- a/ci/packages.json +++ b/ci/packages.json @@ -88,6 +88,7 @@ "qt6-base-dev", "libkf6sonnet-dev", "sonnet6-plugins", + "kde-style-breeze", "hunspell-en-us", "hunspell-de-at", "libgit2-dev", @@ -108,6 +109,7 @@ "qt6-qtbase-devel", "kf6-sonnet-devel", "kf6-sonnet-hunspell", + "plasma-breeze-qt6", "hunspell-en-US", "hunspell-de", "libgit2-devel", From 826cbd2af2b0c579a36415a9880589c9eb17c689 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:14:32 +0100 Subject: [PATCH 4/9] Measure the status disc independently of later child-row chevrons --- tests/codex/NodeGraphThreadPaneUiTest.cpp | 7399 ++++++++++----------- 1 file changed, 3522 insertions(+), 3877 deletions(-) diff --git a/tests/codex/NodeGraphThreadPaneUiTest.cpp b/tests/codex/NodeGraphThreadPaneUiTest.cpp index f40b5f0..944f3a2 100644 --- a/tests/codex/NodeGraphThreadPaneUiTest.cpp +++ b/tests/codex/NodeGraphThreadPaneUiTest.cpp @@ -58,3999 +58,3644 @@ #include namespace codexui::codex { -namespace { - -ui::ThreadListRow localDraft(std::string id, std::string key, - std::string title, std::string cwd, - std::string project = {}, std::string section = {}) { - ui::ThreadListRow row; - row.id = std::move(id); - row.presentationKey = std::move(key); - row.title = std::move(title); - row.cwd = std::move(cwd); - row.projectId = std::move(project); - row.sectionId = std::move(section); - return row; -} + namespace { + + ui::ThreadListRow localDraft( + std::string id, std::string key, std::string title, std::string cwd, std::string project = {}, std::string section = {}) { + ui::ThreadListRow row; + row.id = std::move(id); + row.presentationKey = std::move(key); + row.title = std::move(title); + row.cwd = std::move(cwd); + row.projectId = std::move(project); + row.sectionId = std::move(section); + return row; + } -class AnimationDurationStyle final : public QProxyStyle { -public: - explicit AnimationDurationStyle(int duration) : duration_(duration) {} - AnimationDurationStyle(QStyle *base, int duration) - : QProxyStyle(base), duration_(duration) {} - - int styleHint(StyleHint hint, const QStyleOption *option = nullptr, - const QWidget *widget = nullptr, - QStyleHintReturn *returnData = nullptr) const override { - return hint == SH_Widget_Animation_Duration - ? duration_ - : QProxyStyle::styleHint(hint, option, widget, returnData); - } - -private: - int duration_; -}; - -void installAnimationDurationStyle(QWidget &widget, int duration) { - QStyle *base = widget.style(); - if (base && base->parent() == &widget) - base->setParent(nullptr); - else - base = nullptr; - auto *style = new AnimationDurationStyle(base, duration); - style->setParent(&widget); - widget.setStyle(style); -} + class AnimationDurationStyle final : public QProxyStyle { + public: + explicit AnimationDurationStyle(int duration) + : duration_(duration) { + } + AnimationDurationStyle(QStyle* base, int duration) + : QProxyStyle(base) + , duration_(duration) { + } -bool require(bool condition, const char *message) { - if (condition) - return true; - std::cerr << message << '\n'; - return false; -} + int styleHint(StyleHint hint, + const QStyleOption* option = nullptr, + const QWidget* widget = nullptr, + QStyleHintReturn* returnData = nullptr) const override { + return hint == SH_Widget_Animation_Duration ? duration_ : QProxyStyle::styleHint(hint, option, widget, returnData); + } -QTreeWidget *threadTree(QWidget &owner) { - return owner.findChild(QStringLiteral("threadList")); -} + private: + int duration_; + }; -void click(QWidget* widget, QPoint position, Qt::MouseButton button = Qt::LeftButton) { - if (auto* child = widget->childAt(position)) { - position = child->mapFrom(widget, position); - widget = child; - } - QMouseEvent press( - QEvent::MouseButtonPress, QPointF(position), QPointF(position), widget->mapToGlobal(position), button, button, Qt::NoModifier); - QApplication::sendEvent(widget, &press); - QMouseEvent release(QEvent::MouseButtonRelease, - QPointF(position), - QPointF(position), - widget->mapToGlobal(position), - button, - Qt::NoButton, - Qt::NoModifier); - QApplication::sendEvent(widget, &release); - QApplication::processEvents(); -} + void installAnimationDurationStyle(QWidget& widget, int duration) { + QStyle* base = widget.style(); + if (base && base->parent() == &widget) + base->setParent(nullptr); + else + base = nullptr; + auto* style = new AnimationDurationStyle(base, duration); + style->setParent(&widget); + widget.setStyle(style); + } -QTreeWidgetItem *threadItem(QTreeWidget *tree, std::string_view id, - QTreeWidgetItem *parent = nullptr) { - const int count = parent ? parent->childCount() - : tree ? tree->topLevelItemCount() - : 0; - for (int index = 0; index < count; ++index) { - QTreeWidgetItem *item = - parent ? parent->child(index) : tree->topLevelItem(index); - if (item->data(0, Qt::UserRole).toString() == - QString::fromUtf8(id.data(), static_cast(id.size()))) - return item; - if (QTreeWidgetItem *found = threadItem(tree, id, item)) - return found; - } - return nullptr; -} + bool require(bool condition, const char* message) { + if (condition) + return true; + std::cerr << message << '\n'; + return false; + } -QAccessibleInterface *threadAccessible(QTreeWidget *tree, - QTreeWidgetItem *item) { - if (!tree || !item) - return nullptr; - std::vector path; - for (QTreeWidgetItem *current = item; current; current = current->parent()) - path.push_back(current->parent() ? current->parent()->indexOfChild(current) - : tree->indexOfTopLevelItem(current)); - QAccessibleInterface *accessible = - QAccessible::queryAccessibleInterface(tree); - for (auto index = path.rbegin(); accessible && index != path.rend(); ++index) - accessible = accessible->child(*index); - return accessible; -} + QTreeWidget* threadTree(QWidget& owner) { + return owner.findChild(QStringLiteral("threadList")); + } -bool groupLabelsIdentifyDestinationsWithoutRoutineIds() { - using namespace nodegraph; - NodeGraph graph; - NodeRef thread; - { - auto write = graph.write(); - const auto entity = [&](NodeKind kind, std::string id, - nlohmann::json fields) { - NodeState state; - state.fields = *valueFromJson(fields).asObject(); - return write.upsert({kind, std::move(id)}, std::move(state)); - }; - const auto connection = - entity(NodeKind::Connection, "connection", - {{"providerState", "ready"}, {"role", "controller"}}); - write.setStatus(connection, NodeStatus::Connected); - for (const auto method : {"project/list", "threadSection/list"}) - entity(NodeKind::Catalog, - threadBrowserKey(method, nlohmann::json::object()), - {{"loaded", true}}); - const auto project = [&](const char *id, const char *name, - std::initializer_list paths) { - nlohmann::json roots = nlohmann::json::array(); - for (const auto path : paths) - roots.push_back({{"path", path}}); - return entity(NodeKind::Project, id, - {{"id", id}, {"name", name}, {"roots", roots}}); - }; - project("unique-project-id", "Research & Design", {"/workspace/design"}); - project("book-first-id", "Book", {"/home/work/book"}); - project("book-second-id", "Book", {"/home/private/book"}); - project("multi-first-id", "Multi", {"/work/shared", "/work/frontend"}); - project("multi-second-id", "Multi", {"/work/shared", "/work/backend"}); - project("shared-root-1111111", "Same", {"/same/root"}); - project("shared-root-2111111", "Same", {"/same/root"}); - project("rootless-aaaaaa", "Rootless", {}); - project("rootless-bbbbbb", "Rootless", {}); - project("windows-first-id", "Windows", {"C:\\work\\book"}); - project("windows-second-id", "Windows", {"D:\\work\\book"}); - project("literal-name-id", "Book — work/book", {}); - entity(NodeKind::ThreadSection, "section-one-1111111", {{"name", "Review"}, {"appearance", {{"icon", "star"}, {"color", "purple"}}}}); - entity(NodeKind::ThreadSection, "section-two-2111111", - {{"name", "Review"}}); - entity(NodeKind::ThreadSection, "unique-section-id", {{"name", "Ready"}}); - thread = - entity(NodeKind::Thread, "label-thread", {{"name", "Label selection"}}); - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.resize(620, 900); - std::vector> mutations; - middle::ThreadPane::Actions actions; - actions.manage = [&](auto kind, nlohmann::json params) { - mutations.emplace_back(kind, std::move(params)); - }; - pane.setActions(std::move(actions)); - auto snapshot = adapter.threads(thread, nullptr, &pane.browserOptions()); - if (!require(snapshot.has_value(), "label fixture projects successfully")) - return false; - bool passed = true; - const auto label = [&](const auto &groups, const char *id) { - const auto found = std::ranges::find(groups, id, &ui::ThreadGroup::id); - return found == groups.end() ? std::string{} : found->label; - }; - passed &= require( - label(snapshot->projects, "unique-project-id") == "Research & Design" && - label(snapshot->sections, "unique-section-id") == "Ready", - "unique names carry no routine IDs"); - passed &= require(label(snapshot->projects, "book-second-id") == - "Book — private/book" && - label(snapshot->projects, "multi-first-id") == - "Multi — shared, frontend" && - label(snapshot->projects, "multi-second-id") == - "Multi — shared, backend", - "duplicate project names use distinguishing folder " - "suffixes across all roots"); - passed &= require( - label(snapshot->projects, "windows-first-id").find("C:/work/book") != - std::string::npos && - label(snapshot->projects, "windows-second-id").find("D:/work/book") != - std::string::npos, - "remote Windows paths retain their distinguishing drive"); - passed &= require( - label(snapshot->sections, "section-one-1111111") == "Review · 1111111" && - label(snapshot->sections, "section-two-2111111") == - "Review · 2111111", - "short ID suffixes expand until colliding sections are distinguishable"); - for (const auto *groups : {&snapshot->projects, &snapshot->sections}) { - std::unordered_set labels; - for (const auto &group : *groups) { - passed &= require(labels.insert(group.label).second, - "all displayed choices are distinct, including " - "literal-label and short-ID collisions"); - passed &= require(group.label.find(group.id) == std::string::npos, - "full IDs are absent from routine labels"); - } - } - pane.refresh(*snapshot); - pane.show(); - QApplication::processEvents(); - auto *tree = threadTree(pane); - const auto openMenu = [&](QTreeWidgetItem *item) -> QMenu * { - tree->scrollToItem(item); - QApplication::processEvents(); - QMetaObject::invokeMethod( - tree, "customContextMenuRequested", Qt::DirectConnection, - Q_ARG(QPoint, tree->visualItemRect(item).center())); - QApplication::processEvents(); - for (auto *menu : tree->findChildren()) - if (menu->isVisible()) - return menu; - return nullptr; - }; - QPointer menu = openMenu(threadItem(tree, "label-thread")); - passed &= require(menu != nullptr, "actual thread context menu opens"); - if (menu) { - for (auto *action : menu->actions()) { - const bool project = action->text() == "Assign project"; - if (!project && action->text() != "Assign section") - continue; - const auto &groups = project ? snapshot->projects : snapshot->sections; - auto *submenu = action->menu(); - passed &= require(submenu && submenu->actions().size() == groups.size() + 2, "assignment menus retain every destination"); - if (!submenu || submenu->actions().size() != groups.size() + 2) - continue; - passed &= require(submenu->actions().at(0)->text() == (project ? "New project…" : "New section…") && - submenu->actions().at(1)->isSeparator(), - "creation is first, separated from existing destinations"); - for (std::size_t i = 0; i < groups.size(); ++i) { - auto* entry = submenu->actions().at(i + 2); - const auto& group = groups[i]; - passed &= require(entry->text() == QString::fromStdString(group.label).replace("&", "&&"), - "menu uses the same label as the sidebar and preserves " - "literal ampersands"); - entry->trigger(); - passed &= require(!mutations.empty() && - mutations.back().first == (project ? RuntimeActionKind::AssignProject : RuntimeActionKind::AssignSection) && - mutations.back().second.value(project ? "projectId" : "sectionId", "") == group.id, - "disambiguated actions still target the full canonical ID"); - } - } - if (menu) - menu->close(); - } - for (bool project : {true, false}) { - for (bool cancel : {true, false}) { - menu = openMenu(threadItem(tree, "label-thread")); - QAction* create = nullptr; - if (menu) { - for (auto* action : menu->actions()) { - if (action->text() == (project ? "Assign project" : "Assign section")) { - create = action->menu()->actions().front(); - } - } - } - passed &= require(create != nullptr, "fresh creation action is reachable"); - const auto count = mutations.size(); - if (create) { - QTimer::singleShot(0, &pane, [&pane, cancel, &passed] { - auto* dialog = pane.findChild("threadGroupDialog"); - passed &= require(dialog != nullptr, "assignment opens the existing creation dialog"); - if (dialog) { - if (cancel) { - dialog->reject(); - } else { - dialog->findChild("groupName")->setText("Created from assignment"); - dialog->findChild()->button(QDialogButtonBox::Save)->click(); - } - } - }); - create->trigger(); - } - passed &= require(mutations.size() == count + (cancel ? 0 : 1), "creation cancellation preserves assignments"); - if (!cancel && mutations.size() > count) { - passed &= require(mutations.back().first == (project ? RuntimeActionKind::CreateProject : RuntimeActionKind::CreateSection) && - mutations.back().second.value("threadId", "") == "label-thread", - "creation retains the context thread for assignment after success"); - } - if (menu) { - menu->close(); - } - } - } - for (const auto *groups : {&snapshot->projects, &snapshot->sections}) - for (const auto &group : *groups) { - auto *item = threadItem(tree, group.id); - const auto *accessible = item ? threadAccessible(tree, item) : nullptr; - passed &= require( - accessible && accessible->text(QAccessible::Name) - .endsWith(QString::fromStdString(group.label)), - "accessible sidebar names share the canonical menu labels"); - } - menu = openMenu(threadItem(tree, "unique-project-id")); - passed &= require(menu != nullptr, "project ordering menu opens"); - if (menu) { - for (auto *action : menu->actions()) { - if (action->text() != "Move project before") - continue; - for (auto *entry : action->menu()->actions()) { - const auto found = - std::ranges::find_if(snapshot->projects, [&](const auto &group) { - return entry->text() == - QString::fromStdString(group.label).replace("&", "&&"); - }); - passed &= require(found != snapshot->projects.end(), - "ordering menu shares catalog labels"); - if (found != snapshot->projects.end()) { - entry->trigger(); - passed &= require( - mutations.back().first == RuntimeActionKind::MoveProject && - mutations.back().second.value("beforeProjectId", "") == - found->id, - "ordering label selects its canonical destination"); + void click(QWidget* widget, QPoint position, Qt::MouseButton button = Qt::LeftButton) { + if (auto* child = widget->childAt(position)) { + position = child->mapFrom(widget, position); + widget = child; + } + QMouseEvent press(QEvent::MouseButtonPress, + QPointF(position), + QPointF(position), + widget->mapToGlobal(position), + button, + button, + Qt::NoModifier); + QApplication::sendEvent(widget, &press); + QMouseEvent release(QEvent::MouseButtonRelease, + QPointF(position), + QPointF(position), + widget->mapToGlobal(position), + button, + Qt::NoButton, + Qt::NoModifier); + QApplication::sendEvent(widget, &release); + QApplication::processEvents(); } - } - } - if (menu) - menu->close(); - } - for (const auto &[id, name] : - std::array{std::pair{"book-first-id", "Book"}, - std::pair{"section-one-1111111", "Review"}}) { - menu = openMenu(threadItem(tree, id)); - passed &= require(menu != nullptr, "group Details menu opens"); - if (!menu) - continue; - for (auto *action : menu->actions()) { - if (action->text() != "Details…") - continue; - bool inspected = false; - QTimer::singleShot(0, [&] { - auto *dialog = pane.findChild("threadGroupDialog"); - if (!dialog) - return; - const auto *identifier = dialog->findChild("groupId"); - const auto *authoredName = dialog->findChild("groupName"); - inspected = identifier && identifier->text() == id && - identifier->isReadOnly() && authoredName && - authoredName->text() == name; - if (std::string_view(id) == "section-one-1111111") { - inspected &= dialog->findChildren().size() == 2 && authoredName->isReadOnly(); - if (const QString path = qEnvironmentVariable("CODEXUI_SECTION_DETAILS_SCREENSHOT"); !path.isEmpty()) { - passed &= require(dialog->grab().save(path), "section details screenshot saved"); + + QTreeWidgetItem* threadItem(QTreeWidget* tree, std::string_view id, QTreeWidgetItem* parent = nullptr) { + const int count = parent ? parent->childCount() : tree ? tree->topLevelItemCount() : 0; + for (int index = 0; index < count; ++index) { + QTreeWidgetItem* item = parent ? parent->child(index) : tree->topLevelItem(index); + if (item->data(0, Qt::UserRole).toString() == QString::fromUtf8(id.data(), static_cast(id.size()))) + return item; + if (QTreeWidgetItem* found = threadItem(tree, id, item)) + return found; } + return nullptr; } - dialog->reject(); - }); - action->trigger(); - passed &= require( - inspected, - "Details retains the full copyable ID and original authored name"); - break; - } - if (menu) - menu->close(); - } - { - auto read = graph.tryRead(); - const auto state = - read->state(read->find({NodeKind::Project, "book-first-id"})); - passed &= require( - exactStringFromValue(valueMember(state->fields, "name")) == "Book", - "display disambiguation does not alter authoritative names"); - } - if (const auto path = qEnvironmentVariable("CODEXUI_GROUP_LABEL_SCREENSHOT"); - !path.isEmpty()) { - tree->scrollToTop(); - QApplication::processEvents(); - passed &= require(pane.grab().save(path), "group label screenshot saved"); - } - { - auto write = graph.write(); - write.setField(write.find({NodeKind::Project, "book-first-id"}), "name", - "Other book"); - static_cast(write.finish()); - } - auto changed = adapter.threads(thread, nullptr, &pane.browserOptions()); - passed &= - require(changed && label(changed->projects, "book-second-id") == "Book", - "renaming a duplicate removes obsolete disambiguation"); - return passed; -} -bool localDraftsUseOneGroupingProjection() { - using namespace nodegraph; - NodeGraph graph; - const auto fields = [](nlohmann::json value) { return *valueFromJson(value).asObject(); }; - NodeRef firstProject, secondProject, section; - { - auto write = graph.write(); - const auto entity = [&](NodeKind kind, std::string id, nlohmann::json data) { - NodeState state; - state.fields = fields(std::move(data)); - return write.upsert({kind, std::move(id)}, std::move(state)); - }; - firstProject = entity(NodeKind::Project, "project-a", {{"name", "OpenWRT"}}); - secondProject = entity(NodeKind::Project, "project-b", {{"name", "CodexUI"}}); - section = entity(NodeKind::ThreadSection, "shared-section", {{"name", "Pinned"}}); - entity(NodeKind::ThreadSection, "standalone-section", {{"name", "Research"}}); - for (const std::string method : {"project/list", "threadSection/list"}) - entity(NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object()), - {{"loaded", true}, {"unsupported", false}}); - NodeState connection; - connection.status = NodeStatus::Connected; - connection.fields = fields({{"providerState", "ready"}, {"role", "controller"}}); - static_cast(write.upsert({NodeKind::Connection, "connection"}, std::move(connection))); - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - AnimationDurationStyle normalMotion(100); - middle::ThreadPane pane; - pane.resize(330, 680); - if (const int width = qEnvironmentVariableIntValue("CODEXUI_GROUP_WIDTH"); width > 0) - pane.resize(width, 680); - auto snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); - if (!snapshot) - return false; - pane.refresh(*snapshot); - pane.show(); - QApplication::processEvents(); - auto *tree = threadTree(pane); - tree->setStyle(&normalMotion); - bool passed = true; - for (const auto &[project, sectionId] : - {std::pair{"project-a", ""}, std::pair{"project-b", "shared-section"}, - std::pair{"", "standalone-section"}}) { - const ui::ThreadListRow local = localDraft("draft:new-thread", "creation:group-draft", - "New thread", "/workspace", project, sectionId); - pane.beginOptimisticThread(local); - const auto retained = pane.optimisticThread(); - const auto projected = adapter.threads({}, nullptr, &pane.browserOptions(), - retained ? &*retained : nullptr); - passed &= require(projected.has_value(), "local draft projects with graph groups"); - if (!projected) - continue; - pane.refresh(*projected); - QApplication::processEvents(); - auto *draft = threadItem(tree, local.id); - auto *const stableDraft = draft; - auto *parent = draft ? draft->parent() : nullptr; - passed &= require(draft && parent && tree->currentItem() == draft && - parent->data(0, Qt::UserRole).toString().toStdString() == - (local.sectionId.empty() ? local.projectId : local.sectionId), - "a draft is selected inside its chosen project or section"); - if (!draft) - continue; - if (!local.projectId.empty() && !local.sectionId.empty()) - passed &= require(parent->parent() == threadItem(tree, local.projectId), - "a section draft retains its project ancestry"); - const auto epoch = pane.findChild(QStringLiteral("optimisticThreadAnimation")); - const auto accessibleDraft = threadAccessible(tree, draft); - const auto accessibleId = accessibleDraft ? QAccessible::uniqueId(accessibleDraft) : 0; - pane.refresh(*projected); - passed &= require(threadItem(tree, local.id) == stableDraft && - stableDraft->parent() == parent && tree->currentItem() == stableDraft && - pane.optimisticThread() && epoch && epoch->isActive() && - (!accessibleId || QAccessible::accessibleInterface(accessibleId) == accessibleDraft), - "refresh preserves grouped draft lifetime, selection and animation"); - const QString captures = qEnvironmentVariable("CODEXUI_DRAFT_SCREENSHOT_DIR"); - if (!captures.isEmpty()) - passed &= require(pane.grab().save(captures + "/draft-dpr-" + QString::number(pane.devicePixelRatioF()) + "-" + QString::fromStdString(local.projectId) + "-" + QString::fromStdString(local.sectionId) + ".png"), - "grouped draft screenshot is captured"); - ui::ThreadBrowserOptions filtered = pane.browserOptions(); - filtered.title = "does not match the draft"; - filtered.archived = 1; - const auto filteredProjection = adapter.threads({}, nullptr, &filtered, &local); - if (filteredProjection) - pane.refresh(*filteredProjection); - passed &= require(threadItem(tree, local.id) == stableDraft && stableDraft->parent() && - tree->currentItem() == stableDraft, - "an active local draft remains in its group under browser filters"); - pane.refresh(*projected); - for (const auto mode : {ui::ThreadGrouping::Sections, ui::ThreadGrouping::Ungrouped, - ui::ThreadGrouping::Projects}) { - ui::ThreadBrowserOptions browser = pane.browserOptions(); - browser.grouping = mode; - const auto changed = adapter.threads({}, nullptr, &browser, &local); - if (changed) - pane.refresh(*changed); - passed &= require(threadItem(tree, local.id) == stableDraft && tree->currentItem() == stableDraft && - (mode != ui::ThreadGrouping::Ungrouped || !stableDraft->parent()), - "changing grouping reuses the local draft's row and selection"); - } - parent = stableDraft->parent(); - const auto admitted = [&] { - auto write = graph.write(); - NodeState state; - state.fields = fields({{"name", local.title}, {"creationCorrelation", "group-draft"}, {"local", true}}); - auto target = write.upsert({NodeKind::Thread, "local-thread:group-draft"}, std::move(state)); - if (!local.projectId.empty()) - write.relate(target, RelationKind::ProjectMembership, - local.projectId == "project-a" ? firstProject : secondProject); - if (!local.sectionId.empty()) - write.relate(target, RelationKind::SectionMembership, - local.sectionId == "shared-section" ? section : - write.find({NodeKind::ThreadSection, local.sectionId})); - static_cast(write.finish()); - return target; - }(); - const auto promoted = adapter.threads(admitted, nullptr, &pane.browserOptions(), &local); - if (promoted) - pane.refresh(*promoted); - passed &= require(threadItem(tree, admitted->id().canonical) == stableDraft && - stableDraft->parent() == parent && tree->currentItem() == stableDraft && - !pane.optimisticThread() && !threadItem(tree, local.id), - "graph admission promotes the same grouped row without duplication or movement"); - { - auto write = graph.write(); - write.remove(admitted); - static_cast(write.finish()); - } - pane.refresh(*snapshot); - } - return passed; -} + QAccessibleInterface* threadAccessible(QTreeWidget* tree, QTreeWidgetItem* item) { + if (!tree || !item) + return nullptr; + std::vector path; + for (QTreeWidgetItem* current = item; current; current = current->parent()) + path.push_back(current->parent() ? current->parent()->indexOfChild(current) : tree->indexOfTopLevelItem(current)); + QAccessibleInterface* accessible = QAccessible::queryAccessibleInterface(tree); + for (auto index = path.rbegin(); accessible && index != path.rend(); ++index) + accessible = accessible->child(*index); + return accessible; + } -bool groupedThreadsPreserveIdentityAndInteractions() { - using namespace nodegraph; - NodeGraph graph; - NodeRef root, child, sibling, firstProject, secondProject, section; - const auto fields = [](nlohmann::json value) { - return *valueFromJson(value).asObject(); - }; - { - auto write = graph.write(); - NodeState connection; - connection.status = NodeStatus::Connected; - connection.fields = - fields({{"providerState", "ready"}, {"role", "controller"}}); - static_cast(write.upsert({NodeKind::Connection, "connection"}, - std::move(connection))); - const auto entity = [&](NodeKind kind, std::string id, - nlohmann::json data) { - NodeState state; - state.fields = fields(std::move(data)); - return write.upsert({kind, std::move(id)}, std::move(state)); - }; - firstProject = - entity(NodeKind::Project, "project-a", - {{"name", "CodexUI — project"}, - {"position", 0}, - {"roots", nlohmann::json::array({{{"path", "/workspace/ui"}}})}, - {"metadata", - {{"codexui.description", - "Project description\nNot model instructions"}, - {"other-client", "preserved"}}}}); - secondProject = entity( - NodeKind::Project, "project-b", - {{"name", "AISuite — very long project name with Unicode 日本語"}, - {"position", 1}, - {"metadata", nlohmann::json::object()}}); - section = entity( - NodeKind::ThreadSection, "shared-section", {{"name", "In progress"}, {"appearance", {{"icon", "star"}, {"color", "purple"}}}}); - root = entity( - NodeKind::Thread, "group-parent", - {{"name", "Parent"}, {"cwd", "/workspace/ui"}, {"recencyAt", 10}}); - child = entity( - NodeKind::Thread, "group-child", - {{"name", "Child"}, {"cwd", "/workspace/bridge"}, {"recencyAt", 20}}); - sibling = entity( - NodeKind::Thread, "group-sibling", - {{"name", "Sibling"}, {"cwd", "/workspace/ui"}, {"recencyAt", 30}}); - write.relate(root, RelationKind::AgentChildThread, child); - write.relate(root, RelationKind::ProjectMembership, firstProject); - write.relate(child, RelationKind::ProjectMembership, secondProject); - write.relate(sibling, RelationKind::ProjectMembership, firstProject); - for (const auto &thread : {root, child, sibling}) - write.relate(thread, RelationKind::SectionMembership, section); - const auto standaloneSection = entity(NodeKind::ThreadSection, - "standalone-section", - {{"name", "Personal research"}, {"appearance", {{"icon", "folder"}, {"color", "blue"}}}}); - const auto standaloneMember = - entity(NodeKind::Thread, "standalone-member", - {{"name", "Research outside projects"}}); - write.relate(standaloneMember, RelationKind::SectionMembership, - standaloneSection); - static_cast(entity(NodeKind::Thread, "ungrouped-thread", - {{"name", "Independent conversation"}})); - for (std::string method : {"project/list", "threadSection/list"}) - entity(NodeKind::Catalog, - threadBrowserKey(method, nlohmann::json::object()), - {{"loaded", true}, - {"pending", false}, - {"unsupported", false}, - {"hasMore", false}}); - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.resize(330, 680); - if (const int width = qEnvironmentVariableIntValue("CODEXUI_GROUP_WIDTH"); - width > 0) - pane.resize(width, 680); - if (const int points = qEnvironmentVariableIntValue("CODEXUI_GROUP_FONT"); - points > 0) { - auto font = pane.font(); - font.setPointSize(points); - pane.setFont(font); - } - NodeRef selected; - int changes = 0; - std::vector queries; - std::vector> mutations; - std::optional> newThreadContext; - middle::ThreadPane::Actions actions; - actions.select = [&](const auto &node) { selected = node; }; - actions.browserChanged = [&] { ++changes; }; - actions.browse = [&](nlohmann::json query) { - queries.push_back(std::move(query)); - }; - actions.manage = [&](auto kind, nlohmann::json parameters) { - mutations.emplace_back(kind, std::move(parameters)); - }; - actions.newGroupedThread = [&](std::string project, std::string section) { - newThreadContext = std::array{std::move(project), std::move(section)}; - }; - pane.setActions(std::move(actions)); - auto snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); - bool passed = - require(snapshot && snapshot->groupingAvailable, - "project and section catalogs enable grouped projection"); - if (!snapshot) - return false; - pane.refresh(*snapshot); - pane.show(); - QApplication::processEvents(); - auto *tree = threadTree(pane); - auto *rootItem = threadItem(tree, "group-parent"); - auto *childItem = threadItem(tree, "group-child"); - auto *siblingItem = threadItem(tree, "group-sibling"); - passed &= require(rootItem && childItem && siblingItem, - "grouping preserves all three threads"); - if (!rootItem || !childItem || !siblingItem) - return false; - const auto *standalone = threadItem(tree, "standalone-section"); - const auto *ungrouped = threadItem(tree, "ungrouped-thread"); - if (standalone && standalone->childCount()) { - const bool expanded = standalone->isExpanded(); - tree->expandItem(standalone); - QApplication::processEvents(); - const auto sectionMember = tree->visualItemRect(standalone->child(0)); - const auto bodies = tree->findChildren(QStringLiteral("projectThreadBody")); - const auto projectRow = - bodies.isEmpty() ? QRect{} : bodies.front()->visualRect(bodies.front()->model()->index(0, 0, bodies.front()->rootIndex())); - passed &= require(projectRow.isValid() && sectionMember.height() == projectRow.height() && - sectionMember.height() >= tree->fontMetrics().height(), - "standalone and project members share actual compact geometry without clipping their font"); - passed &= require(tree->visualItemRect(standalone).height() == sectionMember.height() + UiStyle::projectCardEdgePadding, - "expanded section headers reserve only the card's top padding before their first member"); - const auto* last = standalone->child(standalone->childCount() - 1); - passed &= require(tree->visualItemRect(last).height() == sectionMember.height() + UiStyle::projectCardEdgePadding, - "the terminal section row owns the enclosing card's bottom padding"); - tree->setExpanded(tree->indexFromItem(standalone), expanded); - } - - for (const auto* id : {"shared-section", "standalone-section"}) { - const auto tooltip = threadItem(tree, id)->data(0, Qt::ToolTipRole).toString(); - passed &= require(!tooltip.contains("star") && !tooltip.contains("folder") && !tooltip.contains("appearance"), - "nested and standalone section headings and tooltips ignore appearance metadata"); - } - tree->scrollToItem(threadItem(tree, "ungrouped-thread")); - QApplication::processEvents(); - const auto currentBeforeContext = tree->currentIndex(); - const auto selectionBeforeContext = tree->selectionModel()->selectedRows(); - const auto activeBeforeContext = selected; - click(tree->viewport(), tree->visualItemRect(ungrouped).center(), Qt::RightButton); - passed &= require(tree->currentIndex() == currentBeforeContext && tree->selectionModel()->selectedRows() == selectionBeforeContext && - selected == activeBeforeContext, - "an outer-tree context click preserves the current conversation and shared selection"); - const auto projectsFirst = [&] { - const int first = tree->indexOfTopLevelItem(threadItem(tree, "project-a")); - const int second = tree->indexOfTopLevelItem(threadItem(tree, "project-b")); - return std::min(first, second) == 0 && std::max(first, second) == 1; - }; - passed &= require(projectsFirst(), - "projects precede standalone threads and sections"); - for (auto criterion : {middle::ThreadPane::SortCriterion::Alphanumeric, - middle::ThreadPane::SortCriterion::Created, - middle::ThreadPane::SortCriterion::Recency}) { - pane.setSortCriterion(criterion); - passed &= - require(projectsFirst(), "changing thread sort keeps projects first"); - } - pane.beginOptimisticThread(localDraft("draft-order", "draft-order", "Draft", "/workspace")); - passed &= require(projectsFirst(), "creating a draft keeps projects first"); - pane.refresh(*snapshot); - passed &= - require(projectsFirst(), "refreshing with a draft keeps projects first"); - pane.discardOptimisticThread("draft-order"); - passed &= - require(standalone && !standalone->parent() && ungrouped && - !ungrouped->parent() && - threadItem(tree, "standalone-member")->parent() == standalone, - "standalone sections and ungrouped threads are outer cards " - "without a synthetic No project container"); - passed &= require(childItem->parent() != rootItem && - childItem->parent()->parent() == - threadItem(tree, "project-b"), - "a cross-project child is shown once in its own project"); - passed &= require(tree->currentItem() == childItem, - "selected thread survives grouped population"); - const auto accessible = threadAccessible(tree, childItem); - const auto accessibleId = accessible ? QAccessible::uniqueId(accessible) : 0; - const auto before = pane.grab().toImage(); - pane.refresh(*snapshot); - QApplication::processEvents(); - passed &= - require(pane.grab().toImage() == before && - threadItem(tree, "group-child") == childItem, - "a grouped semantic no-op preserves pixels and row identity"); - { - auto write = graph.write(); - write.setField(section, "appearance", *valueFromJson({{"icon", "changed-marker"}, {"color", "orange"}}).asObject()); - static_cast(write.finish()); - } - snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - QApplication::processEvents(); - passed &= require(pane.grab().toImage() == before, "another client's section appearance change leaves native presentation unchanged"); - { - auto write = graph.write(); - write.replaceRelated(child, RelationKind::ProjectMembership, - std::array{firstProject}); - static_cast(write.finish()); - } - snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - QApplication::processEvents(); - passed &= - require(threadItem(tree, "group-child") == childItem && - childItem->parent() == rootItem, - "membership reconciliation reparents the existing child row"); - passed &= require( - tree->currentItem() == childItem && threadAccessible(tree, childItem) && - QAccessible::uniqueId(threadAccessible(tree, childItem)) == - accessibleId, - "reparenting preserves selection and accessible identity"); - auto *groupControl = pane.findChild("threadGroupingButton"); - passed &= require(groupControl->property("codexChevron").toBool() && - groupControl->minimumHeight() == 28 && - !groupControl->toolTip().isEmpty(), - "grouping uses the same styled single-chevron control as sorting"); - for (auto *action : groupControl->menu()->actions()) - if (action->text() == "Sections") - action->trigger(); - QMetaObject::invokeMethod(groupControl->menu(), "aboutToShow", Qt::DirectConnection); - int checkedModes = 0; - for (auto *action : groupControl->menu()->actions()) { - if (!action->actionGroup()) - continue; - checkedModes += action->isChecked(); - passed &= require(action->isCheckable() && - action->isChecked() == (action->text() == "Sections"), - "grouping menu reflects the authoritative selected mode"); - } - passed &= require(checkedModes == 1, "exactly one grouping mode is checked"); - snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - QApplication::processEvents(); - passed &= - require(changes > 0 && childItem->parent() == rootItem && - rootItem->parent() == threadItem(tree, "shared-section"), - "Sections view preserves same-group family nesting"); - passed &= require(!rootItem->parent()->data(0, Qt::ToolTipRole).toString().contains("changed-marker"), - "Sections view ignores appearance metadata after regrouping"); - - auto *search = pane.findChild("threadTitleSearch"); - search->setText("Sibling"); - QMetaObject::invokeMethod(search, "returnPressed", Qt::DirectConnection); - snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - QApplication::processEvents(); - passed &= require( - !threadItem(tree, "group-parent") && threadItem(tree, "group-sibling"), - "title filtering changes discovery without deleting graph entities"); - passed &= require( - !queries.empty() && - queries.back().at("parameters").value("searchTerm", "") == "Sibling", - "title search submits a server-backed query"); - search->clear(); - auto *archive = pane.findChild("threadArchiveFilter"); - archive->setCurrentIndex(1); - snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - passed &= require(!threadItem(tree, "group-sibling"), - "archive filtering excludes active threads"); - archive->setCurrentIndex(0); - for (auto *action : groupControl->menu()->actions()) - if (action->text() == "Projects → Sections") - action->trigger(); - snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - tree->expandAll(); - QApplication::processEvents(); - const auto titleImage = [&](const std::string &title) { - { - auto write = graph.write(); - write.setField(root, "name", title); - static_cast(write.finish()); - } - pane.refresh(*adapter.threads(root, nullptr, &pane.browserOptions())); - QApplication::processEvents(); - return pane.grab().toImage(); - }; - for (const auto &title : - {std::string("First\nSecond"), std::string("First\r\nSecond"), - std::string("First\xE2\x80\xA8Second"), - std::string( - "First\nSecond with a very long title 日本語 and more words")}) { - const auto multiline = titleImage(title); - auto *row = threadItem(tree, "group-parent"); - const auto geometry = tree->visualItemRect(row); - passed &= - require(threadAccessible(tree, row) - ->text(QAccessible::Name) - .contains(QString::fromStdString(title)), - "single-line painting preserves the full accessible title"); - const auto singleline = - titleImage(QString::fromStdString(title).simplified().toStdString()); - passed &= require(multiline == singleline && - geometry == tree->visualItemRect(row), - "multiline titles paint as one elided line without " - "changing row geometry"); - } - if (const QString path = qEnvironmentVariable("CODEXUI_GROUP_SCREENSHOT"); - !path.isEmpty()) { - static_cast(titleImage( - "First\nSecond with a very long title 日本語 and more words")); - passed &= - require(pane.grab().save(path), "grouped live-widget screenshot saved"); - } - - // Exercise the actual edit dialog and emit authored data, not a handcrafted - // projection of what the dialog ought to send. - for (const bool project : {true, false}) { - const auto beforeEdit = mutations.size(); - auto* groupItem = threadItem(tree, project ? "project-a" : "standalone-section"); - tree->scrollToItem(groupItem); - QApplication::processEvents(); - const QPoint point = tree->visualItemRect(groupItem).topLeft() + QPoint(40, UiStyle::projectCardEdgePadding + 12); - QMetaObject::invokeMethod(tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, point)); - QApplication::processEvents(); - QPointer context; - for (auto* candidate : tree->findChildren()) { - if (candidate->isVisible()) { - context = candidate; - } - } - if (context) { - QAction* edit = nullptr; - for (auto* action : context->actions()) { - if (action->text() == "Edit…") { - edit = action; - } - } - QTimer::singleShot(0, [&] { - auto* dialog = pane.findChild("threadGroupDialog"); - passed &= require(dialog != nullptr, "group edit opens the real dialog"); - if (dialog) { - auto* description = dialog->findChild("projectDescription"); - if (description) { - description->setPlainText("Edited description 日本語"); - } - if (!project) { - passed &= require(dialog->findChildren().size() == 1, "section editing exposes only the name field"); - dialog->findChild("groupName")->setText("Renamed section"); - } - if (const QString path = qEnvironmentVariable("CODEXUI_GROUP_DIALOG_SCREENSHOT"); !path.isEmpty()) { - passed &= require(dialog->grab().save(project ? path : path + ".section.png"), "group edit dialog screenshot saved"); - } - auto* buttons = dialog->findChild(); - if (buttons) { - buttons->button(QDialogButtonBox::Save)->click(); - } - } - }); - if (edit) { - edit->trigger(); - } - if (context) { - context->close(); - } - } - passed &= require( - mutations.size() == beforeEdit + 1 && - mutations.back().first == (project ? RuntimeActionKind::UpdateProject : RuntimeActionKind::UpdateSection) && - (project ? mutations.back().second.value("description", "") == "Edited description 日本語" - : mutations.back().second == nlohmann::json{{"sectionId", "standalone-section"}, {"name", "Renamed section"}}), - "group edits submit authored fields without foreign project metadata or section appearance"); - } - for (const bool project : {true, false}) { - const QString label = project ? "New project…" : "New section…"; - const std::string id = project ? "new-empty-project" : "new-empty-section"; - const auto beforeCreate = mutations.size(); - QTimer::singleShot(0, [&] { - auto *dialog = pane.findChild("threadGroupDialog"); - if (!dialog) - return; - auto *name = dialog->findChild("groupName"); - if (!project) { - passed &= require(dialog->findChildren().size() == 1, "new section dialog exposes only the name field"); - if (const QString prefix = qEnvironmentVariable("CODEXUI_GROUP_CREATE_SCREENSHOT"); !prefix.isEmpty()) { - passed &= require(dialog->grab().save(prefix + "-empty-section.png"), "empty section dialog screenshot saved"); - } - } - auto *save = dialog->findChild()->button( - QDialogButtonBox::Save); - save->click(); - passed &= require(mutations.size() == beforeCreate && dialog->isVisible(), - "empty group names do not dispatch a mutation"); - name->setText(QString::fromStdString(id)); - if (project) { - auto *roots = dialog->findChild("projectRoots"); - roots->setPlainText("relative/path"); - save->click(); - passed &= - require(mutations.size() == beforeCreate && dialog->isVisible(), - "relative project roots are rejected before dispatch"); - roots->setPlainText("/workspace/new\n/workspace/second"); - auto* add = dialog->findChild("addProjectRoot"); - passed &= require(add && add->isEnabled(), "a controller can add project roots"); - if (add) { - const auto choose = [&](QString path, bool accept) { - QTimer::singleShot(0, dialog, [&, path, accept] { - auto* selection = dynamic_cast(QApplication::activeModalWidget()); - passed &= require(selection != nullptr, "Add root opens the existing workspace dialog"); - if (selection) { - selection->findChild("codexWorkspaceDirectory")->setText(path); - if (accept) { - selection->accept(); - } else { - selection->reject(); + bool groupLabelsIdentifyDestinationsWithoutRoutineIds() { + using namespace nodegraph; + NodeGraph graph; + NodeRef thread; + { + auto write = graph.write(); + const auto entity = [&](NodeKind kind, std::string id, nlohmann::json fields) { + NodeState state; + state.fields = *valueFromJson(fields).asObject(); + return write.upsert({kind, std::move(id)}, std::move(state)); + }; + const auto connection = entity(NodeKind::Connection, "connection", {{"providerState", "ready"}, {"role", "controller"}}); + write.setStatus(connection, NodeStatus::Connected); + for (const auto method : {"project/list", "threadSection/list"}) + entity(NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object()), {{"loaded", true}}); + const auto project = [&](const char* id, const char* name, std::initializer_list paths) { + nlohmann::json roots = nlohmann::json::array(); + for (const auto path : paths) + roots.push_back({{"path", path}}); + return entity(NodeKind::Project, id, {{"id", id}, {"name", name}, {"roots", roots}}); + }; + project("unique-project-id", "Research & Design", {"/workspace/design"}); + project("book-first-id", "Book", {"/home/work/book"}); + project("book-second-id", "Book", {"/home/private/book"}); + project("multi-first-id", "Multi", {"/work/shared", "/work/frontend"}); + project("multi-second-id", "Multi", {"/work/shared", "/work/backend"}); + project("shared-root-1111111", "Same", {"/same/root"}); + project("shared-root-2111111", "Same", {"/same/root"}); + project("rootless-aaaaaa", "Rootless", {}); + project("rootless-bbbbbb", "Rootless", {}); + project("windows-first-id", "Windows", {"C:\\work\\book"}); + project("windows-second-id", "Windows", {"D:\\work\\book"}); + project("literal-name-id", "Book — work/book", {}); + entity(NodeKind::ThreadSection, + "section-one-1111111", + {{"name", "Review"}, {"appearance", {{"icon", "star"}, {"color", "purple"}}}}); + entity(NodeKind::ThreadSection, "section-two-2111111", {{"name", "Review"}}); + entity(NodeKind::ThreadSection, "unique-section-id", {{"name", "Ready"}}); + thread = entity(NodeKind::Thread, "label-thread", {{"name", "Label selection"}}); + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.resize(620, 900); + std::vector> mutations; + middle::ThreadPane::Actions actions; + actions.manage = [&](auto kind, nlohmann::json params) { + mutations.emplace_back(kind, std::move(params)); + }; + pane.setActions(std::move(actions)); + auto snapshot = adapter.threads(thread, nullptr, &pane.browserOptions()); + if (!require(snapshot.has_value(), "label fixture projects successfully")) + return false; + bool passed = true; + const auto label = [&](const auto& groups, const char* id) { + const auto found = std::ranges::find(groups, id, &ui::ThreadGroup::id); + return found == groups.end() ? std::string{} : found->label; + }; + passed &= require(label(snapshot->projects, "unique-project-id") == "Research & Design" && + label(snapshot->sections, "unique-section-id") == "Ready", + "unique names carry no routine IDs"); + passed &= require(label(snapshot->projects, "book-second-id") == "Book — private/book" && + label(snapshot->projects, "multi-first-id") == "Multi — shared, frontend" && + label(snapshot->projects, "multi-second-id") == "Multi — shared, backend", + "duplicate project names use distinguishing folder " + "suffixes across all roots"); + passed &= require(label(snapshot->projects, "windows-first-id").find("C:/work/book") != std::string::npos && + label(snapshot->projects, "windows-second-id").find("D:/work/book") != std::string::npos, + "remote Windows paths retain their distinguishing drive"); + passed &= require(label(snapshot->sections, "section-one-1111111") == "Review · 1111111" && + label(snapshot->sections, "section-two-2111111") == "Review · 2111111", + "short ID suffixes expand until colliding sections are distinguishable"); + for (const auto* groups : {&snapshot->projects, &snapshot->sections}) { + std::unordered_set labels; + for (const auto& group : *groups) { + passed &= require(labels.insert(group.label).second, + "all displayed choices are distinct, including " + "literal-label and short-ID collisions"); + passed &= require(group.label.find(group.id) == std::string::npos, "full IDs are absent from routine labels"); + } + } + pane.refresh(*snapshot); + pane.show(); + QApplication::processEvents(); + auto* tree = threadTree(pane); + const auto openMenu = [&](QTreeWidgetItem* item) -> QMenu* { + tree->scrollToItem(item); + QApplication::processEvents(); + QMetaObject::invokeMethod( + tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, tree->visualItemRect(item).center())); + QApplication::processEvents(); + for (auto* menu : tree->findChildren()) + if (menu->isVisible()) + return menu; + return nullptr; + }; + QPointer menu = openMenu(threadItem(tree, "label-thread")); + passed &= require(menu != nullptr, "actual thread context menu opens"); + if (menu) { + for (auto* action : menu->actions()) { + const bool project = action->text() == "Assign project"; + if (!project && action->text() != "Assign section") + continue; + const auto& groups = project ? snapshot->projects : snapshot->sections; + auto* submenu = action->menu(); + passed &= + require(submenu && submenu->actions().size() == groups.size() + 2, "assignment menus retain every destination"); + if (!submenu || submenu->actions().size() != groups.size() + 2) + continue; + passed &= require(submenu->actions().at(0)->text() == (project ? "New project…" : "New section…") && + submenu->actions().at(1)->isSeparator(), + "creation is first, separated from existing destinations"); + for (std::size_t i = 0; i < groups.size(); ++i) { + auto* entry = submenu->actions().at(i + 2); + const auto& group = groups[i]; + passed &= require(entry->text() == QString::fromStdString(group.label).replace("&", "&&"), + "menu uses the same label as the sidebar and preserves " + "literal ampersands"); + entry->trigger(); + passed &= require(!mutations.empty() && + mutations.back().first == + (project ? RuntimeActionKind::AssignProject : RuntimeActionKind::AssignSection) && + mutations.back().second.value(project ? "projectId" : "sectionId", "") == group.id, + "disambiguated actions still target the full canonical ID"); + } + } + if (menu) + menu->close(); + } + for (bool project : {true, false}) { + for (bool cancel : {true, false}) { + menu = openMenu(threadItem(tree, "label-thread")); + QAction* create = nullptr; + if (menu) { + for (auto* action : menu->actions()) { + if (action->text() == (project ? "Assign project" : "Assign section")) { + create = action->menu()->actions().front(); + } } } - }); - add->click(); - }; - choose("/workspace/third", true); - choose("/workspace/fourth", true); - choose("/workspace/third", true); - choose("/cancelled", false); - passed &= require(roots->toPlainText() == "/workspace/new\n/workspace/second\n/workspace/third\n/workspace/fourth" && - mutations.size() == beforeCreate, - "root additions preserve manual lines, reject duplicates and leave cancellation unsent"); + passed &= require(create != nullptr, "fresh creation action is reachable"); + const auto count = mutations.size(); + if (create) { + QTimer::singleShot(0, &pane, [&pane, cancel, &passed] { + auto* dialog = pane.findChild("threadGroupDialog"); + passed &= require(dialog != nullptr, "assignment opens the existing creation dialog"); + if (dialog) { + if (cancel) { + dialog->reject(); + } else { + dialog->findChild("groupName")->setText("Created from assignment"); + dialog->findChild()->button(QDialogButtonBox::Save)->click(); + } + } + }); + create->trigger(); + } + passed &= require(mutations.size() == count + (cancel ? 0 : 1), "creation cancellation preserves assignments"); + if (!cancel && mutations.size() > count) { + passed &= require(mutations.back().first == + (project ? RuntimeActionKind::CreateProject : RuntimeActionKind::CreateSection) && + mutations.back().second.value("threadId", "") == "label-thread", + "creation retains the context thread for assignment after success"); + } + if (menu) { + menu->close(); + } + } + } + for (const auto* groups : {&snapshot->projects, &snapshot->sections}) + for (const auto& group : *groups) { + auto* item = threadItem(tree, group.id); + const auto* accessible = item ? threadAccessible(tree, item) : nullptr; + passed &= require(accessible && accessible->text(QAccessible::Name).endsWith(QString::fromStdString(group.label)), + "accessible sidebar names share the canonical menu labels"); + } + menu = openMenu(threadItem(tree, "unique-project-id")); + passed &= require(menu != nullptr, "project ordering menu opens"); + if (menu) { + for (auto* action : menu->actions()) { + if (action->text() != "Move project before") + continue; + for (auto* entry : action->menu()->actions()) { + const auto found = std::ranges::find_if(snapshot->projects, [&](const auto& group) { + return entry->text() == QString::fromStdString(group.label).replace("&", "&&"); + }); + passed &= require(found != snapshot->projects.end(), "ordering menu shares catalog labels"); + if (found != snapshot->projects.end()) { + entry->trigger(); + passed &= require(mutations.back().first == RuntimeActionKind::MoveProject && + mutations.back().second.value("beforeProjectId", "") == found->id, + "ordering label selects its canonical destination"); + } + } + } + if (menu) + menu->close(); + } + for (const auto& [id, name] : std::array{std::pair{"book-first-id", "Book"}, std::pair{"section-one-1111111", "Review"}}) { + menu = openMenu(threadItem(tree, id)); + passed &= require(menu != nullptr, "group Details menu opens"); + if (!menu) + continue; + for (auto* action : menu->actions()) { + if (action->text() != "Details…") + continue; + bool inspected = false; + QTimer::singleShot(0, [&] { + auto* dialog = pane.findChild("threadGroupDialog"); + if (!dialog) + return; + const auto* identifier = dialog->findChild("groupId"); + const auto* authoredName = dialog->findChild("groupName"); + inspected = identifier && identifier->text() == id && identifier->isReadOnly() && authoredName && + authoredName->text() == name; + if (std::string_view(id) == "section-one-1111111") { + inspected &= dialog->findChildren().size() == 2 && authoredName->isReadOnly(); + if (const QString path = qEnvironmentVariable("CODEXUI_SECTION_DETAILS_SCREENSHOT"); !path.isEmpty()) { + passed &= require(dialog->grab().save(path), "section details screenshot saved"); + } + } + dialog->reject(); + }); + action->trigger(); + passed &= require(inspected, "Details retains the full copyable ID and original authored name"); + break; + } + if (menu) + menu->close(); + } + { + auto read = graph.tryRead(); + const auto state = read->state(read->find({NodeKind::Project, "book-first-id"})); + passed &= require(exactStringFromValue(valueMember(state->fields, "name")) == "Book", + "display disambiguation does not alter authoritative names"); + } + if (const auto path = qEnvironmentVariable("CODEXUI_GROUP_LABEL_SCREENSHOT"); !path.isEmpty()) { + tree->scrollToTop(); + QApplication::processEvents(); + passed &= require(pane.grab().save(path), "group label screenshot saved"); + } + { + auto write = graph.write(); + write.setField(write.find({NodeKind::Project, "book-first-id"}), "name", "Other book"); + static_cast(write.finish()); + } + auto changed = adapter.threads(thread, nullptr, &pane.browserOptions()); + passed &= require(changed && label(changed->projects, "book-second-id") == "Book", + "renaming a duplicate removes obsolete disambiguation"); + return passed; } - dialog->findChild("projectDescription") - ->setPlainText("Description 日本語"); - } - if (const QString prefix = qEnvironmentVariable("CODEXUI_GROUP_CREATE_SCREENSHOT"); !prefix.isEmpty()) { - auto* roots = dialog->findChild("projectRoots"); - const auto original = roots ? roots->toPlainText() : QString{}; - if (roots) { - roots->appendPlainText("/server/" + QString("long-directory/").repeated(30)); - } - for (const auto width : {dialog->minimumSizeHint().width(), 520}) { - dialog->resize(width, dialog->height()); - QApplication::processEvents(); - for (auto* label : dialog->findChildren()) { - if (!project && label->wordWrap() && !label->text().isEmpty()) { - passed &= require(label->height() >= label->heightForWidth(label->width()), - "section dialog text remains fully visible at narrow widths and enlarged fonts"); - } - } - passed &= require(dialog->grab().save(prefix + (project ? "-project-" : "-section-") + QString::number(width) + ".png"), - "group creation dialog screenshot saved"); - } - if (roots) { - roots->setPlainText(original); - } - } - save->click(); - }); - for (auto *action : groupControl->menu()->actions()) - if (action->text() == label) - action->trigger(); - passed &= - require(mutations.size() == beforeCreate + 1 && - mutations.back().first == - (project ? RuntimeActionKind::CreateProject - : RuntimeActionKind::CreateSection) && - mutations.back().second.at("name") == id, - "creation menu submits exactly one authored group mutation"); - if (mutations.size() == beforeCreate) - continue; - const auto ¶meters = mutations.back().second; - if (!project) { - passed &= require(parameters == nlohmann::json{{"name", id}}, "section creation submits only its name"); - } - if (project) - passed &= - require(parameters.at("roots").size() == 4 && parameters.at("metadata").at(ProjectDescriptionKey) == "Description 日本語" && - !parameters.value("idempotencyKey", "").empty(), - "project creation retains roots, description and idempotency key"); - passed &= require(!threadItem(tree, id), - "creation does not invent an optimistic group"); - // Deliver the authoritative entity, as the separately tested runtime - // reducer does after the create response. No thread membership exists yet. - { - auto write = graph.write(); - NodeState state; - state.fields = fields(parameters); - static_cast(write.upsert( - {project ? NodeKind::Project : NodeKind::ThreadSection, id}, - std::move(state))); - static_cast(write.finish()); - } - snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - QApplication::processEvents(); - auto *created = threadItem(tree, id); - passed &= require(created && !created->parent(), - "new empty projects and sections are visible outer cards " - "in Projects view"); - if (!created) - continue; - tree->scrollToItem(created); - QApplication::processEvents(); - QMetaObject::invokeMethod( - tree, "customContextMenuRequested", Qt::DirectConnection, - Q_ARG(QPoint, tree->visualItemRect(created).center())); - for (auto *menu : tree->findChildren()) - if (menu->isVisible()) { - for (auto *action : menu->actions()) - if (action->text() == "New thread here…") - action->trigger(); - menu->close(); - } - passed &= require(newThreadContext == std::optional(std::array{project ? id : std::string{}, project ? std::string{} : id}), - "an empty group passes project and section identity to thread creation, " - "which owns workspace selection"); - if (!project) { - for (const bool assign : {true, false}) { - { - auto write = graph.write(); - const auto member = - write.find({NodeKind::Thread, "standalone-member"}); - if (assign) - write.replaceRelated( - member, RelationKind::SectionMembership, - std::array{write.find({NodeKind::ThreadSection, id})}); - else - write.replaceRelated(member, RelationKind::SectionMembership, {}); - static_cast(write.finish()); + bool localDraftsUseOneGroupingProjection() { + using namespace nodegraph; + NodeGraph graph; + const auto fields = [](nlohmann::json value) { + return *valueFromJson(value).asObject(); + }; + NodeRef firstProject, secondProject, section; + { + auto write = graph.write(); + const auto entity = [&](NodeKind kind, std::string id, nlohmann::json data) { + NodeState state; + state.fields = fields(std::move(data)); + return write.upsert({kind, std::move(id)}, std::move(state)); + }; + firstProject = entity(NodeKind::Project, "project-a", {{"name", "OpenWRT"}}); + secondProject = entity(NodeKind::Project, "project-b", {{"name", "CodexUI"}}); + section = entity(NodeKind::ThreadSection, "shared-section", {{"name", "Pinned"}}); + entity(NodeKind::ThreadSection, "standalone-section", {{"name", "Research"}}); + for (const std::string method : {"project/list", "threadSection/list"}) + entity( + NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object()), {{"loaded", true}, {"unsupported", false}}); + NodeState connection; + connection.status = NodeStatus::Connected; + connection.fields = fields({{"providerState", "ready"}, {"role", "controller"}}); + static_cast(write.upsert({NodeKind::Connection, "connection"}, std::move(connection))); + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + AnimationDurationStyle normalMotion(100); + middle::ThreadPane pane; + pane.resize(330, 680); + if (const int width = qEnvironmentVariableIntValue("CODEXUI_GROUP_WIDTH"); width > 0) + pane.resize(width, 680); + auto snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); + if (!snapshot) + return false; + pane.refresh(*snapshot); + pane.show(); + QApplication::processEvents(); + auto* tree = threadTree(pane); + tree->setStyle(&normalMotion); + bool passed = true; + for (const auto& [project, sectionId] : + {std::pair{"project-a", ""}, std::pair{"project-b", "shared-section"}, std::pair{"", "standalone-section"}}) { + const ui::ThreadListRow local = + localDraft("draft:new-thread", "creation:group-draft", "New thread", "/workspace", project, sectionId); + pane.beginOptimisticThread(local); + const auto retained = pane.optimisticThread(); + const auto projected = adapter.threads({}, nullptr, &pane.browserOptions(), retained ? &*retained : nullptr); + passed &= require(projected.has_value(), "local draft projects with graph groups"); + if (!projected) + continue; + pane.refresh(*projected); + QApplication::processEvents(); + auto* draft = threadItem(tree, local.id); + auto* const stableDraft = draft; + auto* parent = draft ? draft->parent() : nullptr; + passed &= require(draft && parent && tree->currentItem() == draft && + parent->data(0, Qt::UserRole).toString().toStdString() == + (local.sectionId.empty() ? local.projectId : local.sectionId), + "a draft is selected inside its chosen project or section"); + if (!draft) + continue; + if (!local.projectId.empty() && !local.sectionId.empty()) + passed &= + require(parent->parent() == threadItem(tree, local.projectId), "a section draft retains its project ancestry"); + const auto epoch = pane.findChild(QStringLiteral("optimisticThreadAnimation")); + const auto accessibleDraft = threadAccessible(tree, draft); + const auto accessibleId = accessibleDraft ? QAccessible::uniqueId(accessibleDraft) : 0; + pane.refresh(*projected); + passed &= require(threadItem(tree, local.id) == stableDraft && stableDraft->parent() == parent && + tree->currentItem() == stableDraft && pane.optimisticThread() && epoch && epoch->isActive() && + (!accessibleId || QAccessible::accessibleInterface(accessibleId) == accessibleDraft), + "refresh preserves grouped draft lifetime, selection and animation"); + const QString captures = qEnvironmentVariable("CODEXUI_DRAFT_SCREENSHOT_DIR"); + if (!captures.isEmpty()) + passed &= require(pane.grab().save(captures + "/draft-dpr-" + QString::number(pane.devicePixelRatioF()) + "-" + + QString::fromStdString(local.projectId) + "-" + + QString::fromStdString(local.sectionId) + ".png"), + "grouped draft screenshot is captured"); + ui::ThreadBrowserOptions filtered = pane.browserOptions(); + filtered.title = "does not match the draft"; + filtered.archived = 1; + const auto filteredProjection = adapter.threads({}, nullptr, &filtered, &local); + if (filteredProjection) + pane.refresh(*filteredProjection); + passed &= require(threadItem(tree, local.id) == stableDraft && stableDraft->parent() && tree->currentItem() == stableDraft, + "an active local draft remains in its group under browser filters"); + pane.refresh(*projected); + for (const auto mode : {ui::ThreadGrouping::Sections, ui::ThreadGrouping::Ungrouped, ui::ThreadGrouping::Projects}) { + ui::ThreadBrowserOptions browser = pane.browserOptions(); + browser.grouping = mode; + const auto changed = adapter.threads({}, nullptr, &browser, &local); + if (changed) + pane.refresh(*changed); + passed &= require(threadItem(tree, local.id) == stableDraft && tree->currentItem() == stableDraft && + (mode != ui::ThreadGrouping::Ungrouped || !stableDraft->parent()), + "changing grouping reuses the local draft's row and selection"); + } + parent = stableDraft->parent(); + const auto admitted = [&] { + auto write = graph.write(); + NodeState state; + state.fields = fields({{"name", local.title}, {"creationCorrelation", "group-draft"}, {"local", true}}); + auto target = write.upsert({NodeKind::Thread, "local-thread:group-draft"}, std::move(state)); + if (!local.projectId.empty()) + write.relate( + target, RelationKind::ProjectMembership, local.projectId == "project-a" ? firstProject : secondProject); + if (!local.sectionId.empty()) + write.relate(target, + RelationKind::SectionMembership, + local.sectionId == "shared-section" ? section + : write.find({NodeKind::ThreadSection, local.sectionId})); + static_cast(write.finish()); + return target; + }(); + const auto promoted = adapter.threads(admitted, nullptr, &pane.browserOptions(), &local); + if (promoted) + pane.refresh(*promoted); + passed &= require(threadItem(tree, admitted->id().canonical) == stableDraft && stableDraft->parent() == parent && + tree->currentItem() == stableDraft && !pane.optimisticThread() && !threadItem(tree, local.id), + "graph admission promotes the same grouped row without duplication or movement"); + { + auto write = graph.write(); + write.remove(admitted); + static_cast(write.finish()); + } + pane.refresh(*snapshot); + } + return passed; } - snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - passed &= - require(threadItem(tree, id) == created && - (threadItem(tree, "standalone-member")->parent() == - created) == assign, - "empty-to-populated-to-empty sections retain their " - "existing row identity"); - } - } - } - snapshot->canControl = false; - pane.refresh(*snapshot); - const auto observerPoint = - tree->visualItemRect(threadItem(tree, "project-a")).topLeft() + QPoint(40, UiStyle::projectCardEdgePadding + 12); - QMetaObject::invokeMethod(tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, observerPoint)); - QPointer observerMenu; - QAction* details = nullptr; - for (auto* menu : tree->findChildren()) { - if (menu->isVisible()) { - observerMenu = menu; - for (auto* action : menu->actions()) { - if (action->text() == "Details…") { - details = action; - } - } - } - } - passed &= require(details != nullptr, "observer project menu offers details"); - if (details) { - QTimer::singleShot(0, &pane, [&] { - auto* dialog = pane.findChild("threadGroupDialog"); - passed &= require(dialog != nullptr, "observer can inspect project details"); - if (dialog) { - auto* add = dialog->findChild("addProjectRoot"); - auto* roots = dialog->findChild("projectRoots"); - passed &= require(add && !add->isEnabled() && roots && roots->isReadOnly(), - "observer project roots cannot be edited through text or Add root"); - dialog->reject(); - } - }); - details->trigger(); - } - if (observerMenu) { - observerMenu->close(); - } - - QMetaObject::invokeMethod(groupControl->menu(), "aboutToShow", - Qt::DirectConnection); - for (auto *action : groupControl->menu()->actions()) - if (action->text().startsWith("New ")) - passed &= require(!action->isEnabled(), - "observer group-creation controls are disabled"); - { - auto write = graph.write(); - write.setField(write.find({NodeKind::Catalog, - threadBrowserKey("project/list", - nlohmann::json::object())}), - "unsupported", true); - static_cast(write.finish()); - } - snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); - pane.refresh(*snapshot); - passed &= require(!snapshot->groupingAvailable && - threadItem(tree, "group-parent") && - !threadItem(tree, "group-parent")->parent() && - !threadItem(tree, "project-a"), - "older servers retain the existing thread hierarchy " - "without invented projects"); - pane.hide(); - return passed; -} -bool forkNamesPreserveTheirLineage() { - const std::vector titles{"Original", - "Original (fork 1)", - "Original (fork 2)", - "Original (fork 1.1)", - "Original (fork 1.3)", - "Original (fork 1.1.1)"}; - return require(suggestForkName("Original", titles) == "Original (fork 3)", - "a repeated root fork did not use the next root number") && - require(suggestForkName("Original (fork 1)", titles) == - "Original (fork 1.2)", - "a fork of a fork lost its parent lineage") && - require(suggestForkName("Original (fork 1.1)", titles) == - "Original (fork 1.1.2)", - "a nested fork did not use its own next child number") && - require(suggestForkName("Separate", titles) == "Separate (fork 1)", - "an unrelated thread did not start at fork 1"); -} + bool groupedThreadsPreserveIdentityAndInteractions() { + using namespace nodegraph; + NodeGraph graph; + NodeRef root, child, sibling, firstProject, secondProject, section; + const auto fields = [](nlohmann::json value) { + return *valueFromJson(value).asObject(); + }; + { + auto write = graph.write(); + NodeState connection; + connection.status = NodeStatus::Connected; + connection.fields = fields({{"providerState", "ready"}, {"role", "controller"}}); + static_cast(write.upsert({NodeKind::Connection, "connection"}, std::move(connection))); + const auto entity = [&](NodeKind kind, std::string id, nlohmann::json data) { + NodeState state; + state.fields = fields(std::move(data)); + return write.upsert({kind, std::move(id)}, std::move(state)); + }; + firstProject = + entity(NodeKind::Project, + "project-a", + {{"name", "CodexUI — project"}, + {"position", 0}, + {"roots", nlohmann::json::array({{{"path", "/workspace/ui"}}})}, + {"metadata", + {{"codexui.description", "Project description\nNot model instructions"}, {"other-client", "preserved"}}}}); + secondProject = entity(NodeKind::Project, + "project-b", + {{"name", "AISuite — very long project name with Unicode 日本語"}, + {"position", 1}, + {"metadata", nlohmann::json::object()}}); + section = entity(NodeKind::ThreadSection, + "shared-section", + {{"name", "In progress"}, {"appearance", {{"icon", "star"}, {"color", "purple"}}}}); + root = entity(NodeKind::Thread, "group-parent", {{"name", "Parent"}, {"cwd", "/workspace/ui"}, {"recencyAt", 10}}); + child = entity(NodeKind::Thread, "group-child", {{"name", "Child"}, {"cwd", "/workspace/bridge"}, {"recencyAt", 20}}); + sibling = entity(NodeKind::Thread, "group-sibling", {{"name", "Sibling"}, {"cwd", "/workspace/ui"}, {"recencyAt", 30}}); + write.relate(root, RelationKind::AgentChildThread, child); + write.relate(root, RelationKind::ProjectMembership, firstProject); + write.relate(child, RelationKind::ProjectMembership, secondProject); + write.relate(sibling, RelationKind::ProjectMembership, firstProject); + for (const auto& thread : {root, child, sibling}) + write.relate(thread, RelationKind::SectionMembership, section); + const auto standaloneSection = + entity(NodeKind::ThreadSection, + "standalone-section", + {{"name", "Personal research"}, {"appearance", {{"icon", "folder"}, {"color", "blue"}}}}); + const auto standaloneMember = entity(NodeKind::Thread, "standalone-member", {{"name", "Research outside projects"}}); + write.relate(standaloneMember, RelationKind::SectionMembership, standaloneSection); + static_cast(entity(NodeKind::Thread, "ungrouped-thread", {{"name", "Independent conversation"}})); + for (std::string method : {"project/list", "threadSection/list"}) + entity(NodeKind::Catalog, + threadBrowserKey(method, nlohmann::json::object()), + {{"loaded", true}, {"pending", false}, {"unsupported", false}, {"hasMore", false}}); + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.resize(330, 680); + if (const int width = qEnvironmentVariableIntValue("CODEXUI_GROUP_WIDTH"); width > 0) + pane.resize(width, 680); + if (const int points = qEnvironmentVariableIntValue("CODEXUI_GROUP_FONT"); points > 0) { + auto font = pane.font(); + font.setPointSize(points); + pane.setFont(font); + } + NodeRef selected; + int changes = 0; + std::vector queries; + std::vector> mutations; + std::optional> newThreadContext; + middle::ThreadPane::Actions actions; + actions.select = [&](const auto& node) { + selected = node; + }; + actions.browserChanged = [&] { + ++changes; + }; + actions.browse = [&](nlohmann::json query) { + queries.push_back(std::move(query)); + }; + actions.manage = [&](auto kind, nlohmann::json parameters) { + mutations.emplace_back(kind, std::move(parameters)); + }; + actions.newGroupedThread = [&](std::string project, std::string section) { + newThreadContext = std::array{std::move(project), std::move(section)}; + }; + pane.setActions(std::move(actions)); + auto snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); + bool passed = require(snapshot && snapshot->groupingAvailable, "project and section catalogs enable grouped projection"); + if (!snapshot) + return false; + pane.refresh(*snapshot); + pane.show(); + QApplication::processEvents(); + auto* tree = threadTree(pane); + auto* rootItem = threadItem(tree, "group-parent"); + auto* childItem = threadItem(tree, "group-child"); + auto* siblingItem = threadItem(tree, "group-sibling"); + passed &= require(rootItem && childItem && siblingItem, "grouping preserves all three threads"); + if (!rootItem || !childItem || !siblingItem) + return false; + const auto* standalone = threadItem(tree, "standalone-section"); + const auto* ungrouped = threadItem(tree, "ungrouped-thread"); + if (standalone && standalone->childCount()) { + const bool expanded = standalone->isExpanded(); + tree->expandItem(standalone); + QApplication::processEvents(); + const auto sectionMember = tree->visualItemRect(standalone->child(0)); + const auto bodies = tree->findChildren(QStringLiteral("projectThreadBody")); + const auto projectRow = bodies.isEmpty() + ? QRect{} + : bodies.front()->visualRect(bodies.front()->model()->index(0, 0, bodies.front()->rootIndex())); + passed &= require(projectRow.isValid() && sectionMember.height() == projectRow.height() && + sectionMember.height() >= tree->fontMetrics().height(), + "standalone and project members share actual compact geometry without clipping their font"); + passed &= require(tree->visualItemRect(standalone).height() == sectionMember.height() + UiStyle::projectCardEdgePadding, + "expanded section headers reserve only the card's top padding before their first member"); + const auto* last = standalone->child(standalone->childCount() - 1); + passed &= require(tree->visualItemRect(last).height() == sectionMember.height() + UiStyle::projectCardEdgePadding, + "the terminal section row owns the enclosing card's bottom padding"); + tree->setExpanded(tree->indexFromItem(standalone), expanded); + } -bool forkHierarchyIgnoresRootReadOrder() { - using namespace nodegraph; - NodeGraph graph; - ProtocolUpdater updater(graph); - std::vector threads; - for (const char* id : {"origin", "fork", "nested-fork"}) { - Value::Object fields{{"id", Value(id)}, {"name", Value(id)}, {"projectId", Value("project")}}; - if (std::string_view(id) != "origin") { - fields.emplace("forkedFromId", Value(std::string_view(id) == "fork" ? "origin" : "fork")); + for (const auto* id : {"shared-section", "standalone-section"}) { + const auto tooltip = threadItem(tree, id)->data(0, Qt::ToolTipRole).toString(); + passed &= require(!tooltip.contains("star") && !tooltip.contains("folder") && !tooltip.contains("appearance"), + "nested and standalone section headings and tooltips ignore appearance metadata"); + } + tree->scrollToItem(threadItem(tree, "ungrouped-thread")); + QApplication::processEvents(); + const auto currentBeforeContext = tree->currentIndex(); + const auto selectionBeforeContext = tree->selectionModel()->selectedRows(); + const auto activeBeforeContext = selected; + click(tree->viewport(), tree->visualItemRect(ungrouped).center(), Qt::RightButton); + passed &= require(tree->currentIndex() == currentBeforeContext && + tree->selectionModel()->selectedRows() == selectionBeforeContext && selected == activeBeforeContext, + "an outer-tree context click preserves the current conversation and shared selection"); + const auto projectsFirst = [&] { + const int first = tree->indexOfTopLevelItem(threadItem(tree, "project-a")); + const int second = tree->indexOfTopLevelItem(threadItem(tree, "project-b")); + return std::min(first, second) == 0 && std::max(first, second) == 1; + }; + passed &= require(projectsFirst(), "projects precede standalone threads and sections"); + for (auto criterion : {middle::ThreadPane::SortCriterion::Alphanumeric, + middle::ThreadPane::SortCriterion::Created, + middle::ThreadPane::SortCriterion::Recency}) { + pane.setSortCriterion(criterion); + passed &= require(projectsFirst(), "changing thread sort keeps projects first"); + } + pane.beginOptimisticThread(localDraft("draft-order", "draft-order", "Draft", "/workspace")); + passed &= require(projectsFirst(), "creating a draft keeps projects first"); + pane.refresh(*snapshot); + passed &= require(projectsFirst(), "refreshing with a draft keeps projects first"); + pane.discardOptimisticThread("draft-order"); + passed &= require(standalone && !standalone->parent() && ungrouped && !ungrouped->parent() && + threadItem(tree, "standalone-member")->parent() == standalone, + "standalone sections and ungrouped threads are outer cards " + "without a synthetic No project container"); + passed &= require(childItem->parent() != rootItem && childItem->parent()->parent() == threadItem(tree, "project-b"), + "a cross-project child is shown once in its own project"); + passed &= require(tree->currentItem() == childItem, "selected thread survives grouped population"); + const auto accessible = threadAccessible(tree, childItem); + const auto accessibleId = accessible ? QAccessible::uniqueId(accessible) : 0; + const auto before = pane.grab().toImage(); + pane.refresh(*snapshot); + QApplication::processEvents(); + passed &= require(pane.grab().toImage() == before && threadItem(tree, "group-child") == childItem, + "a grouped semantic no-op preserves pixels and row identity"); + { + auto write = graph.write(); + write.setField(section, "appearance", *valueFromJson({{"icon", "changed-marker"}, {"color", "orange"}}).asObject()); + static_cast(write.finish()); + } + snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + QApplication::processEvents(); + passed &= + require(pane.grab().toImage() == before, "another client's section appearance change leaves native presentation unchanged"); + { + auto write = graph.write(); + write.replaceRelated(child, RelationKind::ProjectMembership, std::array{firstProject}); + static_cast(write.finish()); + } + snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + QApplication::processEvents(); + passed &= require(threadItem(tree, "group-child") == childItem && childItem->parent() == rootItem, + "membership reconciliation reparents the existing child row"); + passed &= require(tree->currentItem() == childItem && threadAccessible(tree, childItem) && + QAccessible::uniqueId(threadAccessible(tree, childItem)) == accessibleId, + "reparenting preserves selection and accessible identity"); + auto* groupControl = pane.findChild("threadGroupingButton"); + passed &= require(groupControl->property("codexChevron").toBool() && groupControl->minimumHeight() == 28 && + !groupControl->toolTip().isEmpty(), + "grouping uses the same styled single-chevron control as sorting"); + for (auto* action : groupControl->menu()->actions()) + if (action->text() == "Sections") + action->trigger(); + QMetaObject::invokeMethod(groupControl->menu(), "aboutToShow", Qt::DirectConnection); + int checkedModes = 0; + for (auto* action : groupControl->menu()->actions()) { + if (!action->actionGroup()) + continue; + checkedModes += action->isChecked(); + passed &= require(action->isCheckable() && action->isChecked() == (action->text() == "Sections"), + "grouping menu reflects the authoritative selected mode"); + } + passed &= require(checkedModes == 1, "exactly one grouping mode is checked"); + snapshot = adapter.threads(child, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + QApplication::processEvents(); + passed &= require(changes > 0 && childItem->parent() == rootItem && rootItem->parent() == threadItem(tree, "shared-section"), + "Sections view preserves same-group family nesting"); + passed &= require(!rootItem->parent()->data(0, Qt::ToolTipRole).toString().contains("changed-marker"), + "Sections view ignores appearance metadata after regrouping"); + + auto* search = pane.findChild("threadTitleSearch"); + search->setText("Sibling"); + QMetaObject::invokeMethod(search, "returnPressed", Qt::DirectConnection); + snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + QApplication::processEvents(); + passed &= require(!threadItem(tree, "group-parent") && threadItem(tree, "group-sibling"), + "title filtering changes discovery without deleting graph entities"); + passed &= require(!queries.empty() && queries.back().at("parameters").value("searchTerm", "") == "Sibling", + "title search submits a server-backed query"); + search->clear(); + auto* archive = pane.findChild("threadArchiveFilter"); + archive->setCurrentIndex(1); + snapshot = adapter.threads({}, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + passed &= require(!threadItem(tree, "group-sibling"), "archive filtering excludes active threads"); + archive->setCurrentIndex(0); + for (auto* action : groupControl->menu()->actions()) + if (action->text() == "Projects → Sections") + action->trigger(); + snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + tree->expandAll(); + QApplication::processEvents(); + const auto titleImage = [&](const std::string& title) { + { + auto write = graph.write(); + write.setField(root, "name", title); + static_cast(write.finish()); + } + pane.refresh(*adapter.threads(root, nullptr, &pane.browserOptions())); + QApplication::processEvents(); + return pane.grab().toImage(); + }; + for (const auto& title : {std::string("First\nSecond"), + std::string("First\r\nSecond"), + std::string("First\xE2\x80\xA8Second"), + std::string("First\nSecond with a very long title 日本語 and more words")}) { + const auto multiline = titleImage(title); + auto* row = threadItem(tree, "group-parent"); + const auto geometry = tree->visualItemRect(row); + passed &= require(threadAccessible(tree, row)->text(QAccessible::Name).contains(QString::fromStdString(title)), + "single-line painting preserves the full accessible title"); + const auto singleline = titleImage(QString::fromStdString(title).simplified().toStdString()); + passed &= require(multiline == singleline && geometry == tree->visualItemRect(row), + "multiline titles paint as one elided line without " + "changing row geometry"); + } + if (const QString path = qEnvironmentVariable("CODEXUI_GROUP_SCREENSHOT"); !path.isEmpty()) { + static_cast(titleImage("First\nSecond with a very long title 日本語 and more words")); + passed &= require(pane.grab().save(path), "grouped live-widget screenshot saved"); + } + + // Exercise the actual edit dialog and emit authored data, not a handcrafted + // projection of what the dialog ought to send. + for (const bool project : {true, false}) { + const auto beforeEdit = mutations.size(); + auto* groupItem = threadItem(tree, project ? "project-a" : "standalone-section"); + tree->scrollToItem(groupItem); + QApplication::processEvents(); + const QPoint point = tree->visualItemRect(groupItem).topLeft() + QPoint(40, UiStyle::projectCardEdgePadding + 12); + QMetaObject::invokeMethod(tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, point)); + QApplication::processEvents(); + QPointer context; + for (auto* candidate : tree->findChildren()) { + if (candidate->isVisible()) { + context = candidate; + } + } + if (context) { + QAction* edit = nullptr; + for (auto* action : context->actions()) { + if (action->text() == "Edit…") { + edit = action; + } + } + QTimer::singleShot(0, [&] { + auto* dialog = pane.findChild("threadGroupDialog"); + passed &= require(dialog != nullptr, "group edit opens the real dialog"); + if (dialog) { + auto* description = dialog->findChild("projectDescription"); + if (description) { + description->setPlainText("Edited description 日本語"); + } + if (!project) { + passed &= + require(dialog->findChildren().size() == 1, "section editing exposes only the name field"); + dialog->findChild("groupName")->setText("Renamed section"); + } + if (const QString path = qEnvironmentVariable("CODEXUI_GROUP_DIALOG_SCREENSHOT"); !path.isEmpty()) { + passed &= require(dialog->grab().save(project ? path : path + ".section.png"), + "group edit dialog screenshot saved"); + } + auto* buttons = dialog->findChild(); + if (buttons) { + buttons->button(QDialogButtonBox::Save)->click(); + } + } + }); + if (edit) { + edit->trigger(); + } + if (context) { + context->close(); + } + } + passed &= + require(mutations.size() == beforeEdit + 1 && + mutations.back().first == (project ? RuntimeActionKind::UpdateProject : RuntimeActionKind::UpdateSection) && + (project ? mutations.back().second.value("description", "") == "Edited description 日本語" + : mutations.back().second == + nlohmann::json{{"sectionId", "standalone-section"}, {"name", "Renamed section"}}), + "group edits submit authored fields without foreign project metadata or section appearance"); + } + for (const bool project : {true, false}) { + const QString label = project ? "New project…" : "New section…"; + const std::string id = project ? "new-empty-project" : "new-empty-section"; + const auto beforeCreate = mutations.size(); + QTimer::singleShot(0, [&] { + auto* dialog = pane.findChild("threadGroupDialog"); + if (!dialog) + return; + auto* name = dialog->findChild("groupName"); + if (!project) { + passed &= require(dialog->findChildren().size() == 1, "new section dialog exposes only the name field"); + if (const QString prefix = qEnvironmentVariable("CODEXUI_GROUP_CREATE_SCREENSHOT"); !prefix.isEmpty()) { + passed &= require(dialog->grab().save(prefix + "-empty-section.png"), "empty section dialog screenshot saved"); + } + } + auto* save = dialog->findChild()->button(QDialogButtonBox::Save); + save->click(); + passed &= + require(mutations.size() == beforeCreate && dialog->isVisible(), "empty group names do not dispatch a mutation"); + name->setText(QString::fromStdString(id)); + if (project) { + auto* roots = dialog->findChild("projectRoots"); + roots->setPlainText("relative/path"); + save->click(); + passed &= require(mutations.size() == beforeCreate && dialog->isVisible(), + "relative project roots are rejected before dispatch"); + roots->setPlainText("/workspace/new\n/workspace/second"); + auto* add = dialog->findChild("addProjectRoot"); + passed &= require(add && add->isEnabled(), "a controller can add project roots"); + if (add) { + const auto choose = [&](QString path, bool accept) { + QTimer::singleShot(0, dialog, [&, path, accept] { + auto* selection = dynamic_cast(QApplication::activeModalWidget()); + passed &= require(selection != nullptr, "Add root opens the existing workspace dialog"); + if (selection) { + selection->findChild("codexWorkspaceDirectory")->setText(path); + if (accept) { + selection->accept(); + } else { + selection->reject(); + } + } + }); + add->click(); + }; + choose("/workspace/third", true); + choose("/workspace/fourth", true); + choose("/workspace/third", true); + choose("/cancelled", false); + passed &= + require(roots->toPlainText() == "/workspace/new\n/workspace/second\n/workspace/third\n/workspace/fourth" && + mutations.size() == beforeCreate, + "root additions preserve manual lines, reject duplicates and leave cancellation unsent"); + } + + dialog->findChild("projectDescription")->setPlainText("Description 日本語"); + } + if (const QString prefix = qEnvironmentVariable("CODEXUI_GROUP_CREATE_SCREENSHOT"); !prefix.isEmpty()) { + auto* roots = dialog->findChild("projectRoots"); + const auto original = roots ? roots->toPlainText() : QString{}; + if (roots) { + roots->appendPlainText("/server/" + QString("long-directory/").repeated(30)); + } + for (const auto width : {dialog->minimumSizeHint().width(), 520}) { + dialog->resize(width, dialog->height()); + QApplication::processEvents(); + for (auto* label : dialog->findChildren()) { + if (!project && label->wordWrap() && !label->text().isEmpty()) { + passed &= require(label->height() >= label->heightForWidth(label->width()), + "section dialog text remains fully visible at narrow widths and enlarged fonts"); + } + } + passed &= require( + dialog->grab().save(prefix + (project ? "-project-" : "-section-") + QString::number(width) + ".png"), + "group creation dialog screenshot saved"); + } + if (roots) { + roots->setPlainText(original); + } + } + save->click(); + }); + for (auto* action : groupControl->menu()->actions()) + if (action->text() == label) + action->trigger(); + passed &= + require(mutations.size() == beforeCreate + 1 && + mutations.back().first == (project ? RuntimeActionKind::CreateProject : RuntimeActionKind::CreateSection) && + mutations.back().second.at("name") == id, + "creation menu submits exactly one authored group mutation"); + if (mutations.size() == beforeCreate) + continue; + const auto& parameters = mutations.back().second; + if (!project) { + passed &= require(parameters == nlohmann::json{{"name", id}}, "section creation submits only its name"); + } + if (project) + passed &= require(parameters.at("roots").size() == 4 && + parameters.at("metadata").at(ProjectDescriptionKey) == "Description 日本語" && + !parameters.value("idempotencyKey", "").empty(), + "project creation retains roots, description and idempotency key"); + passed &= require(!threadItem(tree, id), "creation does not invent an optimistic group"); + // Deliver the authoritative entity, as the separately tested runtime + // reducer does after the create response. No thread membership exists yet. + { + auto write = graph.write(); + NodeState state; + state.fields = fields(parameters); + static_cast(write.upsert({project ? NodeKind::Project : NodeKind::ThreadSection, id}, std::move(state))); + static_cast(write.finish()); + } + snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + QApplication::processEvents(); + auto* created = threadItem(tree, id); + passed &= require(created && !created->parent(), + "new empty projects and sections are visible outer cards " + "in Projects view"); + if (!created) + continue; + tree->scrollToItem(created); + QApplication::processEvents(); + QMetaObject::invokeMethod( + tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, tree->visualItemRect(created).center())); + for (auto* menu : tree->findChildren()) + if (menu->isVisible()) { + for (auto* action : menu->actions()) + if (action->text() == "New thread here…") + action->trigger(); + menu->close(); + } + passed &= require(newThreadContext == std::optional(std::array{project ? id : std::string{}, project ? std::string{} : id}), + "an empty group passes project and section identity to thread creation, " + "which owns workspace selection"); + if (!project) { + for (const bool assign : {true, false}) { + { + auto write = graph.write(); + const auto member = write.find({NodeKind::Thread, "standalone-member"}); + if (assign) + write.replaceRelated( + member, RelationKind::SectionMembership, std::array{write.find({NodeKind::ThreadSection, id})}); + else + write.replaceRelated(member, RelationKind::SectionMembership, {}); + static_cast(write.finish()); + } + snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + passed &= require(threadItem(tree, id) == created && + (threadItem(tree, "standalone-member")->parent() == created) == assign, + "empty-to-populated-to-empty sections retain their " + "existing row identity"); + } + } + } + snapshot->canControl = false; + pane.refresh(*snapshot); + const auto observerPoint = + tree->visualItemRect(threadItem(tree, "project-a")).topLeft() + QPoint(40, UiStyle::projectCardEdgePadding + 12); + QMetaObject::invokeMethod(tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, observerPoint)); + QPointer observerMenu; + QAction* details = nullptr; + for (auto* menu : tree->findChildren()) { + if (menu->isVisible()) { + observerMenu = menu; + for (auto* action : menu->actions()) { + if (action->text() == "Details…") { + details = action; + } + } + } + } + passed &= require(details != nullptr, "observer project menu offers details"); + if (details) { + QTimer::singleShot(0, &pane, [&] { + auto* dialog = pane.findChild("threadGroupDialog"); + passed &= require(dialog != nullptr, "observer can inspect project details"); + if (dialog) { + auto* add = dialog->findChild("addProjectRoot"); + auto* roots = dialog->findChild("projectRoots"); + passed &= require(add && !add->isEnabled() && roots && roots->isReadOnly(), + "observer project roots cannot be edited through text or Add root"); + dialog->reject(); + } + }); + details->trigger(); + } + if (observerMenu) { + observerMenu->close(); + } + + QMetaObject::invokeMethod(groupControl->menu(), "aboutToShow", Qt::DirectConnection); + for (auto* action : groupControl->menu()->actions()) + if (action->text().startsWith("New ")) + passed &= require(!action->isEnabled(), "observer group-creation controls are disabled"); + { + auto write = graph.write(); + write.setField( + write.find({NodeKind::Catalog, threadBrowserKey("project/list", nlohmann::json::object())}), "unsupported", true); + static_cast(write.finish()); + } + snapshot = adapter.threads(root, nullptr, &pane.browserOptions()); + pane.refresh(*snapshot); + passed &= require(!snapshot->groupingAvailable && threadItem(tree, "group-parent") && + !threadItem(tree, "group-parent")->parent() && !threadItem(tree, "project-a"), + "older servers retain the existing thread hierarchy " + "without invented projects"); + pane.hide(); + return passed; } - static_cast( - updater.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", Value(std::move(fields))}}})); - auto read = graph.tryRead(); - threads.push_back(read->find({NodeKind::Thread, id})); - } - { - auto write = graph.write(); - for (const char* method : {"project/list", "threadSection/list"}) { - static_cast(write.upsert({NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object())})); + + bool forkNamesPreserveTheirLineage() { + const std::vector titles{"Original", + "Original (fork 1)", + "Original (fork 2)", + "Original (fork 1.1)", + "Original (fork 1.3)", + "Original (fork 1.1.1)"}; + return require(suggestForkName("Original", titles) == "Original (fork 3)", + "a repeated root fork did not use the next root number") && + require(suggestForkName("Original (fork 1)", titles) == "Original (fork 1.2)", + "a fork of a fork lost its parent lineage") && + require(suggestForkName("Original (fork 1.1)", titles) == "Original (fork 1.1.2)", + "a nested fork did not use its own next child number") && + require(suggestForkName("Separate", titles) == "Separate (fork 1)", "an unrelated thread did not start at fork 1"); } - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.resize(340, 600); - pane.show(); - bool passed = true; - QTreeWidgetItem* retainedFork = nullptr; - for (const auto& selected : {threads[0], threads[1], threads[2], threads[0]}) { - const ProtocolRequestId requestId("read-" + selected->id().canonical); - const auto request = - updater.apply({DecodedMessageKind::ClientRequest, "thread/read", requestId, {{"threadId", Value(selected->id().canonical)}}}); - DecodedMessage response{DecodedMessageKind::ClientResult, - "thread/read", - requestId, - {{"thread", Value(Value::Object{{"id", Value(selected->id().canonical)}})}}}; - response.expectedNode = request.primary; - static_cast(updater.apply(std::move(response))); - for (const auto grouping : {ui::ThreadGrouping::Ungrouped, ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { + + bool forkHierarchyIgnoresRootReadOrder() { + using namespace nodegraph; + NodeGraph graph; + ProtocolUpdater updater(graph); + std::vector threads; + for (const char* id : {"origin", "fork", "nested-fork"}) { + Value::Object fields{{"id", Value(id)}, {"name", Value(id)}, {"projectId", Value("project")}}; + if (std::string_view(id) != "origin") { + fields.emplace("forkedFromId", Value(std::string_view(id) == "fork" ? "origin" : "fork")); + } + static_cast( + updater.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", Value(std::move(fields))}}})); + auto read = graph.tryRead(); + threads.push_back(read->find({NodeKind::Thread, id})); + } + { + auto write = graph.write(); + for (const char* method : {"project/list", "threadSection/list"}) { + static_cast(write.upsert({NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object())})); + } + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.resize(340, 600); + pane.show(); + bool passed = true; + QTreeWidgetItem* retainedFork = nullptr; + for (const auto& selected : {threads[0], threads[1], threads[2], threads[0]}) { + const ProtocolRequestId requestId("read-" + selected->id().canonical); + const auto request = updater.apply( + {DecodedMessageKind::ClientRequest, "thread/read", requestId, {{"threadId", Value(selected->id().canonical)}}}); + DecodedMessage response{DecodedMessageKind::ClientResult, + "thread/read", + requestId, + {{"thread", Value(Value::Object{{"id", Value(selected->id().canonical)}})}}}; + response.expectedNode = request.primary; + static_cast(updater.apply(std::move(response))); + for (const auto grouping : {ui::ThreadGrouping::Ungrouped, ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { + ui::ThreadBrowserOptions browser; + browser.grouping = grouping; + pane.refresh(*adapter.threads(selected, nullptr, &browser)); + QApplication::processEvents(); + auto* tree = threadTree(pane); + auto* origin = threadItem(tree, "origin"); + auto* fork = threadItem(tree, "fork"); + auto* nested = threadItem(tree, "nested-fork"); + passed &= require(origin && fork && nested && fork->parent() == origin && nested->parent() == fork && + tree->currentItem() == threadItem(tree, selected->id().canonical), + "fork lineage and selection must survive read order and grouping"); + passed &= require(!retainedFork || retainedFork == fork, "fork refresh and regrouping must preserve row identity"); + retainedFork = fork; + } + } ui::ThreadBrowserOptions browser; - browser.grouping = grouping; - pane.refresh(*adapter.threads(selected, nullptr, &browser)); - QApplication::processEvents(); + browser.title = "nested-fork"; + pane.refresh(*adapter.threads(threads[2], nullptr, &browser)); auto* tree = threadTree(pane); - auto* origin = threadItem(tree, "origin"); - auto* fork = threadItem(tree, "fork"); - auto* nested = threadItem(tree, "nested-fork"); - passed &= require(origin && fork && nested && fork->parent() == origin && nested->parent() == fork && - tree->currentItem() == threadItem(tree, selected->id().canonical), - "fork lineage and selection must survive read order and grouping"); - passed &= require(!retainedFork || retainedFork == fork, "fork refresh and regrouping must preserve row identity"); - retainedFork = fork; - } - } - ui::ThreadBrowserOptions browser; - browser.title = "nested-fork"; - pane.refresh(*adapter.threads(threads[2], nullptr, &browser)); - auto* tree = threadTree(pane); - auto* visible = threadItem(tree, "nested-fork"); - passed &= require(visible && visible->parent() && !threadItem(tree, "origin") && !threadItem(tree, "fork"), - "a matching nested fork stays visible when its ancestors are filtered"); - { - auto write = graph.write(); - auto otherProject = write.upsert({NodeKind::Project, "other-project"}); - auto otherSection = write.upsert({NodeKind::ThreadSection, "other-section"}); - for (const auto& thread : {threads[1], threads[2]}) { - write.replaceRelated(thread, RelationKind::ProjectMembership, std::array{otherProject}); - write.replaceRelated(thread, RelationKind::SectionMembership, std::array{otherSection}); - } - static_cast(write.finish()); - } - browser.title.clear(); - for (const auto grouping : {ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { - browser.grouping = grouping; - pane.refresh(*adapter.threads(threads[1], nullptr, &browser)); - auto* origin = threadItem(tree, "origin"); - auto* fork = threadItem(tree, "fork"); - auto* nested = threadItem(tree, "nested-fork"); - passed &= - require(origin && fork && nested && fork->parent() != origin && fork->parent() != origin->parent() && nested->parent() == fork, - "forks in another group retain their membership and nested lineage"); - } - const auto split = adapter.threads(threads[1], nullptr, &browser); - const auto checkParent = [&](const auto& self, const std::vector& rows) -> void { - for (const auto& row : rows) { - if (row.target == threads[1]) { - passed &= require(row.parentThread == threads[0], "cross-project fork retains Go to parent identity"); + auto* visible = threadItem(tree, "nested-fork"); + passed &= require(visible && visible->parent() && !threadItem(tree, "origin") && !threadItem(tree, "fork"), + "a matching nested fork stays visible when its ancestors are filtered"); + { + auto write = graph.write(); + auto otherProject = write.upsert({NodeKind::Project, "other-project"}); + auto otherSection = write.upsert({NodeKind::ThreadSection, "other-section"}); + for (const auto& thread : {threads[1], threads[2]}) { + write.replaceRelated(thread, RelationKind::ProjectMembership, std::array{otherProject}); + write.replaceRelated(thread, RelationKind::SectionMembership, std::array{otherSection}); + } + static_cast(write.finish()); + } + browser.title.clear(); + for (const auto grouping : {ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { + browser.grouping = grouping; + pane.refresh(*adapter.threads(threads[1], nullptr, &browser)); + auto* origin = threadItem(tree, "origin"); + auto* fork = threadItem(tree, "fork"); + auto* nested = threadItem(tree, "nested-fork"); + passed &= require(origin && fork && nested && fork->parent() != origin && fork->parent() != origin->parent() && + nested->parent() == fork, + "forks in another group retain their membership and nested lineage"); } - self(self, row.children); + const auto split = adapter.threads(threads[1], nullptr, &browser); + const auto checkParent = [&](const auto& self, const std::vector& rows) -> void { + for (const auto& row : rows) { + if (row.target == threads[1]) { + passed &= require(row.parentThread == threads[0], "cross-project fork retains Go to parent identity"); + } + self(self, row.children); + } + }; + checkParent(checkParent, split->roots); + return passed; } - }; - checkParent(checkParent, split->roots); - return passed; -} -bool selectedChildRetainsRootAndCanonicalIdentity() { - nodegraph::NodeGraph graph; - nodegraph::NodeRef root; - nodegraph::NodeRef child; - { - auto write = graph.write(); - nodegraph::NodeRef runtime = - write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); - nodegraph::NodeState rootState; - rootState.fields.emplace("name", "Root"); - root = write.upsert({nodegraph::NodeKind::Thread, "root"}, - std::move(rootState)); - nodegraph::NodeState childState; - childState.fields.emplace("name", "Child"); - child = write.upsert({nodegraph::NodeKind::Thread, "child"}, - std::move(childState)); - write.relate(runtime, nodegraph::RelationKind::RootThread, root); - write.relate(root, nodegraph::RelationKind::AgentChildThread, child); - static_cast(write.finish()); - } - - ui::NodeGraphUiAdapter adapter(graph); - const auto snapshot = adapter.threads(child); - if (!require(snapshot.has_value(), "thread adapter read failed")) - return false; - - middle::ThreadPane pane; - pane.resize(300, 500); - nodegraph::NodeRef selected; - int selectionCount = 0; - middle::ThreadPane::Actions actions; - actions.select = [&](const nodegraph::NodeRef &target) { - selected = target; - ++selectionCount; - }; - pane.setActions(std::move(actions)); - pane.refresh(*snapshot); - pane.show(); - QApplication::processEvents(); - - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *rootItem = threadItem(tree, "root"); - QTreeWidgetItem *childItem = threadItem(tree, "child"); - if (!require(tree && tree->topLevelItemCount() == 1 && rootItem && childItem, - "selected child did not retain its tree hierarchy") || - !require(childItem->parent() == rootItem && rootItem->isExpanded(), - "selected child is not nested below its expanded root")) - return false; - tree->setCurrentItem(rootItem); - QApplication::processEvents(); - selected.reset(); - tree->setCurrentItem(childItem); - QApplication::processEvents(); - if (!require(selected == child, - "thread UI changed the exact selection identity")) - return false; - selected.reset(); - selectionCount = 0; - tree->setCurrentItem(rootItem); - tree->setCurrentItem(childItem); - tree->setCurrentItem(rootItem); - QApplication::processEvents(); - return require(selected == root && selectionCount == 1, - "queued selection dispatched a stale intermediate target") && - require(tree->topLevelItem(0) == rootItem, - "selecting a child removed its root row"); -} + bool selectedChildRetainsRootAndCanonicalIdentity() { + nodegraph::NodeGraph graph; + nodegraph::NodeRef root; + nodegraph::NodeRef child; + { + auto write = graph.write(); + nodegraph::NodeRef runtime = write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); + nodegraph::NodeState rootState; + rootState.fields.emplace("name", "Root"); + root = write.upsert({nodegraph::NodeKind::Thread, "root"}, std::move(rootState)); + nodegraph::NodeState childState; + childState.fields.emplace("name", "Child"); + child = write.upsert({nodegraph::NodeKind::Thread, "child"}, std::move(childState)); + write.relate(runtime, nodegraph::RelationKind::RootThread, root); + write.relate(root, nodegraph::RelationKind::AgentChildThread, child); + static_cast(write.finish()); + } + + ui::NodeGraphUiAdapter adapter(graph); + const auto snapshot = adapter.threads(child); + if (!require(snapshot.has_value(), "thread adapter read failed")) + return false; + + middle::ThreadPane pane; + pane.resize(300, 500); + nodegraph::NodeRef selected; + int selectionCount = 0; + middle::ThreadPane::Actions actions; + actions.select = [&](const nodegraph::NodeRef& target) { + selected = target; + ++selectionCount; + }; + pane.setActions(std::move(actions)); + pane.refresh(*snapshot); + pane.show(); + QApplication::processEvents(); + + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* rootItem = threadItem(tree, "root"); + QTreeWidgetItem* childItem = threadItem(tree, "child"); + if (!require(tree && tree->topLevelItemCount() == 1 && rootItem && childItem, + "selected child did not retain its tree hierarchy") || + !require(childItem->parent() == rootItem && rootItem->isExpanded(), "selected child is not nested below its expanded root")) + return false; + tree->setCurrentItem(rootItem); + QApplication::processEvents(); + selected.reset(); + tree->setCurrentItem(childItem); + QApplication::processEvents(); + if (!require(selected == child, "thread UI changed the exact selection identity")) + return false; + selected.reset(); + selectionCount = 0; + tree->setCurrentItem(rootItem); + tree->setCurrentItem(childItem); + tree->setCurrentItem(rootItem); + QApplication::processEvents(); + return require(selected == root && selectionCount == 1, "queued selection dispatched a stale intermediate target") && + require(tree->topLevelItem(0) == rootItem, "selecting a child removed its root row"); + } -bool accessibilityFollowsTheNativeHierarchy() { + bool accessibilityFollowsTheNativeHierarchy() { #if !QT_CONFIG(accessibility) - return true; + return true; #else - ui::ThreadListRow root; - root.id = "accessible-root"; - root.presentationKey = root.id; - root.title = "Accessible root"; - root.cwd = "/workspace"; - root.status = nodegraph::NodeStatus::Running; - ui::ThreadListRow child; - child.id = "accessible-child"; - child.presentationKey = child.id; - child.title = "Accessible child"; - root.children.push_back(child); - ui::ThreadListSnapshot snapshot; - snapshot.selectedThreadId = root.id; - snapshot.roots.push_back(root); - - middle::ThreadPane pane; - pane.resize(320, 420); - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *rootItem = threadItem(tree, root.id); - QTreeWidgetItem *childItem = threadItem(tree, child.id); - rootItem->setExpanded(false); - QApplication::processEvents(); - QAccessibleInterface *treeAccessible = - QAccessible::queryAccessibleInterface(tree); - QAccessibleInterface *rootAccessible = threadAccessible(tree, rootItem); - QAccessibleInterface *childAccessible = threadAccessible(tree, childItem); - QAccessibleActionInterface *rootActions = - rootAccessible ? rootAccessible->actionInterface() : nullptr; - QAccessibleActionInterface *childActions = - childAccessible ? childAccessible->actionInterface() : nullptr; - QAccessibleSelectionInterface *selection = - treeAccessible ? treeAccessible->selectionInterface() : nullptr; - if (!require(tree && rootItem && childItem && treeAccessible && - rootAccessible && childAccessible && rootActions && - childActions && selection, - "thread hierarchy did not expose semantic accessibility")) - return false; - - tests::AccessibilityEventProbe events; - const QAccessible::Id treeId = QAccessible::uniqueId(treeAccessible); - const QAccessible::Id rootId = QAccessible::uniqueId(rootAccessible); - const QAccessible::Id childId = QAccessible::uniqueId(childAccessible); - - bool passed = true; - passed &= require(treeAccessible->role() == QAccessible::Tree && - treeAccessible->text(QAccessible::Name) == - QStringLiteral("Threads") && - rootAccessible->role() == QAccessible::TreeItem && - childAccessible->role() == QAccessible::TreeItem && - treeAccessible->indexOfChild(rootAccessible) == 0 && - treeAccessible->indexOfChild(childAccessible) == -1 && - rootAccessible->parent() == treeAccessible && - rootAccessible->indexOfChild(childAccessible) == 0 && - childAccessible->parent() == rootAccessible && - selection->selectedItemCount() == 1 && - selection->selectedItems().front() == rootAccessible, - "accessible parentage does not match the native tree"); - passed &= - require(rootAccessible->text(QAccessible::Name) == - QStringLiteral("Accessible root") && - childAccessible->text(QAccessible::Name) == - QStringLiteral("Accessible child") && - rootAccessible->text(QAccessible::Description) - .contains(QStringLiteral("Status: running")) && - rootAccessible->text(QAccessible::Description) - .contains(QStringLiteral("Level 1")) && - childAccessible->text(QAccessible::Description) - .contains(QStringLiteral("Level 2")) && - childAccessible->text(QAccessible::Description) - .contains(QStringLiteral("Parent: Accessible root")), - "accessible names or descriptions diverged from presentation"); - passed &= require(rootAccessible->state().collapsed && - childAccessible->state().invisible && - !childAccessible->state().focusable && - !childAccessible->state().selectable && - childAccessible->rect().isEmpty(), - "collapsed descendants remained visibly accessible"); - childActions->doAction(QAccessibleActionInterface::setFocusAction()); - passed &= - require(childActions->actionNames().isEmpty() && - !selection->select(childAccessible) && - tree->currentItem() == rootItem && !childItem->isSelected(), - "collapsed descendant accepted an accessibility action"); - - events.clear(); - rootActions->doAction(QAccessibleActionInterface::toggleAction()); - QApplication::processEvents(); - const QRect rootRect = rootAccessible->rect(); - const QRect childRect = childAccessible->rect(); - passed &= require( - rootItem->isExpanded() && rootAccessible->state().expanded && - !childAccessible->state().invisible && !childRect.isEmpty() && - rootRect.width() == tree->viewport()->width() && - childRect.width() == tree->viewport()->width() && - rootAccessible->childAt(childRect.center().x(), - childRect.center().y()) == childAccessible && - treeAccessible->childAt(childRect.center().x(), - childRect.center().y()) == rootAccessible, - "accessible expansion, bounds, or hit hierarchy is incorrect"); - const auto expandedEvents = - events.events(rootId, QAccessible::StateChanged); - passed &= require( - expandedEvents.size() == 1 && - expandedEvents.front().changedStates.expanded && - expandedEvents.front().changedStates.collapsed && - expandedEvents.front().state.expanded, - "thread expansion did not emit once on its semantic TreeItem"); - events.clear(); - rootActions->doAction(QAccessibleActionInterface::toggleAction()); - QApplication::processEvents(); - const auto collapsedEvents = - events.events(rootId, QAccessible::StateChanged); - passed &= require( - collapsedEvents.size() == 1 && - collapsedEvents.front().changedStates.expanded && - collapsedEvents.front().changedStates.collapsed && - collapsedEvents.front().state.collapsed, - "thread collapse did not emit once on its semantic TreeItem"); - events.clear(); - rootItem->setExpanded(false); - QApplication::processEvents(); - passed &= require(events.events(rootId, QAccessible::StateChanged).isEmpty(), - "an identical collapsed state emitted accessibility work"); - rootActions->doAction(QAccessibleActionInterface::toggleAction()); - QApplication::processEvents(); - events.clear(); - rootItem->setExpanded(true); - QApplication::processEvents(); - passed &= require(events.events(rootId, QAccessible::StateChanged).isEmpty(), - "an identical expanded state emitted accessibility work"); - - tree->setFocus(Qt::OtherFocusReason); - QApplication::processEvents(); - events.clear(); - passed &= require(!selection->select(childAccessible), - "the root selection interface accepted a nested item"); - childActions->doAction(QAccessibleActionInterface::pressAction()); - QApplication::processEvents(); - const auto selectedChild = - events.events(childId, QAccessible::SelectionAdd); - const auto deselectedRoot = - events.events(rootId, QAccessible::SelectionRemove); - int addOrder = -1; - int removeOrder = -1; - for (qsizetype event = 0; event < events.all().size(); ++event) { - const auto &record = events.all().at(event); - if (record.target == childId && record.type == QAccessible::SelectionAdd) - addOrder = static_cast(event); - if (record.target == rootId && - record.type == QAccessible::SelectionRemove) - removeOrder = static_cast(event); - } - passed &= require(tree->currentItem() == childItem && - childAccessible->state().selected && - childAccessible->state().focused && - selection->selectedItemCount() == 0 && - selection->selectedItems().isEmpty() && - selectedChild.size() == 1 && - deselectedRoot.size() == 1 && - addOrder >= 0 && removeOrder > addOrder && - events.events(childId, QAccessible::Focus).size() == 1 && - std::ranges::none_of(events.all(), [](const auto &event) { - return event.target == 0 && - (event.type == QAccessible::SelectionAdd || - event.type == QAccessible::SelectionRemove || - event.type == QAccessible::Focus); - }), - "accessible focus and selection did not emit once on the " - "semantic items"); - - events.clear(); - childActions->doAction(QAccessibleActionInterface::pressAction()); - QApplication::processEvents(); - passed &= require(events.events(childId).isEmpty(), - "reselecting the current Thread item emitted a semantic event"); - - events.clear(); - childItem->setSelected(false); - passed &= require(tree->currentItem() == childItem && - !childAccessible->state().selected && - childAccessible->state().focused, - "native unselect discarded or hid keyboard focus"); - QApplication::processEvents(); - const auto unselectedChild = - events.events(childId, QAccessible::SelectionRemove); - passed &= require(unselectedChild.size() == 1 && - !unselectedChild.front().state.selected, - "accessible unselect did not notify its semantic item"); - const QRect focusedRow = tree->visualItemRect(childItem); - const auto closestFocusColor = [&focusedRow](const QImage &image) { - const QColor expected(QString::fromLatin1(UiStyle::threadFocusBorder)); - int result = 3 * 255; - for (int x = 0; x <= 2; ++x) - for (int y = focusedRow.top() + 12; y <= focusedRow.bottom() - 12; ++y) { - const qreal dpr = image.devicePixelRatio(); - const QColor actual = - image.pixelColor(qRound(x * dpr), qRound(y * dpr)); - result = - std::min(result, std::abs(actual.red() - expected.red()) + - std::abs(actual.green() - expected.green()) + - std::abs(actual.blue() - expected.blue())); - } - return result; - }; - const QImage focused = tree->viewport()->grab().toImage(); - tree->clearFocus(); - QApplication::processEvents(); - const QImage unfocused = tree->viewport()->grab().toImage(); - const int focusedDistance = closestFocusColor(focused); - const int unfocusedDistance = closestFocusColor(unfocused); - passed &= - require(focusedDistance <= 20 && focusedDistance + 20 < unfocusedDistance, - "unselected keyboard focus lacks its tokenized outline"); - events.clear(); - childActions->doAction(QAccessibleActionInterface::setFocusAction()); - QApplication::processEvents(); - passed &= require( - tree->hasFocus() && childItem->isSelected() && - events.events(treeId, QAccessible::Focus).size() == 1 && - events.events(childId, QAccessible::Focus).isEmpty() && - treeAccessible->focusChild() == childAccessible && - events.events(childId, QAccessible::SelectionAdd).size() == 1, - "native tree focus did not resolve to its unchanged current item"); - events.clear(); - childActions->doAction(QAccessibleActionInterface::setFocusAction()); - QApplication::processEvents(); - passed &= require(events.events(treeId).isEmpty() && - events.events(childId).isEmpty(), - "refocusing the current Thread item emitted semantic work"); - - events.clear(); - snapshot.selectedThreadId = child.id; - snapshot.roots.front().title = "Renamed accessible root"; - snapshot.roots.front().cwd = "/renamed/workspace"; - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(rootId, QAccessible::NameChanged).size() == 1 && - events.events(rootId, QAccessible::DescriptionChanged).size() == 1 && - events.events(childId, QAccessible::DescriptionChanged).size() == 1 && - rootAccessible->text(QAccessible::Name) == - QStringLiteral("Renamed accessible root"), - "Thread presentation mutation did not notify its retained semantic item"); - events.clear(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(rootId, QAccessible::NameChanged).isEmpty() && - events.events(rootId, QAccessible::DescriptionChanged).isEmpty() && - events.events(childId, QAccessible::DescriptionChanged).isEmpty(), - "an identical Thread snapshot emitted accessibility changes"); - events.clear(); - snapshot.roots.front().pending = 1; - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(rootId, QAccessible::NameChanged).size() == 1 && - events.events(rootId, QAccessible::DescriptionChanged).size() == 1 && - events.events(childId, QAccessible::DescriptionChanged).size() == 1, - "a pending-derived parent name did not notify its retained subtree once"); - events.clear(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(rootId, QAccessible::NameChanged).isEmpty() && - events.events(rootId, QAccessible::DescriptionChanged).isEmpty() && - events.events(childId, QAccessible::DescriptionChanged).isEmpty(), - "an identical pending Thread snapshot emitted accessibility changes"); - - events.clear(); - snapshot.selectedThreadId = root.id; - pane.refresh(snapshot); - QApplication::processEvents(); - const auto rootSelection = events.events(rootId, QAccessible::SelectionAdd); - const auto childDeselection = - events.events(childId, QAccessible::SelectionRemove); - passed &= require( - rootSelection.size() == 1 && childDeselection.size() == 1 && - events.events(rootId, QAccessible::Focus).size() == 1 && - rootSelection.front().state.selected && - !childDeselection.front().state.selected, - "snapshot selection did not publish the final semantic replacement"); - events.clear(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require(events.events(rootId).isEmpty() && - events.events(childId).isEmpty(), - "an identical snapshot selection emitted semantic work"); - events.clear(); - snapshot.selectedThreadId = child.id; - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(childId, QAccessible::SelectionAdd).size() == 1 && - events.events(rootId, QAccessible::SelectionRemove).size() == 1 && - events.events(childId, QAccessible::Focus).size() == 1, - "reverse snapshot selection did not publish the semantic replacement"); - - tree->setEnabled(false); - rootActions->doAction(QAccessibleActionInterface::toggleAction()); - passed &= - require(rootItem->isExpanded() && !selection->unselect(childAccessible) && - childItem->isSelected(), - "disabled accessibility actions mutated the tree"); - tree->setEnabled(true); - tree->clearSelection(); - pane.hide(); - QApplication::processEvents(); - passed &= require( - rootAccessible->state().invisible && childAccessible->state().invisible && - !childAccessible->state().focused && - childActions->actionNames().isEmpty() && - treeAccessible->focusChild() == nullptr && - rootAccessible->rect().isEmpty() && childAccessible->rect().isEmpty(), - "hidden thread items retained visible accessibility bounds"); - passed &= require(!selection->unselect(childAccessible) && - !selection->select(childAccessible), - "a hidden nested thread entered root selection semantics"); - childActions->doAction(QAccessibleActionInterface::pressAction()); - passed &= require(!childItem->isSelected(), - "a hidden thread accepted an accessible press"); - - events.clear(); - ui::ThreadListRow reparentedChild = snapshot.roots.front().children.front(); - reparentedChild.title = "Reparented accessible child"; - reparentedChild.cwd = "/reparented/workspace"; - reparentedChild.status = nodegraph::NodeStatus::Completed; - snapshot.roots.front().children.clear(); - snapshot.roots.push_back(reparentedChild); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - QAccessible::accessibleInterface(childId) == childAccessible && - childAccessible->parent() == treeAccessible && - events.events(childId, QAccessible::ParentChanged).size() == 1 && - events.events(childId, QAccessible::NameChanged).size() == 1 && - events.events(childId, QAccessible::DescriptionChanged).size() == 1 && - events.events(rootId, QAccessible::StateChanged).size() == 1 && - events.events(rootId, QAccessible::StateChanged) - .front() - .changedStates.expandable && - events.events(rootId, QAccessible::StateChanged) - .front() - .changedStates.expanded && - !events.events(rootId, QAccessible::StateChanged) - .front() - .changedStates.collapsed && - !rootAccessible->state().expandable && - !rootAccessible->state().expanded && - !rootAccessible->state().collapsed, - "Thread reparenting did not preserve and notify the semantic item"); - events.clear(); - snapshot.selectedThreadId = root.id; - snapshot.roots.pop_back(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(childId, QAccessible::ObjectDestroyed).size() == 1 && - QAccessible::accessibleInterface(childId) == nullptr, - "Thread retirement did not destroy the exact semantic interface once"); - events.clear(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require( - events.events(childId, QAccessible::ObjectDestroyed).isEmpty(), - "an identical retired Thread snapshot repeated destruction"); - return passed; + ui::ThreadListRow root; + root.id = "accessible-root"; + root.presentationKey = root.id; + root.title = "Accessible root"; + root.cwd = "/workspace"; + root.status = nodegraph::NodeStatus::Running; + ui::ThreadListRow child; + child.id = "accessible-child"; + child.presentationKey = child.id; + child.title = "Accessible child"; + root.children.push_back(child); + ui::ThreadListSnapshot snapshot; + snapshot.selectedThreadId = root.id; + snapshot.roots.push_back(root); + + middle::ThreadPane pane; + pane.resize(320, 420); + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* rootItem = threadItem(tree, root.id); + QTreeWidgetItem* childItem = threadItem(tree, child.id); + rootItem->setExpanded(false); + QApplication::processEvents(); + QAccessibleInterface* treeAccessible = QAccessible::queryAccessibleInterface(tree); + QAccessibleInterface* rootAccessible = threadAccessible(tree, rootItem); + QAccessibleInterface* childAccessible = threadAccessible(tree, childItem); + QAccessibleActionInterface* rootActions = rootAccessible ? rootAccessible->actionInterface() : nullptr; + QAccessibleActionInterface* childActions = childAccessible ? childAccessible->actionInterface() : nullptr; + QAccessibleSelectionInterface* selection = treeAccessible ? treeAccessible->selectionInterface() : nullptr; + if (!require(tree && rootItem && childItem && treeAccessible && rootAccessible && childAccessible && rootActions && + childActions && selection, + "thread hierarchy did not expose semantic accessibility")) + return false; + + tests::AccessibilityEventProbe events; + const QAccessible::Id treeId = QAccessible::uniqueId(treeAccessible); + const QAccessible::Id rootId = QAccessible::uniqueId(rootAccessible); + const QAccessible::Id childId = QAccessible::uniqueId(childAccessible); + + bool passed = true; + passed &= require(treeAccessible->role() == QAccessible::Tree && + treeAccessible->text(QAccessible::Name) == QStringLiteral("Threads") && + rootAccessible->role() == QAccessible::TreeItem && childAccessible->role() == QAccessible::TreeItem && + treeAccessible->indexOfChild(rootAccessible) == 0 && + treeAccessible->indexOfChild(childAccessible) == -1 && rootAccessible->parent() == treeAccessible && + rootAccessible->indexOfChild(childAccessible) == 0 && childAccessible->parent() == rootAccessible && + selection->selectedItemCount() == 1 && selection->selectedItems().front() == rootAccessible, + "accessible parentage does not match the native tree"); + passed &= require(rootAccessible->text(QAccessible::Name) == QStringLiteral("Accessible root") && + childAccessible->text(QAccessible::Name) == QStringLiteral("Accessible child") && + rootAccessible->text(QAccessible::Description).contains(QStringLiteral("Status: running")) && + rootAccessible->text(QAccessible::Description).contains(QStringLiteral("Level 1")) && + childAccessible->text(QAccessible::Description).contains(QStringLiteral("Level 2")) && + childAccessible->text(QAccessible::Description).contains(QStringLiteral("Parent: Accessible root")), + "accessible names or descriptions diverged from presentation"); + passed &= + require(rootAccessible->state().collapsed && childAccessible->state().invisible && !childAccessible->state().focusable && + !childAccessible->state().selectable && childAccessible->rect().isEmpty(), + "collapsed descendants remained visibly accessible"); + childActions->doAction(QAccessibleActionInterface::setFocusAction()); + passed &= require(childActions->actionNames().isEmpty() && !selection->select(childAccessible) && + tree->currentItem() == rootItem && !childItem->isSelected(), + "collapsed descendant accepted an accessibility action"); + + events.clear(); + rootActions->doAction(QAccessibleActionInterface::toggleAction()); + QApplication::processEvents(); + const QRect rootRect = rootAccessible->rect(); + const QRect childRect = childAccessible->rect(); + passed &= require(rootItem->isExpanded() && rootAccessible->state().expanded && !childAccessible->state().invisible && + !childRect.isEmpty() && rootRect.width() == tree->viewport()->width() && + childRect.width() == tree->viewport()->width() && + rootAccessible->childAt(childRect.center().x(), childRect.center().y()) == childAccessible && + treeAccessible->childAt(childRect.center().x(), childRect.center().y()) == rootAccessible, + "accessible expansion, bounds, or hit hierarchy is incorrect"); + const auto expandedEvents = events.events(rootId, QAccessible::StateChanged); + passed &= require(expandedEvents.size() == 1 && expandedEvents.front().changedStates.expanded && + expandedEvents.front().changedStates.collapsed && expandedEvents.front().state.expanded, + "thread expansion did not emit once on its semantic TreeItem"); + events.clear(); + rootActions->doAction(QAccessibleActionInterface::toggleAction()); + QApplication::processEvents(); + const auto collapsedEvents = events.events(rootId, QAccessible::StateChanged); + passed &= require(collapsedEvents.size() == 1 && collapsedEvents.front().changedStates.expanded && + collapsedEvents.front().changedStates.collapsed && collapsedEvents.front().state.collapsed, + "thread collapse did not emit once on its semantic TreeItem"); + events.clear(); + rootItem->setExpanded(false); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::StateChanged).isEmpty(), + "an identical collapsed state emitted accessibility work"); + rootActions->doAction(QAccessibleActionInterface::toggleAction()); + QApplication::processEvents(); + events.clear(); + rootItem->setExpanded(true); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::StateChanged).isEmpty(), + "an identical expanded state emitted accessibility work"); + + tree->setFocus(Qt::OtherFocusReason); + QApplication::processEvents(); + events.clear(); + passed &= require(!selection->select(childAccessible), "the root selection interface accepted a nested item"); + childActions->doAction(QAccessibleActionInterface::pressAction()); + QApplication::processEvents(); + const auto selectedChild = events.events(childId, QAccessible::SelectionAdd); + const auto deselectedRoot = events.events(rootId, QAccessible::SelectionRemove); + int addOrder = -1; + int removeOrder = -1; + for (qsizetype event = 0; event < events.all().size(); ++event) { + const auto& record = events.all().at(event); + if (record.target == childId && record.type == QAccessible::SelectionAdd) + addOrder = static_cast(event); + if (record.target == rootId && record.type == QAccessible::SelectionRemove) + removeOrder = static_cast(event); + } + passed &= require(tree->currentItem() == childItem && childAccessible->state().selected && childAccessible->state().focused && + selection->selectedItemCount() == 0 && selection->selectedItems().isEmpty() && + selectedChild.size() == 1 && deselectedRoot.size() == 1 && addOrder >= 0 && removeOrder > addOrder && + events.events(childId, QAccessible::Focus).size() == 1 && + std::ranges::none_of(events.all(), + [](const auto& event) { + return event.target == 0 && (event.type == QAccessible::SelectionAdd || + event.type == QAccessible::SelectionRemove || + event.type == QAccessible::Focus); + }), + "accessible focus and selection did not emit once on the " + "semantic items"); + + events.clear(); + childActions->doAction(QAccessibleActionInterface::pressAction()); + QApplication::processEvents(); + passed &= require(events.events(childId).isEmpty(), "reselecting the current Thread item emitted a semantic event"); + + events.clear(); + childItem->setSelected(false); + passed &= require(tree->currentItem() == childItem && !childAccessible->state().selected && childAccessible->state().focused, + "native unselect discarded or hid keyboard focus"); + QApplication::processEvents(); + const auto unselectedChild = events.events(childId, QAccessible::SelectionRemove); + passed &= require(unselectedChild.size() == 1 && !unselectedChild.front().state.selected, + "accessible unselect did not notify its semantic item"); + const QRect focusedRow = tree->visualItemRect(childItem); + const auto closestFocusColor = [&focusedRow](const QImage& image) { + const QColor expected(QString::fromLatin1(UiStyle::threadFocusBorder)); + int result = 3 * 255; + for (int x = 0; x <= 2; ++x) + for (int y = focusedRow.top() + 12; y <= focusedRow.bottom() - 12; ++y) { + const qreal dpr = image.devicePixelRatio(); + const QColor actual = image.pixelColor(qRound(x * dpr), qRound(y * dpr)); + result = std::min(result, + std::abs(actual.red() - expected.red()) + std::abs(actual.green() - expected.green()) + + std::abs(actual.blue() - expected.blue())); + } + return result; + }; + const QImage focused = tree->viewport()->grab().toImage(); + tree->clearFocus(); + QApplication::processEvents(); + const QImage unfocused = tree->viewport()->grab().toImage(); + const int focusedDistance = closestFocusColor(focused); + const int unfocusedDistance = closestFocusColor(unfocused); + passed &= require(focusedDistance <= 20 && focusedDistance + 20 < unfocusedDistance, + "unselected keyboard focus lacks its tokenized outline"); + events.clear(); + childActions->doAction(QAccessibleActionInterface::setFocusAction()); + QApplication::processEvents(); + passed &= require(tree->hasFocus() && childItem->isSelected() && events.events(treeId, QAccessible::Focus).size() == 1 && + events.events(childId, QAccessible::Focus).isEmpty() && treeAccessible->focusChild() == childAccessible && + events.events(childId, QAccessible::SelectionAdd).size() == 1, + "native tree focus did not resolve to its unchanged current item"); + events.clear(); + childActions->doAction(QAccessibleActionInterface::setFocusAction()); + QApplication::processEvents(); + passed &= require(events.events(treeId).isEmpty() && events.events(childId).isEmpty(), + "refocusing the current Thread item emitted semantic work"); + + events.clear(); + snapshot.selectedThreadId = child.id; + snapshot.roots.front().title = "Renamed accessible root"; + snapshot.roots.front().cwd = "/renamed/workspace"; + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::NameChanged).size() == 1 && + events.events(rootId, QAccessible::DescriptionChanged).size() == 1 && + events.events(childId, QAccessible::DescriptionChanged).size() == 1 && + rootAccessible->text(QAccessible::Name) == QStringLiteral("Renamed accessible root"), + "Thread presentation mutation did not notify its retained semantic item"); + events.clear(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::NameChanged).isEmpty() && + events.events(rootId, QAccessible::DescriptionChanged).isEmpty() && + events.events(childId, QAccessible::DescriptionChanged).isEmpty(), + "an identical Thread snapshot emitted accessibility changes"); + events.clear(); + snapshot.roots.front().pending = 1; + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::NameChanged).size() == 1 && + events.events(rootId, QAccessible::DescriptionChanged).size() == 1 && + events.events(childId, QAccessible::DescriptionChanged).size() == 1, + "a pending-derived parent name did not notify its retained subtree once"); + events.clear(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(rootId, QAccessible::NameChanged).isEmpty() && + events.events(rootId, QAccessible::DescriptionChanged).isEmpty() && + events.events(childId, QAccessible::DescriptionChanged).isEmpty(), + "an identical pending Thread snapshot emitted accessibility changes"); + + events.clear(); + snapshot.selectedThreadId = root.id; + pane.refresh(snapshot); + QApplication::processEvents(); + const auto rootSelection = events.events(rootId, QAccessible::SelectionAdd); + const auto childDeselection = events.events(childId, QAccessible::SelectionRemove); + passed &= require(rootSelection.size() == 1 && childDeselection.size() == 1 && + events.events(rootId, QAccessible::Focus).size() == 1 && rootSelection.front().state.selected && + !childDeselection.front().state.selected, + "snapshot selection did not publish the final semantic replacement"); + events.clear(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(rootId).isEmpty() && events.events(childId).isEmpty(), + "an identical snapshot selection emitted semantic work"); + events.clear(); + snapshot.selectedThreadId = child.id; + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(childId, QAccessible::SelectionAdd).size() == 1 && + events.events(rootId, QAccessible::SelectionRemove).size() == 1 && + events.events(childId, QAccessible::Focus).size() == 1, + "reverse snapshot selection did not publish the semantic replacement"); + + tree->setEnabled(false); + rootActions->doAction(QAccessibleActionInterface::toggleAction()); + passed &= require(rootItem->isExpanded() && !selection->unselect(childAccessible) && childItem->isSelected(), + "disabled accessibility actions mutated the tree"); + tree->setEnabled(true); + tree->clearSelection(); + pane.hide(); + QApplication::processEvents(); + passed &= + require(rootAccessible->state().invisible && childAccessible->state().invisible && !childAccessible->state().focused && + childActions->actionNames().isEmpty() && treeAccessible->focusChild() == nullptr && + rootAccessible->rect().isEmpty() && childAccessible->rect().isEmpty(), + "hidden thread items retained visible accessibility bounds"); + passed &= require(!selection->unselect(childAccessible) && !selection->select(childAccessible), + "a hidden nested thread entered root selection semantics"); + childActions->doAction(QAccessibleActionInterface::pressAction()); + passed &= require(!childItem->isSelected(), "a hidden thread accepted an accessible press"); + + events.clear(); + ui::ThreadListRow reparentedChild = snapshot.roots.front().children.front(); + reparentedChild.title = "Reparented accessible child"; + reparentedChild.cwd = "/reparented/workspace"; + reparentedChild.status = nodegraph::NodeStatus::Completed; + snapshot.roots.front().children.clear(); + snapshot.roots.push_back(reparentedChild); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= + require(QAccessible::accessibleInterface(childId) == childAccessible && childAccessible->parent() == treeAccessible && + events.events(childId, QAccessible::ParentChanged).size() == 1 && + events.events(childId, QAccessible::NameChanged).size() == 1 && + events.events(childId, QAccessible::DescriptionChanged).size() == 1 && + events.events(rootId, QAccessible::StateChanged).size() == 1 && + events.events(rootId, QAccessible::StateChanged).front().changedStates.expandable && + events.events(rootId, QAccessible::StateChanged).front().changedStates.expanded && + !events.events(rootId, QAccessible::StateChanged).front().changedStates.collapsed && + !rootAccessible->state().expandable && !rootAccessible->state().expanded && !rootAccessible->state().collapsed, + "Thread reparenting did not preserve and notify the semantic item"); + events.clear(); + snapshot.selectedThreadId = root.id; + snapshot.roots.pop_back(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(childId, QAccessible::ObjectDestroyed).size() == 1 && + QAccessible::accessibleInterface(childId) == nullptr, + "Thread retirement did not destroy the exact semantic interface once"); + events.clear(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(events.events(childId, QAccessible::ObjectDestroyed).isEmpty(), + "an identical retired Thread snapshot repeated destruction"); + return passed; #endif -} + } -bool presentationLifetimeFollowsExactThreadIncarnation() { - nodegraph::NodeGraph graph; - nodegraph::NodeRef runtime; - nodegraph::NodeRef firstRoot; - nodegraph::NodeRef firstChild; - { - auto write = graph.write(); - runtime = write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); - nodegraph::NodeState connectionState; - connectionState.status = nodegraph::NodeStatus::Connected; - connectionState.fields = {{"providerState", "ready"}, - {"role", "controller"}}; - static_cast( - write.upsert({nodegraph::NodeKind::Connection, "connection"}, - std::move(connectionState))); - nodegraph::NodeState rootState; - rootState.fields.emplace("name", "Stable root"); - firstRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, - std::move(rootState)); - nodegraph::NodeState childState; - childState.fields.emplace("name", "Stable child"); - firstChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, - std::move(childState)); - write.relate(runtime, nodegraph::RelationKind::RootThread, firstRoot); - write.relate(firstRoot, nodegraph::RelationKind::AgentChildThread, - firstChild); - static_cast(write.finish()); - } - - ui::NodeGraphUiAdapter adapter(graph); - auto first = adapter.threads(firstRoot); - if (!require( - first && first->roots.size() == 1 && - first->roots.front().children.size() == 1 && - first->roots.front().target == firstRoot && - first->roots.front().children.front().target == firstChild && - !first->roots.front().presentationKey.empty() && - !first->roots.front().children.front().presentationKey.empty(), - "the first exact thread incarnation was not projected")) - return false; - const std::string firstRootKey = first->roots.front().presentationKey; - const std::string firstChildKey = - first->roots.front().children.front().presentationKey; - - middle::ThreadPane pane; - pane.resize(320, 500); - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); - nodegraph::NodeRef reloaded; - nodegraph::NodeRef selected; - middle::ThreadPane::Actions actions; - actions.select = [&](const nodegraph::NodeRef &target) { selected = target; }; - actions.reload = [&](const nodegraph::NodeRef &target) { reloaded = target; }; - pane.setActions(std::move(actions)); - pane.refresh(*first); - pane.show(); - QApplication::processEvents(); - - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *firstRootItem = threadItem(tree, "stable-root"); - QTreeWidgetItem *firstChildItem = threadItem(tree, "stable-child"); - if (firstRootItem) { - firstRootItem->setExpanded(false); - } - if (!require(tree && tree->topLevelItemCount() == 1 && firstRootItem && - firstRootItem->childCount() == 1 && firstChildItem && - firstChildItem->parent() == firstRootItem && - !firstRootItem->isExpanded(), - "the first incarnation did not render as one collapsed tree")) - return false; - tree->setCurrentItem(firstRootItem); - QKeyEvent expand(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier); - QApplication::sendEvent(tree, &expand); - QApplication::processEvents(); - if (!require(firstRootItem->isExpanded(), - "native tree navigation did not expand the hierarchy")) - return false; - const QPersistentModelIndex firstRootIndex( - tree->indexFromItem(firstRootItem)); - QAccessibleInterface *treeAccessible = - QAccessible::queryAccessibleInterface(tree); - QAccessibleInterface *firstAccessible = - treeAccessible ? treeAccessible->child(0) : nullptr; - const QAccessible::Id firstAccessibleId = - firstAccessible ? QAccessible::uniqueId(firstAccessible) : 0; - - const auto openContextMenu = [&]() -> QMenu * { - const QPoint position = - tree->visualItemRect(tree->topLevelItem(0)).center(); - QMetaObject::invokeMethod(tree, "customContextMenuRequested", - Qt::DirectConnection, Q_ARG(QPoint, position)); - QApplication::processEvents(); - for (QMenu *menu : pane.findChildren()) { - if (!menu->isVisible()) - continue; - for (QAction *action : menu->actions()) - if (action && action->text() == QStringLiteral("Reload")) - return menu; - } - return nullptr; - }; - QPointer firstMenu = openContextMenu(); - QPointer firstReload; - if (firstMenu) - for (QAction *action : firstMenu->actions()) - if (action && action->text() == QStringLiteral("Reload")) { - firstReload = action; - break; - } - if (!require(firstMenu && firstMenu->isVisible() && firstReload && - firstReload->isEnabled(), - "the first incarnation did not own its visible Reload menu")) - return false; - - ui::ThreadListSnapshot unavailable = *first; - unavailable.providerReady = false; - unavailable.canControl = false; - pane.refresh(unavailable); - QApplication::processEvents(); - if (!require(!firstMenu || !firstMenu->isVisible(), - "a capability transition left stale enabled menu actions " - "visible")) - return false; - pane.refresh(*first); - QApplication::processEvents(); - firstMenu = openContextMenu(); - firstReload = nullptr; - if (firstMenu) - for (QAction *action : firstMenu->actions()) - if (action && action->text() == QStringLiteral("Reload")) { - firstReload = action; - break; - } - if (!require(firstMenu && firstReload && firstReload->isEnabled(), - "the restored capability snapshot did not produce a fresh " - "exact menu")) - return false; - - { - const std::array oldThreads{firstRoot, firstChild}; - auto write = graph.write(); - write.removeMany(oldThreads); - static_cast(write.finish()); - } - nodegraph::NodeRef secondRoot; - nodegraph::NodeRef secondChild; - { - auto write = graph.write(); - nodegraph::NodeState rootState; - rootState.fields.emplace("name", "Stable root"); - secondRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, - std::move(rootState)); - nodegraph::NodeState childState; - childState.fields.emplace("name", "Stable child"); - secondChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, - std::move(childState)); - write.relate(runtime, nodegraph::RelationKind::RootThread, secondRoot); - write.relate(secondRoot, nodegraph::RelationKind::AgentChildThread, - secondChild); - static_cast(write.finish()); - } - auto second = adapter.threads(secondRoot); - if (!require(second && second->roots.size() == 1 && - second->roots.front().children.size() == 1 && - second->roots.front().target == secondRoot && - second->roots.front().children.front().target == - secondChild && - second->roots.front().presentationKey != firstRootKey && - second->roots.front().children.front().presentationKey != - firstChildKey, - "same canonical IDs reused the retired presentation lifetime")) - return false; - - tree->setCurrentItem(firstChildItem); - QApplication::processEvents(); - if (!require(selected == firstChild && selected != secondChild && - pane.visiblySelectedThread() && - pane.visiblySelectedThread()->target == firstChild, - "a stale visible selection retargeted the replacement child")) - return false; - tree->setCurrentItem(firstRootItem); - QApplication::processEvents(); - if (!require(pane.visiblySelectedThread() && - pane.visiblySelectedThread()->target == firstRoot, - "the visible row lost its exact pre-refresh target")) - return false; - firstReload->trigger(); - if (!require(reloaded == firstRoot && reloaded != secondRoot, - "a delayed row action retargeted the replacement incarnation")) - return false; - QPointer staleMenu = openContextMenu(); - ui::ThreadListRow forgedStaleDelta = first->roots.front(); - forgedStaleDelta.target = secondRoot; - if (!require(!pane.applyRowPresentation(forgedStaleDelta), - "an incremental row update accepted a stale exact target")) - return false; - - pane.refresh(*second); - QApplication::processEvents(); - QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); - QApplication::processEvents(); - QTreeWidgetItem *secondItem = threadItem(tree, "stable-root"); - QAccessibleInterface *secondAccessible = - treeAccessible ? treeAccessible->child(0) : nullptr; - bool result = - require(tree->topLevelItemCount() == 1 && secondItem && secondItem->childCount() == 1 && secondItem->isExpanded(), - "the replacement incarnation did not use initially expanded hierarchy") && - require(!firstRootIndex.isValid() && (!firstAccessibleId || !QAccessible::accessibleInterface(firstAccessibleId)), - "the replacement incarnation retained retired model or " - "accessibility identity") && - require(staleMenu.isNull() || !staleMenu->isVisible(), "the replacement incarnation retained the retired context menu") && - require(pane.visiblySelectedThread() && pane.visiblySelectedThread()->target == secondRoot && - pane.currentSortCriterion() == middle::ThreadPane::SortCriterion::Alphanumeric, - "reincarnation lost canonical navigation or global sorting") && - require(secondAccessible && secondAccessible->role() == QAccessible::TreeItem && secondAccessible->parent() == treeAccessible && - secondAccessible->state().expandable && secondAccessible->state().expanded, - "the fresh hierarchy did not expose nested expanded " - "accessibility"); - - const auto selectedSecond = adapter.threads(secondChild); - if (!require(selectedSecond.has_value(), - "the selected replacement child was not projected")) - return false; - pane.refresh(*selectedSecond); - QApplication::processEvents(); - result &= - require(secondItem->isExpanded() && threadItem(tree, "stable-child") && - pane.visiblySelectedThread() && - pane.visiblySelectedThread()->target == secondChild, - "selecting a child did not expand its current ancestors"); - - { - const std::array oldThreads{secondRoot, secondChild}; - auto write = graph.write(); - write.removeMany(oldThreads); - static_cast(write.finish()); - } - nodegraph::NodeRef thirdRoot; - nodegraph::NodeRef thirdChild; - { - auto write = graph.write(); - nodegraph::NodeState rootState; - rootState.fields.emplace("name", "Stable root"); - thirdRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, - std::move(rootState)); - nodegraph::NodeState childState; - childState.fields.emplace("name", "Stable child"); - thirdChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, - std::move(childState)); - write.relate(runtime, nodegraph::RelationKind::RootThread, thirdRoot); - write.relate(thirdRoot, nodegraph::RelationKind::AgentChildThread, - thirdChild); - static_cast(write.finish()); - } - const auto third = adapter.threads(thirdChild); - if (!require(third && third->roots.size() == 1 && - third->roots.front().children.size() == 1, - "the second replacement tree was not projected")) - return false; - pane.refresh(*third); - QApplication::processEvents(); - result &= require( - third && - third->roots.front().presentationKey != - second->roots.front().presentationKey && - third->roots.front().children.front().presentationKey != - second->roots.front().children.front().presentationKey && - tree->topLevelItemCount() == 1 && - tree->topLevelItem(0)->isExpanded() && - tree->topLevelItem(0)->childCount() == 1 && - pane.visiblySelectedThread() && - pane.visiblySelectedThread()->target == thirdChild, - "a reincarnated selected child did not expand only its new ancestor"); - return result; -} + bool presentationLifetimeFollowsExactThreadIncarnation() { + nodegraph::NodeGraph graph; + nodegraph::NodeRef runtime; + nodegraph::NodeRef firstRoot; + nodegraph::NodeRef firstChild; + { + auto write = graph.write(); + runtime = write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); + nodegraph::NodeState connectionState; + connectionState.status = nodegraph::NodeStatus::Connected; + connectionState.fields = {{"providerState", "ready"}, {"role", "controller"}}; + static_cast(write.upsert({nodegraph::NodeKind::Connection, "connection"}, std::move(connectionState))); + nodegraph::NodeState rootState; + rootState.fields.emplace("name", "Stable root"); + firstRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, std::move(rootState)); + nodegraph::NodeState childState; + childState.fields.emplace("name", "Stable child"); + firstChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, std::move(childState)); + write.relate(runtime, nodegraph::RelationKind::RootThread, firstRoot); + write.relate(firstRoot, nodegraph::RelationKind::AgentChildThread, firstChild); + static_cast(write.finish()); + } -bool sortingAndPromptAnimationAreFixed() { - AnimationDurationStyle normalMotion(100); - middle::ThreadPane pane; - pane.resize(300, 500); - ui::ThreadListSnapshot snapshot; - ui::ThreadListRow older; - older.id = "older"; - older.presentationKey = older.id; - older.title = "20 tasks"; - older.createdAt = 500; - older.updatedAt = 900; - older.recencyAt = 10; - ui::ThreadListRow recent; - recent.id = "recent"; - recent.presentationKey = recent.id; - recent.title = "Alpha"; - recent.createdAt = 1; - recent.updatedAt = 2; - recent.recencyAt = 30; - ui::ThreadListRow missing; - missing.id = "missing"; - missing.presentationKey = missing.id; - missing.title = "2 tasks"; - snapshot.roots = {older, recent, missing}; - - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - if (tree) - tree->setStyle(&normalMotion); - auto *sortButton = - pane.findChild(QStringLiteral("threadSortButton")); - if (!require(tree && tree->topLevelItemCount() == 3, "thread tree missing") || - !require(sortButton && sortButton->menu(), - "thread sort control missing") || - !require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == - QStringLiteral("recent"), - "thread rows are not ordered by recencyAt newest first")) - return false; - if (!require(tree->topLevelItem(0)->toolTip(0).contains( - QStringLiteral("Recent turn:")) && - tree->topLevelItem(0)->toolTip(0).contains( - QStringLiteral("Created:")), - "thread hover omits provider recent-turn or creation time")) - return false; - - QStringList sortLabels; - for (QAction *action : sortButton->menu()->actions()) - sortLabels.push_back(action->text()); - if (!require(sortLabels == QStringList{QStringLiteral("Alphanumeric"), - QStringLiteral("Created"), - QStringLiteral("Recent"), - QStringLiteral("Section order")}, - "thread sort menu does not expose the four supported contracts")) - return false; - - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); - QApplication::processEvents(); - if (!require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == - QStringLiteral("missing"), - "alphanumeric order is not numeric-aware") || - !require(tree->topLevelItem(1)->data(0, Qt::UserRole).toString() == - QStringLiteral("older"), - "alphanumeric order did not place 20 after 2") || - !require(tree->topLevelItem(2)->data(0, Qt::UserRole).toString() == - QStringLiteral("recent"), - "alphanumeric order did not place letters after numeric titles")) - return false; - - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Created); - QApplication::processEvents(); - if (!require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == - QStringLiteral("older"), - "Created order is not newest first") || - !require(tree->topLevelItem(1)->data(0, Qt::UserRole).toString() == - QStringLiteral("recent"), - "Created order did not keep older dated rows before missing") || - !require(tree->topLevelItem(2)->data(0, Qt::UserRole).toString() == - QStringLiteral("missing"), - "Created order did not put missing timestamps last")) - return false; - - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Recency); - QApplication::processEvents(); - - snapshot.roots[0].recencyAt = 31; - snapshot.roots[0].awaitingPromptConversation = true; - snapshot.roots[0].pendingPromptAdmittedAtMs = - QDateTime::currentMSecsSinceEpoch() - 1500; - pane.refresh(snapshot); - QApplication::processEvents(); - auto *animation = - pane.findChild(QStringLiteral("optimisticThreadAnimation")); - QTreeWidgetItem *promoted = tree->topLevelItem(0); - QAccessibleInterface *promotedAccessible = threadAccessible(tree, promoted); - if (!require(promoted->data(0, Qt::UserRole).toString() == - QStringLiteral("older"), - "new turn admission did not promote its thread") || - !require(promotedAccessible && - promotedAccessible->text(QAccessible::Name) == - QStringLiteral("20 tasks"), - "promotion substituted a canonical ID for the chosen name") || - !require(animation && animation->isActive(), - "thread-card animation did not follow the pending prompt")) - return false; - - snapshot.roots[1].status = nodegraph::NodeStatus::Running; - pane.refresh(snapshot); - QApplication::processEvents(); - if (!require(animation->isActive(), - "unrelated thread traffic stopped pending prompt animation")) - return false; - - pane.hide(); - if (!require(!animation->isActive(), - "hiding the thread pane retained animation work")) - return false; - pane.show(); - QApplication::processEvents(); - if (!require(animation->isActive(), - "showing the thread pane did not resume visible animation")) - return false; - - snapshot.roots[0].awaitingPromptConversation = false; - snapshot.roots[0].pendingPromptAdmittedAtMs.reset(); - pane.refresh(snapshot); - QApplication::processEvents(); - return require(!animation->isActive(), - "prompt acknowledgement did not stop thread-card animation") && - require(tree->topLevelItem(0) == promoted && promotedAccessible && - promotedAccessible->isValid() && - promotedAccessible->text(QAccessible::Name) == - QStringLiteral("20 tasks"), - "prompt acknowledgement changed the chosen name"); -} + ui::NodeGraphUiAdapter adapter(graph); + auto first = adapter.threads(firstRoot); + if (!require(first && first->roots.size() == 1 && first->roots.front().children.size() == 1 && + first->roots.front().target == firstRoot && first->roots.front().children.front().target == firstChild && + !first->roots.front().presentationKey.empty() && + !first->roots.front().children.front().presentationKey.empty(), + "the first exact thread incarnation was not projected")) + return false; + const std::string firstRootKey = first->roots.front().presentationKey; + const std::string firstChildKey = first->roots.front().children.front().presentationKey; -bool reducedMotionStopsThreadFeedbackAtTheStyleBoundary() { - ui::ThreadListRow row; - row.id = "reduced-motion-thread"; - row.presentationKey = row.id; - row.title = "Reduced motion"; - row.cwd = "/workspace"; - row.awaitingPromptConversation = true; - row.pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; - ui::ThreadListSnapshot snapshot; - snapshot.roots.push_back(row); - - AnimationDurationStyle normalMotion(100); - AnimationDurationStyle reducedMotion(0); - middle::ThreadPane pane; - pane.resize(320, 240); - if (QTreeWidget *tree = threadTree(pane)) - tree->setStyle(&normalMotion); - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - auto *animation = - pane.findChild(QStringLiteral("optimisticThreadAnimation")); - bool result = require(animation && animation->isActive(), - "normal motion did not start visible thread feedback"); - - if (tree) - tree->setStyle(&reducedMotion); - QElapsedTimer stopped; - stopped.start(); - while (animation && animation->isActive() && stopped.elapsed() < 100) { - QApplication::processEvents(QEventLoop::AllEvents, 10); - QThread::msleep(1); - } - const QImage staticFrame = - tree ? tree->viewport()->grab().toImage() : QImage{}; - QElapsedTimer stable; - stable.start(); - while (stable.elapsed() < 110) { - QApplication::processEvents(QEventLoop::AllEvents, 10); - QThread::msleep(1); - } - result &= require( - tree && animation && !animation->isActive() && - tree->viewport()->grab().toImage() == staticFrame, - "reduced motion did not stop thread feedback at the style boundary"); - - if (tree) - tree->setStyle(&normalMotion); - QApplication::processEvents(); - result &= require(animation && animation->isActive(), - "restoring motion did not resume visible thread feedback"); - return result; -} + middle::ThreadPane pane; + pane.resize(320, 500); + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); + nodegraph::NodeRef reloaded; + nodegraph::NodeRef selected; + middle::ThreadPane::Actions actions; + actions.select = [&](const nodegraph::NodeRef& target) { + selected = target; + }; + actions.reload = [&](const nodegraph::NodeRef& target) { + reloaded = target; + }; + pane.setActions(std::move(actions)); + pane.refresh(*first); + pane.show(); + QApplication::processEvents(); -int colorDistance(const QColor &left, const QColor &right) { - return std::abs(left.red() - right.red()) + - std::abs(left.green() - right.green()) + - std::abs(left.blue() - right.blue()); -} + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* firstRootItem = threadItem(tree, "stable-root"); + QTreeWidgetItem* firstChildItem = threadItem(tree, "stable-child"); + if (firstRootItem) { + firstRootItem->setExpanded(false); + } + if (!require(tree && tree->topLevelItemCount() == 1 && firstRootItem && firstRootItem->childCount() == 1 && firstChildItem && + firstChildItem->parent() == firstRootItem && !firstRootItem->isExpanded(), + "the first incarnation did not render as one collapsed tree")) + return false; + tree->setCurrentItem(firstRootItem); + QKeyEvent expand(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier); + QApplication::sendEvent(tree, &expand); + QApplication::processEvents(); + if (!require(firstRootItem->isExpanded(), "native tree navigation did not expand the hierarchy")) + return false; + const QPersistentModelIndex firstRootIndex(tree->indexFromItem(firstRootItem)); + QAccessibleInterface* treeAccessible = QAccessible::queryAccessibleInterface(tree); + QAccessibleInterface* firstAccessible = treeAccessible ? treeAccessible->child(0) : nullptr; + const QAccessible::Id firstAccessibleId = firstAccessible ? QAccessible::uniqueId(firstAccessible) : 0; + + const auto openContextMenu = [&]() -> QMenu* { + const QPoint position = tree->visualItemRect(tree->topLevelItem(0)).center(); + QMetaObject::invokeMethod(tree, "customContextMenuRequested", Qt::DirectConnection, Q_ARG(QPoint, position)); + QApplication::processEvents(); + for (QMenu* menu : pane.findChildren()) { + if (!menu->isVisible()) + continue; + for (QAction* action : menu->actions()) + if (action && action->text() == QStringLiteral("Reload")) + return menu; + } + return nullptr; + }; + QPointer firstMenu = openContextMenu(); + QPointer firstReload; + if (firstMenu) + for (QAction* action : firstMenu->actions()) + if (action && action->text() == QStringLiteral("Reload")) { + firstReload = action; + break; + } + if (!require(firstMenu && firstMenu->isVisible() && firstReload && firstReload->isEnabled(), + "the first incarnation did not own its visible Reload menu")) + return false; + + ui::ThreadListSnapshot unavailable = *first; + unavailable.providerReady = false; + unavailable.canControl = false; + pane.refresh(unavailable); + QApplication::processEvents(); + if (!require(!firstMenu || !firstMenu->isVisible(), + "a capability transition left stale enabled menu actions " + "visible")) + return false; + pane.refresh(*first); + QApplication::processEvents(); + firstMenu = openContextMenu(); + firstReload = nullptr; + if (firstMenu) + for (QAction* action : firstMenu->actions()) + if (action && action->text() == QStringLiteral("Reload")) { + firstReload = action; + break; + } + if (!require(firstMenu && firstReload && firstReload->isEnabled(), + "the restored capability snapshot did not produce a fresh " + "exact menu")) + return false; -QColor logicalPixel(const QImage &image, QPoint point) { - const qreal dpr = image.devicePixelRatio(); - point = QPoint(qRound(point.x() * dpr), qRound(point.y() * dpr)); - return image.rect().contains(point) ? image.pixelColor(point) : QColor{}; -} + { + const std::array oldThreads{firstRoot, firstChild}; + auto write = graph.write(); + write.removeMany(oldThreads); + static_cast(write.finish()); + } + nodegraph::NodeRef secondRoot; + nodegraph::NodeRef secondChild; + { + auto write = graph.write(); + nodegraph::NodeState rootState; + rootState.fields.emplace("name", "Stable root"); + secondRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, std::move(rootState)); + nodegraph::NodeState childState; + childState.fields.emplace("name", "Stable child"); + secondChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, std::move(childState)); + write.relate(runtime, nodegraph::RelationKind::RootThread, secondRoot); + write.relate(secondRoot, nodegraph::RelationKind::AgentChildThread, secondChild); + static_cast(write.finish()); + } + auto second = adapter.threads(secondRoot); + if (!require(second && second->roots.size() == 1 && second->roots.front().children.size() == 1 && + second->roots.front().target == secondRoot && second->roots.front().children.front().target == secondChild && + second->roots.front().presentationKey != firstRootKey && + second->roots.front().children.front().presentationKey != firstChildKey, + "same canonical IDs reused the retired presentation lifetime")) + return false; + + tree->setCurrentItem(firstChildItem); + QApplication::processEvents(); + if (!require(selected == firstChild && selected != secondChild && pane.visiblySelectedThread() && + pane.visiblySelectedThread()->target == firstChild, + "a stale visible selection retargeted the replacement child")) + return false; + tree->setCurrentItem(firstRootItem); + QApplication::processEvents(); + if (!require(pane.visiblySelectedThread() && pane.visiblySelectedThread()->target == firstRoot, + "the visible row lost its exact pre-refresh target")) + return false; + firstReload->trigger(); + if (!require(reloaded == firstRoot && reloaded != secondRoot, "a delayed row action retargeted the replacement incarnation")) + return false; + QPointer staleMenu = openContextMenu(); + ui::ThreadListRow forgedStaleDelta = first->roots.front(); + forgedStaleDelta.target = secondRoot; + if (!require(!pane.applyRowPresentation(forgedStaleDelta), "an incremental row update accepted a stale exact target")) + return false; + + pane.refresh(*second); + QApplication::processEvents(); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + QApplication::processEvents(); + QTreeWidgetItem* secondItem = threadItem(tree, "stable-root"); + QAccessibleInterface* secondAccessible = treeAccessible ? treeAccessible->child(0) : nullptr; + bool result = + require(tree->topLevelItemCount() == 1 && secondItem && secondItem->childCount() == 1 && secondItem->isExpanded(), + "the replacement incarnation did not use initially expanded hierarchy") && + require(!firstRootIndex.isValid() && (!firstAccessibleId || !QAccessible::accessibleInterface(firstAccessibleId)), + "the replacement incarnation retained retired model or " + "accessibility identity") && + require(staleMenu.isNull() || !staleMenu->isVisible(), "the replacement incarnation retained the retired context menu") && + require(pane.visiblySelectedThread() && pane.visiblySelectedThread()->target == secondRoot && + pane.currentSortCriterion() == middle::ThreadPane::SortCriterion::Alphanumeric, + "reincarnation lost canonical navigation or global sorting") && + require(secondAccessible && secondAccessible->role() == QAccessible::TreeItem && + secondAccessible->parent() == treeAccessible && secondAccessible->state().expandable && + secondAccessible->state().expanded, + "the fresh hierarchy did not expose nested expanded " + "accessibility"); + + const auto selectedSecond = adapter.threads(secondChild); + if (!require(selectedSecond.has_value(), "the selected replacement child was not projected")) + return false; + pane.refresh(*selectedSecond); + QApplication::processEvents(); + result &= require(secondItem->isExpanded() && threadItem(tree, "stable-child") && pane.visiblySelectedThread() && + pane.visiblySelectedThread()->target == secondChild, + "selecting a child did not expand its current ancestors"); -bool projectBodiesCapVisibleRows() { - bool passed = true; - nodegraph::NodeGraph graph; - std::vector targets; - { - auto write = graph.write(); - for (int index = 0; index < 20; ++index) { - targets.push_back(write.upsert({nodegraph::NodeKind::Thread, "cap-" + std::to_string(index)})); - } - static_cast(write.finish()); - } - for (const auto& [width, points] : std::array{std::pair{260, 10}, std::pair{440, 10}, std::pair{260, 16}, std::pair{440, 16}}) { - middle::ThreadPane pane; - auto font = pane.font(); - font.setPointSize(points); - pane.setFont(font); - pane.resize(width, 800); - ui::ThreadListRow large; - large.kind = ui::ThreadRowKind::Project; - large.id = large.presentationKey = "cap-large"; - large.title = "Large project"; - ui::ThreadListRow section; - section.kind = ui::ThreadRowKind::Section; - section.id = section.presentationKey = "cap-section"; - section.title = "Section counts as one row"; - for (int index = 0; index < 20; ++index) { - section.children.push_back(localDraft( - "cap-" + std::to_string(index), "cap-" + std::to_string(index), "Thread " + std::to_string(index), "/workspace")); - section.children.back().target = targets[index]; + { + const std::array oldThreads{secondRoot, secondChild}; + auto write = graph.write(); + write.removeMany(oldThreads); + static_cast(write.finish()); + } + nodegraph::NodeRef thirdRoot; + nodegraph::NodeRef thirdChild; + { + auto write = graph.write(); + nodegraph::NodeState rootState; + rootState.fields.emplace("name", "Stable root"); + thirdRoot = write.upsert({nodegraph::NodeKind::Thread, "stable-root"}, std::move(rootState)); + nodegraph::NodeState childState; + childState.fields.emplace("name", "Stable child"); + thirdChild = write.upsert({nodegraph::NodeKind::Thread, "stable-child"}, std::move(childState)); + write.relate(runtime, nodegraph::RelationKind::RootThread, thirdRoot); + write.relate(thirdRoot, nodegraph::RelationKind::AgentChildThread, thirdChild); + static_cast(write.finish()); + } + const auto third = adapter.threads(thirdChild); + if (!require(third && third->roots.size() == 1 && third->roots.front().children.size() == 1, + "the second replacement tree was not projected")) + return false; + pane.refresh(*third); + QApplication::processEvents(); + result &= require( + third && third->roots.front().presentationKey != second->roots.front().presentationKey && + third->roots.front().children.front().presentationKey != second->roots.front().children.front().presentationKey && + tree->topLevelItemCount() == 1 && tree->topLevelItem(0)->isExpanded() && tree->topLevelItem(0)->childCount() == 1 && + pane.visiblySelectedThread() && pane.visiblySelectedThread()->target == thirdChild, + "a reincarnated selected child did not expand only its new ancestor"); + return result; } - ui::ThreadListRow page; - page.kind = ui::ThreadRowKind::Page; - page.id = page.presentationKey = "cap-page"; - page.title = "Load more"; - page.query = {{"method", "thread/list"}, {"parameters", {{"projectId", "cap-large"}}}}; - section.children.push_back(page); - large.children = {section}; - int pagesRequested = 0; - int selections = 0; - nodegraph::NodeRef archived; - middle::ThreadPane::Actions actions; - actions.select = [&](const nodegraph::NodeRef&) { - ++selections; - }; - actions.toggleArchive = [&](const nodegraph::NodeRef& target) { - archived = target; - }; - actions.browse = [&](const nlohmann::json&) { - ++pagesRequested; - }; - pane.setActions(std::move(actions)); - ui::ThreadListRow small = large; - small.id = small.presentationKey = "cap-small"; - small.title = "Small project"; - small.children = {localDraft("small-1", "small-1", "First", "/workspace"), - localDraft("small-2", "small-2", "Second", "/workspace")}; - ui::ThreadListSnapshot snapshot; - snapshot.providerReady = true; - snapshot.canControl = true; - snapshot.roots = {large, small}; - for (int index = 0; index < 15; ++index) { - ui::ThreadListRow empty; - empty.kind = ui::ThreadRowKind::Project; - empty.id = empty.presentationKey = "zz-empty-" + std::to_string(index); - empty.title = "Empty project " + std::to_string(index); - snapshot.roots.push_back(empty); + + bool sortingAndPromptAnimationAreFixed() { + AnimationDurationStyle normalMotion(100); + middle::ThreadPane pane; + pane.resize(300, 500); + ui::ThreadListSnapshot snapshot; + ui::ThreadListRow older; + older.id = "older"; + older.presentationKey = older.id; + older.title = "20 tasks"; + older.createdAt = 500; + older.updatedAt = 900; + older.recencyAt = 10; + ui::ThreadListRow recent; + recent.id = "recent"; + recent.presentationKey = recent.id; + recent.title = "Alpha"; + recent.createdAt = 1; + recent.updatedAt = 2; + recent.recencyAt = 30; + ui::ThreadListRow missing; + missing.id = "missing"; + missing.presentationKey = missing.id; + missing.title = "2 tasks"; + snapshot.roots = {older, recent, missing}; + + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + if (tree) + tree->setStyle(&normalMotion); + auto* sortButton = pane.findChild(QStringLiteral("threadSortButton")); + if (!require(tree && tree->topLevelItemCount() == 3, "thread tree missing") || + !require(sortButton && sortButton->menu(), "thread sort control missing") || + !require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == QStringLiteral("recent"), + "thread rows are not ordered by recencyAt newest first")) + return false; + if (!require(tree->topLevelItem(0)->toolTip(0).contains(QStringLiteral("Recent turn:")) && + tree->topLevelItem(0)->toolTip(0).contains(QStringLiteral("Created:")), + "thread hover omits provider recent-turn or creation time")) + return false; + + QStringList sortLabels; + for (QAction* action : sortButton->menu()->actions()) + sortLabels.push_back(action->text()); + if (!require(sortLabels == QStringList{QStringLiteral("Alphanumeric"), + QStringLiteral("Created"), + QStringLiteral("Recent"), + QStringLiteral("Section order")}, + "thread sort menu does not expose the four supported contracts")) + return false; + + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); + QApplication::processEvents(); + if (!require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == QStringLiteral("missing"), + "alphanumeric order is not numeric-aware") || + !require(tree->topLevelItem(1)->data(0, Qt::UserRole).toString() == QStringLiteral("older"), + "alphanumeric order did not place 20 after 2") || + !require(tree->topLevelItem(2)->data(0, Qt::UserRole).toString() == QStringLiteral("recent"), + "alphanumeric order did not place letters after numeric titles")) + return false; + + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Created); + QApplication::processEvents(); + if (!require(tree->topLevelItem(0)->data(0, Qt::UserRole).toString() == QStringLiteral("older"), + "Created order is not newest first") || + !require(tree->topLevelItem(1)->data(0, Qt::UserRole).toString() == QStringLiteral("recent"), + "Created order did not keep older dated rows before missing") || + !require(tree->topLevelItem(2)->data(0, Qt::UserRole).toString() == QStringLiteral("missing"), + "Created order did not put missing timestamps last")) + return false; + + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Recency); + QApplication::processEvents(); + + snapshot.roots[0].recencyAt = 31; + snapshot.roots[0].awaitingPromptConversation = true; + snapshot.roots[0].pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; + pane.refresh(snapshot); + QApplication::processEvents(); + auto* animation = pane.findChild(QStringLiteral("optimisticThreadAnimation")); + QTreeWidgetItem* promoted = tree->topLevelItem(0); + QAccessibleInterface* promotedAccessible = threadAccessible(tree, promoted); + if (!require(promoted->data(0, Qt::UserRole).toString() == QStringLiteral("older"), + "new turn admission did not promote its thread") || + !require(promotedAccessible && promotedAccessible->text(QAccessible::Name) == QStringLiteral("20 tasks"), + "promotion substituted a canonical ID for the chosen name") || + !require(animation && animation->isActive(), "thread-card animation did not follow the pending prompt")) + return false; + + snapshot.roots[1].status = nodegraph::NodeStatus::Running; + pane.refresh(snapshot); + QApplication::processEvents(); + if (!require(animation->isActive(), "unrelated thread traffic stopped pending prompt animation")) + return false; + + pane.hide(); + if (!require(!animation->isActive(), "hiding the thread pane retained animation work")) + return false; + pane.show(); + QApplication::processEvents(); + if (!require(animation->isActive(), "showing the thread pane did not resume visible animation")) + return false; + + snapshot.roots[0].awaitingPromptConversation = false; + snapshot.roots[0].pendingPromptAdmittedAtMs.reset(); + pane.refresh(snapshot); + QApplication::processEvents(); + return require(!animation->isActive(), "prompt acknowledgement did not stop thread-card animation") && + require(tree->topLevelItem(0) == promoted && promotedAccessible && promotedAccessible->isValid() && + promotedAccessible->text(QAccessible::Name) == QStringLiteral("20 tasks"), + "prompt acknowledgement changed the chosen name"); } - pane.refresh(snapshot); - pane.show(); - auto* tree = threadTree(pane); - tree->expandAll(); - threadItem(tree, "cap-section")->setExpanded(true); - QApplication::processEvents(); - QTreeView* largeBody = nullptr; - QTreeView* smallBody = nullptr; - for (auto* body : pane.findChildren("projectThreadBody")) { - if (body->rootIndex().data(Qt::UserRole).toString() == "cap-large") { - largeBody = body; + + bool reducedMotionStopsThreadFeedbackAtTheStyleBoundary() { + ui::ThreadListRow row; + row.id = "reduced-motion-thread"; + row.presentationKey = row.id; + row.title = "Reduced motion"; + row.cwd = "/workspace"; + row.awaitingPromptConversation = true; + row.pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; + ui::ThreadListSnapshot snapshot; + snapshot.roots.push_back(row); + + AnimationDurationStyle normalMotion(100); + AnimationDurationStyle reducedMotion(0); + middle::ThreadPane pane; + pane.resize(320, 240); + if (QTreeWidget* tree = threadTree(pane)) + tree->setStyle(&normalMotion); + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + auto* animation = pane.findChild(QStringLiteral("optimisticThreadAnimation")); + bool result = require(animation && animation->isActive(), "normal motion did not start visible thread feedback"); + + if (tree) + tree->setStyle(&reducedMotion); + QElapsedTimer stopped; + stopped.start(); + while (animation && animation->isActive() && stopped.elapsed() < 100) { + QApplication::processEvents(QEventLoop::AllEvents, 10); + QThread::msleep(1); } - if (body->rootIndex().data(Qt::UserRole).toString() == "cap-small") { - smallBody = body; + const QImage staticFrame = tree ? tree->viewport()->grab().toImage() : QImage{}; + QElapsedTimer stable; + stable.start(); + while (stable.elapsed() < 110) { + QApplication::processEvents(QEventLoop::AllEvents, 10); + QThread::msleep(1); } + result &= require(tree && animation && !animation->isActive() && tree->viewport()->grab().toImage() == staticFrame, + "reduced motion did not stop thread feedback at the style boundary"); + + if (tree) + tree->setStyle(&normalMotion); + QApplication::processEvents(); + result &= require(animation && animation->isActive(), "restoring motion did not resume visible thread feedback"); + return result; } - passed &= require(largeBody && smallBody, "expanded projects have native body viewports"); - if (largeBody && smallBody) { - auto* group = threadItem(tree, "cap-large"); - auto* sectionItem = threadItem(tree, "cap-section"); - const auto sectionIndex = tree->indexFromItem(sectionItem); - const int rowHeight = largeBody->visualRect(sectionIndex).height(); - passed &= require(largeBody->viewport()->height() == 8 * rowHeight && smallBody->viewport()->height() == 2 * rowHeight, - "eight physical rows include section headings, while small projects shrink"); - passed &= require(largeBody->model() == tree->model() && largeBody->selectionModel() == tree->selectionModel() && - largeBody->itemDelegate() == tree->itemDelegate(), - "project bodies reuse the authoritative model, selection and row renderer"); - passed &= require(pagesRequested == 0, "a page beyond the eight visible rows is not requested early"); - const QRect headerBefore = tree->visualItemRect(group); - const QPoint wheelPoint(80, 60); - QWheelEvent wheel(QPointF(wheelPoint), - largeBody->viewport()->mapToGlobal(wheelPoint), - QPoint{}, - QPoint(0, -120), - Qt::NoButton, - Qt::NoModifier, - Qt::NoScrollPhase, - false); - QApplication::sendEvent(largeBody->viewport(), &wheel); - QApplication::processEvents(); - passed &= require(largeBody->verticalScrollBar()->value() > 0 && tree->visualItemRect(group) == headerBefore, - "wheel input scrolls the actual project body while its heading stays fixed"); - largeBody->verticalScrollBar()->setValue(0); - auto* last = threadItem(tree, "cap-19"); - const auto lastIndex = tree->indexFromItem(last); - auto* accessible = threadAccessible(tree, last); - const auto identity = accessible ? QAccessible::uniqueId(accessible) : 0; - largeBody->scrollTo(lastIndex); - QApplication::processEvents(); - click(largeBody->viewport(), largeBody->visualRect(lastIndex).center()); - passed &= require(tree->currentItem() == last && tree->visualItemRect(group) == headerBefore && - smallBody->verticalScrollBar()->value() == 0, - "scrolling and selecting a late thread keeps project headings and other cards fixed"); - passed &= require(accessible && !accessible->rect().isEmpty() && accessible->state().selected && - QAccessible::uniqueId(threadAccessible(tree, last)) == identity, - "scrolled thread selection uses its visible accessible geometry and stable identity"); - largeBody->setFocus(); - auto* bodyAccessible = QAccessible::queryAccessibleInterface(largeBody); - passed &= require(bodyAccessible && bodyAccessible->focusChild() == accessible && accessible->state().focused, - "native body focus resolves to the existing logical row accessible"); - tree->verticalScrollBar()->setValue(2 * rowHeight); - QApplication::processEvents(); - const int panelScrollBeforeContext = tree->verticalScrollBar()->value(); - passed &= require(panelScrollBeforeContext > 0 && tree->visualItemRect(group).top() < 0, - "the project heading is clipped above the panel before the context click"); - const auto selectedBeforeContext = tree->selectionModel()->selectedRows(); - const auto currentBeforeContext = tree->currentIndex(); - const int selectionsBeforeContext = selections; - const int scrollBeforeContext = largeBody->verticalScrollBar()->value(); - const QPoint contextPoint(80, std::max(4, -largeBody->geometry().top() + rowHeight / 2)); - const QPoint contextGlobal = largeBody->viewport()->mapToGlobal(contextPoint); - const auto contextIndex = largeBody->indexAt(contextPoint); - const auto contextId = contextIndex.data(Qt::UserRole).toString().toStdString(); - nodegraph::NodeRef expectedArchive; + + int colorDistance(const QColor& left, const QColor& right) { + return std::abs(left.red() - right.red()) + std::abs(left.green() - right.green()) + std::abs(left.blue() - right.blue()); + } + + QColor logicalPixel(const QImage& image, QPoint point) { + const qreal dpr = image.devicePixelRatio(); + point = QPoint(qRound(point.x() * dpr), qRound(point.y() * dpr)); + return image.rect().contains(point) ? image.pixelColor(point) : QColor{}; + } + + bool projectBodiesCapVisibleRows() { + bool passed = true; + nodegraph::NodeGraph graph; + std::vector targets; { - auto read = graph.tryRead(); - expectedArchive = read->find({nodegraph::NodeKind::Thread, contextId}); - } - passed &= require(expectedArchive && contextIndex != lastIndex, - "the pointer addresses a different older thread in the scrolled project"); - QMouseEvent contextPress(QEvent::MouseButtonPress, - QPointF(contextPoint), - QPointF(contextPoint), - largeBody->viewport()->mapToGlobal(contextPoint), - Qt::RightButton, - Qt::RightButton, - Qt::NoModifier); - QApplication::sendEvent(largeBody->viewport(), &contextPress); - const QPoint releasePoint = largeBody->viewport()->mapFromGlobal(contextGlobal); - QMouseEvent contextRelease(QEvent::MouseButtonRelease, - QPointF(releasePoint), - QPointF(releasePoint), - contextGlobal, - Qt::RightButton, - Qt::NoButton, - Qt::NoModifier); - QApplication::sendEvent(largeBody->viewport(), &contextRelease); - QApplication::processEvents(); - passed &= require(tree->selectionModel()->selectedRows() == selectedBeforeContext && - tree->currentIndex() == currentBeforeContext && selections == selectionsBeforeContext, - "a project-body context click preserves both current and selected thread without activating a conversation"); - passed &= require(largeBody->verticalScrollBar()->value() == scrollBeforeContext && - tree->verticalScrollBar()->value() == panelScrollBeforeContext && - largeBody->indexAt(largeBody->viewport()->mapFromGlobal(contextGlobal)) == contextIndex, - "a context click keeps the older thread under the pointer without moving the project viewport"); - QContextMenuEvent contextEvent(QContextMenuEvent::Mouse, largeBody->viewport()->mapFromGlobal(contextGlobal), contextGlobal); - QApplication::sendEvent(largeBody->viewport(), &contextEvent); - QApplication::processEvents(); - QMenu* contextMenu = nullptr; - for (auto* menu : pane.findChildren()) { - if (menu->isVisible()) { - contextMenu = menu; + auto write = graph.write(); + for (int index = 0; index < 20; ++index) { + targets.push_back(write.upsert({nodegraph::NodeKind::Thread, "cap-" + std::to_string(index)})); } + static_cast(write.finish()); } - passed &= require(contextMenu, "the scrolled project's native context menu opens"); - if (contextMenu) { - QAction* archiveAction = nullptr; - for (auto* action : contextMenu->actions()) { - if (action->text() == "Archive") { - archiveAction = action; + for (const auto& [width, points] : std::array{std::pair{260, 10}, std::pair{440, 10}, std::pair{260, 16}, std::pair{440, 16}}) { + middle::ThreadPane pane; + auto font = pane.font(); + font.setPointSize(points); + pane.setFont(font); + pane.resize(width, 800); + ui::ThreadListRow large; + large.kind = ui::ThreadRowKind::Project; + large.id = large.presentationKey = "cap-large"; + large.title = "Large project"; + ui::ThreadListRow section; + section.kind = ui::ThreadRowKind::Section; + section.id = section.presentationKey = "cap-section"; + section.title = "Section counts as one row"; + for (int index = 0; index < 20; ++index) { + section.children.push_back(localDraft( + "cap-" + std::to_string(index), "cap-" + std::to_string(index), "Thread " + std::to_string(index), "/workspace")); + section.children.back().target = targets[index]; + } + ui::ThreadListRow page; + page.kind = ui::ThreadRowKind::Page; + page.id = page.presentationKey = "cap-page"; + page.title = "Load more"; + page.query = {{"method", "thread/list"}, {"parameters", {{"projectId", "cap-large"}}}}; + section.children.push_back(page); + large.children = {section}; + int pagesRequested = 0; + int selections = 0; + nodegraph::NodeRef archived; + middle::ThreadPane::Actions actions; + actions.select = [&](const nodegraph::NodeRef&) { + ++selections; + }; + actions.toggleArchive = [&](const nodegraph::NodeRef& target) { + archived = target; + }; + actions.browse = [&](const nlohmann::json&) { + ++pagesRequested; + }; + pane.setActions(std::move(actions)); + ui::ThreadListRow small = large; + small.id = small.presentationKey = "cap-small"; + small.title = "Small project"; + small.children = {localDraft("small-1", "small-1", "First", "/workspace"), + localDraft("small-2", "small-2", "Second", "/workspace")}; + ui::ThreadListSnapshot snapshot; + snapshot.providerReady = true; + snapshot.canControl = true; + snapshot.roots = {large, small}; + for (int index = 0; index < 15; ++index) { + ui::ThreadListRow empty; + empty.kind = ui::ThreadRowKind::Project; + empty.id = empty.presentationKey = "zz-empty-" + std::to_string(index); + empty.title = "Empty project " + std::to_string(index); + snapshot.roots.push_back(empty); + } + pane.refresh(snapshot); + pane.show(); + auto* tree = threadTree(pane); + tree->expandAll(); + threadItem(tree, "cap-section")->setExpanded(true); + QApplication::processEvents(); + QTreeView* largeBody = nullptr; + QTreeView* smallBody = nullptr; + for (auto* body : pane.findChildren("projectThreadBody")) { + if (body->rootIndex().data(Qt::UserRole).toString() == "cap-large") { + largeBody = body; + } + if (body->rootIndex().data(Qt::UserRole).toString() == "cap-small") { + smallBody = body; } } - passed &= require(archiveAction && archiveAction->isEnabled(), "the older thread can be archived from its context menu"); - if (archiveAction) { - archiveAction->trigger(); + passed &= require(largeBody && smallBody, "expanded projects have native body viewports"); + if (largeBody && smallBody) { + auto* group = threadItem(tree, "cap-large"); + auto* sectionItem = threadItem(tree, "cap-section"); + const auto sectionIndex = tree->indexFromItem(sectionItem); + const int rowHeight = largeBody->visualRect(sectionIndex).height(); + passed &= require(largeBody->viewport()->height() == 8 * rowHeight && smallBody->viewport()->height() == 2 * rowHeight, + "eight physical rows include section headings, while small projects shrink"); + passed &= require(largeBody->model() == tree->model() && largeBody->selectionModel() == tree->selectionModel() && + largeBody->itemDelegate() == tree->itemDelegate(), + "project bodies reuse the authoritative model, selection and row renderer"); + passed &= require(pagesRequested == 0, "a page beyond the eight visible rows is not requested early"); + const QRect headerBefore = tree->visualItemRect(group); + const QPoint wheelPoint(80, 60); + QWheelEvent wheel(QPointF(wheelPoint), + largeBody->viewport()->mapToGlobal(wheelPoint), + QPoint{}, + QPoint(0, -120), + Qt::NoButton, + Qt::NoModifier, + Qt::NoScrollPhase, + false); + QApplication::sendEvent(largeBody->viewport(), &wheel); + QApplication::processEvents(); + passed &= require(largeBody->verticalScrollBar()->value() > 0 && tree->visualItemRect(group) == headerBefore, + "wheel input scrolls the actual project body while its heading stays fixed"); + largeBody->verticalScrollBar()->setValue(0); + auto* last = threadItem(tree, "cap-19"); + const auto lastIndex = tree->indexFromItem(last); + auto* accessible = threadAccessible(tree, last); + const auto identity = accessible ? QAccessible::uniqueId(accessible) : 0; + largeBody->scrollTo(lastIndex); + QApplication::processEvents(); + click(largeBody->viewport(), largeBody->visualRect(lastIndex).center()); + passed &= require(tree->currentItem() == last && tree->visualItemRect(group) == headerBefore && + smallBody->verticalScrollBar()->value() == 0, + "scrolling and selecting a late thread keeps project headings and other cards fixed"); + passed &= require(accessible && !accessible->rect().isEmpty() && accessible->state().selected && + QAccessible::uniqueId(threadAccessible(tree, last)) == identity, + "scrolled thread selection uses its visible accessible geometry and stable identity"); + largeBody->setFocus(); + auto* bodyAccessible = QAccessible::queryAccessibleInterface(largeBody); + passed &= require(bodyAccessible && bodyAccessible->focusChild() == accessible && accessible->state().focused, + "native body focus resolves to the existing logical row accessible"); + tree->verticalScrollBar()->setValue(2 * rowHeight); + QApplication::processEvents(); + const int panelScrollBeforeContext = tree->verticalScrollBar()->value(); + passed &= require(panelScrollBeforeContext > 0 && tree->visualItemRect(group).top() < 0, + "the project heading is clipped above the panel before the context click"); + const auto selectedBeforeContext = tree->selectionModel()->selectedRows(); + const auto currentBeforeContext = tree->currentIndex(); + const int selectionsBeforeContext = selections; + const int scrollBeforeContext = largeBody->verticalScrollBar()->value(); + const QPoint contextPoint(80, std::max(4, -largeBody->geometry().top() + rowHeight / 2)); + const QPoint contextGlobal = largeBody->viewport()->mapToGlobal(contextPoint); + const auto contextIndex = largeBody->indexAt(contextPoint); + const auto contextId = contextIndex.data(Qt::UserRole).toString().toStdString(); + nodegraph::NodeRef expectedArchive; + { + auto read = graph.tryRead(); + expectedArchive = read->find({nodegraph::NodeKind::Thread, contextId}); + } + passed &= require(expectedArchive && contextIndex != lastIndex, + "the pointer addresses a different older thread in the scrolled project"); + QMouseEvent contextPress(QEvent::MouseButtonPress, + QPointF(contextPoint), + QPointF(contextPoint), + largeBody->viewport()->mapToGlobal(contextPoint), + Qt::RightButton, + Qt::RightButton, + Qt::NoModifier); + QApplication::sendEvent(largeBody->viewport(), &contextPress); + const QPoint releasePoint = largeBody->viewport()->mapFromGlobal(contextGlobal); + QMouseEvent contextRelease(QEvent::MouseButtonRelease, + QPointF(releasePoint), + QPointF(releasePoint), + contextGlobal, + Qt::RightButton, + Qt::NoButton, + Qt::NoModifier); + QApplication::sendEvent(largeBody->viewport(), &contextRelease); + QApplication::processEvents(); + passed &= require( + tree->selectionModel()->selectedRows() == selectedBeforeContext && tree->currentIndex() == currentBeforeContext && + selections == selectionsBeforeContext, + "a project-body context click preserves both current and selected thread without activating a conversation"); + passed &= require(largeBody->verticalScrollBar()->value() == scrollBeforeContext && + tree->verticalScrollBar()->value() == panelScrollBeforeContext && + largeBody->indexAt(largeBody->viewport()->mapFromGlobal(contextGlobal)) == contextIndex, + "a context click keeps the older thread under the pointer without moving the project viewport"); + QContextMenuEvent contextEvent( + QContextMenuEvent::Mouse, largeBody->viewport()->mapFromGlobal(contextGlobal), contextGlobal); + QApplication::sendEvent(largeBody->viewport(), &contextEvent); + QApplication::processEvents(); + QMenu* contextMenu = nullptr; + for (auto* menu : pane.findChildren()) { + if (menu->isVisible()) { + contextMenu = menu; + } + } + passed &= require(contextMenu, "the scrolled project's native context menu opens"); + if (contextMenu) { + QAction* archiveAction = nullptr; + for (auto* action : contextMenu->actions()) { + if (action->text() == "Archive") { + archiveAction = action; + } + } + passed &= + require(archiveAction && archiveAction->isEnabled(), "the older thread can be archived from its context menu"); + if (archiveAction) { + archiveAction->trigger(); + } + contextMenu->close(); + } + passed &= require(archived == expectedArchive, "Archive targets the older thread originally right-clicked"); + const int scrollBefore = largeBody->verticalScrollBar()->value(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= + require(largeBody->verticalScrollBar()->value() == scrollBefore && tree->selectionModel()->isSelected(lastIndex), + "a semantic refresh preserves internal scroll and selection"); + largeBody->setExpanded(sectionIndex, false); + QApplication::processEvents(); + passed &= require(!sectionItem->isExpanded() && largeBody->viewport()->height() == rowHeight && + largeBody->verticalScrollBar()->maximum() == 0, + "collapsing a section excludes descendants from the project height"); + sectionItem->setExpanded(true); + QApplication::processEvents(); + passed &= require(largeBody->isExpanded(sectionIndex) && largeBody->viewport()->height() == 8 * rowHeight, + "the body projects authoritative expansion changes"); + tree->setCurrentItem(group); + tree->setFocus(); + QKeyEvent down(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier); + QApplication::sendEvent(tree, &down); + passed &= + require(tree->currentItem() == sectionItem && largeBody->hasFocus(), "keyboard navigation enters the project body"); + QKeyEvent up(QEvent::KeyPress, Qt::Key_Up, Qt::NoModifier); + QApplication::sendEvent(largeBody, &up); + passed &= require(tree->currentItem() == group && tree->hasFocus(), + "keyboard navigation returns to the fixed project heading"); + if (const auto path = qEnvironmentVariable("CODEXUI_CAP_SCREENSHOT_DIR"); !path.isEmpty()) { + passed &= + require(pane.grab().save(path + "/project-cap-" + QString::number(width) + "-font-" + QString::number(points) + + "-dpr-" + QString::number(pane.devicePixelRatioF()) + ".png"), + "capped project screenshot saved"); + } + largeBody->verticalScrollBar()->setValue(largeBody->verticalScrollBar()->maximum()); + QApplication::processEvents(); + passed &= require(pagesRequested == 1, "scrolling the project body to its page requests that page once"); + const int retainedScroll = largeBody->verticalScrollBar()->value(); + QPointer retiredBody = largeBody; + tree->setFocus(); + tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); + QApplication::processEvents(); + passed &= require(!retiredBody, "offscreen projects release their native body widgets"); + tree->verticalScrollBar()->setValue(0); + QApplication::processEvents(); + largeBody = nullptr; + for (auto* body : pane.findChildren("projectThreadBody")) { + if (body->rootIndex() == tree->indexFromItem(group)) { + largeBody = body; + } + } + passed &= require(largeBody && largeBody->verticalScrollBar()->value() == retainedScroll, + "recreating a visible body restores its semantic project scroll position"); + const QPoint labelPoint(100, tree->visualItemRect(group).top() + UiStyle::projectCardEdgePadding + 12); + QMouseEvent doubleClick(QEvent::MouseButtonDblClick, + QPointF(labelPoint), + QPointF(labelPoint), + tree->viewport()->mapToGlobal(labelPoint), + Qt::LeftButton, + Qt::LeftButton, + Qt::NoModifier); + QApplication::sendEvent(tree->viewport(), &doubleClick); + QApplication::processEvents(); + passed &= require(!group->isExpanded(), "double-clicking a project label collapses its body"); + group->setExpanded(false); + QApplication::processEvents(); + passed &= require(!pane.findChild("projectThreadBody") || + pane.findChildren("projectThreadBody").size() == 1, + "collapsing the project releases its body view"); + passed &= require(tree->sizeHintForIndex(tree->indexFromItem(group)).height() == tree->visualItemRect(group).height() && + sectionItem->childCount() == 21, + "collapse restores the complete one-line card without dropping threads"); } - contextMenu->close(); } - passed &= require(archived == expectedArchive, "Archive targets the older thread originally right-clicked"); - const int scrollBefore = largeBody->verticalScrollBar()->value(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require(largeBody->verticalScrollBar()->value() == scrollBefore && tree->selectionModel()->isSelected(lastIndex), - "a semantic refresh preserves internal scroll and selection"); - largeBody->setExpanded(sectionIndex, false); - QApplication::processEvents(); - passed &= require(!sectionItem->isExpanded() && largeBody->viewport()->height() == rowHeight && - largeBody->verticalScrollBar()->maximum() == 0, - "collapsing a section excludes descendants from the project height"); - sectionItem->setExpanded(true); - QApplication::processEvents(); - passed &= require(largeBody->isExpanded(sectionIndex) && largeBody->viewport()->height() == 8 * rowHeight, - "the body projects authoritative expansion changes"); - tree->setCurrentItem(group); - tree->setFocus(); - QKeyEvent down(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier); - QApplication::sendEvent(tree, &down); - passed &= require(tree->currentItem() == sectionItem && largeBody->hasFocus(), "keyboard navigation enters the project body"); - QKeyEvent up(QEvent::KeyPress, Qt::Key_Up, Qt::NoModifier); - QApplication::sendEvent(largeBody, &up); - passed &= require(tree->currentItem() == group && tree->hasFocus(), "keyboard navigation returns to the fixed project heading"); - if (const auto path = qEnvironmentVariable("CODEXUI_CAP_SCREENSHOT_DIR"); !path.isEmpty()) { - passed &= require(pane.grab().save(path + "/project-cap-" + QString::number(width) + "-font-" + QString::number(points) + - "-dpr-" + QString::number(pane.devicePixelRatioF()) + ".png"), - "capped project screenshot saved"); - } - largeBody->verticalScrollBar()->setValue(largeBody->verticalScrollBar()->maximum()); - QApplication::processEvents(); - passed &= require(pagesRequested == 1, "scrolling the project body to its page requests that page once"); - const int retainedScroll = largeBody->verticalScrollBar()->value(); - QPointer retiredBody = largeBody; - tree->setFocus(); - tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); - QApplication::processEvents(); - passed &= require(!retiredBody, "offscreen projects release their native body widgets"); - tree->verticalScrollBar()->setValue(0); - QApplication::processEvents(); - largeBody = nullptr; - for (auto* body : pane.findChildren("projectThreadBody")) { - if (body->rootIndex() == tree->indexFromItem(group)) { - largeBody = body; + return passed; + } + + bool projectDisclosureRestoresCollapsedGeometry() { + bool passed = true; + for (const int points : {10, 16}) { + for (const int width : {260, 440}) { + middle::ThreadPane pane; + auto font = pane.font(); + font.setPointSize(points); + pane.setFont(font); + pane.resize(width, 680); + pane.show(); + ui::ThreadListRow project; + project.kind = ui::ThreadRowKind::Project; + project.id = "height-project"; + project.presentationKey = project.id; + project.title = "Project name with Unicode 日本語 and a long label"; + ui::ThreadListRow section; + section.kind = ui::ThreadRowKind::Section; + section.id = "height-section"; + section.presentationKey = section.id; + section.title = "Section"; + ui::ThreadListRow member; + member.id = "height-member"; + member.presentationKey = member.id; + member.title = "Member"; + section.children = {member}; + project.children = {section, member}; + // Distinct semantic identities for the two member rows. + project.children.back().id = "direct-member"; + project.children.back().presentationKey = "direct-member"; + ui::ThreadListRow sibling; + sibling.kind = ui::ThreadRowKind::Project; + sibling.id = "next-project"; + sibling.presentationKey = sibling.id; + sibling.title = "Next project"; + ui::ThreadListSnapshot snapshot; + snapshot.roots = {project, sibling}; + pane.refresh(snapshot); + auto* tree = threadTree(pane); + auto* item = threadItem(tree, project.id); + auto* next = threadItem(tree, sibling.id); + tree->collapseAll(); + QApplication::processEvents(); + QRect initial = tree->visualItemRect(item); + initial.setHeight(tree->sizeHintForIndex(tree->indexFromItem(item)).height()); + auto* accessible = threadAccessible(tree, item); + const auto accessibleId = accessible ? QAccessible::uniqueId(accessible) : 0; + passed &= require(accessible && accessible->text(QAccessible::Name) == QString::fromStdString(project.title), + "project headings expose the complete authored name without a Project prefix"); + passed &= + require(tree->visualItemRect(item) == initial, "initially collapsed project uses the delegate's canonical height"); + for (const bool mouseExpand : {true, false}) { + tree->setCurrentItem(item); + tree->setFocus(); + if (mouseExpand) { + const QRect rect = tree->visualItemRect(item); + click(tree->viewport(), QPoint(rect.left() - 1, rect.center().y())); + } else { + QKeyEvent expand(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier); + QApplication::sendEvent(tree, &expand); + } + QApplication::processEvents(); + passed &= require(item->isExpanded(), "project expands through mouse and keyboard input"); + const QRect expanded = tree->visualItemRect(item); + passed &= require(expanded.height() == tree->sizeHintForIndex(tree->indexFromItem(item)).height(), + "expanded project header matches the current delegate geometry"); + if (const auto path = qEnvironmentVariable("CODEXUI_COLLAPSE_SCREENSHOT_DIR"); !path.isEmpty()) { + passed &= + require(pane.grab().save(path + "/expanded-" + QString::number(width) + "-font-" + QString::number(points) + + "-dpr-" + QString::number(pane.devicePixelRatioF()) + ".png"), + "expanded project visual evidence saved"); + } + if (mouseExpand) { + QKeyEvent collapse(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier); + QApplication::sendEvent(tree, &collapse); + } else { + click(tree->viewport(), QPoint(expanded.left() - 1, expanded.top() + UiStyle::projectCardEdgePadding + 12)); + } + QApplication::processEvents(); + const QRect collapsed = tree->visualItemRect(item); + passed &= + require(!item->isExpanded() && collapsed == initial && tree->visualItemRect(next).top() == initial.bottom() + 1, + "collapsing a project restores its full one-line card and following-row position"); + passed &= + require(threadAccessible(tree, item) && QAccessible::uniqueId(threadAccessible(tree, item)) == accessibleId && + tree->currentItem() == item, + "project disclosure retains focus and accessible identity"); + if (const auto path = qEnvironmentVariable("CODEXUI_COLLAPSE_SCREENSHOT_DIR"); !path.isEmpty()) { + passed &= require(pane.grab().save(path + "/collapsed-" + QString::number(width) + "-font-" + + QString::number(points) + "-dpr-" + + QString::number(pane.devicePixelRatioF()) + ".png"), + "collapsed project visual evidence saved"); + } + } } } - passed &= require(largeBody && largeBody->verticalScrollBar()->value() == retainedScroll, - "recreating a visible body restores its semantic project scroll position"); - const QPoint labelPoint(100, tree->visualItemRect(group).top() + UiStyle::projectCardEdgePadding + 12); - QMouseEvent doubleClick(QEvent::MouseButtonDblClick, - QPointF(labelPoint), - QPointF(labelPoint), - tree->viewport()->mapToGlobal(labelPoint), - Qt::LeftButton, - Qt::LeftButton, - Qt::NoModifier); - QApplication::sendEvent(tree->viewport(), &doubleClick); - QApplication::processEvents(); - passed &= require(!group->isExpanded(), "double-clicking a project label collapses its body"); - group->setExpanded(false); - QApplication::processEvents(); - passed &= - require(!pane.findChild("projectThreadBody") || pane.findChildren("projectThreadBody").size() == 1, - "collapsing the project releases its body view"); - passed &= require(tree->sizeHintForIndex(tree->indexFromItem(group)).height() == tree->visualItemRect(group).height() && - sectionItem->childCount() == 21, - "collapse restores the complete one-line card without dropping threads"); + return passed; + } + + bool groupsReportDescendantThreadStatus() { + using namespace nodegraph; + NodeGraph graph; + std::array threads; + { + auto write = graph.write(); + const auto entity = [&](NodeKind kind, const std::string& id, nlohmann::json fields) { + NodeState state; + state.fields = *valueFromJson(fields).asObject(); + return write.upsert({kind, id}, std::move(state)); + }; + const auto project = entity(NodeKind::Project, "status-project", {{"name", "Project"}}); + const auto section = + entity(NodeKind::ThreadSection, "status-section", {{"name", "Section"}, {"appearance", {{"color", "#ff0000"}}}}); + static_cast(entity(NodeKind::Project, "empty-project", {{"name", "Empty project"}})); + static_cast(entity(NodeKind::ThreadSection, "empty-section", {{"name", "Empty section"}})); + for (std::size_t index = 0; index < threads.size(); ++index) { + threads[index] = + entity(NodeKind::Thread, "member-" + std::to_string(index), {{"name", "Member " + std::to_string(index)}}); + write.setStatus(threads[index], NodeStatus::NotLoaded); + write.relate(threads[index], RelationKind::ProjectMembership, project); + write.relate(threads[index], RelationKind::SectionMembership, section); + } + write.relate(threads[0], RelationKind::StructuralChildThread, threads[1]); + write.relate(threads[1], RelationKind::AgentChildThread, threads[2]); + for (const auto* method : {"project/list", "threadSection/list"}) { + static_cast(entity( + NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object()), {{"loaded", true}, {"hasMore", false}})); + } + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.show(); + bool passed = true; + // Active grandchildren must win over a loaded sibling in either iteration order; + // terminal errors still mean loaded, and unloading must clear the aggregate. + const std::array cases{std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, + std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Completed, NodeStatus::NotLoaded}, + std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Running, NodeStatus::Completed}, + std::array{NodeStatus::Completed, NodeStatus::NotLoaded, NodeStatus::Running, NodeStatus::NotLoaded}, + std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Failed, NodeStatus::NotLoaded}, + std::array{NodeStatus::NotLoaded, NodeStatus::Interrupted, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, + std::array{NodeStatus::Running, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, + std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}}; + for (const auto grouping : {ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { + auto options = pane.browserOptions(); + options.grouping = grouping; + for (const auto& statuses : cases) { + { + auto write = graph.write(); + for (std::size_t index = 0; index < threads.size(); ++index) { + write.setStatus(threads[index], statuses[index]); + } + static_cast(write.finish()); + } + const bool active = std::ranges::find(statuses, NodeStatus::Running) != statuses.end(); + const bool loaded = std::ranges::any_of(statuses, [](NodeStatus status) { + return status != NodeStatus::NotLoaded; + }); + const NodeStatus expected = active ? NodeStatus::Running : loaded ? NodeStatus::Completed : NodeStatus::NotLoaded; + const QColor expectedColor(active ? UiStyle::statusIndirect + : loaded ? UiStyle::statusSuccess + : UiStyle::threadInactive); + const auto snapshot = adapter.threads({}, nullptr, &options); + passed &= require(snapshot.has_value(), "group status fixture projects through the adapter"); + if (snapshot) { + const auto checkRows = [&](const auto& self, const std::vector& rows) -> void { + for (const auto& row : rows) { + if (row.kind == ui::ThreadRowKind::Project || row.kind == ui::ThreadRowKind::Section) { + passed &= + require(row.status.semantic == (row.id.starts_with("empty-") ? NodeStatus::NotLoaded : expected), + "projects and sections aggregate descendant status with active precedence"); + } + self(self, row.children); + } + }; + checkRows(checkRows, snapshot->roots); + pane.refresh(*snapshot); + auto* tree = threadTree(pane); + for (const int width : {260, 420}) { + pane.resize(width, 1000); + for (const bool expanded : {true, false}) { + tree->expandAll(); + if (!expanded) { + threadItem(tree, "member-0")->setExpanded(false); + threadItem(tree, "status-section")->setExpanded(false); + } + QApplication::processEvents(); + const QImage image = tree->viewport()->grab().toImage(); + for (const auto* id : {"status-project", "status-section", "empty-project", "empty-section"}) { + auto* item = threadItem(tree, id); + if (item) { + const bool empty = std::string_view(id).starts_with("empty-"); + const QColor color = empty ? QColor(UiStyle::threadInactive) : expectedColor; + const QRect rect = tree->visualItemRect(item); + // Measure the disc's continuous pixel band; later child-row chevrons can share its color. + const qreal dpr = image.devicePixelRatio(); + QRect disc; + const QRect search(qRound((rect.left() + 7) * dpr), + qRound(rect.top() * dpr), + qRound(15 * dpr), + qRound(std::min(rect.height(), 40) * dpr)); + for (int y = search.top(); y <= search.bottom() && (disc.isEmpty() || y <= disc.bottom() + 1); + ++y) { + for (int x = search.left(); x <= search.right(); ++x) { + if (image.rect().contains(x, y) && colorDistance(image.pixelColor(x, y), color) <= 12) { + disc = disc.united(QRect(x, y, 1, 1)); + } + } + } + passed &= require(!disc.isEmpty() && std::abs(disc.width() - 10 * dpr) <= 2 && + std::abs(disc.height() - 10 * dpr) <= 2 && + std::abs(disc.center().x() / dpr - (rect.left() + 14)) <= 1, + "group circle uses the thread color, position and ten-pixel diameter"); + const auto* accessible = threadAccessible(tree, item); + passed &= require(accessible && accessible->text(QAccessible::Description) + .contains(empty || !loaded ? "Threads: not loaded" + : active ? "Threads: active" + : "Threads: loaded"), + "group aggregate status is available without relying on color"); + } + } + if (const auto path = qEnvironmentVariable("CODEXUI_STATUS_SCREENSHOT_DIR"); + !path.isEmpty() && expanded && width == 420) { + passed &= + require(pane.grab().save(path + "/group-status-" + QString::number(static_cast(grouping)) + + "-" + QString::number(static_cast(expected)) + "-dpr-" + + QString::number(pane.devicePixelRatioF()) + ".png"), + "group status visual evidence saved"); + } + } + } + } + } + } + return passed; + } + + bool selectedThreadUsesSemanticSurface() { + bool passed = + require(QColor(UiStyle::threadSelected) == QColor("#ffffb3"), "selected thread must use the bright pure-yellow tint"); + for (const bool grouped : {false, true}) { + middle::ThreadPane pane; + pane.resize(360, 360); + ui::ThreadListSnapshot snapshot; + ui::ThreadListRow row; + row.id = "color-selected"; + row.presentationKey = row.id; + row.title = "Selected"; + ui::ThreadListRow other; + other.id = "color-other"; + other.presentationKey = other.id; + other.title = "Other"; + if (grouped) { + ui::ThreadListRow project; + project.kind = ui::ThreadRowKind::Project; + project.id = "color-project"; + project.presentationKey = project.id; + project.title = "Project"; + project.children = {row, other}; + snapshot.roots = {project}; + } else { + snapshot.roots = {row, other}; + } + snapshot.selectedThreadId = row.id; + pane.refresh(snapshot); + pane.show(); + QTreeWidget* tree = threadTree(pane); + if (!require(tree != nullptr, "color fixture has no thread tree")) { + passed = false; + continue; + } + QApplication::processEvents(); + auto* selected = threadItem(tree, row.id); + auto* unselected = threadItem(tree, other.id); + if (!require(selected && unselected, "color fixture has missing rows")) { + passed = false; + continue; + } + const QRect selectedRect = tree->visualItemRect(selected); + const QRect otherRect = tree->visualItemRect(unselected); + const QImage rendered = tree->viewport()->grab().toImage(); + const int sampleX = tree->viewport()->width() - 16; + passed &= require( + colorDistance(logicalPixel(rendered, {sampleX, selectedRect.center().y()}), QColor(UiStyle::threadSelected)) == 0, + "thread selection must use its semantic surface in grouped and ungrouped views"); + passed &= require(colorDistance(logicalPixel(rendered, {sampleX, otherRect.center().y()}), + QColor(grouped ? UiStyle::activeGroupSurface : UiStyle::panel)) == 0, + "unselected threads must inherit their enclosing surface"); + } + return passed; + } + + bool threadDisclosureIsReadyOnFirstPresentation() { + bool passed = true; + for (bool grouped : {false, true}) { + middle::ThreadPane pane; + pane.resize(340, 650); + ui::ThreadListRow origin, fork, nested, project; + origin.id = origin.presentationKey = origin.title = "initial-origin"; + fork.id = fork.presentationKey = fork.title = "initial-fork"; + nested.id = nested.presentationKey = nested.title = "initial-nested"; + project.kind = ui::ThreadRowKind::Project; + project.id = project.presentationKey = project.title = "initial-project"; + fork.children = {nested}; + origin.children = {fork}; + project.children = {origin}; + ui::ThreadListSnapshot snapshot; + snapshot.roots = {grouped ? project : origin}; + snapshot.selectedThreadId = origin.id; + auto initial = snapshot; + if (grouped) { + initial.roots.front().children.front().children.clear(); + } else { + initial.roots.front().children.clear(); + } + pane.refresh(initial); + pane.show(); + auto* tree = threadTree(pane); + if (grouped) { + tree->topLevelItem(0)->setExpanded(true); + } + QApplication::processEvents(); + pane.refresh(snapshot); + QApplication::processEvents(); + auto* originItem = threadItem(tree, origin.id); + auto* forkItem = threadItem(tree, fork.id); + auto* nestedItem = threadItem(tree, nested.id); + passed &= require(originItem && forkItem && nestedItem && originItem->isExpanded() && forkItem->isExpanded(), + "new thread hierarchies must start expanded without selecting a fork"); + const auto checkChevron = [&](QTreeWidgetItem* item) { + const QRect rect = tree->visualItemRect(item); + const QImage image = tree->viewport()->grab().toImage(); + int pixels = 0; + for (int y = rect.center().y() - 7; y <= rect.center().y() + 7; ++y) { + for (int x = rect.left() - 7; x <= rect.left() + 5; ++x) { + if (colorDistance(logicalPixel(image, QPoint(x, y)), QColor(QString::fromLatin1(UiStyle::secondary))) < 40) { + ++pixels; + } + } + } + passed &= require(rect.isValid() && pixels >= 3, + ("fork-parent chevron missing: " + item->data(0, Qt::UserRole).toString().toStdString() + + " grouped=" + std::to_string(grouped)) + .c_str()); + }; + checkChevron(originItem); + originItem->setExpanded(false); + QApplication::processEvents(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(!originItem->isExpanded(), "refresh must preserve a manually folded thread"); + checkChevron(originItem); + snapshot.selectedThreadId = nested.id; + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(originItem->isExpanded() && forkItem->isExpanded() && tree->currentItem() == nestedItem, + "selecting a descendant must reveal its ancestors"); + checkChevron(forkItem); + } + return passed; } - } - return passed; -} -bool projectDisclosureRestoresCollapsedGeometry() { - bool passed = true; - for (const int points : {10, 16}) { - for (const int width : {260, 440}) { + bool threadRowsConsumeCanonicalStatusTone() { middle::ThreadPane pane; - auto font = pane.font(); - font.setPointSize(points); - pane.setFont(font); - pane.resize(width, 680); + pane.resize(300, 300); pane.show(); - ui::ThreadListRow project; - project.kind = ui::ThreadRowKind::Project; - project.id = "height-project"; - project.presentationKey = project.id; - project.title = "Project name with Unicode 日本語 and a long label"; - ui::ThreadListRow section; - section.kind = ui::ThreadRowKind::Section; - section.id = "height-section"; - section.presentationKey = section.id; - section.title = "Section"; - ui::ThreadListRow member; - member.id = "height-member"; - member.presentationKey = member.id; - member.title = "Member"; - section.children = {member}; - project.children = {section, member}; - // Distinct semantic identities for the two member rows. - project.children.back().id = "direct-member"; - project.children.back().presentationKey = "direct-member"; - ui::ThreadListRow sibling; - sibling.kind = ui::ThreadRowKind::Project; - sibling.id = "next-project"; - sibling.presentationKey = sibling.id; - sibling.title = "Next project"; ui::ThreadListSnapshot snapshot; - snapshot.roots = {project, sibling}; - pane.refresh(snapshot); - auto* tree = threadTree(pane); - auto* item = threadItem(tree, project.id); - auto* next = threadItem(tree, sibling.id); - tree->collapseAll(); - QApplication::processEvents(); - QRect initial = tree->visualItemRect(item); - initial.setHeight(tree->sizeHintForIndex(tree->indexFromItem(item)).height()); - auto* accessible = threadAccessible(tree, item); - const auto accessibleId = accessible ? QAccessible::uniqueId(accessible) : 0; - passed &= require(accessible && accessible->text(QAccessible::Name) == QString::fromStdString(project.title), - "project headings expose the complete authored name without a Project prefix"); - passed &= require(tree->visualItemRect(item) == initial, "initially collapsed project uses the delegate's canonical height"); - for (const bool mouseExpand : {true, false}) { - tree->setCurrentItem(item); - tree->setFocus(); - if (mouseExpand) { - const QRect rect = tree->visualItemRect(item); - click(tree->viewport(), QPoint(rect.left() - 1, rect.center().y())); - } else { - QKeyEvent expand(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier); - QApplication::sendEvent(tree, &expand); + ui::ThreadListRow row; + row.id = "status-thread"; + row.presentationKey = row.id; + row.title = "Status thread"; + ui::ThreadListRow child; + child.id = "status-child"; + child.presentationKey = child.id; + ui::ThreadListRow grandchild; + grandchild.id = "status-grandchild"; + grandchild.presentationKey = grandchild.id; + child.children.push_back(grandchild); + row.children.push_back(child); + snapshot.roots.push_back(row); + const std::array cases{std::pair{nodegraph::NodeStatus::Running, UiStyle::statusActive}, + std::pair{nodegraph::NodeStatus::Completed, UiStyle::statusSuccess}, + std::pair{nodegraph::NodeStatus::Connected, UiStyle::statusSuccess}, + std::pair{nodegraph::NodeStatus::Interrupted, UiStyle::statusWarning}, + std::pair{nodegraph::NodeStatus::Failed, UiStyle::statusDanger}, + std::pair{nodegraph::NodeStatus::Disconnected, UiStyle::statusDanger}}; + bool passed = true; + for (const auto& [status, color] : cases) { + snapshot.roots.front().status = status; + pane.refresh(snapshot); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* item = tree ? tree->topLevelItem(0) : nullptr; + if (item) { + item->setExpanded(false); } QApplication::processEvents(); - passed &= require(item->isExpanded(), "project expands through mouse and keyboard input"); - const QRect expanded = tree->visualItemRect(item); - passed &= require(expanded.height() == tree->sizeHintForIndex(tree->indexFromItem(item)).height(), - "expanded project header matches the current delegate geometry"); - if (const auto path = qEnvironmentVariable("CODEXUI_COLLAPSE_SCREENSHOT_DIR"); !path.isEmpty()) { - passed &= require(pane.grab().save(path + "/expanded-" + QString::number(width) + "-font-" + QString::number(points) + - "-dpr-" + QString::number(pane.devicePixelRatioF()) + ".png"), - "expanded project visual evidence saved"); - } - if (mouseExpand) { - QKeyEvent collapse(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier); - QApplication::sendEvent(tree, &collapse); - } else { - click(tree->viewport(), QPoint(expanded.left() - 1, expanded.top() + UiStyle::projectCardEdgePadding + 12)); - } + const QRect rect = item ? tree->visualItemRect(item) : QRect{}; + const QColor actual = rect.isValid() + ? logicalPixel(tree->viewport()->grab().toImage(), QPoint(rect.left() + 14, rect.center().y())) + : QColor{}; + const QColor chevron = rect.isValid() + ? logicalPixel(tree->viewport()->grab().toImage(), QPoint(rect.left() - 1, rect.center().y())) + : QColor{}; + passed &= require(item && colorDistance(actual, QColor(QString::fromLatin1(color))) <= 6, + "thread delegate bypassed the canonical status tone"); + passed &= require(item && colorDistance(chevron, QColor(QString::fromLatin1(UiStyle::secondary))) <= 30, + "thread disclosure drifted from the status indicator"); + } + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* item = tree ? tree->topLevelItem(0) : nullptr; + const QRect rect = item ? tree->visualItemRect(item) : QRect{}; + const QPoint disclosureEdge(rect.left(), rect.center().y()); + const QColor edgePixel = rect.isValid() ? logicalPixel(tree->viewport()->grab().toImage(), disclosureEdge) : QColor{}; + passed &= require(item && !item->isExpanded() && colorDistance(edgePixel, QColor(QString::fromLatin1(UiStyle::panel))) > 50, + "disclosure mouse fixture did not target a visible chevron pixel"); + if (tree && item) { + click(tree->viewport(), QPoint(rect.left() - 12, rect.center().y())); + passed &= require(!item->isExpanded(), + "mouse disclosure target extended before its legacy " + "leading edge"); + click(tree->viewport(), QPoint(rect.left() - 11, rect.center().y())); + passed &= require(item->isExpanded(), + "mouse disclosure target omitted its legacy leading " + "edge"); + click(tree->viewport(), QPoint(rect.left() + 13, rect.center().y())); + passed &= require(item->isExpanded(), + "mouse disclosure target extended after its legacy " + "trailing edge"); + click(tree->viewport(), QPoint(rect.left() + 12, rect.center().y())); + passed &= require(!item->isExpanded(), + "mouse disclosure target omitted its legacy trailing " + "edge"); + click(tree->viewport(), QPoint(rect.left(), rect.top() + 7)); + passed &= require(!item->isExpanded(), + "mouse disclosure target extended above its legacy " + "leading edge"); + click(tree->viewport(), QPoint(rect.left(), rect.top() + 8)); + passed &= require(item->isExpanded(), "mouse disclosure target omitted its legacy top edge"); + click(tree->viewport(), QPoint(rect.left(), rect.bottom() - 7)); + passed &= require(item->isExpanded(), + "mouse disclosure target extended below its legacy " + "trailing edge"); + click(tree->viewport(), QPoint(rect.left(), rect.bottom() - 8)); + passed &= require(!item->isExpanded(), "mouse disclosure target omitted its legacy bottom edge"); + click(tree->viewport(), disclosureEdge); + QTreeWidgetItem* nested = item->child(0); + nested->setExpanded(false); QApplication::processEvents(); - const QRect collapsed = tree->visualItemRect(item); - passed &= require(!item->isExpanded() && collapsed == initial && tree->visualItemRect(next).top() == initial.bottom() + 1, - "collapsing a project restores its full one-line card and following-row position"); - passed &= require(threadAccessible(tree, item) && QAccessible::uniqueId(threadAccessible(tree, item)) == accessibleId && - tree->currentItem() == item, - "project disclosure retains focus and accessible identity"); - if (const auto path = qEnvironmentVariable("CODEXUI_COLLAPSE_SCREENSHOT_DIR"); !path.isEmpty()) { - passed &= require(pane.grab().save(path + "/collapsed-" + QString::number(width) + "-font-" + QString::number(points) + - "-dpr-" + QString::number(pane.devicePixelRatioF()) + ".png"), - "collapsed project visual evidence saved"); - } + const QRect nestedRect = tree->visualItemRect(nested); + click(tree->viewport(), QPoint(nestedRect.left() - 11, nestedRect.center().y())); + passed &= require(nested && nested->isExpanded(), "nested disclosure did not share the native target"); + click(tree->viewport(), QPoint(nestedRect.left() + 12, nestedRect.center().y())); + passed &= require(!nested->isExpanded(), "nested disclosure trailing edge did not collapse"); } + return passed; } - } - return passed; -} -bool groupsReportDescendantThreadStatus() { - using namespace nodegraph; - NodeGraph graph; - std::array threads; - { - auto write = graph.write(); - const auto entity = [&](NodeKind kind, const std::string& id, nlohmann::json fields) { - NodeState state; - state.fields = *valueFromJson(fields).asObject(); - return write.upsert({kind, id}, std::move(state)); - }; - const auto project = entity(NodeKind::Project, "status-project", {{"name", "Project"}}); - const auto section = - entity(NodeKind::ThreadSection, "status-section", {{"name", "Section"}, {"appearance", {{"color", "#ff0000"}}}}); - static_cast(entity(NodeKind::Project, "empty-project", {{"name", "Empty project"}})); - static_cast(entity(NodeKind::ThreadSection, "empty-section", {{"name", "Empty section"}})); - for (std::size_t index = 0; index < threads.size(); ++index) { - threads[index] = entity(NodeKind::Thread, "member-" + std::to_string(index), {{"name", "Member " + std::to_string(index)}}); - write.setStatus(threads[index], NodeStatus::NotLoaded); - write.relate(threads[index], RelationKind::ProjectMembership, project); - write.relate(threads[index], RelationKind::SectionMembership, section); - } - write.relate(threads[0], RelationKind::StructuralChildThread, threads[1]); - write.relate(threads[1], RelationKind::AgentChildThread, threads[2]); - for (const auto* method : {"project/list", "threadSection/list"}) { - static_cast( - entity(NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object()), {{"loaded", true}, {"hasMore", false}})); + bool rowDotUsesColor(QTreeWidget* tree, QTreeWidgetItem* item, const QColor& expected) { + if (!tree || !item) + return false; + QRect rect = tree->visualItemRect(item); + if (item->childCount() > 0) { + const QRect child = tree->visualItemRect(item->child(0)); + if (child.isValid() && rect.contains(child.center())) { + rect.setTop(rect.top() + UiStyle::projectCardEdgePadding); + rect.setBottom(child.top() - 1); + } + } + return rect.isValid() && + colorDistance(logicalPixel(tree->viewport()->grab().toImage(), QPoint(rect.left() + 14, rect.center().y())), expected) <= + 6; } - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.show(); - bool passed = true; - // Active grandchildren must win over a loaded sibling in either iteration order; - // terminal errors still mean loaded, and unloading must clear the aggregate. - const std::array cases{std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, - std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Completed, NodeStatus::NotLoaded}, - std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Running, NodeStatus::Completed}, - std::array{NodeStatus::Completed, NodeStatus::NotLoaded, NodeStatus::Running, NodeStatus::NotLoaded}, - std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::Failed, NodeStatus::NotLoaded}, - std::array{NodeStatus::NotLoaded, NodeStatus::Interrupted, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, - std::array{NodeStatus::Running, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}, - std::array{NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded, NodeStatus::NotLoaded}}; - for (const auto grouping : {ui::ThreadGrouping::Projects, ui::ThreadGrouping::Sections}) { - auto options = pane.browserOptions(); - options.grouping = grouping; - for (const auto& statuses : cases) { + + bool uninspectedResultsFollowCompletionAndSelection() { + using namespace nodegraph; + std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-inspection.json"); + const auto fixture = nlohmann::json::parse(input); + NodeGraph graph; + ThreadChannels channels; + WorkerLogic logic(graph, channels); + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.resize(480, 780); { auto write = graph.write(); - for (std::size_t index = 0; index < threads.size(); ++index) { - write.setStatus(threads[index], statuses[index]); + for (const auto& [key, kind] : + std::array{std::pair{"project", NodeKind::Project}, std::pair{"section", NodeKind::ThreadSection}}) { + NodeState state; + state.fields = *valueFromJson(fixture.at(key)).asObject(); + static_cast(write.upsert({kind, fixture.at(key).at("id").get()}, std::move(state))); + } + for (const auto method : {"project/list", "threadSection/list"}) { + NodeState state; + state.fields = {{"loaded", true}}; + static_cast( + write.upsert({NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object())}, std::move(state))); } static_cast(write.finish()); } - const bool active = std::ranges::find(statuses, NodeStatus::Running) != statuses.end(); - const bool loaded = std::ranges::any_of(statuses, [](NodeStatus status) { - return status != NodeStatus::NotLoaded; - }); - const NodeStatus expected = active ? NodeStatus::Running : loaded ? NodeStatus::Completed : NodeStatus::NotLoaded; - const QColor expectedColor(active ? UiStyle::statusIndirect : loaded ? UiStyle::statusSuccess : UiStyle::threadInactive); - const auto snapshot = adapter.threads({}, nullptr, &options); - passed &= require(snapshot.has_value(), "group status fixture projects through the adapter"); - if (snapshot) { - const auto checkRows = [&](const auto& self, const std::vector& rows) -> void { - for (const auto& row : rows) { - if (row.kind == ui::ThreadRowKind::Project || row.kind == ui::ThreadRowKind::Section) { - passed &= require(row.status.semantic == (row.id.starts_with("empty-") ? NodeStatus::NotLoaded : expected), - "projects and sections aggregate descendant status with active precedence"); - } - self(self, row.children); + for (const auto& thread : fixture.at("threads")) { + static_cast( + logic.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", valueFromJson(thread)}}})); + } + NodeRef selected; + int requestSerial = 0; + bool passed = true; + pane.show(); + for (const auto& step : fixture.at("steps")) { + if (step.contains("select")) { + { + auto read = graph.tryRead(); + selected = read->find({NodeKind::Thread, step.at("select").get()}); } - }; - checkRows(checkRows, snapshot->roots); - pane.refresh(*snapshot); - auto* tree = threadTree(pane); - for (const int width : {260, 420}) { - pane.resize(width, 1000); - for (const bool expanded : {true, false}) { - tree->expandAll(); - if (!expanded) { - threadItem(tree, "member-0")->setExpanded(false); - threadItem(tree, "status-section")->setExpanded(false); - } - QApplication::processEvents(); - const QImage image = tree->viewport()->grab().toImage(); - for (const auto* id : {"status-project", "status-section", "empty-project", "empty-section"}) { - auto* item = threadItem(tree, id); - if (item) { - const bool empty = std::string_view(id).starts_with("empty-"); - const QColor color = empty ? QColor(UiStyle::threadInactive) : expectedColor; - const QRect rect = tree->visualItemRect(item); - // Measure the painted disc in device pixels, excluding labels and chevrons. - const qreal dpr = image.devicePixelRatio(); - QRect disc; - const QRect search(qRound((rect.left() + 7) * dpr), - qRound(rect.top() * dpr), - qRound(15 * dpr), - qRound(std::min(rect.height(), 40) * dpr)); - for (int y = search.top(); y <= search.bottom(); ++y) { - for (int x = search.left(); x <= search.right(); ++x) { - if (image.rect().contains(x, y) && colorDistance(image.pixelColor(x, y), color) <= 12) { - disc = disc.united(QRect(x, y, 1, 1)); - } - } - } - passed &= require(!disc.isEmpty() && std::abs(disc.width() - 10 * dpr) <= 2 && - std::abs(disc.height() - 10 * dpr) <= 2 && - std::abs(disc.center().x() / dpr - (rect.left() + 14)) <= 1, - "group circle uses the thread color, position and ten-pixel diameter"); - const auto* accessible = threadAccessible(tree, item); - passed &= require(accessible && accessible->text(QAccessible::Description) - .contains(empty || !loaded ? "Threads: not loaded" - : active ? "Threads: active" - : "Threads: loaded"), - "group aggregate status is available without relying on color"); - } + static_cast(logic.inspectThread(selected)); + } else if (step.contains("method")) { + static_cast(logic.apply({DecodedMessageKind::ServerNotification, + step.at("method").get(), + {}, + *valueFromJson(step.at("params")).asObject()})); + } else if (step.contains("history")) { + const ProtocolRequestId id("inspection-history-" + std::to_string(++requestSerial)); + const auto admitted = + logic.applyDetailed({DecodedMessageKind::ClientRequest, + "thread/read", + id, + {{"threadId", valueFromJson(step.at("history").at("id"))}, {"includeTurns", true}}}); + static_cast(logic.applyDetailed({DecodedMessageKind::ClientResult, + "thread/read", + id, + {{"thread", valueFromJson(step.at("history"))}}, + admitted.primary})); + } else { + pane.refresh(*adapter.threads(selected, nullptr, &pane.browserOptions())); + auto* tree = threadTree(pane); + tree->expandAll(); + QApplication::processEvents(); + for (const auto& [id, value] : step.at("expected").items()) { + const auto tone = value.get(); + const QColor expected(tone == "active" ? UiStyle::statusActive + : tone == "indirect" ? UiStyle::statusIndirect + : tone == "uninspected" ? "#ec4899" + : UiStyle::statusSuccess); + auto* item = threadItem(tree, id); + const bool correct = item && rowDotUsesColor(tree, item, expected); + if (!correct) { + std::cerr << "Inspection fixture: " << step.at("label") << " row " << id << " expected " << tone << '\n'; } - if (const auto path = qEnvironmentVariable("CODEXUI_STATUS_SCREENSHOT_DIR"); - !path.isEmpty() && expanded && width == 420) { - passed &= require(pane.grab().save(path + "/group-status-" + QString::number(static_cast(grouping)) + "-" + - QString::number(static_cast(expected)) + "-dpr-" + - QString::number(pane.devicePixelRatioF()) + ".png"), - "group status visual evidence saved"); + passed &= require(correct, "native indicator violates the shared inspection contract"); + if (tone == "uninspected") { + passed &= require(item && item->toolTip(0).contains("not yet inspected"), + "uninspected results have a readable accessible description"); } } + auto* project = threadItem(tree, "ready-project"); + project->setExpanded(false); + QApplication::processEvents(); + const auto tone = step.at("expected").at("ready-project").get(); + const QColor expected(tone == "indirect" ? UiStyle::statusIndirect + : tone == "uninspected" ? "#ec4899" + : UiStyle::statusSuccess); + passed &= require(rowDotUsesColor(tree, project, expected), "collapsed projects preserve descendant result attention"); } } + return passed; } - } - return passed; -} - -bool selectedThreadUsesSemanticSurface() { - bool passed = require(QColor(UiStyle::threadSelected) == QColor("#ffffb3"), - "selected thread must use the bright pure-yellow tint"); - for (const bool grouped : {false, true}) { - middle::ThreadPane pane; - pane.resize(360, 360); - ui::ThreadListSnapshot snapshot; - ui::ThreadListRow row; - row.id = "color-selected"; - row.presentationKey = row.id; - row.title = "Selected"; - ui::ThreadListRow other; - other.id = "color-other"; - other.presentationKey = other.id; - other.title = "Other"; - if (grouped) { - ui::ThreadListRow project; - project.kind = ui::ThreadRowKind::Project; - project.id = "color-project"; - project.presentationKey = project.id; - project.title = "Project"; - project.children = {row, other}; - snapshot.roots = {project}; - } else { - snapshot.roots = {row, other}; - } - snapshot.selectedThreadId = row.id; - pane.refresh(snapshot); - pane.show(); - QTreeWidget *tree = threadTree(pane); - if (!require(tree != nullptr, "color fixture has no thread tree")) { - passed = false; - continue; - } - QApplication::processEvents(); - auto *selected = threadItem(tree, row.id); - auto *unselected = threadItem(tree, other.id); - if (!require(selected && unselected, "color fixture has missing rows")) { - passed = false; - continue; - } - const QRect selectedRect = tree->visualItemRect(selected); - const QRect otherRect = tree->visualItemRect(unselected); - const QImage rendered = tree->viewport()->grab().toImage(); - const int sampleX = tree->viewport()->width() - 16; - passed &= require( - colorDistance(logicalPixel(rendered, {sampleX, selectedRect.center().y()}), - QColor(UiStyle::threadSelected)) == 0, - "thread selection must use its semantic surface in grouped and ungrouped views"); - passed &= require( - colorDistance(logicalPixel(rendered, {sampleX, otherRect.center().y()}), - QColor(grouped ? UiStyle::activeGroupSurface - : UiStyle::panel)) == 0, - "unselected threads must inherit their enclosing surface"); - } - return passed; -} -bool threadDisclosureIsReadyOnFirstPresentation() { - bool passed = true; - for (bool grouped : {false, true}) { - middle::ThreadPane pane; - pane.resize(340, 650); - ui::ThreadListRow origin, fork, nested, project; - origin.id = origin.presentationKey = origin.title = "initial-origin"; - fork.id = fork.presentationKey = fork.title = "initial-fork"; - nested.id = nested.presentationKey = nested.title = "initial-nested"; - project.kind = ui::ThreadRowKind::Project; - project.id = project.presentationKey = project.title = "initial-project"; - fork.children = {nested}; - origin.children = {fork}; - project.children = {origin}; - ui::ThreadListSnapshot snapshot; - snapshot.roots = {grouped ? project : origin}; - snapshot.selectedThreadId = origin.id; - auto initial = snapshot; - if (grouped) { - initial.roots.front().children.front().children.clear(); - } else { - initial.roots.front().children.clear(); - } - pane.refresh(initial); - pane.show(); - auto* tree = threadTree(pane); - if (grouped) { - tree->topLevelItem(0)->setExpanded(true); - } - QApplication::processEvents(); - pane.refresh(snapshot); - QApplication::processEvents(); - auto* originItem = threadItem(tree, origin.id); - auto* forkItem = threadItem(tree, fork.id); - auto* nestedItem = threadItem(tree, nested.id); - passed &= require(originItem && forkItem && nestedItem && originItem->isExpanded() && forkItem->isExpanded(), - "new thread hierarchies must start expanded without selecting a fork"); - const auto checkChevron = [&](QTreeWidgetItem* item) { - const QRect rect = tree->visualItemRect(item); - const QImage image = tree->viewport()->grab().toImage(); - int pixels = 0; - for (int y = rect.center().y() - 7; y <= rect.center().y() + 7; ++y) { - for (int x = rect.left() - 7; x <= rect.left() + 5; ++x) { - if (colorDistance(logicalPixel(image, QPoint(x, y)), QColor(QString::fromLatin1(UiStyle::secondary))) < 40) { - ++pixels; + bool threadIndicatorsDistinguishDirectAndIndirectActivity() { + using namespace nodegraph; + std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-activity.json"); + const auto cases = nlohmann::json::parse(input); + NodeGraph graph; + ProtocolUpdater updater(graph); + ui::NodeGraphUiAdapter adapter(graph); + middle::ThreadPane pane; + pane.resize(340, 650); + pane.show(); + bool passed = true; + const std::array ids{"indicator-origin", "indicator-fork", "indicator-nested"}; + for (const auto& entry : cases) { + for (std::size_t index = 0; index < ids.size(); ++index) { + nlohmann::json fields{{"id", ids[index]}, {"name", ids[index]}, {"status", {{"type", entry.at("statuses").at(index)}}}}; + if (index != 0) { + fields["forkedFromId"] = ids[index - 1]; } + static_cast( + updater.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", valueFromJson(fields)}}})); + } + pane.refresh(*adapter.threads({})); + auto* tree = threadTree(pane); + auto* origin = threadItem(tree, ids[0]); + origin->setExpanded(true); + threadItem(tree, ids[1])->setExpanded(true); + QApplication::processEvents(); + for (std::size_t index = 0; index < ids.size(); ++index) { + const auto tone = entry.at("tones").at(index).get(); + const QColor color(tone == "active" ? UiStyle::statusActive + : tone == "indirect" ? UiStyle::statusIndirect + : tone == "success" ? UiStyle::statusSuccess + : UiStyle::threadInactive); + auto* item = threadItem(tree, ids[index]); + passed &= + require(rowDotUsesColor(tree, item, color), "thread indicator violates shared direct/indirect activity contract"); + passed &= require(item->toolTip(0).contains("Indirect activity") == (tone == "indirect"), + "indirect activity must have a readable tooltip and accessible description"); } + origin->setExpanded(false); + QApplication::processEvents(); + const auto tone = entry.at("tones").at(0).get(); + const QColor color(tone == "active" ? UiStyle::statusActive + : tone == "indirect" ? UiStyle::statusIndirect + : tone == "success" ? UiStyle::statusSuccess + : UiStyle::threadInactive); + passed &= require(rowDotUsesColor(tree, origin, color), "folding must preserve direct/indirect activity indication"); } - passed &= require(rect.isValid() && pixels >= 3, - ("fork-parent chevron missing: " + item->data(0, Qt::UserRole).toString().toStdString() + - " grouped=" + std::to_string(grouped)) - .c_str()); - }; - checkChevron(originItem); - originItem->setExpanded(false); - QApplication::processEvents(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require(!originItem->isExpanded(), "refresh must preserve a manually folded thread"); - checkChevron(originItem); - snapshot.selectedThreadId = nested.id; - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require(originItem->isExpanded() && forkItem->isExpanded() && tree->currentItem() == nestedItem, - "selecting a descendant must reveal its ancestors"); - checkChevron(forkItem); - } - return passed; -} - -bool threadRowsConsumeCanonicalStatusTone() { - middle::ThreadPane pane; - pane.resize(300, 300); - pane.show(); - ui::ThreadListSnapshot snapshot; - ui::ThreadListRow row; - row.id = "status-thread"; - row.presentationKey = row.id; - row.title = "Status thread"; - ui::ThreadListRow child; - child.id = "status-child"; - child.presentationKey = child.id; - ui::ThreadListRow grandchild; - grandchild.id = "status-grandchild"; - grandchild.presentationKey = grandchild.id; - child.children.push_back(grandchild); - row.children.push_back(child); - snapshot.roots.push_back(row); - const std::array cases{ - std::pair{nodegraph::NodeStatus::Running, UiStyle::statusActive}, - std::pair{nodegraph::NodeStatus::Completed, UiStyle::statusSuccess}, - std::pair{nodegraph::NodeStatus::Connected, UiStyle::statusSuccess}, - std::pair{nodegraph::NodeStatus::Interrupted, UiStyle::statusWarning}, - std::pair{nodegraph::NodeStatus::Failed, UiStyle::statusDanger}, - std::pair{nodegraph::NodeStatus::Disconnected, UiStyle::statusDanger}}; - bool passed = true; - for (const auto &[status, color] : cases) { - snapshot.roots.front().status = status; - pane.refresh(snapshot); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *item = tree ? tree->topLevelItem(0) : nullptr; - if (item) { - item->setExpanded(false); - } - QApplication::processEvents(); - const QRect rect = item ? tree->visualItemRect(item) : QRect{}; - const QColor actual = - rect.isValid() - ? logicalPixel(tree->viewport()->grab().toImage(), - QPoint(rect.left() + 14, rect.center().y())) - : QColor{}; - const QColor chevron = - rect.isValid() - ? logicalPixel(tree->viewport()->grab().toImage(), - QPoint(rect.left() - 1, rect.center().y())) - : QColor{}; - passed &= require( - item && colorDistance(actual, QColor(QString::fromLatin1(color))) <= 6, - "thread delegate bypassed the canonical status tone"); - passed &= - require(item && colorDistance(chevron, QColor(QString::fromLatin1( - UiStyle::secondary))) <= 30, - "thread disclosure drifted from the status indicator"); - } - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *item = tree ? tree->topLevelItem(0) : nullptr; - const QRect rect = item ? tree->visualItemRect(item) : QRect{}; - const QPoint disclosureEdge(rect.left(), rect.center().y()); - const QColor edgePixel = - rect.isValid() - ? logicalPixel(tree->viewport()->grab().toImage(), disclosureEdge) - : QColor{}; - passed &= require( - item && !item->isExpanded() && - colorDistance(edgePixel, - QColor(QString::fromLatin1(UiStyle::panel))) > 50, - "disclosure mouse fixture did not target a visible chevron pixel"); - if (tree && item) { - click(tree->viewport(), QPoint(rect.left() - 12, rect.center().y())); - passed &= require(!item->isExpanded(), - "mouse disclosure target extended before its legacy " - "leading edge"); - click(tree->viewport(), QPoint(rect.left() - 11, rect.center().y())); - passed &= require(item->isExpanded(), - "mouse disclosure target omitted its legacy leading " - "edge"); - click(tree->viewport(), QPoint(rect.left() + 13, rect.center().y())); - passed &= require(item->isExpanded(), - "mouse disclosure target extended after its legacy " - "trailing edge"); - click(tree->viewport(), QPoint(rect.left() + 12, rect.center().y())); - passed &= require(!item->isExpanded(), - "mouse disclosure target omitted its legacy trailing " - "edge"); - click(tree->viewport(), QPoint(rect.left(), rect.top() + 7)); - passed &= require(!item->isExpanded(), - "mouse disclosure target extended above its legacy " - "leading edge"); - click(tree->viewport(), QPoint(rect.left(), rect.top() + 8)); - passed &= require(item->isExpanded(), - "mouse disclosure target omitted its legacy top edge"); - click(tree->viewport(), QPoint(rect.left(), rect.bottom() - 7)); - passed &= require(item->isExpanded(), - "mouse disclosure target extended below its legacy " - "trailing edge"); - click(tree->viewport(), QPoint(rect.left(), rect.bottom() - 8)); - passed &= require(!item->isExpanded(), - "mouse disclosure target omitted its legacy bottom edge"); - click(tree->viewport(), disclosureEdge); - QTreeWidgetItem *nested = item->child(0); - nested->setExpanded(false); - QApplication::processEvents(); - const QRect nestedRect = tree->visualItemRect(nested); - click(tree->viewport(), - QPoint(nestedRect.left() - 11, nestedRect.center().y())); - passed &= require(nested && nested->isExpanded(), - "nested disclosure did not share the native target"); - click(tree->viewport(), - QPoint(nestedRect.left() + 12, nestedRect.center().y())); - passed &= require(!nested->isExpanded(), - "nested disclosure trailing edge did not collapse"); - } - return passed; -} - -bool rowDotUsesColor(QTreeWidget *tree, QTreeWidgetItem *item, - const QColor &expected) { - if (!tree || !item) - return false; - QRect rect = tree->visualItemRect(item); - if (item->childCount() > 0) { - const QRect child = tree->visualItemRect(item->child(0)); - if (child.isValid() && rect.contains(child.center())) { - rect.setTop(rect.top() + UiStyle::projectCardEdgePadding); - rect.setBottom(child.top() - 1); - } - } - return rect.isValid() && - colorDistance( - logicalPixel(tree->viewport()->grab().toImage(), - QPoint(rect.left() + 14, rect.center().y())), - expected) <= 6; -} - -bool uninspectedResultsFollowCompletionAndSelection() { - using namespace nodegraph; - std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-inspection.json"); - const auto fixture = nlohmann::json::parse(input); - NodeGraph graph; - ThreadChannels channels; - WorkerLogic logic(graph, channels); - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.resize(480, 780); - { - auto write = graph.write(); - for (const auto& [key, kind] : std::array{std::pair{"project", NodeKind::Project}, std::pair{"section", NodeKind::ThreadSection}}) { - NodeState state; - state.fields = *valueFromJson(fixture.at(key)).asObject(); - static_cast(write.upsert({kind, fixture.at(key).at("id").get()}, std::move(state))); + return passed; } - for (const auto method : {"project/list", "threadSection/list"}) { - NodeState state; - state.fields = {{"loaded", true}}; - static_cast(write.upsert({NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object())}, std::move(state))); - } - static_cast(write.finish()); - } - for (const auto& thread : fixture.at("threads")) { - static_cast(logic.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", valueFromJson(thread)}}})); - } - NodeRef selected; - int requestSerial = 0; - bool passed = true; - pane.show(); - for (const auto& step : fixture.at("steps")) { - if (step.contains("select")) { + + bool optimisticCreationHandsOneRowToGraphAuthority() { + nodegraph::NodeGraph graph; + nodegraph::NodeRef localTarget; + nodegraph::NodeRef canonicalTarget; { - auto read = graph.tryRead(); - selected = read->find({NodeKind::Thread, step.at("select").get()}); - } - static_cast(logic.inspectThread(selected)); - } else if (step.contains("method")) { - static_cast(logic.apply({DecodedMessageKind::ServerNotification, - step.at("method").get(), - {}, - *valueFromJson(step.at("params")).asObject()})); - } else if (step.contains("history")) { - const ProtocolRequestId id("inspection-history-" + std::to_string(++requestSerial)); - const auto admitted = logic.applyDetailed({DecodedMessageKind::ClientRequest, - "thread/read", - id, - {{"threadId", valueFromJson(step.at("history").at("id"))}, {"includeTurns", true}}}); - static_cast(logic.applyDetailed( - {DecodedMessageKind::ClientResult, "thread/read", id, {{"thread", valueFromJson(step.at("history"))}}, admitted.primary})); - } else { - pane.refresh(*adapter.threads(selected, nullptr, &pane.browserOptions())); - auto* tree = threadTree(pane); - tree->expandAll(); - QApplication::processEvents(); - for (const auto& [id, value] : step.at("expected").items()) { - const auto tone = value.get(); - const QColor expected(tone == "active" ? UiStyle::statusActive - : tone == "indirect" ? UiStyle::statusIndirect - : tone == "uninspected" ? "#ec4899" - : UiStyle::statusSuccess); - auto* item = threadItem(tree, id); - const bool correct = item && rowDotUsesColor(tree, item, expected); - if (!correct) { - std::cerr << "Inspection fixture: " << step.at("label") << " row " << id << " expected " << tone << '\n'; - } - passed &= require(correct, "native indicator violates the shared inspection contract"); - if (tone == "uninspected") { - passed &= require(item && item->toolTip(0).contains("not yet inspected"), - "uninspected results have a readable accessible description"); - } + auto write = graph.write(); + localTarget = write.upsert({nodegraph::NodeKind::Thread, "local-thread:1"}); + canonicalTarget = write.upsert({nodegraph::NodeKind::Thread, "created-thread"}); + static_cast(write.finish()); } - auto* project = threadItem(tree, "ready-project"); - project->setExpanded(false); + AnimationDurationStyle normalMotion(100); + middle::ThreadPane pane; + pane.resize(320, 420); + if (QTreeWidget* tree = threadTree(pane)) + tree->setStyle(&normalMotion); + pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:test", "Chosen name", "/workspace")); + ui::ThreadListSnapshot empty; + empty.selectedThreadId = "draft:new-thread"; + pane.refresh(empty); + pane.show(); QApplication::processEvents(); - const auto tone = step.at("expected").at("ready-project").get(); - const QColor expected(tone == "indirect" ? UiStyle::statusIndirect - : tone == "uninspected" ? "#ec4899" - : UiStyle::statusSuccess); - passed &= require(rowDotUsesColor(tree, project, expected), "collapsed projects preserve descendant result attention"); - } - } - return passed; -} - -bool threadIndicatorsDistinguishDirectAndIndirectActivity() { - using namespace nodegraph; - std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-activity.json"); - const auto cases = nlohmann::json::parse(input); - NodeGraph graph; - ProtocolUpdater updater(graph); - ui::NodeGraphUiAdapter adapter(graph); - middle::ThreadPane pane; - pane.resize(340, 650); - pane.show(); - bool passed = true; - const std::array ids{"indicator-origin", "indicator-fork", "indicator-nested"}; - for (const auto& entry : cases) { - for (std::size_t index = 0; index < ids.size(); ++index) { - nlohmann::json fields{{"id", ids[index]}, {"name", ids[index]}, {"status", {{"type", entry.at("statuses").at(index)}}}}; - if (index != 0) { - fields["forkedFromId"] = ids[index - 1]; - } - static_cast( - updater.apply({DecodedMessageKind::ServerNotification, "thread/started", {}, {{"thread", valueFromJson(fields)}}})); - } - pane.refresh(*adapter.threads({})); - auto* tree = threadTree(pane); - auto* origin = threadItem(tree, ids[0]); - origin->setExpanded(true); - threadItem(tree, ids[1])->setExpanded(true); - QApplication::processEvents(); - for (std::size_t index = 0; index < ids.size(); ++index) { - const auto tone = entry.at("tones").at(index).get(); - const QColor color(tone == "active" ? UiStyle::statusActive - : tone == "indirect" ? UiStyle::statusIndirect - : tone == "success" ? UiStyle::statusSuccess - : UiStyle::threadInactive); - auto* item = threadItem(tree, ids[index]); - passed &= require(rowDotUsesColor(tree, item, color), "thread indicator violates shared direct/indirect activity contract"); - passed &= require(item->toolTip(0).contains("Indirect activity") == (tone == "indirect"), - "indirect activity must have a readable tooltip and accessible description"); - } - origin->setExpanded(false); - QApplication::processEvents(); - const auto tone = entry.at("tones").at(0).get(); - const QColor color(tone == "active" ? UiStyle::statusActive - : tone == "indirect" ? UiStyle::statusIndirect - : tone == "success" ? UiStyle::statusSuccess - : UiStyle::threadInactive); - passed &= require(rowDotUsesColor(tree, origin, color), "folding must preserve direct/indirect activity indication"); - } - return passed; -} -bool optimisticCreationHandsOneRowToGraphAuthority() { - nodegraph::NodeGraph graph; - nodegraph::NodeRef localTarget; - nodegraph::NodeRef canonicalTarget; - { - auto write = graph.write(); - localTarget = write.upsert({nodegraph::NodeKind::Thread, "local-thread:1"}); - canonicalTarget = - write.upsert({nodegraph::NodeKind::Thread, "created-thread"}); - static_cast(write.finish()); - } - AnimationDurationStyle normalMotion(100); - middle::ThreadPane pane; - pane.resize(320, 420); - if (QTreeWidget *tree = threadTree(pane)) - tree->setStyle(&normalMotion); - pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:test", "Chosen name", "/workspace")); - ui::ThreadListSnapshot empty; - empty.selectedThreadId = "draft:new-thread"; - pane.refresh(empty); - pane.show(); - QApplication::processEvents(); - - QTreeWidget *tree = threadTree(pane); - auto *animation = - pane.findChild(QStringLiteral("optimisticThreadAnimation")); - QTreeWidgetItem *draft = - tree && tree->topLevelItemCount() == 1 ? tree->topLevelItem(0) : nullptr; + QTreeWidget* tree = threadTree(pane); + auto* animation = pane.findChild(QStringLiteral("optimisticThreadAnimation")); + QTreeWidgetItem* draft = tree && tree->topLevelItemCount() == 1 ? tree->topLevelItem(0) : nullptr; #if QT_CONFIG(accessibility) - QAccessibleInterface *draftAccessible = threadAccessible(tree, draft); - const QAccessible::Id draftAccessibleId = - draftAccessible ? QAccessible::uniqueId(draftAccessible) : 0; - tests::AccessibilityEventProbe events; + QAccessibleInterface* draftAccessible = threadAccessible(tree, draft); + const QAccessible::Id draftAccessibleId = draftAccessible ? QAccessible::uniqueId(draftAccessible) : 0; + tests::AccessibilityEventProbe events; #endif - const QColor orange(QString::fromLatin1(UiStyle::statusWarning)); - if (!require(draft && animation && animation->isActive(), - "dialog Continue did not immediately animate its draft row") || - !require(rowDotUsesColor(tree, draft, orange), - "the initial optimistic row is not orange")) - return false; - - ui::ThreadListSnapshot admitted; - admitted.selectedThreadId = "local-thread:1"; - ui::ThreadListRow canonical; - canonical.id = "local-thread:1"; - canonical.presentationKey = "creation:test"; - canonical.target = localTarget; - canonical.title = "Chosen name"; - canonical.status = nodegraph::NodeStatus::Running; - canonical.awaitingPromptConversation = true; - canonical.pendingPromptAdmittedAtMs = - QDateTime::currentMSecsSinceEpoch() - 1500; - admitted.roots.push_back(canonical); + const QColor orange(QString::fromLatin1(UiStyle::statusWarning)); + if (!require(draft && animation && animation->isActive(), "dialog Continue did not immediately animate its draft row") || + !require(rowDotUsesColor(tree, draft, orange), "the initial optimistic row is not orange")) + return false; + + ui::ThreadListSnapshot admitted; + admitted.selectedThreadId = "local-thread:1"; + ui::ThreadListRow canonical; + canonical.id = "local-thread:1"; + canonical.presentationKey = "creation:test"; + canonical.target = localTarget; + canonical.title = "Chosen name"; + canonical.status = nodegraph::NodeStatus::Running; + canonical.awaitingPromptConversation = true; + canonical.pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; + admitted.roots.push_back(canonical); #if QT_CONFIG(accessibility) - events.clear(); + events.clear(); #endif - pane.refresh(admitted); - QApplication::processEvents(); - QTreeWidgetItem *promoted = tree->topLevelItem(0); - const QColor blue(QString::fromLatin1(UiStyle::statusActive)); - if (!require(promoted == draft && animation->isActive(), - "graph admission replaced or stopped the draft row") || - !require(promoted->data(0, Qt::UserRole).toString() == - QStringLiteral("local-thread:1"), - "graph admission did not update the row's action identity") || - !require(rowDotUsesColor(tree, promoted, blue), - "graph admission did not take ownership of pending feedback")) - return false; + pane.refresh(admitted); + QApplication::processEvents(); + QTreeWidgetItem* promoted = tree->topLevelItem(0); + const QColor blue(QString::fromLatin1(UiStyle::statusActive)); + if (!require(promoted == draft && animation->isActive(), "graph admission replaced or stopped the draft row") || + !require(promoted->data(0, Qt::UserRole).toString() == QStringLiteral("local-thread:1"), + "graph admission did not update the row's action identity") || + !require(rowDotUsesColor(tree, promoted, blue), "graph admission did not take ownership of pending feedback")) + return false; #if QT_CONFIG(accessibility) - if (!require(QAccessible::accessibleInterface(draftAccessibleId) == - draftAccessible && - events.events(draftAccessibleId, QAccessible::SelectionAdd) - .isEmpty() && - events.events(draftAccessibleId, - QAccessible::SelectionRemove) - .isEmpty() && - events.events(draftAccessibleId, QAccessible::Focus) - .isEmpty(), - "optimistic admission replaced or refocused its semantic item")) - return false; - events.clear(); + if (!require(QAccessible::accessibleInterface(draftAccessibleId) == draftAccessible && + events.events(draftAccessibleId, QAccessible::SelectionAdd).isEmpty() && + events.events(draftAccessibleId, QAccessible::SelectionRemove).isEmpty() && + events.events(draftAccessibleId, QAccessible::Focus).isEmpty(), + "optimistic admission replaced or refocused its semantic item")) + return false; + events.clear(); #endif - admitted.selectedThreadId = "created-thread"; - admitted.roots.front().id = "created-thread"; - admitted.roots.front().target = canonicalTarget; - pane.refresh(admitted); - QApplication::processEvents(); - if (!require(tree->topLevelItem(0) == draft && - draft->data(0, Qt::UserRole).toString() == - QStringLiteral("created-thread"), - "canonical attachment replaced the graph-owned row")) - return false; + admitted.selectedThreadId = "created-thread"; + admitted.roots.front().id = "created-thread"; + admitted.roots.front().target = canonicalTarget; + pane.refresh(admitted); + QApplication::processEvents(); + if (!require(tree->topLevelItem(0) == draft && draft->data(0, Qt::UserRole).toString() == QStringLiteral("created-thread"), + "canonical attachment replaced the graph-owned row")) + return false; #if QT_CONFIG(accessibility) - if (!require(QAccessible::accessibleInterface(draftAccessibleId) == - draftAccessible && - events.events(draftAccessibleId, QAccessible::SelectionAdd) - .isEmpty() && - events.events(draftAccessibleId, - QAccessible::SelectionRemove) - .isEmpty() && - events.events(draftAccessibleId, QAccessible::Focus) - .isEmpty(), - "canonical promotion replaced or refocused its semantic item")) - return false; + if (!require(QAccessible::accessibleInterface(draftAccessibleId) == draftAccessible && + events.events(draftAccessibleId, QAccessible::SelectionAdd).isEmpty() && + events.events(draftAccessibleId, QAccessible::SelectionRemove).isEmpty() && + events.events(draftAccessibleId, QAccessible::Focus).isEmpty(), + "canonical promotion replaced or refocused its semantic item")) + return false; #endif - admitted.roots.front().awaitingPromptConversation = false; - admitted.roots.front().pendingPromptAdmittedAtMs.reset(); - pane.refresh(admitted); - QApplication::processEvents(); - return require(tree->topLevelItem(0) == draft && !animation->isActive(), - "authoritative acknowledgement did not end the same row's " - "pending animation") && - require(!rowDotUsesColor(tree, draft, orange), - "acknowledged thread row did not return to its native color"); -} + admitted.roots.front().awaitingPromptConversation = false; + admitted.roots.front().pendingPromptAdmittedAtMs.reset(); + pane.refresh(admitted); + QApplication::processEvents(); + return require(tree->topLevelItem(0) == draft && !animation->isActive(), + "authoritative acknowledgement did not end the same row's " + "pending animation") && + require(!rowDotUsesColor(tree, draft, orange), "acknowledged thread row did not return to its native color"); + } -bool optimisticDiscardRetiresAuthorityBeforeSelectionReentry() { - nodegraph::NodeGraph graph; - nodegraph::NodeRef existingTarget; - { - auto write = graph.write(); - existingTarget = - write.upsert({nodegraph::NodeKind::Thread, "existing-thread"}); - static_cast(write.finish()); - } - - middle::ThreadPane pane; - ui::ThreadListSnapshot snapshot; - snapshot.selectedThreadId = "existing-thread"; - ui::ThreadListRow existing; - existing.id = "existing-thread"; - existing.presentationKey = existing.id; - existing.target = existingTarget; - snapshot.roots.push_back(existing); - pane.refresh(snapshot); - - int selections = 0; - middle::ThreadPane::Actions actions; - actions.select = [&](const nodegraph::NodeRef &target) { - if (target != existingTarget) - return; - ++selections; - pane.discardOptimisticThread("draft:new-thread"); - }; - pane.setActions(std::move(actions)); - pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:first", "First", "/workspace")); - pane.show(); - QApplication::processEvents(); - - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *existingItem = threadItem(tree, "existing-thread"); - if (!require(tree && existingItem, - "reentrant draft-retirement fixture lacks its real row")) - return false; - tree->setCurrentItem(existingItem); - QApplication::processEvents(); - if (!require(selections == 1 && !threadItem(tree, "draft:new-thread") && - tree->currentItem() == existingItem && - existingItem->isSelected(), - "draft retirement repeated or disturbed the user selection")) - return false; - - pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:second", "Second", "/workspace")); - QApplication::processEvents(); - return require(threadItem(tree, "draft:new-thread") == tree->currentItem(), - "draft retirement prevented a later creation from starting"); -} + bool optimisticDiscardRetiresAuthorityBeforeSelectionReentry() { + nodegraph::NodeGraph graph; + nodegraph::NodeRef existingTarget; + { + auto write = graph.write(); + existingTarget = write.upsert({nodegraph::NodeKind::Thread, "existing-thread"}); + static_cast(write.finish()); + } -bool pagingFollowsTheVisibleListEnd() { - middle::ThreadPane shortPane; - shortPane.resize(300, 500); - int shortPageRequests = 0; - middle::ThreadPane::Actions shortActions; - shortActions.loadMore = [&] { ++shortPageRequests; }; - shortPane.setActions(std::move(shortActions)); - ui::ThreadListSnapshot shortSnapshot; - for (int index = 0; index < 2; ++index) { - ui::ThreadListRow row; - row.id = "short-" + std::to_string(index); - row.presentationKey = row.id; - shortSnapshot.roots.push_back(std::move(row)); - } - shortPane.refresh(shortSnapshot); - shortPane.show(); - QApplication::processEvents(); - if (!require(shortPageRequests == 1, - "an initially short thread page did not request more rows")) - return false; - shortPageRequests = 0; - ui::ThreadListRow appended; - appended.id = "short-2"; - appended.presentationKey = appended.id; - shortSnapshot.roots.push_back(std::move(appended)); - shortPane.refresh(shortSnapshot); - QApplication::processEvents(); - if (!require(shortPageRequests == 1, - "a still-short appended page did not continue pagination")) - return false; - - middle::ThreadPane pane; - pane.resize(300, 500); - int loadMoreRequests = 0; - middle::ThreadPane::Actions actions; - actions.loadMore = [&] { ++loadMoreRequests; }; - pane.setActions(std::move(actions)); - - ui::ThreadListSnapshot longSnapshot; - for (int index = 0; index < 80; ++index) { - ui::ThreadListRow row; - row.id = "long-" + std::to_string(index); - row.presentationKey = row.id; - row.title = row.id; - row.recencyAt = 1000 - index; - longSnapshot.roots.push_back(std::move(row)); - } - pane.refresh(longSnapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - if (!require(tree && tree->verticalScrollBar()->maximum() > 0, - "long thread page did not produce a scroll range")) - return false; - loadMoreRequests = 0; - tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); - QApplication::processEvents(); - if (!require(loadMoreRequests == 1, - "scrolling to the visible list end did not request exactly one " - "thread page")) - return false; - loadMoreRequests = 0; - ui::ThreadListRow newest; - newest.id = "long-newest"; - newest.presentationKey = newest.id; - newest.title = newest.id; - newest.recencyAt = 2000; - longSnapshot.roots.push_back(std::move(newest)); - pane.refresh(longSnapshot); - QApplication::processEvents(); - if (!require(loadMoreRequests == 0 && - tree->verticalScrollBar()->value() == 0, - "a new most-recent thread was hidden or requested older history")) - return false; - tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); - QApplication::processEvents(); - loadMoreRequests = 0; - appended.id = appended.presentationKey = appended.title = "long-older"; - appended.recencyAt = 500; - longSnapshot.roots.push_back(std::move(appended)); - pane.refresh(longSnapshot); - QApplication::processEvents(); - return require(loadMoreRequests == 1, - "anchor restoration requested the next thread page more than " - "once"); -} + middle::ThreadPane pane; + ui::ThreadListSnapshot snapshot; + snapshot.selectedThreadId = "existing-thread"; + ui::ThreadListRow existing; + existing.id = "existing-thread"; + existing.presentationKey = existing.id; + existing.target = existingTarget; + snapshot.roots.push_back(existing); + pane.refresh(snapshot); -bool structuralInsertionPreservesTheViewportAnchor() { - middle::ThreadPane pane; - pane.resize(300, 500); - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); - ui::ThreadListSnapshot snapshot; - for (int index = 0; index < 100; ++index) { - ui::ThreadListRow row; - row.id = "b-" + std::to_string(index); - row.presentationKey = row.id; - row.title = "B " + std::to_string(index); - snapshot.roots.push_back(std::move(row)); - } - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *anchor = threadItem(tree, "b-50"); - if (!require(tree && anchor && tree->verticalScrollBar()->maximum() > 0, - "anchor fixture did not produce a scrollable tree")) - return false; - tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); - QApplication::processEvents(); - const QPoint probe(tree->viewport()->width() / 2, 0); - const QModelIndex before = tree->indexAt(probe); - const QString beforeId = before.data(Qt::UserRole).toString(); - const int beforeY = tree->visualRect(before).top(); - const int beforeScroll = tree->verticalScrollBar()->value(); - - for (int index = 0; index < 10; ++index) { - ui::ThreadListRow row; - row.id = "a-" + std::to_string(index); - row.presentationKey = row.id; - row.title = "A " + std::to_string(index); - snapshot.roots.push_back(std::move(row)); - } - pane.refresh(snapshot); - QApplication::processEvents(); - const QModelIndex after = tree->indexAt(probe); - return require(beforeId == QStringLiteral("b-50") && - after.data(Qt::UserRole).toString() == beforeId && - tree->visualRect(after).top() == beforeY && - tree->verticalScrollBar()->value() > beforeScroll, - "structural insertion moved the stable viewport anchor"); -} + int selections = 0; + middle::ThreadPane::Actions actions; + actions.select = [&](const nodegraph::NodeRef& target) { + if (target != existingTarget) + return; + ++selections; + pane.discardOptimisticThread("draft:new-thread"); + }; + pane.setActions(std::move(actions)); + pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:first", "First", "/workspace")); + pane.show(); + QApplication::processEvents(); -bool authoritativeSelectionWinsOverThePriorViewportAnchor() { - middle::ThreadPane pane; - pane.resize(300, 500); - pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); - ui::ThreadListSnapshot snapshot; - snapshot.selectedThreadId = "b-50"; - for (int index = 0; index < 100; ++index) { - ui::ThreadListRow row; - row.id = "b-" + std::to_string(index); - row.presentationKey = row.id; - row.title = "B " + std::to_string(index); - snapshot.roots.push_back(std::move(row)); - } - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *anchor = threadItem(tree, "b-50"); - QTreeWidgetItem *nextSelection = threadItem(tree, "b-99"); - if (!require(tree && anchor && nextSelection, - "selection-priority fixture did not populate the tree")) - return false; - tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); - QApplication::processEvents(); - for (int index = 0; index < 10; ++index) { - ui::ThreadListRow row; - row.id = "a-" + std::to_string(index); - row.presentationKey = row.id; - row.title = "A " + std::to_string(index); - snapshot.roots.push_back(std::move(row)); - } - snapshot.selectedThreadId = "b-99"; - pane.refresh(snapshot); - QApplication::processEvents(); - return require(tree->currentItem() == nextSelection && - nextSelection->isSelected() && - tree->visualItemRect(nextSelection) - .intersects(tree->viewport()->rect()), - "the prior viewport anchor hid the new authoritative " - "selection"); -} + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* existingItem = threadItem(tree, "existing-thread"); + if (!require(tree && existingItem, "reentrant draft-retirement fixture lacks its real row")) + return false; + tree->setCurrentItem(existingItem); + QApplication::processEvents(); + if (!require(selections == 1 && !threadItem(tree, "draft:new-thread") && tree->currentItem() == existingItem && + existingItem->isSelected(), + "draft retirement repeated or disturbed the user selection")) + return false; -bool retainedSelectionRemainsVisibleAfterReparenting() { - ui::ThreadListRow moving; - moving.id = "moving"; - moving.presentationKey = moving.id; - moving.title = "Moving"; - ui::ThreadListRow parent; - parent.id = "parent"; - parent.presentationKey = parent.id; - parent.title = "Parent"; - ui::ThreadListSnapshot snapshot; - snapshot.selectedThreadId = moving.id; - snapshot.roots = {moving, parent}; - middle::ThreadPane pane; - pane.resize(300, 500); - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *movingItem = threadItem(tree, moving.id); - if (!require(tree && movingItem && tree->currentItem() == movingItem, - "reparenting fixture did not select the original row")) - return false; - - snapshot.selectedThreadId.clear(); - parent.children.push_back(moving); - snapshot.roots = {parent}; - pane.refresh(snapshot); - QApplication::processEvents(); - QTreeWidgetItem *parentItem = threadItem(tree, parent.id); - return require( - threadItem(tree, moving.id) == movingItem && parentItem && - movingItem->parent() == parentItem && parentItem->isExpanded() && - tree->currentItem() == movingItem && - tree->visualItemRect(movingItem).intersects(tree->viewport()->rect()), - "reparenting hid or replaced the retained current thread"); -} + pane.beginOptimisticThread(localDraft("draft:new-thread", "creation:second", "Second", "/workspace")); + QApplication::processEvents(); + return require(threadItem(tree, "draft:new-thread") == tree->currentItem(), + "draft retirement prevented a later creation from starting"); + } -bool incrementalRootSortPreservesTheViewportAnchor() { - nodegraph::NodeGraph graph; - nodegraph::NodeRef selected; - { - auto write = graph.write(); - const nodegraph::NodeRef runtime = - write.upsert({nodegraph::NodeKind::Runtime, "sort-runtime"}); - for (int index = 0; index < 100; ++index) { - const std::string id = "sort-" + std::to_string(index); - nodegraph::NodeState state; - state.fields.emplace("name", "Sort " + std::to_string(index)); - state.fields.emplace("recencyAt", static_cast(index)); - const nodegraph::NodeRef thread = - write.upsert({nodegraph::NodeKind::Thread, id}, std::move(state)); - write.relate(runtime, nodegraph::RelationKind::RootThread, thread); - if (index == 50) - selected = thread; - } - static_cast(write.finish()); - } - ui::NodeGraphUiAdapter adapter(graph); - const auto snapshot = adapter.threads(selected); - middle::ThreadPane pane; - pane.resize(300, 500); - if (!require(snapshot && snapshot->roots.size() == 100, - "incremental-sort fixture did not project every thread")) - return false; - pane.refresh(*snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *anchor = threadItem(tree, "sort-50"); - if (!require(tree && anchor, - "incremental-sort fixture did not retain its selected row")) - return false; - tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); - QApplication::processEvents(); - const QPoint probe(tree->viewport()->width() / 2, 0); - const QModelIndex before = tree->indexAt(probe); - const QString beforeId = before.data(Qt::UserRole).toString(); - const int beforeY = tree->visualRect(before).top(); - const auto promoted = std::ranges::find( - snapshot->roots, std::string("sort-0"), &ui::ThreadListRow::id); - if (!require(promoted != snapshot->roots.end(), - "incremental-sort fixture omitted the promoted row")) - return false; - ui::ThreadListRow row = *promoted; - row.recencyAt = 75; - if (!require(pane.applyRowPresentation(row), - "incremental root presentation update was rejected")) - return false; - QApplication::processEvents(); - const QModelIndex after = tree->indexAt(probe); - bool passed = require(beforeId == QStringLiteral("sort-50") && - after.data(Qt::UserRole).toString() == beforeId && - tree->visualRect(after).top() == beforeY, - "incremental root sorting moved the stable viewport anchor"); - row.recencyAt = 99; - passed &= require(pane.applyRowPresentation(row), "tied recency was rejected"); - QApplication::processEvents(); - passed &= require(tree->indexAt(probe).data(Qt::UserRole).toString() == beforeId, - "a recency tie stole the viewport"); - row.recencyAt = 75; - passed &= require(pane.applyRowPresentation(row), "recency demotion was rejected"); - row.recencyAt = 1000; - passed &= require(pane.applyRowPresentation(row), - "most-recent incremental update was rejected"); - QApplication::processEvents(); - passed &= require(tree->topLevelItem(0) == threadItem(tree, row.id) && - tree->verticalScrollBar()->value() == 0, - "incremental promotion hid the new most-recent thread"); - return passed; -} + bool pagingFollowsTheVisibleListEnd() { + middle::ThreadPane shortPane; + shortPane.resize(300, 500); + int shortPageRequests = 0; + middle::ThreadPane::Actions shortActions; + shortActions.loadMore = [&] { + ++shortPageRequests; + }; + shortPane.setActions(std::move(shortActions)); + ui::ThreadListSnapshot shortSnapshot; + for (int index = 0; index < 2; ++index) { + ui::ThreadListRow row; + row.id = "short-" + std::to_string(index); + row.presentationKey = row.id; + shortSnapshot.roots.push_back(std::move(row)); + } + shortPane.refresh(shortSnapshot); + shortPane.show(); + QApplication::processEvents(); + if (!require(shortPageRequests == 1, "an initially short thread page did not request more rows")) + return false; + shortPageRequests = 0; + ui::ThreadListRow appended; + appended.id = "short-2"; + appended.presentationKey = appended.id; + shortSnapshot.roots.push_back(std::move(appended)); + shortPane.refresh(shortSnapshot); + QApplication::processEvents(); + if (!require(shortPageRequests == 1, "a still-short appended page did not continue pagination")) + return false; + + middle::ThreadPane pane; + pane.resize(300, 500); + int loadMoreRequests = 0; + middle::ThreadPane::Actions actions; + actions.loadMore = [&] { + ++loadMoreRequests; + }; + pane.setActions(std::move(actions)); + + ui::ThreadListSnapshot longSnapshot; + for (int index = 0; index < 80; ++index) { + ui::ThreadListRow row; + row.id = "long-" + std::to_string(index); + row.presentationKey = row.id; + row.title = row.id; + row.recencyAt = 1000 - index; + longSnapshot.roots.push_back(std::move(row)); + } + pane.refresh(longSnapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + if (!require(tree && tree->verticalScrollBar()->maximum() > 0, "long thread page did not produce a scroll range")) + return false; + loadMoreRequests = 0; + tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); + QApplication::processEvents(); + if (!require(loadMoreRequests == 1, + "scrolling to the visible list end did not request exactly one " + "thread page")) + return false; + loadMoreRequests = 0; + ui::ThreadListRow newest; + newest.id = "long-newest"; + newest.presentationKey = newest.id; + newest.title = newest.id; + newest.recencyAt = 2000; + longSnapshot.roots.push_back(std::move(newest)); + pane.refresh(longSnapshot); + QApplication::processEvents(); + if (!require(loadMoreRequests == 0 && tree->verticalScrollBar()->value() == 0, + "a new most-recent thread was hidden or requested older history")) + return false; + tree->verticalScrollBar()->setValue(tree->verticalScrollBar()->maximum()); + QApplication::processEvents(); + loadMoreRequests = 0; + appended.id = appended.presentationKey = appended.title = "long-older"; + appended.recencyAt = 500; + longSnapshot.roots.push_back(std::move(appended)); + pane.refresh(longSnapshot); + QApplication::processEvents(); + return require(loadMoreRequests == 1, + "anchor restoration requested the next thread page more than " + "once"); + } -bool newestThreadPromotionRevealsOnce() { - bool passed = true; - for (const bool incremental : {false, true}) { - for (const bool startAtTop : {false, true}) { - nodegraph::NodeGraph graph; - ui::ThreadListSnapshot snapshot; - { - auto write = graph.write(); - for (int index = 0; index < 100; ++index) { - ui::ThreadListRow row; - row.id = row.presentationKey = row.title = std::to_string(index); - row.recencyAt = 100 - index; - row.target = write.upsert({nodegraph::NodeKind::Thread, row.id}); - snapshot.roots.push_back(std::move(row)); + bool structuralInsertionPreservesTheViewportAnchor() { + middle::ThreadPane pane; + pane.resize(300, 500); + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); + ui::ThreadListSnapshot snapshot; + for (int index = 0; index < 100; ++index) { + ui::ThreadListRow row; + row.id = "b-" + std::to_string(index); + row.presentationKey = row.id; + row.title = "B " + std::to_string(index); + snapshot.roots.push_back(std::move(row)); + } + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* anchor = threadItem(tree, "b-50"); + if (!require(tree && anchor && tree->verticalScrollBar()->maximum() > 0, "anchor fixture did not produce a scrollable tree")) + return false; + tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); + QApplication::processEvents(); + const QPoint probe(tree->viewport()->width() / 2, 0); + const QModelIndex before = tree->indexAt(probe); + const QString beforeId = before.data(Qt::UserRole).toString(); + const int beforeY = tree->visualRect(before).top(); + const int beforeScroll = tree->verticalScrollBar()->value(); + + for (int index = 0; index < 10; ++index) { + ui::ThreadListRow row; + row.id = "a-" + std::to_string(index); + row.presentationKey = row.id; + row.title = "A " + std::to_string(index); + snapshot.roots.push_back(std::move(row)); + } + pane.refresh(snapshot); + QApplication::processEvents(); + const QModelIndex after = tree->indexAt(probe); + return require(beforeId == QStringLiteral("b-50") && after.data(Qt::UserRole).toString() == beforeId && + tree->visualRect(after).top() == beforeY && tree->verticalScrollBar()->value() > beforeScroll, + "structural insertion moved the stable viewport anchor"); } - static_cast(write.finish()); - } - snapshot.selectedThreadId = "50"; - middle::ThreadPane pane; - pane.resize(300, 500); - pane.refresh(snapshot); - pane.show(); - QApplication::processEvents(); - QTreeWidget *tree = threadTree(pane); - QTreeWidgetItem *promoted = threadItem(tree, "50"); - if (!require(tree && promoted, "promotion fixture is missing its thread")) - return false; - tree->scrollToItem(startAtTop ? tree->topLevelItem(0) : promoted, - QAbstractItemView::PositionAtTop); - QApplication::processEvents(); - auto &row = snapshot.roots[50]; - const auto apply = [&] { - if (incremental) - passed &= require(pane.applyRowPresentation(row), - "prompt promotion update was rejected"); - else - pane.refresh(snapshot); - QApplication::processEvents(); - }; - row.recencyAt = 1000; - apply(); - passed &= require(tree->topLevelItem(0) == promoted && - tree->visualItemRect(promoted).top() == 0 && - tree->verticalScrollBar()->value() == 0, - "prompt-promoted thread was left above the viewport"); - tree->scrollToItem(threadItem(tree, "70"), QAbstractItemView::PositionAtTop); - QApplication::processEvents(); - const int detachedScroll = tree->verticalScrollBar()->value(); - row.status = nodegraph::NodeStatus::Running; - apply(); - row.recencyAt = 1001; - apply(); - passed &= require(tree->verticalScrollBar()->value() == detachedScroll, - "already-first thread updates stole the viewport"); - if (!incremental) { - snapshot.selectedThreadId = "70"; - pane.refresh(snapshot); - QApplication::processEvents(); - snapshot.roots.erase(snapshot.roots.begin() + 50); - QTreeWidgetItem *anchor = threadItem(tree, "70"); - const int anchorY = tree->visualItemRect(anchor).top(); - pane.refresh(snapshot); - QApplication::processEvents(); - passed &= require(tree->visualItemRect(anchor).top() == anchorY, - "removing the newest thread stole the viewport"); - } - } - } - return passed; -} -class ViewportPaintProbe final : public QObject { -public: - void reset(QAbstractItemView *nextView, QRect nextAllowed = {}) { - view = nextView; - allowed = nextAllowed; - paints = 0; - bounded = true; - } - - int paints = 0; - bool bounded = true; - -protected: - bool eventFilter(QObject *watched, QEvent *event) override { - if (view && watched == view->viewport() && event->type() == QEvent::Paint) { - ++paints; - if (!allowed.isNull()) { - const QRect dirty = - static_cast(event)->region().boundingRect(); - bounded = bounded && allowed.adjusted(-2, -2, 2, 2).contains(dirty); - } - } - return false; - } - -private: - QPointer view; - QRect allowed; -}; - -void settleThreadPane() { - for (int pass = 0; pass < 4; ++pass) { - QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); - QApplication::processEvents(QEventLoop::AllEvents, 10); - } -} + bool authoritativeSelectionWinsOverThePriorViewportAnchor() { + middle::ThreadPane pane; + pane.resize(300, 500); + pane.setSortCriterion(middle::ThreadPane::SortCriterion::Alphanumeric); + ui::ThreadListSnapshot snapshot; + snapshot.selectedThreadId = "b-50"; + for (int index = 0; index < 100; ++index) { + ui::ThreadListRow row; + row.id = "b-" + std::to_string(index); + row.presentationKey = row.id; + row.title = "B " + std::to_string(index); + snapshot.roots.push_back(std::move(row)); + } + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* anchor = threadItem(tree, "b-50"); + QTreeWidgetItem* nextSelection = threadItem(tree, "b-99"); + if (!require(tree && anchor && nextSelection, "selection-priority fixture did not populate the tree")) + return false; + tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); + QApplication::processEvents(); + for (int index = 0; index < 10; ++index) { + ui::ThreadListRow row; + row.id = "a-" + std::to_string(index); + row.presentationKey = row.id; + row.title = "A " + std::to_string(index); + snapshot.roots.push_back(std::move(row)); + } + snapshot.selectedThreadId = "b-99"; + pane.refresh(snapshot); + QApplication::processEvents(); + return require(tree->currentItem() == nextSelection && nextSelection->isSelected() && + tree->visualItemRect(nextSelection).intersects(tree->viewport()->rect()), + "the prior viewport anchor hid the new authoritative " + "selection"); + } -void waitThreadPane(int milliseconds) { - QEventLoop loop; - QTimer::singleShot(milliseconds, &loop, &QEventLoop::quit); - loop.exec(); - settleThreadPane(); -} + bool retainedSelectionRemainsVisibleAfterReparenting() { + ui::ThreadListRow moving; + moving.id = "moving"; + moving.presentationKey = moving.id; + moving.title = "Moving"; + ui::ThreadListRow parent; + parent.id = "parent"; + parent.presentationKey = parent.id; + parent.title = "Parent"; + ui::ThreadListSnapshot snapshot; + snapshot.selectedThreadId = moving.id; + snapshot.roots = {moving, parent}; + middle::ThreadPane pane; + pane.resize(300, 500); + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* movingItem = threadItem(tree, moving.id); + if (!require(tree && movingItem && tree->currentItem() == movingItem, "reparenting fixture did not select the original row")) + return false; + + snapshot.selectedThreadId.clear(); + parent.children.push_back(moving); + snapshot.roots = {parent}; + pane.refresh(snapshot); + QApplication::processEvents(); + QTreeWidgetItem* parentItem = threadItem(tree, parent.id); + return require(threadItem(tree, moving.id) == movingItem && parentItem && movingItem->parent() == parentItem && + parentItem->isExpanded() && tree->currentItem() == movingItem && + tree->visualItemRect(movingItem).intersects(tree->viewport()->rect()), + "reparenting hid or replaced the retained current thread"); + } -quint64 imageChecksum(const QImage &image) { - quint64 result = 1469598103934665603ULL; - const uchar *bits = image.constBits(); - for (qsizetype offset = 0; offset < image.sizeInBytes(); offset += 97) { - result ^= bits[offset]; - result *= 1099511628211ULL; - } - return result ^ static_cast(image.width()) ^ - (static_cast(image.height()) << 32U); -} + bool incrementalRootSortPreservesTheViewportAnchor() { + nodegraph::NodeGraph graph; + nodegraph::NodeRef selected; + { + auto write = graph.write(); + const nodegraph::NodeRef runtime = write.upsert({nodegraph::NodeKind::Runtime, "sort-runtime"}); + for (int index = 0; index < 100; ++index) { + const std::string id = "sort-" + std::to_string(index); + nodegraph::NodeState state; + state.fields.emplace("name", "Sort " + std::to_string(index)); + state.fields.emplace("recencyAt", static_cast(index)); + const nodegraph::NodeRef thread = write.upsert({nodegraph::NodeKind::Thread, id}, std::move(state)); + write.relate(runtime, nodegraph::RelationKind::RootThread, thread); + if (index == 50) + selected = thread; + } + static_cast(write.finish()); + } + ui::NodeGraphUiAdapter adapter(graph); + const auto snapshot = adapter.threads(selected); + middle::ThreadPane pane; + pane.resize(300, 500); + if (!require(snapshot && snapshot->roots.size() == 100, "incremental-sort fixture did not project every thread")) + return false; + pane.refresh(*snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* anchor = threadItem(tree, "sort-50"); + if (!require(tree && anchor, "incremental-sort fixture did not retain its selected row")) + return false; + tree->scrollToItem(anchor, QAbstractItemView::PositionAtTop); + QApplication::processEvents(); + const QPoint probe(tree->viewport()->width() / 2, 0); + const QModelIndex before = tree->indexAt(probe); + const QString beforeId = before.data(Qt::UserRole).toString(); + const int beforeY = tree->visualRect(before).top(); + const auto promoted = std::ranges::find(snapshot->roots, std::string("sort-0"), &ui::ThreadListRow::id); + if (!require(promoted != snapshot->roots.end(), "incremental-sort fixture omitted the promoted row")) + return false; + ui::ThreadListRow row = *promoted; + row.recencyAt = 75; + if (!require(pane.applyRowPresentation(row), "incremental root presentation update was rejected")) + return false; + QApplication::processEvents(); + const QModelIndex after = tree->indexAt(probe); + bool passed = require(beforeId == QStringLiteral("sort-50") && after.data(Qt::UserRole).toString() == beforeId && + tree->visualRect(after).top() == beforeY, + "incremental root sorting moved the stable viewport anchor"); + row.recencyAt = 99; + passed &= require(pane.applyRowPresentation(row), "tied recency was rejected"); + QApplication::processEvents(); + passed &= require(tree->indexAt(probe).data(Qt::UserRole).toString() == beforeId, "a recency tie stole the viewport"); + row.recencyAt = 75; + passed &= require(pane.applyRowPresentation(row), "recency demotion was rejected"); + row.recencyAt = 1000; + passed &= require(pane.applyRowPresentation(row), "most-recent incremental update was rejected"); + QApplication::processEvents(); + passed &= require(tree->topLevelItem(0) == threadItem(tree, row.id) && tree->verticalScrollBar()->value() == 0, + "incremental promotion hid the new most-recent thread"); + return passed; + } -std::string benchmarkThreadId(std::size_t index) { - std::ostringstream value; - value << "thread-" << std::setw(6) << std::setfill('0') << index; - return value.str(); -} + bool newestThreadPromotionRevealsOnce() { + bool passed = true; + for (const bool incremental : {false, true}) { + for (const bool startAtTop : {false, true}) { + nodegraph::NodeGraph graph; + ui::ThreadListSnapshot snapshot; + { + auto write = graph.write(); + for (int index = 0; index < 100; ++index) { + ui::ThreadListRow row; + row.id = row.presentationKey = row.title = std::to_string(index); + row.recencyAt = 100 - index; + row.target = write.upsert({nodegraph::NodeKind::Thread, row.id}); + snapshot.roots.push_back(std::move(row)); + } + static_cast(write.finish()); + } + snapshot.selectedThreadId = "50"; + middle::ThreadPane pane; + pane.resize(300, 500); + pane.refresh(snapshot); + pane.show(); + QApplication::processEvents(); + QTreeWidget* tree = threadTree(pane); + QTreeWidgetItem* promoted = threadItem(tree, "50"); + if (!require(tree && promoted, "promotion fixture is missing its thread")) + return false; + tree->scrollToItem(startAtTop ? tree->topLevelItem(0) : promoted, QAbstractItemView::PositionAtTop); + QApplication::processEvents(); + auto& row = snapshot.roots[50]; + const auto apply = [&] { + if (incremental) + passed &= require(pane.applyRowPresentation(row), "prompt promotion update was rejected"); + else + pane.refresh(snapshot); + QApplication::processEvents(); + }; + row.recencyAt = 1000; + apply(); + passed &= require(tree->topLevelItem(0) == promoted && tree->visualItemRect(promoted).top() == 0 && + tree->verticalScrollBar()->value() == 0, + "prompt-promoted thread was left above the viewport"); + tree->scrollToItem(threadItem(tree, "70"), QAbstractItemView::PositionAtTop); + QApplication::processEvents(); + const int detachedScroll = tree->verticalScrollBar()->value(); + row.status = nodegraph::NodeStatus::Running; + apply(); + row.recencyAt = 1001; + apply(); + passed &= + require(tree->verticalScrollBar()->value() == detachedScroll, "already-first thread updates stole the viewport"); + if (!incremental) { + snapshot.selectedThreadId = "70"; + pane.refresh(snapshot); + QApplication::processEvents(); + snapshot.roots.erase(snapshot.roots.begin() + 50); + QTreeWidgetItem* anchor = threadItem(tree, "70"); + const int anchorY = tree->visualItemRect(anchor).top(); + pane.refresh(snapshot); + QApplication::processEvents(); + passed &= require(tree->visualItemRect(anchor).top() == anchorY, "removing the newest thread stole the viewport"); + } + } + } + return passed; + } + + class ViewportPaintProbe final : public QObject { + public: + void reset(QAbstractItemView* nextView, QRect nextAllowed = {}) { + view = nextView; + allowed = nextAllowed; + paints = 0; + bounded = true; + } + + int paints = 0; + bool bounded = true; + + protected: + bool eventFilter(QObject* watched, QEvent* event) override { + if (view && watched == view->viewport() && event->type() == QEvent::Paint) { + ++paints; + if (!allowed.isNull()) { + const QRect dirty = static_cast(event)->region().boundingRect(); + bounded = bounded && allowed.adjusted(-2, -2, 2, 2).contains(dirty); + } + } + return false; + } + + private: + QPointer view; + QRect allowed; + }; + + void settleThreadPane() { + for (int pass = 0; pass < 4; ++pass) { + QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + QApplication::processEvents(QEventLoop::AllEvents, 10); + } + } + + void waitThreadPane(int milliseconds) { + QEventLoop loop; + QTimer::singleShot(milliseconds, &loop, &QEventLoop::quit); + loop.exec(); + settleThreadPane(); + } + + quint64 imageChecksum(const QImage& image) { + quint64 result = 1469598103934665603ULL; + const uchar* bits = image.constBits(); + for (qsizetype offset = 0; offset < image.sizeInBytes(); offset += 97) { + result ^= bits[offset]; + result *= 1099511628211ULL; + } + return result ^ static_cast(image.width()) ^ (static_cast(image.height()) << 32U); + } + + std::string benchmarkThreadId(std::size_t index) { + std::ostringstream value; + value << "thread-" << std::setw(6) << std::setfill('0') << index; + return value.str(); + } #if defined(__SANITIZE_ADDRESS__) -constexpr bool InstrumentedBuild = true; + constexpr bool InstrumentedBuild = true; #elif defined(__has_feature) #if __has_feature(address_sanitizer) -constexpr bool InstrumentedBuild = true; + constexpr bool InstrumentedBuild = true; #else -constexpr bool InstrumentedBuild = false; + constexpr bool InstrumentedBuild = false; #endif #else -constexpr bool InstrumentedBuild = false; + constexpr bool InstrumentedBuild = false; #endif -bool threadPerformanceProfile(std::size_t count, qreal expectedDpr, - bool enforceGates, bool grouped = false) { - QStringList failures; - const auto gate = [&failures](bool condition, QString message) { - if (condition) - return; - failures.push_back(std::move(message)); - std::cerr << "THREAD PERFORMANCE GATE FAILED: " - << failures.back().toStdString() << '\n'; - }; - - nodegraph::NodeGraph graph; - nodegraph::NodeRef selected; - nodegraph::NodeRef offscreenThread; - { - auto write = graph.write(); - const nodegraph::NodeRef runtime = - write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); - std::vector projects; - if (grouped) { - for (int i = 0; i != 10; ++i) { - nodegraph::NodeState state; - state.fields.emplace("name", "Project " + std::to_string(i)); - projects.push_back( - write.upsert({nodegraph::NodeKind::Project, std::to_string(i)}, - std::move(state))); - } - for (const auto method : {"project/list", "threadSection/list"}) { - nodegraph::NodeState state; - state.fields.emplace("loaded", true); - static_cast( - write.upsert({nodegraph::NodeKind::Catalog, - threadBrowserKey(method, nlohmann::json::object())}, - std::move(state))); - } - } - for (std::size_t index = 0; index < count; ++index) { - nodegraph::NodeState state; - const std::string id = benchmarkThreadId(index); - state.fields.emplace("name", "Thread " + id); - state.fields.emplace("cwd", "/workspace/" + id); - state.fields.emplace("createdAt", static_cast(index + 1)); - state.fields.emplace("recencyAt", static_cast(index + 1)); - const nodegraph::NodeRef thread = - write.upsert({nodegraph::NodeKind::Thread, id}, std::move(state)); - write.relate(runtime, nodegraph::RelationKind::RootThread, thread); - if (grouped) - write.relate(thread, nodegraph::RelationKind::ProjectMembership, - projects[index % projects.size()]); - offscreenThread = thread; - if (index == count / 2) - selected = thread; - } - static_cast(write.finish()); - } - - ui::NodeGraphUiAdapter adapter(graph); - QElapsedTimer adapterTimer; - adapterTimer.start(); - const ui::ThreadBrowserOptions browser; - const std::optional snapshot = - adapter.threads(selected, nullptr, grouped ? &browser : nullptr); - const qint64 adapterMicros = adapterTimer.nsecsElapsed() / 1000; - const auto countThreads = - [&](const auto &self, - const std::vector &rows) -> std::size_t { - std::size_t total = 0; - for (const auto &row : rows) - total += - (row.kind == ui::ThreadRowKind::Thread) + self(self, row.children); - return total; - }; - gate(snapshot && countThreads(countThreads, snapshot->roots) == count, - QStringLiteral("actual graph projection lost thread rows")); - if (!snapshot) - return false; - - middle::ThreadPane pane; - pane.resize(320, 520); - const int fixedWidgets = pane.findChildren().size(); - const int fixedDocuments = pane.findChildren().size(); - auto *view = - pane.findChild(QStringLiteral("threadList")); - gate(view != nullptr, QStringLiteral("thread item view missing")); - if (!view) - return false; - installAnimationDurationStyle(*view, 100); - - ViewportPaintProbe paints; - qApp->installEventFilter(&paints); - paints.reset(view); - QElapsedTimer populationTimer; - populationTimer.start(); - pane.refresh(*snapshot); - if (grouped) - qobject_cast(view)->expandAll(); - pane.show(); - settleThreadPane(); - const qint64 populationMicros = populationTimer.nsecsElapsed() / 1000; - const qreal actualDpr = pane.devicePixelRatioF(); - const int populatedWidgets = pane.findChildren().size(); - const int documents = pane.findChildren().size(); - const int rootRows = view->model()->rowCount(); - const std::function countIndexWidgets = - [&](const QModelIndex &parent) { - int result = 0; - for (int row = 0; row < view->model()->rowCount(parent); ++row) { - const QModelIndex index = view->model()->index(row, 0, parent); - result += view->indexWidget(index) != nullptr; - result += countIndexWidgets(index); + bool threadPerformanceProfile(std::size_t count, qreal expectedDpr, bool enforceGates, bool grouped = false) { + QStringList failures; + const auto gate = [&failures](bool condition, QString message) { + if (condition) + return; + failures.push_back(std::move(message)); + std::cerr << "THREAD PERFORMANCE GATE FAILED: " << failures.back().toStdString() << '\n'; + }; + + nodegraph::NodeGraph graph; + nodegraph::NodeRef selected; + nodegraph::NodeRef offscreenThread; + { + auto write = graph.write(); + const nodegraph::NodeRef runtime = write.upsert({nodegraph::NodeKind::Runtime, "runtime"}); + std::vector projects; + if (grouped) { + for (int i = 0; i != 10; ++i) { + nodegraph::NodeState state; + state.fields.emplace("name", "Project " + std::to_string(i)); + projects.push_back(write.upsert({nodegraph::NodeKind::Project, std::to_string(i)}, std::move(state))); + } + for (const auto method : {"project/list", "threadSection/list"}) { + nodegraph::NodeState state; + state.fields.emplace("loaded", true); + static_cast(write.upsert({nodegraph::NodeKind::Catalog, threadBrowserKey(method, nlohmann::json::object())}, + std::move(state))); + } + } + for (std::size_t index = 0; index < count; ++index) { + nodegraph::NodeState state; + const std::string id = benchmarkThreadId(index); + state.fields.emplace("name", "Thread " + id); + state.fields.emplace("cwd", "/workspace/" + id); + state.fields.emplace("createdAt", static_cast(index + 1)); + state.fields.emplace("recencyAt", static_cast(index + 1)); + const nodegraph::NodeRef thread = write.upsert({nodegraph::NodeKind::Thread, id}, std::move(state)); + write.relate(runtime, nodegraph::RelationKind::RootThread, thread); + if (grouped) + write.relate(thread, nodegraph::RelationKind::ProjectMembership, projects[index % projects.size()]); + offscreenThread = thread; + if (index == count / 2) + selected = thread; + } + static_cast(write.finish()); + } + + ui::NodeGraphUiAdapter adapter(graph); + QElapsedTimer adapterTimer; + adapterTimer.start(); + const ui::ThreadBrowserOptions browser; + const std::optional snapshot = adapter.threads(selected, nullptr, grouped ? &browser : nullptr); + const qint64 adapterMicros = adapterTimer.nsecsElapsed() / 1000; + const auto countThreads = [&](const auto& self, const std::vector& rows) -> std::size_t { + std::size_t total = 0; + for (const auto& row : rows) + total += (row.kind == ui::ThreadRowKind::Thread) + self(self, row.children); + return total; + }; + gate(snapshot && countThreads(countThreads, snapshot->roots) == count, + QStringLiteral("actual graph projection lost thread rows")); + if (!snapshot) + return false; + + middle::ThreadPane pane; + pane.resize(320, 520); + const int fixedWidgets = pane.findChildren().size(); + const int fixedDocuments = pane.findChildren().size(); + auto* view = pane.findChild(QStringLiteral("threadList")); + gate(view != nullptr, QStringLiteral("thread item view missing")); + if (!view) + return false; + installAnimationDurationStyle(*view, 100); + + ViewportPaintProbe paints; + qApp->installEventFilter(&paints); + paints.reset(view); + QElapsedTimer populationTimer; + populationTimer.start(); + pane.refresh(*snapshot); + if (grouped) + qobject_cast(view)->expandAll(); + pane.show(); + settleThreadPane(); + const qint64 populationMicros = populationTimer.nsecsElapsed() / 1000; + const qreal actualDpr = pane.devicePixelRatioF(); + const int populatedWidgets = pane.findChildren().size(); + const int documents = pane.findChildren().size(); + const int rootRows = view->model()->rowCount(); + const std::function countIndexWidgets = [&](const QModelIndex& parent) { + int result = 0; + for (int row = 0; row < view->model()->rowCount(parent); ++row) { + const QModelIndex index = view->model()->index(row, 0, parent); + result += view->indexWidget(index) != nullptr; + result += countIndexWidgets(index); + } + return result; + }; + const int indexWidgets = countIndexWidgets({}); + + QTreeWidget* tree = qobject_cast(view); + QTreeWidgetItem* selectedItem = tree ? threadItem(tree, snapshot->selectedThreadId) : nullptr; + const QModelIndex selectedIndex = selectedItem ? tree->indexFromItem(selectedItem) : QModelIndex{}; + gate(selectedIndex.isValid(), QStringLiteral("authoritative selection is absent from the tree")); + view->setCurrentIndex(selectedIndex); + view->scrollTo(selectedIndex, QAbstractItemView::PositionAtCenter); + view->setFocus(); + settleThreadPane(); + const int anchorX = view->viewport()->width() / 2; + const QModelIndex anchorBefore = view->indexAt(QPoint(anchorX, 1)); + const QString anchorIdBefore = anchorBefore.data(Qt::UserRole).toString(); + const int anchorYBefore = anchorBefore.isValid() ? view->visualRect(anchorBefore).top() : 0; + const int scrollBefore = view->verticalScrollBar()->value(); + const QPersistentModelIndex persistentSelected(selectedIndex); + const quint64 pixelsBefore = imageChecksum(view->viewport()->grab().toImage()); + + int modelMutations = 0; + const auto mutation = [&modelMutations] { + ++modelMutations; + }; + QObject::connect(view->model(), &QAbstractItemModel::modelReset, &pane, mutation); + QObject::connect(view->model(), &QAbstractItemModel::layoutChanged, &pane, mutation); + QObject::connect(view->model(), &QAbstractItemModel::rowsInserted, &pane, [&modelMutations] { + ++modelMutations; + }); + QObject::connect(view->model(), &QAbstractItemModel::rowsRemoved, &pane, [&modelMutations] { + ++modelMutations; + }); + QObject::connect(view->model(), &QAbstractItemModel::rowsMoved, &pane, [&modelMutations] { + ++modelMutations; + }); + QObject::connect(view->model(), &QAbstractItemModel::dataChanged, &pane, [&modelMutations] { + ++modelMutations; + }); + + paints.reset(view); + QElapsedTimer noOpTimer; + noOpTimer.start(); + pane.refresh(*snapshot); + settleThreadPane(); + const qint64 noOpMicros = noOpTimer.nsecsElapsed() / 1000; + const int noOpPaints = paints.paints; + const QModelIndex anchorAfter = view->indexAt(QPoint(anchorX, 1)); + const bool noOpStable = modelMutations == 0 && persistentSelected.isValid() && persistentSelected == view->currentIndex() && + view->verticalScrollBar()->value() == scrollBefore && + anchorAfter.data(Qt::UserRole).toString() == anchorIdBefore && + (!anchorAfter.isValid() || view->visualRect(anchorAfter).top() == anchorYBefore) && + imageChecksum(view->viewport()->grab().toImage()) == pixelsBefore; + + ui::ThreadListRow offscreen = *adapter.threadRow(offscreenThread); + offscreen.awaitingPromptConversation = true; + offscreen.pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; + paints.reset(view); + const bool offscreenApplied = pane.applyRowPresentation(offscreen); + settleThreadPane(); + paints.reset(view); + waitThreadPane(170); + const int offscreenAnimationPaints = paints.paints; + auto* animation = pane.findChild(QStringLiteral("optimisticThreadAnimation")); + const bool offscreenTimerActive = animation && animation->isActive(); + offscreen.awaitingPromptConversation = false; + offscreen.pendingPromptAdmittedAtMs.reset(); + static_cast(pane.applyRowPresentation(offscreen)); + settleThreadPane(); + + const auto selectedRow = adapter.threadRow(selected); + gate(selectedRow.has_value(), QStringLiteral("selected row is absent from the snapshot")); + ui::ThreadListRow visible = selectedRow.value_or(ui::ThreadListRow{}); + visible.awaitingPromptConversation = true; + visible.pendingPromptAdmittedAtMs = QDateTime::currentMSecsSinceEpoch() - 1500; + QRect visibleRect = view->visualRect(view->currentIndex()); + visibleRect.setLeft(view->viewport()->rect().left()); + visibleRect.setRight(view->viewport()->rect().right()); + const bool visibleApplied = pane.applyRowPresentation(visible); + settleThreadPane(); + QAbstractItemView* visibleView = view; + for (auto* body : pane.findChildren("projectThreadBody")) { + QModelIndex root = view->currentIndex(); + while (root.parent().isValid()) { + root = root.parent(); + } + if (body->rootIndex() == root) { + visibleView = body; + } + } + if (visibleView != view) { + visibleRect = visibleView->visualRect(view->currentIndex()); + visibleRect.setLeft(0); + visibleRect.setWidth(visibleView->viewport()->width()); + } + paints.reset(visibleView, visibleRect); + waitThreadPane(170); + const int visibleAnimationPaints = paints.paints; + const bool visiblePaintsBounded = paints.bounded; + visible.awaitingPromptConversation = false; + visible.pendingPromptAdmittedAtMs.reset(); + static_cast(pane.applyRowPresentation(visible)); + settleThreadPane(); + + std::cout << "THREAD_PROFILE grouped=" << grouped << " rows=" << count << " expected_dpr=" << expectedDpr + << " actual_dpr=" << actualDpr << " adapter_us=" << adapterMicros << " population_us=" << populationMicros + << " fixed_widgets=" << fixedWidgets << " populated_widgets=" << populatedWidgets << " index_widgets=" << indexWidgets + << " documents=" << documents << " no_op_us=" << noOpMicros << " no_op_paints=" << noOpPaints + << " no_op_stable=" << noOpStable << " offscreen_animation_paints=" << offscreenAnimationPaints + << " offscreen_timer_active=" << offscreenTimerActive << " visible_animation_paints=" << visibleAnimationPaints + << " visible_paints_bounded=" << visiblePaintsBounded << '\n'; + + gate(std::abs(actualDpr - expectedDpr) < 0.02, QStringLiteral("actual DPR did not match the requested profile")); + gate(rootRows == static_cast(snapshot->roots.size()), QStringLiteral("thread model cardinality is not exact")); + gate(offscreenApplied && visibleApplied, QStringLiteral("exact row update was rejected")); + if (enforceGates) { + const qint64 scaleAllowance = InstrumentedBuild ? 4 : 1; + gate(indexWidgets == 0, QStringLiteral("thread rows retained index widgets")); + const int projectBodies = pane.findChildren("projectThreadBody").size(); + gate(projectBodies <= 3 && populatedWidgets <= fixedWidgets + 12 * projectBodies + 4, + QStringLiteral("QWidget residency grew with thread count")); + gate(documents == fixedDocuments, QStringLiteral("thread rows retained QTextDocuments")); + gate(noOpStable && noOpPaints == 0, QStringLiteral("semantic no-op changed model, pixels, focus, or anchor")); + gate(codexui::testing::timingLimit(noOpMicros <= 100000 * scaleAllowance), + QStringLiteral("10k semantic no-op exceeded the work budget")); + gate(codexui::testing::timingLimit(adapterMicros <= 500000 * scaleAllowance), + QStringLiteral("thread projection exceeded the quantitative budget")); + gate(codexui::testing::timingLimit(populationMicros <= 2000000 * scaleAllowance), + QStringLiteral("thread population exceeded the quantitative budget")); + gate(!offscreenTimerActive && offscreenAnimationPaints == 0, + QStringLiteral("offscreen animation retained timer or paint work")); + gate(visibleAnimationPaints >= 2 && visibleAnimationPaints <= 8 && visiblePaintsBounded, + QStringLiteral("visible animation did not remain row-local")); + } + qApp->removeEventFilter(&paints); + return failures.isEmpty(); } - return result; - }; - const int indexWidgets = countIndexWidgets({}); - - QTreeWidget *tree = qobject_cast(view); - QTreeWidgetItem *selectedItem = - tree ? threadItem(tree, snapshot->selectedThreadId) : nullptr; - const QModelIndex selectedIndex = - selectedItem ? tree->indexFromItem(selectedItem) : QModelIndex{}; - gate(selectedIndex.isValid(), - QStringLiteral("authoritative selection is absent from the tree")); - view->setCurrentIndex(selectedIndex); - view->scrollTo(selectedIndex, QAbstractItemView::PositionAtCenter); - view->setFocus(); - settleThreadPane(); - const int anchorX = view->viewport()->width() / 2; - const QModelIndex anchorBefore = view->indexAt(QPoint(anchorX, 1)); - const QString anchorIdBefore = anchorBefore.data(Qt::UserRole).toString(); - const int anchorYBefore = - anchorBefore.isValid() ? view->visualRect(anchorBefore).top() : 0; - const int scrollBefore = view->verticalScrollBar()->value(); - const QPersistentModelIndex persistentSelected(selectedIndex); - const quint64 pixelsBefore = - imageChecksum(view->viewport()->grab().toImage()); - - int modelMutations = 0; - const auto mutation = [&modelMutations] { ++modelMutations; }; - QObject::connect(view->model(), &QAbstractItemModel::modelReset, &pane, - mutation); - QObject::connect(view->model(), &QAbstractItemModel::layoutChanged, &pane, - mutation); - QObject::connect(view->model(), &QAbstractItemModel::rowsInserted, &pane, - [&modelMutations] { ++modelMutations; }); - QObject::connect(view->model(), &QAbstractItemModel::rowsRemoved, &pane, - [&modelMutations] { ++modelMutations; }); - QObject::connect(view->model(), &QAbstractItemModel::rowsMoved, &pane, - [&modelMutations] { ++modelMutations; }); - QObject::connect(view->model(), &QAbstractItemModel::dataChanged, &pane, - [&modelMutations] { ++modelMutations; }); - - paints.reset(view); - QElapsedTimer noOpTimer; - noOpTimer.start(); - pane.refresh(*snapshot); - settleThreadPane(); - const qint64 noOpMicros = noOpTimer.nsecsElapsed() / 1000; - const int noOpPaints = paints.paints; - const QModelIndex anchorAfter = view->indexAt(QPoint(anchorX, 1)); - const bool noOpStable = - modelMutations == 0 && persistentSelected.isValid() && - persistentSelected == view->currentIndex() && - view->verticalScrollBar()->value() == scrollBefore && - anchorAfter.data(Qt::UserRole).toString() == anchorIdBefore && - (!anchorAfter.isValid() || - view->visualRect(anchorAfter).top() == anchorYBefore) && - imageChecksum(view->viewport()->grab().toImage()) == pixelsBefore; - - ui::ThreadListRow offscreen = *adapter.threadRow(offscreenThread); - offscreen.awaitingPromptConversation = true; - offscreen.pendingPromptAdmittedAtMs = - QDateTime::currentMSecsSinceEpoch() - 1500; - paints.reset(view); - const bool offscreenApplied = pane.applyRowPresentation(offscreen); - settleThreadPane(); - paints.reset(view); - waitThreadPane(170); - const int offscreenAnimationPaints = paints.paints; - auto *animation = - pane.findChild(QStringLiteral("optimisticThreadAnimation")); - const bool offscreenTimerActive = animation && animation->isActive(); - offscreen.awaitingPromptConversation = false; - offscreen.pendingPromptAdmittedAtMs.reset(); - static_cast(pane.applyRowPresentation(offscreen)); - settleThreadPane(); - - const auto selectedRow = adapter.threadRow(selected); - gate(selectedRow.has_value(), - QStringLiteral("selected row is absent from the snapshot")); - ui::ThreadListRow visible = selectedRow.value_or(ui::ThreadListRow{}); - visible.awaitingPromptConversation = true; - visible.pendingPromptAdmittedAtMs = - QDateTime::currentMSecsSinceEpoch() - 1500; - QRect visibleRect = view->visualRect(view->currentIndex()); - visibleRect.setLeft(view->viewport()->rect().left()); - visibleRect.setRight(view->viewport()->rect().right()); - const bool visibleApplied = pane.applyRowPresentation(visible); - settleThreadPane(); - QAbstractItemView* visibleView = view; - for (auto* body : pane.findChildren("projectThreadBody")) { - QModelIndex root = view->currentIndex(); - while (root.parent().isValid()) { - root = root.parent(); - } - if (body->rootIndex() == root) { - visibleView = body; - } - } - if (visibleView != view) { - visibleRect = visibleView->visualRect(view->currentIndex()); - visibleRect.setLeft(0); - visibleRect.setWidth(visibleView->viewport()->width()); - } - paints.reset(visibleView, visibleRect); - waitThreadPane(170); - const int visibleAnimationPaints = paints.paints; - const bool visiblePaintsBounded = paints.bounded; - visible.awaitingPromptConversation = false; - visible.pendingPromptAdmittedAtMs.reset(); - static_cast(pane.applyRowPresentation(visible)); - settleThreadPane(); - - std::cout << "THREAD_PROFILE grouped=" << grouped << " rows=" << count - << " expected_dpr=" << expectedDpr << " actual_dpr=" << actualDpr - << " adapter_us=" << adapterMicros - << " population_us=" << populationMicros - << " fixed_widgets=" << fixedWidgets - << " populated_widgets=" << populatedWidgets - << " index_widgets=" << indexWidgets << " documents=" << documents - << " no_op_us=" << noOpMicros << " no_op_paints=" << noOpPaints - << " no_op_stable=" << noOpStable - << " offscreen_animation_paints=" << offscreenAnimationPaints - << " offscreen_timer_active=" << offscreenTimerActive - << " visible_animation_paints=" << visibleAnimationPaints - << " visible_paints_bounded=" << visiblePaintsBounded << '\n'; - - gate(std::abs(actualDpr - expectedDpr) < 0.02, - QStringLiteral("actual DPR did not match the requested profile")); - gate(rootRows == static_cast(snapshot->roots.size()), - QStringLiteral("thread model cardinality is not exact")); - gate(offscreenApplied && visibleApplied, - QStringLiteral("exact row update was rejected")); - if (enforceGates) { - const qint64 scaleAllowance = InstrumentedBuild ? 4 : 1; - gate(indexWidgets == 0, - QStringLiteral("thread rows retained index widgets")); - const int projectBodies = pane.findChildren("projectThreadBody").size(); - gate(projectBodies <= 3 && populatedWidgets <= fixedWidgets + 12 * projectBodies + 4, - QStringLiteral("QWidget residency grew with thread count")); - gate(documents == fixedDocuments, - QStringLiteral("thread rows retained QTextDocuments")); - gate(noOpStable && noOpPaints == 0, - QStringLiteral( - "semantic no-op changed model, pixels, focus, or anchor")); - gate(codexui::testing::timingLimit(noOpMicros <= 100000 * scaleAllowance), - QStringLiteral("10k semantic no-op exceeded the work budget")); - gate( - codexui::testing::timingLimit(adapterMicros <= 500000 * scaleAllowance), - QStringLiteral("thread projection exceeded the quantitative budget")); - gate(codexui::testing::timingLimit(populationMicros <= - 2000000 * scaleAllowance), - QStringLiteral("thread population exceeded the quantitative budget")); - gate(!offscreenTimerActive && offscreenAnimationPaints == 0, - QStringLiteral("offscreen animation retained timer or paint work")); - gate(visibleAnimationPaints >= 2 && visibleAnimationPaints <= 8 && - visiblePaintsBounded, - QStringLiteral("visible animation did not remain row-local")); - } - qApp->removeEventFilter(&paints); - return failures.isEmpty(); -} -} // namespace + } // namespace } // namespace codexui::codex -int main(int argc, char **argv) { - QApplication application(argc, argv); - if (const int points = qEnvironmentVariableIntValue("CODEXUI_GROUP_FONT"); points > 0) { - auto font = application.font(); - font.setPointSize(points); - application.setFont(font); - application.setStyleSheet(codexui::UiStyle::applicationStyleSheet()); - } - QTemporaryDir settings; - QSettings::setDefaultFormat(QSettings::IniFormat); - QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, - settings.path()); - if (argc >= 3) { - const std::size_t count = - std::max(1, std::strtoull(argv[1], nullptr, 10)); - const qreal expectedDpr = std::max(0.1, std::strtod(argv[2], nullptr)); - const bool enforceGates = - argc < 4 || std::string_view(argv[3]) != "baseline"; - return codexui::codex::threadPerformanceProfile( - count, expectedDpr, enforceGates, - argc >= 5 && std::string_view(argv[4]) == "grouped") - ? EXIT_SUCCESS - : EXIT_FAILURE; - } - bool passed = true; - const QString expectedDprValue = qEnvironmentVariable("CODEXUI_EXPECTED_DPR"); - if (!expectedDprValue.isEmpty()) { - bool validDpr = false; - const qreal expectedDpr = expectedDprValue.toDouble(&validDpr); - QWidget probe; - probe.show(); - QApplication::processEvents(); - passed &= codexui::codex::require( - validDpr && std::abs(probe.devicePixelRatioF() - expectedDpr) < 0.02, - "ThreadPane visual test did not run at its requested DPR"); - } - passed &= codexui::codex::forkNamesPreserveTheirLineage(); - passed &= codexui::codex::groupLabelsIdentifyDestinationsWithoutRoutineIds(); - passed &= codexui::codex::localDraftsUseOneGroupingProjection(); - passed &= codexui::codex::groupedThreadsPreserveIdentityAndInteractions(); - passed &= codexui::codex::forkHierarchyIgnoresRootReadOrder(); - passed &= codexui::codex::selectedChildRetainsRootAndCanonicalIdentity(); - passed &= codexui::codex::accessibilityFollowsTheNativeHierarchy(); - passed &= codexui::codex::presentationLifetimeFollowsExactThreadIncarnation(); - passed &= codexui::codex::sortingAndPromptAnimationAreFixed(); - passed &= - codexui::codex::reducedMotionStopsThreadFeedbackAtTheStyleBoundary(); - passed &= codexui::codex::projectBodiesCapVisibleRows(); - passed &= codexui::codex::projectDisclosureRestoresCollapsedGeometry(); - passed &= codexui::codex::groupsReportDescendantThreadStatus(); - passed &= codexui::codex::selectedThreadUsesSemanticSurface(); - passed &= codexui::codex::threadDisclosureIsReadyOnFirstPresentation(); - passed &= codexui::codex::threadRowsConsumeCanonicalStatusTone(); - passed &= codexui::codex::threadIndicatorsDistinguishDirectAndIndirectActivity(); - passed &= codexui::codex::uninspectedResultsFollowCompletionAndSelection(); - passed &= codexui::codex::optimisticCreationHandsOneRowToGraphAuthority(); - passed &= - codexui::codex::optimisticDiscardRetiresAuthorityBeforeSelectionReentry(); - passed &= codexui::codex::pagingFollowsTheVisibleListEnd(); - passed &= codexui::codex::structuralInsertionPreservesTheViewportAnchor(); - passed &= - codexui::codex::authoritativeSelectionWinsOverThePriorViewportAnchor(); - passed &= codexui::codex::retainedSelectionRemainsVisibleAfterReparenting(); - passed &= codexui::codex::incrementalRootSortPreservesTheViewportAnchor(); - passed &= codexui::codex::newestThreadPromotionRevealsOnce(); - if (passed) - std::cout << "NodeGraph ThreadPane UI tests passed\n"; - return passed ? EXIT_SUCCESS : EXIT_FAILURE; +int main(int argc, char** argv) { + QApplication application(argc, argv); + if (const int points = qEnvironmentVariableIntValue("CODEXUI_GROUP_FONT"); points > 0) { + auto font = application.font(); + font.setPointSize(points); + application.setFont(font); + application.setStyleSheet(codexui::UiStyle::applicationStyleSheet()); + } + QTemporaryDir settings; + QSettings::setDefaultFormat(QSettings::IniFormat); + QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settings.path()); + if (argc >= 3) { + const std::size_t count = std::max(1, std::strtoull(argv[1], nullptr, 10)); + const qreal expectedDpr = std::max(0.1, std::strtod(argv[2], nullptr)); + const bool enforceGates = argc < 4 || std::string_view(argv[3]) != "baseline"; + return codexui::codex::threadPerformanceProfile( + count, expectedDpr, enforceGates, argc >= 5 && std::string_view(argv[4]) == "grouped") + ? EXIT_SUCCESS + : EXIT_FAILURE; + } + bool passed = true; + const QString expectedDprValue = qEnvironmentVariable("CODEXUI_EXPECTED_DPR"); + if (!expectedDprValue.isEmpty()) { + bool validDpr = false; + const qreal expectedDpr = expectedDprValue.toDouble(&validDpr); + QWidget probe; + probe.show(); + QApplication::processEvents(); + passed &= codexui::codex::require(validDpr && std::abs(probe.devicePixelRatioF() - expectedDpr) < 0.02, + "ThreadPane visual test did not run at its requested DPR"); + } + passed &= codexui::codex::forkNamesPreserveTheirLineage(); + passed &= codexui::codex::groupLabelsIdentifyDestinationsWithoutRoutineIds(); + passed &= codexui::codex::localDraftsUseOneGroupingProjection(); + passed &= codexui::codex::groupedThreadsPreserveIdentityAndInteractions(); + passed &= codexui::codex::forkHierarchyIgnoresRootReadOrder(); + passed &= codexui::codex::selectedChildRetainsRootAndCanonicalIdentity(); + passed &= codexui::codex::accessibilityFollowsTheNativeHierarchy(); + passed &= codexui::codex::presentationLifetimeFollowsExactThreadIncarnation(); + passed &= codexui::codex::sortingAndPromptAnimationAreFixed(); + passed &= codexui::codex::reducedMotionStopsThreadFeedbackAtTheStyleBoundary(); + passed &= codexui::codex::projectBodiesCapVisibleRows(); + passed &= codexui::codex::projectDisclosureRestoresCollapsedGeometry(); + passed &= codexui::codex::groupsReportDescendantThreadStatus(); + passed &= codexui::codex::selectedThreadUsesSemanticSurface(); + passed &= codexui::codex::threadDisclosureIsReadyOnFirstPresentation(); + passed &= codexui::codex::threadRowsConsumeCanonicalStatusTone(); + passed &= codexui::codex::threadIndicatorsDistinguishDirectAndIndirectActivity(); + passed &= codexui::codex::uninspectedResultsFollowCompletionAndSelection(); + passed &= codexui::codex::optimisticCreationHandsOneRowToGraphAuthority(); + passed &= codexui::codex::optimisticDiscardRetiresAuthorityBeforeSelectionReentry(); + passed &= codexui::codex::pagingFollowsTheVisibleListEnd(); + passed &= codexui::codex::structuralInsertionPreservesTheViewportAnchor(); + passed &= codexui::codex::authoritativeSelectionWinsOverThePriorViewportAnchor(); + passed &= codexui::codex::retainedSelectionRemainsVisibleAfterReparenting(); + passed &= codexui::codex::incrementalRootSortPreservesTheViewportAnchor(); + passed &= codexui::codex::newestThreadPromotionRevealsOnce(); + if (passed) + std::cout << "NodeGraph ThreadPane UI tests passed\n"; + return passed ? EXIT_SUCCESS : EXIT_FAILURE; } From 70266710e155da4360f807290e251936dd8e9529 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:35:35 +0100 Subject: [PATCH 5/9] fix(ci): install frontend SDK tools and diagnose touch focus bounds --- .snodec/repo.yml | 2 ++ web/tools/qualify-browser.mjs | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.snodec/repo.yml b/.snodec/repo.yml index 65e4d8e..7fd2198 100644 --- a/.snodec/repo.yml +++ b/.snodec/repo.yml @@ -3,6 +3,8 @@ ci: profile: cpp apt: - libgit2-dev + - nodejs + - npm - qt6-base-dev - libkf6sonnet-dev - sonnet6-plugins diff --git a/web/tools/qualify-browser.mjs b/web/tools/qualify-browser.mjs index 4621d61..067ef6d 100644 --- a/web/tools/qualify-browser.mjs +++ b/web/tools/qualify-browser.mjs @@ -1205,8 +1205,8 @@ try { } await devTools.call("Emulation.setTouchEmulationEnabled", {enabled: true, maxTouchPoints: 1}); await waitUntil(devTools, `matchMedia('(pointer: coarse)').matches`, "touch navigation"); - const touchNavigation = await devTools.evaluate(`(async()=>{const group=document.querySelector('.thread-heading-context'),buttons=[...group.querySelectorAll('button')].filter(button=>!button.closest('.menu-popover')),height=group.getBoundingClientRect().height,frame=()=>new Promise(done=>requestAnimationFrame(()=>requestAnimationFrame(done)));buttons.filter(button=>!button.disabled).at(-1).focus();await frame();const last=buttons.filter(button=>!button.disabled).at(-1).getBoundingClientRect(),lastReachable=last.left>=0&&last.right<=innerWidth;buttons[0].focus();await frame();const first=buttons[0].getBoundingClientRect();return {lastReachable,firstReachable:first.left>=0&&first.right<=innerWidth,sameHeight:group.getBoundingClientRect().height===height,hitTargets:buttons.every(button=>button.getBoundingClientRect().width>=44&&button.getBoundingClientRect().height>=44)};})()`); - assert.deepEqual(touchNavigation, {lastReachable: true, firstReachable: true, sameHeight: true, hitTargets: true}); + const {diagnostics, ...touchNavigation} = await devTools.evaluate(`(async()=>{const group=document.querySelector('.thread-heading-context'),buttons=[...group.querySelectorAll('button')].filter(button=>!button.closest('.menu-popover')),height=group.getBoundingClientRect().height,frame=()=>new Promise(done=>requestAnimationFrame(()=>requestAnimationFrame(done)));buttons.filter(button=>!button.disabled).at(-1).focus();await frame();const last=buttons.filter(button=>!button.disabled).at(-1).getBoundingClientRect(),lastReachable=last.left>=0&&last.right<=innerWidth;buttons[0].focus();await frame();const first=buttons[0].getBoundingClientRect();return {diagnostics:JSON.stringify({last:last.toJSON(),first:first.toJSON(),width:innerWidth,scroll:group.scrollLeft}),lastReachable,firstReachable:first.left>=0&&first.right<=innerWidth,sameHeight:group.getBoundingClientRect().height===height,hitTargets:buttons.every(button=>button.getBoundingClientRect().width>=44&&button.getBoundingClientRect().height>=44)};})()`); + assert.deepEqual(touchNavigation, {lastReachable: true, firstReachable: true, sameHeight: true, hitTargets: true}, diagnostics); const headerScrollPoint = await devTools.evaluate(`(()=>{const r=document.querySelector('.thread-heading-context').getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2};})()`); await devTools.call("Input.dispatchMouseEvent", {type: "mouseWheel", ...headerScrollPoint, deltaX: 600, deltaY: 0}); await waitUntil(devTools, `(()=>{const row=document.querySelector('.thread-heading-context').getBoundingClientRect(),copy=document.querySelector('.thread-workspace-copy').getBoundingClientRect();return copy.left>=row.left-1&©.right<=row.right+1;})()`, "rightmost Copy reachable through horizontal scrolling even without a workspace"); From 9dbf89db6cd9a6de6215e58be4456abdccbbd142 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 13:47:14 +0100 Subject: [PATCH 6/9] fix(web): reveal focused touch controls across fallback font metrics --- web/src/styles.css | 2 +- web/tools/qualify-browser.mjs | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/web/src/styles.css b/web/src/styles.css index a874435..c379fa6 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -95,7 +95,7 @@ h1, h2, h3, p { margin: 0; } .turn-outline .menu-popover button[aria-current] { background: var(--presentation-selected-surface); color: var(--text-strong); } .turn-outline-count { padding: 4px 9px 8px; color: var(--text-secondary); font-size: 12px; } @media (pointer: coarse) and (max-width: 520px) { - .conversation-view-controls, .thread-heading-context { justify-content: flex-start; min-width: 0; overflow-x: auto; scrollbar-width: none; } + .conversation-view-controls, .thread-heading-context { justify-content: flex-start; min-width: 0; overflow-x: auto; scroll-padding-inline: 44px; scrollbar-width: none; } .conversation-view-controls > button, .thread-heading-context > button, .conversation-state { flex: none; } } .conversation-scroll { position: relative; overflow: auto; padding: 8px 24px calc(var(--composer-overlay-height) + 8px); } diff --git a/web/tools/qualify-browser.mjs b/web/tools/qualify-browser.mjs index 067ef6d..8182d57 100644 --- a/web/tools/qualify-browser.mjs +++ b/web/tools/qualify-browser.mjs @@ -1205,8 +1205,14 @@ try { } await devTools.call("Emulation.setTouchEmulationEnabled", {enabled: true, maxTouchPoints: 1}); await waitUntil(devTools, `matchMedia('(pointer: coarse)').matches`, "touch navigation"); - const {diagnostics, ...touchNavigation} = await devTools.evaluate(`(async()=>{const group=document.querySelector('.thread-heading-context'),buttons=[...group.querySelectorAll('button')].filter(button=>!button.closest('.menu-popover')),height=group.getBoundingClientRect().height,frame=()=>new Promise(done=>requestAnimationFrame(()=>requestAnimationFrame(done)));buttons.filter(button=>!button.disabled).at(-1).focus();await frame();const last=buttons.filter(button=>!button.disabled).at(-1).getBoundingClientRect(),lastReachable=last.left>=0&&last.right<=innerWidth;buttons[0].focus();await frame();const first=buttons[0].getBoundingClientRect();return {diagnostics:JSON.stringify({last:last.toJSON(),first:first.toJSON(),width:innerWidth,scroll:group.scrollLeft}),lastReachable,firstReachable:first.left>=0&&first.right<=innerWidth,sameHeight:group.getBoundingClientRect().height===height,hitTargets:buttons.every(button=>button.getBoundingClientRect().width>=44&&button.getBoundingClientRect().height>=44)};})()`); - assert.deepEqual(touchNavigation, {lastReachable: true, firstReachable: true, sameHeight: true, hitTargets: true}, diagnostics); + let touchNavigation; + for (const font of ["", "DejaVu Sans", "monospace"]) { + await devTools.evaluate(`(()=>{const group=document.querySelector('.thread-heading-context');group.style.fontFamily=${JSON.stringify(font)};group.scrollLeft=0;})()`); + const {diagnostics, ...measurement} = await devTools.evaluate(`(async()=>{const group=document.querySelector('.thread-heading-context'),buttons=[...group.querySelectorAll('button')].filter(button=>!button.closest('.menu-popover')),height=group.getBoundingClientRect().height,frame=()=>new Promise(done=>requestAnimationFrame(()=>requestAnimationFrame(done)));buttons.filter(button=>!button.disabled).at(-1).focus();await frame();const last=buttons.filter(button=>!button.disabled).at(-1).getBoundingClientRect(),lastReachable=last.left>=0&&last.right<=innerWidth;buttons[0].focus();await frame();const first=buttons[0].getBoundingClientRect();return {diagnostics:JSON.stringify({last:last.toJSON(),first:first.toJSON(),width:innerWidth,scroll:group.scrollLeft}),lastReachable,firstReachable:first.left>=0&&first.right<=innerWidth,sameHeight:group.getBoundingClientRect().height===height,hitTargets:buttons.every(button=>button.getBoundingClientRect().width>=44&&button.getBoundingClientRect().height>=44)};})()`); + assert.deepEqual(measurement, {lastReachable: true, firstReachable: true, sameHeight: true, hitTargets: true}, `${font}: ${diagnostics}`); + touchNavigation = measurement; + } + await devTools.evaluate(`document.querySelector('.thread-heading-context').style.fontFamily=''`); const headerScrollPoint = await devTools.evaluate(`(()=>{const r=document.querySelector('.thread-heading-context').getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2};})()`); await devTools.call("Input.dispatchMouseEvent", {type: "mouseWheel", ...headerScrollPoint, deltaX: 600, deltaY: 0}); await waitUntil(devTools, `(()=>{const row=document.querySelector('.thread-heading-context').getBoundingClientRect(),copy=document.querySelector('.thread-workspace-copy').getBoundingClientRect();return copy.left>=row.left-1&©.right<=row.right+1;})()`, "rightmost Copy reachable through horizontal scrolling even without a workspace"); From bca33dc941f7b17799a4ab5512f0b397048789f0 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 14:14:52 +0100 Subject: [PATCH 7/9] fix(ci): restore hosted build concurrency after repeated runner shutdowns --- .snodec/repo.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.snodec/repo.yml b/.snodec/repo.yml index 7fd2198..84efe98 100644 --- a/.snodec/repo.yml +++ b/.snodec/repo.yml @@ -27,6 +27,8 @@ ci: - '14' ipv6: true runtime_dirs: true - parallel: 14 + # Hosted runners repeatedly shut down during the 14-job dependency build. + # Restore the original build limit; CTest and local qualification retain 14 jobs. + parallel: 4 env: {CODEXUI_TIMING_POLICY: report} ctest_launcher: [xvfb-run, -a, env, QT_QPA_PLATFORM=offscreen] From f137f6ccb26749294c6ac7fd5591f1779e92e594 Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 15:05:26 +0100 Subject: [PATCH 8/9] fix(tests): discover staged AISuite tools and restore hosted test concurrency --- .snodec/repo.yml | 4 ++-- tests/manager/CMakeLists.txt | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/.snodec/repo.yml b/.snodec/repo.yml index 84efe98..933d3cb 100644 --- a/.snodec/repo.yml +++ b/.snodec/repo.yml @@ -24,11 +24,11 @@ ci: - --output-on-failure - --verbose - --parallel - - '14' + - '4' ipv6: true runtime_dirs: true # Hosted runners repeatedly shut down during the 14-job dependency build. - # Restore the original build limit; CTest and local qualification retain 14 jobs. + # Restore the original hosted limits; local qualification retains 14 jobs. parallel: 4 env: {CODEXUI_TIMING_POLICY: report} ctest_launcher: [xvfb-run, -a, env, QT_QPA_PLATFORM=offscreen] diff --git a/tests/manager/CMakeLists.txt b/tests/manager/CMakeLists.txt index 7237792..da7df40 100644 --- a/tests/manager/CMakeLists.txt +++ b/tests/manager/CMakeLists.txt @@ -6,8 +6,15 @@ target_link_libraries( codexui-build-options ) add_test(NAME codexmanager COMMAND codexmanager-test) +find_program(CODEXMANAGER_TEST_BRIDGE codex-bridge REQUIRED) +get_filename_component( + CODEXMANAGER_TEST_BIN "${CODEXMANAGER_TEST_BRIDGE}" DIRECTORY +) set_tests_properties( - codexmanager PROPERTIES TIMEOUT 90 ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + codexmanager + PROPERTIES + TIMEOUT 90 ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;PATH=${CODEXMANAGER_TEST_BIN}:$ENV{PATH}" ) target_compile_definitions( From c9718bd2d316cbf79c78a06634fe4e94f5233f5b Mon Sep 17 00:00:00 2001 From: Volker Christian Date: Wed, 11 Nov 2026 15:32:40 +0100 Subject: [PATCH 9/9] fix(tests): await a readable fork projection after asynchronous completion --- tests/codex/ClientRuntimeDispatchTest.cpp | 6867 ++++++++++----------- 1 file changed, 3144 insertions(+), 3723 deletions(-) diff --git a/tests/codex/ClientRuntimeDispatchTest.cpp b/tests/codex/ClientRuntimeDispatchTest.cpp index df19017..32335e1 100644 --- a/tests/codex/ClientRuntimeDispatchTest.cpp +++ b/tests/codex/ClientRuntimeDispatchTest.cpp @@ -38,3824 +38,3245 @@ #include namespace codexui::codex { -namespace { + namespace { -using namespace std::chrono_literals; -using namespace nodegraph; + using namespace std::chrono_literals; + using namespace nodegraph; -int failures = 0; + int failures = 0; -Value::Object userInputSubmission(std::string questionId, std::string answer) { - return { - {"choice", Value("submit")}, - {"input", - Value(Value::Object{ - {std::move(questionId), - Value(Value::Object{{"answers", Value(Value::Array{Value( - std::move(answer))})}})}})}}; -} - -nlohmann::json userInputQuestions(std::string id) { - return nlohmann::json::array({{{"id", std::move(id)}, - {"question", "Provide a value"}, - {"options", nullptr}}}); -} - -void expect(bool condition, std::string_view message) { - if (condition) - return; - ++failures; - std::cerr << "FAILED: " << message << '\n'; -} + Value::Object userInputSubmission(std::string questionId, std::string answer) { + return {{"choice", Value("submit")}, + {"input", + Value(Value::Object{ + {std::move(questionId), Value(Value::Object{{"answers", Value(Value::Array{Value(std::move(answer))})}})}})}}; + } -class UnixBridge final { -public: - explicit UnixBridge(std::string_view suffix = {}) { - path_ = "/tmp/codexui-runtime-dispatch-" + - std::to_string(static_cast(::getpid())) + - std::string(suffix) + ".sock"; - static_cast(::unlink(path_.c_str())); - listener_ = - ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); - if (listener_ < 0) - return; - - sockaddr_un address{}; - address.sun_family = AF_UNIX; - if (path_.size() >= sizeof(address.sun_path)) - return; - std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1U); - if (::bind(listener_, reinterpret_cast(&address), - sizeof(address)) != 0 || - ::listen(listener_, 1) != 0) { - static_cast(::close(listener_)); - listener_ = -1; - } - } - - ~UnixBridge() { - if (client_ >= 0) - static_cast(::close(client_)); - if (listener_ >= 0) - static_cast(::close(listener_)); - static_cast(::unlink(path_.c_str())); - } - - UnixBridge(const UnixBridge &) = delete; - UnixBridge &operator=(const UnixBridge &) = delete; - - [[nodiscard]] bool valid() const noexcept { return listener_ >= 0; } - [[nodiscard]] const std::string &path() const noexcept { return path_; } - - bool acceptClient(std::chrono::milliseconds timeout = 5s) { - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline) { - pollfd event{listener_, POLLIN, 0}; - const int ready = ::poll(&event, 1, 20); - if (ready < 0 && errno == EINTR) - continue; - if (ready <= 0) - continue; - const int incoming = - ::accept4(listener_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC); - if (incoming >= 0) { - if (client_ >= 0) - static_cast(::close(client_)); - client_ = incoming; - buffered_.clear(); - nextSequence_ = 4; - return true; - } - if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) - return false; - } - return false; - } - - bool peerClosed() const { - char byte; - return client_ >= 0 && - ::recv(client_, &byte, 1, MSG_PEEK | MSG_DONTWAIT) == 0; - } - - bool send(nlohmann::json message, std::chrono::milliseconds timeout = 2s) { - std::string encoded = message.dump(); - encoded.push_back('\n'); - std::size_t offset = 0; - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (offset < encoded.size() && - std::chrono::steady_clock::now() < deadline) { - const ssize_t written = - ::write(client_, encoded.data() + offset, encoded.size() - offset); - if (written > 0) { - offset += static_cast(written); - continue; - } - if (written < 0 && errno == EINTR) - continue; - if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) - return false; - pollfd event{client_, POLLOUT, 0}; - static_cast(::poll(&event, 1, 10)); - } - return offset == encoded.size(); - } - - std::optional - receive(std::chrono::milliseconds timeout = 2s) { - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline) { - if (const std::size_t newline = buffered_.find('\n'); - newline != std::string::npos) { - std::string line = buffered_.substr(0, newline); - buffered_.erase(0, newline + 1U); - try { - return nlohmann::json::parse(line); - } catch (...) { - return std::nullopt; + nlohmann::json userInputQuestions(std::string id) { + return nlohmann::json::array({{{"id", std::move(id)}, {"question", "Provide a value"}, {"options", nullptr}}}); } - } - - std::array incoming{}; - const ssize_t received = - ::read(client_, incoming.data(), incoming.size()); - if (received > 0) { - buffered_.append(incoming.data(), static_cast(received)); - continue; - } - if (received == 0) - return std::nullopt; - if (errno == EINTR) - continue; - if (errno != EAGAIN && errno != EWOULDBLOCK) - return std::nullopt; - pollfd event{client_, POLLIN, 0}; - static_cast(::poll(&event, 1, 10)); - } - return std::nullopt; - } - - std::optional - receiveAppServer(std::chrono::milliseconds timeout = 2s) { - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline) { - const auto remaining = - std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()); - std::optional envelope = receive(remaining); - if (!envelope) - return std::nullopt; - if (envelope->value("kind", std::string{}) == "appserver" && - envelope->contains("payload")) - return envelope->at("payload"); - } - return std::nullopt; - } - - bool reply(const nlohmann::json &request, nlohmann::json result) { - return send({{"kind", "appserver"}, - {"connectionId", "runtime-test"}, - {"role", "controller"}, - {"seq", nextSequence_++}, - {"payload", - {{"jsonrpc", "2.0"}, - {"id", request.at("id")}, - {"result", std::move(result)}}}}); - } - - bool replyError(const nlohmann::json &request, int code, - std::string message) { - return send( - {{"kind", "appserver"}, - {"connectionId", "runtime-test"}, - {"role", "controller"}, - {"seq", nextSequence_++}, - {"payload", - {{"jsonrpc", "2.0"}, - {"id", request.at("id")}, - {"error", {{"code", code}, {"message", std::move(message)}}}}}}); - } - - bool appServerRequest(std::string id, std::string method, - nlohmann::json parameters, - std::string role = "controller") { - return send({{"kind", "appserver"}, - {"connectionId", "runtime-test"}, - {"role", std::move(role)}, - {"seq", nextSequence_++}, - {"payload", - {{"jsonrpc", "2.0"}, - {"id", std::move(id)}, - {"method", std::move(method)}, - {"params", std::move(parameters)}}}}); - } - - bool appServerNotification(std::string method, nlohmann::json parameters, - std::int64_t emittedAtMs = 1234567890123) { - return send({{"kind", "appserver"}, - {"connectionId", "runtime-test"}, - {"role", "controller"}, - {"seq", nextSequence_++}, - {"payload", - {{"jsonrpc", "2.0"}, - {"method", std::move(method)}, - {"emittedAtMs", emittedAtMs}, - {"params", std::move(parameters)}}}}); - } - - bool setRole(std::string role, std::string controllerConnectionId) { - if (!send({{"kind", "bridge.connection"}, - {"event", "opened"}, - {"connectionId", "runtime-test"}, - {"role", std::move(role)}, - {"seq", nextSequence_++}})) - return false; - return send({{"kind", "bridge.controller"}, - {"controllerConnectionId", std::move(controllerConnectionId)}, - {"seq", nextSequence_++}}); - } - - bool setProviderGeneration(std::uint64_t generation) { - return send({{"kind", "bridge.provider"}, - {"state", "ready"}, - {"providerGeneration", generation}, - {"seq", nextSequence_++}}); - } - -private: - std::string path_; - int listener_ = -1; - int client_ = -1; - std::uint64_t nextSequence_ = 4; - std::string buffered_; -}; - -class RunningRuntime final { -public: - explicit RunningRuntime(Configuration &configuration) - : configuration_(configuration) {} - - ~RunningRuntime() { stop(); } - - RunningRuntime(const RunningRuntime &) = delete; - RunningRuntime &operator=(const RunningRuntime &) = delete; - - void start() { - worker_ = std::thread([this] { - result_.store(runClientRuntime(configuration_, graph_, channels_, false), - std::memory_order_release); - }); - } - - void stop() { - if (!worker_.joinable()) - return; - ShutdownRequest shutdown; - for (int attempt = 0; attempt != 1000; ++attempt) { - if (messageAdmitted(channels_.sendShutdown(shutdown))) - break; - std::this_thread::sleep_for(1ms); - } - worker_.join(); - } - - NodeGraph &graph() noexcept { return graph_; } - ThreadChannels &channels() noexcept { return channels_; } - - std::optional workerCpuTime() { - if (!worker_.joinable()) - return std::nullopt; - clockid_t clock{}; - if (::pthread_getcpuclockid(worker_.native_handle(), &clock) != 0) - return std::nullopt; - timespec value{}; - if (::clock_gettime(clock, &value) != 0) - return std::nullopt; - return std::chrono::seconds(value.tv_sec) + - std::chrono::nanoseconds(value.tv_nsec); - } - - void drainNotifications() { - static_cast(channels_.drainWorkerToQtWake()); - WorkerToQtMessage message; - while (channels_.tryReceiveForQt(message)) - message = WorkerStopped{}; - } - - std::vector takeProtocolDiagnostics() { - std::vector diagnostics; - static_cast(channels_.drainWorkerToQtWake()); - WorkerToQtMessage message; - while (channels_.tryReceiveForQt(message)) { - if (ProtocolDiagnostic *diagnostic = - std::get_if(&message)) { - if (diagnostic->diagnosticBatch.empty()) { - diagnostics.emplace_back(std::move(*diagnostic)); - } else { - for (Value::Object &details : diagnostic->diagnosticBatch) - diagnostics.push_back({std::move(details), {}}); + + void expect(bool condition, std::string_view message) { + if (condition) + return; + ++failures; + std::cerr << "FAILED: " << message << '\n'; } - } - message = WorkerStopped{}; - } - return diagnostics; - } - -private: - Configuration &configuration_; - NodeGraph graph_; - ThreadChannels channels_; - std::thread worker_; - std::atomic result_{-1}; -}; - -template -bool waitUntil(Predicate predicate, std::chrono::milliseconds timeout = 2s) { - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline) { - if (predicate()) - return true; - std::this_thread::sleep_for(2ms); - } - return predicate(); -} -NodeRef findNode(NodeGraph &graph, NodeId id) { - NodeRef found; - static_cast(waitUntil([&] { - std::optional read = graph.tryRead(); - if (!read) - return false; - found = read->find(id); - return static_cast(found); - })); - return found; -} + class UnixBridge final { + public: + explicit UnixBridge(std::string_view suffix = {}) { + path_ = + "/tmp/codexui-runtime-dispatch-" + std::to_string(static_cast(::getpid())) + std::string(suffix) + ".sock"; + static_cast(::unlink(path_.c_str())); + listener_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (listener_ < 0) + return; + + sockaddr_un address{}; + address.sun_family = AF_UNIX; + if (path_.size() >= sizeof(address.sun_path)) + return; + std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1U); + if (::bind(listener_, reinterpret_cast(&address), sizeof(address)) != 0 || ::listen(listener_, 1) != 0) { + static_cast(::close(listener_)); + listener_ = -1; + } + } -NodeRef findRetiredNode(NodeGraph &graph, const NodeId &id) { - NodeRef found; - static_cast(waitUntil([&] { - std::optional read = graph.tryRead(); - if (!read) - return false; - for (std::size_t index = 0; index < read->retiredCount(); ++index) { - const NodeRef node = read->retiredAt(index); - if (node && node->id() == id) { - found = node; - return true; - } - } - return false; - })); - return found; -} + ~UnixBridge() { + if (client_ >= 0) + static_cast(::close(client_)); + if (listener_ >= 0) + static_cast(::close(listener_)); + static_cast(::unlink(path_.c_str())); + } -bool operationPending(NodeGraph &graph, const nlohmann::json &requestId) { - const ProtocolRequestId id = requestIdFromJson(requestId); - std::optional read = graph.tryRead(); - if (!read) - return false; - const NodeRef operation = read->find({NodeKind::Operation, id.canonical()}); - return operation && read->state(operation)->status == NodeStatus::Pending; -} + UnixBridge(const UnixBridge&) = delete; + UnixBridge& operator=(const UnixBridge&) = delete; -bool operationTargets(NodeGraph &graph, const nlohmann::json &requestId, - const NodeRef &target) { - const ProtocolRequestId id = requestIdFromJson(requestId); - std::optional read = graph.tryRead(); - if (!read) - return false; - const NodeRef operation = read->find({NodeKind::Operation, id.canonical()}); - return operation && read->related(target, RelationKind::PendingOperation) == - std::vector{operation}; -} + [[nodiscard]] bool valid() const noexcept { + return listener_ >= 0; + } + [[nodiscard]] const std::string& path() const noexcept { + return path_; + } -bool operationRetired(NodeGraph &graph, const nlohmann::json &requestId) { - const ProtocolRequestId id = requestIdFromJson(requestId); - std::optional read = graph.tryRead(); - return read && !read->find({NodeKind::Operation, id.canonical()}); -} + bool acceptClient(std::chrono::milliseconds timeout = 5s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + pollfd event{listener_, POLLIN, 0}; + const int ready = ::poll(&event, 1, 20); + if (ready < 0 && errno == EINTR) + continue; + if (ready <= 0) + continue; + const int incoming = ::accept4(listener_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC); + if (incoming >= 0) { + if (client_ >= 0) + static_cast(::close(client_)); + client_ = incoming; + buffered_.clear(); + nextSequence_ = 4; + return true; + } + if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) + return false; + } + return false; + } -bool interactionRetired(NodeGraph &graph, const NodeRef &interaction) { - if (!interaction) - return false; - std::optional read = graph.tryRead(); - if (!read || read->find(interaction->id())) - return false; - for (std::size_t index = 0; index < read->retiredCount(); ++index) - if (read->retiredAt(index) == interaction) - return true; - return false; -} + bool peerClosed() const { + char byte; + return client_ >= 0 && ::recv(client_, &byte, 1, MSG_PEEK | MSG_DONTWAIT) == 0; + } -bool sendAction(ThreadChannels &channels, NodeAction action) { - return messageAdmitted(channels.sendNodeAction(action)); -} + bool send(nlohmann::json message, std::chrono::milliseconds timeout = 2s) { + std::string encoded = message.dump(); + encoded.push_back('\n'); + std::size_t offset = 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (offset < encoded.size() && std::chrono::steady_clock::now() < deadline) { + const ssize_t written = ::write(client_, encoded.data() + offset, encoded.size() - offset); + if (written > 0) { + offset += static_cast(written); + continue; + } + if (written < 0 && errno == EINTR) + continue; + if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) + return false; + pollfd event{client_, POLLOUT, 0}; + static_cast(::poll(&event, 1, 10)); + } + return offset == encoded.size(); + } -bool sendAction(ThreadChannels &channels, RuntimeAction action) { - return messageAdmitted(channels.sendRuntimeAction(action)); -} + std::optional receive(std::chrono::milliseconds timeout = 2s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (const std::size_t newline = buffered_.find('\n'); newline != std::string::npos) { + std::string line = buffered_.substr(0, newline); + buffered_.erase(0, newline + 1U); + try { + return nlohmann::json::parse(line); + } catch (...) { + return std::nullopt; + } + } -nlohmann::json listedThread() { - return {{"id", "runtime-thread"}, - {"name", "Runtime dispatch"}, - {"status", "idle"}, - {"historyMode", "legacy"}, - {"createdAt", 1}, - {"updatedAt", 2}, - {"turns", nlohmann::json::array()}}; -} + std::array incoming{}; + const ssize_t received = ::read(client_, incoming.data(), incoming.size()); + if (received > 0) { + buffered_.append(incoming.data(), static_cast(received)); + continue; + } + if (received == 0) + return std::nullopt; + if (errno == EINTR) + continue; + if (errno != EAGAIN && errno != EWOULDBLOCK) + return std::nullopt; + pollfd event{client_, POLLIN, 0}; + static_cast(::poll(&event, 1, 10)); + } + return std::nullopt; + } -bool rejectedAutomaticCurrentTimeResponseIsTerminal(UnixBridge &bridge, - RunningRuntime &runtime) { - constexpr std::string_view RequestId = "clock-before-identity"; - if (!bridge.appServerRequest(std::string(RequestId), "currentTime/read", - {{"threadId", "pre-identity-thread"}})) - return false; - - // The transport is attached, but CodexBridge has not received its - // bridge.connection identity yet. Its sender therefore deterministically - // rejects the automatic response without disconnecting the worker. - const NodeId interactionId{ - NodeKind::Interaction, - ProtocolRequestId(std::string(RequestId)).canonical()}; - const NodeRef retired = findRetiredNode(runtime.graph(), interactionId); - std::optional read = runtime.graph().tryRead(); - const bool terminal = retired && read && !read->find(interactionId); - read.reset(); - return terminal && !bridge.receiveAppServer(100ms); -} + std::optional receiveAppServer(std::chrono::milliseconds timeout = 2s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + const auto remaining = + std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); + std::optional envelope = receive(remaining); + if (!envelope) + return std::nullopt; + if (envelope->value("kind", std::string{}) == "appserver" && envelope->contains("payload")) + return envelope->at("payload"); + } + return std::nullopt; + } -bool establishProvider(UnixBridge &bridge, RunningRuntime &runtime) { - RuntimeAction configure; - configure.kind = RuntimeActionKind::ConfigureConnection; - configure.payload = {{"transport", Value("unix")}, - {"path", Value(bridge.path())}}; - if (!sendAction(runtime.channels(), std::move(configure))) - return false; - if (!bridge.acceptClient()) - return false; - - expect(rejectedAutomaticCurrentTimeResponseIsTerminal(bridge, runtime), - "a rejected automatic current-time response retires its interaction " - "instead of exposing an unresolvable UI action"); - - if (!bridge.send({{"kind", "bridge.connection"}, - {"event", "opened"}, - {"connectionId", "runtime-test"}, - {"role", "controller"}, - {"seq", 1}}) || - !bridge.send({{"kind", "bridge.controller"}, - {"controllerConnectionId", "runtime-test"}, - {"seq", 2}}) || - !bridge.send({{"kind", "bridge.provider"}, - {"state", "ready"}, - {"providerGeneration", 1}, - {"seq", 3}})) - return false; - - std::unordered_map methods; - for (int count = 0; count != 8; ++count) { - std::optional request = bridge.receiveAppServer(); - if (!request || !request->contains("id")) - return false; - const std::string method = request->value("method", std::string{}); - ++methods[method]; - nlohmann::json result{{"data", nlohmann::json::array()}}; - if (method == "account/usage/read") - result = {{"summary", {{"lifetimeTokens", 12000}}}}; - if (method == "thread/list") { - const bool firstThreadPage = methods[method] == 1; - expect(request->at("params").value("sortKey", std::string{}) == "recency_at" && - request->at("params").value("sortDirection", std::string{}) == "desc" && - request->at("params").value("limit", 0) == 100 && - request->at("params").value("useStateDbOnly", false) == firstThreadPage, - "initial thread hydration requests a fast DB page followed by " - "the repair page"); - result["data"].push_back(listedThread()); - result["nextCursor"] = nullptr; - } - if (method == "thread/read") { - expect(request->at("params").value("includeTurns", true) == false, "startup lineage discovery excludes conversation turns"); - auto metadata = listedThread(); - metadata["forkedFromId"] = nullptr; - metadata["parentThreadId"] = nullptr; - result = {{"thread", metadata}}; - } - if (!bridge.reply(*request, std::move(result))) - return false; - } - return methods == std::unordered_map{{"thread/list", 2}, - {"thread/read", 1}, - {"project/list", 1}, - {"threadSection/list", 1}, - {"model/list", 1}, - {"permissionProfile/list", 1}, - {"account/usage/read", 1}} && - static_cast(findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"})); -} + bool reply(const nlohmann::json& request, nlohmann::json result) { + return send({{"kind", "appserver"}, + {"connectionId", "runtime-test"}, + {"role", "controller"}, + {"seq", nextSequence_++}, + {"payload", {{"jsonrpc", "2.0"}, {"id", request.at("id")}, {"result", std::move(result)}}}}); + } -void replyAccountUsage(UnixBridge &bridge) { - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "account/usage/read", - "turn completion refreshes account usage"); - if (request) - expect(bridge.reply(*request, {{"summary", {{"lifetimeTokens", 12000}}}}), - "account usage snapshot is returned without sending a prompt"); -} + bool replyError(const nlohmann::json& request, int code, std::string message) { + return send( + {{"kind", "appserver"}, + {"connectionId", "runtime-test"}, + {"role", "controller"}, + {"seq", nextSequence_++}, + {"payload", + {{"jsonrpc", "2.0"}, {"id", request.at("id")}, {"error", {{"code", code}, {"message", std::move(message)}}}}}}); + } -void accountUsageRefreshIsCoalescedAndAccountScoped(UnixBridge &bridge, - RunningRuntime &runtime) { - const auto hasUsage = [&](std::optional expected, - NodeStatus status) { - auto read = runtime.graph().tryRead(); - if (!read) - return false; - const auto node = read->find({NodeKind::Account, "account/usage/read"}); - if (!node || read->state(node)->status != status) - return false; - const auto *value = valueMember(*read->state(node), "summary"); - const auto *summary = value ? value->asObject() : nullptr; - return (summary ? signedIntegerFromValue(valueMember(*summary, "lifetimeTokens")) - : std::nullopt) == expected; - }; - expect(waitUntil([&] { return hasUsage(12000, NodeStatus::Completed); }), - "startup retrieves account usage without a prompt"); - expect(bridge.appServerNotification("account/updated", {{"authMode", "chatgpt"}}), - "account change requests a fresh usage snapshot"); - const auto old = bridge.receiveAppServer(); - expect(old && old->value("method", "") == "account/usage/read", - "account usage refresh uses the dedicated read endpoint"); - expect(bridge.appServerNotification("account/updated", {{"authMode", "apiKey"}}) && - bridge.appServerNotification("account/updated", {{"authMode", "apiKey"}}), - "overlapping account changes reach the worker"); - expect(!bridge.receiveAppServer(100ms), "overlapping refreshes share one in-flight read"); - if (old) - expect(bridge.reply(*old, {{"summary", {{"lifetimeTokens", 999999}}}}), - "an old-account response arrives after the account changed"); - const auto followup = bridge.receiveAppServer(); - expect(followup && followup->value("method", "") == "account/usage/read", - "overlapping refreshes produce one follow-up read"); - if (followup) - expect(bridge.replyError(*followup, -32600, "account usage unsupported"), - "an unsupported account reports its usage error"); - expect(waitUntil([&] { return hasUsage(std::nullopt, NodeStatus::Failed); }), - "unsupported usage stays unknown and never displays the previous account total"); - expect(!bridge.receiveAppServer(100ms), "unsupported usage does not start a retry loop"); - expect(bridge.appServerNotification("account/updated", {{"authMode", "chatgpt"}}), - "supported authentication can refresh usage again"); - replyAccountUsage(bridge); - expect(waitUntil([&] { return hasUsage(12000, NodeStatus::Completed); }), - "successful authentication recovers the account usage snapshot"); -} + bool appServerRequest(std::string id, std::string method, nlohmann::json parameters, std::string role = "controller") { + return send( + {{"kind", "appserver"}, + {"connectionId", "runtime-test"}, + {"role", std::move(role)}, + {"seq", nextSequence_++}, + {"payload", + {{"jsonrpc", "2.0"}, {"id", std::move(id)}, {"method", std::move(method)}, {"params", std::move(parameters)}}}}); + } -std::string diagnosticField(const ProtocolDiagnostic &effect, std::string_view key) { - const auto found = effect.details.find(key); - if (found == effect.details.end() || !found->second.asString()) - return {}; - return *found->second.asString(); -} + bool appServerNotification(std::string method, nlohmann::json parameters, std::int64_t emittedAtMs = 1234567890123) { + return send({{"kind", "appserver"}, + {"connectionId", "runtime-test"}, + {"role", "controller"}, + {"seq", nextSequence_++}, + {"payload", + {{"jsonrpc", "2.0"}, + {"method", std::move(method)}, + {"emittedAtMs", emittedAtMs}, + {"params", std::move(parameters)}}}}); + } -void protocolDiagnosticsPreserveMetadataWithoutPayloads( - UnixBridge &bridge, RunningRuntime &runtime) { - const std::vector initialDiagnostics = - runtime.takeProtocolDiagnostics(); - expect(std::ranges::any_of(initialDiagnostics, - [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "subject") == - "connection.lifecycle"; - }) && - std::ranges::any_of(initialDiagnostics, - [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "subject") == - "connection.provider" && - diagnosticField( - effect, "authority") == "replace"; - }), - "transport lifecycle and bridge provider diagnostics remain visible"); - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - if (!thread) - return; - - NodeAction rename{thread, NodeActionKind::Rename}; - rename.payload = {{"name", Value("authored-name-must-not-appear")}}; - expect(sendAction(runtime.channels(), std::move(rename)), - "diagnostic rename enters the typed mailbox"); - const std::optional request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/name/set", - "diagnostic fixture receives the direct request"); - if (!request) - return; - expect(bridge.replyError(*request, -32041, "rename rejected safely"), - "diagnostic fixture receives a benign JSON-RPC error"); - - std::vector diagnostics; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - diagnostics.insert(diagnostics.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::any_of(diagnostics, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == "client error" && - diagnosticField(effect, "subject") == "thread/name/set"; - }); - }), - "request and response diagnostics cross the typed worker queue"); - - const ProtocolDiagnostic *sent = nullptr; - const ProtocolDiagnostic *failed = nullptr; - for (const ProtocolDiagnostic &effect : diagnostics) { - if (diagnosticField(effect, "subject") != "thread/name/set") - continue; - if (diagnosticField(effect, "direction") == "client request") - sent = &effect; - if (diagnosticField(effect, "direction") == "client error") - failed = &effect; - } - expect(sent && failed && diagnosticField(*sent, "source") == "CodexUI" && - diagnosticField(*sent, "authority") == "none" && - diagnosticField(*sent, "threadId") == "runtime-thread" && - diagnosticField(*failed, "source") == "app-server" && - diagnosticField(*failed, "authority") == "none" && - diagnosticField(*failed, "threadId") == "runtime-thread" && - diagnosticField(*failed, "outcome") == "ERROR" && - diagnosticField(*failed, "errorCategory") == "json-rpc" && - diagnosticField(*failed, "errorCode") == "-32041" && - diagnosticField(*failed, "error") == "rename rejected safely" && - diagnosticField(*sent, "correlation") == - diagnosticField(*failed, "correlation"), - "diagnostics preserve direction, source, semantic authority, scope, " - "correlation, and safe errors"); - - for (const ProtocolDiagnostic &effect : diagnostics) { - const std::string rendered = diagnosticField(effect, "subject") + - diagnosticField(effect, "error") + - diagnosticField(effect, "threadId"); - expect(rendered.find("authored-name-must-not-appear") == std::string::npos, - "diagnostics never copy an authored request payload"); - } - - RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; - expect(sendAction(runtime.channels(), std::move(refresh)), - "secret-error fixture enters the typed mailbox"); - const std::optional secretRequest = bridge.receiveAppServer(); - expect(secretRequest && - secretRequest->value("method", std::string{}) == "thread/list", - "secret-error fixture receives the direct request"); - if (secretRequest) { - expect(secretRequest->at("params").value("useStateDbOnly", false), - "the foreground diagnostic request uses the fast DB path"); - expect(bridge.replyError(*secretRequest, -32042, - "Bearer sk-runtime-secret eyJabc.def.ghi"), - "secret-shaped error reaches the runtime"); - std::vector secretDiagnostics; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - secretDiagnostics.insert(secretDiagnostics.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::any_of( - secretDiagnostics, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == - "client error" && - diagnosticField(effect, "subject") == "thread/list"; - }); - }), - "secret-shaped error produces bounded metadata"); - bool redactedSecretError = false; - for (const ProtocolDiagnostic &effect : secretDiagnostics) { - if (diagnosticField(effect, "subject") != "thread/list" || - diagnosticField(effect, "direction") != "client error") - continue; - redactedSecretError = - diagnosticField(effect, "error") == "[redacted error detail]"; - } - expect(redactedSecretError, - "credential-shaped protocol error detail is redacted"); - const std::optional repairRequest = - bridge.receiveAppServer(); - expect(repairRequest && - repairRequest->value("method", std::string{}) == "thread/list" && - !repairRequest->at("params").value("useStateDbOnly", true), - "a failed fast DB request still falls back to repair scanning"); - if (repairRequest) - expect(bridge.reply(*repairRequest, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "repair fallback completes after the fast-path failure"); - } - - const auto readAuthority = [&](bool insertInterveningFrame) { - runtime.drainNotifications(); - NodeAction reload{thread, NodeActionKind::Reload}; - expect(sendAction(runtime.channels(), std::move(reload)), - "paginated diagnostic reload enters the typed mailbox"); - const std::optional resumeRequest = - bridge.receiveAppServer(); - expect(resumeRequest && - resumeRequest->value("method", std::string{}) == - "thread/resume" && - resumeRequest->at("params").value("excludeTurns", false), - "diagnostic reload establishes metadata-only live state first"); - if (!resumeRequest) - return std::string{}; - expect(bridge.reply(*resumeRequest, nlohmann::json::object()), - "metadata-only settings refresh response is delivered"); - const std::optional readRequest = bridge.receiveAppServer(); - expect(readRequest && readRequest->value("method", std::string{}) == - "thread/turns/list", - "diagnostic reload pages history after metadata resume"); - if (!readRequest) - return std::string{}; - expect(readRequest->at("params").value("itemsView", std::string{}) == - "summary", - "thread hydration separates bounded turn summaries from items"); - if (insertInterveningFrame) { - expect(bridge.appServerNotification( - "thread/name/updated", - {{"threadId", "runtime-thread"}, - {"name", "Changed while pagination was pending"}}), - "intervening provider delta is delivered before pagination"); - } - expect(bridge.reply(*readRequest, {{"data", listedThread().at("turns")}, - {"nextCursor", nullptr}}), - "turn summary diagnostic response is delivered"); - - const ProtocolRequestId readOperation = - requestIdFromJson(readRequest->at("id")); - expect(waitUntil([&] { - const std::optional read = - runtime.graph().tryRead(); - if (!read) - return false; - const NodeRef current = - read->find({NodeKind::Thread, "runtime-thread"}); - if (!current) - return false; - const auto state = read->state(current); - return !read->find( - {NodeKind::Operation, readOperation.canonical()}) && - exactStringFromValue( - valueMember(*state, "hydrationState")) == "ready" && - !valueMember(*state, "hydrationError"); - }), - "the exact bridge turn page retires its Operation and makes the " - "same thread ready without a synthetic failure"); - - std::string authority; - expect(waitUntil([&] { - for (ProtocolDiagnostic &effect : runtime.takeProtocolDiagnostics()) { - if (diagnosticField(effect, "direction") == "client result" && - diagnosticField(effect, "subject") == "thread/turns/list") - authority = diagnosticField(effect, "authority"); - } - return !authority.empty(); - }), - "thread/turns/list result retains its diagnostic authority"); - return authority; - }; - expect(readAuthority(true) == "merge", - "an intervening provider frame retains paginated merge authority"); - expect(readAuthority(false) == "merge", - "an immediately correlated page retains paginated merge authority"); - - runtime.drainNotifications(); - expect( - bridge.appServerNotification("skills/changed", nlohmann::json::object()), - "state-neutral catalog invalidation is delivered"); - expect(bridge.appServerNotification("thread/goal/cleared", - {{"threadId", "runtime-thread"}}), - "authoritative removal notification is delivered"); - std::vector notificationDiagnostics; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - notificationDiagnostics.insert( - notificationDiagnostics.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::any_of(notificationDiagnostics, - [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, - "subject") == - "skills/changed"; - }) && - std::ranges::any_of( - notificationDiagnostics, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "subject") == - "thread/goal/cleared"; - }); - }), - "notification diagnostics preserve semantic authority"); - const auto authorityFor = [&](std::string_view subject) { - const auto found = std::ranges::find_if( - notificationDiagnostics, [subject](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "subject") == subject; - }); - return found == notificationDiagnostics.end() - ? std::string{} - : diagnosticField(*found, "authority"); - }; - for (const auto &diagnostic : notificationDiagnostics) { - const auto emitted = - signedIntegerFromValue(valueMember(diagnostic.details, "emittedAtMs")); - const auto recorded = - signedIntegerFromValue(valueMember(diagnostic.details, "recordedAtMs")); - if (diagnosticField(diagnostic, "subject") == "skills/changed") - expect(emitted == 1234567890123 && recorded && *recorded != *emitted, - "server emission time and local boundary-record time remain " - "distinct"); - } - expect(authorityFor("skills/changed") == "none" && - authorityFor("thread/goal/cleared") == "remove", - "state-neutral and removal notifications remain distinguishable"); - - runtime.drainNotifications(); - expect(bridge.appServerRequest("diagnostic-clock", "currentTime/read", - {{"threadId", "runtime-thread"}}), - "reverse-request diagnostic fixture is delivered"); - const std::optional automaticClockResponse = - bridge.receiveAppServer(); - expect(automaticClockResponse && - !automaticClockResponse->contains("method") && - automaticClockResponse->value("id", std::string{}) == - "diagnostic-clock", - "reverse-request diagnostic fixture consumes its automatic response"); - std::vector reverseDiagnostics; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - reverseDiagnostics.insert(reverseDiagnostics.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::any_of( - reverseDiagnostics, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == - "server result" && - diagnosticField(effect, "correlation") == - "diagnostic-clock"; - }); - }), - "reverse request and automatic response are both diagnosed"); - const ProtocolDiagnostic *reverseRequest = nullptr; - const ProtocolDiagnostic *reverseResult = nullptr; - for (const ProtocolDiagnostic &effect : reverseDiagnostics) { - if (diagnosticField(effect, "correlation") != "diagnostic-clock") - continue; - if (diagnosticField(effect, "direction") == "server request") - reverseRequest = &effect; - if (diagnosticField(effect, "direction") == "server result") - reverseResult = &effect; - } - const auto *clockTimes = - reverseResult ? valueMember(reverseResult->details, "timing") : nullptr; - expect(clockTimes && clockTimes->asArray() && - clockTimes->asArray()->size() == 1 && - exactStringFromValue(clockTimes->asArray()->front().find( - "field")) == "currentTimeAt", - "client-reported clock response keeps its schema timestamp without " - "retaining other payload"); - expect(reverseRequest && reverseResult && - diagnosticField(*reverseRequest, "authority") == "merge" && - diagnosticField(*reverseResult, "authority") == "remove" && - diagnosticField(*reverseRequest, "threadId") == "runtime-thread" && - diagnosticField(*reverseRequest, "correlation") == - diagnosticField(*reverseResult, "correlation"), - "reverse interaction diagnostics preserve scope and correlation"); - - runtime.drainNotifications(); - constexpr std::string_view SensitiveRequestId = - "failed:sk-sensitive-correlation"; - expect(bridge.appServerRequest(std::string(SensitiveRequestId), - "currentTime/read", - {{"threadId", "runtime-thread"}}), - "sensitive request-id diagnostic fixture is delivered"); - const std::optional sensitiveClockResponse = - bridge.receiveAppServer(); - expect(sensitiveClockResponse && - !sensitiveClockResponse->contains("method") && - sensitiveClockResponse->value("id", std::string{}) == - SensitiveRequestId, - "sensitive request-id fixture consumes its automatic response"); - std::vector sensitiveIdDiagnostics; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - sensitiveIdDiagnostics.insert(sensitiveIdDiagnostics.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::any_of( - sensitiveIdDiagnostics, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == - "server result" && - diagnosticField(effect, "correlation") == - ""; - }); - }), - "sensitive request ids remain visible only as redacted chronology"); - for (const ProtocolDiagnostic &effect : sensitiveIdDiagnostics) { - std::string visibleMetadata; - for (const auto &[key, value] : effect.details) { - visibleMetadata += key; - if (value.asString()) - visibleMetadata += *value.asString(); - } - expect(visibleMetadata.find(SensitiveRequestId) == std::string::npos, - "sensitive request ids are neither retained nor correlated"); - } - runtime.drainNotifications(); -} + bool setRole(std::string role, std::string controllerConnectionId) { + if (!send({{"kind", "bridge.connection"}, + {"event", "opened"}, + {"connectionId", "runtime-test"}, + {"role", std::move(role)}, + {"seq", nextSequence_++}})) + return false; + return send({{"kind", "bridge.controller"}, + {"controllerConnectionId", std::move(controllerConnectionId)}, + {"seq", nextSequence_++}}); + } -void directNodeActionsUseOneCorrelatedRequest(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), "provider hydration creates action target"); - if (!thread) - return; - - NodeAction missingName{thread, NodeActionKind::Rename}; - missingName.correlation = "missing-name-action"; - expect(sendAction(runtime.channels(), std::move(missingName)), - "a missing-name rename can enter the typed mailbox"); - expect(!bridge.receiveAppServer(100ms), - "worker validation blocks a missing rename name"); - - NodeAction emptyName{thread, NodeActionKind::Rename}; - emptyName.payload = {{"name", Value(" \t\n")}}; - emptyName.correlation = "blank-name-action"; - expect(sendAction(runtime.channels(), std::move(emptyName)), - "a blank-name rename can enter the typed mailbox"); - expect(!bridge.receiveAppServer(100ms), - "worker validation blocks an empty rename name"); - std::vector localRejections; - expect(waitUntil([&] { - std::vector batch = runtime.takeProtocolDiagnostics(); - localRejections.insert(localRejections.end(), - std::make_move_iterator(batch.begin()), - std::make_move_iterator(batch.end())); - return std::ranges::count_if( - localRejections, [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == - "local result" && - diagnosticField(effect, "subject") == - "thread/name/set"; - }) >= 2; - }), - "local validation failures reach the bounded Protocol chronology"); - const auto localRenameRejection = [&localRejections]( - std::string_view correlation) { - return std::ranges::any_of(localRejections, [correlation]( - const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == "local result" && - diagnosticField(effect, "subject") == "thread/name/set" && - diagnosticField(effect, "authority") == "none" && - diagnosticField(effect, "outcome") == "ERROR" && - diagnosticField(effect, "errorCategory") == "local-validation" && - diagnosticField(effect, "correlation") == correlation && - diagnosticField(effect, "threadId") == "runtime-thread" && - diagnosticField(effect, "targetId") == "runtime-thread" && - diagnosticField(effect, "error") == - "A non-empty thread name is required"; - }); - }; - expect(localRenameRejection("missing-name-action") && - localRenameRejection("blank-name-action"), - "local rejection diagnostics preserve action correlation and safe " - "error metadata without sending a wire operation"); - - NodeAction rename{thread, NodeActionKind::Rename}; - rename.payload = {{"name", Value("Renamed once")}, - {"turnId", Value("payload-decoy-turn")}, - {"itemId", Value("payload-decoy-item")}}; - expect(sendAction(runtime.channels(), std::move(rename)), - "rename action enters the worker mailbox"); - std::optional request = bridge.receiveAppServer(); - expect( - request && request->value("method", std::string{}) == "thread/name/set" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("name", std::string{}) == "Renamed once", - "rename action emits one addressed CodexBridge request"); - if (!request) - return; - expect(waitUntil([&] { - return operationPending(runtime.graph(), request->at("id")); - }), - "emitted request has one pending graph correlation"); - expect(operationTargets(runtime.graph(), request->at("id"), thread), - "the operation retains the exact NodeRef selected by the UI action"); - { - std::optional read = runtime.graph().tryRead(); - const NodeId decoyTurn = - scopedTurnNodeId("runtime-thread", "payload-decoy-turn"); - expect(read && !read->find(decoyTurn) && - !read->find(scopedItemNodeId(decoyTurn, "payload-decoy-item")), - "payload identifiers cannot synthesize a replacement operation " - "target when an exact action target was supplied"); - } - expect(!bridge.receiveAppServer(100ms), - "non-idempotent rename is not dual-sent"); - expect(bridge.reply(*request, nlohmann::json::object()), - "matching rename response is delivered"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "matching response retires the exact pending operation"); - - NodeAction archive{thread, NodeActionKind::Archive}; - expect(sendAction(runtime.channels(), std::move(archive)), - "archive action enters the worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/archive" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread", - "archive action emits one addressed CodexBridge request"); - if (request) { - expect(!bridge.receiveAppServer(100ms), - "non-idempotent archive is not dual-sent"); - expect(bridge.reply(*request, nlohmann::json::object()), - "archive response is delivered"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "archive response correlates to and retires its operation"); - } - runtime.drainNotifications(); -} + bool setProviderGeneration(std::uint64_t generation) { + return send( + {{"kind", "bridge.provider"}, {"state", "ready"}, {"providerGeneration", generation}, {"seq", nextSequence_++}}); + } -void remainingUiCommandFamiliesUseExactWirePaths(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), - "remaining UI command coverage has a stable thread target"); - if (!thread) - return; - - NodeRef wrongHistoryTarget; - { - auto write = runtime.graph().write(); - NodeState wrongTargetState; - wrongTargetState.fields = {{"type", Value("agentMessage")}, - {"threadId", Value("runtime-thread")}}; - wrongHistoryTarget = write.upsert({NodeKind::Item, "wrong-history-target"}, - std::move(wrongTargetState)); - write.setField(thread, "historyNextCursor", Value("graph-history-cursor")); - static_cast(write.finish()); - } - NodeAction wrongHistory{wrongHistoryTarget, NodeActionKind::LoadHistory}; - expect(sendAction(runtime.channels(), std::move(wrongHistory)), - "a malformed history target reaches typed validation"); - expect(!bridge.receiveAppServer(100ms), - "history loading rejects a non-Thread target before wire dispatch"); - - NodeAction history{thread, NodeActionKind::LoadHistory}; - history.payload = {{"cursor", Value("payload-decoy-cursor")}, - {"limit", Value(std::uint64_t{23})}}; - expect(sendAction(runtime.channels(), std::move(history)), - "history paging enters the typed worker mailbox"); - std::optional request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/turns/list" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("cursor", std::string{}) == - "graph-history-cursor" && - request->at("params").value("limit", 0) == 80 && - request->at("params").value("sortDirection", std::string{}) == - "desc" && - request->at("params").value("itemsView", std::string{}) == - "summary", - "Load More derives one scoped page from authoritative graph state"); - if (request) { - expect(operationTargets(runtime.graph(), request->at("id"), thread), - "history paging preserves its exact thread NodeRef"); - NodeAction duplicate{thread, NodeActionKind::LoadHistory}; - expect(sendAction(runtime.channels(), std::move(duplicate)), - "a duplicate history action reaches the worker"); - expect(!bridge.receiveAppServer(100ms), - "the live graph operation is the history single-flight gate"); - expect(bridge.replyError(*request, -32044, "temporary history failure"), - "history paging exposes a retryable provider failure"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "history paging failure retires its exact operation"); - - NodeAction retry{thread, NodeActionKind::LoadHistory}; - retry.payload = {{"cursor", Value("different-decoy-cursor")}, - {"limit", Value(std::uint64_t{7})}}; - expect(sendAction(runtime.channels(), std::move(retry)), - "a failed history operation can be retried"); - request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/turns/list" && - request->at("params").value("cursor", std::string{}) == - "graph-history-cursor" && - request->at("params").value("limit", 0) == 80, - "history retry preserves the same authoritative page demand"); - if (request) - expect( - bridge.reply(*request, - {{"data", nlohmann::json::array( - {{{"id", "paged-runtime-turn"}, - {"items", nlohmann::json::array()}}})}, - {"nextCursor", nullptr}}), - "the retried history page decodes its typed result"); - std::optional itemPage = bridge.receiveAppServer(); - expect(itemPage && - itemPage->value("method", std::string{}) == - "thread/items/list" && - itemPage->at("params").value("threadId", std::string{}) == - "runtime-thread" && - itemPage->at("params").value("turnId", std::string{}) == - "paged-runtime-turn" && - itemPage->at("params").value("limit", 0) == 80 && - itemPage->at("params").value("sortDirection", std::string{}) == - "desc", - "turn summaries schedule one bounded item page"); - if (itemPage) - expect(bridge.reply(*itemPage, {{"data", nlohmann::json::array()}, - {"nextCursor", "older-items"}}), - "item pagination retains its continuation"); - itemPage = bridge.receiveAppServer(); - expect(itemPage && - itemPage->value("method", std::string{}) == - "thread/items/list" && - itemPage->at("params").value("cursor", std::string{}) == - "older-items", - "item pagination continues through the provider cursor"); - if (itemPage) - expect(bridge.reply(*itemPage, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the final item page completes bounded hydration"); - } - expect(!bridge.receiveAppServer(100ms), - "history paging is never duplicated on the wire"); - - NodeAction fork{thread, NodeActionKind::Fork}; - expect(sendAction(runtime.channels(), std::move(fork)), - "fork enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/fork" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("excludeTurns", false), - "fork encodes one request addressed by the supplied NodeRef"); - if (request) { - expect(operationTargets(runtime.graph(), request->at("id"), thread), - "fork preserves its exact thread NodeRef"); - expect(bridge.replyError(*request, -32043, "focused fork rejection"), - "fork decodes a typed provider error"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "fork error retires its correlated operation"); - } - expect(!bridge.receiveAppServer(100ms), "fork is never dual-sent"); - NodeAction invalidFork{thread, NodeActionKind::Fork}; - invalidFork.payload.emplace("lastTurnId", Value("missing-boundary")); - expect(sendAction(runtime.channels(), std::move(invalidFork)), "stale boundary reaches worker validation"); - expect(!bridge.receiveAppServer(100ms), "missing turn cannot silently fall back to a full-thread fork"); - - const auto archivedIs = [&](bool expected) { - std::optional read = runtime.graph().tryRead(); - if (!read || read->find(thread->id()) != thread) - return false; - const auto state = read->state(thread); - const auto archived = state->fields.find("archived"); - return archived != state->fields.end() && archived->second.asBool() && - *archived->second.asBool() == expected; - }; - expect(bridge.appServerNotification("thread/archived", - {{"threadId", "runtime-thread"}}) && - waitUntil([&] { return archivedIs(true); }), - "unarchive coverage starts from authoritative archived state"); - NodeAction unarchive{thread, NodeActionKind::Unarchive}; - expect(sendAction(runtime.channels(), std::move(unarchive)), - "unarchive enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/unarchive" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread", - "unarchive encodes one request addressed by the supplied NodeRef"); - if (request) { - expect(operationTargets(runtime.graph(), request->at("id"), thread), - "unarchive preserves its exact thread NodeRef"); - expect(bridge.reply(*request, nlohmann::json::object()), - "unarchive decodes its typed result"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "unarchive result retires its correlated operation"); - } - expect(!bridge.receiveAppServer(100ms), "unarchive is never dual-sent"); - expect(bridge.appServerNotification("thread/unarchived", - {{"threadId", "runtime-thread"}}) && - waitUntil([&] { return archivedIs(false); }), - "authoritative unarchive restores the thread for prompt coverage"); - - RuntimeAction create{RuntimeActionKind::CreateThread}; - create.correlation = "wire-create-correlation"; - create.promptText = "Create and send exactly once"; - create.attachments.push_back( - {"/tmp/wire-image.png", "wire-image.png", "image/png", std::nullopt}); - create.payload = { - {"requestedName", Value("Unsupported ephemeral name")}, - {"sectionId", Value("wire-section")}, - {"threadStart", - Value(Value::Object{ - {"cwd", Value("/tmp/wire-create")}, - {"projectId", Value("wire-project")}, - {"baseInstructions", Value("Ephemeral base instructions")}, - {"developerInstructions", Value("Ephemeral developer instructions")}, - {"ephemeral", Value(true)}})}, - {"turnStart", - Value(Value::Object{{"approvalPolicy", Value("on-request")}})}}; - expect(sendAction(runtime.channels(), std::move(create)), - "new-thread prompt enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect( - request && request->value("method", std::string{}) == "thread/start" && - request->at("params").value("cwd", std::string{}) == - "/tmp/wire-create" && - request->at("params").value("baseInstructions", std::string{}) == - "Ephemeral base instructions" && - request->at("params").value("developerInstructions", std::string{}) == - "Ephemeral developer instructions" && - request->at("params").value("ephemeral", false) && - request->at("params").value("projectId", "") == "wire-project" && - !request->at("params").contains("historyMode"), - "Create Thread keeps ephemeral instructions and leaves app-server's " - "legacy history default authoritative"); - if (!request) { - runtime.drainNotifications(); - return; - } - expect(bridge.reply(*request, {{"thread", - {{"id", "wire-created-thread"}, - {"name", "Wire created"}, - {"status", "idle"}, - {"turns", nlohmann::json::array()}}}}), - "thread/start decodes the canonical created thread"); - - request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/section/move" && - request->at("params").value("sectionId", "") == "wire-section", - "new-thread section assignment follows successful creation"); - if (request) - expect(bridge.replyError(*request, -32000, "section assignment failed"), - "section failure retains the created thread and does not resend the " - "first prompt"); - request = bridge.receiveAppServer(); - const nlohmann::json input = - request && request->contains("params") - ? request->at("params").value("input", nlohmann::json::array()) - : nlohmann::json::array(); - expect(request && request->value("method", std::string{}) == "turn/start" && - request->at("params").value("threadId", std::string{}) == - "wire-created-thread" && - request->at("params").value("approvalPolicy", std::string{}) == - "on-request" && - input.size() == 2 && - input.at(0).value("type", std::string{}) == "text" && - input.at(0) - .value("text", std::string{}) - .find("Create and send exactly once") != - std::string::npos && - input.at(1).value("type", std::string{}) == "localImage" && - input.at(1).value("path", std::string{}) == "/tmp/wire-image.png", - "the first ephemeral prompt skips metadata updates and moves text, " - "options, and attachment into one turn/start request"); - if (request) { - expect(bridge.reply(*request, {{"turn", - {{"id", "wire-created-turn"}, - {"status", "inProgress"}, - {"items", nlohmann::json::array()}}}}), - "turn/start decodes its canonical turn result"); - } - expect(!bridge.receiveAppServer(100ms), - "the first new-thread prompt is never dual-sent"); - - const NodeRef created = - findNode(runtime.graph(), {NodeKind::Thread, "wire-created-thread"}); - const NodeRef active = - findNode(runtime.graph(), - scopedTurnNodeId("wire-created-thread", "wire-created-turn")); - expect(created && active, - "created-thread command results retain natural thread and turn nodes"); - if (created && active) { - NodeAction steer{created, NodeActionKind::SubmitPrompt}; - steer.promptText = "Steer the exact active turn"; - steer.payload.emplace("model", "must-not-steer"); - steer.payload.emplace("summary", "must-not-steer"); - expect(sendAction(runtime.channels(), std::move(steer)), - "active-turn steering enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "turn/steer" && - request->at("params").value("threadId", std::string{}) == - "wire-created-thread" && - request->at("params").value("expectedTurnId", std::string{}) == - "wire-created-turn" && - !request->at("params").contains("model") && - !request->at("params").contains("summary"), - "Submit while active encodes one turn/steer without start settings"); - if (request) - expect(bridge.reply(*request, {{"turnId", "wire-created-turn"}}), - "turn/steer decodes its typed result"); - expect(!bridge.receiveAppServer(100ms), "steering is never dual-sent"); - NodeAction imageOnly{created, NodeActionKind::SubmitPrompt}; - imageOnly.attachments.push_back({"/tmp/pasted-image.png", - "pasted-image.png", "image/png", - std::nullopt}); - expect(sendAction(runtime.channels(), std::move(imageOnly)), - "image-only steering enters the existing worker admission path"); - request = bridge.receiveAppServer(); - expect( - request && request->value("method", std::string{}) == "turn/steer" && - request->at("params").at("input") == - nlohmann::json::array({{{"type", "localImage"}, - {"path", "/tmp/pasted-image.png"}}}), - "image-only input has a localImage and no fabricated empty text item"); - if (request) - expect(bridge.reply(*request, {{"turnId", "wire-created-turn"}}), - "image-only steering decodes its typed result"); - } - - expect(bridge.appServerNotification("turn/completed", - {{"threadId", "wire-created-thread"}, - {"turn", - {{"id", "wire-created-turn"}, - {"status", "completed"}, - {"items", nlohmann::json::array()}}}}), - "created active turn receives its authoritative completion"); - replyAccountUsage(bridge); - - if (created) { - NodeAction remove{created, NodeActionKind::Delete}; - expect(sendAction(runtime.channels(), std::move(remove)), - "delete enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/delete" && - request->at("params").value("threadId", std::string{}) == - "wire-created-thread", - "delete encodes one request addressed by the supplied NodeRef"); - if (request) { - expect(operationTargets(runtime.graph(), request->at("id"), created), - "delete preserves its exact thread NodeRef"); - expect(bridge.reply(*request, nlohmann::json::object()), - "delete decodes its typed result"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), request->at("id")); - }), - "delete result retires its correlated operation"); - } - expect(!bridge.receiveAppServer(100ms), "delete is never dual-sent"); - expect(bridge.appServerNotification( - "thread/deleted", {{"threadId", "wire-created-thread"}}) && - waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - return read && !read->find(created->id()); - }), - "authoritative delete retires the exact created thread"); - } - runtime.drainNotifications(); -} + private: + std::string path_; + int listener_ = -1; + int client_ = -1; + std::uint64_t nextSequence_ = 4; + std::string buffered_; + }; + + class RunningRuntime final { + public: + explicit RunningRuntime(Configuration& configuration) + : configuration_(configuration) { + } -void itemHistoryHydrationHasAnExactConcurrencyCeiling(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), - "bounded item hydration has a stable thread target"); - if (!thread) - return; - { - auto write = runtime.graph().write(); - write.setField(thread, "historyNextCursor", Value("bounded-items-page")); - static_cast(write.finish()); - } - expect(sendAction(runtime.channels(), - NodeAction{thread, NodeActionKind::LoadHistory}), - "bounded item hydration enters the worker mailbox"); - const std::optional turnPage = bridge.receiveAppServer(); - expect(turnPage && - turnPage->value("method", std::string{}) == "thread/turns/list", - "bounded item hydration starts from one turn page"); - if (!turnPage) - return; - nlohmann::json turns = nlohmann::json::array(); - for (int index = 0; index < 10; ++index) - turns.push_back({{"id", "bounded-turn-" + std::to_string(index)}, - {"items", nlohmann::json::array()}}); - expect(bridge.reply(*turnPage, - {{"data", std::move(turns)}, {"nextCursor", nullptr}}), - "ten turn summaries are delivered in one bounded page"); - - std::vector firstWave; - for (int index = 0; index < 8; ++index) { - const std::optional request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/items/list", - "the first item-hydration wave contains eight item pages"); - if (request) - firstWave.push_back(*request); - } - expect(firstWave.size() == 8, - "the native item scheduler fills its exact eight-request ceiling"); - expect(!bridge.receiveAppServer(100ms), - "a ninth item page waits while eight requests remain in flight"); - if (firstWave.size() != 8) - return; - - expect(bridge.reply(firstWave[0], {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "one completed item page releases one scheduler slot"); - const std::optional ninth = bridge.receiveAppServer(); - expect(ninth && ninth->value("method", std::string{}) == "thread/items/list", - "one completion admits exactly the ninth item page"); - expect(bridge.reply(firstWave[1], {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "a second completed item page releases the final queued turn"); - const std::optional tenth = bridge.receiveAppServer(); - expect(tenth && tenth->value("method", std::string{}) == "thread/items/list", - "the second completion admits exactly the tenth item page"); - for (std::size_t index = 2; index < firstWave.size(); ++index) - expect(bridge.reply(firstWave[index], {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the remaining first-wave item page completes"); - if (ninth) - expect(bridge.reply(*ninth, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the ninth item page completes"); - if (tenth) - expect(bridge.reply(*tenth, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the tenth item page completes"); - expect(!bridge.receiveAppServer(100ms), - "item hydration emits no extra pages after the ten turns complete"); - runtime.drainNotifications(); -} + ~RunningRuntime() { + stop(); + } -void conversationSnapshotsShareOneAdmissionAuthority(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), - "snapshot single-flight coverage has a stable thread target"); - if (!thread) - return; - - { - auto write = runtime.graph().write(); - write.setField(thread, "historyHasMore", Value(true)); - write.setField(thread, "historyNextCursor", Value("read-overlap-cursor")); - static_cast(write.finish()); - } - - expect(sendAction(runtime.channels(), - NodeAction{thread, NodeActionKind::Reload}), - "reload enters the worker before competing Load More coverage"); - const std::optional resumeRequest = bridge.receiveAppServer(); - expect(resumeRequest && - resumeRequest->value("method", std::string{}) == "thread/resume" && - resumeRequest->at("params").value("excludeTurns", false), - "reload owns one metadata-only resume before its history page"); - expect(sendAction(runtime.channels(), - NodeAction{thread, NodeActionKind::LoadHistory}), - "Load More reaches admission while reload resume is pending"); - expect(!bridge.receiveAppServer(100ms), - "reload resume suppresses a competing history page"); - if (resumeRequest) { - expect(bridge.reply(*resumeRequest, nlohmann::json::object()), - "metadata-only reload resume completes"); - const std::optional readRequest = bridge.receiveAppServer(); - expect(readRequest && - readRequest->value("method", std::string{}) == - "thread/turns/list" && - readRequest->at("params").value("itemsView", std::string{}) == - "summary", - "reload owns one bounded conversation snapshot"); - if (readRequest) - expect(bridge.reply(*readRequest, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the sole reload page completes"); - } - - { - auto write = runtime.graph().write(); - write.setField(thread, "historyHasMore", Value(true)); - write.setField(thread, "historyNextCursor", Value("page-overlap-cursor")); - static_cast(write.finish()); - } - expect(sendAction(runtime.channels(), - NodeAction{thread, NodeActionKind::LoadHistory}), - "Load More enters the worker before competing reload coverage"); - const std::optional pageRequest = bridge.receiveAppServer(); - expect(pageRequest && - pageRequest->value("method", std::string{}) == "thread/turns/list", - "Load More owns one paginated conversation snapshot"); - expect(sendAction(runtime.channels(), - NodeAction{thread, NodeActionKind::Reload}), - "reload reaches admission while thread/turns/list is pending"); - expect(!bridge.receiveAppServer(100ms), - "thread/turns/list suppresses a competing reload snapshot"); - if (pageRequest) - expect(bridge.reply(*pageRequest, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the sole paginated snapshot completes"); - runtime.drainNotifications(); -} + RunningRuntime(const RunningRuntime&) = delete; + RunningRuntime& operator=(const RunningRuntime&) = delete; -void firstNavigationDrainsTheExistingHistoryPager(UnixBridge& bridge, RunningRuntime& runtime) { - NodeRef thread; - { - auto write = runtime.graph().write(); - NodeState state; - state.fields = {{"historyHasMore", Value(true)}, {"historyNextCursor", Value("first-1")}}; - thread = write.upsert({NodeKind::Thread, "first-navigation"}, std::move(state)); - static_cast(write.finish()); - } - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", Value(true)}}, {}}), - "First enters the existing typed history action"); - for (int page = 1; page <= 3; ++page) { - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/turns/list" && - request->at("params").value("cursor", "") == "first-" + std::to_string(page) && - request->at("params").value("sortDirection", "") == "desc", - "First sequentially follows authoritative cursors through the existing history pager"); - if (request) { - const nlohmann::json cursor = page == 3 ? nlohmann::json(nullptr) : nlohmann::json("first-" + std::to_string(page + 1)); - expect(bridge.reply(*request, {{"data", nlohmann::json::array()}, {"nextCursor", cursor}}), "First receives an earlier page"); + void start() { + worker_ = std::thread([this] { + result_.store(runClientRuntime(configuration_, graph_, channels_, false), std::memory_order_release); + }); + } + + void stop() { + if (!worker_.joinable()) + return; + ShutdownRequest shutdown; + for (int attempt = 0; attempt != 1000; ++attempt) { + if (messageAdmitted(channels_.sendShutdown(shutdown))) + break; + std::this_thread::sleep_for(1ms); + } + worker_.join(); + } + + NodeGraph& graph() noexcept { + return graph_; + } + ThreadChannels& channels() noexcept { + return channels_; + } + + std::optional workerCpuTime() { + if (!worker_.joinable()) + return std::nullopt; + clockid_t clock{}; + if (::pthread_getcpuclockid(worker_.native_handle(), &clock) != 0) + return std::nullopt; + timespec value{}; + if (::clock_gettime(clock, &value) != 0) + return std::nullopt; + return std::chrono::seconds(value.tv_sec) + std::chrono::nanoseconds(value.tv_nsec); + } + + void drainNotifications() { + static_cast(channels_.drainWorkerToQtWake()); + WorkerToQtMessage message; + while (channels_.tryReceiveForQt(message)) + message = WorkerStopped{}; + } + + std::vector takeProtocolDiagnostics() { + std::vector diagnostics; + static_cast(channels_.drainWorkerToQtWake()); + WorkerToQtMessage message; + while (channels_.tryReceiveForQt(message)) { + if (ProtocolDiagnostic* diagnostic = std::get_if(&message)) { + if (diagnostic->diagnosticBatch.empty()) { + diagnostics.emplace_back(std::move(*diagnostic)); + } else { + for (Value::Object& details : diagnostic->diagnosticBatch) + diagnostics.push_back({std::move(details), {}}); + } + } + message = WorkerStopped{}; + } + return diagnostics; + } + + private: + Configuration& configuration_; + NodeGraph graph_; + ThreadChannels channels_; + std::thread worker_; + std::atomic result_{-1}; + }; + + template + bool waitUntil(Predicate predicate, std::chrono::milliseconds timeout = 2s) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (predicate()) + return true; + std::this_thread::sleep_for(2ms); + } + return predicate(); } - } - expect(!bridge.receiveAppServer(100ms), "First stops paging at the authoritative beginning"); - { - auto write = runtime.graph().write(); - write.setField(thread, "historyNextCursor", Value("first-retry")); - write.setField(thread, "historyHasMore", Value(true)); - static_cast(write.finish()); - } - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", Value(true)}}, {}}), - "First can request retained earlier history again"); - const auto failed = bridge.receiveAppServer(); - expect(failed.has_value(), "First failure coverage receives a request"); - if (failed) { - expect(bridge.replyError(*failed, -32000, "First paging failed"), "First exposes history failure"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), failed->at("id")); - }), - "First failure retires its operation"); - } - expect(!bridge.receiveAppServer(100ms), "First does not loop or automatically retry after failure"); - runtime.drainNotifications(); -} -void staleHistoryFailureIsSemanticallyInert(UnixBridge &bridge, - RunningRuntime &runtime) { - constexpr std::string_view ThreadId = "stale-history-thread"; - constexpr std::string_view ErrorText = - "late history failure must remain invisible"; - NodeRef thread; - { - auto write = runtime.graph().write(); - NodeState state; - state.fields = {{"historyHasMore", Value(true)}, - {"historyNextCursor", Value("stale-cursor")}}; - thread = write.upsert({NodeKind::Thread, std::string(ThreadId)}, - std::move(state)); - static_cast(write.finish()); - } - static_cast(runtime.takeProtocolDiagnostics()); - - NodeAction action{thread, NodeActionKind::LoadHistory}; - expect(sendAction(runtime.channels(), std::move(action)), - "stale-history coverage admits one exact action"); - const std::optional request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/turns/list" && - operationTargets(runtime.graph(), request->at("id"), thread), - "stale-history coverage observes the target-owned Operation"); - if (!request) - return; - - { - auto write = runtime.graph().write(); - write.remove(thread); - static_cast(write.finish()); - } - expect(operationRetired(runtime.graph(), request->at("id")), - "removing the history target cascades its pending Operation"); - static_cast(runtime.takeProtocolDiagnostics()); - expect(bridge.replyError(*request, -32055, std::string(ErrorText)), - "the retired history request receives its late provider failure"); - expect(bridge.appServerNotification( - "thread/started", {{"thread", - {{"id", "stale-history-barrier"}, - {"name", "Stale history barrier"}}}}) && - waitUntil([&] { - return static_cast( - findNode(runtime.graph(), - {NodeKind::Thread, "stale-history-barrier"})); - }), - "a later wire frame proves the late callback has settled"); - - const std::vector effects = - runtime.takeProtocolDiagnostics(); - expect(std::ranges::any_of( - effects, - [](const ProtocolDiagnostic &effect) { - return diagnosticField(effect, "direction") == "client error" && - diagnosticField(effect, "subject") == "thread/turns/list"; - }), - "the late history failure remains visible to protocol diagnostics"); - const NodeRef notice = - findNode(runtime.graph(), {NodeKind::Notice, "local-worker-notice"}); - const std::optional noticeRead = - runtime.graph().tryRead(); - const Value *noticeMessage = - notice && noticeRead - ? valueMember(*noticeRead->state(notice), "message") - : nullptr; - expect(!noticeMessage || !noticeMessage->asString() || - noticeMessage->asString()->find(ErrorText) == std::string::npos, - "a stale history failure cannot become authoritative visible notice " - "state"); - expect(!findNode(runtime.graph(), {NodeKind::Thread, std::string(ThreadId)}), - "the stale history result cannot recreate its retired thread"); -} + NodeRef findNode(NodeGraph& graph, NodeId id) { + NodeRef found; + static_cast(waitUntil([&] { + std::optional read = graph.tryRead(); + if (!read) + return false; + found = read->find(id); + return static_cast(found); + })); + return found; + } -void forksPersistSourceMembership(UnixBridge& bridge, RunningRuntime& runtime) { - std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/fork-membership.json"); - const auto fixtures = nlohmann::json::parse(input); - const auto section = [](const std::string& id) { - return id.empty() ? nlohmann::json(nullptr) : nlohmann::json{{"id", id}, {"name", id}}; - }; - for (const auto& fixture : fixtures) { - const std::string name = fixture.at("name"); - const std::string sourceId = "membership-source-" + name; - const std::string forkId = "membership-fork-" + name; - const std::string projectId = fixture.at("projectId"), sectionId = fixture.at("sectionId"); - const std::string originalProject = fixture.at("forkProjectId"), originalSection = fixture.at("forkSectionId"); - const std::string rejected = fixture.value("reject", ""); - const nlohmann::json source{{"id", sourceId}, - {"name", "Find Slides"}, - {"cwd", "/source-workspace"}, - {"projectId", projectId}, - {"section", section(sectionId)}, - {"status", "idle"}, - {"forkedFromId", nullptr}, - {"parentThreadId", nullptr}, - {"turns", - nlohmann::json::array({{{"id", "first"}, {"status", "completed"}}, - {{"id", "middle"}, {"status", "completed"}}, - {{"id", "last"}, {"status", "completed"}}})}}; - expect(bridge.appServerNotification("thread/started", {{"thread", source}}), name + ": source metadata delivered"); - const auto sourceNode = findNode(runtime.graph(), {NodeKind::Thread, sourceId}); - expect(static_cast(sourceNode), name + ": source exists"); - NodeAction action{sourceNode, NodeActionKind::Fork}; - if (fixture.contains("lastTurnId")) { - action.payload.emplace("lastTurnId", Value(fixture.at("lastTurnId").get())); + NodeRef findRetiredNode(NodeGraph& graph, const NodeId& id) { + NodeRef found; + static_cast(waitUntil([&] { + std::optional read = graph.tryRead(); + if (!read) + return false; + for (std::size_t index = 0; index < read->retiredCount(); ++index) { + const NodeRef node = read->retiredAt(index); + if (node && node->id() == id) { + found = node; + return true; + } + } + return false; + })); + return found; } - const bool ephemeral = fixture.value("ephemeral", false); - if (!ephemeral) { - action.payload.emplace("requestedName", Value("Find Slides (fork 1)")); + + bool operationPending(NodeGraph& graph, const nlohmann::json& requestId) { + const ProtocolRequestId id = requestIdFromJson(requestId); + std::optional read = graph.tryRead(); + if (!read) + return false; + const NodeRef operation = read->find({NodeKind::Operation, id.canonical()}); + return operation && read->state(operation)->status == NodeStatus::Pending; } - if (fixture.at("options").get()) { - action.payload.emplace("cwd", Value("/fork-workspace")); - action.payload.emplace("baseInstructions", Value("Fork base")); - action.payload.emplace("developerInstructions", Value("Fork developer")); - action.payload.emplace("ephemeral", Value(ephemeral)); + + bool operationTargets(NodeGraph& graph, const nlohmann::json& requestId, const NodeRef& target) { + const ProtocolRequestId id = requestIdFromJson(requestId); + std::optional read = graph.tryRead(); + if (!read) + return false; + const NodeRef operation = read->find({NodeKind::Operation, id.canonical()}); + return operation && read->related(target, RelationKind::PendingOperation) == std::vector{operation}; } - expect(sendAction(runtime.channels(), std::move(action)), name + ": fork admitted"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/fork", name + ": one fork request"); - if (request) { - expect(request->at("params").value("lastTurnId", "") == fixture.value("lastTurnId", ""), - name + ": fork retains the selected inclusive boundary"); - expect(static_cast(findNode(runtime.graph(), scopedTurnNodeId(sourceId, "last"))), - name + ": source retains later history"); - expect(request->at("params").value("cwd", "") == (fixture.at("options").get() ? "/fork-workspace" : ""), - name + ": workspace option is independent of grouping"); - if (fixture.value("moveSource", false)) { - auto moved = source; - moved["projectId"] = "moved-project"; - moved["section"] = section("moved-section"); - expect(bridge.appServerNotification("thread/started", {{"thread", moved}}), name + ": source moved in flight"); - } - nlohmann::json forked{{"id", forkId}, - {"name", "Provider title"}, - {"cwd", "/fork-workspace"}, - {"projectId", originalProject}, - {"section", section(originalSection)}, - {"forkedFromId", sourceId}, - {"parentThreadId", nullptr}, - {"status", "idle"}, - {"turns", nlohmann::json::array()}}; - expect(bridge.reply(*request, {{"thread", forked}}), name + ": fork result delivered"); - std::vector assignments; - std::unordered_map methods; - std::optional history; - const int expectedCount = 1 + !ephemeral + (projectId != originalProject) + (sectionId != originalSection); - for (int index = 0; index < expectedCount; ++index) { - const auto pending = bridge.receiveAppServer(); - expect(static_cast(pending), name + ": completion request delivered"); - if (pending) { - const auto method = pending->value("method", ""); - ++methods[method]; - expect(pending->at("params").value("threadId", "") == forkId, name + ": completion targets the fork"); - if (method == "thread/metadata/update" || method == "thread/section/move") { - assignments.push_back(*pending); - } else if (method == "thread/turns/list") { - history = *pending; - } else { - expect(method == "thread/name/set", name + ": no unexpected completion operation"); - expect(bridge.reply(*pending, nlohmann::json::object()), name + ": rename acknowledged"); - } + + bool operationRetired(NodeGraph& graph, const nlohmann::json& requestId) { + const ProtocolRequestId id = requestIdFromJson(requestId); + std::optional read = graph.tryRead(); + return read && !read->find({NodeKind::Operation, id.canonical()}); + } + + bool interactionRetired(NodeGraph& graph, const NodeRef& interaction) { + if (!interaction) + return false; + std::optional read = graph.tryRead(); + if (!read || read->find(interaction->id())) + return false; + for (std::size_t index = 0; index < read->retiredCount(); ++index) + if (read->retiredAt(index) == interaction) + return true; + return false; + } + + bool sendAction(ThreadChannels& channels, NodeAction action) { + return messageAdmitted(channels.sendNodeAction(action)); + } + + bool sendAction(ThreadChannels& channels, RuntimeAction action) { + return messageAdmitted(channels.sendRuntimeAction(action)); + } + + nlohmann::json listedThread() { + return {{"id", "runtime-thread"}, + {"name", "Runtime dispatch"}, + {"status", "idle"}, + {"historyMode", "legacy"}, + {"createdAt", 1}, + {"updatedAt", 2}, + {"turns", nlohmann::json::array()}}; + } + + bool rejectedAutomaticCurrentTimeResponseIsTerminal(UnixBridge& bridge, RunningRuntime& runtime) { + constexpr std::string_view RequestId = "clock-before-identity"; + if (!bridge.appServerRequest(std::string(RequestId), "currentTime/read", {{"threadId", "pre-identity-thread"}})) + return false; + + // The transport is attached, but CodexBridge has not received its + // bridge.connection identity yet. Its sender therefore deterministically + // rejects the automatic response without disconnecting the worker. + const NodeId interactionId{NodeKind::Interaction, ProtocolRequestId(std::string(RequestId)).canonical()}; + const NodeRef retired = findRetiredNode(runtime.graph(), interactionId); + std::optional read = runtime.graph().tryRead(); + const bool terminal = retired && read && !read->find(interactionId); + read.reset(); + return terminal && !bridge.receiveAppServer(100ms); + } + + bool establishProvider(UnixBridge& bridge, RunningRuntime& runtime) { + RuntimeAction configure; + configure.kind = RuntimeActionKind::ConfigureConnection; + configure.payload = {{"transport", Value("unix")}, {"path", Value(bridge.path())}}; + if (!sendAction(runtime.channels(), std::move(configure))) + return false; + if (!bridge.acceptClient()) + return false; + + expect(rejectedAutomaticCurrentTimeResponseIsTerminal(bridge, runtime), + "a rejected automatic current-time response retires its interaction " + "instead of exposing an unresolvable UI action"); + + if (!bridge.send({{"kind", "bridge.connection"}, + {"event", "opened"}, + {"connectionId", "runtime-test"}, + {"role", "controller"}, + {"seq", 1}}) || + !bridge.send({{"kind", "bridge.controller"}, {"controllerConnectionId", "runtime-test"}, {"seq", 2}}) || + !bridge.send({{"kind", "bridge.provider"}, {"state", "ready"}, {"providerGeneration", 1}, {"seq", 3}})) + return false; + + std::unordered_map methods; + for (int count = 0; count != 8; ++count) { + std::optional request = bridge.receiveAppServer(); + if (!request || !request->contains("id")) + return false; + const std::string method = request->value("method", std::string{}); + ++methods[method]; + nlohmann::json result{{"data", nlohmann::json::array()}}; + if (method == "account/usage/read") + result = {{"summary", {{"lifetimeTokens", 12000}}}}; + if (method == "thread/list") { + const bool firstThreadPage = methods[method] == 1; + expect(request->at("params").value("sortKey", std::string{}) == "recency_at" && + request->at("params").value("sortDirection", std::string{}) == "desc" && + request->at("params").value("limit", 0) == 100 && + request->at("params").value("useStateDbOnly", false) == firstThreadPage, + "initial thread hydration requests a fast DB page followed by " + "the repair page"); + result["data"].push_back(listedThread()); + result["nextCursor"] = nullptr; } + if (method == "thread/read") { + expect(request->at("params").value("includeTurns", true) == false, + "startup lineage discovery excludes conversation turns"); + auto metadata = listedThread(); + metadata["forkedFromId"] = nullptr; + metadata["parentThreadId"] = nullptr; + result = {{"thread", metadata}}; + } + if (!bridge.reply(*request, std::move(result))) + return false; + } + return methods == std::unordered_map{{"thread/list", 2}, + {"thread/read", 1}, + {"project/list", 1}, + {"threadSection/list", 1}, + {"model/list", 1}, + {"permissionProfile/list", 1}, + {"account/usage/read", 1}} && + static_cast(findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"})); + } + + void replyAccountUsage(UnixBridge& bridge) { + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "account/usage/read", "turn completion refreshes account usage"); + if (request) + expect(bridge.reply(*request, {{"summary", {{"lifetimeTokens", 12000}}}}), + "account usage snapshot is returned without sending a prompt"); + } + + void accountUsageRefreshIsCoalescedAndAccountScoped(UnixBridge& bridge, RunningRuntime& runtime) { + const auto hasUsage = [&](std::optional expected, NodeStatus status) { + auto read = runtime.graph().tryRead(); + if (!read) + return false; + const auto node = read->find({NodeKind::Account, "account/usage/read"}); + if (!node || read->state(node)->status != status) + return false; + const auto* value = valueMember(*read->state(node), "summary"); + const auto* summary = value ? value->asObject() : nullptr; + return (summary ? signedIntegerFromValue(valueMember(*summary, "lifetimeTokens")) : std::nullopt) == expected; + }; + expect(waitUntil([&] { + return hasUsage(12000, NodeStatus::Completed); + }), + "startup retrieves account usage without a prompt"); + expect(bridge.appServerNotification("account/updated", {{"authMode", "chatgpt"}}), + "account change requests a fresh usage snapshot"); + const auto old = bridge.receiveAppServer(); + expect(old && old->value("method", "") == "account/usage/read", "account usage refresh uses the dedicated read endpoint"); + expect(bridge.appServerNotification("account/updated", {{"authMode", "apiKey"}}) && + bridge.appServerNotification("account/updated", {{"authMode", "apiKey"}}), + "overlapping account changes reach the worker"); + expect(!bridge.receiveAppServer(100ms), "overlapping refreshes share one in-flight read"); + if (old) + expect(bridge.reply(*old, {{"summary", {{"lifetimeTokens", 999999}}}}), + "an old-account response arrives after the account changed"); + const auto followup = bridge.receiveAppServer(); + expect(followup && followup->value("method", "") == "account/usage/read", "overlapping refreshes produce one follow-up read"); + if (followup) + expect(bridge.replyError(*followup, -32600, "account usage unsupported"), "an unsupported account reports its usage error"); + expect(waitUntil([&] { + return hasUsage(std::nullopt, NodeStatus::Failed); + }), + "unsupported usage stays unknown and never displays the previous account total"); + expect(!bridge.receiveAppServer(100ms), "unsupported usage does not start a retry loop"); + expect(bridge.appServerNotification("account/updated", {{"authMode", "chatgpt"}}), + "supported authentication can refresh usage again"); + replyAccountUsage(bridge); + expect(waitUntil([&] { + return hasUsage(12000, NodeStatus::Completed); + }), + "successful authentication recovers the account usage snapshot"); + } + + std::string diagnosticField(const ProtocolDiagnostic& effect, std::string_view key) { + const auto found = effect.details.find(key); + if (found == effect.details.end() || !found->second.asString()) + return {}; + return *found->second.asString(); + } + + void protocolDiagnosticsPreserveMetadataWithoutPayloads(UnixBridge& bridge, RunningRuntime& runtime) { + const std::vector initialDiagnostics = runtime.takeProtocolDiagnostics(); + expect(std::ranges::any_of(initialDiagnostics, + [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "subject") == "connection.lifecycle"; + }) && + std::ranges::any_of(initialDiagnostics, + [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "subject") == "connection.provider" && + diagnosticField(effect, "authority") == "replace"; + }), + "transport lifecycle and bridge provider diagnostics remain visible"); + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + if (!thread) + return; + + NodeAction rename{thread, NodeActionKind::Rename}; + rename.payload = {{"name", Value("authored-name-must-not-appear")}}; + expect(sendAction(runtime.channels(), std::move(rename)), "diagnostic rename enters the typed mailbox"); + const std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/name/set", + "diagnostic fixture receives the direct request"); + if (!request) + return; + expect(bridge.replyError(*request, -32041, "rename rejected safely"), "diagnostic fixture receives a benign JSON-RPC error"); + + std::vector diagnostics; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + diagnostics.insert(diagnostics.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::any_of(diagnostics, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "client error" && + diagnosticField(effect, "subject") == "thread/name/set"; + }); + }), + "request and response diagnostics cross the typed worker queue"); + + const ProtocolDiagnostic* sent = nullptr; + const ProtocolDiagnostic* failed = nullptr; + for (const ProtocolDiagnostic& effect : diagnostics) { + if (diagnosticField(effect, "subject") != "thread/name/set") + continue; + if (diagnosticField(effect, "direction") == "client request") + sent = &effect; + if (diagnosticField(effect, "direction") == "client error") + failed = &effect; + } + expect(sent && failed && diagnosticField(*sent, "source") == "CodexUI" && diagnosticField(*sent, "authority") == "none" && + diagnosticField(*sent, "threadId") == "runtime-thread" && diagnosticField(*failed, "source") == "app-server" && + diagnosticField(*failed, "authority") == "none" && diagnosticField(*failed, "threadId") == "runtime-thread" && + diagnosticField(*failed, "outcome") == "ERROR" && diagnosticField(*failed, "errorCategory") == "json-rpc" && + diagnosticField(*failed, "errorCode") == "-32041" && diagnosticField(*failed, "error") == "rename rejected safely" && + diagnosticField(*sent, "correlation") == diagnosticField(*failed, "correlation"), + "diagnostics preserve direction, source, semantic authority, scope, " + "correlation, and safe errors"); + + for (const ProtocolDiagnostic& effect : diagnostics) { + const std::string rendered = + diagnosticField(effect, "subject") + diagnosticField(effect, "error") + diagnosticField(effect, "threadId"); + expect(rendered.find("authored-name-must-not-appear") == std::string::npos, + "diagnostics never copy an authored request payload"); + } + + RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; + expect(sendAction(runtime.channels(), std::move(refresh)), "secret-error fixture enters the typed mailbox"); + const std::optional secretRequest = bridge.receiveAppServer(); + expect(secretRequest && secretRequest->value("method", std::string{}) == "thread/list", + "secret-error fixture receives the direct request"); + if (secretRequest) { + expect(secretRequest->at("params").value("useStateDbOnly", false), + "the foreground diagnostic request uses the fast DB path"); + expect(bridge.replyError(*secretRequest, -32042, "Bearer sk-runtime-secret eyJabc.def.ghi"), + "secret-shaped error reaches the runtime"); + std::vector secretDiagnostics; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + secretDiagnostics.insert( + secretDiagnostics.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::any_of(secretDiagnostics, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "client error" && + diagnosticField(effect, "subject") == "thread/list"; + }); + }), + "secret-shaped error produces bounded metadata"); + bool redactedSecretError = false; + for (const ProtocolDiagnostic& effect : secretDiagnostics) { + if (diagnosticField(effect, "subject") != "thread/list" || diagnosticField(effect, "direction") != "client error") + continue; + redactedSecretError = diagnosticField(effect, "error") == "[redacted error detail]"; + } + expect(redactedSecretError, "credential-shaped protocol error detail is redacted"); + const std::optional repairRequest = bridge.receiveAppServer(); + expect(repairRequest && repairRequest->value("method", std::string{}) == "thread/list" && + !repairRequest->at("params").value("useStateDbOnly", true), + "a failed fast DB request still falls back to repair scanning"); + if (repairRequest) + expect(bridge.reply(*repairRequest, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "repair fallback completes after the fast-path failure"); + } + + const auto readAuthority = [&](bool insertInterveningFrame) { + runtime.drainNotifications(); + NodeAction reload{thread, NodeActionKind::Reload}; + expect(sendAction(runtime.channels(), std::move(reload)), "paginated diagnostic reload enters the typed mailbox"); + const std::optional resumeRequest = bridge.receiveAppServer(); + expect(resumeRequest && resumeRequest->value("method", std::string{}) == "thread/resume" && + resumeRequest->at("params").value("excludeTurns", false), + "diagnostic reload establishes metadata-only live state first"); + if (!resumeRequest) + return std::string{}; + expect(bridge.reply(*resumeRequest, nlohmann::json::object()), "metadata-only settings refresh response is delivered"); + const std::optional readRequest = bridge.receiveAppServer(); + expect(readRequest && readRequest->value("method", std::string{}) == "thread/turns/list", + "diagnostic reload pages history after metadata resume"); + if (!readRequest) + return std::string{}; + expect(readRequest->at("params").value("itemsView", std::string{}) == "summary", + "thread hydration separates bounded turn summaries from items"); + if (insertInterveningFrame) { + expect(bridge.appServerNotification("thread/name/updated", + {{"threadId", "runtime-thread"}, {"name", "Changed while pagination was pending"}}), + "intervening provider delta is delivered before pagination"); + } + expect(bridge.reply(*readRequest, {{"data", listedThread().at("turns")}, {"nextCursor", nullptr}}), + "turn summary diagnostic response is delivered"); + + const ProtocolRequestId readOperation = requestIdFromJson(readRequest->at("id")); + expect(waitUntil([&] { + const std::optional read = runtime.graph().tryRead(); + if (!read) + return false; + const NodeRef current = read->find({NodeKind::Thread, "runtime-thread"}); + if (!current) + return false; + const auto state = read->state(current); + return !read->find({NodeKind::Operation, readOperation.canonical()}) && + exactStringFromValue(valueMember(*state, "hydrationState")) == "ready" && + !valueMember(*state, "hydrationError"); + }), + "the exact bridge turn page retires its Operation and makes the " + "same thread ready without a synthetic failure"); + + std::string authority; + expect(waitUntil([&] { + for (ProtocolDiagnostic& effect : runtime.takeProtocolDiagnostics()) { + if (diagnosticField(effect, "direction") == "client result" && + diagnosticField(effect, "subject") == "thread/turns/list") + authority = diagnosticField(effect, "authority"); + } + return !authority.empty(); + }), + "thread/turns/list result retains its diagnostic authority"); + return authority; + }; + expect(readAuthority(true) == "merge", "an intervening provider frame retains paginated merge authority"); + expect(readAuthority(false) == "merge", "an immediately correlated page retains paginated merge authority"); + + runtime.drainNotifications(); + expect(bridge.appServerNotification("skills/changed", nlohmann::json::object()), + "state-neutral catalog invalidation is delivered"); + expect(bridge.appServerNotification("thread/goal/cleared", {{"threadId", "runtime-thread"}}), + "authoritative removal notification is delivered"); + std::vector notificationDiagnostics; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + notificationDiagnostics.insert( + notificationDiagnostics.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::any_of(notificationDiagnostics, + [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "subject") == "skills/changed"; + }) && + std::ranges::any_of(notificationDiagnostics, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "subject") == "thread/goal/cleared"; + }); + }), + "notification diagnostics preserve semantic authority"); + const auto authorityFor = [&](std::string_view subject) { + const auto found = std::ranges::find_if(notificationDiagnostics, [subject](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "subject") == subject; + }); + return found == notificationDiagnostics.end() ? std::string{} : diagnosticField(*found, "authority"); + }; + for (const auto& diagnostic : notificationDiagnostics) { + const auto emitted = signedIntegerFromValue(valueMember(diagnostic.details, "emittedAtMs")); + const auto recorded = signedIntegerFromValue(valueMember(diagnostic.details, "recordedAtMs")); + if (diagnosticField(diagnostic, "subject") == "skills/changed") + expect(emitted == 1234567890123 && recorded && *recorded != *emitted, + "server emission time and local boundary-record time remain " + "distinct"); } - expect(methods["thread/metadata/update"] == (projectId != originalProject), name + ": project assignment only on mismatch"); - expect(methods["thread/section/move"] == (sectionId != originalSection), name + ": section assignment only on mismatch"); - expect(methods["thread/name/set"] == !ephemeral, name + ": ephemeral fork avoids rename"); - const auto forkNode = findNode(runtime.graph(), {NodeKind::Thread, forkId}); - ui::NodeGraphUiAdapter adapter(runtime.graph()); - const auto before = adapter.threadRow(forkNode); - expect(before && before->projectId == originalProject && before->sectionId == originalSection, - name + ": unacknowledged membership is not projected optimistically"); - NodeAction prompt{forkNode, NodeActionKind::SubmitPrompt}; - prompt.promptText = "Answer while assignments and history are pending"; - expect(sendAction(runtime.channels(), std::move(prompt)), name + ": first prompt admitted"); - const auto turn = bridge.receiveAppServer(); - expect(turn && turn->value("method", "") == "turn/start", name + ": first prompt is independent of membership and history"); - if (turn) { - expect(bridge.reply(*turn, - {{"turn", {{"id", "membership-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), - name + ": prompt acknowledged"); - } - if (fixture.value("reverse", false)) { - std::ranges::reverse(assignments); - } - for (const auto& assignment : assignments) { - const bool project = assignment.at("method") == "thread/metadata/update"; - const std::string kind = project ? "project" : "section"; - expect(assignment.at("params").at(project ? "projectId" : "sectionId") == (project ? nlohmann::json(projectId) - : sectionId.empty() ? nlohmann::json(nullptr) - : nlohmann::json(sectionId)), - name + ": assignment retains source membership at submission"); - if (rejected == kind) { - expect(bridge.replyError(assignment, -32000, "fixture " + kind + " assignment failed"), name + ": assignment rejected"); - } else if (project) { - forked["projectId"] = projectId; - // A project result can contain section metadata captured before its concurrent move. - auto projectResult = forked; - projectResult["section"] = section(originalSection); - expect(bridge.reply(assignment, {{"thread", projectResult}}), name + ": project acknowledged"); - } else { - forked["section"] = section(sectionId); - expect(bridge.reply(assignment, nlohmann::json::object()), name + ": empty section acknowledgement accepted"); + expect(authorityFor("skills/changed") == "none" && authorityFor("thread/goal/cleared") == "remove", + "state-neutral and removal notifications remain distinguishable"); + + runtime.drainNotifications(); + expect(bridge.appServerRequest("diagnostic-clock", "currentTime/read", {{"threadId", "runtime-thread"}}), + "reverse-request diagnostic fixture is delivered"); + const std::optional automaticClockResponse = bridge.receiveAppServer(); + expect(automaticClockResponse && !automaticClockResponse->contains("method") && + automaticClockResponse->value("id", std::string{}) == "diagnostic-clock", + "reverse-request diagnostic fixture consumes its automatic response"); + std::vector reverseDiagnostics; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + reverseDiagnostics.insert( + reverseDiagnostics.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::any_of(reverseDiagnostics, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "server result" && + diagnosticField(effect, "correlation") == "diagnostic-clock"; + }); + }), + "reverse request and automatic response are both diagnosed"); + const ProtocolDiagnostic* reverseRequest = nullptr; + const ProtocolDiagnostic* reverseResult = nullptr; + for (const ProtocolDiagnostic& effect : reverseDiagnostics) { + if (diagnosticField(effect, "correlation") != "diagnostic-clock") + continue; + if (diagnosticField(effect, "direction") == "server request") + reverseRequest = &effect; + if (diagnosticField(effect, "direction") == "server result") + reverseResult = &effect; + } + const auto* clockTimes = reverseResult ? valueMember(reverseResult->details, "timing") : nullptr; + expect(clockTimes && clockTimes->asArray() && clockTimes->asArray()->size() == 1 && + exactStringFromValue(clockTimes->asArray()->front().find("field")) == "currentTimeAt", + "client-reported clock response keeps its schema timestamp without " + "retaining other payload"); + expect(reverseRequest && reverseResult && diagnosticField(*reverseRequest, "authority") == "merge" && + diagnosticField(*reverseResult, "authority") == "remove" && + diagnosticField(*reverseRequest, "threadId") == "runtime-thread" && + diagnosticField(*reverseRequest, "correlation") == diagnosticField(*reverseResult, "correlation"), + "reverse interaction diagnostics preserve scope and correlation"); + + runtime.drainNotifications(); + constexpr std::string_view SensitiveRequestId = "failed:sk-sensitive-correlation"; + expect(bridge.appServerRequest(std::string(SensitiveRequestId), "currentTime/read", {{"threadId", "runtime-thread"}}), + "sensitive request-id diagnostic fixture is delivered"); + const std::optional sensitiveClockResponse = bridge.receiveAppServer(); + expect(sensitiveClockResponse && !sensitiveClockResponse->contains("method") && + sensitiveClockResponse->value("id", std::string{}) == SensitiveRequestId, + "sensitive request-id fixture consumes its automatic response"); + std::vector sensitiveIdDiagnostics; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + sensitiveIdDiagnostics.insert( + sensitiveIdDiagnostics.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::any_of(sensitiveIdDiagnostics, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "server result" && + diagnosticField(effect, "correlation") == ""; + }); + }), + "sensitive request ids remain visible only as redacted chronology"); + for (const ProtocolDiagnostic& effect : sensitiveIdDiagnostics) { + std::string visibleMetadata; + for (const auto& [key, value] : effect.details) { + visibleMetadata += key; + if (value.asString()) + visibleMetadata += *value.asString(); } + expect(visibleMetadata.find(SensitiveRequestId) == std::string::npos, + "sensitive request ids are neither retained nor correlated"); } - if (history) { - expect(bridge.reply(*history, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), - name + ": history completes independently"); + runtime.drainNotifications(); + } + + void directNodeActionsUseOneCorrelatedRequest(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "provider hydration creates action target"); + if (!thread) + return; + + NodeAction missingName{thread, NodeActionKind::Rename}; + missingName.correlation = "missing-name-action"; + expect(sendAction(runtime.channels(), std::move(missingName)), "a missing-name rename can enter the typed mailbox"); + expect(!bridge.receiveAppServer(100ms), "worker validation blocks a missing rename name"); + + NodeAction emptyName{thread, NodeActionKind::Rename}; + emptyName.payload = {{"name", Value(" \t\n")}}; + emptyName.correlation = "blank-name-action"; + expect(sendAction(runtime.channels(), std::move(emptyName)), "a blank-name rename can enter the typed mailbox"); + expect(!bridge.receiveAppServer(100ms), "worker validation blocks an empty rename name"); + std::vector localRejections; + expect(waitUntil([&] { + std::vector batch = runtime.takeProtocolDiagnostics(); + localRejections.insert( + localRejections.end(), std::make_move_iterator(batch.begin()), std::make_move_iterator(batch.end())); + return std::ranges::count_if(localRejections, [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "local result" && + diagnosticField(effect, "subject") == "thread/name/set"; + }) >= 2; + }), + "local validation failures reach the bounded Protocol chronology"); + const auto localRenameRejection = [&localRejections](std::string_view correlation) { + return std::ranges::any_of(localRejections, [correlation](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "local result" && + diagnosticField(effect, "subject") == "thread/name/set" && diagnosticField(effect, "authority") == "none" && + diagnosticField(effect, "outcome") == "ERROR" && + diagnosticField(effect, "errorCategory") == "local-validation" && + diagnosticField(effect, "correlation") == correlation && + diagnosticField(effect, "threadId") == "runtime-thread" && + diagnosticField(effect, "targetId") == "runtime-thread" && + diagnosticField(effect, "error") == "A non-empty thread name is required"; + }); + }; + expect(localRenameRejection("missing-name-action") && localRenameRejection("blank-name-action"), + "local rejection diagnostics preserve action correlation and safe " + "error metadata without sending a wire operation"); + + NodeAction rename{thread, NodeActionKind::Rename}; + rename.payload = { + {"name", Value("Renamed once")}, {"turnId", Value("payload-decoy-turn")}, {"itemId", Value("payload-decoy-item")}}; + expect(sendAction(runtime.channels(), std::move(rename)), "rename action enters the worker mailbox"); + std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/name/set" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("name", std::string{}) == "Renamed once", + "rename action emits one addressed CodexBridge request"); + if (!request) + return; + expect(waitUntil([&] { + return operationPending(runtime.graph(), request->at("id")); + }), + "emitted request has one pending graph correlation"); + expect(operationTargets(runtime.graph(), request->at("id"), thread), + "the operation retains the exact NodeRef selected by the UI action"); + { + std::optional read = runtime.graph().tryRead(); + const NodeId decoyTurn = scopedTurnNodeId("runtime-thread", "payload-decoy-turn"); + expect(read && !read->find(decoyTurn) && !read->find(scopedItemNodeId(decoyTurn, "payload-decoy-item")), + "payload identifiers cannot synthesize a replacement operation " + "target when an exact action target was supplied"); } + expect(!bridge.receiveAppServer(100ms), "non-idempotent rename is not dual-sent"); + expect(bridge.reply(*request, nlohmann::json::object()), "matching rename response is delivered"); expect(waitUntil([&] { - const auto row = adapter.threadRow(forkNode); - return row && row->projectId == (rejected == "project" ? originalProject : projectId) && - row->sectionId == (rejected == "section" ? originalSection : sectionId); + return operationRetired(runtime.graph(), request->at("id")); }), - name + ": authoritative projection reflects acknowledged memberships only"); - if (!rejected.empty()) { + "matching response retires the exact pending operation"); + + NodeAction archive{thread, NodeActionKind::Archive}; + expect(sendAction(runtime.channels(), std::move(archive)), "archive action enters the worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/archive" && + request->at("params").value("threadId", std::string{}) == "runtime-thread", + "archive action emits one addressed CodexBridge request"); + if (request) { + expect(!bridge.receiveAppServer(100ms), "non-idempotent archive is not dual-sent"); + expect(bridge.reply(*request, nlohmann::json::object()), "archive response is delivered"); expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto notice = read ? read->find({NodeKind::Notice, "local-worker-notice"}) : NodeRef{}; - return notice && exactStringFromValue(valueMember(*read->state(notice), "message")) == - "fixture " + rejected + " assignment failed"; + return operationRetired(runtime.graph(), request->at("id")); }), - name + ": assignment failure remains visible"); - } - if (rejected.empty() && !fixture.value("moveSource", false)) { - const auto snapshot = adapter.threads(forkNode); - bool nested = false; - const auto inspect = [&](const auto& self, const auto& rows) -> void { - for (const auto& row : rows) { - if (row.id == sourceId) { - nested = std::ranges::any_of(row.children, [&](const auto& child) { - return child.id == forkId; - }); - } - self(self, row.children); - } - }; - if (snapshot) { - inspect(inspect, snapshot->roots); + "archive response correlates to and retires its operation"); + } + runtime.drainNotifications(); + } + + void remainingUiCommandFamiliesUseExactWirePaths(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "remaining UI command coverage has a stable thread target"); + if (!thread) + return; + + NodeRef wrongHistoryTarget; + { + auto write = runtime.graph().write(); + NodeState wrongTargetState; + wrongTargetState.fields = {{"type", Value("agentMessage")}, {"threadId", Value("runtime-thread")}}; + wrongHistoryTarget = write.upsert({NodeKind::Item, "wrong-history-target"}, std::move(wrongTargetState)); + write.setField(thread, "historyNextCursor", Value("graph-history-cursor")); + static_cast(write.finish()); + } + NodeAction wrongHistory{wrongHistoryTarget, NodeActionKind::LoadHistory}; + expect(sendAction(runtime.channels(), std::move(wrongHistory)), "a malformed history target reaches typed validation"); + expect(!bridge.receiveAppServer(100ms), "history loading rejects a non-Thread target before wire dispatch"); + + NodeAction history{thread, NodeActionKind::LoadHistory}; + history.payload = {{"cursor", Value("payload-decoy-cursor")}, {"limit", Value(std::uint64_t{23})}}; + expect(sendAction(runtime.channels(), std::move(history)), "history paging enters the typed worker mailbox"); + std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/turns/list" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("cursor", std::string{}) == "graph-history-cursor" && + request->at("params").value("limit", 0) == 80 && + request->at("params").value("sortDirection", std::string{}) == "desc" && + request->at("params").value("itemsView", std::string{}) == "summary", + "Load More derives one scoped page from authoritative graph state"); + if (request) { + expect(operationTargets(runtime.graph(), request->at("id"), thread), "history paging preserves its exact thread NodeRef"); + NodeAction duplicate{thread, NodeActionKind::LoadHistory}; + expect(sendAction(runtime.channels(), std::move(duplicate)), "a duplicate history action reaches the worker"); + expect(!bridge.receiveAppServer(100ms), "the live graph operation is the history single-flight gate"); + expect(bridge.replyError(*request, -32044, "temporary history failure"), + "history paging exposes a retryable provider failure"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), request->at("id")); + }), + "history paging failure retires its exact operation"); + + NodeAction retry{thread, NodeActionKind::LoadHistory}; + retry.payload = {{"cursor", Value("different-decoy-cursor")}, {"limit", Value(std::uint64_t{7})}}; + expect(sendAction(runtime.channels(), std::move(retry)), "a failed history operation can be retried"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/turns/list" && + request->at("params").value("cursor", std::string{}) == "graph-history-cursor" && + request->at("params").value("limit", 0) == 80, + "history retry preserves the same authoritative page demand"); + if (request) + expect( + bridge.reply(*request, + {{"data", nlohmann::json::array({{{"id", "paged-runtime-turn"}, {"items", nlohmann::json::array()}}})}, + {"nextCursor", nullptr}}), + "the retried history page decodes its typed result"); + std::optional itemPage = bridge.receiveAppServer(); + expect(itemPage && itemPage->value("method", std::string{}) == "thread/items/list" && + itemPage->at("params").value("threadId", std::string{}) == "runtime-thread" && + itemPage->at("params").value("turnId", std::string{}) == "paged-runtime-turn" && + itemPage->at("params").value("limit", 0) == 80 && + itemPage->at("params").value("sortDirection", std::string{}) == "desc", + "turn summaries schedule one bounded item page"); + if (itemPage) + expect(bridge.reply(*itemPage, {{"data", nlohmann::json::array()}, {"nextCursor", "older-items"}}), + "item pagination retains its continuation"); + itemPage = bridge.receiveAppServer(); + expect(itemPage && itemPage->value("method", std::string{}) == "thread/items/list" && + itemPage->at("params").value("cursor", std::string{}) == "older-items", + "item pagination continues through the provider cursor"); + if (itemPage) + expect(bridge.reply(*itemPage, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "the final item page completes bounded hydration"); + } + expect(!bridge.receiveAppServer(100ms), "history paging is never duplicated on the wire"); + + NodeAction fork{thread, NodeActionKind::Fork}; + expect(sendAction(runtime.channels(), std::move(fork)), "fork enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/fork" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("excludeTurns", false), + "fork encodes one request addressed by the supplied NodeRef"); + if (request) { + expect(operationTargets(runtime.graph(), request->at("id"), thread), "fork preserves its exact thread NodeRef"); + expect(bridge.replyError(*request, -32043, "focused fork rejection"), "fork decodes a typed provider error"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), request->at("id")); + }), + "fork error retires its correlated operation"); + } + expect(!bridge.receiveAppServer(100ms), "fork is never dual-sent"); + NodeAction invalidFork{thread, NodeActionKind::Fork}; + invalidFork.payload.emplace("lastTurnId", Value("missing-boundary")); + expect(sendAction(runtime.channels(), std::move(invalidFork)), "stale boundary reaches worker validation"); + expect(!bridge.receiveAppServer(100ms), "missing turn cannot silently fall back to a full-thread fork"); + + const auto archivedIs = [&](bool expected) { + std::optional read = runtime.graph().tryRead(); + if (!read || read->find(thread->id()) != thread) + return false; + const auto state = read->state(thread); + const auto archived = state->fields.find("archived"); + return archived != state->fields.end() && archived->second.asBool() && *archived->second.asBool() == expected; + }; + expect(bridge.appServerNotification("thread/archived", {{"threadId", "runtime-thread"}}) && waitUntil([&] { + return archivedIs(true); + }), + "unarchive coverage starts from authoritative archived state"); + NodeAction unarchive{thread, NodeActionKind::Unarchive}; + expect(sendAction(runtime.channels(), std::move(unarchive)), "unarchive enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/unarchive" && + request->at("params").value("threadId", std::string{}) == "runtime-thread", + "unarchive encodes one request addressed by the supplied NodeRef"); + if (request) { + expect(operationTargets(runtime.graph(), request->at("id"), thread), "unarchive preserves its exact thread NodeRef"); + expect(bridge.reply(*request, nlohmann::json::object()), "unarchive decodes its typed result"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), request->at("id")); + }), + "unarchive result retires its correlated operation"); + } + expect(!bridge.receiveAppServer(100ms), "unarchive is never dual-sent"); + expect(bridge.appServerNotification("thread/unarchived", {{"threadId", "runtime-thread"}}) && waitUntil([&] { + return archivedIs(false); + }), + "authoritative unarchive restores the thread for prompt coverage"); + + RuntimeAction create{RuntimeActionKind::CreateThread}; + create.correlation = "wire-create-correlation"; + create.promptText = "Create and send exactly once"; + create.attachments.push_back({"/tmp/wire-image.png", "wire-image.png", "image/png", std::nullopt}); + create.payload = {{"requestedName", Value("Unsupported ephemeral name")}, + {"sectionId", Value("wire-section")}, + {"threadStart", + Value(Value::Object{{"cwd", Value("/tmp/wire-create")}, + {"projectId", Value("wire-project")}, + {"baseInstructions", Value("Ephemeral base instructions")}, + {"developerInstructions", Value("Ephemeral developer instructions")}, + {"ephemeral", Value(true)}})}, + {"turnStart", Value(Value::Object{{"approvalPolicy", Value("on-request")}})}}; + expect(sendAction(runtime.channels(), std::move(create)), "new-thread prompt enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/start" && + request->at("params").value("cwd", std::string{}) == "/tmp/wire-create" && + request->at("params").value("baseInstructions", std::string{}) == "Ephemeral base instructions" && + request->at("params").value("developerInstructions", std::string{}) == "Ephemeral developer instructions" && + request->at("params").value("ephemeral", false) && request->at("params").value("projectId", "") == "wire-project" && + !request->at("params").contains("historyMode"), + "Create Thread keeps ephemeral instructions and leaves app-server's " + "legacy history default authoritative"); + if (!request) { + runtime.drainNotifications(); + return; + } + expect( + bridge.reply( + *request, + {{"thread", + {{"id", "wire-created-thread"}, {"name", "Wire created"}, {"status", "idle"}, {"turns", nlohmann::json::array()}}}}), + "thread/start decodes the canonical created thread"); + + request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/section/move" && + request->at("params").value("sectionId", "") == "wire-section", + "new-thread section assignment follows successful creation"); + if (request) + expect(bridge.replyError(*request, -32000, "section assignment failed"), + "section failure retains the created thread and does not resend the " + "first prompt"); + request = bridge.receiveAppServer(); + const nlohmann::json input = request && request->contains("params") + ? request->at("params").value("input", nlohmann::json::array()) + : nlohmann::json::array(); + expect(request && request->value("method", std::string{}) == "turn/start" && + request->at("params").value("threadId", std::string{}) == "wire-created-thread" && + request->at("params").value("approvalPolicy", std::string{}) == "on-request" && input.size() == 2 && + input.at(0).value("type", std::string{}) == "text" && + input.at(0).value("text", std::string{}).find("Create and send exactly once") != std::string::npos && + input.at(1).value("type", std::string{}) == "localImage" && + input.at(1).value("path", std::string{}) == "/tmp/wire-image.png", + "the first ephemeral prompt skips metadata updates and moves text, " + "options, and attachment into one turn/start request"); + if (request) { + expect( + bridge.reply(*request, + {{"turn", {{"id", "wire-created-turn"}, {"status", "inProgress"}, {"items", nlohmann::json::array()}}}}), + "turn/start decodes its canonical turn result"); + } + expect(!bridge.receiveAppServer(100ms), "the first new-thread prompt is never dual-sent"); + + const NodeRef created = findNode(runtime.graph(), {NodeKind::Thread, "wire-created-thread"}); + const NodeRef active = findNode(runtime.graph(), scopedTurnNodeId("wire-created-thread", "wire-created-turn")); + expect(created && active, "created-thread command results retain natural thread and turn nodes"); + if (created && active) { + NodeAction steer{created, NodeActionKind::SubmitPrompt}; + steer.promptText = "Steer the exact active turn"; + steer.payload.emplace("model", "must-not-steer"); + steer.payload.emplace("summary", "must-not-steer"); + expect(sendAction(runtime.channels(), std::move(steer)), "active-turn steering enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/steer" && + request->at("params").value("threadId", std::string{}) == "wire-created-thread" && + request->at("params").value("expectedTurnId", std::string{}) == "wire-created-turn" && + !request->at("params").contains("model") && !request->at("params").contains("summary"), + "Submit while active encodes one turn/steer without start settings"); + if (request) + expect(bridge.reply(*request, {{"turnId", "wire-created-turn"}}), "turn/steer decodes its typed result"); + expect(!bridge.receiveAppServer(100ms), "steering is never dual-sent"); + NodeAction imageOnly{created, NodeActionKind::SubmitPrompt}; + imageOnly.attachments.push_back({"/tmp/pasted-image.png", "pasted-image.png", "image/png", std::nullopt}); + expect(sendAction(runtime.channels(), std::move(imageOnly)), + "image-only steering enters the existing worker admission path"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/steer" && + request->at("params").at("input") == + nlohmann::json::array({{{"type", "localImage"}, {"path", "/tmp/pasted-image.png"}}}), + "image-only input has a localImage and no fabricated empty text item"); + if (request) + expect(bridge.reply(*request, {{"turnId", "wire-created-turn"}}), "image-only steering decodes its typed result"); + } + + expect(bridge.appServerNotification( + "turn/completed", + {{"threadId", "wire-created-thread"}, + {"turn", {{"id", "wire-created-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), + "created active turn receives its authoritative completion"); + replyAccountUsage(bridge); + + if (created) { + NodeAction remove{created, NodeActionKind::Delete}; + expect(sendAction(runtime.channels(), std::move(remove)), "delete enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/delete" && + request->at("params").value("threadId", std::string{}) == "wire-created-thread", + "delete encodes one request addressed by the supplied NodeRef"); + if (request) { + expect(operationTargets(runtime.graph(), request->at("id"), created), "delete preserves its exact thread NodeRef"); + expect(bridge.reply(*request, nlohmann::json::object()), "delete decodes its typed result"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), request->at("id")); + }), + "delete result retires its correlated operation"); } - expect(nested, name + ": fork is nested beneath its source in the project tree"); + expect(!bridge.receiveAppServer(100ms), "delete is never dual-sent"); + expect(bridge.appServerNotification("thread/deleted", {{"threadId", "wire-created-thread"}}) && waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + return read && !read->find(created->id()); + }), + "authoritative delete retires the exact created thread"); } - expect(!bridge.receiveAppServer(80ms), name + ": no duplicate request or automatic mutation retry"); + runtime.drainNotifications(); + } + + void itemHistoryHydrationHasAnExactConcurrencyCeiling(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "bounded item hydration has a stable thread target"); + if (!thread) + return; + { + auto write = runtime.graph().write(); + write.setField(thread, "historyNextCursor", Value("bounded-items-page")); + static_cast(write.finish()); + } + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::LoadHistory}), + "bounded item hydration enters the worker mailbox"); + const std::optional turnPage = bridge.receiveAppServer(); + expect(turnPage && turnPage->value("method", std::string{}) == "thread/turns/list", + "bounded item hydration starts from one turn page"); + if (!turnPage) + return; + nlohmann::json turns = nlohmann::json::array(); + for (int index = 0; index < 10; ++index) + turns.push_back({{"id", "bounded-turn-" + std::to_string(index)}, {"items", nlohmann::json::array()}}); + expect(bridge.reply(*turnPage, {{"data", std::move(turns)}, {"nextCursor", nullptr}}), + "ten turn summaries are delivered in one bounded page"); + + std::vector firstWave; + for (int index = 0; index < 8; ++index) { + const std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/items/list", + "the first item-hydration wave contains eight item pages"); + if (request) + firstWave.push_back(*request); + } + expect(firstWave.size() == 8, "the native item scheduler fills its exact eight-request ceiling"); + expect(!bridge.receiveAppServer(100ms), "a ninth item page waits while eight requests remain in flight"); + if (firstWave.size() != 8) + return; + + expect(bridge.reply(firstWave[0], {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "one completed item page releases one scheduler slot"); + const std::optional ninth = bridge.receiveAppServer(); + expect(ninth && ninth->value("method", std::string{}) == "thread/items/list", + "one completion admits exactly the ninth item page"); + expect(bridge.reply(firstWave[1], {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "a second completed item page releases the final queued turn"); + const std::optional tenth = bridge.receiveAppServer(); + expect(tenth && tenth->value("method", std::string{}) == "thread/items/list", + "the second completion admits exactly the tenth item page"); + for (std::size_t index = 2; index < firstWave.size(); ++index) + expect(bridge.reply(firstWave[index], {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "the remaining first-wave item page completes"); + if (ninth) + expect(bridge.reply(*ninth, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "the ninth item page completes"); + if (tenth) + expect(bridge.reply(*tenth, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "the tenth item page completes"); + expect(!bridge.receiveAppServer(100ms), "item hydration emits no extra pages after the ten turns complete"); + runtime.drainNotifications(); + } + + void conversationSnapshotsShareOneAdmissionAuthority(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "snapshot single-flight coverage has a stable thread target"); + if (!thread) + return; + + { + auto write = runtime.graph().write(); + write.setField(thread, "historyHasMore", Value(true)); + write.setField(thread, "historyNextCursor", Value("read-overlap-cursor")); + static_cast(write.finish()); + } + + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Reload}), + "reload enters the worker before competing Load More coverage"); + const std::optional resumeRequest = bridge.receiveAppServer(); + expect(resumeRequest && resumeRequest->value("method", std::string{}) == "thread/resume" && + resumeRequest->at("params").value("excludeTurns", false), + "reload owns one metadata-only resume before its history page"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::LoadHistory}), + "Load More reaches admission while reload resume is pending"); + expect(!bridge.receiveAppServer(100ms), "reload resume suppresses a competing history page"); + if (resumeRequest) { + expect(bridge.reply(*resumeRequest, nlohmann::json::object()), "metadata-only reload resume completes"); + const std::optional readRequest = bridge.receiveAppServer(); + expect(readRequest && readRequest->value("method", std::string{}) == "thread/turns/list" && + readRequest->at("params").value("itemsView", std::string{}) == "summary", + "reload owns one bounded conversation snapshot"); + if (readRequest) + expect(bridge.reply(*readRequest, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "the sole reload page completes"); + } + + { + auto write = runtime.graph().write(); + write.setField(thread, "historyHasMore", Value(true)); + write.setField(thread, "historyNextCursor", Value("page-overlap-cursor")); + static_cast(write.finish()); + } + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::LoadHistory}), + "Load More enters the worker before competing reload coverage"); + const std::optional pageRequest = bridge.receiveAppServer(); + expect(pageRequest && pageRequest->value("method", std::string{}) == "thread/turns/list", + "Load More owns one paginated conversation snapshot"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Reload}), + "reload reaches admission while thread/turns/list is pending"); + expect(!bridge.receiveAppServer(100ms), "thread/turns/list suppresses a competing reload snapshot"); + if (pageRequest) + expect(bridge.reply(*pageRequest, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "the sole paginated snapshot completes"); + runtime.drainNotifications(); + } + + void firstNavigationDrainsTheExistingHistoryPager(UnixBridge& bridge, RunningRuntime& runtime) { + NodeRef thread; + { + auto write = runtime.graph().write(); + NodeState state; + state.fields = {{"historyHasMore", Value(true)}, {"historyNextCursor", Value("first-1")}}; + thread = write.upsert({NodeKind::Thread, "first-navigation"}, std::move(state)); + static_cast(write.finish()); + } + expect(sendAction(runtime.channels(), + NodeAction{thread, NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", Value(true)}}, {}}), + "First enters the existing typed history action"); + for (int page = 1; page <= 3; ++page) { + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/turns/list" && + request->at("params").value("cursor", "") == "first-" + std::to_string(page) && + request->at("params").value("sortDirection", "") == "desc", + "First sequentially follows authoritative cursors through the existing history pager"); + if (request) { + const nlohmann::json cursor = page == 3 ? nlohmann::json(nullptr) : nlohmann::json("first-" + std::to_string(page + 1)); + expect(bridge.reply(*request, {{"data", nlohmann::json::array()}, {"nextCursor", cursor}}), + "First receives an earlier page"); + } + } + expect(!bridge.receiveAppServer(100ms), "First stops paging at the authoritative beginning"); + { + auto write = runtime.graph().write(); + write.setField(thread, "historyNextCursor", Value("first-retry")); + write.setField(thread, "historyHasMore", Value(true)); + static_cast(write.finish()); + } + expect(sendAction(runtime.channels(), + NodeAction{thread, NodeActionKind::LoadHistory, {}, {}, {{"throughFirst", Value(true)}}, {}}), + "First can request retained earlier history again"); + const auto failed = bridge.receiveAppServer(); + expect(failed.has_value(), "First failure coverage receives a request"); + if (failed) { + expect(bridge.replyError(*failed, -32000, "First paging failed"), "First exposes history failure"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), failed->at("id")); + }), + "First failure retires its operation"); + } + expect(!bridge.receiveAppServer(100ms), "First does not loop or automatically retry after failure"); + runtime.drainNotifications(); } - runtime.drainNotifications(); - } -} -void creationAssignsOnlyTheReturnedGroup(UnixBridge& bridge, RunningRuntime& runtime) { - std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/context-menu-creation.json"); - const auto fixtures = nlohmann::json::parse(input); - for (const auto& fixture : fixtures) { - const std::string kind = fixture.at("kind"), failure = fixture.at("failure"); - const bool project = kind == "project"; - const std::string sourceId = "creation-source-" + kind + "-" + failure; - const nlohmann::json source{{"id", sourceId}, - {"name", "Original"}, - {"status", "idle"}, - {"projectId", "old-project"}, - {"section", {{"id", "old-section"}, {"name", "Old"}}}}; - expect(bridge.appServerNotification("thread/started", {{"thread", source}}), "creation source delivered"); - const auto target = findNode(runtime.graph(), {NodeKind::Thread, sourceId}); - expect(bool(target), "creation source is authoritative"); - RuntimeAction action{project ? RuntimeActionKind::CreateProject : RuntimeActionKind::CreateSection}; - action.payload = {{"name", Value("Chosen name")}, {"threadId", Value(sourceId)}}; - if (project) { - action.payload.emplace("idempotencyKey", Value("identity-" + sourceId)); - action.payload.emplace("roots", Value(Value::Array{})); + void staleHistoryFailureIsSemanticallyInert(UnixBridge& bridge, RunningRuntime& runtime) { + constexpr std::string_view ThreadId = "stale-history-thread"; + constexpr std::string_view ErrorText = "late history failure must remain invisible"; + NodeRef thread; + { + auto write = runtime.graph().write(); + NodeState state; + state.fields = {{"historyHasMore", Value(true)}, {"historyNextCursor", Value("stale-cursor")}}; + thread = write.upsert({NodeKind::Thread, std::string(ThreadId)}, std::move(state)); + static_cast(write.finish()); + } + static_cast(runtime.takeProtocolDiagnostics()); + + NodeAction action{thread, NodeActionKind::LoadHistory}; + expect(sendAction(runtime.channels(), std::move(action)), "stale-history coverage admits one exact action"); + const std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/turns/list" && + operationTargets(runtime.graph(), request->at("id"), thread), + "stale-history coverage observes the target-owned Operation"); + if (!request) + return; + + { + auto write = runtime.graph().write(); + write.remove(thread); + static_cast(write.finish()); + } + expect(operationRetired(runtime.graph(), request->at("id")), "removing the history target cascades its pending Operation"); + static_cast(runtime.takeProtocolDiagnostics()); + expect(bridge.replyError(*request, -32055, std::string(ErrorText)), + "the retired history request receives its late provider failure"); + expect(bridge.appServerNotification("thread/started", + {{"thread", {{"id", "stale-history-barrier"}, {"name", "Stale history barrier"}}}}) && + waitUntil([&] { + return static_cast(findNode(runtime.graph(), {NodeKind::Thread, "stale-history-barrier"})); + }), + "a later wire frame proves the late callback has settled"); + + const std::vector effects = runtime.takeProtocolDiagnostics(); + expect(std::ranges::any_of(effects, + [](const ProtocolDiagnostic& effect) { + return diagnosticField(effect, "direction") == "client error" && + diagnosticField(effect, "subject") == "thread/turns/list"; + }), + "the late history failure remains visible to protocol diagnostics"); + const NodeRef notice = findNode(runtime.graph(), {NodeKind::Notice, "local-worker-notice"}); + const std::optional noticeRead = runtime.graph().tryRead(); + const Value* noticeMessage = notice && noticeRead ? valueMember(*noticeRead->state(notice), "message") : nullptr; + expect(!noticeMessage || !noticeMessage->asString() || noticeMessage->asString()->find(ErrorText) == std::string::npos, + "a stale history failure cannot become authoritative visible notice " + "state"); + expect(!findNode(runtime.graph(), {NodeKind::Thread, std::string(ThreadId)}), + "the stale history result cannot recreate its retired thread"); } - expect(sendAction(runtime.channels(), std::move(action)), "create-and-assign enters the existing runtime path"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == (project ? "project/create" : "threadSection/create"), - "one group creation is sent"); - if (request) { - expect(!request->at("params").contains("threadId"), "assignment context is not sent in the creation request"); - if (failure == "create") { - expect(bridge.replyError(*request, -32000, "creation denied"), "creation failure delivered"); - } else { - if (failure == "retired-target") { - expect(bridge.appServerNotification("thread/deleted", {{"threadId", sourceId}}), "target retirement delivered"); + + void forksPersistSourceMembership(UnixBridge& bridge, RunningRuntime& runtime) { + std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/fork-membership.json"); + const auto fixtures = nlohmann::json::parse(input); + const auto section = [](const std::string& id) { + return id.empty() ? nlohmann::json(nullptr) : nlohmann::json{{"id", id}, {"name", id}}; + }; + for (const auto& fixture : fixtures) { + const std::string name = fixture.at("name"); + const std::string sourceId = "membership-source-" + name; + const std::string forkId = "membership-fork-" + name; + const std::string projectId = fixture.at("projectId"), sectionId = fixture.at("sectionId"); + const std::string originalProject = fixture.at("forkProjectId"), originalSection = fixture.at("forkSectionId"); + const std::string rejected = fixture.value("reject", ""); + const nlohmann::json source{{"id", sourceId}, + {"name", "Find Slides"}, + {"cwd", "/source-workspace"}, + {"projectId", projectId}, + {"section", section(sectionId)}, + {"status", "idle"}, + {"forkedFromId", nullptr}, + {"parentThreadId", nullptr}, + {"turns", + nlohmann::json::array({{{"id", "first"}, {"status", "completed"}}, + {{"id", "middle"}, {"status", "completed"}}, + {{"id", "last"}, {"status", "completed"}}})}}; + expect(bridge.appServerNotification("thread/started", {{"thread", source}}), name + ": source metadata delivered"); + const auto sourceNode = findNode(runtime.graph(), {NodeKind::Thread, sourceId}); + expect(static_cast(sourceNode), name + ": source exists"); + NodeAction action{sourceNode, NodeActionKind::Fork}; + if (fixture.contains("lastTurnId")) { + action.payload.emplace("lastTurnId", Value(fixture.at("lastTurnId").get())); + } + const bool ephemeral = fixture.value("ephemeral", false); + if (!ephemeral) { + action.payload.emplace("requestedName", Value("Find Slides (fork 1)")); + } + if (fixture.at("options").get()) { + action.payload.emplace("cwd", Value("/fork-workspace")); + action.payload.emplace("baseInstructions", Value("Fork base")); + action.payload.emplace("developerInstructions", Value("Fork developer")); + action.payload.emplace("ephemeral", Value(ephemeral)); + } + expect(sendAction(runtime.channels(), std::move(action)), name + ": fork admitted"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/fork", name + ": one fork request"); + if (request) { + expect(request->at("params").value("lastTurnId", "") == fixture.value("lastTurnId", ""), + name + ": fork retains the selected inclusive boundary"); + expect(static_cast(findNode(runtime.graph(), scopedTurnNodeId(sourceId, "last"))), + name + ": source retains later history"); + expect(request->at("params").value("cwd", "") == (fixture.at("options").get() ? "/fork-workspace" : ""), + name + ": workspace option is independent of grouping"); + if (fixture.value("moveSource", false)) { + auto moved = source; + moved["projectId"] = "moved-project"; + moved["section"] = section("moved-section"); + expect(bridge.appServerNotification("thread/started", {{"thread", moved}}), name + ": source moved in flight"); + } + nlohmann::json forked{{"id", forkId}, + {"name", "Provider title"}, + {"cwd", "/fork-workspace"}, + {"projectId", originalProject}, + {"section", section(originalSection)}, + {"forkedFromId", sourceId}, + {"parentThreadId", nullptr}, + {"status", "idle"}, + {"turns", nlohmann::json::array()}}; + expect(bridge.reply(*request, {{"thread", forked}}), name + ": fork result delivered"); + std::vector assignments; + std::unordered_map methods; + std::optional history; + const int expectedCount = 1 + !ephemeral + (projectId != originalProject) + (sectionId != originalSection); + for (int index = 0; index < expectedCount; ++index) { + const auto pending = bridge.receiveAppServer(); + expect(static_cast(pending), name + ": completion request delivered"); + if (pending) { + const auto method = pending->value("method", ""); + ++methods[method]; + expect(pending->at("params").value("threadId", "") == forkId, name + ": completion targets the fork"); + if (method == "thread/metadata/update" || method == "thread/section/move") { + assignments.push_back(*pending); + } else if (method == "thread/turns/list") { + history = *pending; + } else { + expect(method == "thread/name/set", name + ": no unexpected completion operation"); + expect(bridge.reply(*pending, nlohmann::json::object()), name + ": rename acknowledged"); + } + } + } + expect(methods["thread/metadata/update"] == (projectId != originalProject), + name + ": project assignment only on mismatch"); + expect(methods["thread/section/move"] == (sectionId != originalSection), + name + ": section assignment only on mismatch"); + expect(methods["thread/name/set"] == !ephemeral, name + ": ephemeral fork avoids rename"); + const auto forkNode = findNode(runtime.graph(), {NodeKind::Thread, forkId}); + ui::NodeGraphUiAdapter adapter(runtime.graph()); + const auto before = adapter.threadRow(forkNode); + expect(before && before->projectId == originalProject && before->sectionId == originalSection, + name + ": unacknowledged membership is not projected optimistically"); + NodeAction prompt{forkNode, NodeActionKind::SubmitPrompt}; + prompt.promptText = "Answer while assignments and history are pending"; + expect(sendAction(runtime.channels(), std::move(prompt)), name + ": first prompt admitted"); + const auto turn = bridge.receiveAppServer(); + expect(turn && turn->value("method", "") == "turn/start", + name + ": first prompt is independent of membership and history"); + if (turn) { + expect(bridge.reply( + *turn, + {{"turn", {{"id", "membership-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), + name + ": prompt acknowledged"); + } + if (fixture.value("reverse", false)) { + std::ranges::reverse(assignments); + } + for (const auto& assignment : assignments) { + const bool project = assignment.at("method") == "thread/metadata/update"; + const std::string kind = project ? "project" : "section"; + expect(assignment.at("params").at(project ? "projectId" : "sectionId") == (project ? nlohmann::json(projectId) + : sectionId.empty() + ? nlohmann::json(nullptr) + : nlohmann::json(sectionId)), + name + ": assignment retains source membership at submission"); + if (rejected == kind) { + expect(bridge.replyError(assignment, -32000, "fixture " + kind + " assignment failed"), + name + ": assignment rejected"); + } else if (project) { + forked["projectId"] = projectId; + // A project result can contain section metadata captured before its concurrent move. + auto projectResult = forked; + projectResult["section"] = section(originalSection); + expect(bridge.reply(assignment, {{"thread", projectResult}}), name + ": project acknowledged"); + } else { + forked["section"] = section(sectionId); + expect(bridge.reply(assignment, nlohmann::json::object()), name + ": empty section acknowledgement accepted"); + } + } + if (history) { + expect(bridge.reply(*history, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + name + ": history completes independently"); + } expect(waitUntil([&] { - return !findNode(runtime.graph(), {NodeKind::Thread, sourceId}); + const auto row = adapter.threadRow(forkNode); + return row && row->projectId == (rejected == "project" ? originalProject : projectId) && + row->sectionId == (rejected == "section" ? originalSection : sectionId); }), - "target retires before creation completes"); + name + ": authoritative projection reflects acknowledged memberships only"); + if (!rejected.empty()) { + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto notice = read ? read->find({NodeKind::Notice, "local-worker-notice"}) : NodeRef{}; + return notice && exactStringFromValue(valueMember(*read->state(notice), "message")) == + "fixture " + rejected + " assignment failed"; + }), + name + ": assignment failure remains visible"); + } + if (rejected.empty() && !fixture.value("moveSource", false)) { + expect(waitUntil([&] { + const auto snapshot = adapter.threads(forkNode); + bool nested = false; + const auto inspect = [&](const auto& self, const auto& rows) -> void { + for (const auto& row : rows) { + if (row.id == sourceId) { + nested = std::ranges::any_of(row.children, [&](const auto& child) { + return child.id == forkId; + }); + } + self(self, row.children); + } + }; + if (snapshot) { + inspect(inspect, snapshot->roots); + } + return nested; + }), + name + ": fork is nested beneath its source in the project tree"); + } + expect(!bridge.receiveAppServer(80ms), name + ": no duplicate request or automatic mutation retry"); } - const nlohmann::json group{{"id", "returned-" + sourceId}, {"name", "Chosen name"}}; - expect(bridge.reply(*request, {{kind, group}}), "creation returns an authoritative group ID"); - } - int assignments = 0; - bool receiving = true; - for (int count = 0; receiving && count < 12; ++count) { - const auto pending = bridge.receiveAppServer(100ms); - receiving = bool(pending); - if (pending) { - const auto method = pending->value("method", ""); - if (method == "thread/metadata/update" || method == "thread/section/move") { - ++assignments; - expect(pending->at("params") == nlohmann::json{{"threadId", sourceId}, {kind + "Id", "returned-" + sourceId}}, - "assignment uses the returned ID and original context thread"); - if (failure == "assign") { - expect(bridge.replyError(*pending, -32000, "assignment denied"), "assignment failure delivered"); - } else { - auto assigned = source; - if (project) { - assigned["projectId"] = "returned-" + sourceId; + runtime.drainNotifications(); + } + } + + void creationAssignsOnlyTheReturnedGroup(UnixBridge& bridge, RunningRuntime& runtime) { + std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/context-menu-creation.json"); + const auto fixtures = nlohmann::json::parse(input); + for (const auto& fixture : fixtures) { + const std::string kind = fixture.at("kind"), failure = fixture.at("failure"); + const bool project = kind == "project"; + const std::string sourceId = "creation-source-" + kind + "-" + failure; + const nlohmann::json source{{"id", sourceId}, + {"name", "Original"}, + {"status", "idle"}, + {"projectId", "old-project"}, + {"section", {{"id", "old-section"}, {"name", "Old"}}}}; + expect(bridge.appServerNotification("thread/started", {{"thread", source}}), "creation source delivered"); + const auto target = findNode(runtime.graph(), {NodeKind::Thread, sourceId}); + expect(bool(target), "creation source is authoritative"); + RuntimeAction action{project ? RuntimeActionKind::CreateProject : RuntimeActionKind::CreateSection}; + action.payload = {{"name", Value("Chosen name")}, {"threadId", Value(sourceId)}}; + if (project) { + action.payload.emplace("idempotencyKey", Value("identity-" + sourceId)); + action.payload.emplace("roots", Value(Value::Array{})); + } + expect(sendAction(runtime.channels(), std::move(action)), "create-and-assign enters the existing runtime path"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == (project ? "project/create" : "threadSection/create"), + "one group creation is sent"); + if (request) { + expect(!request->at("params").contains("threadId"), "assignment context is not sent in the creation request"); + if (failure == "create") { + expect(bridge.replyError(*request, -32000, "creation denied"), "creation failure delivered"); + } else { + if (failure == "retired-target") { + expect(bridge.appServerNotification("thread/deleted", {{"threadId", sourceId}}), "target retirement delivered"); + expect(waitUntil([&] { + return !findNode(runtime.graph(), {NodeKind::Thread, sourceId}); + }), + "target retires before creation completes"); + } + const nlohmann::json group{{"id", "returned-" + sourceId}, {"name", "Chosen name"}}; + expect(bridge.reply(*request, {{kind, group}}), "creation returns an authoritative group ID"); + } + int assignments = 0; + bool receiving = true; + for (int count = 0; receiving && count < 12; ++count) { + const auto pending = bridge.receiveAppServer(100ms); + receiving = bool(pending); + if (pending) { + const auto method = pending->value("method", ""); + if (method == "thread/metadata/update" || method == "thread/section/move") { + ++assignments; + expect(pending->at("params") == + nlohmann::json{{"threadId", sourceId}, {kind + "Id", "returned-" + sourceId}}, + "assignment uses the returned ID and original context thread"); + if (failure == "assign") { + expect(bridge.replyError(*pending, -32000, "assignment denied"), "assignment failure delivered"); + } else { + auto assigned = source; + if (project) { + assigned["projectId"] = "returned-" + sourceId; + } + expect(bridge.reply( + *pending, + project ? nlohmann::json{{"thread", assigned}} + : nlohmann::json{{"threadId", sourceId}, {"sectionId", "returned-" + sourceId}}), + "assignment acknowledged"); + } + } else { + expect(method == "thread/list" || method == "project/list" || method == "threadSection/list", + "only existing browser queries are refreshed"); + expect(bridge.reply(*pending, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "query refresh acknowledged"); } - expect(bridge.reply(*pending, - project ? nlohmann::json{{"thread", assigned}} - : nlohmann::json{{"threadId", sourceId}, {"sectionId", "returned-" + sourceId}}), - "assignment acknowledged"); } - } else { - expect(method == "thread/list" || method == "project/list" || method == "threadSection/list", - "only existing browser queries are refreshed"); - expect(bridge.reply(*pending, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), - "query refresh acknowledged"); + } + expect(assignments == (failure == "create" || failure == "retired-target" ? 0 : 1), + "creation and target failures cannot dispatch assignments or retries"); + if (!failure.empty()) { + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto notice = read ? read->find({NodeKind::Notice, "local-worker-notice"}) : NodeRef{}; + const auto message = + notice ? exactStringFromValue(valueMember(*read->state(notice), "message")) : std::string{}; + return message.find(failure == "retired-target" ? "Group created, but assignment could not be sent" + : failure == "create" ? "creation denied" + : "assignment denied") != std::string::npos; + }), + "creation and assignment failures are reported accurately"); + } + if (failure != "retired-target") { + ui::NodeGraphUiAdapter adapter(runtime.graph()); + expect(waitUntil([&] { + const auto row = adapter.threadRow(target); + return row && (project ? row->projectId : row->sectionId) == + (failure.empty() ? "returned-" + sourceId : "old-" + kind); + }), + "confirmed membership changes only after successful assignment"); } } + runtime.drainNotifications(); } - expect(assignments == (failure == "create" || failure == "retired-target" ? 0 : 1), - "creation and target failures cannot dispatch assignments or retries"); - if (!failure.empty()) { - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto notice = read ? read->find({NodeKind::Notice, "local-worker-notice"}) : NodeRef{}; - const auto message = notice ? exactStringFromValue(valueMember(*read->state(notice), "message")) : std::string{}; - return message.find(failure == "retired-target" ? "Group created, but assignment could not be sent" - : failure == "create" ? "creation denied" - : "assignment denied") != std::string::npos; - }), - "creation and assignment failures are reported accurately"); + } + + void firstPromptAfterForkStartsANewTurn(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef source = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(source), "successful fork coverage has a stable source thread"); + if (!source) + return; + + NodeAction fork{source, NodeActionKind::Fork}; + fork.payload = {{"requestedName", Value("Runtime thread (fork 1)")}, + {"cwd", Value("/fork-workspace")}, + {"baseInstructions", Value("Fork base")}, + {"developerInstructions", Value("Fork developer")}, + {"ephemeral", Value(true)}}; + expect(sendAction(runtime.channels(), std::move(fork)), "successful fork enters the typed worker mailbox"); + std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/fork" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("cwd", std::string{}) == "/fork-workspace" && + request->at("params").value("baseInstructions", std::string{}) == "Fork base" && + request->at("params").value("developerInstructions", std::string{}) == "Fork developer" && + request->at("params").value("ephemeral", false) && request->at("params").value("excludeTurns", false) && + !request->at("params").contains("requestedName") && !request->at("params").contains("name"), + "successful fork sends adjustable options but keeps its chosen name " + "out of thread/fork"); + if (!request) + return; + const nlohmann::json forkedThread{{"id", "runtime-fork"}, + {"name", "Runtime fork"}, + {"forkedFromId", "runtime-thread"}, + {"status", "idle"}, + {"createdAt", 3}, + {"updatedAt", 4}, + {"recencyAt", 4}, + {"turns", nlohmann::json::array()}}; + expect(bridge.reply(*request, {{"thread", forkedThread}}), "successful fork result is delivered"); + + NodeRef forked; + expect(waitUntil([&] { + forked = findNode(runtime.graph(), {NodeKind::Thread, "runtime-fork"}); + if (!forked) + return false; + auto read = runtime.graph().tryRead(); + if (!read) + return false; + const auto state = read->state(forked); + const auto overlay = state->fields.find("localNameOverlay"); + return overlay != state->fields.end() && overlay->second.asString() && + *overlay->second.asString() == "Runtime thread (fork 1)"; + }), + "successful fork immediately applies its chosen local name"); + expect(static_cast(forked), "successful fork retains its authoritative thread node"); + if (!forked) + return; + const std::optional historyPage = bridge.receiveAppServer(); + expect(historyPage && historyPage->value("method", std::string{}) == "thread/turns/list" && + historyPage->at("params").value("threadId", std::string{}) == "runtime-fork" && + historyPage->at("params").value("itemsView", std::string{}) == "summary", + "metadata-only fork hydrates copied history through bounded pages"); + NodeAction prompt{forked, NodeActionKind::SubmitPrompt}; + prompt.promptText = "Answer after a successful fork"; + expect(sendAction(runtime.channels(), std::move(prompt)), "the first fork prompt enters the typed worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/start" && + request->at("params").value("threadId", std::string{}) == "runtime-fork", + "the first fork prompt starts immediately without a redundant read or " + "resume"); + if (!request) + return; + expect(bridge.reply(*request, + {{"turn", {{"id", "runtime-fork-turn"}, {"status", "inProgress"}, {"items", nlohmann::json::array()}}}}), + "the first fork prompt acknowledgement is delivered"); + if (historyPage) + expect(bridge.reply(*historyPage, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "fork history can complete after its first prompt starts"); + expect(bridge.appServerNotification( + "turn/completed", + {{"threadId", "runtime-fork"}, + {"turn", {{"id", "runtime-fork-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), + "the fork turn reaches an authoritative terminal state"); + replyAccountUsage(bridge); + runtime.drainNotifications(); + } + + void ordinaryThreadPromptStillStartsAndCompletes(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "ordinary prompt coverage has a stable thread"); + if (!thread) + return; + + { + auto write = runtime.graph().write(); + write.setStatus(thread, NodeStatus::Completed); + write.setField(thread, "status", Value("notLoaded")); + write.setField(thread, "hydrationState", Value("ready")); + static_cast(write.finish()); } - if (failure != "retired-target") { - ui::NodeGraphUiAdapter adapter(runtime.graph()); - expect(waitUntil([&] { - const auto row = adapter.threadRow(target); - return row && - (project ? row->projectId : row->sectionId) == (failure.empty() ? "returned-" + sourceId : "old-" + kind); - }), - "confirmed membership changes only after successful assignment"); + NodeAction prompt{thread, NodeActionKind::SubmitPrompt}; + prompt.promptText = "Answer an ordinary thread prompt"; + expect(sendAction(runtime.channels(), std::move(prompt)), "an ordinary prompt enters the typed worker mailbox"); + std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/start" && + request->at("params").value("threadId", std::string{}) == "runtime-thread", + "typed completed state overrides conflicting raw notLoaded text"); + if (!request) + return; + expect( + bridge.reply(*request, + {{"turn", {{"id", "ordinary-runtime-turn"}, {"status", "inProgress"}, {"items", nlohmann::json::array()}}}}), + "the ordinary prompt acknowledgement is delivered"); + expect(bridge.appServerNotification( + "turn/completed", + {{"threadId", "runtime-thread"}, + {"turn", {{"id", "ordinary-runtime-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), + "the ordinary prompt reaches an authoritative terminal state"); + replyAccountUsage(bridge); + runtime.drainNotifications(); + + const auto activeTurnCleared = [&] { + const std::optional read = runtime.graph().tryRead(); + return read && read->related(thread, RelationKind::ActiveTurn).empty(); + }; + expect(waitUntil(activeTurnCleared), "the ordinary prompt releases its active-turn relation"); + + { + auto write = runtime.graph().write(); + write.setStatus(thread, NodeStatus::NotLoaded); + write.setField(thread, "status", Value("completed")); + write.setField(thread, "hydrationState", Value("ready")); + static_cast(write.finish()); + } + NodeAction resumedPrompt{thread, NodeActionKind::SubmitPrompt}; + resumedPrompt.promptText = "Resume from typed thread state"; + expect(sendAction(runtime.channels(), std::move(resumedPrompt)), "a typed not-loaded prompt enters the worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/resume" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("excludeTurns", false), + "typed not-loaded state overrides conflicting raw completed text"); + if (request) + expect(bridge.reply(*request, nlohmann::json::object()), "the typed-state resume acknowledgement is delivered"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/start" && + request->at("params").value("threadId", std::string{}) == "runtime-thread", + "the resumed prompt continues through one turn/start"); + if (request) + expect(bridge.reply( + *request, + {{"turn", {{"id", "resumed-runtime-turn"}, {"status", "inProgress"}, {"items", nlohmann::json::array()}}}}), + "the resumed prompt acknowledgement is delivered"); + expect(bridge.appServerNotification( + "turn/completed", + {{"threadId", "runtime-thread"}, + {"turn", {{"id", "resumed-runtime-turn"}, {"status", "completed"}, {"items", nlohmann::json::array()}}}}), + "the resumed prompt reaches an authoritative terminal state"); + replyAccountUsage(bridge); + runtime.drainNotifications(); + expect(waitUntil(activeTurnCleared), "the resumed prompt releases its active-turn relation"); + { + auto write = runtime.graph().write(); + write.setStatus(thread, NodeStatus::Completed); + write.setField(thread, "status", Value("idle")); + static_cast(write.finish()); } } - runtime.drainNotifications(); - } -} -void firstPromptAfterForkStartsANewTurn(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef source = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(source), - "successful fork coverage has a stable source thread"); - if (!source) - return; - - NodeAction fork{source, NodeActionKind::Fork}; - fork.payload = {{"requestedName", Value("Runtime thread (fork 1)")}, - {"cwd", Value("/fork-workspace")}, - {"baseInstructions", Value("Fork base")}, - {"developerInstructions", Value("Fork developer")}, - {"ephemeral", Value(true)}}; - expect(sendAction(runtime.channels(), std::move(fork)), - "successful fork enters the typed worker mailbox"); - std::optional request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/fork" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("cwd", std::string{}) == - "/fork-workspace" && - request->at("params").value("baseInstructions", std::string{}) == - "Fork base" && - request->at("params").value("developerInstructions", - std::string{}) == "Fork developer" && - request->at("params").value("ephemeral", false) && - request->at("params").value("excludeTurns", false) && - !request->at("params").contains("requestedName") && - !request->at("params").contains("name"), - "successful fork sends adjustable options but keeps its chosen name " - "out of thread/fork"); - if (!request) - return; - const nlohmann::json forkedThread{{"id", "runtime-fork"}, - {"name", "Runtime fork"}, - {"forkedFromId", "runtime-thread"}, - {"status", "idle"}, - {"createdAt", 3}, - {"updatedAt", 4}, - {"recencyAt", 4}, - {"turns", nlohmann::json::array()}}; - expect(bridge.reply(*request, {{"thread", forkedThread}}), - "successful fork result is delivered"); - - NodeRef forked; - expect(waitUntil([&] { - forked = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-fork"}); - if (!forked) - return false; - auto read = runtime.graph().tryRead(); - if (!read) - return false; - const auto state = read->state(forked); - const auto overlay = state->fields.find("localNameOverlay"); - return overlay != state->fields.end() && - overlay->second.asString() && - *overlay->second.asString() == "Runtime thread (fork 1)"; - }), - "successful fork immediately applies its chosen local name"); - expect(static_cast(forked), - "successful fork retains its authoritative thread node"); - if (!forked) - return; - const std::optional historyPage = bridge.receiveAppServer(); - expect(historyPage && - historyPage->value("method", std::string{}) == - "thread/turns/list" && - historyPage->at("params").value("threadId", std::string{}) == - "runtime-fork" && - historyPage->at("params").value("itemsView", std::string{}) == - "summary", - "metadata-only fork hydrates copied history through bounded pages"); - NodeAction prompt{forked, NodeActionKind::SubmitPrompt}; - prompt.promptText = "Answer after a successful fork"; - expect(sendAction(runtime.channels(), std::move(prompt)), - "the first fork prompt enters the typed worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "turn/start" && - request->at("params").value("threadId", std::string{}) == - "runtime-fork", - "the first fork prompt starts immediately without a redundant read or " - "resume"); - if (!request) - return; - expect(bridge.reply(*request, {{"turn", - {{"id", "runtime-fork-turn"}, - {"status", "inProgress"}, - {"items", nlohmann::json::array()}}}}), - "the first fork prompt acknowledgement is delivered"); - if (historyPage) - expect(bridge.reply(*historyPage, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "fork history can complete after its first prompt starts"); - expect(bridge.appServerNotification("turn/completed", - {{"threadId", "runtime-fork"}, - {"turn", - {{"id", "runtime-fork-turn"}, - {"status", "completed"}, - {"items", nlohmann::json::array()}}}}), - "the fork turn reaches an authoritative terminal state"); - replyAccountUsage(bridge); - runtime.drainNotifications(); -} + void runtimeRefreshActionsHaveExactRequestCardinality(UnixBridge& bridge, RunningRuntime& runtime) { + RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; + refresh.payload = {{"limit", Value(std::uint64_t{17})}}; + expect(sendAction(runtime.channels(), std::move(refresh)), "thread refresh enters the worker mailbox"); + std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/list" && request->at("params").value("limit", 0) == 100 && + request->at("params").value("sortKey", std::string{}) == "recency_at" && + request->at("params").value("sortDirection", std::string{}) == "desc" && + request->at("params").value("useStateDbOnly", false) && !request->at("params").contains("cursor"), + "thread refresh emits the fast DB-only Recent first page"); + if (request) + expect(bridge.reply(*request, {{"data", nlohmann::json::array({listedThread()})}, {"nextCursor", "discarded-fast-cursor"}}), + "fast thread refresh page is delivered immediately"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/list" && request->at("params").value("limit", 0) == 100 && + request->at("params").value("sortKey", std::string{}) == "recency_at" && + request->at("params").value("sortDirection", std::string{}) == "desc" && + !request->at("params").value("useStateDbOnly", true) && !request->at("params").contains("cursor"), + "thread refresh follows with one scan-and-repair first page"); + if (request) + expect(bridge.reply(*request, {{"data", nlohmann::json::array({listedThread()})}, {"nextCursor", "recent-page-2"}}), + "thread repair page establishes the reconciled pagination cursor"); + RuntimeAction loadMore{RuntimeActionKind::LoadMoreThreads}; + expect(sendAction(runtime.channels(), std::move(loadMore)), "scroll pagination enters the worker mailbox"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/list" && request->at("params").value("limit", 0) == 100 && + request->at("params").value("sortKey", std::string{}) == "recency_at" && + request->at("params").value("sortDirection", std::string{}) == "desc" && + request->at("params").value("useStateDbOnly", false) && + request->at("params").value("cursor", std::string{}) == "recent-page-2", + "scroll pagination follows the repaired cursor through the DB-only path"); + if (request) + expect(bridge.replyError(*request, -32000, "temporary paging failure"), "a transient page failure is delivered"); + RuntimeAction retryLoadMore{RuntimeActionKind::LoadMoreThreads}; + expect(sendAction(runtime.channels(), std::move(retryLoadMore)), "a failed page cursor can be retried"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/list" && + request->at("params").value("cursor", std::string{}) == "recent-page-2", + "retry preserves the failed page cursor"); + if (request) + expect(bridge.reply(*request, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), + "the retried additional page is delivered"); + expect(!bridge.receiveAppServer(100ms), "pagination stops after the requested final page"); + + RuntimeAction catalogs{RuntimeActionKind::RefreshCatalogs}; + catalogs.payload = {{"cwd", Value("/tmp/runtime-dispatch")}}; + expect(sendAction(runtime.channels(), std::move(catalogs)), "catalog refresh enters the worker mailbox"); + std::unordered_map methods; + for (int count = 0; count != 2; ++count) { + request = bridge.receiveAppServer(); + if (!request) + break; + ++methods[request->value("method", std::string{})]; + expect(request->at("params").value("cwd", std::string{}) == "/tmp/runtime-dispatch", + "catalog refresh preserves the newly authored payload"); + expect(bridge.reply(*request, {{"data", nlohmann::json::array()}}), "catalog response is delivered"); + } + expect(methods == std::unordered_map{{"model/list", 1}, {"permissionProfile/list", 1}}, + "catalog refresh emits one request for each concrete catalog"); + expect(!bridge.receiveAppServer(100ms), "catalog operations are not duplicated"); + runtime.drainNotifications(); + } -void ordinaryThreadPromptStillStartsAndCompletes(UnixBridge &bridge, - RunningRuntime &runtime) { - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), - "ordinary prompt coverage has a stable thread"); - if (!thread) - return; - - { - auto write = runtime.graph().write(); - write.setStatus(thread, NodeStatus::Completed); - write.setField(thread, "status", Value("notLoaded")); - write.setField(thread, "hydrationState", Value("ready")); - static_cast(write.finish()); - } - NodeAction prompt{thread, NodeActionKind::SubmitPrompt}; - prompt.promptText = "Answer an ordinary thread prompt"; - expect(sendAction(runtime.channels(), std::move(prompt)), - "an ordinary prompt enters the typed worker mailbox"); - std::optional request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "turn/start" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread", - "typed completed state overrides conflicting raw notLoaded text"); - if (!request) - return; - expect(bridge.reply(*request, {{"turn", - {{"id", "ordinary-runtime-turn"}, - {"status", "inProgress"}, - {"items", nlohmann::json::array()}}}}), - "the ordinary prompt acknowledgement is delivered"); - expect(bridge.appServerNotification("turn/completed", - {{"threadId", "runtime-thread"}, - {"turn", - {{"id", "ordinary-runtime-turn"}, - {"status", "completed"}, - {"items", nlohmann::json::array()}}}}), - "the ordinary prompt reaches an authoritative terminal state"); - replyAccountUsage(bridge); - runtime.drainNotifications(); - - const auto activeTurnCleared = [&] { - const std::optional read = runtime.graph().tryRead(); - return read && read->related(thread, RelationKind::ActiveTurn).empty(); - }; - expect(waitUntil(activeTurnCleared), - "the ordinary prompt releases its active-turn relation"); - - { - auto write = runtime.graph().write(); - write.setStatus(thread, NodeStatus::NotLoaded); - write.setField(thread, "status", Value("completed")); - write.setField(thread, "hydrationState", Value("ready")); - static_cast(write.finish()); - } - NodeAction resumedPrompt{thread, NodeActionKind::SubmitPrompt}; - resumedPrompt.promptText = "Resume from typed thread state"; - expect(sendAction(runtime.channels(), std::move(resumedPrompt)), - "a typed not-loaded prompt enters the worker mailbox"); - request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "thread/resume" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("excludeTurns", false), - "typed not-loaded state overrides conflicting raw completed text"); - if (request) - expect(bridge.reply(*request, nlohmann::json::object()), - "the typed-state resume acknowledgement is delivered"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "turn/start" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread", - "the resumed prompt continues through one turn/start"); - if (request) - expect(bridge.reply(*request, {{"turn", - {{"id", "resumed-runtime-turn"}, - {"status", "inProgress"}, - {"items", nlohmann::json::array()}}}}), - "the resumed prompt acknowledgement is delivered"); - expect(bridge.appServerNotification("turn/completed", - {{"threadId", "runtime-thread"}, - {"turn", - {{"id", "resumed-runtime-turn"}, - {"status", "completed"}, - {"items", nlohmann::json::array()}}}}), - "the resumed prompt reaches an authoritative terminal state"); - replyAccountUsage(bridge); - runtime.drainNotifications(); - expect(waitUntil(activeTurnCleared), - "the resumed prompt releases its active-turn relation"); - { - auto write = runtime.graph().write(); - write.setStatus(thread, NodeStatus::Completed); - write.setField(thread, "status", Value("idle")); - static_cast(write.finish()); - } -} + void startupListsResolveLineageBeforePublishing(UnixBridge& bridge, RunningRuntime& runtime) { + const auto browse = [&](const std::string& search, bool refresh = false) { + RuntimeAction action{RuntimeActionKind::LoadThreadGroup}; + action.payload = *valueFromJson({{"parameters", {{"searchTerm", search}}}, {"refresh", refresh}}).asObject(); + expect(sendAction(runtime.channels(), std::move(action)), "lineage query enters the existing browser scheduler"); + }; + const std::array ids{"startup-origin", "startup-fork", "startup-nested"}; + std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-lineage.json"); + const auto fixture = nlohmann::json::parse(input); + const auto data = fixture.at("listed"); + browse("lineage-first"); + const auto first = bridge.receiveAppServer(); + expect(first && bridge.reply(*first, {{"data", data}, {"nextCursor", nullptr}}), + "initial list has the real backend's null lineage"); + auto metadata = bridge.receiveAppServer(); + browse("lineage-overlap"); + const auto overlap = bridge.receiveAppServer(); + expect(overlap && overlap->value("method", "") == "thread/list" && + bridge.reply(*overlap, {{"data", data}, {"nextCursor", nullptr}}), + "overlapping discovery shares the two-read ceiling"); + expect(!bridge.receiveAppServer(80ms), "overlapping queries do not read the same unknown lineage concurrently"); + for (std::size_t index = 0; index < ids.size(); ++index) { + expect(metadata && metadata->value("method", "") == "thread/read" && + metadata->at("params").value("threadId", "") == ids[index] && + !metadata->at("params").value("includeTurns", true), + "startup discovery reads metadata only, once per listed thread"); + { + auto read = runtime.graph().tryRead(); + const auto thread = read->find({NodeKind::Thread, ids[index]}); + expect(!thread, "discovery belongs to the pending page and cannot create a temporary thread row"); + } + if (metadata) { + const auto thread = fixture.at("metadata").at(index); + expect(bridge.reply(*metadata, {{"thread", thread}}), "metadata provides authoritative fork lineage"); + } + if (index + 1 < ids.size()) { + metadata = bridge.receiveAppServer(); + } + } + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto root = read->find({NodeKind::Thread, ids[0]}); + const auto child = read->find({NodeKind::Thread, ids[1]}); + const auto nested = read->find({NodeKind::Thread, ids[2]}); + return root && child && nested && + read->related(root, RelationKind::ForkChildThread) == std::vector{child} && + read->related(child, RelationKind::ForkChildThread) == std::vector{nested}; + }), + "the first published page has the complete nested fork hierarchy without selecting a thread"); + expect(!bridge.receiveAppServer(80ms), "metadata discovery never requests resume or turn history"); + browse("lineage-first", true); + const auto refresh = bridge.receiveAppServer(); + expect(refresh && bridge.reply(*refresh, {{"data", data}, {"nextCursor", nullptr}}), "later listings still omit lineage"); + expect(!bridge.receiveAppServer(80ms), "resolved lineage is reused instead of read again on refresh"); + { + auto read = runtime.graph().tryRead(); + const auto root = read->find({NodeKind::Thread, ids[0]}); + expect(root && read->relatedCount(root, RelationKind::ForkChildThread) == 1, + "a later null listing cannot flatten the known fork family"); + } + const nlohmann::json retryThread{{"id", "startup-retry"}, {"name", "Retry metadata"}, {"forkedFromId", nullptr}}; + browse("lineage-retry"); + auto retryPage = bridge.receiveAppServer(); + expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), + "retry fixture lists an unknown thread"); + auto failedRead = bridge.receiveAppServer(); + expect(failedRead && bridge.replyError(*failedRead, -32000, "metadata unavailable"), + "metadata failure reaches the existing error path"); + expect(waitUntil([&] { + return retryPage && operationRetired(runtime.graph(), retryPage->at("id")); + }), + "failed discovery retires its pending list operation"); + browse("lineage-retry", true); + retryPage = bridge.receiveAppServer(); + expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), + "failed metadata discovery can be retried"); + const auto staleRead = bridge.receiveAppServer(); + browse("lineage-retry", true); + expect(waitUntil([&] { + return staleRead && operationRetired(runtime.graph(), staleRead->at("id")); + }), + "refresh retires discovery before a stale reply arrives"); + expect(staleRead && bridge.reply(*staleRead, {{"thread", retryThread}}), "refresh retires an outstanding metadata reply"); + retryPage = bridge.receiveAppServer(); + { + auto read = runtime.graph().tryRead(); + expect(!read->find({NodeKind::Thread, "startup-retry"}), "failed and superseded metadata cannot publish a temporary row"); + } + expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), + "replacement list has its own discovery operation"); + const auto freshRead = bridge.receiveAppServer(); + expect(freshRead && bridge.reply(*freshRead, {{"thread", retryThread}}), "replacement metadata completes successfully"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return static_cast(read->find({NodeKind::Thread, "startup-retry"})); + }), + "successful retry publishes the thread"); + } -void runtimeRefreshActionsHaveExactRequestCardinality(UnixBridge &bridge, - RunningRuntime &runtime) { - RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; - refresh.payload = {{"limit", Value(std::uint64_t{17})}}; - expect(sendAction(runtime.channels(), std::move(refresh)), - "thread refresh enters the worker mailbox"); - std::optional request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/list" && - request->at("params").value("limit", 0) == 100 && - request->at("params").value("sortKey", std::string{}) == - "recency_at" && - request->at("params").value("sortDirection", std::string{}) == - "desc" && - request->at("params").value("useStateDbOnly", false) && - !request->at("params").contains("cursor"), - "thread refresh emits the fast DB-only Recent first page"); - if (request) - expect(bridge.reply(*request, - {{"data", nlohmann::json::array({listedThread()})}, - {"nextCursor", "discarded-fast-cursor"}}), - "fast thread refresh page is delivered immediately"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/list" && - request->at("params").value("limit", 0) == 100 && - request->at("params").value("sortKey", std::string{}) == - "recency_at" && - request->at("params").value("sortDirection", std::string{}) == - "desc" && - !request->at("params").value("useStateDbOnly", true) && - !request->at("params").contains("cursor"), - "thread refresh follows with one scan-and-repair first page"); - if (request) - expect(bridge.reply(*request, - {{"data", nlohmann::json::array({listedThread()})}, - {"nextCursor", "recent-page-2"}}), - "thread repair page establishes the reconciled pagination cursor"); - RuntimeAction loadMore{RuntimeActionKind::LoadMoreThreads}; - expect(sendAction(runtime.channels(), std::move(loadMore)), - "scroll pagination enters the worker mailbox"); - request = bridge.receiveAppServer(); - expect( - request && request->value("method", std::string{}) == "thread/list" && - request->at("params").value("limit", 0) == 100 && - request->at("params").value("sortKey", std::string{}) == - "recency_at" && - request->at("params").value("sortDirection", std::string{}) == - "desc" && - request->at("params").value("useStateDbOnly", false) && - request->at("params").value("cursor", std::string{}) == - "recent-page-2", - "scroll pagination follows the repaired cursor through the DB-only path"); - if (request) - expect(bridge.replyError(*request, -32000, "temporary paging failure"), - "a transient page failure is delivered"); - RuntimeAction retryLoadMore{RuntimeActionKind::LoadMoreThreads}; - expect(sendAction(runtime.channels(), std::move(retryLoadMore)), - "a failed page cursor can be retried"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/list" && - request->at("params").value("cursor", std::string{}) == - "recent-page-2", - "retry preserves the failed page cursor"); - if (request) - expect(bridge.reply(*request, {{"data", nlohmann::json::array()}, - {"nextCursor", nullptr}}), - "the retried additional page is delivered"); - expect(!bridge.receiveAppServer(100ms), - "pagination stops after the requested final page"); - - RuntimeAction catalogs{RuntimeActionKind::RefreshCatalogs}; - catalogs.payload = {{"cwd", Value("/tmp/runtime-dispatch")}}; - expect(sendAction(runtime.channels(), std::move(catalogs)), - "catalog refresh enters the worker mailbox"); - std::unordered_map methods; - for (int count = 0; count != 2; ++count) { - request = bridge.receiveAppServer(); - if (!request) - break; - ++methods[request->value("method", std::string{})]; - expect(request->at("params").value("cwd", std::string{}) == - "/tmp/runtime-dispatch", - "catalog refresh preserves the newly authored payload"); - expect(bridge.reply(*request, {{"data", nlohmann::json::array()}}), - "catalog response is delivered"); - } - expect(methods == - std::unordered_map{ - {"model/list", 1}, {"permissionProfile/list", 1}}, - "catalog refresh emits one request for each concrete catalog"); - expect(!bridge.receiveAppServer(100ms), - "catalog operations are not duplicated"); - runtime.drainNotifications(); -} + void threadOrganisationUsesBoundedAuthoritativeRequests(UnixBridge& bridge, RunningRuntime& runtime) { + const auto action = [&](RuntimeActionKind kind, nlohmann::json parameters) { + RuntimeAction request{kind}; + request.payload = *valueFromJson(parameters).asObject(); + expect(sendAction(runtime.channels(), std::move(request)), "organisation action enters worker"); + }; + const nlohmann::json project{{"id", "runtime-project"}, + {"name", "Runtime project"}, + {"roots", nlohmann::json::array()}, + {"metadata", {{"foreign", "retain"}}}, + {"position", 0}, + {"createdAt", 1}, + {"updatedAt", 2}}; + const nlohmann::json section{ + {"id", "runtime-section"}, {"name", "Runtime section"}, {"createdAt", 1}, {"updatedAt", 2}, {"appearance", nullptr}}; + const auto respondPage = [&](const nlohmann::json& request) { + const auto method = request.value("method", ""); + auto data = nlohmann::json::array(); + if (method == "project/list") + data.push_back(project); + else if (method == "threadSection/list") + data.push_back(section); + else + expect(method == "thread/list", "mutation refreshes only organisational lists"); + expect(bridge.reply(request, {{"data", data}, {"nextCursor", nullptr}}), "list reply delivered"); + }; + const auto drainPages = [&] { + int count = 0; + while (const auto request = bridge.receiveAppServer(120ms)) { + respondPage(*request); + if (++count > 12) { + expect(false, "mutation must not crawl unopened groups"); + break; + } + } + }; + action(RuntimeActionKind::RefreshThreadGroups, nlohmann::json::object()); + auto first = bridge.receiveAppServer(); + auto second = bridge.receiveAppServer(); + expect(first && second && !bridge.receiveAppServer(80ms), "two catalog reads, no eager history or extra reads"); + if (!first || !second) + return; + respondPage(*first); + respondPage(*second); + expect(static_cast(findNode(runtime.graph(), {NodeKind::Project, "runtime-project"})) && + static_cast(findNode(runtime.graph(), {NodeKind::ThreadSection, "runtime-section"})), + "catalog replies establish authoritative group entities"); + + for (int i = 0; i != 3; ++i) + action(RuntimeActionKind::LoadThreadGroup, + {{"parameters", + {{"projectId", "runtime-project"}, {"searchTerm", "query-" + std::to_string(i)}, {"archived", i == 1}}}}); + first = bridge.receiveAppServer(); + second = bridge.receiveAppServer(); + expect(first && second && !bridge.receiveAppServer(80ms), "group reads have an exact two-request ceiling"); + if (!first || !second) + return; + expect(first->at("params").value("limit", 0) == 100 && first->at("params").value("useStateDbOnly", false), + "group discovery is bounded and never starts a rollout repair"); + auto archived = listedThread(); + archived["id"] = "archived-discovery"; + expect(bridge.reply(*second, {{"data", nlohmann::json::array({archived})}, {"nextCursor", nullptr}}), + "archived list response has no per-thread archive flag"); + auto third = bridge.receiveAppServer(); + expect(third && !bridge.receiveAppServer(80ms), "finishing one read admits only the next queued query"); + expect(bridge.reply(*first, {{"data", nlohmann::json::array()}, {"nextCursor", "group-next"}}), "group cursor delivered"); + if (third) + respondPage(*third); + const auto metadata = bridge.receiveAppServer(); + expect(metadata && metadata->value("method", "") == "thread/read" && + metadata->at("params").value("threadId", "") == "archived-discovery" && + !metadata->at("params").value("includeTurns", true), + "the archived page resolves lineage before publishing its rows"); + if (metadata) { + expect(bridge.reply(*metadata, {{"thread", archived}}), "archived lineage metadata completes"); + } + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto node = read ? read->find({NodeKind::Thread, "archived-discovery"}) : NodeRef{}; + return node && boolFromValue(valueMember(read->state(node)->fields, "archived")); + }), + "archive membership comes from the correlated authoritative list filter"); + action(RuntimeActionKind::LoadThreadGroup, + {{"parameters", {{"projectId", "runtime-project"}, {"searchTerm", "query-0"}, {"archived", false}}}}); + auto page = bridge.receiveAppServer(); + expect(page && page->at("params").value("cursor", "") == "group-next", "each group retains its own cursor"); + if (page) + expect(bridge.replyError(*page, -32000, "retryable"), "group page failure delivered"); + action(RuntimeActionKind::LoadThreadGroup, + {{"parameters", {{"projectId", "runtime-project"}, {"searchTerm", "query-0"}, {"archived", false}}}}); + page = bridge.receiveAppServer(); + expect(page && page->at("params").value("cursor", "") == "group-next", "failed group cursor remains retryable"); + if (page) + respondPage(*page); + + action(RuntimeActionKind::UpdateProject, + {{"projectId", "runtime-project"}, {"name", "Renamed"}, {"description", "Description 日本語"}}); + auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "project/read", "editing metadata reads latest map before replacement"); + if (!request) + return; + auto fresh = project; + fresh["metadata"]["concurrent-client"] = "new value"; + expect(bridge.reply(*request, {{"project", fresh}}), "fresh project metadata delivered"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "project/update" && + request->at("params").at("metadata") == + nlohmann::json( + {{"foreign", "retain"}, {"concurrent-client", "new value"}, {"codexui.description", "Description 日本語"}}), + "description update preserves all other clients' metadata keys"); + if (request) + expect(bridge.reply(*request, {{"project", fresh}}), "project update succeeds"); + drainPages(); + + action(RuntimeActionKind::AssignSection, {{"threadId", "runtime-thread"}, {"sectionId", "runtime-section"}}); + request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/section/move", + "section assignment uses its exact protocol operation"); + if (request) + expect(bridge.reply(*request, nlohmann::json::object()), "empty section move acknowledgement delivered"); + drainPages(); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto thread = read ? read->find({NodeKind::Thread, "runtime-thread"}) : NodeRef{}; + return thread && read->relatedCount(thread, RelationKind::SectionMembership) == 1; + }), + "empty response applies correlated section membership without a UI " + "overlay"); + + struct MutationCase { + RuntimeActionKind kind; + const char* method; + nlohmann::json parameters; + nlohmann::json result; + }; + auto createdProject = project; + createdProject["id"] = "created-project"; + auto createdSection = section; + createdSection["id"] = "created-section"; + auto assignedThread = listedThread(); + assignedThread["projectId"] = "runtime-project"; + const std::vector mutations{ + {RuntimeActionKind::CreateProject, + "project/create", + {{"name", "Created"}, {"roots", nlohmann::json::array()}, {"idempotencyKey", "unique-create-operation"}}, + {{"project", createdProject}}}, + {RuntimeActionKind::MoveProject, + "project/move", + {{"projectId", "created-project"}, {"beforeProjectId", "runtime-project"}}, + {{"project", createdProject}}}, + {RuntimeActionKind::AssignProject, + "thread/metadata/update", + {{"threadId", "runtime-thread"}, {"projectId", "runtime-project"}}, + {{"thread", assignedThread}}}, + {RuntimeActionKind::CreateSection, "threadSection/create", {{"name", "Created"}}, {{"section", createdSection}}}, + {RuntimeActionKind::UpdateSection, + "threadSection/update", + {{"sectionId", "created-section"}, {"name", "Renamed"}}, + {{"section", createdSection}}}, + {RuntimeActionKind::AssignSection, + "thread/section/move", + {{"threadId", "runtime-thread"}, {"sectionId", nullptr}}, + nlohmann::json::object()}, + {RuntimeActionKind::DeleteSection, "threadSection/delete", {{"sectionId", "created-section"}}, nlohmann::json::object()}, + {RuntimeActionKind::DeleteProject, "project/delete", {{"projectId", "created-project"}}, nlohmann::json::object()}}; + for (const auto& mutation : mutations) { + action(mutation.kind, mutation.parameters); + request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == mutation.method && request->at("params") == mutation.parameters, + std::string("exact typed organisational mutation: ") + mutation.method); + if (request) + expect(bridge.reply(*request, mutation.result), "typed organisational result delivered"); + drainPages(); + } -void startupListsResolveLineageBeforePublishing(UnixBridge& bridge, RunningRuntime& runtime) { - const auto browse = [&](const std::string& search, bool refresh = false) { - RuntimeAction action{RuntimeActionKind::LoadThreadGroup}; - action.payload = *valueFromJson({{"parameters", {{"searchTerm", search}}}, {"refresh", refresh}}).asObject(); - expect(sendAction(runtime.channels(), std::move(action)), "lineage query enters the existing browser scheduler"); - }; - const std::array ids{"startup-origin", "startup-fork", "startup-nested"}; - std::ifstream input(std::filesystem::path(__FILE__).parent_path().parent_path() / "fixtures/thread-lineage.json"); - const auto fixture = nlohmann::json::parse(input); - const auto data = fixture.at("listed"); - browse("lineage-first"); - const auto first = bridge.receiveAppServer(); - expect(first && bridge.reply(*first, {{"data", data}, {"nextCursor", nullptr}}), "initial list has the real backend's null lineage"); - auto metadata = bridge.receiveAppServer(); - browse("lineage-overlap"); - const auto overlap = bridge.receiveAppServer(); - expect(overlap && overlap->value("method", "") == "thread/list" && bridge.reply(*overlap, {{"data", data}, {"nextCursor", nullptr}}), - "overlapping discovery shares the two-read ceiling"); - expect(!bridge.receiveAppServer(80ms), "overlapping queries do not read the same unknown lineage concurrently"); - for (std::size_t index = 0; index < ids.size(); ++index) { - expect(metadata && metadata->value("method", "") == "thread/read" && metadata->at("params").value("threadId", "") == ids[index] && - !metadata->at("params").value("includeTurns", true), - "startup discovery reads metadata only, once per listed thread"); - { - auto read = runtime.graph().tryRead(); - const auto thread = read->find({NodeKind::Thread, ids[index]}); - expect(!thread, "discovery belongs to the pending page and cannot create a temporary thread row"); + // A filter abandoned and then recreated must not accept its old reply. + action(RuntimeActionKind::LoadThreadGroup, {{"parameters", {{"searchTerm", "old"}}}, {"reset", true}, {"refresh", true}}); + auto old = bridge.receiveAppServer(); + action(RuntimeActionKind::LoadThreadGroup, {{"parameters", {{"searchTerm", "new"}}}, {"reset", true}, {"refresh", true}}); + auto current = bridge.receiveAppServer(); + action(RuntimeActionKind::LoadThreadGroup, {{"parameters", {{"searchTerm", "old"}}}, {"reset", true}, {"refresh", true}}); + auto stale = listedThread(); + stale["id"] = "obsolete-query-thread"; + if (old) + expect(bridge.reply(*old, {{"data", nlohmann::json::array({stale})}, {"nextCursor", nullptr}}), + "obsolete result delivered"); + auto recreated = bridge.receiveAppServer(); + expect(recreated && recreated->at("params").value("searchTerm", "") == "old", "recreated query gets its own request identity"); + if (current) + respondPage(*current); + if (recreated) + respondPage(*recreated); + expect(waitUntil([&] { + return recreated && operationRetired(runtime.graph(), recreated->at("id")); + }), + "recreated request completes"); + { + auto read = runtime.graph().tryRead(); + expect(read && !read->find({NodeKind::Thread, "obsolete-query-thread"}), "obsolete query data never enters graph"); + } + expect(bridge.setRole("observer", "other-controller"), "observer role delivered"); + action(RuntimeActionKind::CreateSection, {{"name", "forbidden"}}); + expect(!bridge.receiveAppServer(150ms), "observer organisation mutation never reaches wire"); + expect(bridge.setRole("controller", "runtime-test"), "controller role restored"); + action(RuntimeActionKind::LoadThreadGroup, + {{"method", "project/list"}, {"refresh", true}, {"parameters", nlohmann::json::object()}}); + request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "project/list", "capability failure is scoped to its catalog"); + if (request) + expect(bridge.replyError(*request, -32601, "method not found"), "older server rejects project API"); + action(RuntimeActionKind::LoadThreadGroup, + {{"method", "project/list"}, {"refresh", true}, {"parameters", nlohmann::json::object()}}); + expect(!bridge.receiveAppServer(120ms), "unsupported catalog does not retry in a loop"); + runtime.drainNotifications(); } - if (metadata) { - const auto thread = fixture.at("metadata").at(index); - expect(bridge.reply(*metadata, {{"thread", thread}}), "metadata provides authoritative fork lineage"); + + void failedWakeUsesBoundedWorkerRecovery(UnixBridge& bridge, RunningRuntime& runtime) { + RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; + refresh.payload = {{"limit", Value(std::uint64_t{9})}}; + runtime.channels().failNextQtToWorkerWakeForTest(); + const ChannelSendStatus status = runtime.channels().sendRuntimeAction(refresh); + expect(status == ChannelSendStatus::AcceptedWakeFailed && deliveryGuaranteed(status) && wakeFailed(status) && + runtime.channels().drainQtToWorkerWake().status == EventFd::DrainStatus::Empty, + "a failed Qt wake leaves one non-retryable action for timeout " + "delivery"); + + std::optional request = bridge.receiveAppServer(1500ms); + expect(request && request->value("method", std::string{}) == "thread/list" && request->at("params").value("limit", 0) == 100 && + request->at("params").value("sortKey", std::string{}) == "recency_at" && + request->at("params").value("sortDirection", std::string{}) == "desc" && + request->at("params").value("useStateDbOnly", false), + "the existing worker thread consumes an unwoken action within its " + "bounded recovery interval using fixed Recent ordering"); + if (request) + expect(bridge.reply(*request, {{"data", nlohmann::json::array({listedThread()})}, {"nextCursor", nullptr}}), + "the timeout-delivered action completes normally"); + request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "thread/list" && + !request->at("params").value("useStateDbOnly", true), + "the admitted refresh schedules exactly one repair stage"); + if (request) + expect(bridge.reply(*request, {{"data", nlohmann::json::array({listedThread()})}, {"nextCursor", nullptr}}), + "the repair stage completes after wake recovery"); + expect(!bridge.receiveAppServer(150ms), "wake recovery never duplicates either loading stage"); + runtime.drainNotifications(); } - if (index + 1 < ids.size()) { - metadata = bridge.receiveAppServer(); + + void idleWorkerSleepsBetweenWakeRecoveryChecks(RunningRuntime& runtime) { + const auto before = runtime.workerCpuTime(); + std::this_thread::sleep_for(350ms); + const auto after = runtime.workerCpuTime(); + expect(before && after && *after >= *before && *after - *before < 100ms, + "an idle worker rearms its mailbox timeout instead of zero-timeout " + "polling"); } - } - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto root = read->find({NodeKind::Thread, ids[0]}); - const auto child = read->find({NodeKind::Thread, ids[1]}); - const auto nested = read->find({NodeKind::Thread, ids[2]}); - return root && child && nested && read->related(root, RelationKind::ForkChildThread) == std::vector{child} && - read->related(child, RelationKind::ForkChildThread) == std::vector{nested}; - }), - "the first published page has the complete nested fork hierarchy without selecting a thread"); - expect(!bridge.receiveAppServer(80ms), "metadata discovery never requests resume or turn history"); - browse("lineage-first", true); - const auto refresh = bridge.receiveAppServer(); - expect(refresh && bridge.reply(*refresh, {{"data", data}, {"nextCursor", nullptr}}), "later listings still omit lineage"); - expect(!bridge.receiveAppServer(80ms), "resolved lineage is reused instead of read again on refresh"); - { - auto read = runtime.graph().tryRead(); - const auto root = read->find({NodeKind::Thread, ids[0]}); - expect(root && read->relatedCount(root, RelationKind::ForkChildThread) == 1, - "a later null listing cannot flatten the known fork family"); - } - const nlohmann::json retryThread{{"id", "startup-retry"}, {"name", "Retry metadata"}, {"forkedFromId", nullptr}}; - browse("lineage-retry"); - auto retryPage = bridge.receiveAppServer(); - expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), - "retry fixture lists an unknown thread"); - auto failedRead = bridge.receiveAppServer(); - expect(failedRead && bridge.replyError(*failedRead, -32000, "metadata unavailable"), - "metadata failure reaches the existing error path"); - expect(waitUntil([&] { - return retryPage && operationRetired(runtime.graph(), retryPage->at("id")); - }), - "failed discovery retires its pending list operation"); - browse("lineage-retry", true); - retryPage = bridge.receiveAppServer(); - expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), - "failed metadata discovery can be retried"); - const auto staleRead = bridge.receiveAppServer(); - browse("lineage-retry", true); - expect(waitUntil([&] { - return staleRead && operationRetired(runtime.graph(), staleRead->at("id")); - }), - "refresh retires discovery before a stale reply arrives"); - expect(staleRead && bridge.reply(*staleRead, {{"thread", retryThread}}), "refresh retires an outstanding metadata reply"); - retryPage = bridge.receiveAppServer(); - { - auto read = runtime.graph().tryRead(); - expect(!read->find({NodeKind::Thread, "startup-retry"}), "failed and superseded metadata cannot publish a temporary row"); - } - expect(retryPage && bridge.reply(*retryPage, {{"data", nlohmann::json::array({retryThread})}}), - "replacement list has its own discovery operation"); - const auto freshRead = bridge.receiveAppServer(); - expect(freshRead && bridge.reply(*freshRead, {{"thread", retryThread}}), "replacement metadata completes successfully"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return static_cast(read->find({NodeKind::Thread, "startup-retry"})); - }), - "successful retry publishes the thread"); -} -void threadOrganisationUsesBoundedAuthoritativeRequests( - UnixBridge &bridge, RunningRuntime &runtime) { - const auto action = [&](RuntimeActionKind kind, nlohmann::json parameters) { - RuntimeAction request{kind}; - request.payload = *valueFromJson(parameters).asObject(); - expect(sendAction(runtime.channels(), std::move(request)), - "organisation action enters worker"); - }; - const nlohmann::json project{{"id", "runtime-project"}, - {"name", "Runtime project"}, - {"roots", nlohmann::json::array()}, - {"metadata", {{"foreign", "retain"}}}, - {"position", 0}, - {"createdAt", 1}, - {"updatedAt", 2}}; - const nlohmann::json section{{"id", "runtime-section"}, - {"name", "Runtime section"}, - {"createdAt", 1}, - {"updatedAt", 2}, - {"appearance", nullptr}}; - const auto respondPage = [&](const nlohmann::json &request) { - const auto method = request.value("method", ""); - auto data = nlohmann::json::array(); - if (method == "project/list") - data.push_back(project); - else if (method == "threadSection/list") - data.push_back(section); - else - expect(method == "thread/list", - "mutation refreshes only organisational lists"); - expect(bridge.reply(request, {{"data", data}, {"nextCursor", nullptr}}), - "list reply delivered"); - }; - const auto drainPages = [&] { - int count = 0; - while (const auto request = bridge.receiveAppServer(120ms)) { - respondPage(*request); - if (++count > 12) { - expect(false, "mutation must not crawl unopened groups"); - break; - } - } - }; - action(RuntimeActionKind::RefreshThreadGroups, nlohmann::json::object()); - auto first = bridge.receiveAppServer(); - auto second = bridge.receiveAppServer(); - expect(first && second && !bridge.receiveAppServer(80ms), - "two catalog reads, no eager history or extra reads"); - if (!first || !second) - return; - respondPage(*first); - respondPage(*second); - expect( - static_cast( - findNode(runtime.graph(), {NodeKind::Project, "runtime-project"})) && - static_cast(findNode( - runtime.graph(), {NodeKind::ThreadSection, "runtime-section"})), - "catalog replies establish authoritative group entities"); - - for (int i = 0; i != 3; ++i) - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", - {{"projectId", "runtime-project"}, - {"searchTerm", "query-" + std::to_string(i)}, - {"archived", i == 1}}}}); - first = bridge.receiveAppServer(); - second = bridge.receiveAppServer(); - expect(first && second && !bridge.receiveAppServer(80ms), - "group reads have an exact two-request ceiling"); - if (!first || !second) - return; - expect(first->at("params").value("limit", 0) == 100 && - first->at("params").value("useStateDbOnly", false), - "group discovery is bounded and never starts a rollout repair"); - auto archived = listedThread(); - archived["id"] = "archived-discovery"; - expect(bridge.reply(*second, {{"data", nlohmann::json::array({archived})}, - {"nextCursor", nullptr}}), - "archived list response has no per-thread archive flag"); - auto third = bridge.receiveAppServer(); - expect(third && !bridge.receiveAppServer(80ms), - "finishing one read admits only the next queued query"); - expect(bridge.reply(*first, {{"data", nlohmann::json::array()}, - {"nextCursor", "group-next"}}), - "group cursor delivered"); - if (third) - respondPage(*third); - const auto metadata = bridge.receiveAppServer(); - expect(metadata && metadata->value("method", "") == "thread/read" && - metadata->at("params").value("threadId", "") == "archived-discovery" && !metadata->at("params").value("includeTurns", true), - "the archived page resolves lineage before publishing its rows"); - if (metadata) { - expect(bridge.reply(*metadata, {{"thread", archived}}), "archived lineage metadata completes"); - } - expect( - waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto node = - read ? read->find({NodeKind::Thread, "archived-discovery"}) - : NodeRef{}; - return node && boolFromValue( - valueMember(read->state(node)->fields, "archived")); - }), - "archive membership comes from the correlated authoritative list filter"); - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", - {{"projectId", "runtime-project"}, - {"searchTerm", "query-0"}, - {"archived", false}}}}); - auto page = bridge.receiveAppServer(); - expect(page && page->at("params").value("cursor", "") == "group-next", - "each group retains its own cursor"); - if (page) - expect(bridge.replyError(*page, -32000, "retryable"), - "group page failure delivered"); - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", - {{"projectId", "runtime-project"}, - {"searchTerm", "query-0"}, - {"archived", false}}}}); - page = bridge.receiveAppServer(); - expect(page && page->at("params").value("cursor", "") == "group-next", - "failed group cursor remains retryable"); - if (page) - respondPage(*page); - - action(RuntimeActionKind::UpdateProject, - {{"projectId", "runtime-project"}, - {"name", "Renamed"}, - {"description", "Description 日本語"}}); - auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "project/read", - "editing metadata reads latest map before replacement"); - if (!request) - return; - auto fresh = project; - fresh["metadata"]["concurrent-client"] = "new value"; - expect(bridge.reply(*request, {{"project", fresh}}), - "fresh project metadata delivered"); - request = bridge.receiveAppServer(); - expect( - request && request->value("method", "") == "project/update" && - request->at("params").at("metadata") == - nlohmann::json({{"foreign", "retain"}, - {"concurrent-client", "new value"}, - {"codexui.description", "Description 日本語"}}), - "description update preserves all other clients' metadata keys"); - if (request) - expect(bridge.reply(*request, {{"project", fresh}}), - "project update succeeds"); - drainPages(); - - action(RuntimeActionKind::AssignSection, - {{"threadId", "runtime-thread"}, {"sectionId", "runtime-section"}}); - request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/section/move", - "section assignment uses its exact protocol operation"); - if (request) - expect(bridge.reply(*request, nlohmann::json::object()), - "empty section move acknowledgement delivered"); - drainPages(); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto thread = - read ? read->find({NodeKind::Thread, "runtime-thread"}) - : NodeRef{}; - return thread && read->relatedCount( - thread, RelationKind::SectionMembership) == 1; - }), - "empty response applies correlated section membership without a UI " - "overlay"); - - struct MutationCase { - RuntimeActionKind kind; - const char *method; - nlohmann::json parameters; - nlohmann::json result; - }; - auto createdProject = project; - createdProject["id"] = "created-project"; - auto createdSection = section; - createdSection["id"] = "created-section"; - auto assignedThread = listedThread(); - assignedThread["projectId"] = "runtime-project"; - const std::vector mutations{ - {RuntimeActionKind::CreateProject, - "project/create", - {{"name", "Created"}, {"roots", nlohmann::json::array()}, {"idempotencyKey", "unique-create-operation"}}, - {{"project", createdProject}}}, - {RuntimeActionKind::MoveProject, - "project/move", - {{"projectId", "created-project"}, {"beforeProjectId", "runtime-project"}}, - {{"project", createdProject}}}, - {RuntimeActionKind::AssignProject, - "thread/metadata/update", - {{"threadId", "runtime-thread"}, {"projectId", "runtime-project"}}, - {{"thread", assignedThread}}}, - {RuntimeActionKind::CreateSection, "threadSection/create", {{"name", "Created"}}, {{"section", createdSection}}}, - {RuntimeActionKind::UpdateSection, - "threadSection/update", - {{"sectionId", "created-section"}, {"name", "Renamed"}}, - {{"section", createdSection}}}, - {RuntimeActionKind::AssignSection, - "thread/section/move", - {{"threadId", "runtime-thread"}, {"sectionId", nullptr}}, - nlohmann::json::object()}, - {RuntimeActionKind::DeleteSection, "threadSection/delete", {{"sectionId", "created-section"}}, nlohmann::json::object()}, - {RuntimeActionKind::DeleteProject, "project/delete", {{"projectId", "created-project"}}, nlohmann::json::object()}}; - for (const auto &mutation : mutations) { - action(mutation.kind, mutation.parameters); - request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == mutation.method && - request->at("params") == mutation.parameters, - std::string("exact typed organisational mutation: ") + - mutation.method); - if (request) - expect(bridge.reply(*request, mutation.result), - "typed organisational result delivered"); - drainPages(); - } - - // A filter abandoned and then recreated must not accept its old reply. - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", {{"searchTerm", "old"}}}, - {"reset", true}, - {"refresh", true}}); - auto old = bridge.receiveAppServer(); - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", {{"searchTerm", "new"}}}, - {"reset", true}, - {"refresh", true}}); - auto current = bridge.receiveAppServer(); - action(RuntimeActionKind::LoadThreadGroup, - {{"parameters", {{"searchTerm", "old"}}}, - {"reset", true}, - {"refresh", true}}); - auto stale = listedThread(); - stale["id"] = "obsolete-query-thread"; - if (old) - expect(bridge.reply(*old, {{"data", nlohmann::json::array({stale})}, - {"nextCursor", nullptr}}), - "obsolete result delivered"); - auto recreated = bridge.receiveAppServer(); - expect(recreated && recreated->at("params").value("searchTerm", "") == "old", - "recreated query gets its own request identity"); - if (current) - respondPage(*current); - if (recreated) - respondPage(*recreated); - expect(waitUntil([&] { - return recreated && - operationRetired(runtime.graph(), recreated->at("id")); - }), - "recreated request completes"); - { - auto read = runtime.graph().tryRead(); - expect(read && !read->find({NodeKind::Thread, "obsolete-query-thread"}), - "obsolete query data never enters graph"); - } - expect(bridge.setRole("observer", "other-controller"), - "observer role delivered"); - action(RuntimeActionKind::CreateSection, {{"name", "forbidden"}}); - expect(!bridge.receiveAppServer(150ms), - "observer organisation mutation never reaches wire"); - expect(bridge.setRole("controller", "runtime-test"), - "controller role restored"); - action(RuntimeActionKind::LoadThreadGroup, - {{"method", "project/list"}, - {"refresh", true}, - {"parameters", nlohmann::json::object()}}); - request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "project/list", - "capability failure is scoped to its catalog"); - if (request) - expect(bridge.replyError(*request, -32601, "method not found"), - "older server rejects project API"); - action(RuntimeActionKind::LoadThreadGroup, - {{"method", "project/list"}, - {"refresh", true}, - {"parameters", nlohmann::json::object()}}); - expect(!bridge.receiveAppServer(120ms), - "unsupported catalog does not retry in a loop"); - runtime.drainNotifications(); -} + void reverseInteractionsRespondOnceWithAuthoredData(UnixBridge& bridge, RunningRuntime& runtime) { + expect(bridge.appServerRequest("approval-runtime", + "item/commandExecution/requestApproval", + {{"threadId", "runtime-thread"}, + {"turnId", "runtime-turn"}, + {"itemId", "runtime-command"}, + {"command", "printf runtime"}, + {"cwd", "/tmp"}}), + "approval request reaches CodexBridge"); + const NodeRef approval = findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("approval-runtime").canonical()}); + expect(static_cast(approval), "reverse approval is represented by its stable interaction node"); + if (approval) { + NodeAction resolve{approval, NodeActionKind::ResolveInteraction}; + resolve.payload = {{"choice", Value("accept")}}; + expect(sendAction(runtime.channels(), std::move(resolve)), "approval response action enters the worker mailbox"); + const std::optional response = bridge.receiveAppServer(); + expect(response && !response->contains("method") && response->value("id", std::string{}) == "approval-runtime" && + response->at("result").value("decision", std::string{}) == "accept", + "approval action emits one typed response with the original id"); + expect(!bridge.receiveAppServer(100ms), "approval response is never dual-sent"); + expect(waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + return read && !read->find({NodeKind::Interaction, ProtocolRequestId("approval-runtime").canonical()}); + }), + "accepted response retires the exact interaction"); + } -void failedWakeUsesBoundedWorkerRecovery(UnixBridge &bridge, - RunningRuntime &runtime) { - RuntimeAction refresh{RuntimeActionKind::RefreshThreads}; - refresh.payload = {{"limit", Value(std::uint64_t{9})}}; - runtime.channels().failNextQtToWorkerWakeForTest(); - const ChannelSendStatus status = - runtime.channels().sendRuntimeAction(refresh); - expect(status == ChannelSendStatus::AcceptedWakeFailed && - deliveryGuaranteed(status) && wakeFailed(status) && - runtime.channels().drainQtToWorkerWake().status == - EventFd::DrainStatus::Empty, - "a failed Qt wake leaves one non-retryable action for timeout " - "delivery"); - - std::optional request = bridge.receiveAppServer(1500ms); - expect(request && request->value("method", std::string{}) == "thread/list" && - request->at("params").value("limit", 0) == 100 && - request->at("params").value("sortKey", std::string{}) == - "recency_at" && - request->at("params").value("sortDirection", std::string{}) == - "desc" && - request->at("params").value("useStateDbOnly", false), - "the existing worker thread consumes an unwoken action within its " - "bounded recovery interval using fixed Recent ordering"); - if (request) - expect(bridge.reply(*request, - {{"data", nlohmann::json::array({listedThread()})}, - {"nextCursor", nullptr}}), - "the timeout-delivered action completes normally"); - request = bridge.receiveAppServer(); - expect(request && request->value("method", std::string{}) == "thread/list" && - !request->at("params").value("useStateDbOnly", true), - "the admitted refresh schedules exactly one repair stage"); - if (request) - expect(bridge.reply(*request, - {{"data", nlohmann::json::array({listedThread()})}, - {"nextCursor", nullptr}}), - "the repair stage completes after wake recovery"); - expect(!bridge.receiveAppServer(150ms), - "wake recovery never duplicates either loading stage"); - runtime.drainNotifications(); -} + expect(bridge.appServerRequest("input-runtime", + "item/tool/requestUserInput", + {{"threadId", "runtime-thread"}, + {"turnId", "runtime-turn"}, + {"itemId", "runtime-question"}, + {"isBlocking", true}, + {"questions", userInputQuestions("question-1")}}), + "user-input request reaches CodexBridge"); + const NodeRef input = findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("input-runtime").canonical()}); + expect(static_cast(input), "reverse user input is represented by its interaction node"); + if (input) { + NodeAction answer{input, NodeActionKind::ResolveInteraction}; + answer.payload = userInputSubmission("question-1", "yes"); + expect(sendAction(runtime.channels(), std::move(answer)), "user-input response action enters the worker mailbox"); + const std::optional response = bridge.receiveAppServer(); + expect(response && response->value("id", std::string{}) == "input-runtime" && + response->at("result").at("answers").at("question-1").at("answers") == nlohmann::json::array({"yes"}), + "user-input response moves only newly authored answers to the wire"); + expect(!bridge.receiveAppServer(100ms), "user-input response is never dual-sent"); + expect(waitUntil([&] { + return interactionRetired(runtime.graph(), input); + }), + "user-input response removes the exact interaction once"); + } + runtime.drainNotifications(); + } -void idleWorkerSleepsBetweenWakeRecoveryChecks(RunningRuntime &runtime) { - const auto before = runtime.workerCpuTime(); - std::this_thread::sleep_for(350ms); - const auto after = runtime.workerCpuTime(); - expect(before && after && *after >= *before && *after - *before < 100ms, - "an idle worker rearms its mailbox timeout instead of zero-timeout " - "polling"); -} + void invalidAuthoredReverseResponseNeverReachesWire(UnixBridge& bridge, RunningRuntime& runtime) { + expect(bridge.appServerRequest("invalid-input-runtime", + "item/tool/requestUserInput", + {{"threadId", "runtime-thread"}, + {"turnId", "runtime-turn"}, + {"itemId", "invalid-runtime-question"}, + {"isBlocking", true}, + {"questions", userInputQuestions("required-question")}}), + "invalid-submission fixture reaches CodexBridge"); + const NodeRef interaction = + findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("invalid-input-runtime").canonical()}); + expect(static_cast(interaction), "invalid-submission fixture has one exact interaction"); + if (!interaction) + return; + + const Value::Object malformed = userInputSubmission("unexpected-question", "must remain local"); + NodeAction invalid{interaction, NodeActionKind::ResolveInteraction}; + invalid.payload = malformed; + expect(sendAction(runtime.channels(), std::move(invalid)), "malformed authored response enters the typed worker mailbox"); + expect(!bridge.receiveAppServer(200ms), "malformed authored response never reaches the wire"); + expect(waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + if (!read || read->find(interaction->id()) != interaction) + return false; + const auto state = read->state(interaction); + const auto retained = state->fields.find("retainedResponsePayload"); + const auto revision = state->fields.find("responseRevision"); + const auto error = state->fields.find("error"); + return state->status == NodeStatus::Failed && error != state->fields.end() && error->second.asString() && + *error->second.asString() == "The authored pending response is invalid." && retained != state->fields.end() && + retained->second.asObject() && *retained->second.asObject() == malformed && revision != state->fields.end() && + revision->second.asUInt64() && *revision->second.asUInt64() != 0; + }), + "invalid submission remains exact, recoverable, and authoritatively " + "acknowledged"); + + NodeAction corrected{interaction, NodeActionKind::ResolveInteraction}; + corrected.payload = userInputSubmission("required-question", "corrected answer"); + expect(sendAction(runtime.channels(), std::move(corrected)), "a deliberate corrected response can reuse the exact interaction"); + const std::optional response = bridge.receiveAppServer(); + expect(response && response->value("id", std::string{}) == "invalid-input-runtime" && + response->at("result").at("answers").at("required-question").at("answers") == + nlohmann::json::array({"corrected answer"}) && + waitUntil([&] { + return interactionRetired(runtime.graph(), interaction); + }), + "the corrected authored response is sent once and retires the exact " + "interaction"); + expect(!bridge.receiveAppServer(100ms), "invalid-response recovery never duplicates the wire response"); + runtime.drainNotifications(); + } -void reverseInteractionsRespondOnceWithAuthoredData(UnixBridge &bridge, - RunningRuntime &runtime) { - expect(bridge.appServerRequest("approval-runtime", - "item/commandExecution/requestApproval", - {{"threadId", "runtime-thread"}, - {"turnId", "runtime-turn"}, - {"itemId", "runtime-command"}, - {"command", "printf runtime"}, - {"cwd", "/tmp"}}), - "approval request reaches CodexBridge"); - const NodeRef approval = findNode( - runtime.graph(), {NodeKind::Interaction, - ProtocolRequestId("approval-runtime").canonical()}); - expect(static_cast(approval), - "reverse approval is represented by its stable interaction node"); - if (approval) { - NodeAction resolve{approval, NodeActionKind::ResolveInteraction}; - resolve.payload = {{"choice", Value("accept")}}; - expect(sendAction(runtime.channels(), std::move(resolve)), - "approval response action enters the worker mailbox"); - const std::optional response = bridge.receiveAppServer(); - expect(response && !response->contains("method") && - response->value("id", std::string{}) == "approval-runtime" && - response->at("result").value("decision", std::string{}) == - "accept", - "approval action emits one typed response with the original id"); - expect(!bridge.receiveAppServer(100ms), - "approval response is never dual-sent"); - expect(waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - return read && - !read->find( - {NodeKind::Interaction, - ProtocolRequestId("approval-runtime").canonical()}); - }), - "accepted response retires the exact interaction"); - } - - expect(bridge.appServerRequest( - "input-runtime", "item/tool/requestUserInput", - {{"threadId", "runtime-thread"}, - {"turnId", "runtime-turn"}, - {"itemId", "runtime-question"}, - {"isBlocking", true}, - {"questions", userInputQuestions("question-1")}}), - "user-input request reaches CodexBridge"); - const NodeRef input = findNode( - runtime.graph(), - {NodeKind::Interaction, ProtocolRequestId("input-runtime").canonical()}); - expect(static_cast(input), - "reverse user input is represented by its interaction node"); - if (input) { - NodeAction answer{input, NodeActionKind::ResolveInteraction}; - answer.payload = userInputSubmission("question-1", "yes"); - expect(sendAction(runtime.channels(), std::move(answer)), - "user-input response action enters the worker mailbox"); - const std::optional response = bridge.receiveAppServer(); - expect(response && - response->value("id", std::string{}) == "input-runtime" && - response->at("result") - .at("answers") - .at("question-1") - .at("answers") == nlohmann::json::array({"yes"}), - "user-input response moves only newly authored answers to the wire"); - expect(!bridge.receiveAppServer(100ms), - "user-input response is never dual-sent"); - expect( - waitUntil([&] { return interactionRetired(runtime.graph(), input); }), - "user-input response removes the exact interaction once"); - } - runtime.drainNotifications(); -} + void workerRevalidatesCurrentAuthorityAndRetainsResponses(UnixBridge& bridge, RunningRuntime& runtime) { + const auto graphRoleIs = [&](std::string_view expected) { + std::optional read = runtime.graph().tryRead(); + if (!read) + return false; + const NodeRef connection = read->find({NodeKind::Connection, "connection"}); + if (!connection) + return false; + const auto state = read->state(connection); + const auto role = state->fields.find("role"); + return role != state->fields.end() && role->second.asString() && *role->second.asString() == expected; + }; + + expect(bridge.setRole("observer", "another-connection") && waitUntil([&] { + return graphRoleIs("observer"); + }), + "runtime enters observer role before receiving a reverse request"); + expect(bridge.appServerRequest("observer-input", + "item/tool/requestUserInput", + {{"threadId", "runtime-thread"}, + {"turnId", "observer-turn"}, + {"itemId", "observer-question"}, + {"isBlocking", true}, + {"questions", userInputQuestions("question")}}, + "observer"), + "observer-delivered reverse request reaches the graph"); + const NodeRef observerInput = + findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("observer-input").canonical()}); + expect(static_cast(observerInput), "observer-delivered request has one stable interaction"); + + expect(bridge.setRole("controller", "runtime-test") && waitUntil([&] { + return graphRoleIs("controller"); + }), + "the same connection can subsequently claim controller"); + if (observerInput) { + NodeAction response{observerInput, NodeActionKind::ResolveInteraction}; + response.payload = userInputSubmission("question", "claimed"); + expect(sendAction(runtime.channels(), std::move(response)), "new controller admits the earlier observer request response"); + const std::optional wire = bridge.receiveAppServer(); + expect(wire && wire->value("id", std::string{}) == "observer-input" && + wire->at("result").at("answers").at("question").at("answers") == nlohmann::json::array({"claimed"}), + "current controller role, not receipt-time role, authorizes the " + "exact response"); + } -void invalidAuthoredReverseResponseNeverReachesWire(UnixBridge &bridge, - RunningRuntime &runtime) { - expect(bridge.appServerRequest( - "invalid-input-runtime", "item/tool/requestUserInput", - {{"threadId", "runtime-thread"}, - {"turnId", "runtime-turn"}, - {"itemId", "invalid-runtime-question"}, - {"isBlocking", true}, - {"questions", userInputQuestions("required-question")}}), - "invalid-submission fixture reaches CodexBridge"); - const NodeRef interaction = - findNode(runtime.graph(), - {NodeKind::Interaction, - ProtocolRequestId("invalid-input-runtime").canonical()}); - expect(static_cast(interaction), - "invalid-submission fixture has one exact interaction"); - if (!interaction) - return; - - const Value::Object malformed = - userInputSubmission("unexpected-question", "must remain local"); - NodeAction invalid{interaction, NodeActionKind::ResolveInteraction}; - invalid.payload = malformed; - expect(sendAction(runtime.channels(), std::move(invalid)), - "malformed authored response enters the typed worker mailbox"); - expect(!bridge.receiveAppServer(200ms), - "malformed authored response never reaches the wire"); - expect( - waitUntil([&] { - std::optional read = runtime.graph().tryRead(); - if (!read || read->find(interaction->id()) != interaction) - return false; - const auto state = read->state(interaction); - const auto retained = state->fields.find("retainedResponsePayload"); - const auto revision = state->fields.find("responseRevision"); - const auto error = state->fields.find("error"); - return state->status == NodeStatus::Failed && - error != state->fields.end() && error->second.asString() && - *error->second.asString() == - "The authored pending response is invalid." && - retained != state->fields.end() && retained->second.asObject() && - *retained->second.asObject() == malformed && - revision != state->fields.end() && revision->second.asUInt64() && - *revision->second.asUInt64() != 0; - }), - "invalid submission remains exact, recoverable, and authoritatively " - "acknowledged"); - - NodeAction corrected{interaction, NodeActionKind::ResolveInteraction}; - corrected.payload = - userInputSubmission("required-question", "corrected answer"); - expect(sendAction(runtime.channels(), std::move(corrected)), - "a deliberate corrected response can reuse the exact interaction"); - const std::optional response = bridge.receiveAppServer(); - expect(response && - response->value("id", std::string{}) == "invalid-input-runtime" && - response->at("result") - .at("answers") - .at("required-question") - .at("answers") == - nlohmann::json::array({"corrected answer"}) && - waitUntil([&] { - return interactionRetired(runtime.graph(), interaction); - }), - "the corrected authored response is sent once and retires the exact " - "interaction"); - expect(!bridge.receiveAppServer(100ms), - "invalid-response recovery never duplicates the wire response"); - runtime.drainNotifications(); -} + expect(bridge.appServerRequest("lost-control-input", + "item/tool/requestUserInput", + {{"threadId", "runtime-thread"}, + {"turnId", "lost-control-turn"}, + {"itemId", "lost-control-question"}, + {"isBlocking", true}, + {"questions", userInputQuestions("question")}}), + "second reverse request arrives while controlled"); + const NodeRef lostControl = + findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("lost-control-input").canonical()}); + expect(bridge.setRole("observer", "another-connection") && waitUntil([&] { + return graphRoleIs("observer"); + }), + "controller loss is visible before queued action consumption"); + if (lostControl) { + NodeAction rejected{lostControl, NodeActionKind::ResolveInteraction}; + rejected.payload = userInputSubmission("question", "preserved"); + expect(sendAction(runtime.channels(), std::move(rejected)), "stale Qt response still enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), "worker revalidation prevents a response after controller loss"); + expect(waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + if (!read) + return false; + const NodeRef current = read->find(lostControl->id()); + if (current != lostControl || read->state(current)->status != NodeStatus::Failed) + return false; + const auto state = read->state(current); + const auto retained = state->fields.find("retainedResponsePayload"); + return retained != state->fields.end() && retained->second.asObject() && + *retained->second.asObject() == userInputSubmission("question", "preserved"); + }), + "worker rejection keeps the authored answer on the actionable " + "interaction for manual recovery"); + } -void workerRevalidatesCurrentAuthorityAndRetainsResponses( - UnixBridge &bridge, RunningRuntime &runtime) { - const auto graphRoleIs = [&](std::string_view expected) { - std::optional read = runtime.graph().tryRead(); - if (!read) - return false; - const NodeRef connection = read->find({NodeKind::Connection, "connection"}); - if (!connection) - return false; - const auto state = read->state(connection); - const auto role = state->fields.find("role"); - return role != state->fields.end() && role->second.asString() && - *role->second.asString() == expected; - }; - - expect(bridge.setRole("observer", "another-connection") && - waitUntil([&] { return graphRoleIs("observer"); }), - "runtime enters observer role before receiving a reverse request"); - expect( - bridge.appServerRequest("observer-input", "item/tool/requestUserInput", - {{"threadId", "runtime-thread"}, - {"turnId", "observer-turn"}, - {"itemId", "observer-question"}, - {"isBlocking", true}, - {"questions", userInputQuestions("question")}}, - "observer"), - "observer-delivered reverse request reaches the graph"); - const NodeRef observerInput = findNode( - runtime.graph(), - {NodeKind::Interaction, ProtocolRequestId("observer-input").canonical()}); - expect(static_cast(observerInput), - "observer-delivered request has one stable interaction"); - - expect(bridge.setRole("controller", "runtime-test") && - waitUntil([&] { return graphRoleIs("controller"); }), - "the same connection can subsequently claim controller"); - if (observerInput) { - NodeAction response{observerInput, NodeActionKind::ResolveInteraction}; - response.payload = userInputSubmission("question", "claimed"); - expect(sendAction(runtime.channels(), std::move(response)), - "new controller admits the earlier observer request response"); - const std::optional wire = bridge.receiveAppServer(); - expect(wire && wire->value("id", std::string{}) == "observer-input" && - wire->at("result").at("answers").at("question").at("answers") == - nlohmann::json::array({"claimed"}), - "current controller role, not receipt-time role, authorizes the " - "exact response"); - } - - expect(bridge.appServerRequest( - "lost-control-input", "item/tool/requestUserInput", - {{"threadId", "runtime-thread"}, - {"turnId", "lost-control-turn"}, - {"itemId", "lost-control-question"}, - {"isBlocking", true}, - {"questions", userInputQuestions("question")}}), - "second reverse request arrives while controlled"); - const NodeRef lostControl = findNode( - runtime.graph(), {NodeKind::Interaction, - ProtocolRequestId("lost-control-input").canonical()}); - expect(bridge.setRole("observer", "another-connection") && - waitUntil([&] { return graphRoleIs("observer"); }), - "controller loss is visible before queued action consumption"); - if (lostControl) { - NodeAction rejected{lostControl, NodeActionKind::ResolveInteraction}; - rejected.payload = userInputSubmission("question", "preserved"); - expect(sendAction(runtime.channels(), std::move(rejected)), - "stale Qt response still enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker revalidation prevents a response after controller loss"); - expect(waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - if (!read) - return false; - const NodeRef current = read->find(lostControl->id()); - if (current != lostControl || - read->state(current)->status != NodeStatus::Failed) - return false; - const auto state = read->state(current); - const auto retained = - state->fields.find("retainedResponsePayload"); - return retained != state->fields.end() && - retained->second.asObject() && - *retained->second.asObject() == - userInputSubmission("question", "preserved"); - }), - "worker rejection keeps the authored answer on the actionable " - "interaction for manual recovery"); - } - - const NodeRef thread = - findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - if (thread) { - NodeAction rename{thread, NodeActionKind::Rename}; - rename.payload = {{"name", Value("must not leave observer")}}; - expect(sendAction(runtime.channels(), std::move(rename)), - "observer thread mutation enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker current-role validation blocks provider mutations"); - } - expect(bridge.setRole("controller", "runtime-test") && - waitUntil([&] { return graphRoleIs("controller"); }), - "runtime restores controller for remaining coverage"); - if (lostControl) { - NodeAction retry{lostControl, NodeActionKind::ResolveInteraction}; - retry.payload = userInputSubmission("question", "preserved"); - expect(sendAction(runtime.channels(), std::move(retry)), - "the user can explicitly resubmit the preserved response"); - const std::optional wire = bridge.receiveAppServer(); - expect(wire && wire->value("id", std::string{}) == "lost-control-input" && - wire->at("result").at("answers").at("question").at("answers") == - nlohmann::json::array({"preserved"}) && - waitUntil([&] { - return interactionRetired(runtime.graph(), lostControl); - }), - "manual recovery sends exactly once after control is restored"); - } - - expect(bridge.appServerNotification( - "turn/started", - {{"threadId", "runtime-thread"}, - {"turn", - {{"id", "already-finished-turn"}, {"status", "inProgress"}}}}), - "active turn fixture reaches the worker"); - const NodeRef finishedTurn = - findNode(runtime.graph(), - scopedTurnNodeId("runtime-thread", "already-finished-turn")); - expect(bridge.appServerNotification( - "turn/completed", - {{"threadId", "runtime-thread"}, - {"turn", - {{"id", "already-finished-turn"}, {"status", "completed"}}}}) && - waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - return read && finishedTurn && - read->state(finishedTurn)->status == - NodeStatus::Completed; - }), - "turn fixture is terminal before the stale stop action"); - replyAccountUsage(bridge); - if (finishedTurn) { - NodeAction stop{finishedTurn, NodeActionKind::InterruptTurn}; - expect(sendAction(runtime.channels(), std::move(stop)), - "stale stop enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker revalidation blocks interrupt for a non-active turn"); - } - - const auto threadArchived = [&](bool expected) { - std::optional read = runtime.graph().tryRead(); - if (!read || !thread) - return false; - const NodeRef current = read->find(thread->id()); - if (current != thread) - return false; - const auto state = read->state(current); - const auto archived = state->fields.find("archived"); - return archived != state->fields.end() && archived->second.asBool() && - *archived->second.asBool() == expected; - }; - expect(thread && - bridge.appServerNotification("thread/archived", - {{"threadId", "runtime-thread"}}) && - waitUntil([&] { return threadArchived(true); }), - "the worker observes an authoritative archive before a queued " - "duplicate action"); - if (thread) { - NodeAction duplicateArchive{thread, NodeActionKind::Archive}; - expect(sendAction(runtime.channels(), std::move(duplicateArchive)), - "a now-stale archive action still enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker lifecycle revalidation blocks duplicate archive"); - } - - expect(bridge.appServerNotification( - "turn/started", - {{"threadId", "runtime-thread"}, - {"turn", - {{"id", "archived-active-turn"}, {"status", "inProgress"}}}}), - "an out-of-order active turn can coexist with archived thread state"); - const NodeRef archivedActiveTurn = - findNode(runtime.graph(), - scopedTurnNodeId("runtime-thread", "archived-active-turn")); - if (archivedActiveTurn) { - NodeAction stop{archivedActiveTurn, NodeActionKind::InterruptTurn}; - stop.payload = {{"turnId", Value("stale-payload-turn")}}; - expect(sendAction(runtime.channels(), std::move(stop)), - "an archived-thread stop enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker revalidation prevents archived active state from reaching " - "CodexBridge"); - } - - expect(bridge.appServerNotification("thread/unarchived", - {{"threadId", "runtime-thread"}}) && - waitUntil([&] { return threadArchived(false); }), - "the authoritative thread returns to unarchived state"); - if (thread) { - NodeAction duplicateUnarchive{thread, NodeActionKind::Unarchive}; - expect(sendAction(runtime.channels(), std::move(duplicateUnarchive)), - "a now-stale unarchive action still enters the typed mailbox"); - expect(!bridge.receiveAppServer(200ms), - "worker lifecycle revalidation blocks duplicate unarchive"); - } - if (archivedActiveTurn) { - NodeAction stop{archivedActiveTurn, NodeActionKind::InterruptTurn}; - stop.payload = {{"threadId", Value("stale-payload-thread")}, - {"turnId", Value("stale-payload-turn")}}; - expect(sendAction(runtime.channels(), std::move(stop)), - "the current unarchived active turn admits a stop action"); - const std::optional request = bridge.receiveAppServer(); - expect(request && - request->value("method", std::string{}) == "turn/interrupt" && - request->at("params").value("threadId", std::string{}) == - "runtime-thread" && - request->at("params").value("turnId", std::string{}) == - "archived-active-turn", - "worker addressing replaces stale payload ids with the current " - "canonical active-turn address"); - if (request) - expect(bridge.reply(*request, nlohmann::json::object()), - "the revalidated interrupt response reaches the worker"); - } - - expect(bridge.appServerNotification("thread/started", - {{"thread", - {{"id", "removed-action-thread"}, - {"name", "Removed before dispatch"}, - {"cwd", "/tmp"}}}}), - "stale thread-action fixture reaches the graph"); - const NodeRef removedActionThread = - findNode(runtime.graph(), {NodeKind::Thread, "removed-action-thread"}); - expect(removedActionThread && - bridge.appServerNotification( - "thread/deleted", {{"threadId", "removed-action-thread"}}) && - waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - return read && !read->find(removedActionThread->id()); - }), - "the worker retires the exact action target before dispatch"); - if (removedActionThread) { - NodeAction staleRename{removedActionThread, NodeActionKind::Rename}; - staleRename.payload = {{"name", Value("must not reach provider")}}; - expect(sendAction(runtime.channels(), std::move(staleRename)), - "a removed target remains safely pinnable in the typed queue"); - expect(!bridge.receiveAppServer(200ms), - "worker membership revalidation blocks a removed thread target"); - } - - expect( - bridge.appServerRequest("generation-input", "item/tool/requestUserInput", - {{"threadId", "runtime-thread"}, - {"turnId", "generation-turn"}, - {"itemId", "generation-question"}, - {"isBlocking", true}, - {"questions", userInputQuestions("question")}}), - "generation-change request reaches the current graph"); - const NodeRef generationInput = findNode( - runtime.graph(), {NodeKind::Interaction, - ProtocolRequestId("generation-input").canonical()}); - expect(bridge.setProviderGeneration(2), - "a new provider generation reaches the runtime"); - std::size_t refreshes = 0; - while (refreshes != 7) { - const std::optional refresh = bridge.receiveAppServer(); - if (!refresh) - break; - nlohmann::json result{{"data", nlohmann::json::array()}}; - if (refresh->value("method", std::string{}) == "thread/list") - result["nextCursor"] = nullptr; - if (refresh->value("method", std::string{}) == "account/usage/read") - result = {{"summary", {{"lifetimeTokens", 13000}}}}; - if (bridge.reply(*refresh, std::move(result))) - ++refreshes; - } - expect(refreshes == 7 && generationInput && waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - if (!read) - return false; - const NodeRef current = read->find(generationInput->id()); - if (current != generationInput || - read->state(current)->status != NodeStatus::Failed) - return false; - const auto state = read->state(current); - const auto recovery = state->fields.find("recoveryOnly"); - return recovery != state->fields.end() && - recovery->second.asBool() && *recovery->second.asBool(); - }), - "provider replacement keeps the expired interaction as explicit " - "response-recovery state"); - if (generationInput) { - NodeAction response{generationInput, NodeActionKind::ResolveInteraction}; - response.payload = userInputSubmission("question", "generation"); - expect(sendAction(runtime.channels(), std::move(response)), - "authored response can reach the worker after generation reset"); - expect(!bridge.receiveAppServer(200ms), - "expired-generation response is never sent to the replacement " - "provider"); - expect(waitUntil([&] { - std::optional read = - runtime.graph().tryRead(); - if (!read) - return false; - const NodeRef current = read->find(generationInput->id()); - if (current != generationInput) - return false; - const auto state = read->state(current); - const auto retained = - state->fields.find("retainedResponsePayload"); - return retained != state->fields.end() && - retained->second.asObject() && - *retained->second.asObject() == - userInputSubmission("question", "generation"); - }), - "generation rejection preserves newly authored response data in " - "the shared graph"); - } - runtime.drainNotifications(); -} + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + if (thread) { + NodeAction rename{thread, NodeActionKind::Rename}; + rename.payload = {{"name", Value("must not leave observer")}}; + expect(sendAction(runtime.channels(), std::move(rename)), "observer thread mutation enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), "worker current-role validation blocks provider mutations"); + } + expect(bridge.setRole("controller", "runtime-test") && waitUntil([&] { + return graphRoleIs("controller"); + }), + "runtime restores controller for remaining coverage"); + if (lostControl) { + NodeAction retry{lostControl, NodeActionKind::ResolveInteraction}; + retry.payload = userInputSubmission("question", "preserved"); + expect(sendAction(runtime.channels(), std::move(retry)), "the user can explicitly resubmit the preserved response"); + const std::optional wire = bridge.receiveAppServer(); + expect(wire && wire->value("id", std::string{}) == "lost-control-input" && + wire->at("result").at("answers").at("question").at("answers") == nlohmann::json::array({"preserved"}) && + waitUntil([&] { + return interactionRetired(runtime.graph(), lostControl); + }), + "manual recovery sends exactly once after control is restored"); + } -void remainingReverseRequestFamiliesRoundTripExactlyOnce( - UnixBridge &bridge, RunningRuntime &runtime) { - const auto roundTrip = - [&](std::string id, std::string method, nlohmann::json requestPayload, - Value::Object responsePayload) -> std::optional { - expect(bridge.appServerRequest(id, method, std::move(requestPayload)), - method + " reaches CodexBridge"); - const NodeRef interaction = - findNode(runtime.graph(), - {NodeKind::Interaction, ProtocolRequestId(id).canonical()}); - expect(static_cast(interaction), - method + " creates its stable interaction node"); - if (!interaction) - return std::nullopt; - - NodeAction resolve{interaction, NodeActionKind::ResolveInteraction}; - resolve.payload = std::move(responsePayload); - expect(sendAction(runtime.channels(), std::move(resolve)), - method + " typed response enters the worker mailbox"); - std::optional response = bridge.receiveAppServer(); - expect(response && response->value("id", std::string{}) == id, - method + " response preserves the original JSON-RPC id"); - expect(!bridge.receiveAppServer(100ms), - method + " response is never dual-sent"); - expect(waitUntil([&] { - return interactionRetired(runtime.graph(), interaction); - }), - method + " response removes the exact interaction once"); - return response; - }; - - const nlohmann::json address{{"threadId", "runtime-thread"}, - {"turnId", "reverse-turn"}}; - - nlohmann::json fileChangeRequest = address; - fileChangeRequest["itemId"] = "reverse-file-change"; - fileChangeRequest["reason"] = "write the focused test"; - std::optional response = - roundTrip("file-change-runtime", "item/fileChange/requestApproval", - std::move(fileChangeRequest), {{"choice", Value("accept")}}); - expect(response && response->contains("result") && - response->at("result") == nlohmann::json{{"decision", "accept"}}, - "file-change approval encodes the authored decision exactly"); - - nlohmann::json elicitationRequest = address; - elicitationRequest["serverName"] = "test-mcp"; - elicitationRequest["message"] = "Choose a value"; - elicitationRequest["mode"] = "form"; - elicitationRequest["requestedSchema"] = nlohmann::json{{"type", "object"}}; - response = - roundTrip("mcp-runtime", "mcpServer/elicitation/request", - std::move(elicitationRequest), - {{"choice", Value("accept")}, - {"input", Value(Value::Object{{"choice", Value("safe")}})}, - {"metadata", Value(Value::Object{{"source", Value("qt")}})}}); - expect(response && response->contains("result") && - response->at("result") == - nlohmann::json{{"action", "accept"}, - {"content", {{"choice", "safe"}}}, - {"_meta", {{"source", "qt"}}}}, - "MCP elicitation encodes action, content, and metadata exactly"); - - const nlohmann::json requestedPermissions{ - {"fileSystem", {{"read", nlohmann::json::array({"/workspace"})}}}, - {"network", {{"enabled", false}}}}; - nlohmann::json permissionsRequest = address; - permissionsRequest["itemId"] = "reverse-permissions"; - permissionsRequest["permissions"] = requestedPermissions; - response = - roundTrip("permissions-runtime", "item/permissions/requestApproval", - std::move(permissionsRequest), {{"choice", Value("turn")}}); - expect(response && response->contains("result") && - response->at("result") == - nlohmann::json{{"permissions", requestedPermissions}, - {"scope", "turn"}}, - "permission approval returns the exact requested permission object " - "and authored scope"); - - nlohmann::json dynamicToolRequest = address; - dynamicToolRequest["callId"] = "reverse-dynamic-tool"; - dynamicToolRequest["tool"] = "unsupported_tool"; - dynamicToolRequest["arguments"] = nlohmann::json{{"value", 7}}; - response = roundTrip("dynamic-tool-runtime", "item/tool/call", - std::move(dynamicToolRequest), - {{"choice", Value("unavailable")}}); - expect(response && response->contains("result") && - response->at("result") == - nlohmann::json{ - {"contentItems", - nlohmann::json::array( - {{{"type", "inputText"}, - {"text", - "CodexUI does not provide this dynamic tool"}}})}, - {"success", false}}, - "dynamic-tool response encodes one explicit failure content item"); - - response = roundTrip( - "auth-refresh-runtime", "account/chatgptAuthTokens/refresh", - {{"reason", "unauthorized"}}, {{"choice", Value("unsupported")}}); - expect(response && response->contains("error") && - response->at("error").value("code", 0) == -32601 && - response->at("error").value("message", std::string{}) == - "CodexUI does not support authentication token refresh", - "authentication refresh emits the explicit unsupported error"); - - response = roundTrip("attestation-runtime", "attestation/generate", - {{"challenge", "challenge-value"}}, - {{"choice", Value("unsupported")}}); - expect(response && response->contains("error") && - response->at("error").value("code", 0) == -32601 && - response->at("error").value("message", std::string{}) == - "CodexUI does not support attestation generation", - "attestation generation emits the explicit unsupported error"); - - response = roundTrip("apply-patch-runtime", "applyPatchApproval", - {{"conversationId", "runtime-thread"}, - {"callId", "reverse-apply-patch"}, - {"fileChanges", nlohmann::json::object()}}, - {{"choice", Value("denied")}}); - expect( - response && response->contains("result") && - response->at("result") == - nlohmann::json{{"decision", - {{"denied", {{"rejection", "Denied by user"}}}}}}, - "apply-patch approval derives the typed denial from authored intent"); - - response = roundTrip("exec-command-runtime", "execCommandApproval", - {{"conversationId", "runtime-thread"}, - {"callId", "reverse-exec"}, - {"command", nlohmann::json::array({"printf", "test"})}, - {"cwd", "/tmp"}}, - {{"choice", Value("approved_for_session")}}); - expect(response && response->contains("result") && - response->at("result") == - nlohmann::json{{"decision", "approved_for_session"}}, - "exec-command approval maps the authored session decision exactly"); - - runtime.drainNotifications(); -} + expect(bridge.appServerNotification( + "turn/started", + {{"threadId", "runtime-thread"}, {"turn", {{"id", "already-finished-turn"}, {"status", "inProgress"}}}}), + "active turn fixture reaches the worker"); + const NodeRef finishedTurn = findNode(runtime.graph(), scopedTurnNodeId("runtime-thread", "already-finished-turn")); + expect(bridge.appServerNotification( + "turn/completed", + {{"threadId", "runtime-thread"}, {"turn", {{"id", "already-finished-turn"}, {"status", "completed"}}}}) && + waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + return read && finishedTurn && read->state(finishedTurn)->status == NodeStatus::Completed; + }), + "turn fixture is terminal before the stale stop action"); + replyAccountUsage(bridge); + if (finishedTurn) { + NodeAction stop{finishedTurn, NodeActionKind::InterruptTurn}; + expect(sendAction(runtime.channels(), std::move(stop)), "stale stop enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), "worker revalidation blocks interrupt for a non-active turn"); + } -void unknownInboundIsRetainedWithoutCorruptingKnownState( - UnixBridge &bridge, RunningRuntime &runtime) { - constexpr std::string_view RequestMethod = "future/runtime-request"; - expect(bridge.appServerRequest( - "future-runtime-request", std::string(RequestMethod), - {{"threadId", "runtime-thread"}, {"futureValue", 23}}), - "unknown inbound request reaches CodexBridge"); - const std::optional rejection = bridge.receiveAppServer(); - expect(rejection && !rejection->contains("method") && - rejection->value("id", std::string{}) == - "future-runtime-request" && - rejection->contains("error") && - rejection->at("error").value("code", 0) == -32601, - "CodexBridge automatically rejects an unregistered server request"); - { - std::optional read = runtime.graph().tryRead(); - expect(read && - !read->find( - {NodeKind::Interaction, - ProtocolRequestId("future-runtime-request").canonical()}), - "unknown server request creates no phantom UI interaction"); - } - expect(!bridge.receiveAppServer(100ms), - "unknown server request is rejected exactly once"); - - constexpr std::string_view Method = "future/runtime-event"; - expect(bridge.appServerNotification( - std::string(Method), {{"threadId", "runtime-thread"}, - {"name", "must-not-overwrite-known-thread"}, - {"futureValue", 17}}), - "unknown inbound notification reaches CodexBridge's raw hook"); - - const std::string unknownId = std::to_string(static_cast( - ProtocolDirection::ServerNotification)) + - ":" + std::string(Method); - const NodeRef unknown = - findNode(runtime.graph(), {NodeKind::UnknownProtocol, unknownId}); - expect(static_cast(unknown), - "unknown inbound notification is retained in the shared graph"); - - std::optional read = runtime.graph().tryRead(); - const NodeRef thread = - read ? read->find({NodeKind::Thread, "runtime-thread"}) : NodeRef{}; - const auto unknownState = read && unknown ? read->state(unknown) : nullptr; - const auto threadState = read && thread ? read->state(thread) : nullptr; - const auto unknownMethod = unknownState ? unknownState->fields.find("method") - : Value::Object::const_iterator{}; - const auto knownName = threadState ? threadState->fields.find("name") - : Value::Object::const_iterator{}; - expect(unknownState && unknownMethod != unknownState->fields.end() && - unknownMethod->second.asString() && - *unknownMethod->second.asString() == Method, - "unknown graph state identifies the unrecognized method"); - expect(threadState && knownName != threadState->fields.end() && - knownName->second.asString() && - *knownName->second.asString() == "Runtime dispatch", - "unknown addressed fields cannot mutate a known thread"); - runtime.drainNotifications(); -} + const auto threadArchived = [&](bool expected) { + std::optional read = runtime.graph().tryRead(); + if (!read || !thread) + return false; + const NodeRef current = read->find(thread->id()); + if (current != thread) + return false; + const auto state = read->state(current); + const auto archived = state->fields.find("archived"); + return archived != state->fields.end() && archived->second.asBool() && *archived->second.asBool() == expected; + }; + expect(thread && bridge.appServerNotification("thread/archived", {{"threadId", "runtime-thread"}}) && waitUntil([&] { + return threadArchived(true); + }), + "the worker observes an authoritative archive before a queued " + "duplicate action"); + if (thread) { + NodeAction duplicateArchive{thread, NodeActionKind::Archive}; + expect(sendAction(runtime.channels(), std::move(duplicateArchive)), + "a now-stale archive action still enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), "worker lifecycle revalidation blocks duplicate archive"); + } -void explicitReconnectsControlTheLatestFlow(UnixBridge &bridge, - RunningRuntime &runtime) { - for (const auto kind : - {RuntimeActionKind::Reconnect, RuntimeActionKind::Reconnect, - RuntimeActionKind::Disconnect}) { - RuntimeAction action; - action.kind = kind; - expect(sendAction(runtime.channels(), std::move(action)), - "connection lifecycle action reaches the worker"); - expect(waitUntil([&] { return bridge.peerClosed(); }), - "terminating the current flow closes the current connection"); - if (kind == RuntimeActionKind::Disconnect) { - expect(!bridge.acceptClient(100ms), - "manual disconnect does not start another flow"); - RuntimeAction connect; - connect.kind = RuntimeActionKind::Connect; - expect(sendAction(runtime.channels(), std::move(connect)), - "explicit connect is admitted after flow termination"); - } - expect(bridge.acceptClient(), - "each explicit reconnect or connect starts a fresh working flow"); - runtime.drainNotifications(); - } -} + expect( + bridge.appServerNotification( + "turn/started", {{"threadId", "runtime-thread"}, {"turn", {{"id", "archived-active-turn"}, {"status", "inProgress"}}}}), + "an out-of-order active turn can coexist with archived thread state"); + const NodeRef archivedActiveTurn = findNode(runtime.graph(), scopedTurnNodeId("runtime-thread", "archived-active-turn")); + if (archivedActiveTurn) { + NodeAction stop{archivedActiveTurn, NodeActionKind::InterruptTurn}; + stop.payload = {{"turnId", Value("stale-payload-turn")}}; + expect(sendAction(runtime.channels(), std::move(stop)), "an archived-thread stop enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), + "worker revalidation prevents archived active state from reaching " + "CodexBridge"); + } -void endpointReconfigurationUsesTheSelectedAddress(UnixBridge &bridge, - RunningRuntime &runtime) { - UnixBridge alternative("-alternative"); - expect(alternative.valid(), "the alternative endpoint has its own listener"); - UnixBridge *previous = &bridge; - for (UnixBridge *next : {&alternative, &bridge}) { - RuntimeAction configure; - configure.kind = RuntimeActionKind::ConfigureConnection; - configure.payload = {{"transport", Value("unix")}, - {"path", Value(next->path())}}; - expect(sendAction(runtime.channels(), std::move(configure)), - "an endpoint change reaches the existing connection transition"); - expect(waitUntil([&] { return previous->peerClosed(); }), - "reconfiguration closes the previous endpoint"); - expect(next->acceptClient(), - "reconfiguration connects to the new endpoint, including a reused client"); - previous = next; - runtime.drainNotifications(); - } -} + expect(bridge.appServerNotification("thread/unarchived", {{"threadId", "runtime-thread"}}) && waitUntil([&] { + return threadArchived(false); + }), + "the authoritative thread returns to unarchived state"); + if (thread) { + NodeAction duplicateUnarchive{thread, NodeActionKind::Unarchive}; + expect(sendAction(runtime.channels(), std::move(duplicateUnarchive)), + "a now-stale unarchive action still enters the typed mailbox"); + expect(!bridge.receiveAppServer(200ms), "worker lifecycle revalidation blocks duplicate unarchive"); + } + if (archivedActiveTurn) { + NodeAction stop{archivedActiveTurn, NodeActionKind::InterruptTurn}; + stop.payload = {{"threadId", Value("stale-payload-thread")}, {"turnId", Value("stale-payload-turn")}}; + expect(sendAction(runtime.channels(), std::move(stop)), "the current unarchived active turn admits a stop action"); + const std::optional request = bridge.receiveAppServer(); + expect(request && request->value("method", std::string{}) == "turn/interrupt" && + request->at("params").value("threadId", std::string{}) == "runtime-thread" && + request->at("params").value("turnId", std::string{}) == "archived-active-turn", + "worker addressing replaces stale payload ids with the current " + "canonical active-turn address"); + if (request) + expect(bridge.reply(*request, nlohmann::json::object()), "the revalidated interrupt response reaches the worker"); + } -void filesystemRequestsRetainResultsUntilCollected(UnixBridge& bridge, RunningRuntime& runtime) { - std::uint64_t authority = 0; - { - auto read = runtime.graph().tryRead(); - const auto connection = read ? read->find({NodeKind::Connection, "connection"}) : NodeRef{}; - if (connection) { - authority = unsignedIntegerFromValue(valueMember(*read->state(connection), "providerAuthorityRevision")).value_or(0); - } - } - const auto result = [&](const std::string& key) { - auto read = runtime.graph().tryRead(); - const auto node = read ? read->find({NodeKind::Catalog, key}) : NodeRef{}; - return node ? jsonFromValue(Value(read->state(node)->fields)) : nlohmann::json::object(); - }; - for (const auto& method : {"fs/readDirectory", "fs/getMetadata", "fs/writeFile"}) { - const std::string key = std::string("filesystem:") + method; - nlohmann::json parameters = {{"path", "/only-on-server/photo.png"}}; - if (std::string_view(method) == "fs/writeFile") { - parameters["dataBase64"] = "cGl4ZWxz"; + expect(bridge.appServerNotification( + "thread/started", + {{"thread", {{"id", "removed-action-thread"}, {"name", "Removed before dispatch"}, {"cwd", "/tmp"}}}}), + "stale thread-action fixture reaches the graph"); + const NodeRef removedActionThread = findNode(runtime.graph(), {NodeKind::Thread, "removed-action-thread"}); + expect(removedActionThread && bridge.appServerNotification("thread/deleted", {{"threadId", "removed-action-thread"}}) && + waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + return read && !read->find(removedActionThread->id()); + }), + "the worker retires the exact action target before dispatch"); + if (removedActionThread) { + NodeAction staleRename{removedActionThread, NodeActionKind::Rename}; + staleRename.payload = {{"name", Value("must not reach provider")}}; + expect(sendAction(runtime.channels(), std::move(staleRename)), + "a removed target remains safely pinnable in the typed queue"); + expect(!bridge.receiveAppServer(200ms), "worker membership revalidation blocks a removed thread target"); + } + + expect(bridge.appServerRequest("generation-input", + "item/tool/requestUserInput", + {{"threadId", "runtime-thread"}, + {"turnId", "generation-turn"}, + {"itemId", "generation-question"}, + {"isBlocking", true}, + {"questions", userInputQuestions("question")}}), + "generation-change request reaches the current graph"); + const NodeRef generationInput = + findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId("generation-input").canonical()}); + expect(bridge.setProviderGeneration(2), "a new provider generation reaches the runtime"); + std::size_t refreshes = 0; + while (refreshes != 7) { + const std::optional refresh = bridge.receiveAppServer(); + if (!refresh) + break; + nlohmann::json result{{"data", nlohmann::json::array()}}; + if (refresh->value("method", std::string{}) == "thread/list") + result["nextCursor"] = nullptr; + if (refresh->value("method", std::string{}) == "account/usage/read") + result = {{"summary", {{"lifetimeTokens", 13000}}}}; + if (bridge.reply(*refresh, std::move(result))) + ++refreshes; + } + expect(refreshes == 7 && generationInput && waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + if (!read) + return false; + const NodeRef current = read->find(generationInput->id()); + if (current != generationInput || read->state(current)->status != NodeStatus::Failed) + return false; + const auto state = read->state(current); + const auto recovery = state->fields.find("recoveryOnly"); + return recovery != state->fields.end() && recovery->second.asBool() && *recovery->second.asBool(); + }), + "provider replacement keeps the expired interaction as explicit " + "response-recovery state"); + if (generationInput) { + NodeAction response{generationInput, NodeActionKind::ResolveInteraction}; + response.payload = userInputSubmission("question", "generation"); + expect(sendAction(runtime.channels(), std::move(response)), + "authored response can reach the worker after generation reset"); + expect(!bridge.receiveAppServer(200ms), + "expired-generation response is never sent to the replacement " + "provider"); + expect(waitUntil([&] { + std::optional read = runtime.graph().tryRead(); + if (!read) + return false; + const NodeRef current = read->find(generationInput->id()); + if (current != generationInput) + return false; + const auto state = read->state(current); + const auto retained = state->fields.find("retainedResponsePayload"); + return retained != state->fields.end() && retained->second.asObject() && + *retained->second.asObject() == userInputSubmission("question", "generation"); + }), + "generation rejection preserves newly authored response data in " + "the shared graph"); + } + runtime.drainNotifications(); } - RuntimeAction action; - action.kind = RuntimeActionKind::Filesystem; - action.correlation = key; - action.payload = objectFromJson({{"method", method}, {"parameters", parameters}, {"authority", authority}}); - expect(sendAction(runtime.channels(), action), "filesystem request enters the existing worker queue"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == method && request->at("params") == parameters, - "filesystem request uses the exact app-server wire path and payload"); - if (request) { - const auto reply = std::string_view(method) == "fs/readDirectory" - ? nlohmann::json{{"entries", {{{"fileName", "photo.png"}, {"isFile", true}, {"isDirectory", false}}}}} - : std::string_view(method) == "fs/getMetadata" ? nlohmann::json{{"isFile", true}, - {"isDirectory", false}, - {"isSymlink", false}, - {"createdAtMs", 0}, - {"modifiedAtMs", 0}} - : nlohmann::json::object(); - expect(bridge.reply(*request, reply), "filesystem result reaches the real runtime"); - expect(waitUntil([&] { - return result(key).contains("result"); - }) && - result(key).at("result") == reply, - "filesystem results survive until the UI explicitly collects them"); - expect(operationRetired(runtime.graph(), request->at("id")), - "the wire operation is retired without losing the pending UI result"); + + void remainingReverseRequestFamiliesRoundTripExactlyOnce(UnixBridge& bridge, RunningRuntime& runtime) { + const auto roundTrip = [&](std::string id, + std::string method, + nlohmann::json requestPayload, + Value::Object responsePayload) -> std::optional { + expect(bridge.appServerRequest(id, method, std::move(requestPayload)), method + " reaches CodexBridge"); + const NodeRef interaction = findNode(runtime.graph(), {NodeKind::Interaction, ProtocolRequestId(id).canonical()}); + expect(static_cast(interaction), method + " creates its stable interaction node"); + if (!interaction) + return std::nullopt; + + NodeAction resolve{interaction, NodeActionKind::ResolveInteraction}; + resolve.payload = std::move(responsePayload); + expect(sendAction(runtime.channels(), std::move(resolve)), method + " typed response enters the worker mailbox"); + std::optional response = bridge.receiveAppServer(); + expect(response && response->value("id", std::string{}) == id, method + " response preserves the original JSON-RPC id"); + expect(!bridge.receiveAppServer(100ms), method + " response is never dual-sent"); + expect(waitUntil([&] { + return interactionRetired(runtime.graph(), interaction); + }), + method + " response removes the exact interaction once"); + return response; + }; + + const nlohmann::json address{{"threadId", "runtime-thread"}, {"turnId", "reverse-turn"}}; + + nlohmann::json fileChangeRequest = address; + fileChangeRequest["itemId"] = "reverse-file-change"; + fileChangeRequest["reason"] = "write the focused test"; + std::optional response = roundTrip( + "file-change-runtime", "item/fileChange/requestApproval", std::move(fileChangeRequest), {{"choice", Value("accept")}}); + expect(response && response->contains("result") && response->at("result") == nlohmann::json{{"decision", "accept"}}, + "file-change approval encodes the authored decision exactly"); + + nlohmann::json elicitationRequest = address; + elicitationRequest["serverName"] = "test-mcp"; + elicitationRequest["message"] = "Choose a value"; + elicitationRequest["mode"] = "form"; + elicitationRequest["requestedSchema"] = nlohmann::json{{"type", "object"}}; + response = roundTrip("mcp-runtime", + "mcpServer/elicitation/request", + std::move(elicitationRequest), + {{"choice", Value("accept")}, + {"input", Value(Value::Object{{"choice", Value("safe")}})}, + {"metadata", Value(Value::Object{{"source", Value("qt")}})}}); + expect(response && response->contains("result") && + response->at("result") == + nlohmann::json{{"action", "accept"}, {"content", {{"choice", "safe"}}}, {"_meta", {{"source", "qt"}}}}, + "MCP elicitation encodes action, content, and metadata exactly"); + + const nlohmann::json requestedPermissions{{"fileSystem", {{"read", nlohmann::json::array({"/workspace"})}}}, + {"network", {{"enabled", false}}}}; + nlohmann::json permissionsRequest = address; + permissionsRequest["itemId"] = "reverse-permissions"; + permissionsRequest["permissions"] = requestedPermissions; + response = roundTrip( + "permissions-runtime", "item/permissions/requestApproval", std::move(permissionsRequest), {{"choice", Value("turn")}}); + expect(response && response->contains("result") && + response->at("result") == nlohmann::json{{"permissions", requestedPermissions}, {"scope", "turn"}}, + "permission approval returns the exact requested permission object " + "and authored scope"); + + nlohmann::json dynamicToolRequest = address; + dynamicToolRequest["callId"] = "reverse-dynamic-tool"; + dynamicToolRequest["tool"] = "unsupported_tool"; + dynamicToolRequest["arguments"] = nlohmann::json{{"value", 7}}; + response = + roundTrip("dynamic-tool-runtime", "item/tool/call", std::move(dynamicToolRequest), {{"choice", Value("unavailable")}}); + expect(response && response->contains("result") && + response->at("result") == + nlohmann::json{ + {"contentItems", + nlohmann::json::array({{{"type", "inputText"}, {"text", "CodexUI does not provide this dynamic tool"}}})}, + {"success", false}}, + "dynamic-tool response encodes one explicit failure content item"); + + response = roundTrip("auth-refresh-runtime", + "account/chatgptAuthTokens/refresh", + {{"reason", "unauthorized"}}, + {{"choice", Value("unsupported")}}); + expect(response && response->contains("error") && response->at("error").value("code", 0) == -32601 && + response->at("error").value("message", std::string{}) == "CodexUI does not support authentication token refresh", + "authentication refresh emits the explicit unsupported error"); + + response = roundTrip( + "attestation-runtime", "attestation/generate", {{"challenge", "challenge-value"}}, {{"choice", Value("unsupported")}}); + expect(response && response->contains("error") && response->at("error").value("code", 0) == -32601 && + response->at("error").value("message", std::string{}) == "CodexUI does not support attestation generation", + "attestation generation emits the explicit unsupported error"); + + response = roundTrip( + "apply-patch-runtime", + "applyPatchApproval", + {{"conversationId", "runtime-thread"}, {"callId", "reverse-apply-patch"}, {"fileChanges", nlohmann::json::object()}}, + {{"choice", Value("denied")}}); + expect(response && response->contains("result") && + response->at("result") == nlohmann::json{{"decision", {{"denied", {{"rejection", "Denied by user"}}}}}}, + "apply-patch approval derives the typed denial from authored intent"); + + response = roundTrip("exec-command-runtime", + "execCommandApproval", + {{"conversationId", "runtime-thread"}, + {"callId", "reverse-exec"}, + {"command", nlohmann::json::array({"printf", "test"})}, + {"cwd", "/tmp"}}, + {{"choice", Value("approved_for_session")}}); + expect(response && response->contains("result") && + response->at("result") == nlohmann::json{{"decision", "approved_for_session"}}, + "exec-command approval maps the authored session decision exactly"); + + runtime.drainNotifications(); } - action.payload.clear(); - expect(sendAction(runtime.channels(), action) && waitUntil([&] { - return result(key).empty(); - }), - "collected filesystem results are removed"); - } - RuntimeAction stale; - stale.kind = RuntimeActionKind::Filesystem; - stale.correlation = "filesystem:stale"; - stale.payload = {{"method", "fs/writeFile"}, - {"authority", authority + 1}, - {"parameters", Value::Object{{"path", "/wrong-host"}, {"dataBase64", ""}}}}; - expect(sendAction(runtime.channels(), stale) && waitUntil([&] { - return result(stale.correlation).contains("error"); - }), - "a stale server binding is rejected visibly"); - expect(!bridge.receiveAppServer(100ms), "a stale binding cannot write to a replacement server"); - stale.payload.clear(); - expect(sendAction(runtime.channels(), stale), "stale error state is collected"); -} -void workspaceChangesUseAcknowledgedThreadContext(UnixBridge& bridge, RunningRuntime& runtime) { - expect(bridge.appServerNotification( - "thread/started", - {{"thread", {{"id", "workspace-wire"}, {"name", "Workspace wire"}, {"cwd", "/old"}, {"status", {{"type", "idle"}}}}}}), - "workspace fixture reaches the real runtime"); - const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "workspace-wire"}); - const auto workspace = [&] { - auto read = runtime.graph().tryRead(); - std::string value; - if (read && read->live(thread)) { - value = exactStringFromValue(valueMember(*read->state(thread), "cwd")); + void unknownInboundIsRetainedWithoutCorruptingKnownState(UnixBridge& bridge, RunningRuntime& runtime) { + constexpr std::string_view RequestMethod = "future/runtime-request"; + expect(bridge.appServerRequest( + "future-runtime-request", std::string(RequestMethod), {{"threadId", "runtime-thread"}, {"futureValue", 23}}), + "unknown inbound request reaches CodexBridge"); + const std::optional rejection = bridge.receiveAppServer(); + expect(rejection && !rejection->contains("method") && rejection->value("id", std::string{}) == "future-runtime-request" && + rejection->contains("error") && rejection->at("error").value("code", 0) == -32601, + "CodexBridge automatically rejects an unregistered server request"); + { + std::optional read = runtime.graph().tryRead(); + expect(read && !read->find({NodeKind::Interaction, ProtocolRequestId("future-runtime-request").canonical()}), + "unknown server request creates no phantom UI interaction"); + } + expect(!bridge.receiveAppServer(100ms), "unknown server request is rejected exactly once"); + + constexpr std::string_view Method = "future/runtime-event"; + expect(bridge.appServerNotification( + std::string(Method), + {{"threadId", "runtime-thread"}, {"name", "must-not-overwrite-known-thread"}, {"futureValue", 17}}), + "unknown inbound notification reaches CodexBridge's raw hook"); + + const std::string unknownId = + std::to_string(static_cast(ProtocolDirection::ServerNotification)) + ":" + std::string(Method); + const NodeRef unknown = findNode(runtime.graph(), {NodeKind::UnknownProtocol, unknownId}); + expect(static_cast(unknown), "unknown inbound notification is retained in the shared graph"); + + std::optional read = runtime.graph().tryRead(); + const NodeRef thread = read ? read->find({NodeKind::Thread, "runtime-thread"}) : NodeRef{}; + const auto unknownState = read && unknown ? read->state(unknown) : nullptr; + const auto threadState = read && thread ? read->state(thread) : nullptr; + const auto unknownMethod = unknownState ? unknownState->fields.find("method") : Value::Object::const_iterator{}; + const auto knownName = threadState ? threadState->fields.find("name") : Value::Object::const_iterator{}; + expect(unknownState && unknownMethod != unknownState->fields.end() && unknownMethod->second.asString() && + *unknownMethod->second.asString() == Method, + "unknown graph state identifies the unrecognized method"); + expect(threadState && knownName != threadState->fields.end() && knownName->second.asString() && + *knownName->second.asString() == "Runtime dispatch", + "unknown addressed fields cannot mutate a known thread"); + runtime.drainNotifications(); } - return value; - }; - const auto change = [&](std::string path) { - NodeAction action{thread, NodeActionKind::ChangeWorkspace}; - action.payload = {{"cwd", std::move(path)}, {"threadId", "decoy"}}; - return sendAction(runtime.channels(), std::move(action)); - }; - expect(change("/remote/not-on-frontend"), "explicit workspace change enters the mailbox"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/settings/update" && - request->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"cwd", "/remote/not-on-frontend"}}, - "one supported request targets the exact thread and ignores payload decoys"); - if (request) { - expect(change("/duplicate") && !bridge.receiveAppServer(100ms), "workspace changes are single-flight"); - expect(bridge.reply(*request, nlohmann::json::object()), "enqueue acknowledgement is delivered"); - std::this_thread::sleep_for(20ms); - expect(workspace() == "/old" && !operationRetired(runtime.graph(), request->at("id")), - "empty success never authors confirmed cwd and retains pending confirmation"); - expect(change("/duplicate-after-accept") && !bridge.receiveAppServer(100ms), - "single-flight extends through authoritative confirmation"); - expect(bridge.appServerNotification("thread/settings/updated", - {{"threadId", "workspace-wire"}, {"threadSettings", {{"cwd", "/remote/not-on-frontend"}}}}), - "authoritative workspace event is delivered"); - expect(waitUntil([&] { - return workspace() == "/remote/not-on-frontend" && operationRetired(runtime.graph(), request->at("id")); - }), - "notification confirms workspace and settles its operation"); - } - expect(change("/failed"), "a settled workspace operation permits another explicit change"); - const auto failed = bridge.receiveAppServer(); - if (failed) { - expect(bridge.replyError(*failed, -32000, "workspace rejected"), "workspace error reaches runtime"); - expect(waitUntil([&] { - return operationRetired(runtime.graph(), failed->at("id")); - }) && - workspace() == "/remote/not-on-frontend", - "failure retains the confirmed path and retires only its operation"); - } - expect(bridge.appServerNotification( - "thread/status/changed", - {{"threadId", "workspace-wire"}, {"status", {{"type", "active"}, {"activeFlags", nlohmann::json::array()}}}}), - "active execution context reaches runtime"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->state(thread)->status == NodeStatus::Running; - }), - "active state is observed before admission"); - expect(change("/during-active-turn") && !bridge.receiveAppServer(100ms), "worker rejects workspace changes during active execution"); - expect(bridge.appServerNotification("thread/status/changed", {{"threadId", "workspace-wire"}, {"status", {{"type", "idle"}}}}), - "thread returns to idle"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->state(thread)->status != NodeStatus::Running; - }), - "idle transition is observed"); - expect(bridge.appServerNotification("thread/status/changed", {{"threadId", "workspace-wire"}, {"status", {{"type", "notLoaded"}}}}), - "an unselected unloaded thread is reported"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->state(thread)->status == NodeStatus::NotLoaded; - }), - "unloaded context is observed before the change action"); - expect(change("/cold-context"), "cold workspace action is admitted"); - const auto resume = bridge.receiveAppServer(); - expect(resume && resume->value("method", "") == "thread/resume" && - resume->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"excludeTurns", true}}, - "cold workspace changes first resume metadata without authoring cwd or selecting the thread"); - if (resume) { - expect(change("/duplicate-cold") && !bridge.receiveAppServer(100ms), "cold context loading is single-flight"); - expect(bridge.reply(*resume, - {{"thread", {{"id", "workspace-wire"}, {"cwd", "/remote/not-on-frontend"}, {"status", {{"type", "idle"}}}}}}), - "cold metadata resume completes"); - const auto changed = bridge.receiveAppServer(); - expect(changed && changed->value("method", "") == "thread/settings/update" && - changed->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"cwd", "/cold-context"}}, - "successful resume continues the exact targeted workspace operation without loading history"); - if (changed) { - expect(bridge.reply(*changed, nlohmann::json::object()) && - bridge.appServerNotification("thread/settings/updated", - {{"threadId", "workspace-wire"}, {"threadSettings", {{"cwd", "/cold-context"}}}}), - "cold workspace change receives authoritative confirmation"); - expect(waitUntil([&] { - return workspace() == "/cold-context"; - }), - "cold workspace is confirmed by app-server"); + + void explicitReconnectsControlTheLatestFlow(UnixBridge& bridge, RunningRuntime& runtime) { + for (const auto kind : {RuntimeActionKind::Reconnect, RuntimeActionKind::Reconnect, RuntimeActionKind::Disconnect}) { + RuntimeAction action; + action.kind = kind; + expect(sendAction(runtime.channels(), std::move(action)), "connection lifecycle action reaches the worker"); + expect(waitUntil([&] { + return bridge.peerClosed(); + }), + "terminating the current flow closes the current connection"); + if (kind == RuntimeActionKind::Disconnect) { + expect(!bridge.acceptClient(100ms), "manual disconnect does not start another flow"); + RuntimeAction connect; + connect.kind = RuntimeActionKind::Connect; + expect(sendAction(runtime.channels(), std::move(connect)), "explicit connect is admitted after flow termination"); + } + expect(bridge.acceptClient(), "each explicit reconnect or connect starts a fresh working flow"); + runtime.drainNotifications(); + } } - } - expect(change("/late"), "pending workspace request precedes thread deletion"); - const auto late = bridge.receiveAppServer(); - if (late) { - expect(bridge.appServerNotification("thread/deleted", {{"threadId", "workspace-wire"}}), "target deletion reaches runtime"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && !read->live(thread); - }), - "old exact thread identity retires"); - expect(bridge.appServerNotification("thread/started", {{"thread", {{"id", "workspace-wire"}, {"cwd", "/replacement"}}}}), - "a fresh incarnation reuses the canonical id"); - expect(bridge.reply(*late, nlohmann::json::object()), "late old success is delivered"); - const NodeRef replacement = findNode(runtime.graph(), {NodeKind::Thread, "workspace-wire"}); - expect(replacement && replacement != thread && waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && exactStringFromValue(valueMember(*read->state(replacement), "cwd")) == "/replacement"; - }), - "late workspace response cannot change the replacement thread"); - } - runtime.drainNotifications(); -} -void inspectionIsLocalToTheActualConversation(UnixBridge& bridge, RunningRuntime& runtime) { - const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), "inspection targets the retained thread"); - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::InspectThread}), - "inspection enters the existing worker mailbox"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto owner = read ? read->find({NodeKind::Runtime, "runtime"}) : NodeRef{}; - return owner && read->related(owner, RelationKind::UiInspectionTarget) == std::vector{thread}; - }), - "runtime dispatch records the actual inspected conversation"); - expect(!bridge.receiveAppServer(100ms), "inspection sends no app-server request"); - expect(sendAction(runtime.channels(), NodeAction{{}, NodeActionKind::InspectThread}), - "new draft clears inspection through the same mailbox"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - const auto owner = read ? read->find({NodeKind::Runtime, "runtime"}) : NodeRef{}; - return owner && read->related(owner, RelationKind::UiInspectionTarget).empty(); - }), - "runtime dispatch clears the inspected conversation for a draft"); - runtime.drainNotifications(); -} + void endpointReconfigurationUsesTheSelectedAddress(UnixBridge& bridge, RunningRuntime& runtime) { + UnixBridge alternative("-alternative"); + expect(alternative.valid(), "the alternative endpoint has its own listener"); + UnixBridge* previous = &bridge; + for (UnixBridge* next : {&alternative, &bridge}) { + RuntimeAction configure; + configure.kind = RuntimeActionKind::ConfigureConnection; + configure.payload = {{"transport", Value("unix")}, {"path", Value(next->path())}}; + expect(sendAction(runtime.channels(), std::move(configure)), + "an endpoint change reaches the existing connection transition"); + expect(waitUntil([&] { + return previous->peerClosed(); + }), + "reconfiguration closes the previous endpoint"); + expect(next->acceptClient(), "reconfiguration connects to the new endpoint, including a reused client"); + previous = next; + runtime.drainNotifications(); + } + } -void cachedSettingsRefreshDoesNotReloadHistory(UnixBridge& bridge, RunningRuntime& runtime) { - const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); - expect(static_cast(thread), "settings refresh targets the retained thread"); - if (thread) { - { - auto write = runtime.graph().write(); - const NodeRef connection = write.find({NodeKind::Connection, "connection"}); - write.setField(thread, "hydrationState", Value("ready")); - write.setField(thread, "hydrationConnectionGeneration", *valueMember(*write.state(connection), "connectionGeneration")); - static_cast(write.finish()); + void filesystemRequestsRetainResultsUntilCollected(UnixBridge& bridge, RunningRuntime& runtime) { + std::uint64_t authority = 0; + { + auto read = runtime.graph().tryRead(); + const auto connection = read ? read->find({NodeKind::Connection, "connection"}) : NodeRef{}; + if (connection) { + authority = unsignedIntegerFromValue(valueMember(*read->state(connection), "providerAuthorityRevision")).value_or(0); + } + } + const auto result = [&](const std::string& key) { + auto read = runtime.graph().tryRead(); + const auto node = read ? read->find({NodeKind::Catalog, key}) : NodeRef{}; + return node ? jsonFromValue(Value(read->state(node)->fields)) : nlohmann::json::object(); + }; + for (const auto& method : {"fs/readDirectory", "fs/getMetadata", "fs/writeFile"}) { + const std::string key = std::string("filesystem:") + method; + nlohmann::json parameters = {{"path", "/only-on-server/photo.png"}}; + if (std::string_view(method) == "fs/writeFile") { + parameters["dataBase64"] = "cGl4ZWxz"; + } + RuntimeAction action; + action.kind = RuntimeActionKind::Filesystem; + action.correlation = key; + action.payload = objectFromJson({{"method", method}, {"parameters", parameters}, {"authority", authority}}); + expect(sendAction(runtime.channels(), action), "filesystem request enters the existing worker queue"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == method && request->at("params") == parameters, + "filesystem request uses the exact app-server wire path and payload"); + if (request) { + const auto reply = + std::string_view(method) == "fs/readDirectory" + ? nlohmann::json{{"entries", {{{"fileName", "photo.png"}, {"isFile", true}, {"isDirectory", false}}}}} + : std::string_view(method) == "fs/getMetadata" ? nlohmann::json{{"isFile", true}, + {"isDirectory", false}, + {"isSymlink", false}, + {"createdAtMs", 0}, + {"modifiedAtMs", 0}} + : nlohmann::json::object(); + expect(bridge.reply(*request, reply), "filesystem result reaches the real runtime"); + expect(waitUntil([&] { + return result(key).contains("result"); + }) && + result(key).at("result") == reply, + "filesystem results survive until the UI explicitly collects them"); + expect(operationRetired(runtime.graph(), request->at("id")), + "the wire operation is retired without losing the pending UI result"); + } + action.payload.clear(); + expect(sendAction(runtime.channels(), action) && waitUntil([&] { + return result(key).empty(); + }), + "collected filesystem results are removed"); + } + RuntimeAction stale; + stale.kind = RuntimeActionKind::Filesystem; + stale.correlation = "filesystem:stale"; + stale.payload = {{"method", "fs/writeFile"}, + {"authority", authority + 1}, + {"parameters", Value::Object{{"path", "/wrong-host"}, {"dataBase64", ""}}}}; + expect(sendAction(runtime.channels(), stale) && waitUntil([&] { + return result(stale.correlation).contains("error"); + }), + "a stale server binding is rejected visibly"); + expect(!bridge.receiveAppServer(100ms), "a stale binding cannot write to a replacement server"); + stale.payload.clear(); + expect(sendAction(runtime.channels(), stale), "stale error state is collected"); } - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), "cached selection requests fresh settings"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/resume" && - request->at("params") == nlohmann::json{{"threadId", "runtime-thread"}, {"excludeTurns", true}}, - "cached selection sends a metadata-only resume without overrides"); - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), "repeated cached selection reaches admission"); - expect(!bridge.receiveAppServer(100ms), "settings refresh is single-flight"); - if (request) { - expect(bridge.reply(*request, - {{"thread", {{"id", "runtime-thread"}}}, - {"model", "restored-model"}, - {"reasoningEffort", "high"}, - {"approvalPolicy", "never"}, - {"sandbox", {{"type", "readOnly"}, {"networkAccess", true}}}}), - "app-server supplies effective settings for the retained thread"); + + void workspaceChangesUseAcknowledgedThreadContext(UnixBridge& bridge, RunningRuntime& runtime) { + expect( + bridge.appServerNotification( + "thread/started", + {{"thread", {{"id", "workspace-wire"}, {"name", "Workspace wire"}, {"cwd", "/old"}, {"status", {{"type", "idle"}}}}}}), + "workspace fixture reaches the real runtime"); + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "workspace-wire"}); + const auto workspace = [&] { + auto read = runtime.graph().tryRead(); + std::string value; + if (read && read->live(thread)) { + value = exactStringFromValue(valueMember(*read->state(thread), "cwd")); + } + return value; + }; + const auto change = [&](std::string path) { + NodeAction action{thread, NodeActionKind::ChangeWorkspace}; + action.payload = {{"cwd", std::move(path)}, {"threadId", "decoy"}}; + return sendAction(runtime.channels(), std::move(action)); + }; + expect(change("/remote/not-on-frontend"), "explicit workspace change enters the mailbox"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/settings/update" && + request->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"cwd", "/remote/not-on-frontend"}}, + "one supported request targets the exact thread and ignores payload decoys"); + if (request) { + expect(change("/duplicate") && !bridge.receiveAppServer(100ms), "workspace changes are single-flight"); + expect(bridge.reply(*request, nlohmann::json::object()), "enqueue acknowledgement is delivered"); + std::this_thread::sleep_for(20ms); + expect(workspace() == "/old" && !operationRetired(runtime.graph(), request->at("id")), + "empty success never authors confirmed cwd and retains pending confirmation"); + expect(change("/duplicate-after-accept") && !bridge.receiveAppServer(100ms), + "single-flight extends through authoritative confirmation"); + expect(bridge.appServerNotification( + "thread/settings/updated", + {{"threadId", "workspace-wire"}, {"threadSettings", {{"cwd", "/remote/not-on-frontend"}}}}), + "authoritative workspace event is delivered"); + expect(waitUntil([&] { + return workspace() == "/remote/not-on-frontend" && operationRetired(runtime.graph(), request->at("id")); + }), + "notification confirms workspace and settles its operation"); + } + expect(change("/failed"), "a settled workspace operation permits another explicit change"); + const auto failed = bridge.receiveAppServer(); + if (failed) { + expect(bridge.replyError(*failed, -32000, "workspace rejected"), "workspace error reaches runtime"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), failed->at("id")); + }) && + workspace() == "/remote/not-on-frontend", + "failure retains the confirmed path and retires only its operation"); + } + expect(bridge.appServerNotification( + "thread/status/changed", + {{"threadId", "workspace-wire"}, {"status", {{"type", "active"}, {"activeFlags", nlohmann::json::array()}}}}), + "active execution context reaches runtime"); expect(waitUntil([&] { auto read = runtime.graph().tryRead(); - bool restored = false; - if (read) { - const auto state = read->state(thread); - restored = exactStringFromValue(valueMember(*state, "model")) == "restored-model" && - exactStringFromValue(valueMember(*state, "reasoningEffort")) == "high" && - exactStringFromValue(valueMember(*state, "approvalPolicy")) == "never" && - exactStringFromValue(valueMember(*state, "hydrationState")) == "ready"; - } - return restored; + return read && read->state(thread)->status == NodeStatus::Running; }), - "resume settings replace retained values without invalidating history"); + "active state is observed before admission"); + expect(change("/during-active-turn") && !bridge.receiveAppServer(100ms), + "worker rejects workspace changes during active execution"); + expect(bridge.appServerNotification("thread/status/changed", {{"threadId", "workspace-wire"}, {"status", {{"type", "idle"}}}}), + "thread returns to idle"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->state(thread)->status != NodeStatus::Running; + }), + "idle transition is observed"); + expect(bridge.appServerNotification("thread/status/changed", + {{"threadId", "workspace-wire"}, {"status", {{"type", "notLoaded"}}}}), + "an unselected unloaded thread is reported"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->state(thread)->status == NodeStatus::NotLoaded; + }), + "unloaded context is observed before the change action"); + expect(change("/cold-context"), "cold workspace action is admitted"); + const auto resume = bridge.receiveAppServer(); + expect(resume && resume->value("method", "") == "thread/resume" && + resume->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"excludeTurns", true}}, + "cold workspace changes first resume metadata without authoring cwd or selecting the thread"); + if (resume) { + expect(change("/duplicate-cold") && !bridge.receiveAppServer(100ms), "cold context loading is single-flight"); + expect(bridge.reply( + *resume, + {{"thread", {{"id", "workspace-wire"}, {"cwd", "/remote/not-on-frontend"}, {"status", {{"type", "idle"}}}}}}), + "cold metadata resume completes"); + const auto changed = bridge.receiveAppServer(); + expect(changed && changed->value("method", "") == "thread/settings/update" && + changed->at("params") == nlohmann::json{{"threadId", "workspace-wire"}, {"cwd", "/cold-context"}}, + "successful resume continues the exact targeted workspace operation without loading history"); + if (changed) { + expect( + bridge.reply(*changed, nlohmann::json::object()) && + bridge.appServerNotification("thread/settings/updated", + {{"threadId", "workspace-wire"}, {"threadSettings", {{"cwd", "/cold-context"}}}}), + "cold workspace change receives authoritative confirmation"); + expect(waitUntil([&] { + return workspace() == "/cold-context"; + }), + "cold workspace is confirmed by app-server"); + } + } + expect(change("/late"), "pending workspace request precedes thread deletion"); + const auto late = bridge.receiveAppServer(); + if (late) { + expect(bridge.appServerNotification("thread/deleted", {{"threadId", "workspace-wire"}}), "target deletion reaches runtime"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && !read->live(thread); + }), + "old exact thread identity retires"); + expect(bridge.appServerNotification("thread/started", {{"thread", {{"id", "workspace-wire"}, {"cwd", "/replacement"}}}}), + "a fresh incarnation reuses the canonical id"); + expect(bridge.reply(*late, nlohmann::json::object()), "late old success is delivered"); + const NodeRef replacement = findNode(runtime.graph(), {NodeKind::Thread, "workspace-wire"}); + expect(replacement && replacement != thread && waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && exactStringFromValue(valueMember(*read->state(replacement), "cwd")) == "/replacement"; + }), + "late workspace response cannot change the replacement thread"); + } + runtime.drainNotifications(); } - expect(!bridge.receiveAppServer(100ms), "settings refresh does not re-page turns or items"); - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), "a settled refresh can be retried"); - const auto failed = bridge.receiveAppServer(); - expect(failed && failed->value("method", "") == "thread/resume", "a subsequent selection owns a new settings refresh"); - if (failed) { - expect(bridge.replyError(*failed, -32000, "settings unavailable"), "settings refresh failure is delivered"); + + void inspectionIsLocalToTheActualConversation(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "inspection targets the retained thread"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::InspectThread}), + "inspection enters the existing worker mailbox"); expect(waitUntil([&] { - return operationRetired(runtime.graph(), failed->at("id")); + auto read = runtime.graph().tryRead(); + const auto owner = read ? read->find({NodeKind::Runtime, "runtime"}) : NodeRef{}; + return owner && read->related(owner, RelationKind::UiInspectionTarget) == std::vector{thread}; + }), + "runtime dispatch records the actual inspected conversation"); + expect(!bridge.receiveAppServer(100ms), "inspection sends no app-server request"); + expect(sendAction(runtime.channels(), NodeAction{{}, NodeActionKind::InspectThread}), + "new draft clears inspection through the same mailbox"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + const auto owner = read ? read->find({NodeKind::Runtime, "runtime"}) : NodeRef{}; + return owner && read->related(owner, RelationKind::UiInspectionTarget).empty(); }), - "failed settings refresh settles its operation"); + "runtime dispatch clears the inspected conversation for a draft"); + runtime.drainNotifications(); } - expect(!bridge.receiveAppServer(100ms), "failed settings refresh does not reload usable history"); - runtime.drainNotifications(); - } -} -void removingTurnsUsesOneAuthoritativeWireOperation(UnixBridge& bridge, RunningRuntime& runtime) { - const nlohmann::json metadata{ - {"id", "revert-wire"}, {"historyMode", "paginated"}, {"ephemeral", false}, {"status", {{"type", "idle"}}}}; - expect(bridge.appServerNotification("thread/started", {{"thread", metadata}}), "revert fixture reaches runtime"); - const auto thread = findNode(runtime.graph(), {NodeKind::Thread, "revert-wire"}); - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), - "revert fixture is hydrated through public worker path"); - const auto resume = bridge.receiveAppServer(); - expect(resume && resume->value("method", "") == "thread/resume", "revert hydration resumes metadata"); - if (resume) { - expect(bridge.reply(*resume, {{"thread", metadata}}), "revert metadata is returned"); - } - const auto page = bridge.receiveAppServer(); - expect(page && page->value("method", "") == "thread/turns/list", "revert hydration requests paginated turns"); - nlohmann::json listed = nlohmann::json::array(); - for (int index = 3; index >= 1; --index) { - listed.push_back({{"id", "t" + std::to_string(index)}, {"status", "completed"}, {"items", nlohmann::json::array()}}); - } - if (page) { - expect(bridge.reply(*page, {{"data", listed}, {"nextCursor", nullptr}}), "three retained turns arrive"); - } - for (int index = 0; index < 3; ++index) { - const auto items = bridge.receiveAppServer(); - expect(items && items->value("method", "") == "thread/items/list", "turn items hydrate through bounded path"); - if (items) { - expect(bridge.reply(*items, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "item hydration completes"); + void cachedSettingsRefreshDoesNotReloadHistory(UnixBridge& bridge, RunningRuntime& runtime) { + const NodeRef thread = findNode(runtime.graph(), {NodeKind::Thread, "runtime-thread"}); + expect(static_cast(thread), "settings refresh targets the retained thread"); + if (thread) { + { + auto write = runtime.graph().write(); + const NodeRef connection = write.find({NodeKind::Connection, "connection"}); + write.setField(thread, "hydrationState", Value("ready")); + write.setField(thread, "hydrationConnectionGeneration", *valueMember(*write.state(connection), "connectionGeneration")); + static_cast(write.finish()); + } + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), + "cached selection requests fresh settings"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/resume" && + request->at("params") == nlohmann::json{{"threadId", "runtime-thread"}, {"excludeTurns", true}}, + "cached selection sends a metadata-only resume without overrides"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), + "repeated cached selection reaches admission"); + expect(!bridge.receiveAppServer(100ms), "settings refresh is single-flight"); + if (request) { + expect(bridge.reply(*request, + {{"thread", {{"id", "runtime-thread"}}}, + {"model", "restored-model"}, + {"reasoningEffort", "high"}, + {"approvalPolicy", "never"}, + {"sandbox", {{"type", "readOnly"}, {"networkAccess", true}}}}), + "app-server supplies effective settings for the retained thread"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + bool restored = false; + if (read) { + const auto state = read->state(thread); + restored = exactStringFromValue(valueMember(*state, "model")) == "restored-model" && + exactStringFromValue(valueMember(*state, "reasoningEffort")) == "high" && + exactStringFromValue(valueMember(*state, "approvalPolicy")) == "never" && + exactStringFromValue(valueMember(*state, "hydrationState")) == "ready"; + } + return restored; + }), + "resume settings replace retained values without invalidating history"); + } + expect(!bridge.receiveAppServer(100ms), "settings refresh does not re-page turns or items"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), "a settled refresh can be retried"); + const auto failed = bridge.receiveAppServer(); + expect(failed && failed->value("method", "") == "thread/resume", "a subsequent selection owns a new settings refresh"); + if (failed) { + expect(bridge.replyError(*failed, -32000, "settings unavailable"), "settings refresh failure is delivered"); + expect(waitUntil([&] { + return operationRetired(runtime.graph(), failed->at("id")); + }), + "failed settings refresh settles its operation"); + } + expect(!bridge.receiveAppServer(100ms), "failed settings refresh does not reload usable history"); + runtime.drainNotifications(); + } } - } - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->relatedCount(thread, RelationKind::PendingOperation) == 0; - }), - "all history work settles before removal"); - const auto turn = findNode(runtime.graph(), scopedTurnNodeId("revert-wire", "t2")); - expect(sendAction(runtime.channels(), NodeAction{turn, NodeActionKind::RevertTurn}), "turn removal enters worker mailbox"); - const auto request = bridge.receiveAppServer(); - expect(request && request->value("method", "") == "thread/revert" && - request->at("params") == nlohmann::json{{"threadId", "revert-wire"}, {"beforeTurnId", "t2"}}, - "one inclusive request uses exact turn identity"); - if (request) { - expect(sendAction(runtime.channels(), NodeAction{turn, NodeActionKind::RevertTurn}) && !bridge.receiveAppServer(100ms), - "duplicate removal is rejected at dispatch"); - expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Delete}) && !bridge.receiveAppServer(100ms), - "thread deletion cannot race an admitted history removal"); - NodeAction workspace{thread, NodeActionKind::ChangeWorkspace}; - workspace.payload = {{"cwd", "/unused-during-removal"}}; - expect(sendAction(runtime.channels(), std::move(workspace)) && !bridge.receiveAppServer(100ms), - "workspace context cannot change during history removal"); - expect(bridge.reply(*request, - {{"thread", metadata}, {"turnsBackwardsCursor", "retained-anchor"}, {"itemsBackwardsCursor", "items-anchor"}}), - "server confirms prefix and reload cursors"); - const auto retained = bridge.receiveAppServer(); - expect(retained && retained->value("method", "") == "thread/turns/list" && - retained->at("params").value("cursor", "") == "retained-anchor", - "retained history reload uses the exact server anchor"); - expect(bridge.appServerNotification("thread/reverted", {{"threadId", "revert-wire"}}), "trailing notification is delivered"); - if (retained) { - expect(bridge.reply(*retained, {{"data", nlohmann::json::array({listed.at(2)})}, {"nextCursor", nullptr}}), - "retained prefix is returned"); - const auto items = bridge.receiveAppServer(); - expect(items && items->value("method", "") == "thread/items/list", "retained turn items reload"); - if (items) { - expect(bridge.reply(*items, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "retained items finish"); + + void removingTurnsUsesOneAuthoritativeWireOperation(UnixBridge& bridge, RunningRuntime& runtime) { + const nlohmann::json metadata{ + {"id", "revert-wire"}, {"historyMode", "paginated"}, {"ephemeral", false}, {"status", {{"type", "idle"}}}}; + expect(bridge.appServerNotification("thread/started", {{"thread", metadata}}), "revert fixture reaches runtime"); + const auto thread = findNode(runtime.graph(), {NodeKind::Thread, "revert-wire"}); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Hydrate}), + "revert fixture is hydrated through public worker path"); + const auto resume = bridge.receiveAppServer(); + expect(resume && resume->value("method", "") == "thread/resume", "revert hydration resumes metadata"); + if (resume) { + expect(bridge.reply(*resume, {{"thread", metadata}}), "revert metadata is returned"); + } + const auto page = bridge.receiveAppServer(); + expect(page && page->value("method", "") == "thread/turns/list", "revert hydration requests paginated turns"); + nlohmann::json listed = nlohmann::json::array(); + for (int index = 3; index >= 1; --index) { + listed.push_back({{"id", "t" + std::to_string(index)}, {"status", "completed"}, {"items", nlohmann::json::array()}}); + } + if (page) { + expect(bridge.reply(*page, {{"data", listed}, {"nextCursor", nullptr}}), "three retained turns arrive"); + } + for (int index = 0; index < 3; ++index) { + const auto items = bridge.receiveAppServer(); + expect(items && items->value("method", "") == "thread/items/list", "turn items hydrate through bounded path"); + if (items) { + expect(bridge.reply(*items, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "item hydration completes"); + } + } + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->relatedCount(thread, RelationKind::PendingOperation) == 0; + }), + "all history work settles before removal"); + const auto turn = findNode(runtime.graph(), scopedTurnNodeId("revert-wire", "t2")); + expect(sendAction(runtime.channels(), NodeAction{turn, NodeActionKind::RevertTurn}), "turn removal enters worker mailbox"); + const auto request = bridge.receiveAppServer(); + expect(request && request->value("method", "") == "thread/revert" && + request->at("params") == nlohmann::json{{"threadId", "revert-wire"}, {"beforeTurnId", "t2"}}, + "one inclusive request uses exact turn identity"); + if (request) { + expect(sendAction(runtime.channels(), NodeAction{turn, NodeActionKind::RevertTurn}) && !bridge.receiveAppServer(100ms), + "duplicate removal is rejected at dispatch"); + expect(sendAction(runtime.channels(), NodeAction{thread, NodeActionKind::Delete}) && !bridge.receiveAppServer(100ms), + "thread deletion cannot race an admitted history removal"); + NodeAction workspace{thread, NodeActionKind::ChangeWorkspace}; + workspace.payload = {{"cwd", "/unused-during-removal"}}; + expect(sendAction(runtime.channels(), std::move(workspace)) && !bridge.receiveAppServer(100ms), + "workspace context cannot change during history removal"); + expect(bridge.reply( + *request, + {{"thread", metadata}, {"turnsBackwardsCursor", "retained-anchor"}, {"itemsBackwardsCursor", "items-anchor"}}), + "server confirms prefix and reload cursors"); + const auto retained = bridge.receiveAppServer(); + expect(retained && retained->value("method", "") == "thread/turns/list" && + retained->at("params").value("cursor", "") == "retained-anchor", + "retained history reload uses the exact server anchor"); + expect(bridge.appServerNotification("thread/reverted", {{"threadId", "revert-wire"}}), + "trailing notification is delivered"); + if (retained) { + expect(bridge.reply(*retained, {{"data", nlohmann::json::array({listed.at(2)})}, {"nextCursor", nullptr}}), + "retained prefix is returned"); + const auto items = bridge.receiveAppServer(); + expect(items && items->value("method", "") == "thread/items/list", "retained turn items reload"); + if (items) { + expect(bridge.reply(*items, {{"data", nlohmann::json::array()}, {"nextCursor", nullptr}}), "retained items finish"); + } + } + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->childCount(thread) == 1 && read->relatedCount(thread, RelationKind::PendingOperation) == 0; + }), + "authoritative prefix survives and mutation settles"); + expect(!bridge.receiveAppServer(100ms), "response and notification do not duplicate history refresh"); } + expect( + bridge.appServerNotification("thread/status/changed", {{"threadId", "revert-wire"}, {"status", {{"type", "notLoaded"}}}}), + "a retained thread can become unloaded"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->state(thread)->status == NodeStatus::NotLoaded; + }), + "unloaded status becomes authoritative before dispatch"); + const auto retainedTurn = findNode(runtime.graph(), scopedTurnNodeId("revert-wire", "t1")); + expect(sendAction(runtime.channels(), NodeAction{retainedTurn, NodeActionKind::RevertTurn}), + "explicit removal of an unloaded thread is admitted"); + const auto reload = bridge.receiveAppServer(); + expect(reload && reload->value("method", "") == "thread/resume" && reload->at("params").value("excludeTurns", false), + "unloaded removal resumes metadata before dispatch"); + if (reload) { + expect(bridge.reply(*reload, {{"thread", metadata}}), "unloaded target resumes successfully"); + } + const auto rejected = bridge.receiveAppServer(); + expect(rejected && rejected->value("method", "") == "thread/revert" && rejected->at("params").value("beforeTurnId", "") == "t1", + "resume revalidates the exact captured turn before removal"); + if (rejected) { + expect(bridge.replyError(*rejected, -32000, "fixture rejection"), "ordinary removal rejection reaches worker"); + expect(waitUntil([&] { + auto read = runtime.graph().tryRead(); + return read && read->live(retainedTurn) && read->childCount(thread) == 1 && + read->relatedCount(thread, RelationKind::PendingOperation) == 0 && + !boolFromValue(valueMember(*read->state(thread), "historyStale")); + }), + "rejection retains history and retires only the failed operation"); + expect(!bridge.receiveAppServer(100ms), "rejected removal is never automatically resent"); + } + runtime.drainNotifications(); } - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->childCount(thread) == 1 && read->relatedCount(thread, RelationKind::PendingOperation) == 0; - }), - "authoritative prefix survives and mutation settles"); - expect(!bridge.receiveAppServer(100ms), "response and notification do not duplicate history refresh"); - } - expect(bridge.appServerNotification("thread/status/changed", {{"threadId", "revert-wire"}, {"status", {{"type", "notLoaded"}}}}), - "a retained thread can become unloaded"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->state(thread)->status == NodeStatus::NotLoaded; - }), - "unloaded status becomes authoritative before dispatch"); - const auto retainedTurn = findNode(runtime.graph(), scopedTurnNodeId("revert-wire", "t1")); - expect(sendAction(runtime.channels(), NodeAction{retainedTurn, NodeActionKind::RevertTurn}), - "explicit removal of an unloaded thread is admitted"); - const auto reload = bridge.receiveAppServer(); - expect(reload && reload->value("method", "") == "thread/resume" && reload->at("params").value("excludeTurns", false), - "unloaded removal resumes metadata before dispatch"); - if (reload) { - expect(bridge.reply(*reload, {{"thread", metadata}}), "unloaded target resumes successfully"); - } - const auto rejected = bridge.receiveAppServer(); - expect(rejected && rejected->value("method", "") == "thread/revert" && rejected->at("params").value("beforeTurnId", "") == "t1", - "resume revalidates the exact captured turn before removal"); - if (rejected) { - expect(bridge.replyError(*rejected, -32000, "fixture rejection"), "ordinary removal rejection reaches worker"); - expect(waitUntil([&] { - auto read = runtime.graph().tryRead(); - return read && read->live(retainedTurn) && read->childCount(thread) == 1 && - read->relatedCount(thread, RelationKind::PendingOperation) == 0 && - !boolFromValue(valueMember(*read->state(thread), "historyStale")); - }), - "rejection retains history and retires only the failed operation"); - expect(!bridge.receiveAppServer(100ms), "rejected removal is never automatically resent"); - } - runtime.drainNotifications(); -} -} // namespace + } // namespace } // namespace codexui::codex -int main(int argc, char **argv) { - auto *configuration = - utils::Config::configRoot.newSubCommand(); - core::SNodeC::init(argc, argv); - - codexui::codex::UnixBridge bridge; - codexui::codex::expect(bridge.valid(), - "test bridge creates a private Unix listener"); - if (!bridge.valid()) - return EXIT_FAILURE; - - codexui::codex::RunningRuntime runtime(*configuration); - runtime.start(); - const bool ready = codexui::codex::establishProvider(bridge, runtime); - codexui::codex::expect( - ready, "runtime connects and performs one initial provider hydration"); - if (ready) { - codexui::codex::accountUsageRefreshIsCoalescedAndAccountScoped(bridge, runtime); - codexui::codex::idleWorkerSleepsBetweenWakeRecoveryChecks(runtime); - codexui::codex::protocolDiagnosticsPreserveMetadataWithoutPayloads(bridge, - runtime); - codexui::codex::removingTurnsUsesOneAuthoritativeWireOperation(bridge, runtime); - codexui::codex::inspectionIsLocalToTheActualConversation(bridge, runtime); - codexui::codex::cachedSettingsRefreshDoesNotReloadHistory(bridge, runtime); - codexui::codex::workspaceChangesUseAcknowledgedThreadContext(bridge, runtime); - codexui::codex::filesystemRequestsRetainResultsUntilCollected(bridge, runtime); - codexui::codex::directNodeActionsUseOneCorrelatedRequest(bridge, runtime); - codexui::codex::remainingUiCommandFamiliesUseExactWirePaths(bridge, - runtime); - codexui::codex::itemHistoryHydrationHasAnExactConcurrencyCeiling(bridge, - runtime); - codexui::codex::conversationSnapshotsShareOneAdmissionAuthority(bridge, - runtime); - codexui::codex::firstNavigationDrainsTheExistingHistoryPager(bridge, runtime); - codexui::codex::staleHistoryFailureIsSemanticallyInert(bridge, runtime); - codexui::codex::ordinaryThreadPromptStillStartsAndCompletes(bridge, - runtime); - codexui::codex::firstPromptAfterForkStartsANewTurn(bridge, runtime); - codexui::codex::forksPersistSourceMembership(bridge, runtime); - codexui::codex::creationAssignsOnlyTheReturnedGroup(bridge, runtime); - codexui::codex::runtimeRefreshActionsHaveExactRequestCardinality(bridge, - runtime); - codexui::codex::failedWakeUsesBoundedWorkerRecovery(bridge, runtime); - codexui::codex::reverseInteractionsRespondOnceWithAuthoredData(bridge, - runtime); - codexui::codex::invalidAuthoredReverseResponseNeverReachesWire(bridge, - runtime); - codexui::codex::remainingReverseRequestFamiliesRoundTripExactlyOnce( - bridge, runtime); - codexui::codex::unknownInboundIsRetainedWithoutCorruptingKnownState( - bridge, runtime); - codexui::codex::startupListsResolveLineageBeforePublishing(bridge, runtime); - codexui::codex::threadOrganisationUsesBoundedAuthoritativeRequests(bridge, - runtime); - codexui::codex::workerRevalidatesCurrentAuthorityAndRetainsResponses( - bridge, runtime); - codexui::codex::explicitReconnectsControlTheLatestFlow(bridge, runtime); - codexui::codex::endpointReconfigurationUsesTheSelectedAddress(bridge, runtime); - } - runtime.channels().failNextQtToWorkerWakeForTest(); - const auto shutdownStarted = std::chrono::steady_clock::now(); - runtime.stop(); - codexui::codex::expect( - std::chrono::steady_clock::now() - shutdownStarted < - std::chrono::seconds(2), - "an unwoken ShutdownRequest is consumed without hanging worker join"); - codexui::codex::expect(bridge.peerClosed(), - "shutdown closes the most recently connected flow"); - - if (codexui::codex::failures != 0) { - std::cerr << codexui::codex::failures - << " client-runtime dispatch assertion(s) failed\n"; - return EXIT_FAILURE; - } - std::cout << "ClientRuntime typed dispatch integration test passed\n"; - return EXIT_SUCCESS; +int main(int argc, char** argv) { + auto* configuration = utils::Config::configRoot.newSubCommand(); + core::SNodeC::init(argc, argv); + + codexui::codex::UnixBridge bridge; + codexui::codex::expect(bridge.valid(), "test bridge creates a private Unix listener"); + if (!bridge.valid()) + return EXIT_FAILURE; + + codexui::codex::RunningRuntime runtime(*configuration); + runtime.start(); + const bool ready = codexui::codex::establishProvider(bridge, runtime); + codexui::codex::expect(ready, "runtime connects and performs one initial provider hydration"); + if (ready) { + codexui::codex::accountUsageRefreshIsCoalescedAndAccountScoped(bridge, runtime); + codexui::codex::idleWorkerSleepsBetweenWakeRecoveryChecks(runtime); + codexui::codex::protocolDiagnosticsPreserveMetadataWithoutPayloads(bridge, runtime); + codexui::codex::removingTurnsUsesOneAuthoritativeWireOperation(bridge, runtime); + codexui::codex::inspectionIsLocalToTheActualConversation(bridge, runtime); + codexui::codex::cachedSettingsRefreshDoesNotReloadHistory(bridge, runtime); + codexui::codex::workspaceChangesUseAcknowledgedThreadContext(bridge, runtime); + codexui::codex::filesystemRequestsRetainResultsUntilCollected(bridge, runtime); + codexui::codex::directNodeActionsUseOneCorrelatedRequest(bridge, runtime); + codexui::codex::remainingUiCommandFamiliesUseExactWirePaths(bridge, runtime); + codexui::codex::itemHistoryHydrationHasAnExactConcurrencyCeiling(bridge, runtime); + codexui::codex::conversationSnapshotsShareOneAdmissionAuthority(bridge, runtime); + codexui::codex::firstNavigationDrainsTheExistingHistoryPager(bridge, runtime); + codexui::codex::staleHistoryFailureIsSemanticallyInert(bridge, runtime); + codexui::codex::ordinaryThreadPromptStillStartsAndCompletes(bridge, runtime); + codexui::codex::firstPromptAfterForkStartsANewTurn(bridge, runtime); + codexui::codex::forksPersistSourceMembership(bridge, runtime); + codexui::codex::creationAssignsOnlyTheReturnedGroup(bridge, runtime); + codexui::codex::runtimeRefreshActionsHaveExactRequestCardinality(bridge, runtime); + codexui::codex::failedWakeUsesBoundedWorkerRecovery(bridge, runtime); + codexui::codex::reverseInteractionsRespondOnceWithAuthoredData(bridge, runtime); + codexui::codex::invalidAuthoredReverseResponseNeverReachesWire(bridge, runtime); + codexui::codex::remainingReverseRequestFamiliesRoundTripExactlyOnce(bridge, runtime); + codexui::codex::unknownInboundIsRetainedWithoutCorruptingKnownState(bridge, runtime); + codexui::codex::startupListsResolveLineageBeforePublishing(bridge, runtime); + codexui::codex::threadOrganisationUsesBoundedAuthoritativeRequests(bridge, runtime); + codexui::codex::workerRevalidatesCurrentAuthorityAndRetainsResponses(bridge, runtime); + codexui::codex::explicitReconnectsControlTheLatestFlow(bridge, runtime); + codexui::codex::endpointReconfigurationUsesTheSelectedAddress(bridge, runtime); + } + runtime.channels().failNextQtToWorkerWakeForTest(); + const auto shutdownStarted = std::chrono::steady_clock::now(); + runtime.stop(); + codexui::codex::expect(std::chrono::steady_clock::now() - shutdownStarted < std::chrono::seconds(2), + "an unwoken ShutdownRequest is consumed without hanging worker join"); + codexui::codex::expect(bridge.peerClosed(), "shutdown closes the most recently connected flow"); + + if (codexui::codex::failures != 0) { + std::cerr << codexui::codex::failures << " client-runtime dispatch assertion(s) failed\n"; + return EXIT_FAILURE; + } + std::cout << "ClientRuntime typed dispatch integration test passed\n"; + return EXIT_SUCCESS; }